GUI freezing when I use '.get' - python-2.7

Heres the relevant code:
def opencommand():
number=entry1.get()
mydata = csv.reader(open('result.csv','rU'))
card_name = []
for row in mydata:
card_name.append(row[9])
r=0
while r<number:
randomnumbers=[]
counter=0
while counter<5:
randomnumbers.append(randint(1,90))
counter=counter+1
pack1=[]
p=0
while p<5:
pack1.append(card_name[randomnumbers[p]])
p=p+1
print pack1
r=r+1
and....
numpac = Label(options_frame,text='Number of Packs')
entry1 = Entry(options_frame)
numpac.grid(row=0,column=0,sticky=E)
entry1.grid(row=0,column=1)
openbutton = Button(options_frame, text='Open',command=opencommand)
openbutton.grid(row=1,column=0,columnspan=2)
Can anyone tell me why when i include the get part it freezes but if i set it to a fixed number i doesnt?
heres some text as it says theres to much code: vkjberbverihjbvjerhbvjhebvjhervhjberjvhberjhbverhjbvjlerbvjlerbvljerbverjlhbvrejlvhberljvhberljvhberljvbherjlvhberjvlhbevljerbvljerbvlerjhbvelrjbvlerjhbvlejrhbv

Because get() returns a string, not a number. You need to convert it:
number = int(entry1.get())

Related

filtering random objects in django

How can i filter 12 random objects from a model in django .
I tried to do this but It does not work and It just returned me 1 object.
max = product.objects.aggregate(id = Max('id'))
max_p = int(max['id'])
l = []
for s in range(1 , 13):
l.append(random.randint(1 , max_p))
for i in l:
great_proposal = product.objects.filter(id=i)
products = product.objects.all().order_by('-id')[:50]
great_proposal1 = random.sample(list(products) , 12)
Hi . It worked with this code !
Try this:
product.objects.order_by('?')[:12]
The '?' will "sort" randomly and "[:12]" will get only 12 objects.
I'm pretty sure the code is correct, but maybe you did not realize that you're just using great_proposal as variable to save the output, which is not an array, and therefore only returns one output.
Try:
result_array = []
for i in l:
result_array.append(product.objects.filter(index=i))

NZEC error in Python - SPOJ

def multiply(num1, num2):
result = num1 * num2
print(result)
return result
tc = raw_input("") #testcases
tc = [int(tc)]
#count = [int(count)]
count = 0
while ( count < tc) :
var1, var2 = raw_input("").split()
var1, var2 = [int(var1), int(var2)]
multiply (var1,var2)
print '\n'`**enter code here**`
count = count + 1
I'm getting NZEC on SPOJ . I'm new to python programming .
Please help me. Thanks in advance . Link to the Question on SPOJ
There are two issues in you code:
Line 7: tc = [int(tc)]
You shouldn't wrap variable tv into the list. You have created a singleton with the number of test cases as an element. Variable tc should be a number, therefore, the line should look like this:
tc = int(tc)
Line 14: print '\n'**enter code here**
You should remove the weird part "**enter code here**".
After mentioned changes your code should be a correct solution to the MUL problem on Spoj.

How to resize tables generated by Stargazer in R Markdown?

I included resize.height=0.5,resize.width=0.5 in the code chunk, but still can't resize the table generated by stargazer. Can anyone tell me why?
My code chunk options look like this:
echo=FALSE,warning=FALSE,results='asis',resize.height=0.5,resize.width=0.5}
The stargazer codes are like this:
stargazer(did.student,student.control.kmt,student.control.neu,student.control.dpp,header = FALSE,
title="DD Model",
covariate.labels = c("Treatment","group","Treatment*group"),
dep.var.labels = "attitude",
column.labels = c("","party1","Independent","party2"),
label = "DiD-students")
Would appreciate any help!
--
Forgot to mention - I'm using beamer with the table.
I kind of solve the problem myself:
To adjust table size with stargazer, you can change the font size font.size=, make the Stargazer single row single.row = TRUE and change the space between columns column.sep.width = "1pt" in stargazer().
Though the link here suggests using print(stargazer(),scalebox='0.7'), it doesn't work for me perhaps because I'm using Markdown with Beamer, but I'm not sure. Would still love to have more contribution on this.
I was hoping for a more straightforward answer, but this works!
This comment on GitHub inspired me to implement \resizebox{} into stargazer(). You can use resizebox.stargazer() to specify the size of the table outputted from stargazer() with tab.width and/or tab.height arguments. To activate the function, you need to run the following code first:
resizebox.stargazer = function(..., tab.width = "!", tab.height = "!"
){
#Activate str_which() function:
require(stringr)
#Extract the code returned from stargazer()
res = capture.output(
stargazer::stargazer(...)
)
#Render the arguments:
tab.width = tab.width
tab.height = tab.height
#Attach "}" between \end{tabular} and \end{table}
res =
prepend(res, "}", before = length(res))
#Input \resizebox before \begin{tabular}
res =
c(res[1:str_which(res, "^\\\\begin\\{tabular\\}.*")-1],
paste0("\\resizebox{",tab.width,"}{",tab.height,"}{%"),
res[str_which(res, "^\\\\begin\\{tabular\\}.*"):length(res)]
)
#Produce the whole strings
cat(res, sep = "\n")
}
You can specify the table size by e.g. resizebox.stargazer(..., tab.width = "0.7\\textwidth"). Note that you have to write the TeX commands from \\ instead of \.
I would follow #yuan-ning and manipulate the options of stargazer. Try the following for PDF output of R markdown:
stargazer(model_1, model_2, model_3, model_4, model_5,
type = 'latex',
header=FALSE, # to get rid of r package output text
single.row = TRUE, # to put coefficients and standard errors on same line
no.space = TRUE, # to remove the spaces after each line of coefficients
column.sep.width = "3pt", # to reduce column width
font.size = "small" # to make font size smaller
)
Here is an alternative to Carlos' solution that writes the output to a LaTeX file:
mkTexTable <- function(..., file){
tbl <- capture.output({
stargazer(...)
})
tbl <- gsub("\\begin{tabular}", "\\resizebox{\\textwidth}{!}{\\begin{tabular}", tbl, fixed = T)
tbl <- gsub("\\end{tabular}", "\\end{tabular}}", tbl, fixed = T)
fileConn <- file(file)
writeLines(tbl, fileConn)
close(fileConn)
}
mkTexTable(lm1, lm2, "texOutput.tex")
This post also provided some help: https://stackoverflow.com/a/36018251/2289444
If the problem is with html Rmd files, you sould specify {r, results = 'asis'} at the beginning of the chunck and then in stargazer type = 'html'. That worked for me.

TypeError: list indices must be integers, not unicode in python code

I used the split() function to convert string to a list time = time.split() and this is how my output looks like :
[u'1472120400.107']
[u'1472120399.999']
[u'1472120399.334']
[u'1472120397.633']
[u'1472120397.261']
[u'1472120394.328']
[u'1472120393.762']
[u'1472120393.737']
Then I tried accessing the contents of the list using print time[1] which gives the index out of range error (cause only a single value is stored in one list). I checked questions posted by other people and used print len(time). This is the output for that:
1
[u'1472120400.107']
1
[u'1472120399.999']
1
[u'1472120399.334']
1
[u'1472120397.633']
1
[u'1472120397.261']
1
[u'1472120394.328']
1
[u'1472120393.762']
1
[u'1472120393.737']
I do this entire thing inside a for loop because I get logs dynamically and have to extract out just the time.
This is part of my code:
line_collect = lines.collect() #spark function
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
time = time.split()
#print time[1] #index out of range error which is why I wrote another for below
for k in time :
time1 = time[k]#trying to put those individual list values into one variable but get type error
print len(time1)
I get the following error :
time1 = time[k]
TypeError: list indices must be integers, not unicode
Can someone tell me how to read each of those single list values into just one list so I can access each of them using a single index[value]. I'm new to python.
My required output:
time =['1472120400.107','1472120399.999','1472120399.334','1472120397.633','1472120397.261','1472120394.328','1472120393.762','1472120393.737']
so that i can use time[1] to give 1472120399.999 as result.
Update: I misunderstood what you wanted. You have the correct output already and it's a string. The reason you have a u before the string is because it's a unicode string that has 16 bits. u is a python flag to distinguish it from a normal string. Printing it to the screen will give you the correct string. Use it normally as you would any other string.
time = [u'1472120400.107'] # One element just to show
for k in time:
print(k)
Looping over a list using a for loop will give you one value at a time, not the index itself. Consider using enumerate:
for k, value in enumerate(time):
time1 = value # Or time1 = time[k]
print(time1)
Or just getting the value itself:
for k in time:
time1 = k
print(time1)
--
Also, Python is zero based language, so to get the first element out of a list you probably want to use time[0].
Thanks for your help. I finally got the code right:
newlst = []
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
newlst.append(float(time))
print newlst
This will put the whole list values into one list.
Output:
[1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633,
1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737]

Python remove odd numbers and print only even

user = int(raw_input("Type 5 numbers"))
even = []
def purify(odd):
for n in odd:
even.append(n)
if n % 2 > 0:
print n
print purify(user)
Hello I am a beginner and I would like to understand what is wrong with this code.
The User chose 5 numers and I want to print the even numbers only.
Thanks for helping
There are a few problems:
You can't apply int to an overall string, just to one integer at a time.
So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.
Also, your purify function appends every value to the list even without testing it first.
Also, your test is backwards -- you are printing only odd numbers, not even.
Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.
I think this edited version should work.
user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split() # defaults to white space
def purify(odd):
even = []
for n in odd:
if int(n) % 2 == 0:
even.append(n)
return even
print purify(user)
raw_input returns a string and this cannot be converted to type int.
You can use this:
user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]
def purify(x):
new_lst = []
for i in x:
if i % 2 == 0:
new_lst.append(i)
return new_lst
for search even
filter would be the simplest way to "filter" even numbers:
output = filter(lambda x:~x&1, input)
def purify(list_number):
s=[]
for number in list_number:
if number%2==0:
s+=[number]
return s