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
Django rest framework, should be able to override get_queryset and not define queryset attribute?
39,435,836
<p>I am confused. Looking through the ViewSet source code it looks like I should be able to not define a queryset in a viewset and then just override the get queryset function to get whatever queryset I want. But my code fails with this error:</p> <pre><code>AssertionError: `base_name` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. </code></pre> <p>So even if I override the queryset attribute I still need to set it to some fake attribute in the beginning... this works, but it feels weird to define the queryset and then just override it a second later.</p> <pre><code>class StudyQuestion(viewsets.ReadOnlyModelViewSet): queryset = Model.objects.all() serializer_class = ModelSerializer permission_classes = (permissions.IsAuthenticated, ) def get_queryset(self): """""" return Model.objects.order_by('-word__frequency') </code></pre>
1
2016-09-11T12:01:09Z
39,436,584
<p>A DRF ModelViewSet uses the <code>queryset</code> to derive the URL base. If the <code>queryset</code> property is not set, DRF asks that you use the optional <code>base_name</code> property when registering the router to declare the base.</p> <p>Check out this page in the DRF docs:</p> <p><a href="http://www.django-rest-framework.org/api-guide/routers/" rel="nofollow">http://www.django-rest-framework.org/api-guide/routers/</a></p>
2
2016-09-11T13:25:58Z
[ "python", "django", "django-rest-framework" ]
Not able to select value - error "Select only works on <select> elements, not on <a>"
39,435,840
<p>I am trying to retrieve all possible year, model and make from [<a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx]" rel="nofollow">https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx]</a></p> <pre><code>from selenium import webdriver import time from selenium.webdriver.support.ui import Select from bs4 import BeautifulSoup driver = webdriver.Chrome() driver.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx") # Switch to new window opened driver.switch_to.window(driver.window_handles[-1]) # Close the new window driver.close() # Switch back to original browser (first window) driver.switch_to.window(driver.window_handles[0]) el = driver.find_element_by_css_selector("div#fldYear a.sbToggle") el.click() select = Select(el) select.select_by_visible_text("2016") </code></pre> <p>However if I try to select year 2016. It is giving error : Select only works on <code>&lt;select&gt;</code> elements, not on <code>&lt;a&gt;</code></p>
1
2016-09-11T12:01:27Z
39,435,870
<p>The problem with your current approach is that you are finding the <code>a</code> element and trying to use it as a <code>select</code> element. <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.support.select.Select" rel="nofollow"><code>Select</code> class</a> will only work with <code>select</code> elements.</p> <p>Note that in this case, it's easier to get to the invisible <code>select</code> element and get the years from its options directly:</p> <pre><code>options = [option.get_attribute("innerText") for option in driver.find_elements_by_css_selector("select#ddlYear option")[1:]] print(options) </code></pre> <p>The <code>[1:]</code> slice here is to skip the very first <code>Select Year</code> element.</p> <hr> <p>Complete working code:</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver driver = webdriver.Chrome("/usr/local/bin/chromedriver") driver.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx") wait = WebDriverWait(driver, 10) toggle = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#fldYear a.sbToggle"))) toggle.click() options = [option.get_attribute("innerText") for option in driver.find_elements_by_css_selector("select#ddlYear option")[1:]] print(options) </code></pre> <p>Prints:</p> <pre><code>[u'2016', u'2015', u'2014', u'2013', u'2012', u'2011', u'2010', u'2009', u'2008', u'2007', u'2006', u'2005', u'2004', u'2003', u'2002', u'2001', u'2000', u'1999', u'1998', u'1997', u'1996', u'1995', u'1994', u'1993', u'1992', u'1991', u'1990', u'1989', u'1988', u'1987', u'1986', u'1985', u'1984', u'1983', u'1982', u'1981', u'1980', u'1979', u'1978', u'1977', u'1976', u'1975', u'1974', u'1973', u'1972', u'1971', u'1970', u'1969', u'1968', u'1967', u'1966', u'1965', u'1964', u'1963', u'1962', u'1961', u'1960', u'1959', u'1958', u'1957', u'1956', u'1955'] </code></pre>
1
2016-09-11T12:04:21Z
[ "python", "selenium", "web-scraping" ]
Not able to select value - error "Select only works on <select> elements, not on <a>"
39,435,840
<p>I am trying to retrieve all possible year, model and make from [<a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx]" rel="nofollow">https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx]</a></p> <pre><code>from selenium import webdriver import time from selenium.webdriver.support.ui import Select from bs4 import BeautifulSoup driver = webdriver.Chrome() driver.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx") # Switch to new window opened driver.switch_to.window(driver.window_handles[-1]) # Close the new window driver.close() # Switch back to original browser (first window) driver.switch_to.window(driver.window_handles[0]) el = driver.find_element_by_css_selector("div#fldYear a.sbToggle") el.click() select = Select(el) select.select_by_visible_text("2016") </code></pre> <p>However if I try to select year 2016. It is giving error : Select only works on <code>&lt;select&gt;</code> elements, not on <code>&lt;a&gt;</code></p>
1
2016-09-11T12:01:27Z
39,436,211
<p>You don't actually need <code>selenium</code> and automate any visual interactions to get the year+make+model data from the page and can approach the problem with <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a> only making appropriate GET requests:</p> <pre><code># -*- coding: utf-8 -*- from collections import defaultdict from pprint import pprint import requests year = 2016 d = defaultdict(lambda: defaultdict(list)) with requests.Session() as session: session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'} session.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx") while True: response = session.get("https://www.osram-americas.com/_Layouts/Sylvania.Web.LRGHandler/LRGHandler.ashx", params={"rt": "fetchmake", "year": str(year)}) data = response.json() if not data: # break if no makes in a year break for make in data: response = session.get("https://www.osram-americas.com/_Layouts/Sylvania.Web.LRGHandler/LRGHandler.ashx", params={"rt": "fetchmodel", "year": str(year), "make": make["Id"]}) for model in response.json(): d[year][make["Value"]].append(model["Value"]) year -= 1 pprint(dict(d)) </code></pre>
1
2016-09-11T12:41:44Z
[ "python", "selenium", "web-scraping" ]
Nginx - Seems to be running old python scripts
39,435,884
<p>I have a website (panicselect.com), and I have made some changes to the python code which i pushed onto Github and then pulled onto my server, which seems to be successful. I have tried restarting the server, but it still seems to be running my older version of the code even though I have successfully pulled the new version. I believe this as some 'champions' are still missing and the rating seems to be calculated the old way, which is in contrast to what is on my localhost. Do you have an idea of what this could be? I'm running Ubuntu Linux on Digital Ocean with sendfile off and nginx uses Uwsgi to run the Py code.</p>
-2
2016-09-11T12:06:29Z
39,441,234
<p>To fully determine how to deploy changes to your production server, you must understand 2 things:</p> <h1>1. Most WSGI servers (including uWSGI) will load code on start, not on each execution.</h1> <p>That means, changes in your code won't be reflected immediately, because old code is still loaded into your WSGI server. It differs from PHP execution, where code is reloaded on every request. That means, you must restart your WSGI server when you want your new code to be loaded.</p> <h1>2. WSGI and nginx are NOT related</h1> <p>Yes, nginx will connect your WSGI server to outside world, but that's it! It doesn't manage your WSGI server. That means, you must restart your WSGI server by hand. Restarting nginx won't cause that.</p> <p>Also it is good to note here: restarting nginx is not required, unless you've changed nginx configuration.</p>
1
2016-09-11T22:25:30Z
[ "python", "git", "nginx", "github", "uwsgi" ]
Merged Sort Algorithm
39,435,885
<p>I have a merge algorithm which is really fast: it's currently set up to check unknown words between lists; this function checks common words, I need to change the function below to check if words are in vocab or wds or neither I don't properly understand the function so any comments about what specific lines do would be great.</p> <p>def find_unknowns_merge_pattern(vocab, wds):</p> <pre><code>result = [] xi = 0 yi = 0 while True: if xi &gt;= len(vocab): result.extend(wds[yi:]) return result if yi &gt;= len(wds): return result if vocab[xi] == wds[yi]: # Good, word exists in vocab yi += 1 elif vocab[xi] &lt; wds[yi]: # Move past this vocab word, xi += 1 else: # Got word that is not in vocab result.append(wds[yi]) yi += 1 </code></pre> <p>def check(bigger_vocab,book_words):</p> <pre><code> both = [ ] for words in bigger_vocab: for people in book_words: if words == people: words.split() both.append(words) return both </code></pre> <p>The problem is it takes at least 5 seconds whereas my merge algorithm takes 0.08. How can I call that function so I can make this one faster?</p>
-4
2016-09-11T12:06:30Z
39,437,246
<p>Are you just trying to find words that appear in bigger_vocab and book_words? If so:</p> <pre><code>both = list(set(bigger_vocab).intersection(book_words)) </code></pre>
0
2016-09-11T14:44:42Z
[ "python" ]
Write a program that prints the number of times the string contains a substring
39,435,988
<pre><code>s = "bobobobobobsdfsdfbob" count = 0 for x in s : if x == "bob" : count += 1 print count </code></pre> <p>i want to count how many bobs in string s, the result if this gives me 17 what's wrong with my code i'm newbie python.</p>
0
2016-09-11T12:16:44Z
39,436,019
<p>When you are looping overt the string, the throwaway variable will hold the characters, so in your loop <code>x</code> is never equal with <code>bob</code>.</p> <p>If you want to count the non-overlaping strings you can simply use <code>str.count</code>:</p> <pre><code>In [52]: s.count('bob') Out[52]: 4 </code></pre> <p>For overlapping sub-strings you can use lookaround in regex:</p> <pre><code>In [57]: import re In [59]: len(re.findall(r'(?=bob)', s)) Out[59]: 6 </code></pre>
3
2016-09-11T12:20:50Z
[ "python", "python-2.7", "python-3.x" ]
Write a program that prints the number of times the string contains a substring
39,435,988
<pre><code>s = "bobobobobobsdfsdfbob" count = 0 for x in s : if x == "bob" : count += 1 print count </code></pre> <p>i want to count how many bobs in string s, the result if this gives me 17 what's wrong with my code i'm newbie python.</p>
0
2016-09-11T12:16:44Z
39,436,031
<p>you can use string.count</p> <p>for example:</p> <pre><code>s = "bobobobobobsdfsdfbob" count = s.count("bob") print(count) </code></pre>
1
2016-09-11T12:22:47Z
[ "python", "python-2.7", "python-3.x" ]
Write a program that prints the number of times the string contains a substring
39,435,988
<pre><code>s = "bobobobobobsdfsdfbob" count = 0 for x in s : if x == "bob" : count += 1 print count </code></pre> <p>i want to count how many bobs in string s, the result if this gives me 17 what's wrong with my code i'm newbie python.</p>
0
2016-09-11T12:16:44Z
39,436,122
<p>I'm not giving the best solution, just trying to correct your code. </p> <p><strong>Understanding what <code>for each (a.k.a range for)</code> does in your case</strong> </p> <pre><code>for c in "Hello": print c </code></pre> <p>Outputs: </p> <pre><code>H e l l o </code></pre> <p>In each iteration you are comparing a character to a string which results in a wrong answer.<br> Try something like<br> (For no overlapping, i.e no span) </p> <pre><code>s = "bobobobobobsdfsdfbob" w = "bob" count = 0 i = 0 while i &lt;= len(s) - len(w): if s[i:i+len(w)] == w: count += 1 i += len(w) else: i += 1 print (count) </code></pre> <p>Output:</p> <p><code>Count = 4</code></p> <p>Overlapping </p> <pre><code>s = "bobobobobobsdfsdfbob" w = "bob" count = 0 for i in range(len(s) - len(w) + 1): if s[i:i+len(w)] == w: count += 1 print (count) </code></pre> <p>Output:<br> <code>Count = 6</code></p>
0
2016-09-11T12:31:37Z
[ "python", "python-2.7", "python-3.x" ]
How to drop null values in Pandas?
39,436,018
<p>I try to drop null values of column 'Age' in dataframe, which consists of float values, but it doesn't work. I tried</p> <pre><code>data.dropna(subset=['Age'], how='all') data['Age'] = data['Age'].dropna() data=data.dropna(axis=1,how='all') </code></pre> <p>It works for other columns but not for 'Age'</p> <pre><code> Pclass Fare Age Sex 0 3 7.2500 22.0 1 1 1 71.2833 38.0 0 2 3 7.9250 26.0 0 3 1 53.1000 35.0 0 4 3 8.0500 35.0 1 5 3 8.4583 NaN 1 6 1 51.8625 54.0 1 7 3 21.0750 2.0 1 </code></pre>
1
2016-09-11T12:20:45Z
39,436,068
<p><code>data.dropna(subset=['Age'])</code> would work, but you should either set <code>inplace=True</code> or assign it back to <code>data</code>:</p> <pre><code>data = data.dropna(subset=['Age']) </code></pre> <p>or </p> <pre><code>data.dropna(subset=['Age'], inplace=True) </code></pre>
2
2016-09-11T12:26:47Z
[ "python", "pandas" ]
Python: Value of dictionary is list of strings
39,436,055
<pre><code>reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\"" print reclist data= { "ids": [ reclist #"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7" ] } print data </code></pre> <p>Output: `</p> <pre><code>"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"` {'ids': [' "MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7" ']} </code></pre> <p>But expecting output is:</p> <pre><code>"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7" {'ids': ["MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"]} </code></pre> <p>When I print <code>rectlist</code>, it did not shows extra ' ', but when I used <code>reclist</code> in <code>data</code>, then due to extra ' ' in <code>reclist</code>, showing error <code>urllib2.HTTPError: HTTP Error 400: Bad Request</code>, as I have to add this data to <code>urllib2.Request</code>.How to strip out extra ' ' from <code>reclist</code> when used in data?</p>
3
2016-09-11T12:25:28Z
39,436,095
<p><code>reclist</code> is a string not an iterable, you can use <code>ast.literal_eval</code> in order to convert it to a tuple directly:</p> <pre><code>In [60]: import ast In [61]: reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\"" In [62]: ast.literal_eval(reclist) Out[62]: ('MOBEEVHDBBYSQFC8', 'MOBE9J587QGMXBB7') </code></pre>
1
2016-09-11T12:29:25Z
[ "python", "dictionary" ]
Python: Value of dictionary is list of strings
39,436,055
<pre><code>reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\"" print reclist data= { "ids": [ reclist #"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7" ] } print data </code></pre> <p>Output: `</p> <pre><code>"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"` {'ids': [' "MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7" ']} </code></pre> <p>But expecting output is:</p> <pre><code>"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7" {'ids': ["MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"]} </code></pre> <p>When I print <code>rectlist</code>, it did not shows extra ' ', but when I used <code>reclist</code> in <code>data</code>, then due to extra ' ' in <code>reclist</code>, showing error <code>urllib2.HTTPError: HTTP Error 400: Bad Request</code>, as I have to add this data to <code>urllib2.Request</code>.How to strip out extra ' ' from <code>reclist</code> when used in data?</p>
3
2016-09-11T12:25:28Z
39,436,241
<p>You can also <code>split()</code> and <code>strip()</code> the double quotes:</p> <pre><code>&gt;&gt;&gt; reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\"" &gt;&gt;&gt; [item.strip('"') for item in reclist.split(",")] ['MOBEEVHDBBYSQFC8', 'MOBE9J587QGMXBB7'] </code></pre>
1
2016-09-11T12:45:30Z
[ "python", "dictionary" ]
TypeError: unorderable types: str() <= int() error
39,436,070
<p>Could you guys help me out with finding the wrong part of the code? I tried some things and searched on this site, but I couldn't find the solution.. If you guys know something, please let it know :D</p> <pre><code>print("Uw formule is ax**2+bx+c") a= float(input("Geef getal a:" )) b= float(input("Geef getal b:" )) c= float(input("Geef getal c:" )) D=b**2-4*a*c while (D&lt;=0) or (a==0): print("Voer nieuwe getallen in, de uitkomst is niet te berekenen") a= float(input("Geef getal a:" )) b= float(input("Geef getal b:" )) c= float(input("Geef getal c:" )) D=b*b-4*a*c D= format(D,'.1f') if (D&gt;0): print("\nDe discriminant is:", D ) x1= (-b-(D)**0.5)/(2*a) x1= format(x1,'.1f') x2= (-b+(D)**0.5)/(2*a) x2= format(x2,'.1f') print("De uitkomst van x1=", x1) print("De uitkomst van x2=", x2) </code></pre> <p>Then the error:</p> <pre><code>Traceback (most recent call last): File "*****", line 15, in &lt;module&gt; while (D&lt;=0) or (a==0): TypeError: unorderable types: str() &lt;= int() </code></pre>
0
2016-09-11T12:26:58Z
39,436,093
<p>At the end of your for loop you reassign <code>D</code> to the result of calling <code>format</code>. That will always make it a string.</p> <p>I'm not sure why you're doing that, but you should remove that line.</p>
0
2016-09-11T12:29:15Z
[ "python" ]
TypeError: unorderable types: str() <= int() error
39,436,070
<p>Could you guys help me out with finding the wrong part of the code? I tried some things and searched on this site, but I couldn't find the solution.. If you guys know something, please let it know :D</p> <pre><code>print("Uw formule is ax**2+bx+c") a= float(input("Geef getal a:" )) b= float(input("Geef getal b:" )) c= float(input("Geef getal c:" )) D=b**2-4*a*c while (D&lt;=0) or (a==0): print("Voer nieuwe getallen in, de uitkomst is niet te berekenen") a= float(input("Geef getal a:" )) b= float(input("Geef getal b:" )) c= float(input("Geef getal c:" )) D=b*b-4*a*c D= format(D,'.1f') if (D&gt;0): print("\nDe discriminant is:", D ) x1= (-b-(D)**0.5)/(2*a) x1= format(x1,'.1f') x2= (-b+(D)**0.5)/(2*a) x2= format(x2,'.1f') print("De uitkomst van x1=", x1) print("De uitkomst van x2=", x2) </code></pre> <p>Then the error:</p> <pre><code>Traceback (most recent call last): File "*****", line 15, in &lt;module&gt; while (D&lt;=0) or (a==0): TypeError: unorderable types: str() &lt;= int() </code></pre>
0
2016-09-11T12:26:58Z
39,436,154
<p>Thanks! I solved it with:</p> <pre><code>print("Uw formule is ax**2+bx+c") a= float(input("Geef getal a:" )) b= float(input("Geef getal b:" )) c= float(input("Geef getal c:" )) D=b**2-4*a*c while (D&lt;=0) or (a==0): print("Voer nieuwe getallen in, de uitkomst is niet te berekenen") a= float(input("Geef getal a:" )) b= float(input("Geef getal b:" )) c= float(input("Geef getal c:" )) D=b*b-4*a*c D1= format(D,'.1f') #this code if (D&gt;0): print("\nDe discriminant is:", D1 ) x1= (-b-(D)**0.5)/(2*a) x1= format(x1,'.1f') x2= (-b+(D)**0.5)/(2*a) x2= format(x2,'.1f') print("De uitkomst van x1=", x1) print("De uitkomst van x2=", x2) </code></pre>
0
2016-09-11T12:35:19Z
[ "python" ]
I can't change the image using label.configure
39,436,088
<p>I am trying to create a GUI in which I can process images, so I have to change the default image to the one chosen by the browse button. The default image disappears but the new image doesn't appear. Help Please! Here is my code:</p> <pre><code>from Tkinter import * from tkFileDialog import askopenfilename import cv2 class Browse_image : def __init__ (self,master) : frame = Frame(master) frame.grid(sticky=W+E+N+S) self.browse = Button(frame, text="Browse", command = lambda: self.browseim()) self.browse.grid(row=13, columnspan=2) self.check = Checkbutton(frame, text="On/Off") self.check.grid(row=0) self.maxval = Scale(frame, from_=0, to=100, orient=HORIZONTAL) self.maxval.grid(row=1,columnspan=2) self.minval = Scale(frame, from_=0, to=100, orient=HORIZONTAL) self.minval.grid(row=2,columnspan=2) self.photo = PhotoImage(file="browse.png") self.label = Label(frame, image=self.photo) self.label.grid(row=3,rowspan=10) def browseim(self): path = askopenfilename(filetypes=(("png files","*.png"),("jpeg files","*.jpeg")) ) if path: self.photo = PhotoImage(path) self.label.configure(image = self.photo) #self.label.image = self.photo #self.label.grid(row=3,rowspan=10) root= Tk() b= Browse_image(root) root.mainloop() </code></pre>
0
2016-09-11T12:29:07Z
39,436,552
<p>Change <code>self.photo = PhotoImage(path)</code> to <code>self.photo = PhotoImage(file=path)</code>. The <code>file</code> parameter is required to define an image path in <a href="http://effbot.org/tkinterbook/photoimage.htm" rel="nofollow"><code>PhotoImage</code> class</a>.</p>
0
2016-09-11T13:22:24Z
[ "python", "tkinter", "photoimage" ]
Python Tkinter TTK Treeview Find Selected Items' ID Or Row
39,436,098
<p>I am creating a program which uses a TTK Treeview as an item hierarchy. So far, the user is able to insert their own values into the tree, but I need to have a check running for when the user clicks on an item in the tree. I need the check to find the selected items ID and return it.</p> <p>The check I have running relies on the <code>&lt;&lt;TreeviewSelect&gt;&gt;</code> bind. Currently, it finds the selected item and stores some information, but I need for it to also find the row the item is in or it's ID.</p> <p>I tried implementing my own tag using a counter and the tag attribute of Treeview items, but it would return the number as a <code>NoneType</code>. I also tried using the value attribute, but it returned the same problem.</p> <p>For information, I have read through many sites and a few questions on here, but none (that I have found) answer what I need.</p> <p>Any help would be greatly appreciated, thank you for taking the time to read.</p>
-2
2016-09-11T12:29:35Z
39,436,297
<p>You can call the <a href="https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview.selection" rel="nofollow">selection</a> method to get a list of all selected items:</p> <pre><code>selected_items = self.tree.selection() </code></pre>
0
2016-09-11T12:52:09Z
[ "python", "tkinter", "treeview", "ttk" ]
Pyparsing pulp error
39,436,329
<p>When I try installing ManPy I got the following error message:</p> <blockquote> <p>error: pyparsing 2.1.4 is installed but pyparsing&lt;=1.9.9 is required by set(['pulp'])</p> </blockquote> <p>I checked the Pyparsing setup, but I didn't find the solution.</p>
0
2016-09-11T12:56:36Z
39,437,610
<p>This is actually an error in the setup.py of PuLP (which apparently is used by ManPy):</p> <pre><code>#hack because pyparsing made version 2 python 3 specific if sys.version_info[0] &lt;= 2: pyparsing_ver = 'pyparsing&lt;=1.9.9' else: pyparsing_ver = 'pyparsing&gt;=2.0.0' </code></pre> <p>As of pyparsing 2.0.1, pyparsing was unified to use a single code base for both Py2 and Py3 installs, but using only Py3 constructs that had been backported to 2.7. It took a few version releases to get this all worked out, but pyparsing (since 2.0.3, now at version 2.1.9) is now compatible with Python 2.6 and later.</p> <p>If you are using a Python version before 2.6, then you would need to install pyparsing 1.5.7, which is the last pre-2.6 compatible version, and no new 1.x releases are planned. </p> <p>Contact the maintainer of PuLP and see if you can get them to fix up this version testing in their setup.py file.</p> <p><strong>UPDATE</strong>: On closer inspection, I see that PuLP uses a little module called Amply that does the actual expression parsing. I just ran some tests with Amply on my pyparsing 2.1.9 environment, and they run just fine.</p>
0
2016-09-11T15:20:10Z
[ "python", "pyparsing", "pulp" ]
Having trouble playing music using IPython
39,436,524
<p>I have the lines of code</p> <pre><code>import IPython IPython.display.Audio(url="http://www.1happybirthday.com/PlaySong/Anna",embed=True,autoplay=True) </code></pre> <p>And I'm not really sure what's wrong. I am using try.jupyter.org to run my code, and this is within if statements. The notebook is also taking in user inputs and printing outputs. It gives no error, but just doesn't show up/start playing. I'm not really sure what's wrong.</p> <p>Any help would be appreciated. Thanks!</p>
0
2016-09-11T13:18:45Z
39,457,223
<p>First you should try it without the <code>if</code> statement. Just the two lines you mention above. This will still not work, because your URL does point to an HTML page instead of a sound file. In your case the correct URL would be <code>'https://s3-us-west-2.amazonaws.com/1hbcf/Anna.mp3'</code>.</p> <p>The <code>Audio</code> object which you are creating, will only be displayed if it is the last statement in a notebook cell. See <a href="http://nbviewer.jupyter.org/github/mgeier/python-audio/blob/master/intro-python.ipynb" rel="nofollow">my Python intro</a> for details. If you want to use it within an <code>if</code> clause, you can use <code>IPython.display.display()</code> like this:</p> <pre><code>url = 'https://s3-us-west-2.amazonaws.com/1hbcf/Anna.mp3' if 3 &lt; 5: IPython.display.display(IPython.display.Audio(url=url, autoplay=True)) else: print('Hello!') </code></pre>
1
2016-09-12T19:16:02Z
[ "python", "audio", "ipython", "jupyter-notebook" ]
Issue in running hive udf written in python
39,436,537
<p>I have written a simple hive udf in python, but when I run it in hive shell, it throws below error: </p> <pre><code>Diagnostic Messages for this Task: Error: java.lang.RuntimeException: Hive Runtime Error while closing operators at org.apache.hadoop.hive.ql.exec.mr.ExecMapper.close(ExecMapper.java:260) at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:61) at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343) at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:415) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657) at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158) Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: [Error 20003]: An error occurred when trying to close the Operator running your custom script. at org.apache.hadoop.hive.ql.exec.ScriptOperator.close(ScriptOperator.java:514) at org.apache.hadoop.hive.ql.exec.Operator.close(Operator.java:588) at org.apache.hadoop.hive.ql.exec.Operator.close(Operator.java:588) at org.apache.hadoop.hive.ql.exec.Operator.close(Operator.java:588) at org.apache.hadoop.hive.ql.exec.mr.ExecMapper.close(ExecMapper.java:227) ... 8 more FAILED: Execution Error, return code 20003 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask. An error occurred when trying to close the Operator running your custom script. </code></pre> <p>`</p> <p><strong>Commands used in hive shell:</strong></p> <p><code>add file /path/to/mycode.py;</code></p> <p>created the table;</p> <p>loaded the data;</p> <p><code>SELECT TRANSFORM (fname,lname) USING 'python mycode.py' AS (fname,LNAME) from table;</code></p> <p><strong>Hadoop version: 2.7</strong></p> <p><strong>Hive: 0.13</strong></p> <p><strong>mycode.py</strong></p> <pre><code>#!/usr/bin/python import sys import string try: for line in sys.stdin: lines = string.strip(line,'\n') fname,lname = string.split(lines,',') #print (fname,lname) LNAME = lname.lower() #print LNAME print([fname,LNAME]) except: print sys.exc_info() </code></pre> <p><strong>Error:</strong></p> <p><code>(&lt;type 'exceptions.ValueError'&gt;, ValueError('need more than 1 value to unpack',), &lt;traceback object at 0x7f3441c14050&gt;) NULL</code></p> <p>Though, when I try <code>cat pyinp.txt | python mycode.py</code> it gives the desired output.</p> <p>Can someone help me in resolving this issue?</p>
0
2016-09-11T13:20:05Z
39,436,936
<p>This solved the problem for others cases like yours: <a href="http://themrmax.github.io/2015/07/16/a-python-nltk-wordnet-udf-in-hive.html" rel="nofollow">here</a> </p> <p>They are using a try catch block into the function, did you do the same? </p>
0
2016-09-11T14:09:41Z
[ "python", "hive" ]
Encoding issue when writing to CSV file in Python
39,436,560
<p>I have some encoding issue while writing an array to CSV.</p> <p>Code:</p> <pre><code>import csv a = [u'eNTfxfwc', 'Pushkar', 'Waghulde', 'pushkar.waghulde@gmail.com', 'Los Angeles', '', 'UNITED STATES', '2652 Ellendale Pl # 9', '', 'Los Angeles, UNITED STATES', u'90007', u'', u'(213)458-2091', u'None', u'', u'imports/jobvite/eNTfxfwc.txt', '07/17/2012', u'2012-24', u'pWOjJfww', u'Undefined', u'Import', u' ', '', '', u'\u8edf\u9ad4\u5de5\u7a0b\u5e2b (Software Engineer)', '07/17/2012', '', u'Undefined', '', u'None', '', '', u'Undefined', u'Not Considered', '', '07/17/2012', u'import/jobvite/eNTfxfwc_1.txt'] f3 = open('test.csv', 'at') writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL) writer.writerow(a).encode('utf-8') </code></pre> <p>How can I fix this issue and write array into CSV file?</p>
-1
2016-09-11T13:22:58Z
39,437,076
<p>Just encode the elements in a before writing them</p> <pre><code>a = [i.encode('utf-8') for i in a] f3 = open('test.csv', 'at') writer = csv.writer(f3,delimiter = ',',lineterminator='\n',quoting=csv.QUOTE_ALL) writer.writerow(a) </code></pre>
-1
2016-09-11T14:26:33Z
[ "python", "csv", "encoding" ]
Lowest common ancestor, how to build the tree from command line input?
39,436,570
<pre><code># Python program to find LCA of n1 and n2 using one # traversal of Binary tree # def build_graph(): # n = input() # ex1, ex2 = raw_input(), raw_input() # d = {} # for i in xrange(n-1): # e1, e2 = map(str, raw_input().split()) # if e1 not in d: # node = Node(e1) # node.left = Node(e2) # d.update({e1:node}) # if e1 in d: # d[e1].right = Node(e2) # # for i in d.values(): # # print i.key, i.left.left.key, i.right.key # print d.get(next(d.__iter__())) # return d def build_graph(): l = [] n = input() ex1, ex2 = raw_input(), raw_input() for i in xrange(n-1): e1, e2 = map(str, raw_input().split()) node1 = Node(e1) node2 = Node(e2) if len(l) &gt; 0: if node1 not in l: node1.left = node2 l.append(node1) if e1 in d: # A binary tree node class Node: # Constructor to create a new tree node def __init__(self, key): self.key = key self.left = None self.right = None # This function returns pointer to LCA of two given # values n1 and n2 # This function assumes that n1 and n2 are present in # Binary Tree def findLCA(root, n1, n2): # print graph # if type(graph) is dict: # root = graph.popitem() # root = root[1] # else: # root = graph # Base Case if root is None: return root # If either n1 or n2 matches with root's key, report # the presence by returning root (Note that if a key is # ancestor of other, then the ancestor key becomes LCA if root.key == n1 or root.key == n2: return root # Look for keys in left and right subtrees left_lca = findLCA(root.left, n1, n2) right_lca = findLCA(root.right, n1, n2) # If both of the above calls return Non-NULL, then one key # is present in once subtree and other is present in other, # So this node is the LCA if left_lca and right_lca: return root # Otherwise check if left subtree or right subtree is LCA return left_lca if left_lca is not None else right_lca # Driver program to test above function # Let us create a binary tree given in the above example root = Node('A') root.left = Node('B') root.right = Node('C') root.left.left = Node('D') root.left.right = Node('E') root.left.left.left = Node('F') # root.left.left.right = Node('F') build_graph() # not being used not but want to take input and build a tree print findLCA(root , 'Hilary', 'James').key </code></pre> <p>The input on command line will be like this:</p> <pre class="lang-none prettyprint-override"><code>6 D F A B A C B D B E E F </code></pre> <p>As you could see, I could hardcode it, by using Node class, but I want to build the tree using command line input as mentioned above.</p> <p>INPUT FORMAT: The first number is the number of unique people in a family. And, then the two selected people in a family, i.e; D,F, and then the rest of the lines contains name of two people with a space separator. A B means, A is senior to B, and B is senior to E and D etc. For simplicity the first set that is A B, A has to be considered as root of the tree.</p> <p>So, how could I read input through command line and build the same tree as I am able to do it through <code>root = Node('A')</code>, <code>root.left = Node('B')</code>, etc.?</p> <p>I am trying to learn LCA, so would really appreciate some help in the right direction in a simplest way.</p>
2
2016-09-11T13:24:13Z
39,437,136
<p>I'd recommend you use a dictionary or some other way to keep track of the members of the tree. </p> <p>According to the way you build the tree, this is what I came up with: When you parse each ordered pair, </p> <ul> <li>Check whether the parent is in the tree or not. If the parent is present, check if there already exists a left child. <ul> <li>If a left child exists, make the child the <em>right</em> child of the parent. </li> <li>If a left child doesn't exist, make the child the <em>left</em> child of the parent.</li> </ul></li> <li>If the parent isn't present in the tree, it means that either the pair <ul> <li>Is the first one to be read, therefore the parent must be made the root, or</li> <li>Contains an invalid parent.</li> </ul></li> </ul> <p>Python-ish pseudocode (without error handling):</p> <pre><code>members = {} for line in input: parent_key, child_key = line.split(' ') if parent_key not in members: # I'm assuming this will happen only for # the first pair root = members[parent_key] = Node(parent_key) parent = members[parent_key] if parent.left is None: # If the child already exists, don't create a new one # You can change this and the next statement if this isn't what you want # This also assumes that the given child, if exists # is not already a child of any member # If that can happen, you'll need to keep track of parents too parent.left = members.get(child_key, Node(child_key)) members[child_key] = parent.left else: # Assuming that the parent will not have # a right child if we're here parent.right = members.get(child_key, Node(child_key)) members[child_key] = parent.right </code></pre>
1
2016-09-11T14:33:30Z
[ "python", "algorithm", "tree", "binary-tree", "lowest-common-ancestor" ]
AWS Lambda subprocess OSError: [Errno 2] No such file or directory
39,436,579
<p>I'm trying to create a lambda function that makes collection of thumbnails from a video on amazon s3 using ffmpeg. ffmpeg binary is included into fuction package.</p> <p>function code:</p> <pre><code># -*- coding: utf-8 -*- import stat import shutil import boto3 import logging import subprocess as sp import os import threading thumbnail_prefix = 'thumb_' thumbnail_ext = '.jpg' time_delta = 1 video_frames_path = 'media/videos/frames' print('Loading function') logger = logging.getLogger() logger.setLevel(logging.INFO) lambda_tmp_dir = '/tmp' # Lambda fuction can use this directory. # ffmpeg is stored with this script. # When executing ffmpeg, execute permission is requierd. # But Lambda source directory do not have permission to change it. # So move ffmpeg binary to `/tmp` and add permission. ffmpeg_bin = "{0}/ffmpeg.linux64".format(lambda_tmp_dir) shutil.copyfile('/var/task/ffmpeg.linux64', ffmpeg_bin) os.chmod(ffmpeg_bin, 777) # tried also: # os.chmod(ffmpeg_bin, os.stat(ffmpeg_bin).st_mode | stat.S_IEXEC) s3 = boto3.client('s3') def get_thumb_filename(num): return '{prefix}{num:03d}{ext}'.format(prefix=thumbnail_prefix, num=num, ext=thumbnail_ext) def create_thumbnails(video_url): i = 1 filenames_list = [] filename = None while i == 1 or os.path.isfile(os.path.join(os.getcwd(), get_thumb_filename(i-1))): if filename: filenames_list.append(filename) time = time_delta * (i - 1) filename = get_thumb_filename(i) print(ffmpeg_bin) if os.path.isfile(ffmpeg_bin): print('ok') sp.call(['sudo', ffmpeg_bin, '-ss', str(time), '-i', video_url, '-frames:v', '1', get_thumb_filename(i)]) i += 1 print(filenames_list) return filenames_list def s3_upload_file(file_path, key, bucket, acl, content_type): file = open(file_path, 'r') s3.put_object( Bucket=bucket, ACL=acl, Body=file, Key=key, ContentType=content_type ) logger.info("file {0} moved to {1}/{2}".format(file_path, bucket, key)) def s3_upload_files_in_threads(filenames_list, dir_path, bucket, s3path, acl, content_type): for filename in filenames_list: if os.path.isfile(os.path.join(dir_path, filename)): print(os.path.join(dir_path, filename)) t = threading.Thread(target=s3_upload_file, args=(os.path.join(dir_path, filename), '{0}/{1}'.format(s3path, filename), bucket, acl, content_type)).start() def lambda_handler(event, context): bucket = event['Records'][0]['s3']['bucket']['name'] video_key = event['Records'][0]['s3']['object']['key'] video_name = video_key.split('/')[-1].split('.')[0] video_url = 'http://{0}/{1}'.format(bucket, video_key) filenames_list = create_thumbnails(video_url) s3_upload_files_in_threads(filenames_list, os.getcwd(), bucket, '{0}/{1}'.format(video_frames_path, video_name), 'public-read', 'image/jpeg') return </code></pre> <p>during the execution I get following logs:</p> <pre><code>Loading function /tmp/ffmpeg.linux64 ok [Errno 2] No such file or directory: OSError Traceback (most recent call last): File "/var/task/lambda_function.py", line 112, in lambda_handler filenames_list = create_thumbnails(video_url) File "/var/task/lambda_function.py", line 77, in create_thumbnails get_thumb_filename(i)]) File "/usr/lib64/python2.7/subprocess.py", line 522, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib64/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib64/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory </code></pre> <p>When I use the same sp.call() with the same ffmpeg binary on my ec2 instance it works fine. </p>
0
2016-09-11T13:25:30Z
39,437,269
<p>The problem is not because of <code>ffmpeg</code>. The error is for <code>sudo</code> not found. Lambda instances do not come with <code>sudo</code>. Why do you need <code>sudo</code>? Can you print whatever you pass to <code>sp.call()</code>?</p>
3
2016-09-11T14:46:42Z
[ "python", "amazon-web-services", "ffmpeg", "aws-lambda" ]
How can I get uploaded text file in view through Django?
39,436,612
<p>I'm now making web app. This app gets text file having not-organized data and organize it. I'm now using Django in Python3.</p> <p>I already made form data in templates.</p> <ul> <li>Teplates</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&gt; &lt;form action="/practice/kakao_reader/" method="post"enctype="multipart/form-data"&gt;{% csrf_token %} &gt; File: &gt; &lt;input type="file" name="file"/&gt; &gt; &lt;input type="submit" value="UPLOAD" /&gt; &gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>But I have difficulty in getting uploaded file through VIEW. The first code that I've tried was </p> <ul> <li>View.py</li> </ul> <blockquote> <p>def kakao_reader(request):</p> <p>f = codecs.open(request.FILES['file'], encoding = 'utf-8') </p> <p>data = f.read()</p> </blockquote> <p>And I get <strong><em>invalid file: InMemoryUploadedFile:</em></strong> this error.</p> <p>The specific Error is</p> <blockquote> <p>Environment:</p> <p>Request Method: POST Request URL: <a href="http://localhost:8000/practice/kakao_reader/" rel="nofollow">http://localhost:8000/practice/kakao_reader/</a></p> <p>Django Version: 1.10 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'elections', 'practice'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']</p> <p>Traceback:</p> <p>File "C:\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request)</p> <p>File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request)</p> <p>File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)</p> <p>File "C:\Django\mysite\practice\views.py" in kakao_json 43. f = codecs.open(request.FILES['file'], encoding = 'utf-8')</p> <p>File "C:\Python35\Lib\codecs.py" in open 895. file = builtins.open(filename, mode, buffering)</p> <p>Exception Type: TypeError at /practice/kakao_reader/ Exception Value: invalid file: </p> </blockquote> <p>How can I fix it? thank you.</p>
0
2016-09-11T13:29:43Z
39,437,140
<p><code>request.FILES['file']</code> is already a file handler, so you don't have to open it. Just use <code>request.FILES['file'].read()</code>.</p>
1
2016-09-11T14:34:16Z
[ "python", "django", "python-3.x" ]
Wrap a function that takes a struct of optional arguments using kwargs
39,436,632
<p>In C it's not uncommon to see a function that takes a lot of inputs, many/most of which are optional group these up in a struct to make the interface cleaner for developers. (Even though you should be able to rely on a compiler accepting <a href="http://stackoverflow.com/questions/9034787/function-parameters-max-number">at least 127 arguments to a function</a> nobody actually wants to write that many, especially as C has no overloading or default function argument support). As a hypothetical example we could consider the following struct/function pair (test.h) to illustrate the problem:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdbool.h&gt; typedef struct { const char *name; void *stuff; int max_size; char flags; _Bool swizzle; double frobination; //... } ComplexArgs; void ComplexFun(const ComplexArgs *arg) {} </code></pre> <p>When it comes to wrapping this using SWIG we can get something working quickly using:</p> <pre class="lang-c prettyprint-override"><code>%module test %{ #include "test.h" %} typedef bool _Bool; %include "test.h" </code></pre> <p>That works and we can use it as follows:</p> <pre class="lang-py prettyprint-override"><code>import test args=test.ComplexArgs() args.flags=100; args.swizzle=True test.ComplexFun(args) </code></pre> <p>But that isn't exactly Pythonic. A Python developer would be more accustomed to seeing kwargs used to support this kind of calling:</p> <pre><code>import test # Not legal in the interface currently: test.ComplexFun(flags=100, swizzle=True) </code></pre> <p>How can we make that work? The SWIG -keyword command line option doesn't help either because there's only one actual argument to the function. </p>
1
2016-09-11T13:32:49Z
39,436,633
<p>Normally in Python the way to modify function arguments and return values is to use a decorator. As a starting point I sketched out the following decorator, which solves the problem:</p> <pre><code>def StructArgs(ty): def wrap(f): def _wrapper(*args, **kwargs): arg=(ty(),) if len(kwargs) else tuple() for it in kwargs.iteritems(): setattr(arg[0], *it) return f(*(args+arg)) return _wrapper return wrap </code></pre> <p>It has some further neat properties when written like that:</p> <ol> <li>It also doesn't break the syntax for calling the function directly with the single struct argument</li> <li>It can support functions with mandatory positional arguments <em>and</em> a struct full of optional arguments as the last argument. (Although it can't use kwargs syntax for mandatory non-struct arguments currently)</li> </ol> <p>The question then becomes one of simply applying that decorator to the right function inside the SWIG generated Python code. My plan was to wrap it up in the simplest possible macro I could, because the pattern is repeated across the library I'm wrapping lots. That turned out to be harder than I expected though. (And I'm apparently <a href="http://swig.10945.n7.nabble.com/python-decorators-td12134.html" rel="nofollow">not the only one</a>) I initially tried:</p> <ol> <li><code>%feature("shadow")</code> - I was pretty sure that would work, and indeed it does work for C++ member functions, but it doesn't work for free functions at global scope for some reason I didn't figure out.</li> <li><code>%feature("autodoc")</code> and <code>%feature("docstring")</code> - optimistically I'd hoped to be able to abuse them slightly, but no joy</li> <li><code>%pythoncode</code> right before the SWIG sees the function declaration on the C side. Generates the right code, but unfortunately SWIG immediately hides the function we decorated by adding <code>ComplexFun = _test.ComplexFun</code>. Couldn't find a way around it for quite a while.</li> <li>Use <code>%rename</code> to hide the real function we call and then write a wrapper around the real function which was also decorated. That worked, but felt really inelegant, because it basically made writing the above decorator pointless instead of just writing it in the new wrapper.</li> </ol> <p>Finally I found a neater trick to decorate the free function. By using <code>%pythonprepend</code> on the function I could insert something (anything, a comment, <code>pass</code>, empty string etc.) which as enough to suppress the extra code that was preventing #3 from working.</p> <p>The final problem I encountered was that to make it all work as a single macro and get the position of the <code>%pythoncode</code> directive right (also still permit <code>%include</code>ing of the header file which contained the declaration) I had to call the macro before <code>%include</code>. That necessitated adding an additional <code>%ignore</code> to ignore the function if/when it's seen a second time in an actual header file. However the other problem it introduced is that we now wrap the function before the struct, so inside the Python module the type of the struct we need the decorator to populate isn't yet known when we call the decorator. That's easily enough fixed by passing a string to the decorator instead of a type and looking it up later, in the <a href="http://stackoverflow.com/a/990450/168175">module <code>globals()</code></a>.</p> <p>So with that said the complete, working interface that wraps this becomes:</p> <pre><code>%module test %pythoncode %{ def StructArgs(type_name): def wrap(f): def _wrapper(*args, **kwargs): ty=globals()[type_name] arg=(ty(),) if kwargs else tuple() for it in kwargs.iteritems(): setattr(arg[0], *it) return f(*(args+arg)) return _wrapper return wrap %} %define %StructArgs(func, ret, type) %pythoncode %{ @StructArgs(#type) %} // *very* position sensitive %pythonprepend func %{ %} // Hack to workaround problem with #3 ret func(const type*); %ignore func; %enddef %{ #include "test.h" %} typedef bool _Bool; %StructArgs(ComplexFun, void, ComplexArgs) %include "test.h" </code></pre> <p>This then was enough to work with the following Python code:</p> <pre><code>import test args=test.ComplexArgs() args.flags=100; args.swizzle=True test.ComplexFun(args) test.ComplexFun(flags=100, swizzle=True) </code></pre> <p>Things you'd probably want to do before using this for real:</p> <ol> <li>With this decorator and kwargs as currently written it's pretty hard to get any kind of TypeError back. Probably your C function has a way of indicating invalid combinations of inputs. Convert those into TypeError exceptions for Python users. </li> <li>Adapt the macro to support mandatory positional arguments if needed. </li> </ol>
2
2016-09-11T13:32:49Z
[ "python", "c", "swig" ]
Numba Lowering error when iterating over 3D array
39,436,719
<p>I have a 3D array (n, 3,2) for holding groups of three 2D vectors and I'm iterating over them something like this:</p> <pre><code>import numpy as np for x in np.zeros((n,2,3), dtype=np.float64): print(x) # for example </code></pre> <p>With normal numpy this works fine but when I wrap the function in question in a</p> <pre><code> @numba.jit(nopython=True) </code></pre> <p>I get an error like the one below.</p> <pre><code>numba.errors.LoweringError: Failed at nopython (nopython mode backend) iterating over 3D array File "paint.py", line 111 [1] During: lowering "$77.2 = iternext(value=$phi77.1)" at paint.py (111) </code></pre> <p>For reference the actual code is <a href="https://github.com/charlieb/paint/blob/master/paint.py" rel="nofollow">here</a></p>
0
2016-09-11T13:44:28Z
39,437,130
<p>It looks like this is just not implemented. </p> <pre><code>In [13]: @numba.njit ...: def f(v): ...: for x in v: ...: y = x ...: return y In [14]: f(np.zeros((2,2,2))) NotImplementedError Traceback (most recent call last) &lt;snip&gt; LoweringError: Failed at nopython (nopython mode backend) iterating over 3D array File "&lt;ipython-input-13-788b4772d1d9&gt;", line 3 [1] During: lowering "$7.2 = iternext(value=$phi7.1)" at &lt;ipython-input-13-788b4772d1d9&gt; (3) </code></pre> <p>Seem to works ok if you loop using the index.</p> <pre><code>In [15]: @numba.njit ...: def f(v): ...: for i in range(len(v)): ...: y = v[i] ...: return y In [16]: f(np.zeros((2,2,2))) Out[16]: array([[ 0., 0.], [ 0., 0.]]) </code></pre>
1
2016-09-11T14:32:59Z
[ "python", "numpy", "numba" ]
Need to make code all modular. Goal is to calculate gross and bonus pay contributions based on user input
39,436,720
<pre><code>#global variable CONTRIBUTION_RATE = 0.05 def main(): #if these are set to 0 they do not calculate contribution but it does run the program. grossPay = 0 bonusPay = 0 #gets gross pay from input GetGrossPay(grossPay) #gets bonus pay from input GetBonusPay(bonusPay) #takes input from GetGrossPay to calculate contrib showGrossPayContrib(grossPay) #takes input from GetBonusPay to calculate contrib showBonusContrib(bonusPay) #This will prompt user to enter gross pay def GetGrossPay(grossPay): grossPay = float(input("Enter the total gross pay: ")) return grossPay #This will prompt user to enter bonus pay def GetBonusPay(bonusPay): bonusPay = float(input("Enter the total bonus pay: ")) return bonusPay #This SHOULD take the grossPay from GetGrossPay module to get GrossPayContrib def showGrossPayContrib(theGrossPay): theGrossPay = CONTRIBUTION_RATE * theGrossPay print("The contribution for the gross pay is $ ",theGrossPay) #This SHOULD take the bonusPay from GetBonusPay module to get BonusContrib def showBonusContrib(theBonus): theBonus = CONTRIBUTION_RATE * theBonus print("The contribution for the bonuses is $ ",theBonus) main() </code></pre>
1
2016-09-11T13:44:35Z
39,436,954
<p>Should be what you're looking for. Try this</p> <pre><code>#global variable CONTRIBUTION_RATE = 0.05 def main(): gross = GetGrossPay() bonus = GetBonusPay() sum = GetSumContribution(gross, bonus) showGrossPayContrib(gross) showBonusContrib(bonus) showSumContrib(sum) def GetGrossPay(): #as it stands there is no reason to pass a variable in return float(input("Enter the total gross pay: ")) def GetBonusPay(): return float(input("Enter the total bonus pay: ")) def GetSumContribution(gross, bonus): return sum((gross*CONTRIBUTION_RATE, bonus*CONTRIBUTION_RATE)) def showGrossPayContrib(theGrossPay): theGrossPay = CONTRIBUTION_RATE * theGrossPay print("The contribution for the gross pay is $ ",theGrossPay) def showBonusContrib(theBonus): theBonus = CONTRIBUTION_RATE * theBonus print("The contribution for the bonuses is $ ",theBonus) def showSumContrib(sumContrib): print("The sum of the Bonus and Gross contributions is ${}".format(sumContrib)) main() </code></pre>
0
2016-09-11T14:11:45Z
[ "python", "python-3.x", "module", "global-variables" ]
When accessing single element from list of float values, value get's rounded off
39,436,802
<p>My list contains values which are converted to float :</p> <pre><code>time = [1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633, 1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737] </code></pre> <p>But when i do <code>time[0]</code>, the value gets rounded off to 2 decimal places like <code>1472120400.11</code> . How do I retain the original values (upto 3 decimal places for accurate calculations) when accessing single list values?</p> <p>My code:</p> <pre><code>for line in line_collect : a = re.search(rx1,line) time = a.group() newlst.append(float(time)) print newlst print newlst[0] </code></pre> <p>Output:</p> <blockquote> <p>[1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633, 1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737]</p> <p>1472120400.11</p> </blockquote>
2
2016-09-11T13:53:16Z
39,436,862
<p>The list itself doesn't have rounded values. It is the default "print" that shows rounding:</p> <pre><code>&gt;&gt;&gt; time = [1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633, 1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737] &gt;&gt;&gt; time[0] 1472120400.107 &gt;&gt;&gt; print time[0] 1472120400.11 </code></pre> <p>You can get full precision output by printing the <a href="https://docs.python.org/2.7/library/functions.html#func-repr" rel="nofollow"><em>repr</em></a> instead:</p> <pre><code>&gt;&gt;&gt; print repr(time[0]) 1472120400.107 </code></pre>
4
2016-09-11T14:01:33Z
[ "python", "python-2.7" ]
Custom create method to prevent duplicates
39,436,853
<p>I would like to add some logic to my serializer.py.</p> <p>Currently it creates duplicate tags (giving a new ID to the item, but often it will match a tag name already).</p> <h1>In plain english</h1> <pre><code>if exists: # Find the PK that matches the "name" field # "link" the key with Movie Class item else: # Create the "name" inside of Tag class # "link" the key with Movie Class item </code></pre> <h1>The data being posted looks like this:</h1> <pre><code>{ "title": "Test", "tag": [ { "name": "a", "taglevel": 1 } ], "info": [ ] } </code></pre> <h1>Models.py</h1> <pre><code>class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) taglevel = models.IntegerField("Tag level", blank=True) def __str__(self): return self.name class Movie(models.Model): title = models.CharField("Whats happening?", max_length=100, blank=True) tag = models.ManyToManyField('Tag', blank=True) def __str__(self): return self.title </code></pre> <hr> <h2>Serializers</h2> <pre><code>class MovieSerializer(serializers.ModelSerializer): tag = TagSerializer(many=True, read_only=False) class Meta: model = Movie fields = ('title', 'tag', 'info') def create(self, validated_data): tags_data = validated_data.pop('tag') movie = Movie.objects.create(**validated_data) for tag_data in tags_data: movie.tag.create(**tag_data) return movie </code></pre>
0
2016-09-11T14:00:28Z
39,437,063
<p>This will probably solve your issue:</p> <pre><code>tag = Tag.objects.get_or_create(**tag_data)[0] movie.tag.add(tag) </code></pre> <p><code>get_or_create</code> function returns tuple <code>(instance, created)</code>, so you have to get <code>instance</code> with <code>[0]</code>.</p> <p>So the full code is:</p> <pre><code>def create(self, validated_data): tags_data = validated_data.pop('tag') movie = Movie.objects.create(**validated_data) for tag_data in tags_data: tag = Tag.objects.get_or_create(**tag_data)[0] movie.tag.add(tag) return movie </code></pre> <p>To make function case insensitive, you have to do "get or create" manually (the main part is to use <code>__iexact</code> in <code>filter</code>):</p> <pre><code>tag_qs = Tag.objects.filter(name__iexact=tag_data['name']) if tag_qs.exists(): tag = tag_qs.first() else: tag = Tag.objects.create(**tag_data) movie.tag.add(tag) </code></pre>
1
2016-09-11T14:25:22Z
[ "python", "django", "django-rest-framework" ]
Making a list containing string sentences a 2 dimensional list
39,437,036
<p>In python 3, I have a list where each element of this list is a sentence string, for example</p> <pre><code>list = ["the dog ate a bone", "the cat is fat"] </code></pre> <p>How do I split each sentence string into an individual list while keeping everything in the individual list, making it a 2 dimensional list </p> <p>For example...</p> <pre><code>list_2 = [["the", "dog", "ate", "a", "bone"], ["the", "cat", "is", "cat"]] </code></pre>
0
2016-09-11T14:22:21Z
39,437,735
<p>You can simply do the following.Use split() method on each of the value and reassign the value of every index with new comma seperated text</p> <pre><code>mylist=['the dog ate a bone', 'the cat is fat'] print(mylist) def make_two_dimensional(list): counter=0 for value in list: list[counter]= value.split(' ') counter += 1 make_two_dimensional(mylist) print(mylist) </code></pre>
0
2016-09-11T15:33:27Z
[ "python", "list", "dimensional" ]
Making a list containing string sentences a 2 dimensional list
39,437,036
<p>In python 3, I have a list where each element of this list is a sentence string, for example</p> <pre><code>list = ["the dog ate a bone", "the cat is fat"] </code></pre> <p>How do I split each sentence string into an individual list while keeping everything in the individual list, making it a 2 dimensional list </p> <p>For example...</p> <pre><code>list_2 = [["the", "dog", "ate", "a", "bone"], ["the", "cat", "is", "cat"]] </code></pre>
0
2016-09-11T14:22:21Z
39,438,208
<p>You can use list comprehension:</p> <pre><code>list2 = [s.split(' ') for s in list] </code></pre>
2
2016-09-11T16:25:23Z
[ "python", "list", "dimensional" ]
Supporting matplotlib for both python 2 and python 3 on Mac OS X
39,437,057
<p>We're building code that we want to run on both Python 2 &amp; 3. It uses matplotlib. My local machine runs OS X Yosemite. </p> <p>The <a href="http://matplotlib.org/faq/installing_faq.html#os-x-notes" rel="nofollow">matplotlib installation documentation</a> provides instructions for both python 2 &amp; 3, but implies that both cannot be supported on a single Mac. Is this true, and if not how can both be supported with matplotlib?</p> <p>(Parenthetically, I know that separate installations can be made with virtual environments or machines. However, I've found these cumbersome on Macs. On the other hand, I'm also testing builds on a commercial cloud-based build tester that uses separate VMs for each configuration, which works reasonably well.)</p>
0
2016-09-11T14:24:45Z
39,455,644
<p>This appears to work:</p> <blockquote> <p>python 3: install <a href="https://www.python.org/ftp/python/3.5.2/python-3.5.2-macosx10.6.pkg" rel="nofollow">https://www.python.org/ftp/python/3.5.2/python-3.5.2-macosx10.6.pkg</a></p> </blockquote> <pre><code>curl -O https://bootstrap.pypa.io/get-pip.py python3 get-pip.py pip3 install nose pip3 install matplotlib pip3 install cobra pip3 install numpy pip3 install scipy pip3 install openpyxl pip3 install future pip3 install recordtype pip3 install lxml pip3 install python-libsbml </code></pre> <blockquote> <p>python 2: install <a href="https://www.python.org/ftp/python/2.7.12/python-2.7.12-macosx10.6.pkg" rel="nofollow">https://www.python.org/ftp/python/2.7.12/python-2.7.12-macosx10.6.pkg</a></p> </blockquote> <pre><code>curl -O https://bootstrap.pypa.io/get-pip.py python get-pip.py sudo pip2 install nose sudo pip2 install matplotlib sudo pip2 install cobra sudo pip2 install numpy sudo pip2 install scipy sudo pip2 install openpyxl sudo pip2 install future sudo pip2 install recordtype sudo pip2 install lxml sudo pip2 install python-libsbml sudo pip2 uninstall python-dateutil # deal with bug in six; see http://stackoverflow.com/a/27634264/509882 sudo pip2 install python-dateutil==2.2 </code></pre>
0
2016-09-12T17:27:00Z
[ "python", "osx", "matplotlib" ]
Supporting matplotlib for both python 2 and python 3 on Mac OS X
39,437,057
<p>We're building code that we want to run on both Python 2 &amp; 3. It uses matplotlib. My local machine runs OS X Yosemite. </p> <p>The <a href="http://matplotlib.org/faq/installing_faq.html#os-x-notes" rel="nofollow">matplotlib installation documentation</a> provides instructions for both python 2 &amp; 3, but implies that both cannot be supported on a single Mac. Is this true, and if not how can both be supported with matplotlib?</p> <p>(Parenthetically, I know that separate installations can be made with virtual environments or machines. However, I've found these cumbersome on Macs. On the other hand, I'm also testing builds on a commercial cloud-based build tester that uses separate VMs for each configuration, which works reasonably well.)</p>
0
2016-09-11T14:24:45Z
39,455,725
<p>I too find virtualenvs annoying for this sort of thing, and have run into strange issues on OSX virutalenvs with matplotlib in particular. But there is a really nice tool for supporting parallel installations of different package &amp; python versions: <code>conda</code>. It will manage parallel environments with any Python version; for your case you can do the following:</p> <ol> <li><p>Install <a href="http://conda.pydata.org/miniconda.html" rel="nofollow">miniconda</a></p></li> <li><p>Create a Python 3 environment: <code>conda create -n py3env python=3.5 matplotlib</code></p></li> <li><p>Create a Python 2 environment: <code>conda create -n py2env python=2.7 matplotlib</code></p></li> <li><p>Activate the one you want with, e.g. <code>source activate py2env</code></p></li> </ol> <p>And you're ready to go. For more information on conda environments, see the <a href="http://conda.pydata.org/docs/using/envs.html" rel="nofollow">conda-env docs</a>.</p>
1
2016-09-12T17:33:18Z
[ "python", "osx", "matplotlib" ]
How to use chrome extensions with Selenium Webdriver
39,437,064
<p>I want to use one of chrome's extensions inside my python code, how could I do this? Is it possible?</p>
0
2016-09-11T14:25:26Z
39,447,351
<p>I know the solution in Java, hope it will provide you a hint how it can be done in python.</p> <pre><code>ChromeOptions options = new ChromeOptions(); String browserExtension = "path/to/the/extension/name.crx"; options.addExtensions(new File(browserExtension)); WebDriver driver = new ChromeDriver(options); </code></pre>
1
2016-09-12T09:36:13Z
[ "python", "selenium", "selenium-webdriver", "selenium-chromedriver" ]
Using proxy(private) in PhantomJs with python
39,437,106
<p>I am using a private poxy IP with PhatomJS and Python, My code below</p> <pre><code>phantomjs_path = r"phantomjs.exe" service_args = [ '--proxy=MY Private IP', '--proxy-type=socks5', '--proxy-auth=username:password', # I enter real user name and pass here ] browser = webdriver.PhantomJS(executable_path=phantomjs_path,service_args=service_args) browser.get("Any website") # I use any website unblocked on that I.P print(browser.page_source) </code></pre> <p>when I run the bot and I am trying to get the page source</p> <p>But the output for any page is this why?</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> <p>There is no error message shown I don't know what I have missed here?</p> <p>Also tested with sleep function(I thought the page took some time to load)</p>
0
2016-09-11T14:30:20Z
39,447,962
<p>The port number needs to be added here,</p> <pre><code>service_args = [ '--proxy=MY Private IP:port', # See the difference '--proxy-type=socks5', '--proxy-auth=username:password', # I enter real user name and pass here ] </code></pre>
0
2016-09-12T10:10:41Z
[ "python", "selenium", "phantomjs" ]
Curve_fitting data (I'm close to the params values, but curve_fit says optimal parameters not found)
39,437,133
<p>I'm trying to fit the data in <a href="http://www.filedropper.com/aluminio33920umaire" rel="nofollow">this file</a> with <code>curve_fit</code> from scipy in Python. The file contains data points of temperature vs time in celsius and milliseconds. I convert them to kelvin and seconds:</p> <pre><code>thefile = open("aluminio_33920um_aire.txt", "r") data = np.loadtxt(thefile, delimiter='\t', skiprows=1) Temp = data[:, 0] + 273.15 #kelvin Time = data[:, 1]*1e-3 #secs thefile.close() </code></pre> <p>I define a couple of functions to be fitted:</p> <pre><code>def newton(t, a, b, tau): return a + b * np.exp(-t/tau) def dulong(t, ta, dift, f, n): return ta + (dift + (n-1)*t/f)**(1/(1-n)) </code></pre> <p>newton's fitting works perfectly. But dulong does not. I have plotted several values for the parameters of duolong to see which values draw a line that more or less fits the data, and I found the values given here:</p> <pre><code>poptd, pcovd = curve_fit(dulong, Time, Temp, p0=[295, 0.155, 6000, 1.38], sigma=[1]*len(Temp), absolute_sigma=True) </code></pre> <p>However, passing these values <code>p0</code> to curve_fit does not help since I get the error</p> <pre><code>RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 1000. </code></pre> <p>Don't know how to improve since the initial guess of my parameters is a really good guess. I appreciate your help.</p>
2
2016-09-11T14:33:15Z
39,437,586
<p>Your dulong function is highly sensitive to changes in n because of its <code>n^n</code> dependancy. You might want set bounds for it or even keep it as a constant if thats good enough for you.</p> <p>Also, if you are dealing with sufficient small timescales you could consider using a approximating function. If not, try to take the logarithm of your temp data and fit the logarithm of the dulong function. This can be useful if the algorithm takes steps too big when variating n.</p> <p>For debugging purposes you can add a line to your function which prints the parameters passed, that way you will be able to see which parameter is varied by how much and you can work from there. As another measure you can take a look at the minimize function from scipy.optimize, there you will be able to specify more options like solving algorithm and stepwidth to be taken and you can also pass the jacobian to further improve efficiency.</p>
2
2016-09-11T15:17:31Z
[ "python", "scipy", "curve-fitting" ]
Curve_fitting data (I'm close to the params values, but curve_fit says optimal parameters not found)
39,437,133
<p>I'm trying to fit the data in <a href="http://www.filedropper.com/aluminio33920umaire" rel="nofollow">this file</a> with <code>curve_fit</code> from scipy in Python. The file contains data points of temperature vs time in celsius and milliseconds. I convert them to kelvin and seconds:</p> <pre><code>thefile = open("aluminio_33920um_aire.txt", "r") data = np.loadtxt(thefile, delimiter='\t', skiprows=1) Temp = data[:, 0] + 273.15 #kelvin Time = data[:, 1]*1e-3 #secs thefile.close() </code></pre> <p>I define a couple of functions to be fitted:</p> <pre><code>def newton(t, a, b, tau): return a + b * np.exp(-t/tau) def dulong(t, ta, dift, f, n): return ta + (dift + (n-1)*t/f)**(1/(1-n)) </code></pre> <p>newton's fitting works perfectly. But dulong does not. I have plotted several values for the parameters of duolong to see which values draw a line that more or less fits the data, and I found the values given here:</p> <pre><code>poptd, pcovd = curve_fit(dulong, Time, Temp, p0=[295, 0.155, 6000, 1.38], sigma=[1]*len(Temp), absolute_sigma=True) </code></pre> <p>However, passing these values <code>p0</code> to curve_fit does not help since I get the error</p> <pre><code>RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 1000. </code></pre> <p>Don't know how to improve since the initial guess of my parameters is a really good guess. I appreciate your help.</p>
2
2016-09-11T14:33:15Z
39,437,625
<p>When I call <code>curve_fit</code> using the <code>dulong</code> function I get the following warning:</p> <blockquote> <p><code>RuntimeWarning: invalid value encountered in power</code></p> </blockquote> <p>This suggests that, as <code>curve_fit</code> tests various values of the parameters, evaluation of <code>dulong</code> requires computation of the form <code>(negative real)**(real)</code>, which results in a complex number. Hence, the optimization procedure fails. </p> <p>One approach is to restrict the search space of your parameters so that this issue does not occur. Without knowing the physical meaning of the parameters, I can see that, as long as <code>n</code> is greater than <code>1</code> and all other parameters are non-negative, <code>dulong</code> will return only real numbers. </p> <p>Calling <code>curve_fit</code> with a <code>bounds</code> option as described above has no problem finding the optimal parameters.</p> <pre><code>poptd, pcovd = curve_fit(dulong, Time, Temp, p0=[295, 0.155, 6000, 1.38], sigma=[1]*len(Temp), absolute_sigma=True, bounds = ([0,0,0,1],[1000,1,10000,10])) print(poptd) </code></pre> <blockquote> <p><code>[ 304.5965 0.0857 9999.1743 1.5099]</code></p> </blockquote> <p>Here's the plot of the fit</p> <p><a href="http://i.stack.imgur.com/aLg7L.png" rel="nofollow"><img src="http://i.stack.imgur.com/aLg7L.png" alt="enter image description here"></a></p>
2
2016-09-11T15:21:59Z
[ "python", "scipy", "curve-fitting" ]
Curve_fitting data (I'm close to the params values, but curve_fit says optimal parameters not found)
39,437,133
<p>I'm trying to fit the data in <a href="http://www.filedropper.com/aluminio33920umaire" rel="nofollow">this file</a> with <code>curve_fit</code> from scipy in Python. The file contains data points of temperature vs time in celsius and milliseconds. I convert them to kelvin and seconds:</p> <pre><code>thefile = open("aluminio_33920um_aire.txt", "r") data = np.loadtxt(thefile, delimiter='\t', skiprows=1) Temp = data[:, 0] + 273.15 #kelvin Time = data[:, 1]*1e-3 #secs thefile.close() </code></pre> <p>I define a couple of functions to be fitted:</p> <pre><code>def newton(t, a, b, tau): return a + b * np.exp(-t/tau) def dulong(t, ta, dift, f, n): return ta + (dift + (n-1)*t/f)**(1/(1-n)) </code></pre> <p>newton's fitting works perfectly. But dulong does not. I have plotted several values for the parameters of duolong to see which values draw a line that more or less fits the data, and I found the values given here:</p> <pre><code>poptd, pcovd = curve_fit(dulong, Time, Temp, p0=[295, 0.155, 6000, 1.38], sigma=[1]*len(Temp), absolute_sigma=True) </code></pre> <p>However, passing these values <code>p0</code> to curve_fit does not help since I get the error</p> <pre><code>RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 1000. </code></pre> <p>Don't know how to improve since the initial guess of my parameters is a really good guess. I appreciate your help.</p>
2
2016-09-11T14:33:15Z
39,438,046
<p>Since i can't post comments yet, i will instead post another answer as reply to your comment: The big error from the third parameter is likely due to the algorithm not being allowed to assign it a value above 10000. Adjust your bounds and it should work.</p>
0
2016-09-11T16:05:36Z
[ "python", "scipy", "curve-fitting" ]
IndexError after running program multiple times
39,437,142
<p>After running my program that generates passwords multiple times I get an IndexError: list Index out of range. I am not sure what is causing the problem</p> <pre><code>import string import random def random_pass(length): alphabet = list(string.ascii_letters + string.digits + string.punctuation) password = [] upper_case = list(string.ascii_uppercase) count = 0 while count &lt; length: random_num = random.randint(0,len(alphabet)) password.append(alphabet[random_num]) #Checks to see if first character is a uppercase Letter if password[0] not in upper_case: first_letter = random.randint(0,len(upper_case)) password[0] = upper_case[first_letter] count += 1 return ''.join(password) def welcome(): print("*****************************************************************") print("*****************************************************************") def main(): try: get_length = int(input("Please enter the length of your password ")) except ValueError: print("Please enter numbers only") main() else: print("Your {} character password is {}".format(get_length, random_pass(get_length))) restart = input("Do you wish to create another password? y/n") password = [] if restart.lower() == 'y': main() else: exit() main() </code></pre>
-1
2016-09-11T14:34:25Z
39,437,167
<p><code>random.randint</code> can generate the <em>end</em> value as well; you'd need to use <code>random.randrange</code> to generate random numbers in the range that includes the start value and <em>excludes</em> the end.</p>
2
2016-09-11T14:37:39Z
[ "python" ]
IndexError after running program multiple times
39,437,142
<p>After running my program that generates passwords multiple times I get an IndexError: list Index out of range. I am not sure what is causing the problem</p> <pre><code>import string import random def random_pass(length): alphabet = list(string.ascii_letters + string.digits + string.punctuation) password = [] upper_case = list(string.ascii_uppercase) count = 0 while count &lt; length: random_num = random.randint(0,len(alphabet)) password.append(alphabet[random_num]) #Checks to see if first character is a uppercase Letter if password[0] not in upper_case: first_letter = random.randint(0,len(upper_case)) password[0] = upper_case[first_letter] count += 1 return ''.join(password) def welcome(): print("*****************************************************************") print("*****************************************************************") def main(): try: get_length = int(input("Please enter the length of your password ")) except ValueError: print("Please enter numbers only") main() else: print("Your {} character password is {}".format(get_length, random_pass(get_length))) restart = input("Do you wish to create another password? y/n") password = [] if restart.lower() == 'y': main() else: exit() main() </code></pre>
-1
2016-09-11T14:34:25Z
39,439,715
<p>Antti Haapala's answers your question but I see a few things that could be improved in your code. The idea is to make your code clearer.</p> <p>First of all here's my version of your code:</p> <pre><code>import string import random alphabet = string.ascii_letters + string.digits + string.punctuation def random_pass(length): first_character = random.choice(string.ascii_uppercase) password = ''.join(random.choice(alphabet) for x in range(length - 1)) return first_character + password another_password = True while another_password: try: length_requested = int(input("Please enter the length of your password ")) except ValueError: print("Please enter numbers only") another_password = True else: print("Your {} character password is {}".format(length_requested, random_pass(length_requested))) restart = input("Do you wish to create another password (Y/N)? ") another_password = restart.lower() == 'y' </code></pre> <p>The modifications I made of you code:</p> <ul> <li>Since <code>alphabet</code> is never modified, you don't need to recreate it each time you call <code>random_pass()</code>. I have put it in the global scope outside of every functions</li> <li>Since you can access a character inside a string the same way you access an element in a list you don't need to create a list with the content of <code>alphabet</code> or <code>string.ascii_uppercase</code>.</li> <li>You don't gain more understanding defining a variable with the same content of <code>string.ascii_uppercase</code></li> <li>Instead of choosing a random number that you use to choose a character in <code>alphabet</code>, you can directly choose a random character with <a href="https://docs.python.org/3.5/library/random.html#random.choice" rel="nofollow"><code>random.choice(alphabet)</code></a></li> <li>It looks like you have a requirement that the first character of the password has to be an upper case letter. In your code you check this inside your while-loop for each new character but that first character won't change once you set it. So I dragged it outside of this loop. <ul> <li>Since your first character is going to chosen inside <code>string.ascii_uppercase</code>, I used <a href="https://docs.python.org/3.5/library/random.html#random.choice" rel="nofollow"><code>random.choice(string.ascii_uppercase)</code></a> for it.</li> </ul></li> <li>To build the rest of the password, I used a <a href="https://docs.python.org/3.5/tutorial/classes.html#generator-expressions" rel="nofollow">generator expression</a> to choose a random character from <code>alphabet</code> and the <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>.join()</code></a> string method. Since I have already chosen the first character I only need <code>length - 1</code> random characters.</li> <li>You don't need to define <code>main()</code> if all you do is call it later. <ul> <li>Even if you define <code>main()</code> it's not a good idea to call it recursively because for every new password requested (and every time an invalid input is entered by the user), your code has to create a new small scope environment for this function call and, more importantly, it has to keep of all previous small scope environment. You risk exhausting memory eventually. I have used instead a while-loop.</li> </ul></li> <li><code>restart.lower() == 'y'</code> will give a boolean value I have used to change <code>another_password</code> which controls whether we continue to ask the user if it wants a new password</li> <li>You don't need to call <code>exit()</code> unless you want to return an exit code to the environment.</li> </ul> <p>If you have more questions, don't hesitate to ask. And continue experimenting.</p>
0
2016-09-11T19:12:05Z
[ "python" ]
pandas new dataframe based on number of occurences
39,437,171
<p>I want to create a new dataframe that only contains the rows that occurred the most:</p> <p>My code is below:</p> <pre><code>import pandas as pd f1=pd.read_csv('FILE1.csv') f2=pd.read_csv('FILE2.csv') df_all = f2.merge(f1, how='left', on='Symbol') df_sort = df_all.sort_values(by=['Symbol','Date'], ascending=[True,True]) df_sort=df_sort.dropna() df_cnt=df_sort['Symbol'].value_counts() </code></pre> <p>original data from 2 files gets merged into df_all:</p> <pre><code>In[1]: f1 Out[2]: Symbol Weight 0 IBM 0.2 1 GE 0.3 2 AAPL 0.4 3 XOM 0.1 In[2]: f2 Out[3]: Date Symbol ClosingPrice 0 3/1/2010 IBM 116.51 1 3/2/2010 IBM 117.32 2 3/3/2010 IBM 116.40 3 3/4/2010 IBM 116.58 4 3/5/2010 IBM 117.61 5 3/1/2010 GE 45.00 6 3/2/2010 GE 43.50 7 3/3/2010 GE 46.00 8 3/1/2010 AAPL 85.07 9 3/2/2010 AAPL 85.10 10 3/3/2010 AAPL 86.20 11 3/4/2010 AAPL 84.93 12 3/5/2010 AAPL 84.80 13 3/1/2010 XOM 98.15 14 3/2/2010 XOM 99.00 15 3/3/2010 XOM 98.23 16 3/4/2010 XOM 97.56 17 3/1/2010 MSFT 99.00 18 3/2/2010 MSFT 98.00 19 3/3/2010 MSFT 97.00 20 3/4/2010 MSFT 98.00 21 3/5/2010 MSFT 97.00 In[4]:df_all Out[4]: Date Symbol ClosingPrice Weight 0 3/1/2010 IBM 116.51 0.2 1 3/2/2010 IBM 117.32 0.2 2 3/3/2010 IBM 116.40 0.2 3 3/4/2010 IBM 116.58 0.2 4 3/5/2010 IBM 117.61 0.2 5 3/1/2010 GE 45.00 0.3 6 3/2/2010 GE 43.50 0.3 7 3/3/2010 GE 46.00 0.3 8 3/1/2010 AAPL 85.07 0.4 9 3/2/2010 AAPL 85.10 0.4 10 3/3/2010 AAPL 86.20 0.4 11 3/4/2010 AAPL 84.93 0.4 12 3/5/2010 AAPL 84.80 0.4 13 3/1/2010 XOM 98.15 0.1 14 3/2/2010 XOM 99.00 0.1 15 3/3/2010 XOM 98.23 0.1 16 3/4/2010 XOM 97.56 0.1 17 3/1/2010 MSFT 99.00 NaN 18 3/2/2010 MSFT 98.00 NaN 19 3/3/2010 MSFT 97.00 NaN 20 3/4/2010 MSFT 98.00 NaN 21 3/5/2010 MSFT 97.00 NaN </code></pre> <p>I then sort the data with the NaN values removed:</p> <pre><code>In[5]: df_sort Out[5]: Date Symbol ClosingPrice Weight 8 3/1/2010 AAPL 85.07 0.4 9 3/2/2010 AAPL 85.10 0.4 10 3/3/2010 AAPL 86.20 0.4 11 3/4/2010 AAPL 84.93 0.4 12 3/5/2010 AAPL 84.80 0.4 5 3/1/2010 GE 45.00 0.3 6 3/2/2010 GE 43.50 0.3 7 3/3/2010 GE 46.00 0.3 0 3/1/2010 IBM 116.51 0.2 1 3/2/2010 IBM 117.32 0.2 2 3/3/2010 IBM 116.40 0.2 3 3/4/2010 IBM 116.58 0.2 4 3/5/2010 IBM 117.61 0.2 13 3/1/2010 XOM 98.15 0.1 14 3/2/2010 XOM 99.00 0.1 15 3/3/2010 XOM 98.23 0.1 16 3/4/2010 XOM 97.56 0.1 </code></pre> <p>I then determine the total number of occurrences of each Symbol</p> <pre><code>In[6]: df_cnt Out[6]: AAPL 5 IBM 5 XOM 4 GE 3 Name: Symbol, dtype: int64 </code></pre> <p>At this point I am stuck as to how to create a new dataframe, df_final, which contains only the data where the number of occurrences is at the max number. . . in this case 5.</p> <p>My final dataframe should look like this:</p> <pre><code> Date Symbol ClosingPrice Weight 3/1/2010 AAPL 85.07 0.4 3/2/2010 AAPL 85.10 0.4 3/3/2010 AAPL 86.20 0.4 3/4/2010 AAPL 84.93 0.4 3/5/2010 AAPL 84.80 0.4 3/1/2010 IBM 116.51 0.2 3/2/2010 IBM 117.32 0.2 3/3/2010 IBM 116.40 0.2 3/4/2010 IBM 116.58 0.2 3/5/2010 IBM 117.61 0.2 </code></pre>
1
2016-09-11T14:37:47Z
39,437,306
<p>You can find out the <code>Symbol</code> with maximum group size from <code>df_cnt</code> and filter rows from <code>df_sort</code>:</p> <pre><code>df_sort[df_sort.Symbol.isin(df_cnt.index[df_cnt == df_cnt.max()])] # Date Symbol ClosingPrice Weight # 8 3/1/2010 AAPL 85.07 0.4 # 9 3/2/2010 AAPL 85.10 0.4 #10 3/3/2010 AAPL 86.20 0.4 #11 3/4/2010 AAPL 84.93 0.4 #12 3/5/2010 AAPL 84.80 0.4 # 0 3/1/2010 IBM 116.51 0.2 # 1 3/2/2010 IBM 117.32 0.2 # 2 3/3/2010 IBM 116.40 0.2 # 3 3/4/2010 IBM 116.58 0.2 # 4 3/5/2010 IBM 117.61 0.2 </code></pre>
2
2016-09-11T14:50:45Z
[ "python", "pandas", "dataframe", "slice" ]
pandas new dataframe based on number of occurences
39,437,171
<p>I want to create a new dataframe that only contains the rows that occurred the most:</p> <p>My code is below:</p> <pre><code>import pandas as pd f1=pd.read_csv('FILE1.csv') f2=pd.read_csv('FILE2.csv') df_all = f2.merge(f1, how='left', on='Symbol') df_sort = df_all.sort_values(by=['Symbol','Date'], ascending=[True,True]) df_sort=df_sort.dropna() df_cnt=df_sort['Symbol'].value_counts() </code></pre> <p>original data from 2 files gets merged into df_all:</p> <pre><code>In[1]: f1 Out[2]: Symbol Weight 0 IBM 0.2 1 GE 0.3 2 AAPL 0.4 3 XOM 0.1 In[2]: f2 Out[3]: Date Symbol ClosingPrice 0 3/1/2010 IBM 116.51 1 3/2/2010 IBM 117.32 2 3/3/2010 IBM 116.40 3 3/4/2010 IBM 116.58 4 3/5/2010 IBM 117.61 5 3/1/2010 GE 45.00 6 3/2/2010 GE 43.50 7 3/3/2010 GE 46.00 8 3/1/2010 AAPL 85.07 9 3/2/2010 AAPL 85.10 10 3/3/2010 AAPL 86.20 11 3/4/2010 AAPL 84.93 12 3/5/2010 AAPL 84.80 13 3/1/2010 XOM 98.15 14 3/2/2010 XOM 99.00 15 3/3/2010 XOM 98.23 16 3/4/2010 XOM 97.56 17 3/1/2010 MSFT 99.00 18 3/2/2010 MSFT 98.00 19 3/3/2010 MSFT 97.00 20 3/4/2010 MSFT 98.00 21 3/5/2010 MSFT 97.00 In[4]:df_all Out[4]: Date Symbol ClosingPrice Weight 0 3/1/2010 IBM 116.51 0.2 1 3/2/2010 IBM 117.32 0.2 2 3/3/2010 IBM 116.40 0.2 3 3/4/2010 IBM 116.58 0.2 4 3/5/2010 IBM 117.61 0.2 5 3/1/2010 GE 45.00 0.3 6 3/2/2010 GE 43.50 0.3 7 3/3/2010 GE 46.00 0.3 8 3/1/2010 AAPL 85.07 0.4 9 3/2/2010 AAPL 85.10 0.4 10 3/3/2010 AAPL 86.20 0.4 11 3/4/2010 AAPL 84.93 0.4 12 3/5/2010 AAPL 84.80 0.4 13 3/1/2010 XOM 98.15 0.1 14 3/2/2010 XOM 99.00 0.1 15 3/3/2010 XOM 98.23 0.1 16 3/4/2010 XOM 97.56 0.1 17 3/1/2010 MSFT 99.00 NaN 18 3/2/2010 MSFT 98.00 NaN 19 3/3/2010 MSFT 97.00 NaN 20 3/4/2010 MSFT 98.00 NaN 21 3/5/2010 MSFT 97.00 NaN </code></pre> <p>I then sort the data with the NaN values removed:</p> <pre><code>In[5]: df_sort Out[5]: Date Symbol ClosingPrice Weight 8 3/1/2010 AAPL 85.07 0.4 9 3/2/2010 AAPL 85.10 0.4 10 3/3/2010 AAPL 86.20 0.4 11 3/4/2010 AAPL 84.93 0.4 12 3/5/2010 AAPL 84.80 0.4 5 3/1/2010 GE 45.00 0.3 6 3/2/2010 GE 43.50 0.3 7 3/3/2010 GE 46.00 0.3 0 3/1/2010 IBM 116.51 0.2 1 3/2/2010 IBM 117.32 0.2 2 3/3/2010 IBM 116.40 0.2 3 3/4/2010 IBM 116.58 0.2 4 3/5/2010 IBM 117.61 0.2 13 3/1/2010 XOM 98.15 0.1 14 3/2/2010 XOM 99.00 0.1 15 3/3/2010 XOM 98.23 0.1 16 3/4/2010 XOM 97.56 0.1 </code></pre> <p>I then determine the total number of occurrences of each Symbol</p> <pre><code>In[6]: df_cnt Out[6]: AAPL 5 IBM 5 XOM 4 GE 3 Name: Symbol, dtype: int64 </code></pre> <p>At this point I am stuck as to how to create a new dataframe, df_final, which contains only the data where the number of occurrences is at the max number. . . in this case 5.</p> <p>My final dataframe should look like this:</p> <pre><code> Date Symbol ClosingPrice Weight 3/1/2010 AAPL 85.07 0.4 3/2/2010 AAPL 85.10 0.4 3/3/2010 AAPL 86.20 0.4 3/4/2010 AAPL 84.93 0.4 3/5/2010 AAPL 84.80 0.4 3/1/2010 IBM 116.51 0.2 3/2/2010 IBM 117.32 0.2 3/3/2010 IBM 116.40 0.2 3/4/2010 IBM 116.58 0.2 3/5/2010 IBM 117.61 0.2 </code></pre>
1
2016-09-11T14:37:47Z
39,437,401
<p>You could try</p> <pre><code> df_sort[df_sort.Symbol.isin(df_cnt[df_cnt &gt;= df_cnt.max()].index)] </code></pre> <ul> <li><p><code>df_cnt.max()</code> is the maximum value of <code>df_cnt</code>.</p></li> <li><p><code>df_cnt[df_cnt &gt;= df_cnt.max()].index</code> is the index of all the items whose count was at least the max.</p></li> <li><p>Now just check which entries in the <code>Symbol</code> column are in the result.</p></li> </ul>
1
2016-09-11T15:00:30Z
[ "python", "pandas", "dataframe", "slice" ]
pandas new dataframe based on number of occurences
39,437,171
<p>I want to create a new dataframe that only contains the rows that occurred the most:</p> <p>My code is below:</p> <pre><code>import pandas as pd f1=pd.read_csv('FILE1.csv') f2=pd.read_csv('FILE2.csv') df_all = f2.merge(f1, how='left', on='Symbol') df_sort = df_all.sort_values(by=['Symbol','Date'], ascending=[True,True]) df_sort=df_sort.dropna() df_cnt=df_sort['Symbol'].value_counts() </code></pre> <p>original data from 2 files gets merged into df_all:</p> <pre><code>In[1]: f1 Out[2]: Symbol Weight 0 IBM 0.2 1 GE 0.3 2 AAPL 0.4 3 XOM 0.1 In[2]: f2 Out[3]: Date Symbol ClosingPrice 0 3/1/2010 IBM 116.51 1 3/2/2010 IBM 117.32 2 3/3/2010 IBM 116.40 3 3/4/2010 IBM 116.58 4 3/5/2010 IBM 117.61 5 3/1/2010 GE 45.00 6 3/2/2010 GE 43.50 7 3/3/2010 GE 46.00 8 3/1/2010 AAPL 85.07 9 3/2/2010 AAPL 85.10 10 3/3/2010 AAPL 86.20 11 3/4/2010 AAPL 84.93 12 3/5/2010 AAPL 84.80 13 3/1/2010 XOM 98.15 14 3/2/2010 XOM 99.00 15 3/3/2010 XOM 98.23 16 3/4/2010 XOM 97.56 17 3/1/2010 MSFT 99.00 18 3/2/2010 MSFT 98.00 19 3/3/2010 MSFT 97.00 20 3/4/2010 MSFT 98.00 21 3/5/2010 MSFT 97.00 In[4]:df_all Out[4]: Date Symbol ClosingPrice Weight 0 3/1/2010 IBM 116.51 0.2 1 3/2/2010 IBM 117.32 0.2 2 3/3/2010 IBM 116.40 0.2 3 3/4/2010 IBM 116.58 0.2 4 3/5/2010 IBM 117.61 0.2 5 3/1/2010 GE 45.00 0.3 6 3/2/2010 GE 43.50 0.3 7 3/3/2010 GE 46.00 0.3 8 3/1/2010 AAPL 85.07 0.4 9 3/2/2010 AAPL 85.10 0.4 10 3/3/2010 AAPL 86.20 0.4 11 3/4/2010 AAPL 84.93 0.4 12 3/5/2010 AAPL 84.80 0.4 13 3/1/2010 XOM 98.15 0.1 14 3/2/2010 XOM 99.00 0.1 15 3/3/2010 XOM 98.23 0.1 16 3/4/2010 XOM 97.56 0.1 17 3/1/2010 MSFT 99.00 NaN 18 3/2/2010 MSFT 98.00 NaN 19 3/3/2010 MSFT 97.00 NaN 20 3/4/2010 MSFT 98.00 NaN 21 3/5/2010 MSFT 97.00 NaN </code></pre> <p>I then sort the data with the NaN values removed:</p> <pre><code>In[5]: df_sort Out[5]: Date Symbol ClosingPrice Weight 8 3/1/2010 AAPL 85.07 0.4 9 3/2/2010 AAPL 85.10 0.4 10 3/3/2010 AAPL 86.20 0.4 11 3/4/2010 AAPL 84.93 0.4 12 3/5/2010 AAPL 84.80 0.4 5 3/1/2010 GE 45.00 0.3 6 3/2/2010 GE 43.50 0.3 7 3/3/2010 GE 46.00 0.3 0 3/1/2010 IBM 116.51 0.2 1 3/2/2010 IBM 117.32 0.2 2 3/3/2010 IBM 116.40 0.2 3 3/4/2010 IBM 116.58 0.2 4 3/5/2010 IBM 117.61 0.2 13 3/1/2010 XOM 98.15 0.1 14 3/2/2010 XOM 99.00 0.1 15 3/3/2010 XOM 98.23 0.1 16 3/4/2010 XOM 97.56 0.1 </code></pre> <p>I then determine the total number of occurrences of each Symbol</p> <pre><code>In[6]: df_cnt Out[6]: AAPL 5 IBM 5 XOM 4 GE 3 Name: Symbol, dtype: int64 </code></pre> <p>At this point I am stuck as to how to create a new dataframe, df_final, which contains only the data where the number of occurrences is at the max number. . . in this case 5.</p> <p>My final dataframe should look like this:</p> <pre><code> Date Symbol ClosingPrice Weight 3/1/2010 AAPL 85.07 0.4 3/2/2010 AAPL 85.10 0.4 3/3/2010 AAPL 86.20 0.4 3/4/2010 AAPL 84.93 0.4 3/5/2010 AAPL 84.80 0.4 3/1/2010 IBM 116.51 0.2 3/2/2010 IBM 117.32 0.2 3/3/2010 IBM 116.40 0.2 3/4/2010 IBM 116.58 0.2 3/5/2010 IBM 117.61 0.2 </code></pre>
1
2016-09-11T14:37:47Z
39,437,464
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> for this purpose.</p> <pre><code>df_sort[df_sort['Symbol'].map(df_cnt==df_cnt.max())] Date Symbol ClosingPrice Weight 8 3/1/2010 AAPL 85.07 0.4 9 3/2/2010 AAPL 85.10 0.4 10 3/3/2010 AAPL 86.20 0.4 11 3/4/2010 AAPL 84.93 0.4 12 3/5/2010 AAPL 84.80 0.4 0 3/1/2010 IBM 116.51 0.2 1 3/2/2010 IBM 117.32 0.2 2 3/3/2010 IBM 116.40 0.2 3 3/4/2010 IBM 116.58 0.2 4 3/5/2010 IBM 117.61 0.2 </code></pre>
1
2016-09-11T15:06:32Z
[ "python", "pandas", "dataframe", "slice" ]
How to display parent model with its child model in a template
39,437,207
<p>Here is my structure:</p> <p><strong>model.py</strong></p> <pre><code>class Doctor(models.Model): name = models.CharField(max_length=50) room_no = models.IntegerField() floor_no = models.IntegerField() contact_no = models.CharField(max_length=50, blank=True, null=True) notes = models.CharField(max_length=70, blank=True, null=True) class Meta: managed = False db_table = 'doctor' class DoctorSpecialization(models.Model): doc = models.ForeignKey(Doctor, models.DO_NOTHING) spec = models.ForeignKey('Specialization', models.DO_NOTHING) class Meta: managed = False db_table = 'doctor_specialization' class Specialization(models.Model): title = models.CharField(unique=True, max_length=45) class Meta: managed = False db_table = 'specialization' </code></pre> <p>I would like to display this on my template just like on this post: <a href="http://stackoverflow.com/questions/30435949/in-django-how-to-display-parent-model-data-with-child-model-data-in-change-list">In django How to display parent model data with child model data in change list view?</a></p> <pre><code>Internal Medicine - Joanne Doe M.D. - Andrew Fuller M.D. - Nancy Davolio M.D. OB-Gyne - John Doe M.D. - Janet Leverling M.D. ENT - Margaret Peacock M.D. - Steven Buchanan M.D. - Laura Callahan M.D. - Michael Suyama M.D. </code></pre> <p><strong>But the problem is i have many to many relationship structure. I am new to django please your help is highly appreciated.</strong></p>
0
2016-09-11T14:41:02Z
39,437,499
<p>You have to render your structure with</p> <pre><code>doctors = {} for spec in Specialization.objects.all(): doctors[spec.title] = [doc_spec.doc.name for doc_spec in DoctorSpecialization.objects.filter(spec=spec)] </code></pre> <p>then pass this dict to template:</p> <pre><code>from django.template import Context, loader template = loader.get_template('&lt;path_to_your_template&gt;') context = Context({"doctors": doctors}) template.render(context) </code></pre> <p>or you can use <a href="https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render" rel="nofollow"><code>render</code></a> shortcut for this part:</p> <pre><code>render(request, '&lt;path_to_your_template&gt;', {"doctors": doctors}) </code></pre> <p>and render it using double <code>for</code> loop:</p> <pre><code>{% for title, doc_list in doctors.items %} &lt;strong&gt;{{ title }}:&lt;/strong&gt;&lt;br&gt; &lt;ul&gt; {% for doc in doc_list %} &lt;li&gt;{{ doc }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endfor %} </code></pre>
0
2016-09-11T15:09:40Z
[ "python", "django", "django-models" ]
What purpose does [0] serve in numpy.where(y_euler<0.0)[0]
39,437,226
<p>Also what is the difference between this:</p> <pre><code>idx_negative_euler = numpy.where(y_euler&lt;0.0)[0] </code></pre> <p>and this:</p> <pre><code>idx_negative_euler = numpy.where(y_euler&lt;0.0)[0][0] </code></pre> <p>I realize that this returns an array of indices where the array <code>y_euler</code> is negative, however I simply can't figure out what the <code>[0]</code> or the <code>[0][0]</code> at the end of the line is supposed to do.</p> <p>I couldn't find any documentation regarding this (I'm not even sure what to search for). I've already looked into the <code>numpy.where</code> documentation but that didn't help.</p>
-3
2016-09-11T14:42:41Z
39,437,744
<p><code>[0]</code> means "get the first item of the sequence." For example if you had this list:</p> <pre><code>x = [5, 7, 9] </code></pre> <p>Then <code>x[0]</code> would be the first item of that sequence: 5.</p> <p><code>numpy.where()</code> returns a sequence. Putting <code>[0]</code> on the end of that expression gets the first item in that sequence.</p> <p><code>[0][0]</code> means "get the first item in the sequence (which is itself also a sequence), and then get the first item in <em>that</em> sequence". So if <code>numpy.where()</code> returned a list of lists, <code>[0][0]</code> would get the first item in the first list.</p>
0
2016-09-11T15:34:08Z
[ "python", "arrays", "numpy" ]
What purpose does [0] serve in numpy.where(y_euler<0.0)[0]
39,437,226
<p>Also what is the difference between this:</p> <pre><code>idx_negative_euler = numpy.where(y_euler&lt;0.0)[0] </code></pre> <p>and this:</p> <pre><code>idx_negative_euler = numpy.where(y_euler&lt;0.0)[0][0] </code></pre> <p>I realize that this returns an array of indices where the array <code>y_euler</code> is negative, however I simply can't figure out what the <code>[0]</code> or the <code>[0][0]</code> at the end of the line is supposed to do.</p> <p>I couldn't find any documentation regarding this (I'm not even sure what to search for). I've already looked into the <code>numpy.where</code> documentation but that didn't help.</p>
-3
2016-09-11T14:42:41Z
39,438,221
<p>Make a simple 1d array:</p> <pre><code>In [60]: x=np.array([0,1,-1,2,-1,0]) </code></pre> <p>Where returns a tuple <code>(...,)</code> of arrays, one for each dimension:</p> <pre><code>In [61]: np.where(x&lt;0) Out[61]: (array([2, 4], dtype=int32),) </code></pre> <p>pull the first (here only) element from the tuple</p> <pre><code>In [62]: np.where(x&lt;0)[0] Out[62]: array([2, 4], dtype=int32) </code></pre> <p>get the first element of the indexing array</p> <pre><code>In [63]: np.where(x&lt;0)[0][0] Out[63]: 2 </code></pre> <p>the whole tuple returned by <code>where</code> can be used to index the array. </p> <pre><code>In [64]: x[np.where(x&lt;0)] Out[64]: array([-1, -1]) </code></pre> <p><code>x[2,4]</code>, <code>x[([2,4],)]</code> do the same indexing.</p> <p>The usefulness of the <code>tuple</code> value becomes more obvious when working on a 2d or higher dim array. In that case <code>np.where(...)[0]</code> would give the 'rows' index array. But the <code>where(...)[0]</code> is most common in the 1d case where the tuple layer usually isn't needed.</p>
0
2016-09-11T16:26:44Z
[ "python", "arrays", "numpy" ]
How do you extract the floats from the elements in a python list?
39,437,366
<p>I am using BeautifulSoup4 to build a script that does financial calculations. I have successfully extracted data to a list, but only need the float numbers from the elements.</p> <p>For Example:</p> <pre><code>Volume = soup.find_all('td', {'class':'text-success'}) print (Volume) </code></pre> <p>This gives me the list output of:</p> <pre><code>[&lt;td class="text-success"&gt;+1.3 LTC&lt;/td&gt;, &lt;td class="text- success"&gt;+5.49&lt;span class="muteds"&gt;340788&lt;/span&gt; LTC&lt;/td&gt;, &lt;td class="text-success"&gt;+1.3 LTC&lt;/td&gt;,] </code></pre> <p>I want it to become:</p> <pre><code>[1.3, 5.49, 1.3] </code></pre> <p>How can I do this?</p> <p>Thank-you so much for reading my post I greatly appreciate any help I can get.</p>
2
2016-09-11T14:56:32Z
39,437,400
<p>You can do</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.findall("\d+\.\d+", yourString) ['1.3', '5.49', '1.3'] &gt;&gt;&gt; </code></pre> <p>Then to convert to floats</p> <pre><code>&gt;&gt;&gt; [float(x) for x in re.findall("\d+\.\d+", yourString)] [1.3, 5.49, 1.3] &gt;&gt;&gt; </code></pre>
1
2016-09-11T15:00:30Z
[ "python", "regex", "beautifulsoup" ]
How do you extract the floats from the elements in a python list?
39,437,366
<p>I am using BeautifulSoup4 to build a script that does financial calculations. I have successfully extracted data to a list, but only need the float numbers from the elements.</p> <p>For Example:</p> <pre><code>Volume = soup.find_all('td', {'class':'text-success'}) print (Volume) </code></pre> <p>This gives me the list output of:</p> <pre><code>[&lt;td class="text-success"&gt;+1.3 LTC&lt;/td&gt;, &lt;td class="text- success"&gt;+5.49&lt;span class="muteds"&gt;340788&lt;/span&gt; LTC&lt;/td&gt;, &lt;td class="text-success"&gt;+1.3 LTC&lt;/td&gt;,] </code></pre> <p>I want it to become:</p> <pre><code>[1.3, 5.49, 1.3] </code></pre> <p>How can I do this?</p> <p>Thank-you so much for reading my post I greatly appreciate any help I can get.</p>
2
2016-09-11T14:56:32Z
39,437,404
<p>You can find the first text node inside every <code>td</code>, split it by space, get the first item and convert it to <code>float</code> via <code>float()</code> - the <code>+</code> would be handled automatically:</p> <pre><code>from bs4 import BeautifulSoup data = """ &lt;table&gt; &lt;tr&gt; &lt;td class="text-success"&gt;+1.3 LTC&lt;/td&gt; &lt;td class="text-success"&gt;+5.49&lt;span class="muteds"&gt;340788&lt;/span&gt; LTC&lt;/td&gt; &lt;td class="text-success"&gt;+1.3 LTC&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;""" soup = BeautifulSoup(data, "html.parser") print([ float(td.find(text=True).split(" ", 1)[0]) for td in soup.find_all('td', {'class':'text-success'}) ]) </code></pre> <p>Prints <code>[1.3, 5.49, 1.3]</code>.</p> <p>Note how the <code>find(text=True)</code> helps to avoid extracting the <code>340788</code> in the second <code>td</code>.</p>
2
2016-09-11T15:00:54Z
[ "python", "regex", "beautifulsoup" ]
Pandas Dataframe Transpose
39,437,387
<p>I have tried to find something that could help me but I couldn't. I'd appreciate if someone could link me to it, if my question is already answered.</p> <p>I have a pandas dataframe that has row-wise features. For example:</p> <pre><code> Patient_ID Feature_Id Feature_Value 0 3 10 0.30 1 3 50 0.20 2 3 60 1.00 3 4 10 0.25 </code></pre> <p>I need to convert them into column-wise features(essentially columns in Pandas) -- something like below:</p> <pre><code>Patient_Id 10 50 60 3 0.30 0.2 1.0 4 0.25 Nan Nan </code></pre>
1
2016-09-11T14:59:00Z
39,437,442
<p>You could try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pd.pivot_table</code></a></p> <pre><code>In [16]: pd.pivot_table(df, index='Patient_ID', values='Feature_Value', columns='Feature_ID') Out[16]: Feature_ID 10 50 60 Patient_ID 3 0.30 0.2 1.0 4 0.25 NaN NaN </code></pre> <p>Note that if you need to specify what to do if more than a single entry exists (which you don't have in your example), you can use the <code>aggfunc</code> parameter (the default is to calculate the mean).</p>
1
2016-09-11T15:04:37Z
[ "python", "pandas" ]
IndexError: string index out of range?
39,437,396
<p>I keep getting an <code>IndexError: string index out of range</code> exception on the following code and I cannot figure out why.</p> <p>I am supposed to solve the following problem recursively.</p> <blockquote> <p>Finally, write <code>transcribe( S )</code>. Here is its description:</p> <p>In an incredible molecular feat called transcription, your cells create molecules of messenger RNA that mirror the sequence of nucleotides in your DNA. The RNA is then used to create proteins that do the work of the cell. Write a recursive function <code>transcribe( S )</code>, which should take as input a string <code>S</code>, which will have DNA nucleotides (capital letter As, Cs, Gs, and Ts). There may be other characters, too, though they will be ignored by your transcribe function—these might be spaces or other characters that are not really DNA nucleotides.</p> <p>Then, transcribe should return as output the messenger RNA that would be produced from that string S. The correct output simply uses replacement:</p> <p>As in the input become Us in the output.<br> Cs in the input become Gs in the output.<br> Gs in the input become Cs in the output.<br> Ts in the input become As in the output.<br> any other input characters should disappear from the output altogether</p> </blockquote> <pre><code>def transcribe( S ): tran = '' * len(S) if S[0] == 'A': tran = tran + 'U' + transcribe( S[1:] ) return tran elif S[0] == 'C': tran = tran + 'G' + transcribe( S[1:] ) return tran elif S[0] == 'G': tran = tran + 'C' + transcribe( S[1:] ) return tran elif S[0] == 'T': tran = tran + 'A' + transcribe( S[1:] ) return tran else: return "" print transcribe('GATTACA') </code></pre>
1
2016-09-11T14:59:46Z
39,437,408
<p>Trying to index with <code>[0]</code> into an <em>empty string</em> raises an <code>IndexError</code>.</p> <p>You need to test if the string is empty <em>first</em>, as eventually <code>S[1:]</code> will pass an empty sting into <code>transcribe()</code>:</p> <pre><code>if not S: return '' </code></pre> <p>You should drop the <code>tran</code> string altogether; that is <em>always</em> an empty string. <code>'' * &lt;any number&gt;</code> is still <code>''</code>.</p> <p>Rather than test each possible letter in a separate <code>if</code> statement, use a dictionary to map one character to another:</p> <pre><code>mapping = {'A': 'U', 'C': 'G', 'G': 'C', 'T': 'A'} def transcribe(S): if not S: return '' replacement = mapping.get(S[0], '') # default is empty return replacement + transcribe(S[1:]) </code></pre>
3
2016-09-11T15:01:21Z
[ "python", "python-2.7" ]
IndexError: string index out of range?
39,437,396
<p>I keep getting an <code>IndexError: string index out of range</code> exception on the following code and I cannot figure out why.</p> <p>I am supposed to solve the following problem recursively.</p> <blockquote> <p>Finally, write <code>transcribe( S )</code>. Here is its description:</p> <p>In an incredible molecular feat called transcription, your cells create molecules of messenger RNA that mirror the sequence of nucleotides in your DNA. The RNA is then used to create proteins that do the work of the cell. Write a recursive function <code>transcribe( S )</code>, which should take as input a string <code>S</code>, which will have DNA nucleotides (capital letter As, Cs, Gs, and Ts). There may be other characters, too, though they will be ignored by your transcribe function—these might be spaces or other characters that are not really DNA nucleotides.</p> <p>Then, transcribe should return as output the messenger RNA that would be produced from that string S. The correct output simply uses replacement:</p> <p>As in the input become Us in the output.<br> Cs in the input become Gs in the output.<br> Gs in the input become Cs in the output.<br> Ts in the input become As in the output.<br> any other input characters should disappear from the output altogether</p> </blockquote> <pre><code>def transcribe( S ): tran = '' * len(S) if S[0] == 'A': tran = tran + 'U' + transcribe( S[1:] ) return tran elif S[0] == 'C': tran = tran + 'G' + transcribe( S[1:] ) return tran elif S[0] == 'G': tran = tran + 'C' + transcribe( S[1:] ) return tran elif S[0] == 'T': tran = tran + 'A' + transcribe( S[1:] ) return tran else: return "" print transcribe('GATTACA') </code></pre>
1
2016-09-11T14:59:46Z
39,438,384
<p>Here's something a bit closer to your original:</p> <pre><code>def transcribe( S ): if S == '': return '' elif S[0] == 'A': return 'U' + transcribe( S[1:] ) elif S[0] == 'C': return 'G' + transcribe( S[1:] ) elif S[0] == 'G': return 'C' + transcribe( S[1:] ) elif S[0] == 'T': return 'A' + transcribe( S[1:] ) else: return transcribe( S[1:] ) print transcribe('GATTACA') </code></pre>
0
2016-09-11T16:47:05Z
[ "python", "python-2.7" ]
Parameter dependencies in Python - can't make it work
39,437,461
<p>I am trying to add a parameter dependency to my script. The idea is that <em>--clone</em> argument will require non-empty <em>--gituser</em>.</p> <p>After perusing <a href="http://stackoverflow.com/questions/21879657/argparse-argument-dependency">this example</a>, I tried the following</p> <pre><code>In [93]: class CloneAction(argparse.Action): ...: def __call__(self, parser, namespace, _): ...: if not namespace.git_user and namespace.clone: ...: parser.error('"--clone" requires legal git user') ...: In [94]: parser = argparse.ArgumentParser() In [95]: parser.add_argument('-g', '--gituser', dest='git_user', type=str, default='', action=CloneAction) Out[95]: CloneAction(option_strings=['-g', '--gituser'], dest='git_user', nargs=None, const=None, default='', type=&lt;type 'str'&gt;, choices=None, help=None, metavar=None) In [96]: parser.add_argument('--clone', action='store_true', default=False) Out[96]: _StoreTrueAction(option_strings=['--clone'], dest='clone', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None) </code></pre> <p>Alas, it did not work</p> <pre><code>In [97]: parser.parse_args(['--clone']) Out[97]: Namespace(clone=True, git_user='') </code></pre> <p>What did I do wrong?</p>
1
2016-09-11T15:06:16Z
39,438,351
<p>This kind of inter argument dependency is easier to implement <strong>after</strong> parsing.</p> <pre><code>args = parser.parse_args() if not namespace.git_user and namespace.clone: parser.error('"--clone" requires legal git user') </code></pre> <p>At that point, both <code>git_user</code> and <code>clone</code> have been parsed, and have their final values.</p> <p>As you implemented it, the custom action is run only when there's a <code>--gituser</code> argument. So I think it will raise the error when you give it <code>--gituser</code> without <code>--clone</code>. </p> <p>You could give <code>--clone</code> a similar custom action, but it would also have to handle the <code>store_true</code> details. And what should happen with the <code>--clone --gituser value</code> sequence? The <code>clone</code> action will be run before the <code>gituser</code> value has been parsed. Tests like this run into some tough argument order problems.</p> <p>A couple of other issues:</p> <ul> <li><p>your custom action does not store any value, regardless of error not. It's better to customize the <code>store</code> subclass.</p></li> <li><p>custom actions should raise <code>argparse.ArgumentError</code> rather than call <code>parser.error</code> directly. </p></li> </ul> <p>The unittest file, <code>test/test_argparse.py</code> has an example of custom actions with mutual tests like this. But it's just a toy, verifying that such code is allowed.</p> <p>==================</p> <p>You could, in theory, implement a <code>--clone</code> action that sets the <code>required</code> attribute of the <code>--gituser</code> Action. That way, if <code>--gituser</code> is not used, the final <code>required</code> actions test of <code>parse_args</code> will raise an error. But that requires saving a reference to the Action displayed in <code>out[95]</code> (or finding that in the <code>parse._actions</code> list. Feasible but messy.</p> <p>===================</p> <p>Here's an example of a pair of interacting custom action classes from <code>test/test_argparse.py</code>.</p> <pre><code>class OptionalAction(argparse.Action): def __call__(self, parser, namespace, value, option_string=None): try: # check destination and option string assert self.dest == 'spam', 'dest: %s' % self.dest assert option_string == '-s', 'flag: %s' % option_string # when option is before argument, badger=2, and when # option is after argument, badger=&lt;whatever was set&gt; expected_ns = NS(spam=0.25) if value in [0.125, 0.625]: expected_ns.badger = 2 elif value in [2.0]: expected_ns.badger = 84 else: raise AssertionError('value: %s' % value) assert expected_ns == namespace, ('expected %s, got %s' % (expected_ns, namespace)) except AssertionError: e = sys.exc_info()[1] raise ArgumentParserError('opt_action failed: %s' % e) setattr(namespace, 'spam', value) </code></pre> <p><code>NS</code> is a shorthand for <code>argparse.Namespace</code>.</p> <pre><code>class PositionalAction(argparse.Action): def __call__(self, parser, namespace, value, option_string=None): try: assert option_string is None, ('option_string: %s' % option_string) # check destination assert self.dest == 'badger', 'dest: %s' % self.dest # when argument is before option, spam=0.25, and when # option is after argument, spam=&lt;whatever was set&gt; expected_ns = NS(badger=2) if value in [42, 84]: expected_ns.spam = 0.25 elif value in [1]: expected_ns.spam = 0.625 elif value in [2]: expected_ns.spam = 0.125 else: raise AssertionError('value: %s' % value) assert expected_ns == namespace, ('expected %s, got %s' % (expected_ns, namespace)) except AssertionError: e = sys.exc_info()[1] raise ArgumentParserError('arg_action failed: %s' % e) setattr(namespace, 'badger', value) </code></pre> <p>They are used in</p> <pre><code>parser = argparse.ArgumentParser() parser.add_argument('-s', dest='spam', action=OptionalAction, type=float, default=0.25) parser.add_arugment('badger', action=PositionalAction, type=int, nargs='?', default=2) </code></pre> <p>And supposed to work with:</p> <pre><code>'-s0.125' producing: NS(spam=0.125, badger=2)), '42', NS(spam=0.25, badger=42)), '-s 0.625 1', NS(spam=0.625, badger=1)), '84 -s2', NS(spam=2.0, badger=84)), </code></pre> <p>This is an example of the kind of cross checking that can be done. But I'll repeat that generally interactions are best handled after parsing, not during.</p> <p>As to the implementation question - if the user does not give you <code>--gituser</code>, your custom Action is never called. The <code>Action.__call__</code> of an <code>optional</code> is only used when that argument is used. <code>positionals</code> are always used, but not <code>optionals</code>.</p>
3
2016-09-11T16:42:09Z
[ "python", "argparse" ]
Get rows from DataFrame based on array of indices
39,437,485
<p>I have an array with numbers which corresponds to the row numbers that need to be selected from a DataFrame. For example, <code>arr = np.array([0,0,1,1])</code> and the DataFrame is seen below. <code>arr</code> is the row number and not the index. </p> <pre><code>Index A B C D 3 10 0 0 0 4 5 2 0 0 </code></pre> <p>Using <code>arr</code> I would like to produce a DataFrame that looks like this </p> <pre><code> Index A B C D 3 10 0 0 0 3 10 0 0 0 4 5 2 0 0 4 5 2 0 0 </code></pre>
0
2016-09-11T15:08:38Z
39,437,540
<p>You can use <code>iloc</code> with integer indexing:</p> <pre><code>df.iloc[[0,0,1,1], :] # or df.iloc[arr, :] # A B C D #Index #3 10 0 0 0 #3 10 0 0 0 #4 5 2 0 0 #4 5 2 0 0 </code></pre>
2
2016-09-11T15:13:10Z
[ "python", "arrays", "pandas", "dataframe" ]
How to count rows efficiently with one pass over the dataframe
39,437,504
<p>I have a dataframe made of strings like this:</p> <pre><code>ID_0 ID_1 g k a h c i j e d i i h b b d d i a d h </code></pre> <p>For each pair of strings I can count how many rows have either string in them as follows.</p> <pre><code>import pandas as pd import itertools df = pd.read_csv("test.csv", header=None, prefix="ID_", usecols = [0,1]) alphabet_1 = set(df['ID_0']) alphabet_2 = set(df['ID_1']) # This just makes a set of all the strings in the dataframe. alphabet = alphabet_1 | alphabet_2 #This iterates over all pairs and counts how many rows have either in either column for (x,y) in itertools.combinations(alphabet, 2): print x, y, len(df.loc[df['ID_0'].isin([x,y]) | df['ID_1'].isin([x,y])]) </code></pre> <p>This gives:</p> <pre><code>a c 3 a b 3 a e 3 a d 5 a g 3 a i 5 a h 4 a k 3 a j 3 c b 2 c e 2 c d 4 [...] </code></pre> <p>The problem is that my dataframe is very large and the alphabet is of size 200 and this method does an independent traversal over the whole dataframe for each pair of letters. </p> <p>Is it possible to get the same output by doing a single pass over the dataframe somehow?</p> <hr> <p><strong>Timings</strong></p> <p>I created some data with:</p> <pre><code>import numpy as np import pandas as pd from string import ascii_lowercase n = 10**4 data = np.random.choice(list(ascii_lowercase), size=(n,2)) df = pd.DataFrame(data, columns=['ID_0', 'ID_1']) #Testing Parfait's answer def f(row): ser = len(df[(df['ID_0'] == row['ID_0']) | (df['ID_1'] == row['ID_0'])| (df['ID_0'] == row['ID_1']) | (df['ID_1'] == row['ID_1'])]) return(ser) %timeit df.apply(f, axis=1) 1 loops, best of 3: 37.8 s per loop </code></pre> <blockquote> <p>I would like to be able to do this for n = 10**8. Can this be sped up?</p> </blockquote>
2
2016-09-11T15:10:02Z
39,452,228
<p>Consider a <code>DataFrame.apply()</code> method:</p> <pre><code>from io import StringIO import pandas as pd data = '''ID_0,ID_1 g,k a,h c,i j,e d,i i,h b,b d,d i,a d,h ''' df = pd.read_csv(StringIO(data)) def f(row): ser = len(df[(df['ID_0'] == row['ID_0']) | (df['ID_1'] == row['ID_0'])| (df['ID_0'] == row['ID_1']) | (df['ID_1'] == row['ID_1'])]) return(ser) df['CountIDs'] = df.apply(f, axis=1) print df # ID_0 ID_1 CountIDs # 0 g k 1 # 1 a h 4 # 2 c i 4 # 3 j e 1 # 4 d i 6 # 5 i h 6 # 6 b b 1 # 7 d d 3 # 8 i a 5 # 9 d h 5 </code></pre> <p>Alternatives solutions:</p> <pre><code># VECTORIZED w/ list comprehension def f(x, y, z): ser = [len(df[(df['ID_0'] == x[i]) | (df['ID_1'] == x[i])| (df['ID_0'] == y[i]) | (df['ID_1'] == y[i])]) for i in z] return(ser) df['CountIDs'] = f(df['ID_0'], df['ID_1'], df.index) # USING map() def f(x, y): ser = len(df[(df['ID_0'] == x) | (df['ID_1'] == x)| (df['ID_0'] == y) | (df['ID_1'] == y)]) return(ser) df['CountIDs'] = list(map(f, df['ID_0'], df['ID_1'])) # USING zip() w/ list comprehnsion def f(x, y): ser = len(df[(df['ID_0'] == x) | (df['ID_1'] == x)| (df['ID_0'] == y) | (df['ID_1'] == y)]) return(ser) df['CountIDs'] = [f(x,y) for x,y in zip(df['ID_0'], df['ID_1'])] # USING apply() w/ isin() def f(row): ser = len(df[(df['ID_0'].isin([row['ID_0'], row['ID_1']]))| (df['ID_1'].isin([row['ID_0'], row['ID_1']]))]) return(ser) df['CountIDs'] = df.apply(f, axis=1) </code></pre>
1
2016-09-12T14:04:04Z
[ "python", "pandas" ]
How to count rows efficiently with one pass over the dataframe
39,437,504
<p>I have a dataframe made of strings like this:</p> <pre><code>ID_0 ID_1 g k a h c i j e d i i h b b d d i a d h </code></pre> <p>For each pair of strings I can count how many rows have either string in them as follows.</p> <pre><code>import pandas as pd import itertools df = pd.read_csv("test.csv", header=None, prefix="ID_", usecols = [0,1]) alphabet_1 = set(df['ID_0']) alphabet_2 = set(df['ID_1']) # This just makes a set of all the strings in the dataframe. alphabet = alphabet_1 | alphabet_2 #This iterates over all pairs and counts how many rows have either in either column for (x,y) in itertools.combinations(alphabet, 2): print x, y, len(df.loc[df['ID_0'].isin([x,y]) | df['ID_1'].isin([x,y])]) </code></pre> <p>This gives:</p> <pre><code>a c 3 a b 3 a e 3 a d 5 a g 3 a i 5 a h 4 a k 3 a j 3 c b 2 c e 2 c d 4 [...] </code></pre> <p>The problem is that my dataframe is very large and the alphabet is of size 200 and this method does an independent traversal over the whole dataframe for each pair of letters. </p> <p>Is it possible to get the same output by doing a single pass over the dataframe somehow?</p> <hr> <p><strong>Timings</strong></p> <p>I created some data with:</p> <pre><code>import numpy as np import pandas as pd from string import ascii_lowercase n = 10**4 data = np.random.choice(list(ascii_lowercase), size=(n,2)) df = pd.DataFrame(data, columns=['ID_0', 'ID_1']) #Testing Parfait's answer def f(row): ser = len(df[(df['ID_0'] == row['ID_0']) | (df['ID_1'] == row['ID_0'])| (df['ID_0'] == row['ID_1']) | (df['ID_1'] == row['ID_1'])]) return(ser) %timeit df.apply(f, axis=1) 1 loops, best of 3: 37.8 s per loop </code></pre> <blockquote> <p>I would like to be able to do this for n = 10**8. Can this be sped up?</p> </blockquote>
2
2016-09-11T15:10:02Z
39,477,292
<p>You can get past the row level subiteration by using some clever combinatorics/set theory to do the counting:</p> <pre><code># Count of individual characters and pairs. char_count = df['ID_0'].append(df.loc[df['ID_0'] != df['ID_1'], 'ID_1']).value_counts().to_dict() pair_count = df.groupby(['ID_0', 'ID_1']).size().to_dict() # Get the counts. df['count'] = [char_count[x] if x == y else char_count[x] + char_count[y] - (pair_count[x,y] + pair_count.get((y,x),0)) for x,y in df[['ID_0', 'ID_1']].values] </code></pre> <p>The resulting output:</p> <pre><code> ID_0 ID_1 count 0 g k 1 1 a h 4 2 c i 4 3 j e 1 4 d i 6 5 i h 6 6 b b 1 7 d d 3 8 i a 5 9 d h 5 </code></pre> <p>I've compared the output of my method to the row level iteration method on a dataset with 5000 rows and all of the counts match.</p> <p>Why does this work? It essentially just relies on the formula for counting the union of two sets: <a href="http://i.stack.imgur.com/J4VOc.gif" rel="nofollow"><img src="http://i.stack.imgur.com/J4VOc.gif" alt="set_union_equation"></a></p> <p>The cardinality of a given element is just the <code>char_count</code>. When the elements are distinct, the cardinality of the intersection is just the count of pairs of the elements in any order. Note that when the two elements are identical, the formula reduces to just the <code>char_count</code>.</p> <p><strong>Timings</strong></p> <p>Using the timing setup in the question, and the following function for my answer:</p> <pre><code>def root(df): char_count = df['ID_0'].append(df.loc[df['ID_0'] != df['ID_1'], 'ID_1']).value_counts().to_dict() pair_count = df.groupby(['ID_0', 'ID_1']).size().to_dict() df['count'] = [char_count[x] if x == y else char_count[x] + char_count[y] - (pair_count[x,y] + pair_count.get((y,x),0)) for x,y in df[['ID_0', 'ID_1']].values] return df </code></pre> <p>I get the following timings for <code>n=10**4</code>:</p> <pre><code>%timeit root(df.copy()) 10 loops, best of 3: 25 ms per loop %timeit df.apply(f, axis=1) 1 loop, best of 3: 49.4 s per loop </code></pre> <p>I get the following timing for <code>n=10**6</code>:</p> <pre><code>%timeit root(df.copy()) 10 loops best of 3: 2.22 s per loop </code></pre> <p>It appears that my solution scales approximately linearly.</p>
1
2016-09-13T19:07:06Z
[ "python", "pandas" ]
sklearn DictVectorizer(sparse=False) with a different default value, Impute a constant
39,437,687
<p>I'm building a pipeline that starts with a <code>DictVectorizer</code> that produces a sparse matrix. Specifying <code>sparse=True</code> changes the output from a scipy sparse matrix to a numpy dense matrix which is good, but the next stages in the pipeline complain about <code>NaN</code> values, which our obvious outcome of using the <code>DictVectorizer</code> in my case. I'd like the pipeline to consider missing dictionary values not as not available but as zero.</p> <p><code>Imputer</code> doesn't help me as far as I can see, because I want to "impute" with a constant value and not a statistical value dependant of other values of the column.</p> <p>Following is the code I've been using:</p> <pre><code>vectorize = skl.feature_extraction.DictVectorizer(sparse=False) variance = skl.feature_selection.VarianceThreshold() knn = skl.neighbors.KNeighborsClassifier(4, weights='distance', p=1) pipe = skl.pipeline.Pipeline([('vectorize', vectorize), # here be dragons ('fillna', ), ('variance', variance), ('knn', knn)]) pipe.fit(dict_data, labels) </code></pre> <p>And some mocked dictionaries:</p> <pre><code>dict_data = [{'city': 'Dubai', 'temperature': 33., 'assume_zero_when_missing': 7}, {'city': 'London', 'temperature': 12.}, {'city': 'San Fransisco', 'temperature': 18.}] </code></pre> <p>Notiec that in this example, <code>assume_zero_when_missing</code> is missing from most dictionaries, which will lead later estimators to complain about <code>NaN</code> values:</p> <blockquote> <p>ValueError: Input contains NaN, infinity or a value too large for dtype('float64').</p> </blockquote> <p>While the result I'm hoping for is that <code>NaN</code> values will be replaced with <code>0</code>.</p>
1
2016-09-11T15:28:10Z
39,438,952
<p>You could fill the <code>NaNs</code> with 0's after converting your <code>list</code> of <code>dictionaries</code> to a pandas <code>dataframe</code> using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>DF.fillna</code></a> as shown:</p> <pre><code>df = pd.DataFrame(dict_data) df.fillna(0, inplace=True) </code></pre> <hr> <p>Inorder to use it as steps inside the pipeline estimator, you could write a custom class implementing the <code>fit</code> and <code>transform</code> methods yourself as shown:</p> <pre><code>class FillingNans(object): ''' Custom function for assembling into the pipeline object ''' def transform(self, X): nans_replaced = X.fillna(0) return nans_replaced def fit(self, X, y=None): return self </code></pre> <p>Then, you could modify the manual feature selection steps in pipeline as shown:</p> <pre><code>pipe = skl.pipeline.Pipeline([('vectorize', vectorize), ('fill_nans', FillingNans()), ('variance', variance), ('knn', knn)]) </code></pre>
1
2016-09-11T17:47:17Z
[ "python", "pandas", "dataframe", "machine-learning", "scikit-learn" ]
Why does Python 3.5 Return a TypeError and not in Python 2.7
39,437,722
<p>I have a working piece of code in Python 2.7:</p> <pre><code>def reversetomd5(knownhash): clean="" for i in [1,2,3,4,5,7,8,9,10,11,13,14,15,16,18,19,20,21,22,24,25,26,27,28]: clean+=knownhash[i] b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" block=[] for i in xrange(2,24,3): p1 = b64.index(clean[i-2]) p2 = b64.index(clean[i-1]) p3 = b64.index(clean[i]) block.append(p1 &lt;&lt; 12 | p2 &lt;&lt; 6 | p3) md5hash="" for i in block: n1 = i &gt;&gt; 8 n2 = i &amp; 0xff md5hash+=chr(n1)+chr(n2) return binascii.hexlify(md5hash) </code></pre> <p>I'm trying to get it working in Python 3.5 I swapped <code>xrange</code> with <code>range</code> but the character shifting at the bottom doesn't work anymore and returns <code>TypeError: a bytes-like object is required, not 'str'</code>. I haven't been able to figure out what changed in Python 3 to cause that. Any help is greatly appreciated.</p>
0
2016-09-11T15:31:48Z
39,438,455
<p>Got it working correctly. <code>chr()</code> was replaced to return the <code>byte</code> equivalent of the character. Had to change the <code>md5hash</code> initialization to an empty <code>byte</code> variable instead of a <code>string</code>. Then just <code>.decode()</code> it at the end to return a nice string.</p> <pre><code>def reversetomd5(knownhash): clean="" for i in [1,2,3,4,5,7,8,9,10,11,13,14,15,16,18,19,20,21,22,24,25,26,27,28]: clean+=knownhash[i] b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" block=[] for i in range(2,24,3): p1 = b64.index(clean[i-2]) p2 = b64.index(clean[i-1]) p3 = b64.index(clean[i]) block.append(p1 &lt;&lt; 12 | p2 &lt;&lt; 6 | p3) md5hash=b'' for i in block: n1 = i &gt;&gt; 8 n2 = i &amp; 0xff md5hash+=bytes[(n1)]+bytes[(n2)] return binascii.hexlify(md5hash).decode() </code></pre>
4
2016-09-11T16:55:23Z
[ "python", "python-2.7", "python-3.x" ]
Tabs in txt file vs terminal
39,437,725
<p>I'm learning Python at the moment and I'm wondering why tabs look a little different in a txt file than when written to the terminal.</p> <p>In particular, I've run this script</p> <pre><code>my_file = open('power.txt', 'w') print( 'N \t\t2**N\t\t3**N' ) print( '---\t\t----\t\t----' ) my_file.write( 'N \t\t2**N\t\t3**N\n' ) my_file.write( '---\t\t----\t\t----\n' ) for N in range(11) : print( "{:d}\t\t{:d}\t\t{:d}".format(N, pow(2,N), pow(3,N)) ) my_file.write( "{:d}\t\t{:d}\t\t{:d}\n".format(N, pow(2,N), pow(3,N)) ) my_file.close() </code></pre> <p>In it you can see that I'm writing the same thing to both the terminal and the power.txt file. What I see in the terminal is </p> <p><a href="http://i.stack.imgur.com/3eiPQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/3eiPQ.png" alt="enter image description here"></a></p> <p>and what I see in the txt file is</p> <p><a href="http://i.stack.imgur.com/0wxIQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/0wxIQ.png" alt="enter image description here"></a></p> <p>As you can see the third column lines up much nicer in the terminal than the txt file. I've got two questions:</p> <ol> <li>As I'm writing the exact same data to both, why does the information display differently in the txt file?</li> <li>If I wanted the columns in the txt file to line up like they do in the terminal (to improve readability), how could I alter my script to do so?</li> </ol>
1
2016-09-11T15:32:25Z
39,437,808
<p>Don't rely on tabs, they're application/console dependent. Use <code>str.format</code> instead (<a href="https://docs.python.org/2/library/string.html" rel="nofollow">format specification</a>)</p> <p>BTW <code>pow(2,N)</code> is a floating number. You want integral powers: <code>2**N</code></p> <p>Standalone example writing to standard output:</p> <pre><code>import sys my_file = sys.stdout header = "{:&lt;10s}{:&lt;10s}{:&lt;10s}\n".format('N','2**N','3**N' ) my_file.write(header) for N in range(11) : row = "{:&lt;10d}{:&lt;10d}{:&lt;10d}\n".format(N, 2**N, 3**N) my_file.write(row) </code></pre> <p>result:</p> <pre><code>N 2**N 3**N 0 1 1 1 2 3 2 4 9 3 8 27 4 16 81 5 32 243 6 64 729 7 128 2187 8 256 6561 9 512 19683 10 1024 59049 </code></pre> <p>(you could use legacy C-style format like <code>%20s</code> or <code>%-10s</code> but it's frowned upon now as deprecated, and the <code>format</code> interface is much much more powerful)</p>
1
2016-09-11T15:40:16Z
[ "python", "file" ]
Find parent in Binary Search Tree?
39,437,745
<p>I wish to find the parent to a node with a certain value in a BST. My node class has attributes item (i.e the value/key), left and right. </p> <p>The idea to find a parent is like this:<br> 1) If the value (key) does not exist, return None, None<br> 2) If the root is equal to the value (key) then return None, root<br> 3) Else find the value (key) and return (par, node) where par is the parent and node </p> <p>My function looks like this:</p> <pre><code>def findpar(self,key): if not self._exists(key): return None,None elif self.root.item==key: return None, self.root p=self.root found=False while not found: if p.left.item==key: return p, p.left found=True elif p.right.item==key: return p, p.right found=True elif p.item&lt;key: p=p.left elif p.item&gt;key: p=p.right </code></pre> <p>How do I handle the issue when <code>p.left</code> or <code>p.right</code> is None? </p>
1
2016-09-11T15:34:28Z
39,438,029
<p>As your code currently works, it is impossible that you're turning toward a <code>None</code> left or right child. This is because your code starts with</p> <pre><code>if not self._exists(key): return None,None </code></pre> <p>So <code>key</code> must exist, and if it must exist, it must exist on the search path. </p> <p>It should be noted that you're effectively performing the search twice, though, which is not that efficient. Instead, you could try something like this:</p> <pre><code>def findpar(self,key): parent, node = None, self.root while True: if node is None: return (None, None) if node.item == key: return (parent, node) parent, node = node, node.left if key &lt; node.item else node, node.right </code></pre>
1
2016-09-11T16:04:07Z
[ "python", "python-3.x" ]
Django: How to display author of query of posts?
39,437,751
<p>I'm trying to make individual pages for each author showing their name and posts. I can't seem to get the username displayed.</p> <p>views.py</p> <pre><code>class UserProfileView(generic.ListView): template_name = 'howl/user-profile.html' context_object_name = 'user_howls' def get_queryset(self): author = self.request.user u = User.objects.get(username=author) return Howl.objects.filter(author=u) </code></pre> <p>models.py</p> <pre><code>class Howl(models.Model): author = models.ForeignKey(User, null=True) content = models.CharField(max_length=150) </code></pre> <p>Here is where I'm stuck.</p> <p>user-profile.html</p> <pre><code>{% extends 'howl/base.html' %} {% block content %} &lt;h1&gt;User: {{user_howl.author}}&lt;/h1&gt; {% for user_howl in user_howls %} &lt;ul&gt; &lt;li&gt;{{user_howl.content}}&lt;/li&gt; &lt;/ul&gt; {% endfor %} {% endblock %} </code></pre> <p>The content is displayed just fine, but the heading just says "User: ", how do I give it a context without using a for loop? I've tried:</p> <pre><code>{% for author in user_howls.author %} &lt;h1&gt;User: {{author}}&lt;/h1&gt; {% endfor %} </code></pre> <p>and </p> <pre><code>{% if user_howls.author %} &lt;h1&gt;User: {{user_howl.author}}&lt;/h1&gt; {% endif %} </code></pre> <p>Still the same outcome, displaying "User: "</p>
0
2016-09-11T15:34:50Z
39,437,797
<p><code>user_howls</code> is a queryset so it won't have an <code>author</code> attribute, you need to get the author of the iterated object</p> <pre><code>{% for howl in user_howls %} &lt;h1&gt;User: {{ howl.author}}&lt;/h1&gt; {% endfor %} </code></pre> <p>More to the point though, it doesn't make sense to start from a <code>Howl</code> list, when you are just returning the results for the user_profile, nor does it make sense to use a <code>ListView</code>. so instead, start from the user and then look up its howls</p> <pre><code>user_obj.howl_set.all() </code></pre>
3
2016-09-11T15:39:34Z
[ "python", "django" ]
Django: How to display author of query of posts?
39,437,751
<p>I'm trying to make individual pages for each author showing their name and posts. I can't seem to get the username displayed.</p> <p>views.py</p> <pre><code>class UserProfileView(generic.ListView): template_name = 'howl/user-profile.html' context_object_name = 'user_howls' def get_queryset(self): author = self.request.user u = User.objects.get(username=author) return Howl.objects.filter(author=u) </code></pre> <p>models.py</p> <pre><code>class Howl(models.Model): author = models.ForeignKey(User, null=True) content = models.CharField(max_length=150) </code></pre> <p>Here is where I'm stuck.</p> <p>user-profile.html</p> <pre><code>{% extends 'howl/base.html' %} {% block content %} &lt;h1&gt;User: {{user_howl.author}}&lt;/h1&gt; {% for user_howl in user_howls %} &lt;ul&gt; &lt;li&gt;{{user_howl.content}}&lt;/li&gt; &lt;/ul&gt; {% endfor %} {% endblock %} </code></pre> <p>The content is displayed just fine, but the heading just says "User: ", how do I give it a context without using a for loop? I've tried:</p> <pre><code>{% for author in user_howls.author %} &lt;h1&gt;User: {{author}}&lt;/h1&gt; {% endfor %} </code></pre> <p>and </p> <pre><code>{% if user_howls.author %} &lt;h1&gt;User: {{user_howl.author}}&lt;/h1&gt; {% endif %} </code></pre> <p>Still the same outcome, displaying "User: "</p>
0
2016-09-11T15:34:50Z
39,437,975
<p>Since your queryset is based on the posts belonging to the current user, you can shortcut all of this and just show the user directly:</p> <pre><code>User: {{ user }} </code></pre>
1
2016-09-11T15:58:46Z
[ "python", "django" ]
Compare elements in large list of data
39,437,766
<p>I've got the question on interview by python recently. The question was:</p> <blockquote> <p>we have a large list of pictures in python(as I understood we simply read their content, and then got list of their contents), <code>[...]</code>, this list will occupy 1gb of RAM e.g. What is the best way to compare them(do pictures the same)? I answered that we can separate this list into several lists and then compare elements in them.</p> </blockquote> <p>But I got answer that: "it is wrong". So my question the same what is the best way here to compare them?</p> <p>Currently I think maybe use python's sets and compare lengths of source list and set?</p>
0
2016-09-11T15:36:03Z
39,437,863
<p>Assuming the list contains the raw byte strings of the image contents, one quick and dirty way to weed out possible duplicates is to compare the <em>lengths</em> of the byte strings. Two pictures with unequal length byte strings cannot be duplicates.</p> <p>Then, for each group of pictures with equal length byte strings, hash the byte strings and compare those. If the hashes are equal then the pictures are duplicates, otherwise they're not. (For extra speed, don't bother hashing if there are only two byte strings in a group; just compare the strings directly byte-by-byte.)</p>
1
2016-09-11T15:47:01Z
[ "python", "bigdata" ]
numpy extract 3d cubes from 3d array
39,437,806
<p>I would like to extract the 3D cubes (3x3x3) from a boolean 3D array of (180x180x197). This is similar to scipy.ndimage.measurements.label but need to fixed size of (3x3x3). Is there a fast way of doing this than using for loops. </p>
0
2016-09-11T15:40:06Z
39,438,310
<p>In your special case, I suggest to use ndimage.minimum_filter Let's say your array is called ``a''. The following:</p> <pre><code>centers = ndimage.minimum_filter(a, 3, mode="constant") </code></pre> <p>will only contain ones where your array contained such box of True's Then you can use scipy.ndimage.measurements.label with the default structure to classify the boxes and maybe identify connected boxs. To locate them you can use ndimage.measurements.find_objects</p> <p>edit:</p> <p>The way above, you will correctly get the centers of <strong>all</strong> cubes in the array. To be clear, I think that is the answer to your initial question. In the comments, it turned out, that indeed only non-overlapping cubes are needed. Therefore, one needs to analyze the output of minimum_filter, where I can imagine many approaches.</p> <p>One can use the following to obtain only one cube per cluster:</p> <pre><code>s = ndimage.generate_binary_structure(3,3) labels, num = ndimage.measurements.label(centers, s) locations = ndimage.measurements.find_objects(labels) locations = map(lambda slices: [slices[i].start for i in xrange(3)], locations) </code></pre> <p>Now the problem occurs that cubes are lost which are not overlapping but share a face. Actually one can imagine quite complicated structures of non-overlapping, facesharing cubes. Certainly, there are several solutions (sets of non-overlapping cubes) that can be found for this problem. So it is a completely new task to choose a set of cubes from the found centers and I think you will have to find one which is ideal for you.</p> <p>One way could be to iterate through all solutions and set each found cube to False:</p> <pre><code>get_starting_point = numpy.vectorize(lambda sl: sl.start) #to be applied on slices s = ndimage.generate_binary_structure(3,3) result = [] while True: labels, num = ndimage.measurements.label(centers, s) if not num: break locations = ndimage.measurements.find_objects(labels) sp = get_starting_point(locations) result.append(sp) for p in sp: centers[p[0]-1:p[0]+2, p[1]-1:p[1]+2, p[2]-1:p[2]+2] = False numiter = len(results) results = numpy.vstack(results) </code></pre> <p>I guess only very few iterations will be necessary.</p> <p>I hope this is what you were looking for</p>
1
2016-09-11T16:36:44Z
[ "python", "numpy", "multidimensional-array", "scipy" ]
numpy extract 3d cubes from 3d array
39,437,806
<p>I would like to extract the 3D cubes (3x3x3) from a boolean 3D array of (180x180x197). This is similar to scipy.ndimage.measurements.label but need to fixed size of (3x3x3). Is there a fast way of doing this than using for loops. </p>
0
2016-09-11T15:40:06Z
39,473,100
<p>Final solution with help from dnalow</p> <pre><code>get_starting_point = numpy.vectorize(lambda sl: sl.start) s = ndimage.generate_binary_structure(3,3) result = [] while True: centers = ndimage.minimum_filter(b, 3, mode="constant") labels, num = ndimage.measurements.label(centers, s) if not num: break locations = ndimage.measurements.find_objects(labels) sp = get_starting_point(locations) for p in sp: if numpy.all(a[p[0]-1:p[0]+2, p[1]-1:p[1]+2, p[2]-1:p[2]+2]): result.append(p) b[p[0]-1:p[0]+2, p[1]-1:p[1]+2, p[2]-1:p[2]+2] = False numiter = len(result) results = numpy.vstack(result) </code></pre>
0
2016-09-13T14:56:05Z
[ "python", "numpy", "multidimensional-array", "scipy" ]
Interpolating in 3D, plotting with matplotlib - something is going wrong
39,437,895
<p>Here is some toy data:</p> <pre><code>import pandas as pd import numpy as np testDF = pd.DataFrame(np.linspace(100.,200.,40).reshape(10,4), columns=list('abcd')) </code></pre> <p>It looks like this (the face is just there for illustration, the top line of each parallelogram is what we are interested in):</p> <p><a href="http://i.stack.imgur.com/nNXgt.png" rel="nofollow"><img src="http://i.stack.imgur.com/nNXgt.png" alt="enter image description here"></a></p> <p>Which for the purposes of my application I turn into an ordered dictionary:</p> <pre><code>OrderedDict([('a', array([[ 0. , 0. , 1.62], [ 1. , 1. , 1.62], [ 2. , 2. , 1.62], [ 3. , 3. , 1.62], [ 4. , 4. , 1.62], [ 5. , 5. , 1.62], [ 6. , 6. , 1.62], [ 7. , 7. , 1.62], [ 8. , 8. , 1.62], [ 9. , 9. , 1.62]])), ('b', array([[ 0. , 1. , 1.12], [ 1. , 2. , 1.12], [ 2. , 3. , 1.12], [ 3. , 4. , 1.12], [ 4. , 5. , 1.12], [ 5. , 6. , 1.12], [ 6. , 7. , 1.12], [ 7. , 8. , 1.12], [ 8. , 9. , 1.12], [ 9. , 10. , 1.12]])), ('c', array([[ 0. , 4. , 0.7], [ 1. , 5. , 0.7], [ 2. , 6. , 0.7], [ 3. , 7. , 0.7], [ 4. , 8. , 0.7], [ 5. , 9. , 0.7], [ 6. , 10. , 0.7], [ 7. , 11. , 0.7], [ 8. , 12. , 0.7], [ 9. , 13. , 0.7]])), ('d', array([[ 0. , 9. , 0.56], [ 1. , 10. , 0.56], [ 2. , 11. , 0.56], [ 3. , 12. , 0.56], [ 4. , 13. , 0.56], [ 5. , 14. , 0.56], [ 6. , 15. , 0.56], [ 7. , 16. , 0.56], [ 8. , 17. , 0.56], [ 9. , 18. , 0.56]]))]) </code></pre> <p>Now I am trying to interpolate in the third dimensions i.e. the one with values <code>[1.62,1.12,0.7,0.56]</code> - I would like to get some idea of what is happening in between.</p> <p>This is my function:</p> <pre><code>import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from scipy.interpolate import griddata from matplotlib import cm class jointInterpolation(object): """ Class for performing various forms of interpolation. """ def __init__(self,trajDict): # Concat dictionary into (n_i x D) for all i in speeds. D = np.vstack(trajDict.values()) # Grid the data: [time,angle,velocity] self.X = D[:,0] self.Y = D[:,1] self.Z = D[:,2] def myRegularGridInterpolator(self,df): pass from scipy.interpolate import RegularGridInterpolator as RGI def standardGridInterpolation(self,intMethod,plot=False): """ Interpolate unstructured D-dimensional data. """ # [time,angle,velocity] # Time xi = np.linspace(self.X.min(),self.X.max(),100) # # Angle yi = np.linspace(self.Y.min(),self.Y.max(),100) # Velocity # zi = np.linspace(self.Z.min(),self.Z.max(),100) # VERY IMPORTANT: tell matplotlib how the observations are organised zi = griddata((self.X, self.Y), self.Z, (xi[None,:], yi[:,None]), method=intMethod) # yi = griddata((self.X, self.Z), self.Y, (xi[None,:], zi[:,None]), method=intMethod) if plot: fig = plt.figure(figsize=(10,10)) ax = fig.gca(projection='3d') xig, yig = np.meshgrid(xi, yi) # xig, zig = np.meshgrid(xi, zi) surf = ax.plot_wireframe(xig, yig, zi, #xig, zig, yi rstride= 4, cstride= 4, color = 'darkviolet', linewidth = 1.5, alpha=0.7, antialiased = True) plt.show() </code></pre> <p>But I seem to be messing up the order somehow, I just don't see how:</p> <pre><code>intstuff = jointInterpolation(myDict) intstuff.standardGridInterpolation('nearest',True) </code></pre> <p><a href="http://i.stack.imgur.com/tSR7n.png" rel="nofollow"><img src="http://i.stack.imgur.com/tSR7n.png" alt="enter image description here"></a></p> <p>EDIT:</p> <p><em>I am not entirely sure if this qualifies as a a unstructured grid.</em></p> <p>Also an updated version with less points, on request.</p> <pre><code>testDF = pd.DataFrame(np.linspace(0.,10.,40).reshape(10,4), columns=list('abcd')) </code></pre> <p><a href="http://i.stack.imgur.com/j5S2y.png" rel="nofollow"><img src="http://i.stack.imgur.com/j5S2y.png" alt="enter image description here"></a></p>
0
2016-09-11T15:50:21Z
39,438,787
<p>Ok so I figured it out:</p> <pre><code>class jointInterpolation(object): """ Class for performing various forms of interpolation. """ def __init__(self,trajDict): # Concat dictionary into (n_i x D) for all i in speeds. D = np.vstack(trajDict.values()) # Grid the data: [time,angle,velocity] self.X = D[:,0] self.Y = D[:,1] self.Z = D[:,2] def myRegularGridInterpolator(self,df): pass from scipy.interpolate import RegularGridInterpolator as RGI def standardGridInterpolation(self,intMethod,plot=False): """ Interpolate unstructured D-dimensional data. """ # [time,angle,velocity] # Velocity zi = np.linspace(self.Z.min(),self.Z.max(),100) # Angle xi = np.linspace(self.X.min(),self.X.max(),100) # Velocity # VERY IMPORTANT: tell matplotlib how the observations are organised yi = griddata((self.Z, self.X), self.Y, (zi[None,:], xi[:,None]), method=intMethod) if plot: fig = plt.figure(figsize=(10,10)) ax = fig.gca(projection='3d') zig, yig = np.meshgrid(zi, xi) surf = ax.plot_wireframe(zig, yig, yi, #xig, zig, yi rstride= 5, cstride= 5, color = 'darkviolet', linewidth = 1.5, alpha=0.7, antialiased = True) </code></pre> <p>This produces the required figure:</p> <pre><code>intstuff.standardGridInterpolation('linear',True) </code></pre> <p><a href="http://i.stack.imgur.com/qgRk5.png" rel="nofollow"><img src="http://i.stack.imgur.com/qgRk5.png" alt="enter image description here"></a></p>
0
2016-09-11T17:30:13Z
[ "python", "matplotlib" ]
Redis pipeline - atomic getting a value of another key value
39,437,922
<p>I have a string key named "a" and its value is "b", I also have a hash set which is named "b" and it has multiple values for example:</p> <pre><code>"a" (value equals to "b") "b": { "first_name": "John", "last_name": "Doe" } </code></pre> <p>is it possible to use a pipeline so given the key "a" I will receive the object b value ?</p> <p>Thanks</p>
2
2016-09-11T15:52:57Z
39,438,427
<p>Pipeline is an optimization for sending multiple operations. It doesn't guarantee atomicity and the replies are available only after the pipeline is executed. That being the case, it would appear that it isn't suitable for what you're trying to do.</p> <p>IIUC, you want to "dereference" the value in the first key and get the data in the second key. I suspect that when you use the term "atomically" your meaning is with one call to the server. That pattern isn't supported by Redis - instead, you should GET the value in <code>a</code> and then HMGET from <code>b</code>.</p>
2
2016-09-11T16:52:19Z
[ "python", "redis" ]
Redis pipeline - atomic getting a value of another key value
39,437,922
<p>I have a string key named "a" and its value is "b", I also have a hash set which is named "b" and it has multiple values for example:</p> <pre><code>"a" (value equals to "b") "b": { "first_name": "John", "last_name": "Doe" } </code></pre> <p>is it possible to use a pipeline so given the key "a" I will receive the object b value ?</p> <p>Thanks</p>
2
2016-09-11T15:52:57Z
39,442,703
<p>Pipeline won't work, since you must wait until the first <code>get</code> command returns the <em>real key</em>, i.e. <em>b</em>.</p> <p>Instead, you can achieve it with <code>lua scripts</code>.</p> <pre><code>local real_key = redis.call('get', KEYS[1]) if real_key then return redis.call('hgetall', real_key) end </code></pre> <p>The whole lua script executes atomically.</p>
3
2016-09-12T02:40:08Z
[ "python", "redis" ]
what anti-ddos security systems python use for socket TCP connections?
39,438,003
<p>More in detail, would like to know:</p> <ul> <li>what is the default SYN_RECEIVED timer,</li> <li>how do i get to change it,</li> <li>are SYN cookies or SYN caches implemented.</li> </ul> <p>I'm about to create a simple special-purpose publically accessible server. i must choose whether using built-in TCP sockets or RAW sockets and re-implement the TCP handshake if these security mechanisms are not present.</p>
1
2016-09-11T16:01:29Z
39,438,366
<p>What you describe are internals of the TCP stack of the operating system. Python just uses this stack via the socket interface. I doubt that any of these settings can be changed specific to the application at all, i.e. these are system wide settings which can only be changed with administrator privileges. </p>
1
2016-09-11T16:44:02Z
[ "python", "sockets", "tcp", "ddos", "python-sockets" ]
How to set the default python path for anaconda?
39,438,049
<p>i have installed anaconda on a linux machine. I noticed that after deactivating the anaconda environment with:</p> <pre><code>source deactivate </code></pre> <p>When running:</p> <pre><code>which python </code></pre> <p>I get:</p> <pre><code>/home/user/anaconda/bin/python </code></pre> <p>Instead of</p> <pre><code>/usr/bin/python </code></pre> <p>How can i restore this setting?</p>
1
2016-09-11T16:05:53Z
39,470,093
<p>The comments somewhat cover the answer to the question, but to clarify:</p> <p>When you installed Anaconda you must have agreed to have it added to your PATH. You'll want to check in your <code>~/.bash*</code> files and look for any <code>export PATH=</code> lines to check this. So Anaconda is <strong>always</strong> on your path. The <code>source deactivate</code> command will only deactivate "sub" Conda environments. It will never remove what is called the "root" Conda environment (the one you originally installed). If you don't want Anaconda on your <code>PATH</code> by default then remove it from your <code>~/.bash*</code> startup files. Then when you want to use Anaconda you'll need to add it to your <code>PATH</code>. Or just add the specific Conda environment you are interested in to your <code>PATH</code> directly, and don't worry about the <code>activate</code> and <code>deactivate</code> scripts. At their core all they do is modify <code>PATH</code>.</p> <p>I hope that helps clarify things.</p>
0
2016-09-13T12:27:07Z
[ "python", "anaconda" ]
How can I set up data validation to restrict input for 3 fields to number only?
39,438,107
<p>I was just introducted to <code>python</code> a few days ago</p> <p>I need user input for three different fields. How can I restrict user input to numbers for all three questions?</p> <pre><code>while True: try: workinghours = int(raw_input("what is your working hours?")) except ValueError: print "Try again! what is your working hours?" continue normalrate = int(raw_input("what is your normal rate?")) except ValueError: print "Try again! what is your normal rate?" continue overtimerate = int(raw_input("what is your overtime rate")) except ValueError: print "Try again! what is your overtime rate?" continue if workinghours &gt; 40: overworkinghours = workinghours - 40 overtimepayment = overtimerate * overworkinghours print ("your extra overtime salary is + $%.2f" % overtimepayment) normalpayment = normalrate * 40 print ("your normal hours salary is + $%.2f" % normalpayment) totalsalary = float(normalpayment) + float(overtimepayment) print ("your total salary is: + $%.2f" % totalsalary) else: normalpayment = normalrate * workinghours print ("your total salary without overtime is $%.2f" % normalpayment) </code></pre>
1
2016-09-11T16:11:59Z
39,438,392
<h3>You're asking the poor soul the same information over and over again, no escape is possible :)</h3> <p>Apart from the fact that the while loop never ends because there is no <code>break</code>statement anywhere, you are misunderstanding the <code>continue</code> statement. As we can read <a href="http://www.tutorialspoint.com/python/python_loop_control.htm" rel="nofollow">here</a>:</p> <blockquote> <p>The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.</p> </blockquote> <p>That means that if your user makes a mistake (wrong type of input), he returns to <em>the first question</em>, instead of the question he made the mistake in. </p> <h3>Separate while loop foor each field</h3> <p>You need to make it three separate <code>while</code> loops, one for each field:</p> <pre><code>while True: try: workinghours = int(raw_input("what is your working hours? ")) except ValueError: print "Try again! " else: break while True: try: normalrate = int(raw_input("what is your normal rate? ")) except ValueError: print "Try again! " else: break while True: try: overtimerate = int(raw_input("what is your overtime rate? ")) except ValueError: print "Try again! " else: break if workinghours &gt; 40: overworkinghours = workinghours - 40 overtimepayment = overtimerate * overworkinghours print ("your extra overtime salary is + $%.2f" % overtimepayment) normalpayment = normalrate * 40 print ("your normal hours salary is + $%.2f" % normalpayment) totalsalary = float(normalpayment) + float(overtimepayment) print ("your total salary is: + $%.2f" % totalsalary) else: normalpayment = normalrate * workinghours print ("your total salary without overtime is $%.2f" % normalpayment) </code></pre>
0
2016-09-11T16:47:59Z
[ "python", "validation" ]
python remove obect from array using condition
39,438,133
<p>I have a list of dictionaries like below:</p> <pre><code>tt = [ { 'property1': 'value1', 'property2': 'value2', 'property3': 'value3' }, { 'property1': 'value4', 'property2': 'value5', 'property3': 'value6' }, .............................. ............................. ] </code></pre> <p>How i can remove <code>'property3' : 'value6'</code> from above list of dictionaries?</p> <p>To be precise, i need to remove all instances of key('property3') with specific value('value6') from all dictionaries in the list?</p> <p>I am in need of fastest method, because list can be vary large.</p>
-3
2016-09-11T16:15:20Z
39,438,364
<p>This should do it. Fairly straight forward so I won't explain it. Good Luck</p> <pre><code>def search(dict, key=None, val=None): c_dict = copy.deepcopy(dict) for i, n in enumerate(dict): for k, v in n.iteritems(): if key and val and k == key and val == v: c_dict[i].pop(k) elif key and k == key: c_dict[i].pop(k) elif v and val == v: c_dict[i].pop(k) else: continue return c_dict print search(d, 'property3', 'value6') </code></pre>
1
2016-09-11T16:43:57Z
[ "python", "python-3.x" ]
python remove obect from array using condition
39,438,133
<p>I have a list of dictionaries like below:</p> <pre><code>tt = [ { 'property1': 'value1', 'property2': 'value2', 'property3': 'value3' }, { 'property1': 'value4', 'property2': 'value5', 'property3': 'value6' }, .............................. ............................. ] </code></pre> <p>How i can remove <code>'property3' : 'value6'</code> from above list of dictionaries?</p> <p>To be precise, i need to remove all instances of key('property3') with specific value('value6') from all dictionaries in the list?</p> <p>I am in need of fastest method, because list can be vary large.</p>
-3
2016-09-11T16:15:20Z
39,440,787
<p>Sorry, I didn't notice that the poster only wanted to remove specific properties. Here's the correct solution:</p> <pre><code>tt=[{k:v for k,v in i.items() if k != 'property3' or v != 'value6'} for i in tt] </code></pre> <p>LazyScripter's solution will delete dictionary elements where the key OR the value OR both match. If I understand the original question, I don't think this is what was desired.</p> <p>I've also compared the efficiency of the two proposed solutions and the one-liner seems to be about 12X faster...</p> <pre><code>python -m cProfile test.py </code></pre> <p>outputs:</p> <pre><code>1780059 function calls (1500059 primitive calls) in 2.759 seconds ncalls tottime percall cumtime percall filename:lineno(function) ... 1 0.026 0.026 2.759 2.759 test.py:1(&lt;module&gt;) 1 0.036 0.036 0.917 0.917 test.py:19(search) 1 0.035 0.035 0.073 0.073 test.py:33(search2) ... </code></pre> <p>For the following code:</p> <pre><code>import copy tt = [ { 'property1': 'value1', 'property2': 'value2', 'property3': 'value3' }, { 'property1': 'value4', 'property2': 'value5', 'property3': 'value6' } ] d=[] [d.extend(copy.deepcopy(tt)) for _ in range(10000)] def search(dict, key=None, val=None): c_dict = copy.deepcopy(dict) for i, n in enumerate(dict): for k, v in n.iteritems(): if key and val and k == key and val == v: c_dict[i].pop(k) # elif key and k == key: # c_dict[i].pop(k) # elif v and val == v: # c_dict[i].pop(k) else: continue return c_dict def search2(d,a,b): return [{k:v for k,v in i.items() if k != a or v != b} for i in d] search (d, 'property3', 'value6') search2(d, 'property3', 'value6') </code></pre>
0
2016-09-11T21:22:39Z
[ "python", "python-3.x" ]
Setting a descriptor in python3.5 asynchronously
39,438,163
<p>I can write a descriptor returning a future which could be awaited on.</p> <pre><code>class AsyncDescriptor: def __get__(self, obj, cls=None): # generate some async future here return future def __set__(self, obj, value): # generate some async future here return future class Device: attr=AsyncDescriptor() device=Device() </code></pre> <p>Now I can get the value in a coroutine with <code>value=await device.attr</code>.</p> <p>How would I set this attribute?</p> <ul> <li><code>await device.attr=5</code> -> SyntaxError: can't assign to await expression</li> <li><code>await setattr(device, 'attr', 5)</code> -> TypeError: object NoneType can't be used in 'await' expression</li> <li><code>device.attr=5</code> -> RuntimeWarning: coroutine '__set__' was never awaited</li> </ul>
2
2016-09-11T16:18:47Z
39,438,844
<p>What you are trying to do is not possible (with Python 3.5).</p> <p>While it may be sensible for <code>__get__</code> to return a Future, making <code>__set__</code> async is simply not supported by Python 3.5. The return value of <code>__set__</code> is ignored by Python since there is no "return value" of assignments. And the call to <code>__set__</code> is always synchronous. Something like <code>a = (b.c = 5)</code> actually raises a <code>SyntaxError</code> as you already noticed.</p> <p>If async assignments like <code>await device.attr = 5</code> were allowed, there would probably be a separate protocol for async descriptors, i.e. with coroutines <code>__aget__</code> and <code>__aset__</code> as special methods in analogy to async context manager (<code>async with</code> / <code>__aenter__</code> ) and async iteration (<code>async for</code> / <code>__aiter__</code>). See <a href="https://www.python.org/dev/peps/pep-0492/" rel="nofollow">PEP 492</a> for the design decisions behind the <code>async</code> / <code>await</code> support.</p> <p>Also note that <code>__get__</code> returning a future does not make <code>__get__</code> a coroutine.</p> <p>Without further context, it looks like you want to hide something behind the attribute access abstraction provided by the descriptor protocol which should better be done explicitly, but that's up to you of course. </p>
2
2016-09-11T17:36:15Z
[ "python", "python-3.5", "python-asyncio", "descriptor" ]
palindromes of sums less than 30, help to optimize my code
39,438,191
<p>On my way of studying Python i stacked on the problem:<br><br> I have to count all numbers from <b>0</b> to <b>130000</b> which are palindromes, but they should be palindromes after sum of the number and its reversed version. For example: <br> <code>i</code> = 93 <br>93 + 39 = 132 <br>132 + 231 = 363 <br><code>count_of_palindromes</code> should count all <code>i</code> which are palindromes after <b>1</b> or more iterations of summing, but less than <b>50</b>. <br>I've already written the code but it's too way difficult to run on my PC, Python stops responding :( <br><br>Any advices how to optimize my code?</p> <pre><code> count_of_palindromes = 0 for i in range(0,130000): trying = 0 if (i == int(str(i)[::-1])) != True: trying += 1 sum = i + int(str(i)[::-1]) while trying &lt;= 50: while (sum == int(str(sum)[::-1])) != True: trying += 1 sum += int(str(sum)[::-1]) if trying &gt; 0 and trying &lt;= 50: count_of_palindromes += 1 break print(count_of_palindromes) </code></pre> <p>Thank you very much!</p>
-2
2016-09-11T16:22:42Z
39,438,346
<p>This solution has a lot of conversions so it may not be the best solution but regardless it is a solution. have a look at this post he has a seemingly much better method of reversing integers without conversion <a href="http://stackoverflow.com/a/3806212/1642546">http://stackoverflow.com/a/3806212/1642546</a> </p> <p>If you combine my code and that posts code. you probably will have a faster solution, but you must benchmark it to see. </p> <pre><code>token = 0 for x in range(130000): reversed = str(x)[::-1] original = str(x) sum = int(reversed) + int(original) if str(sum) == str(sum)[::-1]: token+=1 print(token) </code></pre>
0
2016-09-11T16:41:39Z
[ "python", "optimization" ]
palindromes of sums less than 30, help to optimize my code
39,438,191
<p>On my way of studying Python i stacked on the problem:<br><br> I have to count all numbers from <b>0</b> to <b>130000</b> which are palindromes, but they should be palindromes after sum of the number and its reversed version. For example: <br> <code>i</code> = 93 <br>93 + 39 = 132 <br>132 + 231 = 363 <br><code>count_of_palindromes</code> should count all <code>i</code> which are palindromes after <b>1</b> or more iterations of summing, but less than <b>50</b>. <br>I've already written the code but it's too way difficult to run on my PC, Python stops responding :( <br><br>Any advices how to optimize my code?</p> <pre><code> count_of_palindromes = 0 for i in range(0,130000): trying = 0 if (i == int(str(i)[::-1])) != True: trying += 1 sum = i + int(str(i)[::-1]) while trying &lt;= 50: while (sum == int(str(sum)[::-1])) != True: trying += 1 sum += int(str(sum)[::-1]) if trying &gt; 0 and trying &lt;= 50: count_of_palindromes += 1 break print(count_of_palindromes) </code></pre> <p>Thank you very much!</p>
-2
2016-09-11T16:22:42Z
39,438,805
<p>I had an error in the code, that made the program almost ifinite :) <br>The correct code (in my opinion is below)</p> <pre><code>count_of_palindromes = 0 for i in range(12814): if (i == int(str(i)[::-1])) != True: trying = 1 sum = i + int(str(i)[::-1]) while trying &lt;= 50: while (sum == int(str(sum)[::-1])) != True and trying &lt;=50: trying += 1 sum += int(str(sum)[::-1]) if trying &gt; 0 and trying &lt;= 50: count_of_palindromes += 1 break print(count_of_palindromes) </code></pre>
0
2016-09-11T17:31:49Z
[ "python", "optimization" ]
palindromes of sums less than 30, help to optimize my code
39,438,191
<p>On my way of studying Python i stacked on the problem:<br><br> I have to count all numbers from <b>0</b> to <b>130000</b> which are palindromes, but they should be palindromes after sum of the number and its reversed version. For example: <br> <code>i</code> = 93 <br>93 + 39 = 132 <br>132 + 231 = 363 <br><code>count_of_palindromes</code> should count all <code>i</code> which are palindromes after <b>1</b> or more iterations of summing, but less than <b>50</b>. <br>I've already written the code but it's too way difficult to run on my PC, Python stops responding :( <br><br>Any advices how to optimize my code?</p> <pre><code> count_of_palindromes = 0 for i in range(0,130000): trying = 0 if (i == int(str(i)[::-1])) != True: trying += 1 sum = i + int(str(i)[::-1]) while trying &lt;= 50: while (sum == int(str(sum)[::-1])) != True: trying += 1 sum += int(str(sum)[::-1]) if trying &gt; 0 and trying &lt;= 50: count_of_palindromes += 1 break print(count_of_palindromes) </code></pre> <p>Thank you very much!</p>
-2
2016-09-11T16:22:42Z
39,439,019
<p>Let's tidy your code up a bit first for readability. We'll just take some of the syntax heavy string stuff and encapsulate it.</p> <pre><code>def reverse(n): return int(str(n)[::-1]) def is_palindrome(n): return n == reverse(n) </code></pre> <p>That's better. I think your problem is the second nested while loop. It runs until it finds a palindrome, then checks if it found it in the first fifty tries. You want it to run up to fifty times, then give up. I think the best way would be a second for loop</p> <pre><code>count_of_palindromes = 0 for i in range(130000): for tries in range(50): if(is_palindrome(i)): counter += 1 break else: i = i + reverse(i) print(count_of_palindromes) </code></pre> <p>There are some more ways of speeding this up by avoiding string operations and replacing them with math, but that's overkill for this. I was a little unclear on how your problem wants you to treat natural palindromes, so you may need to modify this solution</p>
0
2016-09-11T17:56:15Z
[ "python", "optimization" ]
Python: how could I access tarfile.add()'s 'name' parameter in add()'s filter method?
39,438,335
<p>I would like to filter subdirectories (skip them) while creating tar(gz) file with <strong>tarfile</strong> (python 3.4).</p> <p>Files on disk:</p> <ul> <li>/home/myuser/temp/test1/</li> <li>/home/myuser/temp/test1/home/foo.txt</li> <li>/home/myuser/temp/test1/thing/bar.jpg</li> <li>/home/myuser/temp/test1/lemon/juice.png</li> <li>/home/myuser/temp/test1/</li> </ul> <p>Tried to compress <code>/home/myuser/temp/test1/</code> by <code>tarfile.add()</code>.</p> <p>I use with- and without-path modes. With full path it's OK, but with short path I have this problem: <strong>directory exclusion doesn't work because tarfile.add() passes the <em><code>arcname</code></em> parameter to filter method - not <code>name</code> parameter!</strong></p> <blockquote> <p>archive.add(entry, arcname=os.path.basename(entry), filter=self.filter_general)</p> </blockquote> <p>Example:</p> <p>file: <code>/home/myuser/temp/test1/thing/bar.jpg</code> -> <code>arcname = test1/thing/bar.jpg</code></p> <p>So because of <code>/home/myuser/temp/test1/thing</code> element in <code>exclude_dir_fullpath</code>, the filter method should exclude this file, but it can not because filter method gets <code>test1/thing/bar.jpg</code>.</p> <p><strong>How could I access tarfile.add()'s 'name' parameter in filter method?</strong></p> <pre><code>def filter_general(item): exclude_dir_fullpath = ['/home/myuser/temp/test1/thing', '/home/myuser/temp/test1/lemon'] if any(dirname in item.name for dirname in exclude_dir_fullpath): print("Exclude fullpath dir matched at: %s" % item.name) # DEBUG return None return item def compress_tar(): filepath = '/tmp/test.tar.gz' include_dir = '/home/myuser/temp/test1/' archive = tarfile.open(name=filepath, mode="w:gz") archive.add(include_dir, arcname=os.path.basename(include_dir), filter=filter_general) compress_tar() </code></pre>
0
2016-09-11T16:39:02Z
39,439,567
<p>You want to create a general/re-useable function to filter out files given their absolute path name. I understand that filtering on the archive name is not enough since sometimes it would be OK to include a file or not depending on where it is originated.</p> <p>First, add a parameter to your filter function</p> <pre><code>def filter_general(item,root_dir): full_path = os.path.join(root_dir,item.name) </code></pre> <p>Then, replace your "add to archive" code line by:</p> <pre><code>archive.add(include_dir, arcname=os.path.basename(include_dir), filter=lambda x: filter_general(x,os.path.dirname(include_dir))) </code></pre> <p>the filter function has been replaced by a <code>lambda</code> which passes the directory name of the include directory (else, root dir would be repeated)</p> <p>Now your filter function knows the root dir and you can filter by absolute path, allowing you to reuse your filter function in several locations in your code.</p>
0
2016-09-11T18:57:59Z
[ "python", "filter", "compression", "tarfile" ]
Assigning a set properties to each element of a list python
39,438,446
<p>I have a list containing unique items (names if you will) that changes every time I run my script. All of these items have some calculated properties that are modified during the script. For example 'S1' will have pos = 55 and ori = 'R'. I'd like an easy way to access these properties based on their name.</p> <p>What is the best way to 'assign' these properties? I have been looking around and dictionaries do not seem be the right way to go forward so I tried with classes and made the following non-functional code code:</p> <pre><code>class Primer: #contains all properties of a primer def __init__(self): """ Contains all properties of the primer """ self.pos = 0 #outermost 5' position in sequence to bind self.ori = '' #F(orward) or R(everse) primer_list = ['S', 'M1', 'M2', 'M3', 'E'] for i in primer_list: i = primer() print S.pos #this should give me the pos value of 'S' </code></pre> <p>Am I on the right track but missing something or is there a better way to do this?</p> <p><strong>EDIT</strong> I forgot to mentioned that I also need to get my values back somehow. Equally clueless how to do this</p> <pre><code>print primer_list[0].pos #should give me the pos value of S in my example </code></pre>
0
2016-09-11T16:54:16Z
39,438,586
<p>You were having problems with the list, you didn't actually replace the old values with the created instance. I also added a name field so you could keep track of each instance.</p> <pre><code>class Primer: #contains all properties of a primer def __init__(self, name): """ Contains all properties of the primer """ self.name = name self.pos = 0 #outermost 5' position in sequence to bind self.ori = '' #F(orward) or R(everse) def __str__(self): return self.name primer_list = ['S', 'M1', 'M2', 'M3', 'E'] new_primer = [Primer(x) for x in primer_list] for i in new_primer: print i print i.pos print i.ori </code></pre>
0
2016-09-11T17:08:22Z
[ "python", "list", "class" ]
Dynamically importing a module in a Celery task
39,438,504
<p>Is it possible to dynamically import a module in a Celery task?</p> <p>For example, I have a module called <code>hello.py</code> in my working directory:</p> <pre><code>$ cat hello.py def run(): print('hello world') </code></pre> <p>I can import it dynamically with <code>importlib</code>:</p> <pre><code>$ python3 Python 3.5.2 (default, Jul 5 2016, 12:43:10) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import importlib &gt;&gt;&gt; p = importlib.import_module('hello') &gt;&gt;&gt; p.run() hello world </code></pre> <p>I want to do the same as above from a Celery task:</p> <pre><code>@celery.task() def exec_module(module, args={}): print('celery task running: %s' % (module)) print(args) print(os.getcwd()) print(os.listdir()) module = importlib.import_module('hello') module.run() </code></pre> <p>I get the following error when the task runs:</p> <pre><code>[2016-09-11 17:51:48,132: WARNING/MainProcess] celery@user-HP-EliteBook-840-G2 ready. [2016-09-11 17:52:05,516: INFO/MainProcess] Received task: web.tasks.exec_module[f24e3d03-5a17-41dc-afa9-541c99b60a35] [2016-09-11 17:52:05,518: WARNING/Worker-1] celery task running: example_module [2016-09-11 17:52:05,518: WARNING/Worker-1] {'example_file': '/tmp/tmpo4ks9ql0.xml', 'example_string': 'asd'} [2016-09-11 17:52:05,518: WARNING/Worker-1] /home/user/Learning/vision-boilerplate [2016-09-11 17:52:05,518: WARNING/Worker-1] ['run.py', 'requirements.txt', 'gulpfile.js', 'tsconfig.json', 'typings.json', 'package.json', 'vision_modules', 'typings', 'web', 'config', 'hello.py', 'docker-compose.yml', 'ng', 'node_modules', 'Dockerfile'] [2016-09-11 17:52:05,523: ERROR/MainProcess] Task web.tasks.exec_module[f24e3d03-5a17-41dc-afa9-541c99b60a35] raised unexpected: ImportError("No module named 'hello'",) Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/home/user/Learning/vision-boilerplate/web/__init__.py", line 21, in __call__ return TaskBase.__call__(self, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/home/user/Learning/vision-boilerplate/web/tasks.py", line 19, in exec_module module = importlib.import_module('hello') File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 956, in _find_and_load_unlocked ImportError: No module named 'hello' </code></pre> <p>Note from the output of <code>print(os.listdir())</code> (line 6 in the debug output above) that we are definitely in the correct directory and <code>hello.py</code> is right there.</p> <p><strong>Is it possible to dynamically import a module from within a Celery task?</strong></p>
0
2016-09-11T17:00:24Z
39,466,034
<p>Is it possible to dynamically import a module in a Celery task?</p> <p>Yes. Because I have done it. When the module is single and not belong to any package, you should add the directory of the module to the sys path.</p> <blockquote> <p>sys.path.append('path of the module')</p> </blockquote> <p>For example:</p> <pre><code>import importlib import os import sys import celery from demo import celeryconfig # add your path to the sys path sys.path.append(os.getcwd()) app = celery.Celery('tasks',) app.config_from_object(celeryconfig) @celery.task() def exec_module(module, args={}): print('celery task running: %s' % (module)) print(args) print(os.getcwd()) print(os.listdir()) module = importlib.import_module('hello') module.run() </code></pre> <p>I hope it will be helpful for you. Thanks</p>
1
2016-09-13T08:59:34Z
[ "python", "celery", "python-importlib" ]
TypeError: fun() missing 1 required positional argument: 'link'
39,438,509
<p>I am facing a basic problem and unable to resolve it. I am getting this error</p> <blockquote> <p>TypeError: fun() missing 1 required positional argument: 'link'</p> </blockquote> <p>If i give <code>self</code> as positional argument in call of <code>fun()</code> as <code>fun(self,glit)</code> then I an getting </p> <blockquote> <p>Undefined Variable self</p> </blockquote> <p>There is no indentation problem in this small function. I also tried <code>self.fun(glit)</code> But it is also giving</p> <blockquote> <p>Undefined Variable self.</p> </blockquote> <p>If I delete the word <code>self</code> from <code>def fun(self,link):</code> then it is also not working. Any way out?</p> <pre><code>class myClass: def fun(self,link): print("fun") glit = "http://www.google.com" fun(glit) </code></pre>
0
2016-09-11T17:00:52Z
39,438,528
<p>[Edit] Use the <code>__init__</code> function to set variables inside of a class, like</p> <pre><code>def __init__(self): self.glit = 'www.google.com' </code></pre> <p>Now use <code>self.fun(self.glit)</code></p>
0
2016-09-11T17:03:05Z
[ "python" ]
TypeError: fun() missing 1 required positional argument: 'link'
39,438,509
<p>I am facing a basic problem and unable to resolve it. I am getting this error</p> <blockquote> <p>TypeError: fun() missing 1 required positional argument: 'link'</p> </blockquote> <p>If i give <code>self</code> as positional argument in call of <code>fun()</code> as <code>fun(self,glit)</code> then I an getting </p> <blockquote> <p>Undefined Variable self</p> </blockquote> <p>There is no indentation problem in this small function. I also tried <code>self.fun(glit)</code> But it is also giving</p> <blockquote> <p>Undefined Variable self.</p> </blockquote> <p>If I delete the word <code>self</code> from <code>def fun(self,link):</code> then it is also not working. Any way out?</p> <pre><code>class myClass: def fun(self,link): print("fun") glit = "http://www.google.com" fun(glit) </code></pre>
0
2016-09-11T17:00:52Z
39,438,594
<p>The problem is that you are trying to call that code from the class. Class should only contain methods, not your logic. You should call it from outside of the class:</p> <pre><code>class = myClass() glit = "http://www.google.com/" class.fun(glit) </code></pre>
0
2016-09-11T17:09:35Z
[ "python" ]
Removing every nth element from a list until two elements remain in python3
39,438,533
<p>modeling a game of Russian roulette where the contestants stand in a circle. -every 7th contestant loses until 2 are left alive.</p> <pre><code>contestants = list(range(1, 51)) dead_men = [] dead_man = 6 while len(contestants) &gt; 2: if dead_man &gt; len(contestants): dead_man = dead_man - len(contestants) loser = contestants.pop(dead_man) dead_men.append(loser) dead_man += 6 </code></pre> <p>This gives me an index error with an index of 9 when my list length is 8</p>
-1
2016-09-11T17:03:21Z
39,438,576
<p>I assume you meant <code>contestants</code> instead of <code>soldiers</code> everywhere?</p> <p>If so, then I think you just need:</p> <pre><code>while dead_man &gt;= len(contestants): </code></pre> <p>(<code>while</code> rather than <code>if</code> in case you need to subtract multiple times, and <code>&gt;=</code> rather than just <code>&gt;</code> since indexes always need to be less than the length of the list)</p> <p>You might also use <code>dead_man %= len(contestants)</code>. This uses module arithmetic.</p> <p>My favorite way to do this sort of thing with the modulo trick:</p> <pre><code>contestants = list(range(1, 51)) dead_men = [] dead_man = 6 % len(contestants) while len(contestants) &gt; 2: loser = contestants.pop(dead_man) dead_men.append(loser) dead_man = (dead_man + 6) % len(contestants) </code></pre>
0
2016-09-11T17:06:57Z
[ "python" ]
How does Python print a variable that is out of scope
39,438,573
<p>I have the following function in Pyton that seems to be working:</p> <pre><code>def test(self): x = -1 # why don't I need to initialize y = 0 here? if (x &lt; 0): y = 23 return y </code></pre> <p>But for this to work why don't I need to initialize variable y? I thought Python had block scope so how is this possible? </p>
2
2016-09-11T17:06:29Z
39,438,593
<p>This appears to be a simple misunderstanding about <a href="http://stackoverflow.com/q/291978/674039">scope in Python</a>. Conditional statements don't create a scope. The name <code>y</code> is in the local scope inside the function, because of this statement which is present in the syntax tree:</p> <pre><code>y = 23 </code></pre> <p>This is determined at function definition time, when the function is parsed. The fact that the name <code>y</code> might be used whilst unbound at runtime is irrelevant. </p> <p>Here's a simpler example highlighting the same issue:</p> <pre><code>&gt;&gt;&gt; def foo(): ... return y ... y = 23 ... &gt;&gt;&gt; def bar(): ... return y ... &gt;&gt;&gt; foo.func_code.co_varnames ('y',) &gt;&gt;&gt; bar.func_code.co_varnames () &gt;&gt;&gt; foo() # UnboundLocalError: local variable 'y' referenced before assignment &gt;&gt;&gt; bar() # NameError: global name 'y' is not defined </code></pre>
4
2016-09-11T17:09:25Z
[ "python", "block" ]
How does Python print a variable that is out of scope
39,438,573
<p>I have the following function in Pyton that seems to be working:</p> <pre><code>def test(self): x = -1 # why don't I need to initialize y = 0 here? if (x &lt; 0): y = 23 return y </code></pre> <p>But for this to work why don't I need to initialize variable y? I thought Python had block scope so how is this possible? </p>
2
2016-09-11T17:06:29Z
39,438,619
<p>As in <a href="http://stackoverflow.com/questions/2829528/whats-the-scope-of-a-python-variable-declared-in-an-if-statement">What&#39;s the scope of a Python variable declared in an if statement?</a>: "Python variables are scoped to the innermost function or module; control blocks like if and while blocks don't count."</p> <p>Also useful: <a href="http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules">Short Description of Python Scoping Rules</a> </p>
0
2016-09-11T17:11:20Z
[ "python", "block" ]
How does Python print a variable that is out of scope
39,438,573
<p>I have the following function in Pyton that seems to be working:</p> <pre><code>def test(self): x = -1 # why don't I need to initialize y = 0 here? if (x &lt; 0): y = 23 return y </code></pre> <p>But for this to work why don't I need to initialize variable y? I thought Python had block scope so how is this possible? </p>
2
2016-09-11T17:06:29Z
39,438,628
<p>There is actually no block scope in python. Variables may be local (inside of a function) or global (same for the whole scope of the program).</p> <p>Once you've defined the variable y inside the 'if' block its value is kept for this specific function until you specifically delete it using the 'del' command, or the function exits. From the moment y is defined in the function, it is a local variable of this function.</p>
1
2016-09-11T17:11:57Z
[ "python", "block" ]
How does Python print a variable that is out of scope
39,438,573
<p>I have the following function in Pyton that seems to be working:</p> <pre><code>def test(self): x = -1 # why don't I need to initialize y = 0 here? if (x &lt; 0): y = 23 return y </code></pre> <p>But for this to work why don't I need to initialize variable y? I thought Python had block scope so how is this possible? </p>
2
2016-09-11T17:06:29Z
39,440,422
<p>It seems that you misunderstood this part of <a href="https://docs.python.org/3/reference/executionmodel.html" rel="nofollow" title="4. Execution model">Python's documentation</a>:</p> <blockquote> <p>A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.<br> ...<br> A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block.</p> </blockquote> <p>So in this case block is <em>something completely different</em> from visual blocks of your code. Thereby <code>if</code>, <code>for</code>, <code>while</code> statements doesn't have their own scopes. But it is worth noting that <strong>comprehensions and generator expressions are implemented using a function scope</strong>, so they have their own scopes.</p>
2
2016-09-11T20:38:31Z
[ "python", "block" ]
Drawing a random number from set of numbers excluding those given in certain sets
39,438,582
<p>Suppose I have a two arrays:</p> <pre><code>import numpy as np a = np.random.randint(0,10,10) b = np.random.randint(0,10,10) </code></pre> <p>I want to generate another length-10 array whose i-th entry is a random integer drawn from the set (<code>{0...9}</code> <strong>minus</strong> the elements <code>a[i]</code> and <code>b[i]</code>).</p> <p>Being a relative rookie when it comes to NumPy, I thought the easiest way to do this might be:</p> <ol> <li>obtain the set difference <code>x = {0...9} - (a[i] union b[i])</code> for each <code>i</code></li> <li>do <code>np.random.choice(x[i], 1)</code> for each <code>i</code></li> </ol> <p>But I'm finding this a little tricky because I can't figure out how to map <code>setdiff1d</code> elementwise across 2 arrays. Is there an obvious way to do this in NumPy (i.e. ideally without having to resort to Python sets etc.)?</p>
2
2016-09-11T17:07:09Z
39,438,723
<p>Here is one way:</p> <pre><code>In [87]: col = np.array((a, b)).T # Or as a better way np.column_stack((a,b)); suggested by @Divakar In [88]: r = np.arange(10) In [89]: np.ravel([np.random.choice(np.setdiff1d(r, i), 1) for i in col]) Out[89]: array([7, 8, 8, 6, 6, 8, 6, 5, 5, 6]) </code></pre> <p>Or as a numpytonic approach:</p> <pre><code>In [101]: def func(x): return np.random.choice(np.setdiff1d(r, x), 1) .....: In [102]: np.apply_along_axis(func, 1, col).ravel() Out[102]: array([6, 7, 9, 6, 4, 6, 7, 4, 0, 7]) </code></pre>
2
2016-09-11T17:22:53Z
[ "python", "numpy" ]
Drawing a random number from set of numbers excluding those given in certain sets
39,438,582
<p>Suppose I have a two arrays:</p> <pre><code>import numpy as np a = np.random.randint(0,10,10) b = np.random.randint(0,10,10) </code></pre> <p>I want to generate another length-10 array whose i-th entry is a random integer drawn from the set (<code>{0...9}</code> <strong>minus</strong> the elements <code>a[i]</code> and <code>b[i]</code>).</p> <p>Being a relative rookie when it comes to NumPy, I thought the easiest way to do this might be:</p> <ol> <li>obtain the set difference <code>x = {0...9} - (a[i] union b[i])</code> for each <code>i</code></li> <li>do <code>np.random.choice(x[i], 1)</code> for each <code>i</code></li> </ol> <p>But I'm finding this a little tricky because I can't figure out how to map <code>setdiff1d</code> elementwise across 2 arrays. Is there an obvious way to do this in NumPy (i.e. ideally without having to resort to Python sets etc.)?</p>
2
2016-09-11T17:07:09Z
39,438,724
<p>The <code>np.random.choice</code> function seems to not allow to operate on several sets at once. Thus, you will need some form of loop to make the separate calls to <code>np.random.choice</code> for each element of the output. Given that a loop is needed, I don't think one can do much better than your suggestion in the question. The following code implements your idea and hides the required loop a bit by using a list comprehension:</p> <pre><code>import numpy as np a = np.random.randint(0,10,10) b = np.random.randint(0,10,10) domain = set(range(10)) res = [ np.random.choice(list(domain - set(avoid))) for avoid in zip(a, b) ] res = np.array(res) </code></pre>
0
2016-09-11T17:23:26Z
[ "python", "numpy" ]
Namespace questions: Mutable variable doesn't need to be declared as global in function?
39,438,643
<p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p> <p><strong>ex1:</strong></p> <pre><code>def func1(): a = 1 b.add('b') a = 0 b = set() func1() print(a,b) </code></pre> <p>the result is 0 {'b'}</p> <p>Neither a nor b is declared as global, but assignment to b has changed the global value of b, is it because b is mutable variable? </p> <p><strong>ex2:</strong></p> <pre><code>def func1(): b.add('b') def func2(): b = set() func1() func2() print(b) Traceback (most recent call last):   File "test_variables.py", line 10, in &lt;module&gt;     func2()   File "test_variables.py", line 8, in func2     func1()   File "test_variables.py", line 4, in func1     b.add('b') NameError: name 'b' is not defined </code></pre> <p>why in this case, b cannot be assigned in func1()? </p> <p><strong>ex3:</strong></p> <p>I have to pass the variable from function to function </p> <pre><code>def func1(b): b.add('b') def func2(): b = set() func1(b) print(b) func2() </code></pre> <p>it prints {'b'} this time</p> <p><strong>ex4:</strong></p> <p>what I can also do is to define b outside</p> <pre><code>def func1(): b.add('b') def func2(): func1() print(b) b = set() func2() </code></pre> <p>it prints {'b'} as well</p> <p>thanks in advance for your kind help </p>
-1
2016-09-11T17:13:19Z
39,438,767
<p>When you pass a mutable variable to a function you pass if by reference, which means you're creating another variable (which exist only in the scope of the function) which points to the same object.</p> <p>Moreover, Python works in a way that you can use and see variables that are in you're outer scope (that's why in <code>ex1</code> you are able to add things to </p> <p>In <strong>EX1</strong>, <code>func1()</code> knows <code>a</code> and <code>b</code> but cannot assign values to them (unless you define them as <code>global</code> inside the function!). When you're doing <code>a = 1</code>, python just creates a new <code>a</code> variable that lives inside that function only.<br> <code>b.add('b')</code> is possible because you're referring to the <code>set</code> object (which is no mutable). If you'll try to to something like <code>b = 'b'</code> inside the function you will, again, create a local <code>b</code> variable and leave the outer set untouched.</p>
0
2016-09-11T17:28:09Z
[ "python" ]
Namespace questions: Mutable variable doesn't need to be declared as global in function?
39,438,643
<p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p> <p><strong>ex1:</strong></p> <pre><code>def func1(): a = 1 b.add('b') a = 0 b = set() func1() print(a,b) </code></pre> <p>the result is 0 {'b'}</p> <p>Neither a nor b is declared as global, but assignment to b has changed the global value of b, is it because b is mutable variable? </p> <p><strong>ex2:</strong></p> <pre><code>def func1(): b.add('b') def func2(): b = set() func1() func2() print(b) Traceback (most recent call last):   File "test_variables.py", line 10, in &lt;module&gt;     func2()   File "test_variables.py", line 8, in func2     func1()   File "test_variables.py", line 4, in func1     b.add('b') NameError: name 'b' is not defined </code></pre> <p>why in this case, b cannot be assigned in func1()? </p> <p><strong>ex3:</strong></p> <p>I have to pass the variable from function to function </p> <pre><code>def func1(b): b.add('b') def func2(): b = set() func1(b) print(b) func2() </code></pre> <p>it prints {'b'} this time</p> <p><strong>ex4:</strong></p> <p>what I can also do is to define b outside</p> <pre><code>def func1(): b.add('b') def func2(): func1() print(b) b = set() func2() </code></pre> <p>it prints {'b'} as well</p> <p>thanks in advance for your kind help </p>
-1
2016-09-11T17:13:19Z
39,438,770
<p>The following is a simplified answer based on the explanation given in the <a href="https://docs.python.org/2/reference/executionmodel.html" rel="nofollow">Python Language Reference "Naming and Binding"</a> document.</p> <p>Let's look at your first example:</p> <pre><code>def func1(): a = 1 b.add('b') </code></pre> <p>You do two separate operations in this example.</p> <p>First, you take the value <code>1</code> and <strong>bind</strong> it to the name <code>a</code>. This binding takes place <em>in the scope that encloses its execution</em>: In this case, the scope is the function <code>func1</code>.</p> <p>Second, you <strong>look up</strong> the value associated with the name <code>b</code> and call the method <code>add</code> on that value. Since this is in a look up, not a binding, it is not limited to immediately enclosing scope, but will find the <em>nearest enclosing scope</em> that contains that name. In this case, since the scope of function <code>func1</code> does not include the name <code>b</code>, the next enclosing scope is checked: this is the global scope, which <em>does</em> include the name <code>b</code>, and that is the value that is used.</p>
0
2016-09-11T17:28:31Z
[ "python" ]
Namespace questions: Mutable variable doesn't need to be declared as global in function?
39,438,643
<p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p> <p><strong>ex1:</strong></p> <pre><code>def func1(): a = 1 b.add('b') a = 0 b = set() func1() print(a,b) </code></pre> <p>the result is 0 {'b'}</p> <p>Neither a nor b is declared as global, but assignment to b has changed the global value of b, is it because b is mutable variable? </p> <p><strong>ex2:</strong></p> <pre><code>def func1(): b.add('b') def func2(): b = set() func1() func2() print(b) Traceback (most recent call last):   File "test_variables.py", line 10, in &lt;module&gt;     func2()   File "test_variables.py", line 8, in func2     func1()   File "test_variables.py", line 4, in func1     b.add('b') NameError: name 'b' is not defined </code></pre> <p>why in this case, b cannot be assigned in func1()? </p> <p><strong>ex3:</strong></p> <p>I have to pass the variable from function to function </p> <pre><code>def func1(b): b.add('b') def func2(): b = set() func1(b) print(b) func2() </code></pre> <p>it prints {'b'} this time</p> <p><strong>ex4:</strong></p> <p>what I can also do is to define b outside</p> <pre><code>def func1(): b.add('b') def func2(): func1() print(b) b = set() func2() </code></pre> <p>it prints {'b'} as well</p> <p>thanks in advance for your kind help </p>
-1
2016-09-11T17:13:19Z
39,438,790
<p>What your asking about is called scope. Scope is a generic name for what's defined where. So when you declare a variable:</p> <pre><code>b = 0 </code></pre> <p>anything at the same level of scope, or lower can see its definition.</p> <pre><code>b = 1 def func(): print(b) func() </code></pre> <p>This works because b has already been defined in that scope, in this instance b is global(everything can see its definition).</p> <pre><code>def func(): b = 0 def func1(): print(b) func() func1() </code></pre> <p>This will not work because b is now a local variable, its only defined in func(), not func1()</p> <pre><code>b = 1 def func(): b = 0 def func1(): print(b) func() func1() </code></pre> <p>This will print 0 because b was defined at a global level. Setting a global variable to a new value, no matter where you do that, will always make that new value available globally</p> <p>But you also have to consider ordering.</p> <pre><code>print(b) b = 1 </code></pre> <p>will not work</p> <pre><code>b = 1 print(b) b = 0 </code></pre> <p>Will print b = 1 because the value wasn't set to 0, before being print</p>
0
2016-09-11T17:30:18Z
[ "python" ]
Namespace questions: Mutable variable doesn't need to be declared as global in function?
39,438,643
<p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p> <p><strong>ex1:</strong></p> <pre><code>def func1(): a = 1 b.add('b') a = 0 b = set() func1() print(a,b) </code></pre> <p>the result is 0 {'b'}</p> <p>Neither a nor b is declared as global, but assignment to b has changed the global value of b, is it because b is mutable variable? </p> <p><strong>ex2:</strong></p> <pre><code>def func1(): b.add('b') def func2(): b = set() func1() func2() print(b) Traceback (most recent call last):   File "test_variables.py", line 10, in &lt;module&gt;     func2()   File "test_variables.py", line 8, in func2     func1()   File "test_variables.py", line 4, in func1     b.add('b') NameError: name 'b' is not defined </code></pre> <p>why in this case, b cannot be assigned in func1()? </p> <p><strong>ex3:</strong></p> <p>I have to pass the variable from function to function </p> <pre><code>def func1(b): b.add('b') def func2(): b = set() func1(b) print(b) func2() </code></pre> <p>it prints {'b'} this time</p> <p><strong>ex4:</strong></p> <p>what I can also do is to define b outside</p> <pre><code>def func1(): b.add('b') def func2(): func1() print(b) b = set() func2() </code></pre> <p>it prints {'b'} as well</p> <p>thanks in advance for your kind help </p>
-1
2016-09-11T17:13:19Z
39,438,791
<p>This blog post(<a href="http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/" rel="nofollow">1</a>) explains the parameter passing of Python.</p> <p>When you declare b in example 1 you declared it globally.</p> <p>In example two you overwrite the name b so it is only known in func2 and thats why func1 does not know any b.</p> <p>Hope this helps :)</p>
0
2016-09-11T17:30:20Z
[ "python" ]
How to use ExtraTreeClassifier to predict multiclass classifications
39,438,671
<p>I'm quite new to machine learning techniques, and I'm having trouble following some of the scikit-learn documentation and other stackoverflow posts.. I'm trying to create a simple model from a bunch of medical data that will help me predict which of three classes a patient could fall into. </p> <p>I load the data via pandas, convert all the objects to integers (Male = 0, Female=1 for example), and run the following code:</p> <pre><code>import numpy as np import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.preprocessing import label_binarize from sklearn.ensemble import ExtraTreesClassifier # Upload data file with all integers: data = pd.read_csv('datafile.csv') y = data["Target"] features = list(data.columns[:-1]) # Last column being the target data x = data[features] ydata = label_binarize(y, classes=[0, 1, 2]) n_classes = ydata.shape[1] X_train, X_test, y_train, y_test = train_test_split(x, ydata, test_size=.5) model2 = ExtraTreesClassifier() model2.fit(X_train, y_train) out = model2.predict(X_test) print np.min(out),np.max(out) </code></pre> <p>The predicted values of <code>out</code> range between 0.0 and 1.0, but the classes I am trying to predict are 0,1, and 2. What am I missing?</p>
0
2016-09-11T17:16:47Z
39,439,423
<p>That's normal behaviour in scikit-learn.</p> <p>There are two approaches possible:</p> <h3>A:You use "label binarize"</h3> <ul> <li>Binarizing transforms <code>y=[n_samples, ] -&gt; y[n_samples, n_classes]</code> (1 dimension added; integers in range(0, X) get transformed to binary values)</li> <li>Because of this input to fit, <code>classifier.predict()</code> will also return results of the form <code>[n_predict_samples, n_classes]</code> (with 0 and 1 as the only values) / <strong>That's what you observe!</strong></li> <li>Example output: <code>[[0 0 0 1], [1 0 0 0], [0 1 0 0]]</code> = predictions for class: 3, 0, 1</li> </ul> <h3>B: You skip "label binarize" (multi-class handling automatically done by sklearn)</h3> <ul> <li>Without binarizing (assuming your data is using integer-markers for classes): <code>y=[n_samples, ]</code></li> <li>Because of this input to fit, <code>classifier.predict()</code> will also return results of the form <code>[n_predict_samples, ]</code> (with possibly other values than 0, 1)</li> <li>Example output conform to above example: <code>[3 0 1]</code></li> </ul> <p>Both outputs are mentioned in the docs <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesClassifier.html#sklearn.ensemble.ExtraTreesClassifier.predict" rel="nofollow">here</a>:</p> <pre><code>predict(X) Returns: y : array of shape = [n_samples] or [n_samples, n_outputs] The predicted classes. </code></pre> <p><strong>Remark</strong>: the above behaviour should be valid for most/all classifiers! (not only <em>ExtraTreesClassifier</em>)</p>
1
2016-09-11T18:41:16Z
[ "python", "python-2.7", "scikit-learn", "decision-tree" ]
Get attributes from a returned function in Python
39,438,732
<pre><code>def outerFunc(number): if number &lt; 0: def innerFunc(factor): return number * factor else: def innerFunc(summand): return number + summand return innerFunc x = outerFunc(-8) print(x(4)) </code></pre> <p>The result of the print statement is <code>-32</code>, as expected. I'm using Python 3.5.2</p> <p>I would like to ask two questions regarding this code snippet:</p> <ol> <li>Is it possible to access the inner function's <code>number</code> property, after having bound <code>innerFunc</code> to <code>x</code> with the statement <code>x = outerFunc(-8)</code>? In other words: is it possible to directly access the preserved value of <code>number</code>, in this case <code>-8</code>, after having performed the closure?</li> <li>Is it good programming style to return a function, depending on the evaluation of an if-statement? Personally, I think there is better approach, but I'm not sure.</li> </ol> <p>Thanks for your help.</p>
1
2016-09-11T17:24:06Z
39,438,813
<blockquote> <p>Is it possible to access the inner function's <code>number</code> property</p> </blockquote> <p>It's not a property. You can technically access it, but not in a particularly nice way:</p> <pre><code>number = x.__closure__[0].cell_contents </code></pre> <blockquote> <p>Is it good programming style to return a function, depending on the evaluation of an if-statement?</p> </blockquote> <p>Yeah, it's fine.</p>
2
2016-09-11T17:32:51Z
[ "python", "closures" ]
Get attributes from a returned function in Python
39,438,732
<pre><code>def outerFunc(number): if number &lt; 0: def innerFunc(factor): return number * factor else: def innerFunc(summand): return number + summand return innerFunc x = outerFunc(-8) print(x(4)) </code></pre> <p>The result of the print statement is <code>-32</code>, as expected. I'm using Python 3.5.2</p> <p>I would like to ask two questions regarding this code snippet:</p> <ol> <li>Is it possible to access the inner function's <code>number</code> property, after having bound <code>innerFunc</code> to <code>x</code> with the statement <code>x = outerFunc(-8)</code>? In other words: is it possible to directly access the preserved value of <code>number</code>, in this case <code>-8</code>, after having performed the closure?</li> <li>Is it good programming style to return a function, depending on the evaluation of an if-statement? Personally, I think there is better approach, but I'm not sure.</li> </ol> <p>Thanks for your help.</p>
1
2016-09-11T17:24:06Z
39,438,830
<ol> <li>No.</li> <li>Rarely, but there are cases where it could make sense. If you have to ask the question, you should probably consider the answer to be 'no,' at least for now.</li> </ol>
-1
2016-09-11T17:34:51Z
[ "python", "closures" ]
What is the difference between Cerberus Custom Rules and Custom Validators?
39,438,774
<p>From the <a href="http://docs.python-cerberus.org/en/latest/customize.html#custom-rules" rel="nofollow">documentation</a>, it is not clear to me what the difference in use case for the Custom Rule and the Custom Validators are. In the examples given in the documentation, the only difference is an extra <code>if</code> statement that checks the value of <code>is_odd</code> in the custom rule. When should I prefer the Custom Rule, and when should I prefer the Custom Validator?</p> <hr> <p>Custom Rule</p> <pre><code>schema = {'amount': {'isodd': True, 'type': 'integer'}} from cerberus import Validator class MyValidator(Validator): def _validate_isodd(self, isodd, field, value): """ Test the oddity of a value. The rule's arguments are validated against this schema: {'type': 'boolean'} """ if isodd and not bool(value &amp; 1): self._error(field, "Must be an odd number") </code></pre> <hr> <p>Custom Validator</p> <pre><code>from cerberus import Validator schema = {'amount': {'validator': 'oddity'}} class AValidator(Validator): def _validator_oddity(self, field, value): if value &amp; 1: self._error(field, "Must be an odd number") </code></pre>
2
2016-09-11T17:28:59Z
39,452,599
<p>You use the <code>validator</code> rule when you want to delegate validation of a certain field to a custom function, like so:</p> <pre><code>&gt;&gt;&gt; def oddity(field, value, error): ... if not value &amp; 1: ... error(field, "Must be an odd number") &gt;&gt;&gt; schema = {'amount': {'validator': oddity}} &gt;&gt;&gt; v = Validator(schema) &gt;&gt;&gt; v.validate({'amount': 10}) False &gt;&gt;&gt; v.errors {'amount': 'Must be an odd number'} &gt;&gt;&gt; v.validate({'amount': 9}) True </code></pre> <p>Custom rules are only used in your <code>Validator</code> subclass whereas custom validators are delegate functions. It appears that the documentation for the <code>validator</code> rule is misleading if not plain wrong, and I should go and fix it as soon as possible! Thanks for reporting.</p>
1
2016-09-12T14:23:02Z
[ "python", "cerberus" ]
Biggest number in a text file
39,438,927
<p>I have a text file with numbers and names in the following format:</p> <pre><code>129308123, Some Name 12390123, Some Other Name </code></pre> <p>I am trying to grab the biggest number in this textfile and also read on what line it is located. I tried multiple methods but none seem to be working for me. What am I doing wrong?</p> <p>My code:</p> <pre><code>file_in = open('kaartnummers.txt', 'r') regels = len(file_in.readlines()) smallestInt = 0 intList = [int(x) for x in file_in.readlines()] number = max(intList) laatsteregel = '' string_format = 'Deze file telt {0} regels\n' \ 'Het grootste kaartnummer is: {1} en dat staat op regel {2}' result = string_format.format(regels, number, laatsteregel) print(result) </code></pre>
-1
2016-09-11T17:45:29Z
39,439,150
<p>To find the largest number in the file, split the line with <code>split</code></p> <pre><code>file_in = open('kaartnummers.txt', 'r') smallestInt = 0 intList = [int(x.split(",")[0]) for x in file_in.readlines()] print(intList) regels = len(intList) number = max(intList) laatsteregel = '' string_format = 'Deze file telt {0} regels\n' \ 'Het grootste kaartnummer is: {1} en dat staat op regel {2}' result = string_format.format(regels, number, laatsteregel) print(result) </code></pre> <p><strong>kaartnummers.txt</strong></p> <pre><code>11, Bob 22, James 33, Nick 23, Steve 25, John 21, Ken </code></pre> <p>Output</p> <pre><code>python pyprog.py [11, 22, 33, 23, 25, 21] Deze file telt 6 regels Het grootste kaartnummer is: 33 en dat staat op regel </code></pre> <p>To get the line number, you can use this code (remember it starts at 0)</p> <pre><code>print("line number " + str(intList.index(max(intList)))) </code></pre>
0
2016-09-11T18:09:56Z
[ "python", "python-3.x" ]
python SQL query insert shows empty rows
39,438,941
<p>I am trying to do a insert query in the SQL. It indicates that it succeed but shows no record in the database. Here's my code </p> <pre><code>conn = MySQLdb.connect("localhost",self.user,"",self.db) cursor = conn.cursor() id_val = 123456; path_val = "/homes/error.path" host_val = "123.23.45.64" time_val = 7 cursor.execute("INSERT INTO success (id,path,hostname,time_elapsed) VALUES (%s,%s,%s,%s)", (id_val, path_val,host_val,time_val)) print "query executed" rows = cursor.fetchall() print rows </code></pre> <p>this outputs the following </p> <pre><code>query executed () </code></pre> <p>it gives me no errors but the database seems to be empty. I tried my SQL query in the mysql console. executed the following command.</p> <pre><code>INSERT INTO success (id,path,hostname,time_elapsed) VALUES (1,'sometext','hosttext',4); </code></pre> <p>This works fine as I can see the database got populated.</p> <pre><code>mysql&gt; SELECT * FROM success LIMIT 5; +----+----------+----------+--------------+ | id | path | hostname | time_elapsed | +----+----------+----------+--------------+ | 1 | sometext | hosttext | 4 | +----+----------+----------+--------------+ </code></pre> <p>so I am guessing the SQL query command is right. Not sure why my <code>cursor.execute</code> is not responding. Could someone please point me to the right direction. Can't seem to figure out the bug. thanks</p>
0
2016-09-11T17:46:21Z
39,439,178
<p>After you are sending your INSERT record, you should commit your changes in the database:</p> <pre><code>cursor.execute("INSERT INTO success (id,path,hostname,time_elapsed) VALUES (%s,%s,%s,%s)", (id_val, path_val,host_val,time_val)) conn.commit() </code></pre> <p>When you want to read the data, you should first send your query as you did through your interpreter.</p> <p>So before you fetch the data, execute the SELECT command:</p> <pre><code>cursor.execute("SELECT * FROM success") rows = cursor.fetchall() print rows </code></pre> <p>If you want to do it pythonic:</p> <pre><code>cursor.execute("SELECT * FROM success") for row in cursor: print(row) </code></pre>
0
2016-09-11T18:13:18Z
[ "python", "mysql", "python-2.7", "mysql-python" ]
What is the cleanest way of setting default values for attributes unless provided by the class call?
39,439,011
<p>Currently this is what I'm doing:</p> <pre><code>class NewShip: def __init__(self, position = (0,0), x_velocity = 25, y_velocity = 15, anim_frame = 1, frame1 = "space_ship_1.png", frame2 = "space_ship_2.png", angle = 0, border_size = 900): self.position = position self.angle = angle self.x_velocity = x_velocity #in pixels per frame self.y_velocity = y_velocity #in pixels per frame self.anim_frame = anim_frame self.frame1 = pygame.image.load(frame1).convert_alpha() self.frame2 = pygame.image.load(frame2).convert_alpha() self.frame1 = pygame.transform.scale(self.frame1, (128,128)) self.frame2 = pygame.transform.scale(self.frame2, (128,128)) self.position = DummyObject() self.position.x = position[0] self.position.y = position[1] self.border_size = border_size </code></pre> <p>but honestly that's quite tedious and makes adding any more facultative attributes a real pain.</p> <p>Should I just skip the whole 'letting people declare attributes with keyword arguments' thing and just instantiate objects in a fully default state before changing any of their attributes?</p> <p>EDIT: apparently this works perfectly:</p> <pre><code>class NewShip: def __init__(self, **kwargs): self.angle = 0 self.x_velocity = 25 #in pixels per frame self.y_velocity = 15 #in pixels per frame self.anim_frame = 1 frame1 = "space_ship_1.png" frame2 = "space_ship_2.png" self.position = DummyObject() self.position.x = 0 self.position.y = 0 self.border_size = 900 for element in kwargs: setattr(self, element, kwargs[element]) self.frame1 = pygame.image.load(frame1).convert_alpha() self.frame2 = pygame.image.load(frame2).convert_alpha() self.frame1 = pygame.transform.scale(self.frame1, (128,128)) self.frame2 = pygame.transform.scale(self.frame2, (128,128)) </code></pre> <p>that is, just setting all defaults values then overriding them with the keyword args using <code>for element in kwargs: setattr(self, element, kwargs[element])</code></p> <p>Let me know if there's any cleaner way, though I have to say I'm much more satisfied with this.</p>
2
2016-09-11T17:55:24Z
39,439,219
<p>To reduce the clutter, you could alternatively define a defaults dictionary attribute <code>_init_attrs</code> for example, define your function with <code>**kwargs</code> and then <code>setattr</code> on <code>self</code> with a loop, using <code>_init_attrs[k]</code> as a <code>default</code> value for <code>kwargs.get</code> when no parameters were supplied:</p> <pre><code>class NewShip: def __init__(self, **kwargs): _init_attrs = {'angle': 0, 'anim_frame': 1, 'border_size': 900, 'frame1': 'space_ship_1.png', 'frame2': 'space_ship_2.png', 'position': (0, 0), 'x_velocity': 25, 'y_velocity': 15 } for k, v in _init_attrs.items(): setattr(self, k, kwargs.get(k, v) </code></pre> <p>This makes <code>__init__</code> a bit more mystifying but achieves the goal of making it way more extensible while cutting down the size.</p>
3
2016-09-11T18:17:19Z
[ "python", "python-3.x" ]
file is not defined, python 3.5
39,439,018
<p>I try to create an xml file. THis is the program I am using python 3.5 and as IDE pycharm. Do I miss a library? Or something? Or is it the IDE what not correct is?</p> <p>but I get this error:</p> <pre><code>NameError: name 'file' is not defined </code></pre> <p>I have this:</p> <pre><code>import datetime import random import time def main(): # Write an XML file with the results file = open("ListAccessTiming.xml","w") file.write('&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt;\n') file.write('&lt;Plot title="Average List Element Access Time"&gt;\n') xmin = 1000 xmax = 200000 # Record the list sizes in xList and the average access time within # a list that size in yList for 1000 retrievals. xList = [] yList = [] for x in range(xmin, xmax+1, 1000): xList.append(x) prod = 0 lst = [0] * x # let any garbage collection/memory allocation complete or at least # settle down time.sleep(1) # Time before the 1000 test retrievals starttime = datetime.datetime.now() for v in range(1000): # Find a random location within the list # and retrieve a value. Do a dummy operation # with that value to ensure it is really retrieved. index = random.randint(0,x-1) val = lst[index] prod = prod * val # Time after the 1000 test retrievals endtime = datetime.datetime.now() # The difference in time between start and end. deltaT = endtime - starttime # Divide by 1000 for the average access time # But also multiply by 1000000 for microseconds. accessTime = deltaT.total_seconds() * 1000 yList.append(accessTime) file.write(' &lt;Axes&gt;\n') file.write(' &lt;XAxis min="’+str(xmin)+’" max="’+str(xmax)+’"&gt;List Size&lt;/XAxis&gt;\n') file.write(' &lt;YAxis min="’+str(min(yList))+’" max="’+str(60)+’"&gt;Microseconds&lt;/YAxis&gt;\n') file.write(' &lt;/Axes&gt;\n') file.write(' &lt;Sequence title="Average Access Time vs List Size" color="red"&gt;\n') for i in range(len(xList)): file.write('&lt;DataPoint x="’+str(xList[i])+’" y="’+str(yList[i])+’"/&gt;\n') file.write('&lt;/Sequence&gt;\n') # This part of the program tests access at 100 random locations within a list # of 200,000 elements to see that all the locations can be accessed in # about the same amount of time. xList = lst yList = [0] * 200000 time.sleep(2) for i in range(100): starttime = datetime.datetime.now() index = random.randint(0,200000-1) xList[index] = xList[index] + 1 endtime = datetime.datetime.now() deltaT = endtime - starttime yList[index] = yList[index] + deltaT.total_seconds() * 1000000 file.write('&lt;Sequence title="Access Time Distribution" color="blue"&gt;\n'); for i in range(len(xList)): if xList[i] &gt; 0: file.write('&lt;DataPoint x="’+str(i)+’" y="’+str(yList[i]/xList[i])+’"/&gt;\n') file.write('&lt;/Sequence&gt;\n') file.write('&lt;/Plot&gt;\n') file.close() if __name__ == "__main__": main() </code></pre> <p>Thank you</p>
0
2016-09-11T17:56:03Z
39,439,390
<p>tab problem !</p> <p>file variable is not into def main section </p> <p>def main and file have not indentation </p> <p>also your main is not called in your tool's</p>
1
2016-09-11T18:36:43Z
[ "python", "python-3.x" ]
file is not defined, python 3.5
39,439,018
<p>I try to create an xml file. THis is the program I am using python 3.5 and as IDE pycharm. Do I miss a library? Or something? Or is it the IDE what not correct is?</p> <p>but I get this error:</p> <pre><code>NameError: name 'file' is not defined </code></pre> <p>I have this:</p> <pre><code>import datetime import random import time def main(): # Write an XML file with the results file = open("ListAccessTiming.xml","w") file.write('&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt;\n') file.write('&lt;Plot title="Average List Element Access Time"&gt;\n') xmin = 1000 xmax = 200000 # Record the list sizes in xList and the average access time within # a list that size in yList for 1000 retrievals. xList = [] yList = [] for x in range(xmin, xmax+1, 1000): xList.append(x) prod = 0 lst = [0] * x # let any garbage collection/memory allocation complete or at least # settle down time.sleep(1) # Time before the 1000 test retrievals starttime = datetime.datetime.now() for v in range(1000): # Find a random location within the list # and retrieve a value. Do a dummy operation # with that value to ensure it is really retrieved. index = random.randint(0,x-1) val = lst[index] prod = prod * val # Time after the 1000 test retrievals endtime = datetime.datetime.now() # The difference in time between start and end. deltaT = endtime - starttime # Divide by 1000 for the average access time # But also multiply by 1000000 for microseconds. accessTime = deltaT.total_seconds() * 1000 yList.append(accessTime) file.write(' &lt;Axes&gt;\n') file.write(' &lt;XAxis min="’+str(xmin)+’" max="’+str(xmax)+’"&gt;List Size&lt;/XAxis&gt;\n') file.write(' &lt;YAxis min="’+str(min(yList))+’" max="’+str(60)+’"&gt;Microseconds&lt;/YAxis&gt;\n') file.write(' &lt;/Axes&gt;\n') file.write(' &lt;Sequence title="Average Access Time vs List Size" color="red"&gt;\n') for i in range(len(xList)): file.write('&lt;DataPoint x="’+str(xList[i])+’" y="’+str(yList[i])+’"/&gt;\n') file.write('&lt;/Sequence&gt;\n') # This part of the program tests access at 100 random locations within a list # of 200,000 elements to see that all the locations can be accessed in # about the same amount of time. xList = lst yList = [0] * 200000 time.sleep(2) for i in range(100): starttime = datetime.datetime.now() index = random.randint(0,200000-1) xList[index] = xList[index] + 1 endtime = datetime.datetime.now() deltaT = endtime - starttime yList[index] = yList[index] + deltaT.total_seconds() * 1000000 file.write('&lt;Sequence title="Access Time Distribution" color="blue"&gt;\n'); for i in range(len(xList)): if xList[i] &gt; 0: file.write('&lt;DataPoint x="’+str(i)+’" y="’+str(yList[i]/xList[i])+’"/&gt;\n') file.write('&lt;/Sequence&gt;\n') file.write('&lt;/Plot&gt;\n') file.close() if __name__ == "__main__": main() </code></pre> <p>Thank you</p>
0
2016-09-11T17:56:03Z
39,439,398
<p>Python is all about indentation. Blocks are defined by indentation. You define a function <code>main()</code> and start its indented block...</p> <pre><code>def main(): # Write an XML file with the results file = open("ListAccessTiming.xml","w") file.write('&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt;\n') </code></pre> <p>And then you <em>exit</em> that indented block and try to use the <code>file</code> variable:</p> <pre><code>file.write('&lt;Plot title="Average List Element Access Time"&gt;\n') </code></pre> <p>If you are to have the <code>main()</code> function do all your work, then it all needs to be properly indented within the <code>main()</code> function (which, by the way, you never call): (This code has also been reformatted to use a python-normal 4-space indentation)</p> <pre><code>def main(): # Write an XML file with the results file = open("ListAccessTiming.xml","w") file.write('&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt;\n') file.write('&lt;Plot title="Average List Element Access Time"&gt;\n') # ... (rest of your code here) ... # let any garbage collection/memory allocation complete or at least # settle down time.sleep(1) main() </code></pre> <p>If you want to do the work in the module directly, don't bother defining the <code>main()</code> function, and properly indent your code for use at the module level (meaning the top level statements have no indentation):</p> <pre><code># Write an XML file with the results file = open("ListAccessTiming.xml","w") file.write('&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt;\n') file.write('&lt;Plot title="Average List Element Access Time"&gt;\n') # ... (rest of your code here) ... # let any garbage collection/memory allocation complete or at least # settle down time.sleep(1) </code></pre>
1
2016-09-11T18:37:35Z
[ "python", "python-3.x" ]
Python Error message when opening .txt file / change in working directory
39,439,020
<p>I’m a new python user and have written a python script that prompts for the name of a text file (.txt) to be opened and read by the program. </p> <pre><code>name = raw_input("Enter file:") if len(name) &lt; 1: name = "test.txt" handle = open(name) </code></pre> <p>This was working perfectly fine for me, but then I installed Anaconda and tried to run the same <code>.py</code> script and kept getting this error message:</p> <pre><code>$ python /test123.py Enter file:'test.txt' Traceback (most recent call last): File "/test123.py", line 26, in &lt;module&gt; handle = open(name) IOError: [Errno 2] No such file or directory: "'test.txt'" </code></pre> <p>even though I had changed nothing in the script or text file and the text file definitely exists in the directory. So then I uninstalled Anaconda and deleted the Anaconda directory as well as the PATH variable pointing to Anaconda in the <code>~/.bash_profile</code> file to see if that would fix the problem. But I’m still getting the same error :( What’s wrong? I do not get any error if I run the file in the Terminal directly from TextWrangler, and my <code>.py</code> script contains the shebang line <code>#!/usr/bin/env python</code></p> <p>My info:</p> <pre><code>$ sw_vers ProductName: Mac OS X ProductVersion: 10.11.6 BuildVersion: 15G1004 $ python Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 26 2016, 12:10:39) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin $ which python /Library/Frameworks/Python.framework/Versions/2.7/bin/python $ /usr/bin/python -V Python 2.7.10 </code></pre> <p>Thanks so much for the time and help!</p> <p><strong>EDIT:</strong> I copied both the <code>test123.py</code> document and the <code>test.txt</code> file and put them in the directory <code>/Users/myusername/Documents</code> and ran the script again, this time inputting <code>/Users/myusername/Documents/test.txt</code> (without quotes) at the "Enter file" prompt, and it worked fine! So now I need to modify my question:</p> <p>My understanding--and what had been working fine for me previously--is that when a python script is run, the working directory automatically changes to the directory that the <code>.py</code> file is inside. Is this not correct? Or how could I change my settings back to that, since somehow it seemed to have been the case before but now isn't.</p> <p><strong>EDIT 2:</strong> Now that I've realized the source of my original error was a result of the working directory Python was using, I've been able to solve my problem by adding the following lines to my <code>test123.py</code> script:</p> <pre><code>import os abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) </code></pre> <p>as suggested here: <a href="http://stackoverflow.com/questions/1432924/python-change-the-scripts-working-directory-to-the-scripts-own-directory">python: Change the scripts working directory to the script&#39;s own directory</a></p> <p>However, I'm also selecting the answer provided by @SomethingSomething because now that I've been able to change the working directory, the input <code>'test.txt'</code> (with quotes) is not valid, but <code>test.txt</code> (without quotes) works as desired.</p> <p>(The only thing I'm still wondering about is why previously, when I was running python scripts, the working directory automatically changed to the directory that the <code>.py</code> file was inside, and then somehow the setting changed, corresponding with my installation of Anaconda. However, now that I've solved my problem this seems unimportant.)</p> <p>Thanks everyone for the help!</p>
1
2016-09-11T17:56:17Z
39,439,101
<p>It's very simple, your input is wrong:</p> <p>Incorrect:</p> <pre><code>$ python /test123.py Enter file:'test.txt' </code></pre> <p>Correct:</p> <pre><code>$ python /test123.py Enter file:test.txt </code></pre> <p>do not include the <code>'</code> characters. It is not code, it's just standard input</p>
3
2016-09-11T18:04:25Z
[ "python", "python-2.7" ]