I am trying to read in a text file for a maze program. The input is something like:
10 10
OO+E+OO+++
O++O+O+OOO
OOOOOO+O+O
+++++O++OO
OOO+OOO+O+
O+O+O+++O+
O+O+OOO+OO
++O+++O++O
O+OOOOO++O
O+O++O+OOO
When the user click on the open button, this opens a open file dialog box
{
openFileDialog1->InitialDirectory = "C:\Desktop;";
openFileDialog1->Filter = "Maze files (*.DAT)|*.DAT";
if (openFileDialog1->ShowDialog() == ::DialogResult::OK)
{
char filename[1024];
for (int i = 0; i < openFileDialog1->FileName->Length; i++)
{
filename[i] = openFileDialog1->FileName[i];
}
ifstream ifs;
ifs.open(filename); // NULL terminate this
maze = new Maze( panel1, ifs);
ifs.close();
}
}
the following is the maze constructor
Maze::Maze( Panel ^ drawingPanel, ifstream & ifs )
{
try
{
valid = false;
ifs >> width >> height;
int temp = width;
drawingPanel->Size.Width = width;
drawingPanel->Size.Height = height;
for (int i = 0; i < height; i++) // height is always nothing
for (int j = 0; j < width; j++)
{
if (orig[j][i] == DEADEND ||
orig[j][i] == OPEN ||
orig[j][i] == EXIT )
ifs >> orig[j][i]; // NULLS????
else
throw 'D'; // i had to throw something....so i threw the D /* make a slit class and throw the D there? slit.fill(D); */
}
// this should be last
panel = drawingPanel;
valid = true;
}
catch (...)
{
valid = false;
MessageBox::Show( "Not a proper maze file!" );
}
}
when the program runs: ifs >> width >> height width and height do not get set correctly.
I have searched this site for this problem and have not been able to find anything that has helped. Sorry for my inexperience, any help is greatly appreciated.
You'e program very ugly : don't know if you're programming in C or C++ or C++/CLI, or try to mix the 3...
Because you use Windows Form projet, i will give you a .Net solution for read a file, it's not the better solution but this does not mix things.
First for read the file, on a first window :
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
openFileDialog1->Filter = "Maze Files (*.dat) | *.dat";
if (openFileDialog1->ShowDialog() == ::DialogResult::OK)
{
String ^fileName = openFileDialog1->FileName;
IO::StreamReader ^myMazeFile = gcnew IO::StreamReader(fileName);
String ^content = myMazeFile->ReadToEnd();
richTextBox1->Text = content;
myMazeFile->Close();
// display button for open second form wich draw maze
button2->Visible = true;
}
}
now we have our file content, so we pass it to a second form who will draw the maze :
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
{
String ^content = richTextBox1->Text;
Maze ^frm = gcnew Maze(content);
frm->Show();
}
Second window, create overload constructor :
Maze(String ^contentMap)
{
InitializeComponent();
String ^dimension = getWords(contentMap, 2);
array<String ^> ^coordsString = dimension->Split(gcnew array<Char> {' '});
m_width = Convert::ToInt32(coordsString[0]);
m_height = Convert::ToInt32(coordsString[1]);
panel1->Width = m_width;
panel1->Height = m_height;
}
getWords method :
String ^getWords(String ^input, int numWords)
{
try
{
int words = numWords;
for (int i = 0; i < input->Length; ++i)
{
if (input[i] == ' ' ||input[i] == '\n')
words--;
if (words == 0)
{
return input->Substring(0, i);
}
}
}
catch (Exception ^ex)
{
// ...
}
return String::Empty;
}
You have your dimension in full .Net (private member m_width and m_height).
Related
int[] moodIconRes = {
R.drawable.ic_emoticon_01, R.drawable.ic_emoticon_02, R.drawable.ic_emoticon_03,
R.drawable.ic_emoticon_04, R.drawable.ic_emoticon_05, R.drawable.ic_emoticon_06,
R.drawable.ic_emoticon_07, R.drawable.ic_emoticon_08, R.drawable.ic_emoticon_09,
R.drawable.ic_emoticon_10, R.drawable.ic_emoticon_11, R.drawable.ic_emoticon_12
};
Right now I am using it as a drawable.
private void setData1(HashMap<Integer, Integer> hashMap) {
ArrayList entries = new ArrayList<>();
int totalCount = 0; // 총 기분 수 (전체, 올해, 이번달마다 달라지는 값이므로 호출마다 초기화)
maxMoodIndex = -1; // 제일 많은 기분 종류
maxCount = -1; // 제일 많은 기분의 개수
colors.clear(); // 파이차트를 구성할 색깔배열 clear (전체, 올해, 이번달마다 달라지는 값이므로 clear 필요)
for(int i = 0; i < 12; i++) {
int count = 0;
if(hashMap.containsKey(i)) {
count = hashMap.get(i);
setMoodCount(i, count);
totalCount += count;
addColor(i); // 기분 종류에 맞게 색깔 설정
entries.add(new PieEntry(
count,
"",
ContextCompat.getDrawable(requireContext(), moodIconRes[i])
));
} else {
setMoodCount(i, count); // 개수 0
}
}
I wonder if there is a way to call it in the form of a bitmap or r.id.imageview rather than a drawable image in this part. I'd appreciate it if someone could give me an idea.
You can use BitmapDrawable
Drawable d = new BitmapDrawable(getResources(), bitmap);
i need to create a Service and a Task to calculate the Mandelbrot and JuliaSet.
The calculation is working pretty good and now we need to give it into a Service and call it inside the task.
I have now the Problem, that every Time the task is executed, the Parameters are different.
I wrote a little Setter Function to parse those Arguments to the Service first.
But i'm not sure if this is the right Way?!
I'm also not sure how to correctly call the service in the main Function?
Now it works like this:
First time the service is executed, everything seems to work, but when i call it a secound Time, nothing seems to happen.....
Just to make sure: A Service can execute the Task multiple Times at the same Time?
Is it also posible with different Parameters?
Code Task:
private MandelbrotRenderOptions mandelbrot;
private JuliaRenderOptions juliaset;
private Canvas leftCanvas;
private Canvas rightCanvas;
//Constructor
public RenderTask(Canvas leftCanvas, Canvas rightCanvas) {
this.leftCanvas = leftCanvas;
this.rightCanvas = rightCanvas;
}
public void setOptions(MandelbrotRenderOptions mandelbrot, JuliaRenderOptions juliaset) {
this.mandelbrot = mandelbrot;
this.juliaset = juliaset;
}
#Override
protected Void call() throws Exception {
try {
System.out.println("HALLO SERVICE");
// instances for rendering the left canvas [pixel.data -> PixelWriter -> WritableImage -> GraphicsContext -> Canvas]
// creates an writable image which contains the dimensions of the canvas
WritableImage wimLeftCanvas = new WritableImage((int) leftCanvas.getWidth(), (int) leftCanvas.getHeight());
// instance which can write data into the image (instance above)
PixelWriter pwLeftCanvas = wimLeftCanvas.getPixelWriter();
// instance which fills the canvas
GraphicsContext gcLeftCanvas = leftCanvas.getGraphicsContext2D();
// instances for rendering the right canvas [pixel.data -> PixelWriter -> WritableImage -> GraphicsContext -> Canvas]
WritableImage wimRightCanvas = new WritableImage((int) rightCanvas.getWidth(), (int) rightCanvas.getHeight());
PixelWriter pwRight = wimRightCanvas.getPixelWriter();
GraphicsContext gcRightCanvas = rightCanvas.getGraphicsContext2D();
gcLeftCanvas.clearRect(0, 0, leftCanvas.getWidth(), leftCanvas.getHeight());
//Pixel[][] pixels; // contains pixel data for rendering canvas
// instances for logging the rendered data
SimpleImage simpleImageLeftCanvas = new SimpleImage((int) leftCanvas.getWidth(), (int) leftCanvas.getHeight());
SimpleImage simpleImageRightCanvas = new SimpleImage((int) rightCanvas.getWidth(), (int) rightCanvas.getHeight());
short dataSimpleImage[] = new short[3]; // contains pixel data for logging rendered data
// fills left canvas (mandelbrot) PixelWriter instance with data
Pixel[][] pixels = mandelbrot.setAllPixels();
FractalLogger.logRenderCall(mandelbrot);
for (int y = 0; y < (int) leftCanvas.getHeight(); y++) {
for (int x = 0; x < (int) leftCanvas.getWidth(); x++) {
// parses color data to PixelWriter instance
Color color = Color.rgb(pixels[y][x].getRed(), pixels[y][x].getGreen(), pixels[y][x].getBlue());
pwLeftCanvas.setColor(x, y, color);
for (int depth = 0; depth < 3; depth++) {
if (depth == 0) {
dataSimpleImage[depth] = pixels[y][x].getRed();
} else if (depth == 1) {
dataSimpleImage[depth] = pixels[y][x].getGreen();
} else {
dataSimpleImage[depth] = pixels[y][x].getBlue();
}
}
try {
simpleImageLeftCanvas.setPixel(x, y, dataSimpleImage); // because data must not be null
} catch (InvalidDepthException e) {
e.printStackTrace();
}
}
}
// logs that rendering of mandelbrot is finished
FractalLogger.logRenderFinished(FractalType.MANDELBROT, simpleImageLeftCanvas);
// fills left canvas (juliaset) PixelWriter instance with data
pixels = juliaset.setAllPixels();
FractalLogger.logRenderCall(mandelbrot);
for (int y = 0; y < (int) rightCanvas.getHeight(); y++) {
for (int x = 0; x < (int) rightCanvas.getWidth(); x++) {
// pareses color to PixelWriter instance
Color color = Color.rgb(pixels[y][x].getRed(), pixels[y][x].getGreen(), pixels[y][x].getBlue());
pwRight.setColor(x, y, color);
for (int depth = 0; depth < 3; depth++) {
if (depth == 0) {
dataSimpleImage[depth] = pixels[y][x].getRed();
} else if (depth == 1) {
dataSimpleImage[depth] = pixels[y][x].getGreen();
} else {
dataSimpleImage[depth] = pixels[y][x].getBlue();
}
}
try {
simpleImageRightCanvas.setPixel(x, y, dataSimpleImage); // because data must not be null
} catch (InvalidDepthException e) {
e.printStackTrace();
}
}
}
// logs that rendering of juliaset is finished
FractalLogger.logRenderFinished(FractalType.JULIA, simpleImageRightCanvas);
// writes data from WriteableImage instance to GraphicsContext instance, which finally parses renders it into the canvas
gcLeftCanvas.drawImage(wimLeftCanvas, 0, 0);
FractalLogger.logDrawDone(FractalType.MANDELBROT);
gcRightCanvas.drawImage(wimRightCanvas, 0, 0);
FractalLogger.logDrawDone(FractalType.JULIA);
return null;
} catch (Exception e) {
System.out.println("ERROR");
System.out.println(e);
return null;
}
}
#Override
protected void cancelled()
{
super.cancelled();
updateMessage("The task was cancelled.");
}
#Override
protected void failed()
{
super.failed();
updateMessage("The task failed.");
}
#Override
public void succeeded()
{
super.succeeded();
updateMessage("The task finished successfully.");
} ```
And i call it like this in the main:
``` Service service = new Service() {
#Override
protected Task createTask() {
return new RenderTask(leftCanvas, rightCanvas);
}
};
task.setOptions(mandelbrot, juliaset);
service.restart(); ```
My code involves both Processing and Arduino. 5 different photocells are triggering 5 different sounds. My sound files play only when the ldrvalue is above the threshold.
The Null Pointer Exception is highlighted on this line
for (int i = 0; i < ldrValues.length; i++) {
I am not sure which part of my code should be changed so that I can run it.
import processing.serial.*;
import processing.sound.*;
SoundFile[] soundFiles = new SoundFile[5];
Serial myPort; // Create object from Serial class
int[] ldrValues;
int[] thresholds = {440, 490, 330, 260, 450};
int i = 0;
boolean[] states = {false, false, false, false, false};
void setup() {
size(200, 200);
println((Object[])Serial.list());
String portName = Serial.list()[3];
myPort = new Serial(this, portName, 9600);
soundFiles[0] = new SoundFile(this, "1.mp3");
soundFiles[1] = new SoundFile(this, "2.mp3");
soundFiles[2] = new SoundFile(this, "3.mp3");
soundFiles[3] = new SoundFile(this, "4.mp3");
soundFiles[4] = new SoundFile(this, "5.mp3");
}
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}
You're approach is shall we say optimistic ? :)
It's always assuming there was a message from Serial, always formatted the right way so it could be parsed and there were absolutely 0 issues buffering data (incomplete strings, etc.))
The simplest thing you could do is check if the parsing was successful, otherwise the ldrValues array would still be null:
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
// double check parsing int values from the string was successfully as well, not just buffering the string
if(ldrValues != null){
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}else{
// print a helpful debugging message otherwise
println("error parsing ldrValues from string: " + myString);
}
}
(Didn't know you could parse a int[] with int(): nice!)
I need to transform a ppt file to BMP images in my application but using CopyEnhMetaFile() to my ppt object gives me images that are unreadable by applications such as Windows Photo Viewer .I have to point out that the windows paint utility(Windows 7) can view the files fine . Also ,on my test win xp virtual machine I notice that Windows Photo Viewer can open those BMP fine.
The code I use is shown below:
void PowerPointToPic(CString szDocName, CString szOutDir)
{
CPPTApplication m_powerpointApp;
CPPTPresentations m_powerpointPres;
CPPTPresentation m_powerpointPre;
CPPTSlide slide;
CPPTSlides slides;
m_powerpointPres.ReleaseDispatch();
m_powerpointPre.ReleaseDispatch();
try{
CoInitialize(NULL);
if(!m_powerpointApp.CreateDispatch(_T("PowerPoint.Application"), NULL))
{
AfxMessageBox(_T("-------------------"));
return;
}
}
catch(...)
{
return;
}
m_powerpointApp.m_bAutoRelease=true;
m_powerpointApp.put_Visible(long(1));
m_powerpointApp.put_WindowState(long(2));
m_powerpointPres.AttachDispatch(m_powerpointApp.get_Presentations());
m_powerpointPres.Open(szDocName,TRUE, 1, 1);
m_powerpointPre.AttachDispatch(m_powerpointApp.get_ActivePresentation(),TRUE);
slides = m_powerpointPre.get_Slides();
int pageCount = slides.get_Count();
for( int i = 1; i <= pageCount; i++ )
{
slide = slides.Range(COleVariant((long)i));
slide.Copy();
if (::OpenClipboard(NULL))
{
//BOOL ba=::IsClipboardFormatAvailable(CF_ENHMETAFILE); //
BOOL ba=::IsClipboardFormatAvailable(CF_LOCALE);
HENHMETAFILE hEnhMetaFile = NULL;
//CF_LOCALE
//hEnhMetaFile = (HENHMETAFILE)GetClipboardData(CF_ENHMETAFILE);
hEnhMetaFile = (HENHMETAFILE)GetClipboardData(CF_LOCALE);
if (hEnhMetaFile == NULL)
{
int err = GetLastError();
m_powerpointApp.Quit();
EmptyClipboard();
CloseClipboard();
return;
}
CString temp;
temp.Format(_T("%s-ppt-%d.bmp"), szOutDir, i);
//HERE IS WHERE I SAVE MY METAFILE AS A BMP
HENHMETAFILE hMetaFile= CopyEnhMetaFile(hEnhMetaFile, temp);
if (hMetaFile == NULL)
{
int err = GetLastError();
m_powerpointApp.Quit();
EmptyClipboard();
CloseClipboard();
}
DeleteEnhMetaFile(hMetaFile);
EmptyClipboard();
CloseClipboard();
}
}
m_powerpointPre.Close();
m_powerpointApp.Quit();
m_powerpointPre.ReleaseDispatch();
m_powerpointPres.ReleaseDispatch();
slides.ReleaseDispatch();
slide.ReleaseDispatch();
m_powerpointApp.ReleaseDispatch();
CoUninitialize();
}
I would appreciate any pointer.
Thank you for your time.
Edit:The Export method on the slide object saves .bmp images as I wish but can't do the same on word and excel as I can't figure out how to save ranges.Here is what I have tried.
void WordToPic(CString szDocName, CString szOutDir,QString outDir)
{
_ApplicationWord WordApp;
Documents docs;
_Document doc;
Selection m_sel;
Range rg;
docs.ReleaseDispatch();
m_sel.ReleaseDispatch();
WordApp.m_bAutoRelease = true;
try{
if(CoInitialize(NULL) != 0)
;
if(!WordApp.CreateDispatch(_T("Word.Application"),NULL))//
{
AfxMessageBox(_T("-----------------"));
return ;
}
}
catch (...)
{
return;
}
COleVariant varfilepath((LPCTSTR)szDocName);
COleVariant varstrnull(_T(""));
COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR);
COleVariant vartrue((short)TRUE);
COleVariant varfalse((short)FALSE);
docs.AttachDispatch(WordApp.GetDocuments());
try{
docs.Open(varfilepath,varfalse,vartrue,varfalse,
covOptional,covOptional,varfalse,covOptional,
covOptional,COleVariant(long(1)),covOptional,vartrue,covOptional,covOptional,covOptional,covOptional);
}
catch (...)
{
Sleep(600);
WordApp.Quit(covOptional,covOptional,covOptional);
return;
}
doc.AttachDispatch(WordApp.GetActiveDocument());
m_sel.AttachDispatch(WordApp.GetSelection());//
m_sel.WholeStory();
try {
rg.AttachDispatch(doc.Range(COleVariant(long(0)),COleVariant(m_sel.GetEnd())));
}
catch (...)
{
Sleep(600);
WordApp.Quit(covOptional,covOptional,covOptional);
return;
}
long endDoc = rg.GetEnd();
long start = 0;
long end = 0;
m_sel.SetRange(endDoc,endDoc);
long countPage = ((LPVARIANT)COleVariant(m_sel.GetInformation(1) ) ) ->lVal;
m_sel.SetRange(start,end);
int nCount = countPage;
CString picPath;
int curNum=0;
for (int num = 1; num<nCount+1; num++)//
{
curNum = num;
if (num >1 )
{
rg = m_sel.GoToNext( 1 );
start = rg.GetStart();
}
if( num != countPage )
{
rg = m_sel.GoToNext( 1 );
end = rg.GetStart() - 1;
}
else
end = endDoc;
m_sel.SetRange( start, end );
rg = m_sel.GetRange();
try
{
rg.CopyAsPicture();
//SHOULD SAVE AS IMAGE HERE.
}
catch (...)
{
WordApp.Quit(covOptional,covOptional,covOptional);
return;
}
}
WordApp.Quit(covOptional,covOptional,covOptional);
docs.ReleaseDispatch();
m_sel.ReleaseDispatch();
doc.ReleaseDispatch();
rg.ReleaseDispatch();
WordApp.ReleaseDispatch();
CoUninitialize();
}
and for excel:
void ExcelToPic(CString szExcelName, CString szOutDir)
{
_ApplicationExcel app;
Workbooks books;
_Workbook book;
Worksheets sheets;
_Worksheet sheet;
RangeExcel range;
RangeExcel iCell;
LPDISPATCH lpDisp;
COleVariant vResult;
COleVariant
covTrue((short)TRUE),
covFalse((short)FALSE),
covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
//*****
if (CoInitialize(NULL)!=0) ;
if(!app.CreateDispatch(_T("Excel.Application")))
{
AfxMessageBox(_T("-------------"));
return ;
}
//app.SetVisible(TRUE);
app.SetUserControl(TRUE);
books.AttachDispatch(app.GetWorkbooks());
lpDisp = books.Open((LPCTSTR)szExcelName,
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional );
book.AttachDispatch(lpDisp);
sheets.AttachDispatch(book.GetWorksheets());
long countPage = sheets.GetCount();
RangeExcel usedRange;
for(int i = 1; i < countPage+1; i++)
{
COleVariant vOpt((long)i);
sheet = sheets.GetItem(vOpt);
sheet.Activate();
//*****
usedRange.AttachDispatch(sheet.GetUsedRange());
usedRange.Select();
usedRange.CopyPicture(1,1);
//SAVE AS IMAGE.
}
app.Quit();
app.ReleaseDispatch();
books.ReleaseDispatch();
book.ReleaseDispatch();
sheets.ReleaseDispatch();
sheet.ReleaseDispatch();
range.ReleaseDispatch();
usedRange.ReleaseDispatch();
CoUninitialize();
}
If you can work with images on disk, the PowerPoint .Slide object has an .Export method that takes filename, export filter (in this case "BMP"), width, height as parms (width/height are in pixels).
I work in VB/VBA and may be misunderstanding what you're doing here, but it appears that you're putting an EMF format on the clipboard then saving it out with a BMP extension.
Kind of like putting a label that says "Sugar" on the salt shaker, isn't it? ;-)
I want to take input as a char and concatenate them and write LCD. However I can't it. Also, ı want to not show a symbol which is about enter on LCD.
In this code, input does not written by serial monitor.
#include < LiquidCrystal.h >
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
char karakter;
int ksayi;
String yazi = "";
String kaydirilacak = "";
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.home();
lcd.print("Hello World");
delay(1000);
lcd.clear();
lcd.home();
}
void loop() {
ksayi = Serial.available();
if (ksayi > 0) {
while (Serial.available() > 0) {
karakter = Serial.read();
if (karakter != '/n') {
yazi += karakter;
}
else {
kaydirilacak = yazi;
lcd.clear();
lcd.write(Serial.read(); yazi = "";
}
}
}
Kaydirmaca(kaydirilacak);
}
void Kaydirmaca(String s) {
int i;
for (i = 0; i < 16; i++) {
lcd.scrollDisplayLeft();
delay(275);
}
}
You are printing out Serial.read(), which returns nothing because serial.available() is zero.
Also, your code does not compile. You are missing an end parenthesis.
else {
kaydirilacak=yazi;
lcd.clear();
lcd.write(Serial.read();
yazi="";
}