One Minute Man, python 3 - timer

Well, i have this code that is supposed to check if the html is changed by first checking and downloading the html into a string, then checking again every two seconds and printing html if it has changed. The problem is that the script says it has changed all the time, and keeps giving me the same html code back.
#!/usr/bin/env python
import time
start = time.time()
from urllib.request import urlopen
data = str
html = str
def firstcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
html = data
def secondcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
if not html == data:
print(data)
while True:
secondcheck()
time.sleep(2)
print ("it took", time.time() - start, "seconds.")
Thanks in advance;)

You need to tell the interpreter to set the global html variable in the firstcheck() function.
def firstcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
global html
html = data
Right now the secondcheck() function is checking against the html value "str".

It doesn't look like you are calling firstcheck at all, so html is always going to be str. You could make it work by replacing the block inside the while True with:
while True:
firstcheck()
secondcheck()
but it would be cleaner to have a script that looked something like this
while True:
hogniergay = urlopen(url)
result = hogniergay.read()
hogniergay.close()
if result != current:
print (result)
current = result
time.sleep(2)

Related

PHP mailer and FPDF attachment with loop - script stops after first run

I'm running a following script to generate and send email. The email body is generated in a while loop (content differs) - it works fine. But now I have tried to include a script to generate PDF attachment (via FPDF library), in each iteration the attachment is different.
Problem is: the loop runs just once, for the first case and after it stops. Thank you for your commnents in advance.
My code:
<?
$mail = new PHPMailer();
$mail->SMTPDebug = 1;
$mail->isSMTP();
$mail->addReplyTo('');
$mail->isHTML(true);
$mail->Subject = "";
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->CharSet = 'utf-8';
$mail->setFrom('');
while(($data=MySQL_Fetch_Array($vysl))!=NULL) {
require_once('invoicetopdf.php');
$message="";
$mail->AddStringAttachment($invoice, 'Invoice.pdf', 'base64', 'application/pdf');
$mail->Username = "";
$mail->Password = "";
$mail->addAddress($to);
$mail->Body = $message;
if (!$mail->send()) {echo "Mailer Error: " . $mail->ErrorInfo;}
else {
$mail->clearAddresses();
$mail->ClearAllRecipients();
$mail->clearAttachments();
echo "Ok";
}
} //while
//invoicetopdf.php:
$data = MySQL_Fetch_Array($vysl);
require_once('../knihovny/pdf/fpdf.php');
$pdf = new PDF();
$pdf->.....;
$invoice=$pdf->Output('S');
?>
That's a bit of an odd way to run that code repeatedly. I would define a function in your invoicetopdf.php file, load it at the top of your script, and then call the function inside the loop to get the PDF data. You're also calling mysql_fetch_array twice - once in the while loop, once in the function, meaning half your data will be going astray.
require_once('invoicetopdf.php');
while(($data=MySQL_Fetch_Array($vysl))!=NULL) {
$message="";
$mail->AddStringAttachment(generatePDF($data), 'Invoice.pdf', 'base64', 'application/pdf');
...
//invoicetopdf.php:
require_once('../knihovny/pdf/fpdf.php');
function generatePDF($data) {
$pdf = new PDF();
$pdf->.....;
return $invoice=$pdf->Output('S');
}
I also recommend moving the Username and Password out of the loop, and you probably don't need to call clearAllRecipients(); clearAddresses() is enough.
Setting SMTPDebug = 2 will let you see more of what's happening in SMTP land.
Now it works: the main problem was a mixing a class and functions together. See:Multiple PDFs in Loop with FPDF
Thank you guys!

How to store array values in an environment variable in Postman

I am using a postman to automate apis.
Now I am using following request , lets say :-
{
"customerId": "{{currentClientId}}"
}
Where clientid is a dynamic variable whose value is substituted dynamically as 1 , 2, 3,4 so on..
I call this request multiple times using setNextRequest call in this eg lets say 10.This is being done using a counter variable. I am initialising the counter in my previous request to 0 and using for loop with value as counter as 10 calling the request 10 times.There is no response in body just successful http code 204.
I want to store all these clientids coming in request into an environment Client array variable so I wrote a following pre-request script:-
counter = pm.environment.get("counter");
ClientArray = pm.environment.get("ClientArray");
ClientArray.push(pm.environment.get("currentClientId"));
pm.environment.set("ClientArray",ClientArray);
In Test Script, wrote following code :-
counter = pm.environment.get("counter");
if(counter<=10) {
console.log("hi");
postman.setNextRequest("Request");
counter++;
pm.environment.set("counter",counter);
console.log("Counter",counter);
}
The above scipts is throwing
TypeError | ClientArray.push is not a function.
Could someone please advice how to achieve this.
When you retrieve a value from an environment variable like you're doing:
ClientArray = pm.environment.get("ClientArray");
You're not getting an array, you're getting a string which is why you're getting that error. You need to treat the variable like a string, append the currentClientId much like you do for the counter. Something like:
var currentClientIds = pm.environment.get("ClientArray");
currentClientIds = currentClientIds + "," + currentClientId
When you're done appending i.e. out of your loop simply take the string and convert it to an array:
var currentClientIds = pm.environment.get("ClientArray");
var idsArr = curentClientIds.split(',');

Inject user index into body file in Gatling scenario

I want to use ELFileBody and put a variable in a txt file.
This file contains a soap request.
The request (scenario) is executed only one time but as many times as users.
I want to put into file variable, the user index (position in execution).
Something like this :
.set("myVar", userIndex) //myVar is the variable declared in the body file ( ${myVar} )
Here is my code for now :
val users = 1500
val baseUrl = "http://127.0.0.1:7001"
val httpProtocol = http
.baseURL(baseUrl)
.inferHtmlResources()
.acceptEncodingHeader("gzip,deflate")
.contentTypeHeader("text/xml;charset=UTF-8")
.userAgentHeader("Apache-HttpClient/4.1.1 (java 1.5)")
val headers_0 = Map("SOAPAction" -> """""""")
val uri1 = "http://127.0.0.1:7001/myProject-ws/myProjectWebService"
val scn = scenario("Scenario1Name")
.exec(http("scn.Scenario1Name")
.post("/myProject-ws/myProjectWebService")
.headers(headers_0)
.body(RawFileBody("File_0000_request.txt")))
setUp(scn.inject(atOnceUsers(users))).protocols(httpProtocol)
How can I inject the user index into myVar variable in the request body ?
finally, i used a function that return a dynamic reference (id) and I call it from my scenario.
def getDynamicId(): String = {
val formatter = new SimpleDateFormat("yyyyMMddHHmmss.SSS")
val result = "PM".concat(formatter.format(Calendar.getInstance().getTime()))
result
}
//[...]
scenario("ScenarioName")
.exec(session => session.set("myVar", getDynamicId))
// [...]
.body(ElFileBody("BodyFile_0000_request.txt")))
And in the body file, I have the variable ${myVar}
You need read file like e.g.
val customSeparatorFeeder = separatedValues(pathToFile, separator).queue circular
after scenario("Scenario1Name") you need to add .feed(customSeparatorFeeder)
you can read more about it here https://gatling.io/docs/2.3/session/feeder/

Grails read data from file and store it in an object

I am trying to read a file within a controller and store some data in an object, but I cant manage to save it properly. Can anyone help? I am new in Groovy/Grails...
File generals = new File("C:/Grails/Grails-3.3.0/ggts/Test/data.txt")
def line = generals.readLines()
def date = new SetDate(params)
date.save()
date.title = ${line[0]}
date.location = ${line[1]}
date.description = ${line[2]}
date.name = ${line[3]}
date.email = ${line[4]}
date.save()
You may change ${line[0]} to "${line[0]}" and all things alike if you want to use string interpolation.
And as line is a list of String, change ${line[0]} to line[0] is also ok.

image array and .src - image not changing

I have created an array which is being used to store a series of .gif images and I'm just trying to test everything out by using document.getElementById to change the .src value but when I change it and load the page the image stays the same as it was before.
function setImage()
{
var images = new Array();
images[0] = anemone.gif;
images[1] = ball.gif;
images[2] = crab.gif;
images[3] = fish2.gif;
images[4] = gull.gif;
images[5] = jellyfish.gif;
images[6] = moon.gif;
images[7] = sail.gif;
images[8] = shell.gif;
images[9] = snail.gif;
images[10] = sun.gif;
images[11] = sunnies.gif;
images[12] = whale.gif;
var slots = new Array();
slots[0] = document.getElementById("slot" + 0);
slots[1] = document.getElementById("slot" + 1);
slots[2] = document.getElementById("slot" + 2);
slots[0].src = "snail.gif";
document.getElementById('slot0').src = images[0];
alert(images.length);
}
I can't understand why the image wont change, but I know it has to be something very simple. I've been wasting hours trying to get this one thing to change but nothing works. can anyone please point out the error of my ways?
There are a couple of issues with your code:
Your filenames need to be Strings, so they'll have to be quoted (also you can simplify the Array creation):
var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif', 'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif', 'sunnies.gif', 'whale.gif'];
Also make sure you are getting your slot-elements right, quote all the attributes like:
<img id="slot0" class="slot" src="crab.gif" width="120" height="80">
When you create the slots-Array you can do it like this (no need to concat the ID string):
var slots = [document.getElementById('slot0'), document.getElementById('slot1'), document.getElementById('slot2')];
Finally make sure you call your function when the document has loaded / the DOM is ready. If you don't want to use a framework like jQuery your easiest bet is probably still using window.onload:
window.onload = setImage; //note that the parens are missing as you want to refer to the function instead of executing it
Further reading on Arrays, window.onload and DOMReady:
https://developer.mozilla.org/de/docs/DOM/window.onload
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
javascript domready?

Resources