I have a method play_lottery() that I am trying to run in my script.
The method is called at the base of the script but nothing appears to be executing.
I have put the print 10 line in debugging and I cannot even see execution reaching this point.
Any ideas what is going on here?
This is Python 2.7.10 running on OSX.
def play_lottery():
print 10
num = 0
range = 150000000
while num < range:
yield
print num
num += 1
play_lottery()
Calling your generator function creates a generator object. You never actually request anything from the generator though, so it isn't run.
You need to request values from the generator:
import itertools
lot_gen = play_lottery()
# Take the first 3
vals = list(itertools.islice(lot_gen, 3))
This will at least cause your generator to run.
And you don't need to use islice necessarily. You just need to request values from the generator by some means.
What you have created is the python generator since yield keyword is used in side function. Generators in python are memory friendly. Generators won't execute unless you call next method on generator until StopIteration
Here you code looks fine. All you have to do is either of the following. First take the generator into variable
play_lottery_gen = play_lottery()
Now you can retrieve the next value using next method
play_lottery_gen.next()
Or, you can also built in method next to retrieve the next value
next(play_lottery_gen)
You can convert generator into the list by simply passing it into the list factory function. But it is memory inefficient
list(play_lottery_gen)
Related
I have a .lua file as follows:
timeout = 3000
index = 15
function Test()
A(index, timeout)
B()
end
Test()
A and B fuctions are implemented in the c++. It will be excuted with a 'luaL_dofile(L, "test.lua");' in c++.But the timeout and the index will change at different times.
The question is how to modify the params in real time?
I'm going to write two c++ programs.First one is to sent .lua string to the sencond one. The second c++ program implemets the A and B and will dofile the lua script. But the timeout and the index will changes very often. How to do that? My solution is to parse the index and timeout string ,then write the current value to the file in the first c++ program.Any better solution?
Instead of modifying a lua script over and over to call A with different arguments, you should probably just list all arugments in a single script.
local listOfIndices = {1,5,23,124,25,}
local timeout = 3000
for _,index in ipairs(listOfIndices) do
A(index, timeout)
B()
end
Otherwise having 10000 different indices will result in 10000 file write and read operations.
If you're on Windows you might want to give this a read https://learn.microsoft.com/de-de/windows/win32/ipc/interprocess-communications?redirectedfrom=MSDN
I can think of better ways to have two programs communicate, than sending Lua scripts through files.
Also I'm not sure why you need two applications here, why not add whatever applicaton 2 does to application 1 as a library?
I'm testing defaultdict() vs dict.setdefault() efficiency using timeit. For some reason, execution of timeit returns two values;
from collections import defaultdict
from timeit import timeit
dd = defaultdict(list)
ds = {}
def dset():
for i in xrange(100):
ds.setdefault(i, []).append(i)
def defdict():
for y in xrange(100):
dd[y].append(y)
Then I print the execution time of both functions and I get 4 values reteurned;
print timeit('dset()', setup='from def_dict import dset')
print timeit('defdict()', setup='from def_dict import defdict')
22.3247003333
23.1741990197
11.7763511529
12.6160995785
The Timeit.timeit docs says
Time number executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, measured in seconds as a float. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor.
I'm on Python 2.7.
Shouldn't the timeit return one value? Also examples I've seen online returns a single value.
What is the second value then?
It appears that when timeit imports your script indicated in the setup argument, it actually causes it to be called again. When I use your code in python-3, it gives me two values as well, but when it put the timeit statement in another script, it outputs one value each as it should. Additionally, if you add the line:
if __name__ == "__main__":
Just above your timeit statements, then this will also resolve the issue and will only call timeit once (each).
As far as why the two values differ, I would have to guess that the second is the original call made, and as such gets printed after the second returns and prints, which means it has the additional latency of a) output to the print buffer b) the time to return from the other call.
I'm working on a QT project where a user inputs their full name and the program generates a random 5 character password based off of the letters in their name. Unfortunate I've run into an issue where it works but every time I rerun the program it yields the same result. So it clearly isn't very random. Even after exiting QT Creator and opening it again and running the program with the same user input it yields the same results.
I also am required to generate the password without spaces.
Here is my code:
while(password.length() < 5) {
int index = qrand() % fullName.length();
QChar nextChar = fullName.at(index);
if (!nextChar.isSpace()) {
password.append(nextChar);
}
}
Any solution would be much appreciated.
You need to provide qrand with a suitable seed (usually at program startup). Try:
QTime now= QTime::currentTime() ;
qsrand( now.msec() );
You don't ask about this, but are you checking that fullName's length is not zero (as the program would attempt to divide by zero)? Or that it's not composed of blanks only (as it would loop forever)? A simple solution to both is to trim fullName and check that its length is strictly greater than zero.
The subject line basically says it all.
If I give the location based on the file and a line number, that value can change if I edit the file. In fact it tends to change quite often and in an inconvenient way if I edit more than a single function during refactoring. However, it's less likely to change if it were (line-)relative to the beginning of a function.
In case it's not possible to give the line offset from the start of a function, then is it perhaps possible to use convenience variables to emulate it? I.e. if I would declare convenience variables that map to the start of a particular function (a list that I would keep updated)?
According to help break neither seems to be available, but I thought I'd better ask to be sure.
(gdb) help break
Set breakpoint at specified line or function.
break [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]
PROBE_MODIFIER shall be present if the command is to be placed in a
probe point. Accepted values are `-probe' (for a generic, automatically
guessed probe type) or `-probe-stap' (for a SystemTap probe).
LOCATION may be a line number, function name, or "*" and an address.
If a line number is specified, break at start of code for that line.
If a function is specified, break at start of code for that function.
If an address is specified, break at that exact address.
With no LOCATION, uses current execution address of the selected
stack frame. This is useful for breaking on return to a stack frame.
THREADNUM is the number from "info threads".
CONDITION is a boolean expression.
Multiple breakpoints at one place are permitted, and useful if their
conditions are different.
Do "help breakpoints" for info on other commands dealing with breakpoints.
It's a longstanding request to add this to gdb. However, it doesn't exist right now. It's maybe sort of possible with Python, but perhaps not completely, as Python doesn't currently have access to all the breakpoint re-set events (so the breakpoint might work once but not on re-run or library load or some other inferior change).
However, the quoted text shows a nicer way -- use an probe point. These are so-called "SystemTap probe points", but in reality they're more like a generic ELF + GCC feature -- they originated from the SystemTap project but don't depend on it. These let you mark a spot in the source and easily put a breakpoint on it, regardless of other edits to the source. They are already used on linux distros to mark special spots in the unwinder and longjump runtime routines to make debugging work nicely in the presence of these.
I understand that this is an old question, but I still could not find a better solution even now in 2017. Here's a Python solution. Maybe it's not the most robust/cleanest one, but it works very well in many practical scenarios:
class RelativeFunctionBreakpoint (gdb.Breakpoint):
def __init__(self, functionName, lineOffset):
super().__init__(RelativeFunctionBreakpoint.calculate(functionName, lineOffset))
def calculate(functionName, lineOffset):
"""
Calculates an absolute breakpoint location (file:linenumber)
based on functionName and lineOffset
"""
# get info about the file and line number where the function is defined
info = gdb.execute("info line "+functionName, to_string=True)
# extract file name and line number
m = re.match(r'Line[^\d]+(\d+)[^"]+"([^"]+)', info)
if not m:
raise Exception('Failed to find function %s.' % functionName)
line = int(m.group(1))+lineOffset #add the lineOffset
fileName = m.group(2)
return "%s:%d" % (fileName, line)
USAGE:
basic:
RelativeFunctionBreakpoint("yourFunctionName", lineOffset=5)
custom breakpoint:
class YourCustomBreakpoint (RelativeFunctionBreakpoint):
def __init__(self, funcName, lineOffset, customData):
super().__init__(funcName, lineOffset)
self.customData = customData
def stop(self):
# do something
# here you can access self.customData
return False #or True if you want the execution to stop
Advantages of the solution
relatively fast, because the breakpoint is set only once, before the execution starts
robust to changes in the source file if they don't affect the function
Disadvatages
Of course, it's not robust to the edits in the function itself
Not robust to the changes in the output syntax of the info line funcName gdb command (probably there is a better way to extract the file name and line number)
other? you point out
I am using the IBM cplex optimizer to solve an optimization problem and I don't want all terminal prints that the optimizer does. Is there a member that turns this off in the IloCplex or IloModel class? These are the prints about cuts and iterations. Prints to the terminal are expensive and my problem will eventually be on the order of millions of variables and I don't want to waste time with these superfluous outputs. Thanks.
Using cplex/concert, you can completely turn off cplex's logging to the console with
cpx.setOut(env.getNullStream())
Where cpx is an IloCplex object. You can also use the setOut function to redirect logs to a file.
There are several cplex parameters to control what gets logged, for example MIPInterval will set the number of MIP nodes searched between lines. Turning MIPDisplay to 0 will turn off the display of cuts except when new solutions are found, while MIPDisplay of 5 will show detailed information about every lp-subproblem.
Logging-related parameters include MIPInterval MIPDisplay SimDisplay BarDisplay NetDisplay
You set parameters with the setParam function.
cpx.setParam(IloCplex::MIPInterval, 1000)