Writing program for guessing a number in Small basic but the program won't run - random

this is the code I'm using
Sub btnguess_Click
randNum = Math.GetRandomNumber(10)
FCControls.GetText(txtCels)
If txtCels = randNum Then
lblanswer = "That's correct the Madame would like to hire you!"
ElseIf txtCels <1 or >10 Then
lblanswer = "Please enter number between 1 and 10"
Elseif txtCels <> randNum Then
lblanswer = "That's incorrect the Madame asks you to leave."
EndIf
endsub
error that I'm getting : 45,24:Expected a condition here.
I'm not sure what I'm missing here

The problem is at ElseIf txtCels <1 or >10 Then
When specifying a statement, you can't leave out a condition even if previously mentioned.
You'll have to re-write txtCels before the >10, i.e.
ElseIf txtCels <1 or txtCels >10 Then
Without this, you're essentially saying 'greater than 10' by itself, which makes no sense.

Related

Can this Crystal benchmark code be improved significantly?

I'm deciding on a language to use for back-end use. I've looked at Go, Rust, C++, and I thought I'd look at Crystal because it did reasonably well in some benchmarks. Speed is not the ultimate requirement, however speed is important. The syntax is equally important, and I'm not averse to the Crystal syntax. The simple benchmark that I wrote is only a small part of the evaluation and it's also partly familiarisation. I'm using Windows, so I'm using Crystal 0.35.1 on Win10 2004-19041.329 with WSL2 and Ubuntu 20.04 LTS. I don't know if WSL2 has any impact on performance. The benchmark is primarily using integer arithmetic. Go, Rust, and C++ have almost equal performance to each other (on Win10). I've translated that code to Crystal, and it runs a fair bit slower than those three. Out of simple curiosity I also ran the code on Dart (on Win10), and it ran (very surprisingly) almost twice as fast as those three. I do understand that a simple benchmark does not say a lot. I notice from a recent post that Crystal is more efficient with floats than integers, however this was and is aimed at integers.
This is my first Crystal program, so I thought I should ask - is there any simple improvements I can make to the code for performance? I don't want to improve the algorithm other than to correct errors, because all are using this algorithm.
The code is as follows:
# ------ Prime-number counter. -----#
# Brian 25-Jun-2020 Program written - my first Crystal program.
# -------- METHOD TO CALCULATE APPROXIMATE SQRT ----------#
def fnCalcSqrt(iCurrVal) # Calculate approximate sqrt
iPrevDiv = 0.to_i64
iDiv = (iCurrVal // 10)
if iDiv < 2
iDiv = 2
end
while (true)
begin
iProd = (iDiv * iDiv)
rescue vError
puts "Error = #{vError}, iDiv = #{iDiv}, iCurrVal = #{iCurrVal}"
exit
end
if iPrevDiv < iDiv
iDiff = ((iDiv - iPrevDiv) // 2)
else
iDiff = ((iPrevDiv - iDiv) // 2)
end
iPrevDiv = iDiv
if iProd < iCurrVal # iDiv IS TOO LOW #
if iDiff < 1
iDiff = 1
end
iDiv += iDiff
else
if iDiff < 2
return iDiv
end
iDiv -= iDiff
end
end
end
# ---------- PROGRAM MAINLINE --------------#
print "\nCalculate Primes from 1 to selected number"
#iMills = uninitialized Int32 # CHANGED THIS BECAUSE IN --release DOES NOT WORK
iMills = 0.to_i32
while iMills < 1 || iMills > 100
print "\nEnter the ending number of millions (1 to 100) : "
sInput = gets
if sInput == ""
exit
end
iTemp = sInput.try &.to_i32?
if !iTemp
puts "Please enter a valid number"
puts "iMills = #{iTemp}"
elsif iTemp > 100 # > 100m
puts "Invalid - too big must be from 1 to 100 (million)"
elsif iTemp < 1
puts "Invalid - too small - must be from 1 to 100 (million)"
else
iMills = iTemp
end
end
#iCurrVal = 2 # THIS CAUSES ARITHMETIC OVERFLOW IN SQRT CALC.
iCurrVal = 2.to_i64
iEndVal = iMills * 1_000_000
iPrimeTot = 0
# ----- START OF PRIME NUMBER CALCULATION -----#
sEndVal = iEndVal.format(',', group: 3) # => eg. "10,000,000"
puts "Calculating number of prime numbers from 2 to #{sEndVal} ......"
vStartTime = Time.monotonic
while iCurrVal <= iEndVal
if iCurrVal % 2 != 0 || iCurrVal == 2
iSqrt = fnCalcSqrt(iCurrVal)
tfPrime = true # INIT
iDiv = 2
while iDiv <= iSqrt
if ((iCurrVal % iDiv) == 0)
tfPrime = (iDiv == iCurrVal);
break;
end
iDiv += 1
end
if (tfPrime)
iPrimeTot+=1;
end
end
iCurrVal += 1
end
puts "Elapsed time = #{Time.monotonic - vStartTime}"
puts "prime total = #{iPrimeTot}"
You need to compile with --release flag. By default, the Crystal compiler is focused on compilation speed, so you get a compiled program fast. This is particularly important during development. If you want a program that runs fast, you need to pass the --release flag which tells the compiler to take time for optimizations (that's handled by LLVM btw.).
You might also be able to shave off some time by using wrapping operators like &+ in location where it's guaranteed that the result can'd overflow. That skips some overflow checks.
A few other remarks:
Instead of 0.to_i64, you can just use a Int64 literal: 0_i64.
iMills = uninitialized Int32
Don't use uninitialized here. It's completely wrong. You want that variable to be initialized. There are some use cases for uninitialized in C bindings and some very specific, low-level implementations. It should never be used in most regular code.
I notice from a recent post that Crystal is more efficient with floats than integers
Where did you read that?
Adding type prefixes to identifiers doesn't seem to be very useful in Crystal. The compiler already keeps track of the types. You as the developer shouldn't have to do that, too. I've never seen that before.

vbscript won't read file after 8Mb

I have a file written in vbs that wont read a file after about 8MB. I am currently using "Scripting.FileSystemObject". When I test the code, I notice that it runs fine until line ~79500, thats when the "AtEndOfStream" just results in True. I was looking for documentation, but it seems not to exist.
The code is supposed to show duplicate file information and put it in a separate file, which works well enough till around that line.
This is the section of code giving me the problem (it is the second reading function I have in the code):
Set first = fso.OpenTextFile(filePath + firstFileName)
Set secondFile = fso.OpenTextFile(filePath + secondFileName)
count = 0
countInLine = 0
Do Until secondFile.AtEndOfStream
lineMatches = false
lineOfSecond=secondFile.ReadLine
If count > 79440 Then
MsgBox("first line" & first.AtEndOfStream)
End If
Do Until first.AtEndOfStream
lineOfFirst =first.ReadLine
if lineOfSecond = lineOfFirst Then
lineMatches = True
Exit Do
End If
Loop
If Not lineMatches Then
writeFl.Write(count & "second" & lineOfSecond & vbCrLf)
End If
count = count + 1
Loop

'<=' and '>=' operators do not work

To check if the the installer is installed, I did:
installer status |grep Version| cut -c12-13
The ouput [sic] says:
installer not found
But if it were installed, it would say 11 or 10 (any numeric). If the output is <=10 || >=11, then it would say not installed, and would proceed with the installation. In the library, it gives:
def get_installer_linux_version
begin
cmd = Mixlib::ShellOut.new('installer status |grep Version| cut -c12-13')
cmd.run_command
rescue Errno::ENOENT => e
return '0.0'
end
return 'Version 10' if cmd.stdout.include? '10'
return 'Version 11' if cmd.stdout.include? '11'
end
In the install recipe is:
if get_installer_linux_version.to_i <= 10 || get_installer_linux_version.to_i >= 11
log 'installer is installed'
else
log 'installer is not installed so procceding with the installation'
There are numerous things in your code that could be considered flawed, but for the sake of your question, I will focus on that.
get_installer_linux_version returns a few possible values. Either the string "version 10", "version 11", "0.0", or nil. You call this function, then call to to_i on it.
Maybe this will help illistrate it:
"version 10".to_i
#=> 0
I am going to guess that is not the intended behavior. No matter what happens in your get_installer_linux_version, the returned string will always be 0 after you call to_i on it. You then make condition that <= 10, which 0 is still less than 10, and it logs "installer is installed".
I would also venture to guess that using include? 'XX' is going to end up causing you problems when dealing with version numbers, but that is another question.
To further illustrate, let me write your code as it will always, always, always be as you have it written, and see if something looks off:
if 0 <= 10 || 0 >= 11
log 'installer is installed'
else
log 'installer is not installed so procceding with the installation'
What do you expect the result to be?? Although 0 is not ever going to be greater than 11, it will always be less than 10, so your result is always the same.
Just going to put this here, as it may be relevant the more I look at your sample.
>=
Checks if the value of left operand is greater than or equal to the
value of right operand, if yes then condition becomes true.
<=
Checks if the value of left operand is less than or equal to the value
of right operand, if yes then condition becomes true.

Why isn't .replace working in Ruby Shoes?

I am programming a little game based on the Fate RPG. When the dice are rolled, I want to replace a string with another string using .replace. I can get it to work in an isolated environment, but when I try to call the function from inside my program; it is as if Shoes is completely unaware of it.
Here is a simple example of how the function works that is executing correctly:
Shoes.app {
#push = button "Push me"
#note = para "Nothing pushed so far"
#push.click { #note.replace "Aha! Click!" }
}
And here is the relevant code from my game:
$results = para "Roll results go here.", :align => "center",
:margin_bottom => 20, :margin_top => 8
#roll_button.click {
current_roll = Die.new
current_roll.roll
current_roll.display_dice
current_roll.tally
current_roll.calc_total_roll(1) #param = skill level
$shift = current_roll.calc_total_shift(2) #param = opposition
$results.replace "Actual results"
}
The $results block is in a different position in the code than the #roll_button.click block, but I have tries moving the click block to many different places in the code, and it didn't make a difference, so I don't think its relevant. Thanks.
*edit: Removed unnecessary '=' after $results.replace
I finally got it to work. The problem was the .display_dice function running just before .replace. The offending code is here:
if $result1 == 1
$die1.path = "dice_plus-1.png"
elsif $result1 == 0
$die1.path = "dice_nil-1.png"
elsif $result1 == -1
$die1.path = "dice_minus-1.png"
else
exit(1)
end
I intended the exit(1) to let me know if my dice were receiving values they shouldn't, but it somehow prevented the next line of code from running, even though the flow of the program avoided those lines. The fixed code is here:
if $result1 == 1
$die1.path = "dice_plus-1.png"
elsif $result1 == 0
$die1.path = "dice_nil-1.png"
else $result1 == -1
$die1.path = "dice_minus-1.png"
end
You're not calling a replace method, you're calling a replace= method which probably doesn't exist. Try it without the equals sign.

QTP 10 - A function return deifferent results for same data in run and debug modes

I would extremely appreciate if anyone can suggest a solution for this.
I have a simple function that is is expecting for a browser to be opened on a page containing a web list that each value of it represents an account. When an account is selected it's products (if any) are displayed.
The functions goal is to retrieve an index of an account with products (the first to be found) or -1 if there are none.
The problem, which I can't figure out what is causing it, is that the function will return the correct result when I'm debugging it - meaning running the code step by step using F10, but will return a wrong result if I'll run regularly (F5). This behavior is consistent and the function retrieves the same result each time for each type of runs, meaning it's not a bug that just makes the function return a random answer.
This is the function:
' #return: a random account index with products if one exists
' otherwise returns -1
Public Function getRandomAccountWithProducts()
On Error Resume Next
Set Page1 = Browser("micclass:=browser").Page("micclass:=Page")
Set br = Browser("micclass:=Browser")
originalURL = br.GetROProperty("URL")
br.Navigate Environment.Value("SOME URL") & "REST OF URL"
br.Sync
Page1.WebList("name:=accountId").Select "#1"
br.Sync
' Display only products
Page1.WebRadioGroup("name:=name0").Click
Page1.WebList("name:=name1").Select "Display None"
Page1.WebList("name:=name2").Select "Display None"
Page1.WebButton("value:=Apply","visible:=True").Click
' Init
numOfAccounts = Page1.WebList("name:=accountId").GetROProperty("items count") - 1
If numOfAccounts < 1 Then
getRandomAccountWithProducts = -1
Reporter.ReportEvent micFail, "Number of accounts","There are no accounts. No account with products exists"
Exit Function
End If
hasProducts = false
accountIndex = 1
' Get account with products
While ((Not hasProducts) AND (accountIndex =< numOfAccounts))
' Return account if has products
If Page1.WebList("name:=webListName","index:=0","micclass:=WebList","visible:=True").Exist(5) Then
hasProducts = true
End If
If (Not hasProducts) Then
accountIndex = accountIndex + 1
Page1.WebList("name:=accountId").Select "#" & accountIndex
End If
Wend
br.Navigate originalURL
Set Page1= Nothing
Set br = Nothing
' If no account has products, report and exit, else return selected account index
If Not hasProducts Then
Reporter.ReportEvent micFail,"Accounts","No account has products."
getRandomAccountWithProducts = -1
Else
getRandomAccountWithProducts = accountIndex
End If
If Err<>0 Then
errorMessage = "Error number: " & Err.Number & vbNewLine & "Error description: " & Err.Description & vbNewLine & "Error source: " & Err.Source
Reporter.ReportEvent micFail,"Run Time Error",errorMessage
Err.Clear
End If
On Error GoTo 0
End Function
I'm running on Pentium 4, 3.2 GHZ, 2 GB RAM, Win XP, SP 3,IE 7, QTP 10.0 Build 513
Thanks!
Have you considered using the all items property?
AllItems = Page1.WebList("name:=accountId").GetROProperty("all items")
SplitItems = Split(AllItems, ";")
Found = False
For i = 0 To UBound(AllItems)
If AllItems(i) = "<product>" Then
Found = True
Exit For
End If
Next
Solution was found thanks to Jonty,
The problem was in the following section:
' Get account with products
While ((Not hasProducts) AND (accountIndex =< numOfAccounts))
' Return account if has products
If Page1.WebList("name:=webListName","index:=0","micclass:=WebList","visible:=True").Exist(5) Then
hasProducts = true
End If
If (Not hasProducts) Then
accountIndex = accountIndex + 1
Page1.WebList("name:=accountId").Select "#" & accountIndex
End If
Wend
The first time entered to the loop, the account really didn't have any products, so obviously none was recognized. So accountIndex was increased by one and the corresponding account was selected in the web list.
No here lies the problem. The select method caused a refresh in the page and the condition Page1.WebList("name:=webListName","index:=0","micclass:=WebList","visible:=True").Exist(5)
was evaluated before the web list was loaded thus, returning false.
I considered that option, but I thought (wrongly apparently) that the Exist(5) should do the trick, but it seems that it works differently than expected.
Thanks,
Alon

Resources