Esempio n. 1
0
static int parse_port(char *p)
{
    int port = 0, e = -1;
    port = str_int(p, &e);
    if (e || port < 1 || port > 65535)
        sys_die("invalid port '%s'\n", p);

    return port;
}
Esempio n. 2
0
int main(int argc, char* argv[]) {
	std::cout << "\n";

	if(argc != 8) {
		std::cout << "Invalid parameters, usage: <int|double> <rows> <columns> <offset> <range> <seed> <output-file>\n";
		return 1;
	}
	
	int param = 0;
	bool is_int = true; // false -> is_double
	
	std::string str_int("int");
	std::string str_dbl("double");

	std::string type(argv[++param]);

	if(str_int.compare(type) == 0)
		is_int = true;
	else if(str_dbl.compare(type) == 0)
		is_int = false;
	else {
		std::cout << "Invalid type-parameter: write 'int' or 'double'";
		return 2;
	}

	int ctr_i;
	int rng_i;
	double ctr_d;
	double rng_d;
	
	int n = std::stoi(argv[++param]); // number of rows
	int d = std::stoi(argv[++param]); // number of columns
	
	if(is_int) {
		ctr_i = std::stoi(argv[++param]);
		rng_i = std::stoi(argv[++param]);
	}
	else {
		ctr_d = std::stod(argv[++param]); // where the random data should be centered
		rng_d = std::stod(argv[++param]); // the range of the data -> ctr +- rng
	}

	int seed = std::stoi(argv[++param]);
	char *path = argv[++param]; // the output-path

	std::cout << "Generating random " << type  << "-data and dumping to file...\n";

	if(is_int)
		dump_rand_data_i(n, d, ctr_i, rng_i, path, CSV_DELIM, seed);
	else
		dump_rand_data_d(n, d, ctr_d, rng_d, path, CSV_DELIM, seed);

	std::cout << "Done!\n";
}
Esempio n. 3
0
str
parse_host(Request req, str host)
{
	if (!req) return NULL;
	if (! host) {
		req->port = 0;
		return req->host = NULL;
	}
	req->host = name_field(host);
	int port = str_int(skip_fields(host,0));
	request_port(req,port ? port : 80);
	return req->host;
}
Esempio n. 4
0
void search3(node_plist h,char *key)
{
	int flag = 0;
	node_plist q,p;

	for(p = h->next;p != h->prior;p= p->next){
		for(q=p->next;q != h;q=q->next)
			if(str_int(q->info.stime)<str_int(p->info.stime)){

				q->prior->next = q->next;	//将q剪切
				q->next->prior = q->prior;

				q->prior = p->prior;		//将q插到p前面
				p->prior->next = q;
				q->next = p;
				p->prior = q;
			}

	}
	printf(BLUE"*******************************************************************************\n"NONE);
	printf("航班号\t起点站\t终点站\t班期\t机型\t起飞时间\t到达时间\t票价\n");
	printf(GREEN"*******************************************************************************\n"NONE);
	for(p = h->next;p != h;p= p->next){
		if(strcmp(p->info.stime,key)==0){
			printf("%s\t",p->info.number);
			printf("%s\t",p->info.staddress);
			printf("%s\t",p->info.arraddress);
			printf("%s\t",p->info.DATE);
			printf("%s\t",p->info.TYPE);
			printf("%s\t\t",p->info.stime);
			printf("%s\t\t",p->info.atime);
			printf("%d\n",p->info.value);
			flag++;
		}
	}
	if(flag == 0)	
		printf("\033[10CNot found!\n");
}
Esempio n. 5
0
File: qplot.cpp Progetto: beg0/qplot
//----------------------------------------------------------------------------
// run by mission INI-file
bool qplot_run(
  const char  *mission_file, // имя INI-файла задания
  PlotArea    *pa,           // указатель на PlotArea : QwtPlot widget
  QMainWindow *mw)           // указатель на PlotWin  : QMainWindow
{
  qDebug("qplot_run(mission_file='%s')", mission_file);

  // open mission INI-file
  aclass::aini f(mission_file);

  std::string title = f.read_str("", "title", "");
  if (!title.size())
    title = mission_file;
  mw->setWindowTitle("QPlot - " + _QS(title));

  QSize wsize = mw->size();
  int width = (int) f.read_long("", "width", -1);
  if (width > 0) wsize.setWidth(width);
  int height = (int) f.read_long("", "height", -1);
  if (height > 0) wsize.setHeight(height);
  if (width > 0 || height > 0) mw->resize(wsize);

  // read [area] section
  PlotAreaConf conf = pa->getConf();
  qplot_read_conf(&f, "area", &conf);
  pa->setConf(conf);

  // off all markers
  pa->enableMarker(false);
  pa->enableVLine(false);
  pa->enableHLine(false);

  // read [axis] section
  qplot_read_axis(&f, "axis", pa);

  if (!f.has_section("0") && !f.has_section("1"))
    return false; // no curve section

  // remove all old curves
  pa->clear();

  // read curve description sections [0], [1], [2], ...
  int begin = (int) f.read_long("", "begin", 0);
  int end   = (int) f.read_long("", "end", 100);
  for (int i = begin; i <= end; i++)
  {
    qplot_xy_t data;

    str_t tmp = str_int(i);
    std::string s = str_c(&tmp);
    str_free(&tmp);
    if (!f.has_section(s)) continue;

    std::string file = f.read_str(s, "file", "");
    if (file.size() == 0) continue;

    long start = f.read_long(s, "start", 0);
    long size  = f.read_long(s, "size", -1);
    long step  = f.read_long(s, "step",  1);
    if (step <= 0) step = 1;

    std::string fmt = f.read_str(s, "format", "txt");
    if (_STRCMP(fmt, "bin"   ) == 0 ||
        _STRCMP(fmt, "binary") == 0 ||
        _STRCMP(fmt, "raw"   ) == 0)
    { // binary data file format
      long recordSize = f.read_long(s, "recordSize");
      if (recordSize <= 0)
      {
        qDebug("recordSize = %li, skip [%i] section",
               recordSize, i);
        continue;
      }

      int xOff = (int) f.read_long(s, "xOff", -1);
      int yOff = (int) f.read_long(s, "yOff", -1);

      std::string type = f.read_str(s, "xType", "float");
      int xType = qplot_id_by_type(type);

      type = f.read_str(s, "yType", "float");
      int yType = qplot_id_by_type(type);

      data = qplot_read_binary(file, start, size, step,
                               recordSize, xType, yType, xOff, yOff);
    }
    else
    { // text data file format
      std::string sep = f.read_str(s, "separator", " ");
      char separator = (sep.size() > 0) ? sep[0] : ' ';

      int xCol = (int) f.read_long(s, "xCol", -1);
      int yCol = (int) f.read_long(s, "yCol", -1);

      data = qplot_read_text(file, start, size, step,
                             separator, xCol, yCol);
    }

    if (data.size <= 0)
    {
      qDebug("data.size = %i, skip [%i] section", data.size, i);
      continue;
    }

    CurveConf conf;
    conf.legend = _QS(f.read_str(s, "legend", ""));

    conf.curve = qplot_qwt_curve_by_name(f.read_str(s, "curve", "lines"));

    conf.pen = QPen(
      QColor(f.read_str(s, "color", "black").c_str()),
      f.read_double(s, "width", conf.curve == QwtPlotCurve::Dots ? 3.0 : 1.0),
      qplot_pen_by_name(f.read_str(s, "style", "solid")));

    conf.symStyle = qplot_qwt_symbol_by_name(
      f.read_str(s, "symbol", "no"));

    conf.symPen = QPen(
      QColor(f.read_str(s, "symColor", "blue").c_str()),
      f.read_double(s, "symWidth", 1.0),
      Qt::SolidLine);

    conf.symBrush = QBrush(
      QColor(f.read_str(s, "symBrush", "gray").c_str()));

    conf.symSize = (int) f.read_long(s, "symSize", 7);

    std::string axis = f.read_str(s, "axisX", "Bottom");
    conf.xAxis = !_STRCMP(axis, "Top") ? QwtPlot::xTop : QwtPlot::xBottom;

    axis = f.read_str(s, "axisY", "Left");
    conf.yAxis = !_STRCMP(axis, "Right") ? QwtPlot::yRight : QwtPlot::yLeft;

		if (data.size)
      //pa->addCurve(data.x.data(), data.y.data(), data.size, conf /*, false*/);
      pa->addCurve(&data.x[0], &data.y[0], data.size, conf /*, false*/);
  } // for (int i = 0; i < num; i++)

  pa->redraw();
  return true;
}
Esempio n. 6
0
static void test_int()
{
    int error;
    int i = str_int("+12345", &error);
    if (error || i != 12345)
        fail();

    i = str_int("123456789", &error);
    if (error || i != 123456789)
        fail();

    i = str_int("7", &error);
    if (error || i != 7)
        fail();

    i = str_int("-7", &error);
    if (error || i != -7)
        fail();

    i = str_int("0", &error);
    if (error || i != 0)
        fail();

    i = str_int("32asdfa32", &error);
    if (!error)
        fail();

    i = str_int("", &error);
    if (!error)
        fail();

    i = str_int(".", &error);
    if (!error)
        fail();

    i = str_int(" ", &error);
    if (!error)
        fail();

    i = str_int("123123123123", &error);
    if (!error)
        fail();

    i = str_int("-123123123123", &error);
    if (!error)
        fail();
}
static Bitmap read_bmp_or_throw(const FilePath& filePath){
  BinaryReader in(filePath);
  if (!in.good()){
    throw ReadBmpError(error_open_file_read(filePath));
  }

  auto bitmapFileHeader = read_struct_or_throw_bmp<BitmapFileHeader>(in);

  if (bitmapFileHeader.fileType != BITMAP_SIGNATURE){
    throw ReadBmpError(error_bitmap_signature(bitmapFileHeader.fileType));
  }

  auto bitmapInfoHeader = read_struct_or_throw_bmp<BitmapInfoHeader>(in);

  if (invalid_header_length(bitmapInfoHeader.headerLen)){
    throw ReadBmpError(error_truncated_bmp_header(bitmapInfoHeader.headerLen));
  }

  if (bitmapInfoHeader.compression != Compression::BI_RGB){
    throw ReadBmpError(error_compression(bitmapInfoHeader.compression));
  }

  if (bitmapInfoHeader.colorPlanes != 1){
    throw ReadBmpError(error_color_planes(bitmapInfoHeader.colorPlanes));
  }

  auto bmpSize = get_size_and_order(bitmapInfoHeader);

  if (bitmapInfoHeader.paletteColors != 0){
    if (bitmapInfoHeader.bitsPerPixel != 8){ // Fixme: Maybe support?
      throw ReadBmpError("Palette for non 8-bpp bitmaps unsupported by Faint.");
    }
    auto colorList = or_throw(read_color_table(in, bitmapInfoHeader.paletteColors),
      "Failed reading color table.");
    in.seekg(bitmapFileHeader.dataOffset);

    auto alphaMap = or_throw(read_8bipp_BI_RGB(in, bmpSize),
      "Failed reading 8-bits-per-pixel data");

    return bitmap_from_indexed_colors(alphaMap, colorList);
  }
  else{
    // No palette
    in.seekg(bitmapFileHeader.dataOffset);
    if (bitmapInfoHeader.bitsPerPixel == 8){
      auto alphaMap = or_throw(read_8bipp_BI_RGB(in, bmpSize),
        "Failed reading 8-bits-per-pixel data");
      return bitmap_from_indexed_colors(alphaMap, grayscale_color_table());
    }
    else if (bitmapInfoHeader.bitsPerPixel == 24){
      return or_throw(read_24bipp_BI_RGB(in, bmpSize),
        "Failed reading 24-bits-per-pixel data.");
    }
    else if (bitmapInfoHeader.bitsPerPixel == 32){
      return or_throw(read_32bipp_BI_RGB(in, bmpSize),
        "Failed reading 32-bits-per-pixel data.");
    }
  }
  throw ReadBmpError(Sentence("Unsupported bits-per-pixel",
    bracketed(str_int(bitmapInfoHeader.bitsPerPixel))));
}
Esempio n. 8
0
static void processor(const char *tx_addr, int port)
{
    sys_init(1);
    sys_log('E', "started port=%d, tx=%s\n", port, tx_addr);

    /* connect to the control thread */
    char addr[MAX_ADDR];
    sys_address(addr, port);
    IO *io = sys_connect(addr, IO_CHUNK);

    tx_attach(tx_addr);

    /* get env code from the tx */
    char *code = tx_program();
    char *res = mem_alloc(MAX_BLOCK);

    while (!io->stop) {
        sys_iready(io, -1);

        int status = -1;
        long long sid = 0LL, time = sys_millis();

        Env *env = NULL;
        Arg *arg = NULL;
        Vars *v = vars_new(0), *r = NULL, *w = NULL;

        Http_Req *req = http_parse_req(io);
        if (io->stop)
            goto exit;

        if (req == NULL) {
            status = http_400(io);
            goto exit;
        }

        if (req->method == OPTIONS) {
            status = http_opts(io);
            goto exit;
        }

        env = env_new("net", code);

        if (str_idx(req->path, "/fn") == 0) {
            int idx = (req->path[3] == '/') ? 4 : 3;
            int i = 0, len = 1, cnt = 0;
            Func **fns = env_funcs(env, req->path + idx, &cnt);

            status = http_200(io);
            while (status == 200 && len) {
                len = pack_fn2csv(fns, cnt, res, MAX_BLOCK, &i);
                status = http_chunk(io, res, len);
            }

            mem_free(fns);
            goto exit;
        }

        /* compare the request with the function defintion */
        Func *fn = env_func(env, req->path + 1);
        if (fn == NULL) {
            Error *err = error_new("unknown function '%s'", req->path + 1);
            status = http_404(io, err->msg);
            mem_free(err);
            goto exit;
        }

        if (fn->rp.name != NULL && req->method != POST) {
            status = http_405(io, POST);
            goto exit;
        }

        if (fn->rp.name == NULL && req->method == POST) {
            status = http_405(io, GET);
            goto exit;
        }

        /* TODO: think what to do with duplicate parameter values */
        for (int i = 0; i < req->args->len; ++i) {
            char *name = req->args->names[i];
            if (array_freq(req->args->names, req->args->len, name) > 1) {
                Error *err = error_new("duplicate parameter '%s' "
                                       "(not supported)",
                                       name);
                status = http_404(io, err->msg);
                mem_free(err);
                goto exit;
            }
        }

        if (fn->pp.len != req->args->len) {
            Error *err = error_new("expected %d primitive parameters, got %d",
                                   fn->pp.len, req->args->len);
            status = http_404(io, err->msg);
            mem_free(err);
            goto exit;
        }

        arg = mem_alloc(sizeof(Arg));
        for (int i = 0; i < fn->pp.len; ++i) {
            char *name = fn->pp.names[i];
            Type t = fn->pp.types[i];

            int idx = array_scan(req->args->names, req->args->len, name);
            if (idx < 0) {
                Error *err = error_new("unknown parameter '%s'", name);
                status = http_404(io, err->msg);
                mem_free(err);
                goto exit;
            }

            char *val = req->args->vals[idx];
            int error = 0;
            if (t == Int) {
                arg->vals[i].v_int = str_int(val, &error);
            } else if (t == Real)
                arg->vals[i].v_real = str_real(val, &error);
            else if (t == Long)
                arg->vals[i].v_long = str_long(val, &error);
            else if (t == String) {
                error = str_len(val) > MAX_STRING;
                if (!error)
                    str_cpy(arg->vals[i].v_str, val);
            }

            if (error) {
                Error *err = error_new("value '%s' (parameter '%s') "
                                       "is not of type '%s'",
                                       val, name, type_to_str(t));
                status = http_404(io, err->msg);
                mem_free(err);
                goto exit;
            }
        }

        if (fn->rp.name != NULL) {
            TBuf *body = NULL;
            if (req->len > 0) {
                Error *err = pack_csv2rel(req->body, fn->rp.head, &body);
                if (err != NULL) {
                    status = http_404(io, err->msg);
                    mem_free(err);
                    goto exit;
                }
            } else {
                body = tbuf_new();
            }

            vars_add(v, fn->rp.name, 0, body);

            /* project the parameter */
            Rel *param = rel_project(rel_load(fn->rp.head, fn->rp.name),
                                     fn->rp.head->names,
                                     fn->rp.head->len);

            rel_eval(param, v, arg);

            /* clean the previous version */
            tbuf_clean(body);
            tbuf_free(body);

            /* replace with the new body */
            int vpos = array_scan(v->names, v->len, fn->rp.name);
            v->vals[vpos] = param->body;

            param->body = NULL;
            rel_free(param);
        }

        /* start a transaction */
        r = vars_new(fn->r.len);
        w = vars_new(fn->w.len);
        for (int i = 0; i < fn->r.len; ++i)
            vars_add(r, fn->r.names[i], 0, NULL);
        for (int i = 0; i < fn->w.len; ++i)
            vars_add(w, fn->w.names[i], 0, NULL);

        sid = tx_enter(addr, r, w);

        /* prepare variables */
        for (int i = 0; i < r->len; ++i) {
            TBuf *body = vol_read(r->vols[i], r->names[i], r->vers[i]);
            vars_add(v, r->names[i], 0, body);
        }
        for (int i = 0; i < w->len; ++i) {
            int pos = array_scan(v->names, v->len, w->names[i]);
            if (pos < 0)
                vars_add(v, w->names[i], 0, NULL);
        }
        for (int i = 0; i < fn->t.len; ++i)
            vars_add(v, fn->t.names[i], 0, NULL);

        /* evaluate the function body */
        for (int i = 0; i < fn->slen; ++i)
            rel_eval(fn->stmts[i], v, arg);

        /* prepare the return value. note, the resulting relation
           is just a container for the body, so it is not freed */
        Rel *ret = NULL;
        if (fn->ret != NULL)
            ret = fn->stmts[fn->slen - 1];

        /* persist the global variables */
        for (int i = 0; i < w->len; ++i) {
            int idx = array_scan(v->names, v->len, w->names[i]);
            if (idx < 0) {
                status = http_500(io);
                goto exit;
            }

            vol_write(w->vols[i], v->vals[idx], w->names[i], w->vers[i]);
            tbuf_free(v->vals[idx]);
            v->vals[idx] = NULL;
        }

        /* confirm a success and send the result back */
        status = http_200(io);
        if (status != 200)
            goto exit;

        tx_commit(sid);

        /* N.B. there is no explicit revert as the transaction manager handles
           nested tx_enter and a connectivity failure as a rollback */

        int len = 1, i = 0;
        while (status == 200 && len) {
            len = pack_rel2csv(ret, res, MAX_BLOCK, i++);
            status = http_chunk(io, res, len);
        }
exit:
        if (status != -1)
            sys_log('E', "%016llX method %c, path %s, time %lldms - %3d\n",
                         sid,
                         (req == NULL) ? '?' : req->method,
                         (req == NULL) ? "malformed" : req->path,
                         sys_millis() - time,
                         status);


        if (r != NULL)
            vars_free(r);
        if (w != NULL)
            vars_free(w);
        if (arg != NULL)
            mem_free(arg);
        if (req != NULL)
            http_free_req(req);
        if (env != NULL)
            env_free(env);
        for (int i = 0; i < v->len; ++i)
            if (v->vals[i] != NULL) {
                tbuf_clean(v->vals[i]);
                tbuf_free(v->vals[i]);
            }
        vars_free(v);

        sys_term(io);
    }

    mem_free(code);
    mem_free(res);
    tx_detach();
    sys_close(io);
}
Esempio n. 9
0
int main()
{
	{
		A::Enum a;
		B::Enum b;
		int n;
	
		A::init();
		a=A::ONE;
		b=B::ONE;
		//a=B::ONE; //nok
		n=a;
	
		assert(n==1);
		n=b;
		assert(n==1);
		assert(A::str[A::ONE]=="one");
		assert(A::str[1]=="one");
	}
	m[ZERO_]="zero";
	m[ONE_]="one";
	m[TWO_]="two";
	{
		N n=ZERO_;
		int m=ZERO_;
	
		assert(n==m);
	
		//n=m;  //nok
		n=static_cast<N>(m);
	
		m=n;
		assert(m==n);
	
		assert(ZERO_==0);
	}
	{
		N n;
		N *p, *q;
		int* r;
	
		n=ZERO_;
		p=&n;
		//p=new ZERO_; //nok
		//p=&ZERO_; //nok
		q=reinterpret_cast<N*>(new int(2));
		r=reinterpret_cast<int*>(p);
	
		assert(*p==n);
		assert(*p==ZERO_);
	
		assert(str_enum(n)=="zero");
		assert(str_enum(*p)=="zero");
		assert(str_enum(static_cast<N>(0))=="zero");
		assert(str_enum(*q)=="two");
	
		assert(str_int(ZERO_)=="0");
		assert(str_int(*q)=="2");
		assert(str_int(*r)=="0");
	
		// TODO enum =>int*
//		assert(str_int_ptr(ZERO_)=="0");
		//assert(str_int_ptr(&n)=="0"); //nok
		//assert(str_int_ptr(static_cast<int>(n))=="0");
		assert(str_int_ptr(reinterpret_cast<int*>(q))=="2");
		assert(str_int_ptr(r)=="0");
	
		delete q;
	}
	{
		N n=ZERO_;
		//Base b(ZERO_); //nok
		Base b(n);
	}
	{
		const int x=5;
		int y=2;
		//enum temp { x, y }; //nok compile error ''x/y' redeclared as different kind of symbol'
	}
	return 0;
}