bool DbViewerPanel::ImportDb(const wxString& sqlFile, Database* pDb) { DatabaseLayerPtr pDbLayer(NULL); LogDialog dialog( this );//TODO:Doresit parenta dialog.Show(); try { wxFileInputStream input(sqlFile); wxTextInputStream text( input ); text.SetStringSeparators(wxT(";")); wxString command = wxT(""); pDbLayer = pDb->GetDbAdapter()->GetDatabaseLayer(pDb->GetName()); pDbLayer->BeginTransaction(); wxString useSql = pDb->GetDbAdapter()->GetUseDb(pDb->GetName()); if (!useSql.IsEmpty()) pDbLayer->RunQuery(wxString::Format(wxT("USE %s"), pDb->GetName().c_str())); while (!input.Eof()) { wxString line = text.ReadLine(); //dialog.AppendText(line); int index = line.Find(wxT("--")); if (index != wxNOT_FOUND) line = line.Mid(0,index); command.append(line); if (line.Find(wxT(";")) != wxNOT_FOUND) { dialog.AppendSeparator(); dialog.AppendComment(wxT("Run SQL command:")); dialog.AppendText(command); pDbLayer->RunQuery(command); dialog.AppendComment(_("Successful!")); command.clear(); } } pDbLayer->Commit(); pDbLayer->Close(); } catch (DatabaseLayerException& e) { if (pDbLayer) { pDbLayer->RollBack(); pDbLayer->Close(); } wxString errorMessage = wxString::Format(_("Error (%d): %s"), e.GetErrorCode(), e.GetErrorMessage().c_str()); dialog.AppendComment(_("Fail!")); dialog.AppendComment(errorMessage); wxMessageDialog dlg(this,errorMessage,_("DB Error"),wxOK | wxCENTER | wxICON_ERROR); dlg.ShowModal(); } catch( ... ) { if (pDbLayer) { pDbLayer->RollBack(); pDbLayer->Close(); } wxMessageDialog dlg(this,_("Unknown error."),_("DB Error"),wxOK | wxCENTER | wxICON_ERROR); dlg.ShowModal(); } dialog.EnableClose(true); dialog.ShowModal(); return false; }
void AudioNode::updateChannelsForInputs() { for (unsigned i = 0; i < m_inputs.size(); ++i) input(i)->changedOutputs(); }
void StabilizedSqicInterface::generateNativeCode(std::ostream& file) const { // Dump the contents of resource_sqic, but filter out the C bind stuff std::string resource_sqic_input(resource_sqic); std::istringstream stream(resource_sqic_input); std::string line; while (std::getline(stream, line)) { size_t b_i = line.find("bind ( C, "); if (b_i!=std::string::npos) { file << line.substr(0, b_i) << std::endl; } else { file << line << std::endl; } } file.precision(std::numeric_limits<double>::digits10+2); file << std::scientific; // This is really only to force a decimal dot, // would be better if it can be avoided file << "program exported" << std::endl; file << " use SQICModule" << std::endl; file << " implicit none" << std::endl; file << " integer(ip) :: m, n, nInf, nnH, nnzH, nnzA, nS, lenpi" << std::endl; file << " real(rp) :: Obj, mu" << std::endl; file << " real(rp), allocatable:: bl(:), bu(:), x(:), valA(:), valH(:) , pi(:), piE(:), rc(:)" << std::endl; file << " integer(ip), allocatable:: indA(:), locA(:), indH(:), locH(:), hEtype(:), hs(:)" << std::endl; int n = n_; int m = nc_+1; int nnzA=formatA_.output().size(); int nnzH=input(STABILIZED_QP_SOLVER_H).size(); file << " n = " << n << std::endl; file << " m = " << m << std::endl; file << " nnzA = " << nnzA << std::endl; file << " nnzH = " << nnzH << std::endl; file << " allocate ( bl(n+m), bu(n+m) )" << std::endl; file << " allocate ( hEtype(n+m) )" << std::endl; file << " allocate ( locA(n+1), valA(nnzA), indA(nnzA) )" << std::endl; file << " allocate ( pi(m), piE(m), rc(n+m), x(n+m) )" << std::endl; file << " allocate ( hs(n+m) )" << std::endl; file << " allocate ( valH(nnzH), locH(n+1), indH(nnzH) )" << std::endl; for (int i=0;i<indA_.size();++i) { file << " indA(" << i +1 << ") = " << indA_[i] << std::endl; } for (int i=0;i<locA_.size();++i) { file << " locA(" << i +1 << ") = " << locA_[i] << std::endl; } for (int i=0;i<formatA_.output().size();++i) { file << " valA(" << i +1 << ") = " << formatA_.output().at(i) << std::endl; } for (int i=0;i<bl_.size();++i) { file << " bl(" << i +1 << ") = " << bl_[i] << std::endl; file << " bu(" << i +1 << ") = " << bu_[i] << std::endl; } for (int i=0;i<hEtype_.size();++i) { file << " hEtype(" << i +1 << ") = " << hEtype_[i] << std::endl; } for (int i=0;i<hs_.size();++i) { file << " hs(" << i +1 << ") = " << hs_[i] << std::endl; } for (int i=0;i<indH_.size();++i) { file << " indH(" << i +1 << ") = " << indH_[i] << std::endl; } for (int i=0;i<locH_.size();++i) { file << " locH(" << i +1 << ") = " << locH_[i] << std::endl; } for (int i=0;i<input(STABILIZED_QP_SOLVER_H).size();++i) { file << " valH(" << i +1 << ") = " << input(STABILIZED_QP_SOLVER_H).at(i) << std::endl; } for (int i=0;i<input(QP_SOLVER_X0).size();++i) { file << " x(" << i +1 << ") = " << input(QP_SOLVER_X0).at(i) << std::endl; } for (int i=0;i<pi_.size();++i) { file << " pi(" << i +1 << ") = " << 0 << std::endl; //pi_[i] << std::endl; } for (int i=0;i<rc_.size();++i) { file << " rc(" << i +1 << ") = " << ((i<input(QP_SOLVER_LAM_X0).size()) ? -input(QP_SOLVER_LAM_X0).at(i) : 0.0) << std::endl; } file << " lenpi = " << m << std::endl; file << " mu = " << input(STABILIZED_QP_SOLVER_MUR).at(0) << std::endl; for (int i=0;i<piE_.size();++i) { file << " piE(" << i +1 << ") = " << piE_[i] << std::endl; } file << " call wsqic (m, n, nnzA, indA, locA, valA, bl, bu, hEtype, hs, x, " << "pi, rc, nnzH, indH, locH, valH)" << std::endl; /**for (int i=0;i<input(QP_SOLVER_X0).size();++i) { file << " x(" << i +1 << ") = " << input(QP_SOLVER_X0).at(i) << std::endl; } for (int i=0;i<pi_.size();++i) { file << " pi(" << i +1 << ") = " << pi_[i] << std::endl; } for (int i=0;i<rc_.size();++i) { file << " rc(" << i +1 << ") = " << ((i<input(QP_SOLVER_LAM_X0).size()) ? -input(QP_SOLVER_LAM_X0).at(i) : 0.0) << std::endl; }*/ file << " call sqicSolveStabilized (Obj, mu, lenpi, piE)" << std::endl; /**for (int i=0;i<input(QP_SOLVER_X0).size();++i) { file << " x(" << i +1 << ") = " << input(QP_SOLVER_X0).at(i) << std::endl; } for (int i=0;i<pi_.size();++i) { file << " pi(" << i +1 << ") = " << pi_[i] << std::endl; } for (int i=0;i<rc_.size();++i) { file << " rc(" << i +1 << ") = " << ((i<input(QP_SOLVER_LAM_X0).size()) ? -input(QP_SOLVER_LAM_X0).at(i) : 0.0) << std::endl; } file << " call sqicSolveStabilized (Obj, mu, lenpi, piE)" << std::endl;**/ file << " deallocate ( bl, bu )" << std::endl; file << " deallocate ( hEtype )" << std::endl; file << " deallocate ( locA, valA, indA )" << std::endl; file << " deallocate ( pi, piE, rc, x )" << std::endl; file << " deallocate ( valH, locH, indH )" << std::endl; file << " call sqicDestroy()" << std::endl; file << "end program exported" << std::endl; }
int main(int argc, char **argv) { #ifdef CONSOLE_APPLICATION QApplication app(argc, argv, QApplication::Tty); #else QApplication app(argc, argv); #endif #ifdef DO_QWS_DEBUGGING qt_show_painter_debug_output = false; #endif DeviceType type = WidgetType; bool checkers_background = true; QImage::Format imageFormat = QImage::Format_ARGB32_Premultiplied; QLocale::setDefault(QLocale::c()); QStringList files; bool interactive = false; bool printdlg = false; bool highres = false; bool show_cmp = false; int width = 800, height = 800; bool verboseMode = false; #ifndef QT_NO_OPENGL QGLFormat f = QGLFormat::defaultFormat(); f.setSampleBuffers(true); f.setStencil(true); f.setAlpha(true); f.setAlphaBufferSize(8); QGLFormat::setDefaultFormat(f); #endif char *arg; for (int i=1; i<argc; ++i) { arg = argv[i]; if (*arg == '-') { QString option = QString(arg + 1).toLower(); if (option == "widget") type = WidgetType; else if (option == "bitmap") type = BitmapType; else if (option == "pixmap") type = PixmapType; else if (option == "image") type = ImageType; else if (option == "imageformat") { Q_ASSERT_X(i + 1 < argc, "main", "-imageformat must be followed by a value"); QString format = QString(argv[++i]).toLower(); imageFormat = QImage::Format_Invalid; static const int formatCount = sizeof(imageFormats) / sizeof(imageFormats[0]); for (int ff = 0; ff < formatCount; ++ff) { if (QLatin1String(imageFormats[ff].name) == format) { imageFormat = imageFormats[ff].format; break; } } if (imageFormat == QImage::Format_Invalid) { printf("Invalid image format. Available formats are:\n"); for (int ff = 0; ff < formatCount; ++ff) printf("\t%s\n", imageFormats[ff].name); return -1; } } else if (option == "imagemono") type = ImageMonoType; else if (option == "imagewidget") type = ImageWidgetType; #ifndef QT_NO_OPENGL else if (option == "opengl") type = OpenGLType; else if (option == "pbuffer") type = OpenGLPBufferType; #endif #ifdef USE_CUSTOM_DEVICE else if (option == "customdevice") type = CustomDeviceType; else if (option == "customwidget") type = CustomWidgetType; #endif else if (option == "pdf") type = PdfType; else if (option == "ps") type = PsType; else if (option == "picture") type = PictureType; else if (option == "printer") type = PrinterType; else if (option == "highres") { type = PrinterType; highres = true; } else if (option == "printdialog") { type = PrinterType; printdlg = true; } else if (option == "grab") type = GrabType; else if (option == "i") interactive = true; else if (option == "v") verboseMode = true; else if (option == "commands") { displayCommands(); return 0; } else if (option == "w") { Q_ASSERT_X(i + 1 < argc, "main", "-w must be followed by a value"); width = atoi(argv[++i]); } else if (option == "h") { Q_ASSERT_X(i + 1 < argc, "main", "-h must be followed by a value"); height = atoi(argv[++i]); } else if (option == "cmp") { show_cmp = true; } else if (option == "bg-white") { checkers_background = false; } } else { #if defined (Q_WS_WIN) QString input = QString::fromLocal8Bit(argv[i]); if (input.indexOf('*') >= 0) { QFileInfo info(input); QDir dir = info.dir(); QFileInfoList infos = dir.entryInfoList(QStringList(info.fileName())); for (int ii=0; ii<infos.size(); ++ii) files.append(infos.at(ii).absoluteFilePath()); } else { files.append(input); } #else files.append(QString(argv[i])); #endif } } PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); QWidget *activeWidget = 0; if (interactive) { runInteractive(); if (!files.isEmpty()) interactive_widget->load(files.at(0)); } else if (files.isEmpty()) { printHelp(); return 0; } else { for (int j=0; j<files.size(); ++j) { const QString &fileName = files.at(j); QStringList content; QFile file(fileName); QFileInfo fileinfo(file); if (file.open(QIODevice::ReadOnly)) { QTextStream textFile(&file); QString script = textFile.readAll(); content = script.split("\n", QString::SkipEmptyParts); } else { printf("failed to read file: '%s'\n", qPrintable(fileinfo.absoluteFilePath())); continue; } pcmd.setContents(content); if (show_cmp) { QString pmFile = QString(files.at(j)).replace(".qps", "_qps") + ".png"; qDebug() << pmFile << QFileInfo(pmFile).exists(); QPixmap pixmap(pmFile); if (!pixmap.isNull()) { QLabel *label = createLabel(); label->setWindowTitle("VERIFY: " + pmFile); label->setPixmap(pixmap); label->show(); } } switch (type) { case WidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } case ImageWidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } #ifndef QT_NO_OPENGL case OpenGLPBufferType: { QGLPixelBuffer pbuffer(QSize(width, height)); QPainter pt(&pbuffer); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image = pbuffer.toImage(); QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case OpenGLType: { OnScreenWidget<QGLWidget> *qGLWidget = new OnScreenWidget<QGLWidget>(files.at(j)); qGLWidget->setVerboseMode(verboseMode); qGLWidget->setType(type); qGLWidget->setCheckersBackground(checkers_background); qGLWidget->m_commands = content; qGLWidget->resize(width, height); qGLWidget->show(); activeWidget = qGLWidget; break; } #else case OpenGLType: printf("OpenGL type not supported in this Qt build\n"); break; #endif #ifdef USE_CUSTOM_DEVICE case CustomDeviceType: { CustomPaintDevice custom(width, height); QPainter pt; pt.begin(&custom); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage *img = custom.image(); if (img) { QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(*img)); label->resize(label->sizeHint()); label->show(); activeWidget = label; img->save("custom_output_pixmap.png", "PNG"); } else { custom.save("custom_output_pixmap.png", "PNG"); } break; } case CustomWidgetType: { OnScreenWidget<CustomWidget> *cWidget = new OnScreenWidget<CustomWidget>; cWidget->setVerboseMode(verboseMode); cWidget->setType(type); cWidget->setCheckersBackground(checkers_background); cWidget->m_filename = files.at(j); cWidget->setWindowTitle(fileinfo.filePath()); cWidget->m_commands = content; cWidget->resize(width, height); cWidget->show(); activeWidget = cWidget; break; } #endif case PixmapType: { QPixmap pixmap(width, height); pixmap.fill(Qt::white); QPainter pt(&pixmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); pixmap.save("output_pixmap.png", "PNG"); break; } case BitmapType: { QBitmap bitmap(width, height); QPainter pt(&bitmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); bitmap.save("output_bitmap.png", "PNG"); QLabel *label = createLabel(); label->setPixmap(bitmap); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case ImageMonoType: case ImageType: { qDebug() << "Creating image"; QImage image(width, height, type == ImageMonoType ? QImage::Format_MonoLSB : imageFormat); image.fill(0); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); image.convertToFormat(QImage::Format_ARGB32).save("output_image.png", "PNG"); #ifndef CONSOLE_APPLICATION QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; #endif break; } case PictureType: { QPicture pic; QPainter pt(&pic); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(0); pt.begin(&image); pt.drawPicture(0, 0, pic); pt.end(); QLabel *label = createLabel(); label->setWindowTitle(fileinfo.absolutePath()); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case PrinterType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); QString file = QString(files.at(j)).replace(".", "_") + ".ps"; QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); if (printdlg) { QPrintDialog printDialog(&p, 0); if (printDialog.exec() != QDialog::Accepted) break; } else { p.setOutputFileName(file); } QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); if (!printdlg) { printf("wrote file: %s\n", qPrintable(file)); } Q_ASSERT(!p.paintingActive()); #endif break; } case PsType: case PdfType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); bool ps = type == PsType; QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); QFileInfo input(files.at(j)); QString file = QString("%1_%2.%3") .arg(input.baseName()) .arg(input.suffix()) .arg(ps ? "ps" : "pdf"); p.setOutputFormat(ps ? QPrinter::PdfFormat : QPrinter::PostScriptFormat); p.setOutputFileName(file); p.setPageSize(QPrinter::A4); QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); printf("write file: %s\n", qPrintable(file)); #endif break; } case GrabType: { QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(QColor(Qt::white).rgb()); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image1(width, height, QImage::Format_RGB32); image1.fill(QColor(Qt::white).rgb()); QPainter pt1(&image1); pt1.drawImage(QPointF(0, 0), image); pt1.end(); QString filename = QString(files.at(j)).replace(".qps", "_qps") + ".png"; image1.save(filename, "PNG"); printf("%s grabbed to %s\n", qPrintable(files.at(j)), qPrintable(filename)); break; } default: break; } } } #ifndef CONSOLE_APPLICATION if (activeWidget || interactive) { QObject::connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit())); app.exec(); } delete activeWidget; #endif delete interactive_widget; return 0; }
status_t BnGraphicBufferProducer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case REQUEST_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferIdx = data.readInt32(); sp<GraphicBuffer> buffer; int result = requestBuffer(bufferIdx, &buffer); reply->writeInt32(buffer != 0); if (buffer != 0) { reply->write(*buffer); } reply->writeInt32(result); return NO_ERROR; } break; case SET_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferCount = data.readInt32(); int result = setBufferCount(bufferCount); reply->writeInt32(result); return NO_ERROR; } break; case DEQUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool async = data.readInt32(); uint32_t w = data.readInt32(); uint32_t h = data.readInt32(); uint32_t format = data.readInt32(); uint32_t usage = data.readInt32(); int buf; sp<Fence> fence; int result = dequeueBuffer(&buf, &fence, async, w, h, format, usage); reply->writeInt32(buf); reply->writeInt32(fence != NULL); if (fence != NULL) { reply->write(*fence); } reply->writeInt32(result); return NO_ERROR; } break; case QUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); QueueBufferInput input(data); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); status_t result = queueBuffer(buf, input, output); reply->writeInt32(result); return NO_ERROR; } break; case CANCEL_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); sp<Fence> fence = new Fence(); data.read(*fence.get()); cancelBuffer(buf, fence); return NO_ERROR; } break; case QUERY: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int value; int what = data.readInt32(); int res = query(what, &value); reply->writeInt32(value); reply->writeInt32(res); return NO_ERROR; } break; case CONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<IBinder> token = data.readStrongBinder(); int api = data.readInt32(); bool producerControlledByApp = data.readInt32(); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); status_t res = connect(token, api, producerControlledByApp, output); reply->writeInt32(res); return NO_ERROR; } break; case DISCONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int api = data.readInt32(); status_t res = disconnect(api); reply->writeInt32(res); return NO_ERROR; } break; } return BBinder::onTransact(code, data, reply, flags); }
NS_IMETHODIMP nsAutoCompleteController::HandleDelete(bool *_retval) { *_retval = PR_FALSE; if (!mInput) return NS_OK; nsCOMPtr<nsIAutoCompleteInput> input(mInput); bool isOpen = false; input->GetPopupOpen(&isOpen); if (!isOpen || mRowCount <= 0) { // Nothing left to delete, proceed as normal HandleText(); return NS_OK; } nsCOMPtr<nsIAutoCompletePopup> popup; input->GetPopup(getter_AddRefs(popup)); PRInt32 index, searchIndex, rowIndex; popup->GetSelectedIndex(&index); RowIndexToSearch(index, &searchIndex, &rowIndex); NS_ENSURE_TRUE(searchIndex >= 0 && rowIndex >= 0, NS_ERROR_FAILURE); nsIAutoCompleteResult *result = mResults[searchIndex]; NS_ENSURE_TRUE(result, NS_ERROR_FAILURE); nsAutoString search; input->GetSearchParam(search); // Clear the row in our result and in the DB. result->RemoveValueAt(rowIndex, PR_TRUE); --mRowCount; // We removed it, so make sure we cancel the event that triggered this call. *_retval = PR_TRUE; // Unselect the current item. popup->SetSelectedIndex(-1); // Tell the tree that the row count changed. if (mTree) mTree->RowCountChanged(mRowCount, -1); // Adjust index, if needed. if (index >= (PRInt32)mRowCount) index = mRowCount - 1; if (mRowCount > 0) { // There are still rows in the popup, select the current index again. popup->SetSelectedIndex(index); // Complete to the new current value. bool shouldComplete = false; mInput->GetCompleteDefaultIndex(&shouldComplete); if (shouldComplete) { nsAutoString value; if (NS_SUCCEEDED(GetResultValueAt(index, PR_TRUE, value))) { CompleteValue(value); } } // Invalidate the popup. popup->Invalidate(); } else { // Nothing left in the popup, clear any pending search timers and // close the popup. ClearSearchTimer(); ClosePopup(); } return NS_OK; }
void SpawnMonitor::loadSpawnPoints() { QString fileName; fileName = m_zoneName + ".sp"; QFileInfo fileInfo = m_dataLocMgr->findExistingFile("spawnpoints", fileName, false); if (!fileInfo.exists()) { seqWarn("Can't find spawn point file %s", (const char*)fileInfo.absFilePath()); return; } fileName = fileInfo.absFilePath(); QFile spFile(fileName); if (!spFile.open(IO_ReadOnly)) { seqWarn( "Can't open spawn point file %s", (const char*)fileName ); return; } QTextStream input( &spFile ); int16_t x, y, z; unsigned long diffTime; uint32_t count; QString name; while (!input.atEnd()) { input >> x; input >> y; input >> z; input >> diffTime; input >> count; name = input.readLine(); name = name.stripWhiteSpace(); EQPoint loc(x, y, z); SpawnPoint* p = new SpawnPoint( 0, loc, name, diffTime, count ); if (p) { QString key = p->key(); if (!m_points.find(key)) { m_points.insert(key, p); emit newSpawnPoint(p); } else { seqWarn("Warning: spawn point key already in use!"); delete p; } } } seqInfo("Loaded spawn points: %s", (const char*)fileName); m_modified = false; }
void game::show_options() { // Remember what the options were originally so we can restore them if player cancels. option_table OPTIONS_OLD = OPTIONS; WINDOW* w_options_border = newwin(FULL_SCREEN_HEIGHT, FULL_SCREEN_WIDTH, (TERMY > FULL_SCREEN_HEIGHT) ? (TERMY-FULL_SCREEN_HEIGHT)/2 : 0, (TERMX > FULL_SCREEN_WIDTH) ? (TERMX-FULL_SCREEN_WIDTH)/2 : 0); WINDOW* w_options = newwin(FULL_SCREEN_HEIGHT-2, FULL_SCREEN_WIDTH-2, 1 + ((TERMY > FULL_SCREEN_HEIGHT) ? (TERMY-FULL_SCREEN_HEIGHT)/2 : 0), 1 + ((TERMX > FULL_SCREEN_WIDTH) ? (TERMX-FULL_SCREEN_WIDTH)/2 : 0)); int offset = 1; const int MAX_LINE = 22; int line = 0; char ch = ' '; bool changed_options = false; bool needs_refresh = true; wborder(w_options_border, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX, LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX); mvwprintz(w_options_border, 0, 36, c_ltred, _(" OPTIONS ")); wrefresh(w_options_border); do { // TODO: change instructions if(needs_refresh) { werase(w_options); // because those texts use their own \n, do not fold so use a large enough width like 999 fold_and_print(w_options, 0, 40, 999, c_white, _("Use up/down keys to scroll through\navailable options.\nUse left/right keys to toggle.\nPress ESC or q to return.")); // highlight options for option descriptions fold_and_print(w_options, 5, 40, 999, c_white, option_desc(option_key(offset + line)).c_str()); needs_refresh = false; } // Clear the lines for(int i = 0; i < 25; i++) { mvwprintz(w_options, i, 0, c_black, " "); } int valid_option_count = 0; // display options for(int i = 0; i < 26 && offset + i < NUM_OPTION_KEYS; i++) { valid_option_count++; mvwprintz(w_options, i, 0, c_white, "%s: ", option_name(option_key(offset + i)).c_str()); if(option_is_bool(option_key(offset + i))) { bool on = OPTIONS[ option_key(offset + i) ]; if(i == line) { mvwprintz(w_options, i, 30, hilite(c_ltcyan), (on ? _("True") : _("False"))); } else { mvwprintz(w_options, i, 30, (on ? c_ltgreen : c_ltred), (on ? _("True") : _("False"))); } } else { char option_val = OPTIONS[ option_key(offset + i) ]; if(i == line) { mvwprintz(w_options, i, 30, hilite(c_ltcyan), "%d", option_val); } else { mvwprintz(w_options, i, 30, c_ltgreen, "%d", option_val); } } } wrefresh(w_options); ch = input(); needs_refresh = true; switch(ch) { // move up and down case 'j': line++; if(line > MAX_LINE/2 && offset + 1 < NUM_OPTION_KEYS - MAX_LINE) { ++offset; --line; } if(line > MAX_LINE) { line = 0; offset = 1; } break; case 'k': line--; if(line < MAX_LINE/2 && offset > 1) { --offset; ++line; } if(line < 0) { line = MAX_LINE; offset = NUM_OPTION_KEYS - MAX_LINE - 1; } break; // toggle options with left/right keys case 'h': if(option_is_bool(option_key(offset + line))) { OPTIONS[ option_key(offset + line) ] = !(OPTIONS[ option_key(offset + line) ]); } else { OPTIONS[ option_key(offset + line) ]--; if((OPTIONS[ option_key(offset + line) ]) < option_min_options(option_key(offset + line))) { OPTIONS[ option_key(offset + line) ] = option_max_options(option_key(offset + line)) - 1; } } changed_options = true; break; case 'l': if(option_is_bool(option_key(offset + line))) { OPTIONS[ option_key(offset + line) ] = !(OPTIONS[ option_key(offset + line) ]); } else { OPTIONS[ option_key(offset + line) ]++; if((OPTIONS[ option_key(offset + line) ]) >= option_max_options(option_key(offset + line))) { OPTIONS[ option_key(offset + line) ] = option_min_options(option_key(offset + line)); } } changed_options = true; break; } if(changed_options && OPTIONS[OPT_SEASON_LENGTH] < 1) { OPTIONS[OPT_SEASON_LENGTH]=option_max_options(OPT_SEASON_LENGTH)-1; } } while(ch != 'q' && ch != 'Q' && ch != KEY_ESCAPE); if(changed_options) { if(query_yn(_("Save changes?"))) { save_options(); trigdist=(OPTIONS[OPT_CIRCLEDIST] ? true : false); } else { // Player wants to keep the old options. Revert! OPTIONS = OPTIONS_OLD; } } werase(w_options); }
void ConfigParser::normalizeInput( Json::Value& json, const arbiter::Arbiter& arbiter) { Json::Value& input(json["input"]); const bool verbose(json["verbose"].asBool()); const std::string extension( input.isString() ? arbiter::Arbiter::getExtension(input.asString()) : ""); const bool isInferencePath(extension == "entwine-inference"); if (!isInferencePath) { // The input source is a path or array of paths. First, we possibly // need to expand out directories into their containing files. FileInfoList fileInfo; auto insert([&fileInfo, &arbiter, verbose](std::string in) { Paths current(arbiter.resolve(in, verbose)); for (const auto& c : current) fileInfo.emplace_back(c); }); if (input.isArray()) { for (const auto& entry : input) { if (entry.isString()) { insert(directorify(entry.asString())); } else { fileInfo.emplace_back(entry); } } } else if (input.isString()) { insert(directorify(input.asString())); } else return; // Now, we have an array of files (no directories). // // Reset our input with our resolved paths. config.input.fileInfo will // be an array of strings, containing only paths with no associated // information. input = Json::Value(); input.resize(fileInfo.size()); for (std::size_t i(0); i < fileInfo.size(); ++i) { input[Json::ArrayIndex(i)] = fileInfo[i].toJson(); } } else if (isInferencePath) { const std::string path(input.asString()); const Json::Value inference(parse(arbiter.get(path))); input = inference["fileInfo"]; if (!json.isMember("schema")) json["schema"] = inference["schema"]; if (!json.isMember("bounds")) json["bounds"] = inference["bounds"]; if (!json.isMember("numPointsHint")) { json["numPointsHint"] = inference["numPoints"]; } if (inference.isMember("reprojection")) { json["reprojection"] = inference["reprojection"]; } if (Delta::existsIn(inference)) { if (!json.isMember("scale")) json["scale"] = inference["scale"]; if (!json.isMember("offset")) json["offset"] = inference["offset"]; } } }
int main() { double Ts [] = { 7.000000000000001e-02, 8.000000000000000e-02, 9.000000000000000e-02, 9.999999999999999e-02, 1.100000000000000e-01, 1.200000000000000e-01, 1.300000000000000e-01, 1.400000000000000e-01, 1.500000000000000e-01, 1.600000000000000e-01, 1.700000000000000e-01, 1.800000000000000e-01, 1.900000000000000e-01 }; double Us [] = { 2.359999999999992, 2.329999999999993, 2.299999999999994, 2.279999999999994, 2.259999999999994, 2.239999999999995, 2.219999999999995, 2.199999999999996, 2.179999999999996, 2.169999999999996, 2.149999999999997, 2.129999999999997, 2.119999999999997 }; int NT = sizeof(Ts)/sizeof(double); GRID grid("params"); Result result(&grid); grid.assign_omega(result.omega); Input input("params"); double t = 0.5; // always set a default value in case parameter is not found in the input file!!! input.ReadParam(t,"CHM::t"); InitDelta( DOStypes::SemiCircle, // type of DOS grid.get_N(), // total number of omega grid points 0.5, 0.0, 0.01, t, // hybridization-V, chemical potential-mu (defines the omega shift), broadening eta, and hopping amplitude result.omega, result.Delta); // omega-grid array and the array in which Delta will be stored InitDOS( DOStypes::SemiCircle, // type of DOS t, // hopping amplitude grid.get_N(), result.omega, result.NIDOS); // total number of omega grid points, omega-grid array, the array in which NIDOS will be stored double n = 0.5; // always set a default value in case parameter is not found in the input file!!! input.ReadParam(n,"main::n"); result.n = n; CHM chm("params"); for (int i=0; i<NT; i++) { chm.SetParams(Us[i],Ts[i],t); chm.Run(&result); char FN[50]; sprintf( FN, "CHM.U%.3f.T%.3f", chm.get_U(), chm.get_T() ); result.PrintResult(FN); FILE* rhocFile = fopen("rhoc","a"); double rhoc = result.Conductivity( chm.get_T() , 0.5*chm.get_U() , 400.0, 400.0, 10000.0 ) ; fprintf(rhocFile, "%.15le %.15le %.15le\n", chm.get_T(), rhoc, 1/rhoc); fclose(rhocFile); for (double dU=-0.3; dU<0.31; dU+=0.04) { chm.SetParams(Us[i]+dU,Ts[i],t); chm.Run(&result); char FN[50]; sprintf( FN, "CHM.U%.3f.T%.3f", chm.get_U(), chm.get_T() ); result.PrintResult(FN); char rhoFN[50]; sprintf( rhoFN, "rho.dU%.3f", dU ); FILE* rhoFile = fopen(rhoFN,"a"); double rho = result.Conductivity( chm.get_T() , 0.5*chm.get_U() , 400.0, 400.0, 10000.0 ) ; fprintf(rhoFile, "%.15le %.15le %.15le %.15le %.15le\n", chm.get_T(), rho, 1.0/rho, rho/rhoc, rhoc/rho); fclose(rhoFile); } } return 0; }
void PrimitiveShapeClassifier::process(const sensor_msgs::PointCloud2::ConstPtr& ros_cloud, const sensor_msgs::PointCloud2::ConstPtr& ros_normal, const jsk_recognition_msgs::ClusterPointIndices::ConstPtr& ros_indices, const jsk_recognition_msgs::PolygonArray::ConstPtr& ros_polygons) { boost::mutex::scoped_lock lock(mutex_); if (!checkFrameId(ros_cloud, ros_normal, ros_indices, ros_polygons)) return; pcl::PointCloud<PointT>::Ptr input(new pcl::PointCloud<PointT>); pcl::fromROSMsg(*ros_cloud, *input); pcl::PointCloud<pcl::Normal>::Ptr normal(new pcl::PointCloud<pcl::Normal>); pcl::fromROSMsg(*ros_normal, *normal); pcl::ExtractIndices<PointT> ext_input; ext_input.setInputCloud(input); pcl::ExtractIndices<pcl::Normal> ext_normal; ext_normal.setInputCloud(normal); std::vector<jsk_recognition_utils::Polygon::Ptr> polygons = jsk_recognition_utils::Polygon::fromROSMsg(*ros_polygons); jsk_recognition_msgs::ClassificationResult result; result.header = ros_cloud->header; result.classifier = "primitive_shape_classifier"; result.target_names.push_back("box"); result.target_names.push_back("circle"); result.target_names.push_back("other"); pcl::PointCloud<PointT>::Ptr projected_cloud(new pcl::PointCloud<PointT>); std::vector<pcl::PointIndices::Ptr> boundary_indices; NODELET_DEBUG_STREAM("Cluster num: " << ros_indices->cluster_indices.size()); for (size_t i = 0; i < ros_indices->cluster_indices.size(); ++i) { pcl::PointIndices::Ptr indices(new pcl::PointIndices); indices->indices = ros_indices->cluster_indices[i].indices; NODELET_DEBUG_STREAM("Estimating cluster #" << i << " (" << indices->indices.size() << " points)"); pcl::PointCloud<PointT>::Ptr cluster_cloud(new pcl::PointCloud<PointT>); ext_input.setIndices(indices); ext_input.filter(*cluster_cloud); pcl::PointCloud<pcl::Normal>::Ptr cluster_normal(new pcl::PointCloud<pcl::Normal>); ext_normal.setIndices(indices); ext_normal.filter(*cluster_normal); pcl::ModelCoefficients::Ptr support_plane(new pcl::ModelCoefficients); if (!getSupportPlane(cluster_cloud, polygons, support_plane)) { NODELET_ERROR_STREAM("cloud " << i << " has no support plane. skipped"); continue; } pcl::PointIndices::Ptr b(new pcl::PointIndices); pcl::PointCloud<PointT>::Ptr pc(new pcl::PointCloud<PointT>); float circle_likelihood, box_likelihood; estimate(cluster_cloud, cluster_normal, support_plane, b, pc, circle_likelihood, box_likelihood); boundary_indices.push_back(std::move(b)); *projected_cloud += *pc; if (circle_likelihood > circle_threshold_) { // circle result.labels.push_back(1); result.label_names.push_back("circle"); result.label_proba.push_back(circle_likelihood); } else if (box_likelihood > box_threshold_) { // box result.labels.push_back(0); result.label_names.push_back("box"); result.label_proba.push_back(box_likelihood); } else { // other result.labels.push_back(3); result.label_names.push_back("other"); result.label_proba.push_back(0.0); } } // publish results sensor_msgs::PointCloud2 ros_projected_cloud; pcl::toROSMsg(*projected_cloud, ros_projected_cloud); ros_projected_cloud.header = ros_cloud->header; pub_projected_cloud_.publish(ros_projected_cloud); jsk_recognition_msgs::ClusterPointIndices ros_boundary_indices; ros_boundary_indices.header = ros_cloud->header; for (size_t i = 0; i < boundary_indices.size(); ++i) { pcl_msgs::PointIndices ri; pcl_conversions::moveFromPCL(*boundary_indices[i], ri); ros_boundary_indices.cluster_indices.push_back(ri); } pub_boundary_indices_.publish(ros_boundary_indices); pub_class_.publish(result); }
int main ( int argc, const char* argv[] ) { if(argc <= 2) { std::cerr << "You need to specify at least the output file and one input file." << std::endl << "Example: " << argv[0] << " output_file input_file" << std::endl; return 1; } try { std::string headername (argv[1]); std::vector<std::string> input_files; for(int i = 2; i < argc; i++) { input_files.push_back(std::string(argv[i])); } /* Process */ std::ofstream output ( headername, std::ios::out | std::ios::trunc| std::ios::binary ); /* Use buffer */ char outbuffer[BUFFER_SIZE]; output.rdbuf()->pubsetbuf ( outbuffer, BUFFER_SIZE ); if ( !output ) throw std::runtime_error ( "Failed to create output file!" ); /* Show status */ std::cout << "Build : file '" << headername << "'..." << std::endl; /* Get base name of file */ headername = GetFileBasename ( headername ); /* Data string stream */ std::ostringstream data; /* Write header start when wanted */ defineheader_start ( data, headername, /*use macro*/ true, /* const */ true ); /* Write macros */ definemacros ( data ); /* Common input buffer */ char inbuffer[BUFFER_SIZE]; for ( auto iter = input_files.begin(); iter != input_files.end(); iter++ ) { std::string &file = *iter; //std::string fileext = GetFileExtension ( file ); std::ifstream input ( file, std::ios::in | std::ios::binary | std::ios::ate ); input.rdbuf()->pubsetbuf ( inbuffer, BUFFER_SIZE ); if ( input.is_open() ) { /* Show status */ std::cout << "Process: file '" << file << "'..." << std::endl; /* Remove extension */ file = removeExtension(file); std::transform(file.begin(), file.end(), file.begin(), ::tolower); std::transform(file.begin(), file.end(), file.begin(), toUnderscores); /* Process file */ definefile ( data, input, file, true ); } else { /* Only show warning, other files need to be processed */ std::cout << "Warning: input file '" << file << "' failed to open." << std::endl; } } /* Write header end when wanted */ defineheader_end ( data, headername ); /* Write data to output file */ output.seekp ( 0, std::ios::beg ); output << data.str(); } catch ( std::exception& e ) { std::cerr << "Error: " << e.what() << std::endl; } catch ( ... ) { std::cerr << "Error: Exception of unknown type!" << std::endl; } return 0; }
int KruskalWallisCommand::execute(){ try { if (abort) { if (calledHelp) { return 0; } return 2; } DesignMap designMap(designfile); //if user did not select class use first column if (mclass == "") { mclass = designMap.getDefaultClass(); m->mothurOut("\nYou did not provide a class, using " + mclass +".\n\n"); } InputData input(sharedfile, "sharedfile", nullVector); SharedRAbundVectors* lookup = input.getSharedRAbundVectors(); string lastLabel = lookup->getLabel(); //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label. set<string> processedLabels; set<string> userLabels = labels; vector<string> currentLabels = lookup->getOTUNames(); //as long as you are not at the end of the file or done wih the lines you want while((lookup != NULL) && ((allLines == 1) || (userLabels.size() != 0))) { if (m->getControl_pressed()) { delete lookup; return 0; } if(allLines == 1 || labels.count(lookup->getLabel()) == 1){ m->mothurOut(lookup->getLabel()+"\n"); vector<SharedRAbundVector*> data = lookup->getSharedRAbundVectors(); process(data, designMap, currentLabels); for (int i = 0; i < data.size(); i++) { delete data[i]; } data.clear(); processedLabels.insert(lookup->getLabel()); userLabels.erase(lookup->getLabel()); } if ((util.anyLabelsToProcess(lookup->getLabel(), userLabels, "") ) && (processedLabels.count(lastLabel) != 1)) { string saveLabel = lookup->getLabel(); delete lookup; lookup = input.getSharedRAbundVectors(lastLabel); m->mothurOut(lookup->getLabel()+"\n"); vector<SharedRAbundVector*> data = lookup->getSharedRAbundVectors(); process(data, designMap, currentLabels); for (int i = 0; i < data.size(); i++) { delete data[i]; } data.clear(); processedLabels.insert(lookup->getLabel()); userLabels.erase(lookup->getLabel()); //restore real lastlabel to save below lookup->setLabels(saveLabel); } lastLabel = lookup->getLabel(); //prevent memory leak delete lookup; if (m->getControl_pressed()) { return 0; } //get next line to process lookup = input.getSharedRAbundVectors(); } if (m->getControl_pressed()) { return 0; } //output error messages about any remaining user labels set<string>::iterator it; bool needToRun = false; for (it = userLabels.begin(); it != userLabels.end(); it++) { m->mothurOut("Your file does not include the label " + *it); if (processedLabels.count(lastLabel) != 1) { m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine(); needToRun = true; }else { m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine(); } } //run last label if you need to if (needToRun ) { delete lookup; lookup = input.getSharedRAbundVectors(lastLabel); m->mothurOut(lookup->getLabel()+"\n"); vector<SharedRAbundVector*> data = lookup->getSharedRAbundVectors(); process(data, designMap, currentLabels); for (int i = 0; i < data.size(); i++) { delete data[i]; } data.clear(); delete lookup; } //output files created by command m->mothurOut("\nOutput File Names: \n"); for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i] +"\n"); } m->mothurOutEndLine(); return 0; } catch(exception& e) { m->errorOut(e, "KruskalWallisCommand", "execute"); exit(1); } }
int main() { //User prompts //Variables to validate user input std::string input(""); //Prompts user for number of entries user will make int num_entry(0); while(true){ std::cout << "How many phone numbers would you like to enter?\n"; std::getline(std::cin, input); std::stringstream numSS(input); if(numSS >> num_entry && num_entry > 0 && num_entry <= 25){ break; } std::cout << "You've entered invalid input." << std::endl; } //Array to hold all phone entries PhoneNumber *pnums = new PhoneNumber[num_entry]; for(int n = 0; n < num_entry; n++){ std::cout << "Entry #" << n + 1 << ": " << std::endl; //Prompt user for country code int ccode(0); while(true){ std::cout << "Enter a two digit country code.\n"; std::getline(std::cin, input); std::stringstream ccodeSS(input); if((input.length() == 2) && ccodeSS >> ccode && ccode > 9 && ccode <= 99){ pnums[n].setCountry(ccode); break; } else if((input.length() == 1) && ccodeSS >> ccode && ccode > 0 && ccode < 10){ pnums[n].setCountry(ccode); break; } std::cout << "You've entered invalid input." << std::endl; } //Prompts user for area code int acode(0); while(true){ std::cout << "Enter a three digit area code.\n"; std::getline(std::cin, input); std::stringstream acodeSS(input); if((input.length() == 3) && (acodeSS >> acode) && acode > 99 && acode <= 999){ pnums[n].setArea(acode); break; } std::cout << "You've entered invalid input." << std::endl; } //Prompt user for a phone number int phone(0); while(true){ std::cout << "Enter a seven digit phone number.\n"; std::getline(std::cin, input); std::stringstream phoneSS(input); if((input.length() == 7) && (phoneSS >> phone) && phone > 1000000 && phone <= 9999999){ pnums[n].setNumber(phone); break; } std::cout << "You've entered invalid input." << std::endl; } //Prompts user for the type of phone number char num_type = {0}; while(true){ std::cout << "Enter a character for the type of the phone number: 'H' for home, 'C' for cellphone, and 'B' for business.\n"; std::getline(std::cin, input); if((input.length() == 1) && (input == "H" || input == "C" || input == "B")){ num_type = input[0]; pnums[n].setType(num_type); break; } std::cout << "You've entered invalid input." << std::endl; } //Prompts user for year of phone entry int year(0), current_year(2014); while(true){ std::cout << "Enter the year the entry was made.\n"; std::getline(std::cin, input); std::stringstream yearSS(input); if((input.length() == 4) && (yearSS >> year) && year >= 1900 && year <= current_year){ pnums[n].setYear(year); break; } std::cout << "You've entered invalid input." << std::endl; } std::cout << std::endl; pnums[n].printNumber(std::cout); pnums[n].printPhoneNumberStats(std::cout); if(pnums[n].doubleDigits()){ std::cout << "This phone number has repeated digits." << std::endl; } else{ std::cout << "This phone number is made up of unique digits." << std::endl; } std::cout << std::endl; }
NS_IMETHODIMP nsAutoCompleteController::HandleText() { if (!mInput) { // Stop all searches in case they are async. StopSearch(); // Note: if now is after blur and IME end composition, // check mInput before calling. // See https://bugzilla.mozilla.org/show_bug.cgi?id=193544#c31 NS_ERROR("Called before attaching to the control or after detaching from the control"); return NS_OK; } nsAutoString newValue; nsCOMPtr<nsIAutoCompleteInput> input(mInput); input->GetTextValue(newValue); // Note: the events occur in the following order when IME is used. // 1. composition start event(HandleStartComposition) // 2. composition end event(HandleEndComposition) // 3. input event(HandleText) // Note that the input event occurs if IME composition is cancelled, as well. // In HandleEndComposition, we are processing the popup properly. // Therefore, the input event after composition end event should do nothing. // (E.g., calling StopSearch() and ClosePopup().) // If it is not, popup is always closed after composition end. if (mIgnoreHandleText) { mIgnoreHandleText = PR_FALSE; if (newValue.Equals(mSearchString)) return NS_OK; NS_ERROR("Now is after composition end event. But the value was changed."); } // Stop all searches in case they are async. StopSearch(); if (!mInput) { // StopSearch() can call PostSearchCleanup() which might result // in a blur event, which could null out mInput, so we need to check it // again. See bug #395344 for more details return NS_OK; } bool disabled; input->GetDisableAutoComplete(&disabled); NS_ENSURE_TRUE(!disabled, NS_OK); // Don't search again if the new string is the same as the last search if (newValue.Length() > 0 && newValue.Equals(mSearchString)) return NS_OK; // Determine if the user has removed text from the end (probably by backspacing) if (newValue.Length() < mSearchString.Length() && Substring(mSearchString, 0, newValue.Length()).Equals(newValue)) { // We need to throw away previous results so we don't try to search through them again ClearResults(); mBackspaced = PR_TRUE; } else mBackspaced = PR_FALSE; mSearchString = newValue; // Don't search if the value is empty if (newValue.Length() == 0) { ClosePopup(); return NS_OK; } StartSearchTimer(); return NS_OK; }
////////////////////////////////////////////////////////////////////////////// // 슬레이어 셀프 핸들러 ////////////////////////////////////////////////////////////////////////////// void PotentialExplosion::execute(Slayer* pSlayer, SkillSlot* pSkillSlot, CEffectID_t CEffectID) throw(Error) { __BEGIN_TRY //cout << "TID[" << Thread::self() << "]" << getSkillHandlerName() << " Begin" << endl; Assert(pSlayer != NULL); Assert(pSkillSlot != NULL); SkillType_t SkillType = pSkillSlot->getSkillType(); try { Player* pPlayer = pSlayer->getPlayer(); Zone* pZone = pSlayer->getZone(); Assert(pPlayer != NULL); Assert(pZone != NULL); // 무장하고 있는 무기가 널이거나, 도가 아니라면 사용할 수 없다. Item* pItem = pSlayer->getWearItem(Slayer::WEAR_RIGHTHAND); if (pItem == NULL || pItem->getItemClass() != Item::ITEM_CLASS_BLADE) { executeSkillFailException(pSlayer, getSkillType()); //cout << "TID[" << Thread::self() << "]" << getSkillHandlerName() << " End" << endl; return; } GCSkillToSelfOK1 _GCSkillToSelfOK1; GCSkillToSelfOK2 _GCSkillToSelfOK2; SkillInfo* pSkillInfo = g_pSkillInfoManager->getSkillInfo(SkillType); SkillDomainType_t DomainType = pSkillInfo->getDomainType(); ZoneCoord_t X = pSlayer->getX(); ZoneCoord_t Y = pSlayer->getY(); int RequiredMP = (int)pSkillInfo->getConsumeMP(); bool bManaCheck = hasEnoughMana(pSlayer, RequiredMP); bool bTimeCheck = verifyRunTime(pSkillSlot); bool bRangeCheck = checkZoneLevelToUseSkill(pSlayer); bool bHitRoll = HitRoll::isSuccessMagic(pSlayer, pSkillInfo, pSkillSlot); bool bEffected = pSlayer->isFlag(Effect::EFFECT_CLASS_POTENTIAL_EXPLOSION); if (bManaCheck && bTimeCheck && bRangeCheck && bHitRoll && !bEffected) { decreaseMana(pSlayer, RequiredMP, _GCSkillToSelfOK1); SkillInput input(pSlayer, pSkillSlot); SkillOutput output; computeOutput(input, output); // HP가 반보다 작을 때는 약간 더 올라간다. // by sigi. 2002.12.3 if (pSlayer->getHP(ATTR_CURRENT) < (pSlayer->getHP(ATTR_MAX)/2)) { //output.Damage += 4; output.Damage = 8 + input.SkillLevel/15; } else { output.Damage = 3 + input.SkillLevel/20; } int diffSTR = output.Damage; int diffDEX = output.Damage; EffectPotentialExplosion* pEffect = new EffectPotentialExplosion(pSlayer); pEffect->setDeadline(output.Duration); pEffect->setDiffSTR(diffSTR); pEffect->setDiffDEX(diffDEX); pSlayer->addEffect(pEffect); pSlayer->setFlag(Effect::EFFECT_CLASS_POTENTIAL_EXPLOSION); // 이로 인하여 바뀌는 능력치를 보낸다. SLAYER_RECORD prev; pSlayer->getSlayerRecord(prev); pSlayer->initAllStat(); pSlayer->sendRealWearingInfo(); pSlayer->sendModifyInfo(prev); // 경험치를 올려준다. SkillGrade Grade = g_pSkillInfoManager->getGradeByDomainLevel(pSlayer->getSkillDomainLevel(DomainType)); Exp_t ExpUp = 10*(Grade+1); shareAttrExp(pSlayer, ExpUp, 8, 1, 1, _GCSkillToSelfOK1); increaseDomainExp(pSlayer, DomainType, pSkillInfo->getPoint(), _GCSkillToSelfOK1); //increaseSkillExp(pSlayer, DomainType, pSkillSlot, pSkillInfo, _GCSkillToSelfOK1); // 패킷을 보내준다. _GCSkillToSelfOK1.setSkillType(SkillType); _GCSkillToSelfOK1.setCEffectID(CEffectID); _GCSkillToSelfOK1.setDuration(output.Duration); _GCSkillToSelfOK2.setObjectID(pSlayer->getObjectID()); _GCSkillToSelfOK2.setSkillType(SkillType); _GCSkillToSelfOK2.setDuration(output.Duration); pPlayer->sendPacket(&_GCSkillToSelfOK1); pZone->broadcastPacket(X, Y, &_GCSkillToSelfOK2, pSlayer); // 이펙트가 붙었다고 알려준다. GCAddEffect gcAddEffect; gcAddEffect.setObjectID(pSlayer->getObjectID()); gcAddEffect.setEffectID(Effect::EFFECT_CLASS_POTENTIAL_EXPLOSION); gcAddEffect.setDuration(output.Duration); pZone->broadcastPacket(pSlayer->getX(), pSlayer->getY(), &gcAddEffect); GCOtherModifyInfo gcOtherModifyInfo; makeGCOtherModifyInfo(&gcOtherModifyInfo, pSlayer, &prev); pZone->broadcastPacket(pSlayer->getX(), pSlayer->getY(), &gcOtherModifyInfo, pSlayer); pSkillSlot->setRunTime(output.Delay); } else { executeSkillFailNormal(pSlayer, getSkillType(), NULL); } } catch (Throwable & t) { executeSkillFailException(pSlayer, getSkillType()); } //cout << "TID[" << Thread::self() << "]" << getSkillHandlerName() << " End" << endl; __END_CATCH }
NS_IMETHODIMP nsAutoCompleteController::HandleKeyNavigation(PRUint32 aKey, bool *_retval) { // By default, don't cancel the event *_retval = PR_FALSE; if (!mInput) { // Stop all searches in case they are async. StopSearch(); // Note: if now is after blur and IME end composition, // check mInput before calling. // See https://bugzilla.mozilla.org/show_bug.cgi?id=193544#c31 NS_ERROR("Called before attaching to the control or after detaching from the control"); return NS_OK; } nsCOMPtr<nsIAutoCompleteInput> input(mInput); nsCOMPtr<nsIAutoCompletePopup> popup; input->GetPopup(getter_AddRefs(popup)); NS_ENSURE_TRUE(popup != nsnull, NS_ERROR_FAILURE); bool disabled; input->GetDisableAutoComplete(&disabled); NS_ENSURE_TRUE(!disabled, NS_OK); if (aKey == nsIDOMKeyEvent::DOM_VK_UP || aKey == nsIDOMKeyEvent::DOM_VK_DOWN || aKey == nsIDOMKeyEvent::DOM_VK_PAGE_UP || aKey == nsIDOMKeyEvent::DOM_VK_PAGE_DOWN) { // Prevent the input from handling up/down events, as it may move // the cursor to home/end on some systems *_retval = PR_TRUE; bool isOpen = false; input->GetPopupOpen(&isOpen); if (isOpen) { bool reverse = aKey == nsIDOMKeyEvent::DOM_VK_UP || aKey == nsIDOMKeyEvent::DOM_VK_PAGE_UP ? PR_TRUE : PR_FALSE; bool page = aKey == nsIDOMKeyEvent::DOM_VK_PAGE_UP || aKey == nsIDOMKeyEvent::DOM_VK_PAGE_DOWN ? PR_TRUE : PR_FALSE; // Fill in the value of the textbox with whatever is selected in the popup // if the completeSelectedIndex attribute is set. We check this before // calling SelectBy of an earlier attempt to avoid crashing. bool completeSelection; input->GetCompleteSelectedIndex(&completeSelection); // Instruct the result view to scroll by the given amount and direction popup->SelectBy(reverse, page); if (completeSelection) { PRInt32 selectedIndex; popup->GetSelectedIndex(&selectedIndex); if (selectedIndex >= 0) { // A result is selected, so fill in its value nsAutoString value; if (NS_SUCCEEDED(GetResultValueAt(selectedIndex, PR_TRUE, value))) { input->SetTextValue(value); input->SelectTextRange(value.Length(), value.Length()); } } else { // Nothing is selected, so fill in the last typed value input->SetTextValue(mSearchString); input->SelectTextRange(mSearchString.Length(), mSearchString.Length()); } } } else { #ifdef XP_MACOSX // on Mac, only show the popup if the caret is at the start or end of // the input and there is no selection, so that the default defined key // shortcuts for up and down move to the beginning and end of the field // otherwise. PRInt32 start, end; if (aKey == nsIDOMKeyEvent::DOM_VK_UP) { input->GetSelectionStart(&start); input->GetSelectionEnd(&end); if (start > 0 || start != end) *_retval = PR_FALSE; } else if (aKey == nsIDOMKeyEvent::DOM_VK_DOWN) { nsAutoString text; input->GetTextValue(text); input->GetSelectionStart(&start); input->GetSelectionEnd(&end); if (start != end || end < (PRInt32)text.Length()) *_retval = PR_FALSE; } #endif if (*_retval) { // Open the popup if there has been a previous search, or else kick off a new search if (mResults.Count() > 0) { if (mRowCount) { OpenPopup(); } } else { // Stop all searches in case they are async. StopSearch(); if (!mInput) { // StopSearch() can call PostSearchCleanup() which might result // in a blur event, which could null out mInput, so we need to check it // again. See bug #395344 for more details return NS_OK; } StartSearchTimer(); } } } } else if ( aKey == nsIDOMKeyEvent::DOM_VK_LEFT || aKey == nsIDOMKeyEvent::DOM_VK_RIGHT #ifndef XP_MACOSX || aKey == nsIDOMKeyEvent::DOM_VK_HOME #endif ) { // The user hit a text-navigation key. bool isOpen = false; input->GetPopupOpen(&isOpen); if (isOpen) { PRInt32 selectedIndex; popup->GetSelectedIndex(&selectedIndex); bool shouldComplete; input->GetCompleteDefaultIndex(&shouldComplete); if (selectedIndex >= 0) { // The pop-up is open and has a selection, take its value nsAutoString value; if (NS_SUCCEEDED(GetResultValueAt(selectedIndex, PR_TRUE, value))) { input->SetTextValue(value); input->SelectTextRange(value.Length(), value.Length()); } } else if (shouldComplete) { // We usually try to preserve the casing of what user has typed, but // if he wants to autocomplete, we will replace the value with the // actual autocomplete result. // The user wants explicitely to use that result, so this ensures // association of the result with the autocompleted text. nsAutoString value; nsAutoString inputValue; input->GetTextValue(inputValue); if (NS_SUCCEEDED(GetDefaultCompleteValue(selectedIndex, PR_FALSE, value)) && value.Equals(inputValue, nsCaseInsensitiveStringComparator())) { input->SetTextValue(value); input->SelectTextRange(value.Length(), value.Length()); } } // Close the pop-up even if nothing was selected ClearSearchTimer(); ClosePopup(); } // Update last-searched string to the current input, since the input may // have changed. Without this, subsequent backspaces look like text // additions, not text deletions. nsAutoString value; input->GetTextValue(value); mSearchString = value; } return NS_OK; }
void LMSImportChannelMapDialog::LoadMapping(wxCommandEvent& event) { bool strandwarning = false; bool modelwarning = false; if (_dirty) { if (wxMessageBox("Are you sure you dont want to save your changes for future imports?", "Are you sure?", wxYES_NO | wxCENTER, this) == wxNO) { return; } } wxFileDialog dlg(this); if (dlg.ShowModal() == wxID_OK) { for (size_t x = 0; x < modelNames.size(); x++) { ModelsChoice->Append(modelNames[x]); } ChannelMapGrid->BeginBatch(); wxFileInputStream input(dlg.GetPath()); wxTextInputStream text(input, "\t"); MapByStrand->SetValue("true" == text.ReadLine()); int count = wxAtoi(text.ReadLine()); modelNames.clear(); for (int x = 0; x < count; x++) { std::string mn = text.ReadLine().ToStdString(); int idx = ModelsChoice->FindString(mn); if (idx == wxNOT_FOUND) { //wxMessageBox("Model " + mn + " not part of sequence. Not mapping channels to this model.", "", wxICON_WARNING | wxOK , this); if (!modelwarning) { if (wxMessageBox("Model " + mn + " not part of sequence. Not mapping channels to this model. Do you want to see future occurences of this error during this import?", "", wxICON_WARNING | wxYES_NO, this) == wxNO) { modelwarning = true; } } } else { ModelsChoice->Delete(idx); modelNames.push_back(mn); } } if (MapByStrand->GetValue()) { SetupByStrand(); } else { SetupByNode(); } wxString line = text.ReadLine(); int r = 0; while (line != "") { wxString model = FindTab(line); wxString strand = FindTab(line); wxString node = FindTab(line); wxString mapping = FindTab(line); xlColor color(FindTab(line)); Element *modelEl = mSequenceElements->GetElement(model.ToStdString()); if (modelEl == nullptr && allowAddModels) { modelEl = mSequenceElements->AddElement(model.ToStdString(), "model", false, false, false, false); modelEl->AddEffectLayer(); } if (modelEl != nullptr) { while (model != ChannelMapGrid->GetCellValue(r, 0) && r < ChannelMapGrid->GetNumberRows()) { r++; } if (model != ChannelMapGrid->GetCellValue(r, 0) || strand != ChannelMapGrid->GetCellValue(r, 1) || node != ChannelMapGrid->GetCellValue(r, 2)) { if (!strandwarning) { if (wxMessageBox(model + "/" + strand + "/" + node + " not found. Has the models changed? Do you want to see future occurences of this error during this import?", "", wxICON_WARNING | wxYES_NO, this) == wxNO) { strandwarning = true; } } } else { ChannelMapGrid->SetCellValue(r, 3, mapping); ChannelMapGrid->SetCellBackgroundColour(r, 4, color.asWxColor()); } r++; } line = text.ReadLine(); } ChannelMapGrid->EndBatch(); _dirty = false; } }
Superclass::SetNumberOfParameters(3); } // ------------------------------------------------------------------------ template<typename TInputValueType, typename TOutputValueType> typename MRFIsingSmoothnessTerm<TInputValueType, TOutputValueType>::OutputType MRFIsingSmoothnessTerm<TInputValueType, TOutputValueType>:: Evaluate(const InputType &input) const { if(input.Size() != Superclass::m_NumberOfParameters) { itkExceptionMacro(<< "Not the expected number of paramters"); } InputValueType v1 = input(0); InputValueType v2 = input(1); InputValueType dist = input(2); // check if dist is unset if(dist <= 0) dist = 1.0; // compute the smoothness prior double numer = (v1-v2)*(v1-v2); double denom = 2*m_Sigma*m_Sigma; double expVal = exp(- (numer / denom)); return static_cast<TOutputValueType>( expVal * (1.0/dist) ); }
void load_menu () { // load game menu int32_t Key; uint8_t i; uint8_t row , col; uint16_t top ( 0 ); uint8_t selected ( 1 ); std::string currentID; std::list<std::string> listID; std::list<std::string>::reverse_iterator it; std::vector<std::string> vectorID; std::ifstream input ( "saves/index.sav" ); if ( !input ) { getmaxyx ( stdscr , row , col ); clear (); mvprintw ( row / 2 , ( col - STR_NO_SAVE.length () + 1 ) / 2 , STR_NO_SAVE.c_str() ); refresh (); wait ( 2000 ); return; } std::string buff; while ( !input.eof() ) { input >> buff; if ( buff != "" ) listID.push_back(buff); } if ( listID.empty () ) { getmaxyx ( stdscr , row , col ); clear (); mvprintw ( row / 2 , ( col - STR_SAVE_EMPTY.length () + 1 ) / 2 , STR_SAVE_EMPTY.c_str () ); refresh (); wait ( 2000 ); return; } while ( true ) { i = 0; if ( !vectorID.empty() ) vectorID.clear(); if ( selected < 1 ) { if ( top > 0 ) top--; selected = 1; } if ( selected > 10 ) { if ( top < listID.size() ) top++; selected = 10; } for ( it = listID.rbegin() ; it != listID.rend() ; ++it ) { currentID = (*it); if ( i > top + 10 ) break; if ( i >= top ) { if ( std::find ( vectorID.rbegin () , vectorID.rend () , currentID ) == vectorID.rend () ) vectorID.push_back( currentID ); } ++i; } if ( selected > vectorID.size() ) { selected = vectorID.size(); } getmaxyx ( stdscr , row , col ); clear (); attron ( A_BOLD ); mvprintw ( row / 5 , ( col - STR_LOAD_MENU.length () + 1 ) / 2 , STR_LOAD_MENU.c_str () ); mvprintw ( ( row / 3 ) + selected*2 - 2 , 5 * col / 20 , STR_ARROW_RIGHT.c_str () ); mvprintw ( ( row / 3 ) + selected*2 - 2 , 15 * col / 20 , STR_ARROW_LEFT.c_str () ); mvprintw ( 2 , 2 , STR_HELP.c_str () ); attroff ( A_BOLD ); for ( i = 0 ; i < vectorID.size () ; ++i ) { mvprintw ( ( row / 3 ) + ( i * 2 ) , ( col - 13 ) / 2 , vectorID[i].c_str() ); } uint8_t current = selected - 1; currentID = vectorID[current]; refresh (); Key = getch (); if ( Key == ENTER ) { grid *G = new grid ( currentID.c_str() ); if ( grid::initXO ) { play ( G , 5 , 5 , 5 , 1 , G->AI , G->getAI_prof() ); return; } } if ( Key == KEY_DOWN ) selected++; if ( Key == KEY_UP ) selected--; if ( Key == ESC ) return; } return; }
/* ** =================================================================== ** Method : PE_low_level_init (bean MC9S12C32_80) ** ** Description : ** This method is internal. It is used by Processor Expert ** only. ** =================================================================== */ void PE_low_level_init(void) { /* Common initialization of the CPU registers */ /* TSCR1: TEN=0,TSWAI=0,TSFRZ=1 */ output( TSCR1, input( TSCR1 ) & ~192 | 32 ); /* TCTL2: OM0=0,OL0=0 */ output( TCTL2, input( TCTL2 ) & ~3 ); /* TCTL1: OM7=0,OL7=0 */ output( TCTL1, input( TCTL1 ) & ~192 ); /* TIE: C0I=0 */ output( TIE, input( TIE ) & ~1 ); /* TTOV: TOV0=0 */ output( TTOV, input( TTOV ) & ~1 ); /* TSCR2: TOI=0,TCRE=1 */ output( TSCR2, input( TSCR2 ) & ~128 | 8 ); /* TIOS: IOS7=1,IOS0=1 */ output( TIOS, input( TIOS ) | 129 ); /* PPSP: PPSP0=0 */ output( PPSP, input( PPSP ) & ~1 ); /* PERP: PERP0=1 */ output( PERP, input( PERP ) | 1 ); /* DDRP: DDRP0=0 */ output( DDRP, input( DDRP ) & ~1 ); /* PWMCTL: PSWAI=0,PFRZ=0 */ output( PWMCTL, input( PWMCTL ) & ~12 ); /* PWMSDN: PWMIF=0,PWMIE=0,PWMRSTRT=0,PWMLVL=0,??=0,PWM7IN=0,PWM7INL=0,PWM7ENA=0 */ output( PWMSDN, 0 ); /* ### MC9S12C32_80 "Cpu" init code ... */ /* ### ByteIO "Byte1" init code ... */ PORTB = 0; /* Prepare value for output */ DDRB = 255; /* Set direction to output */ /* ### TimerInt "TickTimer" init code ... */ TickTimer_Init(); /* ### External interrupt "ButtonInterrupt" init code ... */ PIEP_PIEP0 = 0; /* Disable interrupt */ /* Common peripheral initialization - ENABLE */ /* TSCR1: TEN=1 */ output( TSCR1, input( TSCR1 ) | 128 ); INTCR_IRQEN = 0; /* Disable the IRQ interrupt. IRQ interrupt is enabled after CPU reset by default. */ __DI(); /* Disable interrupts */ }
bool runTestType(cl::Context context, cl::CommandQueue queue) { cl_uint size = (1 << 16) + 16384; std::vector<T> input(size); std::cout << "##Testing AMD radix sort for " << input.size() << " elements and type " << magnet::CL::detail::traits<T>::kernel_type(); for(size_t i = 0; i < input.size(); ++i) input[i] = input.size() - i - 1; // create input buffer using pinned memory cl::Buffer bufferIn(context, CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sizeof(T) * input.size(), &input[0]); magnet::CL::radixSortAMD<T> radixSortFunctor; radixSortFunctor.build(queue, context); radixSortFunctor(bufferIn, bufferIn); std::vector<T> output(size); queue.enqueueReadBuffer(bufferIn, CL_TRUE, 0, input.size() * sizeof(T), &output[0]); bool failed = !testOutput(input, output); std::cout << " key(only) " << (failed ? "FAILED" : "PASSED") << ", "; //Now test with some data! //Refresh the input array queue.enqueueWriteBuffer(bufferIn, CL_TRUE, 0, input.size() * sizeof(T), &input[0]); //Write a data array std::vector<cl_uint> data(size); for(size_t i = 0; i < input.size(); ++i) data[i] = i; cl::Buffer dataIn(context, CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sizeof(cl_uint) * data.size(), &data[0]) ; radixSortFunctor(bufferIn, dataIn, bufferIn, dataIn); queue.enqueueReadBuffer(dataIn, CL_TRUE, 0, data.size() * sizeof(cl_uint), &data[0]); bool keyfail = !testOutput(input, output); std::cout << " key " << (keyfail ? "FAILED" : "PASSED"); bool datafail = false; for(size_t i = 0; i < input.size(); ++i) if (data[i] != input.size() - 1 - i) datafail = true; std::cout << " data " << (datafail ? "FAILED" : "PASSED") << std::endl; return failed || keyfail || datafail; }
int run() { while ( init(), input() ) { output(solve()); } return 0; }
nsresult nsAutoCompleteController::StartSearch() { NS_ENSURE_STATE(mInput); nsCOMPtr<nsIAutoCompleteInput> input(mInput); mSearchStatus = nsIAutoCompleteController::STATUS_SEARCHING; mDefaultIndexCompleted = PR_FALSE; // Cache the current results so that we can pass these through to all the // searches without losing them nsCOMArray<nsIAutoCompleteResult> resultCache; if (!resultCache.AppendObjects(mResults)) { return NS_ERROR_OUT_OF_MEMORY; } PRUint32 count = mSearches.Count(); mSearchesOngoing = count; mFirstSearchResult = PR_TRUE; // notify the input that the search is beginning input->OnSearchBegin(); PRUint32 searchesFailed = 0; for (PRUint32 i = 0; i < count; ++i) { nsCOMPtr<nsIAutoCompleteSearch> search = mSearches[i]; nsIAutoCompleteResult *result = resultCache.SafeObjectAt(i); if (result) { PRUint16 searchResult; result->GetSearchResult(&searchResult); if (searchResult != nsIAutoCompleteResult::RESULT_SUCCESS && searchResult != nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING && searchResult != nsIAutoCompleteResult::RESULT_NOMATCH) result = nsnull; } nsAutoString searchParam; nsresult rv = input->GetSearchParam(searchParam); if (NS_FAILED(rv)) return rv; rv = search->StartSearch(mSearchString, searchParam, result, static_cast<nsIAutoCompleteObserver *>(this)); if (NS_FAILED(rv)) { ++searchesFailed; --mSearchesOngoing; } // Because of the joy of nested event loops (which can easily happen when some // code uses a generator for an asynchronous AutoComplete search), // nsIAutoCompleteSearch::StartSearch might cause us to be detached from our input // field. The next time we iterate, we'd be touching something that we shouldn't // be, and result in a crash. if (!mInput) { // The search operation has been finished. return NS_OK; } } if (searchesFailed == count) PostSearchCleanup(); return NS_OK; }
/* * void read_grid(bool debug) * * Read all the grid points. This function depends * on the the gridsize being set via the * read_grid_dimensions() function. * * Note that all read_* functions can * be used seperately, although they may depend * on each other and have to be used in some * consecutive order as is done in the read() * wrapper function. * */ void ScalarField::read_grid(bool debug) { std::cout.setf(std::ios_base::unitbuf); // flush after every "<<" if(debug) std::cout << "Reading grid values..."; std::ifstream infile(this->filename.c_str()); std::string line; // skip lines that contain atoms for(unsigned int i=0; i<(this->vasp5_input ? 10 : 9); i++) { std::getline(infile, line); } for(unsigned int i=0; i<this->nrat.size(); i++) { for(unsigned int j=0; j<this->nrat[i]; j++) { std::getline(infile, line); } } this->gridsize = this->grid_dimensions[0] * this->grid_dimensions[1] * this->grid_dimensions[2]; this->gridptr = new float[this->gridsize]; // spin up this->gridptr2 = new float[this->gridsize]; // spin down (not being used now) /* read spin up */ unsigned int i=0; unsigned int cur=0; // for the counter unsigned int linecounter=0; // for the counter unsigned int wordcounter=0; // for the counter pcrecpp::RE re("([0-9Ee.+-]+)"); pcrecpp::RE aug("augmentation.*"); while(std::getline(infile, line)) { // stop looping when a second gridline appears (this // is where the spin down part starts) if(line.compare(this->gridline) == 0) { std::cout << "I am breaking the loop" << std::endl; break; } if(aug.FullMatch(line)) { break; } pcrecpp::StringPiece input(line); wordcounter = 0; if(i > this->gridsize) { break; } while(re.FindAndConsume(&input, &this->gridptr[i])) { i++; wordcounter++; } /* * Track the progress of the read procedure. (this is the task that takes the * most amount of time) */ if(debug) { if(i > (this->gridsize / 5 * cur)) { std::cout << "[" << int(cur * 20) << " %]"; cur++; } } linecounter++; } if(debug) std::cout << "[100%]" << std::endl; if(debug) std::cout << "End reading " << linecounter << " lines" << std::endl; if(debug) std::cout << "Grabbed " << i << "/" << this->gridsize << " values" << std::endl; // /* read spin down */ // i=0; // while(std::getline(infile, line)) { // pcrecpp::StringPiece input(line); // while(re.FindAndConsume(&input, &this->gridptr2[i])) { // i++; // } // } // if(debug) std::cout << "[Done]" << std::endl; }
nsresult nsAutoCompleteController::EnterMatch(bool aIsPopupSelection) { nsCOMPtr<nsIAutoCompleteInput> input(mInput); nsCOMPtr<nsIAutoCompletePopup> popup; input->GetPopup(getter_AddRefs(popup)); NS_ENSURE_TRUE(popup != nsnull, NS_ERROR_FAILURE); bool forceComplete; input->GetForceComplete(&forceComplete); // Ask the popup if it wants to enter a special value into the textbox nsAutoString value; popup->GetOverrideValue(value); if (value.IsEmpty()) { bool shouldComplete; mInput->GetCompleteDefaultIndex(&shouldComplete); bool completeSelection; input->GetCompleteSelectedIndex(&completeSelection); // If completeselectedindex is false or a row was selected from the popup, // enter it into the textbox. If completeselectedindex is true, or // EnterMatch was called via other means, for instance pressing Enter, // don't fill in the value as it will have already been filled in as needed. PRInt32 selectedIndex; popup->GetSelectedIndex(&selectedIndex); if (selectedIndex >= 0 && (!completeSelection || aIsPopupSelection)) GetResultValueAt(selectedIndex, PR_TRUE, value); else if (shouldComplete) { // We usually try to preserve the casing of what user has typed, but // if he wants to autocomplete, we will replace the value with the // actual autocomplete result. // The user wants explicitely to use that result, so this ensures // association of the result with the autocompleted text. nsAutoString defaultIndexValue; nsAutoString inputValue; input->GetTextValue(inputValue); if (NS_SUCCEEDED(GetDefaultCompleteValue(selectedIndex, PR_FALSE, defaultIndexValue)) && defaultIndexValue.Equals(inputValue, nsCaseInsensitiveStringComparator())) value = defaultIndexValue; } if (forceComplete && value.IsEmpty()) { // Since nothing was selected, and forceComplete is specified, that means // we have to find the first default match and enter it instead PRUint32 count = mResults.Count(); for (PRUint32 i = 0; i < count; ++i) { nsIAutoCompleteResult *result = mResults[i]; if (result) { PRInt32 defaultIndex; result->GetDefaultIndex(&defaultIndex); if (defaultIndex >= 0) { result->GetValueAt(defaultIndex, value); break; } } } } } nsCOMPtr<nsIObserverService> obsSvc = mozilla::services::GetObserverService(); NS_ENSURE_STATE(obsSvc); obsSvc->NotifyObservers(input, "autocomplete-will-enter-text", nsnull); if (!value.IsEmpty()) { input->SetTextValue(value); input->SelectTextRange(value.Length(), value.Length()); mSearchString = value; } obsSvc->NotifyObservers(input, "autocomplete-did-enter-text", nsnull); ClosePopup(); bool cancel; input->OnTextEntered(&cancel); return NS_OK; }
void StabilizedSqicInterface::init() { // Call the init method of the base class StabilizedQpSolverInternal::init(); if (is_init_) sqicDestroy(); inf_ = 1.0e+20; // Allocate data structures for SQIC bl_.resize(n_+nc_+1, 0); bu_.resize(n_+nc_+1, 0); x_.resize(n_+nc_+1, 0); hs_.resize(n_+nc_+1, 0); hEtype_.resize(n_+nc_+1, 0); pi_.resize(nc_+1, 0); piE_.resize(nc_+1, 0); rc_.resize(n_+nc_+1, 0); locH_ = st_[QP_STRUCT_H].colind(); indH_ = st_[QP_STRUCT_H].row(); // Fortran indices are one-based for (int i=0;i<indH_.size();++i) indH_[i]+=1; for (int i=0;i<locH_.size();++i) locH_[i]+=1; // Sparsity of augmented linear constraint matrix Sparsity A_ = vertcat(st_[QP_STRUCT_A], Sparsity::dense(1, n_)); locA_ = A_.colind(); indA_ = A_.row(); // Fortran indices are one-based for (int i=0;i<indA_.size();++i) indA_[i]+=1; for (int i=0;i<locA_.size();++i) locA_[i]+=1; // helper functions for augmented linear constraint matrix MX a = MX::sym("A", st_[QP_STRUCT_A]); MX g = MX::sym("g", n_); std::vector<MX> ins; ins.push_back(a); ins.push_back(g); formatA_ = MXFunction(ins, vertcat(a, g.T())); formatA_.init(); // Set objective row of augmented linear constraints bu_[n_+nc_] = inf_; bl_[n_+nc_] = -inf_; is_init_ = true; int n = n_; int m = nc_+1; int nnzA=formatA_.output().size(); int nnzH=input(STABILIZED_QP_SOLVER_H).size(); std::fill(hEtype_.begin()+n_, hEtype_.end(), 3); sqic(&m , &n, &nnzA, &indA_[0], &locA_[0], &formatA_.output().data()[0], &bl_[0], &bu_[0], &hEtype_[0], &hs_[0], &x_[0], &pi_[0], &rc_[0], &nnzH, &indH_[0], &locH_[0], &input(STABILIZED_QP_SOLVER_H).data()[0]); }
nsresult nsAutoCompleteController::ProcessResult(PRInt32 aSearchIndex, nsIAutoCompleteResult *aResult) { NS_ENSURE_STATE(mInput); nsCOMPtr<nsIAutoCompleteInput> input(mInput); // If this is the first search result we are processing // we should clear out the previously cached results if (mFirstSearchResult) { ClearResults(); mFirstSearchResult = PR_FALSE; } PRUint16 result = 0; if (aResult) aResult->GetSearchResult(&result); // if our results are incremental, the search is still ongoing if (result != nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING && result != nsIAutoCompleteResult::RESULT_NOMATCH_ONGOING) { --mSearchesOngoing; } PRUint32 oldMatchCount = 0; PRUint32 matchCount = 0; if (aResult) aResult->GetMatchCount(&matchCount); PRInt32 oldIndex = mResults.IndexOf(aResult); if (oldIndex == -1) { // cache the result mResults.AppendObject(aResult); mMatchCounts.AppendElement(matchCount); } else { // replace the cached result mResults.ReplaceObjectAt(aResult, oldIndex); oldMatchCount = mMatchCounts[aSearchIndex]; mMatchCounts[oldIndex] = matchCount; } PRUint32 oldRowCount = mRowCount; // If the search failed, increase the match count // to include the error description if (result == nsIAutoCompleteResult::RESULT_FAILURE) { nsAutoString error; aResult->GetErrorDescription(error); if (!error.IsEmpty()) { ++mRowCount; if (mTree) mTree->RowCountChanged(oldRowCount, 1); } } else if (result == nsIAutoCompleteResult::RESULT_SUCCESS || result == nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING) { // Increase the match count for all matches in this result mRowCount += matchCount - oldMatchCount; if (mTree) mTree->RowCountChanged(oldRowCount, matchCount - oldMatchCount); // Try to autocomplete the default index for this search CompleteDefaultIndex(aSearchIndex); } // Refresh the popup view to display the new search results nsCOMPtr<nsIAutoCompletePopup> popup; input->GetPopup(getter_AddRefs(popup)); NS_ENSURE_TRUE(popup != nsnull, NS_ERROR_FAILURE); popup->Invalidate(); // Make sure the popup is open, if necessary, since we now have at least one // search result ready to display. Don't force the popup closed if we might // get results in the future to avoid unnecessarily canceling searches. if (mRowCount) OpenPopup(); else if (result != nsIAutoCompleteResult::RESULT_NOMATCH_ONGOING) ClosePopup(); if (mSearchesOngoing == 0) { // If this is the last search to return, cleanup PostSearchCleanup(); } return NS_OK; }
void StabilizedSqicInterface::evaluate() { if (inputs_check_) checkInputs(); std::copy(input(STABILIZED_QP_SOLVER_X0).begin(), input(STABILIZED_QP_SOLVER_X0).end(), x_.begin()); std::fill(x_.begin()+n_, x_.end(), 0); std::transform(input(STABILIZED_QP_SOLVER_LAM_X0).begin(), input(STABILIZED_QP_SOLVER_LAM_X0).end(), rc_.begin(), negate<double>()); std::fill(rc_.begin()+n_, rc_.end(), 0); std::copy(input(STABILIZED_QP_SOLVER_LBX).begin(), input(STABILIZED_QP_SOLVER_LBX).end(), bl_.begin()); std::copy(input(STABILIZED_QP_SOLVER_UBX).begin(), input(STABILIZED_QP_SOLVER_UBX).end(), bu_.begin()); std::copy(input(STABILIZED_QP_SOLVER_LBA).begin(), input(STABILIZED_QP_SOLVER_LBA).end(), bl_.begin()+n_); std::copy(input(STABILIZED_QP_SOLVER_UBA).begin(), input(STABILIZED_QP_SOLVER_UBA).end(), bu_.begin()+n_); std::copy(input(STABILIZED_QP_SOLVER_MUE).begin(), input(STABILIZED_QP_SOLVER_MUE).end(), piE_.begin()); for (int i=0;i<n_+nc_+1;++i) { if (bl_[i]==-std::numeric_limits<double>::infinity()) bl_[i]=-inf_; if (bu_[i]==std::numeric_limits<double>::infinity()) bu_[i]=inf_; } formatA_.setInput(input(STABILIZED_QP_SOLVER_A), 0); formatA_.setInput(input(STABILIZED_QP_SOLVER_G), 1); formatA_.evaluate(); int m = nc_+1; sqicSolveStabilized(&output(QP_SOLVER_COST).data()[0], &input(STABILIZED_QP_SOLVER_MU).data()[0], &m, &piE_[0]); std::copy(x_.begin(), x_.begin()+n_, output(QP_SOLVER_X).begin()); std::transform(rc_.begin(), rc_.begin()+n_, output(QP_SOLVER_LAM_X).begin(), negate<double>()); std::transform(rc_.begin()+n_, rc_.begin()+n_+nc_, output(QP_SOLVER_LAM_A).begin(), negate<double>()); output(QP_SOLVER_COST)[0]+= x_[n_+nc_]; }
void MyApp::DoStreamDemo5(wxCommandEvent& WXUNUSED(event)) { wxTextCtrl& textCtrl = * GetTextCtrl(); textCtrl.Clear(); textCtrl << _T("\nTesting wxFileInputStream's Peek():\n\n"); char ch; wxString str; textCtrl.WriteText( _T("Writing number 0 to 9 to wxFileOutputStream:\n\n") ); wxFileOutputStream file_output( file_name ); for (ch = 0; ch < 10; ch++) file_output.Write( &ch, 1 ); file_output.Sync(); wxFileInputStream file_input( file_name ); ch = file_input.Peek(); str.Printf( wxT("First char peeked: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = file_input.GetC(); str.Printf( wxT("First char read: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = file_input.Peek(); str.Printf( wxT("Second char peeked: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = file_input.GetC(); str.Printf( wxT("Second char read: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = file_input.Peek(); str.Printf( wxT("Third char peeked: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = file_input.GetC(); str.Printf( wxT("Third char read: %d\n"), (int) ch ); textCtrl.WriteText( str ); textCtrl << _T("\n\n\nTesting wxMemoryInputStream's Peek():\n\n"); char buf[] = { 0,1,2,3,4,5,6,7,8,9,10 }; wxMemoryInputStream input( buf, 10 ); ch = input.Peek(); str.Printf( wxT("First char peeked: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = input.GetC(); str.Printf( wxT("First char read: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = input.Peek(); str.Printf( wxT("Second char peeked: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = input.GetC(); str.Printf( wxT("Second char read: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = input.Peek(); str.Printf( wxT("Third char peeked: %d\n"), (int) ch ); textCtrl.WriteText( str ); ch = input.GetC(); str.Printf( wxT("Third char read: %d\n"), (int) ch ); textCtrl.WriteText( str ); }