How To Get A Random Number To Count Down - random

I am trying to get a random number to count down to zero, but what i have keeps giving me a random number. Then every second it will generate a new random number between 4 and 11, and won't count down. if anyone can help it would be greatly appreciated. thanks in advance!
enter code here
private void timer1_Tick(object sender, EventArgs e)
{
Random nuber = new Random();
i = nuber.Next(4, 11);
i--;
textBox1.Text = i.ToString();
if(i == 0)
{
Form1 f1 = new Form1();
Form2 f2 = new Form2();
f2.Show();
f1.Close();
}
}

If I understand what you are trying to do, then you need to generate the number outside of the loop, in an initialization phase, in a static (global) variable. Then the timer tick will count it down. Note your f1 is created and then closed, it never shows, so is superfluous. Also you are creating a new form every time which is maybe not what you want.
Basically you need to move just the two statements:
random nuber = new Random();
i = number.next();
to wherever it is that you create the timer.

Related

Loop values one by one

I am new in Xamarin. I am trying to create my first sample app that will be used loop values one by one. Each button click should print next value. So the first click, should print: 1, second: 2 and so one. How can i do it? Currently i've got only the last value: 9.
for (int i = 0; i < 10; i++)
{
Toast.MakeText(this, i.ToString(), ToastLength.Long).Show();
}
Please try this
Class Yourclass : Activity{
int i = 0;
yourButtonClickEvent(){
i++;
Toast.MakeText(this, i.ToString(), ToastLength.Long).Show();
}}
Update:
I have made a counter variable named i, each time the button is pressed I increase the variable count. So that in your toast you can get the button pressed count and access that required data.
You can maintain a counter variable to achieve this. Make the counter variable global. The counter will keep count for the number of times your button was clicked. Based on the count you can print the next value.

Code is getting slower with every run (PowerPoint VSTO)

I'm writting a PowerPoint AddIn (VSTO) which makes the following (very roughly):
1. Loop through all slides
2. Loop through all tags for each slide and write the tag information to a List-Object
3. Do some calucations on the List-Object and update some columns in the list-Object
4. Loop through the List-Object and write the tags back to the sorresponding slides / tags
I recognized that this code runs for every run slower and slowwer - the 10th run is 3-4 times slower than the first one.
I also see the memory usage goes up for every run.
What are my tools to check where the bottle neck is?
How can I find the problem which makes my code slower for every run?
Is there a way to clear the memory etc. the AddOn uses after each run?
I'm sorry to ask such general question, but please let me know if you need more details
My PowerPoint has 32 Slides - for each slide i want to write tags (in this example 49 Tags). Because of updates etc. the code is executed several times by the user. I simulate this by doing it 11 times automatically. I recognize here the same behavior as by user interaction: the writing of the tags for the 32 Slides is getting slower with every execute.
I reduced my code to the minimum which has the same behavior. I tried also to first delete the tags on every slide but without success.
private void btn_DoIt10Times_Click(object sender, EventArgs e)
{
Stopwatch watch = new Stopwatch();
watch.Start();
SlideTags_Write();
watch.Stop();
//MessageBox.Show("Time spend: " + watch.Elapsed);
for (int i = 1; i <= 10; i++)
{
SlideTags_Write();
}
Stopwatch watch2 = new Stopwatch();
watch2.Start();
SlideTags_Write();
watch2.Stop();
MessageBox.Show("Time 1st run: " + watch.Elapsed + "\n Time 11th run: " + watch2.Elapsed);
}
public void SlideTags_Write()
{
PowerPoint.Presentation oPresentation = Globals.ThisAddIn.Application.ActivePresentation;
foreach (PowerPoint.Slide oSlide in oPresentation.Slides)
{
//for (int iTag = 1; iTag <= oSlide.Tags.Count; iTag++)
//{
// oSlide.Tags.Delete(oSlide.Tags.Name(iTag));
//}
for (int iTag = 1; iTag < 50; iTag++)
{
oSlide.Tags.Add("Tag_" + iTag.ToString(), "Tag Value " + iTag.ToString());
}
}
}

Performance drop loop vs iterator

I am using kotlin in combination with lwjgl. So far I had the following code that ran several thousand times per second:
// val textureMap = HashMap<Int, Texture>()
fun bind() {
var index = 0
for(entry in textureMap) {
glActiveTexture(GL_TEXTURE0 + index)
entry.value.bind()
program.setInt(entry.key, index)
++index
}
}
So while this was running absolutely fast and consumed virtually 0 of my frame time as expected I had to replace it because it created an Iterator in every call, eventually leading to tens of thousands of those objects eventually getting garbage collected and halting my program for a few milliseconds which is of course not usable in my application.
So I went ahead and changed it to the following code:
// textures = ArrayList<Texture>()
// indices = ArrayList<Int>()
fun bind() {
var index = 0
while(index < textures.size) {
val uniform = indices[index]
val texture = textures[index]
glActiveTexture(GL_TEXTURE0 + index)
texture.bind()
program.setInt(uniform, index)
++index
}
}
Now for some reason I am noticing a massive drop in performance, namely the function now uses several seconds per frame. Using jvisualvm I was able to determine that all that time is spent in glActiveTexture in the native part as well as the native function in program.setInt(...). I am absolutely stumped why this is the case, especially after comparing the byte code of the two.
This is the decompiled class file for the first (fast) version:
public final void bind()
{
int index = 0;
Map localMap = (Map)this.textureMap;
for (Map.Entry entry : localMap.entrySet())
{
GL13.glActiveTexture(33984 + index);
((Texture)entry.getValue()).bind(); Program
tmp66_63 = this.program;
if (tmp66_63 == null) {
Intrinsics.throwUninitializedPropertyAccessException("program");
}
tmp66_63.setInt(((Number)entry.getKey()).intValue(), index);
index++;
}
}
And that is the byte code of the slow version:
public final void bind()
{
int index = 0;
while (index < this.textures.size())
{
Integer uniform = (Integer)this.indices.get(index);
Texture texture = (Texture)this.textures.get(index);
GL13.glActiveTexture(33984 + index);
texture.bind(); Program
tmp52_49 = this.program;
if (tmp52_49 == null) {
Intrinsics.throwUninitializedPropertyAccessException("program");
}
Integer tmp62_61 = uniform;Intrinsics.checkExpressionValueIsNotNull(tmp62_61, "uniform");tmp52_49.setInt(tmp62_61.intValue(), index);
index++;
}
}
I am extremely confused what is going on here. In both versions the call to glActiveTexture is GL_TEXTURE0 + <an int value>, yet one takes so much more time thatn the other.
Does anyone have an idea what I am missing here?
Basically my entire question can be removed. I should have debugged and not only profiled. The problem was the code that populated the lists, and it didnt remove the old values so the lists grew larger and larger and the loop just ran so many more times over time...
In case anyone was wondering how I fixed my problem with the allocations I essentially created two collections, one is containing the uniforms and one is mapping them to textures. And then I can iterate over the uniforms and then get the respective texture. So no pointless Iterator objects are created but I am also not having any duplicates :)

Table in Word looks different if halted on breakpoint

I have stumbled on a very annoying problem when setting column widths on a table in Word (using Microsoft Office 15.0 Object Library, VS 2013). If I run the code below without having any breakpoints, the result becomes incorrect (first column width should be 30%), but if I put a breakpoint (e.g.) on line 47, the generated Word file becomes as I want it to be.
The conclusion I make is that when the debugger stops execution, the given column size values are flushed into the data model and the output will be as I want it to be. Without the breakpoint, the merging of cells changes the widths (e.g. the first column becomes 12,5%).
I have searched for some sort of method/function to make the data model adjust to my programmatically given column sizes before the cell merging, with no luck. Anyone out there that can explain why halting on the breakpoint will change the output?
Regards,
Ola
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;
namespace ShowWordProblem
{
class Program
{
private const string WordFileName = #"C:\temp\test.doc";
static void Main(string[] args)
{
var wordApplication = new Application();
wordApplication.Visible = false;
var wordDocument = wordApplication.Documents.Add();
FillDocument(wordDocument);
wordDocument.SaveAs2(WordFileName);
wordDocument.Close();
wordApplication.Quit(Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(wordApplication);
wordApplication = null;
wordApplication = new Microsoft.Office.Interop.Word.Application();
wordApplication.Visible = true;
wordApplication.Documents.Open(WordFileName);
}
private static void FillDocument(Document wordDocument)
{
Range range = wordDocument.Content.Paragraphs.Add().Range;
var table = range.Tables.Add(range, 5, 8);
table.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
table.PreferredWidth = (float)100.0;
table.Columns.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
table.Columns.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
table.Columns[1].PreferredWidth = 30;
for (int i = 2; i <= 8; i++) table.Columns[i].PreferredWidth = 10;
var widths = table.Columns.OfType<Column>().Select(c => c.Width).ToArray();
MergeGroupHeaderCells(table.Rows[1], 5, 9);
MergeGroupHeaderCells(table.Rows[1], 2, 5);
}
private static void MergeGroupHeaderCells(Row row, int startIndex, int lastIndex)
{
var r = row.Cells[startIndex].Range;
Object cell = WdUnits.wdCell;
Object count = lastIndex - startIndex - 1;
r.MoveEnd(ref cell, ref count);
r.Cells.Merge();
}
}
}
Finally I found a way to force the code to apply the given percentage values to the columns before the merging of the cells, and thereby having the correct widths on all columns.
By adding the following line of code after the last PreferredWidth-assignment:
var info = table.Range.Information[WdInformation.wdWithInTable];
it seems that the given PreferredWidth values are propagated to the columns, and the final rendered word document looks exactly as I want it.
/Ola

Java JLabel.getLocation() always returning 0

I'm studying Java so I'm pretty new.
I'm creating a simple 'maze' type game using GUI layouts, images, labels ect..
To create my maze layouts I used an array of strings;
mazeLayout[0] = "WWWWWWWWWW";
mazeLayout[1] = "WSSSWWSWWW";
mazeLayout[2] = "WSWSWWSSSW";
mazeLayout[3] = "WSWSWWWWSW";
mazeLayout[4] = "WSWSWWWWSW";
mazeLayout[5] = "WSWSWSSSSW";
mazeLayout[6] = "WSWSWSWWWW";
mazeLayout[7] = "WSWSWSWWWW";
mazeLayout[8] = "WSWSSSWWWW";
mazeLayout[9] = "WWWWWWWWWW";
and then converted this into a 2d array and placed a label with in image icon in it depending on the string being 'W' for wall or 'S' for space. Also the labels are an array, my thoughts behind this was for restricting movement of the player so they can't walk though walls.
int mw = 0;
int mf = 0;
for(int y = 0; y < 10; y++){
for(int x = 0; x < 10; x++){
mazeLayout2d[y][x] = mazeLayout[y].substring(x, x+1);
if (mazeLayout2d[y][x].equals("W")){
lblmazewall[mw] = new JLabel();
mazewall = new ImageIcon("mazewall.png");
lblmazewall[mw].setIcon(mazewall);
pCenter.add(lblmazewall[mw]);
mw++;
pCenter.revalidate();
}
if (mazeLayout2d[y][x].equals("S")){
lblmazefloor[mf] = new JLabel();
mazefloor = new ImageIcon("mazefloor.png");
lblmazefloor[mf].setIcon(mazefloor);
pCenter.add(lblmazefloor[mf]);
mf++;
pCenter.revalidate();
}
}
}
My problem is when i run this line
System.out.println(lblmazewall[x].getLocation()); //x being any number
I always get java.awt.Point[x=0,y=0]
I would like to know how to get the location of each wall label so i can check it against my player movement.
Is this even a valid way to do something like this?
Could someone teach me a more efficient way?
Sorry for my crude snippets and or bad programming
Thankyou Niall.
public Point getLocation()
Due to the asynchronous nature of native event handling, this method can return outdated values (for instance, after several calls of setLocation() in rapid succession). For this reason, the recommended method of obtaining a component's position is within java.awt.event.ComponentListener.componentMoved(), which is called after the operating system has finished moving the component.
The layout might not have used setLocation() internally. So that getLocation() does not return the value as expected.

Resources