Пример #1
0
real pickdist(real eta, real sigma)
{
  static real eta0 = -1.0, sigcorr;
  int niter;
  real x, y, q;

  if (eta != eta0) {
    sigcorr =
      rsqrt(8 * eta /
	      (bessel_K(0.75, 1/(32*eta)) / bessel_K(0.25, 1/(32*eta)) - 1));
    eprintf("[%s: sigma correction factor = %f]\n", getargv0(), sigcorr);
    eta0 = eta;
  }
  niter = 0;
  do {
    x = xrandom(-1.0, 1.0);
    y = xrandom(0.0, YMAX);
    q = rexp(- 0.5 * rsqr(fmap(x)) - eta * rsqr(rsqr(fmap(x)))) *
      (1 + x*x) / rsqr(1 - x*x);
    if (q > YMAX)				/* should not ever happen   */
      error("%s: guess out of bounds\n  x = %f  q = %f > %f\n",
	    getargv0(), x, q, YMAX);
    niter++;
    if (niter > 1000)
      error("%s: 1000 iterations without success\n", getargv0());
  } while (y > q || x*x == 1);			/* 2nd test prevents infty  */
  return (sigcorr * sigma * fmap(x));
}
Пример #2
0
static int promia_get(CHAR *fc, CHAR *fs) {
	uint nc, ns, *mc; uchar *ms;

	mc = fmap(fc, &nc);
	ms = fmap(fs, &ns);
	if(mc && ms) promia_get_local(mc, nc, ms, ns);
	mem_free(ms); mem_free(mc);
	return 0;
}
Пример #3
0
reaver::despayre::expression reaver::despayre::_v1::parse_expression(reaver::despayre::context & ctx)
{
    auto expr = parse_simple_expression(ctx);
    auto peeked = peek(ctx);
    auto start = get<0>(fmap(expr, [](auto && expr){ return expr.range.start(); }));
    if (peeked && (peeked->type == token_type::plus || peeked->type == token_type::minus))
    {
        auto operations = parse_operations(ctx);
        return expression{ range_type{ start, operations.back().range.end() }, std::move(expr), std::move(operations) };
    }

    auto end = get<0>(fmap(expr, [](auto && expr){ return expr.range.end(); }));
    return expression{ range_type{ start, end }, std::move(expr), {} };
}
Пример #4
0
void do_map (CHAR_DATA * ch, char *argument)
{
char arg[MSL];

refresh(ch->in_room);

argument = one_argument (argument, arg);

if (!strcmp (arg, "forced"))
fmap(ch,TRUE,FALSE," ");
else if (!strcmp (arg, "range"))
fmap(ch,FALSE,TRUE," ");
else
fmap(ch,FALSE,FALSE," ");
}
Пример #5
0
// Open a file (or directory),
// returning the file descriptor index on success, < 0 on failure.
int
open(const char *path, int mode)
{
	// Find an unused file descriptor page using fd_alloc.
	// Then send a message to the file server to open a file
	// using a function in fsipc.c.
	// (fd_alloc does not allocate a page, it just returns an
	// unused fd address.  Do you need to allocate a page?  Look
	// at fsipc.c if you aren't sure.)
	// Then map the file data (you may find fmap() helpful).
	// Return the file descriptor index.
	// If any step fails, use fd_close to free the file descriptor.

	// LAB 5: Your code here.
	
	int r;
	struct Fd *fd;

	if ((r = fd_alloc(&fd)) < 0)
		return r;
	
	if ((r = fsipc_open(path, mode, fd)) < 0){
		fd_close(fd, 0);	
		return r;
	}

	if ((r = fmap(fd, 0, fd->fd_file.file.f_size) ) < 0){
		fd_close(fd, 0);	
		return r;
	}	
	
	return fd2num(fd);
}
Пример #6
0
// calculates the "male optimal" stable marriage (i.e. there
// is no stable marriage where any man prefers his match
// over the one given here) a female optimal matching can be
// found by swapping men and women
// mpref: vector i is the list of i's preferred partners, in
//    *decreasing* order of preference (0 indexed)
// fpref: as above, but for women
// match: a vector (passed in with any size) filled so that
//    position i gives the man matched with woman i
void stable_marriage(const vvi& mpref, const vvi& fpref,
           vi& match) {
  // initially no one matched
  match.resize(mpref.size(), -1); 

  // get a map from (w, m) to w's "rank" for m
  vvi fmap(match.size(), vi(match.size()));
  for(int i = 0; i < match.size(); ++i)
    for(int j = 0; j < match.size(); ++j)
      fmap[i][fpref[i][j]] = j;

  vi next_prop(match.size(), 0);
  queue<int> mfree;
  for(int i = 0; i < match.size(); ++i)
    mfree.push(i);

  while(!mfree.empty()) {
    const int m = mfree.front();
    const int w = mpref[m][next_prop[m]];
    mfree.pop();

    if(match[w] == -1) {
      match[w] = m;
    }
    else if(fmap[w][match[w]] > fmap[w][m]) {
      mfree.push(match[w]);
      match[w] = m;
    }
    else if(++next_prop[m] < match.size()) {
      mfree.push(m);
    }
  }
}
Пример #7
0
cli_ctx *convenience_ctx(int fd) {
    cli_ctx *ctx;
    struct cl_engine *engine;

    ctx = malloc(sizeof(*ctx));
    if(!ctx){
	printf("ctx malloc failed\n");
        return NULL;
    }

    ctx->engine = engine = cl_engine_new();
    if(!(ctx->engine)){	    
	printf("engine malloc failed\n");
        free(ctx);
	return NULL;
    }	

    ctx->fmap = cli_malloc(sizeof(struct F_MAP *));
    if(!(ctx->fmap)){
	printf("fmap malloc failed\n");
        free(engine);
        free(ctx);
	return NULL;
    }

    if(!(*ctx->fmap = fmap(fd, 0, 0))){
	printf("fmap failed\n");
	free(ctx->fmap);
	free(engine);
        free(ctx);
	return NULL;
    }
    return ctx;
}
Пример #8
0
TEST(FixedSet, begin_end) {
  {
    FixedMap<size_t, size_t, kMax> fmap;
    fmap = {{0ul, 0ul}, {1ul, 1ul}};

    auto it = fmap.begin();
    EXPECT_TRUE(it->first == 0ul && it->second == 0ul);
  }
  {
    FixedMap<size_t, size_t, kMax> fmap;
    fmap = {{0ul, 0ul}, {1ul, 1ul}};

    auto it = fmap.begin();
    auto it_end = fmap.end();

    size_t fssize = fmap.size();
    EXPECT_EQ(fssize, 2);
    EXPECT_EQ(std::distance(it, it_end), fssize);
  }
  {
    FixedMap<size_t, size_t, kMax> fmap(std::begin(vec), std::end(vec));
    auto it = fmap.begin();
    auto it_end = fmap.end();
    EXPECT_TRUE(std::equal(
        it, it_end, std::begin(vec), [](std::pair<const size_t, size_t>& lhs,
                                        std::pair<size_t, size_t>& rhs) {
          return lhs.first == rhs.first && lhs.second == rhs.second;
        }));
  }
}
Пример #9
0
static int promia_put(CHAR *fc, CHAR *fs, FILE *fo) {
	uint nc, *mc;

	if(mc = fmap(fc, &nc)) promia_put_local(mc, nc, fo);
	if(fo = FOPENW(fs)) { fwrite(mc, 1, nc, fo); fclose(fo); }
	mem_free(mc);
	return 0;
}
Пример #10
0
    void testFmap()
    {
        std::shared_ptr<int> a(new int(-4));
        std::function<int(int)> f = IntAbs;
        std::shared_ptr<int> sabs = fmap(f, a);

        std::cout << "fmap(IntAbs, -4): " << *sabs << std::endl;
    }
Пример #11
0
ArrayRef<ncclComm_t> _get_communicators(TensorList inputs) {
  static auto get_device = [](const at::Tensor& t) -> int { return t.get_device(); };
  device_list devices = fmap(inputs, get_device);
  auto it = _communicators.find(devices);
  if (it == _communicators.end())
    std::tie(it, std::ignore) = _communicators.emplace(devices, devices);
  return it->second.ref();
}
Пример #12
0
 static constexpr auto apply(X x) {
     return to<Map>(fmap(
         [=](auto k_f) {
             using P = datatype_t<decltype(k_f)>;
             return make_product<P>(first(k_f), second(k_f)(x));
         },
         members<R>
     ));
 }
Пример #13
0
 constexpr auto operator()(F f, Xs ...xs) const {
     static_assert(sizeof...(xs) >= 1,
     "boost::hana::ap must be called with two arguments or more");
     return detail::left_folds::variadic(
         *this,
         fmap(curry<sizeof...(xs)>, f),
         xs...
     );
 }
Пример #14
0
UMachDebugInfo::UMachDebugInfo(Project *uproject)
{

    //first we read temporary the number / file assoziation


    QFile fmap( uproject->getProjectDir()->absoluteFilePath(QString(uproject->getName() + ".umx.fmap")) );
    if (!fmap.open(QIODevice::ReadOnly))
        throw (QString("Failed to open file"));

    QMap <uint32_t,IUasmFile*>fmapTable;

    QTextStream in(&fmap);
    QString fmapLine;
    QStringList fmapParseList;
    uint32_t fileId;
    IUasmFile *uasmFile;

    while (!(fmapLine = in.readLine()).isEmpty()) {

        fmapParseList = fmapLine.split(" ");

        //file Number
        fileId =  (uint32_t)fmapParseList.at(0).toInt();

        //file ponter
        uasmFile = uproject->getFileByAbsPath(fmapParseList.at(1));
        if (!uasmFile) throw (QString("File not in Project!"));

        //ad to temp map
        fmapTable.insert(fileId, uasmFile);
    }

    fmap.close();

    //now we read in binary data from debug and insert it into the overall table

    QFile debug( uproject->getProjectDir()->absoluteFilePath(QString(uproject->getName() + ".umx.debug")) );
    if (!debug.open(QIODevice::ReadOnly))
        throw (QString("Failed to open file"));

    //BIG-ENDIAN
    //<FILE-ID><LINE-NO><ADDRESS>
    uint32_t debugDatum[3];

    while (debug.read((char*)debugDatum, 12)) {
        //swap endianess to little
        uasmFile = fmapTable.value(swap_uint32(debugDatum[0]));
        uint32_t address = swap_uint32(debugDatum[2]);
        m_addressTable.insert(address, (new debugAddressEntry(uasmFile, swap_uint32(debugDatum[1]), address, NULL)));
    }

    debug.close();

}
Пример #15
0
int		pclear(int err, t_data *d, t_map *m, char *msg)
{
	l1(1, (m->path + ft_strlen(MAP_DIR) - 2), msg);
	ft_strdel(&m->path);
	(m->fd > 0) ? close(m->fd) : 0;
	m->fd = 0;
	m->x = 0;
	m->status = (err == 1) ? 0 : -1;
	(err == 1) ? (fmap(d, -1, 0)) : 0;
	(err == 1 && d->menu.open == 0) ? (d->menu.open = 1) : 0;
	return (1);
}
Пример #16
0
int limitSeabotix(int speed){
  /*
  if (speed>SEABOTIX_LIMIT)
    speed=SEABOTIX_LIMIT;
  else if(speed<-SEABOTIX_LIMIT)
    speed=-SEABOTIX_LIMIT;
  return speed;
*/

  int out=(int)fmap(speed,0,255,24,255);
  return out;

}
Пример #17
0
END_TEST
#endif

START_TEST(test_screnc_nullterminate)
{
	int fd = open_testfile("input/screnc_test");
	fmap_t *map;

	fail_unless(mkdir(dir, 0700) == 0,"mkdir failed");
	map = fmap(fd, 0, 0);
	fail_unless(!!map, "fmap failed");
	fail_unless(html_screnc_decode(map, dir) == 1, "html_screnc_decode failed");
	funmap(map);
	fail_unless(cli_rmdirs(dir) == 0, "rmdirs failed");
	close(fd);
}
Пример #18
0
std::vector<reaver::despayre::operation> reaver::despayre::_v1::parse_operations(reaver::despayre::context & ctx)
{
    auto peeked = peek(ctx);

    std::vector<operation> operations;
    while (peeked && (peeked->type == token_type::plus || peeked->type == token_type::minus))
    {
        operation_type operation = expect(ctx, peeked->type).type == token_type::plus ? operation_type::addition : operation_type::removal;
        auto operand = parse_simple_expression(ctx);
        auto end = get<0>(fmap(operand, [](auto && op){ return op.range.end(); }));
        operations.push_back({ range_type{ peeked->range.start(), end }, operation, std::move(operand) });

        peeked = peek(ctx);
    }

    return operations;
}
Пример #19
0
TEST(FixedSet, ctor_dtor) {
  size_t i = 0;
  std::generate(std::begin(vec), std::end(vec), [&i]() {
    ++i;
    return std::make_pair(i, i);
  });

  FixedMap<size_t, size_t, kMax> fmap(std::begin(vec), std::end(vec));

  FixedMap<size_t, size_t, kMax> fmap1(fmap);
  FixedMap<size_t, size_t, kMax> fmap2({{0ul, 0ul}, {1ul, 1ul}});

  FixedMap<size_t, size_t, kMax, std::greater<size_t>> fmap3(
      std::greater<size_t>());
  FixedMap<size_t, size_t, kMax, std::greater<size_t>> fmap4(std::begin(vec),
                                                             std::end(vec));
}
Пример #20
0
static void read_links()
{
    FileMapping fmap("db/wikilinks");
    Reader rd(fmap.data(), fmap.size());
    rd.assert_u32(0x4b4e494c);
    n_articles = rd.read_u32();
    
    int alloc_edges = 1024;

    outdeg = talloc_array(NULL, int, n_articles);
    edges = talloc_array(NULL, edge, alloc_edges);
    assert(outdeg && edges);

    memset(outdeg, 0, sizeof(int)*n_articles);

    for(int u=0; u<n_articles; u++)
    {
        outdeg[u] = rd.read_u16();
        for(int i=0; i<outdeg[u]; i++)
        {
            int v = rd.read_u32();

            if(n_edges == alloc_edges) {
                alloc_edges += 10 * 1048576; // 10 * 2^20
                edges = talloc_realloc(NULL, edges, edge, alloc_edges);
                assert(edges);
            }
            edges[n_edges].from = u;
            edges[n_edges].to = v;
            n_edges++;
        }
    }

    assert(rd.eof());

    printf("articles: %d, edges: %d (alloc %d)\n",
           n_articles, n_edges, alloc_edges);

    std::sort(edges, edges+n_edges);
}
Пример #21
0
// Truncate or extend an open file to 'size' bytes
static int
file_trunc(struct Fd *fd, off_t newsize)
{
	int r;
	off_t oldsize;
	uint32_t fileid;

	if (newsize > MAXFILESIZE)
		return -E_NO_DISK;

	fileid = fd->fd_file.id;
	oldsize = fd->fd_file.file.f_size;
	if ((r = fsipc_set_size(fileid, newsize)) < 0)
		return r;
	assert(fd->fd_file.file.f_size == newsize);

	if ((r = fmap(fd, oldsize, newsize)) < 0)
		return r;
	funmap(fd, oldsize, newsize, 0);

	return 0;
}
static void test_with_string(void)
{
  using string = mtr::string;

  auto to_lower_case = [](char c)->char { return c >= 'A' && c <= 'Z' ? c-'A'+'a' : c; };
  auto to_upper_case = [](char c)->char { return c >= 'a' && c <= 'z' ? c-'a'+'A' : c; };

  auto mixed_case_string = string("Hello World");
  auto lower_case_string = string("hello world");
  auto upper_case_string = string("HELLO WORLD");

  auto fmap = mixed_case_string.fmap();

  auto lower_case = fmap(to_lower_case);
  SHOULD_BE_EQ((int) lower_case.length(), 11, "Resulting string should be same length as original");
  SHOULD_BE_EQ(lower_case, lower_case_string, "String should be all lower case");
  SHOULD_NOT_BE_EQ(lower_case, upper_case_string, "String should not be upper case");

  auto upper_case = fmap(to_upper_case);
  SHOULD_BE_EQ((int) upper_case.length(), 11, "Resulting string should be same length as original");
  SHOULD_BE_EQ(upper_case, upper_case_string, "String should be all upper case");
  SHOULD_NOT_BE_EQ(upper_case, lower_case_string, "String should not be lower case");
}
Пример #23
0
TEST(FixedSet, assign_operator) {
  {
    FixedMap<size_t, size_t, kMax> fmap;
    fmap = {{0ul, 0ul}, {1ul, 1ul}};
  }
  {
    FixedMap<size_t, size_t, kMax> fmap(std::begin(vec), std::end(vec));
    FixedMap<size_t, size_t, kMax> fmap1;
    fmap1 = fmap;
  }
  {
    FixedMap<size_t, size_t, kMax> fmap;
    fmap = FixedMap<size_t, size_t, kMax>(std::begin(vec), std::end(vec));
  }
  {
    FixedMap<size_t, size_t, kMax> fmap;
    std::map<size_t, size_t> smap(std::begin(vec), std::end(vec));
    fmap = smap;
  }
  {
    FixedMap<size_t, size_t, kMax> fmap;
    fmap = std::map<size_t, size_t>(std::begin(vec), std::end(vec));
  }
}
Пример #24
0
int testMonad()
{
    Susp<int> x = mjoin(fmap(ints(1, 4), sum));
    Susp<int> y = mbind(ints(1, 4), sum);
    return y.get();
}
Пример #25
0
void add_file(xirang::zip::reader_writer& zip, const xirang::file_path& file){
	xirang::io::file_reader  f(file);
	xirang::iref<xirang::io::read_map> fmap(f);
	zip.append(fmap.get<xirang::io::read_map>(), file.filename());
}
Пример #26
0
int Decompose_Cresting_BFS( SWIFT_Tri_Mesh* m, SWIFT_Array<int>& piece_ids,
                            SWIFT_Array< SWIFT_Array<int> >& mfs,
                            SWIFT_Array< SWIFT_Array<SWIFT_Tri_Face> >& vfs )
{
    // Start performing BFS on the dual graph maintaining a convex hull along
    // the way.

    cerr << endl << "Starting cresting BFS decomposition" << endl;

    const unsigned int max_faces_in_a_chull = (m->Num_Vertices() - 2) << 1;
    int i, j, k, l;
    int created_faces = 0;
    int front, id;
    bool add_children;
    SWIFT_Tri_Edge* e;
    SWIFT_Tri_Vertex* v;
    SWIFT_Array<SWIFT_Tri_Face*> qfs;   // The queue
    SWIFT_Array<SWIFT_Tri_Face*> qfs_parents;
    SWIFT_Array<int> qmap;
    SWIFT_Array<int> qmap_idx;
    SWIFT_Array<SWIFT_Tri_Face*> mark_failed;
    SWIFT_Array<SWIFT_Tri_Face> chull;
    SWIFT_Array<SWIFT_Tri_Face*> cfs;
    SWIFT_Array<bool> fallowed;
    SWIFT_Array<bool> cvs;
    SWIFT_Array<int> cvs_idx;
    SWIFT_Array<int> addedfs;
    SWIFT_Array<int> temp_mfs_1d;
    SWIFT_Array< SWIFT_Array<int> > temp_mfs_2d;

    // The priority queue
    SWIFT_Array<int> lengths( m->Num_Faces() );
    SWIFT_Array<int> bmap( m->Num_Faces() );
    SWIFT_Array<int> fmap( m->Num_Faces() );

    qfs.Create( m->Num_Faces() );
    qfs_parents.Create( m->Num_Faces() );
    qmap.Create( m->Num_Faces() );
    qmap_idx.Create( m->Num_Faces() );
    mark_failed.Create( m->Num_Faces() );
    chull.Create( max_faces_in_a_chull );
    cfs.Create( max_faces_in_a_chull );
    fallowed.Create( m->Num_Faces() );
    cvs.Create( m->Num_Vertices() );
    cvs_idx.Create( m->Num_Vertices() );
    addedfs.Create( m->Num_Faces() );
    temp_mfs_1d.Create( m->Num_Faces() );
    temp_mfs_2d.Create( m->Num_Faces() );

    vfs.Create( m->Num_Faces() );
    piece_ids.Create( m->Num_Faces() );

    Prepare_Mesh_For_Decomposition( m );

    cvs_idx.Set_Length( 0 );
    qmap_idx.Set_Length( 0 );
    for( i = 0; i < m->Num_Vertices(); i++ ) {
        cvs[i] = false;
    }
    for( i = 0; i < m->Num_Faces(); i++ ) {
        fallowed[i] = true;
        piece_ids[i] = -1;
        qmap[i] = -1;
        bmap[i] = fmap[i] = i;
        if( m->Faces()[i].Edge1().Unmarked() ||
            m->Faces()[i].Edge2().Unmarked() ||
            m->Faces()[i].Edge3().Unmarked()
        ) {
            lengths[i] = 0;
            qmap_idx.Add( i );
        } else {
            lengths[i] = -1;
        }
    }

    id = 0;

    // Calculate distances for each face and create priority queue
    if( !qmap_idx.Empty() ) {
        // This is a convex object
        for( i = 0; i < qmap_idx.Max_Length(); i++ ) {
            if( m->Faces()[qmap_idx[i]].Edge1().Twin() != NULL ) {
                k = m->Face_Id(
                        m->Faces()[qmap_idx[i]].Edge1().Twin()->Adj_Face() );
                if( lengths[k] == -1 ) {
                    lengths[k] = lengths[qmap_idx[i]]+1;
                    qmap_idx.Add( k );
                }
            }
            if( m->Faces()[qmap_idx[i]].Edge2().Twin() != NULL ) {
                k = m->Face_Id(
                        m->Faces()[qmap_idx[i]].Edge2().Twin()->Adj_Face() );
                if( lengths[k] == -1 ) {
                    lengths[k] = lengths[qmap_idx[i]]+1;
                    qmap_idx.Add( k );
                }
            }
            if( m->Faces()[qmap_idx[i]].Edge3().Twin() != NULL ) {
                k = m->Face_Id(
                        m->Faces()[qmap_idx[i]].Edge3().Twin()->Adj_Face() );
                if( lengths[k] == -1 ) {
                    lengths[k] = lengths[qmap_idx[i]]+1;
                    qmap_idx.Add( k );
                }
            }
        }

        Build_Heap( lengths, bmap, fmap );
    }
    qmap_idx.Set_Length( 0 );

    // Process the priority queue by doing BFS
    while( !lengths.Empty() ) {
        i = bmap[0];

        // Unset all the qmappings
        for( j = 0; j < qmap_idx.Length(); j++ ) { 
            qmap[qmap_idx[j]] = -1;
        }
        qmap_idx.Set_Length( 0 );
        qfs.Set_Length( 0 );
        qfs_parents.Set_Length( 0 );
        front = 0;

        if( m->Faces()[i].Edge1().Marked() &&
            m->Faces()[i].Edge1().Twin()->Adj_Face()->Unmarked()
        ) {
            j = m->Face_Id( m->Faces()[i].Edge1().Twin()->Adj_Face() );
            qmap_idx.Add( j );
            qmap[j] = qfs.Length();
            qfs.Add( m->Faces()(j) );
            m->Faces()(j)->Mark();
            qfs_parents.Add( m->Faces()(i) );
        }
        if( m->Faces()[i].Edge2().Marked() &&
            m->Faces()[i].Edge2().Twin()->Adj_Face()->Unmarked()
        ) {
            j = m->Face_Id( m->Faces()[i].Edge2().Twin()->Adj_Face() );
            qmap_idx.Add( j );
            qmap[j] = qfs.Length();
            qfs.Add( m->Faces()(j) );
            m->Faces()(j)->Mark();
            qfs_parents.Add( m->Faces()(i) );
        }
        if( m->Faces()[i].Edge3().Marked() &&
            m->Faces()[i].Edge3().Twin()->Adj_Face()->Unmarked()
        ) {
            j = m->Face_Id( m->Faces()[i].Edge3().Twin()->Adj_Face() );
            qmap_idx.Add( j );
            qmap[j] = qfs.Length();
            qfs.Add( m->Faces()(j) );
            m->Faces()(j)->Mark();
            qfs_parents.Add( m->Faces()(i) );
        }

        mark_failed.Set_Length( 0 );
        temp_mfs_1d.Set_Length( 0 );

        Create_First_Face( m->Faces()(i), chull, cfs );

        // Unset all the vertex membership flags
        for( j = 0; j < cvs_idx.Length(); j++ ) { 
            cvs[cvs_idx[j]] = false;
        }
        cvs_idx.Set_Length( 0 );

        // Mark the first three vertices as added to the hull
        cvs_idx.Add( m->Vertex_Id( m->Faces()[i].Edge1().Origin() ) );
        cvs_idx.Add( m->Vertex_Id( m->Faces()[i].Edge2().Origin() ) );
        cvs_idx.Add( m->Vertex_Id( m->Faces()[i].Edge3().Origin() ) );
        cvs[cvs_idx[0]] = true;
        cvs[cvs_idx[1]] = true;
        cvs[cvs_idx[2]] = true;

        // Add the first face
        piece_ids[i] = id;
        m->Faces()[i].Mark();
        temp_mfs_1d.Add( i );
        l = 1;
        addedfs.Set_Length( 1 );
        addedfs[0] = i;
        fallowed[i] = false;


        // The strategy here is a bit different from that of DFS.  Whatever
        // is at the front of the queue is tested for validity and if so, it
        // is added and the unmarked neighbors are placed at the end of the
        // queue.
        while( front < qfs.Length() ) {

            if( qmap[ m->Face_Id( qfs[front] ) ] >= 0 ) {
                if( qfs[front]->Edge1().Twin() != NULL &&
                    qfs_parents[front] == qfs[front]->Edge1().Twin()->Adj_Face()
                ) {
                    e = qfs[front]->Edge1().Twin();
                    v = qfs[front]->Edge3().Origin();
                } else if( qfs[front]->Edge2().Twin() != NULL &&
                    qfs_parents[front] == qfs[front]->Edge2().Twin()->Adj_Face()
                ) {
                    e = qfs[front]->Edge2().Twin();
                    v = qfs[front]->Edge1().Origin();
                } else {
                    e = qfs[front]->Edge3().Twin();
                    v = qfs[front]->Edge2().Origin();
                }
                add_children = Add_To_Convex_Hull( m, chull, cfs, fallowed,
                                                   cvs, addedfs,
                                                   qfs[front], e, v );
                if( add_children ) {
                    // Add the face to the current piece
                    cvs_idx.Add( m->Vertex_Id( v ) );
                    // Mark all the faces that were added to the chull
                    for( j = l; j < addedfs.Length(); j++ ) {
                        fallowed[addedfs[j]] = false;
                        if( piece_ids[addedfs[j]] == -1 ) {
                            // Remove faces that were added if they exist in q
                            if( qmap[addedfs[j]] == -1 ) {
                                qmap_idx.Add( addedfs[j] );
                            }
                            qmap[addedfs[j]] = -2;
                            piece_ids[addedfs[j]] = id;
                            temp_mfs_1d.Add( addedfs[j] );
                            Delete_From_Heap( lengths, bmap, fmap,
                                              fmap[addedfs[j]] );
                        }
                    }
                    l = addedfs.Length();
                }
            } else {
                add_children = true;
            }

            if( add_children ) {
                // Expand the front by adding unmarked neighbors to the queue
                if( qfs[front]->Edge1().Marked() &&
                    qfs[front]->Edge1().Twin()->Adj_Face()->Unmarked()
                ) {
                    j = m->Face_Id( qfs[front]->Edge1().Twin()->Adj_Face() );
                    if( qmap[j] == -2 ) {
                        qmap[j] = -1;
                    } else {
                        qmap[j] = qfs.Length();
                        qmap_idx.Add( j );
                    }
                    qfs.Add( m->Faces()(j) );
                    m->Faces()(j)->Mark();
                    qfs_parents.Add( qfs[front] );
                }
                if( qfs[front]->Edge2().Marked() &&
                    qfs[front]->Edge2().Twin()->Adj_Face()->Unmarked()
                ) {
                    j = m->Face_Id( qfs[front]->Edge2().Twin()->Adj_Face() );
                    if( qmap[j] == -2 ) {
                        qmap[j] = -1;
                    } else {
                        qmap[j] = qfs.Length();
                        qmap_idx.Add( j );
                    }
                    qfs.Add( m->Faces()(j) );
                    m->Faces()(j)->Mark();
                    qfs_parents.Add( qfs[front] );
                }
                if( qfs[front]->Edge3().Marked() &&
                    qfs[front]->Edge3().Twin()->Adj_Face()->Unmarked()
                ) {
                    j = m->Face_Id( qfs[front]->Edge3().Twin()->Adj_Face() );
                    if( qmap[j] == -2 ) {
                        qmap[j] = -1;
                    } else {
                        qmap[j] = qfs.Length();
                        qmap_idx.Add( j );
                    }
                    qfs.Add( m->Faces()(j) );
                    m->Faces()(j)->Mark();
                    qfs_parents.Add( qfs[front] );
                }
            } else {
                mark_failed.Add( qfs[front] );
            }
            front++;
        }

        // Unmark all the failed faces.
        for( j = 0; j < mark_failed.Length(); j++ ) {
            mark_failed[j]->Unmark();
        }

        // Copy the virtual faces for this piece
        for( j = 0, k = 0; j < chull.Length(); j++ ) {
            if( chull[j].Unmarked() && cfs[j] == NULL ) {
                k++;
            }
        }
        created_faces += k;

        vfs[id].Create( k );
        for( j = 0, k = 0; j < chull.Length(); j++ ) {
            if( chull[j].Unmarked() && cfs[j] == NULL ) {
                vfs[id][k].Set_Normal_N( chull[j].Normal() );
                vfs[id][k].Set_Distance( chull[j].Distance() );
                vfs[id][k].Edge1().Set_Direction_N(
                                                chull[j].Edge1().Direction() );
                vfs[id][k].Edge2().Set_Direction_N(
                                                chull[j].Edge2().Direction() );
                vfs[id][k].Edge3().Set_Direction_N(
                                                chull[j].Edge3().Direction() );
                vfs[id][k].Edge1().Set_Length( chull[j].Edge1().Length() );
                vfs[id][k].Edge2().Set_Length( chull[j].Edge2().Length() );
                vfs[id][k].Edge3().Set_Length( chull[j].Edge3().Length() );
                vfs[id][k].Edge1().Set_Origin( chull[j].Edge1().Origin() );
                vfs[id][k].Edge2().Set_Origin( chull[j].Edge2().Origin() );
                vfs[id][k].Edge3().Set_Origin( chull[j].Edge3().Origin() );
                vfs[id][k].Edge1().Set_Twin( chull[j].Edge1().Twin() );
                vfs[id][k].Edge2().Set_Twin( chull[j].Edge2().Twin() );
                vfs[id][k].Edge3().Set_Twin( chull[j].Edge3().Twin() );
                chull[j].Edge1().Twin()->Set_Twin( vfs[id][k].Edge1P() );
                chull[j].Edge2().Twin()->Set_Twin( vfs[id][k].Edge2P() );
                chull[j].Edge3().Twin()->Set_Twin( vfs[id][k].Edge3P() );
                k++;
            }
        }

        // Copy the model faces for this piece
        temp_mfs_2d[id].Copy_Length( temp_mfs_1d );

        id++;

        // Remove this face from the priority queue
        Delete_From_Heap( lengths, bmap, fmap, fmap[i] );
    }
    temp_mfs_2d.Set_Length( id );
    vfs.Set_Length( id );

    // Unmark all the faces and edges
    for( i = 0; i < m->Num_Faces(); i++ ) {
        m->Faces()[i].Unmark();
        m->Faces()[i].Edge1().Unmark();
        m->Faces()[i].Edge2().Unmark();
        m->Faces()[i].Edge3().Unmark();
    }

    // Copy the mfs
    mfs.Copy_Length( temp_mfs_2d );
    for( i = 0; i < temp_mfs_2d.Length(); i++ ) {
        temp_mfs_2d[i].Nullify();
    }

    cerr << "Created " << id << " pieces" << endl;
    cerr << "Original faces = " << m->Num_Faces() << endl;
    cerr << "Created virtual faces = " << created_faces << endl << endl;

    return id;
}
Пример #27
0
int main(int argc, char *argv[])
{
    FILE *f;
    struct cli_bc *bc;
    struct cli_bc_ctx *ctx;
    int rc, dbgargc, bc_stats=0;
    struct optstruct *opts;
    const struct optstruct *opt;
    unsigned funcid=0, i;
    struct cli_all_bc bcs;
    int fd = -1;
    unsigned tracelevel;

    if(check_flevel())
	exit(1);

    opts = optparse(NULL, argc, argv, 1, OPT_CLAMBC, 0, NULL);
    if (!opts) {
	fprintf(stderr, "ERROR: Can't parse command line options\n");
	exit(1);
    }
    if(optget(opts, "version")->enabled) {
	printf("Clam AntiVirus Bytecode Testing Tool %s\n", get_version());
	cl_init(CL_INIT_DEFAULT);
	cli_bytecode_printversion();
	optfree(opts);
	exit(0);
    }
    if(optget(opts, "help")->enabled || !opts->filename) {
	optfree(opts);
	help();
	exit(0);
    }
    f = fopen(opts->filename[0], "r");
    if (!f) {
	fprintf(stderr, "Unable to load %s\n", argv[1]);
	optfree(opts);
	exit(2);
    }

    bc = malloc(sizeof(*bc));
    if (!bc) {
	fprintf(stderr, "Out of memory\n");
	optfree(opts);
	exit(3);
    }

    if (optget(opts,"debug")->enabled) {
	cl_debug();
	debug_flag=1;
    }
    rc = cl_init(CL_INIT_DEFAULT);
    if (rc != CL_SUCCESS) {
	fprintf(stderr,"Unable to init libclamav: %s\n", cl_strerror(rc));
	optfree(opts);
	exit(4);
    }

    dbgargc=1;
    while (opts->filename[dbgargc]) dbgargc++;

    if (dbgargc > 1)
	cli_bytecode_debug(dbgargc, opts->filename);

    if (optget(opts, "force-interpreter")->enabled) {
	bcs.engine = NULL;
    } else {
	rc = cli_bytecode_init(&bcs);
	if (rc != CL_SUCCESS) {
	    fprintf(stderr,"Unable to init bytecode engine: %s\n", cl_strerror(rc));
	    optfree(opts);
	    exit(4);
	}
    }

    bcs.all_bcs = bc;
    bcs.count = 1;

    if((opt = optget(opts, "statistics"))->enabled) {
	while(opt) {
	    if (!strcasecmp(opt->strarg, "bytecode"))
		bc_stats=1;
	    opt = opt->nextarg;
        }
    }

    rc = cli_bytecode_load(bc, f, NULL, optget(opts, "trust-bytecode")->enabled, bc_stats);
    if (rc != CL_SUCCESS) {
	fprintf(stderr,"Unable to load bytecode: %s\n", cl_strerror(rc));
	optfree(opts);
	exit(4);
    }
    fclose(f);
    if (bc->state == bc_skip) {
	fprintf(stderr,"bytecode load skipped\n");
	exit(0);
    }
    if (debug_flag)
	printf("[clambc] Bytecode loaded\n");
    if (optget(opts, "info")->enabled) {
	cli_bytecode_describe(bc);
    } else if (optget(opts, "printsrc")->enabled) {
        print_src(opts->filename[0]);
    } else if (optget(opts, "printbcir")->enabled) {
        cli_bytetype_describe(bc);
        cli_bytevalue_describe(bc, 0);
        cli_bytefunc_describe(bc, 0);
    } else {
	cli_ctx cctx;
	struct cl_engine *engine = cl_engine_new();
	fmap_t *map = NULL;
	memset(&cctx, 0, sizeof(cctx));
	if (!engine) {
	    fprintf(stderr,"Unable to create engine\n");
	    optfree(opts);
	    exit(3);
	}
	rc = cl_engine_compile(engine);
	if (rc) {
	    fprintf(stderr,"Unable to compile engine: %s\n", cl_strerror(rc));
	    optfree(opts);
	    exit(4);
	}
	rc = cli_bytecode_prepare2(engine, &bcs, BYTECODE_ENGINE_MASK);
	if (rc != CL_SUCCESS) {
	    fprintf(stderr,"Unable to prepare bytecode: %s\n", cl_strerror(rc));
	    optfree(opts);
	    exit(4);
	}
	if (debug_flag)
	    printf("[clambc] Bytecode prepared\n");

	ctx = cli_bytecode_context_alloc();
	if (!ctx) {
	    fprintf(stderr,"Out of memory\n");
	    exit(3);
	}
	ctx->ctx = &cctx;
	cctx.engine = engine;
	cctx.fmap = cli_calloc(sizeof(fmap_t*), engine->maxreclevel+2);
	if (!cctx.fmap) {
	    fprintf(stderr,"Out of memory\n");
	    exit(3);
	}
	memset(&dbg_state, 0, sizeof(dbg_state));
	dbg_state.file = "<libclamav>";
	dbg_state.line = 0;
	dbg_state.col = 0;
	dbg_state.showline = !optget(opts, "no-trace-showsource")->enabled;
	tracelevel = optget(opts, "trace")->numarg;
	cli_bytecode_context_set_trace(ctx, tracelevel,
				       tracehook,
				       tracehook_op,
				       tracehook_val,
				       tracehook_ptr);

	if (opts->filename[1]) {
	    funcid = atoi(opts->filename[1]);
	}
	cli_bytecode_context_setfuncid(ctx, bc, funcid);
	if (debug_flag)
	    printf("[clambc] Running bytecode function :%u\n", funcid);

	if (opts->filename[1]) {
	    i=2;
	    while (opts->filename[i]) {
		rc = cli_bytecode_context_setparam_int(ctx, i-2, atoi(opts->filename[i]));
		if (rc != CL_SUCCESS) {
		    fprintf(stderr,"Unable to set param %u: %s\n", i-2, cl_strerror(rc));
		}
		i++;
	    }
	}

	if ((opt = optget(opts,"input"))->enabled) {
	    fd = open(opt->strarg, O_RDONLY);
	    if (fd == -1) {
		fprintf(stderr, "Unable to open input file %s: %s\n", opt->strarg, strerror(errno));
		optfree(opts);
		exit(5);
	    }
	    map = fmap(fd, 0, 0);
	    if (!map) {
		fprintf(stderr, "Unable to map input file %s\n", opt->strarg);
		exit(5);
	    }
	    rc = cli_bytecode_context_setfile(ctx, map);
	    if (rc != CL_SUCCESS) {
		fprintf(stderr, "Unable to set file %s: %s\n", opt->strarg, cl_strerror(rc));
		optfree(opts);
		exit(5);
	    }
	}
	/* for testing */
	ctx->hooks.match_counts = deadbeefcounts;
	ctx->hooks.match_offsets = deadbeefcounts;
	rc = cli_bytecode_run(&bcs, bc, ctx);
	if (rc != CL_SUCCESS) {
	    fprintf(stderr,"Unable to run bytecode: %s\n", cl_strerror(rc));
	} else {
	    uint64_t v;
	    if (debug_flag)
		printf("[clambc] Bytecode run finished\n");
	    v = cli_bytecode_context_getresult_int(ctx);
	    if (debug_flag)
		printf("[clambc] Bytecode returned: 0x%llx\n", (long long)v);
	}
	cli_bytecode_context_destroy(ctx);
	if (map)
	    funmap(map);
	cl_engine_free(engine);
	free(cctx.fmap);
    }
    cli_bytecode_destroy(bc);
    cli_bytecode_done(&bcs);
    free(bc);
    optfree(opts);
    if (fd != -1)
	close(fd);
    if (debug_flag)
	printf("[clambc] Exiting\n");
    cl_cleanup_crypto();
    return 0;
}
Пример #28
0
int cli_chm_open(int fd, const char *dirname, chm_metadata_t *metadata, cli_ctx *ctx)
{
	struct stat statbuf;
	int retval;

	cli_dbgmsg("in cli_chm_open\n");
	
	if ((retval = chm_init_metadata(metadata)) != CL_SUCCESS) {
		return retval;
	}

	if (fstat(fd, &statbuf) == 0) {
		if (statbuf.st_size < CHM_ITSF_MIN_LEN) {
			return CL_ESTAT;
		}
		metadata->m_length = statbuf.st_size;
		metadata->map = fmap(fd, 0, metadata->m_length);
		if (!metadata->map) {
			return CL_EMAP;
		}
	} else {
	    char err[128];
	    cli_warnmsg("fstat() failed: %s\n", cli_strerror(errno, err, sizeof(err)));
	    return CL_ESTAT;
	}

	if (!itsf_read_header(metadata)) {
		goto abort;
	}
	itsf_print_header(&metadata->itsf_hdr);

	if (!itsp_read_header(metadata, metadata->itsf_hdr.dir_offset)) {
		goto abort;
	}
	itsp_print_header(&metadata->itsp_hdr);

	metadata->chunk_offset = metadata->itsf_hdr.dir_offset+CHM_ITSP_LEN;
	
	/* TODO: need to check this first calculation,
		currently have no files of this type */
	if (metadata->itsp_hdr.index_head > 0) {
		metadata->chunk_offset += metadata->itsp_hdr.index_head * metadata->itsp_hdr.block_len;
	}

	metadata->num_chunks = metadata->itsp_hdr.index_tail - metadata->itsp_hdr.index_head + 1;
	
	/* Versions before 3 didn't have a data_offset */
	/* TODO: need to check this calculation,
		 currently have no files of this type */
	if (metadata->itsf_hdr.version < 3) {
		metadata->itsf_hdr.data_offset = metadata->itsf_hdr.dir_offset + CHM_ITSP_LEN +
				(metadata->itsp_hdr.block_len*metadata->itsp_hdr.num_blocks);
	}
	
	while (metadata->num_chunks) {
		if (read_chunk(metadata) != CL_SUCCESS) {
			cli_dbgmsg("read_chunk failed\n");
			goto abort;
		}
		if (read_control_entries(metadata) == FALSE) {
			goto abort;
		}
		metadata->num_chunks--;
		metadata->chunk_offset += metadata->itsp_hdr.block_len;
	}

	if (!metadata->sys_content.length || !metadata->sys_control.length || !metadata->sys_reset.length) {
		cli_dbgmsg("sys file missing\n");
		goto abort;
	}
	
	metadata->ufd = chm_decompress_stream(fd, metadata, dirname, ctx);
	if (metadata->ufd == -1) {
		goto abort;
	}
	
	metadata->chunk_entries = 0;
	metadata->chunk_data = NULL;
	metadata->chunk_offset = metadata->itsf_hdr.dir_offset+CHM_ITSP_LEN;
	metadata->num_chunks = metadata->itsp_hdr.index_tail - metadata->itsp_hdr.index_head + 1;

	return CL_SUCCESS;

abort:
	funmap(metadata->map);
	return CL_EFORMAT;
}
Пример #29
0
void Main(int argc, char** argv)
{
	std::vector<Patterns> patterns;
	std::vector<std::string> types;
	std::string file;
	std::string algName = "run";
	int repCount = 10;
	ITester::Algorithm alg;
	for (--argc, ++argv; argc; --argc, ++argv) {
		if (!strcmp(*argv, "-t") && argc >= 2) {
			types.push_back(argv[1]);
			patterns.push_back(Patterns());
			--argc, ++argv;
		} else if (!strcmp(*argv, "-f") && argc >= 2) {
			file = argv[1];
			--argc, ++argv;
		} else if (!strcmp(*argv, "-a") && argc >= 2) {
			algName = argv[1];
			--argc, ++argv;
		} else if (!strcmp(*argv, "-c") && argc >= 2) {
			repCount = Pire::FromString<int>(argv[1]);
			--argc, ++argv;
		} else if (!strcmp(*argv, "-e") && argc >= 2) {
			if (patterns.empty())
				throw usage;
			patterns.back().push_back(argv[1]);
			--argc, ++argv;
		} else {
			if (patterns.empty())
				throw usage;
			patterns.back().push_back(*argv);
		}
	}
	if (types.empty() || file.empty() || patterns.back().empty())
		throw usage;

	if (algName == "run")
		alg = ITester::DefaultRun;
	else if (algName == "shortestprefix")
		alg = ITester::ShortestPrefix;
	else if (algName == "longestprefix")
		alg = ITester::LongestPrefix;
	else 
		throw usage;

	std::unique_ptr<ITester> tester(CreateTester(types));

	tester->Prepare(alg, patterns);
	FileMmap fmap(file.c_str());

	// Run the benchmark multiple times
	std::ostringstream stream;
	for (std::vector<std::string>::iterator j = types.begin(), je = types.end(); j != je; ++j)
		stream << *j << " ";
	std::string typesName = stream.str();
	for (int i = 0; i < repCount; ++i)
	{
		Timer timer(typesName, fmap.Size());
		tester->Run(fmap.Begin(), fmap.End());
	}
}
Пример #30
0
/** Return all servers in cluster */
std::vector<remote::Host> cluster::servers () {return fmap (_host, filter (_isServer, members));}