Esempio n. 1
0
		template<class T> bool
		Write (const Matrix<T>& M, const std::string& uri) {

			T t;
			Group group, *tmp;
			std::string path;

            boost::tokenizer<> tok(uri);
			std::vector<std::string> sv (Split (uri, "/"));
			std::string name = sv[sv.size() - 1];
			sv.pop_back(); // data name not part of path

			if (sv.size() == 0)
				path = "/";
			else
				for (size_t i = 0; i < sv.size(); i++) {
					if (sv[i].compare(""))
						path += "/";
						path += sv[i];
				}

			if (this->m_verb)
				printf ("Creating dataset %s at path (%s)\n", name.c_str(), path.c_str());

			try {

				group = m_file.openGroup(path);
				if (this->m_verb)
					printf ("Group %s opened for writing\n", path.c_str()) ;

			} catch (const Exception& e) {

				for (size_t i = 0, depth = 0; i < sv.size(); i++) {

					if (sv[i].compare("")) {

						try {
							group = (depth) ? (*tmp).openGroup(sv[i])   : m_file.openGroup(sv[i]);
						} catch (const Exception& e) {
							group = (depth) ? (*tmp).createGroup(sv[i]) : m_file.createGroup(sv[i]);
						}

						tmp = &group;
						depth++;

					}

				}

			}

			// One more field for complex numbers
			size_t tmpdim = ndims(M);

			std::vector<hsize_t> dims (tmpdim);

			for (size_t i = 0; i < tmpdim; i++)
				dims[i] = M.Dim(tmpdim-1-i);

			if (is_complex(t)) {
				dims.push_back(2);
				tmpdim++;
			}

			DataSpace space (tmpdim, &dims[0]);
			PredType*  type = HDF5Traits<T>::PType();

			DataSet set = group.createDataSet(name, (*type), space);

			set.write   (M.Ptr(), (*type));
			set.close   ();
			space.close ();

            return true;

		}
Esempio n. 2
0
SUMOTime
MSDevice_BTreceiver::BTreceiverUpdate::execute(SUMOTime /*currentTime*/) {
    // build rtree with senders
    NamedRTree rt;
    for (std::map<std::string, MSDevice_BTsender::VehicleInformation*>::const_iterator i = MSDevice_BTsender::sVehicles.begin(); i != MSDevice_BTsender::sVehicles.end(); ++i) {
        MSDevice_BTsender::VehicleInformation* vi = (*i).second;
        Boundary b = vi->getBoxBoundary();
        b.grow(POSITION_EPS);
        const float cmin[2] = {(float) b.xmin(), (float) b.ymin()};
        const float cmax[2] = {(float) b.xmax(), (float) b.ymax()};
        rt.Insert(cmin, cmax, vi);
    }

    // check visibility for all receivers
    OptionsCont& oc = OptionsCont::getOptions();
    bool allRecognitions = oc.getBool("device.btreceiver.all-recognitions");
    bool haveOutput = oc.isSet("bt-output");
    for (std::map<std::string, MSDevice_BTreceiver::VehicleInformation*>::iterator i = MSDevice_BTreceiver::sVehicles.begin(); i != MSDevice_BTreceiver::sVehicles.end();) {
        // collect surrounding vehicles
        MSDevice_BTreceiver::VehicleInformation* vi = (*i).second;
        Boundary b = vi->getBoxBoundary();
        b.grow(vi->range);
        const float cmin[2] = {(float) b.xmin(), (float) b.ymin()};
        const float cmax[2] = {(float) b.xmax(), (float) b.ymax()};
        std::set<std::string> surroundingVehicles;
        Named::StoringVisitor sv(surroundingVehicles);
        rt.Search(cmin, cmax, sv);

        // loop over surrounding vehicles, check visibility status
        for (std::set<std::string>::const_iterator j = surroundingVehicles.begin(); j != surroundingVehicles.end(); ++j) {
            if ((*i).first == *j) {
                // seeing oneself? skip
                continue;
            }
            updateVisibility(*vi, *MSDevice_BTsender::sVehicles.find(*j)->second);
        }

        if (vi->haveArrived) {
            // vehicle has left the simulation; remove
            if (haveOutput) {
                writeOutput((*i).first, vi->seen, allRecognitions);
            }
            delete vi;
            MSDevice_BTreceiver::sVehicles.erase(i++);
        } else {
            // vehicle is still in the simulation; reset state
            vi->updates.erase(vi->updates.begin(), vi->updates.end() - 1);
            ++i;
        }
    }

    // remove arrived senders / reset state
    for (std::map<std::string, MSDevice_BTsender::VehicleInformation*>::iterator i = MSDevice_BTsender::sVehicles.begin(); i != MSDevice_BTsender::sVehicles.end();) {
        MSDevice_BTsender::VehicleInformation* vi = (*i).second;
        if (vi->haveArrived) {
            delete vi;
            MSDevice_BTsender::sVehicles.erase(i++);
        } else {
            vi->updates.erase(vi->updates.begin(), vi->updates.end() - 1);
            ++i;
        }
    }
    return DELTA_T;
}
Esempio n. 3
0
/* When called with c==-1, it just creates the prompt */
static int itype(W *w, int c, void *obj, int *notify)
{
	IREC *i;
	int omid;
	BW *bw;
	struct isrch *isrch = (struct isrch *)obj;
	WIND_BW(bw,w);

	if (isrch->quote) {
		goto in;
	}
	if (c == 8 || c == 127) {	/* Backup */
		if ((i = isrch->irecs.link.prev) != &isrch->irecs) {
			pgoto(bw->cursor, i->disp);
			if (globalsrch)
				globalsrch->wrap_flag = i->wrap_flag;
			omid = opt_mid;
			opt_mid = 1;
			dofollows();
			opt_mid = omid;
			isrch->pattern = vstrunc(isrch->pattern, sLEN(isrch->pattern) - i->what);
			frirec(deque_f(IREC, link, i));
		} else {
			if(joe_beep)
				ttputc(7);
		}
	} else if (c == 'Q' - '@' /* || c == '`' */) {
		isrch->quote = 1;
	} else if (c == 'S' - '@' || c == '\\' - '@' || c == 'L' - '@' || c == 'R' - '@') {
		/* Repeat */
		if (c == 'R' - '@') {
			isrch->dir = 1;
		} else {
			isrch->dir = 0;
		}
		if (qempty(IREC, link, &isrch->irecs)) {
			if (lastpat && lastpat[0]) {
				iappend(bw, isrch, sv(lastpat));
			}
		} else {
			SRCH *srch;
			i = alirec();
			i->disp = i->start = bw->cursor->byte;
			i->what = 0;

			if (!globalsrch)
				srch = mksrch(NULL,NULL,opt_icase,isrch->dir,-1,0,0,0,0);
			else {
				srch = globalsrch;
				globalsrch = 0;
			}

			srch->addr = bw->cursor->byte;

			if (!srch->wrap_p || srch->wrap_p->b!=bw->b) {
				prm(srch->wrap_p);
				srch->wrap_p = pdup(bw->cursor, "itype");
				srch->wrap_p->owner = &srch->wrap_p;
				srch->wrap_flag = 0;
			}

			i->wrap_flag = srch->wrap_flag;

			setpat(srch, vsncpy(NULL, 0, isrch->pattern, sLen(isrch->pattern)));
			srch->backwards = isrch->dir;

			if (dopfnext(bw, srch, NULL)) {
				if(joe_beep)
					ttputc(7);
				frirec(i);
			} else {
				enqueb(IREC, link, &isrch->irecs, i);
			}
		}
	} else if (c >= 0 && c < 32) {
		/* Done when a control character is received */
		nungetc(c);
		if (notify) {
			*notify = 1;
		}
		smode = 2;
		if (lastisrch) {
			lastpat = vstrunc(lastpat, 0);
			lastpat = vsncpy(lastpat, 0, lastisrch->pattern, sLen(lastisrch->pattern));
			rmisrch(lastisrch);
		}
		lastisrch = isrch;
		return 0;
	} else if (c != -1) {
		char buf[16];
		ptrdiff_t buf_len;
		/* Search */

		in:

		if (bw->b->o.charmap->type) {
			buf_len = utf8_encode(buf, c);
		} else {
			buf[0] = TO_CHAR_OK(from_uni(bw->b->o.charmap, c));
			buf_len = 1;
		}		

		isrch->quote = 0;
		iappend(bw, isrch, buf, buf_len);
	}
	omid = opt_mid;
	opt_mid = 1;
	bw->cursor->xcol = piscol(bw->cursor);
	dofollows();
	opt_mid = omid;

	isrch->prompt = vstrunc(isrch->prompt, isrch->ofst);

	if (locale_map->type && !bw->b->o.charmap->type) {
		/* Translate bytes to utf-8 */
		char buf[16];
		int x;
		for (x=0; x!=sLEN(isrch->pattern); ++x) {
			int tc = to_uni(bw->b->o.charmap, isrch->pattern[x]);
			utf8_encode(buf, tc);
			isrch->prompt = vsncpy(sv(isrch->prompt),sz(buf));
		}
	} else if (!locale_map->type && bw->b->o.charmap->type) {
		/* Translate utf-8 to bytes */
		const char *p = isrch->pattern;
		ptrdiff_t len = sLEN(isrch->pattern);
		while (len) {
			int tc = utf8_decode_fwrd(&p, &len);
			if (tc >= 0) {
				tc = from_uni(locale_map, tc);
				isrch->prompt = vsadd(isrch->prompt, TO_CHAR_OK(tc));
			}
		}
	} else {
		/* FIXME: translate when charmaps do not match */
		isrch->prompt = vsncpy(sv(isrch->prompt),sv(isrch->pattern));
	}

	if (mkqwnsr(bw->parent, sv(isrch->prompt), itype, iabrt, isrch, notify)) {
		return 0;
	} else {
		rmisrch(isrch);
		return -1;
	}
}
Esempio n. 4
0
int main(int argc, char **real_argv, char **envv)
{
	CAP *cap;
	unsigned char **argv = (unsigned char **)real_argv;
	struct stat sbuf;
	unsigned char *s;
	unsigned char *t;
	long time_rc;
	unsigned char *run;
#ifdef __MSDOS__
	unsigned char *rundir;
#endif
	SCRN *n;
	int opened = 0;
	int omid;
	int backopt;
	int c;

	init_bufs();

	for (c = 1; argv[c] != NULL; ++c) {
		if (0 == zcmp((unsigned char*)argv[c], USTR "-nosys")) {
			read_sys_configs = 0;
		} else if (0 == zcmp((unsigned char*)argv[c], USTR "-nouser")) {
			read_user_configs = 0;
		} else {
			argv[--c] = argv[0];
			argv += c;
			argc -= c;
			break;
		}
	}

	if (read_user_configs) {
		s = (unsigned char *)getenv("HOME");
		if (s) {
			s = vsncpy(NULL, 0, sz(s));
			s = vsncpy(sv(s), sc("/.joe-p37/only.rc"));
			if (!stat((char*)s, &sbuf)) read_sys_configs = 0;
			vsrm(s);
		}
	}

	joe_locale();

	mainenv = (unsigned char **)envv;

#ifdef __MSDOS__
	_fmode = O_BINARY;
	zcpy(stdbuf, argv[0]);
	joesep(stdbuf);
	run = namprt(stdbuf);
	rundir = dirprt(stdbuf);
	for (c = 0; run[c]; ++c)
		if (run[c] == '.') {
			run = vstrunc(run, c);
			break;
		}
#else
	run = namprt(argv[0]);
#endif

	env_lines = 0;
	if ((s = (unsigned char *)getenv("LINES")) != NULL &&
	    sscanf((char *)s, "%d", &env_lines) != 1)
		env_lines = 0;
	env_columns = 0;
	if ((s = (unsigned char *)getenv("COLUMNS")) != NULL &&
	    sscanf((char *)s, "%d", &env_columns) != 1)
		env_columns = 0;
	if ((s = (unsigned char *)getenv("BAUD")) != NULL)
		sscanf((char *)s, "%u", (unsigned *)&Baud);
	if (getenv("DOPADDING"))
		dopadding = 1;
	if (getenv("NOXON"))
		noxon = 1;
	if ((s = (unsigned char *)getenv("JOETERM")) != NULL)
		joeterm = s;

#ifndef __MSDOS__
	if (!(cap = my_getcap(NULL, 9600, NULL, NULL))) {
		fprintf(stderr, (char *)joe_gettext(_("Couldn't load termcap/terminfo entry\n")));
		return 1;
	}
#endif

#ifdef __MSDOS__

	s = vsncpy(NULL, 0, sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		unsigned char buf[8];

		fprintf(stderr, (char *)joe_gettext(_("There were errors in '%s'.  Use it anyway?")), s);
		fflush(stderr);
		if (NULL == fgets(buf, 8, stdin) || yn_checks(yes_key, buf))
			goto donerc;
	}

	vsrm(s);
	s = vsncpy(NULL, 0, sv(rundir));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c != 0 && c != 1) {
		/* If built-in *fancyjoerc not present, process builtin *joerc,
		 * which is always present.
		 */
		s = vstrunc(s, 0);
		s = vsncpy(sv(s), sc("*joerc"));
		c = procrc(cap, s);
	}
	if (c == 0)
		goto donerc;
	if (c == 1) {
		unsigned char buf[8];

		fprintf(stderr, (char *)joe_gettext(_("There were errors in '%s'.  Use it anyway?")), s);
		fflush(stderr);
		if (NULL == fgets(buf, 8, stdin) || yn_checks(yes_key, buf))
			goto donerc;
	}
#else

	/* Name of system joerc file.  Try to find one with matching language... */
	
	/* Try full language: like joerc.de_DE */
	time_rc = 0;
        if (!read_sys_configs) { t = NULL; goto skip_joerc; }
        t = vsncpy(NULL, 0, sc(JOERC));
	t = vsncpy(sv(t), sv(run));
	t = vsncpy(sv(t), sc("rc."));
	t = vsncpy(sv(t), sz(locale_msgs));
	if (!stat((char *)t,&sbuf))
		time_rc = sbuf.st_mtime;
	else {
		/* Try generic language: like joerc.de */
		if (locale_msgs[0] && locale_msgs[1] && locale_msgs[2]=='_') {
			vsrm(t);
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc."));
			t = vsncpy(sv(t), locale_msgs, 2);
			if (!stat((char *)t,&sbuf))
				time_rc = sbuf.st_mtime;
			else
				goto nope;
		} else {
			nope:
			vsrm(t);
			/* Try Joe's bad english */
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc"));
			if (!stat((char *)t,&sbuf))
				time_rc = sbuf.st_mtime;
			else {
				/* If built-in *fancyjoerc not present, process builtin *joerc,
				 * which is always present.
				 */
				t = vstrunc(s, 0);
				t = vsncpy(sv(s), sc("*joerc"));
				time_rc = stat((char *)t,&sbuf) ? 0 : sbuf.st_mtime;
			}
		}
	}
	skip_joerc:

	/* User's joerc file */
	s = (unsigned char *)getenv("HOME");
	if (s && !read_sys_configs) {
		if (read_user_configs) {  /* TODO(pts): Don't read /dev/null */
			s = vsncpy(NULL, 0, sz(s));
			s = vsncpy(sv(s), sc("/.joe-p37/rc"));
		} else {
			s = vsncpy(NULL, 0, sc("/dev/null/missing"));
		}
		goto process_user_rc;
	} else if (!read_user_configs) {
		s = vsncpy(NULL, 0, sc("/dev/null/missing"));
		goto process_user_rc;
	} else if (s) {
		unsigned char buf[8];

		s = vsncpy(NULL, 0, sz(s));
		s = vsncpy(sv(s), sc("/."));
		s = vsncpy(sv(s), sv(run));
		s = vsncpy(sv(s), sc("rc"));

		if (!stat((char *)s,&sbuf)) {
			if (sbuf.st_mtime < time_rc) {
				fprintf(stderr,(char *)joe_gettext(_("Warning: %s is newer than your %s.\n")),t,s);
				fprintf(stderr,(char *)joe_gettext(_("You should update or delete %s\n")),s);
				fprintf(stderr,(char *)joe_gettext(_("Hit enter to continue with %s ")),t);
				fflush(stderr);
				(void)!fgets((char *)buf, 8, stdin);
				goto use_sys;
			}
		}

	      process_user_rc:
		c = procrc(cap, s);
		if (c == 0) {
			vsrm(t);
			goto donerc;
		}
		if (c == 1) {
			fprintf(stderr,(char *)joe_gettext(_("There were errors in '%s'.  Use it anyway (y,n)? ")), s);
			fflush(stderr);
			if (NULL == fgets((char *)buf, 8, stdin) || ynchecks(yes_key, buf)) {
				vsrm(t);
				goto donerc;
			}
		}
	}

	use_sys:
	vsrm(s);
	s = t;
	c = s ? procrc(cap, s) : -1;
	if (c == 0)
		goto donerc;
	if (c == 1) {
		unsigned char buf[8];

		fprintf(stderr,(char *)joe_gettext(_("There were errors in '%s'.  Use it anyway (y,n)? ")), s);
		fflush(stderr);
		if (NULL == fgets((char *)buf, 8, stdin) || ynchecks(yes_key, buf))
			goto donerc;
	}

	/* Try built-in *fancyjoerc, e.g. "*joe-p37rc" */
	vsrm(s);
	s = vsncpy(NULL, 0, sc("*"));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c != 0 && c != 1) {
		/* If built-in *fancyjoerc not present, process builtin "*joerc",
		 * which is always present.
		 */
		s = vstrunc(s, 0);
		s = vsncpy(sv(s), sc("*joerc"));
		c = procrc(cap, s);
	}
	if (c == 0)
		goto donerc;
	if (c == 1) {
		unsigned char buf[8];

		fprintf(stderr,(char *)joe_gettext(_("There were errors in '%s'.  Use it anyway (y,n)? ")), s);
		fflush(stderr);
		if (NULL == fgets((char *)buf, 8, stdin) || ynchecks(yes_key, buf))
			goto donerc;
	}
#endif

	fprintf(stderr,(char *)joe_gettext(_("Couldn't open '%s'\n")), s);
	vsrm(s);
	return 1;

	donerc:
	vsrm(s);

	if (validate_rc()) {
		fprintf(stderr,(char *)joe_gettext(_("rc file has no :main key binding section or no bindings.  Bye.\n")));
		return 1;
	}


	if (!isatty(fileno(stdin)))
		idleout = 0;

	for (c = 1; argv[c]; ++c) {
		if (argv[c][0] == '-') {
			if (argv[c][1])
				switch (glopt(argv[c] + 1, argv[c + 1], NULL, 1)) {
				case 0:
					fprintf(stderr,(char *)joe_gettext(_("Unknown option '%s'\n")), argv[c]);
					break;
				case 1:
					break;
				case 2:
					++c;
					break;
			} else
				idleout = 0;
		}
	}
	if (!dspasis) {  /* Open all files as ASCII by default if `joe --asis' is specified. This is to avoid writing control characters to the UTF-8 terminal. */
		fdefault.charmap = pdefault.charmap = find_charmap(USTR "ascii");
		fdefault.map_name = pdefault.map_name = USTR "ascii";
	}


	/* initialize mouse support */
	if (xmouse && (s=(unsigned char *)getenv("TERM")) && strstr((char *)s,"xterm"))
		usexmouse=1;

	if (!(n = nopen(cap)))
		return 1;
	maint = screate(n);
	vmem = vtmp();

	startup_log = bfind_scratch_incref(USTR "* Startup Log *");
	startup_log->internal = 1;

	load_state();

	/* It would be better if this ran uedit() to load files */

	/* The business with backopt is to load the file first, then apply file
	 * local options afterwords */

	/* orphan is not compatible with exemac()- macros need a window to exist */
	for (c = 1, backopt = 0; argv[c]; ++c)
		if (argv[c][0] == '+' && argv[c][1]>='0' && argv[c][1]<='9') {
			if (!backopt)
				backopt = c;
		} else if (argv[c][0] == '-' && argv[c][1]) {
			if (!backopt)
				backopt = c;
			if (glopt(argv[c] + 1, argv[c + 1], NULL, 0) == 2)
				++c;
		} else {
			B *b = bfind_incref(argv[c]);
			BW *bw = NULL;
			int er = berror;

			/* This is too annoying */
			/* set_current_dir(argv[c],1); */

			setup_history(&filehist);
			append_history(filehist,sz(argv[c]));

			/* wmktw_takeref() inserts the window before maint->curwin */
			if (!orphan || !opened) {
				bw = wmktw_takeref(maint, b);
				if (er)
					msgnwt(bw->parent, joe_gettext(msgs[-er]));
			} else {
				long line;
				b->orphan = 1;
				b->oldcur = pdup(b->bof, USTR "main");
				pline(b->oldcur, get_file_pos(b->name));
				line = b->oldcur->line - (maint->h - 1) / 2;
				if (line < 0)
					line = 0;
				b->oldtop = pdup(b->oldcur, USTR "main");
				pline(b->oldtop, line);
				p_goto_bol(b->oldtop);
			}
			if (bw) {
				long lnum = 0;

				bw->o.readonly = bw->b->rdonly;
				if (backopt) {
					while (backopt != c) {
						if (argv[backopt][0] == '+') {
							sscanf((char *)(argv[backopt] + 1), "%ld", &lnum);
							++backopt;
						} else {
							if (glopt(argv[backopt] + 1, argv[backopt + 1], &bw->o, 0) == 2)
								backopt += 2;
							else
								backopt += 1;
							lazy_opts(bw->b, &bw->o);
						}
					}
				}
				bw->b->o = bw->o;
				bw->b->rdonly = bw->o.readonly;
				/* Put cursor in window, so macros work properly */
				maint->curwin = bw->parent;
				/* Execute macro */
				if (er == -1 && bw->o.mnew)
					exmacro(bw->o.mnew,1);
				if (er == 0 && bw->o.mold)
					exmacro(bw->o.mold,1);
				/* Hmm... window might not exist any more... depends on what macro does... */
				if (lnum > 0)
					pline(bw->cursor, lnum - 1);
				else
					pline(bw->cursor, get_file_pos(bw->b->name));
				p_goto_bol(bw->cursor);
				/* Go back to first window so windows are in same order as command line  */
				if (opened)
					wnext(maint);
				
			}
			opened = 1;
			backopt = 0;
		}

	

	if (opened) {
		wshowall(maint);
		omid = mid;
		mid = 1;
		dofollows();
		mid = omid;
	} else {
		BW *bw = wmktw_takeref(maint, bfind_incref(USTR ""));

		if (bw->o.mnew)
			exmacro(bw->o.mnew,1);
	}
	maint->curwin = maint->topwin;

	if (startup_log->eof->byte) {
		BW *bw = wmktw_takeref(maint, startup_log);
		startup_log = NULL;
		maint->curwin = bw->parent;
		wshowall(maint);
		uparserr(bw);
	}

	if (help) {
		help_on(maint);
	}
	if (!nonotice) {
		joe_snprintf_3(msgbuf,JOE_MSGBUFSIZE,joe_gettext(_("\\i** Joe's Own Editor v%s ** (%s) ** Copyright %s 2008 **\\i")),VERSION,locale_map->name,(locale_map->type ? "©" : "(C)"));

		msgnw(((BASE *)lastw(maint)->object)->parent, msgbuf);
	}

	if (!idleout) {
		if (!isatty(fileno(stdin)) && modify_logic(maint->curwin->object, ((BW *)maint->curwin->object)->b)) {
			/* Start shell going in first window */
			unsigned char **a;
			unsigned char *cmd;

			a = vamk(10);
			cmd = vsncpy(NULL, 0, sc("/bin/sh"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("-c"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("/bin/cat"));
			a = vaadd(a, cmd);
			
			cstart (maint->curwin->object, USTR "/bin/sh", a, NULL, NULL, 0, 1);
		}
	}

	edloop(0);

	save_state();

	/* Delete all buffer so left over locks get eliminated */
	brmall();

	vclose(vmem);
	nclose(n);

	if (exmsg)
		fprintf(stderr, "\n%s\n", exmsg);
	return 0;
}
Esempio n. 5
0
bool test ( const CharT *s, size_t len ) {
    std::experimental::basic_string_view<CharT> sv ( s, len );
    assert ( sv.length() == len );
    assert ( sv.back() == s[len-1] );
    return &sv.back() == s + len - 1;
    }
Esempio n. 6
0
void test ( const CharT *s, size_t len ) {
    std::experimental::basic_string_view<CharT> sv ( s, len );
    assert ( sv.length() == len );
    assert ( sv.data() == s );
    }
Esempio n. 7
0
double ProjectedKinematics::vsLevelOutTime(const Position& so, const Velocity& vo, double climbRate, double targetAlt, double a) {
	std::pair<Vect3, Velocity> sv(so.point(),vo);
	// we don't need horizontal components, so don't need to project
	return Kinematics::vsLevelOutTime(sv, climbRate, targetAlt, a);
}
Esempio n. 8
0
int main()
{
    // check that it'll find nodes exactly MAX away
    {
        tree_type exact_dist(std::ptr_fun(tac));
        triplet c0(5, 4, 0);
        exact_dist.insert(c0);
        triplet target(7,4,0);

        std::pair<tree_type::const_iterator,double> found = exact_dist.find_nearest(target,2);
        assert(found.first != exact_dist.end());
        assert(found.second == 2);
        std::cout << "Test find_nearest(), found at exact distance away from " << target << ", found " << *found.first << std::endl;
    }

    // do the same test, except use alternate_triplet as the search key
    {
        // NOTE: stores triplet, but we search with alternate_triplet
        typedef KDTree::KDTree<3, triplet, alternate_tac> alt_tree;

        triplet actual_target(7,0,0);

        alt_tree tree;
        tree.insert( triplet(0, 0, 7) );
        tree.insert( triplet(0, 0, 7) );
        tree.insert( triplet(0, 0, 7) );
        tree.insert( triplet(3, 0, 0) );
        tree.insert( actual_target );
        tree.optimise();

        alternate_triplet target( actual_target );

        std::pair<alt_tree::const_iterator,double> found = tree.find_nearest(target);
        assert(found.first != tree.end());
        std::cout << "Test with alternate search type, found: " << *found.first << ", wanted " << actual_target << std::endl;
        assert(found.second == 0);
        assert(*found.first == actual_target);
    }


    {
        tree_type exact_dist(std::ptr_fun(tac));
        triplet c0(5, 2, 0);
        exact_dist.insert(c0);
        triplet target(7,4,0);

        // call find_nearest without a range value - it found a compile error earlier.
        std::pair<tree_type::const_iterator,double> found = exact_dist.find_nearest(target);
        assert(found.first != exact_dist.end());
        std::cout << "Test find_nearest(), found at exact distance away from " << target << ", found " << *found.first << " @ " << found.second << " should be " << std::sqrt(8.0) << std::endl;
        assert(found.second == std::sqrt(8.0));
    }

    {
        tree_type exact_dist(std::ptr_fun(tac));
        triplet c0(5, 2, 0);
        exact_dist.insert(c0);
        triplet target(7,4,0);

        std::pair<tree_type::const_iterator,double> found = exact_dist.find_nearest(target,std::sqrt(8.0));
        assert(found.first != exact_dist.end());
        std::cout << "Test find_nearest(), found at exact distance away from " << target << ", found " << *found.first << " @ " << found.second << " should be " << std::sqrt(8.0) << std::endl;
        assert(found.second == std::sqrt(8.0));
    }

    tree_type src(std::ptr_fun(tac));

    triplet c0(5, 4, 0);
    src.insert(c0);
    triplet c1(4, 2, 1);
    src.insert(c1);
    triplet c2(7, 6, 9);
    src.insert(c2);
    triplet c3(2, 2, 1);
    src.insert(c3);
    triplet c4(8, 0, 5);
    src.insert(c4);
    triplet c5(5, 7, 0);
    src.insert(c5);
    triplet c6(3, 3, 8);
    src.insert(c6);
    triplet c7(9, 7, 3);
    src.insert(c7);
    triplet c8(2, 2, 6);
    src.insert(c8);
    triplet c9(2, 0, 6);
    src.insert(c9);

    std::cout << src << std::endl;

    src.erase(c0);
    src.erase(c1);
    src.erase(c3);
    src.erase(c5);

    src.optimise();


    // test the efficient_replace_and_optimise()
    tree_type eff_repl = src;
    {
        std::vector<triplet> vec;
        // erased above as part of test vec.push_back(triplet(5, 4, 0));
        // erased above as part of test vec.push_back(triplet(4, 2, 1));
        vec.push_back(triplet(7, 6, 9));
        // erased above as part of test vec.push_back(triplet(2, 2, 1));
        vec.push_back(triplet(8, 0, 5));
        // erased above as part of test vec.push_back(triplet(5, 7, 0));
        vec.push_back(triplet(3, 3, 8));
        vec.push_back(triplet(9, 7, 3));
        vec.push_back(triplet(2, 2, 6));
        vec.push_back(triplet(2, 0, 6));

        eff_repl.clear();
        eff_repl.efficient_replace_and_optimise(vec);
    }


    std::cout << std::endl << src << std::endl;

    tree_type copied(src);
    std::cout << copied << std::endl;
    tree_type assigned(std::ptr_fun(tac));
    assigned = src;
    std::cout << assigned << std::endl;

    for (int loop = 0; loop != 4; ++loop)
    {
        tree_type * target;
        switch (loop)
        {
        case 0:
            std::cout << "Testing plain construction" << std::endl;
            target = &src;
            break;

        case 1:
            std::cout << "Testing copy-construction" << std::endl;
            target = &copied;
            break;

        case 2:
            std::cout << "Testing assign-construction" << std::endl;
            target = &assigned;
            break;

        default:
        case 4:
            std::cout << "Testing efficient-replace-and-optimise" << std::endl;
            target = &eff_repl;
            break;
        }
        tree_type & t = *target;

        int i=0;
        for (tree_type::const_iterator iter=t.begin(); iter!=t.end(); ++iter, ++i);
        std::cout << "iterator walked through " << i << " nodes in total" << std::endl;
        if (i!=6)
        {
            std::cerr << "Error: does not tally with the expected number of nodes (6)" << std::endl;
            return 1;
        }
        i=0;
        for (tree_type::const_reverse_iterator iter=t.rbegin(); iter!=t.rend(); ++iter, ++i);
        std::cout << "reverse_iterator walked through " << i << " nodes in total" << std::endl;
        if (i!=6)
        {
            std::cerr << "Error: does not tally with the expected number of nodes (6)" << std::endl;
            return 1;
        }

        triplet s(5, 4, 3);
        std::vector<triplet> v;
        unsigned int const RANGE = 3;

        size_t count = t.count_within_range(s, RANGE);
        std::cout << "counted " << count
                  << " nodes within range " << RANGE << " of " << s << ".\n";
        t.find_within_range(s, RANGE, std::back_inserter(v));

        std::cout << "found   " << v.size() << " nodes within range " << RANGE
                  << " of " << s << ":\n";
        std::vector<triplet>::const_iterator ci = v.begin();
        for (; ci != v.end(); ++ci)
            std::cout << *ci << " ";
        std::cout << "\n" << std::endl;

        std::cout << std::endl << t << std::endl;

        // search for all the nodes at exactly 0 dist away
        for (tree_type::const_iterator target = t.begin(); target != t.end(); ++target)
        {
            std::pair<tree_type::const_iterator,double> found = t.find_nearest(*target,0);
            assert(found.first != t.end());
            assert(*found.first == *target);
            std::cout << "Test find_nearest(), found at exact distance away from " << *target << ", found " << *found.first << std::endl;
        }

        {
            const double small_dist = 0.0001;
            std::pair<tree_type::const_iterator,double> notfound = t.find_nearest(s,small_dist);
            std::cout << "Test find_nearest(), nearest to " << s << " within " << small_dist << " should not be found" << std::endl;

            if (notfound.first != t.end())
            {
                std::cout << "ERROR found a node at dist " << notfound.second << " : " << *notfound.first << std::endl;
                std::cout << "Actual distance = " << s.distance_to(*notfound.first) << std::endl;
            }

            assert(notfound.first == t.end());
        }

        {
            std::pair<tree_type::const_iterator,double> nif = t.find_nearest_if(s,std::numeric_limits<double>::max(),Predicate());
            std::cout << "Test find_nearest_if(), nearest to " << s << " @ " << nif.second << ": " << *nif.first << std::endl;

            std::pair<tree_type::const_iterator,double> cantfind = t.find_nearest_if(s,std::numeric_limits<double>::max(),FalsePredicate());
            std::cout << "Test find_nearest_if(), nearest to " << s << " should never be found (predicate too strong)" << std::endl;
            assert(cantfind.first == t.end());
        }




        {
            std::pair<tree_type::const_iterator,double> found = t.find_nearest(s,std::numeric_limits<double>::max());
            std::cout << "Nearest to " << s << " @ " << found.second << " " << *found.first << std::endl;
            std::cout << "Should be " << found.first->distance_to(s) << std::endl;
            // NOTE: the assert does not check for an exact match, as it is not exact when -O2 or -O3 is
            // switched on.  Some sort of optimisation makes the math inexact.
            assert( fabs(found.second - found.first->distance_to(s)) < std::numeric_limits<double>::epsilon() );
        }

        {
            triplet s2(10, 10, 2);
            std::pair<tree_type::const_iterator,double> found = t.find_nearest(s2,std::numeric_limits<double>::max());
            std::cout << "Nearest to " << s2 << " @ " << found.second << " " << *found.first << std::endl;
            std::cout << "Should be " << found.first->distance_to(s2) << std::endl;
            // NOTE: the assert does not check for an exact match, as it is not exact when -O2 or -O3 is
            // switched on.  Some sort of optimisation makes the math inexact.
            assert( fabs(found.second - found.first->distance_to(s2)) < std::numeric_limits<double>::epsilon() );
        }

        std::cout << std::endl;

        std::cout << t << std::endl;

        // Testing iterators
        {
            std::cout << "Testing iterators" << std::endl;

            t.erase(c2);
            t.erase(c4);
            t.erase(c6);
            t.erase(c7);
            t.erase(c8);
            //    t.erase(c9);

            std::cout << std::endl << t << std::endl;

            std::cout << "Forward iterator test..." << std::endl;
            std::vector<triplet> forwards;
            for (tree_type::iterator i = t.begin(); i != t.end(); ++i)
            {
                std::cout << *i << " " << std::flush;
                forwards.push_back(*i);
            }
            std::cout << std::endl;
            std::cout << "Reverse iterator test..." << std::endl;
            std::vector<triplet> backwards;
            for (tree_type::reverse_iterator i = t.rbegin(); i != t.rend(); ++i)
            {
                std::cout << *i << " " << std::flush;
                backwards.push_back(*i);
            }
            std::cout << std::endl;
            std::reverse(backwards.begin(),backwards.end());
            assert(backwards == forwards);
        }
    }


    // Walter reported that the find_within_range() wasn't giving results that were within
    // the specified range... this is the test.
    {
        // note: we need to store doubles in this tree.
        typedef KDTree::KDTree<3, triplet_t<double>, std::pointer_to_binary_function<triplet_t<double>,size_t,double> > dbl_tree_type;

        dbl_tree_type tree(std::ptr_fun(tac_dbl));
        tree.insert( triplet_t<double>(28.771200,16.921600,-2.665970) );
        tree.insert( triplet_t<double>(28.553101,18.649700,-2.155560) );
        tree.insert( triplet_t<double>(28.107500,20.341400,-1.188940) );
        tree.optimise();

        std::deque< triplet_t<double> > vectors;
        triplet_t<double> sv(18.892500,20.341400,-1.188940);
        tree.find_within_range(sv, 10.0f, std::back_inserter(vectors));

        std::cout << std::endl << "Test find_with_range( " << sv << ", 10.0f) found " << vectors.size() << " candidates." << std::endl;

        // double-check the ranges
        for (std::deque<triplet_t<double> >::iterator v = vectors.begin(); v != vectors.end(); ++v)
        {
            double dist = sv.distance_to(*v);
            std::cout << "  " << *v << " dist=" << dist << std::endl;
            if (dist > 10.0f)
                std::cout << "    This point is too far! But that is by design, its within a 'box' with a 'radius' of 10, not a sphere with a radius of 10" << std::endl;
            // Not a valid test, it can be greater than 10 if the point is in the corners of the box.
            // assert(dist <= 10.0f);
        }
    }


    return 0;
}
Esempio n. 9
0
wxSize wxStaticText::DoGetBestSize() const
{
    Rect bestsize = { 0 , 0 , 0 , 0 } ;
    Point bounds;
    
    // try the built-in best size if available
    Boolean former = m_peer->GetData<Boolean>( kControlStaticTextIsMultilineTag);
    m_peer->SetData( kControlStaticTextIsMultilineTag, (Boolean)0 );
    m_peer->GetBestRect( &bestsize ) ;
    m_peer->SetData( kControlStaticTextIsMultilineTag, former );
    if ( !EmptyRect( &bestsize ) )
    {
        bounds.h = bestsize.right - bestsize.left ;
        bounds.v = bestsize.bottom - bestsize.top ;
    }
    else
    {
        ControlFontStyleRec controlFont;
        OSStatus err = m_peer->GetData<ControlFontStyleRec>( kControlEntireControl, kControlFontStyleTag, &controlFont );
        verify_noerr( err );

        SInt16 baseline;
        wxMacCFStringHolder str( m_label,  m_font.GetEncoding() );

#ifndef __LP64__
        if ( m_font.MacGetThemeFontID() != kThemeCurrentPortFont )
        {
            err = GetThemeTextDimensions(
                (!m_label.empty() ? (CFStringRef)str : CFSTR(" ")),
                m_font.MacGetThemeFontID(), kThemeStateActive, false, &bounds, &baseline );
            verify_noerr( err );
        }
        else
#endif
        {
    #if wxMAC_USE_CORE_GRAPHICS
            wxClientDC dc(const_cast<wxStaticText*>(this));
            wxCoord width, height ;
            dc.GetTextExtent( m_label , &width, &height);
            bounds.h = width;
            bounds.v = height;
    #else
            wxMacWindowStateSaver sv( this );
            ::TextFont( m_font.MacGetFontNum() );
            ::TextSize( (short)(m_font.MacGetFontSize()) );
            ::TextFace( m_font.MacGetFontStyle() );

            err = GetThemeTextDimensions(
                (!m_label.empty() ? (CFStringRef)str : CFSTR(" ")),
                kThemeCurrentPortFont, kThemeStateActive, false, &bounds, &baseline );
            verify_noerr( err );
    #endif
        }

        if ( m_label.empty() )
            bounds.h = 0;
    }
    bounds.h += MacGetLeftBorderSize() + MacGetRightBorderSize();
    bounds.v += MacGetTopBorderSize() + MacGetBottomBorderSize();

    return wxSize( bounds.h, bounds.v );
}
Esempio n. 10
0
/*************************************************************************
Internal fitting subroutine
*************************************************************************/
static void lsfitlinearinternal(const ap::real_1d_array& y,
     const ap::real_1d_array& w,
     const ap::real_2d_array& fmatrix,
     int n,
     int m,
     int& info,
     ap::real_1d_array& c,
     lsfitreport& rep)
{
    double threshold;
    ap::real_2d_array ft;
    ap::real_2d_array q;
    ap::real_2d_array l;
    ap::real_2d_array r;
    ap::real_1d_array b;
    ap::real_1d_array wmod;
    ap::real_1d_array tau;
    int i;
    int j;
    double v;
    ap::real_1d_array sv;
    ap::real_2d_array u;
    ap::real_2d_array vt;
    ap::real_1d_array tmp;
    ap::real_1d_array utb;
    ap::real_1d_array sutb;
    int relcnt;

    if( n<1||m<1 )
    {
        info = -1;
        return;
    }
    info = 1;
    threshold = sqrt(ap::machineepsilon);
    
    //
    // Degenerate case, needs special handling
    //
    if( n<m )
    {
        
        //
        // Create design matrix.
        //
        ft.setlength(n, m);
        b.setlength(n);
        wmod.setlength(n);
        for(j = 0; j <= n-1; j++)
        {
            v = w(j);
            ap::vmove(&ft(j, 0), 1, &fmatrix(j, 0), 1, ap::vlen(0,m-1), v);
            b(j) = w(j)*y(j);
            wmod(j) = 1;
        }
        
        //
        // LQ decomposition and reduction to M=N
        //
        c.setlength(m);
        for(i = 0; i <= m-1; i++)
        {
            c(i) = 0;
        }
        rep.taskrcond = 0;
        rmatrixlq(ft, n, m, tau);
        rmatrixlqunpackq(ft, n, m, tau, n, q);
        rmatrixlqunpackl(ft, n, m, l);
        lsfitlinearinternal(b, wmod, l, n, n, info, tmp, rep);
        if( info<=0 )
        {
            return;
        }
        for(i = 0; i <= n-1; i++)
        {
            v = tmp(i);
            ap::vadd(&c(0), 1, &q(i, 0), 1, ap::vlen(0,m-1), v);
        }
        return;
    }
    
    //
    // N>=M. Generate design matrix and reduce to N=M using
    // QR decomposition.
    //
    ft.setlength(n, m);
    b.setlength(n);
    for(j = 0; j <= n-1; j++)
    {
        v = w(j);
        ap::vmove(&ft(j, 0), 1, &fmatrix(j, 0), 1, ap::vlen(0,m-1), v);
        b(j) = w(j)*y(j);
    }
    rmatrixqr(ft, n, m, tau);
    rmatrixqrunpackq(ft, n, m, tau, m, q);
    rmatrixqrunpackr(ft, n, m, r);
    tmp.setlength(m);
    for(i = 0; i <= m-1; i++)
    {
        tmp(i) = 0;
    }
    for(i = 0; i <= n-1; i++)
    {
        v = b(i);
        ap::vadd(&tmp(0), 1, &q(i, 0), 1, ap::vlen(0,m-1), v);
    }
    b.setlength(m);
    ap::vmove(&b(0), 1, &tmp(0), 1, ap::vlen(0,m-1));
    
    //
    // R contains reduced MxM design upper triangular matrix,
    // B contains reduced Mx1 right part.
    //
    // Determine system condition number and decide
    // should we use triangular solver (faster) or
    // SVD-based solver (more stable).
    //
    // We can use LU-based RCond estimator for this task.
    //
    rep.taskrcond = rmatrixlurcondinf(r, m);
    if( ap::fp_greater(rep.taskrcond,threshold) )
    {
        
        //
        // use QR-based solver
        //
        c.setlength(m);
        c(m-1) = b(m-1)/r(m-1,m-1);
        for(i = m-2; i >= 0; i--)
        {
            v = ap::vdotproduct(&r(i, i+1), 1, &c(i+1), 1, ap::vlen(i+1,m-1));
            c(i) = (b(i)-v)/r(i,i);
        }
    }
    else
    {
        
        //
        // use SVD-based solver
        //
        if( !rmatrixsvd(r, m, m, 1, 1, 2, sv, u, vt) )
        {
            info = -4;
            return;
        }
        utb.setlength(m);
        sutb.setlength(m);
        for(i = 0; i <= m-1; i++)
        {
            utb(i) = 0;
        }
        for(i = 0; i <= m-1; i++)
        {
            v = b(i);
            ap::vadd(&utb(0), 1, &u(i, 0), 1, ap::vlen(0,m-1), v);
        }
        if( ap::fp_greater(sv(0),0) )
        {
            rep.taskrcond = sv(m-1)/sv(0);
            for(i = 0; i <= m-1; i++)
            {
                if( ap::fp_greater(sv(i),threshold*sv(0)) )
                {
                    sutb(i) = utb(i)/sv(i);
                }
                else
                {
                    sutb(i) = 0;
                }
            }
        }
        else
        {
            rep.taskrcond = 0;
            for(i = 0; i <= m-1; i++)
            {
                sutb(i) = 0;
            }
        }
        c.setlength(m);
        for(i = 0; i <= m-1; i++)
        {
            c(i) = 0;
        }
        for(i = 0; i <= m-1; i++)
        {
            v = sutb(i);
            ap::vadd(&c(0), 1, &vt(i, 0), 1, ap::vlen(0,m-1), v);
        }
    }
    
    //
    // calculate errors
    //
    rep.rmserror = 0;
    rep.avgerror = 0;
    rep.avgrelerror = 0;
    rep.maxerror = 0;
    relcnt = 0;
    for(i = 0; i <= n-1; i++)
    {
        v = ap::vdotproduct(&fmatrix(i, 0), 1, &c(0), 1, ap::vlen(0,m-1));
        rep.rmserror = rep.rmserror+ap::sqr(v-y(i));
        rep.avgerror = rep.avgerror+fabs(v-y(i));
        if( ap::fp_neq(y(i),0) )
        {
            rep.avgrelerror = rep.avgrelerror+fabs(v-y(i))/fabs(y(i));
            relcnt = relcnt+1;
        }
        rep.maxerror = ap::maxreal(rep.maxerror, fabs(v-y(i)));
    }
    rep.rmserror = sqrt(rep.rmserror/n);
    rep.avgerror = rep.avgerror/n;
    if( relcnt!=0 )
    {
        rep.avgrelerror = rep.avgrelerror/relcnt;
    }
}
Esempio n. 11
0
void
PRoster::InitBackend(void)
{
	StringValue sv("A application roster service object");
	SetProperty("Description",&sv);
}
Esempio n. 12
0
void dgMatrix::EigenVectors (dgVector &eigenValues, const dgMatrix* const initialGuess)
{
	dgMatrix& mat = *this;
	dgMatrix eigenVectors (dgGetIdentityMatrix());
	if (initialGuess) {
		eigenVectors = *initialGuess;
		mat = eigenVectors.Transpose4X4() * mat * eigenVectors;
	}

	dgVector d (mat[0][0], mat[1][1], mat[2][2], dgFloat32 (0.0f)); 
	dgVector b (d);
	for (dgInt32 i = 0; i < 50; i++) {
		dgFloat32 sm = dgAbsf(mat[0][1]) + dgAbsf(mat[0][2]) + dgAbsf(mat[1][2]);

		if (sm < dgFloat32 (1.0e-12f)) {
			// order the eigenvalue vectors	
			dgVector tmp (eigenVectors.m_front * eigenVectors.m_up);
			if (tmp % eigenVectors.m_right < dgFloat32(0.0f)) {
				dgAssert (0.0f);
				eigenVectors.m_right = eigenVectors.m_right.Scale3 (-dgFloat32(1.0f));
			}
			break;
		}

		dgFloat32 thresh = dgFloat32 (0.0f);
		if (i < 3) {
			thresh = (dgFloat32)(0.2f / 9.0f) * sm;
		}

		dgVector z (dgVector::m_zero);
		for (dgInt32 ip = 0; ip < 2; ip ++) {
			for (dgInt32 iq = ip + 1; iq < 3; iq ++) {
				dgFloat32 g = dgFloat32 (100.0f) * dgAbsf(mat[ip][iq]);
				if ((i > 3) && ((dgAbsf(d[ip]) + g) == dgAbsf(d[ip])) && ((dgAbsf(d[iq]) + g) == dgAbsf(d[iq]))) {
					mat[ip][iq] = dgFloat32 (0.0f);
				} else if (dgAbsf(mat[ip][iq]) > thresh) {

					dgFloat32 t;
					dgFloat32 h = d[iq] - d[ip];
					if (dgAbsf(h) + g == dgAbsf(h)) {
						t = mat[ip][iq] / h;
					} else {
						dgFloat32 theta = dgFloat32 (0.5f) * h / mat[ip][iq];
						t = dgFloat32(1.0f) / (dgAbsf(theta) + dgSqrt(dgFloat32(1.0f) + theta * theta));
						if (theta < dgFloat32 (0.0f)) {
							t = -t;
						}
					}
					dgFloat32 c = dgRsqrt (dgFloat32 (1.0f) + t * t); 
					dgFloat32 s = t * c; 
					dgFloat32 tau = s / (dgFloat32(1.0f) + c); 
					h = t * mat[ip][iq];
					z[ip] -= h; 
					z[iq] += h; 
					d[ip] -= h; 
					d[iq] += h;
					mat[ip][iq] = dgFloat32(0.0f);

					for (dgInt32 j = 0; j <= ip - 1; j ++) {
						dgFloat32 g = mat[j][ip]; 
						dgFloat32 h = mat[j][iq]; 
						mat[j][ip] = g - s * (h + g * tau); 
						mat[j][iq] = h + s * (g - h * tau);
					}
					for (dgInt32 j = ip + 1; j <= iq - 1; j ++) {
						dgFloat32 g = mat[ip][j]; 
						dgFloat32 h = mat[j][iq]; 
						mat[ip][j] = g - s * (h + g * tau); 
						mat[j][iq] = h + s * (g - h * tau);
					}
					for (dgInt32 j = iq + 1; j < 3; j ++) {
						dgFloat32 g = mat[ip][j]; 
						dgFloat32 h = mat[iq][j]; 
						mat[ip][j] = g - s * (h + g * tau); 
						mat[iq][j] = h + s * (g - h * tau);
					}

					dgVector sv (s);
					dgVector tauv (tau);
					dgVector gv (eigenVectors[ip]);
					dgVector hv (eigenVectors[iq]);
					eigenVectors[ip] -= sv.CompProduct4 (hv + gv.CompProduct4(tauv)); 
					eigenVectors[iq] += sv.CompProduct4 (gv - hv.CompProduct4(tauv));
				}
			}
		}

		b += z; 
		d = b; 
	}

	eigenValues = d;
	*this = eigenVectors;
}
Esempio n. 13
0
void TestEnemy::update(){
    Math::Vector2D sv(1, 1);
    WorldHandler::getInstance()->movementCheck(editPosition(), sv, editScene(), true, false);
}
Esempio n. 14
0
//------------------------------------------------------------------------------
//! 
void 
ParametricPatch::evalCubic( const Vec2f& uv, Vec3f& pos, Vec3f& normal ) const
{
   float um1 = (1.0f-uv.x);
   float um2 = um1*um1;
   float um3 = um2*um1;

   float u1 = uv.x;
   float u2 = u1*u1;
   float u3 = u2*u1;

   float vm1 = (1.0f-uv.y);
   float vm2 = vm1*vm1;
   float vm3 = vm2*vm1;

   float v1 = uv.y;
   float v2 = v1*v1;
   float v3 = v2*v1;

   float uc[4];
   uc[0] = um3;
   uc[1] = um2*u1*3.0f;
   uc[2] = um1*u2*3.0f;
   uc[3] = u3;

   float vc[4];
   vc[0] = vm3;
   vc[1] = vm2*v1*3.0f;
   vc[2] = vm1*v2*3.0f;
   vc[3] = v3;

   float ud[4];
   ud[0] = um2*-3.0f;
   ud[1] = um1*(3.0f-9.0f*u1);
   ud[2] = (6.0f-9.0f*u1)*u1;
   ud[3] = u2*3.0f;

   float vd[4];
   vd[0] = vm2*-3.0f;
   vd[1] = vm1*(3.0f-9.0f*v1);
   vd[2] = (6.0f-9.0f*v1)*v1;
   vd[3] = v2*3.0f;

   Vec3f p(0.0f);
   Vec3f su(0.0f);
   Vec3f sv(0.0f);

   const Vec3f* b = _b;
   for( uint j = 0; j < 4; ++j )
   {
      Vec3f cp(0.0f);
      Vec3f csu(0.0f);
      for( uint i = 0; i < 4; ++i, ++b )
      {
         cp  += (*b)*(uc[i]);
         csu += (*b)*(ud[i]);
      }
      p  += cp*vc[j];
      su += csu*vc[j];
      sv += cp*vd[j];
   }

   pos = p;

   // Normal computation.
   Vec3f dir = su.cross( sv );
   float len = dir.length();

   // FIXME: should have a better more general solution.
   if( len < 1e-5 )
   {
      normal = (_b[10]-_b[15]).cross( su ).getNormalized();
   }
   else
   {
      normal = dir / len;
   }
}
Esempio n. 15
0
void MainMenu::launch_sensor_view_num(){
	SensorView sv(SensorView::DISP_NUMBER);
	sv.exec();
}
Esempio n. 16
0
static int dotag(BW *bw, unsigned char *s, void *obj, int *notify)
{
	unsigned char buf[512];
	unsigned char buf1[512];
	FILE *f;
	unsigned char *t = NULL;

	if (notify) {
		*notify = 1;
	}
	if (bw->b->name) {
		t = vsncpy(t, 0, sz(bw->b->name));
		t = vsncpy(sv(t), sc(":"));
		t = vsncpy(sv(t), sv(s));
	}
	/* first try to open the tags file in the current directory */
	f = fopen("tags", "r");
	if (!f) {
		/* if there's no tags file in the current dir, then query
		   for the environment variable TAGS.
		*/
		char *tagspath = getenv("TAGS");
		if(tagspath){
			f = fopen(tagspath, "r");    
		}
		if(!f){
			msgnw(bw->parent, joe_gettext(_("Couldn't open tags file")));
			vsrm(s);
			vsrm(t);
			return -1;
		}
	}
	while (fgets((char *)buf, 512, f)) {
		int x, y, c;

		for (x = 0; buf[x] && buf[x] != ' ' && buf[x] != '\t'; ++x) ;
		c = buf[x];
		buf[x] = 0;
		if (!strcmp(s, buf) || (t && !strcmp(t, buf))) {
			buf[x] = c;
			while (buf[x] == ' ' || buf[x] == '\t') {
				++x;
			}
			for (y = x; buf[y] && buf[y] != ' ' && buf[y] != '\t' && buf[y] != '\n'; ++y) ;
			if (x != y) {
				c = buf[y];
				buf[y] = 0;
				if (doswitch(bw, vsncpy(NULL, 0, sz(buf + x)), NULL, NULL)) {
					vsrm(s);
					vsrm(t);
					fclose(f);
					return -1;
				}
				bw = (BW *) maint->curwin->object;
				p_goto_bof(bw->cursor);
				buf[y] = c;
				while (buf[y] == ' ' || buf[y] == '\t') {
					++y;
				}
				for (x = y; buf[x] && buf[x] != '\n'; ++x) ;
				buf[x] = 0;
				if (x != y) {
					long line = 0;

					if (buf[y] >= '0' && buf[y] <= '9') {
						/* It's a line number */
						sscanf((char *)(buf + y), "%ld", &line);
						if (line >= 1) {
							int omid = mid;

							mid = 1;
							pline(bw->cursor, line - 1), bw->cursor->xcol = piscol(bw->cursor);
							dofollows();
							mid = omid;
						} else {
							msgnw(bw->parent, joe_gettext(_("Invalid line number")));
						}
					} else {
						int z = 0;
						/* It's a search string. New versions of
						   ctags have real regex with vi command.  Old
						   ones do not always quote / and depend on it
						   being last char on line. */
						if (buf[y] == '/' || buf[y] == '?') {
							int ch = buf[y++];
							/* Find terminating / or ? */
							for (x = y + strlen(buf + y); x != y; --x)
								if (buf[x] == ch)
									break;
							/* Copy characters, convert to JOE regex... */
							if (buf[y] == '^') {
								buf1[z++] = '\\';
								buf1[z++] = '^';
								++y;
							}
							while (buf[y] && buf[y] != '\n' && !(buf[y] == ch && y == x)) {
								if (buf[y] == '$' && buf[y+1] == ch) {
									++y;
									buf1[z++] = '\\';
									buf1[z++] = '$';
								} else if (buf[y] == '\\' && buf[y+1]) {
									/* This is going to cause problem...
									   old ctags did not have escape */
									++y;
									if (buf[y] == '\\')
										buf1[z++] = '\\';
									buf1[z++] = buf[y++];
								} else {
									buf1[z++] = buf[y++];
								}
							}
						}
						if (z) {
							vsrm(s);
							vsrm(t);
							fclose(f);
							buf1[z] = 0;
							return dopfnext(bw, mksrch(vsncpy(NULL, 0, sz(buf1)), NULL, 0, 0, -1, 0, 0, 0), NULL);
						}
					}
				}
				vsrm(s);
				vsrm(t);
				fclose(f);
				return 0;
			}
		}
	}
	msgnw(bw->parent, joe_gettext(_("Not found")));
	vsrm(s);
	vsrm(t);
	fclose(f);
	return -1;
}
Esempio n. 17
0
void MainMenu::launch_sensor_view_bar(){
	SensorView sv(SensorView::DISP_PROGRESS);
	sv.exec();
}
Esempio n. 18
0
/*************************************************************************
Internal linear regression subroutine
*************************************************************************/
static void lrinternal(const ap::real_2d_array& xy,
     const ap::real_1d_array& s,
     int npoints,
     int nvars,
     int& info,
     linearmodel& lm,
     lrreport& ar)
{
    ap::real_2d_array a;
    ap::real_2d_array u;
    ap::real_2d_array vt;
    ap::real_2d_array vm;
    ap::real_2d_array xym;
    ap::real_1d_array b;
    ap::real_1d_array sv;
    ap::real_1d_array t;
    ap::real_1d_array svi;
    ap::real_1d_array work;
    int i;
    int j;
    int k;
    int ncv;
    int na;
    int nacv;
    double r;
    double p;
    double epstol;
    lrreport ar2;
    int offs;
    linearmodel tlm;

    epstol = 1000;
    
    //
    // Check for errors in data
    //
    if( npoints<nvars||nvars<1 )
    {
        info = -1;
        return;
    }
    for(i = 0; i <= npoints-1; i++)
    {
        if( ap::fp_less_eq(s(i),0) )
        {
            info = -2;
            return;
        }
    }
    info = 1;
    
    //
    // Create design matrix
    //
    a.setbounds(0, npoints-1, 0, nvars-1);
    b.setbounds(0, npoints-1);
    for(i = 0; i <= npoints-1; i++)
    {
        r = 1/s(i);
        ap::vmove(&a(i, 0), &xy(i, 0), ap::vlen(0,nvars-1), r);
        b(i) = xy(i,nvars)/s(i);
    }
    
    //
    // Allocate W:
    // W[0]     array size
    // W[1]     version number, 0
    // W[2]     NVars (minus 1, to be compatible with external representation)
    // W[3]     coefficients offset
    //
    lm.w.setbounds(0, 4+nvars-1);
    offs = 4;
    lm.w(0) = 4+nvars;
    lm.w(1) = lrvnum;
    lm.w(2) = nvars-1;
    lm.w(3) = offs;
    
    //
    // Solve problem using SVD:
    //
    // 0. check for degeneracy (different types)
    // 1. A = U*diag(sv)*V'
    // 2. T = b'*U
    // 3. w = SUM((T[i]/sv[i])*V[..,i])
    // 4. cov(wi,wj) = SUM(Vji*Vjk/sv[i]^2,K=1..M)
    //
    // see $15.4 of "Numerical Recipes in C" for more information
    //
    t.setbounds(0, nvars-1);
    svi.setbounds(0, nvars-1);
    ar.c.setbounds(0, nvars-1, 0, nvars-1);
    vm.setbounds(0, nvars-1, 0, nvars-1);
    if( !rmatrixsvd(a, npoints, nvars, 1, 1, 2, sv, u, vt) )
    {
        info = -4;
        return;
    }
    if( ap::fp_less_eq(sv(0),0) )
    {
        
        //
        // Degenerate case: zero design matrix.
        //
        for(i = offs; i <= offs+nvars-1; i++)
        {
            lm.w(i) = 0;
        }
        ar.rmserror = lrrmserror(lm, xy, npoints);
        ar.avgerror = lravgerror(lm, xy, npoints);
        ar.avgrelerror = lravgrelerror(lm, xy, npoints);
        ar.cvrmserror = ar.rmserror;
        ar.cvavgerror = ar.avgerror;
        ar.cvavgrelerror = ar.avgrelerror;
        ar.ncvdefects = 0;
        ar.cvdefects.setbounds(0, nvars-1);
        ar.c.setbounds(0, nvars-1, 0, nvars-1);
        for(i = 0; i <= nvars-1; i++)
        {
            for(j = 0; j <= nvars-1; j++)
            {
                ar.c(i,j) = 0;
            }
        }
        return;
    }
    if( ap::fp_less_eq(sv(nvars-1),epstol*ap::machineepsilon*sv(0)) )
    {
        
        //
        // Degenerate case, non-zero design matrix.
        //
        // We can leave it and solve task in SVD least squares fashion.
        // Solution and covariance matrix will be obtained correctly,
        // but CV error estimates - will not. It is better to reduce
        // it to non-degenerate task and to obtain correct CV estimates.
        //
        for(k = nvars; k >= 1; k--)
        {
            if( ap::fp_greater(sv(k-1),epstol*ap::machineepsilon*sv(0)) )
            {
                
                //
                // Reduce
                //
                xym.setbounds(0, npoints-1, 0, k);
                for(i = 0; i <= npoints-1; i++)
                {
                    for(j = 0; j <= k-1; j++)
                    {
                        r = ap::vdotproduct(&xy(i, 0), &vt(j, 0), ap::vlen(0,nvars-1));
                        xym(i,j) = r;
                    }
                    xym(i,k) = xy(i,nvars);
                }
                
                //
                // Solve
                //
                lrinternal(xym, s, npoints, k, info, tlm, ar2);
                if( info!=1 )
                {
                    return;
                }
                
                //
                // Convert back to un-reduced format
                //
                for(j = 0; j <= nvars-1; j++)
                {
                    lm.w(offs+j) = 0;
                }
                for(j = 0; j <= k-1; j++)
                {
                    r = tlm.w(offs+j);
                    ap::vadd(&lm.w(offs), &vt(j, 0), ap::vlen(offs,offs+nvars-1), r);
                }
                ar.rmserror = ar2.rmserror;
                ar.avgerror = ar2.avgerror;
                ar.avgrelerror = ar2.avgrelerror;
                ar.cvrmserror = ar2.cvrmserror;
                ar.cvavgerror = ar2.cvavgerror;
                ar.cvavgrelerror = ar2.cvavgrelerror;
                ar.ncvdefects = ar2.ncvdefects;
                ar.cvdefects.setbounds(0, nvars-1);
                for(j = 0; j <= ar.ncvdefects-1; j++)
                {
                    ar.cvdefects(j) = ar2.cvdefects(j);
                }
                ar.c.setbounds(0, nvars-1, 0, nvars-1);
                work.setbounds(1, nvars);
                matrixmatrixmultiply(ar2.c, 0, k-1, 0, k-1, false, vt, 0, k-1, 0, nvars-1, false, 1.0, vm, 0, k-1, 0, nvars-1, 0.0, work);
                matrixmatrixmultiply(vt, 0, k-1, 0, nvars-1, true, vm, 0, k-1, 0, nvars-1, false, 1.0, ar.c, 0, nvars-1, 0, nvars-1, 0.0, work);
                return;
            }
        }
        info = -255;
        return;
    }
    for(i = 0; i <= nvars-1; i++)
    {
        if( ap::fp_greater(sv(i),epstol*ap::machineepsilon*sv(0)) )
        {
            svi(i) = 1/sv(i);
        }
        else
        {
            svi(i) = 0;
        }
    }
    for(i = 0; i <= nvars-1; i++)
    {
        t(i) = 0;
    }
    for(i = 0; i <= npoints-1; i++)
    {
        r = b(i);
        ap::vadd(&t(0), &u(i, 0), ap::vlen(0,nvars-1), r);
    }
    for(i = 0; i <= nvars-1; i++)
    {
        lm.w(offs+i) = 0;
    }
    for(i = 0; i <= nvars-1; i++)
    {
        r = t(i)*svi(i);
        ap::vadd(&lm.w(offs), &vt(i, 0), ap::vlen(offs,offs+nvars-1), r);
    }
    for(j = 0; j <= nvars-1; j++)
    {
        r = svi(j);
        ap::vmove(vm.getcolumn(j, 0, nvars-1), vt.getrow(j, 0, nvars-1), r);
    }
    for(i = 0; i <= nvars-1; i++)
    {
        for(j = i; j <= nvars-1; j++)
        {
            r = ap::vdotproduct(&vm(i, 0), &vm(j, 0), ap::vlen(0,nvars-1));
            ar.c(i,j) = r;
            ar.c(j,i) = r;
        }
    }
    
    //
    // Leave-1-out cross-validation error.
    //
    // NOTATIONS:
    // A            design matrix
    // A*x = b      original linear least squares task
    // U*S*V'       SVD of A
    // ai           i-th row of the A
    // bi           i-th element of the b
    // xf           solution of the original LLS task
    //
    // Cross-validation error of i-th element from a sample is
    // calculated using following formula:
    //
    //     ERRi = ai*xf - (ai*xf-bi*(ui*ui'))/(1-ui*ui')     (1)
    //
    // This formula can be derived from normal equations of the
    // original task
    //
    //     (A'*A)x = A'*b                                    (2)
    //
    // by applying modification (zeroing out i-th row of A) to (2):
    //
    //     (A-ai)'*(A-ai) = (A-ai)'*b
    //
    // and using Sherman-Morrison formula for updating matrix inverse
    //
    // NOTE 1: b is not zeroed out since it is much simpler and
    // does not influence final result.
    //
    // NOTE 2: some design matrices A have such ui that 1-ui*ui'=0.
    // Formula (1) can't be applied for such cases and they are skipped
    // from CV calculation (which distorts resulting CV estimate).
    // But from the properties of U we can conclude that there can
    // be no more than NVars such vectors. Usually
    // NVars << NPoints, so in a normal case it only slightly
    // influences result.
    //
    ncv = 0;
    na = 0;
    nacv = 0;
    ar.rmserror = 0;
    ar.avgerror = 0;
    ar.avgrelerror = 0;
    ar.cvrmserror = 0;
    ar.cvavgerror = 0;
    ar.cvavgrelerror = 0;
    ar.ncvdefects = 0;
    ar.cvdefects.setbounds(0, nvars-1);
    for(i = 0; i <= npoints-1; i++)
    {
        
        //
        // Error on a training set
        //
        r = ap::vdotproduct(&xy(i, 0), &lm.w(offs), ap::vlen(0,nvars-1));
        ar.rmserror = ar.rmserror+ap::sqr(r-xy(i,nvars));
        ar.avgerror = ar.avgerror+fabs(r-xy(i,nvars));
        if( ap::fp_neq(xy(i,nvars),0) )
        {
            ar.avgrelerror = ar.avgrelerror+fabs((r-xy(i,nvars))/xy(i,nvars));
            na = na+1;
        }
        
        //
        // Error using fast leave-one-out cross-validation
        //
        p = ap::vdotproduct(&u(i, 0), &u(i, 0), ap::vlen(0,nvars-1));
        if( ap::fp_greater(p,1-epstol*ap::machineepsilon) )
        {
            ar.cvdefects(ar.ncvdefects) = i;
            ar.ncvdefects = ar.ncvdefects+1;
            continue;
        }
        r = s(i)*(r/s(i)-b(i)*p)/(1-p);
        ar.cvrmserror = ar.cvrmserror+ap::sqr(r-xy(i,nvars));
        ar.cvavgerror = ar.cvavgerror+fabs(r-xy(i,nvars));
        if( ap::fp_neq(xy(i,nvars),0) )
        {
            ar.cvavgrelerror = ar.cvavgrelerror+fabs((r-xy(i,nvars))/xy(i,nvars));
            nacv = nacv+1;
        }
        ncv = ncv+1;
    }
    if( ncv==0 )
    {
        
        //
        // Something strange: ALL ui are degenerate.
        // Unexpected...
        //
        info = -255;
        return;
    }
    ar.rmserror = sqrt(ar.rmserror/npoints);
    ar.avgerror = ar.avgerror/npoints;
    if( na!=0 )
    {
        ar.avgrelerror = ar.avgrelerror/na;
    }
    ar.cvrmserror = sqrt(ar.cvrmserror/ncv);
    ar.cvavgerror = ar.cvavgerror/ncv;
    if( nacv!=0 )
    {
        ar.cvavgrelerror = ar.cvavgrelerror/nacv;
    }
}
Esempio n. 19
0
  Object* Channel::receive_timeout(STATE, Object* duration, CallFrame* call_frame) {
    if(!value_->empty_p()) return value_->shift(state);

    // Otherwise, we need to wait for a value.
    struct timespec ts = {0,0};
    bool use_timed_wait = true;

    if(Fixnum* fix = try_as<Fixnum>(duration)) {
      ts.tv_sec = fix->to_native();
    } else if(Float* flt = try_as<Float>(duration)) {
      uint64_t nano = (uint64_t)(flt->val * NANOSECONDS);
      ts.tv_sec  =  (time_t)(nano / NANOSECONDS);
      ts.tv_nsec =    (long)(nano % NANOSECONDS);
    } else if(duration->nil_p()) {
      use_timed_wait = false;
    } else {
      return Primitives::failure();
    }

    // Passing control away means that the GC might run. So we need
    // to stash this into a root, and read it back out again after
    // control is returned.
    //
    // DO NOT USE this AFTER wait().

    // We have to do this because we can't pass this to OnStack, since C++
    // won't let us reassign it.
    Channel* self = this;
    OnStack<1> sv(state, self);

    // We pin this so we can pass condition_ out without worrying about
    // us moving it.
    this->pin();

    WaitingOnCondition waiter(condition_);

    state->install_waiter(waiter);
    waiters_++;
    state->thread->sleep(state, Qtrue);

    struct timeval tv = {0,0};
    if(use_timed_wait) {
      gettimeofday(&tv, 0);
      uint64_t nano = ts.tv_nsec + tv.tv_usec * 1000;
      ts.tv_sec  += tv.tv_sec + nano / NANOSECONDS;
      ts.tv_nsec  = nano % NANOSECONDS;
    }

    for(;;) {
      state->set_call_frame(call_frame);

      if(use_timed_wait) {
        if(condition_.wait_until(state->global_lock(), &ts) == thread::cTimedOut) break;
      } else {
        condition_.wait(state->global_lock());
      }

      // Stop waiting if...
      // we've been asked explicitely to wakeup..
      if(waiter.used()) break;

      // or there are values available.
      if(!value_->empty_p()) break;
    }

    self->unpin();
    self->waiters_--;

    state->clear_waiter();
    state->thread->sleep(state, Qfalse);
    if(!state->check_async(call_frame)) return NULL;

    // We were awoken, but there is no value to use. Return nil.
    if(self->value()->empty_p()) {
      return Qnil;
    }

    return self->value()->shift(state);
  }
Esempio n. 20
0
// primaryExpr ::= NUMBER
//               | STRING
//               | variable
//               | function '(' exprList ')'
//               | '(' expr ')'
std::unique_ptr<Expr> FlowParser::primaryExpr()
{
	FNTRACE();

	static struct {
		const char* ident;
		long long nominator;
		long long denominator;
	} units[] = {
		{ "byte", 1, 1 },
		{ "kbyte", 1024llu, 1 },
		{ "mbyte", 1024llu * 1024, 1 },
		{ "gbyte", 1024llu * 1024 * 1024, 1 },
		{ "tbyte", 1024llu * 1024 * 1024 * 1024, 1 },
		{ "bit", 1, 8 },
		{ "kbit", 1024llu, 8 },
		{ "mbit", 1024llu * 1024, 8 },
		{ "gbit", 1024llu * 1024 * 1024, 8 },
		{ "tbit", 1024llu * 1024 * 1024 * 1024, 8 },
		{ "sec", 1, 1 },
		{ "min", 60llu, 1 },
		{ "hour", 60llu * 60, 1 },
		{ "day", 60llu * 60 * 24, 1 },
		{ "week", 60llu * 60 * 24 * 7, 1 },
		{ "month", 60llu * 60 * 24 * 30, 1 },
		{ "year", 60llu * 60 * 24 * 365, 1 },
		{ nullptr, 1, 1 }
	};

	FlowLocation loc(location());

	switch (token()) {
		case FlowToken::Ident: {
			std::string name = stringValue();
			nextToken();

			Symbol* symbol = scope()->lookup(name, Lookup::All);
			if (!symbol) {
                // XXX assume that given symbol is a auto forward-declared handler.
                Handler* href = (Handler*) globalScope()->appendSymbol(std::make_unique<Handler>(name, loc));
				return std::make_unique<HandlerRefExpr>(href, loc);
			}

			if (auto variable = dynamic_cast<Variable*>(symbol))
				return std::make_unique<VariableExpr>(variable, loc);

			if (auto handler = dynamic_cast<Handler*>(symbol))
				return std::make_unique<HandlerRefExpr>(handler, loc);

			if (symbol->type() == Symbol::BuiltinFunction) {
				if (token() != FlowToken::RndOpen)
					return std::make_unique<FunctionCallExpr>((BuiltinFunction*) symbol, ExprList()/*args*/, loc);

				nextToken();
                ExprList args;
				bool rv = listExpr(args);
				consume(FlowToken::RndClose);
				if (!rv) return nullptr;
				return std::make_unique<FunctionCallExpr>((BuiltinFunction*) symbol, std::move(args), loc);
			}

			reportError("Unsupported symbol type of '%s' in expression.", name.c_str());
			return nullptr;
		}
		case FlowToken::Boolean: {
			std::unique_ptr<BoolExpr> e = std::make_unique<BoolExpr>(booleanValue(), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::RegExp: {
			std::unique_ptr<RegExpExpr> e = std::make_unique<RegExpExpr>(RegExp(stringValue()), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::InterpolatedStringFragment:
			return interpolatedStr();
		case FlowToken::String:
		case FlowToken::RawString: {
			std::unique_ptr<StringExpr> e = std::make_unique<StringExpr>(stringValue(), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::Number: { // NUMBER [UNIT]
			auto number = numberValue();
			nextToken();

			if (token() == FlowToken::Ident) {
				std::string sv(stringValue());
				for (size_t i = 0; units[i].ident; ++i) {
					if (sv == units[i].ident
						|| (sv[sv.size() - 1] == 's' && sv.substr(0, sv.size() - 1) == units[i].ident))
					{
						nextToken(); // UNIT
						number = number * units[i].nominator / units[i].denominator;
						loc.update(end());
						break;
					}
				}
			}
			return std::make_unique<NumberExpr>(number, loc);
		}
		case FlowToken::IP: {
			std::unique_ptr<IPAddressExpr> e = std::make_unique<IPAddressExpr>(lexer_->ipValue(), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::Cidr: {
			std::unique_ptr<CidrExpr> e = std::make_unique<CidrExpr>(lexer_->cidr(), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::StringType:
		case FlowToken::NumberType:
		case FlowToken::BoolType:
			return castExpr();
		case FlowToken::Begin: { // lambda-like inline function ref
			char name[64];
			static unsigned long i = 0;
            ++i;
			snprintf(name, sizeof(name), "__lambda_%lu", i);

			FlowLocation loc = location();
			auto st = std::make_unique<SymbolTable>(scope(), name);
			enter(st.get());
			std::unique_ptr<Stmt> body = compoundStmt();
			leave();

			if (!body)
				return nullptr;

			loc.update(body->location().end);

			Handler* handler = new Handler(name, std::move(st), std::move(body), loc);
			// TODO (memory leak): add handler to unit's global scope, i.e. via:
			//       - scope()->rootScope()->insert(handler);
			//       - unit_->scope()->insert(handler);
			//       to get free'd
			return std::make_unique<HandlerRefExpr>(handler, loc);
		}
		case FlowToken::RndOpen: {
			nextToken();
			std::unique_ptr<Expr> e = expr();
			consume(FlowToken::RndClose);
			e->setLocation(loc.update(end()));
			return e;
		}
		default:
			TRACE(1, "Expected primary expression. Got something... else.");
			reportUnexpectedToken();
			return nullptr;
	}
}
Esempio n. 21
0
int test_main(int, char **)
{
  boost::basic_string_ref<char> sv(makeatemp());
  return 0;
}
Esempio n. 22
0
/**
 * \brief drawText,		render 2D text on the screen (Orthogonal Projection)
 * @param str,			text string.
 * @param pos,			2D position on screen,
 * @param rgba,			text color
 * @param tick			time elapsed
 * @return float width 	of text string.
 */
float RenderText::drawText(const char*str, glm::vec3 &pos, glm::vec4 &rgba, float tick)
{
//	checkGLError("RenderText::DrawText   Should be ok!");
	float width = 0;
	mOPos = glm::vec3(0.0f,0.0f,0.0f);
	mOPos = pos;
	int num = strlen(str);
	glm::vec4 *vertices = 0;

	glDisable(GL_DEPTH_TEST);
	glm::mat4 m = glm::ortho(0.0f, static_cast<float>(mWidth),static_cast<float>(mHeight),0.0f,-200.0f,1000.0f);

	// Use the font class to build the vertex array from the sentence text and sentence draw location.
	// Create the vertex array.

	mScaleY = -mScaleY;
	vertices = getVertices(str, false, &width);		// note uses m_pos creates or retrieves existing vertex buffer from a cache table
	mScaleY = -mScaleY;

	TextShader &shader= mTextShader;
	glEnable (GL_BLEND);
	mBlendType = BL_ADDITIVE;
	switch (mBlendType)
	{
	case BL_ADDITIVE:					// Additive
		glBlendFunc(GL_ONE, GL_ONE);
//		glBlendFunc( GL_DST_ALPHA, GL_ONE_MINUS_SRC_COLOR );	// very good additive
		break;
	case BL_TRANSLUCENT:				// Requires alpha
		glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
//		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);	// Texture uses alpha
		break;
	case BL_SUBTRACTIVE:
		//glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
		glBlendFunc( GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA ); //subtractive black => max
//		glBlendFunc(GL_ZERO, GL_SRC_ALPHA);		// needs alpha
//		glBlendFunc(GL_ZERO, GL_SRC_COLOR);
		break;
	case BL_TRANSPARENT:
		glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
		break;
	}

	// Use the program object
	glUseProgram(shader.mShader);
	checkGLError("RenderText::DrawText   glUseProgram (Text)");

	// 1. create buffers tri array for simplicity? so that every tri can be handled separately or with a new index buffer could be expensive though???
	// Load the vertex data
	glVertexAttribPointer(shader.mAttribVtxLoc, 4, GL_FLOAT, GL_FALSE, sizeof(float)*4, &vertices[0].x);
	checkGLError("RenderText::DrawText   glVertexAttribPointer (V)");
	glEnableVertexAttribArray(shader.mAttribVtxLoc);
	checkGLError("RenderText::DrawText   glEnableVertexAttribArray (V)");
	glActiveTexture(GL_TEXTURE0 + 0);
	checkGLError("RenderText::DrawText   glActiveTexture");
	glBindTexture(GL_TEXTURE_2D, mFont->GetTexture(0));
	checkGLError("glBindTexture");
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	checkGLError("glTexParameteri");
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	checkGLError("glTexParameteri");
	glUniform1i(shader.mTexture, 0 ); // Texture Unit 0
	checkGLError("RenderText::DrawText   glUniform1i");

	// Once per frame
	glUniform1f(shader.mTimeLoc, tick);
	checkGLError("RenderText::DrawText   glUniform1f");
	glUniform2f(shader.mResolutionLoc, 1.0f/(float)mWidth, 1.0f/(float)mHeight);
	checkGLError("RenderText::DrawText   glUniform2f");
	glUniformMatrix4fv(shader.mMatrixPVW, 1, GL_FALSE, &m[0][0]);
	checkGLError("RenderText::DrawText   glUniformMatrix4fv");
	glm::vec3 sv(1.0f, 1.0f, 1.0f);
	glUniform3fv(shader.mScaleV,1, (float *)&sv.x);				// mScale location => variable "ScaleV" in vertex shader
	checkGLError("RenderText::DrawText   glUniformMatrix3fv");
	glm::vec4 color = rgba;
	glUniform4fv(shader.mColor,1, (float *)&color.x);
	checkGLError("RenderText::DrawText   glUniformMatrix4fv");
	glm::vec4 TPos(mPos.x,mPos.y,mPos.z, 1.0f);
	glUniform4fv(shader.mTPos, 1, (float *)&TPos.x);
	checkGLError("RenderText::DrawText   glUniformMatrix4fv");
	glDrawArrays(GL_TRIANGLES, 0, 6*num);
	checkGLError("RenderText::DrawText   glDrawArrays");

	// Clean-up
	glDisableVertexAttribArray(shader.mAttribVtxLoc);
	checkGLError("RenderText::DrawText   glDisableVertexAttribArray (Vtx)");
	glBindTexture(GL_TEXTURE_2D, 0);
	glUseProgram(0);
	checkGLError("RenderText::DrawText   glUseProgram(0)");

	releaseVertices(vertices, false);
	glDisable(GL_BLEND);

	return width;			// Generate a buffer for the vertices
}
Esempio n. 23
0
int main(int argc, char **real_argv, char **envv)
{
	CAP *cap;
	unsigned char **argv = (unsigned char **)real_argv;
	struct stat sbuf;
	unsigned char *s;
	unsigned char *t;
	long time_rc;
	unsigned char *run;
#ifdef __MSDOS__
	unsigned char *rundir;
#endif
	SCRN *n;
	int opened = 0;
	int omid;
	int backopt;
	int c;

	joe_locale();

	mainenv = (unsigned char **)envv;
	
	vmem = vtmp();
	startup_log = bfind_scratch(USTR "* Startup Log *");
	startup_log->internal = 1;

#ifdef __MSDOS__
	_fmode = O_BINARY;
	zlcpy(stdbuf, sizeof(stdbuf), argv[0]);
	joesep(stdbuf);
	run = namprt(stdbuf);
	rundir = dirprt(stdbuf);
	for (c = 0; run[c]; ++c)
		if (run[c] == '.') {
			run = vstrunc(run, c);
			break;
		}
#else
	run = namprt(argv[0]);
#endif

	if ((s = (unsigned char *)getenv("LINES")) != NULL)
		sscanf((char *)s, "%d", &lines);
	if ((s = (unsigned char *)getenv("COLUMNS")) != NULL)
		sscanf((char *)s, "%d", &columns);
	if ((s = (unsigned char *)getenv("BAUD")) != NULL)
		sscanf((char *)s, "%u", (unsigned *)&Baud);
	if (getenv("DOPADDING"))
		dopadding = 1;
	if (getenv("NOXON"))
		noxon = 1;
	if ((s = (unsigned char *)getenv("JOETERM")) != NULL)
		joeterm = s;

#ifndef __MSDOS__
	if (!(cap = my_getcap(NULL, 9600, NULL, NULL))) {
		logerror_0((char *)joe_gettext(_("Couldn't load termcap/terminfo entry\n")));
		goto exit_errors;
	}
#endif

#ifdef __MSDOS__

	s = vsncpy(NULL, 0, sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}

	vsrm(s);
	s = vsncpy(NULL, 0, sv(rundir));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}
#else

	/* Name of system joerc file.  Try to find one with matching language... */
	
	/* Try full language: like joerc.de_DE */
	t = vsncpy(NULL, 0, sc(JOERC));
	t = vsncpy(sv(t), sv(run));
	t = vsncpy(sv(t), sc("rc."));
	t = vsncpy(sv(t), sz(locale_msgs));
	if (!stat((char *)t,&sbuf))
		time_rc = sbuf.st_mtime;
	else {
		/* Try generic language: like joerc.de */
		if (locale_msgs[0] && locale_msgs[1] && locale_msgs[2]=='_') {
			vsrm(t);
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc."));
			t = vsncpy(sv(t), locale_msgs, 2);
			if (!stat((char *)t,&sbuf))
				time_rc = sbuf.st_mtime;
			else
				goto nope;
		} else {
			nope:
			vsrm(t);
			/* Try Joe's bad english */
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc"));
			if (!stat((char *)t,&sbuf))
				time_rc = sbuf.st_mtime;
			else
				time_rc = 0;
		}
	}

	/* User's joerc file */
	s = (unsigned char *)getenv("HOME");
	if (s) {
		s = vsncpy(NULL, 0, sz(s));
		s = vsncpy(sv(s), sc("/."));
		s = vsncpy(sv(s), sv(run));
		s = vsncpy(sv(s), sc("rc"));

		if (!stat((char *)s,&sbuf)) {
			if (sbuf.st_mtime < time_rc) {
				logmessage_2((char *)joe_gettext(_("Warning: %s is newer than your %s.\n")),t,s);
			}
		}

		c = procrc(cap, s);
		if (c == 0) {
			vsrm(t);
			goto donerc;
		}
		if (c == 1) {
			logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
		}
	}

	vsrm(s);
	s = t;
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}

	/* Try built-in joerc */
	s = vsncpy(NULL, 0, sc("*"));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c != 0 && c != 1) {
		/* If *fancyjoerc not present, use *joerc which is always there */
		s = vstrunc(s, 0);
		s = vsncpy(sv(s),sc("*joerc"));
		c = procrc(cap, s);
	}
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}
#endif

	logerror_1((char *)joe_gettext(_("Couldn't open '%s'\n")), s);
	goto exit_errors;
	return 1;

	donerc:

	if (validate_rc()) {
		logerror_0((char *)joe_gettext(_("rc file has no :main key binding section or no bindings.  Bye.\n")));
		goto exit_errors;
	}

	{
		unsigned char buf[10];
		int x;
		zlcpy(buf, sizeof(buf), USTR "\"`\"	`  ");
		type_backtick = mparse(0, buf, &x, 0);
	}

	shell_kbd = mkkbd(kmap_getcontext(USTR "shell"));

	if (!isatty(fileno(stdin)))
		idleout = 0;

	for (c = 1; argv[c]; ++c) {
		if (argv[c][0] == '-') {
			if (argv[c][1])
				switch (glopt(argv[c] + 1, argv[c + 1], NULL, 1)) {
				case 0:
					logerror_1((char *)joe_gettext(_("Unknown option '%s'\n")), argv[c]);
					break;
				case 1:
					break;
				case 2:
					++c;
					break;
			} else
				idleout = 0;
		}
	}

	/* initialize mouse support */
	if (xmouse && (s=(unsigned char *)getenv("TERM")) && strstr((char *)s,"xterm"))
		usexmouse=1;

	if (!(n = nopen(cap)))
		goto exit_errors;
	maint = screate(n);

	load_state();

	/* It would be better if this ran uedit() to load files */

	/* The business with backopt is to load the file first, then apply file
	 * local options afterwords */

	/* orphan is not compatible with exemac()- macros need a window to exist */
	for (c = 1, backopt = 0; argv[c]; ++c)
		if (argv[c][0] == '+' && argv[c][1]>='0' && argv[c][1]<='9') {
			if (!backopt)
				backopt = c;
		} else if (argv[c][0] == '-' && argv[c][1]) {
			if (!backopt)
				backopt = c;
			if (glopt(argv[c] + 1, argv[c + 1], NULL, 0) == 2)
				++c;
		} else {
			B *b = bfind(argv[c]);
			BW *bw = NULL;
			int er = berror;

			/* This is too annoying */
			/* set_current_dir(argv[c],1); */

			setup_history(&filehist);
			append_history(filehist,sz(argv[c]));

			/* wmktw inserts the window before maint->curwin */
			if (!orphan || !opened) {
				bw = wmktw(maint, b);
				if (er)
					msgnwt(bw->parent, joe_gettext(msgs[-er]));
			} else {
				long line;
				b->orphan = 1;
				b->oldcur = pdup(b->bof, USTR "main");
				pline(b->oldcur, get_file_pos(b->name));
				p_goto_bol(b->oldcur);
				line = b->oldcur->line - (maint->h - 1) / 2;
				if (line < 0)
					line = 0;
				b->oldtop = pdup(b->oldcur, USTR "main");
				pline(b->oldtop, line);
				p_goto_bol(b->oldtop);
			}
			if (bw) {
				long lnum = 0;

				bw->o.readonly = bw->b->rdonly;
				if (backopt) {
					while (backopt != c) {
						if (argv[backopt][0] == '+') {
							sscanf((char *)(argv[backopt] + 1), "%ld", &lnum);
							++backopt;
						} else {
							if (glopt(argv[backopt] + 1, argv[backopt + 1], &bw->o, 0) == 2)
								backopt += 2;
							else
								backopt += 1;
							lazy_opts(bw->b, &bw->o);
						}
					}
				}
				bw->b->o = bw->o;
				bw->b->rdonly = bw->o.readonly;
				/* Put cursor in window, so macros work properly */
				maint->curwin = bw->parent;
				/* Execute macro */
				if (er == -1 && bw->o.mnew)
					exmacro(bw->o.mnew,1);
				if (er == 0 && bw->o.mold)
					exmacro(bw->o.mold,1);
				/* Hmm... window might not exist any more... depends on what macro does... */
				if (lnum > 0)
					pline(bw->cursor, lnum - 1);
				else
					pline(bw->cursor, get_file_pos(bw->b->name));
				p_goto_bol(bw->cursor);
				/* Go back to first window so windows are in same order as command line  */
				if (opened)
					wnext(maint);
				
			}
			opened = 1;
			backopt = 0;
		}

	

	if (opened) {
		wshowall(maint);
		omid = mid;
		mid = 1;
		dofollows();
		mid = omid;
	} else {
		BW *bw = wmktw(maint, bfind(USTR ""));

		if (bw->o.mnew)
			exmacro(bw->o.mnew,1);
	}
	maint->curwin = maint->topwin;

	if (logerrors) {
		B *copied = bcpy(startup_log->bof, startup_log->eof);
		BW *bw = wmktw(maint, copied);
		copied->name = zdup(startup_log->name);
		copied->internal = 1;
		maint->curwin = bw->parent;
		wshowall(maint);
	}

	if (help) {
		help_on(maint);
	}
	if (!nonotice) {
		joe_snprintf_3(msgbuf,JOE_MSGBUFSIZE,joe_gettext(_("\\i** Joe's Own Editor v%s ** (%s) ** Copyright %s 2015 **\\i")),VERSION,locale_map->name,(locale_map->type ? "©" : "(C)"));

		msgnw(((BASE *)lastw(maint)->object)->parent, msgbuf);
	}

	if (!idleout) {
		if (!isatty(fileno(stdin)) && modify_logic(maint->curwin->object, ((BW *)maint->curwin->object)->b)) {
			/* Start shell going in first window */
			unsigned char **a;
			unsigned char *cmd;

			a = vamk(10);
			cmd = vsncpy(NULL, 0, sc("/bin/sh"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("-c"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("/bin/cat"));
			a = vaadd(a, cmd);
			
			cstart (maint->curwin->object, USTR "/bin/sh", a, NULL, NULL, 0, 1, NULL, 0);
		}
	}

	edloop(0);

	save_state();

	/* Delete all buffer so left over locks get eliminated */
	brmall();

	vclose(vmem);
	nclose(n);

	if  (noexmsg) {
		if (notite)
			fprintf(stderr, "\n");
	} else {
		if (exmsg)
			fprintf(stderr, "\n%s\n", exmsg);
		else if (notite)
			fprintf(stderr, "\n");
	}

	return 0;

exit_errors:

	/* Write out error log to console if we are exiting with errors. */
	if (startup_log && startup_log->eof->byte)
		bsavefd(startup_log->bof, 2, startup_log->eof->byte);
	
	return 1;
}
Esempio n. 24
0
/* static */char *stagen(char *stalin, BW *bw, const char *s, char fill)
{
	char buf[80];
	int x;
	int field;
	W *w = bw->parent;
	time_t n=time(NULL);
	struct tm *cas;
	cas=localtime(&n);

	stalin = vstrunc(stalin, 0);
	while (*s) {
		if (*s == '%' && s[1]) {
			field = 0;
			++s;
			while (*s >= '0' && *s <= '9' && s[1]) {
				field = field * 10 + *s - '0';
				++s;
			}
			switch (*s) {
			case 'v': /* Version of JOE */
				{
					joe_snprintf_1(buf, SIZEOF(buf), "%s", VERSION);
					stalin = vsncpy(sv(stalin), sz(buf));
				}
				break;

			case 'x': /* Context (but only if autoindent is enabled) */
				{
					if ( bw->o.autoindent) {
						char *ts = get_context(bw);
						/* We need to translate between file's character set to
						   locale */
						my_iconv(stdbuf, SIZEOF(stdbuf), locale_map,ts,bw->o.charmap);
						stalin = vsncpy(sv(stalin), sz(stdbuf));
					}
				}
				break;

			case 'y':
				{
					if (bw->o.syntax) {
						joe_snprintf_1(buf, SIZEOF(buf), "(%s)", bw->o.syntax->name);
						stalin = vsncpy(sv(stalin), sz(buf));
					}
				}
				break;
			case 't':
				{
					time_t curtime = time(NULL);
					int l;
					char *d = ctime(&curtime);

					l = (d[11] - '0') * 10 + d[12] - '0';
					if (l > 12)
						l -= 12;
					joe_snprintf_1(buf, SIZEOF(buf), "%2.2d", l);
					if (buf[0] == '0')
						buf[0] = fill;
					stalin = vsncpy(sv(stalin), buf, 2);
					stalin = vsncpy(sv(stalin), d + 13, 3);
				}
				break;
			case 'd':
				{
					if (s[1]) switch (*++s) {
						case 'd' : joe_snprintf_1(buf, SIZEOF(buf), "%02d",cas->tm_mday); break;
						case 'm' : joe_snprintf_1(buf, SIZEOF(buf), "%02d",cas->tm_mon + 1); break;
						case 'y' : joe_snprintf_1(buf, SIZEOF(buf), "%02d",cas->tm_year % 100); break;
						case 'Y' : joe_snprintf_1(buf, SIZEOF(buf), "%04d",cas->tm_year + 1900); break;
						case 'w' : joe_snprintf_1(buf, SIZEOF(buf), "%d",cas->tm_wday); break;
						case 'D' : joe_snprintf_1(buf, SIZEOF(buf), "%03d",cas->tm_yday); break;
						default : buf[0]='d'; buf[1]=*s; buf[2]=0;
					} else {
						buf[0]='d'; buf[1]=0;
					}
					stalin=vsncpy(sv(stalin),sz(buf));
				}
				break;

			case 'E':
				{
					char *ch;
					int l;
					buf[0]=0;
					for(l=0;s[l+1] && s[l+1] != '%'; l++) buf[l]=s[l+1];
					if (s[l+1]=='%' && buf[0]) {
						buf[l]=0;
						s+=l+1;
						ch=getenv(buf);
						if (ch) stalin=vsncpy(sv(stalin),sz(ch));
					} 
				}
				break;

			case 'Z':
				{
					const char *ch;
					int l;
					buf[0]=0;
					for(l=0;s[l+1] && s[l+1] != '%'; l++) buf[l]=s[l+1];
					if (s[l+1]=='%' && buf[0]) {
						buf[l]=0;
						s+=l+1;
						ch=get_status(bw, buf);
						if (ch) stalin=vsncpy(sv(stalin),sz(ch));
					} 
				}
				break;

			case 'u':
				{
					time_t curtime = time(NULL);
					char *d = ctime(&curtime);

					stalin = vsncpy(sv(stalin), d + 11, 5);
				}
				break;
			case 'T':
				if (bw->o.overtype)
					stalin = vsadd(stalin, 'O');
				else
					stalin = vsadd(stalin, 'I');
				break;
			case 'W':
				if (bw->o.wordwrap)
					stalin = vsadd(stalin, 'W');
				else
					stalin = vsadd(stalin, fill);
				break;
			case 'I':
				if (bw->o.autoindent)
					stalin = vsadd(stalin, 'A');
				else
					stalin = vsadd(stalin, fill);
				break;
			case 'X':
				if (square)
					stalin = vsadd(stalin, 'X');
				else
					stalin = vsadd(stalin, fill);
				break;
			case 'n':
				{
				if (bw->b->name) {
					char *tmp = simplify_prefix(bw->b->name);
					char *tmp1 = duplicate_backslashes(sv(tmp));
					vsrm(tmp);
					stalin = vsncpy(sv(stalin), sv(tmp1));
					vsrm(tmp1);
				} else {
					stalin = vsncpy(sv(stalin), sz(joe_gettext(_("Unnamed"))));
				}
				}
				break;
			case 'm':
				if (bw->b->changed)
					stalin = vsncpy(sv(stalin), sz(joe_gettext(_("(Modified)"))));
				break;
			case 'R':
				if (bw->b->rdonly)
					stalin = vsncpy(sv(stalin), sz(joe_gettext(_("(Read only)"))));
				break;
			case '*':
				if (bw->b->changed)
					stalin = vsadd(stalin, '*');
				else
					stalin = vsadd(stalin, fill);
				break;
			case 'r':
				if (field)
#ifdef HAVE_LONG_LONG
					joe_snprintf_1(buf, SIZEOF(buf), "%-4lld", (long long)(bw->cursor->line + 1));
#else
					joe_snprintf_1(buf, SIZEOF(buf), "%-4ld", (long)(bw->cursor->line + 1));
#endif
				else
#ifdef HAVE_LONG_LONG
					joe_snprintf_1(buf, SIZEOF(buf), "%lld", (long long)(bw->cursor->line + 1));
#else
					joe_snprintf_1(buf, SIZEOF(buf), "%ld", (long)(bw->cursor->line + 1));
#endif
				for (x = 0; buf[x]; ++x)
					if (buf[x] == ' ')
						buf[x] = fill;
				stalin = vsncpy(sv(stalin), sz(buf));
				break;
			case 'o':
				if (field)
#ifdef HAVE_LONG_LONG
					joe_snprintf_1(buf, SIZEOF(buf), "%-4lld", (long long)bw->cursor->byte);
#else
					joe_snprintf_1(buf, SIZEOF(buf), "%-4ld", (long)bw->cursor->byte);
#endif
				else
#ifdef HAVE_LONG_LONG
					joe_snprintf_1(buf, SIZEOF(buf), "%lld", (long long)bw->cursor->byte);
#else
					joe_snprintf_1(buf, SIZEOF(buf), "%ld", (long)bw->cursor->byte);
#endif
				for (x = 0; buf[x]; ++x)
					if (buf[x] == ' ')
						buf[x] = fill;
				stalin = vsncpy(sv(stalin), sz(buf));
				break;
			case 'O':
				if (field)
#ifdef HAVE_LONG_LONG
					joe_snprintf_1(buf, SIZEOF(buf), "%-4llX", (unsigned long long)bw->cursor->byte);
#else
					joe_snprintf_1(buf, SIZEOF(buf), "%-4lX", (unsigned long)bw->cursor->byte);
#endif
				else
Esempio n. 25
0
void elasticitySolver::readInputFile(const std::string &fn)
{
  FILE *f = Fopen(fn.c_str(), "r");
  if(!f) {
    Msg::Error("Could not open file '%s'", fn.c_str());
    return;
  }
  char what[256];
  while(!feof(f)) {
    if(fscanf(f, "%s", what) != 1) {
      fclose(f);
      return;
    }
    if(what[0] == '#') {
      char buffer[1024];
      if(fgets(buffer, sizeof(buffer), f) == NULL)
        Msg::Error("Cannot read line.");
    }
    else if(!strcmp(what, "ElasticDomain")) {
      elasticField field;
      int physical;
      if(fscanf(f, "%d %lf %lf", &physical, &field._e, &field._nu) != 3) {
        fclose(f);
        return;
      }
      field._tag = _tag;
      field.g = new groupOfElements(_dim, physical);
      elasticFields.push_back(field);
    }
    else if(!strcmp(what, "LagrangeMultipliers")) {
      LagrangeMultiplierField field;
      int physical;
      double d1, d2, d3, val;
      if(fscanf(f, "%d %lf %lf %lf %lf %lf %d", &physical, &field._tau, &d1,
                &d2, &d3, &val, &field._tag) != 7) {
        fclose(f);
        return;
      }
      SVector3 sv(d1, d2, d3);
      field._d = sv.unit();
      field._f = new simpleFunction<double>(val);
      field.g = new groupOfElements(_dim - 1, physical);
      LagrangeMultiplierFields.push_back(field);
      LagrangeMultiplierSpaces.push_back(
        new ScalarLagrangeFunctionSpaceOfElement(field._tag));
    }
    else if(!strcmp(what, "Void")) {
      elasticField field;
      int physical;
      if(fscanf(f, "%d", &physical) != 1) {
        fclose(f);
        return;
      }
      field._e = field._nu = 0;
      field.g = new groupOfElements(_dim, physical);
      field._tag = 0;
      elasticFields.push_back(field);
    }
    else if(!strcmp(what, "NodeDisplacement")) {
      double val;
      int node, comp;
      if(fscanf(f, "%d %d %lf", &node, &comp, &val) != 3) {
        fclose(f);
        return;
      }
      dirichletBC diri;
      diri.g = new groupOfElements(0, node);
      diri._f = new simpleFunction<double>(val);
      diri._comp = comp;
      diri._tag = node;
      diri.onWhat = BoundaryCondition::ON_VERTEX;
      allDirichlet.push_back(diri);
    }
    else if(!strcmp(what, "EdgeDisplacement")) {
      double val;
      int edge, comp;
      if(fscanf(f, "%d %d %lf", &edge, &comp, &val) != 3) {
        fclose(f);
        return;
      }
      dirichletBC diri;
      diri.g = new groupOfElements(1, edge);
      diri._f = new simpleFunction<double>(val);
      diri._comp = comp;
      diri._tag = edge;
      diri.onWhat = BoundaryCondition::ON_EDGE;
      allDirichlet.push_back(diri);
    }
    else if(!strcmp(what, "FaceDisplacement")) {
      double val;
      int face, comp;
      if(fscanf(f, "%d %d %lf", &face, &comp, &val) != 3) {
        fclose(f);
        return;
      }
      dirichletBC diri;
      diri.g = new groupOfElements(2, face);
      diri._f = new simpleFunction<double>(val);
      diri._comp = comp;
      diri._tag = face;
      diri.onWhat = BoundaryCondition::ON_FACE;
      allDirichlet.push_back(diri);
    }
    else if(!strcmp(what, "NodeForce")) {
      double val1, val2, val3;
      int node;
      if(fscanf(f, "%d %lf %lf %lf", &node, &val1, &val2, &val3) != 4) {
        fclose(f);
        return;
      }
      neumannBC neu;
      neu.g = new groupOfElements(0, node);
      neu._f = new simpleFunction<SVector3>(SVector3(val1, val2, val3));
      neu._tag = node;
      neu.onWhat = BoundaryCondition::ON_VERTEX;
      allNeumann.push_back(neu);
    }
    else if(!strcmp(what, "EdgeForce")) {
      double val1, val2, val3;
      int edge;
      if(fscanf(f, "%d %lf %lf %lf", &edge, &val1, &val2, &val3) != 4) {
        fclose(f);
        return;
      }
      neumannBC neu;
      neu.g = new groupOfElements(1, edge);
      neu._f = new simpleFunction<SVector3>(SVector3(val1, val2, val3));
      neu._tag = edge;
      neu.onWhat = BoundaryCondition::ON_EDGE;
      allNeumann.push_back(neu);
    }
    else if(!strcmp(what, "FaceForce")) {
      double val1, val2, val3;
      int face;
      if(fscanf(f, "%d %lf %lf %lf", &face, &val1, &val2, &val3) != 4) {
        fclose(f);
        return;
      }
      neumannBC neu;
      neu.g = new groupOfElements(2, face);
      neu._f = new simpleFunction<SVector3>(SVector3(val1, val2, val3));
      neu._tag = face;
      neu.onWhat = BoundaryCondition::ON_FACE;
      allNeumann.push_back(neu);
    }
    else if(!strcmp(what, "VolumeForce")) {
      double val1, val2, val3;
      int volume;
      if(fscanf(f, "%d %lf %lf %lf", &volume, &val1, &val2, &val3) != 4) {
        fclose(f);
        return;
      }
      neumannBC neu;
      neu.g = new groupOfElements(3, volume);
      neu._f = new simpleFunction<SVector3>(SVector3(val1, val2, val3));
      neu._tag = volume;
      neu.onWhat = BoundaryCondition::ON_VOLUME;
      allNeumann.push_back(neu);
    }
    else if(!strcmp(what, "MeshFile")) {
      char name[245];
      if(fscanf(f, "%s", name) != 1) {
        fclose(f);
        return;
      }
      setMesh(name);
    }
    else if(!strcmp(what, "CutMeshPlane")) {
      double a, b, c, d;
      if(fscanf(f, "%lf %lf %lf %lf", &a, &b, &c, &d) != 4) {
        fclose(f);
        return;
      }
      int tag = 1;
      gLevelsetPlane ls(a, b, c, d, tag);
      pModel = pModel->buildCutGModel(&ls);
      pModel->writeMSH("cutMesh.msh");
    }
    else if(!strcmp(what, "CutMeshSphere")) {
      double x, y, z, r;
      if(fscanf(f, "%lf %lf %lf %lf", &x, &y, &z, &r) != 4) {
        fclose(f);
        return;
      }
      int tag = 1;
      gLevelsetSphere ls(x, y, z, r, tag);
      pModel = pModel->buildCutGModel(&ls);
      pModel->writeMSH("cutMesh.msh");
    }
    else if(!strcmp(what, "CutMeshMathExpr")) {
      char expr[256];
      if(fscanf(f, "%s", expr) != 1) {
        fclose(f);
        return;
      }
      std::string exprS(expr);
      int tag = 1;
      gLevelsetMathEval ls(exprS, tag);
      pModel = pModel->buildCutGModel(&ls);
      pModel->writeMSH("cutMesh.msh");
    }
    else {
      Msg::Error("Invalid input : '%s'", what);
    }
  }
  fclose(f);
}
Esempio n. 26
0
/*************************************************************************
Dense solver.

This subroutine finds solution of the linear system A*X=B with non-square,
possibly degenerate A.  System  is  solved in the least squares sense, and
general least squares solution  X = X0 + CX*y  which  minimizes |A*X-B| is
returned. If A is non-degenerate, solution in the  usual sense is returned

Additional features include:
* iterative improvement

INPUT PARAMETERS
    A       -   array[0..NRows-1,0..NCols-1], system matrix
    NRows   -   vertical size of A
    NCols   -   horizontal size of A
    B       -   array[0..NCols-1], right part
    Threshold-  a number in [0,1]. Singular values  beyond  Threshold  are
                considered  zero.  Set  it to 0.0, if you don't understand
                what it means, so the solver will choose good value on its
                own.
                
OUTPUT PARAMETERS
    Info    -   return code:
                * -4    SVD subroutine failed
                * -1    if NRows<=0 or NCols<=0 or Threshold<0 was passed
                *  1    if task is solved
    Rep     -   solver report, see below for more info
    X       -   array[0..N-1,0..M-1], it contains:
                * solution of A*X=B if A is non-singular (well-conditioned
                  or ill-conditioned, but not very close to singular)
                * zeros,  if  A  is  singular  or  VERY  close to singular
                  (in this case Info=-3).

SOLVER REPORT

Subroutine sets following fields of the Rep structure:
* R2        reciprocal of condition number: 1/cond(A), 2-norm.
* N         = NCols
* K         dim(Null(A))
* CX        array[0..N-1,0..K-1], kernel of A.
            Columns of CX store such vectors that A*CX[i]=0.

  -- ALGLIB --
     Copyright 24.08.2009 by Bochkanov Sergey
*************************************************************************/
void rmatrixsolvels(const ap::real_2d_array& a,
     int nrows,
     int ncols,
     const ap::real_1d_array& b,
     double threshold,
     int& info,
     densesolverlsreport& rep,
     ap::real_1d_array& x)
{
    ap::real_1d_array sv;
    ap::real_2d_array u;
    ap::real_2d_array vt;
    ap::real_1d_array rp;
    ap::real_1d_array utb;
    ap::real_1d_array sutb;
    ap::real_1d_array tmp;
    ap::real_1d_array ta;
    ap::real_1d_array tx;
    ap::real_1d_array buf;
    ap::real_1d_array w;
    int i;
    int j;
    int nsv;
    int kernelidx;
    double v;
    double verr;
    bool svdfailed;
    bool zeroa;
    int rfs;
    int nrfs;
    bool terminatenexttime;
    bool smallerr;

    if( nrows<=0||ncols<=0||ap::fp_less(threshold,0) )
    {
        info = -1;
        return;
    }
    if( ap::fp_eq(threshold,0) )
    {
        threshold = 1000*ap::machineepsilon;
    }
    
    //
    // Factorize A first
    //
    svdfailed = !rmatrixsvd(a, nrows, ncols, 1, 2, 2, sv, u, vt);
    zeroa = ap::fp_eq(sv(0),0);
    if( svdfailed||zeroa )
    {
        if( svdfailed )
        {
            info = -4;
        }
        else
        {
            info = 1;
        }
        x.setlength(ncols);
        for(i = 0; i <= ncols-1; i++)
        {
            x(i) = 0;
        }
        rep.n = ncols;
        rep.k = ncols;
        rep.cx.setlength(ncols, ncols);
        for(i = 0; i <= ncols-1; i++)
        {
            for(j = 0; j <= ncols-1; j++)
            {
                if( i==j )
                {
                    rep.cx(i,j) = 1;
                }
                else
                {
                    rep.cx(i,j) = 0;
                }
            }
        }
        rep.r2 = 0;
        return;
    }
    nsv = ap::minint(ncols, nrows);
    if( nsv==ncols )
    {
        rep.r2 = sv(nsv-1)/sv(0);
    }
    else
    {
        rep.r2 = 0;
    }
    rep.n = ncols;
    info = 1;
    
    //
    // Iterative improvement of xc combined with solution:
    // 1. xc = 0
    // 2. calculate r = bc-A*xc using extra-precise dot product
    // 3. solve A*y = r
    // 4. update x:=x+r
    // 5. goto 2
    //
    // This cycle is executed until one of two things happens:
    // 1. maximum number of iterations reached
    // 2. last iteration decreased error to the lower limit
    //
    utb.setlength(nsv);
    sutb.setlength(nsv);
    x.setlength(ncols);
    tmp.setlength(ncols);
    ta.setlength(ncols+1);
    tx.setlength(ncols+1);
    buf.setlength(ncols+1);
    for(i = 0; i <= ncols-1; i++)
    {
        x(i) = 0;
    }
    kernelidx = nsv;
    for(i = 0; i <= nsv-1; i++)
    {
        if( ap::fp_less_eq(sv(i),threshold*sv(0)) )
        {
            kernelidx = i;
            break;
        }
    }
    rep.k = ncols-kernelidx;
    nrfs = densesolverrfsmaxv2(ncols, rep.r2);
    terminatenexttime = false;
    rp.setlength(nrows);
    for(rfs = 0; rfs <= nrfs; rfs++)
    {
        if( terminatenexttime )
        {
            break;
        }
        
        //
        // calculate right part
        //
        if( rfs==0 )
        {
            ap::vmove(&rp(0), &b(0), ap::vlen(0,nrows-1));
        }
        else
        {
            smallerr = true;
            for(i = 0; i <= nrows-1; i++)
            {
                ap::vmove(&ta(0), &a(i, 0), ap::vlen(0,ncols-1));
                ta(ncols) = -1;
                ap::vmove(&tx(0), &x(0), ap::vlen(0,ncols-1));
                tx(ncols) = b(i);
                xdot(ta, tx, ncols+1, buf, v, verr);
                rp(i) = -v;
                smallerr = smallerr&&ap::fp_less(fabs(v),4*verr);
            }
            if( smallerr )
            {
                terminatenexttime = true;
            }
        }
        
        //
        // solve A*dx = rp
        //
        for(i = 0; i <= ncols-1; i++)
        {
            tmp(i) = 0;
        }
        for(i = 0; i <= nsv-1; i++)
        {
            utb(i) = 0;
        }
        for(i = 0; i <= nrows-1; i++)
        {
            v = rp(i);
            ap::vadd(&utb(0), &u(i, 0), ap::vlen(0,nsv-1), v);
        }
        for(i = 0; i <= nsv-1; i++)
        {
            if( i<kernelidx )
            {
                sutb(i) = utb(i)/sv(i);
            }
            else
            {
                sutb(i) = 0;
            }
        }
        for(i = 0; i <= nsv-1; i++)
        {
            v = sutb(i);
            ap::vadd(&tmp(0), &vt(i, 0), ap::vlen(0,ncols-1), v);
        }
        
        //
        // update x:  x:=x+dx
        //
        ap::vadd(&x(0), &tmp(0), ap::vlen(0,ncols-1));
    }
    
    //
    // fill CX
    //
    if( rep.k>0 )
    {
        rep.cx.setlength(ncols, rep.k);
        for(i = 0; i <= rep.k-1; i++)
        {
            ap::vmove(rep.cx.getcolumn(i, 0, ncols-1), vt.getrow(kernelidx+i, 0, ncols-1));
        }
    }
}
 void LiveChatMembersControl::adjustWidth()
 {
     int width = (sv(avatarWithFrameHeight) - sv(avatarIntersection) - sv(frameWidth)) * members_.size() + (sv(avatarIntersection) + sv(frameWidth));
     
     setFixedWidth(width);
 }
Esempio n. 28
0
int main()
{
	std::cout << __LINE__ << std::endl;
	// default constructor implies empty string
	{
		stdex::static_cstring<20> sv;
		BOOST_TEST(sv.empty());
		BOOST_TEST(sv.size() == 0);
		BOOST_TEST(sv.c_str() == std::string());
	}
	std::cout << __LINE__ << std::endl;
	// default constructor implies empty string
	{
		stdex::static_cstring<20> sv{};
		BOOST_TEST(sv.empty());
		BOOST_TEST(sv.size() == 0);
		BOOST_TEST(sv.c_str() == std::string());
	}
	std::cout << __LINE__ << std::endl;
	// constructor from a NTXS of length > 0
	{
		const char *str = "Hello";
		std::size_t len;
		bool        b = stdex::ntxs::test_and_set_length<20>(str, len);
		BOOST_TEST(b);
		BOOST_TEST_EQ(5, len);
	}
	{
		const char *              str = "Hello";
		std::size_t               len = 5;
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str, len);
		BOOST_TEST(!sv.empty());
		BOOST_TEST_EQ(5, sv.size());
	}
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv{stdex::null_terminated_t{}, str};
		BOOST_TEST(!sv.empty());
		BOOST_TEST_EQ(5, sv.size());
		BOOST_TEST_EQ(stdex::string_view(sv), std::string(str));
		BOOST_TEST_EQ(sv.to_string(), std::string(str));
		BOOST_TEST_EQ(std::string(sv), std::string(str));
	}
	std::cout << __LINE__ << std::endl;
#if 0
	// constructor from nullptr_t must compile fail
	{
		
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, nullptr);
	}
#endif
	std::cout << __LINE__ << std::endl;
	// constructor from a const char* equal to nullptr is UB, don't do it
	// string_view doesn't throws when not valid as it is required to be UB
	if (0)
	{
		try
		{
			const char *              str = nullptr;
			stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
			BOOST_TEST(false);
		}
		catch (...)
		{
		}
	}
	std::cout << __LINE__ << std::endl;
	// construction from c-string literal
	{
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "Hello");
		BOOST_TEST(!sv.empty());
	}
	std::cout << __LINE__ << std::endl;
	// construction from empty c-string literal
	{
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "");
		BOOST_TEST(sv.to_string().empty());
		BOOST_TEST(sv.empty());
		BOOST_TEST(sv.c_str() == std::string());
	}
	std::cout << __LINE__ << std::endl;
	// construction from std::string
	{
		std::string               str("Hello");
		stdex::static_cstring<20> sv(str);
		BOOST_TEST(!sv.empty());
		BOOST_TEST(sv.c_str() == str);
	}
	std::cout << __LINE__ << std::endl;
	// construction from std::string
	{
		std::string               str{"Hello"};
		stdex::static_cstring<20> sv(str);
		BOOST_TEST(!sv.empty());
		BOOST_TEST(sv.c_str() == str);
	}
	std::cout << __LINE__ << std::endl;
	// construction from N char
	{
		stdex::static_cstring<20> sv(stdex::length_tag_t{}, 3, 'X');
		BOOST_TEST(!sv.empty());
		BOOST_TEST(sv.to_string() == "XXX");
	}
	std::cout << __LINE__ << std::endl;
// implicit construction from N char  compile fails
#if 0
	{
		stdex::static_cstring<20> sv(48, 'X');
	}
#endif
	std::cout << __LINE__ << std::endl;
	// implicit construction from a initializer list
	// construction from N char
	{
		stdex::static_cstring<20> sv{48, 'X'};
		BOOST_TEST(!sv.empty());
		BOOST_TEST(sv.to_string() == "0X");
	}
	std::cout << __LINE__ << std::endl;
	{
		stdex::static_cstring<20> sv = {48, 'X'};
		BOOST_TEST(!sv.empty());
		BOOST_TEST(sv.to_string() == "0X");
	}
	std::cout << __LINE__ << std::endl;
	// iteration over the chars using range-based for loop
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		std::ostringstream        os;
		for (auto ch : sv)
			os << ch;
		BOOST_TEST(os.str() == str);
	}
	// iteration over the chars using range-based for loop
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		for (auto &ch : sv)
			ch = 'a';
		BOOST_TEST(sv.to_string() == "aaaaa");
	}
	// operator=

	// assign
	std::cout << __LINE__ << std::endl;
	// Assign n chars
	{
		stdex::static_cstring<20> sv;
		sv.assign(3, 'X');
		BOOST_TEST(sv.to_string() == "XXX");
	}
	std::cout << __LINE__ << std::endl;
	// Assign another string
	{
		stdex::static_cstring<20> sw{stdex::null_terminated_t{}, "Hello"};
		stdex::static_cstring<20> sv;
		sv.assign(sw);
		BOOST_TEST(sv.to_string() == "Hello");
	}
	std::cout << __LINE__ << std::endl;
	// Assign another substring
	{
		stdex::static_cstring<20> sw{stdex::null_terminated_t{}, "Hello"};
		stdex::static_cstring<20> sv;
		sv.assign(sw, 1, 3);
		BOOST_TEST(sv.to_string() == "ell");
	}
	std::cout << __LINE__ << std::endl;
	// Assign another substring over
	{
		stdex::static_cstring<20> sw{stdex::null_terminated_t{}, "Hello"};
		stdex::static_cstring<20> sv;
		sv.assign(sw, 1, 5);
		std::cout << sv.c_str() << " " << sv.size() << std::endl;
		BOOST_TEST(sv.to_string() == "ello");
	}
	std::cout << __LINE__ << std::endl;
	// Assign another substring npos
	{
		stdex::static_cstring<20> sw{stdex::null_terminated_t{}, "Hello"};
		stdex::static_cstring<20> sv;
		sv.assign(sw, 1, stdex::static_cstring<20>::npos);
		std::cout << sv.c_str() << " " << sv.size() << std::endl;
		BOOST_TEST(sv.to_string() == "ello");
	}
	std::cout << __LINE__ << std::endl;
	// Assign another empty substring
	{
		stdex::static_cstring<20> sw{stdex::null_terminated_t{}, "Hello"};
		stdex::static_cstring<20> sv;
		sv.assign(sw, 1, 0);
		std::cout << sv.c_str() << " " << sv.size() << std::endl;
		BOOST_TEST(sv.to_string() == "");
	}
	std::cout << __LINE__ << std::endl;
	// Assign a literal string
	{
		stdex::static_cstring<20> sv;
		sv.assign("Hello");
		BOOST_TEST(sv.to_string() == "Hello");
	}
	std::cout << __LINE__ << std::endl;
	// Assign a const char *
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv;
		sv.assign(str);
		BOOST_TEST(sv.to_string() == "Hello");
	}
	std::cout << __LINE__ << std::endl;
	// Assign a prefix of a const char *
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv;
		sv.assign(str, 3);
		BOOST_TEST(sv.to_string() == "Hel");
	}
	std::cout << __LINE__ << std::endl;
	// Assign a range
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv;
		sv.assign(str + 1, str + 3);
		BOOST_TEST(sv.to_string() == "el");
	}
	std::cout << __LINE__ << std::endl;
	// Assign a range
	{
		stdex::static_cstring<20> sv;
		sv.assign({'e', 'l'});
		BOOST_TEST(sv.to_string() == "el");
	}

	// range based for loop
	std::cout << __LINE__ << std::endl;
	// iteration over the chars using index and size
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		std::ostringstream        os;
		for (std::size_t i = 0, l = sv.size(); i < l; ++i)
			os << sv[i];
		BOOST_TEST(os.str() == str);
	}
	std::cout << __LINE__ << std::endl;
	// iteration over the chars using index and size
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		for (std::size_t i = 0, l = sv.size(); i < l; ++i)
			sv[i] = 'b';
		BOOST_TEST(sv.to_string() == "bbbbb");
	}
	std::cout << __LINE__ << std::endl;
	// at good index read access
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		BOOST_TEST(sv.at(0) == 'H');
	}
	std::cout << __LINE__ << std::endl;
	// at good index write access
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.at(0) = 'h';
		BOOST_TEST(sv.to_string() == "hello");
	}
	// front/back good index access
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		BOOST_TEST(sv.front() == 'H');
		BOOST_TEST(sv.back() == 'o');
	}
	// front/back good index access
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.front() = 'h';
		BOOST_TEST(sv.to_string() == "hello");
	}
	// front/back good index access
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.back() = 'a';
		BOOST_TEST(sv.to_string() == "Hella");
	}
	// data access
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		BOOST_TEST(sv.data() == std::string(str));
	}
	// c_str access
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		BOOST_TEST(sv.c_str() == std::string(str));
	}
	// implicit conversion to string_view
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> scstr(stdex::null_terminated_t{}, str);
		stdex::string_view        sv{scstr};
		BOOST_TEST(sv.data() == scstr.data());
	}
	// implicit conversion to cstring_view
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> scstr(stdex::null_terminated_t{}, str);
		stdex::cstring_view       sv{scstr};
		BOOST_TEST(sv.data() == scstr.data());
	}
// implicit conversion to cstr_view
#if defined __clang__ && __cplusplus > 201402L
	// fixme: why this is ambiguous and not the following
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> scstr(stdex::null_terminated_t{}, str);
		stdex::cstr_view          sv(scstr);
		BOOST_TEST(sv.data() == scstr.data());
	}
#endif
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> scstr(stdex::null_terminated_t{}, str);
		stdex::cstr_view          sv = scstr;
		BOOST_TEST(sv.data() == scstr.data());
	}
	// to_string
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		BOOST_TEST(sv.to_string() == str);
	}
	// explicit conversion to string
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		BOOST_TEST(std::string(sv) == str);
	}
	// clear()
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.clear();
		BOOST_TEST(sv.to_string() == "");
	}
	// insert
	// ambiguous interface when using 0, which is convertible to size_t and char const* :(
	//         basic_static_cstring &insert(size_type 	 index, size_type count, charT ch)
	//         iterator 			 insert(const_iterator pos, size_type count, charT ch)
	{
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "0123456");
		sv.insert(0ul, 3, 'x');
		BOOST_TEST(sv.to_string() == "xxx0123456");
	}
	{
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "0123456");
		sv.insert(3, 2, 'x');
		BOOST_TEST(sv.to_string() == "012xx3456");
	}
	{
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "01234");
		sv.insert(5, 2, 'x');
		BOOST_TEST(sv.to_string() == "01234xx");
	}
	try
	{

		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "01234");
		sv.insert(6, 2, 'x');
		BOOST_TEST(false);
	}
	catch (stdex::contract_failed &ex)
	{
		stdex::string_view msg = ex.what();
		BOOST_TEST_EQ(msg.substr(0, 28), "JASEL: Pre-condition failure");
	}
	{
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "0123456");
		sv.insert(0ul, "xxx");
		BOOST_TEST(sv.to_string() == "xxx0123456");
	}
	{
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "0123456");
		sv.insert(2, "xxx");
		BOOST_TEST(sv.to_string() == "01xxx23456");
	}
	try
	{
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "012");
		sv.insert(6, "xxx");
		BOOST_TEST(false);
	}
	catch (stdex::contract_failed &ex)
	{
		stdex::string_view msg = ex.what();
		BOOST_TEST_EQ(msg.substr(0, 28), "JASEL: Pre-condition failure");
	}
	{
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "0123456");
		auto                      it = sv.insert(sv.data(), 3, 'x');
		BOOST_TEST(it == sv.data());
		BOOST_TEST(sv.to_string() == "xxx0123456");
	}
	{
		stdex::static_cstring<20> letters(stdex::null_terminated_t{}, "abcdef");
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, "0123456");
		sv.insert(sv.data() + 2, letters.data() + 2, letters.data() + 4);
		BOOST_TEST(sv.to_string() == "01cd23456");
	}

	// erase

	// push_back
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.push_back(' ');
		BOOST_TEST(sv.to_string() == "Hello ");
	}
	// pop_back
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.pop_back();
		BOOST_TEST(sv.to_string() == "Hell");
	}
	// replace

	// resize
	{
		const char *              str = "XXX";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.resize(5, ' ');
		BOOST_TEST(sv.to_string() == "XXX  ");
	}
	// resize
	{
		const char *              str = "XXX";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.resize(2, ' ');
		BOOST_TEST(sv.to_string() == "XX");
	}
	// remove_prefix
	// resize
	{
		const char *              str = "XXX";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.resize(5);
		BOOST_TEST(sv.size() == 5);
		BOOST_TEST(sv[3] == '\0');
		BOOST_TEST(sv[4] == '\0');
		BOOST_TEST(sv[5] == '\0');
		BOOST_TEST(sv.c_str() == std::string("XXX"));
	}
	// resize
	{
		const char *              str = "XXX";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.resize(2);
		BOOST_TEST(sv.to_string() == "XX");
		BOOST_TEST(sv.size() == 2);
	}
	{
		const char *              str = "Hello World";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.remove_prefix(6);
		BOOST_TEST(sv.to_string() == "World");
	}
	// remove_suffix
	{
		const char *              str = "Hello World";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, str);
		sv.remove_suffix(6);
		BOOST_TEST(sv.to_string() == "Hello");
	}
	// swap
	{
		const char *              hello = "Hello";
		const char *              world = "World";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, hello);
		stdex::static_cstring<20> sw(stdex::null_terminated_t{}, world);
		swap(sv, sw);
		BOOST_TEST(sv.to_string() == "World");
	}

	// compare different
	{
		const char *              hello = "Hello";
		const char *              world = "World";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, hello);
		stdex::static_cstring<20> sw(stdex::null_terminated_t{}, world);
		BOOST_TEST(sv.compare(sw) < 0);
		BOOST_TEST(sw.compare(sv) > 0);
	}
	// compare equals
	{
		const char *              hello = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, hello);
		stdex::static_cstring<20> sw(stdex::null_terminated_t{}, hello);
		BOOST_TEST(sv.compare(sw) == 0);
	}
	// compare equals with const char *
	{
		const char *              hello = "Hello";
		stdex::static_cstring<20> sv(stdex::null_terminated_t{}, hello);
		BOOST_TEST(sv.compare("Hello") == 0);
	}
	// test for all the string_view specific functions go here
	{
		auto str = stdex::to_static_cstring<10>(100);
		BOOST_TEST(str.to_string() == std::string("100"));
	}
	{
		stdex::static_cstring<20> str(stdex::null_terminated_t{}, "100");
		int                       value;
		auto                      result = stdex::from_chars(str.c_str(), str.c_str() + str.size(), value, 10);
		BOOST_TEST(result.ec == std::errc{});
		auto i = stdex::sto<int>(str);
		BOOST_TEST_EQ(i, 100);
		//BOOST_TEST_EQ(stdex::sto<int>(str), 100);
		//BOOST_TEST_EQ(stdex::stoi(str), 100);
	}
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> scstr(stdex::null_terminated_t{}, str);

		auto sp = scstr.borrow(10);
		BOOST_TEST(sp.size() == 10);
		BOOST_TEST(sp.data() == scstr.end());
		scstr.give_back(sp);
		BOOST_TEST(scstr.size() == 15);
	}
	{
		const char *              str = "Hello";
		stdex::static_cstring<20> scstr(stdex::null_terminated_t{}, str);

		auto sp = scstr.borrow_all(15);
		BOOST_TEST(sp.size() == 15);
		BOOST_TEST(sp.data() == scstr.data());
		scstr.give_back_all(sp);
		BOOST_TEST(scstr.size() == 15);
	}
	return ::boost::report_errors();
}
Esempio n. 29
0
    virtual void onLbtnDragging(MouseStatus& ms) {
      bool seeBottom = false;
      // Lボタンドラッグで視点または並行移動
      // 注視点平面での画面いっぱいのサイズ
      float32_t vh = static_cast<float32_t>(tan(m_vc.getFovy() * Pai2Rad / 2.0) * m_vc.getEye().distance(m_vc.getTarget()) * 2.0);
      float32_t vw = static_cast<float32_t>(vh * m_vc.getViewAspect());
      vw *= -static_cast<float32_t>(ms.dX) / m_vc.getViewPort().width;
      vh *= static_cast<float32_t>(ms.dY) / m_vc.getViewPort().height;

      // 視線のベクトルを計算
      Vector3D ev(m_vc.camera().target - m_vc.camera().eye);
      if (fabs(ev.x) < 100.0f && fabs(ev.y) < 100.0f) {
        //真上から下を向いている場合
        ev = Vector3D(0.0f, 1.0f, 0.0f);
        if (abs(ms.dY) > abs(ms.dX)) vw = 0.0f;
        seeBottom = true;
      }
      ev.normalize();
      Vector3D sv(ev.y, -ev.x, -ev.z); // evと直行するベクトル
      ev *= vh;
      sv *= vw;
      Vector3D mv(ev + sv);

      if (ms.btn.shiftKey || seeBottom) {
        // シフトを押している場合は平行移動
        if (ms.btn.ctrlKey) {
          // Shift+CtrlでViewControlのObjectOffsetを設定
//          m_vc.addObjectOffset(Vector3D(vw, vh, 0.0f));
          if (seeBottom){ 
            m_vc.camera().eye.y = m_vc.camera().target.y - 1000.0;
          }
        }
        else {
          mv.z = 0;
          m_vc.camera().eye += mv;
          m_vc.camera().target += mv;
        }
        if (ms.btn.shiftKey) {
          // ShiftでgldOriginのObjectOffsetを設定
          if (ms.btn.centerBtn) {
#if 0
            static float sx = 30.0f;
            static float sy = 30.0f;
            sx += vw / 100.0f;
            sy += vh / 100.0f;
            m_bc.getObjectList()->setScaleAll(Vector3D(sx,sy,10.0f));
#endif

          }
          else {
#if 0
            gldOrigin.x += vw;
            gldOrigin.y += vh;
            m_bc.getObjectList()->setOriginAll(gldOrigin);
            TRACE("Origin(%ld,%ld)\n", gldOrigin.x, gldOrigin.y);
#endif
          }
        }
      }
      else if (ms.btn.ctrlKey) {
        // CTRLキーを押してるときは、視点のみ平行移動
        mv.z = 0;
        m_vc.camera().eye += mv;
      }
      else {
        // 見ている方向に対して注視点を移動
        if (seeBottom) {
          sv.y = vh;
          sv.z = 0.0;
          m_vc.camera().target += sv;

        }
        else {
          sv.z = vh;
          m_vc.camera().target += sv;

          // 注視点のzを0に調整する
          Vector3Dd& e = m_vc.camera().eye;
          Vector3Dd& t = m_vc.camera().target;
          // 直線の方程式
          // (x-e.x)/(t.x-e.x)=(y-e.y)/(t.y-e.y)=(z-e.z)/(t.z-e.z)
          // z = 0だから
          // (x-e.x)/(t.x-e.x) = (-e.z)/(t.z-e.z)
          // (x-e.x) = ((-e.z)/(t.z-e.z))/(t.x-e.x)
          // x = e.x + ((-e.z)/(t.z-e.z))/(t.x-e.x)
          m_vc.camera().target.x = e.x + ((-e.z)*(t.x-e.x))/(t.z-e.z);
          m_vc.camera().target.y = e.y + ((-e.z)*(t.y-e.y))/(t.z-e.z);
          m_vc.camera().target.z = 0.0;
        }

      }
      m_vc.setRedrawRequest();
    }
Esempio n. 30
0
void
vpPose::poseDementhonPlan(vpHomogeneousMatrix &cMo)
{ 
#if (DEBUG_LEVEL1)
  std::cout << "begin CCalculPose::PoseDementhonPlan()" << std::endl ;
#endif

  unsigned int i,j,k ;

  if (c3d !=NULL) delete []c3d ;
  c3d = new vpPoint[npt] ;

  vpPoint p0 = listP.front() ;

  vpPoint P ;
  i=0 ;
  for (std::list<vpPoint>::const_iterator it = listP.begin(); it != listP.end(); ++it)
  {
    P = *it;
    c3d[i] = P ;
    c3d[i].set_oX(P.get_oX()-p0.get_oX()) ;
    c3d[i].set_oY(P.get_oY()-p0.get_oY()) ;
    c3d[i].set_oZ(P.get_oZ()-p0.get_oZ()) ;
    i++  ;
  }

  vpMatrix a ;
  try
  {
    a.resize(npt-1,3) ;
  }
  catch(...)
  {
    vpERROR_TRACE(" ") ;
    throw ;
  }


  for (i=1 ; i < npt ; i++)
  {
    a[i-1][0]=c3d[i].get_oX();
    a[i-1][1]=c3d[i].get_oY();
    a[i-1][2]=c3d[i].get_oZ();
  }

  // calcul a^T a
  vpMatrix ata ;
  ata = a.t()*a ;

  /* essai FC pour debug SVD */
  /*
  vpMatrix ata_old ;
  ata_old = a.t()*a ;

  vpMatrix ata((ata_old.getRows()-1),(ata_old.getCols()-1)) ;
  for (i=0;i<ata.getRows();i++)
  for (j=0;j<ata.getCols();j++) ata[i][j] = ata_old[i][j];
  */
  vpMatrix ata_sav;
  ata_sav = ata;

#if (DEBUG_LEVEL2)
  {
    std::cout << "a" << std::endl <<a<<std::endl ;
    std::cout << "ata" << std::endl <<ata<<std::endl ;
  }
#endif

  // calcul (a^T a)^-1
  vpMatrix ata1(ata.getRows(),ata.getCols()) ;
  vpMatrix v(ata.getRows(),ata.getCols());
  vpColVector sv(ata.getRows());
  //  ata1 = ata.i() ;
  unsigned int imin = 0;
  double s = 0.0;

  //calcul de ata^-1
  ata.svd(sv,v) ;

  unsigned int nc = sv.getRows() ;
  for (i=0; i < nc ; i++)
    if (sv[i] > s) s = sv[i];

  s *= 0.0002;
  int  irank = 0;
  for (i=0;i<nc;i++)
    if (sv[i] > s ) irank++;

  double svm = 100.0;
  for (i = 0; i < nc; i++)
    if (sv[i] < svm) { imin = i; svm = sv[i]; }

#if (DEBUG_LEVEL2)
    {
      std::cout << "rang: " << irank << std::endl ;;
      std::cout <<"imin = " << imin << std::endl ;
      std::cout << "sv " << sv.t() << std::endl ;
    }
#endif

    for (i=0 ; i < ata.getRows() ; i++)
      for (j=0 ; j < ata.getCols() ; j++)
      {
        ata1[i][j] = 0.0;
        for (k=0 ; k < nc ; k++)
          if (sv[k] > s)
            ata1[i][j] += ((v[i][k]*ata[j][k])/sv[k]);
      }



      vpMatrix b ;   // b=(at a)^-1*at
      b = ata1*a.t() ;

      //calcul de U
      vpColVector U(3) ;
      U = ata.column(imin+1) ;

#if (DEBUG_LEVEL2)
      {
        std::cout << "a" << std::endl <<a<<std::endl ;
        std::cout << "ata" << std::endl <<ata_sav<<std::endl ;
        std::cout << "ata1" << std::endl <<ata1<<std::endl ;
        std::cout << "ata1*ata"  << std::endl <<  ata1*ata_sav ;
        std::cout << "b"  << std::endl <<  b ;
        std::cout << "U " << U.t()  << std::endl ;
      }
#endif

      vpColVector xi(npt) ;
      vpColVector yi(npt) ;
      //calcul de la premiere solution
      for (i = 0; i < npt; i++)
      {
        xi[i] = c3d[i].get_x() ;
        yi[i] = c3d[i].get_y() ;

      }

      vpColVector I0(3) ; I0 = 0 ;
      vpColVector J0(3) ; J0 = 0 ;
      vpColVector I(3) ;
      vpColVector J(3) ;

      for (i=1;i<npt;i++)
      {
        I0[0] += b[0][i-1] * (xi[i]-xi[0]);
        I0[1] += b[1][i-1] * (xi[i]-xi[0]);
        I0[2] += b[2][i-1] * (xi[i]-xi[0]);

        J0[0] += b[0][i-1] * (yi[i]-yi[0]);
        J0[1] += b[1][i-1] * (yi[i]-yi[0]);
        J0[2] += b[2][i-1] * (yi[i]-yi[0]);
      }


#if (DEBUG_LEVEL2)
      {
        std::cout << "I0 "<<I0.t() ;
        std::cout << "J0 "<<J0.t() ;
      }
#endif

      s = -2.0*vpColVector::dotProd(I0,J0);
      double c = J0.sumSquare() - I0.sumSquare() ;

      double r,theta,si,co ;
      calculRTheta(s, c, r, theta);
      co = cos(theta);
      si = sin(theta);

      // calcul de la premiere solution
      I = I0 + U*r*co ;
      J = J0 + U*r*si ;

      vpHomogeneousMatrix cMo1f ;
      calculSolutionDementhon(xi[0], yi[0], I, J, cMo1f);


      int erreur1 = calculArbreDementhon(b, U, cMo1f);

      // calcul de la deuxieme solution
      I = I0 - U*r*co ;
      J = J0 - U*r*si ;

      vpHomogeneousMatrix cMo2f;
      calculSolutionDementhon(xi[0], yi[0], I, J, cMo2f);

      int erreur2 = calculArbreDementhon(b, U, cMo2f);

      if ((erreur1 == 0) && (erreur2 == -1))   cMo = cMo1f ;
      if ((erreur1 == -1) && (erreur2 == 0))   cMo = cMo2f ;
      if ((erreur1 == 0) && (erreur2 == 0))
      {
        double s1 =  sqrt(computeResidualDementhon(cMo1f)/npt)  ;
        double s2 =  sqrt(computeResidualDementhon(cMo2f)/npt)  ;

        if (s1<=s2) cMo = cMo1f ; else cMo = cMo2f ;
      }

      cMo[0][3] -= p0.get_oX()*cMo[0][0]+p0.get_oY()*cMo[0][1]+p0.get_oZ()*cMo[0][2];
      cMo[1][3] -= p0.get_oX()*cMo[1][0]+p0.get_oY()*cMo[1][1]+p0.get_oZ()*cMo[1][2];
      cMo[2][3] -= p0.get_oX()*cMo[2][0]+p0.get_oY()*cMo[2][1]+p0.get_oZ()*cMo[2][2];

      delete [] c3d ; c3d = NULL ;
#if (DEBUG_LEVEL1)
      std::cout << "end CCalculPose::PoseDementhonPlan()" << std::endl ;
#endif
}