Esempio n. 1
0
    Vertex_info * getNext()
        {
            if (finalized_vertices.size () > 0)
            {
                dias::vertex_id v_id = finalized_vertices.front ();
                finalized_vertices.pop ();
                dias::vertex_db::iterator v_ptr = vertices.find (v_id);
                assert (v_ptr != vertices.end ());
                Vertex_info * result = new Vertex_info;
                result->vid = v_id;
                result->vi = v_ptr->second;
                vertices.erase (v_ptr);
                return result;
            }

            if (!f.eof ())
            {
                while (finalized_vertices.size () == 0 && !f.eof ())
                {
                    std::string line = "";

                    while (line == "")
                    {
                        if (f.eof ())
                            break;
                        std::getline (f, line);
                    }
                    if (f.eof ())
                        break;

                    boost::char_delimiters_separator<char> sep (false, "", 0);
                    boost::tokenizer<> tokens (line, sep);
                    boost::tokenizer<>::iterator p = tokens.begin ();

                    std::string type = *p++;

                    if (type == "#")
                        continue;

                    if (type == "v")
                        read_vertex (p, tokens.end ());
                    else if (type == "c")
                    {
                        dias::tetrahedra t
                            = read_tetrahedra (p, tokens.end ());
                        add_neighbours (t);
                    }
                    else
                        assert (false);
                }

                if (finalized_vertices.size () > 0)
                    return getNext ();
            }

            assert (vertices.size () > 0);
            assert (finalized_vertices.size () == 0);
            dias::vertex_db::const_iterator p = vertices.begin ();
            finalized_vertices.push (p->first);
            return getNext ();
        }
Esempio n. 2
0
File: mm.c Progetto: bkashyap/ece454
/**********************************************************
 * place
 * Mark the block as allocated
 **********************************************************/
void place(void* bp, size_t asize)
{
    
#if DEBUG >= 3
    printf(" ==place== ");
#endif

    // min_size is the smallest free block possible: header(wsize) + 2*WSIZE + footer(wsize)
    // aligned to DSIZE (2*WSIZE)
    size_t min_size = DSIZE+OVERHEAD;
	size_t free_size = GET_SIZE(HDRP(bp));

    size_t bsize = asize;
    uintptr_t * prev;
    uintptr_t * next; 
    if (free_size >= asize+min_size)
    {
        printf(" asize %zu", asize);
        PUT(HDRP(bp), PACK(asize, 1));
        PUT(FTRP(bp), PACK(asize, 1));
        
        
        bsize = free_size - asize;
        printf(" bsize %zu \n", bsize);
        void * free_bp = NEXT_BLKP(bp);
        PUT(HDRP(free_bp), PACK(bsize, 0));
        //printf("footer %p\n",FTRP(free_bp));
        //printf("bsize %zu\n",bsize);
        PUT(FTRP(free_bp), PACK(bsize, 0));
        //printf("bsize in footer %zu\n",GET_SIZE(FTRP(free_bp)));
        //print_heap();

        

        /* free list */
        if (flhead == fltail) { //one free block
            printf("breakpoint1\n");
            flhead = free_bp;
            fltail = free_bp;
            getNext(free_bp) = NULL;
            getPrev(free_bp) = NULL;
        }
        else if (bp == flhead) { //more than one free block and at head
            printf("breakpoint2\n");

            prev = getPrev(bp);
            next = getNext(bp);
            flhead = free_bp;
            getPrev(free_bp) = prev;
            getNext(free_bp) = next; 

            if (prev != NULL ) {
                getNext(prev) = free_bp;
            }
            if (next != NULL) {
                getPrev(next) = free_bp;
            }


        }
        else if (bp == fltail) {
            printf("breakpoint3\n");
            prev = getPrev(bp);
            next = getNext(bp);
            fltail = free_bp;
            getPrev(free_bp) = prev;
            getNext(free_bp) = next; 

            if (prev != NULL ) {
                getNext(prev) = free_bp;
            }
            if (next != NULL) {
                getPrev(next) = free_bp;
            }

        }
        else {
            printf("breakpoint4\n");
            prev = getPrev(bp);
            next = getNext(bp);
            getPrev(free_bp) = prev;
            getNext(free_bp) = next;


            if (prev != NULL ) {
                getNext(prev) = free_bp;
            }
            if (next != NULL) {
                getPrev(next) = free_bp;
            }
        }


    }
    else  //no need to split
    {

        printf(" no split\n");
        //if (counter >=  770) print_heap();
        PUT(HDRP(bp), PACK(free_size, 1));
        PUT(FTRP(bp), PACK(free_size, 1));
        /* free list */
        
        if (flhead == fltail) {
            printf(" 1..\n");    
            flhead = fltail = NULL;
        }
        else if (bp == flhead) {
            printf(" 2..\n");
            flhead = getNext(flhead);
            getPrev(flhead)= NULL;
        }
        else if (bp == fltail) {
            printf(" 3..\n");
            fltail = getPrev(fltail);
            putNext(fltail,NULL);
        }
        else {
            prev = getPrev(bp);
            next = getNext(bp);
            if (prev!=NULL){
                printf(" 4 get prev.....\n");
                printf("prev's %p\n",prev);
                getNext(prev) = next;    
            }
            printf(" 4.2.....\n");
            if (next!=NULL){
                getPrev(next) = prev;
            }
            printf(" 4.3..done\n");
        }

    }

}
Esempio n. 3
0
 void RecordStoreV1Base::IntraExtentIterator::invalidate(const DiskLoc& dl) {
     if (dl == _curr)
         getNext();
 }
Esempio n. 4
0
bool run(ASTNode* mainNode, RuntimeError* error, ExternalFunctions externals, char** libsToLoad, int libsCount)
{
    assert(mainNode->nodeType == AST_MAIN);

    getValueFunc = getGetValueFuncPtr();

    MemoryStack stack = makeMemoryStack(MEGABYTE(16));
    Array<HINSTANCE> libraries = makeArray<HINSTANCE>(KILOBYTE(1));

    Scope scalarTypesScope = makeScope(nullptr);
    Scope globalScope = makeScope(&scalarTypesScope);

    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("s64"), {}, 8 });
    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("u64"), {}, 8 });
    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("f64"), {}, 8 });

    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("s32"), {}, 4 });
    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("u32"), {}, 4 });
    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("f32"), {}, 4 });

    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("s16"), {}, 2 });
    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("u16"), {}, 2 });

    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("s8"), {}, 1 });
    pushType(&scalarTypesScope, &stack, TypeDefinition{ makeSlice("u8"), {}, 1 });

    ExternalArgumentDefinition binarys32Args[] = { { "a", "s32" }, { "b", "s32" } };
    ExternalArgumentDefinition binaryf32Args[] = { { "a", "f32" }, { "b", "f32" } };
    ExternalDefinition buildInExternals[] = {
        { &scalarS32FuncsHandler, "opAdd", "s32", binarys32Args, ArrayCount(binarys32Args) },
        { &scalarS32FuncsHandler, "opSub", "s32", binarys32Args, ArrayCount(binarys32Args) },
        { &scalarS32FuncsHandler, "opEqualsOrLess", "s32", binarys32Args, ArrayCount(binarys32Args) },
        { &scalarS32FuncsHandler, "opEqualsOrsGreater", "s32", binarys32Args, ArrayCount(binarys32Args) },
        { &scalarS32FuncsHandler, "opLess", "s32", binarys32Args, ArrayCount(binarys32Args) },
        { &scalarS32FuncsHandler, "opGreater", "s32", binarys32Args, ArrayCount(binarys32Args) },
        { &scalarS32FuncsHandler, "opEquals", "s32", binarys32Args, ArrayCount(binarys32Args) },
        { &scalarS32FuncsHandler, "opNot", "s32", binarys32Args, ArrayCount(binarys32Args) },
    };

    loadExternals(&scalarTypesScope, &stack, ExternalFunctions{ buildInExternals, ArrayCount(buildInExternals) });
    loadExternals(&scalarTypesScope, &stack, externals);
    loadLibrariries(&libraries, &scalarTypesScope, &stack, libsToLoad, libsCount);

    bool stillWorking = true;

    // load all global function and type definitions
    ListIterator<ASTNode> iterator = makeIterator(&mainNode->main.statements);
    while (stillWorking && hasNext(&iterator))
    {
        ASTNode* statement = getNext(&iterator);
        if (statement->nodeType == AST_STATEMENT_FUNCTION_DEFINITION ||
            statement->nodeType == AST_STATEMENT_TYPE_DEFINITION)
            stillWorking = runStatement(statement, &stack, &globalScope, error);
        else
        {
            // TODO: illigal statement exception? Or do this on parsing stage? 
        }
    }

    if (stillWorking)
    {
        FunctionIdentifier mainIdentifier = {};
        mainIdentifier.name = makeSlice("main");

        Function* func = getFunction(&globalScope, mainIdentifier);

        if (func != nullptr)
            stillWorking = runStatement(func->body, &stack, &globalScope, error);
        else
        {
            stillWorking = false;
            *error = RuntimeError{ RET_UNDEFINED_FUNCTION, mainIdentifier.name, 0 };
        }
    }

    scopeFreeMemory(&globalScope, &stack);
    scopeFreeMemory(&scalarTypesScope, &stack);

    freeAllLibraries(&libraries);

    freeArray(&libraries);
    freeMemoryStack(&stack);
    return stillWorking;
}
Esempio n. 5
0
	void noExplictparam()
	{
		printf("no file supplied\n");
		DlList_T lst=dll_create();
		int hasChanged=0;
		int looping=1;
		char buff[MAX_LINE];
		while(looping)
 		{
 			fgets(buff,MAX_LINE, stdin);
 			strtok(buff,"\n");
			if(strcmp(buff,"Q")==0)
			{

				dll_destroy(lst);
				break;



			}
			else if(strcmp(buff,".")==0)
			{
				showCursor(lst);

			}

			else if(strcmp(buff,"a")==0)
			{

				int currentlooping=1;
				while(currentlooping)
				{
					fgets(buff,MAX_LINE, stdin);
					strtok(buff,"\n");
					if(strcmp(buff,".")==0)
					{
						
						break;

					}
					else
					{
					
						void* input=malloc(sizeof(char)*(strlen(buff)));
						memcpy(input,buff,strlen(buff));
						dll_append(lst, input);
						dll_move_to(lst,dll_size(lst));
						hasChanged=1;
						//printf("SIZE %d\n",dll_size(lst) );
						//showCursor(lst);
						//printList(lst);

					}



				}



			}
			
			else if(strcmp(buff, "\n")==0 || strcmp(buff,"+")==0)
			{
				if(getNext(lst)!=NULL)
				{

					dll_move_to(lst,getCursorNumber(lst) +1);



				}
				else
				{
					printf("?\n" );

				}
				

			}
			else if(strcmp(buff,"-")==0)
			{

				if(getPrevious(lst)!=NULL)
				{

					dll_move_to(lst,getCursorNumber(lst) -1);



				}



			}
			else if(strcmp(buff,"$")==0)
			{

				if(getHead(lst)==NULL)
				{

					printf("?\n");

				}
				else
				{

				dll_move_to(lst,dll_size(lst));
				showCursor(lst);
				}

			}
			//NEEDS WORKS
			else if(isdigit(buff))
			{	printf("GOT HERE\n");
				int newIndex=atoi(buff);
				if(newIndex>=1 && newIndex<=dll_size(lst))
				{

					dll_move_to(lst,newIndex);

				}



			}
			else if(strcmp(buff,".=")==0)
			{


				printf("%d\n",getCursorNumber(lst));

			}
			else if(strcmp(buff,"$=")==0)
			{

				printf("%d\n",dll_size(lst));


			}
			else if(strcmp(buff,"p")==0)
			{
				printListForward(lst);
				dll_move_to(lst,dll_size(lst));


			}
			else if(strcmp(buff,"q")==0)
			{

				if(hasChanged)
				{

					printf("? buffer dirty\n");

				}
				else
				{

					dll_destroy(lst);
					printf("\n");
					printf("Bye\n");
					break;



				}



			}
			else if(strcmp(buff,"w")==0)
			{


				printf("?\n");


			


			}
			else if(strcmp(buff,"wq")==0)
			{
					printf("?\n");





				
			}
			else if(strcmp(buff,"i")==0)
			{	
				
		
				int looping=1;
				while(looping)
				{
					fgets(buff,MAX_LINE, stdin);
					printf("%d\n",strcmp(buff,".") );
					
					if(strcmp(buff,".")==10)
					{
						break;

					}
					else
					{
						dll_insert_at(lst,getCursorNumber(lst),(void *) buff);
						dll_move_to(lst,getCursorNumber(lst));


					}
	

				}
				
				
	



			}
			else if(strcmp(buff,"d")==0)
			{
				dll_pop(lst,getCursorNumber(lst));



			}
			else 
			{
				
			}
}


	}
Esempio n. 6
0
void phase2(char* outputFileName, int numberOfFiles)
{	
	
	int bufferSize = 15000000; /* size of the input buffers*/
	char * recordStart; /* start position of the record */
	char * recordEnd;   /* end position of the record */
	recType rec;
	int index;          /* identify the run we are dealing with */
	std::string tempName = "temp";
	PhaseTwoInfo * info;
	/* initialize struct info */
	info = new PhaseTwoInfo;
	info->numberOfFiles = numberOfFiles;
	info->inputFile = new std::ifstream *[numberOfFiles];
	info->inputBufferArray = new Buffer*[numberOfFiles];
	info->parRec = new partialRecord*[numberOfFiles];
	info->currentRecord = new int[numberOfFiles];
	info->endOfBuffer = new bool[numberOfFiles];
	info->eof = new bool[numberOfFiles];
	info->outputFile = new std::ofstream;
	info->outputFile->open(outputFileName,std::ios::binary);
	if (!info->outputFile->is_open())
	{
		std::cout<<"error opening output file"<<std::endl;
		exit(-1);
	}
	info->outputBuffer = new Buffer;
	info->outputBuffer->buffer = new char[bufferSize+MAX_LENGTH];
	info->outputBuffer->bufferSize = bufferSize+MAX_LENGTH;
	info->outputBuffer->bufferLength = 0;
	info->bufferSize = bufferSize;
	

	for (int i = 0; i < numberOfFiles; i++)
	{
		//info->eof[i] = new bool;
		//info->endOfBuffer[i] = new bool;
		//info->currentRecord[i] = new int;
		info->parRec[i] = new partialRecord;
		info->parRec[i]->partial = false;
		info->inputBufferArray[i] = new Buffer;
		info->inputBufferArray[i]->buffer = new char[bufferSize];
		info->inputBufferArray[i]->bufferSize = bufferSize;
		info->inputFile[i] = new std::ifstream;
		info->inputFile[i]->open(tempName+std::to_string(i),std::ios::binary);
		info->inputFile[i]->read(info->inputBufferArray[i]->buffer, bufferSize);
		info->eof[i] = false;
		info->endOfBuffer[i] = false;
		/* initialize the RecordList*/
		recordStart = info->inputBufferArray[i]->buffer;
		recordEnd = (char*) std::memchr(recordStart,'\n', info->inputBufferArray[i]->buffer+10000-recordStart);
		rec.size = recordEnd-recordStart+1;
		rec.data = recordStart;
		info->currentRecord[i] = rec.size;
		info->recordList.push_back(rec);
	}
	/* our main loop */
	while ((index = getLeast(info)) != -1)
	{
		//std::cout<<"index "<<index<<std::endl;
		putOut(info, index);
		getNext(info,index);
	}
	/* write the records of the last buffer  to the output file */
	if (info->outputBuffer->bufferLength != 0)
	{
		info->outputFile->write(info->outputBuffer->buffer,info->outputBuffer->bufferLength);
	}
}
Esempio n. 7
0
/* Main rtgpoll */
int main(int argc, char *argv[]) {
    crew_t crew;
    pthread_t sig_thread;
    sigset_t signal_set;
    struct timeval now;
    double begin_time, end_time, sleep_time;
    char *conf_file = NULL;
    char errstr[BUFSIZE];
    int ch, i;

	dfp = stderr;

    /* Check argument count */
    if (argc < 3)
	usage(argv[0]);

	/* Set default environment */
    config_defaults(set);

    /* Parse the command-line. */
    while ((ch = getopt(argc, argv, "c:p:dhmDt:vz")) != EOF)
	switch ((char) ch) {
	case 'c':
	    conf_file = optarg;
	    break;
	case 'd':
	    set->dboff = TRUE;
	    break;
	case 'D':
	    set->daemon = FALSE;
	    break;
	case 'h':
	    usage(argv[0]);
	    break;
	case 'm':
	    set->multiple++;
	    break;
	case 'p':
	    pid_file = optarg;
	    break;
	case 't':
	    target_file = optarg;
	    break;
	case 'v':
	    set->verbose++;
	    break;
	case 'z':
	    set->withzeros = TRUE;
	    break;
	}

	debug(LOW, "RTG version %s starting.\n", VERSION);

	if (set->daemon) {
		if (daemon_init() < 0)
			fatal("Could not fork daemon!\n");
		debug(LOW, "Daemon detached\n");
	}


    /* Initialize signal handler */
    sigemptyset(&signal_set);
    sigaddset(&signal_set, SIGHUP);
    sigaddset(&signal_set, SIGUSR1);
    sigaddset(&signal_set, SIGUSR2);
    sigaddset(&signal_set, SIGTERM);
    sigaddset(&signal_set, SIGINT);
    sigaddset(&signal_set, SIGQUIT);
	if (!set->multiple) 
		checkPID(pid_file, set);

    if (pthread_sigmask(SIG_BLOCK, &signal_set, NULL) != 0)
		printf("pthread_sigmask error\n");

    /* Read configuration file to establish local environment */
    if (conf_file) {
      if ((read_rtg_config(conf_file, set)) < 0) 
		fatal("Could not read config file: %s\n", conf_file);
    } else {
      conf_file = malloc(BUFSIZE);
      if (!conf_file) 
         fatal("Fatal malloc error!\n");
      for(i=0;i<CONFIG_PATHS;i++) {
        snprintf(conf_file, BUFSIZE, "%s%s", config_paths[i], DEFAULT_CONF_FILE); 
        if (read_rtg_config(conf_file, set) >= 0)
           break;
        if (i == CONFIG_PATHS-1) {
			snprintf(conf_file, BUFSIZE, "%s%s", config_paths[0], DEFAULT_CONF_FILE); 
			if ((write_rtg_config(conf_file, set)) < 0) 
				fatal("Couldn't write config file.\n");
        }
      }
    }


    /* hash list of targets to be polled */
    init_hash();
	entries = hash_target_file(target_file);
    if (entries <= 0) 
		fatal("Error updating target list.");

	debug(LOW, "Initializing threads (%d).\n", set->threads);
    pthread_mutex_init(&(crew.mutex), NULL);
    pthread_cond_init(&(crew.done), NULL);
    pthread_cond_init(&(crew.go), NULL);
    crew.work_count = 0;

    /* Initialize the SNMP session */
	debug(LOW, "Initializing SNMP (port %d).\n", set->snmp_port);
    init_snmp("RTG");

    /* Attempt to connect to the MySQL Database */
#ifndef FEATURES
 #if HAVE_MYSQL
    if (!(set->dboff)) {
		if (mysql_dbconnect(set->dbdb, &mysql) < 0) 
			fatal("** Database error - check configuration.\n");
		if (!mysql_ping(&mysql))
			debug(LOW, "connected.\n");
		else
			fatal("server not responding.\n");
    }
 #endif
#else
 #if HAVE_MYSQL
	my_init();
 #endif
#endif


	debug(HIGH, "\nStarting threads.\n");
    for (i = 0; i < set->threads; i++) {
		crew.member[i].index = i;
		crew.member[i].crew = &crew;
		if (pthread_create(&(crew.member[i].thread), NULL, poller, (void *) &(crew.member[i])) != 0)
			printf("pthread_create error\n");
	}
    if (pthread_create(&sig_thread, NULL, sig_handler, (void *) &(signal_set)) != 0)
		printf("pthread_create error\n");

    /* give threads time to start up */
    sleep(1);

	debug(LOW, "RTG Ready.\n");

    /* Loop Forever Polling Target List */
    while (1) {
	lock = TRUE;
	gettimeofday(&now, NULL);
	begin_time = (double) now.tv_usec / 1000000 + now.tv_sec;

	PT_MUTEX_LOCK(&(crew.mutex));
	init_hash_walk();
	current = getNext();
	crew.work_count = entries;
	PT_MUTEX_UNLOCK(&(crew.mutex));
	    
	if (set->verbose >= LOW) {
		if (set->daemon)
			sysloginfo("Queue ready, broadcasting thread go condition.");
		else
        	timestamp("Queue ready, broadcasting thread go condition.");
	}
	PT_COND_BROAD(&(crew.go));
	PT_MUTEX_LOCK(&(crew.mutex));
	    
	while (crew.work_count > 0) {
		PT_COND_WAIT(&(crew.done), &(crew.mutex));
	}
	PT_MUTEX_UNLOCK(&(crew.mutex));

	gettimeofday(&now, NULL);
	lock = FALSE;
	end_time = (double) now.tv_usec / 1000000 + now.tv_sec;
	stats.poll_time = end_time - begin_time;
        stats.round++;
	sleep_time = set->interval - stats.poll_time;

	if (waiting) {
		debug(HIGH, "Processing pending SIGHUP.\n");
	    entries = hash_target_file(target_file);
	    waiting = FALSE;
	}

	if (set->verbose >= LOW) {
        snprintf(errstr, sizeof(errstr), "Poll round %d complete.", stats.round);
		if (set->daemon)
			sysloginfo(errstr);
		else
			timestamp(errstr);
	    print_stats(stats, set);
    }

	if (sleep_time <= 0)
	    stats.slow++;
	else
	    sleepy(sleep_time, set);
    } /* while */

#ifndef FEATURES
  #if HAVE_MYSQL
    /* Disconnect from the MySQL Database, exit. */
    if (!(set->dboff))
	mysql_dbdisconnect(&mysql);
  #endif
#endif
    exit(0);
}
Esempio n. 8
0
File: File.cpp Progetto: werkt/kwd
void
class_672708::virt2c( class_672708 *arg )
{
  if( getNext() ) arg->virt2c(getNext());
  setNext(arg);
}
Esempio n. 9
0
void emptyPriorityQueue()
{
	int r = getNext();
	while(r > -1)
		r = getNext();
}
Esempio n. 10
0
void GourceShell::keyPress(SDL_KeyboardEvent *e) {

    bool repeat = false;
#if SDL_VERSION_ATLEAST(2,0,0)
    repeat = (e->repeat > 0);
#endif

    //Quit demo if the user presses ESC
    if (e->type == SDL_KEYDOWN && !repeat) {

#if SDL_VERSION_ATLEAST(2,0,0)
        bool key_escape = e->keysym.sym == SDLK_ESCAPE;
        bool key_return = e->keysym.sym == SDLK_RETURN;
#else
        bool key_escape = e->keysym.unicode == SDLK_ESCAPE;
        bool key_return = e->keysym.unicode == SDLK_RETURN;
#endif

        if (key_escape) {
            quit();
        }

        if (e->keysym.sym == SDLK_F11) {
            toggleWindowFrame();
        }

        if(key_return) {

#if SDL_VERSION_ATLEAST(2,0,0)
            const Uint8* keystate = SDL_GetKeyboardState(NULL);
            if(keystate[SDL_SCANCODE_RALT] || keystate[SDL_SCANCODE_LALT]) {
#else
            Uint8* keystate = SDL_GetKeyState(NULL);
            if(keystate[SDLK_RALT] || keystate[SDLK_LALT]) {
#endif

                toggleFullscreen();

            } else {
                if(gGourceSettings.repo_count>1)
                    next = true;
            }
        }
    }

    if(gource!=0) gource->keyPress(e);
}

void GourceShell::mouseMove(SDL_MouseMotionEvent *e) {
    if(gource!=0) gource->mouseMove(e);
}

#if SDL_VERSION_ATLEAST(2,0,0)
void GourceShell::mouseWheel(SDL_MouseWheelEvent *e) {
    if(gource!=0) gource->mouseWheel(e);
}
#endif

void GourceShell::mouseClick(SDL_MouseButtonEvent *e) {
    if(gource!=0) gource->mouseClick(e);
}

void GourceShell::quit() {
    if(gource!=0) gource->quit();
    gGourceSettings.shutdown=true;
}

Gource* GourceShell::getNext() {

    if(gource!=0) {
        transition_interval = 1.0f;
    }

    if(gGourceSettings.shutdown || gource_settings == conf->getSections("gource")->end()) {

        // if we are done, delete gource and replace it with nothing
        if(gource != 0) {
            Gource* gource_tmp = gource;
                gource = 0;
            delete gource_tmp;
        }

        return 0;
    }

    gGourceSettings.importGourceSettings(*conf, *gource_settings);

    //recording a video kind of implies you want this, unless:
    // -- dont stop requested
    // -- loop requested
    // -- reading from STDIN
    if(exporter!=0 && !(gGourceSettings.dont_stop || gGourceSettings.loop || gGourceSettings.path == "-"))
        gGourceSettings.stop_at_end = true;

    //multiple repo special settings
    if(gGourceSettings.repo_count > 1) {

        //set a stop condition
        if(gGourceSettings.stop_at_time <= 0.0f && gGourceSettings.stop_position <= 0.0f) {
            gGourceSettings.stop_at_time = 60.0f;
        }
    }

    gource_settings++;

    //loop unless only 1 repo
    if(gource_settings == conf->getSections("gource")->end()) {
        if(gGourceSettings.repo_count>1 && exporter==0) {
            gource_settings = conf->getSections("gource")->begin();
        }
    }

    // replace gource

    Gource* gource_tmp = gource;
        gource = new Gource(exporter);
    delete gource_tmp;

    next = false;

    return gource;
}

void GourceShell::blendLastFrame(float dt) {
    if(transition_texture==0 || transition_interval <= 0.0f) return;

    display.mode2D();

    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);
    glEnable(GL_TEXTURE_2D);

    transition_texture->bind();

    glColor4f(1.0, 1.0, 1.0, transition_interval);

    glBegin(GL_QUADS);
        glTexCoord2f(0.0f, 1.0f);
        glVertex2f(0.0f, 0.0);

        glTexCoord2f(1.0, 1.0f);
        glVertex2f(display.width, 0.0);

        glTexCoord2f(1.0, 0.0f);
        glVertex2f(display.width, display.height);

        glTexCoord2f(0.0f, 0.0f);
        glVertex2f(0.0f, display.height);
    glEnd();

    transition_interval -= dt;
}

void GourceShell::update(float t, float dt) {

    if(gource == 0 || gource->isFinished()) {
        if(!getNext()) appFinished=true;

        return;
    }

    gource->fps = this->fps;
    gource->update(t, dt);

    if(toggle_delay > 0.0) toggle_delay -= dt;

    //copy last frame
    if( (next|| gource->isFinished()) && transition_texture!=0) {

        if(gGourceSettings.screenshot_at_end) gource->screenshot();
        glEnable(GL_TEXTURE_2D);
        transition_texture->bind();
        glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, display.width, display.height, 0);

    } else {
        //blend last frame of previous scene
        blendLastFrame(dt);
    }

    if(next) {
        delete gource;
        gource = 0;
        transition_interval = 1.0f;
        next = false;
    }
}
//------------------------------------------------------------------
//------------------------------------------------------------------
ofUniChar ofUTF8::get(const ofUTF8String& input, ofUTF8Ptr iter) {
    return getNext(iter, endPtr(input));
}
/*
 * Routine: 
 * Purpose: 
 * Algorithm:
 * Data Structures:
 *
 * Params:
 * Returns:
 * Called By: 
 * Calls: 
 * Assumptions:
 * Side Effects:
 * TODO: None
 */
int 
main(int ac, char* av[])
{
	template_t *pTemplate;

	process_options (ac, av);

	if (!is_set("QUIET"))
	{
		fprintf (stderr,
		"%s Query Generator (Version %d.%d.%d%s)\n",
		get_str("PROG"), VERSION, RELEASE, MODIFICATION, PATCH);
	fprintf (stderr, "Copyright %s %s\n", COPYRIGHT, C_DATES);
	}

	TemplateList = makeList(L_FL_TAIL, NULL);

	/* sync the keyword defines between lex/yacc/qgen */
	InitKeywords();
	
	if (is_set("YYDEBUG"))
		yydebug = 1;
	

	if (is_set("TEMPLATE"))
      parseTemplate(get_str("TEMPLATE"), 1);
	else
		parseQueries();	/* load the query templates */
	
	
	if (is_set("VERBOSE") && !is_set("QUIET"))
		fprintf(stderr, "Parsed %d templates\n", length(TemplateList));
	if (is_set("DUMP"))
	{
		for (pTemplate = (template_t *)getHead(TemplateList); pTemplate; pTemplate = (template_t *)getNext(TemplateList))
			PrintTemplate(pTemplate);
	}

	init_rand();

	generateQueryStreams();	/* output the resulting SQL */

	exit(0);

}
Esempio n. 13
0
 ValueConstraint *getFirst() {_next = _list->getFirst(); return getNext();}
Esempio n. 14
0
/**
 * /!\ Implémentation légèrement différente de l'algo décrit ci-dessous avec l'intégration du ":=" qui a nécessité d'ajouter un compteur "no_pattern_sequence" pour tolérer le fait qu'on ne rencontre aucun pattern par moment (e.g quand on reçoit ":")
 * TODO :
 *      - si caractère arrêt
 *          * si tout seul dans le buffer [buffer vide] (buffer == caractère arrêt)
 *              -> si pas espace => flux.get() && retourner le symbole
 *              -> si espace => flux.get() et continuer
 *          * si pas tout seul dans le buffer (c'est le symbole d'encore après, [opti : on pourrait le save])
 *              -> si carac_arret == espace => flux.get() et retour du buffer
 *              -> si carac_arret == pas espace => retour du buffer
 *      - si pas caractère arrêt => ajouter caractère au buffer [new_buff]
 *          * tester new_buff sur chaque regex
 *              -> si match => flux.get() mettre un flag à match et continue
 *              -> si non match
                    ** si flag à match => retourner buffer (/!\ pas new_buff)
 *                  ** si flag à non match => retourner erreur (aucun pattern trouvé)
 *
 */
Symbole* Lexer::getNext(string& buff)
{
    // on récupère les core informations
    this->getCurrentLineAndColumn(line, column);

    if (buff.empty())
    {
        return new Symbole(ID_SYMBOLE::dollar); // symbole DOLLAR / EOF
    }

    stringstream flux(buff);
    string buffer = "";
    bool match_flag = false;
    bool error = false;
    bool last_was_no_pattern = false;
    int no_pattern_sequence = 0;
    int id = -1;

    while (!flux.fail())
    {
        char character = (char)flux.peek(); // prochain caractère
        bool stoping_char = false;
        //cout << "BUFFER : " << buffer << " (next character : " << character << ") / no pattern sequence : " << no_pattern_sequence << " !" << endl; // état du buffer

        // TODO : gérer le :=

        // caractère arrêt ?
        switch (character)
        {
            case ' ':
            case ';':
            case '+':
            case '-':
            case '/':
            case '*':
            case ',':
            case '(':
            case ')':
                stoping_char = true;
            break;

            default:

            break;
        }

        if (stoping_char)
        {
            // * si tout seul dans le buffer [buffer vide] (buffer == caractère arrêt)
            if (buffer.empty())
            {
                flux.get();
                charRead++;
                // -> si espace
                if (character == ' ')
                {
                    this->getCurrentLineAndColumn(line, column);
                    continue;
                }
                // -> sinon
                buffer = character;
                break; // return buffer;
            }

            // * sinon
            // -> si espace
            if (character == ' ')
            {
                flux.get();
                charRead++;
            }
            // -> sinon
            break; // return buffer;
        }

        // - si pas caractère arrêt
        string new_buff = buffer + character;

        // test des regex
        bool matched = false;
        for (unsigned int i = 0; i < NB_REGEX; ++i)
        {
            boost::regex re(Lexer::regex[i].c_str());
            boost::cmatch matches;
            bool match = boost::regex_match(new_buff.c_str(), matches, re);
            if (match)
            {
        id = i;
                matched = true;
                break;
            }
        }

        //cout << "NEW BUFF : " << new_buff << " / matched ? " << ((matched) ? "yes" : "no") << endl;
        if (matched)
        {
            flux.get();
            charRead++;
            match_flag = true;
            buffer = new_buff;
            last_was_no_pattern = false;
            continue;
        }
        else
        {
            if (match_flag)
            {
                break; // return buffer;
            }

            // Aucun pattern trouvé, on continue pour voir si un pattern va apparaître
            if (last_was_no_pattern)
            {
                no_pattern_sequence++;
            }
            else
            {
                last_was_no_pattern = true;
                no_pattern_sequence = 1;
            }
 
            if (no_pattern_sequence >= MAX_NO_PATTERN_SEQUENCE)
            {
                error = true;
                break;
            }

            buffer = new_buff;
            flux.get();
            charRead++;
        }
    } // fin du while

    // mise à jour du buffer dans l'automate
    getline(flux, buff);

    if (error)
    {
        #ifdef DEBUG
            cout << "Erreur - aucun pattern trouvé dans les " + std::to_string(MAX_NO_PATTERN_SEQUENCE) + " derniers caractères." << endl;
        #endif
       return NULL;
    }

    Symbole* retour = NULL;

    //cout << "Valeur du symbole lu : " << buffer << "(ID : " << id << ")" << endl;

    switch(id)
    {
        case -1:
            if (buffer == ";")
            {
                retour = new Symbole(ID_SYMBOLE::pv);
            }
            else if (buffer == "+")
            {
                retour = new Symbole(ID_SYMBOLE::add); 
            }
            else if (buffer == "-")
            {
                retour = new Symbole(ID_SYMBOLE::moins);
            }
            else if (buffer == "/")
            {
                retour = new Symbole(ID_SYMBOLE::divise);
            }
            else if (buffer == "*")
            {
                retour = new Symbole(ID_SYMBOLE::fois);
            }
            else if (buffer == ",")
            {
                retour = new Symbole(ID_SYMBOLE::v);
            }
            else if (buffer == "(")
            {
                retour = new Symbole(ID_SYMBOLE::po);
            }
            else if (buffer == ")")
            {
                retour = new Symbole(ID_SYMBOLE::pf);
            }
            else
            {
                // error
                if (buffer.size() > 0)
                {
                    retour = new Unknown(buffer.at(0));
                    cerr << "Erreur lexicale (" << line << ":" << column << ") caractere " << buffer.at(0) << endl;
                    // on ignore le caractère
                    delete retour;
                    retour = getNext(buff);
                }
                else
                {
                    // error, on ignore le caractère
                    #ifdef DEBUG
                        cout << "Erreur : le buffer est vide et on est sorti de la boucle de lecture ..." << endl;
                    #endif
                    retour = getNext(buff);
                }
            }
        break;
        case 0:
            retour = new Symbole(ID_SYMBOLE::ct);
        break;
        case 1:
            retour = new Symbole(ID_SYMBOLE::va);
        break;
        case 2:
            retour = new Symbole(ID_SYMBOLE::r);
        break;
        case 3:
            retour = new Symbole(ID_SYMBOLE::w);
        break;
        case 4:
            retour = new Symbole(ID_SYMBOLE::pv);
        break;
        case 5:
            retour = new Symbole(ID_SYMBOLE::po);
        break;
        case 6:
            retour = new Symbole(ID_SYMBOLE::pf);
        break;
        case 7:
            retour = new Symbole(ID_SYMBOLE::af);
        break;
        case 8:
            retour = new Symbole(ID_SYMBOLE::eg);
        break;
        case 9:
            retour = new Symbole(ID_SYMBOLE::add);
        break;
        case 10:
            retour = new Symbole(ID_SYMBOLE::moins);
        break;
        case 11:
            retour = new Symbole(ID_SYMBOLE::fois);
        break;
        case 12:
            retour = new Symbole(ID_SYMBOLE::divise);
        break;
        case 13:
            retour = new Symbole(ID_SYMBOLE::v);
        break;
        case 14:
        {
            // convertir buffer -> int
            int num;
            istringstream iss(buffer);
            iss >> num;
            retour = new Num(num);
        }
        break;
        case 15:
        {
            retour = new Identificateur(buffer);
        }
        break;
        default:
            // error
            if (buffer.size() > 0)
            {
                retour = new Unknown(buffer.at(0));
                cerr << "Erreur lexicale (" << line << ":" << column << ") caractere " << buffer.at(0) << endl;
                // on ignore le caractère
                delete retour;
                retour = getNext(buff);
            }
            else
            {
                // error, on ignore le caractère
                #ifdef DEBUG
                    cout << "Erreur : le buffer est vide et on est sorti de la boucle de lecture ..." << endl;
                #endif
                retour = getNext(buff);
            }
        break;
    }

    //cout << " --> Lecture d'un symbole : " << *retour << endl;
    return retour;
}
Esempio n. 15
0
void
PackagedAppVerifier::OnManifestVerified(bool aSuccess)
{
  MOZ_RELEASE_ASSERT(NS_IsMainThread(), "OnManifestVerified must be on main thread.");

  LOG(("PackagedAppVerifier::OnManifestVerified: %d", aSuccess));

  // The listener could have been removed before we verify the resource.
  if (!mListener) {
    return;
  }


  if (!aSuccess && mBypassVerification) {
    aSuccess = true;
    LOG(("Developer mode! Treat junk signature valid."));
  }

  if (aSuccess && !mSignature.IsEmpty()) {
    // Get the package location from the manifest
    nsAutoCString packageOrigin;
    mPackagedAppUtils->GetPackageOrigin(packageOrigin);
    if (packageOrigin != mPackageOrigin) {
      aSuccess = false;
      LOG(("moz-package-location doesn't match:\nFrom: %s\nManifest: %s\n", mPackageOrigin.get(), packageOrigin.get()));
    }
  }

  // Only when the manifest verified and package has signature would we
  // regard this package is signed.
  mIsPackageSigned = aSuccess && !mSignature.IsEmpty();

  mState = aSuccess ? STATE_MANIFEST_VERIFIED_OK
                    : STATE_MANIFEST_VERIFIED_FAILED;

  // Obtain the package identifier from manifest if the package is signed.
  if (mIsPackageSigned) {
    mPackagedAppUtils->GetPackageIdentifier(mPackageIdentifer);
    LOG(("PackageIdentifer is: %s", mPackageIdentifer.get()));
  }

  // If the signature verification failed, doom the package cache to
  // make its subresources unavailable in the subsequent requests.
  if (!aSuccess && mPackageCacheEntry) {
    mPackageCacheEntry->AsyncDoom(nullptr);
  }

  // If the package is signed, add related info to the package cache.
  if (mIsPackageSigned && mPackageCacheEntry) {
    LOG(("This package is signed. Add this info to the cache channel."));
    if (mPackageCacheEntry) {
      mPackageCacheEntry->SetMetaDataElement(kSignedPakIdMetadataKey,
                                             mPackageIdentifer.get());
      mPackageCacheEntry = nullptr; // the cache entry is no longer needed.
    }
  }

  RefPtr<ResourceCacheInfo> info(mPendingResourceCacheInfoList.popFirst());
  MOZ_ASSERT(info);

  mListener->OnVerified(true, // aIsManifest.
                        info->mURI,
                        info->mCacheEntry,
                        info->mStatusCode,
                        info->mIsLastPart,
                        aSuccess);

  LOG(("Ready to verify resources that were cached during verification"));
  // Verify the resources which were cached during verification accordingly.
  for (auto i = mPendingResourceCacheInfoList.getFirst(); i; i = i->getNext()) {
    VerifyResource(i);
  }
}
void appendReplicationInfo(OperationContext* opCtx, BSONObjBuilder& result, int level) {
    ReplicationCoordinator* replCoord = ReplicationCoordinator::get(opCtx);
    if (replCoord->getSettings().usingReplSets()) {
        IsMasterResponse isMasterResponse;
        replCoord->fillIsMasterForReplSet(&isMasterResponse);
        result.appendElements(isMasterResponse.toBSON());
        if (level) {
            replCoord->appendSlaveInfoData(&result);
        }
        return;
    }

    result.appendBool("ismaster",
                      ReplicationCoordinator::get(opCtx)->isMasterForReportingPurposes());

    if (level) {
        BSONObjBuilder sources(result.subarrayStart("sources"));

        int n = 0;
        list<BSONObj> src;
        {
            const NamespaceString localSources{"local.sources"};
            AutoGetCollectionForReadCommand ctx(opCtx, localSources);
            auto exec = InternalPlanner::collectionScan(
                opCtx, localSources.ns(), ctx.getCollection(), PlanExecutor::NO_YIELD);
            BSONObj obj;
            PlanExecutor::ExecState state;
            while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) {
                src.push_back(obj.getOwned());
            }

            // Non-yielding collection scans from InternalPlanner will never error.
            invariant(PlanExecutor::IS_EOF == state);
        }

        for (list<BSONObj>::const_iterator i = src.begin(); i != src.end(); i++) {
            BSONObj s = *i;
            BSONObjBuilder bb;
            bb.append(s["host"]);
            string sourcename = s["source"].valuestr();
            if (sourcename != "main")
                bb.append(s["source"]);
            {
                BSONElement e = s["syncedTo"];
                BSONObjBuilder t(bb.subobjStart("syncedTo"));
                t.appendDate("time", e.timestampTime());
                t.append("inc", e.timestampInc());
                t.done();
            }

            if (level > 1) {
                invariant(!opCtx->lockState()->isLocked());
                // note: there is no so-style timeout on this connection; perhaps we should have
                // one.
                ScopedDbConnection conn(s["host"].valuestr());

                DBClientConnection* cliConn = dynamic_cast<DBClientConnection*>(&conn.conn());
                if (cliConn && replAuthenticate(cliConn)) {
                    BSONObj first = conn->findOne((string) "local.oplog.$" + sourcename,
                                                  Query().sort(BSON("$natural" << 1)));
                    BSONObj last = conn->findOne((string) "local.oplog.$" + sourcename,
                                                 Query().sort(BSON("$natural" << -1)));
                    bb.appendDate("masterFirst", first["ts"].timestampTime());
                    bb.appendDate("masterLast", last["ts"].timestampTime());
                    const auto lag = (last["ts"].timestampTime() - s["syncedTo"].timestampTime());
                    bb.append("lagSeconds", durationCount<Milliseconds>(lag) / 1000.0);
                }
                conn.done();
            }

            sources.append(BSONObjBuilder::numStr(n++), bb.obj());
        }

        sources.done();

        replCoord->appendSlaveInfoData(&result);
    }
}
//------------------------------------------------------------------
//------------------------------------------------------------------
ofUniChar ofUTF8::get(ofUTF8Ptr iter, ofUTF8Ptr end) {
    return getNext(iter,end);
}
Esempio n. 18
0
NAError * NAErrorStack::getFirst()
{
  nextEntry_ = errEntry_;
  iterEntries_ = 0;
  return getNext();
} // NAErrorStack::getFirst()
//------------------------------------------------------------------
ofUTF8Ptr ofUTF8::next(ofUTF8Ptr iter, ofUTF8Ptr end) {
    getNext(iter, end); return iter;
}
Esempio n. 20
0
    Runner::RunnerState MultiPlanRunner::getNext(BSONObj* objOut, DiskLoc* dlOut) {
        if (_killed) { return Runner::RUNNER_DEAD; }
        if (_failure) { return Runner::RUNNER_ERROR; }

        // If we haven't picked the best plan yet...
        if (NULL == _bestPlan) {
            if (!pickBestPlan(NULL)) {
                verify(_failure || _killed);
                if (_killed) { return Runner::RUNNER_DEAD; }
                if (_failure) { return Runner::RUNNER_ERROR; }
            }
        }

        // Look for an already produced result that provides the data the caller wants.
        while (!_alreadyProduced.empty()) {
            WorkingSetID id = _alreadyProduced.front();
            _alreadyProduced.pop_front();

            WorkingSetMember* member = _bestPlan->getWorkingSet()->get(id);

            // Note that this copies code from PlanExecutor.
            if (NULL != objOut) {
                if (WorkingSetMember::LOC_AND_IDX == member->state) {
                    if (1 != member->keyData.size()) {
                        _bestPlan->getWorkingSet()->free(id);
                        // If the caller needs the key data and the WSM doesn't have it, drop the
                        // result and carry on.
                        continue;
                    }
                    *objOut = member->keyData[0].keyData;
                }
                else if (member->hasObj()) {
                    *objOut = member->obj;
                }
                else {
                    // If the caller needs an object and the WSM doesn't have it, drop and
                    // try the next result.
                    _bestPlan->getWorkingSet()->free(id);
                    continue;
                }
            }

            if (NULL != dlOut) {
                if (member->hasLoc()) {
                    *dlOut = member->loc;
                }
                else {
                    // If the caller needs a DiskLoc and the WSM doesn't have it, drop and carry on.
                    _bestPlan->getWorkingSet()->free(id);
                    continue;
                }
            }

            // If we're here, the caller has all the data needed and we've set the out
            // parameters.  Remove the result from the WorkingSet.
            _bestPlan->getWorkingSet()->free(id);
            return Runner::RUNNER_ADVANCED;
        }

        RunnerState state = _bestPlan->getNext(objOut, dlOut);

        if (Runner::RUNNER_ERROR == state && (NULL != _backupSolution)) {
            QLOG() << "Best plan errored out switching to backup\n";
            // Uncache the bad solution if we fall back
            // on the backup solution.
            //
            // XXX: Instead of uncaching we should find a way for the
            // cached plan runner to fall back on a different solution
            // if the best solution fails. Alternatively we could try to
            // defer cache insertion to be after the first produced result.
            Database* db = cc().database();
            verify(NULL != db);
            Collection* collection = db->getCollection(_query->ns());
            verify(NULL != collection);
            PlanCache* cache = collection->infoCache()->getPlanCache();
            cache->remove(*_query);

            _bestPlan.reset(_backupPlan);
            _backupPlan = NULL;
            _bestSolution.reset(_backupSolution);
            _backupSolution = NULL;
            _alreadyProduced = _backupAlreadyProduced;
            return getNext(objOut, dlOut);
        }

        if (NULL != _backupSolution && Runner::RUNNER_ADVANCED == state) {
            QLOG() << "Best plan had a blocking sort, became unblocked, deleting backup plan\n";
            delete _backupSolution;
            delete _backupPlan;
            _backupSolution = NULL;
            _backupPlan = NULL;
            // TODO: free from WS?
            _backupAlreadyProduced.clear();
        }

        return state;
    }
Esempio n. 21
0
int test_chapter2(int argc, const char * argv[]) {
    auto listPrinter = [] (int x) {std::cout << x << std::endl;};
    // 2.1
    {
        std::vector<int> v({1, 2, 3, 1, 2, 3, 1});
        std::cout << "Problem 2.1, without sets:\n";
        LinkedListNode<int> * head = create_list<int>(v);
        std::cout << "Before: \n";
        enumerate<int>(head, listPrinter);
        head = remove_duplicates_no_stl<int>(head);
        std::cout << "After: \n";
        enumerate<int>(head, listPrinter);
        std::cout << "Problem 2.1, with sets:\n";
        head = create_list<int>(v);
        std::cout << "Before: \n";
        enumerate<int>(head, listPrinter);
        head = remove_duplicates<int>(head);
        std::cout << "After: \n";
        enumerate<int>(head, listPrinter);
    }
    // 2.2
    {
        std::vector<int> v({5, 4, 3, 2, 1, 0});
        LinkedListNode<int> * head = create_list<int>(v);
        auto node = find_kth_from_the_end<int>(head, 0);
        std::cout << "0th from the end: " << (node != nullptr ? node->getData() : -1) << std::endl;
        node = find_kth_from_the_end<int>(head, 1);
        std::cout << "1st from the end: " << (node != nullptr ? node->getData() : -1) << std::endl;
        node = find_kth_from_the_end<int>(head, 2);
        std::cout << "2nd from the end: " << (node != nullptr ? node->getData() : -1) << std::endl;
        node = find_kth_from_the_end<int>(head, 3);
        std::cout << "3rd from the end: " << (node != nullptr ? node->getData() : -1) << std::endl;
        node = find_kth_from_the_end<int>(head, 5);
        std::cout << "5th from the end: " << (node != nullptr ? node->getData() : -1) << std::endl;
        node = find_kth_from_the_end<int>(head, 6);
        std::cout << "6th from the end: " << (node != nullptr ? node->getData() : -1) << std::endl;
        node = find_kth_from_the_end<int>(head, 7);
        std::cout << "7th from the end: " << (node != nullptr ? node->getData() : -1) << std::endl;
    }
    // 2.3
    {
        std::cout << "Deleting node with val = 3:\n";
        std::vector<int> v({0, 1, 2, 3, 4, 5, 6});
        LinkedListNode<int> * head = create_list<int>(v);
        auto node = head;
        while (node->getData() < 3) {
            node = node->getNext();
        }
        node = delete_in_the_middle(node);
        enumerate<int>(head, listPrinter);
    }
    
    // 2.4
    {
        std::cout << "Partitioning around 4:\n";
        std::vector<int> v({0, 4, 1, 5, 2, 6, 3, 7});
        //        std::vector<int> v({4, 7});
        //        std::vector<int> v({0, 1});
        LinkedListNode<int> * head = create_list<int>(v);
        head = partition_around<int>(head, 4);
        enumerate<int>(head, listPrinter);
    }
    
    // 2.5
    {
        std::cout << "Adding the lists:\n";
        std::vector<int> v1({1, 0, 2}), v2({0, 2, 0});
        LinkedListNode<int> * l1(create_list<int>(v1)), * l2(create_list<int>(v2));
        auto inlineListPrinter = [] (int x) {std::cout << x;};
        int sum = sum_lists<int>(l1, l2);
        std::cout << "The sum of ";
        enumerate<int>(l1, inlineListPrinter);
        std::cout << " and ";
        enumerate<int>(l2, inlineListPrinter);
        std::cout << " is " << sum << std::endl;
        sum = sum_reversed_lists(l1, l2);
        std::cout << "Reversed sum: " << sum << std::endl;
    }
    {
        try {
            std::cout << "Adding the lists:\n";
            std::vector<int> v1({1, 0, 2}), v2({0, 2});
            LinkedListNode<int> * l1(create_list<int>(v1)), * l2(create_list<int>(v2));
            auto inlineListPrinter = [] (int x) {std::cout << x;};
            int sum = sum_lists<int>(l1, l2);
            std::cout << "The sum of ";
            enumerate<int>(l1, inlineListPrinter);
            std::cout << " and ";
            enumerate<int>(l2, inlineListPrinter);
            std::cout << " is " << sum << std::endl;
            sum = sum_reversed_lists(l1, l2);
            std::cout << "Reversed sum: " << sum << std::endl;
        } catch(const std::runtime_error& err) {
            std::cout << "Snafu in progress: " << err.what() << std::endl;
        }
    }
    // 2.6
    {
        std::cout << "Looking for loops:\n";
        std::vector<char> v({'a', 'b', 'c', 'd', 'e'});
        auto head = create_list(v);
        auto node = head;
        while (node->getData() != 'c') {
            node = node->getNext();
        }
        auto tail = head;
        while (tail->getNext() != nullptr) {
            tail = tail->getNext();
        }
        tail->setNext(node);
        auto looper = find_loop_start(head);
        if (looper != nullptr) {
            std::cout << "The loop: " << looper->getData() << std::endl;
        } else {
            std::cout << "Loop not found\n";
        }
        tail->setNext(nullptr);
        looper = find_loop_start(head);
        if (looper != nullptr) {
            std::cout << "The loop: " << looper->getData() << std::endl;
        } else {
            std::cout << "Loop not found\n";
        }
    }
    {
        std::vector<char> v({'a'});
        auto head = create_list(v);
        head->setNext(head);
        auto looper = find_loop_start(head);
        if (looper != nullptr) {
            std::cout << "The loop: " << looper->getData() << std::endl;
        } else {
            std::cout << "Loop not found\n";
        }
    }

    // 2.7
    {
        std::vector<char> v({'b', 'a', 'c', 'a', 'b'});
        auto head = create_list(v);
        auto inlineListPrinter = [] (char x) {std::cout << x;};
        std::cout << "Is ";
        enumerate<char>(head, inlineListPrinter);
        std::cout << " a palindrome? " << is_palindrome(head) << std::endl;
    }
    {
        std::vector<char> v({'b'});
        auto head = create_list(v);
        auto inlineListPrinter = [] (char x) {std::cout << x;};
        std::cout << "Is ";
        enumerate<char>(head, inlineListPrinter);
        std::cout << " a palindrome? " << is_palindrome(head) << std::endl;
    }
    {
        std::vector<char> v({'b', 'a', 'a', 'b'});
        auto head = create_list(v);
        auto inlineListPrinter = [] (char x) {std::cout << x;};
        std::cout << "Is ";
        enumerate<char>(head, inlineListPrinter);
        std::cout << " a palindrome? " << is_palindrome(head) << std::endl;
    }
    {
        std::vector<char> v({'b', 'a', 'c', 'a'});
        auto head = create_list(v);
        auto inlineListPrinter = [] (char x) {std::cout << x;};
        std::cout << "Is ";
        enumerate<char>(head, inlineListPrinter);
        std::cout << " a palindrome? " << is_palindrome(head) << std::endl;
    }
    {
        std::vector<char> v({'b', 'a', 'c', 'a', 'c'});
        auto head = create_list(v);
        auto inlineListPrinter = [] (char x) {std::cout << x;};
        std::cout << "Is ";
        enumerate<char>(head, inlineListPrinter);
        std::cout << " a palindrome? " << is_palindrome(head) << std::endl;
    }

    return 0;
}
Esempio n. 22
0
int main() {
	int i;
	time_t total_time = 0;
	time_t time_on_curr_cycle = 0;
	process_t pid_arr[NUM_PROCESS];
	process_t *proc = NULL;
	
	//Initialize random values to proceses and print their info
	pid_arr[0].pid = 1;
	pid_arr[0].burst = 6;
	pid_arr[0].slice = 2;
	pid_arr[0].execTime = 0;
	addToProcessQueue(&pid_arr[0]);
	
	pid_arr[1].pid = 2;
	pid_arr[1].burst = 3;
	pid_arr[1].slice = 2;
	pid_arr[1].execTime = 0;
	addToProcessQueue(&pid_arr[1]);

	pid_arr[2].pid = 3;
	pid_arr[2].burst = 5;
	pid_arr[2].slice = 2;
	pid_arr[2].execTime = 0;
	addToProcessQueue(&pid_arr[2]);

	printf("Processes info:\n");	
	for(i = 0; i < NUM_PROCESS; i++) {
		printf("PID            : %d\n", pid_arr[i].pid);
		printf("   Burst time  : %d\n", pid_arr[i].burst);
		printf("   Slice time  : %d\n", pid_arr[i].slice);
	}
	printf("############################################\n");		
	printf("Time: %d, CPU State: Idle\n", total_time);
	
	proc = getFirst();
	while(proc) {
		//round-robin through process until all processes are executed
		while(proc->execTime < proc->burst && time_on_curr_cycle < proc->slice) {
			total_time++;
			time_on_curr_cycle++;
			proc->execTime++;
			printf("Time: %d, CPU State: Processing pid: %d\n", total_time, proc->pid);
		}

		time_on_curr_cycle = 0;
		if(proc->execTime == proc->burst) {
			//process completed, remove from pending list
			process_t *del = proc;
			if(!isOnlyProcess(proc)) {
				proc = getNext(proc);
			} else {
				proc = NULL;
			}
			delFromProcessQueue(del);
		} else {
			proc = getNext(proc);
		}
	}	
	
	printf("CPU State: All process complete\n");
}
Esempio n. 23
0
HRESULT TimgFilterResize::process(TfilterQueue::iterator it,TffPict &pict,const TfilterSettingsVideo *cfg0)
{
    const TresizeAspectSettings *cfg=(const TresizeAspectSettings*)cfg0;
    init(pict,cfg->full,0);
    int swsflags = 0;
    if (sizeChanged || !cfg->equal(oldSettings) || oldSettings.is!=cfg->is || oldSettings.full!=cfg->full || oldcsp != pict.csp) {
        sizeChanged=false;
        oldSettings=*cfg;
        oldcsp=pict.csp;
        done();
        inited=false;
        newpict.rectFull=pict.rectFull;
        newpict.rectClip=pict.rectClip;
        newpict.csp=pict.csp;
        getOutputFmt(newpict,cfg);
        enum TffdshowDecVideo::DOWNSTREAM_FILTER_TYPE downstream=(TffdshowDecVideo::DOWNSTREAM_FILTER_TYPE)deciV->get_downstreamID();
        char_t outputfourcc[20];
        deciV->getOutputFourcc(outputfourcc,20);

        if ((pict.rectClip!=newpict.rectClip || pict.rectFull!=newpict.rectFull)
                &&!(   pict.cspInfo.id==FF_CSP_420P       // I want to avoid resizing here. YV12 odd number lines.
                       && pict.rectFull==newpict.rectFull
                       && newpict.rectClip.dy==(pict.rectClip.dy&~1)
                       && newpict.rectClip.dx==pict.rectClip.dx
                       && newpict.rectClip.x==pict.rectClip.x
                       && newpict.rectClip.y==pict.rectClip.y
                   )) {
            switch (TresizeAspectSettings::methodsProps[oldSettings.methodLuma].library) {
                case TresizeAspectSettings::LIB_SWSCALER:
                    Tlibavcodec::swsInitParams(swsparams,TresizeAspectSettings::methodsProps[oldSettings.methodLuma].flags);
                    switch (oldSettings.methodLuma) {
                        case TresizeAspectSettings::METHOD_SWS_BICUBIC:
                            swsparams->methodLuma.param[0]=(double)oldSettings.bicubicLumaParam/100;
                            break;
                        case TresizeAspectSettings::METHOD_SWS_GAUSS:
                            swsparams->methodLuma.param[0]=(double)oldSettings.gaussLumaParam/10;
                            break;
                        case TresizeAspectSettings::METHOD_SWS_LANCZOS:
                            swsparams->methodLuma.param[0]=(double)oldSettings.lanczosLumaParam;
                            break;
                    }
                    if (oldSettings.methodsLocked) {
                        swsparams->methodChroma=swsparams->methodLuma;
                    } else {
                        swsparams->methodChroma.method=TresizeAspectSettings::methodsProps[oldSettings.methodChroma].flags;
                        switch (oldSettings.methodChroma) {
                            case TresizeAspectSettings::METHOD_SWS_BICUBIC:
                                swsparams->methodChroma.param[0]=(double)oldSettings.bicubicChromaParam/100;
                                break;
                            case TresizeAspectSettings::METHOD_SWS_GAUSS:
                                swsparams->methodChroma.param[0]=(double)oldSettings.gaussChromaParam/10;
                                break;
                            case TresizeAspectSettings::METHOD_SWS_LANCZOS:
                                swsparams->methodChroma.param[0]=(double)oldSettings.lanczosChromaParam;
                                break;
                        }
                    }
                    break;
                case TresizeAspectSettings::LIB_NONE:
                    if (pictRect.dy<newpict.rectClip.dy) {
                        dynone=pictRect.dy;
                        ydif1none=(newpict.rectClip.dy-pictRect.dy)/2;
                        ydif2none=0;
                    } else {
                        dynone=newpict.rectClip.dy;
                        ydif1none=0;
                        ydif2none=(pictRect.dy-newpict.rectClip.dy)/2;
                    }
                    if (pictRect.dx<newpict.rectClip.dx) {
                        dxnone=pictRect.dx;
                        xdif1none=(newpict.rectClip.dx-pictRect.dx)/2;
                        xdif2none=0;
                    } else {
                        dxnone=newpict.rectClip.dx;
                        xdif1none=0;
                        xdif2none=(pictRect.dx-newpict.rectClip.dx)/2;
                    }
                    break;
            }
            parent->dirtyBorder=1;
            inited=true;
        }
    }

    if (inited) {
        parent->adhocDVDsub(it, pict); // draw DVD subtitles and menu before resize, if it is not done.

        bool interlace;
        switch (cfg->interlaced) {
            case 0 :
                interlace=false;
                break;
            case 1 :
                interlace=true;
                break;
            case 2 :
                interlace=pict.fieldtype&FIELD_TYPE::MASK_INT?true:false;
                break;
            default:
                interlace=false;
                break;
        }
        switch (TresizeAspectSettings::methodsProps[oldSettings.methodLuma].library) {
            case TresizeAspectSettings::LIB_SWSCALER: {
                if (pict.rectFull.dx!=pict.rectClip.dx) {
                    parent->dirtyBorder=1;
                }
                bool cspChanged=false;
                const unsigned char *src[4];
                cspChanged|=getCur(SWS_IN_CSPS,pict,cfg->full,src);
                unsigned char *dst[4];
                cspChanged|=getNext(SWS_OUT_CSPS,pict,newpict.rectClip,dst,&newpict.rectFull);
                if (cspChanged || !swsc || oldinterlace!=interlace) {
                    if (!libavcodec) {
                        deci->getLibavcodec(&libavcodec);
                    }
                    if (swsc) {
                        libavcodec->sws_freeContext(swsc);
                    }
                    swsc=NULL;
                    if (swsf) {
                        libavcodec->sws_freeFilter(swsf);
                    }
                    swsf=NULL;
                    oldinterlace=interlace;
                    if(cfg->accurateRounding) {
                        swsflags|=SWS_ACCURATE_RND;
                    }

                    // Add the CPU flags and others (SWS_ACCURATE_RND if set) to the chroma & luma flags
                    SwsParams mixedparams;
                    memcpy(&mixedparams, swsparams, sizeof(SwsParams));
                    mixedparams.methodChroma.method|=swsflags;
                    mixedparams.methodLuma.method|=swsflags;

                    swsf=libavcodec->sws_getDefaultFilter(oldSettings.GblurLum/100.0f,oldSettings.GblurChrom/100.0f,oldSettings.sharpenLum/100.0f,oldSettings.sharpenChrom/100.0f,0,0,0);
                    if (!oldinterlace) {
                        swsc=libavcodec->sws_getCachedContext(NULL,pictRect.dx,pictRect.dy,csp_ffdshow2lavc(csp1),newpict.rectClip.dx,newpict.rectClip.dy,csp_ffdshow2lavc(csp2),swsflags,swsf,NULL,NULL,&mixedparams);
                    } else {
                        swsc=libavcodec->sws_getCachedContext(NULL,pictRect.dx,pictRect.dy/2,csp_ffdshow2lavc(csp1),newpict.rectClip.dx,newpict.rectClip.dy/2,csp_ffdshow2lavc(csp2),swsflags,swsf,NULL,NULL,&mixedparams);
                    }
                }
                if (!oldinterlace) {
                    libavcodec->sws_scale(swsc,src,stride1,0,pictRect.dy,dst,stride2);
                } else {
                    stride_t stride1I[]= {stride1[0]*2,stride1[1]*2,stride1[2]*2,stride1[3]*2};
                    stride_t stride2I[]= {stride2[0]*2,stride2[1]*2,stride2[2]*2,stride2[3]*2};
                    libavcodec->sws_scale(swsc,src,stride1I,0,pictRect.dy/2,dst,stride2I);
                    for (unsigned int i=0; i<pict.cspInfo.numPlanes; i++) {
                        src[i]+=stride1[i];
                        dst[i]+=stride2[i];
                    }
                    libavcodec->sws_scale(swsc,src,stride1I,0,pictRect.dy/2,dst,stride2I);
                }
                break;
            }
            case TresizeAspectSettings::LIB_NONE: {
                const unsigned char *src[4];
                getCur(pict.csp,pict,cfg->full,src);
                unsigned char *dst[4];
                getNext(pict.csp,pict,newpict.rectClip,dst,&newpict.rectFull);
                for (unsigned int i=0; i<pict.cspInfo.numPlanes; i++) {
                    const unsigned char *src0=src[i]+(ydif2none>>pict.cspInfo.shiftY[i])*stride1[i]+pict.cspInfo.Bpp*(xdif2none>>pict.cspInfo.shiftX[i]);
                    unsigned char       *dst0=dst[i]+(ydif1none>>pict.cspInfo.shiftY[i])*stride2[i]+pict.cspInfo.Bpp*(xdif1none>>pict.cspInfo.shiftX[i]);
                    TffPict::copy(dst0,stride2[i],src0,stride1[i],pict.cspInfo.Bpp*(dxnone>>pict.cspInfo.shiftX[i]),dynone>>pict.cspInfo.shiftY[i]);
                }
                break;
            }
            case TresizeAspectSettings::LIB_SIMPLE: {
                bool warped=oldSettings.methodLuma==TresizeAspectSettings::METHOD_WARPED;
                if (!simple || oldinterlace!=interlace || oldWarped!=warped) {
                    oldinterlace=interlace;
                    oldWarped=warped;
                    SimpleResize::VideoInfo vi;
                    vi.width=pictRect.dx;
                    vi.height=pictRect.dy/(oldinterlace?2:1);
                    vi.IsYV12=!warped;
                    vi.IsYUY2=!vi.IsYV12;
                    simple=new SimpleResize(vi,newpict.rectClip.dx,newpict.rectClip.dy/(oldinterlace?2:1),warped?cfg->simpleWarpXparam/1000.0:1.0,warped?cfg->simpleWarpYparam/1000.0:1.0,false);
                }
                if (simple->ok) {
                    SimpleResize::PVideoFrame srcFrame;
                    getCur(warped?FF_CSP_YUY2:FF_CSP_420P,pict,cfg->full,(const unsigned char**)srcFrame.ptr);
                    for (unsigned int i=0; i<pict.cspInfo.numPlanes; i++) {
                        srcFrame.pitch[i]=stride1[i];
                        srcFrame.rowSize[i]=dx1[i]*pict.cspInfo.Bpp;
                        srcFrame.height[i]=dy1[i];
                    }
                    SimpleResize::PVideoFrame dstFrame;
                    getNext(warped?FF_CSP_YUY2:FF_CSP_420P,pict,newpict.rectClip,dstFrame.ptr,&newpict.rectFull);
                    for (unsigned int i=0; i<pict.cspInfo.numPlanes; i++) {
                        dstFrame.pitch[i]=stride2[i];
                        dstFrame.rowSize[i]=(newpict.rectClip.dx*pict.cspInfo.Bpp)>>pict.cspInfo.shiftX[i];
                        dstFrame.height[i]=newpict.rectClip.dy>>pict.cspInfo.shiftY[i];
                    }
                    if (!oldinterlace) {
                        simple->GetFrame(&srcFrame,&dstFrame);
                    } else {
                        for (unsigned int i=0; i<pict.cspInfo.numPlanes; i++) {
                            srcFrame.height[i]/=2;
                            srcFrame.pitch[i]*=2;
                            dstFrame.height[i]/=2;
                            dstFrame.pitch[i]*=2;
                        }
                        simple->GetFrame(&srcFrame,&dstFrame);
                        for (unsigned int i=0; i<pict.cspInfo.numPlanes; i++) {
                            srcFrame.ptr[i]+=stride1[i];
                            dstFrame.ptr[i]+=stride2[i];
                        }
                        simple->GetFrame(&srcFrame,&dstFrame);
                    }
                }
                break;
            }
            case TresizeAspectSettings::LIB_SAI:
                switch (TresizeAspectSettings::methodsProps[oldSettings.methodLuma].flags) {
                    case 0: {
                        const unsigned char *src;
                        getCur(FF_CSP_RGB32,pict,cfg->full,&src,NULL,NULL,NULL);
                        unsigned char *dst;
                        getNext(FF_CSP_RGB32,pict,newpict.rectClip,&dst,NULL,NULL,NULL,&newpict.rectFull);
                        T2xSaI::super(src,stride1[0],dst,stride2[0],dx1[0],dy1[0]);
                        break;
                    }
                    case 1: {
                        const unsigned char *src;
                        getCur(FF_CSP_RGB16,pict,cfg->full,&src,NULL,NULL,NULL);
                        unsigned char *dst;
                        getNext(FF_CSP_RGB16,pict,newpict.rectClip,&dst,NULL,NULL,NULL,&newpict.rectFull);
                        T2xSaI::_2xSaI(src,stride1[0],dst,dx1[0],dy1[0],stride2[0]);
                        break;
                    }
                    case 2: {
                        const unsigned char *src;
                        getCur(FF_CSP_RGB16,pict,cfg->full,&src,NULL,NULL,NULL);
                        unsigned char *dst;
                        getNext(FF_CSP_RGB32,pict,newpict.rectClip,&dst,NULL,NULL,NULL,&newpict.rectFull);
                        Thq2x::hq2x_32(src,dst,dx1[0],dy1[0],stride1[0],stride2[0]);
                        break;
                    }
                }
                break;
        }
        if (!parent->dirtyBorder) {
            parent->dirtyBorder=1;
        }
    }
Esempio n. 24
0
File: mm.c Progetto: bkashyap/ece454
/**********************************************************
 * coalesce
 * Covers the 4 cases discussed in the text:
 * - both neighbours are allocated
 * - the next block is available for coalescing
 * - the previous block is available for coalescing
 * - both neighbours are available for coalescing
 **********************************************************/
void *coalesce(void *bp)
{
#if DEBUG >= 3
    printf("coalesce c\n");
#endif

    size_t prev_alloc = GET_ALLOC(FTRP(PREV_BLKP(bp)));
    size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
    size_t size = GET_SIZE(HDRP(bp));


    void * prev;
    void * next; 
    void * fp;


/* free list setup*/
    if (prev_alloc && next_alloc) {       /* Case 1 */
        printf(" case 1 a|self|a\n");

        if (flhead == NULL) {
            flhead = bp;
            fltail = bp;
            printf(" flhead set to bp %p\n",bp);
            getPrev(bp) = NULL;
            getNext(bp) = NULL;

        }
        else {   
            printf(" moved to top of list.. bp %p\n",bp);
            getPrev(flhead) = bp;
            getNext(bp) = flhead;
            flhead = bp;
        }
        getPrev(bp) = NULL;
        return bp;
    }

    else if (prev_alloc && !next_alloc) { /* Case 2 */

        printf(" case 2 a|self|free\n");

        //printf("step0 base case\n");

        size += GET_SIZE(HDRP(NEXT_BLKP(bp)));
        

        if (flhead == NEXT_BLKP(bp)){
            prev = getPrev(flhead);
            next = getNext(flhead);
            getNext(bp) = next;
            getPrev(bp) = prev;
            return flhead;
        }

        //step 1: connect prev and next
        //printf("step1\n");
        fp = NEXT_BLKP(bp);
        prev = getPrev(fp);
        next = getNext(fp);

        
        if (prev != NULL){
            getNext(prev) = next;
        }
        if (next != NULL){
            getPrev(next) = prev;
        }


        //step 2: put in front
        //printf("step2\n");
        PUT(HDRP(bp), PACK(size, 0));
        PUT(FTRP(bp), PACK(size, 0));

        getNext(bp) = flhead;
        getPrev(flhead) = bp;
        flhead = bp;
        getPrev(flhead) = NULL;
        return (bp);
    }

    else if (!prev_alloc && next_alloc) { /* Case 3: a free block on the left*/
        printf("case 3 free|self|a for %p\n", bp);
        //print_heap();

        /*
        //implicit
        size += GET_SIZE(HDRP(PREV_BLKP(bp)));
        PUT(FTRP(bp), PACK(size, 0));
        PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0));
        return (PREV_BLKP(bp));
        */
        //printf("step0 base case\n");

        /* free list */
        //printf(" size before %zu\n",size);
        //printf(" foot address %p\n", ((char *)(bp) - DSIZE));
        //printf(" footer size %zu\n", GET_SIZE(((char *)(bp) - DSIZE)) );
        //printf(" adding size %zu\n", GET_SIZE(HDRP(PREV_BLKP(bp))));
        //printf(" the pointer is at %p\n", PREV_BLKP(bp));
        size += GET_SIZE(HDRP(PREV_BLKP(bp)));
        //printf(" size after %zu\n",size);


        PUT(FTRP(bp), PACK(size, 0));
        PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0));
        

        // base case: at fhead there
        if (flhead == PREV_BLKP(bp)) {
            return flhead; 
        }

        // step 1: connect prev and next
        //printf("step1..\n");
        prev = getPrev(PREV_BLKP(bp));
        next = getNext(PREV_BLKP(bp));


        if (prev != NULL) {
            getNext(prev) = next;
        }

        if (next != NULL){
            getPrev(next) = prev;
        }   

        // step 2: put newly free block at the front of the list
        //printf("step2..\n");
        fp = PREV_BLKP(bp);
        getNext(fp) = flhead;
        getPrev(flhead) = fp;
        flhead = fp;
        getPrev(flhead) = NULL;

        //printf("done!\n");
        return (PREV_BLKP(bp));


    }

    else {            /* Case 4 */ 
        /*
        printf("case4 free|self|free\n");
        size += GET_SIZE(HDRP(PREV_BLKP(bp)))  +
            GET_SIZE(FTRP(NEXT_BLKP(bp)))  ;
        PUT(HDRP(PREV_BLKP(bp)), PACK(size,0));
        PUT(FTRP(NEXT_BLKP(bp)), PACK(size,0));


        return (PREV_BLKP(bp));
        */

        printf(" case4/1 a|self|a\n");

        if (flhead == NULL) {
            flhead = bp;
            fltail = bp;
            printf(" flhead set to bp %p\n",bp);
            getPrev(bp) = NULL;
            getNext(bp) = NULL;

        }
        else {   
            printf(" moved to top of list.. bp %p\n",bp);
            getPrev(flhead) = bp;
            getNext(bp) = flhead;
            flhead = bp;
            getPrev(flhead) = NULL;
        }
        getPrev(bp) = NULL;
        return bp;
    }



}
Esempio n. 25
0
StatusWith<int> CollectionRangeDeleter::_doDeletion(OperationContext* opCtx,
                                                    Collection* collection,
                                                    BSONObj const& keyPattern,
                                                    ChunkRange const& range,
                                                    int maxToDelete) {
    invariant(collection != nullptr);
    invariant(!isEmpty());

    auto const& nss = collection->ns();

    // The IndexChunk has a keyPattern that may apply to more than one index - we need to
    // select the index and get the full index keyPattern here.
    auto catalog = collection->getIndexCatalog();
    const IndexDescriptor* idx = catalog->findShardKeyPrefixedIndex(opCtx, keyPattern, false);
    if (!idx) {
        std::string msg = str::stream() << "Unable to find shard key index for "
                                        << keyPattern.toString() << " in " << nss.ns();
        LOG(0) << msg;
        return {ErrorCodes::InternalError, msg};
    }

    // Extend bounds to match the index we found
    const KeyPattern indexKeyPattern(idx->keyPattern());
    const auto extend = [&](const auto& key) {
        return Helpers::toKeyFormat(indexKeyPattern.extendRangeBound(key, false));
    };

    const auto min = extend(range.getMin());
    const auto max = extend(range.getMax());

    LOG(1) << "begin removal of " << min << " to " << max << " in " << nss.ns();

    const auto indexName = idx->indexName();
    const IndexDescriptor* descriptor =
        collection->getIndexCatalog()->findIndexByName(opCtx, indexName);
    if (!descriptor) {
        std::string msg = str::stream() << "shard key index with name " << indexName << " on '"
                                        << nss.ns() << "' was dropped";
        LOG(0) << msg;
        return {ErrorCodes::InternalError, msg};
    }

    auto deleteStageParams = std::make_unique<DeleteStageParams>();
    deleteStageParams->fromMigrate = true;
    deleteStageParams->isMulti = true;
    deleteStageParams->returnDeleted = true;

    if (serverGlobalParams.moveParanoia) {
        deleteStageParams->removeSaver =
            std::make_unique<RemoveSaver>("moveChunk", nss.ns(), "cleaning");
    }

    auto exec = InternalPlanner::deleteWithIndexScan(opCtx,
                                                     collection,
                                                     std::move(deleteStageParams),
                                                     descriptor,
                                                     min,
                                                     max,
                                                     BoundInclusion::kIncludeStartKeyOnly,
                                                     PlanExecutor::YIELD_MANUAL,
                                                     InternalPlanner::FORWARD);

    PlanYieldPolicy planYieldPolicy(exec.get(), PlanExecutor::YIELD_MANUAL);

    int numDeleted = 0;
    do {
        BSONObj deletedObj;
        PlanExecutor::ExecState state = exec->getNext(&deletedObj, nullptr);

        if (state == PlanExecutor::IS_EOF) {
            break;
        }

        if (state == PlanExecutor::FAILURE) {
            warning() << PlanExecutor::statestr(state) << " - cursor error while trying to delete "
                      << redact(min) << " to " << redact(max) << " in " << nss
                      << ": FAILURE, stats: " << Explain::getWinningPlanStats(exec.get());
            break;
        }

        invariant(PlanExecutor::ADVANCED == state);
        ShardingStatistics::get(opCtx).countDocsDeletedOnDonor.addAndFetch(1);

    } while (++numDeleted < maxToDelete);

    return numDeleted;
}
Esempio n. 26
0
fp_Container * fp_EndnoteContainer::getNextContainerInSection() const
{
	return static_cast<fp_Container *>(getNext());
}
 void connect(TreeLinkNode *root) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     if (!root) return;
     getNext(NULL, root);
 }
Esempio n. 28
0
	void startLookingforInput(DlList_T lst,const char * filename)
	{
		int hasChanged=0;
		int looping=1;
		char buff[MAX_LINE];
		while(looping)
 		{
 			fgets(buff,MAX_LINE, stdin);
 			strtok(buff,"\n");
			if(strcmp(buff,"Q")==0)
			{

				dll_destroy(lst);
				break;



			}
			else if(strcmp(buff,".")==0)
			{
				showCursor(lst);

			}

			else if(strcmp(buff,"a")==0)
			{

				int currentlooping=1;
				while(currentlooping)
				{
					fgets(buff,MAX_LINE, stdin);
					strtok(buff,"\n");
					if(strcmp(buff,".")==0)
					{
						
						break;

					}
					else
					{
					
						void* input=malloc(sizeof(char)*(strlen(buff)));
						memcpy(input,buff,strlen(buff));
						dll_append(lst, input);
						dll_move_to(lst,dll_size(lst));
						hasChanged=1;
						//printf("SIZE %d\n",dll_size(lst) );
						//showCursor(lst);
						//printList(lst);

					}



				}



			}
			
			else if(strcmp(buff, "\n")==0 || strcmp(buff,"+")==0)
			{
				if(getNext(lst)!=NULL)
				{

					dll_move_to(lst,getCursorNumber(lst) +1);



				}
				else
				{
					printf("?\n" );

				}
				

			}
			else if(strcmp(buff,"-")==0)
			{

				if(getPrevious(lst)!=NULL)
				{

					dll_move_to(lst,getCursorNumber(lst) -1);



				}



			}
			else if(strcmp(buff,"$")==0)
			{

				if(getHead(lst)==NULL)
				{

					printf("?\n");

				}
				else
				{

				dll_move_to(lst,dll_size(lst));
				showCursor(lst);
				}

			}
			//NEEDS WORKS
			else if(isdigit(buff))
			{	printf("GOT HERE\n");
				int newIndex=atoi(buff);
				if(newIndex>=1 && newIndex<=dll_size(lst))
				{

					dll_move_to(lst,newIndex);

				}



			}
			else if(strcmp(buff,".=")==0)
			{


				printf("%d\n",getCursorNumber(lst));

			}
			else if(strcmp(buff,"$=")==0)
			{

				printf("%d\n",dll_size(lst));


			}
			else if(strcmp(buff,"p")==0)
			{
				printListForward(lst);
				dll_move_to(lst,dll_size(lst));


			}
			else if(strcmp(buff,"q")==0)
			{

				if(hasChanged)
				{

					printf("? buffer dirty\n");

				}
				else
				{

					dll_destroy(lst);
					printf("\n");
					printf("Bye\n");
					break;



				}



			}
			else if(strcmp(buff,"w")==0)
			{


				FILE* pFile = fopen(filename, "w");
				if (!pFile) {
					perror("The following error occurred:");
				} else {
					struct node* headNode=getHead(lst);

					while(headNode!=NULL)
					{
						
						fprintf(pFile, strcat((char *) (getData(headNode)),"\n"));
						headNode=nextNode(headNode);
					
					
					}
					printf("%s:file\n",filename );
					hasChanged=0;
					fclose(pFile);


			}


			}
			else if(strcmp(buff,"wq")==0)
			{
				FILE* pFile = fopen(filename, "w");
				if (!pFile) {
					perror("The following error occurred:");
				} 
				else {
					struct node* headNode=getHead(lst);

					while(headNode!=NULL)
					{
						
						printf("%s\n", (char *) (getData(headNode)) );
						fprintf(pFile, strcat((char *) (getData(headNode)),"\n"));
						headNode=nextNode(headNode);
					
					
					}
					printf("%s:file\n",filename );
					hasChanged=0;
					fclose(pFile);
					dll_destroy(lst);
					printf("\n");
					printf("Bye\n");
					break;





				}
			}
			else if(strcmp(buff,"i")==0)
			{	
				
		
				int looping=1;
				while(looping)
				{
					fgets(buff,MAX_LINE, stdin);
					printf("%d\n",strcmp(buff,".") );
					
					if(strcmp(buff,".")==10)
					{
						break;

					}
					else
					{
						dll_insert_at(lst,getCursorNumber(lst),(void *) buff);
						dll_move_to(lst,getCursorNumber(lst));


					}
	

				}
				
				
	



			}
			else if(strcmp(buff,"d")==0)
			{
				printf("HITIN\n");
				dll_pop(lst,getCursorNumber(lst));



			}
			else 
			{
				
			}
}
}
Esempio n. 29
0
//平台从第1回合开始调用此函数获得每回合指令,请勿修改此函数声明。
extern "C" Order makeOrder(DataForAI data)
{
	//printf("===================round%d tank%d==================\n",data.round,data.myID);
	Order order;
	order.type=STOP;
	mydata=data;
	updateResource(data);
	if(data.round==1&&data.myID==0)
	{
		assignResource(data);
		//getNext(data);
	}

	short range=data.tank[data.myID].range;
	//printf("range:%d\n",range);
	short vision=range;
	Point me;
	me.row=data.tank[data.myID].row;
	me.col=data.tank[data.myID].col;
	for(int i=-vision;i<=vision;i++)
	{
		for(int j=-vision;j<=vision;j++)
		{
			if(abs(i)+abs(j)<=vision)//in vision
			{
				short nr=me.row+i,nc=me.col+j;
				Point target;
				target.row=nr;
				target.col=nc;
				if(isInMap(nr,nc))//in map
					if(data.map[nr][nc].whoIsHere!=-1)//tank detected
					{
						short n=data.map[nr][nc].whoIsHere;
						if(data.tank[n].flag!=data.myFlag)
						{
							//printf("enemy tank%d\n",n);
							order.row=nr;
							order.col=nc;
							order.type=FIRE;
							return order;
						}

					}
					else if((data.map[nr][nc].type==BREAKBRICK||data.map[nr][nc].type==BRICK)&&isObstacle(target,nextStep[data.myID]))//bricks detected
					{
						//printf("tank%dbricks\n",data.myID);
						order.row=nr;
						order.col=nc;
						order.type=FIRE;
						return order;

					}
			}
		}
	}

	//

	//printf("the nearest point for tank%d (%d,%d)\n",data.myID,nearestS[data.myID].row,nearestS[data.myID].col);
	//assert(nearestS[data.myID].row>0);
	if(data.tank[data.myID].life!=0)
	{
		clock_t tstart,tend;
		float timeuse;
		tstart=clock();

		if(data.map[nearestS[data.myID].row][nearestS[data.myID].col].isHereSource==RedSource||data.map[data.tank[data.myID].row][data.tank[data.myID].col].isHereSource==RedSource||nextStep[data.myID].empty())
		{
			getNearestRS(data);
		}
		getNext(data);
		tend=clock();
		timeuse=(tend-tstart)/CLOCKS_PER_SEC;
		//printf("round%d tank%dchange resource(%d,%d) and next step:(%d,%d),%f seconds used\n",data.round,data.myID,nearestS[data.myID].row,nearestS[data.myID].col,next[data.myID].row,next[data.myID].col,timeuse);
	};

	/*
	if(data.map[next[data.myID].row][next[data.myID].col].whoIsHere!=-1||next[data.myID].row==-1)
	{
	while(1)
	{
	srand((int)time(0));
	short i=rand()%4;
	short nr=data.tank[data.myID].row+dir[i][0],nc=data.tank[data.myID].col+dir[i][1];
	if(data.map[nr][nc].type==PERVIOUS&&data.map[nr][nc].whoIsHere!=-1)
	{
	next[data.myID].row=nr;
	next[data.myID].col=nc;
	break;
	}
	}
	}
	*/
	short x=next[data.myID].row-data.tank[data.myID].row,y=next[data.myID].col-data.tank[data.myID].col;
	//printf("(x,y) for tank%d\n",x,y,data.myID);
	/*if(x<0)x=-1;
	else if(x>0)x=1;
	if(y<0)y=-1;
	else if(y>0)y=1;*/
	for(int i=0;i<4;i++)
	{
		if(dir[i][0]==x&&dir[i][1]==y)
		{

			order.type=direction[i];
			//printf("tank%d is going %s\n",data.myID,ds[i]);
			return order;
		}
		else
		{	
			order.type=STOP;
		}
		//random step
		/*
		else
		{
		srand((int)time(0));
		order.type=direction[rand()%4];
		return order;

		}*/
	}
	return order;
}
Esempio n. 30
-1
static bool runStatement(ASTNode* node, MemoryStack* stack, Scope* scope, RuntimeError* error)
{
    switch (node->nodeType)
    {
        case AST_STATEMENT_TYPE_DEFINITION:
        {
            if (getTypeDefinition(scope, node->typeDefinition.identifier, false))
            {
                *error = RuntimeError{
                    RET_TYPE_ALREADY_DEFINED,
                    node->typeDefinition.identifier,
                    node->typeDefinition.lineNumber
                };

                return false;
            }
            else
            {
                TypeDefinition* typeDef = scopePushToList(scope, stack, &scope->types);
                typeDef->identifier = node->typeDefinition.identifier;
                typeDef->members = {};

                ListIterator<ASTNode> iterator = makeIterator(&node->typeDefinition.definitions);

                int currOffsetInBytes = 0;
                while (hasNext(&iterator))
                {
                    ASTNode* node = getNext(&iterator);

                    StructMember* member = scopePushToList(scope, stack, &typeDef->members);
                    member->identifier = node->variableDeclaration.identifier;
                    member->type = makeType(scope, node->variableDeclaration.typeIdentifier);
                    member->offsetInBytes = currOffsetInBytes;

                    currOffsetInBytes += member->type.definition->totalSizeInBytes;
                }

                typeDef->totalSizeInBytes = currOffsetInBytes;
                return true;
            }
        } break;

        case AST_STATEMENT_VARIABLE_DECLARATION:
        {
            if (getVariable(scope, node->variableDeclaration.identifier, false))
            {
                *error = RuntimeError{ RET_VARIABLE_ALREADY_DEFINED, node->variableDeclaration.identifier, node->variableDeclaration.lineNumber };
                return false;
            }
            else
            {
                Variable* var = defineAVariable(
                    node->variableDeclaration.identifier,
                    makeType(scope, node->variableDeclaration.typeIdentifier), stack, scope);

                if (node->variableDeclaration.expression)
                    return runExpression(node->variableDeclaration.expression, stack, scope, error, &var->value);
                else
                    return true; // TODO: set default value
            }
        } break;

        case AST_STATEMENT_FUNCTION_DEFINITION:
        {
            Function func;

            func.type = FT_INTERNAL;
            func.identifier.name = node->functionDefinition.identifier;
            func.identifier.arguments = {};

            bool stillWorking = true;
            if (!node->functionDefinition.returnType)
                func.returnType = Type{ nullptr, 0 };
            else
            {
                func.returnType = makeType(scope, node->functionDefinition.returnType);
                if (!func.returnType.definition)
                {
                    *error = RuntimeError{ RET_UNDEFINED_TYPE, node->functionDefinition.returnType->typeIdentifier.name, node->functionDefinition.lineNumber };
                    stillWorking = false;
                }
            }

            ListIterator<ASTNode> args = makeIterator(&node->functionDefinition.arguments);
            while (stillWorking && hasNext(&args))
            {
                ASTNode* arg = getNext(&args);

                Argument* argument = scopePushToList(scope, stack, &func.identifier.arguments);
                argument->identifier = arg->variableDeclaration.identifier;
                argument->type = makeType(scope, arg->variableDeclaration.typeIdentifier);

                if (!argument->type.definition)
                {
                    *error = RuntimeError{ RET_UNDEFINED_TYPE, arg->variableDeclaration.typeIdentifier->typeIdentifier.name, arg->variableDeclaration.lineNumber };
                    stillWorking = false;
                }
            }

            func.body = node->functionDefinition.body;

            Function* hasFunc = getFunction(scope, func.identifier, false);
            if (hasFunc)
            {
                *error = RuntimeError{ RET_FUNCTION_ALREADY_DEFINED, node->functionDefinition.identifier, node->functionDefinition.lineNumber };
                stillWorking = false;
            }
            else
            {
                *scopePushToList(scope, stack, &scope->functions) = func;
            }

            return stillWorking;
        } break;

        case AST_STATEMENT_IF:
        {
            Scope ifScope = makeScope(scope);
            Value conditionResult = pushValue(&ifScope, stack, Type{ getTypeDefinition(scope, makeSlice("s32")), false });

            bool stillWorking = runExpression(node->ifStatement.condition, stack, scope, error, &conditionResult);

            if (stillWorking)
            {
                if (*(int*)conditionResult.memory != 0)
                {
                    stillWorking = runStatement(node->ifStatement.ifCase, stack, &ifScope, error);
                }
                else if (node->ifStatement.elseCase != nullptr)
                {
                    stillWorking = runStatement(node->ifStatement.elseCase, stack, &ifScope, error);
                }
            }

            scopeFreeMemory(&ifScope, stack);
            return stillWorking;
        } break;

        case AST_STATEMENT_WHILE:
        {
            Scope whileScope = makeScope(scope);
            Value conditionResult = pushValue(&whileScope, stack, Type{ getTypeDefinition(scope, makeSlice("s32")), false });

            bool stillWorking = runExpression(node->whileStatement.condition, stack, scope, error, &conditionResult);
            if (stillWorking)
            {
                while (*(int*)conditionResult.memory != 0)
                {
                    if (!(stillWorking = runStatement(node->whileStatement.body, stack, &whileScope, error))) break;
                    if (!(stillWorking = runExpression(node->whileStatement.condition, stack, scope, error, &conditionResult))) break;
                }
            }

            scopeFreeMemory(&whileScope, stack);
            return stillWorking;
        } break;

        case AST_STATEMENT_ASSIGNMENT:
        {
            Value value; 
            if (getValue(scope, node->assignment.lValue, error, &value))
            {
                return runExpression(node->assignment.expression, stack, scope, error, &value);
            }
            else
                return false;
        } break;

        case AST_STATEMENTS_BLOCK:
        {
            Scope blockScope = makeScope(scope);
            bool result = runStatements(&node->statementsBlock.statements, stack, &blockScope, error);
            scopeFreeMemory(&blockScope, stack);

            return result;
        } break;

        case AST_FUNCTION_CALL:
        {
            return runFunctionCall(node, stack, scope, error, nullptr);
        } break;

        default:
        {
            assert(!"this is not a statement!");
            return false;
        } break;
    }
}