Пример #1
0
int EC_KEY_print(BIO *bp, const EC_KEY *x, int off)
	{
	unsigned char *buffer=NULL;
	size_t	buf_len=0, i;
	int     ret=0, reason=ERR_R_BIO_LIB;
	BIGNUM  *pub_key=NULL, *order=NULL;
	BN_CTX  *ctx=NULL;
	const EC_GROUP *group;
	const EC_POINT *public_key;
	const BIGNUM *priv_key;
 
	if (x == NULL || (group = EC_KEY_get0_group(x)) == NULL)
		{
		reason = ERR_R_PASSED_NULL_PARAMETER;
		goto err;
		}

	public_key = EC_KEY_get0_public_key(x);
	if ((pub_key = EC_POINT_point2bn(group, public_key,
		EC_KEY_get_conv_form(x), NULL, ctx)) == NULL)
		{
		reason = ERR_R_EC_LIB;
		goto err;
		}

	buf_len = (size_t)BN_num_bytes(pub_key);
	priv_key = EC_KEY_get0_private_key(x);
	if (priv_key != NULL)
		{
		if ((i = (size_t)BN_num_bytes(priv_key)) > buf_len)
			buf_len = i;
		}

	buf_len += 10;
	if ((buffer = OPENSSL_malloc(buf_len)) == NULL)
		{
		reason = ERR_R_MALLOC_FAILURE;
		goto err;
		}

	if (priv_key != NULL)
		{
		if (!BIO_indent(bp, off, 128))
			goto err;
		if ((order = BN_new()) == NULL)
			goto err;
		if (!EC_GROUP_get_order(group, order, NULL))
			goto err;
		if (BIO_printf(bp, "Private-Key: (%d bit)\n", 
			BN_num_bits(order)) <= 0) goto err;
		}
  
	if ((priv_key != NULL) && !print(bp, "priv:", priv_key, 
		buffer, off))
		goto err;
	if ((pub_key != NULL) && !print(bp, "pub: ", pub_key,
		buffer, off))
		goto err;
	if (!ECPKParameters_print(bp, group, off))
		goto err;
	ret=1;
err:
	if (!ret)
 		ECerr(EC_F_EC_KEY_PRINT, reason);
	if (pub_key) 
		BN_free(pub_key);
	if (order)
		BN_free(order);
	if (ctx)
		BN_CTX_free(ctx);
	if (buffer != NULL)
		OPENSSL_free(buffer);
	return(ret);
	}
Пример #2
0
static void
xfol(Prog *p, Prog **last)
{
	Prog *q, *r;
	int a, i;

loop:
	if(p == P)
		return;
	setarch(p);
	a = p->as;
	if(a == AB) {
		q = p->cond;
		if(q != P && q->as != ATEXT) {
			p->mark |= FOLL;
			p = q;
			if(!(p->mark & FOLL))
				goto loop;
		}
	}
	if(p->mark & FOLL) {
		for(i=0,q=p; i<4; i++,q=q->link) {
			if(q == *last || q == nil)
				break;
			a = q->as;
			if(a == ANOP) {
				i--;
				continue;
			}
			if(a == AB || (a == ARET && q->scond == 14) || a == ARFE)
				goto copy;
			if(q->cond == P || (q->cond->mark&FOLL))
				continue;
			if(a != ABEQ && a != ABNE)
				continue;
		copy:
			for(;;) {
				r = prg();
				*r = *p;
				if(!(r->mark&FOLL))
					print("cant happen 1\n");
				r->mark |= FOLL;
				if(p != q) {
					p = p->link;
					(*last)->link = r;
					*last = r;
					continue;
				}
				(*last)->link = r;
				*last = r;
				if(a == AB || (a == ARET && q->scond == 14) || a == ARFE)
					return;
				r->as = ABNE;
				if(a == ABNE)
					r->as = ABEQ;
				r->cond = p->link;
				r->link = p->cond;
				if(!(r->link->mark&FOLL))
					xfol(r->link, last);
				if(!(r->cond->mark&FOLL))
					print("cant happen 2\n");
				return;
			}
		}
		a = AB;
		q = prg();
		q->as = a;
		q->line = p->line;
		q->to.type = D_BRANCH;
		q->to.offset = p->pc;
		q->cond = p;
		p = q;
	}
	p->mark |= FOLL;
	(*last)->link = p;
	*last = p;
	if(a == AB || (a == ARET && p->scond == 14) || a == ARFE){
		return;
	}
	if(p->cond != P)
	if(a != ABL && a != ABX && p->link != P) {
		q = brchain(p->link);
		if(a != ATEXT && a != ABCASE)
		if(q != P && (q->mark&FOLL)) {
			p->as = relinv(a);
			p->link = p->cond;
			p->cond = q;
		}
		xfol(p->link, last);
		q = brchain(p->cond);
		if(q == P)
			q = p->cond;
		if(q->mark&FOLL) {
			p->cond = q;
			return;
		}
		p = q;
		goto loop;
	}
	p = p->link;
	goto loop;
}
Пример #3
0
template<class T> void println(const vector<T> &a)
{
	print(a);
	puts("");
}
Пример #4
0
std::ostream& Logger::debug_impl(const char* file, int line) {
  return print(enable_debug, "[GUA][D]", PRINT_BLUE, file, line);
}
Пример #5
0
std::ostream& Logger::warning_impl(const char* file, int line) {
  return print(enable_warning, "[GUA][W]", PRINT_YELLOW, file, line);
}
Пример #6
0
void led_obj_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in) {
    pyb_led_obj_t *self = self_in;
    print(env, "<LED %lu>", self->led_id);
}
Пример #7
0
static void runChibioTest(void) {
	print("EFI_SHAFT_POSITION_INPUT=%d\r\n", EFI_SHAFT_POSITION_INPUT);
	print("EFI_EMULATE_POSITION_SENSORS=%d\r\n", EFI_EMULATE_POSITION_SENSORS);
	print("EFI_ANALOG_SENSORS=%d\r\n", EFI_ANALOG_SENSORS);
	print("EFI_INTERNAL_ADC=%d\r\n", EFI_INTERNAL_ADC);
	print("EFI_HD44780_LCD=%d\r\n", EFI_HD44780_LCD);
	print("EFI_MAP_AVERAGING=%d\r\n", EFI_MAP_AVERAGING);
	print("EFI_WAVE_ANALYZER=%d\r\n", EFI_WAVE_ANALYZER);
	print("EFI_ENGINE_SNIFFER=%d\r\n", EFI_ENGINE_SNIFFER);
	print("EFI_SENSOR_CHART=%d\r\n", EFI_SENSOR_CHART);
	print("EFI_SHAFT_POSITION_INPUT=%d\r\n", EFI_SHAFT_POSITION_INPUT);
	print("EFI_ENGINE_CONTROL=%d\r\n", EFI_ENGINE_CONTROL);
	print("CH_DBG_SYSTEM_STATE_CHECK=%d\r\n", CH_DBG_SYSTEM_STATE_CHECK);
	print("CH_DBG_ENABLE_CHECKS=%d\r\n", CH_DBG_ENABLE_CHECKS);
	print("CH_DBG_ENABLE_ASSERTS=%d\r\n", CH_DBG_ENABLE_ASSERTS);
	print("CH_DBG_ENABLE_STACK_CHECK=%d\r\n", CH_DBG_ENABLE_STACK_CHECK);
	print("CH_DBG_THREADS_PROFILING=%d\r\n", CH_DBG_THREADS_PROFILING);
	TestThread(getConsoleChannel());
}
Пример #8
0
void
asmb(void)
{
	int32 t;
	int a, dynsym;
	uint32 va, fo, w, startva;
	int strtabsize;
	ElfEhdr *eh;
	ElfPhdr *ph, *pph;
	ElfShdr *sh;
	Section *sect;

	strtabsize = 0;

	if(debug['v'])
		Bprint(&bso, "%5.2f asmb\n", cputime());
	Bflush(&bso);

	sect = segtext.sect;
	seek(cout, sect->vaddr - segtext.vaddr + segtext.fileoff, 0);
	codeblk(sect->vaddr, sect->len);

	/* output read-only data in text segment */
	sect = segtext.sect->next;
	seek(cout, sect->vaddr - segtext.vaddr + segtext.fileoff, 0);
	datblk(sect->vaddr, sect->len);

	if(debug['v'])
		Bprint(&bso, "%5.2f datblk\n", cputime());
	Bflush(&bso);

	seek(cout, segdata.fileoff, 0);
	datblk(segdata.vaddr, segdata.filelen);

	/* output read-only data in text segment */
	sect = segtext.sect->next;
	seek(cout, sect->vaddr - segtext.vaddr + segtext.fileoff, 0);
	datblk(sect->vaddr, sect->len);

	/* output symbol table */
	symsize = 0;
	lcsize = 0;
	if(!debug['s']) {
		// TODO: rationalize
		if(debug['v'])
			Bprint(&bso, "%5.2f sym\n", cputime());
		Bflush(&bso);
		switch(HEADTYPE) {
		case Hnoheader:
		case Hrisc:
		case Hixp1200:
		case Hipaq:
			debug['s'] = 1;
			break;
		case Hplan9x32:
			OFFSET = HEADR+textsize+segdata.filelen;
			seek(cout, OFFSET, 0);
			break;
		case Hnetbsd:
			OFFSET += rnd(segdata.filelen, 4096);
			seek(cout, OFFSET, 0);
			break;
		case Hlinux:
			OFFSET += segdata.filelen;
			seek(cout, rnd(OFFSET, INITRND), 0);
			break;
		}
		if(!debug['s'])
			asmthumbmap();
		cflush();
	}

	cursym = nil;
	if(debug['v'])
		Bprint(&bso, "%5.2f header\n", cputime());
	Bflush(&bso);
	OFFSET = 0;
	seek(cout, OFFSET, 0);
	switch(HEADTYPE) {
	case Hnoheader:	/* no header */
		break;
	case Hrisc:	/* aif for risc os */
		lputl(0xe1a00000);		/* NOP - decompress code */
		lputl(0xe1a00000);		/* NOP - relocation code */
		lputl(0xeb000000 + 12);		/* BL - zero init code */
		lputl(0xeb000000 +
			(entryvalue()
			 - INITTEXT
			 + HEADR
			 - 12
			 - 8) / 4);		/* BL - entry code */

		lputl(0xef000011);		/* SWI - exit code */
		lputl(textsize+HEADR);		/* text size */
		lputl(segdata.filelen);			/* data size */
		lputl(0);			/* sym size */

		lputl(segdata.len - segdata.filelen);			/* bss size */
		lputl(0);			/* sym type */
		lputl(INITTEXT-HEADR);		/* text addr */
		lputl(0);			/* workspace - ignored */

		lputl(32);			/* addr mode / data addr flag */
		lputl(0);			/* data addr */
		for(t=0; t<2; t++)
			lputl(0);		/* reserved */

		for(t=0; t<15; t++)
			lputl(0xe1a00000);	/* NOP - zero init code */
		lputl(0xe1a0f00e);		/* B (R14) - zero init return */
		break;
	case Hplan9x32:	/* plan 9 */
		lput(0x647);			/* magic */
		lput(textsize);			/* sizes */
		lput(segdata.filelen);
		lput(segdata.len - segdata.filelen);
		lput(symsize);			/* nsyms */
		lput(entryvalue());		/* va of entry */
		lput(0L);
		lput(lcsize);
		break;
	case Hnetbsd:	/* boot for NetBSD */
		lput((143<<16)|0413);		/* magic */
		lputl(rnd(HEADR+textsize, 4096));
		lputl(rnd(segdata.filelen, 4096));
		lputl(segdata.len - segdata.filelen);
		lputl(symsize);			/* nsyms */
		lputl(entryvalue());		/* va of entry */
		lputl(0L);
		lputl(0L);
		break;
	case Hixp1200: /* boot for IXP1200 */
		break;
	case Hipaq: /* boot for ipaq */
		lputl(0xe3300000);		/* nop */
		lputl(0xe3300000);		/* nop */
		lputl(0xe3300000);		/* nop */
		lputl(0xe3300000);		/* nop */
		break;
	case Hlinux:
		/* elf arm */
		eh = getElfEhdr();
		fo = HEADR;
		va = INITTEXT;
		startva = INITTEXT - fo;	/* va of byte 0 of file */
		w = textsize;
		
		/* This null SHdr must appear before all others */
		sh = newElfShdr(elfstr[ElfStrEmpty]);

		/* program header info */
		pph = newElfPhdr();
		pph->type = PT_PHDR;
		pph->flags = PF_R + PF_X;
		pph->off = eh->ehsize;
		pph->vaddr = INITTEXT - HEADR + pph->off;
		pph->paddr = INITTEXT - HEADR + pph->off;
		pph->align = INITRND;

		if(!debug['d']) {
			/* interpreter for dynamic linking */
			sh = newElfShdr(elfstr[ElfStrInterp]);
			sh->type = SHT_PROGBITS;
			sh->flags = SHF_ALLOC;
			sh->addralign = 1;
			if(interpreter == nil)
				interpreter = linuxdynld;
			elfinterp(sh, startva, interpreter);

			ph = newElfPhdr();
			ph->type = PT_INTERP;
			ph->flags = PF_R;
			phsh(ph, sh);
		}

		elfphload(&segtext);
		elfphload(&segdata);

		/* Dynamic linking sections */
		if (!debug['d']) {	/* -d suppresses dynamic loader format */
			/* S headers for dynamic linking */
			sh = newElfShdr(elfstr[ElfStrGot]);
			sh->type = SHT_PROGBITS;
			sh->flags = SHF_ALLOC+SHF_WRITE;
			sh->entsize = 4;
			sh->addralign = 4;
			shsym(sh, lookup(".got", 0));

			sh = newElfShdr(elfstr[ElfStrGotPlt]);
			sh->type = SHT_PROGBITS;
			sh->flags = SHF_ALLOC+SHF_WRITE;
			sh->entsize = 4;
			sh->addralign = 4;
			shsym(sh, lookup(".got.plt", 0));

			dynsym = eh->shnum;
			sh = newElfShdr(elfstr[ElfStrDynsym]);
			sh->type = SHT_DYNSYM;
			sh->flags = SHF_ALLOC;
			sh->entsize = ELF32SYMSIZE;
			sh->addralign = 4;
			sh->link = dynsym+1;	// dynstr
			// sh->info = index of first non-local symbol (number of local symbols)
			shsym(sh, lookup(".dynsym", 0));

			sh = newElfShdr(elfstr[ElfStrDynstr]);
			sh->type = SHT_STRTAB;
			sh->flags = SHF_ALLOC;
			sh->addralign = 1;
			shsym(sh, lookup(".dynstr", 0));

			sh = newElfShdr(elfstr[ElfStrHash]);
			sh->type = SHT_HASH;
			sh->flags = SHF_ALLOC;
			sh->entsize = 4;
			sh->addralign = 4;
			sh->link = dynsym;
			shsym(sh, lookup(".hash", 0));

			sh = newElfShdr(elfstr[ElfStrRel]);
			sh->type = SHT_REL;
			sh->flags = SHF_ALLOC;
			sh->entsize = ELF32RELSIZE;
			sh->addralign = 4;
			sh->link = dynsym;
			shsym(sh, lookup(".rel", 0));

			/* sh and PT_DYNAMIC for .dynamic section */
			sh = newElfShdr(elfstr[ElfStrDynamic]);
			sh->type = SHT_DYNAMIC;
			sh->flags = SHF_ALLOC+SHF_WRITE;
			sh->entsize = 8;
			sh->addralign = 4;
			sh->link = dynsym+1;	// dynstr
			shsym(sh, lookup(".dynamic", 0));

			ph = newElfPhdr();
			ph->type = PT_DYNAMIC;
			ph->flags = PF_R + PF_W;
			phsh(ph, sh);

			/*
			 * Thread-local storage segment (really just size).
			if(tlsoffset != 0) {
				ph = newElfPhdr();
				ph->type = PT_TLS;
				ph->flags = PF_R;
				ph->memsz = -tlsoffset;
				ph->align = 4;
			}
			 */
		}

		ph = newElfPhdr();
		ph->type = PT_GNU_STACK;
		ph->flags = PF_W+PF_R;
		ph->align = 4;

		for(sect=segtext.sect; sect!=nil; sect=sect->next)
			elfshbits(sect);
		for(sect=segdata.sect; sect!=nil; sect=sect->next)
			elfshbits(sect);

		if (!debug['s']) {
			sh = newElfShdr(elfstr[ElfStrGosymtab]);
			sh->type = SHT_PROGBITS;
			sh->flags = SHF_ALLOC;
			sh->addralign = 1;
			shsym(sh, lookup("symtab", 0));

			sh = newElfShdr(elfstr[ElfStrGopclntab]);
			sh->type = SHT_PROGBITS;
			sh->flags = SHF_ALLOC;
			sh->addralign = 1;
			shsym(sh, lookup("pclntab", 0));
		}

		sh = newElfShstrtab(elfstr[ElfStrShstrtab]);
		sh->type = SHT_STRTAB;
		sh->addralign = 1;
		shsym(sh, lookup(".shstrtab", 0));

		/* Main header */
		eh->ident[EI_MAG0] = '\177';
		eh->ident[EI_MAG1] = 'E';
		eh->ident[EI_MAG2] = 'L';
		eh->ident[EI_MAG3] = 'F';
		eh->ident[EI_CLASS] = ELFCLASS32;
		eh->ident[EI_DATA] = ELFDATA2LSB;
		eh->ident[EI_VERSION] = EV_CURRENT;

		eh->type = ET_EXEC;
		eh->machine = EM_ARM;
		eh->version = EV_CURRENT;
		eh->entry = entryvalue();

		if(pph != nil) {
			pph->filesz = eh->phnum * eh->phentsize;
			pph->memsz = pph->filesz;
		}

		seek(cout, 0, 0);
		a = 0;
		a += elfwritehdr();
		a += elfwritephdrs();
		a += elfwriteshdrs();
		cflush();
		if(a+elfwriteinterp() > ELFRESERVE)
			diag("ELFRESERVE too small: %d > %d", a, ELFRESERVE);
		break;
	}
	cflush();
	if(debug['c']){
		print("textsize=%d\n", textsize);
		print("datsize=%d\n", segdata.filelen);
		print("bsssize=%d\n", segdata.len - segdata.filelen);
		print("symsize=%d\n", symsize);
		print("lcsize=%d\n", lcsize);
		print("total=%d\n", textsize+segdata.len+symsize+lcsize);
	}
}
Пример #9
0
Файл: main.c Проект: sbaychev/C
int main()
{
LIST *pFirst = NULL, *p;
int res, i, mode, c, t;
double average = 0;
FILE *pOut = NULL, *pIn = NULL;
char Fname[]="Car_List_bin.dat";
BODY car;
char carIDnum [MIN_LENGTH+1], carBran [MAX_LENGTH+1];
char *menu[] = {"USED CAR DEALERSHIP CATALOGUE\n\tSUPPORT DATA MENU",
"1-Enter data for a new car",
"2-Write the data into a binary file",
"3-Read the data from a binary file",
"4-Display all available cars",
"5-Delete a car by a car identification number",
"6-Search and Display available cars by a specified brand",
"7-Display all cars from a speciffic brand that have a price\nlarger than the average for the brand",
"8-Destroy the car data and Exit"};

do
{ system("cls");
for(i=0; i < 9; i++)
printf("\n%s\n",menu[i]);
do
{ 
fflush(stdin);
printf ("\n\nChoose mode[1-8]: ");
res = scanf("%d", &mode);
}while(res !=1);
	switch(mode)
	{
		case 1: //data entry from the keyboard
		for(i = 0; i < LOOPS; i++)
		{
			res = enterBody(&car);
			if (res != 1 ) //the function returns 0 or 1
			{
			printf("\nError in initialization %d!\n", res);
			break;
			}
			p = insertBegin(pFirst, car);
			if(p == NULL)
			{
			printf("\n\nNot enough memory!\n");
			break;
			}
			pFirst = p;
		}
		system("pause");
		break;
		case 2: // openning the file and writing on it the list
		{				
			if (pFirst == NULL)
			{	printf("\nThe CAR CATALOGUE is Empty, there are no car records to be saved!\n");system("pause");break;}
			pOut = fopen(Fname, "wb");
			if(pOut == NULL)
			{ printf("\nCan't open file for writing!\n");
			  break;
			}
			for(p = pFirst; p != NULL ; p = p->pNext)
			{
				res = writeEl(p, pOut);
				if(res != 1)
				{   
					printf("\nWriting error %d !\n\n", res);
					break;
				}
			}
			fclose(pOut);
			removeList(&pFirst);
			printf("\nThe Catalogue data has been recorded on the Car_List_bin.dat file\n");
		}
		system("pause");
		break;
		case 3: // openning the file and reading the list
		{
		pIn = fopen(Fname, "rb");
		if( pIn == NULL)
		{
			printf("\nCan't open file for reading!\n");
			break;
		}
			do
			{
				res = readEl(&car, pIn);
				if (res != 1 && res != -4 )
				{
				printf("\nReading error %d !\n", res);
				break;
				}
				if (res != -4)
				{   p = insertBegin(pFirst, car);
					if ( p == NULL )
					{ printf("\nNot enough memory!\n");
					  break;
					}
				pFirst = p;
				}
			}while(res == 1);
		fclose(pIn);
		printf("\nThe file has been read and the catalogue is available for Display via Option 4.\n");
		}
		system("pause");
		break;
		case 4: // Displaying all available cars on the screen
		if (pFirst!=NULL)
		{
			printf("\nCarID:     Color:               EngineSize: Brand:               Price:\n");
			print(pFirst);
		}
		else
			printf("\nThe CAR CATALOGUE is Empty, there are no cars to be Displayed!\n");
		system("pause");
		break;
		case 5:
			if (pFirst == NULL)
			{	printf("\nThe CAR CATALOGUE is Empty, there are no cars to be deleted!!\n");system("pause");break;}
			do{
				fflush(stdin);
				printf("\nDelete a car by entering carID|It's an alphameric sequence of upto 10 symbols|: "); 
				if(gets(carIDnum) == NULL)//the Ctrl/Z combination
				{
					printf("Error in initialization!\n");
					break;
				}
				if(carIDnum[0] == '\0')//if nothing has been entered
				{
					printf("\nError, nothing has been entered, try again!\n");
					break;
				}
				else
				{
					delByCarID(&pFirst, carIDnum);
				}

			 }while( strlen(carIDnum) != MIN_LENGTH );
		system("pause");
		break;
		case 6: 
		if (pFirst == NULL)
		{	printf("\nThe CAR CATALOGUE is Empty, there are no cars to be searched/ displayed!\n");system("pause");break;}
		do{
			fflush(stdin);
			printf("\nSearch and Display all cars by a specified by you car brand |Character set of up to 20 symbols|: "); 
			if(gets(carBran) == NULL)//the Ctrl/Z combination
			{
				printf("\nError in initialization!\n");
				break;
			}
			if(carBran[0] == '\0')//if nothing has been entered
			{
				printf("\nError, nothing has been entered, try again!\n");
				break;
			}
			else
			{
				displByBrand(carBran, &pFirst);
			}
		}while( !( strlen(carBran) < MAX_LENGTH && strlen(carBran) > 0 ) );
		system("pause");
		break;
		case 7:
		if (pFirst == NULL)
		{	printf("\nThe CAR CATALOGUE is Empty, there are no cars to be searched/ displayed!\n");system("pause");break;}
		do{
			fflush(stdin);
			printf("\nEnter a car brand |Character set of up to 20 symbols|: "); 
			if(gets(carBran) == NULL)//the Ctrl/Z combination
			{
				printf("\nError in initialization!\n");
				break;
			}
			if(carBran[0] == '\0')//if nothing has been entered
			{
				printf("\nError, nothing has been entered, try again!\n");
				break;
			}
			else
			{
				average = brandAvg(&pFirst, carBran);
				if(average != average){ printf("\n\nThe car brand you have entered is NOT in the CAR CATALOGUE!\n\n"); break;}
				printf("\nThe Average Car Price for brand %s is: %f\n",carBran ,average);
				displAllGAvgForBrand(&pFirst, carBran, average);
			}
		}while( !( strlen(carBran) < MAX_LENGTH && strlen(carBran) > 0 ) );
		system("pause");
		break;
		case 8: 
		if (pFirst!=NULL)
		removeList(&pFirst);
		printf("\nThe CAR LIST is Empty!\nProgram exiting...\n");
		break;
	default:
	printf("\nBad choice! \n");
	system("pause");
	}
	}while(mode != 8); // eight because the list gets destroyed and we exit the program
	return 0;
	}
Пример #10
0
void DrugCheck::on_printButton_clicked()
{
	QPrinter       printer( QPrinter::PrinterResolution );
	QPrintDialog   dialog( &printer, this );
	if ( dialog.exec() == QDialog::Accepted ) print( &printer );
}
Пример #11
0
int main(int argc, char* argv[])
{
	std::vector<int> vect;
	for(int i = 0; i < 10; i++)
		vect.push_back(rand() % 100);

	bubble_sort(vect);

	std::cout << "bubble_sort" << std::endl;
    print(vect);

	vect.clear();
	for(int i = 0; i < 10; i++)
		vect.push_back(rand() % 100);

	selection_sort(vect);

	std::cout << "selection sort" << std::endl;
    print(vect);

	vect.clear();
	for(int i = 0; i < 10; i++)
		vect.push_back(rand() % 100);

	coctail_sort(vect);

	std::cout << "coctail sort" << std::endl;
    print(vect);

	vect.clear();
	for(int i = 0; i < 10; i++)
		vect.push_back(rand() % 100);

	gnome_sort(vect);

	std::cout << "gnome sort" << std::endl;
    print(vect);

	vect.clear();
	for(int i = 0; i < 10; i++)
		vect.push_back(rand() % 100);

	insertion_sort(vect);

	std::cout << "instertion sort" << std::endl;
    print(vect);

	vect.clear();
	for(int i = 0; i < 10; i++)
		vect.push_back(rand() % 100);

	vect = merge_sort(vect);
	std::cout << "merge sort" << std::endl;
    print(vect);

	vect.clear();
	for(int i = 0; i < 10; i++)
		vect.push_back(rand() % 100);

	quick_sort(vect, 0, vect.size());

	std::cout << "quick sort" << std::endl;
    print(vect);

	vect.clear();
	for(int i = 0; i < 10; i++)
		vect.push_back(rand() % 100);

	heap_sort(vect);

	std::cout << "heap sort" << std::endl;
    print(vect);

	vect.clear();
	for(int i = 0; i < 10; i++)
		vect.push_back(rand() % 100);

	radix_sort(vect, 10);

	std::cout << "radix sort" << std::endl;
    print(vect);

	return 0;
}
Пример #12
0
// ------------------------------------------------------------------
// ciObjectFactory::print_contents
void ciObjectFactory::print_contents() {
  print();
  tty->cr();
  GUARDED_VM_ENTRY(print_contents_impl();)
}
Пример #13
0
static void append_new_default_deformation_field(Arg_Data *globals)
{

  VIO_Volume
    new_field;
  VIO_Real
    zero,
    st[VIO_MAX_DIMENSIONS],
    wst[VIO_MAX_DIMENSIONS],
    step[VIO_MAX_DIMENSIONS],
    XYZstart[ VIO_MAX_DIMENSIONS ],
    XYZstep[ VIO_MAX_DIMENSIONS ],
    voxel[VIO_MAX_DIMENSIONS],
    point[VIO_N_DIMENSIONS],
    dir[3][3];

  int
    index[VIO_MAX_DIMENSIONS],
    xyzv[VIO_MAX_DIMENSIONS],
    i,
    count[VIO_MAX_DIMENSIONS],
    XYZcount[VIO_MAX_DIMENSIONS],
    count_extended[VIO_MAX_DIMENSIONS];

  VIO_General_transform
    *grid_trans;

   VectorR
    XYZdirections[ VIO_MAX_DIMENSIONS ];

  /* build a vector volume to store the Grid VIO_Transform */

   /*  ALLOC(new_field,1); not needed since create volume allocs it
       internally and returns a pointer*/

  if (globals->flags.debug) { print ("In append_new_default_deformation_field...\n"); }

  new_field = create_volume(4, dim_name_vector_vol, NC_DOUBLE, TRUE, 0.0, 0.0);

  get_volume_XYZV_indices(new_field, xyzv);

                                /* get the global voxel count and voxel size */
  for(i=0; i<VIO_N_DIMENSIONS; i++) {
    count[xyzv[i]] = globals->count[i];
    count_extended[xyzv[i]] = count[xyzv[i]];
    step[xyzv[i]]  = globals->step[i];
  }
                                /* add info for the vector dimension */
  count[xyzv[VIO_Z+1]] = 3;
  count_extended[xyzv[VIO_Z+1]] = 3;
  step[xyzv[VIO_Z+1]] = 0.0;


  set_volume_sizes(       new_field, count);
  set_volume_separations( new_field, step);
  /*
     set_volume_voxel_range( new_field, -MY_MAX_VOX, MY_MAX_VOX);
     set_volume_real_range(  new_field, -1.0*globals->trans_info.max_def_magnitude, globals->trans_info.max_def_magnitude); no longer needed, now using floats */


  for(i=0; i<VIO_N_DIMENSIONS; i++) {
    dir[VIO_X][i]=globals->directions[VIO_X].coords[i];
    dir[VIO_Y][i]=globals->directions[VIO_Y].coords[i];
    dir[VIO_Z][i]=globals->directions[VIO_Z].coords[i];

  }


  set_volume_direction_cosine(new_field,xyzv[VIO_X],dir[VIO_X]);
  set_volume_direction_cosine(new_field,xyzv[VIO_Y],dir[VIO_Y]);
  set_volume_direction_cosine(new_field,xyzv[VIO_Z],dir[VIO_Z]);


  for(i=0; i<VIO_MAX_DIMENSIONS; i++)  /* set the voxel origin, used in the vol def */
    voxel[i] = 0.0;

  set_volume_translation( new_field, voxel, globals->start);



  if (globals->flags.debug) {
    print("in append new def, the start is: %8.3f %8.3f %8.3f\n", globals->start[VIO_X], globals->start[VIO_Y], globals->start[VIO_Z]);
  }

                   /* now pad the volume along the spatial axis
                      to ensure good coverage of the data space
                      with the deformation field */

  for(i=0; i<VIO_N_DIMENSIONS; i++) {
    if (globals->count[i]>1) {
      voxel[xyzv[i]] = -2.5;
      count_extended[xyzv[i]] = globals->count[i]+5;
    }
    else {
      voxel[xyzv[i]] = 0.0;
      count_extended[xyzv[i]] = 1;
    }
  }

  if (globals->flags.debug) {
    print("in append_new_default_deformation_field:\n\tcount_extended= %d %d %d %d\n",
           count_extended[0],count_extended[1],count_extended[2],count_extended[3]);
  }

  set_volume_sizes(new_field, count_extended);
  for(i=0; i<VIO_MAX_DIMENSIONS; i++) count[i] = count_extended[i];

              /* reset the first voxel position with the new origin */
  convert_voxel_to_world(new_field, voxel,
                         &(point[VIO_X]), &(point[VIO_Y]), &(point[VIO_Z]));
  for(i=0; i<VIO_MAX_DIMENSIONS; i++) voxel[i] = 0;

  set_volume_translation(new_field, voxel, point);


  if (globals->flags.debug) {
    print (" point: %8.3f %8.3f %8.3f \n", point[VIO_X], point[VIO_Y], point[VIO_Z]);

    get_volume_starts(new_field, st);
    print (" start: %8.3f %8.3f %8.3f \n", st[xyzv[VIO_X]], st[xyzv[VIO_Y]], st[xyzv[VIO_Z]]);

    voxel[0] = 0;
    voxel[1] = 0;
    voxel[2] = 0;
    get_volume_translation(new_field, voxel, wst);
    print (" wstrt: %8.3f %8.3f %8.3f \n", wst[VIO_X], wst[VIO_Y], wst[VIO_Z]);
    print (" voxel: %8.3f %8.3f %8.3f \n", voxel[xyzv[VIO_X]], voxel[xyzv[VIO_Y]], voxel[xyzv[VIO_Z]]);


    for(i=0; i<3; i++) {
      get_volume_direction_cosine(new_field,xyzv[i], wst);
      print (" dirs: %8.3f %8.3f %8.3f \n", wst[VIO_X], wst[VIO_Y], wst[VIO_Z]);
    }



  }


              /* allocate space for the deformation field data */
  alloc_volume_data(new_field);

              /* Initilize the field to zero deformation */

  /* zero = CONVERT_VALUE_TO_VOXEL(new_field, 0.0); not needed, defs are now doubles */

  for(index[0]=0; index[0]<count[0]; index[0]++)
    for(index[1]=0; index[1]<count[1]; index[1]++)
      for(index[2]=0; index[2]<count[2]; index[2]++)
        for(index[3]=0; index[3]<count[3]; index[3]++)
          {
            SET_VOXEL(new_field, index[0],index[1],index[2],index[3],0, 0.0);  /* was set to 'zero', but now as a double,can be set to 0.0 */
          }

              /* build the new GRID_TRANSFORM */

  ALLOC(grid_trans, 1);

  create_grid_transform(grid_trans, new_field, NULL);

              /* append the deforamation to the current transformation */
  concat_general_transforms(globals->trans_info.transformation, grid_trans,
                            globals->trans_info.transformation);

  delete_volume(new_field);
  delete_general_transform(grid_trans);




}
Пример #14
0
static void resample_the_deformation_field(Arg_Data *globals)
{

  VIO_Volume
    existing_field,
    new_field;
  VIO_Real
    vector_val[3],
    XYZstart[ VIO_MAX_DIMENSIONS ],
    wstart[ VIO_MAX_DIMENSIONS ],
    start[    VIO_MAX_DIMENSIONS ],
    XYZstep[  VIO_MAX_DIMENSIONS ],
    step[     VIO_MAX_DIMENSIONS ],
    step2[    VIO_MAX_DIMENSIONS ],
    s1[       VIO_MAX_DIMENSIONS ],
    voxel[    VIO_MAX_DIMENSIONS ],
    dir[3][3];
  int
    i,
    siz[      VIO_MAX_DIMENSIONS ],
    index[    VIO_MAX_DIMENSIONS ],
    xyzv[     VIO_MAX_DIMENSIONS ],
    XYZcount[ VIO_MAX_DIMENSIONS ],
    count[    VIO_MAX_DIMENSIONS ];
  VIO_General_transform
    *non_lin_part;
  VectorR
    XYZdirections[ VIO_MAX_DIMENSIONS ];
  VIO_Real
    del_x, del_y, del_z, wx, wy,wz;
  VIO_progress_struct
    progress;
  char
    **data_dim_names;


                                /* get the nonlinear part
                                   of the transformation           */

  existing_field = (VIO_Volume)NULL;
  non_lin_part = get_nth_general_transform(globals->trans_info.transformation,
                                           get_n_concated_transforms(
                                               globals->trans_info.transformation)
                                           -1);

  if (get_transform_type( non_lin_part ) == GRID_TRANSFORM){
    existing_field = (VIO_Volume)(non_lin_part->displacement_volume);
  }
  else {
    for(i=0; i<get_n_concated_transforms(globals->trans_info.transformation); i++)
      print ("Transform %d is of type %d\n",i,
             get_transform_type(
                get_nth_general_transform(globals->trans_info.transformation,
                                i) ));

    print_error_and_line_num("Cannot find the deformation field transform to resample",
                             __FILE__, __LINE__);
  }

  /* build a vector volume to store the Grid VIO_Transform */

  new_field = create_volume(4, dim_name_vector_vol, NC_DOUBLE, TRUE, 0.0, 0.0);

  get_volume_XYZV_indices(new_field, xyzv);

  for(i=0; i<VIO_N_DIMENSIONS; i++)
    step2[i] = globals->step[i];
                                /* get new start, count, step and directions,
                                   all returned in X, Y, Z order.          */

  set_up_lattice(existing_field, step2, XYZstart, wstart, XYZcount, XYZstep, XYZdirections);

                                /* reset count and step to be in volume order */
  for(i=0; i<VIO_N_DIMENSIONS; i++) {
    start[      i  ] = wstart[ i ];
    count[ xyzv[i] ] = XYZcount[ i ];
    step[  xyzv[i] ] = XYZstep[  i ];
  }

                                /* add info for the vector dimension */
  count[xyzv[VIO_Z+1]] = 3;
  step[xyzv[VIO_Z+1]] = 0.0;

         /* use the sign of the step returned to set the true step size */
  for(i=0; i<VIO_N_DIMENSIONS; i++) {
    if (step[xyzv[i]]<0)
      step[xyzv[i]] = -1.0 * fabs(globals->step[i]);
    else
      step[xyzv[i]] = fabs(globals->step[i]);
  }

  for(i=0; i<VIO_MAX_DIMENSIONS; i++)  /* set the voxel origin, used in the vol def */
    voxel[i] = 0.0;

  set_volume_sizes(       new_field, count);
  set_volume_separations( new_field, step);

  /*  set_volume_voxel_range( new_field, -MY_MAX_VOX, MY_MAX_VOX);
      set_volume_real_range(  new_field, -1.0*globals->trans_info.max_def_magnitude, globals->trans_info.max_def_magnitude);  - no longer needed, because now using doubles*/

  set_volume_translation( new_field, voxel, start);

  for(i=0; i<VIO_N_DIMENSIONS; i++) {
    dir[VIO_X][i]=XYZdirections[VIO_X].coords[i];
    dir[VIO_Y][i]=XYZdirections[VIO_Y].coords[i];
    dir[VIO_Z][i]=XYZdirections[VIO_Z].coords[i];

  }


  set_volume_direction_cosine(new_field,xyzv[VIO_X],dir[VIO_X]);
  set_volume_direction_cosine(new_field,xyzv[VIO_Y],dir[VIO_Y]);
  set_volume_direction_cosine(new_field,xyzv[VIO_Z],dir[VIO_Z]);


                                /* make sure that the vector dimension
                                   is named! */
  data_dim_names = get_volume_dimension_names(new_field);

  if( strcmp( data_dim_names[ xyzv[VIO_Z+1] ] , MIvector_dimension ) != 0 ) {
    ALLOC((new_field)->dimension_names[xyzv[VIO_Z+1]], \
          strlen(MIvector_dimension  ) + 1 );
    (void) strcpy( (new_field)->dimension_names[xyzv[VIO_Z+1]], MIvector_dimension );
  }

  delete_dimension_names(new_field, data_dim_names);

  if (globals->flags.debug) {
    print ("in resample_deformation_field:\n");
    print ("xyzv[axes] = %d, %d, %d, %d\n",xyzv[VIO_X],xyzv[VIO_Y],xyzv[VIO_Z],xyzv[VIO_Z+1]);

    get_volume_sizes(new_field, siz);
    get_volume_separations(new_field, s1);
    print ("seps: %7.3f %7.3f %7.3f %7.3f %7.3f \n",s1[0],s1[1],s1[2],s1[3],s1[4]);
    print ("size: %7d %7d %7d %7d %7d \n",siz[0],siz[1],siz[2],siz[3],siz[4]);
  }

  alloc_volume_data(new_field);

  if (globals->flags.verbose>0)
    initialize_progress_report( &progress, FALSE, count[xyzv[VIO_X]],
                               "Interpolating new field" );

  /* now resample the values from the input deformation */

  for(i=0; i<VIO_MAX_DIMENSIONS; i++) {
    voxel[i] = 0.0;
    index[i] = 0;
  }

  for(index[xyzv[VIO_X]]=0; index[xyzv[VIO_X]]<count[xyzv[VIO_X]]; index[xyzv[VIO_X]]++) {
    voxel[xyzv[VIO_X]] = (VIO_Real)index[xyzv[VIO_X]];

    for(index[xyzv[VIO_Y]]=0; index[xyzv[VIO_Y]]<count[xyzv[VIO_Y]]; index[xyzv[VIO_Y]]++) {
      voxel[xyzv[VIO_Y]] = (VIO_Real)index[xyzv[VIO_Y]];

      for(index[xyzv[VIO_Z]]=0; index[xyzv[VIO_Z]]<count[xyzv[VIO_Z]]; index[xyzv[VIO_Z]]++) {
        voxel[xyzv[VIO_Z]] = (VIO_Real)index[xyzv[VIO_Z]];

        convert_voxel_to_world(new_field, voxel, &wx,&wy,&wz);


           grid_transform_point(non_lin_part, wx, wy, wz,
                             &del_x, &del_y, &del_z);



                                /* get just the deformation part */
        del_x = del_x - wx;
        del_y = del_y - wy;
        del_z = del_z - wz;


/*        del_x = del_y = del_z = 0.0;
*/
        vector_val[0] = CONVERT_VALUE_TO_VOXEL(new_field, del_x);
        vector_val[1] = CONVERT_VALUE_TO_VOXEL(new_field, del_y);
        vector_val[2] = CONVERT_VALUE_TO_VOXEL(new_field, del_z);

        for(index[xyzv[VIO_Z+1]]=0; index[xyzv[VIO_Z+1]]<3; index[xyzv[VIO_Z+1]]++) {
          SET_VOXEL(new_field, \
                    index[0], index[1], index[2], index[3], index[4], \
                    vector_val[ index[ xyzv[ VIO_Z+1] ] ]);
        }


      }
    }
    if (globals->flags.verbose>0)
      update_progress_report( &progress,index[xyzv[VIO_X]]+1);
  }
  if (globals->flags.verbose>0)
    terminate_progress_report( &progress );

                 /* delete and free up old data */
  delete_volume(non_lin_part->displacement_volume);
               /* set new volumes into transform */
  non_lin_part->displacement_volume = new_field;

}
Пример #15
0
 void Config::makeFile()
 {
     std::fstream f(filename, std::fstream::out | std::fstream::trunc);
     print(f);
     f.close();
 }
Пример #16
0
// *****************************************************************************
// Main
int main(int argc, char* const argv[])
{
try {
    if (argc != 2) {
        std::cout << "Usage: " << argv[0] << " file\n";
        return 1;
    }
    std::string file(argv[1]);

    std::cout <<"----- Some IFD0 tags\n";
    Exiv2::ExifData ed1;
    ed1["Exif.Image.Model"] = "Test 1";

    Exiv2::Value::AutoPtr v1 = Exiv2::Value::create(Exiv2::unsignedShort);
    v1->read("160 161 162 163");
    ed1.add(Exiv2::ExifKey("Exif.Image.SamplesPerPixel"), v1.get());

    Exiv2::Value::AutoPtr v2 = Exiv2::Value::create(Exiv2::signedLong);
    v2->read("-2 -1 0 1");
    ed1.add(Exiv2::ExifKey("Exif.Image.XResolution"), v2.get());

    Exiv2::Value::AutoPtr v3 = Exiv2::Value::create(Exiv2::signedRational);
    v3->read("-2/3 -1/3 0/3 1/3");
    ed1.add(Exiv2::ExifKey("Exif.Image.YResolution"), v3.get());

    Exiv2::Value::AutoPtr v4 = Exiv2::Value::create(Exiv2::undefined);
    v4->read("255 254 253 252");
    ed1.add(Exiv2::ExifKey("Exif.Image.WhitePoint"), v4.get());

    write(file, ed1);
    print(file);

    std::cout <<"\n----- One Exif tag\n";
    Exiv2::ExifData ed2;
    ed2["Exif.Photo.DateTimeOriginal"] = "Test 2";
    write(file, ed2);
    print(file);

    std::cout <<"\n----- One Canon MakerNote tag\n";
    Exiv2::ExifData edMn1;
    edMn1["Exif.Image.Make"]   = "Canon";
    edMn1["Exif.Image.Model"]  = "Canon PowerShot S40";
    edMn1["Exif.Canon.0xabcd"] = "A Canon makernote tag";
    write(file, edMn1);
    print(file);

    std::cout <<"\n----- One Fujifilm MakerNote tag\n";
    Exiv2::ExifData edMn2;
    edMn2["Exif.Image.Make"]      = "FUJIFILM";
    edMn2["Exif.Image.Model"]     = "FinePixS2Pro";
    edMn2["Exif.Fujifilm.0x1000"] = "A Fujifilm QUALITY tag";
    write(file, edMn2);
    print(file);

    std::cout <<"\n----- One Sigma/Foveon MakerNote tag\n";
    Exiv2::ExifData edMn3;
    edMn3["Exif.Image.Make"]   = "SIGMA";
    edMn3["Exif.Image.Model"]  = "SIGMA SD10";
    edMn3["Exif.Sigma.0x0018"] = "Software? Exiv2!";
    write(file, edMn3);
    print(file);

    std::cout <<"\n----- One Nikon1 MakerNote tag\n";
    Exiv2::ExifData edMn4;
    edMn4["Exif.Image.Make"]    = "NIKON";
    edMn4["Exif.Image.Model"]   = "E990";
    edMn4["Exif.Nikon1.0x0080"] = "ImageAdjustment by Exiv2";
    write(file, edMn4);
    print(file);

    std::cout <<"\n----- One Nikon2 MakerNote tag\n";
    Exiv2::ExifData edMn5;
    edMn5["Exif.Image.Make"]    = "NIKON";
    edMn5["Exif.Image.Model"]   = "E950";
    edMn5["Exif.Nikon2.0xffff"] = "An obscure Nikon2 tag";
    write(file, edMn5);
    print(file);

    std::cout <<"\n----- One Nikon3 MakerNote tag\n";
    Exiv2::ExifData edMn6;
    edMn6["Exif.Image.Make"]    = "NIKON CORPORATION";
    edMn6["Exif.Image.Model"]   = "NIKON D70";
    edMn6["Exif.Nikon3.0x0004"] = "A boring Nikon3 Quality tag";
    write(file, edMn6);
    print(file);

    std::cout <<"\n----- One IOP tag\n";
    Exiv2::ExifData ed3;
    ed3["Exif.Iop.InteroperabilityVersion"] = "Test 3";
    write(file, ed3);
    print(file);

    std::cout <<"\n----- One GPS tag\n";
    Exiv2::ExifData ed4;
    ed4["Exif.GPSInfo.GPSVersionID"] = "Test 4";
    write(file, ed4);
    print(file);

    std::cout <<"\n----- One IFD1 tag\n";
    Exiv2::ExifData ed5;
    ed5["Exif.Thumbnail.Artist"] = "Test 5";
    write(file, ed5);
    print(file);

    std::cout <<"\n----- One IOP and one IFD1 tag\n";
    Exiv2::ExifData ed6;
    ed6["Exif.Iop.InteroperabilityVersion"] = "Test 6 Iop tag";
    ed6["Exif.Thumbnail.Artist"] = "Test 6 Ifd1 tag";
    write(file, ed6);
    print(file);

    std::cout <<"\n----- One IFD0 and one IFD1 tag\n";
    Exiv2::ExifData ed7;
    ed7["Exif.Thumbnail.Artist"] = "Test 7";
    Exiv2::Value::AutoPtr v5 = Exiv2::Value::create(Exiv2::unsignedShort);
    v5->read("160 161 162 163");
    ed7.add(Exiv2::ExifKey("Exif.Image.SamplesPerPixel"), v5.get());
    write(file, ed7);
    print(file);

    return 0;
}
catch (Exiv2::Error& e) {
    std::cout << "Caught Exiv2 exception '" << e << "'\n";
    return -1;
}
}
Пример #17
0
/*! MyWindow constructor
 * \param w - window width
 * \param h - window hight
 */
MyWindow::MyWindow(int w, int h) : num_of_colors(18)
{
    myBar = new QTabWidget(this);
    setCentralWidget(myBar);
    m_width = w;
    m_height = h;
    tab_number = 0;
    number_of_tabs = 0;
    testlayer = new Qt_layer( myBar );
    colors_flag = true;
    statusBar();

    m_scailing_factor = 2;

    // Traits Group
    QActionGroup *traitsGroup = new QActionGroup( this ); // Connected later
    traitsGroup->setExclusive( TRUE );

    setSegmentTraits = new QAction("Segment Traits",
                                   QPixmap( (const char**)line_xpm ),
                                   "&Segment Traits", 0 ,traitsGroup,
                                   "Segment Traits" );
    setSegmentTraits->setToggleAction( TRUE );

    setPolylineTraits = new QAction("Polyline Traits",
                                    QPixmap( (const char**)polyline_xpm ),
                                    "&Polyline Traits", 0 , traitsGroup,
                                    "Polyline Traits" );
    setPolylineTraits->setToggleAction( TRUE );

#ifdef CGAL_USE_CORE
    setConicTraits = new QAction("Conic Traits",
                                 QPixmap( (const char**)conic_xpm ),
                                 "&Conic Traits", 0 , traitsGroup,
                                 "Conic Traits" );
    setConicTraits->setToggleAction( TRUE );
#endif

    // Snap Mode Group

    setSnapMode = new QAction("Snap Mode", QPixmap( (const char**)snapvertex_xpm ),
                              "&Snap Mode", 0 , this, "Snap Mode" );
    setSnapMode->setToggleAction( TRUE );

    setGridSnapMode = new QAction("Grid Snap Mode",
                                  QPixmap( (const char**)snapgrid_xpm ),
                                  "&Grid Snap Mode", 0 , this,
                                  "Grid Snap Mode" );
    setGridSnapMode->setToggleAction( TRUE );

    // insert - delete - point_location Mode Group
    QActionGroup *modeGroup = new QActionGroup( this ); // Connected later
    modeGroup->setExclusive( TRUE );

    insertMode = new QAction("Insert", QPixmap( (const char**)insert_xpm ),
                             "&Insert", 0 , modeGroup, "Insert" );
    insertMode->setToggleAction( TRUE );

    deleteMode = new QAction("Delete", QPixmap( (const char**)delete_xpm ),
                             "&Delete", 0 , modeGroup, "Delete" );
    deleteMode->setToggleAction( TRUE );

    pointLocationMode = new QAction("PointLocation",
                                    QPixmap( (const char**)pointlocation_xpm ),
                                    "&Point Location", 0 , modeGroup,
                                    "Point Location" );
    pointLocationMode->setToggleAction( TRUE );

    rayShootingUpMode = new QAction("RayShootingUp",
                                    QPixmap( (const char**)demo_rayshoot_up_xpm ),
                                    "&Ray Shooting Up", 0 , modeGroup,
                                    "Ray Shooting Up" );
    rayShootingUpMode->setToggleAction( TRUE );

    rayShootingDownMode = new QAction("RayShootingDown",
                                      QPixmap( (const char**)demo_rayshoot_down_xpm ),
                                      "&Ray Shooting Down", 0 , modeGroup,
                                      "Ray Shooting Down" );
    rayShootingDownMode->setToggleAction( TRUE );

    dragMode = new QAction("Drag", QPixmap( (const char**)hand_xpm ),
                           "&Drag", 0 , modeGroup, "Drag" );
    dragMode->setToggleAction( TRUE );

    mergeMode = new QAction("Merge", QPixmap( (const char**)merge_xpm ),
                            "&Merge", 0 , modeGroup, "Merge" );
    mergeMode->setToggleAction( TRUE );

    splitMode = new QAction("Split", QPixmap( (const char**)split_xpm ),
                            "&Split", 0 , modeGroup, "Split" );
    splitMode->setToggleAction( TRUE );

    fillfaceMode = new QAction("Fill", QPixmap( (const char**)demo_fill_xpm ),
                               "&Fill", 0 , modeGroup, "Fill" );
    fillfaceMode->setToggleAction( TRUE );



    // zoom in
    zoominBt = new QAction("Zoom in", QPixmap( (const char**)zoomin_xpm ),
                           "&Zoom in", 0 , this, "Zoom in" );
    // zoom out
    zoomoutBt = new QAction("Zoom out", QPixmap( (const char**)zoomout_xpm ),
                            "&Zoom out", 0 , this, "Zoom out" );

    // color dialog
    color_dialog_bt = new QAction("Choose color", QPixmap( (const char**)demo_colors_xpm ),
                                  "&choose color", 0 , this, "choose color" );

    lower_env_dialog_bt = new QAction("Lower envelope", QPixmap( (const char**)lower_env_xpm ),
                                      "&lower envelope", 0, this, "Lower envelop" );
    lower_env_dialog_bt->setToggleAction( TRUE );

    upper_env_dialog_bt = new QAction("Upper envelope", QPixmap( (const char**)upper_env_xpm ),
                                      "&upper envelope", 0, this, "Upper envelop" );
    upper_env_dialog_bt->setToggleAction( TRUE );

#ifdef CGAL_USE_CORE
    // Conic Type Group
    QActionGroup *conicTypeGroup = new QActionGroup( this ); // Connected later
    conicTypeGroup->setExclusive( TRUE );

    setCircle = new QAction("Circle",
                            QPixmap( (const char**)demo_conic_circle_xpm ),
                            "&Circle", 0 ,conicTypeGroup,
                            "Circle" );
    setCircle->setToggleAction( TRUE );
    setSegment = new QAction("Segment",
                             QPixmap( (const char**)demo_conic_segment_xpm ),
                             "&Segment", 0 ,conicTypeGroup,
                             "Segment" );
    setSegment->setToggleAction( TRUE );
    setEllipse = new QAction("Ellipse",
                             QPixmap( (const char**)demo_conic_ellipse_xpm ),
                             "&Ellipse", 0 ,conicTypeGroup,
                             "Ellipse" );
    setEllipse->setToggleAction( TRUE );
    setParabola = new QAction("3 Points Arc",
                              QPixmap( (const char**)demo_conic_3points_xpm ),
                              "&3 Points Arc", 0 ,conicTypeGroup,
                              "3 Points Arc" );
    setParabola->setToggleAction( TRUE );
    setHyperbola = new QAction("5 Points Arc",
                               QPixmap( (const char**)demo_conic_5points_xpm ),
                               "&5 Points Arc", 0 ,conicTypeGroup,
                               "5 Points Arc" );
    setHyperbola->setToggleAction( TRUE );
#endif

    //create a timer for checking if somthing changed
    QTimer *timer = new QTimer( this );
    connect( timer, SIGNAL(timeout()),
             this, SLOT(timer_done()) );
    timer->start( 200, FALSE );

    // file menu
    QPopupMenu * file = new QPopupMenu( this );
    menuBar()->insertItem( "&File", file );
    file->insertItem("&Open Segment File...", this, SLOT(fileOpenSegment()));
    file->insertItem("&Open Polyline File...", this, SLOT(fileOpenPolyline()));
    \

#ifdef CGAL_USE_CORE
    file->insertItem("&Open Conic File...", this, SLOT(fileOpenConic()));
#endif

    file->insertItem("&Open Segment Arr File...", this, SLOT(fileOpenSegmentPm()));
    file->insertItem("&Open Polyline Arr File...", this, SLOT(fileOpenPolylinePm()));
    //file->insertItem("&Open Conic Pm File", this, SLOT(fileOpenConicPm()));
    file->insertItem("&Save...", this, SLOT(fileSave()));
    file->insertItem("&Save As...", this, SLOT(fileSaveAs()));
    //file->insertItem("&Save to ps...", this, SLOT(fileSave_ps()));
    file->insertSeparator();
    file->insertItem("&Print...", this , SLOT(print()));
    file->insertSeparator();
    file->insertItem( "&Close", this, SLOT(close()), CTRL+Key_X );
    file->insertItem( "&Quit", qApp, SLOT( closeAllWindows() ), CTRL+Key_Q );
    menuBar()->insertSeparator();

    // tab menu
    QPopupMenu * tab = new QPopupMenu( this );
    menuBar()->insertItem( "&Tab", tab );
    tab->insertItem("Add &Segment Tab", this, SLOT(add_segment_tab()));
    tab->insertItem("Add &Polyline Tab", this, SLOT(add_polyline_tab()));

#ifdef CGAL_USE_CORE
    tab->insertItem("Add &Conic Tab", this, SLOT(add_conic_tab()));
    tab->insertSeparator();
#endif

    tab->insertItem("Remove &Tab", this, SLOT(remove_tab()));
    menuBar()->insertSeparator();

    // mode menu
    QPopupMenu * mode = new QPopupMenu( this );
    menuBar()->insertItem( "&Mode", mode );
    insertMode->addTo( mode );
    deleteMode->addTo( mode );
    pointLocationMode->addTo( mode );
    rayShootingUpMode->addTo( mode );
    rayShootingDownMode->addTo( mode );
    dragMode->addTo( mode );
    mergeMode->addTo( mode );
    splitMode->addTo( mode );
    fillfaceMode->addTo( mode );
    menuBar()->insertSeparator();

    // snap mode menu
    QPopupMenu * snap_mode = new QPopupMenu( this );
    menuBar()->insertItem( "&Snap mode", snap_mode );
    setSnapMode->addTo(snap_mode);
    setGridSnapMode->addTo(snap_mode);
    menuBar()->insertSeparator();

    // traits menu
    QPopupMenu * traits = new QPopupMenu( this );
    menuBar()->insertItem( "&Traits Type", traits );
    setSegmentTraits->addTo(traits);
    setPolylineTraits->addTo(traits);
#ifdef CGAL_USE_CORE
    setConicTraits->addTo(traits);
#endif

    // options menu
    QPopupMenu * options = new QPopupMenu( this );
    menuBar()->insertItem( "&Options", options );
    options->insertSeparator();
    options->insertItem("Overlay...", this, SLOT(overlay_pm()));
    options->insertSeparator();
    options->insertItem("Properties...", this, SLOT(properties()));
    options->insertSeparator();
    options->insertItem("Show Grid", this, SLOT(showGrid()));
    options->insertItem("Hide Grid", this, SLOT(hideGrid()));
    options->insertSeparator();
    //options->insertItem("Conic Type", this, SLOT(conicType()));
    //options->insertSeparator();
    options->insertItem("Unbounded Face Color...", this, SLOT(backGroundColor()));
    options->insertSeparator();
    options->insertItem("Edge Color...", this, SLOT(changeEdgeColor()));
    options->insertSeparator();
    options->insertItem("Vertex Color...", this, SLOT(changeVertexColor()));
    options->insertSeparator();
    options->insertItem("Point-Locaiton Strategy....", this ,
                        SLOT(pointLocationStrategy()));


    // help menu
    QPopupMenu * help = new QPopupMenu( this );
    menuBar()->insertItem( "&Help", help );
    help->insertItem("How To...", this, SLOT(howto()), Key_F1);
    help->insertSeparator();
    help->insertItem("&About...", this, SLOT(about()), CTRL+Key_A );
    help->insertItem("About &Qt...", this, SLOT(aboutQt()) );

    QToolBar *modeTools = new QToolBar( this, "mode operations" );
    modeTools->setLabel( "Mode Operations" );
    insertMode->addTo( modeTools );
    deleteMode->addTo( modeTools );
    dragMode->addTo( modeTools );
    pointLocationMode->addTo( modeTools );
    rayShootingUpMode->addTo( modeTools );
    rayShootingDownMode->addTo( modeTools );
    mergeMode->addTo( modeTools );
    splitMode->addTo( modeTools );
    fillfaceMode->addTo( modeTools );
    modeTools->addSeparator();

    QToolBar *snapModeTools = new QToolBar( this, "snapMode operations" );
    snapModeTools->setLabel( "Snap Mode Operations" );
    snapModeTools->addSeparator();
    setSnapMode->addTo( snapModeTools );
    setGridSnapMode->addTo( snapModeTools );
    snapModeTools->addSeparator();

    QToolBar *traitsTool = new QToolBar( this, "traits type" );
    traitsTool->setLabel( "Traits Type" );
    traitsTool->addSeparator();
    setSegmentTraits->addTo( traitsTool );
    setPolylineTraits->addTo( traitsTool );
#ifdef CGAL_USE_CORE
    setConicTraits->addTo( traitsTool );
#endif
    traitsTool->addSeparator();

    QToolBar *zoomTool = new QToolBar( this, "zoom" );
    zoomTool->setLabel( "Zoom" );
    zoomTool->addSeparator();
    zoomoutBt->addTo( zoomTool );
    zoominBt->addTo( zoomTool );
    zoomTool->addSeparator();

    QToolBar *colorTool = new QToolBar( this, "color" );
    colorTool->addSeparator();
    colorTool->setLabel("Choose color");
    color_dialog_bt->addTo(colorTool);
    colorTool->addSeparator();

    QToolBar *envelopeTool = new QToolBar( this, "envelopes" );
    envelopeTool->addSeparator();
    envelopeTool->setLabel("Envelopes");
    lower_env_dialog_bt->addTo(envelopeTool);
    upper_env_dialog_bt->addTo(envelopeTool);
    envelopeTool->addSeparator();


#ifdef CGAL_USE_CORE
    conicTypeTool = new QToolBar( this, "conic type" );
    conicTypeTool->setLabel( "Conic Type" );
    conicTypeTool->addSeparator();
    setSegment->addTo( conicTypeTool );
    setCircle->addTo( conicTypeTool );
    setEllipse->addTo( conicTypeTool );
    setParabola->addTo( conicTypeTool );
    setHyperbola->addTo( conicTypeTool );
#endif

    connect( zoomoutBt, SIGNAL( activated () ) ,
             this, SLOT( zoomout() ) );

    connect( zoominBt, SIGNAL( activated () ) ,
             this, SLOT( zoomin() ) );

    connect (color_dialog_bt , SIGNAL( activated()) ,
             this , SLOT(openColorDialog() ) );

    connect (lower_env_dialog_bt, SIGNAL(toggled(bool)) ,
             this, SLOT(lowerEnvelope(bool) ));

    connect (upper_env_dialog_bt, SIGNAL(toggled(bool)) ,
             this, SLOT(upperEnvelope(bool) ));
    // connect mode group
    connect( modeGroup, SIGNAL( selected(QAction*) ),
             this, SLOT( updateMode(QAction*) ) );

    // connect Traits Group
    connect( traitsGroup, SIGNAL( selected(QAction*) ),
             this, SLOT( updateTraitsType(QAction*) ) );

#ifdef CGAL_USE_CORE
    // connect Conic Type Group
    connect( conicTypeGroup, SIGNAL( selected(QAction*) ),
             this, SLOT( updateConicType(QAction*) ) );
#endif

    // connect Snap Mode

    connect( setSnapMode, SIGNAL( toggled( bool ) ) ,
             this, SLOT( updateSnapMode( bool ) ) );

    connect( setGridSnapMode, SIGNAL( toggled( bool ) ) ,
             this, SLOT( updateGridSnapMode( bool ) ) );

    // connect the change of current tab
    connect( myBar, SIGNAL( currentChanged(QWidget * )  ),
             this, SLOT( update() ) );

    colors = new QColor[num_of_colors];
    colors[0]  =  Qt::blue;
    colors[1]  =  Qt::gray;
    colors[2]  =  Qt::green;
    colors[3]  =  Qt::cyan;
    colors[4]  =  Qt::magenta;
    colors[5]  =  Qt::darkRed;
    colors[6]  =  Qt::darkGreen;
    colors[7]  =  Qt::darkBlue;
    colors[8]  =  Qt::darkMagenta;
    colors[9]  =  Qt::darkCyan;
    colors[10] =  Qt::yellow;
    colors[11] =  Qt::white;
    colors[12] =  Qt::darkGray;
    colors[13] =  Qt::gray;
    colors[14] =  Qt::red;
    colors[15] =  Qt::cyan;
    colors[16] =  Qt::darkYellow;
    colors[17] =  Qt::lightGray;

    //state flag
    old_state = 0;
    add_segment_tab();
    resize(m_width,m_height);
}
Пример #18
0
agent * create_soar_agent (char * agent_name) {                                          /* loop index */
  char cur_path[MAXPATHLEN];   /* AGR 536 */

  //agent* newAgent = static_cast<agent *>(malloc(sizeof(agent)));
  agent* newAgent = new agent();

  newAgent->current_tc_number = 0;

  newAgent->name                               = savestring(agent_name);

  /* mvp 5-17-94 */
  newAgent->variables_set                      = NIL;

//#ifdef _WINDOWS
//  newAgent->current_line[0]                    = 0;
//  newAgent->current_line_index                 = 0;
//#endif /* _WINDOWS */

  newAgent->all_wmes_in_rete                   = NIL;
  newAgent->alpha_mem_id_counter               = 0;
  newAgent->alternate_input_string             = NIL;
  newAgent->alternate_input_suffix             = NIL;
  newAgent->alternate_input_exit               = FALSE;/* Soar-Bugs #54 */
  newAgent->backtrace_number                   = 0;
  newAgent->beta_node_id_counter               = 0;
  newAgent->bottom_goal                        = NIL;
  newAgent->changed_slots                      = NIL;
  newAgent->chunk_count                        = 1;
  newAgent->chunk_free_problem_spaces          = NIL;
  newAgent->chunky_problem_spaces              = NIL;  /* AGR MVL1 */
  strcpy(newAgent->chunk_name_prefix,"chunk");	/* ajc (5/14/02) */
  newAgent->context_slots_with_changed_acceptable_preferences = NIL;
  newAgent->current_file                       = NIL;
  newAgent->current_phase                      = INPUT_PHASE;
  newAgent->applyPhase                         = FALSE;
  newAgent->current_symbol_hash_id             = 0;
  newAgent->current_variable_gensym_number     = 0;
  newAgent->current_wme_timetag                = 1;
  newAgent->default_wme_depth                  = 1;  /* AGR 646 */
  newAgent->disconnected_ids                   = NIL;
  newAgent->existing_output_links              = NIL;
  newAgent->output_link_changed                = FALSE;  /* KJC 11/9/98 */
  /* newAgent->explain_flag                       = FALSE; */
  newAgent->go_number                          = 1;
  newAgent->go_type                            = GO_DECISION;
  newAgent->init_count                         = 0;
  newAgent->rl_init_count                      = 0;
  newAgent->grounds_tc                         = 0;
  newAgent->highest_goal_whose_context_changed = NIL;
  newAgent->ids_with_unknown_level             = NIL;
  newAgent->input_period                       = 0;     /* AGR REW1 */
  newAgent->input_cycle_flag                   = TRUE;  /* AGR REW1 */
  newAgent->justification_count                = 1;
  newAgent->lex_alias                          = NIL;  /* AGR 568 */
  newAgent->link_update_mode                   = UPDATE_LINKS_NORMALLY;
  newAgent->locals_tc                          = 0;
  newAgent->max_chunks_reached                 = FALSE; /* MVP 6-24-94 */
  newAgent->mcs_counter                        = 1;
  newAgent->memory_pools_in_use                = NIL;
  newAgent->ms_assertions                      = NIL;
  newAgent->ms_retractions                     = NIL;
  newAgent->num_existing_wmes                  = 0;
  newAgent->num_wmes_in_rete                   = 0;
  newAgent->potentials_tc                      = 0;
  newAgent->prev_top_state                     = NIL;
  newAgent->print_prompt_flag                  = TRUE;
  newAgent->printer_output_column              = 1;
  newAgent->production_being_fired             = NIL;
  newAgent->productions_being_traced           = NIL;
  newAgent->promoted_ids                       = NIL;
  newAgent->reason_for_stopping                = "Startup";
  newAgent->slots_for_possible_removal         = NIL;
  newAgent->stop_soar                          = TRUE;
  newAgent->system_halted                      = FALSE;
  newAgent->token_additions                    = 0;
  newAgent->top_dir_stack                      = NIL;   /* AGR 568 */
  newAgent->top_goal                           = NIL;
  newAgent->top_state                          = NIL;
  newAgent->wmes_to_add                        = NIL;
  newAgent->wmes_to_remove                     = NIL;
  newAgent->wme_filter_list                    = NIL;   /* Added this to avoid
															    access violation
																-AJC (5/13/02) */
  newAgent->multi_attributes                   = NIL;

  /* REW: begin 09.15.96 */

  newAgent->did_PE                             = FALSE;
  newAgent->soar_verbose_flag                  = FALSE;
  newAgent->FIRING_TYPE                        = IE_PRODS;
  newAgent->ms_o_assertions                    = NIL;
  newAgent->ms_i_assertions                    = NIL;

  /* REW: end   09.15.96 */

  newAgent->postponed_assertions			   = NIL;

  /* REW: begin 08.20.97 */
  newAgent->active_goal                        = NIL;
  newAgent->active_level                       = 0;
  newAgent->previous_active_level              = 0;

  /* Initialize Waterfall-specific lists */
  newAgent->nil_goal_retractions               = NIL;
  /* REW: end   08.20.97 */

  /* REW: begin 10.24.97 */
  newAgent->waitsnc                            = FALSE;
  newAgent->waitsnc_detect                     = FALSE;
  /* REW: end   10.24.97 */

  /* Initializing rete stuff */
  for (int i=0; i < 256; i++) {
     newAgent->actual[i]=0;
     newAgent->if_no_merging[i]=0;
     newAgent->if_no_sharing[i]=0;
  }

  /* Initializing lexeme */
  newAgent->lexeme.type = NULL_LEXEME;
  newAgent->lexeme.string[0] = 0;
  newAgent->lexeme.length = 0;
  newAgent->lexeme.int_val = 0;
  newAgent->lexeme.float_val = 0.0;
  newAgent->lexeme.id_letter = 'A';
  newAgent->lexeme.id_number = 0;

  reset_max_stats(newAgent);

  newAgent->real_time_tracker = 0;
  newAgent->attention_lapse_tracker = 0;

  if(!getcwd(cur_path, MAXPATHLEN))
    print(newAgent, "Unable to set current directory while initializing agent.\n");
  newAgent->top_dir_stack = static_cast<dir_stack_struct *>(malloc(sizeof(dir_stack_struct)));   /* AGR 568 */
  newAgent->top_dir_stack->directory = static_cast<char *>(malloc(MAXPATHLEN*sizeof(char)));   /* AGR 568 */
  newAgent->top_dir_stack->next = NIL;   /* AGR 568 */
  strcpy(newAgent->top_dir_stack->directory, cur_path);   /* AGR 568 */

  /* changed all references of 'i', a var belonging to a previous for loop, to 'productionTypeCounter' to be unique
    stokesd Sept 10 2004*/
  for (int productionTypeCounter=0; productionTypeCounter<NUM_PRODUCTION_TYPES; productionTypeCounter++) {
    newAgent->all_productions_of_type[productionTypeCounter] = NIL;
    newAgent->num_productions_of_type[productionTypeCounter] = 0;
  }

  newAgent->o_support_calculation_type = 4; /* KJC 7/00 */ // changed from 3 to 4 by voigtjr  (/* bugzilla bug 339 */)
  newAgent->numeric_indifferent_mode = NUMERIC_INDIFFERENT_MODE_SUM;

  /* JC ADDED: Make sure that the RHS functions get initialized correctly */
  newAgent->rhs_functions = NIL;

  // JRV: Allocates data for XML generation
  xml_create( newAgent );

  soar_init_callbacks( newAgent );

  //
  // This call is needed to set up callbacks.
  init_memory_utilities(newAgent);

  //
  // This was moved here so that system parameters could
  // be set before the agent was initialized.
  init_sysparams (newAgent);

  /* Initializing all the timer structures */
  // Timers must be initialized after sysparams
#ifndef NO_TIMING_STUFF
  newAgent->timers_cpu.set_enabled(&(newAgent->sysparams[TIMERS_ENABLED]));
  newAgent->timers_kernel.set_enabled(&(newAgent->sysparams[TIMERS_ENABLED]));
  newAgent->timers_phase.set_enabled(&(newAgent->sysparams[TIMERS_ENABLED]));
#ifdef DETAILED_TIMING_STATS
  newAgent->timers_gds.set_enabled(&(newAgent->sysparams[TIMERS_ENABLED]));
#endif
  reset_timers(newAgent);
#endif

  // dynamic memory pools (should come before consumers of dynamic pools)
  newAgent->dyn_memory_pools = new std::map< size_t, memory_pool* >();

  // dynamic counters
  newAgent->dyn_counters = new std::map< std::string, uint64_t >();

  // exploration initialization
  newAgent->exploration_params[ EXPLORATION_PARAM_EPSILON ] = exploration_add_parameter( 0.1, &exploration_validate_epsilon, "epsilon" );
  newAgent->exploration_params[ EXPLORATION_PARAM_TEMPERATURE ] = exploration_add_parameter( 25, &exploration_validate_temperature, "temperature" );

  // rl initialization
  newAgent->rl_params = new rl_param_container( newAgent );
  newAgent->rl_stats = new rl_stat_container( newAgent );
  newAgent->rl_prods = new rl_production_memory();

  rl_initialize_template_tracking( newAgent );

  // select initialization
  newAgent->select = new select_info;
  select_init( newAgent );


  // predict initialization
  newAgent->prediction = new std::string();
  predict_init( newAgent );


  // wma initialization
  newAgent->wma_params = new wma_param_container( newAgent );
  newAgent->wma_stats = new wma_stat_container( newAgent );
  newAgent->wma_timers = new wma_timer_container( newAgent );

#ifdef USE_MEM_POOL_ALLOCATORS
  newAgent->wma_forget_pq = new wma_forget_p_queue( std::less< wma_d_cycle >(), soar_module::soar_memory_pool_allocator< std::pair< wma_d_cycle, wma_decay_set* > >( newAgent ) );
  newAgent->wma_touched_elements = new wma_pooled_wme_set( std::less< wme* >(), soar_module::soar_memory_pool_allocator< wme* >( newAgent ) );
  newAgent->wma_touched_sets = new wma_decay_cycle_set( std::less< wma_d_cycle >(), soar_module::soar_memory_pool_allocator< wma_d_cycle >( newAgent ) );
#else
  newAgent->wma_forget_pq = new wma_forget_p_queue();
  newAgent->wma_touched_elements = new wma_pooled_wme_set();
  newAgent->wma_touched_sets = new wma_decay_cycle_set();
#endif
  newAgent->wma_initialized = false;
  newAgent->wma_tc_counter = 2;


  // epmem initialization
  newAgent->epmem_params = new epmem_param_container( newAgent );
  newAgent->epmem_stats = new epmem_stat_container( newAgent );
  newAgent->epmem_timers = new epmem_timer_container( newAgent );

  newAgent->epmem_db = new soar_module::sqlite_database();
  newAgent->epmem_stmts_common = NULL;
  newAgent->epmem_stmts_graph = NULL;

  newAgent->epmem_node_mins = new std::vector<epmem_time_id>();
  newAgent->epmem_node_maxes = new std::vector<bool>();

  newAgent->epmem_edge_mins = new std::vector<epmem_time_id>();
  newAgent->epmem_edge_maxes = new std::vector<bool>();
  newAgent->epmem_id_repository = new epmem_parent_id_pool();
  newAgent->epmem_id_replacement = new epmem_return_id_pool();
  newAgent->epmem_id_ref_counts = new epmem_id_ref_counter();

  // debug module settings
  newAgent->debug_params = new debug_param_container( newAgent );

  #ifdef USE_MEM_POOL_ALLOCATORS
  newAgent->epmem_node_removals = new epmem_id_removal_map( std::less< epmem_node_id >(), soar_module::soar_memory_pool_allocator< std::pair< epmem_node_id, bool > >( newAgent ) );
  newAgent->epmem_edge_removals = new epmem_id_removal_map( std::less< epmem_node_id >(), soar_module::soar_memory_pool_allocator< std::pair< epmem_node_id, bool > >( newAgent ) );

  newAgent->epmem_wme_adds = new epmem_symbol_set( std::less< Symbol* >(), soar_module::soar_memory_pool_allocator< Symbol* >( newAgent ) );
  newAgent->epmem_promotions = new epmem_symbol_set( std::less< Symbol* >(), soar_module::soar_memory_pool_allocator< Symbol* >( newAgent ) );

  newAgent->epmem_id_removes = new epmem_symbol_stack( soar_module::soar_memory_pool_allocator< Symbol* >( newAgent ) );
#else
  newAgent->epmem_node_removals = new epmem_id_removal_map();
  newAgent->epmem_edge_removals = new epmem_id_removal_map();

  newAgent->epmem_wme_adds = new epmem_symbol_set();
  newAgent->epmem_promotions = new epmem_symbol_set();

  newAgent->epmem_id_removes = new epmem_symbol_stack();
#endif

  newAgent->epmem_validation = 0;

  // smem initialization
  newAgent->smem_params = new smem_param_container( newAgent );
  newAgent->smem_stats = new smem_stat_container( newAgent );
  newAgent->smem_timers = new smem_timer_container( newAgent );

  newAgent->smem_db = new soar_module::sqlite_database();

  newAgent->smem_validation = 0;

#ifdef USE_MEM_POOL_ALLOCATORS
  newAgent->smem_changed_ids = new smem_pooled_symbol_set( std::less< Symbol* >(), soar_module::soar_memory_pool_allocator< Symbol* >( newAgent ) );
#else
  newAgent->smem_changed_ids = new smem_pooled_symbol_set();
#endif
  newAgent->smem_ignore_changes = false;

  // statistics initialization
  newAgent->dc_stat_tracking = false;
  newAgent->stats_db = new soar_module::sqlite_database();

  newAgent->substate_break_level = 0;

  return newAgent;
}
Пример #19
0
ApplicationWindow::ApplicationWindow()
    : QMainWindow( 0, "example application main window", WDestructiveClose )
{
    int id;

    printer = new QPrinter;
    QPixmap openIcon, saveIcon, printIcon;

    fileTools = new QToolBar( this, "file operations" );
    fileTools->setLabel( tr( "File Operations" ) );

    openIcon = QPixmap( fileopen );
    QToolButton * fileOpen
	= new QToolButton( openIcon, "Open File", QString::null,
			   this, SLOT(load()), fileTools, "open file" );

    saveIcon = QPixmap( filesave );
    QToolButton * fileSave
	= new QToolButton( saveIcon, "Save File", QString::null,
			   this, SLOT(save()), fileTools, "save file" );

    printIcon = QPixmap( fileprint );
    QToolButton * filePrint
	= new QToolButton( printIcon, "Print File", QString::null,
			   this, SLOT(print()), fileTools, "print file" );

    (void)QWhatsThis::whatsThisButton( fileTools );

    QWhatsThis::add( fileOpen, fileOpenText );
    QMimeSourceFactory::defaultFactory()->setPixmap( "fileopen", openIcon );
    QWhatsThis::add( fileSave, fileSaveText );
    QWhatsThis::add( filePrint, filePrintText );

    QPopupMenu * file = new QPopupMenu( this );
    menuBar()->insertItem( "&File", file );

    file->insertItem( "&New", this, SLOT(newDoc()), CTRL+Key_N );

    id = file->insertItem( openIcon, "&Open",
			   this, SLOT(load()), CTRL+Key_O );
    file->setWhatsThis( id, fileOpenText );

    id = file->insertItem( saveIcon, "&Save",
			   this, SLOT(save()), CTRL+Key_S );
    file->setWhatsThis( id, fileSaveText );
    id = file->insertItem( "Save &as...", this, SLOT(saveAs()) );
    file->setWhatsThis( id, fileSaveText );
    file->insertSeparator();
    id = file->insertItem( printIcon, "&Print",
			   this, SLOT(print()), CTRL+Key_P );
    file->setWhatsThis( id, filePrintText );
    file->insertSeparator();
    file->insertItem( "&Close", this, SLOT(close()), CTRL+Key_W );
    file->insertItem( "&Quit", qApp, SLOT( closeAllWindows() ), CTRL+Key_Q );

    QPopupMenu * help = new QPopupMenu( this );
    menuBar()->insertSeparator();
    menuBar()->insertItem( "&Help", help );

    help->insertItem( "&About", this, SLOT(about()), Key_F1 );
    help->insertItem( "About &Qt", this, SLOT(aboutQt()) );
    help->insertSeparator();
    help->insertItem( "What's &This", this, SLOT(whatsThis()), SHIFT+Key_F1 );

    e = new QMultiLineEdit( this, "editor" );
    e->setFocus();
    setCentralWidget( e );
    statusBar()->message( "Ready", 2000 );
    resize( 450, 600 );
}
Пример #20
0
// *** triggered by top button ***
// This function plays a melody from flash in the background while the two
// user LEDs alternately fade in and out.
unsigned char melodyTest()
{
	unsigned char button;
	int i = 0;

	// the following function does not block execution
	play_from_program_space(fugue);	// play music from flash in the background

	red_led(0);		// turn red and green LEDs off
	green_led(0);

	clear();			// clear the LCD, go to the start of the first LCD line
	print("melody:");	// print to the LCD
	lcd_goto_xy(0, 1);	// go to the start of the second LCD line
	print("fugue");		// print to the LCD

	time_reset();		// reset the internal millisecond timer count to zero

	while (1)			// loop here until we detect a button press and return
	{
		if (get_ms() >= 5)	// if 5 or more milliseconds have elapsed
		{
			time_reset();	// reset timer count to zero
			// check if middle or bottom buttons have been pressed
			button = button_is_pressed(MIDDLE_BUTTON | BOTTOM_BUTTON);
			if (button != 0)	// if so, stop melody and return the button ID
			{
				stop_playing();	// stop playing music
				return button;
			}
			i += 5;		// increase our state variable based on the time
			if (i >= 1000)	// once a second has elapsed, reset the state var
				i = 0;
		}

		// the following code alternately flashes the red and green LEDs,
		// fading them in and out over time as the music plays in the
		// background.  This is accomplished by using high-frequency PWM
		// signals on the LED lines.  Essentially, each LED is flickering
		// on and off very quickly, which gives it the apperance of variable
		// brightness depending on the percentage of the cycle the LED is on.
		// Each LED flicker cycle takes a total approximately 251 us.

		if (i < 250)		// phase 1: ramp up the red LED brightness
		{					//  as i increases over time
			red_led(1);			// turn the red LED on
			delay_us(i + 1);	// microsecond delay
			red_led(0);			// turn the red LED off
			delay_us(250 - i);	// microsecond delay
		}
		else if (i < 500)	// phase 2: ramp down the red LED brightness
		{
			red_led(1);			// turn the red LED on
			delay_us(500 - i);	// microsecond delay
			red_led(0);			// turn the red LED off
			delay_us(i - 249);	// microsecond delay
		}
		else if (i < 750)	// phase 3: ramp up the green LED brightness
		{
			green_led(1);		// turn the green LED on
			delay_us(i - 499);	// microsecond delay
			green_led(0);		// turn the green LED off
			delay_us(750 - i);	// microsecond delay
		}
		else				// phase 4: ramp down the green LED brightness
		{
			green_led(1);		// turn the green LED on
			delay_us(1000 - i);	// microsecond delay
			green_led(0);		// turn the green LED off
			delay_us(i - 749);	// microsecond delay
		}
		
	}
}
Пример #21
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    mSettings(new QSettings(this)),
    mSavePath(""),
    mProgressBar(new QProgressBar(this)),
    mStatusBar(new QStatusBar(this)),
    mToolBar(new QToolBar(this)),
    mMenuBar(new QMenuBar(this)),
    mTabWidget(new QTabWidget(this)),

    // Menus
    mFileMenu(new QMenu(tr("File"), this)),
    mEditMenu(new QMenu(tr("Edit"), this)),
    mToolsMenu(new QMenu(tr("Tools"), this)),
    mHelpMenu(new QMenu(tr("Help"), this)),

    //Actions
    mActionExit(new QAction(QP_ICON("application-exit"), tr("Exit"), this)),
    mActionOpen(new QAction(QP_ICON("document-open"),tr("Open"), this)),
    mActionSave(new QAction(QP_ICON("document-save"),tr("Save"), this)),
    mActionSaveAs(new QAction(QP_ICON("document-save-as"),tr("Save As"), this)),
    mActionPrint(new QAction(QP_ICON("document-print"),tr("Print"), this)),

    mActionClear(new QAction(QP_ICON("edit-clear"), tr("Clear"), this)),
    mActionUndo(new QAction(QP_ICON("edit-undo"),tr("Undo"), this)),
    mActionRedo(new QAction(QP_ICON("edit-redo"),tr("Redo"), this)),
    mActionSwap(new QAction(QP_ICON("system-switch-user"), tr("Swap"), this)),
    mActionOptions(new QAction(QP_ICON("configure"), tr("Options"), this)),

    mActionAbout(new QAction(QIcon::fromTheme("help-about"), tr("About"), this)),
    mActionAboutQt(new QAction(tr("About Qt"), this)),

    mTranslationWidget(new QPTranslationWidget(this)),
    mDictionaryWidget(new DictionaryWidget(this)),
    mSettingsDialog(new Config(this)),

    mPluginsConfig(new PluginsConfig),
    mTranslatorsConfig(new QPTranslatorsConfig(this)),
    mLanguageConfig(new LanguageConfig(this)),
    mDictionaryConfig(new DictionaryConfig(this)),
    mCommonConfig(new CommonConfig(this))
{
    setWindowTitle(qApp->applicationName());

    mActionOpen->setShortcut(QKeySequence("Ctrl+O"));
    mActionSave->setShortcut(QKeySequence("Ctrl+S"));
    mActionSaveAs->setShortcut(QKeySequence("Ctrl+Shift+S"));
    mActionPrint->setShortcut(QKeySequence("Ctrl+P"));
    mActionExit->setShortcut(QKeySequence("Ctrl+Q"));

    mActionUndo->setShortcut(QKeySequence("Ctrl+U"));
    mActionRedo->setShortcut(QKeySequence("Ctrl+R"));
    mActionSwap->setShortcut(QKeySequence("Ctrl+Alt+S"));

    mFileMenu->addAction(mActionOpen);
    mFileMenu->addSeparator();
    mFileMenu->addAction(mActionSave);
    mFileMenu->addAction(mActionSaveAs);
    mFileMenu->addAction(mActionPrint);
    mFileMenu->addSeparator();
    mFileMenu->addAction(mActionExit);

    mEditMenu->addAction(mActionClear);
    mEditMenu->addSeparator();
    mEditMenu->addAction(mActionUndo);
    mEditMenu->addAction(mActionRedo);
    mEditMenu->addAction(mActionSwap);
    mEditMenu->addSeparator();
    mEditMenu->addAction(mActionOptions);

    mHelpMenu->addAction(mActionAbout);
    mHelpMenu->addAction(mActionAboutQt);

    mMenuBar->addMenu(mFileMenu);
    mMenuBar->addMenu(mEditMenu);
    mMenuBar->addMenu(mHelpMenu);

    mToolBar->addAction(mActionOpen);
    mToolBar->addAction(mActionSave);
    mToolBar->addAction(mActionSaveAs);
    mToolBar->addSeparator();
    mToolBar->addAction(mActionClear);
    mToolBar->addAction(mActionUndo);
    mToolBar->addAction(mActionRedo);
    mToolBar->setMovable(false);

    mTabWidget->setTabPosition(QTabWidget::West);

    this->setCentralWidget(mTabWidget);
    this->setStatusBar(mStatusBar);
    this->setMenuBar(mMenuBar);

    mProgressBar->setMaximum(0);
    mProgressBar->setMinimum(0);
    mProgressBar->setValue(0);
    mStatusBar->addPermanentWidget(mProgressBar);

    mProgressBar->setFormat("");
    mProgressBar->setFixedWidth(200);
    stopProgressBar();

    this->addToolBar(mToolBar);
    this->addToolBar(mDictionaryWidget->getToolBar());
    this->addToolBar(mTranslationWidget->mainToolBar());

    mTabWidget->insertTab(mTabWidget->count(), mTranslationWidget, QP_ICON("translator"), tr("Translator"));
    mTabWidget->insertTab(mTabWidget->count(), mDictionaryWidget, QP_ICON("dictionary"), tr("Dictionary"));

    if(mTabWidget->count() > 1)
        mTabWidget->setCurrentIndex(0);

    // Configuring settings pages
    mSettingsDialog->addPage(mTranslatorsConfig, "Translators");
    mSettingsDialog->addPage(mDictionaryConfig, "Dictionaries");
    mSettingsDialog->addPage(mLanguageConfig, "Languages");
    mSettingsDialog->addPage(mPluginsConfig, "Plugins");
    mSettingsDialog->addPage(mCommonConfig, "Generic");

    connect(mActionOpen, SIGNAL(triggered()), this, SLOT(open()));
    connect(mActionPrint, SIGNAL(triggered()), this, SLOT(print()));
    connect(mActionSave, SIGNAL(triggered()), this, SLOT(save()));
    connect(mActionSaveAs, SIGNAL(triggered()), this, SLOT(saveAs()));

    connect(mActionExit, SIGNAL(triggered()), this, SLOT(exit()));
    connect(mActionClear, SIGNAL(triggered()), this, SLOT(clear()));
    connect(mActionUndo, SIGNAL(triggered()), this, SLOT(undo()));
    connect(mActionRedo, SIGNAL(triggered()), this, SLOT(redo()));
    connect(mActionSwap, SIGNAL(triggered()), mTranslationWidget, SLOT(swap()));
    connect(mActionOptions, SIGNAL(triggered()), mSettingsDialog, SLOT(show()));
    connect(mActionAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(mActionAbout, SIGNAL(triggered()), this, SLOT(about()));

    // Widgets , Dialogs, etc
    connect(mSettingsDialog, SIGNAL(accepted()), this, SLOT(onConfigAccept()));
    connect(mTabWidget, SIGNAL(currentChanged(int)), this, SLOT(onIndexChange(int)));

    connect(mTranslatorsConfig, SIGNAL(translatorIndexChanged(int)), mTranslationWidget, SLOT(setTranslatorIndex(int)));
    connect(mTranslationWidget, SIGNAL(translatorIndexChanged(int)), mTranslatorsConfig, SLOT(setTranslatorIndex(int)));
    connect(mTranslationWidget, SIGNAL(translatorIndexChanged(int)), this, SLOT(updateTranslatorConfig()));

    connect(mTranslationWidget, SIGNAL(message(QString)), this, SLOT(setStatusBarMessage(QString)));
    connect(mDictionaryWidget, SIGNAL(message(QString)), this, SLOT(setStatusBarMessage(QString)));

    connect(mTranslationWidget, SIGNAL(started()), this, SLOT(startProgressBar()));
    connect(mDictionaryWidget, SIGNAL(started()), this, SLOT(startProgressBar()));

    connect(mTranslationWidget, SIGNAL(finished()), this, SLOT(stopProgressBar()));
    connect(mDictionaryWidget, SIGNAL(finished()), this, SLOT(stopProgressBar()));

    mSettings->beginGroup(QP_MAINWINDOW_CONFIG_GROUP);

    // Read configs
    updateTranslatorConfig();
    onConfigAccept();

    mTranslationWidget->setTranslatorsNames(mTranslatorsConfig->getTranslatorsNames());

    mTranslatorsConfig->read();

    readCfg();

}
Пример #22
0
// *** triggered by middle button ***
// This function tests the eight user I/O pins and the trimmer potentiometer.
// At any given time, one pin is being driven low while the rest are weakly
// pulled high (to 5 V).  At the same time, the LCD is displaying the input
// values on the eight user I/O pins.  If you short a pin to *GROUND* (note:
// do not short the pin to power, only short it to one of the ground pads
// along the top edge of the board), you will see the corresponding bit on
// the LCD go to zero.  The PD1 bit will always read zero as it is being
// pulled down through the red user LED.
unsigned char IOTest()
{
	// the bits of the "outputs" byte will correspond to the pin states of
	// the user I/O lines as follows:

	// outputs:   b7  b6  b5  b4  b3  b2  b1  b0
	// user I/O: PC5 PC4 PC3 PC2 PC1 PC0 PD1 PD0

	// Only one bit of "outputs" will ever be set (1) at a time; the rest will
	// be cleared (0).  The user I/O pin that corresponds to the set bit will
	// be an output that is driven low while all of the other user I/O pins
	// will be inputs with internal pull-ups enabled (i.e. they will be weakly
	// pulled to 5V and will read as high).
	unsigned int outputs = 0x8000;	// binary: 10000000 00000000
	unsigned char *outputsA = (unsigned char *)&outputs;	// pointer to low byte of outputs
	unsigned char *outputsD = outputsA + 1;					// pointer to high byte of outputs
	unsigned char direction = 0;
	unsigned char button;

	red_led(1);
	green_led(1);

	clear();		// clear the LCD
	print("User I/O");
	lcd_goto_xy(0, 1);
	print("DDDDDDDD AAAAAAAA");
	lcd_goto_xy(0, 2);
	print("76543210 76543210");

	set_analog_mode(MODE_8_BIT);	// configure ADC for 8-bit readings

	while (1)			// loop here until we detect a button press and return
	{
		time_reset();				// reset millisecond timer count to zero

		DDRA = 0;					// make PA0 - PA7 inputs
		PORTA = 0;					// PA0 - PA7 -> high impedance inputs
		DDRD = 0;					// make PD0 - PD7 inputs
		PORTD = 0;					// PD0 - PD7 -> high impedance inputs

		PORTD |= ~(*outputsD);
		DDRD |= *outputsD;
		PORTA |= (~(*outputsA)) & 0x3F;
		DDRA |= *outputsA & 0x3F;	// never make PA6 and PA7 outputs


		// The following loop will execute for an amount of time determined
		// by the position of the user trimmer potentiometer (trimpot).
		// When the trimpot is at one extreme, the loop will take 256*2 = 512
		// milliseconds.  When the trimpot is at the other extreme, the
		// loop will only execute once, which takes slightly more than 20 ms.
		// In this way, the trimpot controls the speed at which the output
		// byte changes.
		do
		{
			// The bits of the "inputs" byte reflect the input values of pins
			// PD0, PD1, and PC0 - PC5.  Bit 0 corresponds to PD0, bit 1 to
			// PD1, and bits 2 - 7 to PC0 - PC5, respectively.
			unsigned char inputsA = PINA;
			unsigned char inputsD = PIND;
			lcd_goto_xy(0, 3);		// go to the start of the fourth LCD line
			print_binary(inputsD);	// print the "input" byte in binary
			print(" ");
			print_binary(inputsA);
			delay_ms(20);			// delay here for 20 milliseconds
			// check if top or bottom buttons have been pressed
			button = button_is_pressed(TOP_BUTTON | BOTTOM_BUTTON);
			if (button != 0)	// if so, reset I/O states, return button ID
			{
				DDRA = 0;					// make PA0 - PA7 inputs
				PORTA = 0;					// PA0 - PA7 -> high impedance inputs
				DDRD = 0;					// make PD0 - PD7 inputs
				PORTD = 0;					// PD0 - PD7 -> high impedance inputs
				return button;
			}
		}
		while (get_ms() < read_trimpot() * 2);

		if (direction)
			outputs <<= 1;		// bit-shift our output byte left by one bit
		else
			outputs >>= 1;		// bit-shift our output byte right by one bit

		if (outputs == 1)		// if we have reached the right edge
			direction = 1;		// switch direction to "left"
		if (outputs == 0x8000)	// if we have reached the left edge
			direction = 0;		// switch direction to "right"
	}
}
Пример #23
0
std::ostream& Logger::message_impl(const char* file, int line) {
  return print(enable_message, "[GUA][M]", PRINT_GREEN, file, line);
}
Пример #24
0
// *** triggered by middle button ***
// This function tests the motors by first ramping motor1 speed from zero
// to full speed "forward", to full speed "reverse", and finally back to zero.
// It then does the same for motor2 before repeating all over again.
// While motor1 is running, the red user LED is on, otherwise it is off.
// While the currently active motor is moving "forward", the green user LED
// is on, otherwise it is off.  The LCD gives you feedback as to which motor
// is currently moving in which direction (FWD = "forward", RVS = "reverse", and
// OFF = inactive).
unsigned char motorTest()
{
	unsigned char button;

	red_led(1);
	green_led(1);

	clear();			// clear the LCD, go to the start of the first LCD line
	print("motor2");	// print to the first line of the LCD
	lcd_goto_xy(0, 1);	// go to the start of the second LCD line
	print("motor1");	// print to the second line of the LCD

	x2_set_acceleration(MOTOR1, 70, 0);
	x2_set_brake_duration(MOTOR1, 0, 0);
	x2_set_acceleration(MOTOR2, 70, 0);
	x2_set_brake_duration(MOTOR2, 0, 0);

	while (1)
	{
		lcd_goto_xy(0, 0);
		print("M1: FWD");
		x2_set_motor(MOTOR1, ACCEL_DRIVE, 255);
		button = motor_wait(700);
		if (button)
			return button;
		lcd_goto_xy(0, 0);
		print("M1:    ");
		x2_set_motor(MOTOR1, IMMEDIATE_DRIVE, 0);
		button = motor_wait(150);
		if (button)
			return button;
		lcd_goto_xy(0, 0);
		print("M1: RVS");
		x2_set_motor(MOTOR1, ACCEL_DRIVE, -255);
		button = motor_wait(700);
		if (button)
			return button;

		lcd_goto_xy(0, 0);
		print("M1: OFF");
		lcd_goto_xy(0, 1);
		print("M2: FWD");
		x2_set_motor(MOTOR1, IMMEDIATE_DRIVE, 0);
		x2_set_motor(MOTOR2, ACCEL_DRIVE, 255);
		button = motor_wait(700);
		if (button)
			return button;
		lcd_goto_xy(0, 1);
		print("M2:    ");
		x2_set_motor(MOTOR2, IMMEDIATE_DRIVE, 0);
		button = motor_wait(150);
		if (button)
			return button;
		lcd_goto_xy(0, 1);
		print("M2: RVS");
		x2_set_motor(MOTOR2, ACCEL_DRIVE, -255);
		button = motor_wait(700);
		if (button)
			return button;
		lcd_goto_xy(0, 1);
		print("M2: OFF");
		x2_set_motor(MOTOR2, IMMEDIATE_DRIVE, 0);
	}
}
Пример #25
0
std::ostream& Logger::error_impl(const char* file, int line) {
  return print(enable_error, "[GUA][E]", PRINT_RED, file, line);
}
Пример #26
0
void test()
{
	unsigned char button;

	clear();

	delay(200);
	print("Orangutan");	// print to the top line of the LCD
	delay_ms(400);		// delay 200 ms
	lcd_goto_xy(0, 1);	// go to the start of the second LCD line
	print(" X2");	// print to the bottom line of the LCD

	red_led(1);
	delay_ms(100);
	green_led(1);
	delay_ms(100);
	red_led2(1);
	delay_ms(100);
	green_led2(1);
	delay_ms(100);
	yellow_led(1);
	delay_ms(100);

	red_led(0);
	delay_ms(100);
	green_led(0);
	delay_ms(100);
	red_led2(0);
	delay_ms(100);
	green_led2(0);
	delay_ms(100);
	yellow_led(0);
	delay_ms(100);

	clear();			// clear the LCD, move cursor to start of top line

	print("  VBAT");

	do
	{
		// Perform 10-bit analog-to-digital conversions on ADC channel 6.
		// Average ten readings and return the result, which will be one
		// third of the battery voltage when the "ADC6 = VBAT/3" solder
		// bridge is in place on the bottom of the Orangutan PCB
		int vbat = read_battery_millivolts_x2();
		lcd_goto_xy(0, 1);	// go to the start of the second LCD line
		print_long(vbat);	// display battery voltage in millivolts
		print(" mV ");		// display the units
		delay_ms(50);		// delay for 50 ms
		button = button_is_pressed(ANY_BUTTON);	// check for button press
	}
	while (button == 0);	// loop if no buttons are being pressed


	red_led(1);
	green_led(1);
	red_led2(1);
	green_led2(1);
	yellow_led(1);


	// *** MAIN LOOP ***

	while (1)	// loop forever
	{
		if (button & TOP_BUTTON)			// if the top button is pressed
			button = melodyTest();	// this func. loops until next button press

		else if (button & MIDDLE_BUTTON)	// if the middle button is pressed
			button = IOTest();		// this func. loops until next button press

		else if (button & BOTTOM_BUTTON)	// if the bottom button is pressed
			button = motorTest();	// this func. loops until next button press
	}
}
Пример #27
0
void KMLVector::findLayers(KMLNode* poNode, int bKeepEmptyContainers)
{
    bool bEmpty = true;

    // Start with the trunk
    if( nullptr == poNode )
    {
        nNumLayers_ = 0;
        poNode = poTrunk_;
    }

    if( isFeature(poNode->getName())
        || isFeatureContainer(poNode->getName())
        || ( isRest(poNode->getName())
             && poNode->getName().compare("kml") != 0 ) )
    {
        return;
    }
    else if( isContainer(poNode->getName()) )
    {
        for( int z = 0; z < (int) poNode->countChildren(); z++ )
        {
            if( isContainer(poNode->getChild(z)->getName()) )
            {
                findLayers(poNode->getChild(z), bKeepEmptyContainers);
            }
            else if( isFeatureContainer(poNode->getChild(z)->getName()) )
            {
                bEmpty = false;
            }
        }

        if( bKeepEmptyContainers && poNode->getName() == "Folder" )
        {
            if (!bEmpty)
                poNode->eliminateEmpty(this);
        }
        else if(bEmpty)
        {
            return;
        }

        Nodetype nodeType = poNode->getType();
        if( bKeepEmptyContainers ||
            isFeature(Nodetype2String(nodeType)) ||
            nodeType == Mixed ||
            nodeType == MultiGeometry || nodeType == MultiPoint ||
            nodeType == MultiLineString || nodeType == MultiPolygon)
        {
            poNode->setLayerNumber(nNumLayers_++);
            papoLayers_ = static_cast<KMLNode**>(
                CPLRealloc(papoLayers_, nNumLayers_ * sizeof(KMLNode*)) );
            papoLayers_[nNumLayers_ - 1] = poNode;
        }
        else
        {
            CPLDebug( "KML", "We have a strange type here for node %s: %s",
                      poNode->getName().c_str(),
                      Nodetype2String(poNode->getType()).c_str() );
        }
    }
    else
    {
        CPLDebug( "KML",
                  "There is something wrong!  Define KML_DEBUG to see details");
        if( CPLGetConfigOption("KML_DEBUG", nullptr) != nullptr )
            print();
    }
}
Пример #28
0
 menu()
{
 int x;
  do{
       {
	clrscr();
	design();
	t();
	textcolor(WHITE);
	gotoxy(24,3);
	cprintf("\xDB\xDB\xDB\xDB\xB2  SAM'S DEPARTMANTAL STORE  \xB2\xDB\xDB\xDB\xDB");
	gotoxy(3,4);
	cprintf("--------------------------------------------------------------------------");
	gotoxy(35,5);
	cprintf("MAIN MENU");
	gotoxy(26,8);
	cprintf(" 1  -   INFORMATION ABOUT PRODUCTS            ");
	gotoxy(26,9);
	cprintf(" 2  -   ENTER  PURCHASE  RECORDS            ");
	gotoxy(26,10);
	cprintf(" 3  -   ENTER PRODUCTS TO BE SALE           ");
	gotoxy(26,11);
	cprintf(" 4  -   SEARCH FOR RECORD                     ");
	gotoxy(26,12);
	cprintf(" 5  -   DELETE RECORD FROM STORE DATABASE     ");
	gotoxy(26,13);
	cprintf(" 6  -   VIEW SALES , PURCHASE & PROFIT REPORT ");
	gotoxy(26,14);
	cprintf(" 7  -   PRINT RECORDS                         ");
	gotoxy(26,15);
	cprintf(" 8  -   BAR  GRAPH OF QUANTITY / PROFIT       ");
	gotoxy(26,16);
	cprintf(" 9  -   RETRIEVE INFORMATION         ");
	gotoxy(26,17);
	cprintf(" H  -   HELP                                  ");
	gotoxy(26,18);
	cprintf(" E  -   EXIT                                  ");
	gotoxy(26,23);
	cprintf("ENTER YOUR CHOICE :: ");
	gotoxy(47,23);
	x=toupper(getch());
	switch(x)
	{
	case '1':
	infor();
	break;

	case '2':
	entry();
	break;

	case '3':
	edit();
	break;

	case '4':
	search();
	break;

	case '5':
	del();
	break;

	case '6':
	report2();
	break;

	case '7':
	print();
	break;

	case 'h': case'H':
	help();
	break;

	case'8':
	graph1();
	break;

	case '9':
	display();
	break;

	case 'e': case 'E':
	exit(0);
	break;

	default:
	clrscr();
	design();
	gotoxy(17,12);
	printf("\a\xDB\xB2  WRONG ENTRY : PRESS ANY KEY AND TRY AGAIN");
	getche();
	}
      }
    }while((x!='e')||(x!='E'));
return x;
}
Пример #29
0
 /*static*/ void log::nextln()
 {
     print ("\n");
 }
Пример #30
0
int ECPKParameters_print(BIO *bp, const EC_GROUP *x, int off)
	{
	unsigned char *buffer=NULL;
	size_t	buf_len=0, i;
	int     ret=0, reason=ERR_R_BIO_LIB;
	BN_CTX  *ctx=NULL;
	const EC_POINT *point=NULL;
	BIGNUM	*p=NULL, *a=NULL, *b=NULL, *gen=NULL,
		*order=NULL, *cofactor=NULL;
	const unsigned char *seed;
	size_t	seed_len=0;
	
	static const char *gen_compressed = "Generator (compressed):";
	static const char *gen_uncompressed = "Generator (uncompressed):";
	static const char *gen_hybrid = "Generator (hybrid):";
 
	if (!x)
		{
		reason = ERR_R_PASSED_NULL_PARAMETER;
		goto err;
		}

	if (EC_GROUP_get_asn1_flag(x))
		{
		/* the curve parameter are given by an asn1 OID */
		int nid;

		if (!BIO_indent(bp, off, 128))
			goto err;

		nid = EC_GROUP_get_curve_name(x);
		if (nid == 0)
			goto err;

		if (BIO_printf(bp, "ASN1 OID: %s", OBJ_nid2sn(nid)) <= 0)
			goto err;
		if (BIO_printf(bp, "\n") <= 0)
			goto err;
		}
	else
		{
		/* explicit parameters */
		int is_char_two = 0;
		point_conversion_form_t form;
		int tmp_nid = EC_METHOD_get_field_type(EC_GROUP_method_of(x));

		if (tmp_nid == NID_X9_62_characteristic_two_field)
			is_char_two = 1;

		if ((p = BN_new()) == NULL || (a = BN_new()) == NULL ||
			(b = BN_new()) == NULL || (order = BN_new()) == NULL ||
			(cofactor = BN_new()) == NULL)
			{
			reason = ERR_R_MALLOC_FAILURE;
			goto err;
			}

		if (is_char_two)
			{
			if (!EC_GROUP_get_curve_GF2m(x, p, a, b, ctx))
				{
				reason = ERR_R_EC_LIB;
				goto err;
				}
			}
		else /* prime field */
			{
			if (!EC_GROUP_get_curve_GFp(x, p, a, b, ctx))
				{
				reason = ERR_R_EC_LIB;
				goto err;
				}
			}

		if ((point = EC_GROUP_get0_generator(x)) == NULL)
			{
			reason = ERR_R_EC_LIB;
			goto err;
			}
		if (!EC_GROUP_get_order(x, order, NULL) || 
            		!EC_GROUP_get_cofactor(x, cofactor, NULL))
			{
			reason = ERR_R_EC_LIB;
			goto err;
			}
		
		form = EC_GROUP_get_point_conversion_form(x);

		if ((gen = EC_POINT_point2bn(x, point, 
				form, NULL, ctx)) == NULL)
			{
			reason = ERR_R_EC_LIB;
			goto err;
			}

		buf_len = (size_t)BN_num_bytes(p);
		if (buf_len < (i = (size_t)BN_num_bytes(a)))
			buf_len = i;
		if (buf_len < (i = (size_t)BN_num_bytes(b)))
			buf_len = i;
		if (buf_len < (i = (size_t)BN_num_bytes(gen)))
			buf_len = i;
		if (buf_len < (i = (size_t)BN_num_bytes(order)))
			buf_len = i;
		if (buf_len < (i = (size_t)BN_num_bytes(cofactor))) 
			buf_len = i;

		if ((seed = EC_GROUP_get0_seed(x)) != NULL)
			seed_len = EC_GROUP_get_seed_len(x);

		buf_len += 10;
		if ((buffer = OPENSSL_malloc(buf_len)) == NULL)
			{
			reason = ERR_R_MALLOC_FAILURE;
			goto err;
			}

		if (!BIO_indent(bp, off, 128))
			goto err;

		/* print the 'short name' of the field type */
		if (BIO_printf(bp, "Field Type: %s\n", OBJ_nid2sn(tmp_nid))
			<= 0)
			goto err;  

		if (is_char_two)
			{
			/* print the 'short name' of the base type OID */
			int basis_type = EC_GROUP_get_basis_type(x);
			if (basis_type == 0)
				goto err;

			if (!BIO_indent(bp, off, 128))
				goto err;

			if (BIO_printf(bp, "Basis Type: %s\n", 
				OBJ_nid2sn(basis_type)) <= 0)
				goto err;

			/* print the polynomial */
			if ((p != NULL) && !print(bp, "Polynomial:", p, buffer,
				off))
				goto err;
			}
		else
			{
			if ((p != NULL) && !print(bp, "Prime:", p, buffer,off))
				goto err;
			}
		if ((a != NULL) && !print(bp, "A:   ", a, buffer, off)) 
			goto err;
		if ((b != NULL) && !print(bp, "B:   ", b, buffer, off))
			goto err;
		if (form == POINT_CONVERSION_COMPRESSED)
			{
			if ((gen != NULL) && !print(bp, gen_compressed, gen,
				buffer, off))
				goto err;
			}
		else if (form == POINT_CONVERSION_UNCOMPRESSED)
			{
			if ((gen != NULL) && !print(bp, gen_uncompressed, gen,
				buffer, off))
				goto err;
			}
		else /* form == POINT_CONVERSION_HYBRID */
			{
			if ((gen != NULL) && !print(bp, gen_hybrid, gen,
				buffer, off))
				goto err;
			}
		if ((order != NULL) && !print(bp, "Order: ", order, 
			buffer, off)) goto err;
		if ((cofactor != NULL) && !print(bp, "Cofactor: ", cofactor, 
			buffer, off)) goto err;
		if (seed && !print_bin(bp, "Seed:", seed, seed_len, off))
			goto err;
		}
	ret=1;
err:
	if (!ret)
 		ECerr(EC_F_ECPKPARAMETERS_PRINT, reason);
	if (p) 
		BN_free(p);
	if (a) 
		BN_free(a);
	if (b)
		BN_free(b);
	if (gen)
		BN_free(gen);
	if (order)
		BN_free(order);
	if (cofactor)
		BN_free(cofactor);
	if (ctx)
		BN_CTX_free(ctx);
	if (buffer != NULL) 
		OPENSSL_free(buffer);
	return(ret);	
	}