//------------------------------------------------------------------------------
    void ResourceVisitor::apply( osg::Node& node )
    {
        if( _currentMode == NONE )
        {
            /////////////
            // COLLECT //
            /////////////
            if( _mode & COLLECT )
            {
                _currentMode = COLLECT;
                collect(node);
                osg::NodeVisitor::traverse( node );
            }
            ////////////////
            // DISTRIBUTE //
            ////////////////
            if( _mode & DISTRIBUTE )
            {
                _currentMode = DISTRIBUTE;
                distribute(node);
                osg::NodeVisitor::traverse( node );
            }
            //////////////
            // EXCHANGE //
            //////////////
            if( _mode & EXCHANGE )
            {
                _currentMode = EXCHANGE;
                exchange(node);
                osg::NodeVisitor::traverse( node );
            }
            ////////////
            // FINISH //
            ////////////
            _currentMode = NONE;
            if( _mode & RESET )
            {
                reset();
            }
        }
        else
        {
            switch( _currentMode )
            {
            case COLLECT:
                collect(node);
                break;
            case DISTRIBUTE:
                distribute(node);
                break;
            case EXCHANGE:
                distribute(node);
                break;
            }

            osg::NodeVisitor::traverse( node );
        }
    }
Exemple #2
0
    // This method will do the main data processing job.
    ModuleState::MODULE_EXITCODE Proxy::body() {

        uint32_t captureCounter = 0;
        while (getModuleState() == ModuleState::RUNNING) {
            // Capture frame.
            if (m_camera != NULL) {
                core::data::image::SharedImage si = m_camera->capture();

                Container c(Container::SHARED_IMAGE, si);
                distribute(c);
                captureCounter++;
            }
            Container containerVehicleControl = getKeyValueDataStore().get(Container::VEHICLECONTROL);
                VehicleControl vc = containerVehicleControl.getData<VehicleControl>();
                cerr << "Speed: '" << vc.getSpeed() << "'" << endl;
                cerr << "Angle: '" << vc.getSteeringWheelAngle() << "'" << endl;

            // TODO: Here, you need to implement the data links to the embedded system
            // to read data from IR/US.

            // Test ***************************
            // Markus Erlach
            string in = "";
            string rec;
            char command[10];
            cout << "Enter command to send, " << endl;
            cout << "Command alternatives: w, f, s, r, n, h, v, m" << endl;
            cin >> in;
            /* w, f, s, r, n, h, v
            w = set speed to 1560, f = accelerate by 10
            s = slow down, r = reverse, n = neutral
            h = turn right, v = turn left    
            */
            strcpy(command, in.c_str());            
            write(port, command, 10);
            cout << "Proxy2 wrote: "<< command << endl;
            rec = msv::readSerial();
            decode(rec);

            Container c = Container(Container::USER_DATA_0, sensorBoardData);
            distribute(c);

            /*int IR1Data = sensorBoardData.getValueForKey_MapOfDistances(0);
            cout << "SBD IR1: " << IR1Data << endl;
            */
            //flushes the input queue, which contains data that have been received but not yet read.
            tcflush(port, TCIFLUSH); 
           
        }
        cout << "Proxy: Captured " << captureCounter << " frames." << endl;

        return ModuleState::OKAY;
    }
sql_rel *
rel_distribute(mvc *sql, sql_rel *rel) 
{
	rel = distribute(sql, rel);
	rel = replica(sql, rel, NULL);
	return rel_remote_func(sql, rel);
}
void RectangleUtils::distribute(RectanglePointers& rects,
                                ofAlignHorz horzAnchor,
                                ofAlignVert vertAnchor)
{
    ofRectangle boundingRect = getBoundingBox(rects);
    distribute(rects,boundingRect,horzAnchor,vertAnchor);
}
Exemple #5
0
//---------------------------- PUBLIC           -----------------------------//
void RNG::repool()
{
	wxLogDebug(wxT("RNG repool"));

	// See the RNG with the current time.  It's lame, but what other better way
	// is there?
	base_generator_type generator(time(NULL));

	// Since we are just creating a pool of values, we want them to be the raw
	// values reported by Mersenne.
	pooled_distribution_type distribute(0, 
		(std::numeric_limits<wxUint32>::max)());
	pooled_generator_type pool(generator, distribute);

	// Fill the pool.
	mPool.reset(new wxUint32[POOL_SIZE]);

	for(size_t i = 0; i < POOL_SIZE; ++i)
	{
		mPool[i] = pool();
	}

	// Start at the beginning again.
	mIndex = 0;
}
void ParallelizablePlanOperation::splitInput() {
  const auto& tables = input.getTables();
  if (_count > 0 && !tables.empty()) {
    auto r = distribute(tables[0]->size(), _part, _count);
    input.setTable(storage::TableRangeView::create(std::const_pointer_cast<AbstractTable>(tables[0]), r.first, r.second), 0);
  }
}
int main(){

	initialDistributor();
	distribute();

	exit(EXIT_SUCCESS);
}
Exemple #8
0
void _PlanOperation::splitInput() {
  const auto& tables = input.getTables();
  if (_count > 0 && !tables.empty()) {
    u_int64_t first, last;
    distribute(tables[0]->size(), first, last);
    input.setTable( TableRangeViewFactory::createView(std::const_pointer_cast<AbstractTable>(tables[0]), first, last), 0);
  }
}
Exemple #9
0
bool reedSolomonCoder::encode(QByteArray &ba,QString extension,eRSType rsType)
{
  int i,j;
  unsigned char dataByte;
  QByteArray temp;
  tr_buf=ba;
  fileType=rsType;
  rs_bsize=RSBSIZE;
  switch (fileType)
    {
    case RST1: rs_dsize=RSDSIZERS1; break;
    case RST2: rs_dsize=RSDSIZERS2; break;
    case RST3: rs_dsize=RSDSIZERS3; break;
    case RST4: rs_dsize=RSDSIZERS4; break;
    case RSTNONE: return FALSE;
    }
  init_rs(rs_dsize);
  got = tr_buf.size();
  chunks = (got+7) / rs_dsize ;
  if (((got+7) % rs_dsize ) > 0) chunks++ ;
  bep_size=chunks;
//  ec_buf.resize(bep_size*RSBSIZE);
  ec_buf.clear();
  bk_buf.resize(bep_size*RSBSIZE);

  dataByte = (unsigned char) ( rs_dsize - ( got % rs_dsize)) ; /* surplus in filelength */
  ec_buf.append(dataByte);
  dataByte = (unsigned char) ( chunks % 256) ;
  ec_buf.append(dataByte);
  dataByte = (unsigned char) (chunks/256) ;
  ec_buf.append(dataByte);
  ec_buf.append(extension.toLatin1().at(0));
  ec_buf.append(extension.toLatin1().at(1));
  ec_buf.append(extension.toLatin1().at(2));
  dataByte=0;
  ec_buf.append(dataByte);
  ec_buf.append(tr_buf.left(rs_dsize-7));
  ec_buf.resize(ec_buf.count()+RSBSIZE-rs_dsize);
  rse32(((byte *)ec_buf.data()),((byte *)ec_buf.data()+(rs_dsize)));
  for (i=1;i<bep_size;i++)
    {
      temp=tr_buf.mid(i*rs_dsize-7,rs_dsize);
      if(temp.count()==0) break;
      ec_buf.append(temp);
      if(temp.count()<rs_dsize)
        {
          for(j=0;j<(rs_dsize-temp.count());j++)
            {
              ec_buf.append((char)0);
            }
        }
      ec_buf.resize(ec_buf.count()+RSBSIZE-rs_dsize);
      rse32(((byte *)ec_buf.data()+i*rs_bsize),((byte *)ec_buf.data()+i*rs_bsize+rs_dsize));
    }
  ba.resize(ec_buf.count());
  distribute((byte *)ec_buf.data(),(byte *)ba.data(),bep_size,rs_bsize,ENCODE);
  return TRUE;
}
Exemple #10
0
int main()
{
	static unsigned char inbuf[1048576];
	register unsigned char *inp;
	int i, r, v, m, d;

	mktab();

	inbuf[read(0, inp = inbuf, sizeof(inbuf))] = 0;

#define READ(var) { \
	while (!isdigz[*inp]) inp++; \
	if (*inp == 0) return 0; \
	for (var = *inp++ - '0'; isdig[*inp];) \
		var = var * 10 + *inp++ - '0'; \
}

	for (adjfree = 1, i = 1; i < MAXM; i++)
		adjnext[i] = i + 1;
	adjnext[MAXM - 1] = 0;

	for (;;) {
		READ(n);
		if (n == 0) break;

		memset(vert, '\0', sizeof(vert[0]) * (n + 1));

		for (i = 0; i < n; i++) {
			READ(v);
			READ(m);
			READ(d);

			vert[v].count = m;
			while (d-- > 0) {
				READ(m);
				vert[v].adj = insert(vert[v].adj, m);
				vert[m].parent = v;
			}
		}

		for (i = 1; i <= n; i++)
			if (vert[i].count >= 2) distribute(i);

		for (r = 0, i = 1; i <= n; i++)
			if (vert[i].use >= 0)
				r += vert[i].use;
			else
				r -= vert[i].use;

		printf("%d\n", r);

		for (i = 1; i <= n; i++)
			release(vert[i].adj);
	}

	return 0;
}
void InferenceEngineBP::distribute(BPNode* xi, BPNode* xj, dVector* phi_i, dMatrix** phi_ij, dVector** m)
{
	std::list<BPNode*>::iterator it;
	sendMessage(xi,xj,phi_i,phi_ij,m);
	for(it=xj->neighbors.begin(); it!=xj->neighbors.end(); it++) {
		if( xi->equal(*it) ) continue;
		distribute(xj,*it,phi_i,phi_ij,m);
	}
}
Exemple #12
0
void PrForwardStrategy::do_timeslot()
{
  Lock lock(mx);
  is_scheduled = false;

  if (distribute(context->prng) <= threshold)
    if (!llayer->forward_one())
      return;

  schedule_timeslot();
}
Exemple #13
0
void GroupByScan::splitInput() {
  hash_table_list_t hashTables = input.getHashTables();
  if (_count > 0 && !hashTables.empty()) {
    uint64_t first, last;
    distribute(hashTables[0]->numKeys(), first, last);

    if ((_indexed_field_definition.size() + _named_field_definition.size()) == 1)
      input.setHash(std::dynamic_pointer_cast<const SingleAggregateHashTable>(hashTables[0])->view(first, last), 0);
    else
      input.setHash(std::dynamic_pointer_cast<const AggregateHashTable>(hashTables[0])->view(first, last), 0);
  }
}
Exemple #14
0
//radix sort start from here.
void radix_sort(sl_list *p_SL)
{
	int i = 0;
	array_t start;
	array_t end;
	for (i = 0; i < (*p_SL).keynum; i++)
	{
		distribute(p_SL, i, start, end);
		collect(p_SL, i, start, end);
		printf("the %d time sorting,result:\n", i + 1);
		display(*p_SL);
	}
}
void LinearRegression::flush()
{
    double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0, sum_y2 = 0, sxx, syy, sxy;
    double slope, slope_error, intercept;
    int n = 0;

	/* Initialize our post- and preprocessor functions */
	for (int i = 0; i < SPACE_DIMS; i++) {
		string s = "box" + string(1, 'X'+i);
		m_prefn.constant(s) = m_simulation->phase()->boundary()->boundingBox().size()[i];
		m_postfn.constant(s) = m_simulation->phase()->boundary()->boundingBox().size()[i];
	}

	m_prefn.FromString(m_str_prefn);
	m_postfn.FromString(m_str_postfn);

	/* Apply m_prefn and do the linear regression */
	for (list<data_sp>::iterator i = m_data.begin(); i != m_data.end(); i++) {
        double x, y;

        x = (*i)->doubleByIndex(m_idx_x);
        y = m_prefn.value((*i)->doubleByIndex(m_idx_y));
        
        sum_x += x;
        sum_y += y;
        sum_xy += x*y;
        sum_x2 += x*x;
        sum_y2 += y*y;
        n++;
    }

    if(n < 3) 
       throw gError
         ("LinearRegression::flush", "I need at least 3 values, but have only " 
           + ObjToString(n));
    sxy = sum_xy - sum_x*sum_y/n;
    sxx = sum_x2 - sum_x*sum_x/n;
    syy = sum_y2 - sum_y*sum_y/n;

    slope = sxy/sxx;
    slope_error = sqrt((syy - (slope*slope*sxx)) / (n - 2));
    intercept = sum_y/n - slope*sum_x/n;

    data_sp data = m_output.newData();
    data->doubleByIndex(IDX_SLOPE) = slope;
//    data->doubleByIndex(IDX_SLOPE_ERROR) = slope_error;
    data->doubleByIndex(IDX_INTERCEPT) = intercept;
//    data->doubleByIndex(IDX_INTERCEPT_ERROR) = 0;
    data->doubleByIndex(IDX_VALUE) = m_postfn.value(slope);
    distribute(data);
}
Exemple #16
0
const wxUint32 RNG::unpooled(const wxUint32 n) const
{
	wxUint32 val = 0;

	if(1 < n)
	{
		unpooled_distribution_type distribute(0, n - 1);
		unpooled_generator_type gen(sUnpooledGenerator, distribute);

		val = gen();
	}

	wxLogDebug(wxT("RNG unpooled returns %u"), val);

	return val;
}
Exemple #17
0
int zmq::dist_t::send (zmq_msg_t *msg_, int flags_)
{
    //  Is this end of a multipart message?
    bool msg_more = msg_->flags & ZMQ_MSG_MORE;

    //  Push the message to active pipes.
    distribute (msg_, flags_);

    //  If multipart message is fully sent, activate all the eligible pipes.
    if (!msg_more)
        active = eligible;

    more = msg_more;

    return 0;
}
Exemple #18
0
void Client::streamReadyRead()
{
	// HACK HACK HACK
	QGuardedPtr<ClientStream> pstream = d->stream;

	while(pstream && d->stream->stanzaAvailable()) {
		Stanza s = d->stream->read();

		QString out = s.toString();
		debug(QString("Client: incoming: [\n%1]\n").arg(out));
		xmlIncoming(out);

		QDomElement x = oldStyleNS(s.element());
		distribute(x);
	}
}
Exemple #19
0
int zmq::dist_t::send_to_matching (msg_t *msg_)
{
    //  Is this end of a multipart message?
    bool msg_more = msg_->flags () & msg_t::more ? true : false;

    //  Push the message to matching pipes.
    distribute (msg_);

    //  If multipart message is fully sent, activate all the eligible pipes.
    if (!msg_more)
        active = eligible;

    more = msg_more;

    return 0;
}
Exemple #20
0
int main(int argv, char** argc)
{
    File* hw;
    Marker* markers;
    Marker* it;
    const char* markersPath;
    const char* hwPath;
    FILE* outFile;

    if (argv != 3)
    {
        printf("Usage: %s markers homeworks\n", argc[0]);
        printf("markers: Markers file path.\n");
        printf("files: HW files path.\n");
        exit(EXIT_FAILURE);
    }

    markersPath = argc[1];
    hwPath = argc[2];

    markers = readMarkers(markersPath);

    srand(time(NULL));
    rand();
    rand();

    hw = makeFileList(hwPath);
    markers = distribute(hw, markers);
    markers = sortMarkers(markers, numMarkers(markers));
    for (it = markers; it; it = it->next)
    {
        it->files = sortFiles(it->files, numFiles(it->files));
    }

    printMarkers(markers);

    for (it = markers; it; it = it->next)
    {
        free((void*)it->name);
    }

    freeMarkers(markers);
    freeFiles(hw);

    return 0;
}
Exemple #21
0
//#include"split_file_mode_a.c"
int main(int argc, char *argv[])
{
/*    if(argv[3][0]=='a')
        distribute(argv[1], atoi(argv[2]), 0, split_file_mode_a);
    else if(argv[3][0]=='b')
        distribute(argv[1], atoi(argv[2]), 0, split_file_mode_b);
    return 0;
*/
    //distribute("~/news", 4, 80, split_file_mode_c);
    distribute(
        argv[1],
        argv[2],
        atoi(argv[3]),
        atoi(argv[4]),
        split_file_mode_c
    );
    return 0;   
}
//排序函数 
void sort(int numbers[]){
	int bucket[10][SIZE] = {0}; // 定义10个桶
	//每个桶第0号记录桶内数字个数 
	int maxDigit; // 最长几位 
	int i = 0;
	//获得最多位数,确定排序次数 
	maxDigit = getMaxDigit(numbers); 
	//printf("maxDigit = %d\n", maxDigit);

	for(i = 0; i < maxDigit; i++){
		//进行第i位排序
		distribute(i, bucket, numbers);
		//按序归位 
		collect(bucket, numbers);
		//debug(numbers);
	}

}
Exemple #23
0
void RandomBattery::runAll(int trials){
    result_t rslt;
    
    std::cout << "distribution over N buckets:" << std::endl;
    rslt = distribute(trials);
    std::cout << "stdev: " << rslt.stdev << " mean: " << rslt.mean << " spread: " << (rslt.stdev / rslt.mean) << std::endl;

    std::cout << "distribution of bits:" << std::endl;
    rslt = bitHistogram(trials);
    std::cout << "stdev: " << rslt.stdev << " mean: " << rslt.mean << " spread: " << (rslt.stdev / rslt.mean) << std::endl;

    std::cout << "distribution of bytes:" << std::endl;
    rslt = byteHistogram(trials);
    std::cout << "stdev: " << rslt.stdev << " mean: " << rslt.mean << " spread: " << (rslt.stdev / rslt.mean) << std::endl;
    
    double t = speed(trials);
    std::cout << "time: " << t << " (" << (trials/t) << " words/sec)" << std::endl;
}
Exemple #24
0
int main(int argc, char *argv[])
{
    /* Declarations */
    int c, option_index = 0;
    struct option long_options[] =
    {
        {"max-concurrent-transfers", required_argument, 0, 'm'},
        {"help", no_argument, 0, 'h'},
        {"version", no_argument, 0, 'v'},
        {0, 0, 0, 0}
    };
    
    unsigned int max_concurrent_transfers = 2;
    
    /* Parse command-line options */
    while((c = getopt_long(argc, argv, "m:hv", long_options, &option_index)) != -1)
    {
        switch(c)
        {
            case 'm':
                max_concurrent_transfers = atoi(optarg);
                break;
            case 'h':
            case '?':
                print_usage(argv[0]);
                return 0;
            case 'v':
                print_version(argv[0]);
                return 0;
        }
    }

    /* Validate options */
    
    if(optind >= argc)
    {
        fprintf(stderr, "ERROR: No manifest specified!\n");
        return 1;
    }
    else
        return distribute(argv[optind], max_concurrent_transfers); /* Execute distribute operation */
}
Exemple #25
0
void Guest::ReqProc(HttpReqHeader* req) {
    LOGD(DHTTP, "guest ReqProc %s: Status:%u\n", getsrc(nullptr), Status_flags);
    assert((Status_flags & GUEST_CONNECT_F) == 0 && (Status_flags & GUEST_SEND_F) == 0);
    assert((Status_flags == GUEST_IDELE_F) || (Status_flags & GUEST_REQ_COMPLETED));
    req->index = (void *)1;
    auto res_ptr = distribute(req, responser_ptr);
    if(!res_ptr.expired()){
        if(req->ismethod("CONNECT")){
            Status_flags |= GUEST_CONNECT_F;
        }else if(req->ismethod("SEND")){
            Status_flags |= GUEST_SEND_F;
        }
        Status_flags |= GUEST_PROCESSING_F;
        Status_flags &= ~GUEST_RES_COMPLETED;
        void* res_index = res_ptr.lock()->request(req);
        if(!responser_ptr.expired() && (res_ptr.lock() != responser_ptr.lock() || res_index != responser_index)){
            responser_ptr.lock()->finish(PEER_LOST_ERR, responser_index);
        }
        responser_ptr = res_ptr;
        responser_index = res_index;
    }else{
        delete req;
    }
}
Exemple #26
0
Pkmn::Pkmn(std::string name,unsigned int level, unsigned int mode){
    poke = Master::getInstance()->dexter.getPoke(name);
    if(level > 100){
        std::cout<<"Level over 100. Level = 100"<<std::endl;
        level = 100;
    }
    atkList.clear();
    c_lvl = level;
    added.resize(6,0);
    c_stages.resize(6,0);
    c_stats.resize(6,0);
    c_dmg = 0;
    c_exp = Master::getInstance()->levelChart[level];
    c_add = level-1;

    setNature();

    levelingMode = mode;

    distribute(c_add);
    c_add = 0;

   // poke.print();
}
static rc_t bogotune(void)
{
    bool skip;
    result_t *best;

    int beg, end;
    uint cnt, scan;
    rc_t status = RC_OK;

    beg = time(NULL);

    ham_cutoff = 0.0;
    spam_cutoff = 0.1;

    /* Note: memory usage highest while reading messages */
    /* usage decreases as distribute() converts to count format */

    /* read all messages, merge training sets, look up scoring sets */
    ns_cnt = filelist_read(REG_GOOD, ham_files);
    sp_cnt = filelist_read(REG_SPAM, spam_files);
    cnt = ns_cnt + sp_cnt;

    end = time(NULL);
    if (verbose >= TIME) {
	show_elapsed_time(beg, end, ns_cnt + sp_cnt, (double)cnt/(end-beg), "messages", "msg/sec");
    }

    distribute(REG_GOOD, ns_msglists);
    distribute(REG_SPAM, sp_msglists);

    create_countlists(ns_msglists);
    create_countlists(sp_msglists);

    if (verbose >= TIME && time(NULL) - end > 2) {
	end = time(NULL);
	show_elapsed_time(beg, end, ns_cnt + sp_cnt, (double)cnt/(end-beg), "messages", "msg/sec");
    }

    if (verbose > PARMS+1) {
	tunelist_print(ns_and_sp);
	tunelist_print(ns_msglists);
	tunelist_print(sp_msglists);
    }

    ns_cnt = count_messages(ns_msglists);
    sp_cnt = count_messages(sp_msglists);

    if (ds_flag == DS_DSK && !check_msg_counts())
	exit(exit_zero ? EX_OK : EX_ERROR);

    fflush(stdout);

    check_percent = CHECK_PCT;	/* for checking low scoring spam
				** and high scoring non-spam */

    ns_scores = xcalloc(ns_cnt, sizeof(double));
    sp_scores = xcalloc(sp_cnt, sizeof(double));

    robs = DEFAULT_ROBS;
    robx = DEFAULT_ROBX;
    min_dev = DEFAULT_MIN_DEV;

    if (check_for_high_ns_scores() | check_for_low_sp_scores())
	scoring_error();

    /*
    ** 5.  Calculate x and cache size
    ** Calculate x with bogoutil's -r option (a new addition).
    ** Bound the calculated value within [0.4, 0.6] and set the range to be
    ** investigated to [x-0.1, x+0.1].
    */

    robx = get_robx();
    if (ds_flag == DS_DSK) {
	db_cachesize = calc_db_cachesize();
	printf("Recommended db cache size is %u MB\n", db_cachesize);
    }

    /*
    ** 6.  Calculate fp target
    ** The fp target will be derived thus: score non-spams with s and md as
    ** shipped, and determine the count that will result from a spam cutoff
    ** of 0.95; if that is < 0.25%, try 0.9375 etc.
    */

    min_dev = 0.02;

    /* set target and spam_cutoff */

    if (coerced_target == 0)
	set_thresh(ns_cnt, ns_scores);
    else {
	/* if coerced target ... */
	target = coerced_target;
	spam_cutoff = ns_scores[target-1];
    }

    skip = ROUND(spam_cutoff,100000) < SCAN_CUTOFF;
    printf("False-positive target is %u (cutoff %8.6f)\n", target, spam_cutoff);

#ifdef	TEST
    if (test) {
	printf("m: %8.6f, s: %8.6f, x: %0.16f\n", min_dev, robs, robx);
	if (verbose < PARMS)
	    print_ns_scores(target-2, target+2, 0);
    }
#endif

    if (!esf_flag && (sp_esf < 1.0 || ns_esf < 1.0))
	fprintf(stderr, "Warning:  Using ESF values (sp=%8.6f, ns=%8.6f) from config file.\n", sp_esf, ns_esf);

    /* No longer needed */
    wordhash_free(train);
    train = NULL;

    for (scan=0; scan <= 1 && !skip; scan ++) {
	uint r_count;
	uint rsi, rxi, mdi, spi, nsi;
	result_t *results, *r, *sorted;

	printf("Performing %s scan:\n", scan==0 ? "coarse" : "fine");

	switch (scan) {
	case 0:		/* COARSE */
	    /*
	    ** 7.  Coarsely scan s, md and x
	    ** The coarse s scan will range from 1 to 0.01 in half decades, and the
	    ** coarse md scan will range from 0.05 to 0.45 in steps of 0.05.  The
	    ** coarse x scan will use steps of 0.05. The trough must be surrounded on
	    ** six sides by values below the 33% quantile (unless bounded on one or
	    ** more sides).
	    */
	    init_coarse(robx);
	    break;
	case 1:		/* FINE */
	    /*
	    ** 8.  Finely scan the peak region
	    ** The fine s scan will range over the estimated s +/- half a decade in
	    ** steps of a quarter decade, and the fine md scan will range over the
	    ** estimated md +/- 0.075 in steps of 0.015.  The fine x scan will range
	    ** over the estimated x +/- 0.04 in steps of 0.02.  Scans of s and md
	    ** are bounded by the limits of the coarse scan.  Again, the trough must
	    ** be surrounded on six sides by values below the 33% quantile.  If no
	    ** such trough exists, a warning is given.
	    */
	    init_fine(robs, min_dev, robx, spex, nsex);
	    break;
	}

	r_count = rsval->cnt * mdval->cnt * rxval->cnt * spexp->cnt * nsexp->cnt;
	results = (result_t *) xcalloc(r_count, sizeof(result_t));

	print_all_parms(r_count);

	if (verbose >= SUMMARY) {
	    if (verbose >= SUMMARY+1)
		printf("%3s ", "cnt");
	    if (verbose >= SUMMARY+2)
		printf(" %s %s %s      ", "s", "m", "x");
	    printf(" %4s %5s   %4s %8s %8s %7s %3s %3s\n",
		   "rs", "md", "rx", "spesf", "nsesf", "cutoff", "fp", "fn");
	}

	cnt = 0;
	beg = time(NULL);
	for (rsi = 0; rsi < rsval->cnt; rsi++) {
	  robs = rsval->data[rsi];
	  for (mdi = 0; mdi < mdval->cnt; mdi++) {
	    min_dev = mdval->data[mdi];
	    for (rxi = 0; rxi < rxval->cnt; rxi++) {
	      robx = rxval->data[rxi];
	      for (spi = 0; spi < spexp->cnt; spi++) {
		spex = spexp->data[spi];
		sp_esf = ESF_SEL(sp_esf, pow(0.75, spex));
		for (nsi = 0; nsi < nsexp->cnt; nsi++) {
		    uint fp, fn;
		    nsex = nsexp->data[nsi];
		    ns_esf = ESF_SEL(ns_esf, pow(0.75, nsex));

		    /* save parms */
		    r = &results[cnt++];
		    r->idx = cnt;
		    r->rsi = rsi; r->rs = robs;
		    r->rxi = rxi; r->rx = robx;
		    r->mdi = mdi; r->md = min_dev;
		    r->spi = spi; r->sp_exp = spex;
		    r->nsi = nsi; r->ns_exp = nsex;

		    if (verbose >= SUMMARY) {
			if (verbose >= SUMMARY+1)
			    printf("%3u ", cnt);
			if (verbose >= SUMMARY+2)
			    printf(" %u %u %u %u %u  ",
				rsi, mdi, rxi, spi, nsi);
			printf("%6.4f %5.3f %5.3f %8.6f %8.6f",
			    robs, min_dev, robx, sp_esf, ns_esf);
			fflush(stdout);
		    }

		    spam_cutoff = 0.01;
		    score_ns(ns_scores);	/* scores in descending order */

		    /* Determine spam_cutoff and false_pos */
		    for (fp = target; fp < ns_cnt; fp += 1) {
			spam_cutoff = ns_scores[fp-1];
			if (spam_cutoff < 0.999999)
			    break;
			if (coerced_target != 0)
			    break;
		    }
		    if (ns_cnt < fp)
			fprintf(stderr,
				"Too few false positives to determine a valid cutoff\n");

		    score_sp(sp_scores);	/* scores in ascending order */
		    fn = get_fn_count(sp_cnt, sp_scores);

		    /* save results */
		    r->co = spam_cutoff;
		    r->fp = fp;
		    r->fn = fn;

		    if (verbose < SUMMARY)
			progress(cnt, r_count);
		    else {
			printf(" %8.6f %2u %3u\n", spam_cutoff, fp, fn);
			fflush(stdout);
		    }

#ifdef	TEST
		    if (test && spam_cutoff < 0.501) {
			printf("co: %0.16f\n", spam_cutoff);
			print_ns_scores(0, fp, 2);
			print_sp_scores(fn-10, fn, 10);
		    }
#endif
		    if (fMakeCheck && cnt >= cMakeCheck)
			break;
		}
		if (fMakeCheck && cnt >= cMakeCheck)
		    break;
	      }
	      if (fMakeCheck && cnt >= cMakeCheck)
		  break;
	    }
	    if (fMakeCheck && cnt >= cMakeCheck)
		break;
	  }
	  fflush(stdout);
	  if (fMakeCheck && cnt >= cMakeCheck)
	      break;
	}

	if (verbose >= TIME) {
	    end = time(NULL);
	    show_elapsed_time(beg, end, cnt, (double)(end-beg)/cnt, "iterations", "secs");
	}

	printf("\n");

	/* Scan complete, now find minima */

	sorted = results_sort(r_count, results);
	top_ten(sorted, r_count);

	best = count_outliers(r_count, sorted, results);
	robs = rsval->data[best->rsi];
	robx = rxval->data[best->rxi];
	min_dev = mdval->data[best->mdi];

	spex = spexp->data[best->spi]; sp_esf = ESF_SEL(sp_esf, pow(0.75, spex));
	nsex = nsexp->data[best->nsi]; ns_esf = ESF_SEL(ns_esf, pow(0.75, nsex));

	printf(
    "Minimum found at s %6.4f, md %5.3f, x %5.3f, spesf %8.6f, nsesf %8.6f\n",
    		robs, min_dev, robx, sp_esf, ns_esf);
	printf("        fp %u (%6.4f%%), fn %u (%6.4f%%)\n",
		best->fp, best->fp*100.0/ns_cnt,
		best->fn, best->fn*100.0/sp_cnt);
	printf("\n");

	data_free(rsval);
	data_free(rxval);
	data_free(mdval);
	data_free(spexp);
	data_free(nsexp);

	xfree(results);
	xfree(sorted);
    }

    /*
    ** 9.  Suggest possible spam and non-spam cutoff values
    ** With the final x, md and s values, score the spams and non-spams and
    ** sort the non-spam scores decreasing and the spam scores increasing;
    ** then, traverse the non-spam list until the 0.2% point; report cutoffs
    ** that give 0.05%, 0.1% and 0.2% fp.
    */

    final_recommendations(skip);

    return status;
}
Exemple #28
0
int main(int argc, char *argv[]){
    int i, j, k, sz, sz01, sz23, sz_fin, ri, name_len;
    elem_t *e;
    result_t sol[16];
    u64 s, name_hash;
    char serial[32+1];

    if(argc<2){
        printf("Keygen for keygenme3 by Dcoder\nUsage: %s <name>\n", 
                argv[0]);
        return 1;
    }

    name_len = strlen(argv[1]);
    hash(KEY_NAME, argv[1], name_len, &name_hash);

    memset(lists, 0, (LISTS+3)*PER_LIST*sizeof(elem_t*));
    memset(buckets, 0, (LISTS+3)*PER_LIST*sizeof(node_t*));
    
    fill_seeds(seeds);

    srand(0);
    fill_lists(lists);
    sub(lists[3], name_hash); //x1+..+(xn-c)=0 -> x1+..+xn=c

    //l0,-l1 -- l2,-l3
    inv(lists[1]);
    inv(lists[3]);

    for(i=0;i<LISTS;i++){
        distribute(lists[i], PER_LIST, buckets[i]);
    }

    sz01 = merge(buckets[0], buckets[1], lists[4]);
    sz23 = merge(buckets[2], buckets[3], lists[5]);
    //l01,-l23
    inv(lists[5]);
    shr(lists[4], sz01, L);
    shr(lists[5], sz23, L);
    distribute(lists[4], sz01, buckets[4]);
    distribute(lists[5], sz23, buckets[5]);
    sz_fin = merge(buckets[4], buckets[5], lists[6]);
    for(i=0;i<sz_fin;i++){
        e = lists[6][i];
        // ">>" is arithmetic shift for u64, so we can check for 0
        // instead of a certain power of 2
        if(e->x==0){
            //printf("i=%d, x=%llx\n", i, e->x);
            sz = walk(e, sol);
            assert(sz == 16);
            s = 0L;
            for(j=0;j<sz;j++){
                s += sol[j].seed;
                ri = sol[j].ri;
                k = sol[j].k;
                assert(ri == j);
                //printf("j=%d, ri=%d, k=%02x, s=%llx\n", j, ri, k, s);
                sprintf(&serial[j*2], "%02x", k);
            }
            assert(s == name_hash);
            serial[32]=0;
            printf("%s\n", serial);
        }
    }
    
    return 0;
}
void InferenceEngineBP::computeBeliefs(Beliefs &beliefs, FeatureGenerator *fGen, 
	DataSequence *X, Model *m, int bComputePartition, int seqLabel, bool bUseStatePerNodes)
{  
	// Variable definition  
	int xi, xj, nbNodes, seqLength;
	std::map<int,BPNode*> nodes; // tree graph
	std::map<int,BPNode*>::iterator itm;
	std::list<BPNode*>::iterator itl;
	BPNode* root;
	iMatrix adjMat;
	iVector nbStates;
	dVector*  phi_i  = 0; // singleton potentials
	dMatrix** phi_ij = 0; // pairwise potentials
	dVector** msg    = 0; // messages

	if( m->isMultiViewMode() )
		m->getAdjacencyMatrixMV(adjMat, X);
	else {
		uMatrix uAdjMat;
		m->getAdjacencyMatrix(uAdjMat, X);
		adjMat.resize(uAdjMat.getWidth(),uAdjMat.getHeight());
		for(xi=0; xi<uAdjMat.getHeight(); xi++)
			for(xj=0; xj<uAdjMat.getWidth(); xj++)
				adjMat(xi,xj) = uAdjMat(xi,xj);
	}

	nbNodes = adjMat.getHeight(); 
	seqLength = X->length();

	// Create a vector that contains nbStates
	nbStates.create(nbNodes);
	for(xi=0; xi<nbNodes; xi++)
		nbStates[xi] = (m->isMultiViewMode()) 
			? m->getNumberOfStatesMV(xi/seqLength) : m->getNumberOfStates();

	// Create BPGraph from adjMat
	for(xi=0; xi<nbNodes; xi++) {		
		BPNode* v = new BPNode(xi, nbStates[xi]);
		nodes.insert( std::pair<int,BPNode*>(xi,v) );
	}
	for(xi=0; xi<nbNodes; xi++) {
		for(xj=xi+1; xj<nbNodes; xj++) {
			if( !adjMat(xi,xj) ) continue;
			nodes[xi]->addNeighbor(nodes[xj]);
			nodes[xj]->addNeighbor(nodes[xi]);
		}
	}

	// Initialize  
	initMessages(msg, X, m, adjMat, nbStates);
	initBeliefs(beliefs, X, m, adjMat, nbStates);
	initPotentials(phi_i, phi_ij, fGen, X, m, adjMat, nbStates, seqLabel);
	
	// Message update
	root = nodes[0]; // any node can be the root node
	{
		for(itl=root->neighbors.begin(); itl!=root->neighbors.end(); itl++)
			collect(root, *itl, phi_i, phi_ij, msg);
		for(itl=root->neighbors.begin(); itl!=root->neighbors.end(); itl++)
			distribute(root, *itl, phi_i, phi_ij, msg);
	}
	updateBeliefs(beliefs, phi_i, phi_ij, msg, X, m, adjMat);

	// Clean up
	for(xi=0; xi<nbNodes; xi++) { 		
		delete[] msg[xi]; msg[xi] = 0; 
		delete[] phi_ij[xi]; phi_ij[xi] = 0;
	}
	delete[] msg; msg=0;
	delete[] phi_i; phi_i = 0;
	delete[] phi_ij;  phi_ij  = 0; 

	for(itm=nodes.begin(); itm!=nodes.end(); itm++) 
		delete (*itm).second; 
	nodes.clear();   
}
void FFTDataDistributor::process() {
	while (!input->empty()) {
		if (!isAnyOutputEmpty()) {
			return;
		}
		DemodulatorThreadIQData *inp;
		input->pop(inp);

		if (inp) {
			if (inputBuffer.sampleRate != inp->sampleRate || inputBuffer.frequency != inp->frequency) {
                
                bufferMax = inp->sampleRate / 4;
//                std::cout << "Buffer Max: " << bufferMax << std::endl;
                bufferOffset = 0;
                
				inputBuffer.sampleRate = inp->sampleRate;
				inputBuffer.frequency = inp->frequency;
                inputBuffer.data.resize(bufferMax);
			}
            if ((bufferOffset + bufferedItems + inp->data.size()) > bufferMax) {
                memmove(&inputBuffer.data[0], &inputBuffer.data[bufferOffset], bufferedItems*sizeof(liquid_float_complex));
                bufferOffset = 0;
            } else {
                memcpy(&inputBuffer.data[bufferOffset+bufferedItems],&inp->data[0],inp->data.size()*sizeof(liquid_float_complex));
                bufferedItems += inp->data.size();
            }
			inp->decRefCount();
		} else {
			continue;
		}

		// number of seconds contained in input
		double inputTime = (double)bufferedItems / (double)inputBuffer.sampleRate;
		// number of lines in input
		double inputLines = (double)bufferedItems / (double)fftSize;

		// ratio required to achieve the desired rate
		double lineRateStep = ((double)linesPerSecond * inputTime)/(double)inputLines;

		if (bufferedItems >= fftSize) {
			int numProcessed = 0;

			if (lineRateAccum + (lineRateStep * ((double)bufferedItems/(double)fftSize)) < 1.0) {
				// move along, nothing to see here..
				lineRateAccum += (lineRateStep * ((double)bufferedItems/(double)fftSize));
				numProcessed = bufferedItems;
			} else {
				for (int i = 0, iMax = bufferedItems; i < iMax; i += fftSize) {
					if ((i + fftSize) > iMax) {
						break;
					}
					lineRateAccum += lineRateStep;

					if (lineRateAccum >= 1.0) {
						DemodulatorThreadIQData *outp = outputBuffers.getBuffer();
						outp->frequency = inputBuffer.frequency;
						outp->sampleRate = inputBuffer.sampleRate;
						outp->data.assign(inputBuffer.data.begin()+bufferOffset+i,inputBuffer.data.begin()+bufferOffset+i+fftSize);
						distribute(outp);

						while (lineRateAccum >= 1.0) {
							lineRateAccum -= 1.0;
						}
					}

					numProcessed += fftSize;
				}
			}
			if (numProcessed) {
                bufferedItems -= numProcessed;
                bufferOffset += numProcessed;
            }
            if (bufferedItems <= 0) {
                bufferedItems = 0;
                bufferOffset = 0;
            }
		}
	}
}