Exemplo n.º 1
0
bool Manager::str2bool(const string &v) {
    return !v.empty() && atoi(v.c_str()) != 0;
}
Exemplo n.º 2
0
int
main(int argc, char* argv[])
{
	uint16 bitspersample, shortv;
	uint32 imagewidth, imagelength;
	uint16 config = PLANARCONFIG_CONTIG;
	uint32 rowsperstrip = (uint32) -1;
	uint16 photometric = PHOTOMETRIC_RGB;
	uint16 *rmap, *gmap, *bmap;
	uint32 row;
	int cmap = -1;
	TIFF *in, *out;
	int c;
	extern int optind;
	extern char* optarg;

	while ((c = getopt(argc, argv, "C:c:p:r:")) != -1)
		switch (c) {
		case 'C':		/* force colormap interpretation */
			cmap = atoi(optarg);
			break;
		case 'c':		/* compression scheme */
			if (!processCompressOptions(optarg))
				usage();
			break;
		case 'p':		/* planar configuration */
			if (streq(optarg, "separate"))
				config = PLANARCONFIG_SEPARATE;
			else if (streq(optarg, "contig"))
				config = PLANARCONFIG_CONTIG;
			else
				usage();
			break;
		case 'r':		/* rows/strip */
			rowsperstrip = atoi(optarg);
			break;
		case '?':
			usage();
			/*NOTREACHED*/
		}
	if (argc - optind != 2)
		usage();
	in = TIFFOpen(argv[optind], "r");
	if (in == NULL)
		return (-1);
	if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &shortv) ||
	    shortv != PHOTOMETRIC_PALETTE) {
		fprintf(stderr, "%s: Expecting a palette image.\n",
		    argv[optind]);
		return (-1);
	}
	if (!TIFFGetField(in, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
		fprintf(stderr,
		    "%s: No colormap (not a valid palette image).\n",
		    argv[optind]);
		return (-1);
	}
	bitspersample = 0;
	TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
	if (bitspersample != 8) {
		fprintf(stderr, "%s: Sorry, can only handle 8-bit images.\n",
		    argv[optind]);
		return (-1);
	}
	out = TIFFOpen(argv[optind+1], "w");
	if (out == NULL)
		return (-2);
	cpTags(in, out);
	TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth);
	TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
	if (compression != (uint16)-1)
		TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
	else
		TIFFGetField(in, TIFFTAG_COMPRESSION, &compression);
	switch (compression) {
	case COMPRESSION_JPEG:
		if (jpegcolormode == JPEGCOLORMODE_RGB)
			photometric = PHOTOMETRIC_YCBCR;
		else
			photometric = PHOTOMETRIC_RGB;
		TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
		TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
		break;
	case COMPRESSION_LZW:
	case COMPRESSION_DEFLATE:
		if (predictor != 0)
			TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
		break;
	}
	TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
	TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
	TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
	TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
	    rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip));
	(void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv);
	if (cmap == -1)
		cmap = checkcmap(1<<bitspersample, rmap, gmap, bmap);
	if (cmap == 16) {
		/*
		 * Convert 16-bit colormap to 8-bit.
		 */
		int i;

		for (i = (1<<bitspersample)-1; i >= 0; i--) {
#define	CVT(x)		(((x) * 255) / ((1L<<16)-1))
			rmap[i] = CVT(rmap[i]);
			gmap[i] = CVT(gmap[i]);
			bmap[i] = CVT(bmap[i]);
		}
	}
	{ unsigned char *ibuf, *obuf;
	  register unsigned char* pp;
	  register uint32 x;
	  ibuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(in));
	  obuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(out));
	  switch (config) {
	  case PLANARCONFIG_CONTIG:
		for (row = 0; row < imagelength; row++) {
			if (!TIFFReadScanline(in, ibuf, row, 0))
				goto done;
			pp = obuf;
			for (x = 0; x < imagewidth; x++) {
				*pp++ = (unsigned char) rmap[ibuf[x]];
				*pp++ = (unsigned char) gmap[ibuf[x]];
				*pp++ = (unsigned char) bmap[ibuf[x]];
			}
			if (!TIFFWriteScanline(out, obuf, row, 0))
				goto done;
		}
		break;
	  case PLANARCONFIG_SEPARATE:
		for (row = 0; row < imagelength; row++) {
			if (!TIFFReadScanline(in, ibuf, row, 0))
				goto done;
			for (pp = obuf, x = 0; x < imagewidth; x++)
				*pp++ = (unsigned char) rmap[ibuf[x]];
			if (!TIFFWriteScanline(out, obuf, row, 0))
				goto done;
			for (pp = obuf, x = 0; x < imagewidth; x++)
				*pp++ = (unsigned char) gmap[ibuf[x]];
			if (!TIFFWriteScanline(out, obuf, row, 0))
				goto done;
			for (pp = obuf, x = 0; x < imagewidth; x++)
				*pp++ = (unsigned char) bmap[ibuf[x]];
			if (!TIFFWriteScanline(out, obuf, row, 0))
				goto done;
		}
		break;
	  }
	  _TIFFfree(ibuf);
	  _TIFFfree(obuf);
	}
done:
	(void) TIFFClose(in);
	(void) TIFFClose(out);
	return (0);
}
Exemplo n.º 3
0
int
main(int argc, char **argv)
{
	int ch, i, nprocs = 1, is_parent = 1, port, *sockets, fds[2];
	pid_t pid;
	char *sp, *ap, *host, *cmd = argv[0];
	struct hostent *he;

	/* Defaults */
	params.count = -1;
	params.rpc = -1;
	params.concurrency = 1;
	memset(params.buckets, 0, sizeof(params.buckets));
	params.buckets[0] = 1;
	params.buckets[1] = 10;
	params.buckets[2] = 100;
	params.nbuckets = 4;

	memset(&counts, 0, sizeof(counts));

	while((ch = getopt(argc, argv, "c:b:n:p:r:i:h")) != -1){
		switch(ch){
		case 'b':
			sp = optarg;

			memset(params.buckets, 0, sizeof(params.buckets));

			for(i=0; i<MAX_BUCKETS && (ap=strsep(&sp, ",")) != nil; i++)
				params.buckets[i] = atoi(ap);

			params.nbuckets = i;

			if(params.buckets[0] == 0)
				panic("first bucket must be >0\n");

			for(i=1; params.buckets[i]!=0; i++){
				if(params.buckets[i]<params.buckets[i-1])
					panic("invalid bucket specification!\n");
			}
			break;

		case 'c':
			params.concurrency = atoi(optarg);
			break;

		case 'n':
			params.count = atoi(optarg);
			break;

		case 'p':
			nprocs = atoi(optarg);
			break;

		case 'i':
			reporttv.tv_sec = atoi(optarg);
			break;

		case 'r':
			params.rpc = atoi(optarg);
			break;

		case 'h':
			usage(cmd);
			break;
		}
	}

	argc -= optind;
	argv += optind;

	host = "127.0.0.1";
	port = 80;
	switch(argc){
	case 2:
		port = atoi(argv[1]);
	case 1:
		host = argv[0];
	case 0:
		break;
	default:
		panic("only 0 or 1(host port) pair are allowed\n");
	}
	
	http_hostname = host;
	http_port = port;
	if(snprintf(http_hosthdr, sizeof(http_hosthdr), "%s:%d", host, port) > sizeof(http_hosthdr))
		panic("snprintf");

	for(i = 0; params.buckets[i] != 0; i++)
		request_timeout = params.buckets[i];

	if(params.count > 0)
		params.count /= nprocs;

#if 0
	event_init();
	dispatch(mkhttp(), 1);
	event_dispatch(); exit(0);
#endif

	fprintf(stderr, "# params: c=%d p=%d n=%d r=%d\n", 
	    params.concurrency, nprocs, params.count, params.rpc);

	fprintf(stderr, "# ts\t\terrors\ttimeout\tcloses\t");
	for(i=0; params.buckets[i]!=0; i++)
		fprintf(stderr, "<%d\t", params.buckets[i]);

	fprintf(stderr, ">=%d\thz\n", params.buckets[i - 1]);

	if((sockets = calloc(nprocs + 1, sizeof(int))) == nil)
		panic("malloc\n");

	sockets[nprocs] = -1;

	for(i=0; i<nprocs; i++){
		if(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0){
			perror("socketpair");
			exit(1);
		}

		sockets[i] = fds[0];

		if((pid = fork()) < 0){
			kill(0, SIGINT);
			perror("fork");
			exit(1);
		}else if(pid != 0){
			close(fds[1]);
			continue;
		}

		is_parent = 0;

		event_init();

		/* Set up output. */
		if(dup2(fds[1], STDOUT_FILENO) < 0){
			perror("dup2");
			exit(1);
		}

		close(fds[1]);

		for(i=0; i<params.concurrency; i++)
			dispatch(mkhttp(), 1);

		evtimer_set(&reportev, reportcb, nil);
		evtimer_add(&reportev, &reporttv);

		event_dispatch();

		break;
	}

	if(is_parent)
		parentd(nprocs, sockets);

	return(0);
}
Exemplo n.º 4
0
gint dvtmcf1_r1(class dvtmcf1_r_data *data)
{
    time_t vremn;
    time(&vremn);
    char strsql[1024];
    iceb_u_str repl;
    iceb_clock sss(data->window);





    short ostkg=0;

    iceb_poldan("Отчет в килограммах",strsql,"matnast.alx",data->window);
    if(iceb_u_SRAV(strsql,"Вкл",1) == 0)
        ostkg=1;

    sprintf(strsql,"select * from Kart");
    SQLCURSOR cur,curtmp;
    SQLCURSOR cur1;
    SQL_str row,rowtmp;
    SQL_str row1;

    int kolstr;

    if((kolstr=cur.make_cursor(&bd,strsql)) < 0)
        iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,data->window);

    if(kolstr == 0)
    {
        iceb_menu_soob(gettext("Не найдено ни одной записи !"),data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }

    class iceb_tmptab tabtmp;
    const char *imatmptab= {"dvtmcf1"};

    char zaprostmp[512];
    memset(zaprostmp,'\0',sizeof(zaprostmp));

    sprintf(zaprostmp,"CREATE TEMPORARY TABLE %s (\
sh char(24) not null,\
skl int not null,\
kgm int not null,\
naim char(112) not null,\
km int not null,\
nk int not null,\
ei char(24) not null,\
cena double(15,6) not null,\
nds float(2) not null,\
mnds smallint not null,\
fas float(2) not null)",imatmptab);


    if(tabtmp.create_tab(imatmptab,zaprostmp,data->window) != 0)
    {
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }
    /*********
    char imaftmp[32];
    FILE *ff1;

    sprintf(imaftmp,"dv%d.tmp",getpid());
    if((ff1 = fopen(imaftmp,"w")) == NULL)
     {
      iceb_er_op_fil(imaftmp,"",errno,data->window);
      sss.clear_data();
      gtk_widget_destroy(data->window);
      return(FALSE);
     }
    **************/
    short dn,mn,gn;
    short dk,mk,gk;

    iceb_rsdatp(&dn,&mn,&gn,data->rk->datan.ravno(),&dk,&mk,&gk,data->rk->datak.ravno(),data->window);

    sprintf(strsql,"%s\n%s %d.%d.%d %s %d.%d.%d\n",
            gettext("Сортируем записи"),
            gettext("Период с"),
            dn,mn,gn,
            gettext("по"),
            dk,mk,gk);

    iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);

    int kgrm=0;
//int kolstr2=0;
    float kolstr1=0.;
    class iceb_u_str naim("");

    while(cur.read_cursor(&row) != 0)
    {
        iceb_pbar(data->bar,kolstr,++kolstr1);

        if(iceb_u_proverka(data->rk->sklad.ravno(),row[0],0,0) != 0)
            continue;

        if(iceb_u_proverka(data->rk->shet.ravno(),row[5],0,0) != 0)
            continue;

        kgrm=0;
        naim.new_plus("");
        /*Читаем код группы материалла*/
        sprintf(strsql,"select kodgr,naimat from Material where kodm=%s",row[2]);
        if(sql_readkey(&bd,strsql,&row1,&cur1) != 1)
        {
            printf("%s %s !\n",gettext("Не найден код материалла"),row[2]);
            continue;
        }
        else
        {
            kgrm=atoi(row1[0]);
            naim.new_plus(row1[1]);
        }

        if(iceb_u_proverka(data->rk->grupa.ravno(),row1[0],0,0) != 0)
            continue;

        if(provndsw(data->rk->nds.ravno(),row) != 0)
            continue;

        if(iceb_u_proverka(data->rk->kodmat.ravno(),row[2],0,0) != 0)
            continue;

//  kolstr2++;
        /************
          fprintf(ff1,"%s|%s|%d|%s|%s|%s|%s|%.10g|%.5g|%s|%s|\n",
          row[5],row[0],kgrm,naim.ravno(),row[2],row[1],row[4],atof(row[6]),atof(row[9]),
          row[3],row[10]);
        *************/
        sprintf(strsql,"insert into %s values ('%s',%s,%d,'%s',%s,%s,'%s',%.10g,%.5g,%s,%s)",
                imatmptab,
                row[5],row[0],kgrm,naim.ravno_filtr(),row[2],row[1],row[4],atof(row[6]),atof(row[9]),
                row[3],row[10]);
        iceb_sql_zapis(strsql,1,0,data->window);

    }

//fclose(ff1);


    if(data->rk->metka_sort == 0) //Сортировать счет-склад-наименование материалла.
    {
//  sprintf(strsql,"sort -o %s -t\\| -k1,2 -k2,3n -k4,5 %s",imaftmp,imaftmp);
//  sprintf(strsql,"sort -o %s -t\\| +0 -1 +1n -2 +3 -4 %s",imaftmp,imaftmp);
        sprintf(strsql,"select * from %s order by sh asc,skl asc,naim asc",imatmptab);
    }
    if(data->rk->metka_sort == 1) //Сортировать счет-склад-группа-наименование материалла.
    {
//  sprintf(strsql,"sort -o %s -t\\| -k1,2 -k2,3n -k3,4n -k4,5 %s",imaftmp,imaftmp);
//  sprintf(strsql,"sort -o %s -t\\| +0 -1 +1n -2 +2n -3 +3 -4 %s",imaftmp,imaftmp);
        sprintf(strsql,"select * from %s order by sh asc,skl asc,kgm asc,naim asc",imatmptab);
    }
//system(strsql); //Запуск сортировки
    int kolstrtmp=0;
    if((kolstrtmp=curtmp.make_cursor(&bd,strsql)) < 0)
    {
        iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }

    sprintf(strsql,"%s.\n",gettext("Делаем отчет"));
    iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);
    /**************
    if((ff1 = fopen(imaftmp,"r")) == NULL)
     {
      iceb_er_op_fil(imaftmp,"",errno,data->window);
      gtk_widget_destroy(data->window);
      return(FALSE);
     }
    *************/
    FILE *ff;
    char imaf[32];

    sprintf(imaf,"zag%d.lst",getpid());
    data->rk->imaf.plus(imaf);

    repl.new_plus(gettext("Оборотная ведомость движния товарно-материальных ценностей"));
    repl.plus(" (");
    repl.plus(gettext("формат"));
    repl.plus(" A3)");

    data->rk->naimf.plus(repl.ravno());

    if((ff = fopen(imaf,"w")) == NULL)
    {
        iceb_er_op_fil(imaf,"",errno,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }
    FILE *ffuz;
    char imafuz[32];

    sprintf(imafuz,"zaguz%d.lst",getpid());
    data->rk->imaf.plus(imafuz);

    repl.new_plus(gettext("Оборотная ведомость движния товарно-материальных ценностей"));
    repl.plus(" (");
    repl.plus(gettext("формат"));
    repl.plus(" A4)");

    data->rk->naimf.plus(repl.ravno());

    if((ffuz = fopen(imafuz,"w")) == NULL)
    {
        iceb_er_op_fil(imafuz,"",errno,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }

    /***************
    if(tipras == 1)
     {
      sprintf(imafkl2,"zagg%d.lst",getpid());

      if((ffkl2 = fopen(imafkl2,"w")) == NULL)
       ERROR1(gettext("Ошибка открытия файла"),errno,imafkl2);
      startfil(ffkl2);
     }
    else
     {
    *****************/
    char imafitog[32];
    sprintf(imafitog,"zai%d.lst",getpid());
    data->rk->imaf.plus(imafitog);

    data->rk->naimf.plus(gettext("Свод движения материальных ценностей"));
    FILE *ffitog;
    if((ffitog = fopen(imafitog,"w")) == NULL)
    {
        iceb_er_op_fil(imafitog,"",errno,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }


    iceb_u_zagolov(gettext("Свод движения материальных ценностей"),dn,mn,gn,dk,mk,gk,organ,ffitog);


    iceb_u_zagolov(gettext("Оборотная ведомость движния товарно-материальных ценностей"),dn,mn,gn,dk,mk,gk,organ,ff);
    iceb_u_zagolov(gettext("Оборотная ведомость движния товарно-материальных ценностей"),dn,mn,gn,dk,mk,gk,organ,ffuz);


    int kst=4;

    if(data->rk->shet.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Счёт"),data->rk->shet.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Счёт"),data->rk->shet.ravno());
        kst++;
    }
    if(data->rk->sklad.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Склад"),data->rk->sklad.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Склад"),data->rk->sklad.ravno());
        kst++;
    }
    if(data->rk->grupa.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Група"),data->rk->grupa.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Група"),data->rk->grupa.ravno());
        kst++;
    }

    if(data->rk->kodmat.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Код материалла"),data->rk->kodmat.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Код материалла"),data->rk->kodmat.ravno());
        kst++;
    }
    if(data->rk->nds.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("НДС"),data->rk->nds.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("НДС"),data->rk->nds.ravno());
        kst++;
    }
    char shbm[32];
    char naiskl[112];

    memset(shbm,'\0',sizeof(shbm));
    memset(naiskl,'\0',sizeof(naiskl));
    int skl=0;
    int sli=1;
    double itg1=0.,itg2=0.,itg3=0.,itg4=0.,itg5=0.,itg6=0.,itg7=0.,itg8=0.;
    double k1=0.,s1=0.,k2=0.,s2=0.,k3=0.,s3=0.,k4=0.,s4=0.;
    double kk1=0.,ss1=0.,kk2=0.,ss2=0.,kk3=0.,ss3=0.,kk4=0.,ss4=0.;
    double kg0=0.,kg1=0.,kg2=0.,kg3=0.;
    double kgs0=0.,kgs1=0.,kgs2=0.,kgs3=0.;
    int kgrmzp=0;
    char str[512];
    memset(str,'\0',sizeof(str));
    memset(str,'.',233);
    int mvsh=0;
    kolstr1=0;
//char str1[1000];
    class ostatok ost;
    char shb[20];
    int skl1;
    int kodm;
    int nk;
    char ei[32];
    char		mnds='\0';
    double cena,nds;
    char naimshet[512];
    char nomn[112];

//while(fgets(str1,sizeof(str1),ff1) != NULL)
// {
    while(curtmp.read_cursor(&rowtmp) != 0)
    {
        iceb_pbar(data->bar,kolstrtmp,++kolstr1);

        /********
          iceb_u_pole(str1,shb,1,'|');
          iceb_u_pole(str1,strsql,2,'|');
          skl1=atoi(strsql);
          iceb_u_pole(str1,strsql,3,'|');
          kgrm=atoi(strsql);

          iceb_u_pole(str1,naim,4,'|');
          iceb_u_pole(str1,strsql,5,'|');
          kodm=atoi(strsql);
          iceb_u_pole(str1,strsql,6,'|');
          nk=atoi(strsql);
        **************/
        strncpy(shb,rowtmp[0],sizeof(shb)-1);
        skl1=atoi(rowtmp[1]);
        kgrm=atoi(rowtmp[2]);
        naim.new_plus(rowtmp[3]);
        kodm=atoi(rowtmp[4]);
        nk=atoi(rowtmp[5]);

        /*Остаток по карточкам*/
        ostkarw(dn,mn,gn,dk,mk,gk,skl1,nk,&ost);

        if(ost.ostm[0] == 0. && ost.ostm[1] == 0. && ost.ostm[3] == 0. && fabs(ost.ostmc[3]) < 0.009)
            continue;
        /************
          iceb_u_pole(str1,ei,7,'|');
          iceb_u_pole(str1,strsql,8,'|');
          cena=atof(strsql);
          iceb_u_pole(str1,strsql,9,'|');
          nds=atof(strsql);

          iceb_u_pole(str1,strsql,10,'|');
        ***********/
        strncpy(ei,rowtmp[6],sizeof(ei)-1);
        cena=atof(rowtmp[7]);
        nds=atof(rowtmp[8]);
        strncpy(strsql,rowtmp[9],sizeof(strsql)-1);

        if(atoi(strsql) == 0)
            mnds=' ';
        if(atoi(strsql) == 1)
            mnds='+';

        if(kgrmzp != kgrm)
        {
            if(kgrmzp != 0)
            {
                if(data->rk->metka_sort == 1)
                    if(itg1 != 0. || itg2 != 0. || itg3 != 0. || itg4 != 0.)
                    {
                        itgrup(kgrmzp,itg1,itg2,itg3,itg4,itg5,itg6,itg7,itg8,ffuz,0,ff);
                        kst+=2;
                    }
            }
            itg1=itg2=itg3=itg4=itg5=itg6=itg7=itg8=0.;
            kgrmzp=kgrm;
        }

        if(iceb_u_SRAV(shb,shbm,1) != 0)
        {
            if(shbm[0] != '\0')
            {
                if(data->rk->metka_sort == 1)
                    if(itg1 != 0. || itg2 != 0. || itg3 != 0. || itg4 != 0.)
                    {
                        itgrup(kgrmzp,itg1,itg2,itg3,itg4,itg5,itg6,itg7,itg8,ffuz,0,ff);
                        itg1=itg2=itg3=itg4=itg5=itg6=itg7=itg8=0.;
                        kst+=2;
                    }
                itskl(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,ffuz,ff,ffitog,data);
                kst+=2;
                if(ostkg == 1 && fabs((kk1+kk2+kk3+kk4) - (kg0+kg1+kg2+kg3)) > 0.0001 &&
                        kg0+kg1+kg2+kg3 > 0.0001)
                {
                    itkg(shbm,skl,kg0,kg1,kg2,kg3,1,ffuz,ff);
                    kst+=2;
                    kg0=kg1=kg2=kg3=0.;
                }
                itsh(shbm,k1,k2,k3,k4,s1,s2,s3,s4,ffuz,ff,ffitog,data);
                kst+=2;
                if(ostkg == 1 && fabs((k1+k2+k3+k4) - (kgs0+kgs1+kgs2+kgs3)) > 0.0001 &&
                        kgs0+kgs1+kgs2+kgs3 > 0.0001)
                {
                    itkg(shbm,skl,kgs0,kgs1,kgs2,kgs3,0,ffuz,ff);
                    kst+=2;
                    kgs0=kgs1=kgs2=kgs3=0.;
                }
                skl=0;
                /****************
                      if(tipras == 1)
                       {
                	itskl1(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,str,ff,ffkl2);
                	skl=0;
                	itsh1(shbm,k1,k2,k3,k4,s1,s2,s3,s4,str,ff,ffkl2);
                	kst+=4;
                       }
                *******************/
            }
            k1=s1=k2=s2=k3=s3=k4=s4=0.;

            /*Читаем наименование счета*/
            memset(naimshet,'\0',sizeof(naimshet));
            sprintf(strsql,"select nais from Plansh where ns='%s'",shb);
            if(sql_readkey(&bd,strsql,&row,&cur1) != 1)
            {
                printf("Не найден счет %s в плане счетов !\n",shb);
                fprintf(ff,"%s %s !\n",gettext("Не найден счет"),shb);
            }
            else
                strncpy(naimshet,row[0],sizeof(naimshet)-1);

            sprintf(strsql,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);

            if(kst > kol_strok_na_liste - 10)
            {
                fprintf(ff,"\f");
                fprintf(ffuz,"\f");
//      if(ffkl2 != NULL)
//         fprintf(ffkl2,"\f");
                kst=0;
                sli++;
            }


            fprintf(ff,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            fprintf(ffuz,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            if(ffitog != NULL)
                fprintf(ffitog,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            kst+=2;
//    if(tipras == 0)
            gsapp(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,ffuz,ff);
//    else
//     gsapp2(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,str,ff,ffkl2);

            mvsh=1;

            strcpy(shbm,shb);
        }

        if(skl != skl1)
        {
            if(skl != 0)
            {
                if(data->rk->metka_sort == 1)
                    if(itg1 != 0. || itg2 != 0. || itg3 != 0. || itg4 != 0.)
                    {
                        itgrup(kgrmzp,itg1,itg2,itg3,itg4,itg5,itg6,itg7,itg8,ffuz,0,ff);
                        itg1=itg2=itg3=itg4=itg5=itg6=itg7=itg8=0.;
                        kst+=2;
                    }

                itskl(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,ffuz,ff,ffitog,data);
                kst+=2;
                if(ostkg == 1 && fabs((kk1+kk2+kk3+kk4) - (kg0+kg1+kg2+kg3)) > 0.0001 &&
                        kg0+kg1+kg2+kg3 > 0.0001)
                {
                    itkg(shbm,skl,kg0,kg1,kg2,kg3,1,ffuz,ff);
                    kst+=2;
                    kg0=kg1=kg2=kg3=0.;
                }

//      if(tipras == 1)
//       {
//	itskl1(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,str,ff,ffkl2);
//        kst+=2;
//       }
            }
            kk1=ss1=kk2=ss2=kk3=ss3=kk4=ss4=0.;

            /*Читаем наименование склада*/
            memset(naiskl,'\0',sizeof(naiskl));
            sprintf(strsql,"select naik from Sklad where kod='%d'",skl1);
            if(sql_readkey(&bd,strsql,&row,&cur1) != 1)
            {
                printf("Не найден склад %d в списке складов\n",skl1);
                fprintf(ff,"%s %d !\n",gettext("Не найден склад"),skl1);
            }
            strncpy(naiskl,row[0],sizeof(naiskl));

            sprintf(strsql,"%s: %d %s\n",gettext("Склад"),skl1,naiskl);
            iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);

            if(kst != 0)
                if(kst > kol_strok_na_liste - 10)
                {
                    fprintf(ff,"\f");
                    fprintf(ffuz,"\f");
//      if(ffkl2 != NULL)
//         fprintf(ffkl2,"\f");
                    kst=0;
                    sli++;
                }
            mvsh=1;
            skl=skl1;

        }
        if(mvsh == 1)
        {
//    if(tipras == 0)
//     {
            shdtmcf1(dn,mn,gn,dk,mk,gk,sli,ff,skl,naiskl,ffuz);
            kst+=6;
//     }
            /***************
                if(tipras == 1)
                 {
                  shdtmcf1k(dn,mn,gn,sli,ff,skl,naiskl,ffkl2);
                  kst+=6;
                 }
            ***************/
            mvsh=0;
        }


        /*Остаток по карточкам*/
//  ostkar(dn,mn,gn,dk,mk,gk,skl1,nk,ostg,ostm,ostgc,ostmc);

//  sprintf(nomn,"%d.%s.%d.%d",skl1,shb,kgrm,nk);
        sprintf(nomn,"%s.%d.%d",shb,kgrm,nk);


//  if(tipras == 0)
//   {
        gsapp(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,ffuz,ff);

        fprintf(ff,"\
%4d %-*.*s %-*s %-*s %c%2.2g %14.10g %15.10g %15.2f %15.10g %15.2f %15.10g %15.2f \
%15.10g %15.2f\n",
                kodm,
                iceb_u_kolbait(40,naim.ravno()),iceb_u_kolbait(40,naim.ravno()),naim.ravno(),
                iceb_u_kolbait(13,nomn),nomn,
                iceb_u_kolbait(10,ei),ei,
                mnds,nds,cena,
                ost.ostm[0],ost.ostmc[0],ost.ostm[1],ost.ostmc[1],ost.ostm[2],ost.ostmc[2],ost.ostm[3],ost.ostmc[3]);

        fprintf(ffuz,"\
%4d %-*.*s %-*s %-*s %c%2.2g %7s %8.8g %8.2f %8.8g %8.2f %8.8g %8.2f \
%8.8g %8.2f\n",
                kodm,
                iceb_u_kolbait(23,naim.ravno()),iceb_u_kolbait(23,naim.ravno()),naim.ravno(),
                iceb_u_kolbait(13,nomn),nomn,
                iceb_u_kolbait(3,ei),ei,
                mnds,nds,iceb_prcn(cena),
                ost.ostm[0],ost.ostmc[0],ost.ostm[1],ost.ostmc[1],ost.ostm[2],ost.ostmc[2],ost.ostm[3],ost.ostmc[3]);


        if(ostkg == 1)
        {
            double ost1=0.,ost2=0.,ost3=0.,ost4=0.;
            double fas=0.;
//       iceb_u_pole(str1,strsql,11,'|');
//       fas=atof(strsql);
            fas=atof(rowtmp[10]);
            if(fas > 0.0000001)
            {
                ost1=ost.ostm[0]*fas;
                ost2=ost.ostm[1]*fas;
                ost3=ost.ostm[2]*fas;
                ost4=ost.ostm[3]*fas;
                kg0+=ost1;
                kg1+=ost2;
                kg2+=ost3;
                kg3+=ost4;
                kgs0+=ost1;
                kgs1+=ost2;
                kgs2+=ost3;
                kgs3+=ost4;

                gsapp(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,ffuz,ff);

                fprintf(ff,"\
%4s %-40.40s %-13s %-10s %3s %14s %15.10g %15s %15.10g %15s %15.10g %15s \
%15.10g %15s\n"," "," "," "," "," "," ",
                        ost1," ",ost2," ",ost3," ",ost4," ");

                fprintf(ffuz,"\
%4s %-23.23s %-13s %-3s %3s %7s %8.8g %8s %8.8g %8s %8.8g %8s \
%8.8g %8s\n"," "," "," "," "," "," ",
                        ost1," ",ost2," ",ost3," ",ost4," ");

            }
            else if(iceb_u_SRAV(ei,"Кг",0) == 0 || iceb_u_SRAV(ei,"кг",0) == 0 ||
Exemplo n.º 5
0
int main(int argc, char const *argv[]) {
  int sockfd, status;
  struct addrinfo hints, *serverinfo, *p;
  struct sockaddr_storage their_addr;
  int rv, j;
  int numbytes;
  char buf[MAXBUFLEN];
  socklen_t addr_len;
  struct timeval tv;
  tv.tv_sec = 5;
  tv.tv_usec = 0;

  if(atoi(argv[1]) == 2) {
  sleep(5);

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_DGRAM;
  hints.ai_flags = AI_PASSIVE;

  if((rv = getaddrinfo(NULL, COM_PORT, &hints, &serverinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
  }

  for(p = serverinfo; p !=NULL; p->ai_next) {
    if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
      perror("listener:socket");
      continue;
    }

setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));

    if(bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
      close(sockfd);
      perror("listener:bind");
      continue;
    }
    break;
  }

  if (p == NULL) {
    fprintf(stderr, "listener:failed to bind to socket\n");
  }

  freeaddrinfo(serverinfo);



  while(1) {


    addr_len = sizeof their_addr;

    if((numbytes = recvfrom(sockfd,buf, MAXBUFLEN-1, 0,(struct sockaddr*)&their_addr, &addr_len)) == -1 ) {
      perror("recvfrom");
      printf("Timeout of process one\n");

      close(sockfd);

      memset(&hints, 0, sizeof hints);
      hints.ai_family = AF_UNSPEC;
      hints.ai_socktype = SOCK_DGRAM;

      if((rv = getaddrinfo("127.0.0.1", COM_PORT, &hints, &serverinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
      }

      for(p = serverinfo; p != NULL; p = p->ai_next) {
        if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
          perror("talker:socket");
          continue;
        }
        break;
      }

      if(p == NULL) {
        fprintf(stderr, "talker: failed to create socket");
        return 2;
      }

      status = system("gnome-terminal -x bash -c './process_pairs 2'");

      while(1) {
        printf("process one:%d\n",j);

        sprintf(buf, "%d", j);

        if((numbytes = sendto(sockfd, buf , strlen(buf), 0, p->ai_addr, p->ai_addrlen)) == -1) {
          perror("talker: sendto");
          exit(1);
        }

        j++;
        if(j > 4) {
          j = 1;
        }
        sleep(1);
      }

    }


    j = atoi(buf);
    printf("process two:%d\n",j);
    sleep(1);


}

  printf( "%s\n",buf);
  close(sockfd);


} else if(atoi(argv[1]) == 1) {

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_DGRAM;

  if((rv = getaddrinfo("127.0.0.1", COM_PORT, &hints, &serverinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
  }

  for(p = serverinfo; p != NULL; p = p->ai_next) {
    if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
      perror("talker:socket");
      continue;
    }
    break;
  }

  if(p == NULL) {
    fprintf(stderr, "talker: failed to create socket");
    return 2;
  }
  j = 1;


  status = system("gnome-terminal -x bash -c './process_pairs 2'");

  while(1) {

  sprintf(buf, "%d", j);
  if((numbytes = sendto(sockfd, buf , strlen(buf), 0, p->ai_addr, p->ai_addrlen)) == -1) {
    perror("talker: sendto");
    exit(1);
  }

  printf("%d\n",j);
  j++;

  if(j > 4)
  {
    j = 1;
  }

  sleep(1);
  }

  freeaddrinfo(serverinfo);

  close(sockfd);


}


}
Exemplo n.º 6
0
int TiXmlAttribute::IntValue() const
{
	return atoi (value.c_str ());
}
Exemplo n.º 7
0
void CommandData::ProcessSwitch(char *Switch)
{

  switch(etoupper(Switch[0]))
  {
    case 'I':
      if (strnicomp(&Switch[1],"LOG",3)==0)
      {
        strncpyz(LogName,Switch[4] ? Switch+4:DefLogName,ASIZE(LogName));
        break;
      }
      if (stricomp(&Switch[1],"SND")==0)
      {
        Sound=true;
        break;
      }
      if (stricomp(&Switch[1],"ERR")==0)
      {
        MsgStream=MSG_STDERR;
        break;
      }
      if (strnicomp(&Switch[1],"EML",3)==0)
      {
        strncpyz(EmailTo,Switch[4] ? Switch+4:"@",ASIZE(EmailTo));
        EmailTo[sizeof(EmailTo)-1]=0;
        break;
      }
      if (stricomp(&Switch[1],"NUL")==0)
      {
        MsgStream=MSG_NULL;
        break;
      }
      if (etoupper(Switch[1])=='D')
      {
        for (int I=2;Switch[I]!=0;I++)
          switch(etoupper(Switch[I]))
          {
            case 'Q':
              MsgStream=MSG_ERRONLY;
              break;
            case 'C':
              DisableCopyright=true;
              break;
            case 'D':
              DisableDone=true;
              break;
            case 'P':
              DisablePercentage=true;
              break;
          }
        break;
      }
      if (stricomp(&Switch[1],"OFF")==0)
      {
        Shutdown=true;
        break;
      }
      break;
    case 'T':
      switch(etoupper(Switch[1]))
      {
        case 'K':
          ArcTime=ARCTIME_KEEP;
          break;
        case 'L':
          ArcTime=ARCTIME_LATEST;
          break;
        case 'O':
          FileTimeBefore.SetAgeText(Switch+2);
          break;
        case 'N':
          FileTimeAfter.SetAgeText(Switch+2);
          break;
        case 'B':
          FileTimeBefore.SetIsoText(Switch+2);
          break;
        case 'A':
          FileTimeAfter.SetIsoText(Switch+2);
          break;
        case 'S':
          {
            EXTTIME_MODE Mode=EXTTIME_HIGH3;
            bool CommonMode=Switch[2]>='0' && Switch[2]<='4';
            if (CommonMode)
              Mode=(EXTTIME_MODE)(Switch[2]-'0');
            if (Switch[2]=='-')
              Mode=EXTTIME_NONE;
            if (CommonMode || Switch[2]=='-' || Switch[2]=='+' || Switch[2]==0)
              xmtime=xctime=xatime=Mode;
            else
            {
              if (Switch[3]>='0' && Switch[3]<='4')
                Mode=(EXTTIME_MODE)(Switch[3]-'0');
              if (Switch[3]=='-')
                Mode=EXTTIME_NONE;
              switch(etoupper(Switch[2]))
              {
                case 'M':
                  xmtime=Mode;
                  break;
                case 'C':
                  xctime=Mode;
                  break;
                case 'A':
                  xatime=Mode;
                  break;
                case 'R':
                  xarctime=Mode;
                  break;
              }
            }
          }
          break;
        case '-':
          Test=false;
          break;
        case 0:
          Test=true;
          break;
        default:
          BadSwitch(Switch);
          break;
      }
      break;
    case 'A':
      switch(etoupper(Switch[1]))
      {
        case 'C':
          ClearArc=true;
          break;
        case 'D':
          AppendArcNameToPath=true;
          break;
        case 'G':
          if (Switch[2]=='-' && Switch[3]==0)
            GenerateArcName=0;
          else
          {
            GenerateArcName=true;
            strncpyz(GenerateMask,Switch+2,ASIZE(GenerateMask));
          }
          break;
        case 'N': //reserved for archive name
          break;
        case 'O':
          AddArcOnly=true;
          break;
        case 'P':
          strcpy(ArcPath,Switch+2);
          break;
        case 'S':
          SyncFiles=true;
          break;
        default:
          BadSwitch(Switch);
          break;
      }
      break;
    case 'D':
      if (Switch[2]==0)
        switch(etoupper(Switch[1]))
        {
          case 'S':
            DisableSortSolid=true;
            break;
          case 'H':
            OpenShared=true;
            break;
          case 'F':
            DeleteFiles=true;
            break;
        }
      break;
    case 'O':
      switch(etoupper(Switch[1]))
      {
        case '+':
          Overwrite=OVERWRITE_ALL;
          break;
        case '-':
          Overwrite=OVERWRITE_NONE;
          break;
        case 'R':
          Overwrite=OVERWRITE_AUTORENAME;
          break;
        case 'W':
          ProcessOwners=true;
          break;
#ifdef SAVE_LINKS
        case 'L':
          SaveLinks=true;
          break;
#endif
#ifdef _WIN_32
        case 'S':
          SaveStreams=true;
          break;
        case 'C':
          SetCompressedAttr=true;
          break;
#endif
        default :
          BadSwitch(Switch);
          break;
      }
      break;
    case 'R':
      switch(etoupper(Switch[1]))
      {
        case 0:
          Recurse=RECURSE_ALWAYS;
          break;
        case '-':
          Recurse=0;
          break;
        case '0':
          Recurse=RECURSE_WILDCARDS;
          break;
#ifndef _WIN_CE
        case 'I':
          {
            Priority=atoi(Switch+2);
            char *ChPtr=strchr(Switch+2,':');
            if (ChPtr!=NULL)
            {
              SleepTime=atoi(ChPtr+1);
              InitSystemOptions(SleepTime);
            }
            SetPriority(Priority);
          }
          break;
#endif
      }
      break;
    case 'Y':
      AllYes=true;
      break;
    case 'N':
    case 'X':
      if (Switch[1]!=0)
      {
        StringList *Args=etoupper(Switch[0])=='N' ? InclArgs:ExclArgs;
        if (Switch[1]=='@' && !IsWildcard(Switch))
        {
          RAR_CHARSET Charset=FilelistCharset;

#if defined(_WIN_32) && !defined(GUI)
          // for compatibility reasons we use OEM encoding
          // in Win32 console version by default

          if (Charset==RCH_DEFAULT)
            Charset=RCH_OEM;
#endif

          ReadTextFile(Switch+2,Args,false,true,Charset,true,true);
        }
        else
          Args->AddString(Switch+1);
      }
      break;
    case 'E':
      switch(etoupper(Switch[1]))
      {
        case 'P':
          switch(Switch[2])
          {
            case 0:
              ExclPath=EXCL_SKIPWHOLEPATH;
              break;
            case '1':
              ExclPath=EXCL_BASEPATH;
              break;
            case '2':
              ExclPath=EXCL_SAVEFULLPATH;
              break;
            case '3':
              ExclPath=EXCL_ABSPATH;
              break;
          }
          break;
        case 'D':
          ExclEmptyDir=true;
          break;
        case 'E':
          ProcessEA=false;
          break;
        case 'N':
          NoEndBlock=true;
          break;
        default:
          if (Switch[1]=='+')
          {
            InclFileAttr=GetExclAttr(&Switch[2]);
            InclAttrSet=true;
          }
          else
            ExclFileAttr=GetExclAttr(&Switch[1]);
          break;
      }
      break;
    case 'P':
      if (Switch[1]==0)
      {
        GetPassword(PASSWORD_GLOBAL,NULL,Password,sizeof(Password));
        eprintf("\n");
      }
      else
        strncpyz(Password,Switch+1,ASIZE(Password));
      break;
    case 'H':
      if (etoupper(Switch[1])=='P')
      {
        EncryptHeaders=true;
        if (Switch[2]!=0)
          strncpyz(Password,Switch+2,ASIZE(Password));
        else
          if (*Password==0)
          {
            GetPassword(PASSWORD_GLOBAL,NULL,Password,sizeof(Password));
            eprintf("\n");
          }
      }
      break;
    case 'Z':
      strncpyz(CommentFile,Switch[1]!=0 ? Switch+1:"stdin",ASIZE(CommentFile));
      break;
    case 'M':
      switch(etoupper(Switch[1]))
      {
        case 'C':
          {
            char *Str=Switch+2;
            if (*Str=='-')
              for (int I=0;I<sizeof(FilterModes)/sizeof(FilterModes[0]);I++)
                FilterModes[I].State=FILTER_DISABLE;
            else
              while (*Str)
              {
                int Param1=0,Param2=0;
                FilterState State=FILTER_AUTO;
                FilterType Type=FILTER_NONE;
                if (isdigit(*Str))
                {
                  Param1=atoi(Str);
                  while (isdigit(*Str))
                    Str++;
                }
                if (*Str==':' && isdigit(Str[1]))
                {
                  Param2=atoi(++Str);
                  while (isdigit(*Str))
                    Str++;
                }
                switch(etoupper(*(Str++)))
                {
                  case 'T': Type=FILTER_PPM;         break;
                  case 'E': Type=FILTER_E8;          break;
                  case 'D': Type=FILTER_DELTA;       break;
                  case 'A': Type=FILTER_AUDIO;       break;
                  case 'C': Type=FILTER_RGB;         break;
                  case 'I': Type=FILTER_ITANIUM;     break;
                  case 'L': Type=FILTER_UPCASETOLOW; break;
                }
                if (*Str=='+' || *Str=='-')
                  State=*(Str++)=='+' ? FILTER_FORCE:FILTER_DISABLE;
                FilterModes[Type].State=State;
                FilterModes[Type].Param1=Param1;
                FilterModes[Type].Param2=Param2;
              }
            }
          break;
        case 'M':
          break;
        case 'D':
          {
            if ((WinSize=atoi(&Switch[2]))==0)
              WinSize=0x10000<<(etoupper(Switch[2])-'A');
            else
              WinSize*=1024;
            if (!CheckWinSize())
              BadSwitch(Switch);
          }
          break;
        case 'S':
          {
            char *Names=Switch+2,DefNames[512];
            if (*Names==0)
            {
              strcpy(DefNames,DefaultStoreList);
              Names=DefNames;
            }
            while (*Names!=0)
            {
              char *End=strchr(Names,';');
              if (End!=NULL)
                *End=0;
              if (*Names=='.')
                Names++;
              char Mask[NM];
              if (strpbrk(Names,"*?.")==NULL)
                sprintf(Mask,"*.%s",Names);
              else
                strcpy(Mask,Names);
              StoreArgs->AddString(Mask);
              if (End==NULL)
                break;
              Names=End+1;
            }
          }
          break;
#ifdef PACK_SMP
        case 'T':
          Threads=atoi(Switch+2);
          if (Threads>MaxSearchThreads)
            BadSwitch(Switch);
          else
          {
          }
          break;
#endif
        default:
          Method=Switch[1]-'0';
          if (Method>5 || Method<0)
            BadSwitch(Switch);
          break;
      }
      break;
    case 'V':
      switch(etoupper(Switch[1]))
      {
#ifdef _WIN_32
        case 'D':
          EraseDisk=true;
          break;
#endif
        case 'N':
          OldNumbering=true;
          break;
        case 'P':
          VolumePause=true;
          break;
        case 'E':
          if (etoupper(Switch[2])=='R')
            VersionControl=atoi(Switch+3)+1;
          break;
        case '-':
          VolSize=0;
          break;
        default:
          {
            Int64 NewVolSize=atoil(&Switch[1]);

            if (NewVolSize==0)
              NewVolSize=INT64ERR;
            else
              switch (Switch[strlen(Switch)-1])
              {
                case 'f':
                case 'F':
                  switch(int64to32(NewVolSize))
                  {
                    case 360:
                      NewVolSize=362496;
                      break;
                    case 720:
                      NewVolSize=730112;
                      break;
                    case 1200:
                      NewVolSize=1213952;
                      break;
                    case 1440:
                      NewVolSize=1457664;
                      break;
                    case 2880:
                      NewVolSize=2915328;
                      break;
                  }
                  break;
                case 'k':
                  NewVolSize*=1024;
                  break;
                case 'm':
                  NewVolSize*=1024*1024;
                  break;
                case 'M':
                  NewVolSize*=1000*1000;
                  break;
                case 'g':
                  NewVolSize*=1024*1024;
                  NewVolSize*=1024;
                  break;
                case 'G':
                  NewVolSize*=1000*1000;
                  NewVolSize*=1000;
                  break;
                case 'b':
                case 'B':
                  break;
                default:
                  NewVolSize*=1000;
                  break;
              }
            if (VolSize==0)
              VolSize=NewVolSize;
            else
              NextVolSizes.Push(NewVolSize);
          }
          break;
      }
      break;
    case 'F':
      if (Switch[1]==0)
        FreshFiles=true;
      else
        BadSwitch(Switch);
      break;
    case 'U':
      if (Switch[1]==0)
        UpdateFiles=true;
      else
        BadSwitch(Switch);
      break;
    case 'W':
      strncpyz(TempPath,&Switch[1],ASIZE(TempPath));
      AddEndSlash(TempPath);
      break;
    case 'S':
      if (strnicomp(Switch,"SFX",3)==0)
      {
        const char *SFXName=Switch[3] ? Switch+3:DefSFXName;
        if (PointToName(SFXName)!=SFXName || FileExist(SFXName))
          strcpy(SFXModule,SFXName);
        else
          GetConfigName(SFXName,SFXModule,true);
      }
      if (isdigit(Switch[1]))
      {
        Solid|=SOLID_COUNT;
        SolidCount=atoi(&Switch[1]);
      }
      else
        switch(etoupper(Switch[1]))
        {
          case 0:
            Solid|=SOLID_NORMAL;
            break;
          case '-':
            Solid=SOLID_NONE;
            break;
          case 'E':
            Solid|=SOLID_FILEEXT;
            break;
          case 'V':
            Solid|=Switch[2]=='-' ? SOLID_VOLUME_DEPENDENT:SOLID_VOLUME_INDEPENDENT;
            break;
          case 'D':
            Solid|=SOLID_VOLUME_DEPENDENT;
            break;
          case 'L':
            if (isdigit(Switch[2]))
              FileSizeLess=atoil(Switch+2);
            break;
          case 'M':
            if (isdigit(Switch[2]))
              FileSizeMore=atoil(Switch+2);
            break;
          case 'C':
            {
              RAR_CHARSET rch;
              switch(etoupper(Switch[2]))
              {
                case 'A':
                  rch=RCH_ANSI;
                  break;
                case 'O':
                  rch=RCH_OEM;
                  break;
                case 'U':
                  rch=RCH_UNICODE;
                  break;
                default :
                  BadSwitch(Switch);
                  break;
              };
              if (Switch[3]==0)
                CommentCharset=FilelistCharset=rch;
              else
                for (int I=3;Switch[I]!=0;I++)
                  switch(etoupper(Switch[I]))
                  {
                    case 'C':
                      CommentCharset=rch;
                      break;
                    case 'L':
                      FilelistCharset=rch;
                      break;
                    default:
                      BadSwitch(Switch);
                      break;
                  }
            }
            break;

        }
      break;
    case 'C':
      if (Switch[2]==0)
        switch(etoupper(Switch[1]))
        {
          case '-':
            DisableComment=true;
            break;
          case 'U':
            ConvertNames=NAMES_UPPERCASE;
            break;
          case 'L':
            ConvertNames=NAMES_LOWERCASE;
            break;
        }
      break;
    case 'K':
      switch(etoupper(Switch[1]))
      {
        case 'B':
          KeepBroken=true;
          break;
        case 0:
          Lock=true;
          break;
      }
      break;
#ifndef GUI
    case '?' :
      OutHelp();
      break;
#endif
    default :
      BadSwitch(Switch);
      break;
  }
}
Exemplo n.º 8
0
int
acmecmd(Article *m, Window *w, char *s)
{
	int n;
	Biobuf *b;

//fprint(2, "cmd %s\n", s);

	s = skip(s, "");

	if(iscmd(s, "Del")){
		if(m == nil){	/* don't close dir until messages close */
			if(mlist != nil){
				ctlprint(mlist->w->ctl, "show\n");
				return 1;
			}
			if(windel(w, 0))
				threadexitsall(nil);
			return 1;
		}else{
			if(windel(w, 0))
				m->dead = 1;
			return 1;
		}
	}
	if(m==nil && iscmd(s, "More")){
		s = skip(s, "More");
		if(n = atoi(s))
			nshow = n;

		if(w->data < 0)
			w->data = winopenfile(w, "data");
		winsetaddr(w, "$", 1);
	
		fprint(w->ctl, "dirty\n");

		b = emalloc(sizeof(*b));
		Binit(b, w->data, OWRITE);
		lo = adddir(b, lo, 0, nshow);
		Bterm(b);
		free(b);		
		winclean(w);
		winsetaddr(w, ".,", 0);
	}
	if(m!=nil && !m->ispost && iscmd(s, "Headers")){
		m->headers = !m->headers;
		fillmesgwindow(-1, m);
		return 1;
	}
	if(iscmd(s, "Newpost")){
		m = newpost();
		winopenbody(m->w, OWRITE);
		Bprint(m->w->body, "%s\nsubject: \n\n", group);
		winclean(m->w);
		winselect(m->w, "$", 0);
		return 1;
	}
	if(m!=nil && !m->ispost && iscmd(s, "Reply")){
		replywindow(m);
		return 1;
	}
//	if(m!=nil && iscmd(s, "Replymail")){
//		fprint(2, "no replymail yet\n");
//		return 1;
//	}
	if(iscmd(s, "Post")){
		mesgpost(m);
		return 1;
	}
	return 0;
}
Exemplo n.º 9
0
int BTGE_Voxel_LoadDungeonInfo(
	BTGE_VoxelDungeonInfo *inf, char *name)
{
	VFILE *fd;
	void *p;
	char buf[256];
	char **a, *s;
	int i, j, k;

//	strcpy(buf, tmp->name);
	strcpy(buf, name);
	s=buf+strlen(buf);
	while((s>buf) && (*s!='.'))s--;
	if(*s!='.')s=buf+strlen(buf);
	strcpy(s, ".txt");

	fd=vffopen(buf, "rt");
	if(!fd)return(-1);

	while(!vfeof(fd))
	{
		vfgets(buf, 255, fd);
		a=gcrsplit(buf);
		if(!a[0])continue;

		if(!strcmp(a[0], "$flags"))
		{
		}

		if(!strcmp(a[0], "$dung_vox"))
		{
			j=BTGE_Voxel_IndexVoxelName(a[1]);
			if(j<0)
			{
				printf("BTGE_Voxel_LoadDungeonInfo: "
					"%s Bad Voxel Type %s\n", name, a[1]);
				continue;
			}

			i=inf->n_idx++;
			inf->idx_vox[i].type=j;

			inf->idx_rgba[i*4+0]=atoi(a[2]);
			inf->idx_rgba[i*4+1]=atoi(a[3]);
			inf->idx_rgba[i*4+2]=atoi(a[4]);
			inf->idx_rgba[i*4+3]=255;
			
			for(j=5; a[j]; j++)
			{
				if(!strcmp(a[j], "unbreakable"))
					{ inf->idx_vox[i].type|=VOX_TYM_UNBREAKABLE; }
				if(!strcmp(a[j], "flexform"))
					{ inf->idx_vox[i].type|=VOX_TYM_FLEXFORM; }
				if(!strncmp(a[j], "aux=", 4))
					{ inf->idx_vox[i].aux=atoi(a[j]+4); }
				if(!strncmp(a[j], "aux2=", 5))
					{ inf->idx_vox[i].aux2=atoi(a[j]+5); }
				if(!strncmp(a[j], "vlight=", 7))
					{ inf->idx_vox[i].vlight=atoi(a[j]+7); }
				if(!strncmp(a[j], "slight=", 7))
					{ inf->idx_vox[i].slight=atoi(a[j]+7); }
				if(!strncmp(a[j], "delay=", 6))
					{ inf->idx_vox[i].delay=atoi(a[j]+6); }
			}
		}
		
		if(!strcmp(a[0], "$dung_allow_nx"))
		{
			i=inf->allow_n_edge[0]++;
			inf->allow_edge[0][i]=BTGE_Voxel_IndexDungeonName(a[1]);
		}
		if(!strcmp(a[0], "$dung_allow_px"))
		{
			i=inf->allow_n_edge[1]++;
			inf->allow_edge[1][i]=BTGE_Voxel_IndexDungeonName(a[1]);
		}
		if(!strcmp(a[0], "$dung_allow_ny"))
		{
			i=inf->allow_n_edge[2]++;
			inf->allow_edge[2][i]=BTGE_Voxel_IndexDungeonName(a[1]);
		}
		if(!strcmp(a[0], "$dung_allow_py"))
		{
			i=inf->allow_n_edge[3]++;
			inf->allow_edge[3][i]=BTGE_Voxel_IndexDungeonName(a[1]);
		}
		if(!strcmp(a[0], "$dung_allow_nz"))
		{
			i=inf->allow_n_edge[4]++;
			inf->allow_edge[4][i]=BTGE_Voxel_IndexDungeonName(a[1]);
		}
		if(!strcmp(a[0], "$dung_allow_pz"))
		{
			i=inf->allow_n_edge[5]++;
			inf->allow_edge[5][i]=BTGE_Voxel_IndexDungeonName(a[1]);
		}

		if(!strcmp(a[0], "$dung_allow_biome"))
		{
			i=inf->allow_n_biome++;
			inf->allow_biome[i]=BTGE_Voxel_IndexBiomeName(a[1]);
		}

		if(!strcmp(a[0], "$dung_deny_biome"))
		{
			i=inf->deny_n_biome++;
			inf->deny_biome[i]=BTGE_Voxel_IndexBiomeName(a[1]);
		}

		if(!strcmp(a[0], "$dung_min_z"))
		{
			inf->min_z=atoi(a[1]);
		}

		if(!strcmp(a[0], "$dung_max_z"))
		{
			inf->max_z=atoi(a[1]);
		}
	}

	vfclose(fd);
	return(0);
}
 unsigned int UIValue(){return (unsigned int)(atoi(this->valueStr.c_str()));}
Exemplo n.º 11
0
static char *scpi_handle_profile(struct osc_plugin *plugin, const char *attrib,
		const char *value)
{
	gchar **elems, **min_max;
	char *buf;
	int i;
	double lvl;
	long long j;
	FILE *fd;

	if (value)
		buf = NULL;
	else {
		buf = malloc(128);
		memset(buf, 0, 128);
	}

	current_instrument = NULL;

	elems = g_strsplit(attrib, ".", 0);
	if (!strncmp(elems[0], "rx", 2))
		current_instrument = &spectrum_analyzer;
	if (!strncmp(elems[0], "tx", 2))
		current_instrument = &signal_generator;

	if (!current_instrument)
		return NULL;

	if (strcmp(elems[1], SERIAL_TOK) == 0) {
		if (value) {
			if (atoi(value) == 1)
				current_instrument->serial = TRUE;
		} else {
			if (current_instrument->serial)
				sprintf(buf, "1");
		}
	} else if (strcmp(elems[1], NET_TOK) == 0) {
		if (value) {
			if (atoi(value) == 1)
				current_instrument->network = TRUE;
		} else {
			if (current_instrument->network)
				sprintf(buf, "1");
		}
	} else if (strcmp(elems[1], REGEX_TOK) == 0) {
		if (value) {
			current_instrument->id_regex = strdup(value);
		} else {
			if (current_instrument->id_regex)
				sprintf(buf, "%s", current_instrument->id_regex);
		}
	} else if (strcmp(elems[1], IP_TOK) == 0) {
		if (value) {
			current_instrument->ip_address = strdup(value);
		} else {
			if (current_instrument->ip_address && current_instrument->network)
				sprintf(buf, "%s", current_instrument->ip_address);
		}
	} else if (strcmp(elems[1], TTY_TOK) == 0) {
		if (value) {
			current_instrument->tty_path = strdup(value);
		} else {
			if (current_instrument->tty_path && current_instrument->serial)
				sprintf(buf, "%s", current_instrument->tty_path);
		}
	} else if (strcmp(elems[1], GPIB_TOK) == 0) {
		if (value) {
			current_instrument->gpib_addr = atoi(value);
		} else {
			if (current_instrument->gpib_addr && current_instrument->serial)
				sprintf(buf, "%i", current_instrument->gpib_addr);
		}
	} else
	/* There are some things testers need to add by hand to do things */
	if (strcmp(elems[1], CON_TOK) == 0) {
		if (value) {
			if (atoi(value) == 1)
				if (scpi_connect(current_instrument) != 0)
					return "FAIL";
		}
		/* We don't save the connect state */
	} else if (MATCH_ATTRIB("tx.freq")) {
		if (value)
			tx_freq_set_Hz(&signal_generator, atoll(value));
		/* We don't save the frequency */
	} else if (MATCH_ATTRIB("tx.mag")) {
		if (value)
			tx_mag_set_dBm(&signal_generator, atof(value));
		/* Don't save the magintude */
	} else if (MATCH_ATTRIB("tx.on")) {
		if (value)
			tx_output_set(&signal_generator, atoi(value));
		/* Don't save the on/off state */
	} else if (MATCH_ATTRIB("rx.setup")) {
		if (value)
			scpi_rx_setup(&spectrum_analyzer);
	} else if (MATCH_ATTRIB("rx.center")) {
		if (value)
			scpi_rx_set_center_frequency(atoll(value));
	} else if (MATCH_ATTRIB("rx.span")) {
		if (value)
			scpi_rx_set_span_frequency(atoll(value));
	} else if (!strncmp(attrib, "rx.marker", strlen("rx.marker"))) {
		if (value) {
			i = atoi(&attrib[strlen("rx.marker")]);
			j = atoll(value);
			if (i && j)
				scpi_rx_set_marker_freq(i, j);
			else
				printf("problems with %s = %s\n", attrib, value);
		}
	} else if (!strncmp(attrib, "rx.log.marker", strlen("rx.log.marker"))) {
		if (value) {
			i = atoi(&attrib[strlen("rx.log.marker")]);
			if (i) {
				scpi_rx_get_marker_level(i, true, &lvl);
				fd = fopen(value, "a");
				if (!fd)
					return NULL;

				fprintf (fd, "%f, ", lvl);
				fclose (fd);
			}
		}
	} else if (!strncmp(attrib, "rx.test.marker", strlen("rx.test.marker"))) {
		if (value) {
			i = atoi(&attrib[strlen("rx.test.marker")]);
			if (i) {
				scpi_rx_get_marker_level(i, true, &lvl);
				min_max = g_strsplit(value, " ", 0);
				if (lvl >= atof(min_max[1]) && lvl <= atof(min_max[0])) {
					printf("Marker%i (%f) didn't match requirements (%f - %f)\n",
						i, lvl, atof(min_max[0]), atof(min_max[1]));
					return "FAIL";
				}
			} else {
				return "FAIL";
			}
		}
	} else {
		printf("Unhandled tokens in ini file,\n"
				"\tSection %s\n\tAtttribute : %s\n\tValue: %s\n",
				"SCPI", attrib, value);
		if (value)
			return "FAIL";
	}

	return buf;
}
 int IValue(){return (int)(atoi(this->valueStr.c_str()));}
Exemplo n.º 13
0
int main (int argc, char *argv[])
{
   int i;
   USHORT Purge, Pack, Import, Export, DaysOld, List, Update;
   USHORT KeepDate;
   CHAR *Config = NULL;

#if !defined(__LINUX__)
   _grow_handles (64);
#endif

   Update = Purge = Pack = List = Import = Export = FALSE;
   KeepDate = FALSE;
   DaysOld = 65535U;

   cprintf ("\r\nLFILE; %s v%s - File maintenance utility\r\n", NAME, VERSION);
   cprintf ("       Copyright (c) 1991-96 by Marco Maccaferri. All Rights Reserved.\r\n\r\n");

/*
   if (ValidateKey ("bbs", NULL, NULL) == KEY_UNREGISTERED) {
      cprintf ("* * *     WARNING: No license key found    * * *\r\n");
      if ((i = CheckExpiration ()) == 0) {
         cprintf ("* * *   This evaluation copy has expired   * * *\r\n\a\r\n");
         exit (0);
      }
      else
         cprintf ("* * * You have %2d days left for evaluation * * * \r\n\a\r\n", i);
   }
*/

   if (argc <= 1) {
      cprintf (" * Command-line parameters:\r\n\r\n");

      cprintf ("        -U[K]     Update FILEBASE\r\n");
      cprintf ("                  K=Keep file date\r\n");
      cprintf ("        -I        Import from FILES.BBS\r\n");
      cprintf ("        -E        Export to FILES.BBS\r\n");
      cprintf ("        -P[K]     Pack (compress) file base\r\n");
      cprintf ("                  K=Purge\r\n");
      cprintf ("        -K<d>     Purge files that are <d> days old\r\n");
      cprintf ("        -L        Create a list of available files\r\n");
      cprintf ("        -C<n>     Multiline descriptions begin at column <n>\r\n");
      cprintf ("        -S<c>     Use <c> as the identifier of a multiline description\r\n");

      cprintf ("\r\n * Please refer to the documentation for a more complete command summary\r\n\r\n");
   }
   else {
      for (i = 1; i < argc; i++) {
         if (argv[i][0] == '-' || argv[i][0] == '/') {
            switch (toupper (argv[i][1])) {
               case 'C':
                  Column = (USHORT)(atoi (&argv[i][2]));
                  break;
               case 'I':
                  Import = TRUE;
                  break;
               case 'E':
                  Export = TRUE;
                  break;
               case 'K':
                  Purge = TRUE;
                  DaysOld = (USHORT)atoi (&argv[i][1]);
                  break;
               case 'L':
                  List = TRUE;
                  break;
               case 'P':
                  Pack = TRUE;
                  if (toupper (argv[i][2]) == 'K')
                     Purge = TRUE;
                  break;
               case 'S':
                  Symbol = argv[i][2];
                  break;
               case 'U':
                  Update = TRUE;
                  if (toupper (argv[i][2]) == 'K')
                     KeepDate = TRUE;
                  break;
            }
         }
         else if (Config == NULL)
            Config = argv[i];
      }

      if ((Cfg = new TConfig) != NULL) {
         if (Cfg->Load (Config, NULL) == FALSE)
            Cfg->Default ();
      }

      if (Update == TRUE)
         UpdateFilebase (KeepDate);
      if (Import == TRUE)
         ImportFilesBBS ();
      if (Purge == TRUE)
         PurgeFiles (DaysOld);
      if (Pack == TRUE)
         PackFilebase ();
      if (Export == TRUE)
         ExportFilesBBS ();
      if (List == TRUE)
         CreateFilesList ();

      if (Import == TRUE || Export == TRUE || Purge == TRUE || Pack == TRUE || List == TRUE || Update == TRUE)
         cprintf (" * Done\r\n\r\n");
      else
         cprintf (" * Nothing to do\r\n\r\n");

      if (Cfg != NULL)
         delete Cfg;
   }

   return 0;
}
Exemplo n.º 14
0
int
main(int ac, char **av) {
  int c, i, mntsize;
  char **command;
  struct procfs_status pfs;
  struct ex_types *funcs;
  struct statfs *mntbuf;
  int in_exec = 0;
  char *fname = NULL;
  int sigexit = 0;
  struct trussinfo *trussinfo;

  /* Initialize the trussinfo struct */
  trussinfo = (struct trussinfo *)malloc(sizeof(struct trussinfo));
  if (trussinfo == NULL)
	  errx(1, "malloc() failed");
  bzero(trussinfo, sizeof(struct trussinfo));
  trussinfo->outfile = stderr;

  /* Check where procfs is mounted if it is mounted */
  if ((mntsize = getmntinfo(&mntbuf, MNT_NOWAIT)) == 0)
	  err(1, "getmntinfo");
  for (i = 0; i < mntsize; i++) {
	  if (strcasecmp(mntbuf[i].f_mntfromname, "procfs") == 0) {
		  strlcpy(procfs_path, mntbuf[i].f_mntonname, sizeof(procfs_path));
		  have_procfs = 1;
		  break;
	  }
  }
  if (!have_procfs) {
	  errno = 2;
	  err(1, "You must have a mounted procfs to use truss");
  }

  while ((c = getopt(ac, av, "p:o:S")) != -1) {
    switch (c) {
    case 'p':	/* specified pid */
      trussinfo->pid = atoi(optarg);
      if (trussinfo->pid == getpid()) {
	      /* make sure truss doesn't trace itself */
	      fprintf(stderr, "truss: attempt to self trace: %d\n", trussinfo->pid);
	      exit(2);
      }
      break;
    case 'o':	/* Specified output file */
      fname = optarg;
      break;
    case 'S':	/* Don't trace signals */ 
      trussinfo->flags |= NOSIGS;
      break;
    default:
      usage();
    }
  }

  ac -= optind; av += optind;
  if ((trussinfo->pid == 0 && ac == 0) || (trussinfo->pid != 0 && ac != 0))
    usage();

  if (fname != NULL) { /* Use output file */
    if ((trussinfo->outfile = fopen(fname, "w")) == NULL)
      errx(1, "cannot open %s", fname);
  }

  /*
   * If truss starts the process itself, it will ignore some signals --
   * they should be passed off to the process, which may or may not
   * exit.  If, however, we are examining an already-running process,
   * then we restore the event mask on these same signals.
   */

  if (trussinfo->pid == 0) {	/* Start a command ourselves */
    command = av;
    trussinfo->pid = setup_and_wait(command);
    signal(SIGINT, SIG_IGN);
    signal(SIGTERM, SIG_IGN);
    signal(SIGQUIT, SIG_IGN);
  } else {
    signal(SIGINT, restore_proc);
    signal(SIGTERM, restore_proc);
    signal(SIGQUIT, restore_proc);
  }


  /*
   * At this point, if we started the process, it is stopped waiting to
   * be woken up, either in exit() or in execve().
   */

  Procfd = start_tracing(
      trussinfo->pid, S_EXEC | S_SCE | S_SCX | S_CORE | S_EXIT |
		     ((trussinfo->flags & NOSIGS) ? 0 : S_SIG));
  if (Procfd == -1)
    return 0;

  pfs.why = 0;

  funcs = set_etype(trussinfo);
  /*
   * At this point, it's a simple loop, waiting for the process to
   * stop, finding out why, printing out why, and then continuing it.
   * All of the grunt work is done in the support routines.
   */

  do {
    int val = 0;

    if (ioctl(Procfd, PIOCWAIT, &pfs) == -1)
      warn("PIOCWAIT top of loop");
    else {
      switch(i = pfs.why) {
      case S_SCE:
	funcs->enter_syscall(trussinfo, pfs.val);
	break;
      case S_SCX:
	/*
	 * This is so we don't get two messages for an exec -- one
	 * for the S_EXEC, and one for the syscall exit.  It also,
	 * conveniently, ensures that the first message printed out
	 * isn't the return-from-syscall used to create the process.
	 */

	if (in_exec) {
	  in_exec = 0;
	  break;
	}
	funcs->exit_syscall(trussinfo, pfs.val);
	break;
      case S_SIG:
	fprintf(trussinfo->outfile, "SIGNAL %lu\n", pfs.val);
	sigexit = pfs.val;
	break;
      case S_EXIT:
	fprintf (trussinfo->outfile, "process exit, rval = %lu\n", pfs.val);
	break;
      case S_EXEC:
	funcs = set_etype(trussinfo);
	in_exec = 1;
	break;
      default:
	fprintf (trussinfo->outfile, "Process stopped because of:  %d\n", i);
	break;
      }
    }
    if (ioctl(Procfd, PIOCCONT, val) == -1) {
      if (kill(trussinfo->pid, 0) == -1 && errno == ESRCH)
	break;
      else
	warn("PIOCCONT");
    }
  } while (pfs.why != S_EXIT);
  fflush(trussinfo->outfile);
  if (sigexit) {
    if (sigexit == SIGQUIT)
      exit(sigexit);
    (void) signal(sigexit, SIG_DFL);
    (void) kill(getpid(), sigexit);
  }
  return 0;
}
int main(int argc, char **argv)
{
	uint32_t *handle, *start_val;
	uint32_t start = 0;
	int i, fd, count;

	igt_simple_init(argc, argv);

	fd = drm_open_driver(DRIVER_INTEL);

	igt_require(IS_GEN3(intel_get_drm_devid(fd)));

	count = 0;
	if (argc > 1)
		count = atoi(argv[1]);
	if (count == 0)
		count = 3 * gem_aperture_size(fd) / (1024*1024) / 2;
	igt_info("Using %d 1MiB buffers\n", count);

	handle = malloc(sizeof(uint32_t)*count*2);
	start_val = handle + count;

	for (i = 0; i < count; i++) {
		handle[i] = create_bo(fd, start);
		start_val[i] = start;
		start += 1024 * 1024 / 4;
	}

	igt_info("Verifying initialisation...\n");
	for (i = 0; i < count; i++)
		check_bo(fd, handle[i], start_val[i]);

	igt_info("Cyclic blits, forward...\n");
	for (i = 0; i < count * 4; i++) {
		int src = i % count;
		int dst = (i + 1) % count;

		copy(fd, handle[dst], handle[src]);
		start_val[dst] = start_val[src];
	}
	for (i = 0; i < count; i++)
		check_bo(fd, handle[i], start_val[i]);

	igt_info("Cyclic blits, backward...\n");
	for (i = 0; i < count * 4; i++) {
		int src = (i + 1) % count;
		int dst = i % count;

		copy(fd, handle[dst], handle[src]);
		start_val[dst] = start_val[src];
	}
	for (i = 0; i < count; i++)
		check_bo(fd, handle[i], start_val[i]);

	igt_info("Random blits...\n");
	for (i = 0; i < count * 4; i++) {
		int src = random() % count;
		int dst = random() % count;

		if (src == dst)
			continue;

		copy(fd, handle[dst], handle[src]);
		start_val[dst] = start_val[src];
	}
	for (i = 0; i < count; i++)
		check_bo(fd, handle[i], start_val[i]);

	igt_exit();
}
Exemplo n.º 16
0
int main(int argc, char *argv[]) {


#ifdef EPETRA_MPI

  // Initialize MPI

  MPI_Init( &argc, &argv );
  //int size, rank; // Number of MPI processes, My process ID

  //MPI_Comm_size(MPI_COMM_WORLD, &size);
  //MPI_Comm_rank(MPI_COMM_WORLD, &rank);

#else

  //int size = 1; // Serial case (not using MPI)
  //int rank = 0;

#endif

  bool verbose = false;

  int nx = 5;
  int ny = 5;

  if( argc > 1 )
  {
    if( argc > 4 )
    {
      cout << "Usage: " << argv[0] << " [-v [nx [ny]]]" << endl;
      exit(1);
    }

    int loc = 1;
    // Check if we should print results to standard out
    if(argv[loc][0]=='-' && argv[loc][1]=='v')
    { verbose = true; ++loc; }

    if (loc < argc) nx = atoi( argv[loc++] );
    if( loc < argc) ny = atoi( argv[loc] );
  }

#ifdef EPETRA_MPI
  Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
  Epetra_SerialComm Comm;
#endif

  int MyPID = Comm.MyPID();
  int NumProc = Comm.NumProc();

  bool verbose1 = false;
  if(verbose) verbose1 = (MyPID==0);

  if(verbose1)
    cout << EpetraExt::EpetraExt_Version() << endl << endl;

  Comm.Barrier();

  if(verbose) cout << Comm << endl << flush;
  Comm.Barrier();

  int NumGlobalElements = nx * ny;
  if( NumGlobalElements < NumProc )
  {
    cout << "NumGlobalElements = " << NumGlobalElements <<
            " cannot be < number of processors = " << NumProc;
    exit(1);
  } 
	
  int IndexBase = 0;
  Epetra_Map Map( NumGlobalElements, IndexBase, Comm );

  // Extract the global indices of the elements local to this processor
  int NumMyElements = Map.NumMyElements();
  std::vector<int> MyGlobalElements( NumMyElements );
  Map.MyGlobalElements( &MyGlobalElements[0] );
  if( verbose ) cout << Map;

  // Create the number of non-zeros for a tridiagonal (1D problem) or banded
  // (2D problem) matrix
  std::vector<int> NumNz( NumMyElements, 5 );
  int global_i;
  int global_j;
  for (int i = 0; i < NumMyElements; ++i)
  {
    global_j = MyGlobalElements[i] / nx;
    global_i = MyGlobalElements[i] - global_j * nx;
    if (global_i == 0)    NumNz[i] -= 1;  // By having separate statements,
    if (global_i == nx-1) NumNz[i] -= 1;  // this works for 2D as well as 1D
    if (global_j == 0)    NumNz[i] -= 1;  // systems (i.e. nx x 1 or 1 x ny)
    if (global_j == ny-1) NumNz[i] -= 1;  // or even a 1 x 1 system
  }
  if(verbose)
  { 
    cout << endl << "NumNz: ";
    for (int i = 0; i < NumMyElements; i++) cout << NumNz[i] << " ";
    cout << endl;
  } // end if
  
  // Create the Epetra Compressed Row Sparse Graph
  Epetra_CrsGraph A( Copy, Map, &NumNz[0] );
  
  std::vector<int> Indices(5);
  int NumEntries;
  
  for (int i = 0; i < NumMyElements; ++i )
  {
    global_j = MyGlobalElements[i] / nx;
    global_i = MyGlobalElements[i] - global_j * nx;
    NumEntries = 0;
    // (i,j-1) entry
    if (global_j > 0 && ny > 1)
      Indices[NumEntries++] = global_i   + (global_j-1)*nx;
    // (i-1,j) entry
    if (global_i > 0)
      Indices[NumEntries++] = global_i-1 +  global_j   *nx;
    // (i,j) entry
    Indices[NumEntries++] = MyGlobalElements[i];
    // (i+1,j) entry
    if (global_i < nx-1)
      Indices[NumEntries++] = global_i+1 +  global_j   *nx;
    // (i,j+1) entry
    if (global_j < ny-1 && ny > 1)
      Indices[NumEntries++] = global_i   + (global_j+1)*nx;

    // Insert the global indices
    A.InsertGlobalIndices( MyGlobalElements[i], NumEntries, &Indices[0] );
  } // end i loop

  // Finish up graph construction
  A.FillComplete();

  EpetraExt::CrsGraph_MapColoring
    Greedy0MapColoringTransform( EpetraExt::CrsGraph_MapColoring::GREEDY,
		                 0, false, verbose );
  Epetra_MapColoring & Greedy0ColorMap = Greedy0MapColoringTransform( A );
  printColoring(Greedy0ColorMap, &A,verbose);

  EpetraExt::CrsGraph_MapColoring
    Greedy1MapColoringTransform( EpetraExt::CrsGraph_MapColoring::GREEDY,
		                 1, false, verbose );
  Epetra_MapColoring & Greedy1ColorMap = Greedy1MapColoringTransform( A );
  printColoring(Greedy1ColorMap, &A,verbose);

  EpetraExt::CrsGraph_MapColoring
    Greedy2MapColoringTransform( EpetraExt::CrsGraph_MapColoring::GREEDY,
		                 2, false, verbose );
  Epetra_MapColoring & Greedy2ColorMap = Greedy2MapColoringTransform( A );
  printColoring(Greedy2ColorMap, &A,verbose);

  EpetraExt::CrsGraph_MapColoring
    Lubi0MapColoringTransform( EpetraExt::CrsGraph_MapColoring::LUBY,
		               0, false, verbose );
  Epetra_MapColoring & Lubi0ColorMap = Lubi0MapColoringTransform( A );
  printColoring(Lubi0ColorMap, &A,verbose);

  EpetraExt::CrsGraph_MapColoring
    Lubi1MapColoringTransform( EpetraExt::CrsGraph_MapColoring::LUBY,
		               1, false, verbose );
  Epetra_MapColoring & Lubi1ColorMap = Lubi1MapColoringTransform( A );
  printColoring(Lubi1ColorMap, &A,verbose);

  EpetraExt::CrsGraph_MapColoring
    Lubi2MapColoringTransform( EpetraExt::CrsGraph_MapColoring::LUBY,
		               2, false, verbose );
  Epetra_MapColoring & Lubi2ColorMap = Lubi2MapColoringTransform( A );
  printColoring(Lubi2ColorMap, &A,verbose);

#ifdef EPETRA_MPI
  if( verbose ) cout << "Parallel Map Coloring 1!\n";
  EpetraExt::CrsGraph_MapColoring
    Parallel1MapColoringTransform( EpetraExt::CrsGraph_MapColoring::PSEUDO_PARALLEL,
		                   0, false, verbose );
  Epetra_MapColoring & Parallel1ColorMap = Parallel1MapColoringTransform( A );
  printColoring(Parallel1ColorMap, &A,verbose);

  if( verbose ) cout << "Parallel Map Coloring 2!\n";
  EpetraExt::CrsGraph_MapColoring
    Parallel2MapColoringTransform( EpetraExt::CrsGraph_MapColoring::JONES_PLASSMAN,
		                   0, false, verbose );
  Epetra_MapColoring & Parallel2ColorMap = Parallel2MapColoringTransform( A );
  printColoring(Parallel2ColorMap, &A,verbose);
#endif


#ifdef EPETRA_MPI
  MPI_Finalize();
#endif

  return 0;
}
Exemplo n.º 17
0
/* open-by-name support for file descriptors */
afs_uint32
xfon_fd(XFILE * X, int flag, char *name)
{
    int fd = atoi(name);
    return xfopen_fd(X, flag, fd);
}
Exemplo n.º 18
0
int TlenMUCRecvError(const char *from, XmlNode *errorNode)
{
	int errCode;
	char str[512];
	JABBER_LIST_ITEM *item;
	MUCCEVENT mucce;
	mucce.cbSize = sizeof(MUCCEVENT);
	mucce.iType = MUCC_EVENT_ERROR;
	mucce.pszID = from;
	mucce.pszModule = jabberProtoName;
	errCode = atoi(JabberXmlGetAttrValue(errorNode, "code"));
	switch (errCode) {
		case 403:
			sprintf(str, Translate("You cannot join this chat room, because you are banned."));
			break;
		case 404:
			sprintf(str, Translate("Chat room not found."));
			break;
		case 407:
			sprintf(str, Translate("This is a private chat room and you are not one of the members."));
			break;
		case 408:
			sprintf(str, Translate("You cannot send any message unless you join this chat room."));
			break;
		case 410:
			sprintf(str, Translate("Chat room with already created."));
			break;
		case 411:
			sprintf(str, Translate("Nickname '%s' is already registered."),
				JabberXmlGetAttrValue(errorNode, "n"));
			break;
		case 412:
			sprintf(str, Translate("Nickname already in use, please try another one. Hint: '%s' is free."),
				JabberXmlGetAttrValue(errorNode, "free"));
			break;
		case 413:
			sprintf(str, Translate("You cannot register more than %s nicknames."),
				JabberXmlGetAttrValue(errorNode, "num"));
			break;
		case 414:
			sprintf(str, Translate("You cannot create more than %s chat rooms."),
				JabberXmlGetAttrValue(errorNode, "num"));
			break;
		case 415:
			sprintf(str, Translate("You cannot join more than %s chat rooms."),
				JabberXmlGetAttrValue(errorNode, "num"));
			break;
		case 601:
			sprintf(str, Translate("Anonymous nicknames are not allowed in this chat room."));
			break;
		default:
			sprintf(str, Translate("Unknown error code : %d"), errCode);
			break;
	}
	mucce.pszText = str;
	CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
	if (jabberOnline) {
		switch (errCode) {
			case 412:
				item = JabberListGetItemPtr(LIST_CHATROOM, from);
				if (item!=NULL) {
					mucce.iType = MUCC_EVENT_JOIN;
					mucce.dwFlags = MUCC_EF_ROOM_NICKNAMES;
					mucce.pszModule = jabberProtoName;
					mucce.pszID = from;
					mucce.pszName = item->roomName;
					mucce.pszNick = JabberXmlGetAttrValue(errorNode, "free");
					CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
				}
				break;
			case 601:
				item = JabberListGetItemPtr(LIST_CHATROOM, from);
				if (item!=NULL) {
					mucce.iType = MUCC_EVENT_JOIN;
					mucce.dwFlags = 0;
					mucce.pszModule = jabberProtoName;
					mucce.pszID = from;
					mucce.pszName = item->roomName;
					mucce.pszNick = NULL;
					CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
				}
				break;
		}
	}
	return 1;
}
Exemplo n.º 19
0
struct Cookie *
Curl_cookie_add(struct CookieInfo *c,
                bool httpheader, /* TRUE if HTTP header-style line */
                char *lineptr,   /* first non-space of the line */
                char *domain)    /* default domain */
{
  struct Cookie *clist;
  char what[MAX_COOKIE_LINE];
  char name[MAX_NAME];
  char *ptr;
  char *semiptr;
  struct Cookie *co;
  struct Cookie *lastc=NULL;
  time_t now = time(NULL);
  bool replace_old = FALSE;

  /* First, alloc and init a new struct for it */
  co = (struct Cookie *)malloc(sizeof(struct Cookie));
  if(!co)
    return NULL; /* bail out if we're this low on memory */

  /* clear the whole struct first */
  memset(co, 0, sizeof(struct Cookie));
	    
  if(httpheader) {
    /* This line was read off a HTTP-header */
    char *sep;
    semiptr=strchr(lineptr, ';'); /* first, find a semicolon */
    ptr = lineptr;
    do {
      /* we have a <what>=<this> pair or a 'secure' word here */
      sep = strchr(ptr, '=');
      if(sep && (!semiptr || (semiptr>sep)) ) {
        /*
         * There is a = sign and if there was a semicolon too, which make sure
         * that the semicolon comes _after_ the equal sign.
         */

        name[0]=what[0]=0; /* init the buffers */
        if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;=]=%"
                       MAX_COOKIE_LINE_TXT "[^;\r\n]",
                       name, what)) {
          /* this is a <name>=<what> pair */

          /* Strip off trailing whitespace from the 'what' */
          int len=strlen(what);
          while(len && isspace((int)what[len-1])) {
            what[len-1]=0;
            len--;
          }

          if(strequal("path", name)) {
            co->path=strdup(what);
          }
          else if(strequal("domain", name)) {
            co->domain=strdup(what);
            co->field1= (what[0]=='.')?2:1;
          }
          else if(strequal("version", name)) {
            co->version=strdup(what);
          }
          else if(strequal("max-age", name)) {
            /* Defined in RFC2109:

               Optional.  The Max-Age attribute defines the lifetime of the
               cookie, in seconds.  The delta-seconds value is a decimal non-
               negative integer.  After delta-seconds seconds elapse, the
               client should discard the cookie.  A value of zero means the
               cookie should be discarded immediately.

             */
            co->maxage = strdup(what);
            co->expires =
              atoi((*co->maxage=='\"')?&co->maxage[1]:&co->maxage[0]) + now;
          }
          else if(strequal("expires", name)) {
            co->expirestr=strdup(what);
            co->expires = curl_getdate(what, &now);
          }
          else if(!co->name) {
            co->name = strdup(name);
            co->value = strdup(what);
          }
          /*
            else this is the second (or more) name we don't know
            about! */
        }
        else {
          /* this is an "illegal" <what>=<this> pair */
        }
      }
      else {
        if(sscanf(ptr, "%" MAX_COOKIE_LINE_TXT "[^;\r\n]",
                  what)) {
          if(strequal("secure", what))
            co->secure = TRUE;
          /* else,
             unsupported keyword without assign! */

        }
      }
      if(!semiptr || !*semiptr) {
        /* we already know there are no more cookies */
        semiptr = NULL;
        continue;
      }

      ptr=semiptr+1;
      while(ptr && *ptr && isspace((int)*ptr))
        ptr++;
      semiptr=strchr(ptr, ';'); /* now, find the next semicolon */

      if(!semiptr && *ptr)
        /* There are no more semicolons, but there's a final name=value pair
           coming up */
        semiptr=strchr(ptr, '\0');
    } while(semiptr);

    if(NULL == co->name) {
      /* we didn't get a cookie name, this is an illegal line, bail out */
      if(co->domain)
        free(co->domain);
      if(co->path)
        free(co->path);
      if(co->name)
        free(co->name);
      if(co->value)
        free(co->value);
      free(co);
      return NULL;
    }

    if(NULL == co->domain)
      /* no domain given in the header line, set the default now */
      co->domain=domain?strdup(domain):NULL;
  }
  else {
    /* This line is NOT a HTTP header style line, we do offer support for
       reading the odd netscape cookies-file format here */
    char *firstptr;
    char *tok_buf;
    int fields;

    if(lineptr[0]=='#') {
      /* don't even try the comments */
      free(co);
      return NULL;
    }
    /* strip off the possible end-of-line characters */
    ptr=strchr(lineptr, '\r');
    if(ptr)
      *ptr=0; /* clear it */
    ptr=strchr(lineptr, '\n');
    if(ptr)
      *ptr=0; /* clear it */

    firstptr=strtok_r(lineptr, "\t", &tok_buf); /* first tokenize it on the TAB */

    /* Here's a quick check to eliminate normal HTTP-headers from this */
    if(!firstptr || strchr(firstptr, ':')) {
      free(co);
      return NULL;
    }

    /* Now loop through the fields and init the struct we already have
       allocated */
    for(ptr=firstptr, fields=0; ptr; ptr=strtok_r(NULL, "\t", &tok_buf), fields++) {
      switch(fields) {
      case 0:
        co->domain = strdup(ptr);
        break;
      case 1:
        /* This field got its explanation on the 23rd of May 2001 by
           Andrés García:

           flag: A TRUE/FALSE value indicating if all machines within a given
           domain can access the variable. This value is set automatically by
           the browser, depending on the value you set for the domain.

           As far as I can see, it is set to true when the cookie says
           .domain.com and to false when the domain is complete www.domain.com

           We don't currently take advantage of this knowledge.
        */
        co->field1=strequal(ptr, "TRUE")+1; /* store information */
        break;
      case 2:
        /* It turns out, that sometimes the file format allows the path
           field to remain not filled in, we try to detect this and work
           around it! Andrés García made us aware of this... */
        if (strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
          /* only if the path doesn't look like a boolean option! */
          co->path = strdup(ptr);
          break;
        }
        /* this doesn't look like a path, make one up! */
        co->path = strdup("/");
        fields++; /* add a field and fall down to secure */
        /* FALLTHROUGH */
      case 3:
        co->secure = strequal(ptr, "TRUE");
        break;
      case 4:
        co->expires = atoi(ptr);
        break;
      case 5:
        co->name = strdup(ptr);
        break;
      case 6:
        co->value = strdup(ptr);
        break;
      }
    }

    if(7 != fields) {
      /* we did not find the sufficient number of fields to recognize this
         as a valid line, abort and go home */

      if(co->domain)
        free(co->domain);
      if(co->path)
        free(co->path);
      if(co->name)
        free(co->name);
      if(co->value)
        free(co->value);

      free(co);
      return NULL;
    }

  }

  co->livecookie = c->running;

  /* now, we have parsed the incoming line, we must now check if this
     superceeds an already existing cookie, which it may if the previous have
     the same domain and path as this */

  clist = c->cookies;
  replace_old = FALSE;
  while(clist) {
    if(strequal(clist->name, co->name)) {
      /* the names are identical */

      if(clist->domain && co->domain) {
        if(strequal(clist->domain, co->domain))
          replace_old=TRUE;
      }
      else if(!clist->domain && !co->domain)
        replace_old = TRUE;

      if(replace_old) {
        /* the domains were identical */

        if(clist->path && co->path) {
          if(strequal(clist->path, co->path)) {
            replace_old = TRUE;
          }
          else
            replace_old = FALSE;
        }
        else if(!clist->path && !co->path)
          replace_old = TRUE;
        else
          replace_old = FALSE;
        
      }

      if(replace_old && !co->livecookie && clist->livecookie) {
        /* Both cookies matched fine, except that the already present
           cookie is "live", which means it was set from a header, while
           the new one isn't "live" and thus only read from a file. We let
           live cookies stay alive */

        /* Free the newcomer and get out of here! */
        if(co->domain)
          free(co->domain);
        if(co->path)
          free(co->path);
        if(co->name)
          free(co->name);
        if(co->value)
          free(co->value);

        free(co);
        return NULL;
      }

      if(replace_old) {
        co->next = clist->next; /* get the next-pointer first */

        /* then free all the old pointers */
        if(clist->name)
          free(clist->name);
        if(clist->value)
          free(clist->value);
        if(clist->domain)
          free(clist->domain);
        if(clist->path)
          free(clist->path);
        if(clist->expirestr)
          free(clist->expirestr);

        if(clist->version)
          free(clist->version);
        if(clist->maxage)
          free(clist->maxage);

        *clist = *co;  /* then store all the new data */

        free(co);   /* free the newly alloced memory */
        co = clist; /* point to the previous struct instead */

        /* We have replaced a cookie, now skip the rest of the list but
           make sure the 'lastc' pointer is properly set */
        do {
          lastc = clist;
          clist = clist->next;
        } while(clist);
        break;
      }
    }
    lastc = clist;
    clist = clist->next;
  }

  if(!replace_old) {
    /* then make the last item point on this new one */
    if(lastc)
      lastc->next = co;
    else
      c->cookies = co;
  }

  c->numcookies++; /* one more cookie in the jar */

  return co;
}
Exemplo n.º 20
0
short processRadioMessages(char *buf, short lenth) {
  short cmdIndex = -1;
  char cmd[lenth];
  char token2[lenth];
  short i = 0;
  short changeLeve = 0;
  short parameter = 0;
  float parameterF = 0.0;
  float rollSpShift = 0;
  float pitchSpShift = 0;
  float yawShiftValue = 0;
  float throttlePercentage = 0;
  static unsigned long  radio_last_tv3 = 0;

#if 0
   unsigned long tv=millis();
  Serial.println(tv-radio_last_tv3);
   radio_last_tv3=tv;
  // Serial.println(buf);
#endif

  resetPacketAccCounter();
  

  memset(cmd, '\0', sizeof(cmd));

  for (i = 1; buf[i] != '#'; i++) {
    cmd[i - 1] = buf[i];
  }
 
  qToken(cmd, token2,lenth, 0);
  cmdIndex = atoi(token2);


  switch (cmdIndex) {
    case ON_OFF_FLY_SYSTEM_MESSAGE:

	  qToken(cmd, token2,lenth,ON_OFF_FLY);
      parameter = atoi(token2);

      if (1 == parameter) {
          enableFlySystem();
      } else {
        disenableFlySystem();
      }

      break;
    case PILOT_CONTROL_MESSAGE:
     // printf("%s\n",buf);

	  qToken(cmd, token2,lenth, THROTTLE_LEVEL);
      parameter = atoi(token2);
	  
      qToken(cmd, token2,lenth, ROLL_SP_SHIFT);
      rollSpShift = atof(token2);

      qToken(cmd, token2,lenth, PITCH_SP_SHIFT);
      pitchSpShift = atof(token2);

       qToken(cmd, token2,lenth, YAW_SP_SHIFT);
      yawShiftValue = atof(token2);
      //printf("factor=%d\n",(int)(((float)(parameter-100)/(float)100)*(float)(MAX_POWER_LEVEL-MIN_POWER_LEVEL)));
      //printf("parameter=%d\n",parameter);
      throttlePercentage = (float)parameter / 100.f;
      parameter = getMinPowerLevel()
                  + (int) (throttlePercentage
                           * (float) (getMaxPowerLeve()
                                      - getMinPowerLevel())); /*(100~200)*10=1000~2000 us*/
      //printf("getMaxPowerLeveRange()- getMinPowerLeveRange()=%f\n",getMaxPowerLeve()- getMinPowerLevel());
      //printf("parameter=%d\n",parameter);

      if (parameter > getMaxPowerLeve()
          || parameter < getMinPowerLevel()) {
         printf( "break\n");
        break;
      }
      if (true == flySystemIsEnable()) {

        setThrottlePowerLevel(parameter);

        if (getMinPowerLevel() == parameter) {
          //printf("STOP\n");
          resetPidRecord(&rollAttitudePidSettings);
          resetPidRecord(&pitchAttitudePidSettings);
          resetPidRecord(&yawAttitudePidSettings);
          resetPidRecord(&rollRatePidSettings);
          resetPidRecord(&pitchRatePidSettings);
          resetPidRecord(&yawRatePidSettings);
          setYawCenterPoint(0);
          setPidSp(&yawAttitudePidSettings, 321.0);

        } else {
          if (getPidSp(&yawAttitudePidSettings) == 321.0) {
             printf( "START Flying\n");
            setYawCenterPoint(getYaw());
            setPidSp(&yawAttitudePidSettings, 0);
          }
          setPidSp(&rollAttitudePidSettings,
                   LIMIT_MIN_MAX_VALUE(rollSpShift, -getAngularLimit(),
                                       getAngularLimit()));
          setPidSp(&pitchAttitudePidSettings,
                   LIMIT_MIN_MAX_VALUE(pitchSpShift, -getAngularLimit(),
                                       getAngularLimit()));
          setYawCenterPoint(getYawCenterPoint() + (yawShiftValue * 1.0));

        }

      }

      //printf("throttle=%d roll=%f pitch=%f\n",parameter,rollSpShift,pitchSpShift);

      break;



    case SYSTEM_SETTING_MESSAGE:
       printf( "%s " , buf);

	  qToken(cmd, token2,lenth, ANAGULAR_VELOVITY_LIMIT);
      parameterF = atof(token2);
      if (parameterF == 0) {
        parameterF = 1;
      }
      setGyroLimit(parameterF);
	  printf( "Angular Velocity Limit: %4.3f\n",getGyroLimit());
      /***/

	  qToken(cmd, token2,lenth, ROLL_CALIBRATION);
      parameterF = atof(token2);
      setPidSpShift(&rollAttitudePidSettings, parameterF);
	  printf( "Roll Angular Calibration: %4.3f\n",getPidSpShift(&rollAttitudePidSettings));

      /***/

	  qToken(cmd, token2,lenth, PITCH_CALIBRATION);
      parameterF = atof(token2);
      setPidSpShift(&pitchAttitudePidSettings, parameterF);
	  printf( "Pitch Angular Calibration: %4.3f\n",getPidSpShift(&pitchAttitudePidSettings));


      break;

    case PID_SETTING_MESSAGE:
	
       printf("%s\n", buf);

    
	  qToken(cmd, token2,lenth, ATTITUDE_ROLL_P);
      parameterF = atof(token2);
      setPGain(&rollAttitudePidSettings, parameterF);
       printf( "Attitude Roll P Gain=%f\n", getPGain(&rollAttitudePidSettings));

      
      qToken(cmd, token2,lenth, ATTITUDE_ROLL_I);
      parameterF = atof(token2);
      setIGain(&rollAttitudePidSettings, parameterF);
      printf("Attitude Roll I Gain=%f\n", getIGain(&rollAttitudePidSettings));

    
       qToken(cmd, token2,lenth,ATTITUDE_ROLL_I_LIMIT );
      parameterF = atof(token2);
      setILimit(&rollAttitudePidSettings, parameterF);
       printf( "Attitude Roll I Output Limit=%f\n",
                getILimit(&rollAttitudePidSettings));

       qToken(cmd, token2,lenth,ATTITUDE_ROLL_D );
      parameterF = atof(token2);
      setDGain(&rollAttitudePidSettings, parameterF);
       printf("Attitude Roll D Gain=%f\n", getDGain(&rollAttitudePidSettings));

       qToken(cmd, token2,lenth,ATTITUDE_PITCH_P );
      parameterF = atof(token2);
      setPGain(&pitchAttitudePidSettings, parameterF);
       printf( "Attitude Pitch P Gain=%f\n", getPGain(&pitchAttitudePidSettings));

       qToken(cmd, token2,lenth, ATTITUDE_PITCH_I);
      parameterF = atof(token2);
      setIGain(&pitchAttitudePidSettings, parameterF);
      printf( "Attitude Pitch I Gain=%f\n", getIGain(&pitchAttitudePidSettings));

       qToken(cmd, token2,lenth, ATTITUDE_PITCH_I_LIMIT);
      parameterF = atof(token2);
      setILimit(&pitchAttitudePidSettings, parameterF);
      printf( "Attitude Pitch I Output Limit=%f\n",
                getILimit(&pitchAttitudePidSettings));

       qToken(cmd, token2,lenth, ATTITUDE_PITCH_D);
      parameterF = atof(token2);
      setDGain(&pitchAttitudePidSettings, parameterF);
       printf( "Attitude Pitch D Gain=%f\n", getDGain(&pitchAttitudePidSettings));


       qToken(cmd, token2,lenth,ATTITUDE_YAW_P );
      parameterF = atof(token2);
      setPGain(&yawAttitudePidSettings, parameterF);
       printf( "Attitude Yaw P Gain=%f\n", getPGain(&yawAttitudePidSettings));

       qToken(cmd, token2,lenth, ATTITUDE_YAW_I);
      parameterF = atof(token2);
      setIGain(&yawAttitudePidSettings, parameterF);
       printf( "Attitude Yaw I Gain=%f\n", getIGain(&yawAttitudePidSettings));

       qToken(cmd, token2,lenth, ATTITUDE_YAW_I_LIMIT);
      parameterF = atof(token2);
      setILimit(&yawAttitudePidSettings, parameterF);
       printf( "Attitude Yaw I Output Limit=%f\n", getILimit(&yawAttitudePidSettings));
	   
       qToken(cmd, token2,lenth, ATTITUDE_YAW_D);
      parameterF = atof(token2);
      setDGain(&yawAttitudePidSettings, parameterF);
       printf( "Attitude Yaw D Gain=%f\n", getDGain(&yawAttitudePidSettings));

       qToken(cmd, token2,lenth, RATE_ROLL_P);
      parameterF = atof(token2);
      setPGain(&rollRatePidSettings, parameterF);
       printf( "Rate Roll P Gain=%f\n", getPGain(&rollRatePidSettings));
    
       qToken(cmd, token2,lenth, RATE_ROLL_I);
      parameterF = atof(token2);
      setIGain(&rollRatePidSettings, parameterF);
       printf( "Rate Roll I Gain=%f\n", getIGain(&rollRatePidSettings));
     
       qToken(cmd, token2,lenth, RATE_ROLL_I_LIMIT);
      parameterF = atof(token2);
      setILimit(&rollRatePidSettings, parameterF);
       printf( "Rate Roll I Output Limit=%f\n",
                getILimit(&rollRatePidSettings));
      
       qToken(cmd, token2,lenth,RATE_ROLL_D);
      parameterF = atof(token2);
      setDGain(&rollRatePidSettings, parameterF);
      printf( "Rate Roll D Gain=%f\n", getDGain(&rollRatePidSettings));                                                                                                                                                                                                                                                     

    
       qToken(cmd, token2,lenth,RATE_PITCH_P );
      parameterF = atof(token2);
      setPGain(&pitchRatePidSettings, parameterF);
      printf( "Rate Pitch P Gain=%f\n", getPGain(&pitchRatePidSettings));
   
       qToken(cmd, token2,lenth,RATE_PITCH_I );
      parameterF = atof(token2);
      setIGain(&pitchRatePidSettings, parameterF);
       printf( "Rate Pitch I Gain=%f\n", getIGain(&pitchRatePidSettings));
     
       qToken(cmd, token2,lenth,RATE_PITCH_I_LIMIT );
      parameterF = atof(token2);
      setILimit(&pitchRatePidSettings, parameterF);
       printf( "Rate Pitch I Output Limit=%f\n",
                getILimit(&pitchRatePidSettings));
  
       qToken(cmd, token2,lenth, RATE_PITCH_D);
      parameterF = atof(token2);
      setDGain(&pitchRatePidSettings, parameterF);
       printf( "Rate Pitch D Gain=%f\n", getDGain(&pitchRatePidSettings));

    
     qToken(cmd, token2,lenth,RATE_YAW_P );
      parameterF = atof(token2);
      setPGain(&yawRatePidSettings, parameterF);
       printf( "Rate Yaw P Gain=%f\n", getPGain(&yawRatePidSettings));
     
       qToken(cmd, token2,lenth, RATE_YAW_I);
      parameterF = atof(token2);
      setIGain(&yawRatePidSettings, parameterF);
      printf( "Rate Yaw I Gain=%f\n", getIGain(&yawRatePidSettings));
    
       qToken(cmd, token2,lenth,RATE_YAW_I_LIMIT );
      parameterF = atof(token2);
      setILimit(&yawRatePidSettings, parameterF);
       printf("Rate Yaw I Output Limit=%f\n",
                getILimit(&yawRatePidSettings));

       qToken(cmd, token2,lenth, RATE_YAW_D);
      parameterF = atof(token2);
      setDGain(&yawRatePidSettings, parameterF);
       printf( "Rate Yaw D Gain=%f\n", getDGain(&yawRatePidSettings));
      break;
	  default:
	  	printf("unknow message\n");
  }

}
Exemplo n.º 21
0
int main(int argc, char **argv)
{
    int i, j, ftype, rg_mode, start_option, start_index, prefix_len, nosort, err;
    ex_off_t fcount;
    char *fname;
    ls_entry_t *lse;
    tbx_list_t *table;
//  lio_path_tuple_t tuple;
    os_regex_table_t *rp_single, *ro_single;
    os_object_iter_t *it;
    tbx_list_iter_t lit;
    opque_t *q;
    op_generic_t *gop;
    char *keys[] = { "system.owner", "system.exnode.size", "system.modify_data", "os.create",  "os.link_count" };
    char *vals[5];
    int v_size[5];
    int n_keys = 5;
    int recurse_depth = 0;
    int obj_types = OS_OBJECT_ANY;
    int return_code = 0;

//printf("argc=%d\n", argc);
    if (argc < 2) {
        printf("\n");
        printf("lio_ls LIO_COMMON_OPTIONS [-rd recurse_depth] [-ns] LIO_PATH_OPTIONS\n");
        lio_print_options(stdout);
        lio_print_path_options(stdout);
        printf("\n");
        printf("    -rd recurse_depth  - Max recursion depth on directories. Defaults to %d\n", recurse_depth);
        printf("    -t  object_types   - Types of objects to list bitwise OR of 1=Files, 2=Directories, 4=symlink, 8=hardlink.  Default is %d.\n", obj_types);
        printf("    -ns                - Don't sort the output\n");
        return(1);
    }

    lio_init(&argc, &argv);

    //*** Parse the args
    rp_single = ro_single = NULL;
    nosort = 0;

    rg_mode = lio_parse_path_options(&argc, argv, lio_gc->auto_translate, &tuple, &rp_single, &ro_single);

    i=1;
    do {
        start_option = i;

        if (strcmp(argv[i], "-rd") == 0) { //** Recurse depth
            i++;
            recurse_depth = atoi(argv[i]);
            i++;
        } else if (strcmp(argv[i], "-t") == 0) {  //** Object types
            i++;
            obj_types = atoi(argv[i]);
            i++;
        } else if (strcmp(argv[i], "-ns") == 0) {  //** Strip off the path prefix
            i++;
            nosort = 1;
        }

    } while ((start_option < i) && (i<argc));
    start_index = i;

    if (rg_mode == 0) {
        if (i>=argc) {
            info_printf(lio_ifd, 0, "Missing directory!\n");
            return(2);
        }
    } else {
        start_index--;  //** Ther 1st entry will be the rp created in lio_parse_path_options
    }

    fcount = 0;

    q = new_opque();
    table = tbx_list_create(0, &tbx_list_string_compare, NULL, tbx_list_no_key_free, tbx_list_no_data_free);


    for (j=start_index; j<argc; j++) {
        log_printf(5, "path_index=%d argc=%d rg_mode=%d\n", j, argc, rg_mode);
        if (rg_mode == 0) {
            //** Create the simple path iterator
            tuple = lio_path_resolve(lio_gc->auto_translate, argv[j]);
            lio_path_wildcard_auto_append(&tuple);
            rp_single = os_path_glob2regex(tuple.path);
        } else {
            rg_mode = 0;  //** Use the initial rp
        }

        for (i=0; i<n_keys; i++) v_size[i] = -tuple.lc->max_attr;
        memset(vals, 0, sizeof(vals));
        it = lio_create_object_iter_alist(tuple.lc, tuple.creds, rp_single, ro_single, obj_types, recurse_depth, keys, (void **)vals, v_size, n_keys);
        if (it == NULL) {
            info_printf(lio_ifd, 0, "ERROR: Failed with object_iter creation\n");
            return_code = EIO;
            goto finished;
        }

        while ((ftype = lio_next_object(tuple.lc, it, &fname, &prefix_len)) > 0) {
            tbx_type_malloc_clear(lse, ls_entry_t, 1);
            lse->fname = fname;
            lse->ftype = ftype;
            lse->prefix_len = prefix_len;
            memcpy(lse->v_size, v_size, sizeof(v_size));
            memcpy(lse->vals, vals, sizeof(vals));

            for (i=0; i<n_keys; i++) v_size[i] = -tuple.lc->max_attr;
            memset(vals, 0, sizeof(vals));

            //** Check if we have a link.  If so we need to resolve the link path
            if ((ftype & OS_OBJECT_SYMLINK) > 0) {
                lse->link_size = -64*1024;
                gop = gop_lio_get_attr(tuple.lc, tuple.creds, lse->fname, NULL, "os.link", (void **)&(lse->link), &(lse->link_size));
                gop_set_private(gop, lse);
                opque_add(q, gop);
                if (nosort == 1) opque_waitall(q);
            }

            if (fcount == 0) {
                info_printf(lio_ifd, 0, "  Perms     Ref   Owner        Size           Creation date              Modify date             Filename [-> link]\n");
                info_printf(lio_ifd, 0, "----------  ---  ----------  ----------  ------------------------  ------------------------  ------------------------------\n");
            }
            fcount++;

            if (nosort == 1) {
                ls_format_entry(lio_ifd, lse);
            } else {
                tbx_list_insert(table, lse->fname, lse);
            }
        }

        lio_destroy_object_iter(tuple.lc, it);

        lio_path_release(&tuple);
        if (rp_single != NULL) {
            os_regex_table_destroy(rp_single);
            rp_single = NULL;
        }
        if (ro_single != NULL) {
            os_regex_table_destroy(ro_single);
            ro_single = NULL;
        }
    }

    //** Wait for any readlinks to complete
    err = (opque_task_count(q) > 0) ? opque_waitall(q) : OP_STATE_SUCCESS;
    if (err != OP_STATE_SUCCESS) {
        info_printf(lio_ifd, 0, "ERROR: Failed with readlink operation!\n");
        return_code = EIO;
    }

    //** Now sort and print things if needed
    if (nosort == 0) {
        lit = tbx_list_iter_search(table, NULL, 0);
        while ((tbx_list_next(&lit, (tbx_list_key_t **)&fname, (tbx_list_data_t **)&lse)) == 0) {
            ls_format_entry(lio_ifd, lse);
        }
    }

    tbx_list_destroy(table);

    if (fcount == 0) return_code = 2;

finished:
    opque_free(q, OP_DESTROY);

    lio_shutdown();

    return(return_code);
}
Exemplo n.º 22
0
void
mi_cmd_disassemble (char *command, char **argv, int argc)
{
  struct gdbarch *gdbarch = get_current_arch ();
  struct ui_out *uiout = current_uiout;
  CORE_ADDR start;

  int mode, disasm_flags;
  struct symtab *s;

  /* Which options have we processed ... */
  int file_seen = 0;
  int line_seen = 0;
  int num_seen = 0;
  int start_seen = 0;
  int end_seen = 0;

  /* ... and their corresponding value. */
  char *file_string = NULL;
  int line_num = -1;
  int how_many = -1;
  CORE_ADDR low = 0;
  CORE_ADDR high = 0;
  struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);

  /* Options processing stuff.  */
  int oind = 0;
  char *oarg;
  enum opt
  {
    FILE_OPT, LINE_OPT, NUM_OPT, START_OPT, END_OPT
  };
  static const struct mi_opt opts[] =
    {
      {"f", FILE_OPT, 1},
      {"l", LINE_OPT, 1},
      {"n", NUM_OPT, 1},
      {"s", START_OPT, 1},
      {"e", END_OPT, 1},
      { 0, 0, 0 }
    };

  /* Get the options with their arguments. Keep track of what we
     encountered.  */
  while (1)
    {
      int opt = mi_getopt ("-data-disassemble", argc, argv, opts,
			   &oind, &oarg);
      if (opt < 0)
	break;
      switch ((enum opt) opt)
	{
	case FILE_OPT:
	  file_string = xstrdup (oarg);
	  file_seen = 1;
	  make_cleanup (xfree, file_string);
	  break;
	case LINE_OPT:
	  line_num = atoi (oarg);
	  line_seen = 1;
	  break;
	case NUM_OPT:
	  how_many = atoi (oarg);
	  num_seen = 1;
	  break;
	case START_OPT:
	  low = parse_and_eval_address (oarg);
	  start_seen = 1;
	  break;
	case END_OPT:
	  high = parse_and_eval_address (oarg);
	  end_seen = 1;
	  break;
	}
    }
  argv += oind;
  argc -= oind;

  /* Allow only filename + linenum (with how_many which is not
     required) OR start_addr + end_addr.  */

  if (!((line_seen && file_seen && num_seen && !start_seen && !end_seen)
	|| (line_seen && file_seen && !num_seen && !start_seen && !end_seen)
	|| (!line_seen && !file_seen && !num_seen && start_seen && end_seen)))
    error (_("-data-disassemble: Usage: ( [-f filename -l linenum [-n "
	     "howmany]] | [-s startaddr -e endaddr]) [--] mode."));

  if (argc != 1)
    error (_("-data-disassemble: Usage: [-f filename -l linenum "
	     "[-n howmany]] [-s startaddr -e endaddr] [--] mode."));

  mode = atoi (argv[0]);
  if (mode < 0 || mode > 3)
    error (_("-data-disassemble: Mode argument must be 0, 1, 2, or 3."));

  /* Convert the mode into a set of disassembly flags.  */

  disasm_flags = 0;
  if (mode & 0x1)
    disasm_flags |= DISASSEMBLY_SOURCE;
  if (mode & 0x2)
    disasm_flags |= DISASSEMBLY_RAW_INSN;

  /* We must get the function beginning and end where line_num is
     contained.  */

  if (line_seen && file_seen)
    {
      s = lookup_symtab (file_string);
      if (s == NULL)
	error (_("-data-disassemble: Invalid filename."));
      if (!find_line_pc (s, line_num, &start))
	error (_("-data-disassemble: Invalid line number"));
      if (find_pc_partial_function (start, NULL, &low, &high) == 0)
	error (_("-data-disassemble: "
		 "No function contains specified address"));
    }

  gdb_disassembly (gdbarch, uiout,
  		   file_string,
  		   disasm_flags,
		   how_many, low, high);

  do_cleanups (cleanups);
}
Exemplo n.º 23
0
int BfastBAFConvert(int argc, char *argv[])
{
	FILE *fpIn=NULL, *fpOut=NULL;
	gzFile fpInGZ=NULL, fpOutGZ=NULL;
	long long int counter;
	char inputFileName[MAX_FILENAME_LENGTH]="\0";
	char outputFileName[MAX_FILENAME_LENGTH]="\0";
	char fastaFileName[MAX_FILENAME_LENGTH]="\0";
	char outputID[MAX_FILENAME_LENGTH]="\0";
	char *readGroupFileName=NULL, *readGroup=NULL, *readGroupString=NULL;
	char *last;
	int outputType=1; // BAF2TEXT
	int outputSubType=TextOutput;
	int inputType=BinaryInput;
	int c, argnum;
	AlignedRead a;
	RGBinary rg;
	char fileExtension[256]="\0";

	// Get parameters
	while((c = getopt(argc, argv, "f:o:r:O:h")) >= 0) {
		switch(c) {
			case 'O': outputType = atoi(optarg); break;
			case 'f': strcpy(fastaFileName, optarg); break;
			case 'o': strcpy(outputID, optarg); break;
			case 'r': readGroupFileName=strdup(optarg); break;
			case 'h':
					  BfastBAFConvertUsage(); return 1;
			default: fprintf(stderr, "Unrecognized option: -%c\n", c); return 1;
		}
	}

	if(argc == optind) {
		BfastBAFConvertUsage(); return 1;
	}

	/* Only read in the brg if necessary */
	switch(outputType) {
		case 2:
		case 3:
		case 4:
			if(0 == strlen(fastaFileName)) {
				PrintError(Name, "fastaFileName", "Required command line argument", Exit, InputArguments);
			}
			RGBinaryReadBinary(&rg,
					NTSpace,
					fastaFileName);
			break;
		default:
			break;
	}

	/* Set types and file extension */
	switch(outputType) {
		case 0:
			outputType=BAF;
			inputType=TextInput;
			outputSubType=BinaryOutput;
			strcat(fileExtension, BFAST_ALIGNED_FILE_EXTENSION);
			break;
		case 1:
			outputType=BAF;
			inputType=BinaryInput;
			outputSubType=TextOutput;
			strcat(fileExtension, "txt");
			break;
		case 2:
			outputType=SAM;
			inputType=BinaryInput;
			outputSubType=TextOutput;
			strcat(fileExtension, BFAST_SAM_FILE_EXTENSION);
			if(NULL != readGroupFileName) {
				readGroup=ReadInReadGroup(readGroupFileName);
				readGroupString=ParseReadGroup(readGroup);
			}
			break;
		default:
			PrintError(Name, NULL, "Could not understand output type", Exit, OutOfRange);
	}

	for(argnum=optind;argnum<argc;argnum++) {
		strcpy(inputFileName, argv[argnum]);

		/* Create output file name */
		last = StrStrGetLast(inputFileName,
				BFAST_ALIGNED_FILE_EXTENSION);
		if(NULL == last) {
			last = StrStrGetLast(inputFileName, "txt");
			if(NULL == last) {
				PrintError(Name, inputFileName, "Could not recognize file extension", Exit, OutOfRange);
			}
		}

		outputFileName[0]='\0';
		strncpy(outputFileName, inputFileName, (last - inputFileName));
		outputFileName[(last-inputFileName)]='\0';
		strcat(outputFileName, fileExtension);

		/* Open the input file */
		if(BinaryInput == inputType) {
			if(!(fpInGZ=gzopen(inputFileName, "rb"))) {
				PrintError(Name, inputFileName, "Could not open file for reading", Exit, OpenFileError);
			}
		}
		else {
			if(!(fpIn=fopen(inputFileName, "rb"))) {
				PrintError(Name, inputFileName, "Could not open file for reading", Exit, OpenFileError);
			}
		}
		/* Open the output file */
		if(BinaryOutput == outputSubType) {
			if(!(fpOutGZ=gzopen(outputFileName, "wb"))) {
				PrintError(Name, outputFileName, "Could not open file for writing", Exit, OpenFileError);
			}
		}
		else {
			if(!(fpOut=fopen(outputFileName, "wb"))) {
				PrintError(Name, outputFileName, "Could not open file for writing", Exit, OpenFileError);
			}
		}

		fprintf(stderr, "Input:%s\nOutput:%s\n", inputFileName, outputFileName);

		/* Print Header */
		AlignedReadConvertPrintHeader(fpOut, &rg, outputType, readGroup);
		/* Initialize */
		AlignedReadInitialize(&a);
		counter = 0;
		fprintf(stderr, "Currently on:\n0");
		/* Read in each match */
		while((TextInput == inputType && EOF != AlignedReadReadText(&a, fpIn)) ||
				(BinaryInput == inputType && EOF != AlignedReadRead(&a, fpInGZ))) {
			if(counter%BAFCONVERT_ROTATE_NUM==0) {
				fprintf(stderr, "\r%lld",
						counter);
			}
			counter++;
			/* Print each match */
			AlignedReadConvertPrintOutputFormat(&a,
					&rg,
					fpOut,
					fpOutGZ,
					outputID,
					readGroupString,
					-1,
					NULL,
					outputType,
					1,
                                        0,
					outputSubType);
			AlignedReadFree(&a);
		}
		fprintf(stderr, "\r%lld\n",
				counter);
		/* Close the input file */
		if(TextInput == inputType) {
			fclose(fpIn);
		}
		else {
			gzclose(fpInGZ);
		}
		/* Close the output file */
		if(TextOutput == outputSubType) {
			fclose(fpOut);
		}
		else {
			gzclose(fpOutGZ);
		}
	}
	if(SAM == outputType) {
		RGBinaryDelete(&rg);
	}
	free(readGroupFileName);
	free(readGroup);
	free(readGroupString);

	fprintf(stderr, "Terminating successfully!\n");
	return 0;
}
Exemplo n.º 24
0
void CheckStatPlan::setNextRunTime (PlanItem &oPlan)
{
    Date d (oPlan.m_sNextRunTime);
    Date dNow;
    char sDate[15];
    char sMsg[1024] = {0};
    
    if (oPlan.m_iIntervalType == 1) //时间间隔(秒)
    {
        int iAddSecs = atoi (oPlan.m_sTimeInterval);
        if (iAddSecs <= 0) {
            strcpy (sDate, "30000101000000");
        }
        else {            
            d.addSec (iAddSecs);
            
            if (oPlan.m_iDataType == 0) {
                while (strcmp(d.toString(), dNow.toString()) <= 0)
                    d.addSec (iAddSecs);
                
                //修正动态刷新指标的数据时间
                Date dData (d.toString());
                dData.addSec (0 - atoi(oPlan.m_sTimeInterval));
                strcpy (oPlan.m_sDataEndTime, dData.toString());
                dData.addSec (0 - atoi(oPlan.m_sTimeInterval));
                strcpy (oPlan.m_sDataBeginTime, dData.toString());
            }
            
            strcpy (sDate, d.toString());
        }
    }
    else if (oPlan.m_iIntervalType == 2) //每个月固定时间
    {
        strcpy (sDate, oPlan.m_sNextRunTime);
        while (strcmp(sDate, dNow.toString()) <= 0)
            getNextMonth (sDate, oPlan.m_sTimeInterval);
    }
    else {
        //##异常, 置无穷大
        strcpy (sDate, "30000101000000");
        strcpy (sMsg, "interval_type 字段值非法, 请检查修改");
    }
    
    //update table    
    DEFINE_QUERY (qry);
    if (sMsg[0])
    {
        qry.setSQL ("update B_Check_Stat_Plan "
            " set next_run_time = to_date(:vDate,'yyyymmddhh24miss'),"
            " Message = :vMsg "
            " where plan_id = :vPlanID "
        );
        qry.setParameter ("vMsg", sMsg);
    }
    else {
        qry.setSQL ("update B_Check_Stat_Plan "
            " set next_run_time = to_date(:vDate,'yyyymmddhh24miss')"
            " where plan_id = :vPlanID "
        );
    }
    qry.setParameter ("vPlanID", oPlan.m_iPlanID);
    qry.setParameter ("vDate", sDate);
    qry.execute();
    qry.close();
    
    if (sMsg[0]) {
        qry.setSQL ("Insert into b_check_stat_log ( "
                " log_id, plan_id, msg_time, message ) "
                " values (:vLogID, :vPlanID, sysdate, '[RUN] '||:vMsg )"
        );
        qry.setParameter ("vLogID", getNextStatLogID());
        qry.setParameter ("vPlanID", oPlan.m_iPlanID);
        qry.setParameter ("vMsg", sMsg);
        qry.execute();
    }
    qry.commit ();
    
    #ifdef _debug
        Log::log (0, "设置下一次运行时间:%s", sDate);
    #endif
}
Exemplo n.º 25
0
// getImageToArray: extract a sub-section from an image HDU, return array
void *getImageToArray(fitsfile *fptr, int *dims, double *cens, char *slice,
		      int *odim1, int *odim2, int *bitpix, int *status){
  int i, naxis;
  int xcen, ycen, dim1, dim2, type;
  int tstatus = 0;
  int doscale = 0;
  void *obuf;
  long totpix, totbytes;
  long naxes[IDIM], fpixel[IDIM], lpixel[IDIM], inc[IDIM];
  double bscale = 1.0;
  double bzero = 0.0;
  char comment[81];
  char *s, *tslice;
  int nslice, idx, iaxis0, iaxis1;
  int iaxes[2] = {0, 1};
  int saxes[IDIM] = {0, 0, 0, 0};
  // seed buffers
  for(i=0; i<IDIM; i++){
    naxes[i] = 0;
    fpixel[i] = 1;
    lpixel[i] = 1;
    inc[i] = 1;
  }
  // get image dimensions and type
  fits_get_img_dim(fptr, &naxis, status);
  fits_get_img_size(fptr, min(IDIM,naxis), naxes, status);
  fits_get_img_type(fptr, bitpix, status);
  if( naxis < 2 ){
    *status = BAD_DIMEN;
    return NULL;
  }
  // parse slice string into primary axes and slice axes
  if( slice && *slice ){
    tslice = (char *)strdup(slice);
    for(s=(char *)strtok(tslice, " :,"), nslice=0, idx=0;
	(s != NULL) && (nslice < IDIM); 
	s=(char *)strtok(NULL," :,"), nslice++){
      if( !strcmp(s, "*") ){
	if( idx < 2 ){
	  iaxes[idx++] = nslice;
	}
      } else {
	saxes[nslice] = atoi(s);
	if( (saxes[nslice] < 1) || (saxes[nslice] > naxes[nslice]) ){
	  *status = SEEK_ERROR;
	  return NULL;
	}
      }
    }
    free(tslice);      
  }
  // convenience variables for the primary axis indexes
  iaxis0 = iaxes[0];
  iaxis1 = iaxes[1];
  // get limits of extracted section
  if( dims && dims[0] && dims[1] ){
    dim1 = min(dims[0], naxes[iaxis0]);
    dim2 = min(dims[1], naxes[iaxis1]);
    // read image section
    if( cens ){
      xcen = cens[0];
      ycen = cens[1];
    } else {
      xcen = dim1/2;
      ycen = dim2/2;
    }
    fpixel[iaxis0] = (int)(xcen - (dim1+1)/2);
    fpixel[iaxis1] = (int)(ycen - (dim2+1)/2);
    lpixel[iaxis0] = (int)(xcen + (dim1/2));
    lpixel[iaxis1] = (int)(ycen + (dim2/2));
  } else {
    // read entire image
    fpixel[iaxis0] = 1;
    fpixel[iaxis1] = 1;
    lpixel[iaxis0] = naxes[iaxis0];
    lpixel[iaxis1] = naxes[iaxis1];
  }
  // stay within image limits
  fpixel[iaxis0] = max(fpixel[iaxis0], 1);
  fpixel[iaxis0] = min(fpixel[iaxis0], naxes[iaxis0]);
  lpixel[iaxis0] = max(lpixel[iaxis0], 1);
  lpixel[iaxis0] = min(lpixel[iaxis0], naxes[iaxis0]);
  fpixel[iaxis1] = max(fpixel[iaxis1], 1);
  fpixel[iaxis1] = min(fpixel[iaxis1], naxes[iaxis0]);
  lpixel[iaxis1] = max(lpixel[iaxis1], 1);
  lpixel[iaxis1] = min(lpixel[iaxis1], naxes[iaxis0]);
  // for sliced dimensions, set first and last pixel to the specified slice
  for(i=0; i<min(IDIM,naxis); i++){
    if( saxes[i] ){
      // 1 pixel slice in this dimension
      fpixel[i] = saxes[i];
      lpixel[i] = saxes[i];
      // stay within image limits
      fpixel[i] = max(fpixel[i], 1);
      fpixel[i] = min(fpixel[i], naxes[i]);
      lpixel[i] = max(lpixel[i], 1);
      lpixel[i] = min(lpixel[i], naxes[i]);
    }
  }
  // section dimensions
  *odim1 = lpixel[iaxis0] - fpixel[iaxis0] + 1;
  *odim2 = lpixel[iaxis1] - fpixel[iaxis1] + 1;
  totpix = *odim1 * *odim2;
  // make sure we have an image with valid dimensions size
  if( totpix <= 1 ){
    *status = NEG_AXIS;
    return NULL;
  }
  // are we scaling?
  fits_read_key(fptr, TDOUBLE, "BSCALE", &bscale, comment, &tstatus);
  if( tstatus != VALUE_UNDEFINED ){
    fits_read_key(fptr, TDOUBLE, "BZERO", &bzero, comment, &tstatus);
  }
  if( (bscale != 1.0) || (bzero != 0.0) ){
    doscale = 1;
  }
  // allocate space for the pixel array
  switch(*bitpix){
    case 8:
      if( doscale ){
	// scaled data has to be float
	*bitpix = -32;
	type = TFLOAT;
	totbytes = totpix * sizeof(float);
      } else {
	type = TBYTE;
	totbytes = totpix * sizeof(char);
      }
      break;
    case 16:
      if( doscale ){
	// scaled data has to be float
	*bitpix = -32;
	type = TFLOAT;
	totbytes = totpix * sizeof(float);
      } else {
	type = TSHORT;
	totbytes = totpix * sizeof(short);
      }
      break;
    case -16:
      if( doscale ){
	// scaled data has to be float
	*bitpix = -32;
	type = TFLOAT;
	totbytes = totpix * sizeof(float);
      } else {
	type = TUSHORT;
	totbytes = totpix * sizeof(unsigned short);
      }
      break;
    case 32:
      if( doscale ){
	// scaled data has to be float
	*bitpix = -32;
	type = TFLOAT;
	totbytes = totpix * sizeof(float);
      } else {
	type = TINT;
	totbytes = totpix * sizeof(int);
      }
      break;
    case 64:
      if( doscale ){
	// scaled data has to be float
	*bitpix = -32;
	type = TFLOAT;
	totbytes = totpix * sizeof(float);
      } else {
	type = TLONGLONG;
	totbytes = totpix * sizeof(long long);
      }
      break;
    case -32:
      type = TFLOAT;
      totbytes = totpix * sizeof(float);
      break;
    case -64:
      type = TDOUBLE;
      totbytes = totpix * sizeof(double);
      break;
  default:
    return NULL;
  }
#if EM
  // sanity check on memory limits
  if( totbytes > max_memory ){
    *status = MEMORY_ALLOCATION;
    return NULL;
  }
#endif
  // try to allocate that much memory
  if(!(obuf = (void *)malloc(totbytes))){
    *status = MEMORY_ALLOCATION;
    return NULL;
  }
  /* read the image section */
  fits_read_subset(fptr, type, fpixel, lpixel, inc, 0, obuf, 0, status);
  // return pixel buffer (and section dimensions)
  return obuf;
}
Exemplo n.º 26
0
void CheckStatPlan::startPlan (PlanItem &oPlan, char ** argv)
{
    m_argv = argv;
    
    StatInterface::m_pPlan = &oPlan;
    
    //##置运行状态
    bool bret = updateState (oPlan.m_iPlanID, "RUN", "<Message> 开始执行...");
    
    if (!bret) {
        Log::log (0,"计划执行失败[Plan_ID=%d],因执行 updateState(RUN) 不成功", oPlan.m_iPlanID);
        return;
    }
    
    while (oPlan.m_iDebugFlag == 1)
        waitDebug (oPlan); //等待调试, 置B_Check_Stat_Plan.DEBUG_FLAG=0 后跳出循环
    
    try {
        //置下一次运行时间
        sleep (1);
        
        setNextRunTime (oPlan);
        
        if (oPlan.m_iAppType == 0)
        {
            switch (atoi (oPlan.m_sStatName))
            {
            
            	///////////////////////HSS数据信息点300000/////////////////////////////////////////
            	case 800001://2.2.1	数据接收平衡(AuditId=0001)
            	{
            		CheckStatInfo oReceBalance;		
            		oReceBalance.checkDataRecvBalance("0001",50,MIDL_FREG);
            		break;
            	}	
            	
            	case 800002://2.2.2	数据加载平衡(AuditId=0002)
            	{
            		CheckStatInfo oReceBalance;
            		oReceBalance.checkDataLoadBalance("0002",50,MIDL_FREG);
            		break;
            	}
            	
            	case 800003://2.2.3	数据入库平衡(AuditId=0003)
            	{
            		CheckStatInfo oReceBalance;
            		oReceBalance.checkDataInputBalance("0003",50,MIDL_FREG);
            		break;
            	}
            	
            	case 800004://2.2.4	数据发布平衡(AuditId=0004)
            	{
            		CheckStatInfo oCheckStatInfo;
            		oCheckStatInfo.checkOutputBalance();
            		break;
            	}
            	
            	case 800005://2.2.5	实例数变更(AuditId=0005)
            	{
            		CheckStatInfo oCheckStatInfo;
            		oCheckStatInfo.checkInstanceUpdate();
            		break;
            	}
            	
            	case 800006://2.2.6	进程日志(AuditId=0006)
            	{
                	CheckStatInfo oCheckHSSStatInfo;
                	oCheckHSSStatInfo.checkHSSAlertLog();            		
            		break;
            	}            	            	            	            	            	            	
            	
            	case 800007://2.2.7	鉴权异常(AuditId=0008)
            	{
            		CheckStatInfo oCheckStatInfo;
            		oCheckStatInfo.checkAuthenticationError();
            		break;
            	}   
            	
            	///////////////////////HSS信息点500000/////////////////////////////////////////
            	//2.3.1 接收接口处理(AuditId=0100)
            	case 502311://	省内非计费域接口(AuditId=0101)	性能指标(AuditId=0101,type=40)
            	{	
            		CheckStatInfo oCheckStatInfo;
            		oCheckStatInfo.checkNoBillingCap();
            		break;
            	}
             	case 502312://		集团HSS接口(AuditId=0102)	性能指标	(AuditId=0102,type = 40)
            	{	
            		CheckStatInfo oCheckStatInfo;
            		oCheckStatInfo.checkHssCap();
            		break;
            	}
            	//2.3.2 同步接口处理(AuditId=0200)
             	case 502321://		OFCS接口(AuditId=0201)	性能指标(AuditId=0201,type=40)
            	{	
            		CheckStatInfo oCheckStatInfo;
            		oCheckStatInfo.checkOfcsCap();
            		break;
            	}
             	case 502322://			OCS接口(AuditId=0202)		性能指标(AuditId=0202,type=40)
            	{	
            		CheckStatInfo oCheckStatInfo;
            		oCheckStatInfo.checkOcsCap();
            		break;
            	}           	      	
            	//2.3.4	系统状态(AuditId=0400)
            	case 502341://2.3.4.1	事件信息点(AuditId=0400,type=60)
            	{
            		CheckStatInfo oCheckHSSEventInfo;
            		oCheckHSSEventInfo.checkOcsCap();
            		break;
            	}	
            	
            	case 502342://2.3.4.2	告警信息点(AuditId=0400,type=20)
            	{
            		CheckStatInfo oCheckHSSSystemCaution;
            		oCheckHSSSystemCaution.checkHSSSystemCaution();
            		break;
            	}
            	         	
            	///////////////////////一下为计费信息点,对HSS无用处//////////////////////
              //数据信息点数据提取
               case 100001:  //##2.2.1	计费接收(AuditId=0001,Type=50)
                {
                	CheckStatInfo oCheckStatInfo(MODULE_CHECK_NORMAL_FILE);
                	oCheckStatInfo.checkNormalFile();
                  break;                	     
                }
               case 100002:  //##2.2.2	计费接收异常文件(AuditId=0002,Type=50)
                {
                	CheckStatInfo oCheckStatInfo(MODULE_CHECK_ERR_FILE);
                  oCheckStatInfo.checkErrFile();
                  break;                	     
                }
               case 100003:  //##2.2.3	预处理平衡(AuditId=0003,Type=50)
                {
                	CheckStatInfo oCheckStatInfo(MODULE_CHECK_FILE_PREP_BALANCE);
                  oCheckStatInfo.checkPrepBalance();
                  break;                	     
                }
               case 100004:  //##2.2.4	批价平衡(AuditId=0004,Type=50)
                {
                	CheckStatInfo oCheckStatInfo(MODULE_CHECK_FILE_PRICING_BALANCE);
                  oCheckStatInfo.checkPricingBalance();
                  break;                	     
                }
               case 100005:  //##2.2.5	入库平衡(AuditId=0005,Type=50)
                {
                	CheckStatInfo oCheckStatInfo(MODULE_CHECK_FILE_INSTORE_BALANCE);
                  oCheckStatInfo.checkInStoreBalance();
                  break;                	     
                }
               case 100006:  //##2.2.6	话单日志(AuditId=0006,Type=50)
                {
                	CheckStatInfo oCheckStatInfo;
                  oCheckStatInfo.checkTicketLog();
                  break;                	     
                }
               case 100007:  //##2.2.7	IDEP文件传输(AuditId=0007,Type=50)
                {
                	CheckStatInfo oCheckStatInfo;
                  oCheckStatInfo.checkTransLog();
                  break;                	     
                }
               case 100008:  //##2.2.8	累帐平衡(AuditId=0008,Type=50)
                {
                  //CheckDailyAcctItemAggr oCheckItem;
                  //oCheckItem.checkDailyAcctItemAggrNew();
                  break;                	     
                }                                                                                                                
                   
               case 100009:  //##2.2.9	日帐日志(AuditId=0009,Type=50)
                {
                 
                  break;                	     
                }
               case 100010:  //##2.2.10	月帐日志(AuditId=0010,Type=50)
                {
                  //CheckDailyAcctItemAggr oCheckItem;
                  //oCheckItem.checkMonthAcctItemAggrNew();                	
                  break;                	     
                }
               case 100011:  //##2.2.11	高额签到(AuditId=0011,Type=50)
                {
                	//CheckStatInfo oCheckStatInfo;
                 // oCheckStatInfo.checkSignHighFee();
                  break;                	     
                }
               case 100012:  //##2.2.12	省级高额(AuditId=0012,Type=50)
                {
                	//CheckStatInfo oCheckStatInfo;
                	//oCheckStatInfo.checkHighFeeServ();
                	/*
                	char sValue1[3+1]={0};
                	ParamDefineMgr::getParam("HIGH_FEE_ALARM", "LOG_OR_DB", sValue1);
                	int iValue=atoi(sValue1);
                	if(iValue >= 2)
                     oCheckStatInfo.checkHighFeeServ();
                  else 
                     oCheckStatInfo.checkHighFeeLog();
                   */
                  break;                	     
                }
               case 100013:  //##2.2.13	进程日志(AuditId=0013,Type=50)
                {
                	CheckStatInfo oCheckStatInfo;
                	oCheckStatInfo.checkAlertLog();
                	/*
                	char sValue1[3+1]={0};
                	ParamDefineMgr::getParam("INFO_DATA", "PROCESSLOG", sValue1);
                	int iValue=atoi(sValue1);
                	if(iValue == 1)                	
                    oCheckStatInfo.checkAlertLog();
                   else 
                    oCheckStatInfo.checkProcessLog();
                    */
                  break;                	     
                }
               case 100014:  //##2.2.14	计费处理话单延迟(AuditId=0014,Type=50)
                {
                	CheckStatInfo oCheckStatInfo(MODULE_CHECK_DELAY_FILE);
                  oCheckStatInfo.checkDelayFile();
                  break;                	     
                }
               case 100015:  //##2.2.15	模块处理性能指标(AuditId=0015,Type=50)
                {
                	CheckStatInfo oCheckStatInfo;
                	oCheckStatInfo.prepMouldeCapability();
                	oCheckStatInfo.pricingMouldeCapability();
                  oCheckStatInfo.checkMouldeCapabilityKpi();
                  break;                	     
                }
               case 100016:  //##2.2.16	系统处理损耗指标(AuditId=0016,Type=50)
                {
                	CheckStatInfo oCheckStatInfo;
                  oCheckStatInfo.checkSystemLossKpi()	;		
                  break;                	     
                }
                
                case 100017:  //##JS_20101215_001(AuditId=0060  Type=50)
                {
                	CheckStatInfo oCheckStatInfo;
                  oCheckStatInfo.checkDayAcctFee();		
                  break;                	     
                }
 
            // 信息点数据提取
            // 20000x 性能指标信息点
                case 200001:  //2.3.1.1	计费接收性能指标(AuditId=0100,Type=40)
                {
                	Information oCheckInfor;
                  oCheckInfor.checkGather()	;		
                  break;                	     
                }  
                case 200002:  //2.3.2.1.1	预处理性能指标(AuditId=0201,Type=40)
                {
                	Information oCheckInfor;
                	//oCheckInfor.checkBalance(MODULE_PREP);  //预处理告警中间数据生成
                  oCheckInfor.checkPerp()	;		
                  break;                	     
                }   
                case 200003:  //2.3.2.2.1	批价性能指标(AuditId=0202,Type=40)
                {
                	Information oCheckInfor;
                	//oCheckInfor.checkBalance(MODULE_PRICING) ;//批价告警中间数据生成  
                  oCheckInfor.checkPricing()	;		
                  break;                	     
                }   
                case 200004:  //2.3.2.3.1	入库性能指标(AuditId=0203,Type=40)
                {
                	Information oCheckInfor;
                	//oCheckInfor.checkBalance(MODULE_INSTORE) ;//入库告警中间数据生成
                  oCheckInfor.checkIndb()	;		
                  break;                	     
                }   
                case 200005:  //2.3.3.1.1	销账性能指标(AuditId=0301,Type=40)
                {
	                CheckStatInfo oCheckAddItem ;
                  oCheckAddItem.checkAcctCap("0301",40,MIDL_FREG)	;
                  break;                	     
                }
                case 200006:  //2.3.3.2.1	累帐性能指标(AuditId=0302,Type=40)
                {
                	CheckStatInfo oCheckAddItem ;
                  oCheckAddItem.checkAddItem()	;		
                  break;                	     
                }  
                case 200007:  //2.3.3.4.1	月帐性能指标(AuditId=0304,Type=40)
                {
                	CheckStatInfo oCheckMonthCap ;
                  oCheckMonthCap.checkMonthCap()	;		
                  break;                	     
                }     
                 
                case 200008:  //2.3.4.1.1	银行性能指标(AuditId=0401,Type=40)
                {
	                CheckStatInfo oCheckAddItem ;
                  oCheckAddItem.checkAcctCap("0401",40,MIDL_FREG)	;
                  break;                	     
                }
                case 200009:  //2.3.4.2.1	充值卡性能指标(AuditId=0402,Type=40)
                {
	                CheckStatInfo oCheckAddItem ;
                  oCheckAddItem.checkAcctCap("0402",40,MIDL_FREG)	;
                  break;                	     
                }      
                 case 200010:  //.3.3.5.1 欠费账龄性能指标(AuditId=0305,Type=40)
                {
                CheckStatInfo oCheckAddItem ;
                  oCheckAddItem.checkAcctCap("0305",40,HIGH_FREG) ;
                  break;                      
                } 
                                                                                          
               //20001x  告警指标信息点
               case 200012:  //2.3.2.1.2       ?
                {
                  Information oCheckInfor;
                  //oCheckInfor.checkBalance(MODULE_PREP);  //?¤′|àí???ˉ?D??êy?Yéú3é
                  oCheckInfor.checkPrepAlarm();
                  oCheckInfor.writePrepAlarm()  ;
                  break;
                }
                case 200013:  //2.3.2.2.2       
                {
                  Information oCheckInfor;
                  //oCheckInfor.checkBalance(MODULE_PRICING) ;//?ú?????ˉ?D??êy?Yéú3é
                  oCheckInfor.checkPricingAlarm();
                  oCheckInfor.writePricingAlarm()       ;
                  break;
                }
                case 200014:  //2.3.2.3.2      
                {
                  Information oCheckInfor;
                  //oCheckInfor.checkBalance(MODULE_INSTORE) ;//è??a???ˉ?D??êy?Yéú3é
                  oCheckInfor.checkIndbAlarm()    ;
                  oCheckInfor.writeIndbAlarm()  ;
                  break;
                }        
                
                case 200015:  //2.3.3.2.2	累帐告警指标(AuditId=0302,Type=20)
                {
                	CheckStatInfo oCheckInfor;
                  oCheckInfor.checkAddItemCaution()	;		
                  break;                	     
                }         
                        
                case 200020:  //2.3.3.5.2 欠费账龄告警指标(AuditId=0305,Type=20
                {
                CheckStatInfo oCheckAddItem ;
                  oCheckAddItem.checkAcctCaution("0305",20,HIGH_FREG) ;
                  break;                      
                } 
                /* 核心参数告警信息点*/
                case 300001:  //检查每日话单参数,话单总数,总时长,总流量
                {
                	CheckStatInfo oCheckInfo;
                  oCheckInfo.checkParamBalance()	;		
                  break;                	     
                }  
                
                case 300002:  //检查每日漫入漫出用户数
                {
                	CheckStatInfo oCheckInfo;
                  oCheckInfo.checkRoamServs()	;		
                  break;                	     
                }   
               /*
                case 400001:  //2.3.5.1	事件信息点(AuditId=0900,Type=60)
                {
                	CheckStatInfo checkEventInfo;
                  checkEventInfo.checkEventInfo()	;		
                  break;                	     
                }    
                */
    
                case 400002:  //2.3.4.3.1	产品配置指标(AuditId=0403,Type=30)
                {
                	Information checkInfo;
                  checkInfo.checkAllProductInfo()	;		
                  break;                	     
                }   
                case 400003:  //2.3.4.4.1	商品配置指标(AuditId=0404,Type=30)
                {
                	Information checkInfo;
                	  checkInfo.checkAllProductOfferInfo()	;		
                 	 break;                	     
                }  
                case 400004:  //2.3.4.5.1	定价计划配置指标(AuditId=0405,Type=30)
                {
                	Information checkInfo;
                  	checkInfo.checkAllPricingPlanInfo()	;		
                  break;                	     
                }  
                
                case 900001:  //2.3.5.1	系统状态性能指标(AuditId=0900,Type=40)
                {
	                CheckStatInfo oCheckAddItem ;
                  oCheckAddItem.checkAcctCap("0900",40,MIDL_FREG)	;
                  break;                	     
                }    
                               
                case 900002:  //2.3.5.2	系统状态事件信息点(AuditId=0900,Type=60)
                {
                	CheckStatInfo checkEventInfo;
                  checkEventInfo.checkHSSEventInfo()	;		
                  break;                	     
                }  
                
                case 900003:  //	2.3.5.3	告警信息点(AuditId=0900,Type=20)
                {
                	CheckStatInfo checkEventInfo;
                  	checkEventInfo.checkSystemCaution()	;		
                  break;                	     
                }
                case 900004 ://    2.3.5.4 VC接口性能指标 (AuditId=0203,Type=40)
                {
               		CheckStatInfo oCheckVCinter ;
                	oCheckVCinter.checkVCCable("0203",40,MIDL_FREG)	;
                	break;
                	
            	}
            	case 900005 ://    2.3.5.5 查询接口性能 (AuditId=0300,Type=40)
                {
               		CheckStatInfo oCheckSeekInter ;
                 	oCheckSeekInter.checkSeekInterCap("0300",40,MIDL_FREG);
                 	break;
                	
            	}
            	case 900006 ://    2.3.5.5 查询接口告警 (AuditId=0300,Type=20)
                {
               		CheckStatInfo oCheckSeekInter ;
                 	oCheckSeekInter.checkSeekInterAlarm("0300",20,MIDL_FREG); 
                 	break;            	
            	}
                                                                                                                                                                                                                                                                                                                                                                  
               default:
                {   //## 置未知统计项ID 错误
                   updateState (oPlan.m_iPlanID, "NUL", "<Error> 未知统计项(stat_name),解析错误", true);
                   return;
                }
            }
        }
        else if (oPlan.m_iAppType == 1) //## PLSQL块执行
        {
            DEFINE_QUERY (qry);
            char sql[4096];
            sprintf (sql,"%s", oPlan.m_sStatName);
            qry.setSQL (sql);
            qry.execute();
            qry.commit ();
        }
        else { //## 未知应用类型(app_type)
            updateState (oPlan.m_iPlanID, "NUL", "<Error> 未知应用类型(app_type),解析错误", true);
            return;
        }
    }
    catch (TOCIException &e)
    {
        DB_LINK->rollback ();
        char sMsg[2048];
        sprintf (sMsg, "<Error> %s \n %s", e.getErrMsg(), e.getErrSrc());
        updateState (oPlan.m_iPlanID, "ERR", sMsg, true);
        return;
    }
    //# TException
    catch (TException &e) 
    {
        DB_LINK->rollback ();
        char sMsg[2048];
        sprintf (sMsg, "<Error> %s ", e.GetErrMsg());
        updateState (oPlan.m_iPlanID, "ERR", sMsg, true);
        return;
    }
    catch (Exception &e) 
    {
        DB_LINK->rollback ();
        char sMsg[2048];
        sprintf (sMsg, "<Error> %s \n", e.descript());
        updateState (oPlan.m_iPlanID, "ERR", sMsg, true);
        return;
    }
    //# Other Exception
    catch (...) 
    {
        DB_LINK->rollback ();
        char sMsg[2048];
        sprintf (sMsg, "<Error> 程序异常退出! \n");
        updateState (oPlan.m_iPlanID, "ERR", sMsg, true);
        return;
    }
        
    updateState (oPlan.m_iPlanID, "END", "<Message> 执行成功!", true);
}
Exemplo n.º 27
0
int
main(int argc, char *argv[])
{
	int     n, i, cnt = 1, pass = 0, hexmode = 0;
	char    passwd[SKEY_MAX_PW_LEN+1], key[SKEY_BINKEY_SIZE];
	char	buf[33], *seed, *slash;

	/* If we were called as otp-METHOD, set algorithm based on that */
	if ((slash = strrchr(argv[0], '/')))
		slash++;
	else
		slash = argv[0];
	if (strncmp(slash, "otp-", 4) == 0) {
		slash += 4;
		if (skey_set_algorithm(slash) == NULL)
			errx(1, "Unknown hash algorithm %s", slash);
	}

	for (i = 1; i < argc && argv[i][0] == '-' && strcmp(argv[i], "--");) {
		if (argv[i][2] == '\0') {
			/* Single character switch */
			switch (argv[i][1]) {
			case 'n':
				if (++i == argc)
					usage(argv[0]);
				cnt = atoi(argv[i]);
				break;
			case 'p':
				if (++i == argc)
					usage(argv[0]);
				if (strlcpy(passwd, argv[i], sizeof(passwd)) >=
				    sizeof(passwd))
					errx(1, "Password too long");
				pass = 1;
				break;
			case 'x':
				hexmode = 1;
				break;
			default:
				usage(argv[0]);
			}
		} else {
			/* Multi character switches are hash types */
			if (skey_set_algorithm(&argv[i][1]) == NULL) {
				warnx("Unknown hash algorithm %s", &argv[i][1]);
				usage(argv[0]);
			}
		}
		i++;
	}

	if (argc > i + 2)
		usage(argv[0]);

	/* Could be in the form <number>/<seed> */
	if (argc <= i + 1) {
		/* look for / in it */
		if (argc <= i)
			usage(argv[0]);
		slash = strchr(argv[i], '/');
		if (slash == NULL)
			usage(argv[0]);
		*slash++ = '\0';
		seed = slash;

		if ((n = atoi(argv[i])) < 0) {
			warnx("%d not positive", n);
			usage(argv[0]);
		} else if (n > SKEY_MAX_SEQ) {
			warnx("%d is larger than max (%d)", n, SKEY_MAX_SEQ);
			usage(argv[0]);
		}
	} else {
		if ((n = atoi(argv[i])) < 0) {
			warnx("%d not positive", n);
			usage(argv[0]);
		} else if (n > SKEY_MAX_SEQ) {
			warnx("%d is larger than max (%d)", n, SKEY_MAX_SEQ);
			usage(argv[0]);
		}
		seed = argv[++i];
	}

	/* Get user's secret passphrase */
	if (!pass) {
		fputs("Reminder - Do not use this program while"
		    " logged in via telnet.\n", stderr);
		(void)fputs("Enter secret passphrase: ", stderr);
		readpass(passwd, sizeof(passwd));
		if (passwd[0] == '\0')
			exit(1);
	}

	/* Crunch seed and passphrase into starting key */
	if (keycrunch(key, seed, passwd) != 0)
		errx(1, "key crunch failed");

	if (cnt == 1) {
		while (n-- != 0)
			f(key);
		(void)puts(hexmode ? put8(buf, key) : btoe(buf, key));
	} else {
		for (i = 0; i <= n - cnt; i++)
			f(key);
		for (; i <= n; i++) {
			if (hexmode)
				(void)printf("%d: %s\n", i, put8(buf, key));
			else
				(void)printf("%d: %-29s\n", i, btoe(buf, key));
			f(key);
		}
	}
	exit(0);
}
Exemplo n.º 28
0
/*------------------------------------------------------------------
Main driver for the simulator
------------------------------------------------------------------*/
int main( int argc, char **argv ){
    double *hz, *hhxh;     /* hamiltonian components */
    double complex *psi;   /* State vector */
    params_t par;
    uint64_t i, *largest, j, samples, maxIdx, ccount;
    struct timeval tend, tbegin;
    double delta;
    double tempV, maxV;
    
    //gettimeofday( &tbegin, NULL );
    
    /* - - - - - - - - - - - Parse configuration file - - - - - - - - - - -*/
    //if( argc < 3 ){
    if( argc < 4 ){
        fprintf( stderr, "Need a json configuration file or json string. Terminating...\n" );
        return 1;
    }

    parse_file( argv[1][1], argv[2], &par );
    samples = atoi( argv[3] );
    
    par.dim = 1 << par.nQ;
    
    hz   = (double *)calloc( (par.dim),sizeof(double) );
    hhxh = (double *)calloc( (par.dim),sizeof(double) );
    psi  = (double complex *)malloc( (par.dim)*sizeof(double complex) );
    
    /* - - - - - - Compute the Hamiltonian for the simulation - - - - - - -*/
    build_h( &par, hz, hhxh );
    free( par.al ); free( par.be ); free( par.de );

    ccount = 0UL;
    for( i = 0; i < samples; ++i ){
        /* - - - - - - Compute the state vector for the simulation - - - - - - */
        init_psi( &par, psi );
        
        /* - - - - - - - - - - - - Run the Simulation - - - - - - - - - - - - -*/
        run_sim( &par, hz, hhxh, psi );

        /* - - - - - - - - - - - - - Check results - - - - - - - - - - - - - - */
        maxV = 0.0;
        for( j = 0UL; j < par.dim; ++j ){
            tempV = cabs( psi[j]*psi[j] );
            if( tempV > maxV ){
                maxV = tempV;
                maxIdx = j;
            }
        }
        ccount += ( maxIdx == par.res ) ? 1UL : 0UL;
    }
    printf( "%f\n", ccount/(double)samples );

    /* - - - - - - - - - - - - - Check results - - - - - - - - - - - - - - */
    /*
    largest = (uint64_t *)calloc( par.L, sizeof(uint64_t) );
    findLargest( par.dim, par.L, psi, largest );
    for( i = par.L; i --> 0; ){ //remember that i is unsigned
        //printf( "|psi[%d]| = %.8f\n",
        printf( "%d %.8f\n",
            largest[i],
            cabs( psi[largest[i]]*psi[largest[i]] ) );
    }
    */
    //statm_t res;
    //read_off_memory_status( &res );
    
    /* - - - - - - - - - - - Clean up and output - - - - - - - - - - - - - */
    //free( largest );
    free( psi );
    free( hz );
    free( hhxh );
    
    //gettimeofday( &tend, NULL );
    //delta = ((tend.tv_sec - tbegin.tv_sec)*1000000u + tend.tv_usec - tbegin.tv_usec)/1.e6;
    //printf( "Total time: %f s\n", delta );
    //printf( "Memory used: %ld kB\n", res.resident );
    
    return 0;
}
Exemplo n.º 29
0
int readHumbugConfig( void ){
	FILE *file;
	char conf_buf[512];

	file = fopen(HBG_CONF_FILE, "r");

	if (NULL == file) {
		fprintf( stdout, "Can`t open config file: %s\n", strerror(errno));
		return -1;
	}

	while (NULL != fgets(conf_buf, 512, file)) {

		if (('#' == *conf_buf) || ('=' == *conf_buf) || ('\n' == *conf_buf)
				|| (';' == *conf_buf) || ('\r' == *conf_buf)) {
			continue;
		}

		if ('\n' == conf_buf[strlen(conf_buf) - 1]) {
			conf_buf[strlen(conf_buf) - 1] = '\0';
		}

		if (strlen(conf_buf) <=2  || '=' == conf_buf[strlen(conf_buf) - 1] || NULL == strchr(conf_buf, '=')) {
			continue;
		}

		char *variable, value[256], *tmp_value, *p;

		variable = strtok(conf_buf, "=");
		tmp_value = strtok(NULL, "=");

		p = value;
		while (*tmp_value) {
			if (*tmp_value == ' ' || *tmp_value == '\t') {
				tmp_value++;
			} else {
				*p++ = *tmp_value++;
			}
		}
		*p = 0;

		if (0 == strncmp("port", variable, 4)) {
			strcpy(params->astPortVal, value);
		} else if (0 == strncmp("address", variable, 7)) {
			strcpy(params->astIpVal, value);
		} else if (0 == strncmp("user", variable, 4)) {
			strcpy(params->astUserVal, value);
		} else if (0 == strncmp("secret", variable, 6)) {
			strcpy(params->astPassVal, value);
		}else if (0 == strncmp("h_port", variable, 6)) {
			strcpy(params->humbugPort, value);
		} else if (0 == strncmp("h_host", variable, 6)) {
			strcpy(params->humbugHost, value);
		}else if (0 == strncmp("h_apikey", variable, 8)) {
			strcpy(params->humbugApikey, value);
		}else if (0 == strncmp("h_read", variable, 6)) {
			char *pEvent;
			params->eventsSize = 0;
			if ( NULL != (pEvent = strtok(value, ",")) ) {
				strcpy( params->events[params->eventsSize++], pEvent );
				while ( NULL != ( pEvent = strtok(NULL, ",")) ) {
					strcpy( params->events[params->eventsSize++], pEvent );
				}
			}
		}else if (0 == strncmp("encrypted", variable, 9)) {
			if (0 == strncasecmp("yes", value, 3)) {
				params->encrypted = 1;
			} else {
				params->encrypted = 0;
			}
		} else if (0 == strncmp("h_key", variable, 5)) {
			strcpy(params->humbugKey, value);
		}else if ( 0 == strncmp("log_file", variable, 8) ) {
			strcpy(params->log_file, value);
		}else if (0 == strncmp("debug_level", variable, 11)) {
			params->debug_level = atoi(value);
		}

	}

	fclose(file);
	return 0;
}
Exemplo n.º 30
0
bool handle(int csock) {
	NOTICE("################# REQUEST");
	PGconn *cnxn = NULL;
	char buf[BUF_LEN + 2];
	buf[0] = 0;
	DEFINE_VAR_ALL(str_response, str_request, str_uri, str_temp, str_form_data);
	DEFINE_VAR_MORE(str_correct_referer_start1, str_correct_referer_start2);
	DEFINE_VAR_MORE(str_referer, str_host, str_request_len, str_boundary);
	DEFINE_VAR_MORE(str_cookie_envelope, str_complete_response, str_buffer);
	
	DEBUG("### get the str_request\n");
	//##########################################
	//### get the str_request
	
	//DEBUG(">%d|%d<", SSIZE_MAX, BUF_LEN);
	
	int int_request_len = BUF_LEN;
	memset(buf, 0, BUF_LEN + 1);
	int_request_len = read(csock, buf, BUF_LEN);
	FINISH_SALLOC(str_request, int_request_len + 1);
	memcpy(str_request, buf, int_request_len);
	str_request[int_request_len] = '\0';
	
	//HERE BE DRAGONS
	//Maintainer: joseph
	//This code reads from the socket only for as long as is necessary.
	//If we have just one extra read command, it will hang until the browser
	//sends more data. Which it won't. So read until end of request.
	//@@@@@@@@@@@@@@@@@@@@@**^^""~~~"^@@^*@*@@**@@@@@@@@@
	//@@@@@@@@@@@@@*^^'"~   , - ' '; ,@@b. '  -e@@@@@@@@@
	//@@@@@@@@*^"~      . '     . ' ,@@@@(  e@*@@@@@@@@@@
	//@@@@@^~         .       .   ' @@@@@@, ~^@@@@@@@@@@@
	//@@@~ ,e**@@*e,  ,e**e, .    ' '@@@@@@e,  "*@@@@@'^@
	//@',e@@@@@@@@@@ e@@@@@@       ' '*@@@@@@    @@@'   0
	//@@@@@@@@@@@@@@@@@@@@@',e,     ;  ~^*^'    ;^~   ' 0
	//@@@@@@@@@@@@@@@^""^@@e@@@   .'           ,'   .'  @
	//@@@@@@@@@@@@@@'    '@@@@@ '         ,  ,e'  .    ;@
	//@@@@@@@@@@@@@' ,&&,  ^@*'     ,  .  i^"@e, ,e@e  @@
	//@@@@@@@@@@@@' ,@@@@,          ;  ,& !,,@@@e@@@@ e@@
	//@@@@@,~*@@*' ,@@@@@@e,   ',   e^~^@,   ~'@@@@@@,@@@
	//@@@@@@, ~" ,e@@@@@@@@@*e*@*  ,@e  @@""@e,,@@@@@@@@@
	//@@@@@@@@ee@@@@@@@@@@@@@@@" ,e@' ,e@' e@@@@@@@@@@@@@
	//@@@@@@@@@@@@@@@@@@@@@@@@" ,@" ,e@@e,,@@@@@@@@@@@@@@
	//@@@@@@@@@@@@@@@@@@@@@@@~ ,@@@,,0@@@@@@@@@@@@@@@@@@@
	//@@@@@@@@@@@@@@@@@@@@@@@@,,@@@@@@@@@@@@@@@@@@@@@@@@@
	//"""""""""""""""""""""""""""""""""""""""""""""""""""

	char *ptr_boundary_start = strstr(str_request, "Content-Type: multipart/form-data; boundary=");
	if (ptr_boundary_start != NULL &&
		strchr(ptr_boundary_start, 13) == NULL) {
		memset(buf, 0, BUF_LEN + 1);
		int int_current_length = read(csock, buf, BUF_LEN);
		FINISH_SREALLOC(str_request, int_current_length + int_request_len + 1);
		memcpy(str_request + int_request_len, buf, int_current_length);
		str_request[int_current_length + int_request_len] = '\0';
		int_request_len = int_request_len + int_current_length;
	}
	
	//DEBUG("test0>%s|%i<", str_request, int_request_len);
	
	char *request_ptr;
	//// ****if upload then special case
	if (strstr(str_request, "Content-Type: multipart/form-data; boundary=") != 0) {
		//get boundary
		char *boundary_ptr = strstr(str_request, "Content-Type: multipart/form-data; boundary=") + 44;
		char *boundary_end_ptr = strchr(boundary_ptr, 13) != 0 ?	strchr(boundary_ptr, 13) : strchr(boundary_ptr, 10);
		DEBUG("str_boundary: %d %d", boundary_end_ptr, boundary_ptr);
		int int_boundary_length = boundary_end_ptr - boundary_ptr;
		DEBUG("str_boundary: %d", int_boundary_length);
		FINISH_SALLOC(str_boundary, int_boundary_length + 3); //extra and null byte
		DEBUG("TESTING1");
		memcpy(str_boundary, boundary_ptr, int_boundary_length);
		DEBUG("TESTING2");
		str_boundary[int_boundary_length + 0] = '-';
		DEBUG("TESTING3");
		str_boundary[int_boundary_length + 1] = '-';
		DEBUG("TESTING4");
		str_boundary[int_boundary_length + 2] = '\0';
		DEBUG("TESTING5");
		int int_current_length = BUF_LEN;
		DEBUG("TESTING6");
		//DEBUG("str_boundary: %s", str_boundary);
		//DEBUG("str_request: %s", str_request);
		DEBUG("bstrstr(\"%-10s\", %d, \"%s\", %d", str_request, int_request_len, str_boundary, int_boundary_length + 2);
		/*
		DEBUG("test0>%s<", bstrstr(
						str_request, int_request_len,
						str_boundary, int_boundary_length + 2) == NULL ? "NULL" : "NOT NULL");
		while (bstrstr(
					str_request, int_request_len,
					str_boundary, int_boundary_length + 2) == NULL) {//while null
			DEBUG("test1");
			memset(buf, 0, BUF_LEN + 1);
			//FINISH_SALLOC(str_buffer, BUF_LEN + 2);
			DEBUG("test2");
			int_current_length = read(csock, buf, BUF_LEN);
			DEBUG("test3");
			FINISH_SREALLOC(str_request, int_request_len + int_current_length + 1);
			DEBUG("test4>%s<", str_request);
			memcpy(str_request + int_request_len, buf, int_current_length);
			int_request_len = int_request_len + int_current_length;
			str_request[int_request_len] = '\0';
			//SFREE(str_buffer);
			DEBUG("test5>%i<", int_request_len);
		}
		*/
		DEBUG(">%s<", bstrstr(
						str_request + int_request_len - int_current_length - int_boundary_length,
						int_current_length + int_boundary_length,
						str_boundary, int_boundary_length + 2) == NULL ? "NULL" : "NOT NULL");
		while (bstrstr(
					str_request + int_request_len - int_current_length - int_boundary_length,
					int_current_length + int_boundary_length,
					str_boundary, int_boundary_length + 2) == NULL) {//while null
			memset(buf, 0, BUF_LEN + 1);
			//DEBUG("test1");
			int_current_length = read(csock, buf, BUF_LEN);
			//DEBUG("test2");
			FINISH_SREALLOC(str_request, int_request_len + int_current_length + 1);
			//DEBUG("test3>%s<", str_request);
			memcpy(str_request + int_request_len, buf, int_current_length);
			int_request_len = int_request_len + int_current_length;
			str_request[int_request_len] = '\0';
			//DEBUG("test4>%i<", int_request_len);
		}
		DEBUG("test5>%s<", bstrstr(
						str_request,
						int_request_len,
						str_boundary, int_boundary_length + 2) - 25);
		SFREE(str_boundary);
	
	////  ****
	// if post or put, then get content length and receive that amount after two newlines, then break
	} else if (strncmp(str_request, "P", 1) == 0) {
		//we need Content-Length: before we can continue
		while (! strstr(str_request, "Content-Length:")) {
			memset(buf, 0, BUF_LEN + 1);
			//DEBUG("test1");
			int_request_len = read(csock, buf, BUF_LEN);
			//DEBUG("test2>%i<", int_request_len);
			//buf[request_len] = 0;
			FINISH_CAT_APPEND(str_request, buf);
			//DEBUG("#request_len:%d", int_request_len);
		}
		request_ptr = strstr(str_request, "Content-Length:");
		// if we didn't find anything we need to stop, len("Content-Length")==15
		if (strlen(request_ptr) < 16) {
			// error bad str_request
			FINISH("Bad str_request");
		}
		// move pointer to start of content length value
		request_ptr = request_ptr + 15;
		//DEBUG("request_ptr>%s<", request_ptr);
		
		// step through the buffer and see if we can get the length
		int req_len = 0;
		while (request_ptr != 0 && *request_ptr != '\r' && *request_ptr != '\n') {
			if (request_ptr == 0 && req_len == 0) {
				// error bad str_request
			}
			//do not comment next line!!!!!!!! give inconsistent output without this line!!!!!! idk why!!!!!!!
			//DEBUG("test1>%c<", *request_ptr);
			///////////////
			if (*request_ptr != '\r' && *request_ptr != '\n') {
				request_ptr = request_ptr + 1;
				req_len = req_len + 1;
			}
		}
		FINISH_SALLOC(str_request_len, req_len + 1);
		request_ptr = request_ptr - req_len;
		memcpy(str_request_len, request_ptr, req_len);
		str_request_len[req_len] = '\0';
		//DEBUG("test2>%s|%s<", str_request_len, request_ptr, req_len);
		req_len = atoi(str_request_len);
		SFREE(str_request_len);
		while (strstr(str_request,"\r\n\r\n") == 0 && strstr(str_request, "\n\n") == 0 && strstr(str_request, "\r\r") == 0) {
			memset(buf,0,BUF_LEN + 1);
			int_request_len = read(csock, buf, BUF_LEN);
			FINISH_CAT_APPEND(str_request, buf);
		}
		request_ptr = strstr(str_request,"\r\n\r\n") != 0 ? strstr(str_request,"\r\n\r\n") + 4 :
			strstr(str_request,"\n\n") != 0 ? strstr(str_request,"\n\n") + 2 :
			strstr(str_request,"\r\r") != 0 ? strstr(str_request,"\r\r") + 2 : 0;
		unsigned int int_length_we_want = ((request_ptr - str_request) + req_len);
		//DEBUG("test3>%s|%s<", str_request, request_ptr);
		//DEBUG("test4>%i|%i|%i|%i<\n", int_length_we_want, strlen( str_request ), (request_ptr - str_request), req_len);
	
		while (int_length_we_want > strlen(str_request)) {
			memset(buf,0,BUF_LEN + 1);
			int_request_len = read(csock, buf, BUF_LEN);
			FINISH_CAT_APPEND(str_request, buf);
			//DEBUG("test4.1>%i|%i<\n", int_length_we_want, strlen( str_request ));
		}
		//DEBUG("test5\n");
		int_request_len = strlen(str_request);
    
	// if not POST, then break at two newlines.
	// (only other request we accept is GET, we don't use any other methods of request)
	} else {
		while (strstr(str_request,"\r\n\r\n") == 0 && strstr(str_request,"\n\n") == 0 && strstr(str_request,"\r\r") == 0) {
			memset(buf, 0, BUF_LEN + 1);
			int_request_len = read(csock, buf, BUF_LEN);
			FINISH_CAT_APPEND(str_request, buf);
		}
		int_request_len = strlen(str_request);
	}
	DEBUG("request_len>%i<", strlen(str_request));
	
	
	/*
	//for testing actions
	GS.ajaxJSON('URI', 'PARAMS', function (data, error) {
		if (!error) {
			console.log(data);
			
		} else {
			GS.ajaxErrorDialog(data);
		}
	});
	*/
	
	
	
	
	str_uri = str_uri_path(str_request);
	FINISH_CHECK(str_uri != NULL,
		"str_uri_path failed");
	INFO("### str_uri: %s", str_uri);
	
	str_host = request_header(str_request, "host");
	INFO("### str_host: %s", str_host);
	//DEBUG("### REQUEST: %s", str_request);
	
	//check referer
	str_referer = request_header(str_request, "Referer");
	INFO("### str_referer: %s", str_referer);
	
	//when we have a referer, we should make sure it matches our website, but we have a few exceptions.
	if (str_referer != NULL) {
		FINISH_CAT_CSTR(str_correct_referer_start1, "https://", str_host);
		FINISH_CAT_CSTR(str_correct_referer_start2, "http://" , str_host);
		FINISH_CHECK(
			strncmp(str_correct_referer_start1, str_referer, strlen(str_correct_referer_start1)) == 0 ||
			strncmp(str_correct_referer_start2, str_referer, strlen(str_correct_referer_start2)) == 0 ||
			strlen(str_referer) <= 0 ||
			strncmp(str_uri, "/v1/"        , 4 ) != 0 ||
			//strncmp(str_uri, "/v1/env/auth", 12) == 0 ||
			strncmp(str_uri, "/v1/cluster" , 11) == 0 ||
			strncmp(str_uri, "/v1/app"     , 7 ) == 0 ||
			strncmp(str_uri, "/v1/dev"     , 7 ) == 0,
			"Referer does not match host.");
		SFREE(str_correct_referer_start1);
		SFREE(str_correct_referer_start2);
	}
	
	//####################################################################################################
	//######################################### MANAGE COOKIES ###########################################
	// set up database connection
	// FEAR NOT GCC! This will not be used uninitialized.
	//PQinitOpenSSL(0, 0); //prevent Libpq from initializing ssl
	
	bool bol_valid_subdomain = false;
	
	//if subdomain database configuration is active, then change int_global_current_conn_port
	//we use int_global_current_conn_port to connect to the postgres instance
	//if the subdomain is the default subdomain, we should connect to production
	//if the subdomain is not the default subdomain, we should connect to the correct developer area
	//if the subdomain is not recognized, we should connect to production
	if (strlen(str_global_developers) > 0) {
		char *temp = strchr(str_host, '.');
		int int_length = temp - str_host;
		FINISH_SALLOC(str_current_subdomain, int_length + 1);
		DEBUG("### str_host: %s, temp: %s, char: %c, int_length: %d\n", str_host, temp, '.', int_length);
		memcpy(str_current_subdomain, str_host, int_length);
		str_current_subdomain[int_length] = '\0';
		str_temp = getport(str_global_developers, str_current_subdomain);
		FINISH_CHECK(str_temp != NULL, "getport failed");
		if (strlen(str_temp) > 0) {
			DEBUG("VALID SUBDOMAIN DETECTED >%s|%s<", str_global_developers, str_temp);
			int_global_current_conn_port = atoi(str_temp);
			bol_valid_subdomain = true;
		}
		SFREE(str_temp);
	} else {
		FINISH_CAT_CSTR(str_current_subdomain, "");
	}
	
	DEBUG(">%s|%s|%i|%i<", str_uri, "/auth_envelope/accept_auth", strlen(str_uri), strncmp(str_uri, "/auth_envelope/accept_auth", 26) == 0);
	
	DEBUG("test0>str_request: %s", str_request);
	str_cookie_envelope = str_cookie(str_request, "envelope");
	DEBUG("test1");
	
	bol_global_public = false;
	
	DEBUG("str_uri: >%s< str_uri + 13 + strcspn(str_uri + 13, \"./\"): >%s<", str_uri, str_uri + 13 + strcspn(str_uri + 13, "./"));
	
	// if the URL does not start with /v1
	// then serve from the web_root
	if (strncmp(str_uri, "/v1/", 4) != 0) {
		str_response = link_web_root(csock, str_uri, bol_valid_subdomain ? str_current_subdomain : "");
		FINISH_CHECK(str_response != NULL, "link_web_root failed");
		goto finish;
		
	// postgres functions that start with actionnc_ or acceptnc_
	// these CAN have a COOKIE, but it WON'T BE USED
	// set up a public connection
	} else if (//str_cookie_envelope == NULL &&
		strlen(str_uri) >= 13 && strncmp(str_uri, "/v1/cluster/", 12) == 0 &&
		(strncmp(str_uri + 13 + strcspn(str_uri + 13, "./"), ".acceptnc_", 10) == 0 ||
		 strncmp(str_uri + 13 + strcspn(str_uri + 13, "./"), ".actionnc_", 10) == 0)) {
		cnxn = set_cnxn_public(csock, str_request);
		
	// built in envelope functions
	// these links CAN have a COOKIE, but if we don't then set up a public connection
	} else if (str_cookie_envelope == NULL &&
			   ((strlen(str_uri) >= 18 && strncmp(str_uri, "/v1/env/action_info"         , 18) == 0) ||
				(strlen(str_uri) >= 20 && strncmp(str_uri, "/v1/env/action_upload"       , 20) == 0) ||
				(strlen(str_uri) >= 22 && strncmp(str_uri, "/v1/env/accept_download"     , 22) == 0) ||
				(strlen(str_uri) >= 23 && strncmp(str_uri, "/v1/envelope/action_info"    , 23) == 0) ||
				(strlen(str_uri) >= 25 && strncmp(str_uri, "/v1/envelope/action_upload"  , 25) == 0) ||
				(strlen(str_uri) >= 27 && strncmp(str_uri, "/v1/envelope/accept_download", 27) == 0) ||
			    (strlen(str_uri) >= 21 && strncmp(str_uri, "/v1/env/action_select", 21) == 0) ||
				(strlen(str_uri) >= 21 && strncmp(str_uri, "/v1/env/action_update", 21) == 0) ||
				(strlen(str_uri) >= 21 && strncmp(str_uri, "/v1/env/action_insert", 21) == 0) ||
				(strlen(str_uri) >= 21 && strncmp(str_uri, "/v1/env/action_delete", 21) == 0) ||
				(strlen(str_uri) >= 20 && strncmp(str_uri, "/v1/env/action_order" , 20) == 0))) {
		cnxn = set_cnxn_public(csock, str_request);
		
	// authentication links for normal user, these CAN have a COOKIE
	} else if ((strlen(str_uri) >= 26 && strncmp(str_uri, "/auth_envelope/accept_auth", 26) == 0) ||
		(strlen(str_uri) >= 12 && strncmp(str_uri, "/v1/env/auth", 12) == 0)) {
		/*
		FINISH_CHECK(strncmp(str_current_subdomain, str_global_subdomain, strlen(str_global_subdomain)) == 0,
			"Must be in \"%s\" subdomain.", str_global_subdomain);
		*/
		
		str_response = link_auth(cnxn, str_request);
		FINISH_CHECK(str_response != NULL, "link_auth failed");
		goto finish;
	
	// authentication links for superuser, these REQUIRE a COOKIE
	} else if ((strlen(str_uri) >= 16 && strncmp(str_uri, "/v1/postage/auth", 16) == 0)) {
		str_response = link_auth_postage(str_request);
		FINISH_CHECK(str_response != NULL, "link_auth_postage failed");
		goto finish;
	
	// superuser links, these REQUIRE a COOKIE
	} else if (strncmp(str_uri, "/v1/dev"    , 7 ) == 0 ||
			   strncmp(str_uri, "/v1/postage", 11) == 0 ||
			   strncmp(str_uri, "/v1/sql"    , 7 ) == 0) {
		cnxn = set_cnxn_postage(csock, str_uri, str_request);
	
	// subdomain links, these REQUIRE a COOKIE
	} else if (bol_valid_subdomain) {
		cnxn = set_cnxn_test(csock, str_uri, str_request);
	
	// production links, these REQUIRE a COOKIE
	} else {
		cnxn = set_cnxn(csock, str_uri, str_request);
	}
	
	//IF NULL THEN EXIT, CSOCK IS ALREADY WRITTEN TO BY set_cnxn AND set_cnxn_test
	if (cnxn == NULL) {
		//if we use FINISH_CHECK, there will be a sunlogf
		//we don't want a sunlogf cause there is no error. we just want to return
		goto finish;
	}
	
	// cnxn GARANTEED TO BE VALID HERE
	
	//if public cookie (or nocookie always) then public action
	if (bol_global_public) {
		str_response = main_public_action(cnxn, csock, str_uri, str_request, int_request_len,
										  bol_valid_subdomain ? str_current_subdomain : "");
		FINISH_CHECK(str_response != NULL, "link_auth failed");
		goto finish;
	}
	
	//################################################################################################
	//########################## HAVE COOKIE, HAVE CNXN, PARSE REQUESTS ##############################
	DEBUG("COOKIE IS VALID");
	
	//not a webroot request
	if (strncmp(str_uri, "/v1/", 4) == 0) {
		char *ptr_uri = str_uri + 3;
		
		//this link is for accessing the database
		if (strlen(ptr_uri) >= 9 && strncmp(ptr_uri, "/cluster/", 9) == 0) {
			str_response = link_cluster(cnxn, ptr_uri, str_request, csock);
			FINISH_CHECK(str_response != NULL, "link_cluster failed");
			
		//this link is for uploading a file to role
		} else if (strlen(ptr_uri) >= 16 && strncmp(ptr_uri, "/upload_envelope", 16) == 0) {
			str_response = link_upload(cnxn, str_request, int_request_len, bol_valid_subdomain ? str_current_subdomain : "");
			FINISH_CHECK(str_response != NULL, "link_upload failed");
			
		//this link is for builtin c actions like action_select (read from view)
		} else if (strlen(ptr_uri) >= 10 && strncmp(ptr_uri, "/envelope/", 10) == 0) {
			// link system is in envelope_handle_c.c
			str_response = link_system(cnxn, csock, ptr_uri + 5, str_request, int_request_len, bol_valid_subdomain ? str_current_subdomain : "");
			FINISH_CHECK(str_response != NULL, "link_system failed");
		
		//shorter version of the above link
		} else if (strlen(ptr_uri) >= 5 && strncmp(ptr_uri, "/env/", 5) == 0) {
			// link system is in envelope_handle_c.c
			str_response = link_system(cnxn, csock, ptr_uri, str_request, int_request_len, bol_valid_subdomain ? str_current_subdomain : "");
			FINISH_CHECK(str_response != NULL, "link_system failed");
			
		//read file from role
		} else if (strlen(ptr_uri) >= 6 && strncmp(ptr_uri, "/role/", 6) == 0) {
			str_response = link_role(csock, cnxn, ptr_uri, bol_valid_subdomain ? str_current_subdomain : "");
			FINISH_CHECK(str_response != NULL, "link_role failed");
			
		//read app file
		} else if (strncmp(ptr_uri, "/app/", 5) == 0) {
			str_response = link_apps(csock, cnxn, ptr_uri, bol_valid_subdomain ? str_current_subdomain : "");
			FINISH_CHECK(str_response != NULL, "link_apps failed");
			
		//read app file, but require superuser
		} else if (strncmp(ptr_uri, "/dev/", 5) == 0) {
			str_response = link_apps(csock, cnxn, ptr_uri, bol_valid_subdomain ? str_current_subdomain : "");
			FINISH_CHECK(str_response != NULL, "link_apps failed");
			
		//more builtin c actions, but require superuser
		} else if (strlen(ptr_uri) >= 9 && strncmp(ptr_uri, "/postage/", 9) == 0) {
			// link system is in postage_handle_c2.c
			str_response = link_system_postage(cnxn, csock, ptr_uri, str_request, int_request_len);
			FINISH_CHECK(str_response != NULL, "link_system_postage failed");
			
		//run arbitrary sql, must be superuser
		} else if (strlen(ptr_uri) >= 4 && strncmp(ptr_uri, "/sql", 4) == 0) {
			str_response = link_sql(csock, cnxn, str_request);
			FINISH_CHECK(str_response != NULL, "link_sql failed");
			
		//if none of these, error
		} else {
			NOTICE("REQUEST TYPE: UNHANDLED str_uri:%s", str_uri);
			FINISH_CAT_CSTR(str_response, "HTTP/1.1 303 See Other\r\nLocation: /index.html\r\n");
		}
	
	//web_root request should already have been handled, error
	} else {
		NOTICE("REQUEST TYPE: UNHANDLED str_uri:%s", str_uri);
		FINISH_CAT_CSTR(str_response, "HTTP/1.1 303 See Other\r\nLocation: /index.html\r\n");
	}
	
finish:
	if (str_response != NULL) {
		INFO("REPLACE COOKIE IN str_response");
		//replace cookie before expiration
		str_complete_response = replace_cookie(str_response, str_request);
		SFREE_PWORD(str_response);
		
		DEBUG("str_complete_response: %s", str_complete_response);
		
		if ((long)write(csock, str_complete_response, strlen(str_complete_response)) != (long)strlen(str_complete_response)) {
			str_complete_response = ERROR_RESPONSE("write failed: %d (%s)", errno, strerror(errno));
			write(csock, str_complete_response, strlen(str_complete_response));
		}
	} else {
		ERROR_NORESPONSE("no str_response");
	}
	fsync(csock);
	NOTICE("RESPONSE SENT");
	if (cnxn != NULL) PQfinish(cnxn);
	SFREE_PWORD(str_request);
	SFREE_ALL();
	return true;
}