Random quote generator repeats the same quotes, why? - ruby

Good day to everyone! There is a quote generator made with Shoes.
#think.click do
#noun_nominative.shuffle
#base.shuffle
#thought.replace(#base.sample)
end
#noun_nominative =
[
"word1", "word2", "word3", "word4",
"word5", "word6", "word7", "word8"
]
#noun_accusative =
[
"word1", "word2", "word3"
]
#base =
[
#noun_nominative.sample.capitalize + "regular quote",
"Regular quote" + #noun_nominative.sample,
"Regular quote" + #noun_accusative.sample,
"Regular quote" + #noun_accusative.sample,
#noun_nominative.sample.capitalize + "regular quote",
"And another one base for a quote"
]
It simply replaces phrases in base array with random words from noun_nominative and noun_accusative, showing a new quote every time button "think" is clicked.
The program should make a brand new quote with every click, however, it keeps showing the same phrases which were generated once. How could I make it regenerate the quotes without reopening the program?
Thank you for answering!

You need to generate random quote on each click, rather than pre-generating them at app startup. This should be the laziest change to do what you want:
def generate_random_quote(nominative, accusative)
all_generated_quotes = [
nominative.sample.capitalize + " - это всякий, кто стремится убить тебя, неважно на чьей он стороне.",
"Иногда " + nominative.sample + " не попадает в " + accusative.sample + ", но " + nominative.sample + " не может промахнуться.",
"Нет ничего труднее, чем гибнуть, не платя смертью за " + accusative.sample + ".",
"Индивидуумы могут составлять " + accusative.sample + ", но только институты могут создать " + accusative.sample + ".",
nominative.sample.capitalize + " - это тот человек, который знает о вас все и не перестает при этом любить вас.",
"Трудно себе представить, что сталось бы с человеком, живи он в государстве, населенном литературными героями."
]
all_generated_quotes.sample
end
#think.click do
freshly_baked_random_quote = generate_random_quote(#noun_nominative, #noun_accusative)
#thought.replace(freshly_baked_random_quote)
end
It is, of course, rather wasteful. It generates all possible quotes and discards all but one. If that's a concern, fixing that would be your homework. :)

Related

How can I call multiple values from the element with the same name with xpath?

I want the last two <dd> elements so that the output will read, Talstrasse 2A 01816 Berggiesshübel
here is the html snippet
<dt>Öffnungszeiten:</dt>
<dd>10:00 - 17:00</dd> <dt>Veranstaltungsart:</dt>
<dd> Herbstmarkt</dd> <dt>Veranstaltungsort:</dt>
<dd> Besucherbergwerk "Marie Louise Stolln" Berggiesshübel</dd> <dt>Strasse:</dt>
<dd>Talstrasse 2A,</dd>
<dt>PLZ / Ort:</dt>
<dd> 01816 Berggiesshübel </dd>
here is the suggested xpath my software gives me.
//div[contains(concat (" ", normalize-space(#class), " "), " container ")]/section[contains(concat (" ", normalize-space(#class), " "), " row event-details ")]/div[1]/div[3][contains(concat (" ", normalize-space(#class), " "), " bg-normal pal mbm ")]/div[1][contains(concat (" ", normalize-space(#class), " "), " row ")]/div[1]/dl[1][contains(concat (" ", normalize-space(#class), " "), " dl-horizontal event-detail-dl ")]/dd[6] | //html/body/div/section/div[1]/div[3]/div[1]/div[1]/dl[1]/dd[6]
can anyone help me?
The last two dd elements would be (//dd)[position() >= last() - 1]. In XPath 2.0 and higher you can get a single string using the string-join function e.g. string-join((//dd)[position() >= last() - 1], ' ').

Expected: 0, instead got: 1 Ruby

I've been working on a task to create a function that returns the total number of smiley faces. Valid smiley faces look like: ":) :D ;-D :~)" and invalid smiling faces: ";( :> :} :] ".
My solution below throws the following error message "expected 0 instead got 1".
def count_smileys(arr)
arr.count do |element|
[":)", ":D", ";-D", ":~)", ";~D", "8~(", ";(", ":>", ":}", ":]",
"8~P", "8-(", "; )", ";-P", ":~P", "~P", ":~P", "~P", "; (", ":-)",
"8~D", "~)", "8D", "~)", "8 )", "; )", "~)", ":-D", " (", ";D",
"8-D", "8-P", ";-D", ": D", ";~D", " ("].include?(element)
end
end
As it stands my solution passes 4 out of 5 basic tests:
Basic tests
Test Passed: Value == 0
Test Passed: Value == 4
Test Passed: Value == 2
Test Passed: Value == 1
Expected: 0, instead got: 1
I've tried removing the parameters but that only worked for the last test and failed me on the rest. Any suggestions? Thanks
Example tests below:
Test.describe("Basic tests") do
Test.assert_equals(count_smileys([]), 0)
Test.assert_equals(count_smileys([":D",":~)",";~D",":)"]), 4)
Test.assert_equals(count_smileys([":)",":(",":D",":O",":;"]), 2)
Test.assert_equals(count_smileys([";]", ":[", ";*", ":$", ";-D"]), 1)
Test.assert_equals(count_smileys([";", ")", ";*", ":$", "8-D"]), 0)
end
Compare or Inspect Using Array Intersection
You don't show your actual test setup, so I won't address that. However, it seems like you're trying to count the number of smileys in a given array using the block form of Array#count. It's arguably simpler to measure the size of an Array intersection, or to inspect the contents of the intersection, using Array#&. For example:
SMILEYS = [
":)", ":D", ";-D", ":~)", ";~D", "8~(", ";(", ":>", ":}", ":]",
"8~P", "8-(", "; )", ";-P", ":~P", "~P", ":~P", "~P", "; (", ":-)",
"8~D", "~)", "8D", "~)", "8 )", "; )", "~)", ":-D", " (", ";D",
"8-D", "8-P", ";-D", ": D", ";~D", " ("
]
SMILEYS.&([":D", ":~)", ";~D", ":)"]).size == 4
#=> true
SMILEYS.&([":)", ":(", ":D", ":O", ":;"]).size == 2
#=> true
SMILEYS.&([";]", ":[", ";*", ":$", ";-D"]).size == 1
#=> true
SMILEYS.&([";", ")", ";*", ":$", "8-D"]).size == 0
#=> false
Note that the last comparison is false because 8-D is defined in your list of SMILEYS. Specifically:
SMILEYS.&([";", ")", ";*", ":$", "8-D"])
#=> ["8-D"]
so the expected value should be 1 unless 8-D doesn't really belong in your array of acceptable values. If that's the case, remove it from the variable or constant containing your allowable values.

Visual Basic cannot display textbox information?

I am working on a vb program, and I am having an error (duh). I'm trying to display the contents of a users input (textbox) in a messagebox, but it's throwing a `System.InvalidCastException'. Here is my code:
Private Sub ThirteenButton1_Click(sender As Object, e As EventArgs) Handles ThirteenButton1.Click
' withdrawBtn
If IsNumeric(withdrawTxtBox.Text) Then
If Val(withdrawTxtBox.Text) > Val(My.Settings.accountBalanceBA) Then
MessageBox.Show("Error: You can not withdraw " + withdrawTxtBox.Text + ", you only have " + My.Settings.accountBalanceBA.ToString + ".")
ElseIf Val(withdrawTxtBox.Text) < Val(My.Settings.accountBalanceBA) Then
MessageBox.Show("Successfully withdrawn $" + Val(withdrawTxtBox.Text) + ". Your remaining balance is $" + Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA.ToString)
End If
End If
End Sub
Entering a number > the account balanceBA will work with no error, but once I enter a number < the balance, it throws the error.
Any help would be greatly appreciated.
The line
MessageBox.Show("Successfully withdrawn $" + Val(withdrawTxtBox.Text) + ". Your remaining balance is $" + Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA.ToString)
Specifically
Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA.ToString
is trying to subtract a string from a number. Use parenthesis to get the order of operations right.
(Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA).ToString
A little advise.. Just avoid using plus sign (+) when performing concatenation, specially when you have mathematical condition to concat with string. You can use "&" instead for concatenation.
Replace plus sign with "&" for best practices.
To correct your code.. you can remove the .ToString or place the .ToString out the subtraction.. after closing parenthesis. ).ToString You have to be careful in using parenthesis to avoid unexpected result or worst will encounter an error.
MessageBox.Show("Successfully withdrawn $" & Val(withdrawTxtBox.Text) & ". Your remaining balance is $" & Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA)
MessageBox.Show("Successfully withdrawn $" & Val(withdrawTxtBox.Text) & ". Your remaining balance is $" & (Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA).ToString

Capturing a screenshot

I'm unable to figure out how to capture a screenshot when a test fails in watir. Please any help/examples?
Here is an exaample of my code
testName = "Entered 000000 - Invalid Unit Number"
browser.text_field(:name => 'unitNumber').set '000000'
browser.button(:name => "OpRetrieve").click
message=browser.text_field(:id => 'messages').text
if message == "Invalid Unit Number"
f1.puts "PASSED #" + testId.to_s + ": " + testName
else
f1.puts "FAILED #" + testId.to_s + ": " + testName + ". Message: " + message
"Capturd screenshot"
end
testId=testId+1
This should do it:
browser.screenshot.save 'screenshot.png'
For more information see http://watir.github.io/docs/screenshots/
This works for phantomjs, I guess it should work for any driver.
browser.driver.screenshot.save 'wtf.png'
Here's a working example I made before. It does something like:
page.driver.render 'test.pdf'
You can achieve like this also.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:\\screenShot1.png"));
for using these you need to import below classes
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.TakesScreenshot;

Carrying an ID with strings to a next page

I'm trying to carry the ID to the next page, but all i manage to get is review.php?ID= without the ID.
Here is the code:
html = html + "Name:" + name + "Type : " + type + "Location : " + location + '<input type="button" value="Write a review!" onclick=parent.location="review.php?ID=" ('+ ID +') />' + "<br/>";
Thanks in advance for any help.
There's a couple things wrong here. You have mismatched quotes (single and double), and I'm pretty sure the id shouldnt have spaces round it with parens. The embeded quotes need to be escaped, too
something like this:
html = html + "Name:" + name + "Type : " + type + "Location : " + location +
"<input type='button' value='Write a review!' onclick='parent.location=\"review.php?ID=("+ID+")\" />" + "<br/>";

Resources