Qt/QML: Save and abort settings - save

I am designing a GUI for my 3D printer. At the home screen you can chose between starting a new print or changing the settings (feedrates, acceleration etc.). Fot the settings I was following this example. But unlinke as in the example, my settings are not properties of the GUI (like x postion, width etc.) but raw data that is entered through text fields and is insignificant to the GUI. The settings are saved at the end of the GUI in a .txt file which is later translated into a code for the printer.
My first question is, how do i design a save- and abort-button? The user should be able to change the text fields but the changes should only be terminal when the save button is pressed.
My second question is, should i ALWAYS read out the text fields? The settings usually shouldnt be changed, so is there a more efficient way? (read the text fields only when the save button was clicked, otherwise adopt the previous values?
For the save Button I was trying something like this, but i doesnt work:
Item {
TextField {id: testField}
Button {id: testButton; text: "Accept"; onClicked: settings.state = "inactive"}
Settings {id:settings; property string state: "active"}
state: settings.state
states: [
State {name: "active"}
State {name:"inactive"; property alias test: testField.text}
]
}

File operations must be done on C++ level. Following code will be a good example of showing open, save and edit operation in Qt.
It uses widget so add the following in .pro file.
QT += widgets
qmlfile.h
//qmlfile.h
#ifndef QMLFILE_H
#define QMLFILE_H
#include <QObject>
class QMLFile : public QObject
{
Q_OBJECT
public:
explicit QMLFile(QObject *parent = 0);
Q_INVOKABLE QString getFileContents() const;
Q_INVOKABLE void saveFileContents(QString fileContents) const;
};
#endif
qmlfile.cpp
#include <QFileDialog>
#include <QTextStream>
#include <QDebug>
#include "qmlfile.h"
QMLFile::QMLFile(QObject *parent): QObject(parent)
{
}
QString QMLFile::getFileContents() const
{
QString fileName = QFileDialog::getOpenFileName(NULL, tr("Open File"), "/home", tr("Text Files (*.txt)"));
qDebug() << "fileName:" << fileName;
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
return "";
QString content = file.readAll();
file.close();
return content;
}
void QMLFile::saveFileContents(QString fileContents) const
{
QString fileName = QFileDialog::getSaveFileName(NULL, tr("Save File"), "/home/ansh/data.txt", tr("Text Files (*.txt)"));
QFile file(fileName);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
qDebug() << "created file:" << fileName;
QTextStream stream(&file);
stream << fileContents << endl;
file.close();
return;
}
else
{
qDebug() << "could not create file:" << fileName;
return;
}
}
main.cpp
#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QApplication>
#include "qmlfile.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQuickView view;
QMLFile qmlFile;
view.rootContext()->setContextProperty("QMLFile", &qmlFile);
QObject::connect((QObject*)view.engine(), SIGNAL(quit()), QApplication::instance(), SLOT(quit()));
view.setSource(QUrl(QLatin1String("qrc:/main.qml")));
view.show();
return app.exec();
}
main.qml
import QtQuick 2.5
import QtQuick.Controls 2.0
Rectangle {
width: 360; height: 360
Rectangle{
id:buttons
height: 50; width: parent.width; anchors.top: parent.top
Row {
Button {
text: "open"
onClicked: txt.text = QMLFile.getFileContents();
}
Button {
text: "save"
onClicked: QMLFile.saveFileContents(txt.text);
}
Button {
text: "Abort"
onClicked: Qt.quit()
}
spacing: 5
}
}
Rectangle{
id:textHandle
width: parent.width; height: parent.height - buttons.height; anchors.bottom: parent.bottom
TextEdit{
id: txt; anchors.fill: parent
}
}
}
For the second question, since the settings are dynamic in nature it has to be read every time.

Related

`std::optional`: How to reduce redundant copies with rvalue reference and std::move()

In this code,
How many times would the generated string be copied for each case(case 1, case 2)?
Could anyone confirm my answers in the code body?
If so, can I tell case 2 is more efficient than case 1?
Or any other suggestions?
#include <optional>
#include <string>
std::optional<std::string> GenerateString() {
std::string s = "very long string";
return s;
}
class Message {
public:
Message(const std::string &s) : payload_{s} {}
Message(std::string &&s) : payload_{std::move(s)} {}
private:
std::string payload_;
};
int main() {
// case 1
const std::optional<std::string> &opt1 = GenerateString(); // no copy
const std::string &s1 = *opt1; // no copy
Message msg1{s1}; // copy: s1 -> payload_
// case 2
std::optional<std::string> &&opt2 = GenerateString(); // no copy
std::string &&s2 = std::move(*opt2); // no copy
Message msg2{std::move(s2)}; // no copy
return 0;
}

Creating Terrain Map with SRTM HGT File

I am working on an iOS application. Where I show the Elevation and Topography map of a certain area. I have managed to download the .hgt file within app from here.
So far I am able to extract the Elevation from the hgt file. Now I have to also show the Terrain Map for that area. I have been searching about it and I think I can't create terrain map directly with hgt file within iOS application. I have to use GRASS GIS, SRTM2OSM or TileMill to create terrain map and then use it in application.
Can please anyone direct me what I can do here and how to proceed.
EDIT:
I have asked to not to use any kind of map for this. So basically I have to create the map by using core drawing, and I have no idea about it.
Something Like this without the text:
With iOS you have access to Maps through MapKit framework to display map or satellite imagery directly from your app's interface, you can use also Google Maps through Google Maps SDK for iOS but both (iOS Maps and Google Maps) don't have a terrain level.
So to avoid to re-create something that already exist you can take a look to the OpenStreetMaps frameworks, here you can find many available frameworks, one of them is called MapBox and you can download the latest sources and example here
As you can read from wiki pages we have also the terrain level:
I think it's a really useful library, updated and working with swift 4 , here you can find an easy tutorial to start:
import Mapbox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let mapView = MGLMapView(frame: view.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.setCenter(CLLocationCoordinate2D(latitude: 40.74699, longitude: -73.98742), zoomLevel: 9, animated: false)
view.addSubview(mapView)
// to show the terrain level
mapView.styleURL = MGLStyle.outdoorsStyleURL()
}
}
I have to create the map by using core drawing
You can draw an Map object from SRTM HGT file [1]
For reading interpolated height from SRTM HGT files [2]
Below is code working with .cpp file you can get some idea for how to draw it from SRTM [3]
#include "generator/srtm_parser.hpp"
#include "coding/endianness.hpp"
#include "coding/zip_reader.hpp"
#include "base/logging.hpp"
#include <iomanip>
#include <sstream>
namespace generator
{
namespace
{
size_t constexpr kArcSecondsInDegree = 60 * 60;
size_t constexpr kSrtmTileSize = (kArcSecondsInDegree + 1) * (kArcSecondsInDegree + 1) * 2;
struct UnzipMemDelegate : public ZipFileReader::Delegate
{
UnzipMemDelegate(std::string & buffer) : m_buffer(buffer), m_completed(false) {}
// ZipFileReader::Delegate overrides:
void OnBlockUnzipped(size_t size, char const * data) override { m_buffer.append(data, size); }
void OnStarted() override
{
m_buffer.clear();
m_completed = false;
}
void OnCompleted() override { m_completed = true; }
std::string & m_buffer;
bool m_completed;
};
} // namespace
// SrtmTile ----------------------------------------------------------------------------------------
SrtmTile::SrtmTile()
{
Invalidate();
}
SrtmTile::SrtmTile(SrtmTile && rhs) : m_data(move(rhs.m_data)), m_valid(rhs.m_valid)
{
rhs.Invalidate();
}
void SrtmTile::Init(std::string const & dir, ms::LatLon const & coord)
{
Invalidate();
std::string const base = GetBase(coord);
std::string const cont = dir + base + ".SRTMGL1.hgt.zip";
std::string file = base + ".hgt";
UnzipMemDelegate delegate(m_data);
try
{
ZipFileReader::UnzipFile(cont, file, delegate);
}
catch (ZipFileReader::LocateZipException const & e)
{
// Sometimes packed file has different name. See N39E051 measure.
file = base + ".SRTMGL1.hgt";
ZipFileReader::UnzipFile(cont, file, delegate);
}
if (!delegate.m_completed)
{
LOG(LWARNING, ("Can't decompress SRTM file:", cont));
Invalidate();
return;
}
if (m_data.size() != kSrtmTileSize)
{
LOG(LWARNING, ("Bad decompressed SRTM file size:", cont, m_data.size()));
Invalidate();
return;
}
m_valid = true;
}
feature::TAltitude SrtmTile::GetHeight(ms::LatLon const & coord)
{
if (!IsValid())
return feature::kInvalidAltitude;
double ln = coord.lon - static_cast<int>(coord.lon);
if (ln < 0)
ln += 1;
double lt = coord.lat - static_cast<int>(coord.lat);
if (lt < 0)
lt += 1;
lt = 1 - lt; // from North to South
size_t const row = kArcSecondsInDegree * lt;
size_t const col = kArcSecondsInDegree * ln;
size_t const ix = row * (kArcSecondsInDegree + 1) + col;
if (ix >= Size())
return feature::kInvalidAltitude;
return ReverseByteOrder(Data()[ix]);
}
std::string SrtmTile::GetBase(ms::LatLon coord)
{
std::ostringstream ss;
if (coord.lat < 0)
{
ss << "S";
coord.lat *= -1;
coord.lat += 1;
}
else
{
ss << "N";
}
ss << std::setw(2) << std::setfill('0') << static_cast<int>(coord.lat);
if (coord.lon < 0)
{
ss << "W";
coord.lon *= -1;
coord.lon += 1;
}
else
{
ss << "E";
}
ss << std::setw(3) << static_cast<int>(coord.lon);
return ss.str();
}
void SrtmTile::Invalidate()
{
m_data.clear();
m_data.shrink_to_fit();
m_valid = false;
}
// SrtmTileManager ---------------------------------------------------------------------------------
SrtmTileManager::SrtmTileManager(std::string const & dir) : m_dir(dir) {}
feature::TAltitude SrtmTileManager::GetHeight(ms::LatLon const & coord)
{
std::string const base = SrtmTile::GetBase(coord);
auto it = m_tiles.find(base);
if (it == m_tiles.end())
{
SrtmTile tile;
try
{
tile.Init(m_dir, coord);
}
catch (RootException const & e)
{
LOG(LINFO, ("Can't init SRTM tile:", base, "reason:", e.Msg()));
}
// It's OK to store even invalid tiles and return invalid height
// for them later.
it = m_tiles.emplace(base, std::move(tile)).first;
}
return it->second.GetHeight(coord);
}
} // namespace generator

objectmaker.exe in haarclassification

I am trying in vs2012 and opencv 2.4.11 to run the objectmaker.exe in my project file which is created by the code and successfully build in release but when i am trying to double click to open it there is a run time error i cant fix it any help please .. my code is :
#include <opencv/cv.h>
#include <opencv/cvaux.h>
#include <opencv/highgui.h>
#include "stdafx.h"
#include "opencv2/highgui/highgui.hpp"
// for filelisting
#include <stdio.h>
#include <io.h>
// for fileoutput
#include <string>
#include <fstream>
#include <sstream>
#include "dirent.h"
#include <sys/types.h>
using namespace std;
using namespace cv;
IplImage* image=0;
IplImage* image2=0;
//int start_roi=0;
int roi_x0=0;
int roi_y0=0;
int roi_x1=0;
int roi_y1=0;
int numOfRec=0;
int startDraw = 0;
char* window_name="<SPACE>add <ENTER>save and load next <ESC>exit";
string IntToString(int num)
{
ostringstream myStream; //creates an ostringstream object
myStream << num << flush;
/*
* outputs the number into the string stream and then flushes
* the buffer (makes sure the output is put into the stream)
*/
return(myStream.str()); //returns the string form of the stringstream object
};
void on_mouse(int event,int x,int y,int flag, void *param)
{
if(event==CV_EVENT_LBUTTONDOWN)
{
if(!startDraw)
{
roi_x0=x;
roi_y0=y;
startDraw = 1;
} else {
roi_x1=x;
roi_y1=y;
startDraw = 0;
}
}
if(event==CV_EVENT_MOUSEMOVE && startDraw)
{
//redraw ROI selection
image2=cvCloneImage(image);
cvRectangle(image2,cvPoint(roi_x0,roi_y0),cvPoint(x,y),
CV_RGB(255,0,255),1);
cvShowImage(window_name,image2);
cvReleaseImage(&image2);
}
}
int main(int argc, char** argv)
{
int iKey=0;
string strPrefix;
string strPostfix;
string input_directory;
string output_file;
if(argc != 3) {
fprintf(stderr, "%s output_info.txt raw/data/directory/\n", argv[0]);
return -1;
}
input_directory = argv[2];
output_file = argv[1];
/* Get a file listing of all files with in the input directory */
DIR *dir_p = opendir (input_directory.c_str());
struct dirent *dir_entry_p;
if(dir_p == NULL) {
fprintf(stderr, "Failed to open directory %s\n", input_directory.c_str());
return -1;
}
fprintf(stderr, "Object Marker: Input Directory: %s Output File: %s\n", input_directory.c_str(), output_file.c_str());
// init highgui
cvAddSearchPath(input_directory);
cvNamedWindow(window_name,1);
cvSetMouseCallback(window_name,on_mouse, NULL);
fprintf(stderr, "Opening directory...");
// init output of rectangles to the info file
ofstream output(output_file.c_str());
fprintf(stderr, "done.\n");
while((dir_entry_p = readdir(dir_p)) != NULL)
{
numOfRec=0;
if(strcmp(dir_entry_p->d_name, ""))
fprintf(stderr, "Examining file %s\n", dir_entry_p->d_name);
/* TODO: Assign postfix/prefix info */
strPostfix="";
strPrefix=input_directory;
strPrefix+=dir_entry_p->d_name;
//strPrefix+=bmp_file.name;
fprintf(stderr, "Loading image %s\n", strPrefix.c_str());
if((image=cvLoadImage(strPrefix.c_str(),1)) != 0)
{
// work on current image
do
{
cvShowImage(window_name,image);
// used cvWaitKey returns:
// <Enter>=13 save added rectangles and show next image
// <ESC>=27 exit program
// <Space>=32 add rectangle to current image
// any other key clears rectangle drawing only
iKey=cvWaitKey(0);
switch(iKey)
{
case 27:
cvReleaseImage(&image);
cvDestroyWindow(window_name);
return 0;
case 32:
numOfRec++;
printf(" %d. rect x=%d\ty=%d\tx2h=%d\ty2=%d\n",numOfRec,roi_x0,roi_y0,roi_x1,roi_y1);
//printf(" %d. rect x=%d\ty=%d\twidth=%d\theight=%d\n",numOfRec,roi_x1,roi_y1,roi_x0-roi_x1,roi_y0-roi_y1);
// currently two draw directions possible:
// from top left to bottom right or vice versa
if(roi_x0<roi_x1 && roi_y0<roi_y1)
{
printf(" %d. rect x=%d\ty=%d\twidth=%d\theight=%d\n",numOfRec,roi_x0,roi_y0,roi_x1-roi_x0,roi_y1-roi_y0);
// append rectangle coord to previous line content
strPostfix+=" "+IntToString(roi_x0)+" "+IntToString(roi_y0)+" "+IntToString(roi_x1-roi_x0)+" "+IntToString(roi_y1-roi_y0);
}
if(roi_x0>roi_x1 && roi_y0>roi_y1)
{
printf(" %d. rect x=%d\ty=%d\twidth=%d\theight=%d\n",numOfRec,roi_x1,roi_y1,roi_x0-roi_x1,roi_y0-roi_y1);
// append rectangle coord to previous line content
strPostfix+=" "+IntToString(roi_x1)+" "+IntToString(roi_y1)+" "+IntToString(roi_x0-roi_x1)+" "+IntToString(roi_y0-roi_y1);
}
break;
}
}
while(iKey!=13);
// save to info file as later used for HaarTraining:
// <rel_path>\bmp_file.name numOfRec x0 y0 width0 height0 x1 y1 width1 height1...
if(numOfRec>0 && iKey==13)
{
//append line
/* TODO: Store output information. */
output << strPrefix << " "<< numOfRec << strPostfix <<"\n";
}
cvReleaseImage(&image);
} else {
fprintf(stderr, "Failed to load image, %s\n", strPrefix.c_str());
}
}
output.close();
cvDestroyWindow(window_name);
closedir(dir_p);
return 0;
}

Interfacing readline into Rust

I try to do this tutorial in rust, so far I have a lot of problems interfacing the C library into Rust.
C equivalent code:
#include <stdio.h>
#include <stdlib.h>
#include <editline/readline.h>
#include <editline/history.h>
int main(int argc, char** argv) {
/* Print Version and Exit Information */
puts("Lispy Version 0.0.0.0.1");
puts("Press Ctrl+c to Exit\n");
/* In a never ending loop */
while (1) {
/* Output our prompt and get input */
char* input = readline("lispy> ");
/* Add input to history */
add_history(input);
/* Echo input back to user */
printf("No you're a %s\n", input);
/* Free retrived input */
free(input);
}
return 0;
}
So far i got this:
extern crate libc;
use std::c_str;
#[link(name = "readline")]
extern {
fn readline (p: *const libc::c_char) -> *const libc::c_char;
}
fn rust_readline (prompt: &str) -> Option<Box<str>> {
let cprmt = prompt.to_c_str();
cprmt.with_ref(|c_buf| {
unsafe {
let ret = c_str::CString::new (readline (c_buf), true);
ret.as_str().map(|ret| ret.to_owned())
}
})
}
fn main() {
println!("Lispy Version 0.0.1");
println!("Press Ctrl+c to Exit.\n");
// I want to have "history" in Linux of this:
//
// loop {
// print!("lispy> ");
// let input = io::stdin().read_line().unwrap();
// print!("No you're a {}", input);
// }
loop {
let val = rust_readline ("lispy> ");
match val {
None => { break }
_ => {
let input = val.unwrap();
println!("No you're a {}", input);
}
}
}
}
Especifically, I'm having issues with rust_readline function, i don't understand very well what's doing inside.
Edit Cargo.toml, put this:
[dependencies.readline]
git = "https://github.com/shaleh/rust-readline"
Code corrected:
extern crate readline;
fn main() {
println!("Lispy Version 0.0.1");
println!("Press Ctrl+c to Exit.\n");
loop {
let input = readline::readline("lispy> ").unwrap();
readline::add_history(input.as_str());
println!("No you're a {}", input);
}
}
Happy Lisping :-) .
Funny thing is, that I found this question reading the very same book, but not including any book specific information in my search query.
There is now a crate for this. Facon's solution worked for me, but the prompt string always printed as garbage using that library, so I looked for another crate and found one working nicely. Here is an updated example:
cargo.toml:
[dependencies]
# https://crates.io/crates/rustyline
rustyline = "3.0.0"
main.rs:
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;
const HISTORY_FILENAME: &str = "history.txt";
fn main() {
println!("Lispy Version 0.0.1");
println!("Press Ctrl+c to Exit.\n");
// We create an editor for the readline history.
let mut readline_editor = Editor::<()>::new();
// And then load the history, if it exists.
if readline_editor.load_history(HISTORY_FILENAME).is_err() {
println!("No previous history.");
}
loop {
// We read some input from CLI.
let readline = readline_editor.readline("LISPY>> ");
// The reading of the input could fail, if a user uses special
// key combinations. So we match against the readline Result
// type. Result can either be some `Ok` or an some `Err`.
match readline {
Ok(line) => {
readline_editor.add_history_entry(line.as_ref());
println!("No, you are {}", line);
},
Err(ReadlineError::Interrupted) => {
println!("CTRL-C");
break
},
Err(ReadlineError::Eof) => {
println!("CTRL-D");
break
},
Err(err) => {
println!("Error: {:?}", err);
break
}
}
readline_editor.save_history(HISTORY_FILENAME).expect("Could not save to readline history.");
}
}

Unable to setting up the Gecko SDK with Visual Studio 2010

I am creating simple XPCOM plugin for firefox by using the code from.
blog.peschla.net code is straight forward but Im getting following error:
Error 1 error MSB3073: The command "xpidl-build.bat IHelloWorld.idl
:VCEnd" exited with code 1. C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets 103 6 HelloWorld
I am using firefox 22 hence gecko-sdk version 22 and vs2010
I used following files.
I have given link above which contains all the code but I am giving code below as well
1)HelloWorld.h
#include "HelloWorld.h"
NS_IMPL_ISUPPORTS1(HelloWorld, IHelloWorld)
HelloWorld::HelloWorld()
{
mName.Assign(L"Nameless");
}
HelloWorld::~HelloWorld(){}
/* attribute AString name; */
NS_IMETHODIMP HelloWorld::GetName(nsAString & aName)
{
aName.Assign(mName);
return NS_OK;
}
NS_IMETHODIMP HelloWorld::SetName(const nsAString & aName)
{
mName.Assign(aName);
return NS_OK;
}
/* long add (in long a, in long b); */
NS_IMETHODIMP HelloWorld::Add(PRInt32 a, PRInt32 b, PRInt32 *_retval NS_OUTPARAM)
{
*_retval = a + b;
return NS_OK;
}
2)HelloWorld.cpp
#include "HelloWorld.h"
NS_IMPL_ISUPPORTS1(HelloWorld, IHelloWorld)
HelloWorld::HelloWorld()
{
mName.Assign(L"Nameless");
}
HelloWorld::~HelloWorld(){}
/* attribute AString name; */
NS_IMETHODIMP HelloWorld::GetName(nsAString & aName)
{
aName.Assign(mName);
return NS_OK;
}
NS_IMETHODIMP HelloWorld::SetName(const nsAString & aName)
{
mName.Assign(aName);
return NS_OK;
}
/* long add (in long a, in long b); */
NS_IMETHODIMP HelloWorld::Add(PRInt32 a, PRInt32 b, PRInt32 *_retval NS_OUTPARAM)
{
*_retval = a + b;
return NS_OK;
}
3)IHelloWorld.idl
#include "nsISupports.idl"
[scriptable, uuid(2f52e0f0-0eac-11e1-be50-0800200c9a66)]
interface IHelloWorld : nsISupports
{
attribute AString name;
long add(in long a, in long b);
}
4)HelloWorldModule.cpp
#include "mozilla/ModuleUtils.h"
#include "nsIClassInfoImpl.h"
#include "HelloWorld.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(HelloWorld)
// The following line defines a kHELLOWORLD_CID CID variable.
NS_DEFINE_NAMED_CID(HELLOWORLD_CID);
static const mozilla::Module::CIDEntry kSampleCIDs[] = {
{ &kHELLOWORLD_CID, false, NULL, HelloWorldConstructor },
{ NULL }
};
static const mozilla::Module::ContractIDEntry kSampleContracts[] = {
{ HELLOWORLD_CONTRACTID, &kHELLOWORLD_CID },
{ NULL }
};
static const mozilla::Module kSampleModule = {
mozilla::Module::kVersion,
kSampleCIDs,
kSampleContracts,
NULL /* or a category definition if you need it */
};
NSMODULE_DEFN(nsSampleModule) = &kSampleModule;
5)xpidl-build.bat (using as Command Line call to the Pre-Build Event)
..\..\xulrunner-sdk\sdk\bin\xpidl.exe -m header -I..\..\xulrunner-sdk\idl %1
..\..\xulrunner-sdk\sdk\bin\xpidl.exe -m typelib -I..\..\xulrunner-sdk\idl %1
I found my mistake.Reason for error: "I was putting gecko-sdk in wrong directory".Now my project is able to build.
Thanks to all who had replied for this thread.

Resources