int main(int argc, char **argv) {
    if (argc < 3) {
        fprintf(stderr, "Please enter a time quantums . . . . \n");
        exit(1);
    }
    time_slice = atoi(argv[1]);
    time_slice_1 = atoi(argv[2]);
    if (time_slice <= 0 || time_slice_1 <= 0) {
        fprintf(stderr, "Error! program usage rr < positive time quantum> < data file . . .\n");
        exit(1);
    }
    init_();
    clock_t ticks;
    time_t start_time, end_time;
    time(&start_time);
    int i;
    int status = 0;
    log_file = fopen("log_file.txt", "w+");
    if (log_file == NULL) {
        fprintf(stderr, "LOG FILE CANNOT BE OPEN\n");
    }
    //initialize cpu's
    for (i = 0; i < NUMBER_OF_PROCESSORS; i++) {
        CPU[i] = NULL;
    }
    initializeProcessQueue(&readyQueue);
    initializeProcessQueue(&waitingQueue);
    initializeProcessQueue(&level_one);
    initializeProcessQueue(&second_level);
    //initializeProcessQueue(&promoted);
    // read in process and initialize process values
    while ((status = (readProcess(&processes[number_of_processes])))) {
        if (status == 1) {
            number_of_processes++;
        }
    }
    if (number_of_processes > MAX_PROCESSES) {
        return -2;
    }
    if (number_of_processes == 0) {
        return -1;
    }
    int remaining_process = 0;
    //sort process by their arrival times
    qsort(processes, number_of_processes, sizeof (process), compareByArrival);
    // main execution loop
    while (TRUE) {
        ticks = clock();
        waiting_to_ready();
        incoming_process_init();
        running_process_to_waiting();
        most_ready_running_in_cpu();

        refresh_processes();
        increase_io_work();
        increase_cpu_work();

        cpu_utilized_time += runningProcesses();
        remaining_process = ex();
        // break when there are no more running or incoming processes, and the waiting queue is empty
        if (remaining_process == 0 && runningProcesses() == 0 && waitingQueue.size == 0) {
            break;
        }
        simulation_time++;
    }
    int total_waiting_time = 0;
    int turn_around_time = 0;
    for (i = 0; i < number_of_processes; i++) {
        turn_around_time += processes[i].endTime - processes[i].arrivalTime;
        total_waiting_time += processes[i].waitingTime;
    }
    printf(">>>>>>>>>>>>> FBQ with Q1 :%d\tQ2 :%d  <<<<<<<<<<<<<<<\n", time_slice, time_slice_1);
    printf("********************************************************************\n");
    printf("Average Waiting Time\t\t\t:%.2f\n", total_waiting_time / (double) number_of_processes);
    printf("Average Turn Around Time\t\t:%.2f\n", turn_around_time / (double) number_of_processes);
    printf("Time all for all CPU processes\t\t:%d\n", simulation_time);
    printf("CPU Utilization Time\t\t\t:%.2f%c\n", (double) (cpu_utilized_time * 100.0) / (double) (simulation_time), (int) 37);
    printf("Total Number of Context Switches\t:%d\n", context_switches);
    printf("Last Process to finish ");
    for (i = 0; i < number_of_processes; i++) {
        if (processes[i].endTime == simulation_time) {
            printf("PID\t\t:%d\n", processes[i].pid);
        }
    }
    printf("********************************************************************\n");
    time(&end_time);
    double prg_time = (end_time - start_time) * 0.001;
    double cpu_time = (double) ticks / CLOCKS_PER_SEC;
    fprintf(log_file, "Program Time\t:%.2fsecs\n", prg_time);
    fprintf(log_file, "CPU Time\t:%.2fsecs\n", cpu_time);
    fclose(log_file);
    return 0;
}
Beispiel #2
0
int ex(nodeType *p) 
{
    if (!p) return 0;	
	
	pushSymbolTable();
	
    switch(p->type) 
	{
		case typeIntCon:
			//printf("Int constant\n");
			return p->conInt.value;
		case typeDoubleCon:
			//printf("Double constant %f\n", p->conDbl.value);
			return p->conDbl.value;
		case typeIntId:
		{
			struct symbol_entry *entry = getSymbolEntry(p->idInt.i);
			if(!entry)
			{
				printf("Undefined variable.\n");
				return 0;
			}
			return entry->iVal;
		}
		case typeDblId:
			//printf("Double variable\n");
			return sym[p->idDbl.i];
		case typeOpr:
			switch(p->opr.oper) 
			{
				case DECLAREINT:
				{
					const char *name = p->opr.op[0]->idInt.i;	
					int value = ex(p->opr.op[1]);
					
					struct symbol_entry *entry = getSymbolEntry(name);
					if(!entry)	//make sure this variable name doesn't already exists
					{
						//entry = calloc(1, sizeof(struct symbol_entry)+300);
						entry = malloc(sizeof(struct symbol_entry));
						entry->name = name;
						entry->iVal = value;
						addSymbol(entry, yylineno);
						free(entry);
					}
					else
					{
						printf("This int variable has already been declared.\n");
					}
				
					break;
				}
				case DO:
					do 
					{
						ex(p->opr.op[0]);
					} while(ex(p->opr.op[1]));
					break;
				case WHILE:
					while(ex(p->opr.op[0]))
					{
						ex(p->opr.op[1]);
					}
					break;
				case REPEAT:
					do 
					{
						ex(p->opr.op[0]);
					} while(!ex(p->opr.op[1]));
					break;
				case IF:        
					if (ex(p->opr.op[0]))
						ex(p->opr.op[1]);
					else if (p->opr.nops > 2)
						ex(p->opr.op[2]);
					return 0;
				case PRINT:  
				{
					printf("%d\n", ex(p->opr.op[0])); 
					return 0;
				}
				case ';':       
					ex(p->opr.op[0]); 
					return ex(p->opr.op[1]);
				case '=':       
				{
					const char *name = p->opr.op[0]->idInt.i;
					int value = ex(p->opr.op[1]);
					
					struct symbol_entry *entry = getSymbolEntry(name);
					
					if(!entry)
					{
						printf("No variable by that name found\n");
					}
					else
					{
						entry->iVal = value;
					}
					
					return value;//sym[p->opr.op[0]->idInt.i] = ex(p->opr.op[1]);
				}
				case UMINUS:    return -ex(p->opr.op[0]);
				case '+':       return ex(p->opr.op[0]) + ex(p->opr.op[1]);
				case '-':       return ex(p->opr.op[0]) - ex(p->opr.op[1]);
				case '*':       return ex(p->opr.op[0]) * ex(p->opr.op[1]);
				case '/':       return ex(p->opr.op[0]) / ex(p->opr.op[1]);
				case '<':       return ex(p->opr.op[0]) < ex(p->opr.op[1]);
				case '>':       return ex(p->opr.op[0]) > ex(p->opr.op[1]);
				case GE:        return ex(p->opr.op[0]) >= ex(p->opr.op[1]);
				case LE:        return ex(p->opr.op[0]) <= ex(p->opr.op[1]);
				case NE:        return ex(p->opr.op[0]) != ex(p->opr.op[1]);
				case EQ:        return ex(p->opr.op[0]) == ex(p->opr.op[1]);
			}
		break; //case typeOpr
    }
    return 0;
}
Beispiel #3
0
int main()
{
  BOOST_THREAD_LOG << BOOST_THREAD_END_LOG;
  {
    boost::basic_thread_pool ex(1);
    boost::future<int> f1 = boost::async(boost::launch::async, &p1);
    BOOST_TEST(f1.valid());
    boost::future<int> f2 = f1.then(ex, &p2);
    BOOST_TEST(f2.valid());
    BOOST_TEST(! f1.valid());
    try
    {
      BOOST_TEST(f2.get()==2);
    }
    catch (std::exception& ex)
    {
      BOOST_THREAD_LOG << "ERRORRRRR "<<ex.what() << "" << BOOST_THREAD_END_LOG;
      BOOST_TEST(false);
    }
    catch (...)
    {
      BOOST_THREAD_LOG << " ERRORRRRR exception thrown" << BOOST_THREAD_END_LOG;
      BOOST_TEST(false);
    }
  }
  BOOST_THREAD_LOG << BOOST_THREAD_END_LOG;
  {
    boost::basic_thread_pool ex(1);
    boost::future<int> f1 = boost::async(boost::launch::async, &p1);
    BOOST_TEST(f1.valid());
    boost::future<void> f2 = f1.then(ex, &p3);
    BOOST_TEST(f2.valid());
    try
    {
      f2.wait();
    }
    catch (std::exception& ex)
    {
      BOOST_THREAD_LOG << "ERRORRRRR "<<ex.what() << "" << BOOST_THREAD_END_LOG;
      BOOST_TEST(false);
    }
    catch (...)
    {
      BOOST_THREAD_LOG << " ERRORRRRR exception thrown" << BOOST_THREAD_END_LOG;
      BOOST_TEST(false);
    }
  }
  BOOST_THREAD_LOG << BOOST_THREAD_END_LOG;
  {
    boost::basic_thread_pool ex(1);
    boost::future<int> f2 = boost::async(p1).then(ex, &p2);
    BOOST_TEST(f2.get()==2);
  }
  BOOST_THREAD_LOG << BOOST_THREAD_END_LOG;
  {
    boost::basic_thread_pool ex(1);
    boost::future<int> f1 = boost::async(p1);
    boost::future<int> f21 = f1.then(ex, &p2);
    boost::future<int> f2= f21.then(ex, &p2);
    BOOST_TEST(f2.get()==4);
  }
  BOOST_THREAD_LOG << BOOST_THREAD_END_LOG;
  {
    boost::basic_thread_pool ex(1);
    boost::future<int> f1 = boost::async(p1);
    boost::future<int> f2= f1.then(&p2).then(ex, &p2);
    BOOST_TEST(f2.get()==4);
  }
  BOOST_THREAD_LOG << BOOST_THREAD_END_LOG;
  {
    boost::basic_thread_pool ex(1);
    boost::future<int> f2 = boost::async(p1).then(ex, &p2).then(ex, &p2);
    BOOST_TEST(f2.get()==4);
  }

  return boost::report_errors();
}
Beispiel #4
0
int ex(nodeType *p) {
  int tmp;

  if(!p)
    return 0;

  switch(p->type) {
    case typeCon:
      return p->con.value;

    case typeId:
      return sym[p->id.i];

    case typeOpr:
      switch(p->opr.oper) {
        case WHILE:
          while(ex(p->opr.op[0]))
            ex(p->opr.op[1]);
          return 0;

        case IF:
          if(ex(p->opr.op[0]))
            ex(p->opr.op[1]);
          else if(p->opr.nops> 2)
            ex(p->opr.op[2]);
          return 0;

        case PRINT:
          printf("%d\n", ex(p->opr.op[0]));
          return 0;

        case ';':
          ex(p->opr.op[0]);
          return ex(p->opr.op[1]);

        case '=':
          return sym[p->opr.op[0]->id.i] = ex(p->opr.op[1]);

        case UMINUS:
          return -ex(p->opr.op[0]);

        case '+': return ex(p->opr.op[0]) +  ex(p->opr.op[1]);
        case '-': return ex(p->opr.op[0]) -  ex(p->opr.op[1]);
        case '*': return ex(p->opr.op[0]) *  ex(p->opr.op[1]);
        case '/': return ex(p->opr.op[0]) /  ex(p->opr.op[1]);
        case '<': return ex(p->opr.op[0]) <  ex(p->opr.op[1]);
        case '>': return ex(p->opr.op[0]) >  ex(p->opr.op[1]);
        case GE:  return ex(p->opr.op[0]) >= ex(p->opr.op[1]);
        case LE:  return ex(p->opr.op[0]) <= ex(p->opr.op[1]);
        case EQ:  return ex(p->opr.op[0]) == ex(p->opr.op[1]);
        case NE:  return ex(p->opr.op[0]) != ex(p->opr.op[1]);
      }
  }

  return 0;
}
Beispiel #5
0
static void doit(char *to, char *line) {
  char *x, **arg, *target, *tmp;
  char *type, *mid, *name, *alias;
  unsigned long uid, gid, mode;
  int in, out, len;
  static char *uid_global, *gid_global, *mode_global, *mid_global, V;

  len=splitmem(0,line,':'); if (len <7) return;
  arg=alloca((len+1) * sizeof(char*)); if (arg==0) nomem();
  splitmem(arg,line,':');

  type	= arg[0]; 
  x=arg[1]; if (!*x==0 && uid_global) x=uid_global; 
  if (*x) uid=atoulong(x); else uid = -1;

  x=arg[2]; if (!*x==0 && gid_global) x=gid_global; 
  if (*x) gid=atoulong(x); else gid = -1;

  x=arg[3];	if (!*x && mode_global) x=mode_global; scan_8ulong(x,&mode);
  mid = arg[4];	if (!*mid && mid_global) mid=mid_global;
  name= arg[5]; 
  x=arg[6]; alias = (*x) ? x : name;

  len = str_len(to) + str_len(mid) + str_len(name);
  x=alloca(2*len + 32); if (x==0) nomem();
  target = x;
  x += str_copy(x,to);
  x += str_copy(x,mid);
  x += str_copy(x,name);
  while (target[0]=='/' && target[1]=='/') target++;
  tmp = (*type=='x') ? x+2 : 0;

  switch(*type) {
  case 'p':
    if (SYS_mknod(target,S_IFIFO|0600,0) == -1)
      if (errno != EEXIST) ex("mknod",target);
    if (V) msg("pipe:\t", target);
    break;

  case 'd':
    if (mkdir(target,0700) == -1)
      if (errno != EEXIST) ex("mkdir",target);
    if (V) msg("mkdir:\t", target);
    break;

  case 'c':
  case 'x':
    if ((in=open(alias, O_RDONLY)) <0) ex("open",alias);

    if (*type == 'c') out = open(target, O_WRONLY|O_CREAT|O_TRUNC, 0600);
    else out = open_tmpfd(target, tmp, 0600);
    if (out <0) ex("open",target);

    x=alloca(8192); if (x==0) nomem();
    for (;;) {
      len=read(in,x,8192);
      if (len==0) break;
      else if (len==-1) ex("read",alias);
      else if (len != write(out,x,len)) { die(111,U,"write",target); }
    }

    close(in);
    if (fsync(out)) ex("fsync",target);
    if (close(out)) ex("close",target);
    if (tmp && rename(tmp,target))
      { die(111,U,"rename: ", tmp, " -> ", target, ": ", e()); }
    if (V) msg(alias, "\t-> ", target);
    break;

  case 'g':
    x=arg[1]; uid_global  = (*x) ? x : 0;
    x=arg[2]; gid_global  = (*x) ? x : 0;
    x=arg[3]; mode_global = (*x) ? x : 0;
    x=arg[4]; mid_global  = (*x) ? x : 0;
    return;

  case 'v':
    if (arg[1][0]) V=1;
    else V=0;

  default:
    return;
  }
  if (SYS_chown(target,uid,gid) <0) ex("chown",target);
  if (chmod(target,mode) <0)    ex("chmod",target);
}
int main()
{
    const my_facet f(1);
    {
        std::ios ios(0);
        unsigned long long v = 0;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0");
    }
    {
        std::ios ios(0);
        unsigned long long v = 1;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "1");
    }
    {
        std::ios ios(0);
        unsigned long long v = -1;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == (sizeof(unsigned long long) == 4 ? "4294967295" : "18446744073709551615"));
    }
    {
        std::ios ios(0);
        unsigned long long v = -1000;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "18446744073709550616");
    }
    {
        std::ios ios(0);
        unsigned long long v = 1000;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "1000");
    }
    {
        std::ios ios(0);
        showpos(ios);
        unsigned long long v = 1000;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "1000");
    }
    {
        std::ios ios(0);
        oct(ios);
        unsigned long long v = 1000;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "1750");
    }
    {
        std::ios ios(0);
        oct(ios);
        showbase(ios);
        unsigned long long v = 1000;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "01750");
    }
    {
        std::ios ios(0);
        hex(ios);
        unsigned long long v = 1000;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "3e8");
    }
    {
        std::ios ios(0);
        hex(ios);
        showbase(ios);
        unsigned long long v = 1000;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0x3e8");
    }
    {
        std::ios ios(0);
        hex(ios);
        showbase(ios);
        uppercase(ios);
        unsigned long long v = 1000;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0X3E8");
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        hex(ios);
        showbase(ios);
        uppercase(ios);
        unsigned long long v = 1000;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0X3E_8");
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        hex(ios);
        showbase(ios);
        unsigned long long v = 2147483647;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0x7f_fff_ff_f");
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        oct(ios);
        unsigned long long v = 0123467;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "123_46_7");
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        oct(ios);
        showbase(ios);
        unsigned long long v = 0123467;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0_123_46_7");
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        oct(ios);
        showbase(ios);
        right(ios);
        ios.width(15);
        unsigned long long v = 0123467;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "*****0_123_46_7");
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        oct(ios);
        showbase(ios);
        left(ios);
        ios.width(15);
        unsigned long long v = 0123467;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0_123_46_7*****");
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        oct(ios);
        showbase(ios);
        internal(ios);
        ios.width(15);
        unsigned long long v = 0123467;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "*****0_123_46_7");
        assert(ios.width() == 0);
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        hex(ios);
        showbase(ios);
        right(ios);
        ios.width(15);
        unsigned long long v = 2147483647;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "**0x7f_fff_ff_f");
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        hex(ios);
        showbase(ios);
        left(ios);
        ios.width(15);
        unsigned long long v = 2147483647;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0x7f_fff_ff_f**");
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        hex(ios);
        showbase(ios);
        internal(ios);
        ios.width(15);
        unsigned long long v = 2147483647;
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0x**7f_fff_ff_f");
        assert(ios.width() == 0);
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        showpos(ios);
        unsigned long long v = 1000;
        right(ios);
        ios.width(10);
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "****1_00_0");
        assert(ios.width() == 0);
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        showpos(ios);
        unsigned long long v = 1000;
        left(ios);
        ios.width(10);
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "1_00_0****");
        assert(ios.width() == 0);
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        showpos(ios);
        unsigned long long v = 1000;
        internal(ios);
        ios.width(10);
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "****1_00_0");
        assert(ios.width() == 0);
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        unsigned long long v = -1000;
        right(ios);
        showpos(ios);
        ios.width(10);
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "18_446_744_073_709_550_61_6");
        assert(ios.width() == 0);
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        unsigned long long v = -1000;
        left(ios);
        ios.width(10);
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "18_446_744_073_709_550_61_6");
        assert(ios.width() == 0);
    }
    {
        std::ios ios(0);
        ios.imbue(std::locale(std::locale::classic(), new my_numpunct));
        unsigned long long v = -1000;
        internal(ios);
        ios.width(10);
        char str[50];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str), ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "18_446_744_073_709_550_61_6");
        assert(ios.width() == 0);
    }
}
ProError SetParametricParameter(  
				e_force             force,
				const std::string	&in_model_name,
				ProMdl				*in_p_model, 
				const std::string   in_ParameterName,
				e_CADParameterType	in_ParameterType,
				const std::string   in_ParameterValue)
									throw (isis::application_exception)
{
	ProError result = PRO_TK_NO_ERROR; 
	std::stringstream msg("SetParametricParameter: (force) ");

	
	
	
	isis_LOG(lg, isis_FILE, isis_INFO) <<  "  SetParametricParameter CADParameter" 
		<< isis_EOL <<  "      Force          "  <<  force
		<< isis_EOL <<  "      Model Name     "  <<  in_model_name 
		<< isis_EOL <<  "      Model Handle   "  <<  in_p_model
		<< isis_EOL <<  "      Type           "  <<  in_ParameterType 
		<< isis_EOL <<  "      Name           "  <<  in_ParameterName
		<< isis_EOL <<  "      Value          "  <<  in_ParameterValue;

	if (in_p_model == NULL) {
		isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << "null model handle";
		return PRO_TK_BAD_INPUTS;
	}

	isis_LOG(lg, isis_FILE, isis_INFO) << "SetParametricParameter : Set up the parameter"; 
	if ( in_ParameterName.size() >= PRO_NAME_SIZE ) {
		msg << "Exceeded maximum number of characters : "
		    << "Parameter Name: " << in_ParameterName << ", Maximum allowed characters: " << (PRO_NAME_SIZE - 1);
		isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
		throw isis::application_exception("C01001", msg);
	}

	ProName parameter_key;
	ProStringToWstring(parameter_key, const_cast<char *>(in_ParameterName.c_str()) );
	ProParamvalue parameter_value;

	switch ( in_ParameterType ) {
		case CAD_FLOAT:
			parameter_value.type = PRO_PARAM_DOUBLE;
			parameter_value.value.d_val = atof(in_ParameterValue.c_str());
			break;
		case CAD_INTEGER:
			parameter_value.type = PRO_PARAM_INTEGER;
			parameter_value.value.i_val = atoi(in_ParameterValue.c_str());
			break;
		case CAD_BOOLEAN:
			parameter_value.type = PRO_PARAM_BOOLEAN;
			parameter_value.value.l_val = isis::String_To_ProBoolean(in_ParameterValue);
			break;
		case CAD_STRING:
			if ( in_ParameterValue.size() > MAX_STRING_PARAMETER_LENGTH )
			{
				msg << "Erroneous CADParameter string value: "
					    << "Parameter: " <<  CADParameterType_string(in_ParameterType) 
					    << "  Value: " << in_ParameterValue 
						<< ", Value must be " << MAX_STRING_PARAMETER_LENGTH << " characters or less.";
				throw isis::application_exception(msg);
			}
			parameter_value.type = PRO_PARAM_STRING;
			ProStringToWstring(parameter_value.value.s_val, const_cast<char *>(in_ParameterValue.c_str()));
			break;

		default:
			msg << "Erroneous CADParameter Type: "
				<<  CADParameterType_string(in_ParameterType) << ", Should be FLOAT, INTEGER, or BOOLEAN.";
			isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
			throw isis::application_exception(msg);
	}

	ProError status;

	isis_LOG(lg, isis_FILE, isis_INFO) << "SetParametricParameter : get the model-item from the model";
	ProModelitem model_item;
	
	switch ( status = ProMdlToModelitem( *in_p_model, &model_item ) ) {
	case PRO_TK_NO_ERROR: 
		{
			isis_LOG(lg, isis_FILE, isis_INFO) << "The ProMdlToModelitem() was successful.";
			break;
		}
	case PRO_TK_BAD_INPUTS: 
		{
			msg	<< "ProMdlToModelitem: An argument is NULL, "
				<< " model: " << in_p_model 
				<< " model-item: " << model_item;
			isis::application_exception ex(msg);
			isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
			throw ex;
		}
	case PRO_TK_INVALID_PTR: 
		{
			msg << "ProMdlToModelitem: The handle is invalid. ";
			isis::application_exception ex(msg);
			isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
			throw ex;
		}
	}

	isis_LOG(lg, isis_FILE, isis_INFO) << "SetParametricParameter : set the property";
	ProParameter parameter_handle;
    switch ( status = ProParameterInit(&model_item, parameter_key, &parameter_handle) ) {
		case PRO_TK_E_NOT_FOUND:
		{
			switch (force) {
			case FORCE_KEY:
				break;
			case FORCE_VALUE:
				{
					msg << "key is not bound and should not be forced";
					isis::application_exception ex(msg);
					isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
					throw ex;
				}
			case FORCE_NEITHER:
				{
					msg << "force neither : not yet implemented";
					isis::application_exception ex(msg);
					isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
					throw ex;
				}
			}
			isis_LOG(lg, isis_FILE, isis_INFO) << "The parameter was not found within the owner, so creating new.";
			switch ( status = ProParameterCreate (&model_item, parameter_key, &parameter_value, &parameter_handle ) ) {
			case PRO_TK_NO_ERROR:
				{
						isis_LOG(lg, isis_FILE, isis_INFO) << "ProParameterCreate successfully added the parameter.";
						result = PRO_TK_E_NOT_FOUND;
						break;
				}
			case PRO_TK_BAD_INPUTS:
				{
					msg	<< "One or more of the input arguments to ProParameterCreate() are invalid,"
						<< " key: " << parameter_key 
						<< " param: " << parameter_handle.owner.type;
					isis::application_exception ex(msg);
					isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
					throw ex;
				}
			case PRO_TK_BAD_CONTEXT:
				{
					msg << "The owner is nonexistent.";
					isis::application_exception ex(msg);
					isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
					throw ex;
				}
			case PRO_TK_E_FOUND:
				{
					msg << "The specified parameter already exists.";
					isis::application_exception ex(msg);
					isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
					throw ex;
				}
			case PRO_TK_GENERAL_ERROR: 
				{
					msg << "The function could not add the parameter to the database.";
					isis::application_exception ex(msg);
					isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
					throw ex;
				}
			}
		}
	case PRO_TK_NO_ERROR: 
		{
			isis_LOG(lg, isis_FILE, isis_INFO) << "ProParameterInit() successfully initialized the handle.";
			switch (force) {
			case FORCE_KEY:
			case FORCE_VALUE:
				break;
			case FORCE_NEITHER:
				{
					msg << "force neither : not yet implemented";
					isis::application_exception ex(msg);
					isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
					throw ex;
				}
			}	
			switch ( status = ProParameterValueSet(&parameter_handle, &parameter_value) ) {
			case PRO_TK_NO_ERROR:
				{
					isis_LOG(lg, isis_FILE, isis_INFO) << "ProParameterValueSet successfully updated the information.";
					result = PRO_TK_NO_ERROR;
					break;
				}
			case PRO_TK_E_NOT_FOUND: 
				{
					msg << "The owner was not found.";
					isis::application_exception ex(msg);
					isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
					throw ex;
				}
			case PRO_TK_GENERAL_ERROR: 
				{
					msg << "The parameter was not found, or the function could not perform the action.";
					isis::application_exception ex(msg);
					isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
					throw ex;
				}
			}
			break;
		}
	case PRO_TK_BAD_INPUTS: 
		{
			msg	<< "One or more of the input arguments are invalid,"
				<< " key: " << parameter_key 
				<< " param: " << parameter_handle.owner.type;
			isis::application_exception ex(msg);
			isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
			throw ex;
		}
	case PRO_TK_BAD_CONTEXT: 
		{
			msg << "The owner is nonexistent.";
			isis::application_exception ex(msg);
			isis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << msg.str();
			throw ex;
		}
		
	}
	isis_LOG(lg, isis_FILE, isis_INFO) << "SetParametricParameter : COMPLETE";
	return result;
		
}  // end ForceParametricParameter
Beispiel #8
0
static value if_builtin(args arg) {
  return vtob(get(arg,1)) ? ex(vtos(get(arg,2))):
    (arg.size()>3?ex(vtos(get(arg,3))):btov(false));
}
Beispiel #9
0
pair<string,bool> exec(const string &s) {
  try {ex(s); return make_pair("",true);}
  catch (const boodew_exception &e) {return make_pair(string(e.what()),false);}
}
Beispiel #10
0
static value if_builtin(args arg) {
  return vtob(get(arg,1)) ? ex(vtos(get(arg,2))):
    (arg.size()>3?ex(vtos(get(arg,3))):btov(false));
}
#define O(S)CMDL(#S,[](args arg){return dtov(vtod(get(arg,1)) S vtod(get(arg,2)));})
O(+) O(-) O(/) O(*)
#undef O
#define O(S)CMDL(#S,[](args arg){return btov(vtod(get(arg,1)) S vtod(get(arg,2)));})
O(==) O(!=) O(<) O(>) O(<=) O(>=)
#undef O
CMDL("int",[](args arg){return stov(to_string(int(vtod(get(arg,1)))));})
CMDL("var",[](args arg){return new_local(vtos(get(arg,1)),arg.size()<3?btov(false):get(arg,2));})
CMDL("#", [](args){return btov(false);})
CMDL("..", [](args arg){return stov(vtos(get(arg,1))+vtos(get(arg,2)));})
CMDL("echo", [](args arg){cout<<vtos(get(arg,1));return get(arg,1);})
CMDL("^", [](args arg){return get(arg,1);})
CMDL("return", [](args arg)->value {throw get(arg,1);})
CMDL("do", [](args arg){try {return ex(vtos(get(arg,1)));} catch (value v) {return v;}})
CMDL("break", [](args arg)->value {throw true;})
CMDL("continue", [](args arg)->value {throw false;})
CMDN("while", while_builtin)
CMDN("loop", loop_builtin)
CMDN("?", if_builtin)
CMDN("$", getvar)
pair<string,bool> exec(const string &s) {
  try {ex(s); return make_pair("",true);}
  catch (const boodew_exception &e) {return make_pair(string(e.what()),false);}
}
} // namespace boodew

Beispiel #11
0
static value while_builtin(args arg) {
  value last;
  while (vtob(ex(vtos(get(arg,1))))) try {return last=ex(vtos(get(arg,2))); }
    catch (bool b) { if (b) break; else continue; }
  return last;
}
void LCGWSpinBBHNR1::ConvertSpinDirToSSB(int iSpin)
{
	double thS, phS, th, ph;
	double iota, stheta, nez;
	double thBS, phBS;
	double phi0(0.);
	LCVector ex(MT), ey(MT), spin(MT), nW(MT), ez(MT);
	
	
	if(iSpin==1){
		thS = thS1;
		phS = phS1;
	}
	if(iSpin==2){
		thS = thS2;
		phS = phS2;
	}
	
	th = M_PI/2. - Beta;
	ph = Lambda;
	
	
	//! **** Compute \f$ \theta_L \f$ and \f$ \phi_L \f$ :
	//! ** Declaration of coordinates of ^k, ^theta, ^phi and ^Ln in SSB frame and cos / sin of some angles
	double x_k, y_k, z_k;
	double x_th, y_th, z_th;
	double x_ph, y_ph, z_ph;
	// double LnBx, LnBy, LnBz;
	double sPhS, cPhS, sPsi, cPsi, sThd, cThd; 
	
	sPhS = sin(phiS);
	cPhS = cos(phiS);
	sPsi = sin(2.*M_PI-NRPolarization);
	cPsi = cos(2.*M_PI-NRPolarization);
	sThd = sin(Thd);
	cThd = cos(Thd);
	
	x_k = - sThS * cPhS;
	y_k = - sThS * sPhS;
	z_k = - cThS;
	
	x_th = cThS * cPhS;
	y_th = cThS * sPhS;
	z_th = - sThS;
    
	x_ph = -y_k * z_th + z_k * y_th;
	y_ph = -z_k * x_th + x_k * z_th;
	z_ph = -x_k * y_th + y_k * x_th;
    
	
    
	
	
	//! ** Following convention of Sofiane for the angle psi (^p = cos psi ^theta + sin psi ^phi) :
	//	 LnBx = (- sThd * sPsi * x_th + sThd * cPsi * x_ph + cThd * x_k  );
	//	 LnBy = (- sThd * sPsi * y_th + sThd * cPsi * y_ph + cThd * y_k  );
	//	 LnBz = (- sThd * sPsi * z_th + sThd * cPsi * z_ph + cThd * z_k  );
	
	
	/*  
	 // new
	 
	 LnBx = (- sThd * sPsi * x_th - sThd * cPsi * x_ph + cThd * x_k  );
	 LnBy = (- sThd * sPsi * y_th - sThd * cPsi * y_ph + cThd * y_k  );
	 LnBz = (- sThd * sPsi * z_th - sThd * cPsi * z_ph + cThd * z_k  );
	 */
    
    /*
	 //! ** Following convention of Antoine for the angle psi (^p = cos psi ^theta - sin psi ^phi) :
	 LnBx = -( sThd * cPsi * x_th - sThd * sPsi * x_ph - cThd * x_k  );
	 LnBy = -( sThd * cPsi * y_th - sThd * sPsi * y_ph - cThd * y_k  );
	 LnBz = -( sThd * cPsi * z_th - sThd * sPsi * z_ph - cThd * z_k  );   
	 */
  	
	// with all angles
	
	
    LnB.x( -LnN.y()*cPsi*x_th+LnN.y()*sPsi*x_ph+LnN.x()*cThd*sPsi*x_th+LnN.x()*cThd*cPsi*x_ph-LnN.z()*sThd*sPsi*x_th-LnN.z()*sThd*cPsi*x_ph+x_k*LnN.x()*sThd+x_k*LnN.z()*cThd );
    LnB.y( -LnN.y()*cPsi*y_th+LnN.y()*sPsi*y_ph+LnN.x()*cThd*sPsi*y_th+LnN.x()*cThd*cPsi*y_ph-LnN.z()*sThd*sPsi*y_th-LnN.z()*sThd*cPsi*y_ph+y_k*LnN.x()*sThd+y_k*LnN.z()*cThd );
    LnB.z( -LnN.y()*cPsi*z_th+LnN.y()*sPsi*z_ph+LnN.x()*cThd*sPsi*z_th+LnN.x()*cThd*cPsi*z_ph-LnN.z()*sThd*sPsi*z_th-LnN.z()*sThd*cPsi*z_ph+z_k*LnN.x()*sThd+z_k*LnN.z()*cThd );
    
    
    double n_LnB = LnB.norm();
    
	//	thBL =   atan2(sqrt(LnBx*LnBx + LnBy*LnBy),LnBz);  // acos(LnBz/n_LnB); corrected by Sofiane
    thBL =  acos(LnB.z()/n_LnB);
    
	//    if(thBL<0.)
	//        thBL +-M_PI;
    
	//	phBL =M_PI*(1-LnBy/fabs(LnBy)) + LnBy/fabs(LnBy) * acos(LnBx / n_LnB / sqrt(1. - LnBz*LnBz / (n_LnB*n_LnB)) );  //  atan2(LnBy,LnBx); corrected by Sofiane
	
    phBL = LnB.ph();
    
    
    if(phBL<0.)
  		phBL += 2.*M_PI;
	
	//  double up = cThS*sin(thBL)*cos(phiS-phBL) - cos(thBL)*sThS;   /: commented by Sofiane
	//  double down = sin(thBL)*sin(phiS - phBL);    // commented by Sofiane
    
    ConvertLS1S2dirNR2SSBSofVer(Phd, thetaS, phiS, thetaJ, phiJ, LnN, S1N, S2N, AmpL, AmpS1, AmpS2, LnB, S1B, S2B);  // see how to use it in more elegant way
    
    
    double up =  cos(Phd - phiS);    // introduced by Sofiane
    double down = cos(thetaS)*sin(Phd - phiS);  // introduced by Sofiane
    
    PSIN =atan2(up,down);
    
    if(PSIN<0.)  
        PSIN +=2*M_PI;
	
	
	iota = acos(sin(th)*sin(thBL)*cos(ph - phBL) + cos(th)*cos(thBL)); 
	
    
	stheta = fabs(sin(iota));
	if (iota == 0.0)
		Cout << "WARNING in LCGWSpinBBHNR1::ConvertSpinDirToSSB : degenerate case need to consider separately: L colinear with n !" << Endl;
	nW.p[0] = sin(th)*cos(ph) ;
	nW.p[1] = sin(th)*sin(ph) ;
	nW.p[2] = cos(th) ;
	ez.p[0] = sin(thBL)*cos(phBL) ;  
	ez.p[1] = sin(thBL)*sin(phBL) ;
	ez.p[2] = cos(thBL) ;
	ey.p[0] = (nW.p[1]*ez.p[2] - nW.p[2]*ez.p[1])/stheta ;
	ey.p[1] = (nW.p[2]*ez.p[0] - nW.p[0]*ez.p[2])/stheta ;
	ey.p[2] = (nW.p[0]*ez.p[1] - nW.p[1]*ez.p[0])/stheta ;
	
	nez = nW.p[0]*ez.p[0] + nW.p[1]*ez.p[1] + nW.p[2]*ez.p[2] ;
	ex.p[0] = (ez.p[0]*nez - nW.p[0])/stheta ;
	ex.p[1] = (ez.p[1]*nez - nW.p[1])/stheta ;
	ex.p[2] = (ez.p[2]*nez - nW.p[2])/stheta ;
	
	//! ** if it is eccentric orbit, we need to rotate ex, ey by -phi0
	
	for(int i=0; i<3; i++)
		spin.p[i] = sin(thS)*cos(phS)*( cos(phi0)*ex.p[i] - sin(phi0)*ey.p[i] ) + sin(thS)*sin(phS)*( sin(phi0)*ex.p[i] + cos(phi0)*ey.p[i] ) + cos(thS)*ez.p[i] ;
	
	thBS = acos(spin.p[2]);
	phBS = atan2(spin.p[1], spin.p[0]);
	if (phBS < 0.)
		phBS = phBS + 2.*M_PI;
	
	if(iSpin==1){
		thBS1 = thBS;
		phBS1 = phBS;
	}
	if(iSpin==2){
		thBS2 = thBS;
		phBS2 = phBS;
	}	
	
	S1B.x( sin(thBS1)*cos(phBS1) );
	S1B.y( sin(thBS1)*sin(phBS1) );
	S1B.z( cos(thBS1) );
	
	S2B.x( sin(thBS2)*cos(phBS2) );
	S2B.y( sin(thBS2)*sin(phBS2) );
	S2B.z( cos(thBS2) );
	
	
}
Beispiel #13
0
Datei: c8c.c Projekt: c8c/c8c
int ex(nodeType *p) {
    int lblx, lbly, lbl1, lbl2, lblz, lbl3;
    int i,j;
    SymbolType type;
    char* fun_name;
    int numofparas;
    FunNode* func;
    nodeType* paras;
    int *size;
    if (!p) return 0;
    switch(p->type) {
        case typeCon:       
        printf("\tpush\t%d\n", p->con.value); 
        break;  
        case typeId:
        printf("\tpush\tfp[%d]\n",getSymbol(p->id.i)->index);
        break;
        case typeStr:
        printf("\tpush\t\"%s\"\n",p->str.value);// " not include in con.value
        break;
        case typeArr:
        storeOffsetInIn(p);
        testOutofBoundary(p);
        printf("\tpush\tfp[in]\n");
        break;
        case typeOpr:
            switch(p->opr.oper) {
                case INT: 
                case CHAR://Declaration
                    if(p->opr.oper == INT)
                        type = INTTYPE;
                    else if(p->opr.oper == CHAR)
                        type = CHARTYPE;
                    else{
                        printf("Compile Error(1072): Unknown indentifier type\n");
                        exit(-1);
                    }
                    switch(p->opr.op[0]->type){
                        case typeId://A variable
                            printf("\tpush\tsp\n");//allocate space in stack
                            printf("\tpush\t1\n");
                            printf("\tadd\t\n");
                            printf("\tpop\tsp\n");
                            break;
                        case typeArr://An array
                            size = (int *)malloc(sizeof(int) * p->opr.op[0]->arr.dimension);
                            for(i = 0; i < p->opr.op[0]->arr.dimension; i++){
                                ex(p->opr.op[0]->arr.index[i]);
                            }
                            for(i = 0; i < p->opr.op[0]->arr.dimension - 1; i++){
                                printf("\tmul\t\n");
                                }
                            printf("\tpush\tsp\n");
                            printf("\tadd\t\n");
                            printf("\tpop\tsp\n");
                            break;
                        default:
                            printf("Compile Error(1070): Unknown declaration type. <%d>\n",p->opr.op[0]->type);
                            exit(-1);
                            break;
                    }
                    break;
                case CODEBLOCK:
                    ex(p->opr.op[0]);
                    ex(p->opr.op[1]);
                    break;
                case FOR:
                    ex(p->opr.op[0]);
                    printf("L%03d:\n", lblx = lbl++);
                    ex(p->opr.op[1]);
                    printf("\tj0\tL%03d\n", lbly = lbl++);
                    lblz = lbl++;
                    push(lblz,lbly);        
                    ex(p->opr.op[3]);
                    printf("L%03d:\n", lblz);
                    ex(p->opr.op[2]);
                    printf("\tjmp\tL%03d\n", lblx);
                    printf("L%03d:\n", lbly);
                    pop();
                    break;
                case CALL:
                    fun_name = p->opr.op[0]->id.i;//get function name;
                    numofparas = 0;
                    /*push parameters in stack*/
                    for(paras = p->opr.op[1];paras != NULL;paras = paras->para.next){
                        storeOffsetInIn(paras->para.name);
                        if(paras->para.name->type == typeArr)
                            testOutofBoundary(paras->para.name);
                        printf("\tpush\tfp[in]\n");//push para in stack
                        numofparas++;
                    }
                    /*actually, this exist check should be done in c8.y*/
                    if(func = getFunc(fun_name) == NULL){ 
                        printf("Error 1051: function (%s())not declared.\n",fun_name);
                        exit(-1);
                    }
                    printf("\tcall\tL%03d,%d\n",func->label,numofparas);
                break;
                case WHILE:
                    printf("L%03d:\n", lbl1 = lbl++);
                    ex(p->opr.op[0]);
                    printf("\tj0\tL%03d\n", lbl2 = lbl++);
                    push(lbl1,lbl2);
                    ex(p->opr.op[1]);
                    printf("\tjmp\tL%03d\n", lbl1);
                    printf("L%03d:\n", lbl2);
                    pop();
                break;
                case DO-WHILE:
                    lbl1 = lbl++;
                    lbl2 = lbl++;
                    lbl3 = lbl++;
                    push(lbl3,lbl2);
                    printf("L%03d:\n",lbl1);
                    ex(p->opr.op[0]);
                    printf("L%03d:\n", lbl3);
                    ex(p->opr.op[1]);
                    printf("\tj0\tL%03d\n", lbl2);
                    printf("\tjmp\tL%03d\n", lbl1);
                    printf("L%03d:\n", lbl2);
                    pop();
                break;
                case BREAK: printf("\tjmp\tL%03d\n", top(1)); break;
                case CONTINUE: printf("\tjmp\tL%03d\n", top(0)); break;
                case IF:
                ex(p->opr.op[0]);
                if (p->opr.nops > 2) {
                    printf("\tj0\tL%03d\n", lbl1 = lbl++);
                    ex(p->opr.op[1]);
                    printf("\tjmp\tL%03d\n", lbl2 = lbl++);
                    printf("L%03d:\n", lbl1);
                    ex(p->opr.op[2]);
                    printf("L%03d:\n", lbl2);
                } else {
                    printf("\tj0\tL%03d\n", lbl1 = lbl++);
                    ex(p->opr.op[1]);
                    printf("L%03d:\n", lbl1);
                }
                break;
                case READ:
                    printf("\tgeti\n");
                    storeOffsetInIn(p->opr.op[0]); 
                    if(p->opr.op[0]->type == typeArr)
                        testOutofBoundary(p->opr.op[0]);               
                    printf("\tpop\tfp[in]\n");
                break;
                case PRINT:     
                    ex(p->opr.op[0]);
                    printf("\tputi\n");
                break;
                case '=':
                    ex(p->opr.op[1]);
                    storeOffsetInIn(p->opr.op[0]);
                    if(p->opr.op[0]->type == typeArr)
                        testOutofBoundary(p->opr.op[0]);
                    printf("\tpop\tfp[in]\n");
                break;
                case UMINUS:    
                    ex(p->opr.op[0]);
                    printf("\tneg\n");
                break;
            default:/*Expr*/
/*semicolon*/
        ex(p->opr.op[0]);
        ex(p->opr.op[1]);
        switch(p->opr.oper) {
            case '+':   printf("\tadd\n"); break;
            case '-':   printf("\tsub\n"); break; 
            case '*':   printf("\tmul\n"); break;
            case '/':   printf("\tdiv\n"); break;
            case '%':   printf("\tmod\n"); break;
            case '<':   printf("\tcomplt\n"); break;
            case '>':   printf("\tcompgt\n"); break;
            case GE:    printf("\tcompge\n"); break;
            case LE:    printf("\tcomple\n"); break;
            case NE:    printf("\tcompne\n"); break;
            case EQ:    printf("\tcompeq\n"); break;
            case AND:   printf("\tand\n"); break;
            case OR:    printf("\tor\n"); break;
        }
    }
}
return 0;
}
Beispiel #14
0
void main() {

    ex();
    ex();

}
Beispiel #15
0
menu::menu(QWidget *parent) :
    QWidget(parent),expend(),dab()

{
    this->setStyleSheet("background-color:black");
    QFont newff("Arial",10,QFont::Normal,false);
     QFont newfb("Arial",8,0,false);
    // QFont newfc("Arial",8,0,false);
     maxexp=new QPushButton("Reset your maximum expenditure limit",this);
     maxexp->setStyleSheet("background-color:#003333;color:white");
     maxexp->setFont(newfb);
     exitt=new QPushButton("Exit",this);
     exitt->setStyleSheet("background-color:#003333;color:white");
     exitt->setFont(newff);

     more=new QPushButton("More options",this);
     more->setStyleSheet("background-color:#003333;color:white");
     more->setFont(newff);



     bacc=new QPushButton("Back",this);
     bacc->setStyleSheet("background-color:#003333;color:white");
     bacc->setFont(newff);


     cancel=new QPushButton("Cancel",this);
     cancel->setStyleSheet("background-color:#003333;color:white");
     cancel->setFont(newff);
     cancel->setVisible(false);

     max=new QLineEdit("",this);
     max->setStyleSheet("background-color:white;color:black");
     max->setVisible(false);
     ok=new QPushButton("OK",this);
     ok->setVisible(false);
    ok->setStyleSheet("background-color:#003333;color:white");
    ok->setFont(newff);

     maxexp->setStyleSheet("background-color:#003333;color:white");
     maxexp->setFont(newff);
     hb4=new QHBoxLayout();

    vb1=new QVBoxLayout(this);

    hb=new QHBoxLayout();
    hb1=new QHBoxLayout();
     hb2=new QHBoxLayout();
      hb3=new QHBoxLayout();
      hb5=new QHBoxLayout();


     //select=new QLabel("<img src='D:/Desert.JPG'/ >",this);
       select=new QLabel("   Choose your category ",this);

       select->setStyleSheet("background-color:black;color:white; qproperty-alignment: AlignCenter");

       select->setAlignment(Qt::AlignTop);



       select->setMaximumHeight(45);
       select->setFont(newff);

       check=new QPushButton("Click to check total savings",this);
       check->setStyleSheet("background-color:#003333;color:white");

       check->setFont(newff);



    food=new QPushButton("food",this);
    food->setStyleSheet("background-color:#003333;color:white");
    food->setFixedSize(180,40);
    food->setFont(newff);

    shopping=new QPushButton("shopping",this);
    shopping->setFixedSize(180,40);
    shopping->setStyleSheet("background-color:#003333;color:white");
    shopping->setFont(newff);

    entertainment=new QPushButton("entertainment",this);
    entertainment->setStyleSheet("background-color:#003333;color:white");
    entertainment->setFixedSize(180,40);
    entertainment->setFont(newfb);

    family=new QPushButton("family/friends",this);
    family->setStyleSheet("background-color:#003333;color:white");
    family->setFixedSize(180,40);
    family->setFont(newff);

    fuel=new QPushButton("fuel",this);
    fuel->setStyleSheet("background-color:#003333;color:white");
    fuel->setFixedSize(180,40);
    fuel->setFont(newff);

    others=new QPushButton("others",this);
    others->setStyleSheet("background-color:#003333;color:white");
    others->setFixedSize(180,40);
 others->setFont(newff);

hb5->addWidget(check);
hb4->addWidget(max);
hb4->addWidget(ok);
hb4->addWidget(cancel);

   hb1->addWidget(food);
   hb1->addWidget(shopping);

   hb2->addWidget(entertainment);
   hb2->addWidget(family);

   hb3->addWidget(fuel);
   hb3->addWidget(others);
   vb1->addItem(hb5);
   vb1->addWidget(maxexp);

   vb1->addItem(hb4);
   vb1->addWidget(more);
   vb1->addWidget(select);

   vb1->addItem(hb1);
   vb1->addItem(hb2);
   vb1->addItem(hb3);
    vb1->addWidget(exitt);
    vb1->addWidget(bacc);



   QObject::connect(food,SIGNAL(clicked()),this,SLOT(foodshowFullScreen()));
   QObject::connect(shopping,SIGNAL(clicked()),this,SLOT(shopshowFullScreen()));
   QObject::connect(entertainment,SIGNAL(clicked()),this,SLOT(entshowFullScreen()));
   QObject::connect(family,SIGNAL(clicked()),this,SLOT(fmshowFullScreen()));
   QObject::connect(fuel,SIGNAL(clicked()),this,SLOT(fushowFullScreen()));
   QObject::connect(others,SIGNAL(clicked()),this,SLOT(otshowFullScreen()));
   QObject::connect(ok,SIGNAL(clicked()),this,SLOT(go()));
   QObject::connect(cancel,SIGNAL(clicked()),this,SLOT(canc()));
   QObject::connect(maxexp,SIGNAL(clicked()),this,SLOT(max_click()));
   QObject::connect(check,SIGNAL(clicked()),this,SLOT(check_save()));
   QObject::connect(exitt,SIGNAL(clicked()),this,SLOT(ex()));
   QObject::connect(bacc,SIGNAL(clicked()),this,SLOT(ba()));
   QObject::connect(more,SIGNAL(clicked()),this,SLOT(mor()));








}
Beispiel #16
0
void AsyncUDPSocket::handleRead() noexcept {
  void* buf{nullptr};
  size_t len{0};

  if (handleErrMessages()) {
    return;
  }

  if (fd_ == -1) {
    // The socket may have been closed by the error callbacks.
    return;
  }

  readCallback_->getReadBuffer(&buf, &len);
  if (buf == nullptr || len == 0) {
    AsyncSocketException ex(
        AsyncSocketException::BAD_ARGS,
        "AsyncUDPSocket::getReadBuffer() returned empty buffer");

    auto cob = readCallback_;
    readCallback_ = nullptr;

    cob->onReadError(ex);
    updateRegistration();
    return;
  }

  struct sockaddr_storage addrStorage;
  socklen_t addrLen = sizeof(addrStorage);
  memset(&addrStorage, 0, size_t(addrLen));
  struct sockaddr* rawAddr = reinterpret_cast<sockaddr*>(&addrStorage);
  rawAddr->sa_family = localAddress_.getFamily();

  ssize_t bytesRead = recvfrom(fd_, buf, len, MSG_TRUNC, rawAddr, &addrLen);
  if (bytesRead >= 0) {
    clientAddress_.setFromSockaddr(rawAddr, addrLen);

    if (bytesRead > 0) {
      bool truncated = false;
      if ((size_t)bytesRead > len) {
        truncated = true;
        bytesRead = ssize_t(len);
      }

      readCallback_->onDataAvailable(
          clientAddress_, size_t(bytesRead), truncated);
    }
  } else {
    if (errno == EAGAIN || errno == EWOULDBLOCK) {
      // No data could be read without blocking the socket
      return;
    }

    AsyncSocketException ex(
        AsyncSocketException::INTERNAL_ERROR, "::recvfrom() failed", errno);

    // In case of UDP we can continue reading from the socket
    // even if the current request fails. We notify the user
    // so that he can do some logging/stats collection if he wants.
    auto cob = readCallback_;
    readCallback_ = nullptr;

    cob->onReadError(ex);
    updateRegistration();
  }
}
Beispiel #17
0
/*a few lines to clean up, s*/
int ex(nodeType *p) {
    int lbl1, lbl2;
    //print assembly header
    if(i++==0) {
    	char *initialisedData = ".data # Initialised data\n\tNEWLINE: .asciz \"\\n\"\n\tMINUS: .asciz \"-\"";
    	printf(".code32\n%s\n.bss #uninitialised data\n",initialisedData);
    	puts("\t.lcomm COUNTER, 4\n\t.lcomm TEMP1, 4");
    	//print variables
    	char c;
		  for(c='a'; c<='z'; ++c)
		     printf("\t.lcomm %c,4\n",c);
			printf(".text\n.globl _start # _start on linux\n");	
			char *types="\t.type print, @function\n\t.type printNumber, @function\n";
			char* printNumber="\tprintNumber:\n\t\tmovl $0, COUNTER\n\t\tcmpl $0, %eax #is it negative number\n\t\tjge loop #if eax is greater or equal zero then go to loop\n\t\tneg %eax #change last bit to 0\n\t\tpush %eax #save eax\n\t\tpush $1\n\t\tpush $MINUS\n\t\tcall print\n\t\taddl $8, %esp #restore stack pointer for 2 arguments\n\t\tpop %eax #get back value\n\t\tloop:\n\t\t\tmovl $0, %edx #MSByte\n\t\t\tmovl $10, %ebx\n\t\t\tidiv %ebx #eax=edx:eax/ebx; # edx=edx:eax MOD ebx 13/10=1, 13 mod 10 = 3 => push 3 on stack, 1 is in eax\n\t\t\taddl $48, %edx #add 48, check ASCII, zero is 48\n\t\t\tpushl %edx\n\t\t\tincl COUNTER #increment by one\n\t\t\tcmpl $0, %eax\n\t\t\tjz   printN #if zero then we have to print otherwise loop\n\t\t\tjmp loop\n\n\t\tprintN:\n\t\t\tcmpl $0, COUNTER\n\t\t\tjz   return\n\t\t\tdecl COUNTER\n\t\t\tmovl $4, %eax\n\t\t\tmovl $1, %ebx\n\t\t\tmovl $1, %edx #how many bytes\n\t\t\tmovl %esp, %ecx #ecx should contain pointer to ascii\n\t\t\tint  $0x80\n\t\t\taddl $4, %esp #decrease stack size, get next number on stack\n\t\t\tjmp  printN\n\t\treturn:\n\t\t\tret\n";
			char* print="\n\tprint:\n\t\tmovl $4, %eax\n\t\tmovl $1, %ebx\n\t\tmovl 4(%esp), %ecx #point to first argument which is on the stack\n\t\tmovl 8(%esp), %edx #point to first argument which is on the stack\n\t\tint $0x80 # call kernel\n\t\tret #change eip to start next instruction\n";
			printf("%s%s%s",types,printNumber, print);
			printf("_start:\n");
		}
    if (!p) return 0;
    switch(p->type) {
    case typeCon:       
        printf("\tpush\t$%d\n", p->con.value); 
        break;
    case typeId:
        printf("\tpush\t%c\n", p->id.i + 'a'); 
        break;
    case typeOpr:
        switch(p->opr.oper) {
        case WHILE:
            printf("L%03d:\n", lbl1 = lbl++);
            ex(p->opr.op[0]);
            printf("\t%s\tL%03d\n",jmpType, lbl2 = lbl++);
            ex(p->opr.op[1]);
            printf("\tjmp\tL%03d\n", lbl1);
            printf("L%03d:\n", lbl2);
            break;
        case IF:
            ex(p->opr.op[0]);
            if (p->opr.nops > 2) {
                /* if else */
                printf("\t%s\tL%03d\n",jmpType, lbl1 = lbl++);
                ex(p->opr.op[1]);
                printf("\tjmp\tL%03d\n", lbl2 = lbl++);
                printf("L%03d:\n", lbl1);
                ex(p->opr.op[2]);
                printf("L%03d:\n", lbl2);
            } else {
                /* if */
                printf("\t%s\tL%03d\n",jmpType, lbl1 = lbl++);
                ex(p->opr.op[1]);
                printf("L%03d:\n", lbl1);
            }
            break;
        case PRINT:     
            ex(p->opr.op[0]);
            puts("\tpop %eax");
            printf("\tcall printNumber\n");
            //print new line
            puts("\tpush $1\n\tpush $NEWLINE\n\tcall print\n\taddl $8, %esp");
            break;
        case '=':       
            ex(p->opr.op[1]);
            printf("\tpop\t%c\n", p->opr.op[0]->id.i + 'a');
            break;
        case UMINUS:    
            ex(p->opr.op[0]);
            puts("\tpop %eax\n\tneg %eax\n\tpush %eax");
            break;
	case FACT:
  	    ex(p->opr.op[0]);
	    puts("\tcall fact\n\tpush %eax");
	    break;
	case LNTWO:
	    ex(p->opr.op[0]);
	    puts("\tcall lntwo\n\tpush %eax");
	    break;
        default:
            ex(p->opr.op[0]);
            ex(p->opr.op[1]);
            switch(p->opr.oper) {
	    case GCD:   puts("\tcall gcd\n\tpush %eax"); break;
	    			//get from the stack and save into TEMP1 then into eax and add TEMP1 to eax, push on the stack
            case '+':   puts("\tpop TEMP1\n\tpop %eax\n\tadd TEMP1, %eax\n\tpush %eax\n"); break;
            case '-':   puts("\tpop TEMP1\n\tpop %eax\n\tsub TEMP1, %eax\n\tpush %eax\n"); break;
            case '*':   puts("\tpop TEMP1\n\tpop %eax\n\timul TEMP1, %eax\n\tpush %eax\n"); break;
            case '/':   puts("\tpop TEMP1\n\tpop %eax\n\tcdq\n\tidiv TEMP1, %eax\n\tpush %eax\n"); break;
            case '<':   puts("\tpop TEMP1\n\tpop %eax\n\tcmp TEMP1,%eax"); strcpy (jmpType,"jge\0"); break;
            case '>':   puts("\tpop TEMP1\n\tpop %eax\n\tcmp TEMP1,%eax"); strcpy (jmpType,"jle\0"); break;
            case GE:    puts("\tpop TEMP1\n\tpop %eax\n\tcmp TEMP1,%eax"); strcpy (jmpType,"jl\0"); break;
            case LE:    puts("\tpop TEMP1\n\tpop %eax\n\tcmp TEMP1,%eax"); strcpy (jmpType,"jg\0"); break;
            case NE:    puts("\tpop TEMP1\n\tpop %eax\n\tcmp TEMP1,%eax"); strcpy (jmpType,"je\0"); break;
            case EQ:    puts("\tpop TEMP1\n\tpop %eax\n\tcmp TEMP1,%eax"); strcpy (jmpType,"jne\0"); break;
            }
        }
    }
    return 0;
}
Beispiel #18
0
int ex(nodeType *p) {
    if (!p) return 0;
    switch(p->type) {
    case typeIntCon:
        printf("Int constant\n");
        return p->conInt.value;
    case typeDoubleCon:
        printf("Double constant\n");
        return p->conDbl.value;
    case typeIntId:
        printf("Int variable\n");
        return sym[p->idInt.i];
    case typeDblId:
        printf("Double variable\n");
        return sym[p->idDbl.i];
    case typeOpr:
        switch(p->opr.oper) {
        case DO:
			printf("DO WHILE\n");
            do {
                ex(p->opr.op[0]);
            } while(ex(p->opr.op[1]));
            return 0;
        case WHILE:
			printf("WHILE\n");
            while(ex(p->opr.op[0])){
                ex(p->opr.op[1]);
            }
            return 0;
/* XXX UNTIL/REPEAT UNUSED FOR NOW */
        case REPEAT:    
		    printf("REPEAT UNTIL\n");
		    do {
                ex(p->opr.op[0]);
            } while(!ex(p->opr.op[1]));
            return 0;
        case IF:        if (ex(p->opr.op[0]))
                            ex(p->opr.op[1]);
                        else if (p->opr.nops > 2)
                            ex(p->opr.op[2]);
                        return 0;
        case PRINT:     printf("%d\n", ex(p->opr.op[0])); return 0;
        case ';':       ex(p->opr.op[0]); return ex(p->opr.op[1]);
        case '=':       return sym[p->opr.op[0]->idInt.i] = ex(p->opr.op[1]);
        case UMINUS:    return -ex(p->opr.op[0]);
        case '+':       return ex(p->opr.op[0]) + ex(p->opr.op[1]);
        case '-':       return ex(p->opr.op[0]) - ex(p->opr.op[1]);
        case '*':       return ex(p->opr.op[0]) * ex(p->opr.op[1]);
        case '/':       return ex(p->opr.op[0]) / ex(p->opr.op[1]);
        case '<':       return ex(p->opr.op[0]) < ex(p->opr.op[1]);
        case '>':       return ex(p->opr.op[0]) > ex(p->opr.op[1]);
        case GE:        return ex(p->opr.op[0]) >= ex(p->opr.op[1]);
        case LE:        return ex(p->opr.op[0]) <= ex(p->opr.op[1]);
        case NE:        return ex(p->opr.op[0]) != ex(p->opr.op[1]);
        case EQ:        return ex(p->opr.op[0]) == ex(p->opr.op[1]);
        }
    }
    return 0;
}
Beispiel #19
0
void XBPyThread::stop()
{
  CSingleLock lock(m_pExecuter->m_critSection);
  if(m_stopping)
    return;

  m_stopping = true;

  if (m_threadState)
  {
    PyEval_AcquireLock();
    PyThreadState* old = PyThreadState_Swap((PyThreadState*)m_threadState);

    //tell xbmc.Monitor to call onAbortRequested()
    if (addon)
      g_pythonParser.OnAbortRequested(addon->ID());

    PyObject *m;
    m = PyImport_AddModule((char*)"xbmc");
    if(!m || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1)))
      CLog::Log(LOGERROR, "XBPyThread::stop - failed to set abortRequested");

    PyThreadState_Swap(old);
    old = NULL;
    PyEval_ReleaseLock();

    XbmcThreads::EndTime timeout(PYTHON_SCRIPT_TIMEOUT);
    while (!stoppedEvent.WaitMSec(15))
    {
      if (timeout.IsTimePast())
      {
        CLog::Log(LOGERROR, "XBPyThread::stop - script didn't stop in %d seconds - let's kill it", PYTHON_SCRIPT_TIMEOUT / 1000);
        break;
      }
      // We can't empty-spin in the main thread and expect scripts to be able to
      // dismantle themselves. Python dialogs aren't normal XBMC dialogs, they rely
      // on TMSG_GUI_PYTHON_DIALOG messages, so pump the message loop.
      if (g_application.IsCurrentThread())
      {
        CSingleExit ex(g_graphicsContext);
        CApplicationMessenger::Get().ProcessMessages();
      }
    }
    // Useful for add-on performance metrics
    if (!timeout.IsTimePast())
      CLog::Log(LOGDEBUG, "XBPyThread::stop - script termination took %dms", PYTHON_SCRIPT_TIMEOUT - timeout.MillisLeft());
    
    //everything which didn't exit by now gets killed
    {
      // grabbing the PyLock while holding the XBPython m_critSection is asking for a deadlock
      CSingleExit ex2(m_pExecuter->m_critSection);
      PyEval_AcquireLock();
    }

    // since we released the XBPython m_critSection it's possible that the state is cleaned up 
    // so we need to recheck for m_threadState == NULL
    if (m_threadState)
    {
      old = PyThreadState_Swap((PyThreadState*)m_threadState);    
      for(PyThreadState* state = ((PyThreadState*)m_threadState)->interp->tstate_head; state; state = state->next)
      {
        // Raise a SystemExit exception in python threads
        Py_XDECREF(state->async_exc);
        state->async_exc = PyExc_SystemExit;
        Py_XINCREF(state->async_exc);
      }

      // If a dialog entered its doModal(), we need to wake it to see the exception
      g_pythonParser.PulseGlobalEvent();

    }

    if (old != NULL)
      PyThreadState_Swap(old);

    lock.Leave();
    PyEval_ReleaseLock();
  }
}
std::vector<cv::Point2f> getChessboardCorners(
        cv::VideoCapture &capture,
        const std::vector<cv::Mat> &rectificationMaps,
        const int &horizon, const int &deadZone,
        const cv::Size &boardSize, const cv::Size &imageSize,
        const cv::Size &winSize, const cv::Size &zeroZone,
        const cv::TermCriteria &termCriteria) {
    cv::Mat newIn;
    cv::Mat undistorted;
    cv::Mat greyNewIn;
    cv::Mat ground;

    cv::Rect lowerRoi(cv::Point2f(0, horizon + deadZone),
            cv::Size(imageSize.width,
                    imageSize.height - horizon - deadZone));
    bool found = false;
    std::vector<cv::Point2f> corners;
    cv::namedWindow("ground", CV_WINDOW_NORMAL);
    char control = ' ';
    cv::Mat resizing;
    do {
        capture >> newIn;
        if (!newIn.empty()) {
            cv::resize(newIn, resizing, imageSize);
            cv::remap(resizing, undistorted, rectificationMaps[0],
                    rectificationMaps[1], cv::INTER_LINEAR);
            cv::cvtColor(undistorted, greyNewIn, CV_RGB2GRAY);
            ground = greyNewIn(lowerRoi);
            found = cv::findChessboardCorners(ground, boardSize,
                    corners,
                    CV_CALIB_CB_FAST_CHECK
                            | CV_CALIB_CB_ADAPTIVE_THRESH
                            | CV_CALIB_CB_NORMALIZE_IMAGE);
            if (corners.size() > 0) {
                drawChessboardCorners(undistorted(lowerRoi),
                        boardSize, corners, found);
                drawChessboardCorners(ground, boardSize, corners,
                        found);
                std::cerr << corners.size() << std::endl;
            }
            drawDeadZoneHorizon(undistorted, horizon, deadZone);
            imshow("ground", ground);
            imshow("main", undistorted);
        }
        control = cv::waitKey(1);
    } while (!found && 'q' != control);

    if ('q' == control) {
        cv::Exception ex(USER_TRIGGERED_EXIT, "user requested exit",
                __func__, __FILE__, __LINE__);
        throw ex;
    }
    cv::cornerSubPix(ground, corners, winSize, zeroZone,
            termCriteria);
    cv::imwrite("chessboard.jpeg", undistorted);
    cv::drawChessboardCorners(undistorted(lowerRoi), boardSize,
            corners, found);
    cv::imshow("main", undistorted);

    cv::destroyWindow("ground");
    cv::destroyWindow("main");

    return corners;
}
Beispiel #21
0
void MagCal::calcMagComp()
{
    /*
     * Inspired by
     * http://davidegironi.blogspot.it/2013/01/magnetometer-calibration-helper-01-for.html#.UriTqkMjulM
     *
     * Ellipsoid fit from:
     * http://www.mathworks.com/matlabcentral/fileexchange/24693-ellipsoid-fit
     *
     * To use Eigen to convert matlab code, have a look at Eigen/AsciiQuickReference.txt
     */

    if (mMagSamples.size() < 9) {
        QMessageBox::warning(this, "Magnetometer compensation",
                             "Too few points.");
        return;
    }

    int samples = mMagSamples.size();
    Eigen::VectorXd ex(samples);
    Eigen::VectorXd ey(samples);
    Eigen::VectorXd ez(samples);

    for (int i = 0;i < samples;i++) {
        ex(i) = mMagSamples.at(i).at(0);
        ey(i) = mMagSamples.at(i).at(1);
        ez(i) = mMagSamples.at(i).at(2);
    }

    Eigen::MatrixXd eD(samples, 9);

    for (int i = 0;i < samples;i++) {
        eD(i, 0) = ex(i) * ex(i);
        eD(i, 1) = ey(i) * ey(i);
        eD(i, 2) = ez(i) * ez(i);
        eD(i, 3) = 2.0 * ex(i) * ey(i);
        eD(i, 4) = 2.0 * ex(i) * ez(i);
        eD(i, 5) = 2.0 * ey(i) * ez(i);
        eD(i, 6) = 2.0 * ex(i);
        eD(i, 7) = 2.0 * ey(i);
        eD(i, 8) = 2.0 * ez(i);
    }

    Eigen::MatrixXd etmp1 = eD.transpose() * eD;
    Eigen::MatrixXd etmp2 = eD.transpose() * Eigen::MatrixXd::Ones(samples, 1);
    Eigen::VectorXd eV = etmp1.lu().solve(etmp2);

    Eigen::MatrixXd eA(4, 4);
    eA(0,0)=eV(0);   eA(0,1)=eV(3);   eA(0,2)=eV(4);   eA(0,3)=eV(6);
    eA(1,0)=eV(3);   eA(1,1)=eV(1);   eA(1,2)=eV(5);   eA(1,3)=eV(7);
    eA(2,0)=eV(4);   eA(2,1)=eV(5);   eA(2,2)=eV(2);   eA(2,3)=eV(8);
    eA(3,0)=eV(6);   eA(3,1)=eV(7);   eA(3,2)=eV(8);   eA(3,3)=-1.0;

    Eigen::MatrixXd eCenter = -eA.topLeftCorner(3, 3).lu().solve(eV.segment(6, 3));
    Eigen::MatrixXd eT = Eigen::MatrixXd::Identity(4, 4);
    eT(3, 0) = eCenter(0);
    eT(3, 1) = eCenter(1);
    eT(3, 2) = eCenter(2);

    Eigen::MatrixXd eR = eT * eA * eT.transpose();

    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eEv(eR.topLeftCorner(3, 3) * (-1.0 / eR(3, 3)));
    Eigen::MatrixXd eVecs = eEv.eigenvectors();
    Eigen::MatrixXd eVals = eEv.eigenvalues();

    Eigen::MatrixXd eRadii(3, 1);
    eRadii(0) = sqrt(1.0 / eVals(0));
    eRadii(1) = sqrt(1.0 / eVals(1));
    eRadii(2) = sqrt(1.0 / eVals(2));

    Eigen::MatrixXd eScale = eRadii.asDiagonal().inverse() * eRadii.minCoeff();
    Eigen::MatrixXd eComp = eVecs * eScale * eVecs.transpose();

    mMagComp.resize(9);
    mMagComp[0] = eComp(0, 0);
    mMagComp[1] = eComp(0, 1);
    mMagComp[2] = eComp(0, 2);

    mMagComp[3] = eComp(1, 0);
    mMagComp[4] = eComp(1, 1);
    mMagComp[5] = eComp(1, 2);

    mMagComp[6] = eComp(2, 0);
    mMagComp[7] = eComp(2, 1);
    mMagComp[8] = eComp(2, 2);

    mMagCompCenter.resize(3);
    mMagCompCenter[0] = eCenter(0, 0);
    mMagCompCenter[1] = eCenter(1, 0);
    mMagCompCenter[2] = eCenter(2, 0);

    QVector<double> magX, magY, magZ;

    for (int i = 0;i < mMagSamples.size();i++) {
        double mx = mMagSamples.at(i).at(0);
        double my = mMagSamples.at(i).at(1);
        double mz = mMagSamples.at(i).at(2);

        mx -= mMagCompCenter.at(0);
        my -= mMagCompCenter.at(1);
        mz -= mMagCompCenter.at(2);

        magX.append(mx * mMagComp.at(0) + my * mMagComp.at(1) + mz * mMagComp.at(2));
        magY.append(mx * mMagComp.at(3) + my * mMagComp.at(4) + mz * mMagComp.at(5));
        magZ.append(mx * mMagComp.at(6) + my * mMagComp.at(7) + mz * mMagComp.at(8));
    }

    ui->magSampXyPlot->graph(1)->setData(magX, magY);
    ui->magSampXzPlot->graph(1)->setData(magX, magZ);
    ui->magSampYzPlot->graph(1)->setData(magY, magZ);

    updateMagPlots();
}
Beispiel #22
0
uint32_t HTTPClientChannel::sendRequest(
    RpcOptions& rpcOptions,
    std::unique_ptr<RequestCallback> cb,
    std::unique_ptr<apache::thrift::ContextStack> ctx,
    unique_ptr<IOBuf> buf,
    std::shared_ptr<THeader> header) {
  // cb is not allowed to be null.
  DCHECK(cb);

  DestructorGuard dg(this);

  cb->context_ = RequestContext::saveContext();

  std::chrono::milliseconds timeout(timeout_);
  if (rpcOptions.getTimeout() > std::chrono::milliseconds(0)) {
    timeout = rpcOptions.getTimeout();
  }

  auto twcb =
      new HTTPTransactionTwowayCallback(std::move(cb),
                                        std::move(ctx),
                                        isSecurityActive(),
                                        protocolId_,
                                        timer_.get(),
                                        std::chrono::milliseconds(timeout_));

  if (!httpSession_) {
    TTransportException ex(TTransportException::NOT_OPEN,
                           "HTTPSession is not open");
    twcb->messageSendError(
        folly::make_exception_wrapper<TTransportException>(std::move(ex)));

    delete twcb;

    return -1;
  }

  auto txn = httpSession_->newTransaction(twcb);

  if (!txn) {
    TTransportException ex(TTransportException::NOT_OPEN,
                            "Too many active requests on connection");
    // Might be able to create another transaction soon
    ex.setOptions(TTransportException::CHANNEL_IS_VALID);
    twcb->messageSendError(
        folly::make_exception_wrapper<TTransportException>(std::move(ex)));

    delete twcb;

    return -1;
  }

  auto streamId = txn->getID();

  setRequestHeaderOptions(header.get());
  addRpcOptionHeaders(header.get(), rpcOptions);

  auto msg = buildHTTPMessage(header.get());

  txn->sendHeaders(msg);
  txn->sendBody(std::move(buf));
  txn->sendEOM();

  twcb->sendQueued();

  return (uint32_t)streamId;
}
bool AdobeThumbnail(const char* adobe_filename , const char* savejpeg_filename)
{
    string file_ext(adobe_filename);
    string rs = "(.+)(\\.(?:ai|AI|indd|INDD|Indd|eps|EPS|Eps))";  // 正则字符串,exp开始的单词
    std::regex expression(rs);                   // 字符串传递给构造函数,建立正则表达式
    bool ret = std::regex_match(file_ext, expression);
    if (!ret) {
        //      cout << "文件格式不对!\n";
        return ret ;
    }

    if (!IsFileExist(adobe_filename))
        return false ;     // 文件不存在


    char* pch = NULL;
    const char* flag = "pGImg:image";  // AI 和 Indd 稍微不同

    /// ************* 获取 ID或者AI文档 的预览图 **************** ///
    FILE* adobe_file = fopen(adobe_filename, "rb");
    size_t file_size = get_fileSize(adobe_filename); // 获得文件大小

    size_t bufsize = 1 * MBsize;        // AI 和EPS 预览图在开头,INDD文件在末位
    char* filebuf = new char[bufsize];  // 文件读到缓冲

    //  文件小于2M 整个文件读,否则遍历读最后2M
    if (file_size < bufsize) {
        bufsize = file_size;
        fread(filebuf, 1, bufsize, adobe_file);
        if (0xF5ED0606 == *(DWORD*)filebuf) { // indd 文件开头好像都这样
            pch = memfind(filebuf, flag , bufsize);   // INDD 可能不只一个预览图
            if ((pch != NULL))
                while ((pch != NULL) && (strlen(pch) < 10 * 1024))
                    pch = memfind(pch + 1, flag , bufsize - (pch - filebuf));

        } else
            pch = memfind(filebuf, flag , bufsize);

    } else {
        fread(filebuf, 1, bufsize, adobe_file);
//        00000000h: 06 06 ED F5 D8 1D 46 E5 BD 31 EF E7 FE 74 B7 1D ; ..眭?F褰1镧?
//        00000010h: 44 4F 43 55 4D 45 4E 54 01 70 0F 00 00 05 00 00 ; DOCUMENT.p......
        if (0xF5ED0606 == *(DWORD*)filebuf) { // indd 文件开头好像都这样
            fseek(adobe_file, (file_size - bufsize), SEEK_SET);
            fread(filebuf, 1, bufsize, adobe_file);

            pch = memfind(filebuf, flag , bufsize);   // INDD 可能不只一个预览图
            if ((pch != NULL))
                while ((pch != NULL) && (strlen(pch) < 10 * 1024))
                    pch = memfind(pch + 1, flag , bufsize - (pch - filebuf));

        } else
            pch = memfind(filebuf, flag , bufsize);   // AI 应该只有一个预览信息,
    }
    // 读取文件结束,关闭
    fclose(adobe_file);

    if (pch == NULL) {
        flag = "%AI7_Thumbnail:";
        size_t width, height, bitCount, Hexsize;
        char AI7_Thumbnail[64]; char BeginData[64]; char Hex_Bytes[64];

        pch = memfind(filebuf, flag , bufsize);
        // 检测到AI低版本预览图标记
        if (pch != NULL) {
            sscanf(pch, "%s %d %d %d\n%s %d %s\n", AI7_Thumbnail, &width, &height, &bitCount , BeginData, &Hexsize , Hex_Bytes);

            pch = memfind(filebuf, "Hex Bytes" , bufsize);
        }

        if (pch != NULL) {  // 解码 AI7_Thumbnail 为 图片
            char savepng_filename[MAX_PATH]={0};    // 源图是 BMP,保存png 失真少一点
            strncpy(savepng_filename , savejpeg_filename, strlen(savejpeg_filename) - 4);
            strcat(savepng_filename, ".png");

            string AI7Thumb(pch + 10 , Hexsize + 1);
            decode_Ai7Thumb_toPng(AI7Thumb , width, height , savepng_filename);
            delete[] filebuf; // 释放文件缓冲
            return true;
        }
    };

    if (pch == NULL)   ret = false;
    if (!ret) {  // 没有找到,返回前
        delete[] filebuf; // 释放文件缓冲
        return ret;
    }


    strtok(pch, "\r\n");
    string Base64_str(pch);

    std::regex ex("pGImg:image>|<\\/x\\wpGImg:image>|pGImg:image=\"");
    std::regex en("&#xA;");
    // 正则删除 xmpGImg 标记和 转意换行替换回来
    Base64_str = std::regex_replace(Base64_str, ex, string(""));
    Base64_str = std::regex_replace(Base64_str, en, string("\n"));

#if(AITEST)
        printf( "pGImg:image标记偏移: %d 在文件%s\n" , pch - filebuf , adobe_filename);
#endif
/// =============================== 解码一个Base64 的JPEG文件 ==============================////

    int b64len = Base64_str.size();
    int jpglen = fromBase64_Decode(Base64_str.c_str() , b64len , filebuf , b64len);

    FILE* jpeg_file = fopen(savejpeg_filename, "wb");
    fwrite(filebuf, 1 , jpglen , jpeg_file);


    delete[] filebuf; // 释放文件缓冲

    fclose(jpeg_file);

    return true;
}
Beispiel #24
0
int
ORBTask::svc (void)
{
    // initialize logging
    if (m_logger)
      {
	LoggingProxy::init(m_logger);
	LoggingProxy::ThreadName("ORBTask");
      }

    
    try
      {

        // handle CORBA requests 
	if (m_timeToRun == 0)
	  {
	    this->m_orb->run ();
	    
	  }
	else
	  {
	    ACE_Time_Value tv (m_timeToRun);
	    this->m_orb->run (tv);
	    
	  }


      }
    catch( CORBA::SystemException &ex ) 
	{
	ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__,
							    "acsdaemon::ORBTask::svc");
	corbaProblemEx.setMinor(ex.minor());
	corbaProblemEx.setCompletionStatus(ex.completed());
	corbaProblemEx.setInfo(ex._info().c_str());
	
	corbaProblemEx.log();
	return 1;
	}
    catch( CORBA::Exception &ex )
      {
      ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__,
							    "acsdaemon::ORBTask::svc");
      corbaProblemEx.setInfo(ex._info().c_str());
      corbaProblemEx.log();
      return 1;
      }
    catch(ACSErr::ACSbaseExImpl &_ex)
	{
	
	ACSErrTypeCommon::UnexpectedExceptionExImpl ex(_ex, __FILE__, __LINE__,
						       "acsdaemon::ORBTask::svc");
	ex.log();
	return 1;
	}
    catch(...)
	{
	ACSErrTypeCommon::UnexpectedExceptionExImpl ex(__FILE__, __LINE__,
						       "acsdaemon::ORBTask::svc");
	ex.log();
	return 1;
	}//try-catch

  // return error free code
  return 0;
}
Beispiel #25
0
void CRemoteControl::Update()
{
  if (!m_bInitialized || !m_used )
    return;

  if (!CheckDevice())
    return;

  uint32_t now = XbmcThreads::SystemClockMillis();

  char buf[128];
  // Read a line from the socket
  while (true)
  {
    {
      CSingleLock lock(m_CS);
      if (fgets(buf, sizeof(buf), m_file) == NULL)
        break;
    }

    // Remove the \n
    buf[strlen(buf)-1] = '\0';

    // Parse the result. Sample line:
    // 000000037ff07bdd 00 OK mceusb
    char scanCode[128];
    char buttonName[128];
    char repeatStr[4];
    char deviceName[128];
    sscanf(buf, "%s %s %s %s", &scanCode[0], &repeatStr[0], &buttonName[0], &deviceName[0]);

    //beginning of lirc reply packet
    //we get one when lirc is done sending something
    if (!m_inReply && strcmp("BEGIN", scanCode) == 0)
    {
      m_inReply = true;
      continue;
    }
    else if (m_inReply && strcmp("END", scanCode) == 0) //end of lirc reply packet
    {
      m_inReply = false;
      if (m_nrSending > 0)
        m_nrSending--;
      continue;
    }

    if (m_inReply)
      continue;

    // Some template LIRC configuration have button names in apostrophes or quotes.
    // If we got a quoted button name, strip 'em
    unsigned int buttonNameLen = strlen(buttonName);
    if ( buttonNameLen > 2
    && ( (buttonName[0] == '\'' && buttonName[buttonNameLen-1] == '\'')
         || ((buttonName[0] == '"' && buttonName[buttonNameLen-1] == '"') ) ) )
    {
      memmove( buttonName, buttonName + 1, buttonNameLen - 2 );
      buttonName[ buttonNameLen - 2 ] = '\0';
    }

    m_button = CServiceBroker::GetInputManager().TranslateLircRemoteString(deviceName, buttonName);

    char *end = NULL;
    long repeat = strtol(repeatStr, &end, 16);
    if (!end || *end != 0)
      CLog::Log(LOGERROR, "LIRC: invalid non-numeric character in expression %s", repeatStr);
    if (repeat == 0)
    {
      CLog::Log(LOGDEBUG, "LIRC: %s - NEW at %d:%s (%s)", __FUNCTION__, now, buf, buttonName);
      m_firstClickTime = now;
      m_holdTime = 0;
      return;
    }
    else if (repeat > g_advancedSettings.m_remoteDelay)
    {
      m_holdTime = now - m_firstClickTime;
    }
    else
    {
      m_holdTime = 0;
      m_button = 0;
    }
  }

  //drop commands when already sending
  //because keypresses come in faster than lirc can send we risk hammering the daemon with commands
  CSingleLock lock(m_CS);

  if (m_nrSending > 0)
  {
    m_sendData.clear();
  }
  else if (!m_sendData.empty())
  {
    fputs(m_sendData.c_str(), m_file);
    fflush(m_file);

    //nr of newlines equals nr of commands
    for (int i = 0; i < (int)m_sendData.size(); i++)
      if (m_sendData[i] == '\n')
        m_nrSending++;

    m_sendData.clear();
  }

  if (feof(m_file) != 0)
  {
    CSingleExit ex(m_CS); //Disconnect takes the lock
    Disconnect();
  }
}
Beispiel #26
0
int ex(nodeType *p) {
    int lbl1, lbl2;

    if (!p) return 0;
    switch(p->type) {
    case typeCon:       
        printf("\tpush\t%d\n", p->con.value); 
        break;
    case typeId:        
        printf("\tpush\t%c\n", p->id.i + 'a'); 
        break;
    case typeOpr:
        switch(p->opr.oper) {
        case WHILE:
            printf("L%03d:\n", lbl1 = lbl++);
            ex(p->opr.op[0]);
            printf("\tjz\tL%03d\n", lbl2 = lbl++);
            ex(p->opr.op[1]);
            printf("\tjmp\tL%03d\n", lbl1);
            printf("L%03d:\n", lbl2);
            break;
        case IF:
            ex(p->opr.op[0]);
            if (p->opr.nops > 2) {
                /* if else */
                printf("\tjz\tL%03d\n", lbl1 = lbl++);
                ex(p->opr.op[1]);
                printf("\tjmp\tL%03d\n", lbl2 = lbl++);
                printf("L%03d:\n", lbl1);
                ex(p->opr.op[2]);
                printf("L%03d:\n", lbl2);
            } else {
                /* if */
                printf("\tjz\tL%03d\n", lbl1 = lbl++);
                ex(p->opr.op[1]);
                printf("L%03d:\n", lbl1);
            }
            break;
        case PRINT:     
            ex(p->opr.op[0]);
            printf("\tprint\n");
            break;
        case '=':       
            ex(p->opr.op[1]);
            printf("\tpop\t%c\n", p->opr.op[0]->id.i + 'a');
            break;
        case UMINUS:    
            ex(p->opr.op[0]);
            printf("\tneg\n");
            break;
        default:
            ex(p->opr.op[0]);
            ex(p->opr.op[1]);
            switch(p->opr.oper) {
            case '+':   printf("\tadd\n"); break;
            case '-':   printf("\tsub\n"); break; 
            case '*':   printf("\tmul\n"); break;
            case '/':   printf("\tdiv\n"); break;
            case '<':   printf("\tcompLT\n"); break;
            case '>':   printf("\tcompGT\n"); break;
            case GE:    printf("\tcompGE\n"); break;
            case LE:    printf("\tcompLE\n"); break;
            case NE:    printf("\tcompNE\n"); break;
            case EQ:    printf("\tcompEQ\n"); break;
            }
        }
    }
    return 0;
}
int main(int, char**)
{
    std::ios ios(0);
    std::string loc_name(LOCALE_en_US_UTF_8);
    ios.imbue(std::locale(ios.getloc(),
                          new std::moneypunct_byname<char, false>(loc_name)));
    ios.imbue(std::locale(ios.getloc(),
                          new std::moneypunct_byname<char, true>(loc_name)));
    ios.imbue(std::locale(ios.getloc(),
                          new std::moneypunct_byname<wchar_t, false>(loc_name)));
    ios.imbue(std::locale(ios.getloc(),
                          new std::moneypunct_byname<wchar_t, true>(loc_name)));
{
    const my_facet f(1);
    // char, national
    {   // zero
        long double v = 0;
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0.00");
    }
    {   // negative one
        long double v = -1;
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "-0.01");
    }
    {   // positive
        long double v = 123456789;
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "1,234,567.89");
    }
    {   // negative
        long double v = -123456789;
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "-1,234,567.89");
    }
    {   // zero, showbase
        long double v = 0;
        showbase(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "$0.00");
    }
    {   // negative one, showbase
        long double v = -1;
        showbase(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "-$0.01");
    }
    {   // positive, showbase
        long double v = 123456789;
        showbase(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "$1,234,567.89");
    }
    {   // negative, showbase
        long double v = -123456789;
        showbase(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "-$1,234,567.89");
    }
    {   // negative, showbase, left
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        left(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, ' ', v);
        std::string ex(str, iter.base());
        assert(ex == "-$1,234,567.89      ");
        assert(ios.width() == 0);
    }
    {   // negative, showbase, internal
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        internal(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, ' ', v);
        std::string ex(str, iter.base());
        assert(ex == "-$      1,234,567.89");
        assert(ios.width() == 0);
    }
    {   // negative, showbase, right
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        right(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            false, ios, ' ', v);
        std::string ex(str, iter.base());
        assert(ex == "      -$1,234,567.89");
        assert(ios.width() == 0);
    }

    // char, international
    noshowbase(ios);
    ios.unsetf(std::ios_base::adjustfield);
    {   // zero
        long double v = 0;
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "0.00");
    }
    {   // negative one
        long double v = -1;
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "-0.01");
    }
    {   // positive
        long double v = 123456789;
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "1,234,567.89");
    }
    {   // negative
        long double v = -123456789;
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "-1,234,567.89");
    }
    {   // zero, showbase
        long double v = 0;
        showbase(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "USD 0.00");
    }
    {   // negative one, showbase
        long double v = -1;
        showbase(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "-USD 0.01");
    }
    {   // positive, showbase
        long double v = 123456789;
        showbase(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "USD 1,234,567.89");
    }
    {   // negative, showbase
        long double v = -123456789;
        showbase(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, '*', v);
        std::string ex(str, iter.base());
        assert(ex == "-USD 1,234,567.89");
    }
    {   // negative, showbase, left
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        left(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, ' ', v);
        std::string ex(str, iter.base());
        assert(ex == "-USD 1,234,567.89   ");
        assert(ios.width() == 0);
    }
    {   // negative, showbase, internal
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        internal(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, ' ', v);
        std::string ex(str, iter.base());
        assert(ex == "-USD    1,234,567.89");
        assert(ios.width() == 0);
    }
    {   // negative, showbase, right
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        right(ios);
        char str[100];
        output_iterator<char*> iter = f.put(output_iterator<char*>(str),
                                            true, ios, ' ', v);
        std::string ex(str, iter.base());
        assert(ex == "   -USD 1,234,567.89");
        assert(ios.width() == 0);
    }
}
{

    const my_facetw f(1);
    // wchar_t, national
    noshowbase(ios);
    ios.unsetf(std::ios_base::adjustfield);
    {   // zero
        long double v = 0;
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"0.00");
    }
    {   // negative one
        long double v = -1;
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-0.01");
    }
    {   // positive
        long double v = 123456789;
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"1,234,567.89");
    }
    {   // negative
        long double v = -123456789;
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-1,234,567.89");
    }
    {   // zero, showbase
        long double v = 0;
        showbase(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"$0.00");
    }
    {   // negative one, showbase
        long double v = -1;
        showbase(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-$0.01");
    }
    {   // positive, showbase
        long double v = 123456789;
        showbase(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"$1,234,567.89");
    }
    {   // negative, showbase
        long double v = -123456789;
        showbase(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-$1,234,567.89");
    }
    {   // negative, showbase, left
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        left(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, ' ', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-$1,234,567.89      ");
        assert(ios.width() == 0);
    }
    {   // negative, showbase, internal
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        internal(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, ' ', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-$      1,234,567.89");
        assert(ios.width() == 0);
    }
    {   // negative, showbase, right
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        right(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            false, ios, ' ', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"      -$1,234,567.89");
        assert(ios.width() == 0);
    }

    // wchar_t, international
    noshowbase(ios);
    ios.unsetf(std::ios_base::adjustfield);
    {   // zero
        long double v = 0;
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"0.00");
    }
    {   // negative one
        long double v = -1;
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-0.01");
    }
    {   // positive
        long double v = 123456789;
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"1,234,567.89");
    }
    {   // negative
        long double v = -123456789;
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-1,234,567.89");
    }
    {   // zero, showbase
        long double v = 0;
        showbase(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"USD 0.00");
    }
    {   // negative one, showbase
        long double v = -1;
        showbase(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-USD 0.01");
    }
    {   // positive, showbase
        long double v = 123456789;
        showbase(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"USD 1,234,567.89");
    }
    {   // negative, showbase
        long double v = -123456789;
        showbase(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, '*', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-USD 1,234,567.89");
    }
    {   // negative, showbase, left
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        left(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, ' ', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-USD 1,234,567.89   ");
        assert(ios.width() == 0);
    }
    {   // negative, showbase, internal
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        internal(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, ' ', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"-USD    1,234,567.89");
        assert(ios.width() == 0);
    }
    {   // negative, showbase, right
        long double v = -123456789;
        showbase(ios);
        ios.width(20);
        right(ios);
        wchar_t str[100];
        output_iterator<wchar_t*> iter = f.put(output_iterator<wchar_t*>(str),
                                            true, ios, ' ', v);
        std::wstring ex(str, iter.base());
        assert(ex == L"   -USD 1,234,567.89");
        assert(ios.width() == 0);
    }
}

  return 0;
}
Beispiel #28
0
/*
 * editor --
 *	Main editor routine.
 *
 * PUBLIC: int editor __P((GS *, int, char *[]));
 */
int
editor(
	GS *gp,
	int argc,
	char *argv[])
{
	extern int optind;
	extern char *optarg;
	const char *p;
	EVENT ev;
	FREF *frp;
	SCR *sp;
	size_t len;
	u_int flags;
	int ch, flagchk, lflag, secure, startup, readonly, rval, silent;
	char *tag_f, *wsizearg, path[256];
	CHAR_T *w;
	size_t wlen;

	/* Initialize the busy routine, if not defined by the screen. */
	if (gp->scr_busy == NULL)
		gp->scr_busy = vs_busy;
	/* Initialize the message routine, if not defined by the screen. */
	if (gp->scr_msg == NULL)
		gp->scr_msg = vs_msg;
	gp->catd = (nl_catd)-1;

	/* Common global structure initialization. */
	TAILQ_INIT(gp->dq);
	TAILQ_INIT(gp->hq);
	SLIST_INIT(gp->ecq);
	SLIST_INSERT_HEAD(gp->ecq, &gp->excmd, q);
	gp->noprint = DEFAULT_NOPRINT;

	/* Structures shared by screens so stored in the GS structure. */
	TAILQ_INIT(gp->frefq);
	TAILQ_INIT(gp->dcb_store.textq);
	SLIST_INIT(gp->cutq);
	SLIST_INIT(gp->seqq);

	/* Set initial screen type and mode based on the program name. */
	readonly = 0;
	if (!strcmp(gp->progname, "ex") || !strcmp(gp->progname, "nex"))
		LF_INIT(SC_EX);
	else {
		/* Nview, view are readonly. */
		if (!strcmp(gp->progname, "nview") ||
		    !strcmp(gp->progname, "view"))
			readonly = 1;
		
		/* Vi is the default. */
		LF_INIT(SC_VI);
	}

	/* Convert old-style arguments into new-style ones. */
	if (v_obsolete(gp->progname, argv))
		return (1);

	/* Parse the arguments. */
	flagchk = '\0';
	tag_f = wsizearg = NULL;
	lflag = secure = silent = 0;
	startup = 1;

	/* Set the file snapshot flag. */
	F_SET(gp, G_SNAPSHOT);

#ifdef DEBUG
	while ((ch = getopt(argc, argv, "c:D:eFlRrSsT:t:vw:")) != EOF)
#else
	while ((ch = getopt(argc, argv, "c:eFlRrSst:vw:")) != EOF)
#endif
		switch (ch) {
		case 'c':		/* Run the command. */
			/*
			 * XXX
			 * We should support multiple -c options.
			 */
			if (gp->c_option != NULL) {
				v_estr(gp->progname, 0,
				    "only one -c command may be specified.");
				return (1);
			}
			gp->c_option = optarg;
			break;
#ifdef DEBUG
		case 'D':
			switch (optarg[0]) {
			case 's':
				startup = 0;
				break;
			case 'w':
				attach(gp);
				break;
			default:
				v_estr(gp->progname, 0,
				    "usage: -D requires s or w argument.");
				return (1);
			}
			break;
#endif
		case 'e':		/* Ex mode. */
			LF_CLR(SC_VI);
			LF_SET(SC_EX);
			break;
		case 'F':		/* No snapshot. */
			F_CLR(gp, G_SNAPSHOT);
			break;
		case 'l':		/* Set lisp, showmatch options. */
			lflag = 1;
			break;
		case 'R':		/* Readonly. */
			readonly = 1;
			break;
		case 'r':		/* Recover. */
			if (flagchk == 't') {
				v_estr(gp->progname, 0,
				    "only one of -r and -t may be specified.");
				return (1);
			}
			flagchk = 'r';
			break;
		case 'S':
			secure = 1;
			break;
		case 's':
			silent = 1;
			break;
#ifdef DEBUG
		case 'T':		/* Trace. */
			if ((gp->tracefp = fopen(optarg, "w")) == NULL) {
				v_estr(gp->progname, errno, optarg);
				goto err;
			}
			(void)fprintf(gp->tracefp,
			    "\n===\ntrace: open %s\n", optarg);
			break;
#endif
		case 't':		/* Tag. */
			if (flagchk == 'r') {
				v_estr(gp->progname, 0,
				    "only one of -r and -t may be specified.");
				return (1);
			}
			if (flagchk == 't') {
				v_estr(gp->progname, 0,
				    "only one tag file may be specified.");
				return (1);
			}
			flagchk = 't';
			tag_f = optarg;
			break;
		case 'v':		/* Vi mode. */
			LF_CLR(SC_EX);
			LF_SET(SC_VI);
			break;
		case 'w':
			wsizearg = optarg;
			break;
		case '?':
		default:
			(void)gp->scr_usage();
			return (1);
		}
	argc -= optind;
	argv += optind;

	/*
	 * -s option is only meaningful to ex.
	 *
	 * If not reading from a terminal, it's like -s was specified.
	 */
	if (silent && !LF_ISSET(SC_EX)) {
		v_estr(gp->progname, 0, "-s option is only applicable to ex.");
		goto err;
	}
	if (LF_ISSET(SC_EX) && F_ISSET(gp, G_SCRIPTED))
		silent = 1;

	/*
	 * Build and initialize the first/current screen.  This is a bit
	 * tricky.  If an error is returned, we may or may not have a
	 * screen structure.  If we have a screen structure, put it on a
	 * display queue so that the error messages get displayed.
	 *
	 * !!!
	 * Everything we do until we go interactive is done in ex mode.
	 */
	if (screen_init(gp, NULL, &sp)) {
		if (sp != NULL)
			TAILQ_INSERT_HEAD(gp->dq, sp, q);
		goto err;
	}
	F_SET(sp, SC_EX);
	TAILQ_INSERT_HEAD(gp->dq, sp, q);

	if (v_key_init(sp))		/* Special key initialization. */
		goto err;

	{ int oargs[5], *oargp = oargs;
	if (lflag) {			/* Command-line options. */
		*oargp++ = O_LISP;
		*oargp++ = O_SHOWMATCH;
	}
	if (readonly)
		*oargp++ = O_READONLY;
	if (secure)
		*oargp++ = O_SECURE;
	*oargp = -1;			/* Options initialization. */
	if (opts_init(sp, oargs))
		goto err;
	}
	if (wsizearg != NULL) {
		ARGS *av[2], a, b;
		(void)snprintf(path, sizeof(path), "window=%s", wsizearg);
		a.bp = (CHAR_T *)path;
		a.len = strlen(path);
		b.bp = NULL;
		b.len = 0;
		av[0] = &a;
		av[1] = &b;
		(void)opts_set(sp, av, NULL);
	}
	if (silent) {			/* Ex batch mode option values. */
		O_CLR(sp, O_AUTOPRINT);
		O_CLR(sp, O_PROMPT);
		O_CLR(sp, O_VERBOSE);
		O_CLR(sp, O_WARN);
		F_SET(sp, SC_EX_SILENT);
	}

	sp->rows = O_VAL(sp, O_LINES);	/* Make ex formatting work. */
	sp->cols = O_VAL(sp, O_COLUMNS);

	if (!silent && startup) {	/* Read EXINIT, exrc files. */
		if (ex_exrc(sp))
			goto err;
		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
			if (screen_end(sp))
				goto err;
			goto done;
		}
	}

	/*
	 * List recovery files if -r specified without file arguments.
	 * Note, options must be initialized and startup information
	 * read before doing this.
	 */
	if (flagchk == 'r' && argv[0] == NULL) {
		if (rcv_list(sp))
			goto err;
		if (screen_end(sp))
			goto err;
		goto done;
	}

	/*
	 * !!!
	 * Initialize the default ^D, ^U scrolling value here, after the
	 * user has had every opportunity to set the window option.
	 *
	 * It's historic practice that changing the value of the window
	 * option did not alter the default scrolling value, only giving
	 * a count to ^D/^U did that.
	 */
	sp->defscroll = (O_VAL(sp, O_WINDOW) + 1) / 2;

	/*
	 * If we don't have a command-line option, switch into the right
	 * editor now, so that we position default files correctly, and
	 * so that any tags file file-already-locked messages are in the
	 * vi screen, not the ex screen.
	 *
	 * XXX
	 * If we have a command-line option, the error message can end
	 * up in the wrong place, but I think that the combination is
	 * unlikely.
	 */
	if (gp->c_option == NULL) {
		F_CLR(sp, SC_EX | SC_VI);
		F_SET(sp, LF_ISSET(SC_EX | SC_VI));
	}

	/* Open a tag file if specified. */
	if (tag_f != NULL) {
		CHAR2INT(sp, tag_f, strlen(tag_f) + 1, w, wlen);
		if (ex_tag_first(sp, w))
			goto err;
	}

	/*
	 * Append any remaining arguments as file names.  Files are recovery
	 * files if -r specified.  If the tag option or ex startup commands
	 * loaded a file, then any file arguments are going to come after it.
	 */
	if (*argv != NULL) {
		if (sp->frp != NULL) {
			/* Cheat -- we know we have an extra argv slot. */
			*--argv = strdup(sp->frp->name);
			if (*argv == NULL) {
				v_estr(gp->progname, errno, NULL);
				goto err;
			}
		}
		sp->argv = sp->cargv = argv;
		F_SET(sp, SC_ARGNOFREE);
		if (flagchk == 'r')
			F_SET(sp, SC_ARGRECOVER);
	}

	/*
	 * If the ex startup commands and or/the tag option haven't already
	 * created a file, create one.  If no command-line files were given,
	 * use a temporary file.
	 */
	if (sp->frp == NULL) {
		if (sp->argv == NULL) {
			if ((frp = file_add(sp, NULL)) == NULL)
				goto err;
		} else  {
			if ((frp = file_add(sp, sp->argv[0])) == NULL)
				goto err;
			if (F_ISSET(sp, SC_ARGRECOVER))
				F_SET(frp, FR_RECOVER);
		}

		if (file_init(sp, frp, NULL, 0))
			goto err;
		if (EXCMD_RUNNING(gp)) {
			(void)ex_cmd(sp);
			if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
				if (screen_end(sp))
					goto err;
				goto done;
			}
		}
	}

	/*
	 * Check to see if we need to wait for ex.  If SC_SCR_EX is set, ex
	 * was forced to initialize the screen during startup.  We'd like to
	 * wait for a single character from the user, but we can't because
	 * we're not in raw mode.  We can't switch to raw mode because the
	 * vi initialization will switch to xterm's alternate screen, causing
	 * us to lose the messages we're pausing to make sure the user read.
	 * So, wait for a complete line.  
	 */
	if (F_ISSET(sp, SC_SCR_EX)) {
		p = msg_cmsg(sp, CMSG_CONT_R, &len);
		(void)write(STDOUT_FILENO, p, len);
		for (;;) {
			if (v_event_get(sp, &ev, 0, 0))
				goto err;
			if (ev.e_event == E_INTERRUPT ||
			    (ev.e_event == E_CHARACTER &&
			     (ev.e_value == K_CR || ev.e_value == K_NL)))
				break;
			(void)gp->scr_bell(sp);
		}
	}

	/* Switch into the right editor, regardless. */
	F_CLR(sp, SC_EX | SC_VI);
	F_SET(sp, LF_ISSET(SC_EX | SC_VI) | SC_STATUS_CNT);

	/*
	 * Main edit loop.  Vi handles split screens itself, we only return
	 * here when switching editor modes or restarting the screen.
	 */
	while (sp != NULL)
		if (F_ISSET(sp, SC_EX) ? ex(&sp) : vi(&sp))
			goto err;

done:	rval = 0;
	if (0)
err:		rval = 1;

	/* Clean out the global structure. */
	v_end(gp);

	return (rval);
}
Beispiel #29
0
void
TiledMesh::buildMesh()
{
  // stitch_meshes() is only implemented for ReplicatedMesh.  So make sure
  // we have one here before continuing.
  ReplicatedMesh * serial_mesh = dynamic_cast<ReplicatedMesh *>(&getMesh());

  if (!serial_mesh)
    mooseError("Error, TiledMesh calls stitch_meshes() which only works on ReplicatedMesh.");
  else
  {
    std::string mesh_file(getParam<MeshFileName>("file"));

    if (mesh_file.rfind(".exd") < mesh_file.size() || mesh_file.rfind(".e") < mesh_file.size())
    {
      ExodusII_IO ex(*this);
      ex.read(mesh_file);
      serial_mesh->prepare_for_use();
    }
    else
      serial_mesh->read(mesh_file);

    BoundaryID left = getBoundaryID(getParam<BoundaryName>("left_boundary"));
    BoundaryID right = getBoundaryID(getParam<BoundaryName>("right_boundary"));
    BoundaryID top = getBoundaryID(getParam<BoundaryName>("top_boundary"));
    BoundaryID bottom = getBoundaryID(getParam<BoundaryName>("bottom_boundary"));
    BoundaryID front = getBoundaryID(getParam<BoundaryName>("front_boundary"));
    BoundaryID back = getBoundaryID(getParam<BoundaryName>("back_boundary"));

    {
      std::unique_ptr<MeshBase> clone = serial_mesh->clone();

      // Build X Tiles
      for (unsigned int i = 1; i < getParam<unsigned int>("x_tiles"); ++i)
      {
        MeshTools::Modification::translate(*clone, _x_width, 0, 0);
        serial_mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone),
                                   right,
                                   left,
                                   TOLERANCE,
                                   /*clear_stitched_boundary_ids=*/true);
      }
    }
    {
      std::unique_ptr<MeshBase> clone = serial_mesh->clone();

      // Build Y Tiles
      for (unsigned int i = 1; i < getParam<unsigned int>("y_tiles"); ++i)
      {
        MeshTools::Modification::translate(*clone, 0, _y_width, 0);
        serial_mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone),
                                   top,
                                   bottom,
                                   TOLERANCE,
                                   /*clear_stitched_boundary_ids=*/true);
      }
    }
    {
      std::unique_ptr<MeshBase> clone = serial_mesh->clone();

      // Build Z Tiles
      for (unsigned int i = 1; i < getParam<unsigned int>("z_tiles"); ++i)
      {
        MeshTools::Modification::translate(*clone, 0, 0, _z_width);
        serial_mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone),
                                   front,
                                   back,
                                   TOLERANCE,
                                   /*clear_stitched_boundary_ids=*/true);
      }
    }
  }
}
Beispiel #30
0
P top(ST s){if(s->p==0)ex("underflow");R s->st[s->p-1];} //top