Python pygame event - how it works - events

I started recently learning python pygame and I got stuck already at the beginning.
I have following code here:
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
I do not understand how the for event in pygame.event.get() works. What kind of loop is that? It does not say how much times it has to loop, there is no range and event is just a variable, so can anyone explain how it works?
Furthermore how does event.type work? Again, event is just a variable, how does Python recognize that this is an event? I could have named it Pink_Panther or so.

I suggest going to https://www.pygame.org/docs/index.html, the home of all official Pygame documentation.
The loop you are asking about works just like a normal Python for loop. pygame.event.get() returns a list (EventList, to be exact, but that doesn't matter right now). If a for loop is given a list, it iterates through it one element at a time, and puts it into the variable specified: in this case, event. The list that the function returns is full of pygame.event.Event or pygame.event.EventType objects. So each loop the earliest unprocessed event is put into the event variable, and it loops through the code to handle that event. Here are the steps it takes, compared to a normal for loop:
Pygame event loop:
pygame.event.get() returns a list with all unprocessed events.
For every event in the returned list, copy the event to the variable "event" and execute the following code:
your code here
Normal for loop:
For every value in the list or tuple, copy the value to the variable and execute the following code:
your code here
Notice that a common form of a for loop is:
for variable in range(stuff):
range() is actually a function that returns a list! Open your terminal and type the following:
>>> range(5)
[0,1,2,3,4]
pygame.event.get() returns a list in the same way range() returns a list! In Python 3 however, range() doesn't return a list but rather a range object. However, the principle is the same.
If you need more clarification, just let me know in the comments.

Related

How to use while loop in jmeter

I am new to Jmeter and trying to do a while loop operation with a condition. So please someone provide solution for the below query.
Query: I am trying to do DELETE request for 50 times using the id as reference. So I kept the condition as "${startId}<=${endId}" in the while loop. But the while loop is executing infinitely. Is there any simple mechanism to iterate the loop for 50 times by increment the startId till it reaches endId.
While Controller accepts function or variable. So you need to either:
provide a variable which has value of "true" and becomes "false" somewhere else
provide a function which returns "false" to exit from While loop.
With your condition it won't evaluate your expression hence it will never become "false". The solution is to wrap your statement into i.e. __javaScript function as:
${__javaScript(${startId}<=${endId},)}
For more information on JMeter functions see How to Use JMeter Functions post series.
You may take help of loop controller and pre-processor.
snaps :

How to trigger a break when an Array is empty?

In my app, I have a problème when I try to reach an index in an Array, the Array is actually empty. I cannot find what is emptying it so I was wondering if it's possible with the debugger to create a dynamic breakpoint that will pop up when my array is empty. So as soon as something is either resetting the array or taking away its last object, I'd like to know.
I tried to create a symbolic breakpoint with "myArray.isEmpty == true" as the condition but it doesn't look to work the way I want.
Is it possible or I'm just dreaming?
Thanks
As #kendall mentions, you could use didSet to detect when the array is being emptied, and put a breakpoint on it:
// a acts like a normal variable
var a: [Int] = [] {
// but whenever it’s updated, the following runs:
didSet {
if a.isEmpty {
// put a breakpoint on the next line:
println("Array is empty")
}
}
}
a.append(1)
a.append(2)
println(a.removeLast())
// will print “Array is empty” before the value is printed:
println(a.removeLast())
What you want is called a Watchpoint, which lets you monitor changes in memory. I'm not sure yet how to set one on a Swift Array, but that could be a good starting point for research.
One idea would be to add a didSet{} block to the property that holds the array, adding a log statement within - break on that based on your condition that the array is empty.
To the best of my knowledge this isn't possible with Swift and Xcode (or with any other language of IDE I have used). To make this work the IDE would have to continually evaluate the given expression at every step of programs execution.
Now, if arrays were classes, you could subclass and add a breakpoint in an override isEmpty method, but as they are classed you cannot. :-(

What do blocks do?

If someone could shed a light for me, or show an equivalent (if one exists) in PHP-style code, I'd really love it.
This piece of code:
require 'sqlite3'
SQLite3::Database.new("metadata.db").execute("SELECT * from BOOKS") do |row|
puts row
end
uses execute method to issue an SQL query. It's doing a loop, but on what? On the returned value of that query? Can you append a block of code to any expression and it will work on its return value? It seems like the loop isn't connected to anything, and |row| appears from nowhere.
For comparison, in PHP to access a database I would write
$db = new mysqli('details');
$results = $db->query("SELECT * FROM books");
while ($row = $results->fetch()) {
echo $row[0];
}
which says to create a database, store the results of a query as results, then start a loop in which each row of that result is turned into an array to be accessed with array notation. Is that not how Rubyists would do it? What's going on here?
It's doing a loop, but on what? On the returned value of that query?
Right. In your example row is whatever is generated by
SQLite3::Database.new("metadata.db").execute("SELECT * from BOOKS")
In this case row a reasonable thing to call this because any actions you do in the block will be based on that row from the db, but you can choose to call this 'block argument' anything you want.
Is this a thing that happens in Ruby, where you can immediately append a block of code to any expression and it'll work on its return value?
Not really, no. There are some methods that take block arguments - each is a good example.
If you have a collection of, say, cats at the animal hospital, you can loop through them and do operations on each cat because each takes a block argument.
#pretend these cats are objects and not just a string name
cats = [ "mrs. muffin face", "princess cupcake", "deathlord 666", ...]
cats.each do |cat|
#do stuff with each cat here. print their name, find their shoe size, etc
end
Blocks are a very fundamental ruby concept, so it's probably worth reading a bit more about them - this answer links to Why's (poignant) guide to ruby which is generally a good basic reference. I would also suggest Eloquent Ruby for more thorough examples of Ruby.
You seem to be assuming that a block is something that loops on a result, but that is not necessarily correct. A block in Ruby is opposed to arguments. Whereas arguments are evaluated before the execution of the main method, a block is not evaluated in advance. Whether to evaluate that block, under what bindings it is to be evaluated, what timing it is to be evaluated, and how many times it is to be evaluated, all is up to the main method. The block variable in | | is a parameter that the main method passes to the block. Often, elements of the value the main method would have returned without the block are passed one after another, which is the case you had in mind, but that is not always the case.
Here is how execute might be coded in Ruby
class SQLite3::Database
def execute(query_str)
results = db.query(query_str)
while (row = results.fetch)
yield row
end
end
end
(assuming db.query and results.fetch work as you would expect from PHP). As you can see, this is nearly identical to what you're used to from PHP except for that weird yield. As the method loops through the rows of the result, yield passes each row to the block.
This lets you focus on the important stuff (what to do with each row) while hiding away the incidental details (like iterating over a result variable).

How to determine if code is getting executed as a function or using cell mode

I like to use cell mode rather than break points when writing/debugging functions.
How would you determine at run-time if the currently executing code is getting executed as a function or using cell mode?
Bonus Points If you can come up with a function that knows it is was invoked from within another function or from a cell.
An example of when this might be useful is when you want to load data differently during the execution of a function or if you want to create plotters for debugging. It becomes a pain to comment out specific lines when switching between executing as a cell or a function.
function doSomethingAwesome(inputs)
%%
if executingAsCell == true
clear
importData
end
% process stuff
if executingAsCell == true
plot(myAwesomeResults)
end
Note, this is not a duplicate of my previous question: How to determine if code is executing as a script or function?
The simplest approach is using dbstack() as suggested by #Junuxx:
if isempty(dbstack)
%# true if you evaluated the cell while not in debug mode
Similarly, a function can know whether it was invoked from another function or from base/cell by checking the length of the dbstack
function doSomething
if length(dbstack)==1
%# the function has been invoked from a cell or the command line
%# (unless you're in debug mode)
A function can actually distinguish whether it was invoked from command-line or from a cell, since the latter doesn't write into the history:
function doSomething
if length(dbstack)==1
javaHistory=com.mathworks.mlservices.MLCommandHistoryServices.getSessionHistory;
lastCommand = javaHistory(end).toCharArray'; % ' added for SO code highlighting
if strfind(lastCommand,'doSomething')
%# Probably invoked via command line
else
%# Probably invoked via executing a cell
If you want to determine whether you're in debug mode or not, one possibility is to use the line-argument from dbstack, and check whether there is a call to the currently executing function on the line the apparent calling function.

dumping the source code for an anonymous function

original (update follows)
I'm working with a lot of anonymous functions, ie functions declared as part of a dictionary, aka "methods". It's getting pretty painful to debug, because I can't tell what function the errors are happening in.
Vim's backtraces look like this:
Error detected while processing function NamedFunction..2111..2105:
line 1:
E730: using List as a String
This trace shows that the error occurred in the third level down the stack, on the first line of anonymous function #2105. IE NamedFunction called anonymous function #2111, which called anonymous function #2105. NamedFunction is one declared through the normal function NamedFunction() ... endfunction syntax; the others were declared using code like function dict.func() ... endfunction.
So obviously I'd like to find out which function has number 2105.
Assuming that it's still in scope, it's possible to find out what Dictionary entry references it by dumping all of the dictionary variables that might contain that reference. This is sort of awkward and it's difficult to be systematic about it, though I guess I could code up a function to search through all of the loaded dictionaries for a reference to that function, watching out for circular references. Although to be really thorough, it would have to search not only script-local and global dictionaries, but buffer-local dictionaries as well; is there a way to access another buffer's local variables?
Anyway I'm wondering if it's possible to dump the source code for the anonymous function instead. This would be a lot easier and probably more reliable.
update
I ended up asking about this a while back on the vim_use mailing list. Bram Moolenar, aka vim's BDFL, responded by saying that "You are not supposed to use the function number." However, a suitable alternative for this functionality has not been suggested, as of early September 2010. It's also not been explicitly mentioned whether or not this functionality will continue to work in subsequent vim releases. I've not tried to do this (or anything else, for that matter) in the recently released vim 7.3.
The :function command tries to stop you from specifying the numbered functions (their name is just a number) but you can trick it using the {...} dynamic function name feature, throw in some :verbose and you have a winner:
:verbose function {43}
function 43()
Last set from /home/peter/test.vim
1 throw "I am an exception"
endfunction
This was not at all obvious in the help docs.
I use the following workaround: I have one plugin that does some stuff like creating commands, global functions for other plugins. It also registers all plugins, so I have a large dictionary with lots of stuff related to plugins. If I see a error I search for a function that produces it using function findnr:
"{{{3 stuf.findf:
function s:F.stuf.findf(nr, pos, d)
if type(a:d)==2 && string(a:d)=~#"'".a:nr."'"
return a:pos
elseif type(a:d)==type({})
for [key, Value] in items(a:d)
let pos=s:F.stuf.findf(a:nr, a:pos."/".key, Value)
unlet Value
if type(pos)==type("")
return pos
endif
endfor
endif
return 0
endfunction
"{{{3 stuf.findr:
function s:F.stuf.findnr(nr)
for [key, value] in items(s:g.reg.registered)+[["load", {"F": s:F}]]
let pos=s:F.stuf.findf(a:nr, "/".key, value.F)
if type(pos)==type("")
return pos
endif
endfor
return 0
endfunction
Here I have this plugin functions in s:F.{key} dictionaries and other plugins' functions under s:g.reg.registered[plugname].F dictionary.

Resources