title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Indent On New Lines In Console
39,758,895
<p>I have a large block of text. It has line breaks in it, but since the lines are still to long even with the line-breaks, it wraps to the next line. Since all of the other script functions have all lines indented one space, I would like this to match it. I understand that if I print just one line, I can just insert a space, and if I want to indent after a linebreak that fit in one line, I can just insert <code>\n</code> with a space after it.</p> <p>How would I make every line in a block of text indent? e.g:</p> <p><code>text = """This is a block of text. It keeps going on and on and on. It has some line breaks \n but mostly just keeps going on without breaks. The lines are sometimes too long, so they wrap to the next line, but they don't indent. I need to fix this"""</code></p> <p>that would print as:</p> <pre><code>&gt;&gt;&gt; print(text) This is a block of text. It keeps going on and on and on. It has some line breaks but mostly just keeps going on without breaks. The lines are sometimes too long, so they wrap to the next line, but they don't indent. I need to fix this </code></pre>
0
2016-09-28T22:58:23Z
39,761,017
<p>Is this what you are looking for?</p> <pre><code>import textwrap from string import join, split text = """This is a block of text. It keeps going on and on and on. It has some line breaks \n but mostly just keeps going on without breaks. The lines are sometimes too long, so they wrap to the next line, but they don't indent. I need to fix this""" print "\nPrinted as one line:\n" t=join(text.split()) print t print "\nPrinted as formatted paragraph:\n" t=join(text.split()) t=textwrap.wrap(t,width=70,initial_indent=' '*4,subsequent_indent=' '*8) t=join(t,"\n") print t </code></pre> <p>Results:</p> <pre><code>Printed as one line: This is a block of text. It keeps going on and on and on. It has some line breaks but mostly just keeps going on without breaks. The lines are sometimes too lo ng, so they wrap to the next line, but they don't indent. I need to fix this Printed as formatted paragraph: This is a block of text. It keeps going on and on and on. It has some line breaks but mostly just keeps going on without breaks. The lines are sometimes too long, so they wrap to the next line, but they don't indent. I need to fix this </code></pre>
0
2016-09-29T03:40:02Z
[ "python", "console", "auto-indent" ]
Indent On New Lines In Console
39,758,895
<p>I have a large block of text. It has line breaks in it, but since the lines are still to long even with the line-breaks, it wraps to the next line. Since all of the other script functions have all lines indented one space, I would like this to match it. I understand that if I print just one line, I can just insert a space, and if I want to indent after a linebreak that fit in one line, I can just insert <code>\n</code> with a space after it.</p> <p>How would I make every line in a block of text indent? e.g:</p> <p><code>text = """This is a block of text. It keeps going on and on and on. It has some line breaks \n but mostly just keeps going on without breaks. The lines are sometimes too long, so they wrap to the next line, but they don't indent. I need to fix this"""</code></p> <p>that would print as:</p> <pre><code>&gt;&gt;&gt; print(text) This is a block of text. It keeps going on and on and on. It has some line breaks but mostly just keeps going on without breaks. The lines are sometimes too long, so they wrap to the next line, but they don't indent. I need to fix this </code></pre>
0
2016-09-28T22:58:23Z
39,775,911
<p>You said that join, split are failing to import. Try the following:</p> <pre><code>import re, textwrap def myformatting(t): t=re.sub('\s+',' ',t); t=re.sub('^\s+','',t); t=re.sub('\s+$','',t) t=textwrap.wrap(t,width=40,initial_indent=' '*4,subsequent_indent=' '*8) s="" for i in (t): s=s+i+"\n" s=re.sub('\s+$','',s) return(s) text = """\t\tThis is a block of text. It keeps going on and on and on. It has some line breaks \n but mostly just keeps going on without breaks. The lines are sometimes too long, so they wrap to the next line, but they don't indent. I need to fix this""" text=myformatting(text) print text </code></pre>
0
2016-09-29T16:50:15Z
[ "python", "console", "auto-indent" ]
Realizing different column formats with numpy.savetxt
39,758,941
<p>I want to create a <code>.csv</code> file using <code>numpy.savetxt</code>. Each <code>row</code> of the file indicates a certain event. Every row has multiple <code>columns</code> indicating different elements of the event. The information stored in each <code>column</code> is different. Certain <code>columns</code> will contain single <code>float</code> values while others should contain two <code>floats</code> that are connected to each other. If I would call that column when loading the <code>.csv</code> I should obtain the two <code>float</code> values. </p> <p>I have the following code:</p> <pre><code>import numpy rows = 5 columns = 2 save_values = numpy.zeros((rows, columns)) for idx in xrange(rows): column_0 = float(idx) column_1 = [idx + 5., idx + 15.] save_values[idx, :] = column_0, column_1 numpy.savetxt("outfile.csv", save_values, delimiter = ",") </code></pre> <p>This however results in the following error message: </p> <pre><code> save_values[idx, :] = column_0, column_1 ValueError: setting an array element with a sequence. </code></pre> <p>which is understandable. However, despite knowing why it is going wrong I am having a hard time realizing my goal.</p> <p>How can I achieve my goal?</p>
0
2016-09-28T23:03:56Z
39,759,564
<p>You aren't even getting to the <code>savetxt</code> step.</p> <pre><code>save_values[idx, :] = column_0, column_1 </code></pre> <p>the target is 2 values (2 columns). The source is <code>idx</code> and a list.</p> <p>That's why it's giving you the 'setting with a sequence' error. It can't put the list in <code>save_values[idx,1]</code>.</p> <p>You could define a <code>save_values</code> array that has 2 fields, and one of the fields having 2 elements. But how would you save it?</p> <p>How should the text file appear - 3 columns separated by <code>,</code>? or two columns with special structure inside the 2nd?, e.g.</p> <pre><code> 1.2, 3.5, 4.2 # or 1.2, [2.5, 4.2] </code></pre> <p>That in turn raises the issue of what can be loaded. <code>genfromtxt</code> can handle the 3 columns; it can't readily hand the nested columns. As a default <code>genfromtxt</code> would read the 3 column case as 3 columns, but it is possible to give it the 2 fields <code>dtype</code>.</p> <p>Anyways, for saving I think generating 3 columns is simplest. Reloading could be done with columns or fields.</p> <p>I can generate a compound dtype array with:</p> <pre><code>In [329]: dt = np.dtype('i,(2,)f') In [330]: dt Out[330]: dtype([('f0', '&lt;i4'), ('f1', '&lt;f4', (2,))]) In [331]: save_values = np.zeros((5,),dtype=dt) In [332]: for i in range(5): ...: save_values[i]=(i,(i+5., i+15.)) ...: In [333]: save_values Out[333]: array([(0, [5.0, 15.0]), (1, [6.0, 16.0]), (2, [7.0, 17.0]), (3, [8.0, 18.0]), (4, [9.0, 19.0])], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f4', (2,))]) </code></pre> <p>But if I try to save it I get an error</p> <pre><code>In [334]: np.savetxt('test.txt',save_values,delimiter=',') ... TypeError: Mismatch between array dtype ('[('f0', '&lt;i4'), ('f1', '&lt;f4', (2,))]') and format specifier ('%.18e,%.18e') </code></pre> <p>I can save it by spelling out the write format, <code>fmt%tuple(save_values[0])</code>, but that puts <code>[]</code> in the output:</p> <pre><code>In [335]: np.savetxt('test.txt',save_values,fmt='%10d, %s') In [336]: cat test.txt 0, [ 5. 15.] 1, [ 6. 16.] 2, [ 7. 17.] 3, [ 8. 18.] 4, [ 9. 19.] </code></pre> <p>I can flatten the array dtype with a view (here I'm keeping the 1st field integer just to keep things interesting):</p> <pre><code>In [337]: dt1=np.dtype('i,f,f') In [338]: save_values.view(dt1) Out[338]: array([(0, 5.0, 15.0), (1, 6.0, 16.0), (2, 7.0, 17.0), (3, 8.0, 18.0), (4, 9.0, 19.0)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f4'), ('f2', '&lt;f4')]) </code></pre> <p>Now I can save it as 3 columns:</p> <pre><code>In [340]: np.savetxt('test.txt',save_values.view(dt1),fmt='%10d, %10f, %10f') In [341]: cat test.txt 0, 5.000000, 15.000000 1, 6.000000, 16.000000 2, 7.000000, 17.000000 3, 8.000000, 18.000000 4, 9.000000, 19.000000 </code></pre> <p>and I can reload it with either dtype:</p> <pre><code>In [342]: np.genfromtxt('test.txt',delimiter=',',dtype=dt) Out[342]: array([(0, [5.0, 15.0]), (1, [6.0, 16.0]), (2, [7.0, 17.0]), (3, [8.0, 18.0]), (4, [9.0, 19.0])], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f4', (2,))]) In [343]: np.genfromtxt('test.txt',delimiter=',',dtype=dt1) Out[343]: array([(0, 5.0, 15.0), (1, 6.0, 16.0), (2, 7.0, 17.0), (3, 8.0, 18.0), (4, 9.0, 19.0)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f4'), ('f2', '&lt;f4')]) </code></pre> <p>I could have also created the <code>text.txt</code> with a 5x3 array of floats.</p> <p>The key point with <code>savetxt</code> is that it iterates over the rows your array, formats them, and writes that line to the file. So your array has to work with:</p> <pre><code>for row in myarray: print(fmt % tuple(row)) </code></pre> <p><code>fmt</code> may be be spelled out, or may build from a single field format, eg.</p> <pre><code>fmt = ','.join(['%10f']*3) # or fmt = '%10d, %10f, %10f' </code></pre> <p>So it comes down to standard Python string formatting.</p>
0
2016-09-29T00:28:19Z
[ "python", "csv", "numpy", "save" ]
Python - How can I pass multiple arguments using Pool map
39,759,046
<p>This is a sniplet of my code:</p> <pre><code>data = [currentAccount.login,currentAccount.password,campaign.titlesFile,campaign.licLocFile,campaign.subCity,campaign.bodiesMainFile,campaign.bodiesKeywordsFile,campaign.bodiesIntroFile] results = multiprocessing.Pool(5).map(partial(self.postAd,data),range(3)) ... def postAd (self,login,password,titlesFile,licLocFile,subCity,bodiesMainFile,bodiesKeywordsFile,bodiesIntroFile): ... </code></pre> <p>(Just so you know what's going on: currentAccount and campaign are classes, those are variables within those classes. Using self b/c this is all being run in a class. I'm trying to run self.postAd 3x passing it all the variables I have in data)</p> <p>When I run that it says " postAd() missing 6 required positional arguments: 'titlesFile', 'licLocFile', 'subCity', 'bodiesMainFile', 'bodiesKeywordsFile', and 'bodiesIntroFile'"</p> <p>What am I doing wrong? Why does it only accept 2 variables?</p> <p>If I cant use Pool map, how should I be doing this?</p> <p>I also tried this with no success:</p> <pre><code>results = multiprocessing.Pool(5).map(lambda args: self.postAd(currentAccount.login,currentAccount.password,campaign.titlesFile,campaign.licLocFile,campaign.subCity,campaign.bodiesMainFile,campaign.bodiesKeywordsFile,campaign.bodiesIntroFile), range(3)) Error: Can't pickle &lt;function NewPostService.processNewAds.&lt;locals&gt;.&lt;lambda&gt; at 0x0000000002F3CBF8&gt;: attribute lookup &lt;lambda&gt; on functions failed </code></pre>
0
2016-09-28T23:16:37Z
39,759,667
<p>Your first attempt is a misuse of <code>partial</code>. <code>data</code> is a single argument: it being a list doesn't automatically unpack its contents. <code>partial</code> simply takes variable arguments and so you should pass those arguments 'normally', either </p> <pre><code>partial(self.postAd, currentAccount.login,currentAccount.password, ... </code></pre> <p>or</p> <pre><code>partial(self.postAd, *data) </code></pre> <p>The reason it says that <code>postAd</code> received two arguments instead of just one (<code>data</code>) is that it also implicitly received the <code>self</code> argument.</p> <p>Your second attempt is the right idea and very close, but it so happens that <a href="http://bugs.python.org/issue19272" rel="nofollow">in older versions of python pickle (which is essential for multiprocessing) can't handle lambdas</a>. Replace the lambda with a named function defined using <code>def</code>:</p> <pre><code>def postNow(arg): # Accepts an argument from map which it ignores self.postAd(currentAccount.login, ..., campaign.bodiesIntroFile) </code></pre> <p>Side notes:</p> <p>It's a bit odd that your argument to the lambda is called <code>args</code> when it's just one argument. If your intention is to make it flexible and accept variable arguments, use <code>lambda *args: ...</code> or even <code>lambda *args, **kwargs: ...</code> to accept keyword arguments. The names are not important, they are just convention. The important part is the <code>*</code> and <code>**</code>. Note that <code>partial</code> has a signature like this, as an example.</p> <p>I have never seen this issue with the second attempt before. I learnt it by Googling the error message. Always Google things.</p>
0
2016-09-29T00:43:18Z
[ "python", "multiprocessing" ]
I cant move up and down with my code
39,759,049
<p>Here is the code I used to use a rectangle move for a game. But every time I press the up and down keys, it goes left and right. If you can paste the correct version in your answer. Thanks!!!! </p> <p>p.s the # is a comment</p> <pre><code>#to start pygame import pygame pygame.init() #game window gameWindow = pygame.display.set_mode((1000, 600)) pygame.display.set_caption("SimpleShooter") #moving character class PlayerActive(): def __init__(self): self.image = pygame.Surface((50, 50)) self.image.fill((0, 0, 255)) self.rect = self.image.get_rect() self.rect.x = 50 self.rect.y = 50 self.speed = 1 def move(self, xdir, ydir): self.rect.x += xdir*self.speed self.rect.x += ydir*self.speed player = PlayerActive() #starting and ending the game gameActive = True while gameActive: for event in pygame.event.get(): #print event (optional) if event.type == pygame.QUIT: gameActive = False #moving character activekey = pygame.key.get_pressed() if activekey[pygame.K_RIGHT]: player.move(1, 0) if activekey[pygame.K_LEFT]: player.move(-1, 0) if activekey[pygame.K_UP]: player.move(0, -1) if activekey[pygame.K_DOWN]: player.move(0, 1) #change the main screen gameWindow.fill((255, 255, 255)) #place moving character gameWindow.blit(player.image, player.rect) #how to draw rectangles pygame.draw.rect(gameWindow, (0, 0, 0), (50, 195, 50, 50), 5) #use to show shapes on gameWindow pygame.display.update() #quit game pygame.quit() quit() </code></pre>
0
2016-09-28T23:16:47Z
39,759,062
<p>The following: </p> <pre><code>def move(self, xdir, ydir): self.rect.x += xdir*self.speed self.rect.x += ydir*self.speed </code></pre> <p>Should be changed to:</p> <pre><code>def move(self, xdir, ydir): self.rect.x += xdir*self.speed self.rect.y += ydir*self.speed </code></pre> <p>You were always incrementing <code>x</code> regardless of if the change was in <code>xdir</code> or <code>ydir</code>. The change change <code>rect.y</code> for <code>ydir</code> and <code>rect.x</code> for <code>xdir</code>.</p>
1
2016-09-28T23:18:21Z
[ "python", "pygame" ]
Python PUT Request to Confluence Webpage - ValueError: No JSON object could be decoded, but <Response [200]>
39,759,155
<p>I'm trying to update some data on a confluence webpage. Everything works fine in Postman (the data is updated). However, when I use python and the requests module I'm getting the following error:</p> <blockquote> <p>ValueError: No JSON object could be decoded</p> </blockquote> <p>The strangest thing is I'm getting a 200 status code back but the webpage isn't updating. The error seems to root from typing 'r.json'.</p> <p>Here is my code (I'm trying to change the content of the webpage to 'Hello World'):</p> <pre><code>import requests import json url = &lt;url&gt; data = { "id": "18219205", "title": "Testapi", "type": "page", "version": { "number": 11 }, "body": { "storage": { "representation": "storage", "value": "Hello world." } } } dumped_data = json.dumps(data) headers = { 'content-type': "application/json", 'authorization': "Basic &lt;token number&gt;", 'cache-control': "no-cache", 'postman-token': "&lt;another token&gt;" } r = requests.put(url, data=dumped_data, headers=headers, verify=False) print r.json() </code></pre>
0
2016-09-28T23:32:09Z
39,759,463
<p>This is happening because the API you're posting to doesn't respond with JSON, so when you call <code>r.json()</code> requests tries to parse the body of the response as JSON and fails. You're seeing a 200 because you were able to send the data to the server correctly, you're just trying to read the response wrong.</p> <p>From the <a href="http://docs.python-requests.org/en/master/user/quickstart/" rel="nofollow">Requests docs</a>:</p> <blockquote> <p>For example, if the response gets a 204 (No Content), or if the response contains invalid JSON, attempting r.json() raises ValueError: No JSON object could be decoded.</p> </blockquote>
0
2016-09-29T00:14:05Z
[ "python", "python-requests", "put", "confluence" ]
How to save value returned from python function if call does not capture return
39,759,188
<p>Let's say I have a python function, where <code>x</code> and <code>y</code> are relatively large objects (lists, NumPy matrices, etc.):</p> <pre><code>def myfun(x): y=some complicated function of x return y </code></pre> <p>If in an interactive session the user calls this as: </p> <pre><code>myfun(5) </code></pre> <p>The call is basically useless, since <code>y</code> is lost. Let's also suppose the function takes a while to run. Is there a way to retrieve the answer, so the user doesn't have to re-run, i.e. <code>answer=myfun(5)</code>? Alternatively, what is a good (pythonic) way to write the function to make it 'fool-proof' for this scenario? Some not-so-great options are:</p> <p>Require a parameter that stores the value, e.g.</p> <pre><code>def myfun(x,y): y = some complicated function of x return y </code></pre> <p>Or maybe:</p> <pre><code>def myfun(x): y = some complicated function of x global temp temp = y return y </code></pre> <p>In the latter case, if a user then mistakenly called <code>myfun(5)</code>, there's the option of <code>y=temp</code> to get the answer back.. but using <code>global</code> just seems wrong.</p>
0
2016-09-28T23:35:11Z
39,759,197
<p><code>y=_</code></p> <p>assuming you are in the interactive python console. <code>_</code> is magic that holds the last "result"</p>
4
2016-09-28T23:36:16Z
[ "python" ]
Showing characters instead of integers in arcs in OpenFST(PyFST)
39,759,240
<p>I'm using the method <code>linear_chain</code> to accept a <code>String</code>. When I convert it into a <code>fst binary</code> to then into a <code>DOT</code> format, I get integers instead of the characters. Also, I have a SymbolTable for each of the corresponding letters being read.</p> <p>What I need is to show the characters instead, be by the command line or by coding directly in Python. Any help or reference would be greatly appreciated.</p>
3
2016-09-28T23:42:51Z
39,793,772
<p>To do this on the command line, make sure you provide both an input and output symbol table. The command should be something like</p> <pre><code>fstdraw --isymbols=input_syms.txt --osymbols=output_syms.txt fst.bin </code></pre> <p>I haven't used "PyFST", but I would suggest you use the Python bindings that are included in OpenFst 1.5.1 and later. The Python support has been getting better in versions 1.5.x, so it's best to use 1.5.3 or later.</p> <p>If using the OpenFST provided Python bindings, make sure you set the symbol tables before attempting to draw.</p> <pre><code>fst.input_symbols = your_symbol_table fst.output_symbols = your_symbol_table fst.draw("fst.dot") </code></pre> <p>There is more documentation for these Python bindings available here: <a href="http://www.openfst.org/twiki/bin/view/FST/PythonExtension" rel="nofollow">http://www.openfst.org/twiki/bin/view/FST/PythonExtension</a></p> <p>If that doesn't help, could you post some example code please?</p>
0
2016-09-30T14:23:03Z
[ "python", "openfst" ]
Ascii stream with missing bits (no parity)
39,759,265
<p>I've been given a task to look for 0's and 1's in a real textbook in order to decipher an ASCII message from it. The problem is that it's really hard to find all 0's and 1's and I have the feeling I am skipping a lot of them. This completely messes up the ASCII conversion. Some of the things I tried:</p> <ul> <li>'synchronize' words by detecting spaces (or something close to a space)</li> <li>trying to correct chars based on assumption of only alphabet characters (a-z, A-Z)</li> <li>trying to correct words based on the assumption of frequency of chars in the language (Dutch)</li> </ul> <p>But I still didn't get much out of it with the main problem being synchronization (when does a new char start?). I probably have to run through the books again (sigh, 3rd time or so) but I was wondering if you guys have any other ideas for the problem of missing bits in an ASCII binary stream?</p>
2
2016-09-28T23:47:26Z
39,759,298
<pre><code>all_ones_and_zeros = re.findall("[01]",corpus_of_text) BITS_PER_ASCII = 8 #(ascii characters are all the ordinals from 0-255 ... or 8 bits) asciis = zip([iter(all_ones_and_zeros)]*BITS_PER_ASCII) bins = [''.join(x) for x in asciis] chars = [chr(int(y,2)) for y in bins] print "MSG:",chars </code></pre> <p>I guess ... its not very clear what your input or expected output is ...</p>
0
2016-09-28T23:52:32Z
[ "python", "ascii", "parity" ]
User form has fields with unwanted initial value, Django
39,759,273
<p>I'm trying to create a view to allow a User to create another User. The problem is that the generated form has initial values for the 'password' and 'last_name' fields, and I don't know why. I need to remove those initial values.</p> <p>I have created a UserForm with ModelForm.</p> <pre><code>class UserForm(forms.ModelForm): # I've tried this, but it doesn't change anything #def __init__(self, *args, **kwargs): #super(UserForm, self).__init__(*args, **kwargs) #self.fields['password'].value = '' #self.fields['last_name'].value = '' password = forms.CharField(widget=forms.PasswordInput(render_value=True)) class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name' ] </code></pre> <p>Then I have the view. I have coded the view following the same pattern for creating views for other objects. After having this problem, I wrote the view down to this:</p> <pre><code>def create_user(request): user_form = UserForm() context = { "user_form": user_form, } return render(request, "remote/user/user_create_form.html", context) </code></pre> <p>I was hoping that if I only tried to display the form, and not treat the form data, this problem would not appear, but it does.</p> <p>My template has this (I'm using crispy forms): </p> <pre><code>&lt;form action="" method="POST"&gt;{% csrf_token %} {{ user_form|crispy }} &lt;input type="submit" class="btn btn-primary" value="Registar" /&gt; &lt;/form&gt; </code></pre> <p>Here is what the form looks like initially: <a href="http://i.stack.imgur.com/wTt4d.png" rel="nofollow">password and last_name fields have initial values</a></p>
0
2016-09-28T23:48:23Z
39,761,484
<p>It's because while testing,You might have used browser feature of saving the field and form data i.e. autosave the password.It generally saves the password and just previous field of the form.Please clear your cache and form autofill data from browser settings. Let us know if the error still exists. Thanks</p>
0
2016-09-29T04:34:43Z
[ "python", "django", "django-forms", "user" ]
Trying to plot a random series on a chart with matplotlib, but the chart will not display when the programe is ran.
39,759,301
<p>The following code will run with no errors, but the chart that I am trying to display will not pop up. I see the screen blink when I run the program like the chart is going to load but that is it, just a quick flash of the screen. Then my command line reads "press any key to continue" which is normal when my programs are finished running, but there is no chart???</p> <pre><code>import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np seedval = 111111 np.random.seed(seedval) s= pd.Series(np.random.randn(1096),index=pd.date_range('2012-01-01','2014-12-31')) walk_ts = s.cumsum() walk_ts.plot() </code></pre> <p>This is the output </p> <pre><code>Press any key to continue . . . </code></pre>
0
2016-09-28T23:52:44Z
39,760,572
<p>It's not clear if you're doing this in a script, interactive python session or ipython. In the first case you need to call <code>plt.show()</code> at the end to show any figures. That's what you can do in a regular interactive python session as well. In ipython you're better off using <code>%matplotlib inline</code> to set everything up for you. </p>
0
2016-09-29T02:45:40Z
[ "python", "pandas", "matplotlib", "dataframe", "charts" ]
Trying to plot a random series on a chart with matplotlib, but the chart will not display when the programe is ran.
39,759,301
<p>The following code will run with no errors, but the chart that I am trying to display will not pop up. I see the screen blink when I run the program like the chart is going to load but that is it, just a quick flash of the screen. Then my command line reads "press any key to continue" which is normal when my programs are finished running, but there is no chart???</p> <pre><code>import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np seedval = 111111 np.random.seed(seedval) s= pd.Series(np.random.randn(1096),index=pd.date_range('2012-01-01','2014-12-31')) walk_ts = s.cumsum() walk_ts.plot() </code></pre> <p>This is the output </p> <pre><code>Press any key to continue . . . </code></pre>
0
2016-09-28T23:52:44Z
39,776,860
<p>You can add this line at the top of your code:</p> <pre><code>% matplotlib inline </code></pre> <p>Here is a good example using your data:</p> <p><a href="http://i.stack.imgur.com/neD0y.png" rel="nofollow"><img src="http://i.stack.imgur.com/neD0y.png" alt="enter image description here"></a></p>
0
2016-09-29T17:47:55Z
[ "python", "pandas", "matplotlib", "dataframe", "charts" ]
Script Error from "Simple Digit Recognition OCR in OpenCV-Python"
39,759,312
<p>I have update the Script but one Error i can not fix. Here my script Version:</p> <pre><code>import sys import numpy as np import cv2 im = cv2.imread('test001.png') res = cv2.resize(im,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC) im3 = res.copy() gray = cv2.cvtColor(res,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2) ################# Now finding Contours ################### _,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) samples = np.empty((0,100)) responses = [] keys = [i for i in range(48,58)] for cnt in contours: if (cv2.contourArea(cnt)&gt;50) and (cv2.contourArea(cnt)&lt;900): [x,y,w,h] = cv2.boundingRect(cnt) if ((h&gt;0) and (h&lt;35)) and ((w&gt;0) and (w&lt;35)): cv2.rectangle(res,(x,y),(x+w,y+h),(0,0,255),1) roi = thresh[y:y+h,x:x+w] roismall = cv2.resize(roi,(30,30)) cv2.imshow('norm',res) key = cv2.waitKey(0) % 256 print ("+") print (key) print ("+") if key == 27: # (escape to quit) sys.exit() elif key in keys: print ("-") print (key) print ("-") responses.append(int(key)) print (len(roismall)) sample = roismall.reshape((1,100)) samples = np.append(samples,sample,0) responses = np.array(responses,np.float32) responses = responses.reshape((responses.size,1)) print ("training complete") np.savetxt('generalsamples.data',samples) np.savetxt('generalresponses.data',responses) </code></pre> <p>When i run the code i get this Error:</p> <blockquote> <p>Traceback (most recent call last): File "file001.py", line 45, in sample = roismall.reshape((1,100)) ValueError: total size of new array must be unchanged</p> </blockquote> <p>The last print "print (len(roismall))" have a Value of 30.</p> <p>regards Thomas</p>
0
2016-09-28T23:53:48Z
39,778,702
<p>this Error was Homemade:</p> <pre><code>sample = roismall.reshape((1,100)) </code></pre> <p>is corresponding to this line:</p> <pre><code>roismall = cv2.resize(roi,(30,30)) </code></pre> <p>The 30 x 30 = 900 is the right Value or 10,10 = 100. I change it back to:</p> <pre><code>roismall = cv2.resize(roi,(10,10)) </code></pre> <p>Here the complett script:</p> <pre><code>import sys import numpy as np import cv2 im = cv2.imread('test001.png') res = cv2.resize(im,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC) im3 = res.copy() gray = cv2.cvtColor(res,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2) ################# Now finding Contours ################### _,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) samples = np.empty((0,100)) sample = np.empty((0,100)) responses = [] keys = [i for i in range(48,58)] for cnt in contours: if (cv2.contourArea(cnt)&gt;10) and (cv2.contourArea(cnt)&lt;900): [x,y,w,h] = cv2.boundingRect(cnt) if ((h&gt;15) and (h&lt;30)) and ((w&gt;8) and (w&lt;30)): cv2.rectangle(res,(x,y),(x+w,y+h),(0,0,255),1) roi = thresh[y:y+h,x:x+w] roismall = cv2.resize(roi,(10,10)) cv2.imshow('roi',roismall) cv2.imshow('norm',res) key = cv2.waitKey(0) % 256 if key == 27: # (escape to quit) sys.exit() elif key in keys: responses.append(int(key)) sample = roismall.reshape((1,100)) samples = np.append(samples,sample) responses = np.array(responses,np.float32) responses = responses.reshape((responses.size,1)) print ("training complete") np.savetxt('generalsamples.data',samples) np.savetxt('generalresponses.data',responses) </code></pre> <p>regards Thomas</p>
0
2016-09-29T19:42:02Z
[ "python", "opencv", "ocr" ]
Why does this keep on giving me a list index out of range error?
39,759,336
<pre><code>count = 0 badIndices = [59,64,68,72,74,77,79,103,104,108,109,118,119,123,124,130,133,139] test1 = [] csvCourses = [] csvExamTime = [] examTime = [] with open("final_exam_schedule.csv") as file: reader = csv.reader(file, delimiter = ",") next(reader) for row in reader: csvCourses.append(row) for i in range(len(csvCourses)): csvExamTime.append(csvCourses[i][5]) examTime.append(findSchedule(csvCourses[i][4],csvCourses[i][1],csvCourses[i][3],csvCourses[i][2])) for i in badIndices: test1.append(csvCourses[i][5]) for i in badIndices: if count &gt;= len(test1): break else: count += 1 examTime[i] = test1[count] #this is where I get my error </code></pre> <p>every time I try to assign examTime[i] to test1, it gives me "out of range", but I thought that my if statement made sure that it didn't exceed the range?</p> <p>For reference, examTime contains 155 different indices, and the badIndices list are the ones that aren't returning a value, so I'm going to that exact index and assigning it a value. findSchedule() is my function that has a bunch of ifs and elses to assign examTime, I didn't include it since it is really long and unnecessary to the problem. Only the specific bad indices don't return a value, the rest do.</p> <p>edit: ok here is the findSchedule function</p> <pre><code>def findSchedule(days,time,cr,period): if days == "TR": if time == "11:00": if period == "AM": return("Tuesday, December 13, 9:45 - 11:45 am") elif period == "PM": return("Class final not found, please try again") elif time == "12:30" or time == "1:00": if period == "PM": return("Tuesday, December 13, 12:00 - 2:00 pm") elif period == "AM": return("Class final not found, please try again") elif time == "3:30": if period == "PM": return("Tuesday, December 13, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") elif time == "5:00": if period == "PM": return("Tuesday, December 13, 4:30 - 6:30 pm") elif period == "AM": return("Class final not found, please try again") elif time == "6:30": if period == "PM": return("Tuesday, December 13, 7:00 - 9:00 pm") elif period == "AM": return("Class final not found, please try again") elif time == "8:00": if period == "AM": return("Wednesday, December 14, 7:30 - 9:30 am") elif period == "PM": return("Class final not found, please try again") elif time == "2:00": if period == "PM": return("Thursday, December 15, 12:00 - 2:00 pm") elif period == "AM": return("Class final not found, please try again") elif time == "9:30": if period == "AM": return("Friday, December 16, 9:45 - 11:45 am") elif time == "9:00": if period == "AM": return("Friday, December 16, 7:30 - 9:30 am") elif time == "10:00": if period == "AM": return("Wednesday, December 14, 9:45 - 11:45 am") elif time == "12:00": if period == "PM": return("Wednesday, December 14, 12:00 - 2:00 pm") elif time == "5:00" and cr == "5": return("Wednesday, December 14, 4:30 - 6:30 pm") elif days == "MWF": if time == "10:00": if period == "AM": return("Wednesday, December 14, 9:45 - 11:45 am") elif period == "PM": return("Class final not found, please try again") elif time == "12:00": if period == "PM": return("Wednesday, December 14, 12:00 - 2:00 pm") elif period == "AM": return("Class final not found, please try again") elif time == "3:00": if period == "PM": return("Wednesday, December 14, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") elif time == "5:00": if period == "PM": return("Wednesday, December 14, 4:30 - 6:30 pm") elif period == "AM": return("Class final not found, please try again") elif time == "6:30" or time == "8:00": if period == "PM": return("Wednesday, December 14, 7:00 - 9:00 pm") elif period == "AM" and time == "8:00": return("Thursday, December 15, 7:30 - 9:30 am") elif time == "11:00": if period == "AM": return("Thursday, December 15, 9:45 - 11:45 am") elif period == "PM": return("Class final not found, please try again") elif time == "2:00": if period == "PM": return("Thursday, December 15, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") elif time == "9:00": if period == "AM": return("Friday, December 16, 7:30 - 9:30 am") elif period == "PM": return("Class final not found, please try again") elif time == "1:00": if period == "PM": return("Friday, December 16, 12:00 - 2:00 pm") elif period == "AM": return("Class final not found, please try again") elif time == "4:00": if period == "PM": return("Friday, December 16, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") elif time == "8:00": if period == "AM": return("Thursday, December 15, 7:30 - 9:30 am") elif time == "9:30": return("Friday, December 16, 9:45 - 11:45 am") elif time == "3:30": return("Tuesday, December 13, 2:15 - 4:15 pm") elif time == "3:00": return("Wednesday, December 14, 2:15 - 4:15 pm") elif time == "11:00" and cr == "5": if period == "AM": return("Thursday, December 15, 9:45 - 11:45 am") elif days == "MW": if time == "8:00": if period == "PM": return("Wednesday, December 14, 7:00 - 9:00 pm") elif period == "AM": return("Thursday, December 15, 7:30 - 9:30 am") elif time == "11:00": if period == "AM": return("Thursday, December 15, 9:45 - 11:45 am") elif period == "AM": return("Class final not found, please try again") elif time == "2:00": if period == "PM": return("Thursday, December 15, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") elif time == "1:00": if period == "PM": return("Friday, December 16, 12:00 - 2:00 pm") elif period == "AM": return("Class final not found, please try again") elif time == "10:00": if period == "AM": return("Wednesday, December 14, 9:45 - 11:45 am") elif time == "9:00": return("Friday, December 16, 7:30 - 9:30 am") elif time == "9:30": return("Friday, December 16, 9:45 - 11:45 am") elif time == "9:30": return("Friday, December 16, 9:45 - 11:45 am") elif time == "3:30": return("Tuesday, December 13, 2:15 - 4:15 pm") elif time == "6:30" and cr == "1": return("Monday, December 12, 6:30 - 7:25 pm") elif time == "6:30" and cr == "2": return("Monday, December 12, 6:30 - 8:20 pm") elif time == "6:30" and cr == "3": return("Monday, December 12, 6:30 - 9:30 pm") elif time == "6:30" and cr == "4": return("Monday, December 12, 6:30 - 10:15 pm") elif time == "5:00" and cr == "5": if period == "PM": return("Wednesday, December 14, 4:30 - 6:30 pm") elif days == "R": if time == "6:30" and period == "PM": return("Thursday, December 15, 7:00 - 9:00 pm") elif days == "WF": if time == "8:00" and (cr == "2" or cr == "5"): if period == "AM": return("Thursday, December 15, 7:30 - 9:30 am") elif period == "PM": return("No class found") elif time == "8:00" and cr == "4": if period == "AM": return("Wednesday, December 14, 7:30 - 9:30 am") elif period == "PM": return("Class not found") elif time == "9:00": if period == "AM": return("Friday, December 16, 7:30 - 9:30 am") if period == "PM": return("Class not found") elif time == "9:30": if period == "AM": return("Friday, December 16, 9:45 - 11:45 am") elif period == "PM": return("Class not found") elif time == "10:00": if period == "AM": return("Wednesday, December 14, 9:45 - 11:45 am") elif period == "PM": return("Class not found") elif time == "11:00": if period == "AM": return("Thursday, December 15, 9:45 - 11:45 am") elif period == "PM": return("Class not found") elif time == "12:00": if period == "PM": return("Wednesday, December 14, 12:00 - 2:00 pm") elif period == "AM": return("Class not found") elif time == "12:30": if period == "PM": return("Tuesday, December 13, 12:00 - 2:00 pm") elif period == "AM": return("Classs not found") elif time == "1:00": if period == "PM": return("Friday, December 16, 12:00 - 2:00 pm") elif period == "AM": return("Class not found") elif time == "2:00": if period == "PM": return("Thursday, December 15, 12:00 - 2:00 pm") elif period == "AM": return("Class not found") elif time == "3:00": if period == "PM": return("Wednesday, December 14, 2:15 - 4:15 pm") elif period == "AM": return("Class not found") elif time == "3:30": if period == "PM": return("Tuesday, December 13, 2:15 - 4:15 pm") elif period == "AM": return("Class not found") elif time == "4:00": if period == "PM": return("Friday, December 16, 2:15 - 4:15 pm") elif period == "AM": return("Class not found") elif time == "5:00" and cr == "2": if period == "PM": return("Tuesday, December 13, 4:30 - 6:30 pm") elif period == "AM": return("Class not found") elif time == "5:00" and cr == "4": if period == "PM": return("Wednesday, December 14, 4:30 - 6:30 pm") elif period == "AM": return("Class not found") elif time == "9:30": return("Friday, December 16, 9:45 - 11:45 am") elif time == "3:30": return("Tuesday, December 13, 2:15 - 4:15 pm") elif days == "M": if time == "6:30": return("Monday, December 12, 6:30 - 7:25 pm") elif days == "T": if time == "6:30": return("Tuesday, December 13, 7:00 - 9:00 pm") else: if (cr == "4" or cr == "2") and time == "12:30": if period == "PM": return("Tuesday, December 13, 1:00 - 2:00 pm") elif period == "AM": return("Class final not found, please try again") elif cr == "4" and time == "3:30": if period == "PM": return("Tuesday, December 13, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") elif cr == "4" and time == "5:00": if period == "PM": return("Tuesday, December 13, 4:30 - 6:30 pm") elif period == "AM": return("Class final not found, please try again") elif cr == "4" and time == "8:00": if period == "AM": return("Wednesday, December 14, 7:30 - 9:30 am") elif period == "PM": return("Class final not found, please try again") elif time == "10:00": if period == "AM": return("Wednesday, December 14, 9:45 - 10:45 am") elif period == "PM": return("Class final not found, please try again") elif time == "12:00": if period == "PM": return("Wednesday, December 14, 12:00 - 2:00 pm") elif period == "AM": return("Class final not found, please try again") elif time == "3:00": if period == "PM": return("Wednesday, December 14, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") elif time == "5:00": if period == "PM": return("Wednesday, December 14, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") elif cr == "5" and time == "8:00": if period == "AM": return("Thursday, December 15, 7:30 - 9:30 am") elif period == "PM": return("Class final not found, please try again") elif time == "11:00": if period == "AM": return("Thursday, December 15, 9:45 - 11:45 am") elif period == "PM": return("Class final not found, please try again") elif cr == "4" and time == "2:00": if period == "PM": return("Thursday, December 15, 12:00 - 2:00 pm") elif period == "AM": return("Class final not found, please try again") elif cr == "5" and time == "2:00": if period == "PM": return("Thursday, December 15, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") elif time == "9:00": if period == "AM": return("Friday, December 16, 7:30 - 9:30 am") elif period == "PM": return("Class final not found, please try again") elif time == "9:30": if period == "AM": return("Friday, December 16, 9:45 - 10:45 am") elif period == "PM": return("Class final not found, please try again") elif time == "1:00": if period == "PM": return("Friday, December 16, 12:00 - 2:00 pm") elif period == "PM": return("Class final not found, please try again") elif time == "4:00": if period == "PM": return("Friday, December 16, 2:15 - 4:15 pm") elif period == "AM": return("Class final not found, please try again") else: return("Class final not found, please try again") </code></pre>
0
2016-09-28T23:56:36Z
39,759,379
<p>It's tough to say without knowing what your data looks like, but here's what I think,</p> <p>Your <code>count</code> variable is being incremented too early. In python list indexes start at <code>0</code> and go to <code>len(list)-1</code> as the last index. You're kind of starting at <code>count=1</code> so it's possible that on the last iteration <code>count=len(list)</code> which gives the error. Try this as a correction for the latter part of your code:</p> <pre><code>for i in badIndices: if count &gt;= len(test1): break else: examTime[i] = test1[count] #We increment count after it is used #to avoid an error count+=1 </code></pre>
0
2016-09-29T00:02:00Z
[ "python" ]
Can't open the desktop app created with pyinstaller
39,759,342
<p>I created a pyinstaller file from a .py file. In this file, I´ve got files with the .ui extensions created using PyQt4. So, when I try to execute the file created, it shows this error:</p> <pre><code>File "C:\Users\Flosh\Desktop\dist\ProgramNew\New.exe", line 1 SyntaxError: Non-ASCII character '\x90' in file C:\Users\Flosh\Desktop\dist\ProgramNew\New.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details </code></pre> <p>In the original file, the .py file, I use the UTF-8 encoding, and this error shows an ASCII problem.</p> <p>How can I fix this error? Hope you can help me. </p>
0
2016-09-28T23:57:49Z
40,062,240
<p>This is a Python traceback, but the first line is showing an <em>exe file</em>:</p> <pre><code>File "C:\Users\Flosh\Desktop\dist\ProgramNew\New.exe", line 1 </code></pre> <p>which suggests you must be trying to run the application like this:</p> <pre><code>python C:\Users\Flosh\Desktop\dist\ProgramNew\New.exe </code></pre> <p>You cannot run exe files with Python. Indeed, the whole point of using tools like PyInstaller is that you don't even need to have Python installed in order to run the program. You have created a <em>self-contained executable</em>, so just run it directly, like this:</p> <pre><code>C:\Users\Flosh\Desktop\dist\ProgramNew\New.exe </code></pre>
1
2016-10-15T17:41:11Z
[ "python", "pyqt4", "pyinstaller" ]
Can't open the desktop app created with pyinstaller
39,759,342
<p>I created a pyinstaller file from a .py file. In this file, I´ve got files with the .ui extensions created using PyQt4. So, when I try to execute the file created, it shows this error:</p> <pre><code>File "C:\Users\Flosh\Desktop\dist\ProgramNew\New.exe", line 1 SyntaxError: Non-ASCII character '\x90' in file C:\Users\Flosh\Desktop\dist\ProgramNew\New.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details </code></pre> <p>In the original file, the .py file, I use the UTF-8 encoding, and this error shows an ASCII problem.</p> <p>How can I fix this error? Hope you can help me. </p>
0
2016-09-28T23:57:49Z
40,081,006
<p>You can try cxfreeze for creating the installer or executable package. Description of creating the setup file is given here <a href="https://cx-freeze.readthedocs.io/en/latest/distutils.html" rel="nofollow">https://cx-freeze.readthedocs.io/en/latest/distutils.html</a>. May be this could help you.</p>
0
2016-10-17T07:48:01Z
[ "python", "pyqt4", "pyinstaller" ]
Set list to a certain length and range
39,759,493
<p>This is my problem.. </p> <p>write a function that takes, as an argument, a list named aList. It returns a Boolean value True if the elements in the list contains at least one integer and no more than six integers whose values range between 1 and 6. It returns the Boolean False if the list contains any other elements (like strings, or integers outside of the range) or is the wrong length (in that it contains either 0 or more than six elements). Call this function checkList(aList).</p> <p>I have the length figured out, but can't seem to get it to set the values range between 1 and 6. I am getting the error "List object is not callable." Here's what I have so far:</p> <pre><code>def checkList(aList): if 1&lt;=len(aList)&lt;=6 and range[aList(1,6)]: return True else: return False </code></pre>
-1
2016-09-29T00:19:05Z
39,759,516
<p>Use <code>set(aList) &lt;= set(range(1, 6))</code>.</p>
2
2016-09-29T00:21:08Z
[ "python", "list", "boolean", "range" ]
Python Pandas datetime64[ns] comparision
39,759,496
<p>I'm trying to use indexing to select rows in my dataframe after the date 2011-01-01. I used following line of code to return only part of dataframe that is after 2011-01-01 </p> <pre><code> df = df[df.Date &gt; np.datetime64('2011-01-01 00:00:00')] </code></pre> <p>I don't get an error. However, I only see dates that are of 2016 year nothing on 2011. When I manually open file I can see that there are plenty of entries starting with 2011 year.</p> <p>What do I do wrong here? Any ideas?</p> <p>Thanks!</p> <p>Here is a sniped of data:<a href="http://i.stack.imgur.com/YhEa3.jpg" rel="nofollow">enter image description here</a></p>
0
2016-09-29T00:19:18Z
39,760,475
<p>After importing your data, it looks like all the values of the <code>Date</code> column are still there, even after filtering. It's just that your data is too large to be displayed fully on your console (take a look at <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html" rel="nofollow">pandas settings</a>). Therefore some of it is being (visually) truncated to fit the page.</p> <p>The trick to use convert the <code>Date</code> column to a pandas datetime object and handle the filtering from there:</p> <pre><code>import pandas as pd df = pd.read_csv('Crimes_-_2001_to_present.csv', header = 0) df.Date = pd.to_datetime(df.Date) filterer = df.Date &gt; pd.to_datetime('2011-01-01 00:00:00') df = df[filterer] </code></pre> <p>Now when you look at the 200th row in the <code>Date</code> column, you should get something:</p> <pre><code>df['Date'].iloc[200] #Timestamp('2011-05-31 19:30:00') </code></pre> <p>At row 2000 in column <code>Date</code>:</p> <pre><code>df['Date'].iloc[2000] #Timestamp('2013-09-19 20:45:00') </code></pre> <p>In essence, everything is there. Your console is perhaps too small to fit it all.</p> <p>I hope this helps.</p>
0
2016-09-29T02:35:31Z
[ "python", "datetime", "pandas" ]
How to document multiple return values using reStructuredText in Python 2?
39,759,503
<p>The <a href="https://docs.python.org/devguide/documenting.html" rel="nofollow">Python docs</a> say that "the markup used for the Python documentation is <a href="http://docutils.sf.net/rst.html" rel="nofollow">reStructuredText</a>". My question is: How is a block comment supposed to be written to show multiple return values?</p> <pre><code>def func_returning_one_value(): """Return just one value. :returns: some value :rtype: str """ def func_returning_three_values(): """Return three values. How do I note in reStructuredText that three values are returned? """ </code></pre> <p>I've found a <a href="http://thomas-cokelaer.info/tutorials/sphinx/docstring_python.html" rel="nofollow">tutorial</a> on Python documentation using reStructuredText, but it doesn't have an example for documenting multiple return values. The <a href="http://www.sphinx-doc.org/en/stable/domains.html" rel="nofollow">Sphinx docs on domains</a> talks about <code>returns</code> and <code>rtype</code> but doesn't talk about multiple return values.</p>
0
2016-09-29T00:19:51Z
39,761,518
<p>As wwi mentioned in the comments, the detailed format to be used is not strictly defined. </p> <p>For myself, I usually use the <a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#field-lists" rel="nofollow">Field List</a> notation style you use above. It supports line breaks, so just break where you feel is necessary</p> <pre><code>def my_func(param1, param2): """ This is a sample function docstring :param param1: this is a first param :param param2: this is a second param :returns: tuple (result1, result2) WHERE str result1 is .... str result2 is .... """ </code></pre>
0
2016-09-29T04:38:15Z
[ "python", "python-2.7", "documentation", "restructuredtext" ]
PyQt - QDialogButtonBox signals and tool tip
39,759,600
<p>I got a couple of questions regarding qDialogButtonBox. While my code still works, I believed that there are a few parts that can be better refined/ I am not finding much info online</p> <pre><code>class testDialog(QtGui.QDialog): def __init_(self, parent=None): ... self.init_ui() self.signals_connection() def init_ui(self): ... self.buttonBox = QtGui.QDialogButtonBox() self.buttonBox.addButton("Help", QtGui.QDialogButtonBox.HelpRole) self.buttonBox.addButton("Apply", QtGui.QDialogButtonBox.AcceptRole) self.buttonBox.addButton("Cancel", QtGui.QDialogButtonBox.RejectRole) # def signals_connection(self): self.test_random.clicked.connect(self.test_rand) # Is this the latest/correct way to write it? self.buttonBox.accepted.connect(self.test_apply) self.buttonBox.rejected.connect(self.test_cancel) self.buttonBox.helpRequested.connect(self.test_help) def test_apply(self): print "I am clicking on Apply" def test_cancel(self): print "I am clicking on Cancel" self.close() def test_help(self): print "I am clicking for Help!" </code></pre> <p>My questions are as follows:</p> <ol> <li>Under my function - signals_connection(), the lines that I wrote for the <code>buttonBox</code> (though the code still works) are quite different for the signal I have wrote for the <code>self.test_random</code> and I am unable to find any similar online for the qdialogbuttonbox.. There is another style that I have found - <code>self.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), self, QtCore.SLOT("accept()"))</code> but I think that is the old style?? Otherwise what should be the right way to write it?</li> <li><p>In my <code>test_cancel()</code> function, is writing <code>self.close()</code> the best way to close the application? The way that I run my program is as follows:</p> <p><code>dialog = testDialog();dialog.show()</code></p></li> <li><p>Lastly, is it possible to add 3 different tool tips to the 3 buttons I have created? I saw that there is a command for it - <code>self.buttonBox.setToolTip("Buttons for life!")</code>, but this will results in all 3 buttons to have the same tool tip. Can I make it as individual?</p></li> </ol>
0
2016-09-29T00:33:56Z
39,776,290
<ol> <li><p>Yes, that is the correct way to write signal connections (the other syntax you found is indeed the old way of doing it). You can find all the signals in the pyqt documentation for <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qdialogbuttonbox.html" rel="nofollow"><code>QDialogButtonBox</code></a>. Different widgets and objects have different signals. <code>QPushButton</code>'s and <code>QDialogButtonBox</code>'s have different signals.</p></li> <li><p>Yes, <code>close()</code> will close the dialog. The <code>QApplication</code> will exit by default if there are no other windows open. However, if this is a modal dialog, you typically want to close a dialog with either the <code>accept</code> or <code>reject</code> command. This will alert the calling function as to whether the dialog was closed with the <code>Ok/Yes/Apply</code> button or closed with the `No/Cancel' button.</p></li> <li><p>You can set different tooltips for different buttons in the <code>QDialogButtonBox</code>. You just need to get a reference to the specific button you want to set the tooltip for.</p></li> </ol> <p>For example</p> <pre><code>self.buttonBox.button(QDialogButtonBox.Help).setToolTip('Help Tooltip') self.buttonBox.button(QDialogButtonBox.Ok).setToolTip('Apply Tooltip') </code></pre> <p>Or you could loop through all the buttons</p> <pre><code>for button in self.buttonBox.buttons(): if button.text() == 'Help': button.setToolTip('Help Tooltip') elif button.text() == 'Apply': button.setToolTip('Apply Tooltip') </code></pre> <p>Also, you could connect the <code>accepted</code> and <code>rejected</code> signals from the <code>QDialogButtonBox</code> to the <code>accept</code> and <code>reject</code> slots on the <code>QDialog</code></p> <pre><code>self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) </code></pre> <p>That way, you won't have to manually connect the <code>Ok</code> and <code>Cancel</code> buttons to your callbacks for closing the dialog.</p>
1
2016-09-29T17:12:59Z
[ "python", "pyqt" ]
Why can't my Python program find the jq module?
39,759,649
<p>I try to use the Python jq module:</p> <pre><code>#!/usr/bin/python3 # Python 3.4 #-------------------------- import datetime import sys import urllib.request import urllib.error import time from jq import jq </code></pre> <p>When I run it on the command line:</p> <pre><code># ./daemon.py </code></pre> <p>it says this:</p> <pre><code>Traceback (most recent call last): File "./daemon.py", line 10, in &lt;module&gt; from jq import jq ImportError: No module named 'jq' </code></pre> <p>List of installed python packages:</p> <pre><code># pip search jq </code></pre> <p>shows this:</p> <pre><code>... jq (0.1.6) - jq is a lightweight and flexible JSON processor. ... </code></pre> <p>So why can't my program import the jq module?</p>
0
2016-09-29T00:39:37Z
39,759,669
<p><code>pip search</code> searches through <em>available</em> packages. To list <em>installed</em> packages, use <code>pip list</code>.</p> <p>Try installing the <code>jq</code> module with <code>pip install jq</code>.</p>
1
2016-09-29T00:43:23Z
[ "python", "python-3.4", "jq" ]
Canvas Update Tkinter Python
39,759,677
<p>I wrote a method to create a canvas</p> <p>But I see that Canvas is not updated and the Gui elements are not updated</p> <p>Please guide here as i want to implement the New Game functionality</p>
-2
2016-09-29T00:44:03Z
39,776,483
<p>Removing all references to a Tkinter widget (like a <code>Canvas</code>) doesn't necessarily delete that object (or its child widgets) from a Tkinter application. You can test this with a small script:</p> <pre><code>import tkinter as tk root = tk.Tk() def f(): tk.Label(root, text='hi').pack() f() </code></pre> <p>No reference to that <code>Label</code> is ever saved, and it's local to a function scope anyway, and yet it persists. If you want to get rid of a Tkinter widget, use its <code>destroy</code> method.</p> <pre><code>self.canvas.destroy() self.canvas = tk.Canvas(self, width=2000, height=800) ... </code></pre> <p>Note that it's still good practice to keep references to your Tkinter objects so that you can work with them (like calling <code>destroy()</code> on them, for example), and some Tkinter objects actually are discarded when there are no more references to them, like image objects (e.g. as used by <a href="http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_image-method" rel="nofollow"><code>Canvas.create_image</code></a> and <a href="http://effbot.org/tkinterbook/label.htm#patterns" rel="nofollow"><code>Label</code></a>).</p>
1
2016-09-29T17:25:10Z
[ "python", "tkinter" ]
Does pytest 3.x have anything significant over 2.x?
39,759,679
<p>I've learned that Python Anaconda's <code>conda</code> program is much better than <code>pip</code> at managing packages and environments --- it even has dependency conflict management, which <code>pip</code> does not have.</p> <p>The problem is that <code>conda</code> uses the Continuum repository instead of PyPI, and many things (e.g. <code>cx_Oracle</code>) are so out of date there! One of the biggest is <code>pytest</code>, which on Continuum only goes to version 2.9.2 at the moment, while PyPI is already at <code>pytest</code> version 3.0.2.</p> <p>So does the version 3.x line of <code>pytest</code> have significant features over the 2.x line? Or must I abandon <code>conda</code> and its superior package management and switch back to <code>pip</code> so I can get the latest packages? (I shouldn't have to make this decision... but such is the Python ecosystem.)</p> <p>P.S. I know I can hunt around and specify a different Continuum channel and perhaps pick up a newer <code>pytest</code> using <code>conda</code>, but I'm getting tired of everything being out of date and having to specify a list of channels every time I create an environment. P.P.S. Yes I know there is probably a requirements list format that includes the channels, but that misses the point. Plus we want the requirements list to interoperate with those using <code>pip</code>.</p>
1
2016-09-29T00:44:15Z
39,760,093
<p>Although I've had good experience with <code>conda</code> in the past, I would suggest taking a look at <a href="https://github.com/yyuu/pyenv" rel="nofollow">pyenv</a>.</p> <p><code>pyenv</code> is written purely in bash and allows you to easily handle the installation and management of different python interpreters and virtual environments.</p> <p>In my opinion, it has the best features of tools like conda, virtualenv, virtualenvwrapper and more, while avoiding any dependency besides bash and playing well with the existing Python ecosystem rather than another package repository like conda.</p>
0
2016-09-29T01:45:05Z
[ "python", "anaconda", "py.test", "pypi", "conda" ]
manually building installing python packages in linux so they are recognized
39,759,680
<p>My system is SLES 11.4 having python 2.6.9. I know little about python and have not found where to download rpm's that give me needed python packages.<br> I acquired numpy 1.4 and 1.11 and I believe did a successful <code>python setup.py build</code> followed by <code>python setup.py install</code> on numpy. Going from memory I think this installed under <code>/usr/local/lib64/python2.6/...</code></p> <p>Next I tried building &amp; installing matplotlib (which requires numpy) and when I do <code>python setup.py build</code> it politely responds with cannot find numpy. So my questions are</p> <p>do i need to set some kind of python related environment variable, something along the lines of LD_LIBRARY_PATH or PATH ?</p> <p>As I get more involved with using python installing packages that I have to build from source I need to understand where things currently are per the default install of python, where new things should go, and where the core settings for python are to know how and where to recognize new packages.</p>
0
2016-09-29T00:44:17Z
39,759,893
<p>If you're using linux, make sure your <code>$PYTHONPATH</code> environment variable is set properly.</p> <p>To do this type the following in the terminal:</p> <pre><code>echo $PYTHONPATH </code></pre> <p>If you can't find it you can manually set the variable with the locations of the modules you want to find in your <code>~/.bashrc</code> file by doing the following (with the editor of your choice, I chose gedit as an example):</p> <pre><code>sudo gedit ~/.bashrc </code></pre> <p>And when you're done don't forget to </p> <pre><code>source ~/.bashrc </code></pre>
0
2016-09-29T01:18:30Z
[ "python" ]
manually building installing python packages in linux so they are recognized
39,759,680
<p>My system is SLES 11.4 having python 2.6.9. I know little about python and have not found where to download rpm's that give me needed python packages.<br> I acquired numpy 1.4 and 1.11 and I believe did a successful <code>python setup.py build</code> followed by <code>python setup.py install</code> on numpy. Going from memory I think this installed under <code>/usr/local/lib64/python2.6/...</code></p> <p>Next I tried building &amp; installing matplotlib (which requires numpy) and when I do <code>python setup.py build</code> it politely responds with cannot find numpy. So my questions are</p> <p>do i need to set some kind of python related environment variable, something along the lines of LD_LIBRARY_PATH or PATH ?</p> <p>As I get more involved with using python installing packages that I have to build from source I need to understand where things currently are per the default install of python, where new things should go, and where the core settings for python are to know how and where to recognize new packages.</p>
0
2016-09-29T00:44:17Z
39,778,818
<p>think i figured it out. Apparently SLES 11.4 does not include the development headers in the default install from their SDK for numpy 1.8. And of course they don't offer matplotlib along with a bunch of common python packages.</p> <p>The python packages per the SLES SDK are the system default are located under<code>/usr/lib64/python2.6/site-packages/</code> and it is under here I see numpy version 1.8. So using the YAST software manager if you choose various python packages this is where they are located.</p> <p>To this point without having the <strong>PYTHONPATH</strong> environment variable set I can launch python, type import numpy, and for the most part use it. But if I try to build matplotlib 0.99.1 it responds that it cannot find the header files for numpy version 1.8, so it knows numpy 1.8 is installed but the development package needs to be installed.</p> <p>Assuming by development headers they mean .h files, If I search under <code>/usr/lib64/python2.6/site-packages</code> I have no .h files for anything!</p> <p>I just downloaded the source for numpy-1.8.0.tar.gz and easily did a <code>python setup.py.build</code> followed by <code>python setup.py install</code> and noticed it installed under <code>/usr/local/lib64/python2.6/site-packages/</code></p> <p>Without the <strong>PYTHONPATH</strong> environment variable set, if i try to build matplotlib I still get the error about header files not found.</p> <p>but in my bash shell, as root, after I do <code>export PYTHONPATH=/usr/local/lib64/python2.6/site-packages</code> I can successfully do the build and install of matplotlib 0.99.1 which also installs <code>/usr/local/lib64/python2.6/site-packages</code></p> <p>Notes:</p> <p>I also just did a successful build &amp; install of numpy-1.11 and that got thrown in under <code>/usr/local/lib64/python2.6/site-packages</code> however when i try to then build matplotlib 0.99.1 with PYTHONPATH set it reports outright that numpy is not installed that version 1.1 or greater is needed. So here it seems this older version of matplotlib needs to use a certain version range of numpy, that the latest numpy 1.11 is not compatible.</p> <p>And the only other environment variable i have which is set by the system is <strong>PYTHONSTARTUP</strong> which points to the file <code>/etc/pythonstart</code>.</p>
0
2016-09-29T19:49:29Z
[ "python" ]
Calculating the Manhattan distance in the eight puzzle
39,759,721
<p>I am working on a program to solve the Eight Puzzle in Python using informed search w/ heuristics. The heuristic we are supposed to use is the Manhattan distance. So for a board like:</p> <pre><code> State Goal Different Goal 7 2 4 1 2 3 1 2 3 5 6 8 4 4 5 6 8 3 1 7 6 5 7 8 </code></pre> <p>The Manhattan distance would be <code>4 + 0 + 3 + 3 + 1 + 0 + 2 + 1 = 14</code></p> <p>Visually, it is easy to count how many spaces away a certain number is, but in Python I am representing a board as a list, so the board above would be <code>[7, 2, 4, 5, 0, 6, 8, 3, 1]</code> and the goal state would be <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]</code>. I've been messing around trying to get this to work using mod but can't seem to get it working properly. My teacher said using mod would be helpful in figuring out how to do this. Some examples I looked at used a 2d array for the <code>abs(x_val - x_goal) + abs(y_val - y_goal)</code> which makes sense, but since I am using a list I am not sure how to implement this. The code I got so far is:</p> <pre><code>distance = 0 xVal = 0 yVal = 0 for i in range(len(self.layoutList)): pos = self.layoutList.index(i) if pos i == 0 or pos i == 1 or pos i == 2: xVal = pos yVal = 0 if pos i == 3 or pos i == 4 or pos i == 5: xVal = pos - 3 yVal = 1 if pos i == 6 or pos i == 7 or pos i == 8: xVal = pos - 6 yVal = 2 </code></pre> <p>This would generate an x, y value for each tile. So the state above represented as <code>[7, 2, 4, 5, 0, 6, 8, 3, 1]</code> would generate <code>(0, 0)</code> for 7, <code>(2, 0)</code> for 4, etc. I would implement this the same way for the goalstate to get the x,y coordinates for that. Then I would take the absolute value of the x-val - x_goal and whatnot. But is there a better/more efficient way of doing this from the list directly instead of using 2 for loops to iterate both lists?</p>
2
2016-09-29T00:51:56Z
39,759,853
<p>Summing over each number's Manhatten distance:</p> <pre><code>&gt;&gt;&gt; board = [7, 2, 4, 5, 0, 6, 8, 3, 1] &gt;&gt;&gt; sum(abs((val-1)%3 - i%3) + abs((val-1)//3 - i//3) for i, val in enumerate(board) if val) 14 </code></pre> <p>For example, the 7 belongs at (zero-based) coordinate (0, 2) = (<code>(7-1)%3</code>, <code>(7-1)//3</code>) but is at coordinate (0, 0), so add <code>abs(0 - 0) + abs(2 - 0)</code> for it.</p> <p>For non-standard goals:</p> <pre><code>&gt;&gt;&gt; goal = [1, 2, 3, 8, 0, 4, 7, 6, 5] &gt;&gt;&gt; sum(abs(b%3 - g%3) + abs(b//3 - g//3) for b, g in ((board.index(i), goal.index(i)) for i in range(1, 9))) 16 </code></pre>
1
2016-09-29T01:12:41Z
[ "python" ]
How can I get the average of a range of inputs?
39,759,815
<p>I have to create a program that shows the arithmetic mean of a list of variables. There are supposed to be 50 grades. </p> <p>I'm pretty much stuck. Right now I´ve only got:</p> <pre><code>for c in range (0,50): grade = ("What is the grade?") </code></pre> <p>Also, how could I print the count of grades that are below 50?</p> <p>Any help is appreciated.</p>
0
2016-09-29T01:07:42Z
39,759,837
<p>If you don't mind using <code>numpy</code> this is ridiculously easy: </p> <pre><code>import numpy as np print np.mean(grades) </code></pre> <p>Or if you'd rather not import anything,</p> <pre><code>print float(sum(grades))/len(grades) </code></pre> <p>To get the number of grades below 50, assuming you have them all in a list, you could do: </p> <pre><code>grades2 = [x for x in grades if x &lt; 50] print len(grades2) </code></pre>
2
2016-09-29T01:10:35Z
[ "python" ]
How can I get the average of a range of inputs?
39,759,815
<p>I have to create a program that shows the arithmetic mean of a list of variables. There are supposed to be 50 grades. </p> <p>I'm pretty much stuck. Right now I´ve only got:</p> <pre><code>for c in range (0,50): grade = ("What is the grade?") </code></pre> <p>Also, how could I print the count of grades that are below 50?</p> <p>Any help is appreciated.</p>
0
2016-09-29T01:07:42Z
39,759,871
<p>Assuming you have a list with all the grades.</p> <pre><code>avg = sum(gradeList)/len(gradeList) </code></pre> <p>This is actually faster than numpy.mean(). </p> <p>To find the number of grades less than 50 you can put it in a loop with a conditional statement.</p> <pre><code>numPoorGrades = 0 for g in grades: if g &lt; 50: numPoorGrades += 1 </code></pre> <p>You could also write this a little more compactly using a list comprehension.</p> <pre><code>numPoorGrades = len([g for g in grades if g &lt; 50]) </code></pre>
1
2016-09-29T01:15:44Z
[ "python" ]
How can I get the average of a range of inputs?
39,759,815
<p>I have to create a program that shows the arithmetic mean of a list of variables. There are supposed to be 50 grades. </p> <p>I'm pretty much stuck. Right now I´ve only got:</p> <pre><code>for c in range (0,50): grade = ("What is the grade?") </code></pre> <p>Also, how could I print the count of grades that are below 50?</p> <p>Any help is appreciated.</p>
0
2016-09-29T01:07:42Z
39,759,877
<p>First of all, assuming <code>grades</code> is a list containing the grades, you would want to iterate over the <code>grades</code> list, and not iterate over <code>range(0,50)</code>.</p> <p>Second, in every iteration you can use a variable to count how many grades you have seen so far, and another variable that sums all the grades so far. Something like that:</p> <pre><code>num_grades = 0 sum_grades = 0 for grade in grades: num_grades += 1 # this is the same as writing num_grades = num_grades + 1 sum_grades += sum # same as writing sum_grades = sum_grades + sum </code></pre> <p>Now all you need to do is to divide <code>sum_grades</code> by <code>num_grades</code> to get the result.</p> <pre><code>average = float(sum_grade)s / max(num_grades,1) </code></pre> <p>I used the <code>max</code> function that returns the maximum number between num_grades and 1 - in case the list of grades is empty, num_grades will be 0 and division by 0 is undefined. I used <code>float</code> to get a fraction.</p> <p>To count the number of grades lower than 50, you can add another variable <code>num_failed</code> and initialize him to <code>0</code> just like num_counts, add an if that check if grade is lower than 50 and if so increase <code>num_failed</code> by 1.</p>
0
2016-09-29T01:16:39Z
[ "python" ]
How can I get the average of a range of inputs?
39,759,815
<p>I have to create a program that shows the arithmetic mean of a list of variables. There are supposed to be 50 grades. </p> <p>I'm pretty much stuck. Right now I´ve only got:</p> <pre><code>for c in range (0,50): grade = ("What is the grade?") </code></pre> <p>Also, how could I print the count of grades that are below 50?</p> <p>Any help is appreciated.</p>
0
2016-09-29T01:07:42Z
39,759,954
<p>Try the following. Function isNumber tries to convert the input, which is read as a string, to a float, which I believe convers the integer range too and is the floating-point type in Python 3, which is the version I'm using. The <code>try...except</code> block is similar in a way to the <code>try...catch</code> statement found in other programming languages.</p> <pre><code>#Checks whether the value is a valid number: def isNumber( value ): try: float( value ) return True except: return False #Variables initialization: numberOfGradesBelow50 = 0 sumOfAllGrades = 0 #Input: for c in range( 0, 5 ): currentGradeAsString = input( "What is the grade? " ) while not isNumber( currentGradeAsString ): currentGradeAsString = input( "Invalid value. What is the grade? " ) currentGradeAsFloat = float( currentGradeAsString ) sumOfAllGrades += currentGradeAsFloat if currentGradeAsFloat &lt; 50.0: numberOfGradesBelow50 += 1 #Displays results: print( "The average is " + str( sumOfAllGrades / 5 ) + "." ) print( "You entered " + str( numberOfGradesBelow50 ) + " grades below 50." ) </code></pre>
0
2016-09-29T01:25:05Z
[ "python" ]
Splitting a mixed number string from a dataframe column and converting it to a float
39,759,867
<p>I have a dataframe with a column of strings that are a mix of whole numbers and mixed fractions. I would like to convert column 'y' to floats. </p> <pre><code>x y z 0 4 Info 1 8 1/2 Info 2 3/4 Info 3 10 Info 4 4 Info 5 6 1/4 Info </code></pre> <p>The logic I am considering is to split column 'y' by ' ' and '/' to create three separate columns that would look like this.</p> <pre><code>x base b c z 0 4 0 0 Info 1 8 1 2 Info 2 0 3 4 Info 3 10 0 0 Info 4 4 0 0 Info 5 6 1 4 Info </code></pre> <p>From here I could</p> <pre><code>def convertReplace(df): convert = lambda x: float(x) df['base'].apply(convert) df['b'].apply(convert) df['c'].apply(convert) decimal = lambda x,y: x/y try: df['d'] = decimal(df['b'],df['c']) df['y'] = df['base'] + df['d'] except: df['y'] = df['base'] return df </code></pre> <p>This might work but I can't get the column to split using the method found <a href="http://stackoverflow.com/questions/14745022/pandas-dataframe-how-do-i-split-a-column-into-two">here</a>. </p> <pre><code>df = pd.DataFrame(df.y.str.split(' ',1).str.split('/',1).tolist(),columns = ['base','b','c']) </code></pre> <p>The error says it expects 3 arguments each time when it may be 1, 2, or 3. Even <a href="http://stackoverflow.com/questions/23317342/pandas-dataframe-split-column-into-multiple-columns-right-align-inconsistent-c">this thread</a> doesn't use multiple separators.</p> <p>The actual dataframe has over 400k rows. Efficiency would be great but I'm more interested in just getting it done. Is this logic correct or is there a more concise way to do this? Any help is appreciated. </p>
1
2016-09-29T01:14:58Z
39,760,048
<p>You could try the <a href="https://docs.python.org/2/library/fractions.html" rel="nofollow">fractions</a> module. Here's a one-liner:</p> <pre><code>import fractions df['y_float'] = df['y'].apply(lambda frac: float(sum([fractions.Fraction(x) for x in frac.split()]))) </code></pre> <p>This gives:</p> <pre><code> y z y_float 0 4 Info 4.00 1 8 1/2 Info 8.50 2 3/4 Info 0.75 3 10 Info 10.00 4 4 Info 4.00 5 6 1/4 Info 6.25 </code></pre> <p><strong>[EDIT] Corrected version accounting for negative fractions, as well as invalid text:</strong></p> <p>I realized the above approach would not work for negative fractions, so here is that taken in to account. As it turns out, a one-liner for this would be very tricky!</p> <pre><code>def get_sign(num_str): """ Verify the sign of the fraction """ return 1-2*num_str.startswith('-') def is_valid_fraction(text_str): """ Check if the string provided is a valid fraction. Here I just used a quick example to check for something of the form of the fraction you have. For something more robust based on what your data can potentially contain, a regex approach would be better. """ return text_str.replace(' ', '').replace('-', '').replace('/', '').isdigit() def convert_to_float(text_str): """ Convert an incoming string to a float if it is a fraction """ if is_valid_fraction(text_str): sgn = get_sign(text_str) return sgn*float(sum([abs(fractions.Fraction(x)) for x in text_str.split()])) else: return pd.np.nan # Insert a NaN if it is invalid text </code></pre> <p>So now you will have this:</p> <pre><code>&gt;&gt;&gt; df['y_float'] = df['y'].apply(lambda frac: convert_to_float(frac)) &gt;&gt;&gt; df y z y_float 0 4 Info 4.00 1 8 1/2 Info 8.50 2 3/4 Info 0.75 3 10 Info 10.00 4 0 Info 0.00 5 6 1/4 Info 6.25 6 -3 2/5 Info -3.40 7 -4/5 Info -0.80 8 gibberish100 Info NaN </code></pre>
1
2016-09-29T01:38:35Z
[ "python", "pandas", "split", "fractions" ]
Spyder not throwing the type error: unsupported operand type(s) for +: 'NoneType' and 'str'
39,759,938
<p>Hi guys I was working in Spyder on python 3 and trying to get some input from the user so i accidentally wrote </p> <pre><code>g = input(print("Give the letter: ")) </code></pre> <p>while it should be</p> <pre><code>g = str(input("Give the letter: ")) </code></pre> <p>But Spyder IPython console ran it and didn't said its a TypeError but when I ran the code on an online python console it said that its a TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'. </p> <p>I know that its an error as print() returns None, so the input() is having both NoneType and str. </p> <p>So my question is why Spyder IPython console didn't mentioned this error?<a href="http://i.stack.imgur.com/sBmNd.png" rel="nofollow">enter image description here</a></p>
2
2016-09-29T01:23:45Z
39,760,014
<p>try this : </p> <pre><code>g = str(raw_input("Give the letter: ")) </code></pre>
0
2016-09-29T01:33:29Z
[ "python", "python-3.x" ]
Need help making a "compliment generator"
39,759,976
<p>I'm trying to make a simple compliment generator that takes a noun and an adjective from two separate list ands randomly combines them together. I can get one on its own to work but trying to get the second word to appear makes weird stuff happen. What am I doing wrong here? any input would be great.</p> <pre><code>import random sentence = "Thou art a *adj *noun." sentence = sentence.split() adjectives = ["decadent", "smelly", "delightful", "volatile", "marvelous"] indexCount= 0 noun = ["dandy", "peaseant", "mule", "maiden", "sir"] wordCount= 0 for word in sentence: if word =="*adj": wordChoice = random.choice (adjectives) sentence [indexCount] = wordChoice indexCount += 1 for word in sentence: if "*noun" in word: wordChoice = random.choice (noun) sentence [wordCount] = wordChoice wordCount += 1 st ="" for word in sentence: st+= word + " " print (st) </code></pre> <p>The end result nets me a double noun. how would I get rid of the duplicate?</p>
-5
2016-09-29T01:27:52Z
39,760,008
<p>You aren't incrementing <code>wordCount</code> in the second loop as you do <code>indexCount</code> in the first.</p>
0
2016-09-29T01:32:40Z
[ "python", "python-3.x" ]
python pandas groupby sorting and concatenating
39,760,063
<p>I have a panda data frame:</p> <pre><code>df = pd.DataFrame({'a': [1,1,1,1,2,2,2], 'b': ['a','a','a','a','b','b','b'], 'c': ['o','o','o','o','p','p','p'], 'd': [ [2,3,4], [1,3,3,4], [3,3,1,2], [4,1,2], [8,2,1], [0,9,1,2,3], [4,3,1] ], 'e': [13,12,5,10,3,2,5] }) </code></pre> <p>What I want is:</p> <p>First group by columns a, b, c --- there are two groups</p> <p>Then sort within each group according to column e in an ascending order</p> <p>Lastly concatenate within each group column d</p> <p>So the result I want is:</p> <pre><code>result = pd.DataFrame({'a':[1,2], 'b':['a','b'], 'c':['o','p'], 'd':[[3,3,1,2,4,1,2,1,3,3,4,2,3,4],[0,9,1,2,3,8,2,1,4,3,1]]}) </code></pre> <p>Could anyone share some quick/elegant ways to get around this? Thanks very much.</p>
1
2016-09-29T01:40:28Z
39,760,656
<p>You can sort by column <code>e</code>, group by <code>a</code>, <code>b</code> and <code>c</code> and then use a list comprehension to concatenate the <code>d</code> column (flatten it). Notice that we can use <code>sort</code> and then <code>groupby</code> since groupby will </p> <blockquote> <p>preserve the order in which observations are sorted within each group:</p> </blockquote> <p>according to the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">doc here:</a></p> <pre><code>(df.sort_values('e').groupby(['a', 'b', 'c'])['d'] .apply(lambda g: [j for i in g for j in i]).reset_index()) </code></pre> <p><a href="http://i.stack.imgur.com/obPAR.png" rel="nofollow"><img src="http://i.stack.imgur.com/obPAR.png" alt="enter image description here"></a></p> <p>An alternative to list-comprehension is the chain from itertools:</p> <pre><code>from itertools import chain (df.sort_values('e').groupby(['a', 'b', 'c'])['d'] .apply(lambda g: list(chain.from_iterable(g))).reset_index()) </code></pre>
1
2016-09-29T02:55:11Z
[ "python", "pandas", "dataframe", "group-by" ]
How to plot an specific function?
39,760,132
<p>I want to graph this function: f(x) =e^−x/10 sin(πx) I have tried with this code, but i don't get a coherent graph.</p> <pre><code>t=np.linspace(0,10) curve1 =np.exp(-t/10)*np.sin(t*np.pi) plt.plot(t,curve1) </code></pre>
1
2016-09-29T01:49:18Z
39,760,198
<p>You have to call <code>show()</code> after you call <code>plot()</code> to actually view your graph. The following is working code based off of your code: </p> <pre><code>from matplotlib.pyplot import plot, show t=np.linspace(0,10) curve1 =np.exp(-t/10)*np.sin(t*np.pi) plot(t,curve1) show() </code></pre> <p>Output:</p> <p><a href="http://i.stack.imgur.com/NM790.png" rel="nofollow"><img src="http://i.stack.imgur.com/NM790.png" alt="enter image description here"></a></p>
1
2016-09-29T01:56:47Z
[ "python" ]
How to plot an specific function?
39,760,132
<p>I want to graph this function: f(x) =e^−x/10 sin(πx) I have tried with this code, but i don't get a coherent graph.</p> <pre><code>t=np.linspace(0,10) curve1 =np.exp(-t/10)*np.sin(t*np.pi) plt.plot(t,curve1) </code></pre>
1
2016-09-29T01:49:18Z
39,760,202
<p>What do you mean you don't get a coherent graph? This code works fine for me, maybe you need to use plt.show()?</p> <pre><code>t=np.linspace(0,10) curve1 =np.exp(-t/10)*np.sin(t*np.pi) plt.plot(t,curve1) plt.show() </code></pre>
0
2016-09-29T01:57:30Z
[ "python" ]
Scripting/Parsing Apple Motion 5 .motn files
39,760,227
<p>I'm new to animating and I've started using Apple Motion 5</p> <p><a href="http://www.apple.com/au/final-cut-pro/motion/" rel="nofollow">http://www.apple.com/au/final-cut-pro/motion/</a></p> <p>The interface can be a bit annoying by not letting me do things in bulk or automate things. Since it saves files in a nice xml format I've been kinda hacking it to do things I like.</p> <p>e.g setting Fixed Resolution off for hundreds of assets wasn't possible in the app without doing each one manually so I wrote a short script to find and replace this line in the file setting value to 0</p> <pre><code>&lt;parameter name="Fixed Resolution" id="113" flags="8606711808" default="1" value="0"/&gt; </code></pre> <p>Are there any python libraries that parse/script .motn files? (other than generic xml parsers)</p>
2
2016-09-29T02:01:45Z
39,903,597
<blockquote> <p>Try <code>Awesome Python</code> at <a href="https://github.com/vinta/awesome-python" rel="nofollow">https://github.com/vinta/awesome-python</a></p> <p>Maybe you'll find there what you're looking for.</p> <p>But if you really want to use cool app try <strong><em>The Foundry Nuke</em></strong> or <strong><em>Blackmagic Fusion</em></strong> instead of Apple Motion or Adobe After Effects. Nuke and Fusion are node-based flexible and powerful compositing applications that support python scripting and programming. There are non-commercial free versions:</p> </blockquote> <p><a href="https://www.thefoundry.co.uk/products/nuke/" rel="nofollow">https://www.thefoundry.co.uk/products/nuke/</a></p> <p><a href="https://www.blackmagicdesign.com/products/fusion" rel="nofollow">https://www.blackmagicdesign.com/products/fusion</a></p> <blockquote> <p>¡Hope this helps!</p> </blockquote>
1
2016-10-06T18:51:08Z
[ "python", "animation", "xml-parsing", "finalcut" ]
Dissecting a python puzzle forloop solution
39,760,263
<p>For a specific puzzle online I had to grab (using python) every lowercase letter surrounded by three uppercase letters on both sides. So for example in <code>'WExWQPoKLGnnNMOkPPOQ'</code>, the letters <code>ok</code> should be printed out. Despite finding a haphazard solution myself, a specific solution by another participant grabbed my attention: </p> <pre><code>import string word = "" for i in range(len(code) - 8): if [c for c in code[i:i+9] if c in string.lowercase] == [code[i], code[i+4], code[i+8]]: word += code[i+4] </code></pre> <p>I was wondering if someone could break down this code for me. I have some specific questions but a rundown would be great too:</p> <ul> <li>why does <code>code[i:i+9]</code> not produce a <code>TypeError: Can't convert 'int' object to str implicitly</code>?</li> <li>what does <code>string.lowercase</code> do in this instance?</li> <li>why does <code>code[i:i+9]</code> grab nine characters instead of seven(six uppercase and the lowercase in the middle)?</li> <li>why bother checking if <code>code[i+8]</code> evaluates to true if <code>[i+4]</code>(the lowercase letter that satisfies the requirement's puzzle) is 4 spaces to the left, especially since only three characters to the right or left of the 'correct' letter are relevant?</li> </ul> <p>The puzzle itself can be found here: <a href="http://www.pythonchallenge.com/pc/def/equality.html" rel="nofollow">http://www.pythonchallenge.com/pc/def/equality.html</a> (inspect the source code)</p>
0
2016-09-29T02:08:23Z
39,760,493
<blockquote> <p>why does code[i:i+9] not produce a TypeError: Can't convert 'int' object to str implicitly?</p> </blockquote> <p>Why would it? It is simply a slice notation, <code>i</code> is an int, <code>code</code> is a string.</p> <blockquote> <p>what does string.lowercase do in this instance?</p> </blockquote> <p>It is a constant that contains all lower case letters. (It does not exist any longer in Python 3, as it is locale dependant.)</p> <blockquote> <p>why does code[i:i+9] grab nine characters instead of seven(six uppercase and the lowercase in the middle)?</p> </blockquote> <p>According to the actual description of the problem, the lowercase must be <em>"surrounded by EXACTLY three"</em> uppercase letters. So you can't just check the 7, you need all the 9.</p> <blockquote> <p>why bother checking if code[i+8] evaluates to true if [i+4](the lowercase letter that satisfies the requirement's puzzle) is 4 spaces to the left, especially since only three characters to the right or left of the 'correct' letter are relevant?</p> </blockquote> <p>Likewise, it is not only the 3 characters that are relevant, it is the 4. The fourth needs to be a lowercase.</p> <p>What this code does it that it filters the 9-letter slice to keep only the lowercase, and checks if that is exactly the 1st, 5th and last letters.</p>
3
2016-09-29T02:36:39Z
[ "python", "for-loop", "encryption" ]
Dissecting a python puzzle forloop solution
39,760,263
<p>For a specific puzzle online I had to grab (using python) every lowercase letter surrounded by three uppercase letters on both sides. So for example in <code>'WExWQPoKLGnnNMOkPPOQ'</code>, the letters <code>ok</code> should be printed out. Despite finding a haphazard solution myself, a specific solution by another participant grabbed my attention: </p> <pre><code>import string word = "" for i in range(len(code) - 8): if [c for c in code[i:i+9] if c in string.lowercase] == [code[i], code[i+4], code[i+8]]: word += code[i+4] </code></pre> <p>I was wondering if someone could break down this code for me. I have some specific questions but a rundown would be great too:</p> <ul> <li>why does <code>code[i:i+9]</code> not produce a <code>TypeError: Can't convert 'int' object to str implicitly</code>?</li> <li>what does <code>string.lowercase</code> do in this instance?</li> <li>why does <code>code[i:i+9]</code> grab nine characters instead of seven(six uppercase and the lowercase in the middle)?</li> <li>why bother checking if <code>code[i+8]</code> evaluates to true if <code>[i+4]</code>(the lowercase letter that satisfies the requirement's puzzle) is 4 spaces to the left, especially since only three characters to the right or left of the 'correct' letter are relevant?</li> </ul> <p>The puzzle itself can be found here: <a href="http://www.pythonchallenge.com/pc/def/equality.html" rel="nofollow">http://www.pythonchallenge.com/pc/def/equality.html</a> (inspect the source code)</p>
0
2016-09-29T02:08:23Z
39,760,502
<p>On each iteration, <code>code[i:i+9]</code> extracts a sequence of 9 consecutive letters in the <code>code</code>string. For example, the first time <code>WExWQPoKL</code>. The next iteration will give <code>ExWQPoKLG</code>.</p> <p>At each of there iterations, out of these 9 letters, positions 1,2,3 and 5,6,7 should be uppercase letters, therefore not appear on the result of <code>[c for c in code[i:i+9] if c in string.lowercase]</code>. Only positions 0,4, and 8 (remember positions in python start at 0). If it is the case, that means that character at position 4 (middle) is surrounded by 3 uppercase letters on the left (1,2,3) and on the right (5,6,7).</p> <p>That means that if the string <code>code</code>is "ABCdEFG", the letter "d" will not be returned by the code you posted. I would change it to: </p> <pre><code>import string code ="ABCdEFGhIJK" word = [] for i in range(len(code) - 6): if [c for c in code[i:i+7] if c in string.lowercase] == [code[i+3]]: word += code[i+3] print word print code </code></pre> <p>This prints (python2)</p> <pre><code>['d', 'h'] ABCdEFGhIJK </code></pre>
1
2016-09-29T02:37:43Z
[ "python", "for-loop", "encryption" ]
Python simulation of a company's
39,760,304
<p>I have an assignment where I have to use Python code to simulate a company's hourly average maximum customer volume. The homework prompt says to import the random module and use the random.random() method. My issue is that I don't know what to put into the function itself. Here's the code I have so far:</p> <pre><code>import random #Function to calculate the average maximum of customers per hour def ave_max_calc(C, H, D): **HELP** print('Hello, welcome to my average maximum hourly customer volume calculator!') C = int(input('Give the number of customers per day: ')) H = int(input('Give the number of business hours per day: ')) D = int(input('Give the number of days to simulate: ')) print('The average maximum hourly customer volume is: ', ave_max_calc(C,H, D)) </code></pre>
0
2016-09-29T02:14:43Z
39,760,365
<p>Maximum hourly customer volume is a rate so you should simulate this with a poisson distribution. You can create a poisson distribution like this:</p> <pre><code>import numpy as np rate = float(C)/H customers = np.random.poisson(rate, D*H) </code></pre> <p>Documentation for the poisson distribution can be found here: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html</a></p> <p>When you say average maximum do you mean the average of the maximum customer rate for each day?</p>
0
2016-09-29T02:22:53Z
[ "python", "random", "module", "simulation" ]
python scripts to create a table on azure
39,760,427
<p>So I'm tryna run a python script that reads data from the Z wave sensors via the Rpi and using crontab on the pi I have set so the python script would run every minute and store it in a text file. Then I have another python script that sends the data to the azure cloud storage in a table form. The problem is that is does create a table but theres an error "<strong>This XML file does not appear to have any style information associated with it</strong>". Ive been trying to figure it out but nothing I can see is wrong. </p> <p>This is the python script that sends data to the cloud </p> <pre><code>from azure.storage import TableService, Entity from datetime import datetime import socket ac_name = 'account name' #you will have to use your own azure account primary_key = 'use your key' table_name = 'Readings' current_temperature = 0 def get_connection_string_and_create_table(): global table_service table_service = TableService(account_name = ac_name,account_key=primary_key) #table_service.delete_table(table_name = table_name) #TO BE USED IF THE TABLE NEEDS TO BE DELETED table_service.create_table(table=table_name) def insert_data(): reading = create_entity() try: if check_internet_available(): table_service.insert_entity(table_name = table_name,entity = reading) return True except Exception, e: return False def create_entity(): """ - Creates the data block that would be sent to the cloud, named as Entity """ time_now = datetime.strftime(datetime.now(),'%d-%m-%Y %H:%M:%S') print('Date time is {0}'.format(time_now)) reading = Entity() reading.PartitionKey = 'Room1' reading.RowKey = time_now reading.Timestamp = datetime.now() reading.Temperature = str(current_temperature) return reading def initialize_azure(): get_connection_string_and_create_table() def send_data_to_cloud(temperature): global current_temperature current_temperature = temperature sent_success = insert_data() print temperature print sent_success return sent_success def check_internet_available(): """ - Checks internet availability, the data will be sent to cloud only if there is an active internet connection remote_server = 'www.google.com' try: host = socket.gethostbyname(remote_server) s = socket.create_connection((host,80),2) return True except: pass return False if __name__ == '__main__': get_connection_string_and_create_table() f = open('Meter.txt', 'r') send_data_to_cloud(f.readline()) </code></pre> <p>And this is the script that reads the data via HTTP requests from an API</p> <pre><code>import urllib2 import json import requests import time import json class EnergyConsumptionControl: # Class constructor def __init__(self): # Global Variables self.energyMeterDeviceUrl = "http://IpaddressofyourRpi" self.session = requests.Session() # Logging in self.Login() def ActivateDevice(self, deviceID): energyMeterDeviceSwitchOn = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].SwitchBinary.Set(255)" response = self.SendGetCommand(energyMeterDeviceSwitchOn) # Command to turn device on return [response] def DeactivateDevice(self, deviceID): energyMeterDeviceSwitchOff = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].SwitchBinary.Set(0)" response = self.SendGetCommand(energyMeterDeviceSwitchOff) # Command to turn device off return [response] def GetDeviceState(self, deviceID): # Call the Get() function to update the SwitchBinary data energyMeterDeviceSwitchGet = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].SwitchBinary.Get()" response = self.SendGetCommand(energyMeterDeviceSwitchGet) # Call to return the SwitchBinary JSON object energyMeterDeviceSwitchGet = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].SwitchBinary" response = self.SendGetDeviceStateCommand(energyMeterDeviceSwitchGet) return response # def GetDeviceMeter(self, deviceID): # # Refreshing server-side information on the Meter through device interrogation # energyMeterDeviceMeterGetVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter.Get()" # response = self.SendGetCommand(energyMeterDeviceMeterGetVals) # # Retrieving the JSON of all Meter related data # energyMeterDeviceMeterGet = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter" # response = self.GetMeterWattage(energyMeterDeviceMeterGet) # return [response] def GetDeviceEnergyConsumption(self, deviceID): # Refreshing server-side information on the Meter through device interrogation energyMeterDeviceMeterRefreshVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter" response = self.SendGetCommand(energyMeterDeviceMeterRefreshVals) # Retrieving the JSON of all Meter related data energyMeterDeviceMeterGetVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter" energyConsumption = self.GetMeterConsumption(energyMeterDeviceMeterGetVals) response = self.ResetDeviceMeter(deviceID) return energyConsumption def GetDeviceEnergyWattage(self, deviceID): # Refreshing server-side information on the Meter through device interrogation energyMeterDeviceMeterRefreshVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter.Get()" response = self.SendGetCommand(energyMeterDeviceMeterRefreshVals) # Retrieving the JSON of all Meter related data energyMeterDeviceMeterGetVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter" energyWattage = self.GetMeterWattage(energyMeterDeviceMeterGetVals) print energyWattage return energyWattage def ResetDeviceMeter(self, deviceID): energyMeterDeviceMeterReset = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter.Reset(255)" response = self.SendPostCommand(energyMeterDeviceMeterReset) # Command to reset device meter value return [response] def Login(self): data = { "form": True, "login": "admin", "password": "#password", "keepme": False, "default_ui": 1 } # Authenticating headers = {'Content-Type': 'application/json'} response = self.session.post(self.energyMeterDeviceUrl + ':8083/ZAutomation/api/v1/login', headers=headers, data=json.dumps(data)) # Generic function to send GET commands to individual Z-Wave devices def SendGetCommand(self, command): status = self.session.get(self.energyMeterDeviceUrl + command) print status print status.text return [status] # Generic function to send POST commands to individual Z-Wave devices def SendPostCommand(self, command): status = self.session.post(self.energyMeterDeviceUrl + command) print status print status.text return [status] def GetMeterWattage(self, command): status = self.session.get(self.energyMeterDeviceUrl + command) json_data = json.loads(status.text) # Parsing the JSON data to get just the energy wattage (W) return json_data['data']['2']['val']['value'] def GetMeterConsumption(self, command): status = self.session.get(self.energyMeterDeviceUrl + command) json_data = json.loads(status.text) # Parsing the JSON data to get just the energy consumption (kWh) return json_data['data']['0']['val']['value'] def SendGetDeviceStateCommand(self, command): status = self.session.get(self.energyMeterDeviceUrl + command) json_data = json.loads(status.text) # Parsing the JSON data to get just the 'level' return int(json_data['data']['level']['value']) control = EnergyConsumptionControl() response = control.GetDeviceEnergyConsumption(8) print response control = EnergyConsumptionControl() response = control.ActivateDevice(8) print response </code></pre> <p>Is there a way to either combine the two so that it calls the data and sends it to the cloud?? How can I fix the error Message</p>
2
2016-09-29T02:30:04Z
39,840,417
<p>This error occurs when there is no presentation/style information present for rendering, and in this case it is an Xml for communication so probably not needed. Here is another related thread - this might help. </p> <p><a href="http://stackoverflow.com/questions/7551106/this-xml-file-does-not-appear-to-have-any-style-information-associated-with-it">This XML file does not appear to have any style information associated with it</a> </p>
0
2016-10-03T21:05:33Z
[ "python", "azure", "windows-azure-storage", "azure-storage-blobs", "raspberry-pi2" ]
Evaluate Array of operators and numbers in Python
39,760,441
<p>I have a program that produces arrays of numbers and operators, like this:<code>[1,'+',6,'*',3,'*',2]</code> What I would like to do is to evaluate this kind of array for its numerical value using order of operations. The array length may very, but they will always begin and end with a number and a number will not follow a number and an operator will not follow an operator.<br> I think I can use the <code>operator</code> module for converting the operator strings into actual operations, but I don't know how to manage the order of operations part.</p>
0
2016-09-29T02:31:31Z
39,760,650
<p>You might try this, pretty naive though.</p> <pre><code>a = [1,'+',6,'*',3,'*',2] source = '' for i in a: source += str(i) print eval(source) # 37 </code></pre>
0
2016-09-29T02:54:48Z
[ "python", "arrays" ]
Python- Entry Level Programming
39,760,474
<p>I need to set up a code that has a 50% chance of selecting the first character of the mother string or the first character of the father string and add it to the child string, and so on for each letter. </p> <pre><code>import random mama_string = "0&gt;Y!j~K:bv9\Y,2" papa_string = "OkEK=gS&lt;mO%DnD{" child = "" while len(child) &lt; 15: random_number = random.randint(0,100) if random_number &lt;= 50: for mama_char in mama_string: child += mama_char break if random_number &gt; 50: for papa_char in papa_string: child += papa_char break print("The mother string is:",mama_string) print("The father string is:",papa_string) print("The child string is:",child) </code></pre> <p>The mother string is: 0>Y!j~K:bv9\Y,2</p> <p>The father string is: OkEK=gS&lt; mO%DnD{</p> <p>The child string is: 0O0O0O0OO0OOO00</p>
-3
2016-09-29T02:35:29Z
39,760,573
<p>You want to add one character per each iteration of the while loop (once for every time to generate a random number). Instead of running a for loop that goes through every character of the mama_string or papa_string. Just do</p> <pre><code> if random_number &lt;= 50: child += mama_char[len(child)] else: child += papa_char[len(child)] </code></pre> <p>The length of the child string sort of keeps track of which character (in the mama or papa string) you should add next.</p>
0
2016-09-29T02:45:41Z
[ "python", "random", "iteration" ]
Python- Entry Level Programming
39,760,474
<p>I need to set up a code that has a 50% chance of selecting the first character of the mother string or the first character of the father string and add it to the child string, and so on for each letter. </p> <pre><code>import random mama_string = "0&gt;Y!j~K:bv9\Y,2" papa_string = "OkEK=gS&lt;mO%DnD{" child = "" while len(child) &lt; 15: random_number = random.randint(0,100) if random_number &lt;= 50: for mama_char in mama_string: child += mama_char break if random_number &gt; 50: for papa_char in papa_string: child += papa_char break print("The mother string is:",mama_string) print("The father string is:",papa_string) print("The child string is:",child) </code></pre> <p>The mother string is: 0>Y!j~K:bv9\Y,2</p> <p>The father string is: OkEK=gS&lt; mO%DnD{</p> <p>The child string is: 0O0O0O0OO0OOO00</p>
-3
2016-09-29T02:35:29Z
39,760,646
<p>You could do it this way:</p> <pre><code>import numpy as np counter = 0 while len(child) &lt; 15: choice = np.random.choice([0,1]) if choice == 0: child += papa_string[counter] else: child += mama_string[counter] counter += 1 </code></pre> <p>This will alternate between selecting from the mother and father.</p>
0
2016-09-29T02:54:30Z
[ "python", "random", "iteration" ]
Using minimise function ('SLSQP' method) in sympy with free and fixed parameters
39,760,542
<p>I am still a beginner in python, so I am sorry if this is too trivial. I want to calculate the minimum value of a function which has 12 variables in total. Of these 12 variables, 10 are fixed at a given value and the remaining 2 is left free to compute the minimum. Here is an example of my code.</p> <pre><code>import numpy as np from sympy import * from scipy.optimize import minimize init_printing(use_unicode=True) X_1,X_2,Y_1,Y_2,X_c1,X_c2,Y_c1,Y_c2,a_1,a_2,b_1,b_2,t_1,t_2,psi_1,psi_2= symbols('X_1 X_2 Y_1 Y_2 X_c1 X_c2 Y_c1 Y_c2 a_1 a_2 b_1 b_2 t_1 t_2 psi_1 psi_2') X_1=X_c1 + (a_1 * cos(t_1) * cos(psi_1)) - ((b_1) * sin(t_1)* sin(psi_1)) X_2=X_c2 + (a_2 * cos(t_2) * cos(psi_2)) - ((b_2) * sin(t_2)* sin(psi_2)) Y_1=Y_c1 + (a_1 * cos(t_1) * sin(psi_1)) + ((b_1) * sin(t_1)* cos(psi_1)) Y_2=Y_c2 + (a_2 * cos(t_2) * sin(psi_2)) + ((b_2) * sin(t_2)* sin(psi_2)) param=(t_1,t_2,X_c1,X_c2,Y_c1,Y_c2,a_1,a_2,b_1,b_2,psi_1,psi_2) #12 parameters, 10 are fixed and 2 are free. free_param=(t_1,t_2) #These are my two free parameters D=((X_2-X_1)**2 + (Y_2-Y_1)**2)**0.5 #Expression to be minimised distance=lambdify(param, D, modules='numpy') </code></pre> <p>Following piece of code has been based on this link: <a href="http://stackoverflow.com/questions/31865549/want-to-do-multi-variation-minimize-with-sympy">Want to do multi-variation minimize with sympy</a></p> <pre><code>#Build Jacobian: jac_D=[D.diff(x) for x in param] jac_distance=[lambdify(param, jf, modules='numpy') for jf in jac_D] def vector_distance(zz): """ Helper for receiving vector parameters """ return distance(zz[0], zz[1], zz[2], zz[3], zz[4], zz[5], zz[6], zz[7], zz[8], zz[9], zz[10], zz[11]) def jac_vector_distance(zz): """ Jacobian Helper for receiving vector parameters """ return np.array([jfn(zz[0], zz[1], zz[2], zz[3], zz[4], zz[5], zz[6], zz[7], zz[8], zz[9], zz[10], zz[11]) for jfn in jac_distance]) zz0 = np.array([np.pi/2, np.p1/2]) #Guess values for t_1 and t_2 </code></pre> <p>Now I want to fix the values of the other 10 variables. I thought of using constrains. (I want X_c1=150, X_c2=2.03 and so on as shown below)</p> <pre><code>cons=({'type': 'eq', 'fun' : lambda x: np.array([X_c1-150])}, {'type': 'eq', 'fun' : lambda x:np.array([X_c2-2.03)]}, {'type': 'eq', 'fun': lambda x:np.array([Y_c1-152])}, {'type': 'eq', 'fun' : lambda x: np.array([Y_c2-2.31])}, {'type': 'eq', 'fun' : lambda x:np.array([a_1-5])}, {'type': 'eq', 'fun': lambda x:np.array([a_2-3])}, {'type': 'eq', 'fun' : lambda x: np.array([b_1-9])}, {'type': 'eq', 'fun' : lambda x:np.array([b_2-4])}, {'type': 'eq', 'fun': lambda x:np.array([psi_1-np.pi/2])}, {'type': 'eq', 'fun' : lambda x: np.array([psi_2-np.pi/4])}, ) bnds=((0,np.2pi), (0,np.2pi)) # My free parameters can take values between 0 and 2pi. rslts = minimize(vector_distance, zz0, method='SLSQP', jac=jac_vector_distance, constraints=cons, bounds=bnds) </code></pre> <p>This returns the following error:</p> <pre><code> --------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: can't convert expression to float During handling of the above exception, another exception occurred: SystemError Traceback (most recent call last) SystemError: &lt;built-in function hasattr&gt; returned a result with an error set During handling of the above exception, another exception occurred: SystemError Traceback (most recent call last) SystemError: &lt;built-in function hasattr&gt; returned a result with an error set During handling of the above exception, another exception occurred: SystemError Traceback (most recent call last) SystemError: &lt;built-in function hasattr&gt; returned a result with an error set During handling of the above exception, another exception occurred: SystemError Traceback (most recent call last) SystemError: &lt;built-in function hasattr&gt; returned a result with an error set During handling of the above exception, another exception occurred: SystemError Traceback (most recent call last) SystemError: &lt;built-in function hasattr&gt; returned a result with an error set During handling of the above exception, another exception occurred: SystemError Traceback (most recent call last) SystemError: &lt;built-in function hasattr&gt; returned a result with an error set During handling of the above exception, another exception occurred: SystemError Traceback (most recent call last) SystemError: &lt;built-in function hasattr&gt; returned a result with an error set During handling of the above exception, another exception occurred: SystemError Traceback (most recent call last) SystemError: &lt;built-in function hasattr&gt; returned a result with an error set During handling of the above exception, another exception occurred: SystemError Traceback (most recent call last) &lt;ipython-input-18-fc64da7d0cae&gt; in &lt;module&gt;() ----&gt; 1 rslts = minimize(vector_distance, zz0, method='SLSQP', jac=jac_vector_distance, constraints=cons) /users/vishnu/anaconda3/lib/python3.5/site-packages/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options) 453 elif meth == 'slsqp': 454 return _minimize_slsqp(fun, x0, args, jac, bounds, --&gt; 455 constraints, callback=callback, **options) 456 elif meth == 'dogleg': 457 return _minimize_dogleg(fun, x0, args, jac, hess, /users/vishnu/anaconda3/lib/python3.5/site-packages/scipy/optimize/slsqp.py in _minimize_slsqp(func, x0, args, jac, bounds, constraints, maxiter, ftol, iprint, disp, eps, callback, **unknown_options) 404 405 # Call SLSQP --&gt; 406 slsqp(m, meq, x, xl, xu, fx, c, g, a, acc, majiter, mode, w, jw) 407 408 # call callback if major iteration has incremented /users/vishnu/anaconda3/lib/python3.5/site-packages/sympy/core/expr.py in __float__(self) 219 # to fail, and if it is we still need to check that it evalf'ed to 220 # a number. --&gt; 221 result = self.evalf() 222 if result.is_Number: 223 return float(result) /users/vishnu/anaconda3/lib/python3.5/site-packages/sympy/core/evalf.py in evalf(self, n, subs, maxn, chop, strict, quad, verbose) 1359 1360 """ -&gt; 1361 from sympy import Float, Number 1362 n = n if n is not None else 15 1363 /users/vishnu/anaconda3/lib/python3.5/importlib/_bootstrap.py in _handle_fromlist(module, fromlist, import_) SystemError: &lt;built-in function hasattr&gt; returned a result with an error set </code></pre>
1
2016-09-29T02:42:00Z
39,767,762
<p>It seems that you are minimizing distance between two ellipse. You don't need sympy to do this. Here is an example:</p> <pre><code>from math import sin, cos, hypot, pi from scipy import optimize import numpy as np def ellipse(xc, yc, a, b, psi): a_cos_p = a * cos(psi) a_sin_p = a * sin(psi) b_cos_p = b * cos(psi) b_sin_p = b * sin(psi) def f(t): cos_t = cos(t) sin_t = sin(t) x = xc + cos_t * a_cos_p - sin_t * b_sin_p y = yc + cos_t * a_sin_p + sin_t * b_cos_p return x, y return f def min_dist_between_ellipses(el1, el2): def dist(pars): t1, t2 = pars.tolist() x1, y1 = el1(t1) x2, y2 = el2(t2) return hypot(x1 - x2, y1 - y2) r = optimize.minimize(dist, (0, 0)) return r.x.tolist(), dist(r.x) xc1 = 150 xc2 = 2.03 yc1 = 152 yc2 = 2.31 a1 = 5 a2 = 3 b1 = 9 b2 = 4 psi1 = pi / 2 psi2 = pi / 4 elpars1 = xc1, yc1, a1, b1, psi1 elpars2 = xc2, yc2, a2, b2, psi2 el1 = ellipse(*elpars1) el2 = ellipse(*elpars2) print((min_dist_between_ellipses(el1, el2))) x1, y1 = np.array([el1(t) for t in np.linspace(0, 2*np.pi, 100)]).T x2, y2 = np.array([el2(t) for t in np.linspace(0, 2*np.pi, 100)]).T print(np.hypot(x1[:, None] - x2[None, :], y1[:, None] - y2[None, :]).min()) </code></pre> <p>outputs:</p> <pre><code>([2.098535986219504, 0.03199718973020122], 200.25805791197473) 200.259630185 </code></pre>
1
2016-09-29T10:27:33Z
[ "python", "numpy", "sympy", "minimization" ]
How to parse XML of nested tags in Python
39,760,555
<p>I have following XML.</p> <pre><code>&lt;component name="QUESTIONS"&gt; &lt;topic name="Chair"&gt; &lt;state&gt;active&lt;/state&gt; &lt;subtopic name="Wooden"&gt; &lt;links&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;Understanding Wooden Chair&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/1111?view=app&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;How To Assemble Wooden CHair&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/2222?view=app&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="11:35" youtubeId="Qasefrt09_2" type="video"&gt; &lt;label&gt;Wooden Chair Tutorial&lt;/label&gt; &lt;url&gt;/&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="1:06" youtubeId="MSDVN235879" type="video"&gt; &lt;label&gt;How To Access Wood&lt;/label&gt; &lt;url&gt;/&lt;/url&gt; &lt;/link&gt; &lt;/links&gt; &lt;/subtopic&gt; &lt;/topic&gt; &lt;topic name="Table"&gt; &lt;state&gt;active&lt;/state&gt; &lt;subtopic name=""&gt; &lt;links&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;Understanding Tables&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/3333?view=app&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;Set-up Table&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/4444?view=app&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;How To Change table&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/5555?view=app&lt;/url&gt; &lt;/link&gt; &lt;/links&gt; &lt;/subtopic&gt; &lt;/topic&gt; &lt;/component&gt; </code></pre> <p>I am trying to parse this xml in python and creating an <code>URL array</code> which will contain: 1. All the http urls present in the xml 2. For the link tab if youtube is present then capture that and prepare youtube url and add it to <code>URL array</code>.</p> <p>I have following code, but it is not giving me url and links.</p> <pre><code>from xml.etree import ElementTree with open('faq.xml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.iter(): print node.tag, node.attrib.get('url') for node in tree.iter('outline'): name = node.attrib.get('link') url = node.attrib.get('url') if name and url: print ' %s :: %s' % (name, url) else: print name </code></pre> <p>How can I achieve this to get all urls?</p> <p>developed the following code based on below answers: Problem with following is, it is printing just 1 url not all.</p> <pre><code>from xml.etree import ElementTree def fetch_faq_urls(): url_list = [] with open('faq.xml', 'rt') as f: tree = ElementTree.parse(f) for link in tree.iter('link'): youtube = link.get('youtubeId') if youtube: print "https://www.youtube.com/watch?v=" + youtube video_url = "https://www.youtube.com/watch?v=" + youtube url_list.append(video_url) # print "youtubeId", link.find('label').text, '???' else: print link.find('url').text article_url = link.find('url').text url_list.append(article_url) # print 'url', link.find('label').text, return url_list faqs = fetch_faq_urls() print faqs </code></pre>
0
2016-09-29T02:43:20Z
39,760,931
<p>The information you want is under <code>&lt;link&gt;</code> so just iterate through those. Use <code>get()</code> to get the youtube id and <code>find()</code> to get the child <code>&lt;url&gt;</code> object. </p> <pre><code>from xml.etree import ElementTree with open('faq.xml', 'rt') as f: tree = ElementTree.parse(f) for link in tree.iter('link'): youtube = link.get('youtubeId') if youtube: print "youtube", link.find('label').text, '???' else: print 'url', link.find('label').text, link.find('url').text </code></pre>
1
2016-09-29T03:28:03Z
[ "python", "xml" ]
How to parse XML of nested tags in Python
39,760,555
<p>I have following XML.</p> <pre><code>&lt;component name="QUESTIONS"&gt; &lt;topic name="Chair"&gt; &lt;state&gt;active&lt;/state&gt; &lt;subtopic name="Wooden"&gt; &lt;links&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;Understanding Wooden Chair&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/1111?view=app&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;How To Assemble Wooden CHair&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/2222?view=app&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="11:35" youtubeId="Qasefrt09_2" type="video"&gt; &lt;label&gt;Wooden Chair Tutorial&lt;/label&gt; &lt;url&gt;/&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="1:06" youtubeId="MSDVN235879" type="video"&gt; &lt;label&gt;How To Access Wood&lt;/label&gt; &lt;url&gt;/&lt;/url&gt; &lt;/link&gt; &lt;/links&gt; &lt;/subtopic&gt; &lt;/topic&gt; &lt;topic name="Table"&gt; &lt;state&gt;active&lt;/state&gt; &lt;subtopic name=""&gt; &lt;links&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;Understanding Tables&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/3333?view=app&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;Set-up Table&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/4444?view=app&lt;/url&gt; &lt;/link&gt; &lt;link videoDuration="" youtubeId="" type="article"&gt; &lt;label&gt;How To Change table&lt;/label&gt; &lt;url&gt;http://abcd.xyz.com/5555?view=app&lt;/url&gt; &lt;/link&gt; &lt;/links&gt; &lt;/subtopic&gt; &lt;/topic&gt; &lt;/component&gt; </code></pre> <p>I am trying to parse this xml in python and creating an <code>URL array</code> which will contain: 1. All the http urls present in the xml 2. For the link tab if youtube is present then capture that and prepare youtube url and add it to <code>URL array</code>.</p> <p>I have following code, but it is not giving me url and links.</p> <pre><code>from xml.etree import ElementTree with open('faq.xml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.iter(): print node.tag, node.attrib.get('url') for node in tree.iter('outline'): name = node.attrib.get('link') url = node.attrib.get('url') if name and url: print ' %s :: %s' % (name, url) else: print name </code></pre> <p>How can I achieve this to get all urls?</p> <p>developed the following code based on below answers: Problem with following is, it is printing just 1 url not all.</p> <pre><code>from xml.etree import ElementTree def fetch_faq_urls(): url_list = [] with open('faq.xml', 'rt') as f: tree = ElementTree.parse(f) for link in tree.iter('link'): youtube = link.get('youtubeId') if youtube: print "https://www.youtube.com/watch?v=" + youtube video_url = "https://www.youtube.com/watch?v=" + youtube url_list.append(video_url) # print "youtubeId", link.find('label').text, '???' else: print link.find('url').text article_url = link.find('url').text url_list.append(article_url) # print 'url', link.find('label').text, return url_list faqs = fetch_faq_urls() print faqs </code></pre>
0
2016-09-29T02:43:20Z
39,762,205
<p>Take a look at <a href="https://github.com/martinblech/xmltodict" rel="nofollow">xmltodict</a>.</p> <pre><code>&gt;&gt;&gt; print(json.dumps(xmltodict.parse(""" ... &lt;mydocument has="an attribute"&gt; ... &lt;and&gt; ... &lt;many&gt;elements&lt;/many&gt; ... &lt;many&gt;more elements&lt;/many&gt; ... &lt;/and&gt; ... &lt;plus a="complex"&gt; ... element as well ... &lt;/plus&gt; ... &lt;/mydocument&gt; ... """), indent=4)) { "mydocument": { "@has": "an attribute", "and": { "many": [ "elements", "more elements" ] }, "plus": { "@a": "complex", "#text": "element as well" } } } </code></pre>
0
2016-09-29T05:39:14Z
[ "python", "xml" ]
Iterating Over CSV Deleting Analyzed Data
39,760,579
<p>Hello I am trying to take a CSV file and iterate over each customers data. To explain, each customer has data for 12 months. I want to analyze their yearly data, save the correlations of this data to a new list and loop this until all customers have been analyzed.</p> <p>For instance here is what a customers data might look like (simplified case): <a href="http://i.stack.imgur.com/gGeR5.png" rel="nofollow"><img src="http://i.stack.imgur.com/gGeR5.png" alt="enter image description here"></a></p> <p>I have been able to get this to work to generate correlations in a CSV of one customers data. However, there are thousands of customers in my datasheet. I want to use a nested for loop to get all of the correlation values for each customer into a list/array. The list would have a row of a specific customer's correlations then the next row would be the next customer.</p> <p>Here is my current code:</p> <pre><code>import numpy from numpy import genfromtxt overalldata = genfromtxt('C:\Users\User V\Desktop\CUSTDATA.csv', delimiter=',') emptylist = [] overalldatasubtract = overalldata[13::] #This is where I try to use the four loop to go through all the customers. I don't know if len will give me all the rows or the number of columns. for x in range(0,len(overalldata),11): for x in range(0,13,1): cust_months = overalldata[0:x,1] cust_balancenormal = overalldata[0:x,16] cust_demo_one = overalldata[0:x,2] cust_demo_two = overalldata[0:x,3] num_acct_A = overalldata[0:x,4] num_acct_B = overalldata[0:x,5] #Correlation Calculations demo_one_corr_balance = numpy.corrcoef(cust_balancenormal, cust_demo_one)[1,0] demo_two_corr_balance = numpy.corrcoef(cust_balancenormal, cust_demo_two)[1,0] demo_one_corr_acct_a = numpy.corrcoef(num_acct_A, cust_demo_one)[1,0] demo_one_corr_acct_b = numpy.corrcoef(num_acct_B, cust_demo_one)[1,0] demo_two_corr_acct_a = numpy.corrcoef(num_acct_A, cust_demo_two)[1,0] demo_two_corr_acct_b = numpy.corrcoef(num_acct_B, cust_demo_two)[1,0] result_correlation = [demo_one_corr_balance, demo_two_corr_balance, demo_one_corr_acct_a, demo_one_corr_acct_b, demo_two_corr_acct_a, demo_two_corr_acct_b] result_correlation_combined = emptylist.append(result_correlation) #This is where I try to delete the rows I have already analyzed. overalldata = overalldata[11**x::] print result_correlation_combined print overalldatasubtract </code></pre> <p>It seemed that my subtraction method was working, but when I tried it with my larger data set, I realized my method is totally wrong.</p> <p>Would you do this a different way? I think that it can work, but I cannot find my mistake.</p>
0
2016-09-29T02:46:30Z
39,766,541
<p>You use the same variable <code>x</code> for both loops. In the second loop <code>x</code> goes from 0 to 12 whatever the customer, and since you set the line number only with <code>x</code> you're stuck on the first customer.</p> <p>Your double loop should rather look like this :</p> <pre><code># loop over the customers for x_customer in range(0,len(overalldata),12): # loop over the months for x_month in range(0,12,1): # line number: x x = x_customer*12 + x_month ... </code></pre> <p>I changed the bounds and steps of the loops because :</p> <ul> <li><strong>loop 1:</strong> there are 12 months so 12 lines per customer -> step = 12</li> <li><strong>loop 2:</strong> there are 12 months, so month number ranges from 0 to 11 -> <code>range(0,12,1)</code></li> </ul>
0
2016-09-29T09:28:50Z
[ "python", "list", "csv", "append" ]
Iterating Over CSV Deleting Analyzed Data
39,760,579
<p>Hello I am trying to take a CSV file and iterate over each customers data. To explain, each customer has data for 12 months. I want to analyze their yearly data, save the correlations of this data to a new list and loop this until all customers have been analyzed.</p> <p>For instance here is what a customers data might look like (simplified case): <a href="http://i.stack.imgur.com/gGeR5.png" rel="nofollow"><img src="http://i.stack.imgur.com/gGeR5.png" alt="enter image description here"></a></p> <p>I have been able to get this to work to generate correlations in a CSV of one customers data. However, there are thousands of customers in my datasheet. I want to use a nested for loop to get all of the correlation values for each customer into a list/array. The list would have a row of a specific customer's correlations then the next row would be the next customer.</p> <p>Here is my current code:</p> <pre><code>import numpy from numpy import genfromtxt overalldata = genfromtxt('C:\Users\User V\Desktop\CUSTDATA.csv', delimiter=',') emptylist = [] overalldatasubtract = overalldata[13::] #This is where I try to use the four loop to go through all the customers. I don't know if len will give me all the rows or the number of columns. for x in range(0,len(overalldata),11): for x in range(0,13,1): cust_months = overalldata[0:x,1] cust_balancenormal = overalldata[0:x,16] cust_demo_one = overalldata[0:x,2] cust_demo_two = overalldata[0:x,3] num_acct_A = overalldata[0:x,4] num_acct_B = overalldata[0:x,5] #Correlation Calculations demo_one_corr_balance = numpy.corrcoef(cust_balancenormal, cust_demo_one)[1,0] demo_two_corr_balance = numpy.corrcoef(cust_balancenormal, cust_demo_two)[1,0] demo_one_corr_acct_a = numpy.corrcoef(num_acct_A, cust_demo_one)[1,0] demo_one_corr_acct_b = numpy.corrcoef(num_acct_B, cust_demo_one)[1,0] demo_two_corr_acct_a = numpy.corrcoef(num_acct_A, cust_demo_two)[1,0] demo_two_corr_acct_b = numpy.corrcoef(num_acct_B, cust_demo_two)[1,0] result_correlation = [demo_one_corr_balance, demo_two_corr_balance, demo_one_corr_acct_a, demo_one_corr_acct_b, demo_two_corr_acct_a, demo_two_corr_acct_b] result_correlation_combined = emptylist.append(result_correlation) #This is where I try to delete the rows I have already analyzed. overalldata = overalldata[11**x::] print result_correlation_combined print overalldatasubtract </code></pre> <p>It seemed that my subtraction method was working, but when I tried it with my larger data set, I realized my method is totally wrong.</p> <p>Would you do this a different way? I think that it can work, but I cannot find my mistake.</p>
0
2016-09-29T02:46:30Z
39,780,384
<p>this is how I solved the problem: It was a problem with the placement of my for loops. A simple indentation problem. Thank you for the help to above poster.</p> <p>for x_customer in range(0,len(overalldata),12):</p> <pre><code> for x in range(0,13,1): cust_months = overalldata[0:x,1] cust_balancenormal = overalldata[0:x,16] cust_demo_one = overalldata[0:x,2] cust_demo_two = overalldata[0:x,3] num_acct_A = overalldata[0:x,4] num_acct_B = overalldata[0:x,5] #Correlation Calculations demo_one_corr_balance = numpy.corrcoef(cust_balancenormal, cust_demo_one)[1,0] demo_two_corr_balance = numpy.corrcoef(cust_balancenormal, cust_demo_two)[1,0] demo_one_corr_acct_a = numpy.corrcoef(num_acct_A, cust_demo_one)[1,0] demo_one_corr_acct_b = numpy.corrcoef(num_acct_B, cust_demo_one)[1,0] demo_two_corr_acct_a = numpy.corrcoef(num_acct_A, cust_demo_two)[1,0] demo_two_corr_acct_b = numpy.corrcoef(num_acct_B, cust_demo_two)[1,0] result_correlation = [(demo_one_corr_balance),(demo_two_corr_balance),(demo_one_corr_acct_a),(demo_one_corr_acct_b),(demo_two_corr_acct_a),(demo_two_corr_acct_b)] numpy.savetxt('correlationoutput.csv', (result_correlation)) result_correlation_combined = emptylist.append([result_correlation]) cust_delete_list = [0,(x_customer),1] overalldata = numpy.delete(overalldata, (cust_delete_list), axis=0) </code></pre>
0
2016-09-29T21:33:28Z
[ "python", "list", "csv", "append" ]
How to access Selenium elements as soon as they are available, rather than waiting for the whole page to load
39,760,595
<pre><code>driver = webdriver.Chrome() #driver.set_page_load_timeout(10) driver.get("sitename.com") driver.find_element_by_id("usernameId").send_keys("myusername") </code></pre> <p>Setting a page load time proved counterproductive as the page load was killed even before the elements were actually loaded!</p> <p>Currently, when I try to login on a site, the find_element_by_id() waits for the complete page to load, then gets me the element. I've read about implicit/explicit waits used along with ExpectedConditions, but as far as I understand they are used for waiting for an element to appear(dynamically) after the complete page has loaded. </p> <p>Is there a way I can find an element as soon(polling is good enough) as it is visible(without waiting for the complete page to load)? It would be great to do so, some pages take quite a while to load(heavy traffic/low availability/poor internet connection could be reasons though). I am using Selenium with Python, and a Chrome Driver. Thanks.</p>
0
2016-09-29T02:48:12Z
39,762,067
<p>Take a look at <a href="http://selenium-python.readthedocs.io/waits.html" rel="nofollow">selenium python documentation</a>.</p> <p>It has visibility_of_element_located.</p> <pre><code>from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) element = wait.until(EC.visibility_of_element_located((By.ID,'someid'))) </code></pre>
1
2016-09-29T05:26:53Z
[ "python", "selenium", "selenium-chromedriver" ]
How to access Selenium elements as soon as they are available, rather than waiting for the whole page to load
39,760,595
<pre><code>driver = webdriver.Chrome() #driver.set_page_load_timeout(10) driver.get("sitename.com") driver.find_element_by_id("usernameId").send_keys("myusername") </code></pre> <p>Setting a page load time proved counterproductive as the page load was killed even before the elements were actually loaded!</p> <p>Currently, when I try to login on a site, the find_element_by_id() waits for the complete page to load, then gets me the element. I've read about implicit/explicit waits used along with ExpectedConditions, but as far as I understand they are used for waiting for an element to appear(dynamically) after the complete page has loaded. </p> <p>Is there a way I can find an element as soon(polling is good enough) as it is visible(without waiting for the complete page to load)? It would be great to do so, some pages take quite a while to load(heavy traffic/low availability/poor internet connection could be reasons though). I am using Selenium with Python, and a Chrome Driver. Thanks.</p>
0
2016-09-29T02:48:12Z
39,764,430
<p>It is a best practice to wait for entire page to load before you take any further action. However, if you want to stop the page load in between(or load the page only for a specified time and carry on), you can change this in the browser's profile setting.</p> <p>In case of Firefox :</p> <pre><code>profile = webdriver.FirefoxProfile() profile.set_preference("http.response.timeout", 10) profile.set_preference("dom.max_script_run_time", 10) driver = webdriver.Firefox(firefox_profile=profile) </code></pre> <p>Hope it helps, cheers.</p>
1
2016-09-29T07:52:05Z
[ "python", "selenium", "selenium-chromedriver" ]
Getting a SyntaxError in try:except (python)
39,760,601
<p>Hi so I'm really new to Python and I have a little question.</p> <p>In my code:</p> <pre><code>from collections import Counter </code></pre> <p>try: while True:</p> <pre><code> name1 = input ("your name") list(name1) name1len = len(name1) name2 = input ("other one's name") list(name2) name2len = len(name2) if name1len &gt; 10: print ("name is too long") break if name2len &gt; 10: print ("name is too long") break a1 = (name1[0][0]) a2 = (name2[0][0]) if set(a1) &amp; set(a1) == set(a2): print ("ok") else: print ("none") a3 = (name1[1][0]) a4 = (name2[1][0]) if set(a3) &amp; set(a3) == set(a4): print ("ok") else: print ("none") a5 = (name1[2][0]) a6 = (name2[2][0]) if set(a5) &amp; set(a5) == set(a6): print ("ok") else: print ("none") a7 = (name1[3][0]) a8 = (name2[3][0]) if set(a7) &amp; set(a7) == set(a8): print ("ok") else: print ("none") a9 = (name1[4][0]) a10 = (name2[4][0]) if set(a9) &amp; set(a9) == set(a10): print ("ok") else: print ("none") a11 = (name1[5][0]) a12 = (name2[5][0]) if set(a11) &amp; set(a11) == set(a12): print ("ok") else: print ("none") a13 = (name1[6][0]) a14 = (name2[6][0]) if set(a13) &amp; set(a13) == set(a14): print ("ok") else: print ("none") a15 = (name1[7][0]) a16 = (name2[7][0]) if set(a15) &amp; set(a15) == set(a16): print ("ok") else: print ("none") a17 = (name1[8][0]) a18 = (name2[8][0]) if set(a17) &amp; set(a18) == set(a19): print ("ok") else: print ("none") a19 = (name1[9][0]) a20 = (name2[9][0]) if set(a19) &amp; set(a19) == set(a20): print ("ok") else: print ("none") a21 = (name1[10][0]) a22 = (name2[10][0]) if set(a21) &amp; set(a21) == set(a22): print ("ok") else: print ("none") except (IndexError): pass </code></pre> <p>and in the end at the very bottom, it keeps on giving me this error:</p> <p>File "dr.luvtest.py", line 106 except (IndexError): ^ SyntaxError: invalid syntax</p> <p>Thanks in advance! </p>
0
2016-09-29T02:48:58Z
39,760,695
<p>In order to use the <code>try &amp; except</code> functions, you need to you that first part, the <code>try</code>. In your code there is no <code>try:</code> which is why the <code>except</code> is causing issues.</p> <p>However every time I try to fix one issue, other one pops up. However Python won't even run your code if the syntax is incorrect.</p> <p>In order to fix the syntax error,</p> <p>Change</p> <pre><code>else: print ("none") except IndexError: pass </code></pre> <p>To</p> <p>Wrap the whole thing in a <code>try</code> statement, then the <code>except</code> will catch an <code>IndexError</code></p>
0
2016-09-29T03:01:00Z
[ "python", "python-3.x" ]
How to capture KeyboardInterrupt in pytest?
39,760,629
<p>UnitTests has a feature to capture <code>KeyboardInterrupt</code>, finishes a test and then report the results.</p> <blockquote> <p><strong>-c, --catch</strong> </p> <p><em>Control-C</em> during the test run waits for the current test to end and then reports all the results so far. A second <em>Control-C</em> raises the normal KeyboardInterrupt exception.</p> <p>See Signal Handling for the functions that provide this functionality.</p> <p>c.f. <a href="https://docs.python.org/2/library/unittest.html#command-line-options" rel="nofollow">https://docs.python.org/2/library/unittest.html#command-line-options</a></p> </blockquote> <p>In PyTest, <kbd>Ctrl</kbd>+<kbd>C</kbd> will just stop the session.</p> <p>Is there a way to do the same as UniTests:</p> <ul> <li>Capture <code>KeyboardInterrupt</code></li> <li>Finishes to execute the on-going test [optional]</li> <li>Skip other tests</li> <li>Display a result, and potentially print a report (e.g. usage of <code>pytest-html</code>)</li> </ul> <p>Thanks</p>
0
2016-09-29T02:52:51Z
39,761,889
<p>Take a look at pytest's <a href="http://doc.pytest.org/en/latest/_modules/_pytest/hookspec.html" rel="nofollow">hookspec</a>.</p> <p>They have a hook for keyword interrupt.</p> <pre><code>def pytest_keyboard_interrupt(excinfo): """ called for keyboard interrupt. """ </code></pre>
0
2016-09-29T05:13:06Z
[ "python", "py.test" ]
How can I order elements in a window in python apache beam?
39,760,733
<p>I noticed that java apache beam has class groupby.sortbytimestamp does python have that feature implemented yet? If not what would be the way to sort elements in a window? I figure I could sort the entire window in a DoFn, but I would like to know if there is a better way. </p>
1
2016-09-29T03:04:16Z
39,776,373
<p>There is not currently built-in value sorting in Beam (in either Python or Java). Right now, the best option is to sort the values yourself in a DoFn like you mentioned.</p>
3
2016-09-29T17:17:47Z
[ "python", "google-cloud-dataflow", "dataflow", "apache-beam" ]
Generate Swagger specification from Python code without annotations
39,760,800
<p>I am searching for a way to generate a Swagger specification (the JSON and Swagger-UI) from the definition of a Python service. I have found many options (normally Flask-based), but all of them use annotations, which I cannot properly handle from within the code, e.g. define 10 equivalent services with different routes in a loop (the handler could be currified in this example, first function call to obtain it).</p> <p>Is there any way to do this without annotations? I would like to generate the method in the API and its documentation by calling a function (or a method, or a constructor of a class) with the values corresponding to the implementation and the documentation of that API method.</p>
0
2016-09-29T03:11:23Z
39,761,823
<p>I suggest looking into <a href="http://apispec.readthedocs.io/en/latest/quickstart.html" rel="nofollow">apispec</a>.</p> <p>apispec is a pluggable API specification generator.</p> <p>Currently supports the OpenAPI 2.0 specification (f.k.a. Swagger 2.0)</p> <p><strong><em>apispec</em></strong></p> <pre><code>from apispec import APISpec spec = APISpec( title='Gisty', version='1.0.0', info=dict(description='A minimal gist API') ) spec.definition('Gist', properties={ 'id': {'type': 'integer', 'format': 'int64'}, 'content': 'type': 'string'}, }) spec.add_path( path='/gist/{gist_id}', operations=dict( get=dict( responses={ '200': { 'schema': {'$ref': '#/definitions/Gist'} } } ) ) ) </code></pre>
0
2016-09-29T05:07:10Z
[ "python", "web-services", "python-3.x", "swagger-ui", "swagger-2.0" ]
Why variable still exists after function call finished -python
39,760,910
<p>I read from a book about some code like below, but it was not explained. As you can see, before I call the function, no variable exists. But after function call, var2 was popped form stack and removed from our namespace of func_a as what we expected. But, var1 still exists!!!</p> <blockquote> <p>How to explain this phenomenon? Is var1 a special kind of variable? </p> </blockquote> <pre><code>def func_a(): func_a.var1 = 1 var2 = 2 &gt;&gt;&gt; func_a.var1 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'function' object has no attribute 'var1' &gt;&gt;&gt; var2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'var2' is not defined &gt;&gt;&gt; func_a() &gt;&gt;&gt; func_a.var1 1 &gt;&gt;&gt; var2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'var2' is not defined </code></pre>
1
2016-09-29T03:24:49Z
39,760,955
<blockquote> <p>How to explain this phenomenon? Is var1 a special kind of variable?</p> </blockquote> <p>Yes, <code>var1</code> is a special kind of variable. Or perhaps more precisely, it's not a variable at all. It's an attribute of an object (even though the object is a function). The object existed before the function call, and it continues to exist after. </p> <p>In the function call you are <em>adding an attribute</em> to a global object rather than <em>creating a variable</em> in a local scope.</p>
4
2016-09-29T03:31:27Z
[ "python", "python-2.7" ]
Why variable still exists after function call finished -python
39,760,910
<p>I read from a book about some code like below, but it was not explained. As you can see, before I call the function, no variable exists. But after function call, var2 was popped form stack and removed from our namespace of func_a as what we expected. But, var1 still exists!!!</p> <blockquote> <p>How to explain this phenomenon? Is var1 a special kind of variable? </p> </blockquote> <pre><code>def func_a(): func_a.var1 = 1 var2 = 2 &gt;&gt;&gt; func_a.var1 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'function' object has no attribute 'var1' &gt;&gt;&gt; var2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'var2' is not defined &gt;&gt;&gt; func_a() &gt;&gt;&gt; func_a.var1 1 &gt;&gt;&gt; var2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'var2' is not defined </code></pre>
1
2016-09-29T03:24:49Z
39,760,976
<p>You are confusing the function namespace with the function object. Before the function is called, <code>var1</code> doesn't exist. When the function is called, python creates a temporary local namespace for that one call. When the function hits <code>var2 = 2</code>, <code>var2</code> is created in the local function namespace. When the function hits <code>func_a.var1 = 1</code>, python looks <code>func_a</code> up in the global namespace, finds the function object, and adds <code>var1</code> to it. When the function exits, the local namespace disappears but the function object still exists and so will <code>var1</code>.</p>
2
2016-09-29T03:34:14Z
[ "python", "python-2.7" ]
Not able to frame text while adding a line to middle of file in python
39,760,947
<p>My text.txt looks like this</p> <pre><code>abcd xyzv dead-hosts -abcd.srini.com -asdsfcd.srini.com </code></pre> <p>And I want to insert few lines after "dead-hosts" line, I made a script to add lines to file, there is extra space before last line, that's mandatory in my file, but post added new lines that space got removed, dont know how to maintain the space as it is. Here is my script</p> <pre><code>Failvrlist = ['srini.com','srini1.com'] tmplst = [] with open(‘test.txt’,'r+') as fd: for line in fd: tmplst.append(line.strip()) pos = tmplst.index('dead-hosts:') tmplst.insert(pos+1,"#extra comment ") for i in range(len(Failvrlist)): tmplst.insert(pos+2+i," - "+Failvrlist[i]) tmplst.insert(pos+len(Failvrlist)+2,"\n") for i in xrange(len(tmplst)): fd.write("%s\n" %(tmplst[i])) </code></pre> <p>output is as below</p> <pre><code>abcd xyzv dead-hosts #extra comment - srini.com - srini1.com - abcd.srini.com - asdsfcd.srini.com </code></pre> <p>if you look at the last two lines the space got removed, please advise .</p>
-1
2016-09-29T03:30:39Z
39,761,744
<p><strong>Points:</strong></p> <ul> <li>In you code , <code>pos = tmplst.index('dead-hosts:')</code>, you are trying to find <code>dead-hosts:</code>. However, input file you have given has only "<code>dead hosts</code>". No colon after dead-hosts, I am considering <code>dead-hosts:</code></li> <li>While reading file first time into list, use <code>rstrip()</code> instead of <code>strip()</code>. Using rstrip() will keep spaces at the start of line as it is.</li> <li>Once you read file into list, code after that should be outside <code>with</code> block which is use to open and read file.</li> </ul> <p><strong>Actually, flow of code should be</strong> </p> <ol> <li>Open file and read lines to list and close the file.</li> <li>Modify list by inserting values at specific index.</li> <li>Write the file again.</li> </ol> <p><strong>Code:</strong></p> <pre><code>Failvrlist = ['srini.com','srini1.com'] tmplst = [] #Open file and read it with open('result.txt','r+') as fd: for line in fd: tmplst.append(line.rstrip()) #Modify list pos = tmplst.index('dead-hosts:') tmplst.insert(pos+1,"#extra comment") pos = tmplst.index('#extra comment') a = 1 for i in Failvrlist: to_add = " -" + i tmplst.insert(pos+a,to_add) a+=1 #Write to file with open('result.txt','w') as fd: for i in range(len(tmplst)): fd.write("%s\n" %(tmplst[i])) </code></pre> <p><strong>Content of result.txt:</strong></p> <pre><code>abcd xyzv dead-hosts: #extra comment -srini.com -srini1.com -abcd.srini.com -asdsfcd.srini.com </code></pre>
0
2016-09-29T04:59:47Z
[ "python" ]
List of dicts each with different keys, best way to look for a sequence of dicts
39,760,971
<p>I have a list of dicts (list with each entry being a dict). Each dict has a different set of keys, so one dict may have a key that is not present with the other dicts in the list. I am trying to find a specific order of dicts inside this list. Basically, the list is from a wireshark capture and I want to look for certain packets. There is a specific sequence of packets in the middle of the list. Also, inside this sequence, there are some packets which I wish to ignore/filter. What is the best way to achieve this? I have some pseudo code written below:</p> <pre><code>for i in range(len(packets)): p = packets[i].fields # This method turns the packet object into a dict try: if p['some_field'] == A_CONSTANT_I_HAVE_DEFINED: # Mark this packet as part of the sequence # Save as part of sequence first_packet = p # Do not check for this condition again! I want to go to the next # iteration once I come across a packet with similar property # (the equality satisfied) if p['some_field'] == ANOTHER_CONSTANT: # Same as above second_packet = p if p['some_other_field'] == SOME_OTHER_CONSTANT: # Same as above third_packet = p except KeyError as err: pass # Now I should have first_packet, second_packet and third_packet # The list packets will always have the sequence of packets I am looking for </code></pre> <p>Note how I have the fields <code>some_field</code> and <code>some_other_field</code> different, and the different constants: <code>A_CONSTANT_I_HAVE_DEFINED, ANOTHER_CONSTANT, SOME_OTHER_CONSTANT</code>. Note that <code>some_field</code> may not be in each item in the list, same for <code>some_other_field</code></p>
0
2016-09-29T03:33:22Z
39,761,203
<pre><code>first_packet = None second_packet = None third_packet = None packets_found = 0 for packet in packets: val = packet.get('some_field', None) if (val == A_CONSTANT_I_HAVE_DEFINED) and (first_packet is not None): first_packet = packet packets_found += 1 elif (val == ANOTHER_CONSTANT) and (second_packet is not None): second_packet = packet packets_found += 1 elif (packet.get('some_other_field', None) == SOME_OTHER_CONSTANT) and (third_packet is not None): third_packet = packet packets_found += 1 if packets_found == 3: break </code></pre>
0
2016-09-29T04:03:42Z
[ "python", "list", "dictionary" ]
List of dicts each with different keys, best way to look for a sequence of dicts
39,760,971
<p>I have a list of dicts (list with each entry being a dict). Each dict has a different set of keys, so one dict may have a key that is not present with the other dicts in the list. I am trying to find a specific order of dicts inside this list. Basically, the list is from a wireshark capture and I want to look for certain packets. There is a specific sequence of packets in the middle of the list. Also, inside this sequence, there are some packets which I wish to ignore/filter. What is the best way to achieve this? I have some pseudo code written below:</p> <pre><code>for i in range(len(packets)): p = packets[i].fields # This method turns the packet object into a dict try: if p['some_field'] == A_CONSTANT_I_HAVE_DEFINED: # Mark this packet as part of the sequence # Save as part of sequence first_packet = p # Do not check for this condition again! I want to go to the next # iteration once I come across a packet with similar property # (the equality satisfied) if p['some_field'] == ANOTHER_CONSTANT: # Same as above second_packet = p if p['some_other_field'] == SOME_OTHER_CONSTANT: # Same as above third_packet = p except KeyError as err: pass # Now I should have first_packet, second_packet and third_packet # The list packets will always have the sequence of packets I am looking for </code></pre> <p>Note how I have the fields <code>some_field</code> and <code>some_other_field</code> different, and the different constants: <code>A_CONSTANT_I_HAVE_DEFINED, ANOTHER_CONSTANT, SOME_OTHER_CONSTANT</code>. Note that <code>some_field</code> may not be in each item in the list, same for <code>some_other_field</code></p>
0
2016-09-29T03:33:22Z
39,761,204
<p>I am not clear, this might help:</p> <pre><code>a = [{'a': 1}, {'a':1, 'b':1}, {'c':1}] filtered_list = filter(lambda x: x.get('a') or x.get('b'), a) # OP [{'a': 1}, {'a': 1, 'b': 1}] </code></pre> <p>Hope this helps.</p>
0
2016-09-29T04:04:04Z
[ "python", "list", "dictionary" ]
Sum up values in a column using Pandas
39,761,068
<p>I have a dataframe where one column has a list of zipcodes and the other has property values corresponding to the zipcode. I want to sum up the property values in each row according to the appropriate zipcode. </p> <p>So, for example:</p> <pre><code>zip value 2210 $5,000 2130 $3,000 2210 $2,100 2345 $1,000 </code></pre> <p>I would then add up the values </p> <pre><code>$5,000 + $2,100 = $7,100 </code></pre> <p>and reap the total property value of for zipcode 2210 as $7,100. </p> <p>Any help in this regard will be appreciated</p>
0
2016-09-29T03:45:56Z
39,761,102
<p>You need:</p> <pre><code>df zip value 0 2210 5000 1 2130 3000 2 2210 2100 3 2345 1000 df2 = df.groupby(['zip'])['value'].sum() df2 zip value 2130 3000 2210 7100 2345 1000 Name: value, dtype: int64 </code></pre> <p>You can read more about it <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">here</a>.</p> <p>Also you will need to remove the $ sign in the column values. For that you can use something along the lines of the following while reading the dataframe initially:</p> <pre><code>df = pd.read_csv('zip_value.csv', header=0,names=headers,converters={'value': lambda x: float(x.replace('$',''))}) </code></pre> <p>Edit: Changed the code according to comment. To reset the index after groupby use:</p> <pre><code>df2 = df.groupby(['zip'])['value'].sum().reset_index() </code></pre> <p>Then to remove a particular column with zip value ,say, 2135 , you need</p> <pre><code>df3 = df2[df2['zip']!= 2135] </code></pre>
1
2016-09-29T03:51:12Z
[ "python", "pandas", "dataframe", "sum" ]
Login to website with Python requests
39,761,233
<p>I am having some trouble logging into this website: <a href="https://illinoisjoblink.illinois.gov/ada/r/home" rel="nofollow">https://illinoisjoblink.illinois.gov/ada/r/home</a></p> <p>I am able to submit the payload, but I get redirected to a page claiming a bookmark error. Here is the code and relevant error messages. I'm not sure how to proceed. I appreciate any and all help. Thanks!</p> <pre class="lang-python prettyprint-override"><code> session = requests.Session() soup = BeautifulSoup(session.get(SEARCH_URL).content, "html.parser") inputs = soup.find_all('input') token = '' for t in inputs: try: if t['name'] == 'authenticity_token': token = t['value'] break except KeyError as e: pass login_data = dict(v_username=USER_NAME, v_password=PASSWORD, authenticity_token=token, commit='Log In') login_data['utf-8'] = '&amp;#x2713;' r = session.post(LOGIN_URL, data=login_data) print(r.content) </code></pre> <p> <code>Bookmark Error &lt;b&gt;You may be seeing this error as a result of bookmarking this page. Unfortunately, our site design will not allow the bookmarking of most internal pages.&lt;/b&gt; If you wish to contact the system administra tor concerning this error, you may send an email to &lt;a href="mailto:[email protected]"&gt;[email protected]&lt;/a&gt;. Please reference error number &lt;b&gt;646389&lt;/b&gt;.&lt;p&gt;Thank you for your patience.&lt;br&gt;&lt;br&gt; Hit your browser back button to return to the previous page. </code></p>
0
2016-09-29T04:07:08Z
39,808,378
<p>Perhaps your <code>login_data</code> parameters are wrong? When I inspect the POST for logging in, the necessary parameters appear to be: <code>v_username</code>, <code>v_password</code>, <code>FormName</code>, <code>fromlogin</code>, and maybe most importantly, <code>button</code>. I would suggest you add all these parameters to your <code>login_data</code> dictionary. Your dictionary would look something like:</p> <pre><code>login_data = {'v_username': USER_NAME, 'v_password': PASSWORD, 'authenticity_token': token, 'FormName': 0, 'fromlogin': 1, 'button': 'Log+in'} </code></pre>
0
2016-10-01T15:32:00Z
[ "python", "login", "website", "python-requests", "screen-scraping" ]
Better way to loop through nested categories?
39,761,252
<p>I have a sqlalchemy categories table that looks like this:</p> <pre><code>id | parent_id | name 1 | 0 | license 2 | 1 | Digital Media 3 | 1 | Advertising 4 | 2 | Email Marketing </code></pre> <p>My goal is to convert this into a nested dictionary or list that I can loop through in a Flask template. The code below works but looks very messy to me. Is there a way I can improve it?</p> <pre><code>categories = Category.query.all() roots = [root for root in categories if root.parent_id == 1] items = [] for root in roots: items.append({'root': root.name, 'subcategories': []}) for category in categories: if category.parent_id == root.id: items[-1]['subcategories'].append(category.name) </code></pre>
0
2016-09-29T04:08:41Z
39,761,318
<p>You can nest list comprehensions, so you need not double-loop through <code>roots</code> and <code>categories</code>.</p> <pre><code>categories = Category.query.all() roots = [root for root in categories if root.parent_id == 1] items = [ { 'root': root.name, 'subcategories': [ category.name for category in categories if category.parent_id == root.id ] } for root in roots ] </code></pre>
0
2016-09-29T04:16:46Z
[ "python" ]
Better way to loop through nested categories?
39,761,252
<p>I have a sqlalchemy categories table that looks like this:</p> <pre><code>id | parent_id | name 1 | 0 | license 2 | 1 | Digital Media 3 | 1 | Advertising 4 | 2 | Email Marketing </code></pre> <p>My goal is to convert this into a nested dictionary or list that I can loop through in a Flask template. The code below works but looks very messy to me. Is there a way I can improve it?</p> <pre><code>categories = Category.query.all() roots = [root for root in categories if root.parent_id == 1] items = [] for root in roots: items.append({'root': root.name, 'subcategories': []}) for category in categories: if category.parent_id == root.id: items[-1]['subcategories'].append(category.name) </code></pre>
0
2016-09-29T04:08:41Z
39,761,438
<p>If you just want a more concise way of writing the logic you've put forward, look below:</p> <pre><code>categories = Category.query.all() items = [{'root': root.name, 'subcategories': [category.name for category in categories if category.parent_id == root.id] } for root in categories if root.parent_id == 1] </code></pre> <p>Note that this runs in O(N<sup>2</sup>) where N is the number of categories. If you want this to preform better, you could map <code>parent_id</code>s to categories. For example:</p> <pre><code>categories = Category.query.all() category_by_parent_id = {} for category in categories: if category.parent_id not in category_by_parent_id: category_by_parent_id[category.parent_id] = [category] else: category_by_parent_id[category.parent_id].append(category) items = [{'root': root.name, 'subcategories': category_by_parent_id[root.id] if root.id in category_by_parent_id else []} for root in category_by_parent_id[1]] </code></pre> <p>The above work by making each parent_id map to a list of categories that have that parent id. Then we loop through all root categories (the list at parent_id 1 in the dictionary), and set subcategories equal to the list of categories corresponding to the root's id. If the root's id is not in the dictionary, we instead set subcategories to the empty list. Now the runtime of this operation is O(N) because we're only running through the list twice, and O(2N) = O(N). </p> <p>This approach can be done even better using a default dictionary from collections. <code>default_dict</code> requires a default value to be specified, and all keys that are not currently in the dictionary are assumed to have that default value. For example <code>a = default_dict(0); print(a[1])</code> would print 0 because that is the default value specified for the list, and key 1 does not currently exist. This can be used to simplify the approach from above:</p> <pre><code>from collection import default_dict categories = Category.query.all() category_by_parent_id = default_dict([]) for category in categories: category_by_parent_id[category.parent_id].append(category) items = [{'root': root.name, 'subcategories': category_by_parent_id[root.id]} for root in category_by_parent_id[1]] </code></pre>
1
2016-09-29T04:30:30Z
[ "python" ]
Python reading and writing a csv file working with dates
39,761,272
<p>I would like to see in python, the code that reads a csv file containing years of historical dates with a value (example of each line: 2016-09-23,2173.290039) , this code would then write another csv file with every date and its associated value that occurs on a Friday. Thank you so much for your help.</p>
-1
2016-09-29T04:11:07Z
39,764,275
<p>The following script will do what you need:</p> <pre><code>from datetime import datetime import csv with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output: csv_input = csv.reader(f_input) csv_output = csv.writer(f_output) for row in csv_input: if datetime.strptime(row[0], "%Y-%m-%d").weekday() == 4: # if Friday csv_output.writerow(row) </code></pre> <p>If <code>input.csv</code> contains:</p> <pre><code>2016-09-23,2173.290039 2016-09-24,2174.290039 2016-09-25,2175.290039 2016-09-26,2176.290039 </code></pre> <p>It will create <code>output.csv</code> containing:</p> <pre><code>2016-09-23,2173.290039 </code></pre>
0
2016-09-29T07:42:05Z
[ "python", "csv", "calendar" ]
Where to write the save function in Django?
39,761,280
<p>Where to write my save function in django whether in models.py in a class model or in forms.py in form ?</p> <p>For example : models.py </p> <pre><code>class Customer(models.Model): name = models.CharField(max_length=200) created_by = models.ForeignKey(User) def save(): ........ some code to override it....... </code></pre> <p>forms.py</p> <pre><code>class Addcustomer(forms.ModelForm): class Meta: model = Customer fields = ('name',) def save(): ........code to override it.... </code></pre> <p>where shall i override my save function </p>
-1
2016-09-29T04:12:18Z
39,761,391
<p>It really depends on what you are trying to achieve. Default realization of <code>ModelForm</code>'s save calls <code>Model</code>'s save. But it is usually better to override it on <code>form</code> because it also runs validation. So if you are already using form I would suggest overriding <code>ModelForm.save</code>. And by overriding I mean extending using <code>super</code></p> <p>Here is default realization of <code>ModelForm.save</code></p> <pre><code>def save(self, commit=True): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: # there validation is done raise ValueError( "The %s could not be %s because the data didn't validate." % ( self.instance._meta.object_name, 'created' if self.instance._state.adding else 'changed', ) ) if commit: # If committing, save the instance and the m2m data immediately. self.instance.save() self._save_m2m() else: # If not committing, add a method to the form to allow deferred # saving of m2m data. self.save_m2m = self._save_m2m return self.instance save.alters_data = True </code></pre>
0
2016-09-29T04:25:25Z
[ "python", "django", "django-models", "django-forms" ]
Transpose the data in a column every nth rows in PANDAS
39,761,366
<p>For a research project, I need to process every individual's information from the website into an excel file. I have copied and pasted everything I need from the website onto a single column in an excel file, and I loaded that file using PANDAS. However, I need to present each individual's information horizontally instead of vertically like it is now. For example, this is what I have right now. I only have one column of unorganized data.</p> <pre><code>df= pd.read_csv("ior work.csv", encoding = "ISO-8859-1") </code></pre> <p>Data:</p> <pre><code>0 Andrew 1 School of Music 2 Music: Sound of the wind 3 Dr. Seuss 4 Dr.Sass 5 Michelle 6 School of Theatrics 7 Music: Voice 8 Dr. A 9 Dr. B </code></pre> <p>I want transpose every 5 lines to organize the data into this organizational format; the labels below are labels of the columns. </p> <pre><code>Name School Music Mentor1 Mentor2 </code></pre> <p>What is the most efficient way to do this? </p>
2
2016-09-29T04:22:56Z
39,762,293
<p>If no data are missing, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow"><code>numpy.reshape</code></a>:</p> <pre><code>print (np.reshape(df.values,(2,5))) [['Andrew' 'School of Music' 'Music: Sound of the wind' 'Dr. Seuss' 'Dr.Sass'] ['Michelle' 'School of Theatrics' 'Music: Voice' 'Dr. A' 'Dr. B']] print (pd.DataFrame(np.reshape(df.values,(2,5)), columns=['Name','School','Music','Mentor1','Mentor2'])) Name School Music Mentor1 Mentor2 0 Andrew School of Music Music: Sound of the wind Dr. Seuss Dr.Sass 1 Michelle School of Theatrics Music: Voice Dr. A Dr. B </code></pre> <p>More general solution with generating <code>length</code> of new <code>array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html" rel="nofollow"><code>shape</code></a> divide by number of columns:</p> <pre><code>print (pd.DataFrame(np.reshape(df.values,(df.shape[0] / 5,5)), columns=['Name','School','Music','Mentor1','Mentor2'])) Name School Music Mentor1 Mentor2 0 Andrew School of Music Music: Sound of the wind Dr. Seuss Dr.Sass 1 Michelle School of Theatrics Music: Voice Dr. A Dr. B </code></pre> <p>Thank you <a href="http://stackoverflow.com/questions/39761366/transpose-the-data-in-a-column-every-nth-rows-in-pandas/39762293?noredirect=1#comment66820514_39762293">piRSquared</a> for another solution:</p> <pre><code>print (pd.DataFrame(df.values.reshape(-1, 5), columns=['Name','School','Music','Mentor1','Mentor2'])) </code></pre>
1
2016-09-29T05:45:32Z
[ "python", "pandas", "dataframe", "reshape", "transpose" ]
Why is pip install pyopenssl==0.13 failing?
39,761,380
<p>I'm trying to install PyOpenSSL 0.13 on my Macbook Pro (OSX version 10.11, El-Capitan). But it keeps failing. These are the steps I took</p> <ol> <li>Download and install Command Line Tools (OSX 10.11) for Xcode 7.3.1 from <a href="https://developer.apple.com/download/more/" rel="nofollow">here</a></li> <li><code>$ virtualenv my-new-virtualenv</code></li> <li><code>$ source my-new-virtualenv/bin/activate</code></li> <li><code>$ pip install pyopenssl==0.13</code></li> </ol> <p>When I do step #4, I get the following error:</p> <pre><code>OpenSSL/crypto/x509.h:17:10: fatal error: 'openssl/ssl.h' file not found #include &lt;openssl/ssl.h&gt; ^ 1 error generated. error: command 'cc' failed with exit status 1 ---------------------------------------- Failed building wheel for pyopenssl </code></pre> <p><a href="https://gist.github.com/saqib-zmi/ce8894cd8c40599bc886608dbbf1c9ce" rel="nofollow"><strong>Here</strong></a> is the entire trace showing that error.</p> <p>Why am I getting this error and how can I fix it??</p>
0
2016-09-29T04:24:06Z
39,761,925
<p>It appears you are missing the OpenSSL development headers, as mentioned by <a href="http://stackoverflow.com/users/3929826/klaus-d">@Klaus D.</a> This most likely happened because due to upgrading to El Capitan, these development headers were broken. It can usually be fixed by reinstalling your command line tools. If you have Homebrew, run this code: <code>brew install openssl</code> <p> Also, just out of curiosity, is there a particular reason why you want to use version 0.13? When I did <code>$ pip install pyopenssl==0.14</code> I got no errors. See the bit on pyOpenSSL's documentation: <p><a href="http://i.stack.imgur.com/3uOYP.png" rel="nofollow"><img src="http://i.stack.imgur.com/3uOYP.png" alt="enter image description here"></a></p>
1
2016-09-29T05:16:16Z
[ "python", "osx", "pip", "pyopenssl", "libcrypto" ]
Yielding from a recursive function
39,761,413
<p>So let us say I have a few nodes. Each node has a list of nodes it can go to. This list of nodes can include itself. What I need to do is build all possible paths a node can take that are of n-length.</p> <p>For example: Let's assume a few things. </p> <ul> <li>I have node A and node B</li> <li>I need all possible paths that are three long (No shorter)</li> <li>Node A can go to itself and node B</li> <li>Node B can go to itself and node A</li> </ul> <p>Assuming that then all paths I can build are: </p> <ol> <li>AAA </li> <li>AAB </li> <li>ABA </li> <li>ABB </li> <li>BAA </li> <li>BAB </li> <li>BBA </li> <li>BBB </li> </ol> <p>This is the code I have right now; it works, but in my actual case I need the paths to be eight long with quite a few nodes. This obviously leads to some performance problems. I hit a MemoryError running on a 32bit version of Python2.7. I haven't tried the 64bit version yet. The obvious problem at hand is my current implementation. I thought maybe using yield/generators would help some. Would it? If so how would I even implement using yields in my case?</p> <p>Also I'm not limited to Python 2 if Python 3 has some features that would achieve what I'm asking. Python 2 just happens to be what is on my best performing computer.</p> <pre><code>PARTS = 3 def dive(node, depth=0): combos = [] if depth &gt;= PARTS - 1: if node.key: return ((node.key,),) return () for next_ in node.next_nodes: for combo in dive(next_, depth=depth+1): if not node.key: continue combos.append((node.key,) + combo) return combos </code></pre>
0
2016-09-29T04:28:35Z
39,761,463
<p>you could convert your current solution to a generator the easiest way by changing the return calls to yields ... that may be enough ... it might not also.. there are some graphtraversal libraries out there as well that may solve this very nicely if your goal is simply to solve the problem</p> <pre><code>PARTS = 3 def dive(node, depth=0): combos = [] if depth &gt;= PARTS - 1: if node.key: #return ((node.key,),) yield ((node.key,),) #return () yield () for next_ in node.next_nodes: for combo in dive(next_, depth=depth+1): if not node.key: continue combos.append((node.key,) + combo) #return combos yield combos for result in dive(node): print result </code></pre>
0
2016-09-29T04:33:18Z
[ "python", "recursion" ]
Python Sending command
39,761,444
<p>I'm trying to send a End command to the end of this line of code. I've searched everywhere and not able to find a valuable answer..</p> <pre><code>if args.time: def stopwatch(seconds): start = time.time() time.clock() elapsed = 0 while elapsed &lt; seconds: elapsed = time.time() - start print "Sending for(900) Seconds: %f, seconds count: %02d" % (time.clock() , elapsed) time.sleep(1) stopwatch(5) </code></pre> <p>Wanting to send a <code>Control C</code> of some sort here to stop it without Exiting the program.</p>
0
2016-09-29T04:31:10Z
39,761,496
<p>You can use control-c.</p> <p>You just have to catch the <strong>KeyboardInterrupt</strong> Exception.</p> <pre><code>try: # your loop code here except KeyboardInterrupt: # do whatever you want when user presses ctrl+c </code></pre>
0
2016-09-29T04:35:41Z
[ "python" ]
Python Sending command
39,761,444
<p>I'm trying to send a End command to the end of this line of code. I've searched everywhere and not able to find a valuable answer..</p> <pre><code>if args.time: def stopwatch(seconds): start = time.time() time.clock() elapsed = 0 while elapsed &lt; seconds: elapsed = time.time() - start print "Sending for(900) Seconds: %f, seconds count: %02d" % (time.clock() , elapsed) time.sleep(1) stopwatch(5) </code></pre> <p>Wanting to send a <code>Control C</code> of some sort here to stop it without Exiting the program.</p>
0
2016-09-29T04:31:10Z
39,761,502
<p>You want to catch a <code>KeyboardInterrupt</code>:</p> <pre><code>if args.time: def stopwatch(seconds): start = time.time() time.clock() elapsed = 0 while elapsed &lt; seconds: try: elapsed = time.time() - start print "Sending for(900) Seconds: %f, seconds count: %02d" % (time.clock() , elapsed) time.sleep(1) except KeyboardInterrupt: break stopwatch(5) </code></pre>
1
2016-09-29T04:36:42Z
[ "python" ]
Comparing a dataframe on string lengths for different columns
39,761,488
<p>I am trying to get the string lengths for different columns. Seems quite straightforward with: </p> <pre><code>df['a'].str.len() </code></pre> <p>But I need to apply it to multiple columns. And then get the minimum on it. </p> <p>Something like: </p> <pre><code>df[['a','b','c']].str.len().min </code></pre> <p>I know the above doesn't work, but hopefully you get the idea. Column <code>a</code>, <code>b</code>, <code>c</code> all contain names and I want to retrieve the shortest name. </p> <p>Also because of huge data, I am avoiding creating other columns to save on size. </p>
2
2016-09-29T04:35:00Z
39,761,785
<p>I think you need list comprehension, because <code>string</code> function works only with <code>Series</code> (<code>column</code>):</p> <pre><code>print ([df[col].str.len().min() for col in ['a','b','c']]) </code></pre> <p>Another solution with <code>apply</code>:</p> <pre><code>print ([df[col].apply(len).min() for col in ['a','b','c']]) </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'a':['h','gg','yyy'], 'b':['st','dsws','sw'], 'c':['fffff','','rr'], 'd':[1,3,5]}) print (df) a b c d 0 h st fffff 1 1 gg dsws 3 2 yyy sw rr 5 print ([df[col].str.len().min() for col in ['a','b','c']]) [1, 2, 0] </code></pre> <p><strong>Timings</strong>:</p> <pre><code>#[3000 rows x 4 columns] df = pd.concat([df]*1000).reset_index(drop=True) In [17]: %timeit ([df[col].apply(len).min() for col in ['a','b','c']]) 100 loops, best of 3: 2.63 ms per loop In [18]: %timeit ([df[col].str.len().min() for col in ['a','b','c']]) The slowest run took 4.12 times longer than the fastest. This could mean that an intermediate result is being cached. 100 loops, best of 3: 2.88 ms per loop </code></pre> <p><strong>Conclusion</strong>:</p> <p><code>apply</code> is faster, but not works with <code>None</code>.</p> <pre><code>df = pd.DataFrame({'a':['h','gg','yyy'], 'b':[None,'dsws','sw'], 'c':['fffff','','rr'], 'd':[1,3,5]}) print (df) a b c d 0 h None fffff 1 1 gg dsws 3 2 yyy sw rr 5 print ([df[col].apply(len).min() for col in ['a','b','c']]) </code></pre> <blockquote> <p>TypeError: object of type 'NoneType' has no len()</p> </blockquote> <pre><code>print ([df[col].str.len().min() for col in ['a','b','c']]) [1, 2.0, 0] </code></pre> <p>EDIT by comment:</p> <pre><code>#fail with None print (df[['a','b','c']].applymap(len).min(axis=1)) 0 1 1 0 2 2 dtype: int64 </code></pre> <hr> <pre><code>#working with None print (df[['a','b','c']].apply(lambda x: x.str.len().min(), axis=1)) 0 1 1 0 2 2 dtype: int64 </code></pre>
3
2016-09-29T05:04:21Z
[ "python", "pandas", "dataframe", "min", "string-length" ]
How to run two loop simeltanously in one loop in python
39,761,495
<p>Is there any way available to put two loops in one? I have:</p> <pre><code>for getFeature in layerNameValueGetObj.getFeatures(): for setFeature in layerNameValueSetObj.getFeatures(): </code></pre> <p>I want to run <code>layerNameValueGetObj.getFeatures()</code> and <code>layerNameValueSetObj.getFeatures()</code> under one loop. How can I do this?</p> <p>I don't want to nest them, I want to get both loop columns at a time.</p>
0
2016-09-29T04:35:35Z
39,761,514
<p><code>itertools.product</code> exists for exactly this purpose</p> <pre><code>import itertools for getFeature, setFeature in itertools.product(layerNameValueGetObj.getFeatures(), layerNameValueSetObj.getFeatures()): # dostuff </code></pre>
2
2016-09-29T04:37:23Z
[ "python" ]
How to run two loop simeltanously in one loop in python
39,761,495
<p>Is there any way available to put two loops in one? I have:</p> <pre><code>for getFeature in layerNameValueGetObj.getFeatures(): for setFeature in layerNameValueSetObj.getFeatures(): </code></pre> <p>I want to run <code>layerNameValueGetObj.getFeatures()</code> and <code>layerNameValueSetObj.getFeatures()</code> under one loop. How can I do this?</p> <p>I don't want to nest them, I want to get both loop columns at a time.</p>
0
2016-09-29T04:35:35Z
39,761,594
<p>You can use <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow">zip</a></p> <pre><code>for a, b in zip(list_a, list_b): print a, b </code></pre>
2
2016-09-29T04:45:54Z
[ "python" ]
How to run two loop simeltanously in one loop in python
39,761,495
<p>Is there any way available to put two loops in one? I have:</p> <pre><code>for getFeature in layerNameValueGetObj.getFeatures(): for setFeature in layerNameValueSetObj.getFeatures(): </code></pre> <p>I want to run <code>layerNameValueGetObj.getFeatures()</code> and <code>layerNameValueSetObj.getFeatures()</code> under one loop. How can I do this?</p> <p>I don't want to nest them, I want to get both loop columns at a time.</p>
0
2016-09-29T04:35:35Z
39,761,652
<p><code>zip_longest</code> will iterate until all lists are consumed. For <code>zip</code> the results are truncated to the shortest iterator.</p> <pre><code>from itertools import zip_longest for get_feature, set_feature in zip_longest(layerNameValueGetObj.getFeatures(), layerNameValueSetObj.getFeatures()): print(get_feature, set_feature) </code></pre> <p>Here's an example of both <code>zip</code> and <code>zip_longest</code> output:</p> <p>DummyObject Setup code:</p> <pre><code>class DummyObject: def __init__(self, reversed=False, length=10): self.reversed = reversed self.length = length def getFeatures(self): if self.reversed: g = reversed(range(self.length)) else: g = range(self.length) return g layerNameValueGetObj = DummyObject(False, length=10) layerNameValueSetObj = DummyObject(True, length=15) </code></pre> <p>Run with <code>zip_longest</code>:</p> <pre><code>from itertools import zip_longest for get_feature, set_feature in zip_longest(layerNameValueGetObj.getFeatures(), layerNameValueSetObj.getFeatures()): print(get_feature, set_feature) </code></pre> <p>zip_longest result:</p> <pre><code>0 14 1 13 2 12 3 11 4 10 5 9 6 8 7 7 8 6 9 5 None 4 None 3 None 2 None 1 None 0 </code></pre> <p>Run with <code>zip</code>:</p> <pre><code>for get_feature, set_feature in zip(layerNameValueGetObj.getFeatures(), layerNameValueSetObj.getFeatures()): print(get_feature, set_feature) </code></pre> <p>zip result:</p> <pre><code>0 14 1 13 2 12 3 11 4 10 5 9 6 8 7 7 8 6 9 5 </code></pre> <p>So in this case where layerNameValueGetObj has 10 features and layerNameValueSetObj has 15 features, with <code>zip</code> only a total of 10 features will be processed with the remaining 5 layerNameValueSetObj features truncated.</p> <p>With <code>zip_longest</code>, the shorter iterator will return <code>None</code> where no elements exist. (as seen above)</p>
3
2016-09-29T04:51:01Z
[ "python" ]
flask with many buttons and database update
39,761,505
<p>I am trying to make a web app like a mini-tweets. The posts are pulled out from a database and I want to have an 'up vote' button for each post, like the following picture. </p> <p><a href="http://i.stack.imgur.com/kJySO.png" rel="nofollow"><img src="http://i.stack.imgur.com/kJySO.png" alt="posts"></a></p> <p>Each post has an <code>id</code>, <code>author</code>, <code>body</code>, and <code>likes</code> property. When an up vote is clicked, the <code>likes</code> property needs to be updated.</p> <p>My question is how to determine which button is clicked. What would be a good strategy in this case for the <code>route()</code> function and the html template?</p> <p>I was thinking of adding a name to each button and put <code>post.id</code> in the name, then check if <code>request</code> has it. But the number of posts are not known before hand, how should I write the <code>request</code> check in <code>route()</code> function?</p> <p>My current template is as follows</p> <pre><code>&lt;table class="table table-striped"&gt; {% for post in posts %} &lt;tr&gt; &lt;td&gt; {{ post.id }} &lt;/td&gt; &lt;td&gt; &lt;img src="{{ post.author.avatar(50) }}"&gt; &lt;/td&gt; &lt;td&gt; &lt;b&gt;{{ post.body }}&lt;/b&gt; &lt;/td&gt; &lt;td&gt; &lt;button type="button" name='{{'up.'+ post.id|string}}' class="btn btn-default"&gt; &lt;span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"&gt;&lt;/span&gt; &lt;/button&gt; {{ post.likes}} &lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>and the current <code>route()</code> is like this </p> <pre><code>@bbs.route('/', methods=['GET', 'POST']) def index(): posts = Post.query.all() return render_template('bbs/index.html', posts=posts) </code></pre>
1
2016-09-29T04:36:57Z
39,761,725
<p>A clean way to do that would be to add a data attribute, in your <code>button</code> tag and do one ajax request per upvote / downvote.</p> <p><a href="https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes" rel="nofollow">https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes</a></p> <p>In your case, it would be called <code>data-id</code>.</p> <p>Then in your javascript, when the button is clicked, get this data attribute value, and craft your url as such :</p> <pre><code>/upvote/&lt;data-id&gt; </code></pre> <p>And call it using an ajax GET request (so the page doesn't refresh).</p> <p>Now on flask side get the id as such :</p> <pre><code>@app.route('/upvote/&lt;post_id&gt;') def upvote(post_id): print('%s upvoted' % post_id) # do your db update here and return a json encoded object </code></pre> <p>And on javascript side again, when you get your answer from flask, update your button accordingly.</p> <p>Assuming you put another class in your upvote button for instance : <code>upvote_button</code> and you use jQuery, your javascript could look like that :</p> <pre><code>&lt;script type='text/javascript'&gt; $('.upvote_button').click(function(ev){ var id = $(ev.currentTarget).attr('data-id'); $.get( "/upvote/" + id, function( data ) { // change your button here, and remove its upvote_button class alert(data); }); }); &lt;/script&gt; </code></pre>
1
2016-09-29T04:58:05Z
[ "python", "html", "flask", "html-form", "html-form-post" ]
Django render different templates for two submit buttons in a form
39,761,535
<p>I am a beginner at Django development, and I am trying to make a food diary application. After a user enters his email on <code>index.html</code>, another web page should be rendered according to whichever button he clicks.</p> <p>I can possibly add two templates, but I also want my app to work if a user manually types a valid URL such as <code>/apps/&lt;user_email&gt;/addDiaryEntry/</code>. I don't know what to add in <code>/apps/urls.py</code>. Also, can I somehow access a user object's Id so my routing URL become <code>/apps/&lt;user_id&gt;/addDiaryEntry/</code> instead?</p> <p><strong>/templates/apps/index.html</strong></p> <pre><code>&lt;form method="post" action="/apps/"&gt; {% csrf_token %} &lt;label for="email_add"&gt;Email address&lt;/label&gt; &lt;input id="email_add" type="text"&gt; &lt;button type="submit" name="add_entry"&gt;Add entry&lt;/button&gt; &lt;button type="submit" name="see_history"&gt;See history&lt;/button&gt; </code></pre> <p><strong>/apps/views.py</strong></p> <pre><code>def index(request): if request.POST: if 'add_entry' in request.POST: addDiaryEntry(request) elif 'see_history' in request.POST: seeHistory(request) return render(request, 'apps/index.html'); def addDiaryEntry(request): print ("Add entry") def seeHistory(request): print ("See history") </code></pre> <p><strong>/apps/urls.py</strong></p> <pre><code>urlpatterns = [ url(r'^$', views.index, name='index'), ] </code></pre> <p>Thank you for your help! Please feel free to share any best practices which I am not following.</p>
0
2016-09-29T04:39:34Z
39,761,784
<p>1) passing in an argument into a url, you can use regex groups to pass arguments. Here is an example using a kwarg:</p> <pre><code>url(r'^(?P&lt;user_email&gt;[^@]+@[^@]+\.[^@]+)/addDiaryEntry/$', views.add_diary, name='add-diary-entry'), </code></pre> <p>2) just render a different template depending on which button was pressed:</p> <pre><code>def index(request): if request.POST: if 'add_entry' in request.POST: addDiaryEntry(request) return render(request, 'apps/add_entry.html'); elif 'see_history' in request.POST: seeHistory(request) return render(request, 'apps/see_history.html'); </code></pre> <p>It's always tough starting out, make sure you put in the time to go over the docs, here are some places to look over regarding these topics: <a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#named-groups" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/http/urls/#named-groups</a> <a href="https://docs.djangoproject.com/en/1.10/topics/http/views/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/http/views/</a></p>
0
2016-09-29T05:04:12Z
[ "python", "django", "forms", "django-templates" ]
Extract first two lines of PDF with Python and pyPDF
39,761,609
<p>I'm using python 2.7 and pyPDF to get the title meta info from PDF files. Unfortunately not all of PDF have the meta info. What I want to do now is grab the first two line of text from a PDF. Using what I have now how can I modify the code to capture the first two lines with pyPDF?</p> <pre><code>from pyPdf import PdfFileWriter, PdfFileReader import os for fileName in os.listdir('.'): try: if fileName.lower()[-3:] != "pdf": continue input1 = PdfFileReader(file(fileName, "rb")) # print the title of document1.pdf print fileName, input1.getDocumentInfo().title except: print ",", </code></pre>
0
2016-09-29T04:46:58Z
39,761,680
<pre><code>from PyPDF2 import PdfFileWriter, PdfFileReader import os import StringIO fileName = "HMM.pdf" try: if fileName.lower()[-3:] == "pdf": input1 = PdfFileReader(file(fileName, "rb")) # print the title of document1.pdf #print fileName, input1.getDocumentInfo().title content = input1.getPage(0).extractText() buf = StringIO.StringIO(content) buf.readline() buf.readline() except: print ",", </code></pre> <p>My pwd contains this "HMM.pdf" file and this code is working on python 2.7 properly. </p>
1
2016-09-29T04:53:50Z
[ "python", "python-2.7", "pypdf" ]
Pandas Dataframe comparison with range/stdev
39,761,648
<p>I have to dataframes A and B. Both have a 'datetime' column and another common column X. B is bigger as it has X at every minute while A only has X at intermittent times during a day. For each 'datetime' in A, I want to calculate the range (or stdev) of X during previous 30 minutes using B. So something like:</p> <p><code>For i,time in enumerate(A['time']): temp=B[(B['time'] &gt; time -timedelta(days=0, minutes=30)) and (B['time'] &lt;=time] range[i]=temp.max-temp.min</code></p> <p>Here temp is intended to snapshot all the data within 30 mins prior to A's timestamp in B. Is there a simple way, maybe one that doesn't require a loop, to do this? Note that sizes of A and B are different.</p> <p>Sample A: (only few outputs available along with inputs) <code> Date input output 2015-01-02 20:48:00-00:00 1120 343 2015-01-02 21:25:00-00:00 1345 365</code></p> <p>Sample B: ( all the inputs available but no outputs) <code> Date input 2014-11-02 00:32:00-00:00 1542 2014-11-02 00:33:00-00:00 1285</code></p> <p>Sample Output: <code> Date input output Range_input_previous 30 min 2015-01-02 20:48:00-00:00 1120 343 ??(use table B) 2015-01-02 21:25:00-00:00 1345 365 ??(use table B)</code></p>
-1
2016-09-29T04:50:41Z
39,762,636
<p>This works for me but uses a loop:</p> <p><code>rangex=np.zeros(A.shape[0])<br> for i,Date in enumerate(A['Date']): temp=B[(B['Date'] &gt; Date-datetime.timedelta(days=0, minutes=30)) &amp; (B['Date'] &lt;=Date)] rangex[i]=temp['input'].max()-temp['input'].min()<br> A['range']=pd.Series(rangex, index=A.index)</code></p>
0
2016-09-29T06:10:37Z
[ "python", "pandas", "dataframe", "timestamp", "range" ]
How to run progress bar widget from dask.distributed in a separate thread?
39,761,660
<p>There is an example <a href="http://distributed.readthedocs.io/en/latest/queues.html" rel="nofollow">here</a>, showing insertion of data for processing in a separate thread. I'm interested in reverse, when data are inserted manually and interactively, and background thread submits them to cluster for calculation. </p>
1
2016-09-29T04:51:57Z
39,807,398
<p>This is already the case. When you call </p> <pre><code>client.submit(function, *args, **kwargs) </code></pre> <p>This serializes stuff immediately in the local thread (blocking), but then adds a callback to the Tornado IOLoop (running in a separate thread) to manage the actual communication to the scheduler. This all happens asynchronously to the main thread.</p>
0
2016-10-01T13:48:40Z
[ "python", "distributed", "jupyter-notebook", "dask" ]
AWS Boto3 BASE64 encoding error thrown when invoking client.request_spot_instances method
39,761,666
<p>I am trying to submit a request for an EC2 SPOT instance using boto3 (Environment Python 3.5,Windows 7). I need to pass the <strong>UserData</strong> parameter for running initial scripts.</p> <p>The error I get is File "C:\Users...\Python\Python35\lib\site-packages\botocore\client.py", line 222, in _make_api_call raise ClientError(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (InvalidParameterValue) when calling the <strong><em>RequestSpotInstances operation: Invalid BASE64 encoding of user data Code</em></strong></p> <p>I am following this documentation <a href="https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.request_spot_instances" rel="nofollow">https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.request_spot_instances</a></p> <p><strong>If I take the UserData parameter out – everything works well.</strong> </p> <p>I have tried different ways to pass the parameter but I end up with the same.similar errors.</p> <p><strong>Boto 3 Script</strong></p> <pre><code> client = session.client('ec2') myparam = str(base64.b64encode(bytes('yum install -y php', 'utf-8'))) response = client.request_spot_instances( SpotPrice='0.4', InstanceCount=1, Type='one-time', LaunchSpecification={ 'ImageId': 'ami-xxxxxx', 'KeyName': 'xxxxx', 'InstanceType': 't1.micro', 'UserData': myparam, 'Monitoring': { 'Enabled': True } }) </code></pre>
0
2016-09-29T04:52:33Z
39,762,101
<p>I think you shouldn't convert your base64 string to <code>str</code>. Are you using Python 3?</p> <p>Replace:</p> <pre><code>myparam = str(base64.b64encode(bytes('yum install -y php', 'utf-8'))) </code></pre> <p>By:</p> <pre><code>myparam = base64.b64encode(b'yum install -y php') </code></pre>
1
2016-09-29T05:30:11Z
[ "python", "amazon-web-services", "amazon-ec2", "base64", "boto3" ]
Python 2D Dynamic List Error
39,761,675
<p>I am new to Python.</p> <pre><code> for row in reader: if (int(row[0]) &lt;= nextWeek): y[i].append(row[1]) if (int(row[0]) &gt; nextWeek): i = i + 1 y[i].append(row[1]) </code></pre> <p>These are the parts of the code , here I need to acheive this kind of things in Python , What is the <strong>correct way of declaring y</strong> ?</p> <p>Here I used <strong>y = [ [ ] ]</strong> , But I need the correct type for <strong>y</strong> something like basically 2D Dynamic List Declaration / Initialization example ?</p>
0
2016-09-29T04:53:28Z
39,763,821
<p>I think what you are searching for is a defaultdict. Lets say you've got:</p> <pre><code>from collections import defaultdict y = defaultdict(list) (...) for row in reader: if (int(row[0]) &lt;= nextWeek): y[i].append(row[1]) if (int(row[0]) &gt; nextWeek): i = i + 1 y[i].append(row[1]) </code></pre> <p>In this case, the defaultdict will store the "i" (index) as a key, where the value will be a list by default. (and as such it is easy to extend the list, when not-knowing how many of them should exist). </p>
0
2016-09-29T07:17:52Z
[ "python", "matplotlib" ]
General Python Unicode / ASCII Casting Issue Causing Trouble in Pyorient
39,761,684
<p>UPDATE: I opened an issue on github based on a Ivan Mainetti's suggestion. If you want to weigh in there, it is :<a href="https://github.com/orientechnologies/orientdb/issues/6757" rel="nofollow">https://github.com/orientechnologies/orientdb/issues/6757</a></p> <p>I am working on a database based on OrienDB and using a python interface for it. I've had pretty good luck with it, but I've run into a problem that seems to be the driver's (pyorient) wonkiness when dealing with certain unicode characters.</p> <p>The data structure I'm uploading to the database looks like this:</p> <pre><code>new_Node = {'@Nodes': { "Abs_Address":Ono.absolute_address, 'Content':Ono.content, 'Heading':Ono.heading, 'Type':Ono.type, 'Value':Ono.value } } </code></pre> <p>I have created literally hundreds of records flawlessly on OrientDB / pyorient. I don't think the problem is necessarily a pyorient specific question, however, as I think the reason it is failing on a particular record is because the Ono.absolute_address element has a unicode character that pyorient is somehow choking on. </p> <p>The record I want to create has an Abs_address of /u/c/2/a1–2, but the node I get when I pass the value to the my data structure above is this:</p> <pre><code>{'@Nodes': {'Content': '', 'Abs_Address': u'/u/c/2/a1\u20132', 'Type': 'section', 'Heading': ' Transferred', 'Value': u'1\u20132'}} </code></pre> <p>I think that somehow my problem is python is mixing unicode and ascii strings / chars? I'm a bit new to python and not declaring types, so I'm hoping this isn't an issue with pyorient perse given that the new_Node object doesn't output the properly formatted string...? Or is this an instance of pyorient not liking unicode? I'm tearing my hair out on this one. Any help is appreciated. </p> <p>In case the error is coming from pyorient and not some kind of text encoding, here's the pyorient-related info. I am creating the record using this code:</p> <pre><code>rec_position = self.pyo_client.record_create(14, new_Node) </code></pre> <p>And this is the error I'm getting:</p> <pre><code>com.orientechnologies.orient.core.storage.ORecordDuplicatedException - Cannot index record Nodes{Content:,Abs_Address:null,Type:section,Heading: Transferred,Value:null}: found duplicated key 'null' in index 'Nodes.Abs_Address' previously assigned to the record #14:558 </code></pre> <p>The error is odd as it suggests that the backend database is getting a null object for the address. Apparently it did create an entry for this "address," but it's not what I want it to do. I don't know why address strings with unicode are coming up null in the database... I can create it through orientDB studio using the exact string I fed into the new_Node data structure... but I can't use python to do the same thing. </p> <p>Someone help?</p> <p>EDIT:</p> <p>Thanks to Laurent, I've narrowed the problem down to something to do with unicode objects and pyorient. Whenever a the variable I am passing is type unicode, the pyorient adapter sends a null value to the OrientDB database. I determined the value that is causing the problem is an ndash symbol, and Laurent helped me replace it with a minus sign using this code</p> <pre><code>.replace(u"\u2013",u"-") </code></pre> <p>When I do that, however, pyorient gets unicode objects which it then passes as null values... This is not good. I can fix this short term by recasting the string using str(...) and this appears to solve my immediate problem:</p> <pre><code>str(Ono.absolute_address.replace(u"\u2013",u"-")) </code></pre> <p>. Problem is, I know I will have symbols and other unusual characters in my DB data. I know the database supports the unicode strings because I can add them manually or use SQL syntax to do what I cannot do via pyorient and python... I am assuming this is a dicey casting issue somewhere, but I'm not really sure where. This seems very similar to this problem: <a href="http://stackoverflow.duapp.com/questions/34757352/how-do-i-create-a-linked-record-in-orientdb-using-pyorient-library" rel="nofollow">http://stackoverflow.duapp.com/questions/34757352/how-do-i-create-a-linked-record-in-orientdb-using-pyorient-library</a></p> <p>Any pyorient people out there? Python gods? Lucky s0bs? =)</p>
0
2016-09-29T04:54:05Z
39,990,610
<p>I have tried your example on Python 3 with the development branch of pyorient with the latest version of OrientDB 2.2.11. If I pass the values without escaping them, your example seems to work for me and I get the right values back.</p> <p>So this test works:</p> <pre><code>def test_test1(self): new_Node = {'@Nodes': {'Content': '', 'Abs_Address': '/u/c/2/a1–2', 'Type': 'section', 'Heading': ' Transferred', 'Value': u'1\u20132'} } self.client.record_create(14, new_Node) result = self.client.query('SELECT * FROM V where Abs_Address="/u/c/2/a1–2"') assert result[0].Abs_Address == '/u/c/2/a1–2' </code></pre> <p>I think you may be saving the unicode value as an escaped value and that's where things get tricky.</p> <p>I don't trust replacing values myself so I usually escape the unicode values I send to orientdb with the following code:</p> <pre><code>import json def _escape(string): return json.dumps(string)[1:-1] </code></pre> <p>The following test would fail because the escaped value won't match the escaped value in the DB so no record will be returned:</p> <pre><code>def test_test2(self): new_Node = {'@Nodes': {'Content': '', 'Abs_Address': _escape('/u/c/2/a1–2'), 'Type': 'section', 'Heading': ' Transferred', 'Value': u'1\u20132'} } self.client.record_create(14, new_Node) result = self.client.query('SELECT * FROM V where Abs_Address="%s"' % _escape('/u/c/2/a1–2')) assert result[0].Abs_Address.encode('UTF-8').decode('unicode_escape') == '/u/c/2/a1–2' </code></pre> <p>In order to fix this, you have to escape the value twice:</p> <pre><code>def test_test3(self): new_Node = {'@Nodes': {'Content': '', 'Abs_Address': _escape('/u/c/2/a1–2'), 'Type': 'section', 'Heading': ' Transferred', 'Value': u'1\u20132'} } self.client.record_create(14, new_Node) result = self.client.query('SELECT * FROM V where Abs_Address="%s"' % _escape(_escape('/u/c/2/a1–2'))) assert result[0].Abs_Address.encode('UTF-8').decode('unicode_escape') == '/u/c/2/a1–2' </code></pre> <p>This test will succeed because you will now be asking for the escaped value in the DB.</p>
1
2016-10-12T04:37:03Z
[ "python", "string", "unicode", "orientdb", "pyorient" ]
Create a vector given N input of names and ages python
39,761,767
<p>I need to create a program that takes as inputs multiple entries of names and ages. Then I want it to return the names and ages of those entries that have higher age values than the average age of all entries. For example:</p> <pre><code>input( "Enter a name: ") Albert input( "Enter an age: ") 16 input( "Enter a name: ") Robert input( "Enter an age: ") 18 input( "Enter a name: ") Rose input( "Enter an age: ") 20 The average is = 18 Rose at 20 is higher than the average. </code></pre> <p>How can I do this?</p>
0
2016-09-29T05:02:14Z
39,767,251
<pre><code>answers = {} # Use a flag to indicate that the questionnaire is active. questions_active = True while questions_active: # Ask for the person's name and response. name = raw_input("\nEnter a name: ") response = raw_input("Enter an age: ") # Store the response in the dictionary: answers[name] = int(response) # Check if anyone else is going to take the questionnaire. repeat = raw_input("Would you like to let another person respond? (yes/ no) ") if repeat == 'no': questions_active = False average_age = sum(answers.values())/float(len(answers)) print("The average is " + str(average_age)) # Questionnaire is complete. Show the results. for name, response in answers.items(): if response &gt; average_age: print(name.title() + " at " + str(response) + " is higher than the average.") </code></pre> <p>This answer is based on a similar example from the book "Python Crash Course: A Hands-On, Project-Based Introduction to Programming" <a href="https://www.nostarch.com/pythoncrashcourse" rel="nofollow">https://www.nostarch.com/pythoncrashcourse</a></p>
1
2016-09-29T10:02:18Z
[ "python", "dictionary", "vector" ]
Insides of __getattr__(self, __getitem__) in python 2
39,761,778
<p>In python2, this old-style class:</p> <pre><code>class C: x = 'foo' def __getattr__(self, name): print name print type(name) return getattr(self.x, name) &gt; X = C() &gt; X[1] __getitem__ &lt;type 'str'&gt; 'o' </code></pre> <p>Question is, what is going on in the bowels of this? More specifically, if <code>name</code> is just a string, how is the index <code>1</code> stored so that <code>getattr</code> knows that it has to call <code>__getitem__(1)</code> to retrieve the character <code>o</code>?</p>
1
2016-09-29T05:03:20Z
39,761,974
<p>To cut right to it, this is what is happening step by step.</p> <p>When you call <code>X[1]</code>, it is going to attempt to look up an attribute called <code>__getitem__</code> in your class. As you do not have any attributes (function or variable) with that name, so it will fallback to call your <code>__getattr__</code> method with the name of the attribute (<code>__getitem__</code>) it is requesting. This name is always a string.</p> <p>When you do a <code>"return getattr(self.x, name)"</code> what you are actually doing is returning the <code>__getitem__</code> method of "foo" ie: <code>"foo".__getitem__</code> which then is called with the argument 1: <code>"foo".__getitem__(1)</code> which is the same as <code>"foo"[1]</code> which returns you the first "o".</p>
2
2016-09-29T05:20:00Z
[ "python", "python-2.7" ]
Python: How to assign function name dynamically in Class
39,761,908
<p>I have an question about how to assign function name dynamically in Class.</p> <h2>For example:</h2> <pre><code>If a class wants to be used for "for...in" loop, similar to a list or a tuple, you must implement an __iter__ () method python2.x will use __iter__() and next(), python3.x need to use __iter__() and __next__() </code></pre> <h2>Code:</h2> <p>The sample is get fibonacci numbers within 10</p> <pre><code>class Fib(object): def __init__(self): self.a, self.b = 0, 1 def __iter__(self): return self if sys.version_info[0] == 2: iter_n = 'next' #if python version is 2.x else: iter_n = '__next__' #if python version is 3.x print('iter_n value is ', iter_n) #for py2 I want to replace "iter_n" to "next" dynamically #for py3 I want to replace "iter_n" to "__next__" dynamically def iter_n(self): self.a, self.b = self.b, self.a + self.b if self.a &gt; 10: raise StopIteration(); return self.a </code></pre> <h2>Test:</h2> <pre><code>for i in Fib(): print(i) </code></pre> <h2>Expected Result should be:</h2> <pre><code>('iter_n value is ', 'next') 1 1 2 3 5 8 </code></pre> <h2>Actual Result:</h2> <pre><code>('iter_n value is ', 'next') Traceback (most recent call last): ...... TypeError: iter() returned non-iterator of type 'Fib' </code></pre> <p>Code will be able to get the right results</p> <ul> <li>for python 2, if I replace <code>def iter_n(self)</code> to <code>def next(self)</code></li> <li>for python 3, if I replace <code>def iter_n(self)</code> to <code>def __next__(self)</code></li> </ul> <h2>Question:</h2> <p>How should I put <code>next</code> or <code>__next__</code> to <code>iter_n</code> dynamically?</p>
2
2016-09-29T05:14:37Z
39,762,118
<p>I don't think there's a need to create this method dynamically. Just implement both; clearer and easier. And your code will be Python 2/3 compatible without needing an if-statement.</p> <pre><code>class Fib(object): def __init__(self): self.a, self.b = 0, 1 def __iter__(self): return self def iter_n(self): self.a, self.b = self.b, self.a + self.b if self.a &gt; 10: raise StopIteration(); return self.a def next(self): return self.iter_n() def __next__(self): return self.iter_n() if __name__ == '__main__': for i in Fib(): print(i) </code></pre>
5
2016-09-29T05:31:27Z
[ "python" ]
Python: How to assign function name dynamically in Class
39,761,908
<p>I have an question about how to assign function name dynamically in Class.</p> <h2>For example:</h2> <pre><code>If a class wants to be used for "for...in" loop, similar to a list or a tuple, you must implement an __iter__ () method python2.x will use __iter__() and next(), python3.x need to use __iter__() and __next__() </code></pre> <h2>Code:</h2> <p>The sample is get fibonacci numbers within 10</p> <pre><code>class Fib(object): def __init__(self): self.a, self.b = 0, 1 def __iter__(self): return self if sys.version_info[0] == 2: iter_n = 'next' #if python version is 2.x else: iter_n = '__next__' #if python version is 3.x print('iter_n value is ', iter_n) #for py2 I want to replace "iter_n" to "next" dynamically #for py3 I want to replace "iter_n" to "__next__" dynamically def iter_n(self): self.a, self.b = self.b, self.a + self.b if self.a &gt; 10: raise StopIteration(); return self.a </code></pre> <h2>Test:</h2> <pre><code>for i in Fib(): print(i) </code></pre> <h2>Expected Result should be:</h2> <pre><code>('iter_n value is ', 'next') 1 1 2 3 5 8 </code></pre> <h2>Actual Result:</h2> <pre><code>('iter_n value is ', 'next') Traceback (most recent call last): ...... TypeError: iter() returned non-iterator of type 'Fib' </code></pre> <p>Code will be able to get the right results</p> <ul> <li>for python 2, if I replace <code>def iter_n(self)</code> to <code>def next(self)</code></li> <li>for python 3, if I replace <code>def iter_n(self)</code> to <code>def __next__(self)</code></li> </ul> <h2>Question:</h2> <p>How should I put <code>next</code> or <code>__next__</code> to <code>iter_n</code> dynamically?</p>
2
2016-09-29T05:14:37Z
39,762,151
<p>In python there is the way to call a function ,method ,get any element by using getattr(from,'name of attribute to call').</p> <p>below is the sample example of this:</p> <pre><code>class A(): def s(self): print "s fun" def d(self): print "a fun" def run(self): print "in run" def main(): print "in main" classA = A() func_list = ['s','d','run'] for i in func_list: func = getattr(classA,i) func() main() </code></pre> <p>Try to use this to call function dynamically.</p>
-1
2016-09-29T05:34:12Z
[ "python" ]
Python: How to assign function name dynamically in Class
39,761,908
<p>I have an question about how to assign function name dynamically in Class.</p> <h2>For example:</h2> <pre><code>If a class wants to be used for "for...in" loop, similar to a list or a tuple, you must implement an __iter__ () method python2.x will use __iter__() and next(), python3.x need to use __iter__() and __next__() </code></pre> <h2>Code:</h2> <p>The sample is get fibonacci numbers within 10</p> <pre><code>class Fib(object): def __init__(self): self.a, self.b = 0, 1 def __iter__(self): return self if sys.version_info[0] == 2: iter_n = 'next' #if python version is 2.x else: iter_n = '__next__' #if python version is 3.x print('iter_n value is ', iter_n) #for py2 I want to replace "iter_n" to "next" dynamically #for py3 I want to replace "iter_n" to "__next__" dynamically def iter_n(self): self.a, self.b = self.b, self.a + self.b if self.a &gt; 10: raise StopIteration(); return self.a </code></pre> <h2>Test:</h2> <pre><code>for i in Fib(): print(i) </code></pre> <h2>Expected Result should be:</h2> <pre><code>('iter_n value is ', 'next') 1 1 2 3 5 8 </code></pre> <h2>Actual Result:</h2> <pre><code>('iter_n value is ', 'next') Traceback (most recent call last): ...... TypeError: iter() returned non-iterator of type 'Fib' </code></pre> <p>Code will be able to get the right results</p> <ul> <li>for python 2, if I replace <code>def iter_n(self)</code> to <code>def next(self)</code></li> <li>for python 3, if I replace <code>def iter_n(self)</code> to <code>def __next__(self)</code></li> </ul> <h2>Question:</h2> <p>How should I put <code>next</code> or <code>__next__</code> to <code>iter_n</code> dynamically?</p>
2
2016-09-29T05:14:37Z
39,762,299
<p>Agreed that just implementing both is probably best, but something like this seems to do what you intend:</p> <pre><code> def iter_n(self): self.a, self.b = self.b, self.a + self.b if self.a &gt; 10: raise StopIteration(); return self.a if sys.version_info[0] == 2: next = iter_n else: __next__ = iter_n del iter_n </code></pre> <p>The above removes the original <code>iter_n</code> once it is assigned to the appropriate attribute. Presumably if you're going through this effort you would want to do this cleanup, too.</p>
1
2016-09-29T05:45:45Z
[ "python" ]
Rearranging groupings in bar chart from pandas dataframe
39,761,916
<p>I want a grouped bar chart, but the default plot doesn't have the groupings the way I'd like, and I'm struggling to get them rearranged properly.</p> <p>The dataframe looks like this:</p> <pre> user year cat1 cat2 cat3 cat4 cat5 0 Brad 2014 309 186 119 702 73 1 Brad 2015 280 177 100 625 75 2 Brad 2016 306 148 127 671 74 3 Brian 2014 298 182 131 702 73 4 Brian 2015 295 125 117 607 76 5 Brian 2016 298 137 97 596 75 6 Chris 2014 309 171 111 654 72 7 Chris 2015 251 146 105 559 76 8 Chris 2016 231 130 105 526 75 etc </pre> <p>Elsewhere, the code produces two variables, user1 and user2. I want to produce a bar chart that compares the numbers for those two users over time in cat1, cat2, and cat3. So for example if user1 and user2 were Brian and Chris, I would want a chart that looks something like this:</p> <p><a href="http://i.stack.imgur.com/2s4c5.png" rel="nofollow"><img src="http://i.stack.imgur.com/2s4c5.png" alt="grouped bar chart"></a></p> <p>On an aesthetic note: I'd prefer the year labels be vertical text or a font size that fits on a single line, but it's really the dataframe pivot that's confusing me at the moment.</p>
1
2016-09-29T05:15:08Z
39,774,561
<p>Select the subset of users you want to plot against. Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> later to transform the <code>DF</code> to the required format to be plotted by transposing and unstacking it.</p> <pre><code>import matplotlib.pyplot as plt def select_user_plot(user_1, user_2, cats, frame, idx, col): frame = frame[(frame[idx[0]] == user_1)|(frame[idx[0]] == user_2)] frame_pivot = frame.pivot_table(index=idx, columns=col, values=cats).T.unstack() frame_pivot.plot.bar(legend=True, cmap=plt.get_cmap('RdYlGn'), figsize=(8,8), rot=0) </code></pre> <p>Finally,</p> <p>Choose the users and categories to be included in the bar plot.</p> <pre><code>user_1 = 'Brian' user_2 = 'Chris' cats = ['cat1', 'cat2', 'cat3'] select_user_plot(user_1, user_2, cats, frame=df, idx=['user'], col=['year']) </code></pre> <p><a href="http://i.stack.imgur.com/65s1G.png" rel="nofollow"><img src="http://i.stack.imgur.com/65s1G.png" alt="Image"></a></p> <p>Note: This gives close to the plot that the OP had posted.(Year appearing as Legends instead of the tick labels)</p>
1
2016-09-29T15:36:40Z
[ "python", "pandas", "matplotlib" ]
How to compare an array value with another explicit value in python
39,761,950
<p>I want to do something like this</p> <pre><code>while(x&lt;100 for x in someList): if someList has a value more than 100 the loop should end. </code></pre>
-1
2016-09-29T05:18:26Z
39,761,987
<p>This will also end the loop when value is greater than 100</p> <pre><code>for x in someList: if x &gt; 100: break </code></pre> <p>You can try this:</p> <pre><code>i=0 while ((i&lt;len(someList)) and (someList[i] &lt;= 100) ): '''Do something''' i+=1 </code></pre>
3
2016-09-29T05:21:08Z
[ "python", "loops", "compare" ]
How to compare an array value with another explicit value in python
39,761,950
<p>I want to do something like this</p> <pre><code>while(x&lt;100 for x in someList): if someList has a value more than 100 the loop should end. </code></pre>
-1
2016-09-29T05:18:26Z
39,762,247
<p>You <em>could</em> use <code>itertools.takewhile</code>:</p> <pre><code>for x in takewhile(lambda x: x &lt;= 100, someList): print(x) </code></pre> <p>But I think @sinsuren's <code>break</code> solution is best. I'd only use <code>takewhile</code> when I don't want a loop, for example in <code>sum(takewhile(lambda x: x &lt;= 100, someList))</code>.</p>
1
2016-09-29T05:41:40Z
[ "python", "loops", "compare" ]
How can I simplify my if condition in python?
39,761,962
<p>I would like to know if there's a simpler way to write the condition of the <code>if</code> statement. Something like <code>item1, item2 == "wood":</code>. I currently have this code:</p> <pre><code>item1 = input("item1: ") item2 = input("item2: ") if item1 == "wood" and item2 == "wood": print("You created a stick") </code></pre>
1
2016-09-29T05:19:00Z
39,761,999
<p>This isn't a huge savings but you could take out <code>"wood" and</code></p> <pre><code>item1 = input("item1: ") item2 = input("item2: ") if item1 == item2 == "wood": print("You created a stick") </code></pre>
5
2016-09-29T05:22:26Z
[ "python", "if-statement", "condition", "simplify" ]
How can I simplify my if condition in python?
39,761,962
<p>I would like to know if there's a simpler way to write the condition of the <code>if</code> statement. Something like <code>item1, item2 == "wood":</code>. I currently have this code:</p> <pre><code>item1 = input("item1: ") item2 = input("item2: ") if item1 == "wood" and item2 == "wood": print("You created a stick") </code></pre>
1
2016-09-29T05:19:00Z
39,762,060
<p>In this particular case, it's fine to leave it as is. But if you have three or more elements, try using a list:</p> <pre><code>items = [] # Declare a list # Add items to list for x in range(1, 4): items.append(input("item" + str(x) + ": ")) if all(item == "wood" for item in items): print("You created a stick") </code></pre>
1
2016-09-29T05:26:14Z
[ "python", "if-statement", "condition", "simplify" ]
How can I simplify my if condition in python?
39,761,962
<p>I would like to know if there's a simpler way to write the condition of the <code>if</code> statement. Something like <code>item1, item2 == "wood":</code>. I currently have this code:</p> <pre><code>item1 = input("item1: ") item2 = input("item2: ") if item1 == "wood" and item2 == "wood": print("You created a stick") </code></pre>
1
2016-09-29T05:19:00Z
39,762,219
<p>You have two ways. you can use "==" for two variables.</p> <pre><code>item1 = input("item1: ") item2 = input("item2: ") if item1 == item2 == "wood": print("You created a stick") </code></pre> <p>And also you can do using a for loop. But for that you have to use a list first.So this would help if you are using huge number of inputs.</p> <pre><code>list1=[] item1 = (input("item1: ")) item2 = (input("item1: ")) list1.append(item1) list1.append(item2) if all(item=="wood" for item in list1): print("You created a stick") </code></pre>
0
2016-09-29T05:40:07Z
[ "python", "if-statement", "condition", "simplify" ]
plyer accelerometer not implemented error on Android phone
39,761,977
<p>I installed Qpython (Python 2.7) and plyer on may android phone (Samsung Galaxy J5, with accelerometer - without gyroscope). I want to read the accelerometer values. Simply I enter three lines of code on the console:</p> <pre><code>from plyer.facades import Acceleromter acc = Accelerometer() print acc.acceleration </code></pre> <p>and I get NotImplementedError. What am I missing?</p> <p>EDIT: additional findings:</p> <p>An alternative way to call the accelerometer is like the following. Rather than going through facades, import accelerometer (with small a) directly from plyer, so:</p> <pre><code>from plyer import accelerometer </code></pre> <p>this command looks like working fine with no errors. But if I question what accelerometer is like just typing</p> <pre><code>accelerometer </code></pre> <p>on the python console the I get a lot of jnius errors, ending with:</p> <pre><code>File "jnius_export_class.pxi", line 44, in jnius.jnius.MetaJavaClass.__new__(jnius/jnius.c:13255) SystemError: NULL result without error in PyObject_call </code></pre> <p>But it gives a hex address for the module, so the sw is there. But most probably can not access the hw.</p> <p>I have checked the CPU-Z application is closed. But could it be possible that somehow CPU-z blocks the access by installation setup, even if it is closed? When I open it, I can see accelerometer is working.</p>
0
2016-09-29T05:20:27Z
39,762,284
<p>According to the <a href="https://github.com/kivy/plyer/blob/master/plyer/facades/accelerometer.py" rel="nofollow">documentation</a>, it appears you must first enable the accelerometer. Without doing so, it will throw a <code>NotImplementedError</code> exception as provided in this code:</p> <pre><code>def enable(self): '''Activate the accelerometer sensor. Throws an error if the hardware is not available or not implemented on. ''' self._enable() </code></pre> <p>Further down the code, you will see this:</p> <pre><code>def _enable(self): raise NotImplementedError() </code></pre> <p>I might not have explained myself fully but upon inspecting this code, you should be able to determine what is causing this error. Primarily, it could be that the app (QPython) or hardware just does not support this feature.</p>
0
2016-09-29T05:44:42Z
[ "android", "python" ]
How to read binary files in Python using NumPy?
39,762,019
<p>I know how to read binary files in Python using NumPy's <code>np.fromfile()</code> function. The issue I'm faced with is that when I do so, the array has exceedingly large numbers of the order of 10^100 or so, with random <code>nan</code> and <code>inf</code> values. </p> <p>I need to apply machine learning algorithms to this dataset and I cannot work with this data. I cannot normalise the dataset because of the <code>nan</code> values.</p> <p>I've tried <code>np.nan_to_num()</code> but that doesn't seem to work. After doing so, my min and max values range from 3e-38 and 3e+38 respectively, so I could not normalize it.</p> <p>Is there any way to scale this data down? If not, how should I deal with this?</p> <p>Thank you.</p> <p><strong>EDIT:</strong></p> <p>Some context. I'm working on a malware classification problem. My dataset consists of live malware binaries. They are files of the type .exe, .apk etc. My idea is store these binaries as a numpy array, convert to a grayscale image and then perform pattern analysis on it. </p>
-3
2016-09-29T05:23:29Z
39,762,267
<p><strong>EDIT 2</strong></p> <ul> <li><p>Refer this answer: <a href="http://stackoverflow.com/a/11548224/6633975">http://stackoverflow.com/a/11548224/6633975</a></p> <p>It states: <code>NaN</code> can't be stored in an integer array. This is a known limitation of pandas at the moment; I have been waiting for progress to be made with NA values in NumPy (similar to NAs in R), but it will be at least 6 months to a year before NumPy gets these features, it seems:</p> <p>source: <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na</a></p></li> </ul> <p><a href="http://stackoverflow.com/questions/12708807/numpy-integer-nan">Numpy integer nan</a><br> Accepted answer states:<code>NaN</code> can't be stored in an integer array. A <code>nan</code> is a special value for float arrays <strong>only</strong>. There are talks about introducing a special bit that would allow non-float arrays to store what in practice would correspond to a <code>nan</code>, but so far (2012/10), it's only talks. In the meantime, you may want to consider the <a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.html" rel="nofollow"><code>numpy.ma</code></a> package: instead of picking an invalid integer like -99999, you could use the special <code>numpy.ma.masked</code> value to represent an invalid value.</p> <pre><code>a = np.ma.array([1,2,3,4,5], dtype=int) a[1] = np.ma.masked masked_array(data = [1 -- 3 4 5], mask = [False True False False False], fill_value = 999999) </code></pre> <p><strong>EDIT 1</strong></p> <p>To read binary file:</p> <ol> <li><p>Read the binary file content like this:</p> <pre><code>with open(fileName, mode='rb') as file: # b is important -&gt; binary fileContent = file.read() </code></pre> <p>After that you can "unpack" binary data using <a href="http://docs.python.org/library/struct.html#struct.unpack" rel="nofollow">struct.unpack</a></p></li> <li><p>If you are using <code>np.fromfile()</code> function:</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html" rel="nofollow"><code>numpy.fromfile</code></a>, which can read data from both text and binary files. You would first construct a data type, which represents your file format, using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html" rel="nofollow"><code>numpy.dtype</code></a>, and then read this type from file using <code>numpy.fromfile</code>.</p></li> </ol>
0
2016-09-29T05:43:18Z
[ "python", "numpy", "machine-learning", "data-mining" ]
How to read binary files in Python using NumPy?
39,762,019
<p>I know how to read binary files in Python using NumPy's <code>np.fromfile()</code> function. The issue I'm faced with is that when I do so, the array has exceedingly large numbers of the order of 10^100 or so, with random <code>nan</code> and <code>inf</code> values. </p> <p>I need to apply machine learning algorithms to this dataset and I cannot work with this data. I cannot normalise the dataset because of the <code>nan</code> values.</p> <p>I've tried <code>np.nan_to_num()</code> but that doesn't seem to work. After doing so, my min and max values range from 3e-38 and 3e+38 respectively, so I could not normalize it.</p> <p>Is there any way to scale this data down? If not, how should I deal with this?</p> <p>Thank you.</p> <p><strong>EDIT:</strong></p> <p>Some context. I'm working on a malware classification problem. My dataset consists of live malware binaries. They are files of the type .exe, .apk etc. My idea is store these binaries as a numpy array, convert to a grayscale image and then perform pattern analysis on it. </p>
-3
2016-09-29T05:23:29Z
39,762,706
<p>If you want to make an image out of a binary file, you need to read it in as integer, not float. Currently, the most common format for images is unsigned 8-bit integers.</p> <p>As an example, let's make an image out of the first 10,000 bytes of /bin/bash:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import cv2 &gt;&gt;&gt; xbash = np.fromfile('/bin/bash', dtype='uint8') &gt;&gt;&gt; xbash.shape (1086744,) &gt;&gt;&gt; cv2.imwrite('bash1.png', xbash[:10000].reshape(100,100)) </code></pre> <p>In the above, we used the OpenCV library to write the integers to a PNG file. Any of several other imaging libraries could have been used.</p> <p>This what the first 10,000 bytes of <code>bash</code> "looks" like:</p> <p><a href="http://i.stack.imgur.com/IFGu8.png" rel="nofollow"><img src="http://i.stack.imgur.com/IFGu8.png" alt="enter image description here"></a></p>
1
2016-09-29T06:15:20Z
[ "python", "numpy", "machine-learning", "data-mining" ]
What can I use to pass the file argument in the script from the html code to cherrypy function
39,762,027
<p>So what can I do to pass the argument to the function.</p> <pre><code>import os, random, string import cherrypy class StringGenerator(object): @cherrypy.expose def index(self): return """&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --&gt; &lt;title&gt;Bootstrap 101 Template&lt;/title&gt; &lt;!-- Bootstrap --&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="jumbotron"&gt; &lt;p &gt;&lt;h4 class='text-success' style='margin-left:30%;'&gt;This is the twitter word select &lt;/h1&gt;&lt;/p&gt; &lt;form class="form-inline" action="generate/" style='margin-left:20%;' enctype= "multipart/form-data"&gt; &lt;div class="form-group" &gt; &lt;label for="exampleInputName2"&gt;Enter the file name&lt;/label&gt; &lt;input type="file" class="form-control" name="file1" id="file" placeholder=" enter the file "&gt; &lt;/div&gt;&lt;div class="form-group" &gt; &lt;label for="exampleInputName2"&gt;Enter the prefrence&lt;/label&gt; &lt;input type="text" class="form-control" name="length" id="exampleInputName2" placeholder=" enter the preference "&gt; &lt;/div&gt; &lt;button type="submit" class="btn btn-primary"&gt;Result&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- jQuery (necessary for Bootstrap's JavaScript plugins) --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Include all compiled plugins (below), or include individual files as needed --&gt; &lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;""" @cherrypy.expose def generate(self, length,file1): some_string = "harsh"+length cherrypy.session['mystring'] = some_string fp = open(file1) return fb @cherrypy.expose def display(self): return cherrypy.session['mystring'] if __name__ == '__main__': conf = { '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd()) }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': './public' } } cherrypy.quickstart(StringGenerator(), '/', conf) </code></pre>
1
2016-09-29T05:23:57Z
39,762,884
<p>Take a look into the file <a href="https://github.com/cherrypy/cherrypy/blob/master/cherrypy/tutorial/tut09_files.py" rel="nofollow">cherrypy files tutorial</a>, but to provide you with a concrete answer, your <code>generate</code> method has to use the <code>file</code> attribute of the <code>file1</code> parameter.</p> <p>For example, this method would work:</p> <pre><code>@cherrypy.expose def generate(self, length, file1): some_string = "harsh" + length cherrypy.session['mystring'] = some_string file_content = file1.file.read() return file_content </code></pre> <p>You can also operate on the <code>file</code> attribute to get more information, it's an instance of a python <a href="https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile" rel="nofollow">TemporaryFile</a>.</p>
1
2016-09-29T06:27:02Z
[ "python", "cherrypy" ]
Why i am not able to capture screen shot of selectbox items using selenium-python?
39,762,141
<p>I have a select box on my page. I click on it to expand it and all values are displayed. Now i take screenshot, but in screenshot, select box is not expanded. Please check.</p> <p>Code:</p> <pre><code>import unittest from selenium import webdriver import datetime from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from selenium.common.exceptions import NoSuchElementException from unittest import TestCase import re import time import autoit url="https://www.facebook.com" class SprintTests(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.driver.maximize_window() self.driver.get(url) def test_offer_1(self): a=self.driver.find_element_by_id("day") a.click() time.sleep(5) self.driver.save_screenshot("res.jpg") def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2) </code></pre> <p>Image generated by my code: <a href="http://i.stack.imgur.com/da5Wq.png" rel="nofollow"><img src="http://i.stack.imgur.com/da5Wq.png" alt="enter image description here"></a></p> <p>Expected Image: <a href="http://i.stack.imgur.com/5g6rU.png" rel="nofollow"><img src="http://i.stack.imgur.com/5g6rU.png" alt="enter image description here"></a></p>
0
2016-09-29T05:33:28Z
39,763,816
<p>With the given situation, it is expected to behave in this way. When you perform save_screenshot on driver object, the driver object is now busy getting the screenshot for you instead of keeping the select menu open. One possible solution is that you launch the save_screenshot method in different thread.</p>
0
2016-09-29T07:17:40Z
[ "python", "selenium" ]
Getting unbound method error?
39,762,188
<p>I tried to run this code below </p> <pre><code>class TestStaticMethod: def foo(): print 'calling static method foo()' foo = staticmethod(foo) class TestClassMethod: def foo(cls): print 'calling class method foo()' print 'foo() is part of class: ', cls.__name__ foo = classmethod(foo) </code></pre> <p>After I ran this with the code below </p> <pre><code>tsm = TestStaticMethod() TestStaticMethod.foo() </code></pre> <pre><code>Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; TestStaticMethod.foo() TypeError: unbound method foo() must be called with TestStaticMethod instance as first argument (got nothing instead) </code></pre> <pre><code>tsm.foo() </code></pre> <pre><code>Traceback (most recent call last): File "&lt;pyshell#36&gt;", line 1, in &lt;module&gt; ts.foo() TypeError: foo() takes no arguments (1 given) </code></pre> <p>I really don't get why I'm getting the unbound method. Can anyone help me? </p>
0
2016-09-29T05:37:56Z
39,763,110
<p>You shall try the below code by dedenting the <code>foo</code> variable from class <code>TestStaticMethod</code></p> <pre><code>class TestStaticMethod: def foo(): print 'calling static method foo()' foo = staticmethod(foo) tsm = TestStaticMethod() tsm.foo() </code></pre>
0
2016-09-29T06:39:07Z
[ "python" ]