コード例 #1
0
void DUChainControlFlowJob::start()
{
    emit showProgress(this, 0, 0, 0);
    emit showMessage(this, objectName());

    m_internalJob = new DUChainControlFlowInternalJob(m_duchainControlFlow, m_plugin);
    m_internalJob->setControlFlowJobType(m_controlFlowJobType);
    connect(m_internalJob, SIGNAL(done(ThreadWeaver::Job*)), SLOT(done(ThreadWeaver::Job*)));
    ThreadWeaver::Weaver::instance()->enqueue(m_internalJob);
}
コード例 #2
0
ファイル: replaygain.cpp プロジェクト: Civil/cantata
void ReplayGain::scannerProgress(int p)
{
    TrackScanner *s=qobject_cast<TrackScanner *>(sender());
    if (!s) {
        return;
    }

    tracks[s->index()].progress=p;
    showProgress();
}
コード例 #3
0
ファイル: QueryWidget.cpp プロジェクト: Linutux/robomongo
    void QueryWidget::execute()
    {
        QString query = _scriptWidget->selectedText();

        if (query.isEmpty())
            query = _scriptWidget->text();

        showProgress();
        _shell->open(QtUtils::toStdString(query));
    }
コード例 #4
0
ファイル: pm_brute2.cpp プロジェクト: tantantzp/datastructure
/******************************************************************************************
 * Text     :  0   1   2   .   .   .   i   i+1 .   .   .   i+j .   .   n-1
 *             ------------------------|-------------------|------------
 * Pattern  :                          0   1   .   .   .   j   .   .
 *                                     |-------------------|
 ******************************************************************************************/
int match(char* P, char* T) { //串匹配算法(Brute-force-2)
   size_t n = strlen(T), i = 0; //主串长度、与模式串首字符的对齐位置
   size_t m = strlen(P), j; //模式串长度、当前接受比对字符的位置
   for (i = 0; i < n - m + 1; i++) { //主串从第i个字符起,与
      for (j = 0; j < m; j++) //模式串中对应的字符逐个比对
      /*DSA*/{ showProgress(T, P, i, j); getchar();
         if (T[i + j] != P[j]) break; //若失配,模式串整体右移一个字符,再做一轮比对
      /*DSA*/}
      if (j >= m) break; //找到匹配子串
   }
   return i; //如何通过返回值,判断匹配结果?
}
コード例 #5
0
/******************************************************************************************
 * Text     :  0   1   2   .   .   .   i-j .   .   .   .   i   .   .   n-1
 *             ------------------------|-------------------|------------
 * Pattern  :                          0   .   .   .   .   j   .   .
 *                                     |-------------------|
 ******************************************************************************************/
int match ( char* P, char* T ) { //串匹配算法(Brute-force-1)
   size_t n = strlen ( T ), i = 0; //文本串长度、当前接受比对字符的位置
   size_t m = strlen ( P ), j = 0; //模式串长度、当前接受比对字符的位置
   while ( j < m && i < n ) //自左向右逐个比对字符
      /*DSA*/{
      /*DSA*/showProgress ( T, P, i - j, j );   getchar();
      if ( T[i] == P[j] ) //若匹配
         { i ++;  j ++; } //则转到下一对字符
      else //否则
         { i -= j - 1; j = 0; } //文本串回退、模式串复位
      /*DSA*/}
   return i - j; //如何通过返回值,判断匹配结果?
}
コード例 #6
0
void ConfigurablePage::_configureTimeout()
{
	startTime = time(NULL)-1; /*no FPE*/
	isLoading = true;
	if(globalTimeout) {
		QTimer::singleShot(globalTimeout, this, SLOT(_triggerTimeout()));
	}
	progress = 0;
	if(isatty(STDERR_FILENO)) {
		connect(&progressUpdateTimer, SIGNAL(timeout()), SLOT(showProgress()));
		progressUpdateTimer.start(500);
	}
}
コード例 #7
0
ファイル: main.C プロジェクト: mmm/grover
int main( int argc, char* argv[] ) {

    // some setup
    const int numSteps = 10000; 
    //double stepSize = .5 * 1/(double)numSteps;
    double stepSize = 0.000001;

    int opt;
    while ( (opt = getopt( argc, argv, "n:q:" )) != -1 ) {
        switch ( opt ) {
        case 'n':
            //const_cast<int>(numSteps) = optarg;
            cout << "numSteps = " << optarg << endl;
            break;
        case 'q':
            numQubits = atoi(optarg);
            cout << "numQubits = " << optarg << endl;
            break;
        default:
            usage();
        }
    }

    const int numEquations = getNumOfEqns( numQubits );

    // initial conditions
    double x = 0.0;
    valarray<double> y( 0.0, numEquations );
    init( &x, &y );

    for ( int i = 0; i < numSteps; i++ ){

        // take a step
        y += stepRk4( x, y, stepSize );
        x += stepSize;

#ifdef TELL_ME
//        printVals( x, y );
        showProgress(i,numSteps);

//        char line[80];
//        cin.getline(line,80);
        if ( i == 0 || i == numSteps - 1 ) {
            printDensityMatrix( x, y );
        }
#endif //TELL_ME

    }

}
コード例 #8
0
/*
 * runGame
 * 
 * sequence through each player taking turns, until there is a winner or 
 * players get "bored" (reach max turns)
 *
 */
void GameRunner::runGame()
{
	int currentPlayerNum = selectStartingPlayer();				// starting player

	int turnCount = 0;
	while (!game.hasWinner() && (++turnCount < maxTurns))
	{
		turn(currentPlayerNum);									// sequence through next player's turn

		showProgress();
	
		int numPlayers = game.getPlayers().size();				// current num players in game
		currentPlayerNum = bounded(++currentPlayerNum, numPlayers); // advance to next player
	}	
}
コード例 #9
0
ファイル: pm_kmp.cpp プロジェクト: HillBamboo/MOOCs
int match ( char* P, char* T ) {  //KMP算法
   int* next = buildNext ( P ); //构造next表
   int n = ( int ) strlen ( T ), i = 0; //文本串指针
   int m = ( int ) strlen ( P ), j = 0; //模式串指针
   while ( j < m  && i < n ) //自左向右逐个比对字符
      /*DSA*/{
      /*DSA*/showProgress ( T, P, i - j, j );
      /*DSA*/printNext ( next, i - j, strlen ( P ) );
      /*DSA*/getchar(); printf ( "\n" );
      if ( 0 > j || T[i] == P[j] ) //若匹配,或P已移出最左侧(两个判断的次序不可交换)
         { i ++;  j ++; } //则转到下一字符
      else //否则
         j = next[j]; //模式串右移(注意:文本串不用回退)
      /*DSA*/}
   delete [] next; //释放next表
   return i - j;
}
コード例 #10
0
ファイル: fluushoption.cpp プロジェクト: Shiroy/fluush
FluushOption::FluushOption(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::FluushOption)
{
    ui->setupUi(this);

    QMenu *contextMenu = new QMenu(this);
    QAction *takeFullScreen, *showMe, *quit;

    takeFullScreen = new QAction(tr("Take the full screen"), this);
    takeFullScreen->setCheckable(true);
    takeFullScreen->setChecked(ui->full_screen->isChecked());
    connect(takeFullScreen, SIGNAL(toggled(bool)), ui->full_screen, SLOT(setChecked(bool)));
    connect(ui->full_screen, SIGNAL(toggled(bool)), takeFullScreen, SLOT(setChecked(bool)));

    showMe = new QAction(tr("Show options"), this);
    connect(showMe, SIGNAL(triggered()), this, SLOT(show()));

    quit = new QAction(tr("Quit"), this);
    connect(quit, SIGNAL(triggered()), this, SLOT(quit()));

    contextMenu->addAction(takeFullScreen);
    contextMenu->addSeparator();
    contextMenu->addAction(showMe);
    contextMenu->addAction(quit);

    trayIcon = new QSystemTrayIcon(QIcon(":/icons/fluush-icon"), this);
    trayIcon->setContextMenu(contextMenu);
    trayIcon->show();
    trayIcon->setToolTip(tr("Fluush - Right click to configure"));
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActivated(QSystemTrayIcon::ActivationReason)));

    net = new FluushNetwork(this);

    dia = new QProgressDialog(tr("Uploading to puush"), tr("Cancel"), 0, 100, this);
    dia->setVisible(false);
    dia->setAutoReset(false);
    dia->setAutoClose(false);

    connect(net, SIGNAL(showProgress()), dia, SLOT(show()));
    connect(net, SIGNAL(hideProgress()), dia, SLOT(hide()));
    connect(net, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(uploadProgress(qint64,qint64)));

    loadSettings();
}
コード例 #11
0
ファイル: main.C プロジェクト: mmm/grover
int main() {

    // initial conditions
    double x = 0.0;
    valarray<double> y( 0.0, NUM_OF_EQNS );
    init( &x, &y );

//    cout << y.size()
//         << " "
//         << y[0]
//         << " "
//         << y[1]
//         << endl;

    // some setup
    const int numSteps = 1000000;
    //double stepSize = 1/(double)numSteps;
    double stepSize = 0.001;

    for ( int i = 0; i < numSteps; i++ ) {

        // take a step
        //stepEuler( &x, &y, stepSize );
        //stepAdaptRk4( &x, &y, &stepSize );
        //stepLsode( &x, &y, &stepSize );

        y += stepRk4( x, y, stepSize );
        x += stepSize;

#ifdef TELL_ME
        // we can solve this one, so...
        if ( 0 == i%(numSteps/10) ) {
            compareWithSoln( x, y );
        }
//        printVals( x, y );

//        char line[80];
//        cin.getline(line,80);

        showProgress( i, numSteps );
#endif //TELL_ME

    }

}
コード例 #12
0
ファイル: QueryWidget.cpp プロジェクト: strogo/robomongo
    QueryWidget::QueryWidget(MongoShell *shell, WorkAreaTabWidget *tabWidget, ViewMode viewMode, QWidget *parent) :
        QWidget(parent),
        _shell(shell),
        _tabWidget(tabWidget),
        _app(AppRegistry::instance().app()),
        _bus(AppRegistry::instance().bus()),
        _viewer(NULL),
        _viewMode(viewMode),
        isTextChanged(false)
    {
        setObjectName("queryWidget");
        _bus->subscribe(this, DocumentListLoadedEvent::Type, shell);
        _bus->subscribe(this, ScriptExecutedEvent::Type, shell);
        _bus->subscribe(this, AutocompleteResponse::Type, shell);
        qDebug() << "Subscribed to ScriptExecutedEvent";

        _scriptWidget = new ScriptWidget(_shell);
        connect(_scriptWidget,SIGNAL(textChanged()),this,SLOT(textChange()));
        _scriptWidget->installEventFilter(this);

        _viewer = new OutputWidget(_viewMode, _shell);
        _outputLabel = new QLabel(this);
        _outputLabel->setContentsMargins(0, 5, 0, 0);
        _outputLabel->setVisible(false);
        _viewer->installEventFilter(this);

        QFrame *line = new QFrame(this);
        line->setFrameShape(QFrame::HLine);
        line->setFrameShadow(QFrame::Raised);

        QVBoxLayout *layout = new QVBoxLayout;
        layout->setSpacing(0);
        layout->setContentsMargins(0, 0, 0, 0);
        layout->addWidget(_scriptWidget, 0, Qt::AlignTop);
        layout->addWidget(line);
        layout->addWidget(_outputLabel, 0, Qt::AlignTop);
        layout->addWidget(_viewer, 1);
        setLayout(layout);

        if (shell->isExecutable()) {
            showProgress();
        }
    }
コード例 #13
0
void QgsOfflineEditingPlugin::initGui()
{
  delete mActionConvertProject;

  // Create the action for tool
  mActionConvertProject = new QAction( QIcon( ":/offline_editing/offline_editing_copy.png" ), tr( "Convert to offline project" ), this );
  mActionConvertProject->setObjectName( "mActionConvertProject" );
  // Set the what's this text
  mActionConvertProject->setWhatsThis( tr( "Create offline copies of selected layers and save as offline project" ) );
  // Connect the action to the run
  connect( mActionConvertProject, SIGNAL( triggered() ), this, SLOT( convertProject() ) );
  // Add the icon to the toolbar
  mQGisIface->addDatabaseToolBarIcon( mActionConvertProject );
  mQGisIface->addPluginToDatabaseMenu( tr( "&Offline Editing" ), mActionConvertProject );
  mActionConvertProject->setEnabled( false );

  mActionSynchronize = new QAction( QIcon( ":/offline_editing/offline_editing_sync.png" ), tr( "Synchronize" ), this );
  mActionSynchronize->setObjectName( "mActionSynchronize" );
  mActionSynchronize->setWhatsThis( tr( "Synchronize offline project with remote layers" ) );
  connect( mActionSynchronize, SIGNAL( triggered() ), this, SLOT( synchronize() ) );
  mQGisIface->addDatabaseToolBarIcon( mActionSynchronize );
  mQGisIface->addPluginToDatabaseMenu( tr( "&Offline Editing" ), mActionSynchronize );
  mActionSynchronize->setEnabled( false );

  mOfflineEditing = new QgsOfflineEditing();
  mProgressDialog = new QgsOfflineEditingProgressDialog( mQGisIface->mainWindow(), QgisGui::ModalDialogFlags );

  connect( mOfflineEditing, SIGNAL( progressStarted() ), this, SLOT( showProgress() ) );
  connect( mOfflineEditing, SIGNAL( layerProgressUpdated( int, int ) ), this, SLOT( setLayerProgress( int, int ) ) );
  connect( mOfflineEditing, SIGNAL( progressModeSet( QgsOfflineEditing::ProgressMode, int ) ), this, SLOT( setProgressMode( QgsOfflineEditing::ProgressMode, int ) ) );
  connect( mOfflineEditing, SIGNAL( progressUpdated( int ) ), this, SLOT( updateProgress( int ) ) );
  connect( mOfflineEditing, SIGNAL( progressStopped() ), this, SLOT( hideProgress() ) );
  connect( mOfflineEditing, SIGNAL( warning( QString, QString ) ), mQGisIface->messageBar(), SLOT( pushWarning( QString, QString ) ) );

  connect( mQGisIface->mainWindow(), SIGNAL( projectRead() ), this, SLOT( updateActions() ) );
  connect( mQGisIface->mainWindow(), SIGNAL( newProject() ), this, SLOT( updateActions() ) );
  connect( QgsProject::instance(), SIGNAL( writeProject( QDomDocument & ) ), this, SLOT( updateActions() ) );
  connect( QgsMapLayerRegistry::instance(), SIGNAL( layerWasAdded( QgsMapLayer* ) ), this, SLOT( updateActions() ) );
  connect( QgsMapLayerRegistry::instance(), SIGNAL( layerWillBeRemoved( QString ) ), this, SLOT( updateActions() ) );
  updateActions();
}
コード例 #14
0
ファイル: classifier.cpp プロジェクト: rlcook0/Yttrium
bool Classifier::test(DataSet *data)
{
    cout << "------------------------------------------" << endl;
    cout << "\t\tTesting" << endl;
    
    for (int img = 0; img < data->num_images; ++img) 
    {
        showProgress(img, data->num_images);
        
        vector<int> cluster( data->count(img) );
        for (int i = 0; i < data->count(img); ++i)
            cluster[i] = best_cluster(centers, data->get(img, i) );
        
        
        CvMat *query = cvCreateMat(1, num_clusters, CV_32FC1);
        cvSet(query, cvScalar(0));
        for (int row = 0; row < data->count(img); ++row) {
            int cluster_idx = cluster[row];
            int oldVal = cvGetReal2D(query, 0, cluster_idx);
            cvSetReal2D(query, 0, cluster_idx, oldVal+1);//cvScalar(oldVal+1));
        }
        
        int trueClass = data->get_class(img);
        
        svm.test(query, trueClass);
        rtrees.test(query, trueClass);
        btrees.test(query, trueClass);
        bayes.test(query, trueClass);

    }
    
    svm.scores.out("SVM: ");
    rtrees.scores.out("RTrees: ");
    btrees.scores.out("BTrees: ");
    bayes.scores.out("Bayes: ");
    
    return true;
}
コード例 #15
0
ファイル: replaygain.cpp プロジェクト: Civil/cantata
void ReplayGain::scannerDone()
{
    TrackScanner *s=qobject_cast<TrackScanner *>(sender());
    if (!s) {
        return;
    }
    Track &track=tracks[s->index()];
    if (!track.finished) {
        track.finished=true;
        track.success=s->success();
        track.progress=100;
        showProgress();
        totalScanned++;
    }

    if (toScan.isEmpty()) {
        if (totalScanned==files.count()) {
            showResults();
        }
    } else {
        int index=toScan.takeAt(0);
        createScanner(index);
    }
}
コード例 #16
0
ファイル: progress_info.hpp プロジェクト: AliAlawieh/kalibr
 void showProgress(T1 done, T2 all)
 {
     SM_ASSERT_GT(std::runtime_error, all, 0, "#DIV0");
     showProgress(static_cast<double>(done) / static_cast<double>(all));
 }
コード例 #17
0
ファイル: classifier.cpp プロジェクト: rlcook0/Yttrium
bool Classifier::extract(TTrainingFileList& fileList)
{
    cout << "Classes:" << endl;
    for (int i = 0; i < (int)fileList.classes.size(); i++) {
        cout << fileList.classes[i] << " (";
        int count = 0;
        for (int j = 0; j < (int)fileList.files.size(); j++) {
            if (fileList.files[j].label == fileList.classes[i]) {
                count += 1;
            }
        }
        cout << count << " samples)" << endl;
    }
    cout << endl;

    IplImage *image;
    
    int maxImages = INT_MAX;

    cout << "Processing images..." << endl;

    //vector<int> numIpoints(kNumObjectTypes);
    int minfiles = min(maxImages, (int)fileList.files.size());
    for (int i = 0; i < minfiles; i++) 
    {
        // skip too many others...
        if (fileList.files[i].label == "other" && --max_others < 0) continue;

        // show progress
        if (i % 10 == 0) showProgress(i, minfiles);

        image = cvLoadImage(fileList.files[i].filename.c_str(), 0);
        
        if (image == NULL) {
            cerr << "ERROR: could not load image " << fileList.files[i].filename.c_str() << endl;
            continue;
        }
        
        string label = fileList.files[i].label;

        CvSeq *keypoints = 0, *descriptors = 0;
        CvSURFParams params = cvSURFParams(100, SURF_SIZE == 128);
        cvExtractSURF(image, 0, &keypoints, &descriptors, storage, params);
        
        if (descriptors->total == 0) continue;
        
        vector<float> desc;
        desc.resize(descriptors->total * descriptors->elem_size/sizeof(float));
        cvCvtSeqToArray(descriptors, &desc[0]);
        
        vector<float *> features;
        int where = 0;
        for (int pt = 0; pt < keypoints->total; ++pt) {
            float *f = new float[SURF_SIZE];
            for (int j = 0; j < SURF_SIZE; ++j) {
                f[j] = desc[where];
                ++where;
            }
            features.push_back(f);
        }
        
        if (i % test_to_train == 1 || !test_on) 
            set_train.push(stringToClassInt(label), features);
        else set_test.push(stringToClassInt(label), features);
    }
    
    
    cout << endl << "Extracted surf features. " << endl;

    cout << "Train Set" << endl;
    set_train.recount();
    set_train.stats();
    
    cout << "Test Set" << endl;
    set_train.recount();
    set_test.stats();
    
    return true;
}
コード例 #18
0
ファイル: tex.c プロジェクト: Borf/CaveQuake
void
tex_loadall(void)
{
    int i;
    byte_t *rgb;
    int width, height, format, len, size;

    if (g->r_notextures)
      return;

    g->r_texture_data = (tex_data_t *) gc_malloc(g->r_numtextures * sizeof(tex_data_t));
    
    imgbuf = malloc(IMG_BUFSIZE);
   
    for (i=0; i < g->r_numtextures; ++i) {

        rgb = NULL;
        showProgress(i, g->r_numtextures-1);
	/* printf("loading...%s\n", g->r_texfiles[i].fname);  */

	len = strlen(g->r_texfiles[i].fname);
	if (!strcmp(&(g->r_texfiles[i].fname[len-4]), ".jpg"))
	{
	    if (!jpg_readtex(g->r_texfiles[i].fname, &rgb, &width, &height,
			     &format))
		Error("Could not open file %s", g->r_texfiles[i].fname);
		/* continue; */
                i = i; /* nothing */
	}
	else if (!strcmp(&(g->r_texfiles[i].fname[len-4]), ".tga"))
	{
	    if (!tga_readtex(g->r_texfiles[i].fname, &rgb, &width, &height,
			     &format))
	    {
		/* Might still be a jpg file !!! (compatibility with old
		   shader scripts?) */
		strcpy(&(g->r_texfiles[i].fname[len-3]), "jpg");
		if (!jpg_readtex(g->r_texfiles[i].fname, &rgb, &width,
				 &height, &format))
		{
		    /* FIXME: This should be an error, but still happens
		       in the demo levels ! */
		    strcpy(&(g->r_texfiles[i].fname[len-3]), "tga");
		    printf("Could not open file %s\n", g->r_texfiles[i].fname);
		    /* continue; */
		}
	    }
	}
	else {
	    Error("Unknown format for %s", g->r_texfiles[i].fname);
		/* continue;
 */
	}

        size = width*height* (format == GL_RGB ? 3 : 4);

        /* Not really a gamma: prelighten the texture to compensate for
           darkening after lightmap application. */
        if (rgb && (g->r_gamma != 1.0 || g->r_brightness != 0))
        {
    	    int i, val;
	    for (i=0; i<size; ++i)
	    {
	        val = (rgb[i] + g->r_brightness) * g->r_gamma;
                /*val = gammaCorrect(rgb[i], g->r_gamma);*/
	        if (val > 255) val = 255;
	        rgb[i] = val;
	    }
        }
	g->r_texture_data[i].rgb = rgb;
	g->r_texture_data[i].w = width;
	g->r_texture_data[i].h = height;
	g->r_texture_data[i].format = format;
    }
    free(imgbuf);
}
コード例 #19
0
ファイル: checkerstatus.cpp プロジェクト: KDE/kdevplatform
void CheckerStatus::stop()
{
    emit clearMessage(this);
    emit showProgress(this, 0, d->m_maxItems, d->m_maxItems);
    emit hideProgress(this);
}
コード例 #20
0
ファイル: checkerstatus.cpp プロジェクト: KDE/kdevplatform
void CheckerStatus::start()
{
    d->m_checkedItems = 0;
    emit showProgress(this, 0, d->m_maxItems, d->m_checkedItems);
}
コード例 #21
0
bool SndFileAudioFileReader::run(AudioProcessor& processor)
{
    if (input_file_ == nullptr) {
        return false;
    }

    const int BUFFER_SIZE = 16384;

    float float_buffer[BUFFER_SIZE];
    short input_buffer[BUFFER_SIZE];

    const int sub_type = info_.format & SF_FORMAT_SUBMASK;

    const bool is_floating_point = sub_type == SF_FORMAT_FLOAT ||
                                   sub_type == SF_FORMAT_DOUBLE;

    sf_count_t frames_to_read = BUFFER_SIZE / info_.channels;
    sf_count_t frames_read    = frames_to_read;

    sf_count_t total_frames_read = 0;

    bool success = true;

    success = processor.init(info_.samplerate, info_.channels, BUFFER_SIZE);

    if (success) {
        showProgress(0, info_.frames);

        while (success && frames_read == frames_to_read) {
            if (is_floating_point) {
                frames_read = sf_readf_float(
                    input_file_,
                    float_buffer,
                    frames_to_read
                );

                // Scale floating-point samples from [-1.0, 1.0] to 16-bit
                // integer range. Note: we don't use SFC_SET_SCALE_FLOAT_INT_READ
                // as this scales using the overall measured waveform peak
                // amplitude, resulting in an unwanted amplitude change.

                for (int i = 0; i < frames_read * info_.channels; ++i) {
                    input_buffer[i] = static_cast<short>(
                        float_buffer[i] * std::numeric_limits<short>::max()
                    );
                }
            }
            else {
                frames_read = sf_readf_short(
                    input_file_,
                    input_buffer,
                    frames_to_read
                );
            }

            success = processor.process(
                input_buffer,
                static_cast<int>(frames_read)
            );

            total_frames_read += frames_read;

            showProgress(total_frames_read, info_.frames);
        }

        output_stream << "\nRead " << total_frames_read << " frames\n";

        processor.done();
    }

    close();

    return success;
}
コード例 #22
0
bool Mp3AudioFileReader::run(AudioProcessor& processor)
{
    if (file_ == nullptr) {
        return false;
    }

    enum {
        STATUS_OK,
        STATUS_INIT_ERROR,
        STATUS_READ_ERROR,
        STATUS_PROCESS_ERROR
    } status = STATUS_OK;

    unsigned char input_buffer[INPUT_BUFFER_SIZE + MAD_BUFFER_GUARD];
    unsigned char* guard_ptr = nullptr;
    unsigned long frame_count = 0;

    short output_buffer[OUTPUT_BUFFER_SIZE];
    short* output_ptr = output_buffer;
    const short* const output_buffer_end = output_buffer + OUTPUT_BUFFER_SIZE;

    int channels = 0;

    // Decoding options can here be set in the options field of the stream
    // structure.

    // {1} When decoding from a file we need to know when the end of the file is
    // reached at the same time as the last bytes are read (see also the comment
    // marked {3} below). Neither the standard C fread() function nor the POSIX
    // read() system call provides this feature. We thus need to perform our
    // reads through an interface having this feature, this is implemented here
    // by the bstdfile.c module.

    BStdFile bstd_file(file_);

    // Initialize the structures used by libmad.
    MadStream stream;
    MadFrame frame;
    MadSynth synth;

    mad_timer_t timer;
    mad_timer_reset(&timer);

    // This is the decoding loop.

    for (;;) {
        // The input bucket must be filled if it becomes empty or if it's the
        // first execution of the loop.

        if (stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) {
            size_t read_size;
            size_t remaining;
            unsigned char* read_start;

            // {2} libmad may not consume all bytes of the input buffer. If the
            // last frame in the buffer is not wholly contained by it, then that
            // frame's start is pointed by the next_frame member of the stream
            // structure. This common situation occurs when mad_frame_decode()
            // fails, sets the stream error code to MAD_ERROR_BUFLEN, and sets
            // the next_frame pointer to a non-NULL value. (See also the comment
            // marked {4} below.)
            //
            // When this occurs, the remaining unused bytes must be put back at
            // the beginning of the buffer and taken in account before refilling
            // the buffer. This means that the input buffer must be large enough
            // to hold a whole frame at the highest observable bit-rate
            // (currently 448 kb/s). XXX=XXX Is 2016 bytes the size of the
            // largest frame? (448000*(1152/32000))/8

            if (stream.next_frame != nullptr) {
                remaining = stream.bufend - stream.next_frame;
                memmove(input_buffer, stream.next_frame, remaining);
                read_start = input_buffer + remaining;
                read_size  = INPUT_BUFFER_SIZE - remaining;
            }
            else {
                read_size  = INPUT_BUFFER_SIZE;
                read_start = input_buffer;
                remaining = 0;
            }

            // Fill-in the buffer. If an error occurs print a message and leave
            // the decoding loop. If the end of stream is reached we also leave
            // the loop but the return status is left untouched.

            read_size = bstd_file.read(read_start, 1, read_size);

            if (read_size <= 0) {
                if (ferror(file_)) {
                    error_stream << "\nRead error on bit-stream: "
                                 << strerror(errno) << '\n';
                    status = STATUS_READ_ERROR;
                }

                break;
            }

            // {3} When decoding the last frame of a file, it must be followed
            // by MAD_BUFFER_GUARD zero bytes if one wants to decode that last
            // frame. When the end of file is detected we append that quantity
            // of bytes at the end of the available data. Note that the buffer
            // can't overflow as the guard size was allocated but not used the
            // the buffer management code. (See also the comment marked {1}.)
            //
            // In a message to the mad-dev mailing list on May 29th, 2001, Rob
            // Leslie explains the guard zone as follows:
            //
            //    "The reason for MAD_BUFFER_GUARD has to do with the way
            //    decoding is performed. In Layer III, Huffman decoding may
            //    inadvertently read a few bytes beyond the end of the buffer in
            //    the case of certain invalid input. This is not detected until
            //    after the fact. To prevent this from causing problems, and
            //    also to ensure the next frame's main_data_begin pointer is
            //    always accessible, MAD requires MAD_BUFFER_GUARD (currently 8)
            //    bytes to be present in the buffer past the end of the current
            //    frame in order to decode the frame."

            if (bstd_file.eof()) {
                guard_ptr = read_start + read_size;
                memset(guard_ptr, 0, MAD_BUFFER_GUARD);
                read_size += MAD_BUFFER_GUARD;
            }

            // Pipe the new buffer content to libmad's stream decoder facility.
            mad_stream_buffer(&stream, input_buffer, read_size + remaining);
            stream.error = MAD_ERROR_NONE;
        }

        // Decode the next MPEG frame. The streams is read from the buffer, its
        // constituents are break down and stored the the frame structure, ready
        // for examination/alteration or PCM synthesis. Decoding options are
        // carried in the frame structure from the stream structure.
        //
        // Error handling: mad_frame_decode() returns a non zero value when an
        // error occurs. The error condition can be checked in the error member
        // of the stream structure. A mad error is recoverable or fatal, the
        // error status is checked with the MAD_RECOVERABLE macro.
        //
        // {4} When a fatal error is encountered all decoding activities shall
        // be stopped, except when a MAD_ERROR_BUFLEN is signaled. This
        // condition means that the mad_frame_decode() function needs more input
        // to complete its work. One shall refill the buffer and repeat the
        // mad_frame_decode() call. Some bytes may be left unused at the end of
        // the buffer if those bytes forms an incomplete frame. Before
        // refilling, the remaining bytes must be moved to the beginning of the
        // buffer and used for input for the next mad_frame_decode() invocation.
        // (See the comments marked {2} earlier for more details.)
        //
        // Recoverable errors are caused by malformed bit-streams, in this case
        // one can call again mad_frame_decode() in order to skip the faulty
        // part and re-sync to the next frame.

        if (mad_frame_decode(&frame, &stream)) {
            if (MAD_RECOVERABLE(stream.error)) {
                // Do not print a message if the error is a loss of
                // synchronization and this loss is due to the end of stream
                // guard bytes. (See the comment marked {3} above for more
                // information about guard bytes.)

                if (stream.error != MAD_ERROR_LOSTSYNC ||
                    stream.this_frame != guard_ptr) {

                    // For any MP3 file we typically see two errors in the
                    // first frame processed:
                    // - lost synchronization
                    // - reserved header layer value
                    // This seems to be OK, so don't print these

                    if (frame_count != 0) {
                        error_stream << "\nRecoverable frame level error: "
                                     << mad_stream_errorstr(&stream) << '\n';
                    }
                }

                continue;
            }
            else {
                if (stream.error == MAD_ERROR_BUFLEN) {
                    continue;
                }
                else {
                    error_stream << "\nUnrecoverable frame level error: "
                                 << mad_stream_errorstr(&stream) << '\n';
                    status = STATUS_READ_ERROR;
                    break;
                }
            }
        }

        // Display the characteristics of the stream's first frame. The first
        // frame is representative of the entire stream.

        if (frame_count == 0) {
            const int sample_rate = frame.header.samplerate;
            channels = MAD_NCHANNELS(&frame.header);

            dumpInfo(output_stream, frame.header);

            if (!processor.init(sample_rate, channels, OUTPUT_BUFFER_SIZE)) {
                status = STATUS_PROCESS_ERROR;
                break;
            }

            showProgress(0, file_size_);
        }

        // Accounting. The computed frame duration is in the frame header
        // structure. It is expressed as a fixed point number whole data type is
        // mad_timer_t. It is different from the samples fixed point format and
        // unlike it, it can't directly be added or subtracted. The timer module
        // provides several functions to operate on such numbers. Be careful
        // there, as some functions of libmad's timer module receive some of
        // their mad_timer_t arguments by value!

        frame_count++;
        mad_timer_add(&timer, frame.header.duration);

        // Once decoded the frame is synthesized to PCM samples. No errors are
        // reported by mad_synth_frame();

        mad_synth_frame(&synth, &frame);

        // Synthesized samples must be converted from libmad's fixed point
        // number to the consumer format. Here we use signed 16 bit integers on
        // two channels. Integer samples are temporarily stored in a buffer that
        // is flushed when full.

        for (int i = 0; i < synth.pcm.length; i++) {
            // Left channel
            short sample = MadFixedToSshort(synth.pcm.samples[0][i]);

            *output_ptr++ = sample;

            // Right channel. If the decoded stream is monophonic then the right
            // output channel is the same as the left one.

            if (MAD_NCHANNELS(&frame.header) == 2) {
                sample = MadFixedToSshort(synth.pcm.samples[1][i]);
                *output_ptr++ = sample;
            }

            // Flush the output buffer if it is full

            if (output_ptr == output_buffer_end) {
                long pos = ftell(file_);

                showProgress(pos, file_size_);

                bool success = processor.process(
                    output_buffer,
                    OUTPUT_BUFFER_SIZE / channels
                );

                if (!success) {
                    status = STATUS_PROCESS_ERROR;
                    break;
                }

                output_ptr = output_buffer;
            }
        }
    }

    // If the output buffer is not empty and no error occurred during the last
    // write, then flush it.

    if (output_ptr != output_buffer && status != STATUS_PROCESS_ERROR) {
        int buffer_size = static_cast<int>(output_ptr - output_buffer);

        bool success = processor.process(output_buffer, buffer_size / channels);

        if (!success) {
            status = STATUS_PROCESS_ERROR;
        }
    }

    // Accounting report if no error occurred.

    if (status == STATUS_OK) {
        // Report 100% done.
        showProgress(file_size_, file_size_);

        char buffer[80];

        // The duration timer is converted to a human readable string with the
        // versatile, but still constrained mad_timer_string() function, in a
        // fashion not unlike strftime(). The main difference is that the timer
        // is broken into several values according some of its arguments. The
        // units and fracunits arguments specify the intended conversion to be
        // executed.
        //
        // The conversion unit (MAD_UNIT_MINUTES in our example) also specify
        // the order and kind of conversion specifications that can be used in
        // the format string.
        //
        // It is best to examine libmad's timer.c source-code for details of the
        // available units, fraction of units, their meanings, the format
        // arguments, etc.

        mad_timer_string(timer, buffer, "%lu:%02lu.%03u",
            MAD_UNITS_MINUTES, MAD_UNITS_MILLISECONDS, 0);

        output_stream << "\nFrames decoded: " << frame_count
                      << " (" << buffer << ")\n";
    }

    processor.done();

    close();

    return status == STATUS_OK;
}
コード例 #23
0
/**
 * This is the main() method which is called from the command-line.
 * Return code 0 means success. Any other values means some sort of error occurred.
 */
int main(const int argc, const char **argv) {
    // Assume no extra digits (unless overridden later.
    int extraDigits = 0;

    // If XYZ is added to -b, -r or -g, print x, y, z coordinates
    int useXYZ = 0;

    // Provide usage message if no arguments specified.
    const char *appName = argv[0];
    selfCheckEnabled = (strstr(appName, "debug") != 0);
    if (selfCheckEnabled) {
        fprintf(stderr, "(debug mode: self checking enabled)\n");
    }
    if (argc < 2) {
        usage(appName);
        return NORMAL_ERROR;
    }

    // First argument: command.
    const char *cmd = argv[1];
    if ((strcmp(cmd, "-d") == 0) || (strcmp(cmd, "--decode") == 0)) {

        // ------------------------------------------------------------------
        // Decode: [-d | --decode] <default-territory> <mapcode> [<mapcode> ...]
        // ------------------------------------------------------------------
        if (argc < 4) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }

        const char *defaultTerritory = argv[2];
        double lat;
        double lon;

        // Get the territory context.
        enum Territory context = getTerritoryCode(defaultTerritory, TERRITORY_NONE);

        // Decode every Mapcode.
        for (int i = 3; i < argc; ++i) {

            // Decode the Mapcode to a lat/lon.
            const char *mapcode = argv[i];
            int err = decodeMapcodeToLatLonUtf8(&lat, &lon, mapcode, context, NULL);
            if (err != 0) {
                fprintf(stderr, "error: cannot decode '%s %s'\n", defaultTerritory, mapcode);
                return NORMAL_ERROR;
            }

            // Output the decoded lat/lon.
            printf("%.20g %.20g\n", lat, lon);

            // Self-checking code to see if encoder produces this Mapcode for the lat/lon.
            if (selfCheckEnabled) {
                const char *suffix = strstr(mapcode, "-");
                extraDigits = 0;
                if (suffix != 0) {
                    extraDigits = (int) (strlen(suffix) - 1);
                }
                selfCheckLatLonToMapcode(lat, lon, mapcode, extraDigits);
            }
        }
    } else if ((strcmp(cmd, "-e") == 0) || (strcmp(cmd, "-e0") == 0) ||
               (strcmp(cmd, "-e1") == 0) || (strcmp(cmd, "-e2") == 0) ||
               (strcmp(cmd, "-e3") == 0) || (strcmp(cmd, "-e4") == 0) ||
               (strcmp(cmd, "-e5") == 0) || (strcmp(cmd, "-e6") == 0) ||
               (strcmp(cmd, "-e7") == 0) || (strcmp(cmd, "-e8") == 0) ||
               (strcmp(cmd, "--encode") == 0) || (strcmp(cmd, "--encode0") == 0) ||
               (strcmp(cmd, "--encode1") == 0) || (strcmp(cmd, "--encode2") == 0) ||
               (strcmp(cmd, "--encode3") == 0) || (strcmp(cmd, "--encode4") == 0) ||
               (strcmp(cmd, "--encode5") == 0) || (strcmp(cmd, "--encode5") == 0) ||
               (strcmp(cmd, "--encode7") == 0) || (strcmp(cmd, "--encode8") == 0)) {

        // ------------------------------------------------------------------
        // Encode: [-e[0-8] | --encode[0-8]] <lat:-90..90> <lon:-180..180> [territory]>
        // ------------------------------------------------------------------
        if ((argc != 4) && (argc != 5)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if ((!isdigit(*argv[2]) && (*argv[2] != '-')) || (!isdigit(*argv[3]) && (*argv[3] != '-'))) {
            fprintf(stderr, "error: latitude and longitude must be numeric\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        const double lat = atof(argv[2]);
        const double lon = atof(argv[3]);

        if (strstr(cmd, "-e1") || strstr(cmd, "--encode1")) {
            extraDigits = 1;
        } else if (strstr(cmd, "-e2") || strstr(cmd, "--encode2")) {
            extraDigits = 2;
        } else if (strstr(cmd, "-e3") || strstr(cmd, "--encode3")) {
            extraDigits = 3;
        } else if (strstr(cmd, "-e4") || strstr(cmd, "--encode4")) {
            extraDigits = 4;
        } else if (strstr(cmd, "-e5") || strstr(cmd, "--encode5")) {
            extraDigits = 5;
        } else if (strstr(cmd, "-e6") || strstr(cmd, "--encode6")) {
            extraDigits = 6;
        } else if (strstr(cmd, "-e7") || strstr(cmd, "--encode7")) {
            extraDigits = 7;
        } else if (strstr(cmd, "-e8") || strstr(cmd, "--encode8")) {
            extraDigits = 8;
        } else {
            extraDigits = 0;
        }

        // Get territory context.
        enum Territory context = TERRITORY_NONE;
        const char *defaultTerritory = "AAA";
        if (argc == 5) {
            context = getTerritoryCode(argv[4], TERRITORY_NONE);
            defaultTerritory = argv[4];
        }

        // Encode the lat/lon to a set of Mapcodes.
        Mapcodes mapcodes;
        const int nrResults = encodeLatLonToMapcodes(&mapcodes, lat, lon, context, extraDigits);
        if (nrResults <= 0) {
            fprintf(stderr, "error: cannot encode lat=%.20g, lon=%.20g (default territory=%s)\n",
                    lat, lon, defaultTerritory);
            return NORMAL_ERROR;
        }

        // Output the Mapcode.
        for (int i = 0; i < nrResults; ++i) {
            const char *foundMapcode = mapcodes.mapcode[i];
            printf("%s\n", foundMapcode);

            // Self-checking code to see if decoder produces the lat/lon for all of these Mapcodes.
            if (selfCheckEnabled) {
                selfCheckMapcodeToLatLon(foundMapcode, lat, lon);
            }
        }
    } else if ((strcmp(cmd, "-t") == 0) ||
               (strcmp(cmd, "--territories") == 0)) {

        // ------------------------------------------------------------------
        // Generate a test set based on the Mapcode territories
        // ------------------------------------------------------------------
        if ((argc < 2) || (argc > 2)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        printf("ccode,territorycodes(pipe-separated),alphabets(pipe-seperated),names(pipe-separated)\n");
        for (int i = _TERRITORY_MIN + 1; i < _TERRITORY_MAX; ++i) {
            const enum Territory ccode = (enum Territory) i;
            char territoryName[MAX_MAPCODE_RESULT_LEN];
            printf("%d,", INDEX_OF_TERRITORY(i));

            // Use internal knowledge of ALPHA_SEARCH to show aliases of territoryName.
            printf("%s", getTerritoryIsoName(territoryName, ccode, 0));
            for (int a = 0; a < NR_TERRITORY_RECS; a++) {
                if (ALPHA_SEARCH[a].territory == ccode) {
                    char fullcode[16];
                    strcpy(fullcode, ALPHA_SEARCH[a].alphaCode);
                    if (fullcode[0] >= '0' && fullcode[0] <= '9') {
                        static const char *parents2 = "US,IN,CA,AU,MX,BR,RU,CN,";
                        int p = (fullcode[0] - '0');
                        memcpy(fullcode, &parents2[p * 3 - 3], 2);
                        fullcode[2] = '-';
                        strcpy(fullcode + 3, ALPHA_SEARCH[a].alphaCode + 1);
                    }
                    if (strcmp(fullcode, territoryName) != 0) {
                        printf("|%s", fullcode);
                    }
                }
            }
            printf(",");

            // Print alphabets.
            const TerritoryAlphabets *territoryAlphabets = getAlphabetsForTerritory(ccode);
            for (int j = 0; j < territoryAlphabets->count; j++) {
                if (j > 0) {
                    printf("|");
                }
                printf("%d", territoryAlphabets->alphabet[j]);
            }
            printf(",");

            // Use internal knowledge of TERRITORY_FULL_NAME to show aliases of full territory name.
            char *names = strdup(TERRITORY_FULL_NAME[INDEX_OF_TERRITORY(ccode)]);
            char *s = names;
            while (s) {
                if (s != names) {
                    printf("|");
                }
                char *e = strstr(s, " (");
                if (e) {
                    *e = 0;
                    if (e[-1] == ')') {
                        e[-1] = 0;
                    }
                    printf("%s", s);
                    s = e + 2;
                } else {
                    e = s + strlen(s);
                    if (e[-1] == ')') {
                        e[-1] = 0;
                    }
                    printf("%s", s);
                    s = NULL;
                }
            }
            printf("\n");
        }
    } else if ((strcmp(cmd, "-a") == 0) ||
               (strcmp(cmd, "--alphabets") == 0)) {

        // ------------------------------------------------------------------
        // Generate a test set based on the Mapcode territories
        // ------------------------------------------------------------------
        static const char *mapcodeForCSV[] = {
                // all characters
                "89.EU",
                "00.0A",
                "BCDF.GHJK",
                "LMNP.QRST",
                "VWXY.Z123",
                "4567.890B",
                // all forms
                "pq.xy",
                "pq.xyz",
                "pqx.yz",
                "pq.rxyz",
                "pqr.xyz",
                "pqrx.yz",
                "pqr.sxyz",
                "pqrs.xyz",
                "pqrs.txyz",
                "pqrst.vxyz",
                // all adjad forms
                "p1.xy",
                "pq.2y",
                "3q.x4",
                "5q.6y",
                "pq.1yz",
                "pq1.yz",
                "p2.x3z",
                "p2x.3z",
                "pq.1xy2",
                "pq1.xy2",
                "pq1x.y2",
                "p3.rx4z",
                "p3r.x4z",
                "p3rx.4z",
                "5q.r6y7",
                "5qr.6y7",
                "5qr6.y7",
                "pq1.sx2z",
                "pq1s.x2z",
                "p3r.s4yz",
                "p3rs.4yz",
                "5qr.6xy7",
                "5qr6.xy7",
                "8q9.sx0z",
                "8q9s.x0z",
                "1qr2.tx3z",
                "p4rs.5xy6",
                "p7r8.t9y0",
                "pq1st.2xy3",
                "p4rs5.vx6z",
                "7qr8t.v9yz",
                "p1r2t.3x4z",
                "5q6s7.v8y9",
                // non-mapcode
                "^0123456789!@#$^&*()/:;[]{}<>?|~%",
                "abcdefghijklmnopqrstuvwxyz",
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                // special case for digit-like characters
                "OI.xx",
                "oi.xx",
                "oi.xx-oooooooo",
                "oi.xx-iiiiiiii",
                "PQ.RS-01234567",
                "PQ.RS-890",
                NULL
        };
        if ((argc < 2) || (argc > 2)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }

        printf("alphabetNr,MapcodeInRoman,MapcodeInAlphabet\n");
        for (enum Alphabet alphabet = ALPHABET_ROMAN;
             alphabet < _ALPHABET_MAX; alphabet = (enum Alphabet) (alphabet + 1)) {
            int variant;
            for (variant = 0; variant <= 2; variant++) {
                int m;
                for (m = 0; mapcodeForCSV[m] != NULL; m++) {
                    int i;
                    char asciiString[128];
                    // build a mapcode variant
                    char mapcode[128];
                    strcpy(mapcode, mapcodeForCSV[m]);
                    strcat(mapcode, (variant == 1) ? "-bc" : (variant == 2) ? "-DFGHJKLM" : "");
                    for (i = 0; mapcode[i]; ++i) {
                        mapcode[i] = (char) toupper((int) mapcode[i]);
                    }
                    // convert to alphabet, and back to roman
                    convertMapcodeToAlphabetUtf8(asciiString, mapcode, alphabet);
                    // output a line of csv (in utf8 format)
                    printf("%d,%s,%s\n", alphabet, mapcode, asciiString);
                }
            }
        }
    } else if ((strcmp(cmd, "-b") == 0) || (strcmp(cmd, "-bXYZ") == 0) ||
               (strcmp(cmd, "--boundaries") == 0) || (strcmp(cmd, "--boundariesXYZ") == 0)) {

        // ------------------------------------------------------------------
        // Generate a test set based on the Mapcode boundaries.
        // ------------------------------------------------------------------
        if ((argc < 2) || (argc > 3)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if (argc == 3) {
            extraDigits = atoi(argv[2]);
            if ((extraDigits < 0) || (extraDigits > 8)) {
                fprintf(stderr, "error: parameter extraDigits must be in [0..8]\n\n");
                usage(appName);
                return NORMAL_ERROR;
            }
        }
        useXYZ = (strstr(cmd, "XYZ") != 0);

        resetStatistics(MAPCODE_BOUNDARY_MAX);
        for (int i = 0; i < totalNrOfPoints; ++i) {
            double minLon;
            double maxLon;
            double minLat;
            double maxLat;
            double lat;
            double lon;

            const TerritoryBoundary *mm = TERRITORY_BOUNDARY(i);
            minLon = ((double) mm->minx) / 1.0E6;
            maxLon = ((double) mm->maxx) / 1.0E6;
            minLat = ((double) mm->miny) / 1.0E6;
            maxLat = ((double) mm->maxy) / 1.0E6;

            // Try center.
            lat = (maxLat - minLat) / 2.0;
            lon = (maxLon - minLon) / 2.0;
            generateAndOutputMapcodes(lat, lon, 0, extraDigits, useXYZ);

            // Try corners.
            generateAndOutputMapcodes(minLat, minLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat, maxLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat, minLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat, maxLon, 0, extraDigits, useXYZ);

            // Try JUST inside.
            const double d = 0.000001;
            generateAndOutputMapcodes(minLat + d, minLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat + d, maxLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat - d, minLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat - d, maxLon - d, 0, extraDigits, useXYZ);

            // Try JUST outside.
            generateAndOutputMapcodes(minLat - d, minLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat - d, maxLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat + d, minLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat + d, maxLon + d, 0, extraDigits, useXYZ);

            if ((i % SHOW_PROGRESS) == 0) {
                showProgress(i);
            }
        }
        outputStatistics();
    } else if ((strcmp(cmd, "-g") == 0) || (strcmp(cmd, "-gXYZ") == 0) ||
               (strcmp(cmd, "--grid") == 0) || (strcmp(cmd, "--gridXYZ") == 0) ||
               (strcmp(cmd, "-r") == 0) || (strcmp(cmd, "-rXYZ") == 0) ||
               (strcmp(cmd, "--random") == 0) || (strcmp(cmd, "--randomXYZ") == 0)) {

        // ------------------------------------------------------------------
        // Generate grid test set:    [-g | --grid]   <nrOfPoints> [<extradigits>]
        // Generate uniform test set: [-r | --random] <nrOfPoints> [<seed>]
        // ------------------------------------------------------------------
        if ((argc < 3) || (argc > 5)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        int nrOfPoints = atoi(argv[2]);
        if (nrOfPoints < 1) {
            fprintf(stderr, "error: total number of points to generate must be >= 1\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if (argc >= 4) {
            extraDigits = atoi(argv[3]);
            if ((extraDigits < 0) || (extraDigits > 8)) {
                fprintf(stderr, "error: parameter extraDigits must be in [0..8]\n\n");
                usage(appName);
                return NORMAL_ERROR;
            }
        }
        int random = (strcmp(cmd, "-r") == 0) || (strcmp(cmd, "--random") == 0);
        if (random) {
            if (argc == 5) {
                const int seed = atoi(argv[4]);
                srand((unsigned int) seed);
            } else {
                srand((unsigned int) time(0));
            }
        }
        useXYZ = (strstr(cmd, "XYZ") != 0);

        // Statistics.
        resetStatistics(nrOfPoints);

        int gridX = 0;
        int gridY = 0;
        int line = my_round(sqrt((double) totalNrOfPoints));
        for (int i = 0; i < totalNrOfPoints; ++i) {
            double lat;
            double lon;
            double unit1;
            double unit2;

            if (random) {
                unit1 = ((double) rand()) / RAND_MAX;
                unit2 = ((double) rand()) / RAND_MAX;
            } else {
                unit1 = ((double) gridX) / line;
                unit2 = ((double) gridY) / line;

                if (gridX < line) {
                    ++gridX;
                } else {
                    gridX = 0;
                    ++gridY;
                }
            }

            unitToLatLonDeg(unit1, unit2, &lat, &lon);
            generateAndOutputMapcodes(lat, lon, 1, extraDigits, useXYZ);

            if ((i % SHOW_PROGRESS) == 0) {
                showProgress(i);
            }
        }
        outputStatistics();
    } else {

        // ------------------------------------------------------------------
        // Usage.
        // ------------------------------------------------------------------
        usage(appName);
        return NORMAL_ERROR;
    }
    return 0;
}
コード例 #24
0
ファイル: FullRun.cpp プロジェクト: olli0601/3SEQ
void FullRun::progress(void) {
    if (cloAllBpCalculated) {
        Interface::instance()
                << "                                                Recombinant      Longest Recombinant\n"
                << "Progress    Time Elapsed    Minimum P-Value    Triplets Found          Segment\n";
    } else {
        Interface::instance()
                << "                                                Recombinant\n"
                << "Progress    Time Elapsed    Minimum P-Value    Triplets Found\n";
    }
    Interface::instance().showLog(false);

    recombinationSensitivity = 0;

    for (unsigned long randLoopCounter = 0; randLoopCounter < randomLoopNum; randLoopCounter++) {
        if (isRandomMode) {
            childDataset->randomlyActivate(randomSeqNum);
            calculateTripletNum();
        }

        numRecombinantTriplets = 0.0;
        numComputedExactly = 0.0;
        numApproximated = 0.0;
        numSkipped = getNumTotalTriplets();

        minPVal = 1.0;
        longestRecombinantSegment = 0;

        /* Initialise progress counter */
        unsigned long activeChildNum = childDataset->getNumActiveSeq();
        unsigned long activeParentNum = parentDataset->getNumActiveSeq();

        double totalLoop = static_cast<double> (activeChildNum)
                * static_cast<double> (activeParentNum);
        Interface::instance().initCounter("", 0, totalLoop);


        /* This flag indicates if the progressing should be stopped */
        bool isStoped = false;

        /* Progressing begins */
        unsigned long activeChildCounter = 0;
        unsigned long activeDadCounter = 0;

        Genome* child = NULL;
        Genome* dad = NULL;
        Genome* mum = NULL;
        Triplet* triplet = NULL;

        for (unsigned long childIndex = 0; !isStoped && childIndex < childDataset->getSize(); childIndex++) {
            child = childDataset->getGenome(childIndex);
            if (child->isActive()) {
                activeChildCounter++;
            } else {
                continue;
            }

            activeDadCounter = 0;
            for (unsigned long dadIndex = 0; !isStoped && dadIndex < parentDataset->getSize(); dadIndex++) {
                dad = parentDataset->getGenome(dadIndex);
                if (dad->isActive()) {
                    activeDadCounter++;
                }
                if (!dad->isActive() || dad == child) {
                    continue;
                }

                /* Show progress counter */
                double currentLoop = static_cast<double> (activeChildCounter - 1)
                        * static_cast<double> (activeParentNum)
                        + static_cast<double> (activeDadCounter - 1);
                showProgress(currentLoop, false);

                for (unsigned long mumIndex = 0; !isStoped && mumIndex < parentDataset->getSize(); mumIndex++) {
                    mum = parentDataset->getGenome(mumIndex);
                    if (!mum->isActive() || mum == child || mum == dad) continue;

                    triplet = new Triplet(dad, mum, child);

                    /* Let's see if we can calculate the exact P-value */
                    bool hasPValue = triplet->calculatePVal(cloUseSiegmundApprox);
                    if (!hasPValue) {
                        if (fileSkippedTriplets) {
                            /* No need to open file, writeLine() will do that automatically */
                            fileSkippedTriplets->writeLine(triplet->toString());
                        }
                        delete triplet;
                        continue;
                    }
                    numSkipped -= 1.0;

                    if (triplet->isPValApproximated()) {
                        numApproximated += 1.0;
                    } else {
                        numComputedExactly += 1.0;
                    }

                    double pValue = triplet->getPVal();
                    addPValIntoHistogram(pValue);

                    if (pValue < minPVal)
                        minPVal = pValue;

                    /* Let's see if the P-value is significant */
                    if (stats::correction::dunnSidak(pValue, getNumTripletsForCorrection()) < cloRejectThreshold) {
                        numRecombinantTriplets += 1.0;
                        if (child->getRecombinantType() == Genome::Na_REC) {
                            child->setRecombinantType(Genome::SHORT_REC);
                        }

                        /* Go into this loop either if we're doing ALL breakpoint or
                         * NO breakpoint if we are doing no breakpoint, then the 
                         * breakpoint calculations is skipped. */
                        if (cloAllBpCalculated || cloNoBpCalculated) {
                            recordRecombinantTriplet(triplet);
                        }

                        /* Now check if this is the *best* recombinant (meaning lowest p-value)
                         * and if it is, record it */
                        if (child->getBestRecombinantTriplet() == NULL
                                || pValue < child->getBestRecombinantTriplet()->getPVal()) {
                            child->setBestRecombinantTriplet(triplet);
                        } else {
                            delete triplet;
                        }

                        if (cloStopAtFirstRecombinant) {
                            /* Finish progressing early */
                            isStoped = true;
                        }

                    } else {
                        delete triplet;
                    }
                }
            }
        }

        /* Progressing finished */
        showProgress(0.0, true);

        if (numRecombinantTriplets > 0) {
            recombinationSensitivity++;
        }
    }
}
コード例 #25
0
ファイル: mapcode.cpp プロジェクト: joycepg/mapcode-cpp
/**
 * This is the main() method which is called from the command-line.
 * Return code 0 means success. Any other values means some sort of error occurred.
 */
int main(const int argc, const char **argv) {
    // Assume no extra digits (unless overridden later.
    int extraDigits = 0;

    // If XYZ is added to -b, -r or -g, print x, y, z coordinates
    int useXYZ = 0;

    // Provide usage message if no arguments specified.
    const char *appName = argv[0];
    selfCheckEnabled = (strstr(appName, "debug") != 0);
    if (selfCheckEnabled) {
        fprintf(stderr, "(debug mode: self checking enabled)\n");
    }
    if (argc < 2) {
        usage(appName);
        return NORMAL_ERROR;
    }

    // First argument: command.
    const char *cmd = argv[1];
    if ((strcmp(cmd, "-d") == 0) || (strcmp(cmd, "--decode") == 0)) {

        // ------------------------------------------------------------------
        // Decode: [-d | --decode] <default-territory> <mapcode> [<mapcode> ...]
        // ------------------------------------------------------------------
        if (argc < 4) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }

        const char *defaultTerritory = argv[2];
        double lat;
        double lon;

        // Get the territory context.
        int context = convertTerritoryIsoNameToCode(defaultTerritory, 0);

        // Decode every Mapcode.
        for (int i = 3; i < argc; ++i) {

            // Decode the Mapcode to a lat/lon.
            const char *mapcode = argv[i];
            int err = decodeMapcodeToLatLon(&lat, &lon, mapcode, context);
            if (err != 0) {
                fprintf(stderr, "error: cannot decode '%s %s'\n", defaultTerritory, mapcode);
                return NORMAL_ERROR;
            }

            // Output the decoded lat/lon.
            printf("%.12g %.12g\n", lat, lon);

            // Self-checking code to see if encoder produces this Mapcode for the lat/lon.
            if (selfCheckEnabled) {
                const char *suffix = strstr(mapcode, "-");
                extraDigits = 0;
                if (suffix != 0) {
                    extraDigits = (int) (strlen(suffix) - 1);
                }
                selfCheckLatLonToMapcode(lat, lon, defaultTerritory, mapcode, extraDigits);
            }
        }
    }
    else if ((strcmp(cmd, "-e") == 0) || (strcmp(cmd, "-e0") == 0) ||
             (strcmp(cmd, "-e1") == 0) || (strcmp(cmd, "-e2") == 0) ||
             (strcmp(cmd, "-e3") == 0) || (strcmp(cmd, "-e4") == 0) ||
             (strcmp(cmd, "-e5") == 0) || (strcmp(cmd, "-e6") == 0) ||
             (strcmp(cmd, "-e7") == 0) || (strcmp(cmd, "-e8") == 0) ||
             (strcmp(cmd, "--encode") == 0) || (strcmp(cmd, "--encode0") == 0) ||
             (strcmp(cmd, "--encode1") == 0) || (strcmp(cmd, "--encode2") == 0) ||
             (strcmp(cmd, "--encode3") == 0) || (strcmp(cmd, "--encode4") == 0) ||
             (strcmp(cmd, "--encode5") == 0) || (strcmp(cmd, "--encode5") == 0) ||
             (strcmp(cmd, "--encode7") == 0) || (strcmp(cmd, "--encode8") == 0)) {

        // ------------------------------------------------------------------
        // Encode: [-e[0-8] | --encode[0-8]] <lat:-90..90> <lon:-180..180> [territory]>
        // ------------------------------------------------------------------
        if ((argc != 4) && (argc != 5)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if ((!isdigit(*argv[2]) && (*argv[2] != '-')) || (!isdigit(*argv[3]) && (*argv[3] != '-'))) {
            fprintf(stderr, "error: latitude and longitude must be numeric\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        const double lat = atof(argv[2]);
        const double lon = atof(argv[3]);

        if (strstr(cmd, "-e1") || strstr(cmd, "--encode1")) {
            extraDigits = 1;
        }
        else if (strstr(cmd, "-e2") || strstr(cmd, "--encode2")) {
            extraDigits = 2;
        }
        else if (strstr(cmd, "-e3") || strstr(cmd, "--encode3")) {
            extraDigits = 3;
        }
        else if (strstr(cmd, "-e4") || strstr(cmd, "--encode4")) {
            extraDigits = 4;
        }
        else if (strstr(cmd, "-e5") || strstr(cmd, "--encode5")) {
            extraDigits = 5;
        }
        else if (strstr(cmd, "-e6") || strstr(cmd, "--encode6")) {
            extraDigits = 6;
        }
        else if (strstr(cmd, "-e7") || strstr(cmd, "--encode7")) {
            extraDigits = 7;
        }
        else if (strstr(cmd, "-e8") || strstr(cmd, "--encode8")) {
            extraDigits = 8;
        }
        else {
            extraDigits = 0;
        }

        // Get territory context.
        int context = 0;
        const char *defaultTerritory = "AAA";
        if (argc == 5) {
            context = convertTerritoryIsoNameToCode(argv[4], 0);
            defaultTerritory = argv[4];
        }

        // Encode the lat/lon to a set of Mapcodes.
        char *results[2 * MAX_NR_OF_MAPCODE_RESULTS];
        const int nrResults = encodeLatLonToMapcodes_Deprecated(results, lat, lon, context, extraDigits);
        if (nrResults <= 0) {
            fprintf(stderr, "error: cannot encode lat=%.12g, lon=%.12g (default territory=%s)\n",
                    lat, lon, defaultTerritory);
            return NORMAL_ERROR;
        }

        // Output the Mapcode.
        for (int i = 0; i < nrResults; ++i) {
            const char *foundMapcode = results[(i * 2)];
            const char *foundTerritory = results[(i * 2) + 1];
            printf("%s %s\n", foundTerritory, foundMapcode);

            // Self-checking code to see if decoder produces the lat/lon for all of these Mapcodes.
            if (selfCheckEnabled) {
                selfCheckMapcodeToLatLon(foundTerritory, foundMapcode, lat, lon);
            }
        }
    }
    else if ((strcmp(cmd, "-b") == 0) || (strcmp(cmd, "-bXYZ") == 0) ||
             (strcmp(cmd, "--boundaries") == 0) || (strcmp(cmd, "--boundariesXYZ") == 0)) {

        // ------------------------------------------------------------------
        // Generate a test set based on the Mapcode boundaries.
        // ------------------------------------------------------------------
        if ((argc < 2) || (argc > 3)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if (argc == 3) {
            extraDigits = atoi(argv[2]);
            if ((extraDigits < 0) || (extraDigits > 8)) {
                fprintf(stderr, "error: parameter extraDigits must be in [0..8]\n\n");
                usage(appName);
                return NORMAL_ERROR;
            }
        }
        useXYZ = (strstr(cmd, "XYZ") != 0);

        resetStatistics(NR_BOUNDARY_RECS);
        for (int i = 0; i < totalNrOfPoints; ++i) {
            double minLon;
            double maxLon;
            double minLat;
            double maxLat;
            double lat;
            double lon;

            const mminforec *mm = boundaries(i);
            minLon = ((double) mm->minx) / 1.0E6;
            maxLon = ((double) mm->maxx) / 1.0E6;
            minLat = ((double) mm->miny) / 1.0E6;
            maxLat = ((double) mm->maxy) / 1.0E6;

            // Try center.
            lat = (maxLat - minLat) / 2.0;
            lon = (maxLon - minLon) / 2.0;
            generateAndOutputMapcodes(lat, lon, 0, extraDigits, useXYZ);

            // Try corners.
            generateAndOutputMapcodes(minLat, minLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat, maxLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat, minLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat, maxLon, 0, extraDigits, useXYZ);

            // Try JUST inside.
            const double d = 0.000001;
            generateAndOutputMapcodes(minLat + d, minLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat + d, maxLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat - d, minLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat - d, maxLon - d, 0, extraDigits, useXYZ);

            // Try JUST outside.
            generateAndOutputMapcodes(minLat - d, minLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat - d, maxLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat + d, minLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat + d, maxLon + d, 0, extraDigits, useXYZ);

            if ((i % SHOW_PROGRESS) == 0) {
                showProgress(i);
            }
        }
        outputStatistics();
    }
    else if ((strcmp(cmd, "-g") == 0) || (strcmp(cmd, "-gXYZ") == 0) ||
             (strcmp(cmd, "--grid") == 0) || (strcmp(cmd, "--gridXYZ") == 0) ||
             (strcmp(cmd, "-r") == 0) || (strcmp(cmd, "-rXYZ") == 0) ||
             (strcmp(cmd, "--random") == 0) || (strcmp(cmd, "--randomXYZ") == 0)) {

        // ------------------------------------------------------------------
        // Generate grid test set:    [-g | --grid]   <nrOfPoints> [<extradigits>]
        // Generate uniform test set: [-r | --random] <nrOfPoints> [<seed>]
        // ------------------------------------------------------------------
        if ((argc < 3) || (argc > 5)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        int nrOfPoints = atoi(argv[2]);
        if (nrOfPoints < 1) {
            fprintf(stderr, "error: total number of points to generate must be >= 1\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if (argc >= 4) {
            extraDigits = atoi(argv[3]);
            if ((extraDigits < 0) || (extraDigits > 8)) {
                fprintf(stderr, "error: parameter extraDigits must be in [0..8]\n\n");
                usage(appName);
                return NORMAL_ERROR;
            }
        }
        int random = (strcmp(cmd, "-r") == 0) || (strcmp(cmd, "--random") == 0);
        if (random) {
            if (argc == 5) {
                const int seed = atoi(argv[4]);
                srand((unsigned int) seed);
            }
            else {
                srand((unsigned int) time(0));
            }
        }
        useXYZ = (strstr(cmd, "XYZ") != 0);

        // Statistics.
        resetStatistics(nrOfPoints);

        int gridX = 0;
        int gridY = 0;
        int line = my_round(sqrt((double) totalNrOfPoints));
        for (int i = 0; i < totalNrOfPoints; ++i) {
            double lat;
            double lon;
            double unit1;
            double unit2;

            if (random) {
                unit1 = ((double) rand()) / RAND_MAX;
                unit2 = ((double) rand()) / RAND_MAX;
            }
            else {
                unit1 = ((double) gridX) / line;
                unit2 = ((double) gridY) / line;

                if (gridX < line) {
                    ++gridX;
                }
                else {
                    gridX = 0;
                    ++gridY;
                }
            }

            unitToLatLonDeg(unit1, unit2, &lat, &lon);
            generateAndOutputMapcodes(lat, lon, 1, extraDigits, useXYZ);

            if ((i % SHOW_PROGRESS) == 0) {
                showProgress(i);
            }
        }
        outputStatistics();
    }
    else {

        // ------------------------------------------------------------------
        // Usage.
        // ------------------------------------------------------------------
        usage(appName);
        return NORMAL_ERROR;
    }
    return 0;
}
コード例 #26
0
ファイル: StartStageBase.cpp プロジェクト: korman/Temp
StageUI_Base::StageUI_Base()
{
    m_pkUIPercentLabel = NULL;
    m_pkUILayer = 0;

    m_pkUnzipProgress = 0;
    m_pkBackgroundImage = 0;
    m_pkProgressBgImage = 0;
    m_pkUnzipTextImage = 0;

    m_pkUILayer = new NDUIDialog;
    m_pkUILayer->Initialization();
    m_pkUILayer->SetAlwaysFullScreen(true);
    m_pkUILayer->NoMask();
    getPercentLabel();

    if (m_pkUILayer)
    {
        m_pkUILayer->AddChild( m_pkUIPercentLabel, 1 );
        m_pkUIPercentLabel->SetText(CONVERT_GBK_TO_UTF8("正在检查是否需要更新……"));
    }

    m_pkBackgroundImage = new NDUIImage;
    m_pkBackgroundImage->Initialization();

    m_pkUnzipTextImage = new NDUIImage;
    m_pkUnzipTextImage->Initialization();

    m_pkProgressBgImage = new NDUIImage;
    m_pkProgressBgImage->Initialization();

    m_pkUnzipProgress = new NDUIExp;
    m_pkUnzipProgress->Initialization();
    m_pkUnzipProgress->SetNoText();
    m_pkUnzipProgress->setMaskMode(true);
    m_pkUnzipProgress->setMaskPercent(0.1f);
    //m_pkUnzipProgress->SetFgDrawFirst();

    unsigned long uiBgDataSize = 0;
    unsigned long uiBgProgressDataSize = 0;
    unsigned long uiFgProgressDataSize = 0;
    unsigned long uiProgressEffectSize = 0;
    unsigned long uiUnzipTextSize = 0;

    unsigned char* pszBgImageFileData = 0;
    unsigned char* pszBgProgressImageData = 0;
    unsigned char* pszFgProgressImageData = 0;
    unsigned char* pszProgressEffectData = 0;
    unsigned char* pszUnzipTextData = 0;

    string strPath = "";
    float fWinScale = 2.0f;
    CCSize kWinSize = ccz(0,0);
    CCSize kRealWinSize = CCDirector::sharedDirector()->getWinSize();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    strPath = "assets/install_res/";
    fWinScale = 1.0f;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    strPath = "../install_res/";
    fWinScale = 2.0f;
#endif

    CCRect kRect = m_pkUILayer->GetFrameRect();
    float fHeight = CCDirector::sharedDirector()->getWinSize().height;
    float fWidth = CCDirector::sharedDirector()->getWinSize().width;

    float fWindowScale = fHeight / fWidth;
    float fRealScreenHeight = 960.0f / fWinScale;
    float fRealScreenWidth = 640.0f / fWinScale;

    float fCtrlScale = fWidth / fRealScreenWidth;
    float fCurHeight = (fHeight - fRealScreenHeight * fCtrlScale) / 2.0f * fWinScale;
    kWinSize = ccz(fRealScreenWidth * fCtrlScale * fWinScale,fRealScreenHeight * fCtrlScale * fWinScale);

    m_pkBackgroundImage->SetFrameRect(CCRectMake(0,fCurHeight,kWinSize.width,kWinSize.height));
    //m_nOffsetHeight = fCurHeight;

    m_strBgImageFile = strPath + string("bg_image.png");
    m_strBgProgressImage = strPath + string("bg_progress.png");
    m_strFgProgressImage = strPath + string("fg_progress.png");
    m_strProgressEffect = strPath + string("progress_effect.png");
    m_strUnzipTextFile = strPath + string("load_text.png");

    pszBgImageFileData =
        __getFileData(m_strBgImageFile.c_str(),"rb",&uiBgDataSize);
    pszBgProgressImageData =
        __getFileData(m_strBgProgressImage.c_str(),"rb",&uiBgProgressDataSize);
    pszFgProgressImageData =
        __getFileData(m_strFgProgressImage.c_str(),"rb",&uiFgProgressDataSize);
    pszProgressEffectData =
        __getFileData(m_strProgressEffect.c_str(),"rb",&uiProgressEffectSize);
    pszUnzipTextData =
        __getFileData(m_strUnzipTextFile.c_str(),"rb",&uiUnzipTextSize);

    if (0 == pszBgImageFileData || 0 == pszBgProgressImageData ||
            0 == pszFgProgressImageData || 0 == pszProgressEffectData || 0 == pszUnzipTextData)
    {
        WriteConErr("Data Error!!\n");
        return;
    }

    float fProgressWidth = kWinSize.width * 0.9f;

    CCRect kProgressRect = CCRectMake((kWinSize.width - fProgressWidth) / 2.0f,
                                      kWinSize.height * 0.8f + fCurHeight, fProgressWidth,
                                      fProgressWidth * 0.086207);

    // 	kProgressRect.origin.x *= fWinScale;
    // 	kProgressRect.origin.y *= fWinScale;
    // 	kProgressRect.size.width *= fWinScale;
    // 	kProgressRect.size.height *= fWinScale;

    CCRect kTextRect = kProgressRect;
    kTextRect.origin.y -= kTextRect.size.height;

    m_pkUIPercentLabel->SetFrameRect(kTextRect);

    m_pkUnzipProgress->SetFrameRect(kProgressRect);
    m_pkProgressBgImage->SetFrameRect(kProgressRect);

    //GetUIRootNew()->addDlg(m_pkUILayer);

    NDPicture* pkUnzipTextPicture = new NDPicture;
    pkUnzipTextPicture->Initialization(pszUnzipTextData, uiUnzipTextSize);

    NDPicture* pkBgPicture = new NDPicture;
    pkBgPicture->Initialization(pszBgImageFileData, uiBgDataSize);

    NDPicture* pkEffectPicture = new NDPicture;
    pkEffectPicture->Initialization(pszProgressEffectData,
                                    uiProgressEffectSize);

    NDPicture* pkBgProgressPic = new NDPicture;
    pkBgProgressPic->Initialization(pszBgProgressImageData,
                                    uiBgProgressDataSize);

    NDPicture* pkFgProgressPic = new NDPicture;
    pkFgProgressPic->Initialization(pszFgProgressImageData,
                                    uiFgProgressDataSize);

    m_pkBackgroundImage->SetPicture(pkBgPicture);
    m_pkUnzipProgress->SetPicture(pkBgProgressPic, pkFgProgressPic);
    m_pkProgressBgImage->SetPicture(pkEffectPicture);
    m_pkUnzipTextImage->SetPicture(pkUnzipTextPicture);
    //m_pkUnzipTextImage->SetFrameRect(kUnzipTextRect);

    //m_pkUILayer->SetZOrder(1000);
    GetUIRootNew()->AddChild(m_pkUILayer);
    showProgress(false);
    m_pkUILayer->AddChild(m_pkBackgroundImage, 0);
    m_pkUILayer->AddChild(m_pkProgressBgImage, 2);
    m_pkUILayer->AddChild(m_pkUnzipProgress, 1);
}