Exemple #1
0
int main(void) {
    int x;
    Stack myStack = NULL;

    for(x = 0; x < 4; x++) {
        StackPush(&myStack, x);
    }
   
    print_stack(&myStack);
    while(myStack != NULL) {
        printf("data: %d\n", StackPop(&myStack));
    }
    return 0;
}
Exemple #2
0
int GetResult(ElementType* suffix,int len)//由后缀表达式计算出值
{
	int i = 0;
	char sign = '\0';
	int val1 = 0;
	int val2 = 0;
	int res = 0;
	ElementType temp;
	StackNode* head;
	StackNode* top;
	temp.sign = '\0';
	InitStack(&head, &top);
	for (i = 0; i < len; ++i)
	{
		if (suffix[i].sign == '\0')
		{
			StackPush(head, &top, suffix[i]);
		}
		else
		{
			sign = suffix[i].sign;
			val1 = StackPop(head, &top).num;
			val2 = StackPop(head, &top).num;
			switch (sign)
			{
				case '+':temp.num = val2 + val1; break;
				case '-':temp.num = val2 - val1; break;
				case '*':temp.num = val2 * val1; break;
				case '/':temp.num = val2 / val1; break;
			}
			StackPush(head,&top,temp);
		}
	}
	res = StackPop(head, &top).num;
	return res;
}
void InverseOperator::Reshape(Ifpack_Preconditioner* prec, const Operator& Op, 
                              const bool ownership)
{
  ResetTimer();
  StackPush();

  Op_ = Op;

  RCPRowMatrix_ = Op.GetRCPRowMatrix();

  RCPData_ = Teuchos::rcp(prec,ownership);

  StackPop();
  UpdateTime();
}
Exemple #4
0
static void CheckBrackets(Stack *s, char c) {
  Element top_element;
  switch (c) {
    case '(':
    case '[':
    case '{':
      top_element.c = c;
      top_element.line = line;
      top_element.col = col;
      StackPush(s, &top_element);
      break;
    case ')':
      StackPop(s, &top_element);
      if (top_element.c != '(') {
        printf("line %d, col %d: error: miss match for %c character.\n",
               line, col, c);
      }
      break;
    case ']':
      StackPop(s, &top_element);
      if (top_element.c != '[') {
        printf("line %d, col %d: error: miss match for %c character.\n",
               line, col, c);
      }
      break;
    case '}':
      StackPop(s, &top_element);
      if (top_element.c != '{') {
        printf("line %d, col %d: error: miss match for %c character.\n",
               line, col, c);
      }
      break;
    default:
      break;
  }
}
Exemple #5
0
int main(int argc, const char * argv[])
{
    // insert code here...
    int temp = 0;
    printf("Hello, World!\n");
    
    STACK *pStack = StackInit();
    
    StackPush(pStack, 1);
    StackPush(pStack, 2);
    StackPush(pStack, 3);
    
    StackPop(pStack, &temp);
    printf("%d \n",temp);
    StackPop(pStack, &temp);
    printf("%d \n",temp);

    
    
    
    
    
    return 0;
}
bool DwarfOp<AddressType>::op_deref_size() {
  AddressType bytes_to_read = OperandAt(0);
  if (bytes_to_read > sizeof(AddressType) || bytes_to_read == 0) {
    last_error_.code = DWARF_ERROR_ILLEGAL_VALUE;
    return false;
  }
  // Read the address and dereference it.
  AddressType addr = StackPop();
  AddressType value = 0;
  if (!regular_memory()->ReadFully(addr, &value, bytes_to_read)) {
    last_error_.code = DWARF_ERROR_MEMORY_INVALID;
    last_error_.address = addr;
    return false;
  }
  stack_.push_front(value);
  return true;
}
Exemple #7
0
void StopAllProc(pstack_t **head, struct SyncMethod *type) {
	HANDLE hEvent;
	int size;
	hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, "Event");
	if (hEvent == NULL) {
		exit(EXIT_FAILURE);
	}
	WaitForSingleObject(hEvent, INFINITE);
	while ((size = StackSize(head)) != 0) {
		TerminateProcess((*head)->process.procInfo.hProcess, 0);
		CloseHandle((*head)->process.procInfo.hThread);
		CloseHandle((*head)->process.procInfo.hProcess);
		type->process_count--;
		StackPop(head);
	}
	CloseHandle(hEvent);
	return;
}
Exemple #8
0
void StopProc(pstack_t **head, struct SyncMethod *type) {
	HANDLE hEvent;
	hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, "Event");
	if (hEvent == NULL) {
		StackClear(head);
		exit(EXIT_FAILURE);
	} else {
		WaitForSingleObject(hEvent, INFINITE);
		TerminateProcess((*head)->process.procInfo.hProcess, 0);
		CloseHandle((*head)->process.procInfo.hThread);
		CloseHandle((*head)->process.procInfo.hProcess);
		StackPop(head);
		type->process_count--;
		SetEvent(hEvent);
	}
	CloseHandle(hEvent);
	return;
}
void LoadBalanceInverseOperator::Reshape(Ifpack_Preconditioner* prec, 
                                         const LoadBalanceOperator& Op, 
                                         const bool ownership)
{
  ResetTimer();
  StackPush();

  Op_ = Op;

  if (GetParticipation()) RCPRowMatrix_ = Op.GetRCPRowMatrix();
  else                    RCPRowMatrix_ = Teuchos::null;

  if (GetParticipation()) RCPData_ = Teuchos::rcp(prec,ownership);
  else                    RCPData_ = Teuchos::null;

  StackPop();
  UpdateTime();
}
int 
InverseOperator::Apply(const MultiVector& x, MultiVector& y) const
{
  ResetTimer();
  StackPush();

  if (GetDomainSpace() != x.GetVectorSpace())
    ML_THROW("DomainSpace and x.GetVectorSpace() differ", -1);

  if (GetRangeSpace() != y.GetVectorSpace())
    ML_THROW("RangeSpace and y.GetVectorSpace() differ", -1);

  int x_nv = x.GetNumVectors();
  int y_nv = y.GetNumVectors();
  double FL = 0.0;
  if (RCPData_ != Teuchos::null)
    FL = RCPData_->ComputeFlops();

  if (x_nv != y_nv)
    ML_THROW("Number of vectors of x and y differ (" +
             GetString(x_nv) + " vs. " + GetString(x_nv), -1);

  for (int v = 0 ; v < x_nv ; ++v) {

    Epetra_Vector x_Epetra(View,RowMatrix()->OperatorDomainMap(),
                           (double*)&(x(0,v)));
    Epetra_Vector y_Epetra(View,RowMatrix()->OperatorRangeMap(),
                           (double*)&(y(0,v)));

    if (RCPData_ != Teuchos::null)
      RCPData_->ApplyInverse(x_Epetra,y_Epetra);
    else if (RCPMLPrec_ != Teuchos::null)
      RCPMLPrec_->ApplyInverse(x_Epetra,y_Epetra);
    else
      ML_THROW("Neither Ifpack nor ML smoother is properly set up", -1);
  }

  StackPop();
  if (RCPData_ != Teuchos::null)
    UpdateFlops(RCPData_->ComputeFlops() - FL);
  UpdateTime();

  return(0);
}
Exemple #11
0
int main(void)
{
  Stack s;
  
  if(StackAlloc(&s, 100) == -1){
    puts("すたっくの確保に失敗しました。");
    return (1);
  }
  
  while(1){
    int m, x;
    
    printf("現在のでーた数:%d/%d\n", StackNo(&s), StackSize(&s));
    printf("(1)ぷっしゅ (2)ぽっぷ (0)終了 :");
    scanf("%d", &m);

    if(m == 0){
      break;
    }

    switch (m){
    case 1:
      printf("でーた:");
      scanf("%d", &x);
      if(StackPush(&s, x) == -1){
	puts("すたっくへのぷっしゅに失敗しました。");
      }
      break;
    case 2:
      if(StackPop(&s, &x) == -1){
	puts("ぽっぷできません。");
      }else{
	printf("ぽっぷしたでーたは%dです。\n", x);
      }
      break;
    }
  }

  StackFree(&s);

  return (0);
}
int main(void){

  int a[]={10,20,30,40,50,60};
  int array_size = sizeof(a)/sizeof(a[0]);
  int element_size = sizeof(int);
  int i;
  Stack stackInt;
 
  StackNew(&stackInt,element_size);
  for(i=0;i<array_size;i++){
    StackPush(&stackInt,&a[i]);
  }
  int value; 
  while(!StackEmpty(&stackInt)){
    StackPop(&stackInt, &value);
    printf("Popped Value: %d\n",value);
  }

  StackDispose(&stackInt);
  return 0;
}
Exemple #13
0
int main()
{
	const char *friends[] = {"xx", "jj", "kk"};
	Stack stringStack;
	StackNew(&stringStack, sizeof(char*), freeFn);

	int i;
	for(i = 0; i < 3; ++i) {
		char *copy = strdup(friends[i]);
		StackPush(&stringStack, &copy);
	}

	char *name;
	for(i = 0; i < 3; ++i) {
		StackPop(&stringStack, &name);
		printf("%s\n", name);
		free(name);
	}

	StackDispose(&stringStack);
	return 0;
}
// ======================================================================
MultiVector Redistribute(const MultiVector& y, const int NumEquations)
{
  StackPush();

  if (y.GetMyLength() % NumEquations)
    ML_THROW("NumEquations does not divide MyLength()", -1);

  if (y.GetNumVectors() != 1)
    ML_THROW("Redistribute() works with single vectors only", -1);

  Space NewSpace(y.GetMyLength() / NumEquations);

  MultiVector y2(NewSpace, NumEquations);

  for (int i = 0 ; i < y2.GetMyLength() ; ++i)
    for (int j = 0 ; j < NumEquations ; ++j)
      y2(i, j) = y(j + NumEquations * i);

  StackPop();

  return(y2);
}
Exemple #15
0
void ABPPreOrderRep (PtABPNode proot)  /* travessia em pré-ordem repetitiva - repetitive pre-order traversal */
{
	PtABPNode Node = proot; PtStack Stack;

	if (proot == NULL) { Error = ABP_EMPTY; return;	} /* arvore vazia - empty tree */
	if ((Stack = StackCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return; }

	StackPush (Stack, &Node);	/* armazenar a raiz - storing the root */
	while (!StackIsEmpty (Stack))	/* enquanto existirem nos - while there are nodes */
	{
		StackPop (Stack, &Node);	/* recuperar o no - retrieve the node */
		printf ("%d ", Node->Elem);	/* imprimir o elemento - printing the element */

				/* colocar a raiz da subarvore direita, caso exista - storing the right subtree root if it exists */
		if (Node->PtRight != NULL) StackPush (Stack, &Node->PtRight);

				/* colocar a raiz da subarvore esquerda, caso exista - storing the left subtree root if it exists */
		if (Node->PtLeft != NULL) StackPush (Stack, &Node->PtLeft);
	}

	StackDestroy (&Stack);	/* destruir a pilha - releasing the stack */
    Error = OK;
}
std::ostream& LoadBalanceInverseOperator::Print(std::ostream& os, const bool verbose) const
{

  StackPush();

  if (GetMyPID() == 0) {
    os << "***MLAPI::InverseOperator" << std::endl;
    os << "Label             = " << GetLabel() << std::endl;
    os << "Number of rows    = " << GetRangeSpace().GetNumGlobalElements() << std::endl;
    os << "Number of columns = " << GetRangeSpace().GetNumGlobalElements() << std::endl;
    os << "Flop count        = " << GetFlops() << std::endl;
    os << "Cumulative time   = " << GetTime() << std::endl;
    if (GetTime() != 0.0)
      os << "MFlops rate       = " << 1.0e-6 * GetFlops() / GetTime() << std::endl;
    else
      os << "MFlops rate       = 0.0" << std::endl;
    os << std::endl;
  }

  StackPop();

  return(os);

}
Exemple #17
0
int main(void)
{
    int i;
    char *cadenas[] = {"hola", "mundo", "caca"};
    char *p;

    Stack test;
    StackNew(&test, sizeof(char *), dispose_string);

    for(i=0; i<3; i++)
    {
        p = strdup(cadenas[i]);
        StackPush(&test, &p);
    }

    for(i=0; i<3; i++)
    {
        StackPop(&test, &p);
        printf("%s ", p);
    }

    printf("\nComplete");
    return 0;
}
Exemple #18
0
int main(int argc, char* argv[], char** envp)
{

	int i = 0;
	int count = 20;
	char *s1 = "abcdefg";
	char *s2 = "g";
	size_t len1 = 0;
	size_t n = 3;
	char dest[20];

	node_t *node1 = NULL;
	node_t *node2 = NULL;
	node_t *node3 = NULL;
	node_t *node4 = NULL;
	node_t *node5 = NULL;
	
	char *t = NULL;	
	
	stack_t *stack = NULL;
	size_t n1 = 1;
	size_t n2 = 2;
	size_t n3 = 3;
	size_t n4 = 4;
	size_t n5 = 5;
	
	/*__________  RecFibonacci  __________*/
	printf("\n[%s %s %d]RecFibonacci\n", __FILE__, __func__, __LINE__);
	
	for (i = 0; i < count; ++i)
	{
		printf("RecFibonacci(%i):%i\n", i , RecFibonacci(i));
	}
	
	/*__________  RecStrlen  __________*/
	printf("\n[%s %s %d]RecStrlen\n", __FILE__, __func__, __LINE__);
	
	len1 = RecStrlen(s1);
	printf("len1:%lu\n", len1);
	
	/*__________  RecStrcmp  __________*/
	printf("\n[%s %s %d]RecStrcmp\n", __FILE__, __func__, __LINE__);
	
	printf("RecStrcmp(s1, s2): %i\n", RecStrcmp(s1, s2));
	
	
	/*__________  RecStrncmp  __________*/
	printf("\n[%s %s %d]RecStrncmp\n", __FILE__, __func__, __LINE__);
	
	printf("RecStrncmp(s1, s2, n): %i\n", RecStrncmp(s1, s2, n));


	/*__________  RecStrstr  __________*/
	printf("\n[%s %s %d]RecStrstr\n", __FILE__, __func__, __LINE__);
	
	printf("RecStrstr(s1, s2):%s\n", RecStrstr(s1, s2));
	
	/*__________  RecStrcpy  __________*/
	printf("\n[%s %s %d]RecStrcpy\n", __FILE__, __func__, __LINE__);
	t = RecStrcpy(dest, s1);
	printf("RecStrcpy(dest, s1):%s		expected result:%s\n", t, dest);
	
	
	/*__________  RecStrcat  __________*/
	printf("\n[%s %s %d]RecStrcat\n", __FILE__, __func__, __LINE__);
	
	printf("RecStrcat(dest, s1):%s		expected result:%s\n", 
			RecStrcat(dest, s1), 						"abcgefgabcdefg");
	
	/*__________  RecSlistFlip  __________*/
	printf("\n[%s %s %d]RecSListFlip\n", __FILE__, __func__, __LINE__);
	
	node5 = SListCreateNode((void*)5, NULL);
	node4 = SListCreateNode((void*)4, node5);
	node3 = SListCreateNode((void*)3, node4);
	node2 = SListCreateNode((void*)2, node3);
	node1 = SListCreateNode((void*)1, node2);
	
	printf("SListCount(node1):%lu\n", SListCount(node1));
	
	RecSListFlip(node1);
	
	printf("SListCount(node1):%lu\n", SListCount(node5));
	
	SListFreeAll(node5);
	
	/*__________  Compere  __________*/
	printf("\n[%s %s %d]Compere\n", __FILE__, __func__, __LINE__);
	
	printf("Compere(&n1, &n2):%i		expected result:1\n", Compere(&n1, &n2));
	
	printf("Compere(&n1, &n1):%i		expected result:1\n", Compere(&n1, &n2));
	
	printf("Compere(&n2, &n1):%i		expected result:0\n", Compere(&n2, &n1));
	/*_________________________  END Compere _______________________*/
	
	
	/*________________________________________________________________*/
	printf("\n[%s %s %d]RecStackSort\n", __FILE__, __func__, __LINE__);
	/*_________________________  RecStackSort  _______________________*/
	
	stack = StackCreate(sizeof(size_t), 5);
	assert(stack);
	
	StackPush(stack, &n3);
	StackPush(stack, &n2);
	StackPush(stack, &n5);
	StackPush(stack, &n4);
	StackPush(stack, &n1);

	RecStackSort(stack, &Compere, sizeof(size_t));
	
	for( ; StackSize(stack); StackPop(stack))
	{
		printf("StackPeek(stack):%lu\n", *(size_t*)StackPeek(stack));
	}
	
	StackDestroy(stack);	
	
	
	return(0);
}
Exemple #19
0
void PopBank()
{
  StackPop(bank_stack);
  REFRESH_BANK;
}
Exemple #20
0
/** @brief This function gives the tree functionality
	@param panel the panel handle of the panel on which the button is used
	@param control the control on which the event is generated
	@param event the type of event generated (i.e. left-click causes EVENT_COMMIT)
	@param *callbackData stores the data returned to the UI handled internally by LabWindows
	@param eventData1 stores ancillary information such as the mouse x-position within the panel
	@param eventData2 stores ancillary information such as the mouse y-position within the panel
	@return 1 or 0 specifies whether or not the event should be swallowed. 0 is default-no and 1 is yes-swallow.

### EXTERNAL VARIABLES
    - extern int @ref panelHandle - "OpenPET.c"
	- extern int @ref panelHandle_fmmode_mb - "OpenPET.c"
	- extern int @ref panelHandle_fmmode_duc - "OpenPET.c"
	- extern int @ref panelHandle_fmmode - "OpenPET.c" 
	- extern Stack @ref panel_stack - "UI_Common.c"
	- extern OpenPETTree @ref current_location - "UI_Common.c"

### ABNORMAL TERMINATION CONDITIONS, ERROR AND WARNING MESSAGES
	Errors may be generated by CVI/LabWindows. The LabWindows documentation is available online 
	at <a href="linkURL"> http://zone.ni.com/reference/en-XX/help/370051V-01/ </a>.
	
###	ALGORITHM
	The tree item double-clicked on is given as an index in eventData2. The tag is extracted (i.e. MB0DUC1DB2).
	This tag is parsed to specify the new desired location. The new panel is displayed and the stack is
	updated to allow the desired functionality in the back button.
	
###	DEVELOPMENT HISTORY
       Date    |  Author         |  Email Address     | Ver. |Description Of Change  
	   --------|-----------------|--------------------|------|---------------------
	 08/09/2013| George Netscher | [email protected] | 1.0  |conclusion of summer work
	 
### Copyright (c) 2013 by LBNL. All Rights Reserved.
*/
int CVICALLBACK FloodMapModeTree (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	char item_tag[32];
	OpenPETTree new_location;
	int i, idx=0, current_boards[3]={-1,-1,-1};
	
	switch (event)
	{
		case EVENT_COMMIT:

			// eventData2 contains index of tree item double-clicked
			GetTreeItemTag(panel, control, eventData2, item_tag);
			
			// update current_location so panel will initialize properly
			OpenPETTreeInit(&new_location);   // set to (-1, -1, -1, "NULL")
			new_location.mode = current_location.mode;
			
			for(i=0; i<32; i++)
			{
				// walk through tag string and pull out board numbers
				if( isdigit(item_tag[i]) )
				{
					current_boards[idx++] = (int)(item_tag[i] - '0');
				}
			}
			new_location.MB = current_boards[0];
			new_location.DUC = current_boards[1];
			new_location.DB = current_boards[2];
			
			// clear panel stack up to root panel 
			while( StackPeek(&panel_stack) != panelHandle )
			{
				StackPop(&panel_stack);	
			}
			
			// determine proper panel to display
			/*
			if(new_location.DB != -1) 
			{
				StackPush(&panel_stack, panelHandle_fmmode_mb); 
				StackPush(&panel_stack, panelHandle_fmmode_duc); 
				
				HidePanel (panel);				
				DisplayPanel (panelHandle_fmmode);
				
			}
			*/
			if (new_location.DUC != -1)
			{
				HidePanel(panel);				
				StackPush(&panel_stack, panelHandle_fmmode_mb); 
				StackPush(&panel_stack, panelHandle_fmmode_duc); 
				DisplayPanel(panelHandle_fmmode);
			}
			else if (new_location.MB != -1)
			{
				HidePanel(panel);
				StackPush(&panel_stack, panelHandle_fmmode_mb); 
				DisplayPanel(panelHandle_fmmode_duc);
			}
			else if (new_location.MB == -1)
			{
				HidePanel(panel);
				DisplayPanel(panelHandle_fmmode_mb);
			}
			else {
				HidePanel(panel); 
				DisplayPanel(StackPop(&panel_stack));
			}
			
			current_location.MB = new_location.MB;
			current_location.DUC = new_location.DUC;
			current_location.DB = new_location.DB;
			break;
	}
	return 0;
}
Exemple #21
0
/** @brief This function gives the tree functionality
	@param panel the panel handle of the panel on which the button is used
	@param control the control on which the event is generated
	@param event the type of event generated (i.e. left-click causes EVENT_COMMIT)
	@param *callbackData stores the data returned to the UI handled internally by LabWindows
	@param eventData1 stores ancillary information such as the mouse x-position within the panel
	@param eventData2 stores ancillary information such as the mouse y-position within the panel
	@return 1 or 0 specifies whether or not the event should be swallowed. 0 is default-no and 1 is yes-swallow.

### EXTERNAL VARIABLES
    - extern int @ref panelHandle - "OpenPET.c"
	- extern int @ref panelHandle_timemode_mb - "OpenPET.c"
	- extern int @ref panelHandle_timemode_duc - "OpenPET.c"
	- extern int @ref panelHandle_timemode_db - "OpenPET.c"
	- extern int @ref panelHandle_timemode - "OpenPET.c" 
	- extern Stack @ref panel_stack - "UI_Common.c"
	- extern OpenPETTree @ref current_location - "UI_Common.c"

### ABNORMAL TERMINATION CONDITIONS, ERROR AND WARNING MESSAGES
	Errors may be generated by CVI/LabWindows. The LabWindows documentation is available online 
	at <a href="linkURL"> http://zone.ni.com/reference/en-XX/help/370051V-01/ </a>.
	
###	ALGORITHM
	The tree item double-clicked on is given as an index in eventData2. The tag is extracted (i.e. MB0DUC1DB2).
	This tag is parsed to specify the new desired location. The new panel is displayed and the stack is
	updated to allow the desired functionality in the back button.
	
###	DEVELOPMENT HISTORY
       Date    |  Author         |  Email Address     | Ver. |Description Of Change  
	   --------|-----------------|--------------------|------|---------------------
	 08/09/2013| George Netscher | [email protected] | 1.0  |conclusion of summer work
	 
### Copyright (c) 2013 by LBNL. All Rights Reserved.
*/
int CVICALLBACK TimeModeDBTree (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	char item_tag[32];
	OpenPETTree new_location;
	int i, idx, current_boards[3]={-1,-1,-1};
	
	switch (event)
	{
		case EVENT_COMMIT:
			// eventData2 contains index of tree item double-clicked
			GetTreeItemTag(panel, control, eventData2, item_tag);
			
			// update current_location so panel will initialize properly
			OpenPETTreeInit(&new_location);   // set to (-1, -1, -1, "NULL")
			new_location.mode = current_location.mode;
			
			if(system_size == 1)
				// large system -> fill in MB, DUC, and DB board locations
				idx = 0;
			else if(system_size == 2)
				// medium system -> fill in DUC and DB board locations
				idx = 1;
			else if(system_size == 3)
				// small system -> only fill in DB board location
				idx = 2;
			for(i=0; i<32; i++)
			{
				// walk through tag string and pull out board numbers
				if( isdigit(item_tag[i]) )
				{
					current_boards[idx++] = (int)(item_tag[i] - '0');
				}
			}
			new_location.MB = current_boards[0];
			new_location.DUC = current_boards[1];
			new_location.DB = current_boards[2];
			
			// clear panel stack up to root panel 
			while( StackPeek(&panel_stack) != panelHandle )
			{
				StackPop(&panel_stack);	
			}
			
			// determine proper panel to display
			if(new_location.DB != -1) 
			{
				if(system_size == 1)
					// large size
					StackPush(&panel_stack, panelHandle_timemode_mb); 
				if(system_size == 1 || system_size == 2)
					// large or medium size
					StackPush(&panel_stack, panelHandle_timemode_duc);
				
				StackPush(&panel_stack, panelHandle_timemode_db);
				
				HidePanel (panel);				
				DisplayPanel (panelHandle_timemode);
				
			}
			else if (new_location.DUC != -1)
			{
				// in small size, this will never be reached because DUC always equals -1
				if(system_size == 1)
					// large size
					StackPush(&panel_stack, panelHandle_timemode_mb); 
				if(system_size == 1 || system_size == 2)
					// large or medium size
					StackPush(&panel_stack, panelHandle_timemode_duc); 
				
				HidePanel(panel);
				DisplayPanel(panelHandle_timemode_db);
			}
			else if (new_location.MB != -1)
			{
				// in small or medium size, this will never be reached because MB always equals -1
				if(system_size == 1)
					// large size
					StackPush(&panel_stack, panelHandle_timemode_mb);
				
				HidePanel(panel);  
				DisplayPanel(panelHandle_timemode_duc);
			}
			else 
			{
				// only large system should reach here
				HidePanel(panel);
				DisplayPanel(panelHandle_timemode_mb);
			}
			
			current_location.MB = new_location.MB;
			current_location.DUC = new_location.DUC;
			current_location.DB = new_location.DB;
			
			break;
	}
	return 0;
}
//prints x by x view of the tree
//assumes the grid starts from 0, 0; if there are entries less
//than that, it will be ignored, possibly to yield weird results
void print_tree(circ_tree *c_tree, int x, unsigned int print_mode) {
  rb_red_blk_tree *tree = c_tree->main_tree;
  static int static_x = 0;
  static circ_tree_node query_node_low, query_node_high;
  static char *line, *header_line;
  if (static_x != x) {
    if (line != NULL)
      free(line);
    if (header_line != NULL)
      free(header_line);

    static_x = x;
    query_node_low.pos = 0; //start node
    query_node_high.pos = x;
    int size = sizeof(char) * (x + 3);
    line = (char *) malloc(size);
    header_line = (char *) malloc(size);

    header_line[0] = ' ';
    header_line[1] = ' ';
    int i;
    for (i = 0; i < x; i++)
      header_line[2 + i] = '0' + (i % 10);
    header_line[x + 2] = '\0';

  }
  line[1] = ' ';
  memset(line + 2, print_mode == PRINT_CELLS ? '0' : ' ', x);  //initial line is all zeros
  line[x + 2] = '\0';  //null char at the end 
  stk_stack *stack = RBEnumerate(tree, &query_node_low, &query_node_high);
  int line_n = 0;
  puts(header_line);

  int cont_print = 1;

  while (cont_print) {

    int node_pos;
    rb_red_blk_tree *node_tree;    
    if (cont_print = StackNotEmpty(stack)) {
      circ_tree_node *node = ((rb_red_blk_node *) StackPop(stack))->key;
      node_pos = node->pos;
      node_tree = node->data.tree;
    } else {
      node_pos = x;
      node_tree = c_tree->y_bound_tree;
    }

    for (; line_n < node_pos; line_n++) {  
      //print the lines until this point / rest of the lines
      line[0] = '0' + (line_n % 10);
      puts(line);
    }

    //set the new line
    stk_stack *stack2 = RBEnumerate(node_tree, &query_node_low, &query_node_high);
    char c = print_mode == PRINT_CELLS ? '0' : ' ';
    int row_n = 0;
    while (StackNotEmpty(stack2)) {
      circ_tree_node *node2 = ((rb_red_blk_node *) StackPop(stack2))->key;
      for (; row_n < node2->pos; row_n++)  //print the chars until this point
	line[row_n + 2] = c;
      if (print_mode == PRINT_CELLS)
	c = '0' + node2->data.state;
      else
	line[row_n++ + 2] = '0' + node2->data.state;
    }

    if (print_mode == PRINT_NODES && row_n == 0)
      line[1] = '0';


    for (; row_n < x; row_n++)  //print the rest of the chars
      line[row_n + 2] = c;
    free(stack2);

    if (print_mode == PRINT_NODES || !cont_print) {
      if (cont_print)
	line[0] = '0' + (line_n++ % 10);
      else 
	line[0] = '>';  //print a different indicator for the boundary tree
      puts(line);
      memset(line + 1, ' ', x + 1);
    }
  }
  
  free(stack);
}
int main()
{
	int i,r;
	printf("Testing Queue\n");
	Queue* queue = CreateQueue();

	printf("Inserting values\n");
	for(i = 0; i < 5 ; i++)
	{	
		printf("%d\n",i);
		int result = QueueEnqueue(queue, i);
		if(result == 0)
		{
			printf("%d\n",i);
		}
		else
		{
			printf("Error in enqueuing queue\n");
		}
	}

	printf("Removing values\n");
	for(i = 0; i < 5 ; i++)
	{
		int result =QueueDequeue(queue, &r);
		if(result == 0)
		{
			printf("%d\n",r);
		}
		else
		{
			printf("Error in dequeuing queue\n");
		}
	}

	DeleteQueue(queue);

	printf("\nTesting Stack\n");

	Stack* stack = CreateStack();
	for(i = 0; i < 5 ; i++)
	{
		int result = StackPush(stack, i);
		if(result == 0)
		{
			printf("%d\n",i);
		}
		else
		{
			printf("Error in pushing to stack");
		}
	}

	for(i = 0; i < 5 ; i++)
	{
		int result = StackPop(stack, &r);
		if(result == 0)
		{
			printf("%d\n",r);
		}
		else
		{
			printf("Error in popping values");
		}
	}
	
	DeleteStack(stack); 
	return 0;
}
// strongly connected components
// function takes graph, current node, index array, lowlink array, stack and 
// boolean for nodes in stack
void SCC(Graph* mygraph, int u, int index[], int lowlink[], stackT stack, 
                                                                int inStack[])
{   
    // assign current stack to global stack variable
    stackGl = stack;
    counter = counter + 1;
    index[u] = lowlink[u] = counter;
    
    // add current node to stack
    StackPush(&stackGl, u);
    
    // change current node to true 
    inStack[u] = 1;
    
    // create adjacency list
    // it is outlist of current node
    List* adj = (List*)malloc(sizeof(List));
    adj = mygraph->table[u].outlist;   
    
    // while there is a node outlist of current node
    // update lowlink of current node
    while(adj != NULL)
    {
        // adjacent node of the current node
        int v = adj->index;
        
        // if adjacent node has not discovered yet
        // send node to strongly connected component function
        // update the lowlink of the current node
        if (index[v] == -1)
        {
            SCC(mygraph, v, index, lowlink, stackGl, inStack);        
            lowlink[u] = min(lowlink[u],lowlink[v]);       
        }
        // if adjacent node is already discovered 
        // update lowlink number of the current node anyway
        else if(inStack[v] == 1)
        {
            lowlink[u] = min(lowlink[u], index[v]);
        }

        // pass to next node
        adj = adj->next;
    }
    
    int tmp;
    
    // if lowlink number of current node is equal to the index number of same
    // node, print the node
    if(lowlink[u] == index[u])
    {
        // if current node is in not in the top the stack
        // find the node and print out
        while (stackGl.contents[stackGl.top] != u)
        {
            tmp = stackGl.contents[stackGl.top];
            printf("%d ", tmp);
            inStack[tmp] = 0;
            StackPop(&stackGl);
            
        }
        // print it
        tmp = stackGl.contents[stackGl.top];
        printf(" %d\n ", tmp);
        inStack[tmp] = 0;
        
        // remove nodes from stack
        StackPop(&stackGl);
    }
    
}
Exemple #25
0
/* Pops top element on the stack*/
static inline void Pop(Stack *stack, Element *top) {
  if (!StackPop(stack, top)) {
    printf("Error: empty stack.");
    exit(1);
  }
}
Exemple #26
0
int desempilha() {
    return StackPop(&pilha);
}
Exemple #27
0
  {
    command = (ch & masks[count]);
    if (command != 0)
    {
      next = fgetc(fptr);
      value = ch << cmd_loc;
      next_temp = next >> (8 - cmd_loc);
      value = value | next_temp;
      HuffNode * TreeNode = HuffNode_create(value);
      st = StackPush(st, TreeNode);
      ch = next;
    }
    else
    {
      HuffNode * A = st -> node;
      st = StackPop(st);
      if (st == NULL)
      {
	return A;
      }
      
      else
      {
	HuffNode * B = st -> node;
	st = StackPop(st);
	HuffNode * parent = malloc(sizeof(HuffNode));
	parent -> value = ' ';
	parent -> right = A;
	parent -> left = B;
	st = StackPush(st,parent);
      }
Exemple #28
0
void _seq_batch_r(void* exec)
{



    EtalisEvent* Event_b  = (EtalisEvent*)exec;
    if (Event_b == NULL) return;
    EtalisExecNode* rule_ = Event_b->RootModel->parentNode;

    EtalisEvent* Event_a=NULL;

    /* calculate EAT */

    float EAT = getHighResStamp(&Event_b->timestamps[1]) - rule_->window_size; /* TODO fix */

    if (rule_->leftChild->is_temp)
    {
        _seq_batch_r(StackPop(rule_->leftChild->childNode->rightChild->eventStack));
    }


    do
    {
        /*if (getHighResStamp(&Event_b->timestamps[0]) < EAT ) { free(Event_b); continue;} /* problem : all atomic right side events does not fulfill this condition */
        Event_a = StackPop(rule_->leftChild->eventStack);
        while( Event_a != NULL && getTimeDiff(&(Event_b->timestamps[0]),&(Event_a->timestamps[1])) >= 0 ) /* problem : recursion */
        {
            /*if (getHighResStamp(&Event_a->timestamps[0]) < EAT )*/ /* EAT is not compatible with timestamps */
            if (Event_b->timestamps[1].time - Event_a->timestamps[0].time  > rule_->window_size)
            {
                free (Event_a);
                Event_a = StackPop(rule_->leftChild->eventStack);
                continue; /* normally you don't have to continue here, because events are already choronogically ordered in the stack */ /* fix this */
            }
            if(validate_arguments(Event_b,Event_a) != ETALIS_OK)
            {
#ifdef DEBUG
                printf("Event arguments could not be validated ! \n");
#endif
                free(Event_a); /* check*/
                Event_a = StackPop(rule_->leftChild->eventStack);
                continue;
            }

            EtalisEventNode* cplxEvModel=NULL; /* Complex Event Root Model */

            /* the rest depends on the CEP policy */
            if (_conf.policy==recent) /* recent policy */
            {
                cplxEvModel = rule_->parentEvent;

                /* triggering the complex event */
                EtalisEvent* cplxEvent = (EtalisEvent*)malloc(sizeof(EtalisEvent));
                cplxEvent->RootModel = rule_->parentEvent;
                /* bind the arguments of the complex event */ /* todo validate */
                cplxEvent->args = (int*)malloc(sizeof(int)*cplxEvModel->event.arity);
                size_t arg_iterator=0;
                for(arg_iterator=0; arg_iterator<cplxEvModel->event.arity; arg_iterator++)
                {
                    switch (cplxEvModel->arg_links[arg_iterator].event_)
                    {
                    case 1 :
                        *((int*)cplxEvent->args+arg_iterator)=*((int*)Event_a->args+(cplxEvModel->arg_links[arg_iterator].argument_number));
                        break;

                    case 2 :
                        *((int*)cplxEvent->args+arg_iterator)=*((int*)Event_b->args+(cplxEvModel->arg_links[arg_iterator].argument_number));
                        break;
                    }
                }


                cplxEvent->timestamps[0] = Event_a->timestamps[0]; /* timestamp structure as suggested by the ETALIS paper */
                cplxEvent->timestamps[1] = Event_b->timestamps[1];
                triggerEvent_intern_no_hash(cplxEvent);            /* trigger the complex event (we already know the EventModel, so we don't need to search for it in the _event_hash) */

                /* garbage collect : we don't need these events anymore */
                free(Event_a);
                free(Event_b);
                return;
            }
            else if (_conf.policy==unrestricted)
            {
                /* TODO */
                return ;
            }

            Event_a = StackPop(rule_->leftChild->eventStack);
        }


    }
    while (Event_b = StackPop(Event_b->RootModel->eventStack));









}
Exemple #29
0
/*
* Zstream implementation for seq (right event)
*/
void _seq_win_cep_r(void* exec)
{
    EtalisEvent* Event_b  = (EtalisEvent*)exec;
    EtalisExecNode* rule_ = Event_b->RootModel->parentNode;
    assert(Event_b != NULL && rule_ != NULL);


    EtalisEvent* Event_a = StackPop(rule_->leftChild->eventStack);

    if(Event_a == NULL) /* stack is empty*/
    {
        free(Event_b);
        return;
    }
    /* Event a is in the stack */
    /* a complex event will be generated if the conditions are met */
    /* testing if the conditions could be proven correct */





    if(getTimeDiff(&(Event_b->timestamps[0]),&(Event_a->timestamps[0])) > rule_->window_size) /* out of the window*/
    {
        /* printf(" --- Time difference is %d > window size of %d\n",Event_b->timestamps[0]-Event_a->timestamps[0],rule_->window_size);
        */
        free(Event_a); /* check this */
        free(Event_b);
        return;
    }


    if (Event_b->RootModel->event.arity != 0 )
    {
        if(aprio_validation(Event_b) != ETALIS_OK) /* argument a priori conditions must be true*/
        {
#ifdef DEBUG
            log_err("Event could be validated !");
#endif
            free(Event_a); /* check*/
            free(Event_b);
            return;
        }

        /* event arguments must be valide - implicite condition */
        if(validate_arguments(Event_b,Event_a) != ETALIS_OK)
        {
#ifdef DEBUG
            printf("Event arguments could not be validated ! \n");
#endif
            free(Event_a); /* check*/
            free(Event_b);
            return;
        }
    }


    EtalisEventNode* cplxEvModel=NULL; /* Complex Event Root Model */

    /* the rest depends on the CEP policy */
    if (_conf.policy==recent) /* recent policy */
    {
        cplxEvModel = rule_->parentEvent;

        /* triggering the complex event */
        EtalisEvent* cplxEvent = (EtalisEvent*)malloc(sizeof(EtalisEvent));
        cplxEvent->RootModel = rule_->parentEvent;
        /* bind the arguments of the complex event */ /* todo validate */
        cplxEvent->args = (int*)malloc(sizeof(int)*cplxEvModel->event.arity);
        size_t arg_iterator=0;
        for(arg_iterator=0; arg_iterator<cplxEvModel->event.arity; arg_iterator++)
        {
            switch (cplxEvModel->arg_links[arg_iterator].event_)
            {
            case 1 :
                *((int*)cplxEvent->args+arg_iterator)=*((int*)Event_a->args+(cplxEvModel->arg_links[arg_iterator].argument_number));
                break;

            case 2 :
                *((int*)cplxEvent->args+arg_iterator)=*((int*)Event_b->args+(cplxEvModel->arg_links[arg_iterator].argument_number));
                break;
            }
        }


        cplxEvent->timestamps[0] = Event_a->timestamps[0]; /* timestamp structure as suggested by the ETALIS paper */
        cplxEvent->timestamps[1] = Event_b->timestamps[1];
        triggerEvent_intern_no_hash(cplxEvent);            /* trigger the complex event (we already know the EventModel, so we don't need to search for it in the _event_hash) */

        /* garbage collect : we don't need these events anymore */
        free(Event_a);
        free(Event_b);
        return;
    }
    else if (_conf.policy==unrestricted)
    {
        /* TODO */
        return ;
    }

}
//returns the total number of collided cells
int add_block_1_axis(rb_red_blk_tree *tree, int x1, int y1, int x2, int y2, unsigned int type, int add_amount) {
  circ_tree_node *node_begin, *node_end;
  node_end = get_node(tree, x2, type)->key;  //the end strictly needs to be called before the beginning
  node_begin = get_node(tree, x1, type)->key;
  stk_stack *axis_range = RBEnumerate(tree, node_begin, node_end);

  rb_red_blk_node *rb_node, *rb_node_prev = NULL;
  int temp_collision = 0, collision = 0, prev_pos;

  for (;;) {
    //rb_node_prev = rb_node;
    rb_node = (rb_red_blk_node *) StackPop(axis_range);

    //if (rb_node_prev == NULL)
      rb_node_prev = TreePredecessor(tree, rb_node);
    
    circ_tree_node *node = (circ_tree_node *) rb_node->key;
    circ_tree_node *node_prev;

    if (rb_node_prev == NULL || rb_node_prev == tree->nil)
      node_prev = NULL;
    else
      node_prev = (circ_tree_node *) rb_node_prev->key;

    unsigned int stack_not_empty = StackNotEmpty(axis_range);

    //collision
    if (temp_collision) 
      //if temp collision is non-zero, by definition, node_prev
      //cannot be NULL
      collision += temp_collision * (node->pos - prev_pos);

    prev_pos = node->pos;

    if (type == TOP_LEVEL) {
      if (stack_not_empty) 
	temp_collision = add_block_1_axis(node->data.tree, y1, 0, y2, 0, SECOND_LEVEL, add_amount);
      if ((node_prev != NULL && 
	   !RBTreeCompare(node->data.tree, node_prev->data.tree, 
			  circ_node_equals)) ||
	  (node_prev == NULL && RBIsTreeEmpty(node->data.tree)))
	RBDelete(tree, rb_node);
      
    } else {
      if (stack_not_empty) {
	if (node->data.state > 0 && node->data.state > -add_amount) 
	  //if there is already a block here, and if there would still 
	  //be a block left, assess collision
	  temp_collision = add_amount;
	else
	  temp_collision = 0;
	node->data.state += add_amount;
      }

      //if both nodes are the same
      if ((node_prev != NULL && node_prev->data.state == node->data.state) ||
	  //or the previous node is null and this is zero
	  (node_prev == NULL && node->data.state == 0)) {
	RBDelete(tree, rb_node);
      }
    }

    if (!stack_not_empty)
      break;
  }
  StackDestroy(axis_range, dummy_fun);

  return collision;
}