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
In python how can I add a special case to a regex function?
39,693,490
<p>Say for example I want to remove the following strings from a string: </p> <pre><code>remove = ['\\u266a','\\n'] </code></pre> <p>And I have regex like this:</p> <pre><code>string = re.sub('[^A-Za-z0-9]+', '', string) </code></pre> <p>How can I add "remove" to my regex function?</p>
1
2016-09-26T01:25:12Z
39,693,578
<p>No need for a special case. Just call re.sub in a loop for each member of your remove list.</p>
0
2016-09-26T01:37:22Z
[ "python", "regex" ]
Import Error: No Module named common
39,693,497
<p>My folder structure in pycharm is as follows.</p> <pre><code>--python --concepts --common --myds.py --__init__.py --data_structures --test_ds.py </code></pre> <p>I have the following line in <code>test_ds.py</code></p> <pre><code>from common import my_ds </code></pre> <p>I get the following error.</p> <pre><code>ImportError: No module named 'common' </code></pre> <p>I have added <code>common</code> to <code>Settings --&gt; Project Interpreter -&gt; Interpreter Paths</code> and the folder shows up as <code>library root</code>.</p> <p>Still why am I getting this error.</p>
0
2016-09-26T01:26:00Z
39,693,728
<p>You need to make your common folder into a python package in order to import it in python. I think you've tried to do it and created <code>init</code> file in your <code>common</code> folder but actually it must be <code>__init__.py</code>. Rename it like this and then your package will be visible to python.</p> <p>Hope it helps!</p>
0
2016-09-26T02:02:47Z
[ "python", "python-3.x", "pycharm" ]
Import Error: No Module named common
39,693,497
<p>My folder structure in pycharm is as follows.</p> <pre><code>--python --concepts --common --myds.py --__init__.py --data_structures --test_ds.py </code></pre> <p>I have the following line in <code>test_ds.py</code></p> <pre><code>from common import my_ds </code></pre> <p>I get the following error.</p> <pre><code>ImportError: No module named 'common' </code></pre> <p>I have added <code>common</code> to <code>Settings --&gt; Project Interpreter -&gt; Interpreter Paths</code> and the folder shows up as <code>library root</code>.</p> <p>Still why am I getting this error.</p>
0
2016-09-26T01:26:00Z
39,693,734
<p>Try <code>from ..common import my_ds</code>. Also make sure that it has an <code>__init__.py</code> file in that directory (not required but it's good practice).</p> <p>As for the <code>..</code> they indicate that you're importing from the parent package to the one you're currently on.</p>
1
2016-09-26T02:03:19Z
[ "python", "python-3.x", "pycharm" ]
How to use the __init__ from the main object class in an inherited class?
39,693,512
<p>I have a program that I will be using inheritance in:</p> <pre><code>class Templates(object): def __init__(self, esd_user, start_date, summary, ticket_number, email_type): self.esd = esd_user self.strt_day = start_date self.sum = summary self.ticket = ticket_number self.email = email_type def gather_intel(self): if self.email == "pend": PendingEmail(self.esd, self.ticket, self.strt_day) elif self.email == "generic": GenericEmail(self.esd, self.ticket, self.strt_day) elif self.email == "resolve": ResolveEmail(self.esd, self.ticket, self.strt_day) elif self.email == "osha": OshaEmail(self.esd, self.ticket, self.strt_day) else: return False class PendingEmail(Templates): pass class GenericEmail(Templates): pass class ResolveEmail(Templates): pass class OshaEmail(Templates): pass </code></pre> <p>Is it possible for me to use the <code>__init__</code> from the <code>Templates</code> class as the <code>__init__</code> for the other inherited classes, without having to rewrite the <code>__init__</code> method? Would a call to <code>super</code> be necessary here?</p> <p>For example, is this the proper way to inherit the <code>__init__</code> function from the main <code>Templates</code> class?</p> <pre><code>class PendingEmail(Templates): def __init__(self): super(Templates, self).__init__() </code></pre>
0
2016-09-26T01:27:34Z
39,693,535
<p>If you don't need to add anything to the <code>__init__</code> for the subclasses, just don't implement it, and they'll inherit it automatically. Otherwise, you're a little off for cases where you need to do further initialization:</p> <pre><code>class PendingEmail(Templates): def __init__(self): super(PendingEmail, self).__init__() # Name your own class, not the super class </code></pre>
1
2016-09-26T01:31:14Z
[ "python", "python-2.7", "oop", "inheritance" ]
How to use the __init__ from the main object class in an inherited class?
39,693,512
<p>I have a program that I will be using inheritance in:</p> <pre><code>class Templates(object): def __init__(self, esd_user, start_date, summary, ticket_number, email_type): self.esd = esd_user self.strt_day = start_date self.sum = summary self.ticket = ticket_number self.email = email_type def gather_intel(self): if self.email == "pend": PendingEmail(self.esd, self.ticket, self.strt_day) elif self.email == "generic": GenericEmail(self.esd, self.ticket, self.strt_day) elif self.email == "resolve": ResolveEmail(self.esd, self.ticket, self.strt_day) elif self.email == "osha": OshaEmail(self.esd, self.ticket, self.strt_day) else: return False class PendingEmail(Templates): pass class GenericEmail(Templates): pass class ResolveEmail(Templates): pass class OshaEmail(Templates): pass </code></pre> <p>Is it possible for me to use the <code>__init__</code> from the <code>Templates</code> class as the <code>__init__</code> for the other inherited classes, without having to rewrite the <code>__init__</code> method? Would a call to <code>super</code> be necessary here?</p> <p>For example, is this the proper way to inherit the <code>__init__</code> function from the main <code>Templates</code> class?</p> <pre><code>class PendingEmail(Templates): def __init__(self): super(Templates, self).__init__() </code></pre>
0
2016-09-26T01:27:34Z
39,693,538
<p>Like any other method, classes automatically inherit <code>__init__</code> from their superclasses. What you want to achieve is already happening.</p>
0
2016-09-26T01:31:50Z
[ "python", "python-2.7", "oop", "inheritance" ]
How to use the __init__ from the main object class in an inherited class?
39,693,512
<p>I have a program that I will be using inheritance in:</p> <pre><code>class Templates(object): def __init__(self, esd_user, start_date, summary, ticket_number, email_type): self.esd = esd_user self.strt_day = start_date self.sum = summary self.ticket = ticket_number self.email = email_type def gather_intel(self): if self.email == "pend": PendingEmail(self.esd, self.ticket, self.strt_day) elif self.email == "generic": GenericEmail(self.esd, self.ticket, self.strt_day) elif self.email == "resolve": ResolveEmail(self.esd, self.ticket, self.strt_day) elif self.email == "osha": OshaEmail(self.esd, self.ticket, self.strt_day) else: return False class PendingEmail(Templates): pass class GenericEmail(Templates): pass class ResolveEmail(Templates): pass class OshaEmail(Templates): pass </code></pre> <p>Is it possible for me to use the <code>__init__</code> from the <code>Templates</code> class as the <code>__init__</code> for the other inherited classes, without having to rewrite the <code>__init__</code> method? Would a call to <code>super</code> be necessary here?</p> <p>For example, is this the proper way to inherit the <code>__init__</code> function from the main <code>Templates</code> class?</p> <pre><code>class PendingEmail(Templates): def __init__(self): super(Templates, self).__init__() </code></pre>
0
2016-09-26T01:27:34Z
39,693,542
<p>If you don't define an <code>__init__</code> method in your subclass, your base class <code>__init__</code> will still get called. If you define one, then you need to explicitly call it like you have described before/after any other actions you need. The first argument to super is the class where it is being called.</p>
0
2016-09-26T01:32:04Z
[ "python", "python-2.7", "oop", "inheritance" ]
I have been using pyimgur to upload pictures and I would like to know how to delete them
39,693,682
<p>I have been using this code to upload pictures to imgur:</p> <pre><code>import pyimgur CLIENT_ID = "Your_applications_client_id" PATH = "A Filepath to an image on your computer" im = pyimgur.Imgur(CLIENT_ID) uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur") print(uploaded_image.title) print(uploaded_image.link) print(uploaded_image.size) print(uploaded_image.type) </code></pre> <p>I'm using the client ID from my Imgur account, but after I upload them they wont't appear among my user photos.</p> <p>Do you know where are they stored and how can I delete them? Many thanks in advance.</p>
0
2016-09-26T01:55:01Z
39,693,789
<p>You can delete your images using the method <code>remove_images(list_images)</code>, <code>list_images</code> are the images we want to remove from the album, this method deletes images but no the album itself . If you want delete the album you can use <code>delete()</code> method. You can read the <a href="http://pyimgur.readthedocs.io/en/latest/reference.html" rel="nofollow">docs</a> for more information.</p> <p>Maybe your PATH variable is wrong and your pictures don't upload correctly.</p>
0
2016-09-26T02:12:45Z
[ "python", "imgur" ]
Most efficient way to iterate through list of lists
39,693,722
<p>I'm currently collecting data from quandl and is saved as a list of lists. The list looks something like this (Price data):</p> <pre><code>['2', 1L, datetime.date(1998, 1, 2), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), '82.1900', '83.6200', '81.7500', '83.5000', '28.5183', 1286500.0] </code></pre> <p>This is typically 1 of about 5000 lists, and every once in awhile Quandl will spit back some <code>NaN</code> values that don't like being saved into the database.</p> <pre><code>['2', 1L, datetime.date(1998, 1, 2), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), 'nan', 'nan', 'nan', 'nan', 'nan', 0] </code></pre> <p>What would be the most efficient way of iterating through the list of lists to change 'nan' values into zeros?</p> <p>I know I could do something like this, but it seems rather inefficient. This operation will need to be performed on 11 different values * 5000 different dates * 500 companies:</p> <pre><code>def screen_data(data): new_data = [] for d in data: new_list = [] for x in d: new_value = x if math.isNan(x): new_value = 0 new_list.append(new_value) new_data.append(new_list) return new_data </code></pre> <p>I would be interested in any solution that could reduce the time. I know DataFrames might work, but not sure how it would solve the NaN issue.</p> <p>Or if there is a way to include NaN values in an SQLServer5.6 database along with floats, changing the database is also a viable option.</p>
0
2016-09-26T02:01:36Z
39,693,850
<p>Don't create a new list - rather, edit the old list in-place:</p> <pre><code>import math def screenData(L): for subl in L: for i,n in enumerate(subl): if math.isnan(n): subl[i] = 0 </code></pre> <p>The only way I can think of, to make this faster, would be with multiprocessing</p>
2
2016-09-26T02:22:38Z
[ "python", "performance", "list", "mysql-python", null ]
Most efficient way to iterate through list of lists
39,693,722
<p>I'm currently collecting data from quandl and is saved as a list of lists. The list looks something like this (Price data):</p> <pre><code>['2', 1L, datetime.date(1998, 1, 2), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), '82.1900', '83.6200', '81.7500', '83.5000', '28.5183', 1286500.0] </code></pre> <p>This is typically 1 of about 5000 lists, and every once in awhile Quandl will spit back some <code>NaN</code> values that don't like being saved into the database.</p> <pre><code>['2', 1L, datetime.date(1998, 1, 2), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), 'nan', 'nan', 'nan', 'nan', 'nan', 0] </code></pre> <p>What would be the most efficient way of iterating through the list of lists to change 'nan' values into zeros?</p> <p>I know I could do something like this, but it seems rather inefficient. This operation will need to be performed on 11 different values * 5000 different dates * 500 companies:</p> <pre><code>def screen_data(data): new_data = [] for d in data: new_list = [] for x in d: new_value = x if math.isNan(x): new_value = 0 new_list.append(new_value) new_data.append(new_list) return new_data </code></pre> <p>I would be interested in any solution that could reduce the time. I know DataFrames might work, but not sure how it would solve the NaN issue.</p> <p>Or if there is a way to include NaN values in an SQLServer5.6 database along with floats, changing the database is also a viable option.</p>
0
2016-09-26T02:01:36Z
39,694,794
<p>I haven't timed it but have you tried using <a href="https://docs.python.org/3.5/tutorial/datastructures.html#nested-list-comprehensions" rel="nofollow">nested list comprehension</a> with <a href="https://docs.python.org/3.5/reference/expressions.html#conditional-expressions" rel="nofollow">conditional expressions</a> ?</p> <p>For example:</p> <pre><code>import datetime data = [ ['2', 1, datetime.date(1998, 1, 2), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), '82.1900', '83.6200', '81.7500', '83.5000', '28.5183', 1286500.0], ['2', 1, datetime.date(1998, 1, 2), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), 'nan', 'nan', 'nan', 'nan', 'nan', 0], ] new_data = [[y if str(y).lower() != 'nan' else 0 for y in x] for x in data] print(new_data) </code></pre> <p>I did not use <code>math.isnan(y)</code> because you have to be sure that <code>y</code> is a <a href="https://docs.python.org/3.5/library/functions.html#float" rel="nofollow">float number</a> or you'll get an error. This is much more difficult to do while almost everything has a string representation. But I still made sure that I did the lower case comparison to 'nan' (with <a href="https://docs.python.org/3.5/library/stdtypes.html#str.lower" rel="nofollow">.lower()</a>) since 'NaN' or 'Nan' are legal ways to express "Not a Number". </p>
2
2016-09-26T04:34:00Z
[ "python", "performance", "list", "mysql-python", null ]
Most efficient way to iterate through list of lists
39,693,722
<p>I'm currently collecting data from quandl and is saved as a list of lists. The list looks something like this (Price data):</p> <pre><code>['2', 1L, datetime.date(1998, 1, 2), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), '82.1900', '83.6200', '81.7500', '83.5000', '28.5183', 1286500.0] </code></pre> <p>This is typically 1 of about 5000 lists, and every once in awhile Quandl will spit back some <code>NaN</code> values that don't like being saved into the database.</p> <pre><code>['2', 1L, datetime.date(1998, 1, 2), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), datetime.datetime(2016, 9, 26, 1, 35, 3, 830563), 'nan', 'nan', 'nan', 'nan', 'nan', 0] </code></pre> <p>What would be the most efficient way of iterating through the list of lists to change 'nan' values into zeros?</p> <p>I know I could do something like this, but it seems rather inefficient. This operation will need to be performed on 11 different values * 5000 different dates * 500 companies:</p> <pre><code>def screen_data(data): new_data = [] for d in data: new_list = [] for x in d: new_value = x if math.isNan(x): new_value = 0 new_list.append(new_value) new_data.append(new_list) return new_data </code></pre> <p>I would be interested in any solution that could reduce the time. I know DataFrames might work, but not sure how it would solve the NaN issue.</p> <p>Or if there is a way to include NaN values in an SQLServer5.6 database along with floats, changing the database is also a viable option.</p>
0
2016-09-26T02:01:36Z
39,695,156
<p>how about this</p> <pre><code>import math def clean_nan(data_list,value=0): for i,x in enumerate(data_list): if math.isnan(x): data_list[i] = value return data_list </code></pre> <p>(the return is optional, as the modification was made in-place, but it is needed if used with <code>map</code> or similar, assuming of course that data_list is well a list or similar container)</p> <p>depending on how you get your data and how you work with it will determined how to use it, for instance if you do something like this</p> <pre><code>for data in (my database/Quandl/whatever): #do stuff with data </code></pre> <p>you can change it to</p> <pre><code>for data in (my database/Quandl/whatever): clean_nan(data) #do stuff with data </code></pre> <p>or use <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow">map</a> or if you are in python 2 <a href="https://docs.python.org/2.7/library/itertools.html#itertools.imap" rel="nofollow">imap</a></p> <pre><code>for data in map(clean_nan,(my database/Quandl/whatever)): #do stuff with data </code></pre> <p>that way you get to work with your data as soon as that arrive from the database/Quandl/whatever, granted if the place where you get the data also work as a generator, that is don't process the whole thing all at once, and if it does, procure to change it to a generator if possible. In either case with this you get to work with your data as soon as possible.</p>
0
2016-09-26T05:19:50Z
[ "python", "performance", "list", "mysql-python", null ]
VPython: File Read Error
39,693,881
<p>I'm using VIDLE and VPython. All I'm trying to do is read the values from "weather.txt." The values that I need to read start on the second line of the file, so I need to skip the first line. Here's a snippet of my code:</p> <pre><code>try: filename = "‪‪‪C:\Users\Ashley\Documents\weather.txt" except (ValueError, IndexError), e: print e sys.exit() datafile = open(filename, 'r') datafile.readline() for line in datafile: data = line.split() try: date = data[2] temperature = float(data[3]) year = float(date[0:4]) month = float(date[4:6]) day = float(date[6:8]) decimalYear = getDecimalYear(year, month, day) meanTimes.append(decimalYear) meanTemperatures.append(temperature) except: print "Tossing line", line datafile.close() </code></pre> <p>And, I keep receiving the following error:</p> <blockquote> <p>Traceback (most recent call last): File "Untitled", line 45 datafile = open(filename, 'r') IOError: [Errno 22] invalid mode ('r') or filename: '\xe2\x80\xaa\xe2\x80\xaa\xe2\x80\xaaC:\Users\Ashley\Documents\weather.txt'</p> </blockquote> <p>Any ideas of what exactly I'm doing wrong? Thanks.</p>
1
2016-09-26T02:27:21Z
39,693,915
<p>Looks like you need to escape backslashes in the file path. It would also appear that there are invisible unicode characters at the start of your string.</p> <p>Try using: <code>filename = 'C:\\Users\\Ashley\\Documents\\weather.txt'</code></p> <p>Also, the first <code>try: except:</code> block isn't required, there's no way that those exceptions can be raised simply by setting a variable.</p>
1
2016-09-26T02:32:42Z
[ "python" ]
VPython: File Read Error
39,693,881
<p>I'm using VIDLE and VPython. All I'm trying to do is read the values from "weather.txt." The values that I need to read start on the second line of the file, so I need to skip the first line. Here's a snippet of my code:</p> <pre><code>try: filename = "‪‪‪C:\Users\Ashley\Documents\weather.txt" except (ValueError, IndexError), e: print e sys.exit() datafile = open(filename, 'r') datafile.readline() for line in datafile: data = line.split() try: date = data[2] temperature = float(data[3]) year = float(date[0:4]) month = float(date[4:6]) day = float(date[6:8]) decimalYear = getDecimalYear(year, month, day) meanTimes.append(decimalYear) meanTemperatures.append(temperature) except: print "Tossing line", line datafile.close() </code></pre> <p>And, I keep receiving the following error:</p> <blockquote> <p>Traceback (most recent call last): File "Untitled", line 45 datafile = open(filename, 'r') IOError: [Errno 22] invalid mode ('r') or filename: '\xe2\x80\xaa\xe2\x80\xaa\xe2\x80\xaaC:\Users\Ashley\Documents\weather.txt'</p> </blockquote> <p>Any ideas of what exactly I'm doing wrong? Thanks.</p>
1
2016-09-26T02:27:21Z
39,693,934
<p>The key is in the junk that you see in the error message which was prepended to your filename:</p> <pre><code>'\xe2\x80\xaa\xe2\x80\xaa\xe2\x80\xaaC:\Users\Ashley\Documents\weather.txt' </code></pre> <p>You can investigate what this means at a Python prompt:</p> <pre><code>&gt;&gt;&gt; '\xe2\x80\xaa\xe2\x80\xaa\xe2\x80\xaa'.decode('utf-8') u'\u202a\u202a\u202a' </code></pre> <p>Google tells me that Unicode code point U+202A turns out to be the <a href="http://www.fileformat.info/info/unicode/char/202a/index.htm" rel="nofollow">"left-to-right embedding" character</a> which is probably one of those zero-width characters and it probably got copy-pasted into your source file somehow. I'd suggest deleting the line with the filename and re-typing it.</p>
0
2016-09-26T02:35:48Z
[ "python" ]
Batch script to execute a Python script multiple times
39,693,902
<p>I need to run a Python script N times, so I created the following script:</p> <pre><code>@ECHO OFF cd PATH_TO_SCRIPT @set port=5682 set /P INPUT=Number of servers: FOR /L %%I IN (1, 1, %INPUT%) DO ( @set /a newport=%port%+1 start cmd /k &gt; start python server.py -i 192.168.1.2 -p %newport% ) pause </code></pre> <p>If I enter <strong>1</strong> as input value, such that there is only one iteration, the script works, but if I choose 2, the script only runs one instance of the server and tells me: "Unable to access file. The file is used from another process". What's wrong?</p>
1
2016-09-26T02:31:15Z
39,694,287
<pre><code>@ECHO OFF setlocal enabledelayedexpansion cd PATH_TO_SCRIPT set port=5682 set /P INPUT=Number of servers: set /a newport=%port% FOR /L %%I IN (1, 1, %INPUT%) DO ( set /a newport+=1 start cmd /k &gt; start python server.py -i 192.168.1.2 -p !newport! ) pause </code></pre> <p>Logic error : On each iteration, you are adding 1 to <code>PORT</code>, but <code>port</code> never changes. You need to initialise <code>newport</code> to the value of <code>port</code> and increment <code>newport</code>.</p> <p>Minor style problem: <code>@</code> is not required after <code>@echo off</code>. <code>echo off</code> turns OFF command-reporting. <code>@</code> before a command turns command reporting OFF for <em>that command</em> only</p> <p>Major problem : Please see the many, many articles on SO about <em>delayed expansion</em>. In essence, <code>%var%</code> refers to the value of <code>var</code> as it was set at the <strong>start</strong> of the loop and if you want to access the value as it changes within the loop, you need to invoke <code>delayedexpansion</code> and use <code>!var!</code></p> <p>Your problem to fix: the <code>cmd /k</code> is not required, and the <code>&gt;</code> is, as pointed out already, bizarre.</p> <p>Also, your logic would start numbering at 5683 because you add 1 <em>before</em> invoking the <code>start</code>. May or may not be a problem.</p>
4
2016-09-26T03:28:29Z
[ "python", "windows", "batch-file" ]
Batch script to execute a Python script multiple times
39,693,902
<p>I need to run a Python script N times, so I created the following script:</p> <pre><code>@ECHO OFF cd PATH_TO_SCRIPT @set port=5682 set /P INPUT=Number of servers: FOR /L %%I IN (1, 1, %INPUT%) DO ( @set /a newport=%port%+1 start cmd /k &gt; start python server.py -i 192.168.1.2 -p %newport% ) pause </code></pre> <p>If I enter <strong>1</strong> as input value, such that there is only one iteration, the script works, but if I choose 2, the script only runs one instance of the server and tells me: "Unable to access file. The file is used from another process". What's wrong?</p>
1
2016-09-26T02:31:15Z
39,694,506
<p>As pointed out already, in your FOR loop, %newport% resolves to [empty] upon execution. It's because newport isn't set until AFTER cmd resolves %newport%, since the entire FOR loop is one statement. In other words, %newport% gets resolved before the commands in the loop are executed, which means it's not set yet, and /p gets nothing. So presumably it uses the same port each time.</p> <p>You don't have to use delayed expansion, though. You could just use your FOR /L iterator (%%I). I think this would be simpler.</p> <pre><code>@ECHO OFF &amp; SETLOCAL CD PATH_TO_SCRIPT SET /P INPUT=Number of servers: SET /A END=5682+%INPUT%-1 FOR /L %%I IN (5682, 1, %END%) DO ( START python server.py -i 192.168.1.2 -p %%I ) PAUSE </code></pre> <p>Also, I agree that it is strange that you're redirecting the output to a file named start. I think you must have been trying to do something else.</p>
1
2016-09-26T03:58:50Z
[ "python", "windows", "batch-file" ]
How to plot a defined function against one of its arguments in Python
39,693,925
<pre><code>from __future__ import division import numpy as np import matplotlib.pyplot as plt def f(x, t): #function for x'(t) = f(x,t) return -x def exact(t): #exact solution return np.exp(-t) def Rk4(x0, t0, dt): #Runge-Kutta Fourth Order Approximation t = np.arange(0, 1+dt, dt) n = len(t) x = np.array([x0]*n) E = np.array([x0]*n) E0 = x0-exact(1) x[0],t[0],E[0] = x0,t0,E0 for i in range(n-1): h = t[i+1] - t[i] k1 = h*f(x[i], t[i]) k2 = h*f(x[i] + 0.5 * k1, t[i] + 0.5 * h) k3 = h*f(x[i] + 0.5 * k2, t[i] + 0.5 * h) k4 = h*f(x[i] + k3, t[i+1]) x[i+1] = x[i] + (k1 + 2.0*(k2 + k3) + k4 )/6.0 E[i+1] = E[i]+(x[i+1]-x[i]) return E vecRk4 = np.vectorize(Rk4) dtime = np.arange(10e-4,1,10e-5) S = vecRk4(1.0,0.0,dtime) plt.plot(dtime,S) </code></pre> <p>I'm just trying to plot the Rk4 function for x0 = 1.0, t0 = 0.0 as a function of dt. I tried by vectorizing the function and creating an array for the timestep dt, but get the error "ValueError: setting an array element with a sequence."</p>
1
2016-09-26T02:33:58Z
39,694,320
<p>The problem is that your return value <code>E</code> is not a single number, but a numpy array.</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow">Vectorizing </a>many arrays would give you a list, vectorizing many numpy arrays does not work here.</p> <p>To come back to your original question: The way to plot a function against one of its arguments using vectorization is:</p> <pre><code>from __future__ import division import numpy as np import matplotlib.pyplot as plt def myfunc(a,b): return 2*b+a vecRk4 = np.vectorize(myfunc) dtime = np.arange(10e-4,1,10e-5) S = vecRk4(a=3, b=dtime) plt.plot(dtime,S) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/V2Sy7.png" rel="nofollow"><img src="http://i.stack.imgur.com/V2Sy7.png" alt="enter image description here"></a></p>
1
2016-09-26T03:34:32Z
[ "python", "numpy", "matplotlib", "runge-kutta" ]
Global Name 'q' not Defined - Python
39,694,066
<p>I have a program like :</p> <pre><code>class ABC: q = {} def update: self.state = (xx,xx) global q if self.state in q: // do something </code></pre> <p>I am getting the error :</p> <blockquote> <p>"NameError: global name 'q' is not defined"</p> </blockquote> <p>Im new to python and need some help.</p>
0
2016-09-26T02:55:49Z
39,694,083
<p><code>q</code> isn't being declared as a global variable here - it's being declared as a class variable of class <code>ABC</code>.</p> <p>If you want <code>q</code> to be global, you should define it before you start declaring the class.</p>
0
2016-09-26T02:58:20Z
[ "python", "nameerror" ]
Global Name 'q' not Defined - Python
39,694,066
<p>I have a program like :</p> <pre><code>class ABC: q = {} def update: self.state = (xx,xx) global q if self.state in q: // do something </code></pre> <p>I am getting the error :</p> <blockquote> <p>"NameError: global name 'q' is not defined"</p> </blockquote> <p>Im new to python and need some help.</p>
0
2016-09-26T02:55:49Z
39,694,118
<p>You can move <em>q</em> outside of the class:</p> <pre><code>q = {} class ABC: def update: self.state = (xx,xx) global q if self.state in q: # do something pass </code></pre> <p>or you can reference <em>q</em> as a class variable:</p> <pre><code>class ABC: q = {} def update: self.state = (xx,xx) if self.state in ABC.q: # do something pass </code></pre>
2
2016-09-26T03:04:34Z
[ "python", "nameerror" ]
This code scales each leaf by a factor, but i dont understand one part of the function
39,694,087
<pre><code>#checking if node is a leaf def is_leaf(item): return type(item) != tuple #performing function on every element in sequence def map(fn, seq): if seq == (): return () else: return (fn(seq[0]), ) + map(fn, seq[1:]) #scaling each leaf by factor def scale_tree(tree, factor): def scale_func(subtree): **#dont understand this part** if is_leaf(subtree): return factor * subtree else: return scale_tree(subtree, factor) return map(scale_func, tree) tup = ((3, 2), 1, (4,), 5) print(scale_tree(tup, 2)) </code></pre> <p>how does the function scale_func know what is the argument to be called if it is not stated like scale_tree?</p>
1
2016-09-26T02:58:49Z
39,694,128
<p>Have a look at the <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow">definition</a> of the map function.</p> <p><code>map(scale_func, tree)</code> will apply every item of tree to the function <code>scale_func</code>.</p> <p>So the argument <code>subtree</code>will be sequentially assigned all items of <code>tree</code>.</p>
2
2016-09-26T03:06:01Z
[ "python" ]
This code scales each leaf by a factor, but i dont understand one part of the function
39,694,087
<pre><code>#checking if node is a leaf def is_leaf(item): return type(item) != tuple #performing function on every element in sequence def map(fn, seq): if seq == (): return () else: return (fn(seq[0]), ) + map(fn, seq[1:]) #scaling each leaf by factor def scale_tree(tree, factor): def scale_func(subtree): **#dont understand this part** if is_leaf(subtree): return factor * subtree else: return scale_tree(subtree, factor) return map(scale_func, tree) tup = ((3, 2), 1, (4,), 5) print(scale_tree(tup, 2)) </code></pre> <p>how does the function scale_func know what is the argument to be called if it is not stated like scale_tree?</p>
1
2016-09-26T02:58:49Z
39,694,152
<p>From a quick read, scale_tree is calling map on its return statement with scale_func and the argument <code>tree</code> as parameters. The map function will then call the function passed as the first argument (scale_func in this case) with the sequence passed as a second argument (tree in this case) as an argument to scale_func if the sequence is not an empty tuple.</p> <p>I would make a little diagram but writing on tablets is hard, sorry.</p>
0
2016-09-26T03:08:48Z
[ "python" ]
Accessing property of dynamically created QStandardItems in PyQt5
39,694,111
<p>I'm having a problem determining whether or not the checkboxes that are dynamically created have been checked or unchecked by the user in a simple GUI I've created.</p> <p>I've adapted the relevant code and pasted it below. Although it may be easy to just create and name 4 QStandardItems, I'm dealing with many lists containing many different items that change quite a lot, so it isn't really feasible to create them myself.</p> <p>Any help finding out how to access these properties would be much appreciated. </p> <pre><code>from PyQt5.QtWidgets import * from PyQt5.QtGui import * class Splash(QWidget): def __init__(self): super().__init__() # imagine this is a very long list... self.seasons = ['summer','autumn','winter','spring'] self.initUI() def initUI(self): layout = QVBoxLayout() list = QListView() model = QStandardItemModel() list.setModel(model) printbtn = QPushButton('print values') printbtn.clicked.connect(self.print_action) for season in self.seasons: item = QStandardItem(season) item.setCheckable(True) model.appendRow(item) model.dataChanged.connect(lambda: self.print_action(item.text())) layout.addWidget(printbtn) layout.addWidget(list) self.setLayout(layout) self.show() def print_action(self, item): print('changed', item) if __name__ == '__main__': import sys app = QApplication(sys.argv) ex = Splash() sys.exit(app.exec_()) </code></pre> <p>In short - I can detect when an item has been checked using model.dataChanged and connecting that to a function, but it cannot differentiate between the seasons.</p>
0
2016-09-26T03:03:52Z
39,694,396
<p>It seems you want to get notified when the checkState of a item has been changed.</p> <p>In my opinion, there are possible two ways.</p> <p>First way, QModel will emit "dataChanged" to refresh the view, so you can connect the signal which means the checkState of a item might be changed.</p> <pre><code>model.dataChanged.connect(self.test) def test(self): pass </code></pre> <p>Second way, use a timer to notify yourself and you check it by yourselves.</p> <pre><code>timer = QTimer() timer.timeout.connect(self.test) timer.start(1000) </code></pre>
0
2016-09-26T03:44:37Z
[ "python", "pyqt", "pyqt5" ]
Accessing property of dynamically created QStandardItems in PyQt5
39,694,111
<p>I'm having a problem determining whether or not the checkboxes that are dynamically created have been checked or unchecked by the user in a simple GUI I've created.</p> <p>I've adapted the relevant code and pasted it below. Although it may be easy to just create and name 4 QStandardItems, I'm dealing with many lists containing many different items that change quite a lot, so it isn't really feasible to create them myself.</p> <p>Any help finding out how to access these properties would be much appreciated. </p> <pre><code>from PyQt5.QtWidgets import * from PyQt5.QtGui import * class Splash(QWidget): def __init__(self): super().__init__() # imagine this is a very long list... self.seasons = ['summer','autumn','winter','spring'] self.initUI() def initUI(self): layout = QVBoxLayout() list = QListView() model = QStandardItemModel() list.setModel(model) printbtn = QPushButton('print values') printbtn.clicked.connect(self.print_action) for season in self.seasons: item = QStandardItem(season) item.setCheckable(True) model.appendRow(item) model.dataChanged.connect(lambda: self.print_action(item.text())) layout.addWidget(printbtn) layout.addWidget(list) self.setLayout(layout) self.show() def print_action(self, item): print('changed', item) if __name__ == '__main__': import sys app = QApplication(sys.argv) ex = Splash() sys.exit(app.exec_()) </code></pre> <p>In short - I can detect when an item has been checked using model.dataChanged and connecting that to a function, but it cannot differentiate between the seasons.</p>
0
2016-09-26T03:03:52Z
39,695,425
<p>If you keep a reference to the list (or the model), you can search for the items by their text, and then get their check-state:</p> <pre><code>def print_action(self): model = self.list.model() for text in 'summer', 'autumn', 'winter', 'spring': items = model.findItems(text) if items: checked = items[0].checkState() == Qt.Checked print('%s = %s' % (text, checked)) </code></pre>
0
2016-09-26T05:44:16Z
[ "python", "pyqt", "pyqt5" ]
Javascript regexp with unicode and punctuation
39,694,155
<p>I have the follow test case for splitting unicoded words but don't know how to do in it javascript.</p> <pre><code>describe("garden: utils", () =&gt; { it("should split correctly", () =&gt; { assert.deepEqual(segmentation('Hockey is a popular sport in Canada.'), [ 'Hockey', 'is', 'a', 'popular', 'sport', 'in', 'Canada', '.' ]); assert.deepEqual(segmentation('How many provinces are there in Canada?'), [ 'How', 'many', 'provinces', 'are', 'there', 'in', 'Canada', '?' ]); assert.deepEqual(segmentation('The forest is on fire!'), [ 'The', 'forest', 'is', 'on', 'fire', '!' ]); assert.deepEqual(segmentation('Emily Carr, who was born in 1871, was a great painter.'), [ 'Emily', 'Carr', ',', 'who', 'was', 'born', 'in', '1871', ',', 'was', 'a', 'great', 'painter', '.' ]); assert.deepEqual(segmentation('This is David\'s computer.'), [ 'This', 'is', 'David', '\'', 's', 'computer', '.' ]); assert.deepEqual(segmentation('The prime minister said, "We will win the election."'), [ 'The', 'prime', 'minister', 'said', ',', '"', 'We', 'will', 'win', 'the', 'election', '.', '"' ]); assert.deepEqual(segmentation('There are three positions in hockey: goalie, defence, and forward.'), [ 'There', 'are', 'three', 'positions', 'in', 'hockey', ':', 'goalie', ',', 'defence', ',', 'and', 'forward', '.' ]); assert.deepEqual(segmentation('The festival is very popular; people from all over the world visit each year.'), [ 'The', 'festival', 'is', 'very', 'popular', ';', 'people', 'from', 'all', 'over', 'the', 'world', 'visit', 'each', 'year', '.' ]); assert.deepEqual(segmentation('Mild, wet, and cloudy - these are the characteristics of weather in Vancouver.'), [ 'Mild', ',', 'wet', ',', 'and', 'cloudy', '-', 'these', 'are', 'the', 'characteristics', 'of', 'weather', 'in', 'Vancouver', '.' ]); assert.deepEqual(segmentation('sweet-smelling'), [ 'sweet', '-', 'smelling' ]); }); it("should not split unicoded words", () =&gt; { assert.deepEqual(segmentation('hacer a propósito'), [ 'hacer', 'a', 'propósito' ]); assert.deepEqual(segmentation('nhà em có con mèo'), [ 'nhà', 'em', 'có', 'con', 'mèo' ]); }); it("should group periods", () =&gt; { assert.deepEqual(segmentation('So are ... the fishes.'), [ 'So', 'are', '...', 'the', 'fishes', '.' ]); assert.deepEqual(segmentation('So are ...... the fishes.'), [ 'So', 'are', '......', 'the', 'fishes', '.' ]); assert.deepEqual(segmentation('arriba arriba ja....'), [ 'arriba', 'arriba', 'ja', '....' ]); }); }); </code></pre> <p>Here is the equivalent expression in python:</p> <pre><code>class Segmentation(BaseNLPProcessor): pattern = re.compile('((?u)\w+|\.{2,}|[%s])' % string.punctuation) @classmethod def ignore_value(cls, value): # type: (str) -&gt; bool return negate(compose(is_empty, string.strip))(value) def split(self): # type: () -&gt; List[str] return filter(self.ignore_value, self.pattern.split(self.value())) </code></pre> <p>I want to write a equivalent function in python for javascript to split by unicoded words and punctuation, group by multiple dots ...</p> <pre><code>Segmentation("Hockey is a popular sport in Canada.").split() </code></pre>
2
2016-09-26T03:09:13Z
39,694,445
<p>Pretty complicated given there's no negative look-behind assertions in JavaScript RegExp, and Unicode support is not official yet (only supported in Firefox by a flag at the moment). This uses a library (XRegExp) to handle the unicode classes. If you need the full normal regular expression, <strong><em>it's huge</em></strong>. Just comment and let me know, and I'll update the answer to use the exploded normal RegExp statements that include the Unicode ranges.</p> <pre><code>const rxLetterToOther = XRegExp('(\\p{L})((?!\\s)\\P{L})','g'); const rxOtherToLetter = XRegExp('((?!\\s)\\P{L})(\\p{L})','g'); const rxNumberToOther = XRegExp('(\\p{N})((?!\\s)\\P{N})','g'); const rxOtherToNumber = XRegExp('((?!\\s)\\P{N})(\\p{N})','g'); const rxPuctToPunct = XRegExp('(\\p{P})(\\p{P})','g'); const rxSep = XRegExp('\\s+','g'); function segmentation(s) { return s .replace(rxLetterToOther, '$1 $2') .replace(rxOtherToLetter, '$1 $2') .replace(rxNumberToOther, '$1 $2') .replace(rxOtherToNumber, '$1 $2') .replace(rxPuctToPunct, '$1 $2') .split(rxSep); } </code></pre> <p><a href="https://jsfiddle.net/a3tf68ae/14/" rel="nofollow">Here it is passing all the test cases!</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>window.onbeforeunload = "";</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; padding: 0; border: 0; overflow: hidden; } object { width: 100%; height: 100%; width: 100vw; height: 100vh; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;object data="https://fiddle.jshell.net/a3tf68ae/14/show/" /&gt;</code></pre> </div> </div> </p> <p><em>Edit: Updated the test case to print the huge RegExp sources beneath the test results. Run the snippet to see the embedded test case.</em></p>
3
2016-09-26T03:50:29Z
[ "javascript", "python", "regex", "unicode", "punctuation" ]
Javascript regexp with unicode and punctuation
39,694,155
<p>I have the follow test case for splitting unicoded words but don't know how to do in it javascript.</p> <pre><code>describe("garden: utils", () =&gt; { it("should split correctly", () =&gt; { assert.deepEqual(segmentation('Hockey is a popular sport in Canada.'), [ 'Hockey', 'is', 'a', 'popular', 'sport', 'in', 'Canada', '.' ]); assert.deepEqual(segmentation('How many provinces are there in Canada?'), [ 'How', 'many', 'provinces', 'are', 'there', 'in', 'Canada', '?' ]); assert.deepEqual(segmentation('The forest is on fire!'), [ 'The', 'forest', 'is', 'on', 'fire', '!' ]); assert.deepEqual(segmentation('Emily Carr, who was born in 1871, was a great painter.'), [ 'Emily', 'Carr', ',', 'who', 'was', 'born', 'in', '1871', ',', 'was', 'a', 'great', 'painter', '.' ]); assert.deepEqual(segmentation('This is David\'s computer.'), [ 'This', 'is', 'David', '\'', 's', 'computer', '.' ]); assert.deepEqual(segmentation('The prime minister said, "We will win the election."'), [ 'The', 'prime', 'minister', 'said', ',', '"', 'We', 'will', 'win', 'the', 'election', '.', '"' ]); assert.deepEqual(segmentation('There are three positions in hockey: goalie, defence, and forward.'), [ 'There', 'are', 'three', 'positions', 'in', 'hockey', ':', 'goalie', ',', 'defence', ',', 'and', 'forward', '.' ]); assert.deepEqual(segmentation('The festival is very popular; people from all over the world visit each year.'), [ 'The', 'festival', 'is', 'very', 'popular', ';', 'people', 'from', 'all', 'over', 'the', 'world', 'visit', 'each', 'year', '.' ]); assert.deepEqual(segmentation('Mild, wet, and cloudy - these are the characteristics of weather in Vancouver.'), [ 'Mild', ',', 'wet', ',', 'and', 'cloudy', '-', 'these', 'are', 'the', 'characteristics', 'of', 'weather', 'in', 'Vancouver', '.' ]); assert.deepEqual(segmentation('sweet-smelling'), [ 'sweet', '-', 'smelling' ]); }); it("should not split unicoded words", () =&gt; { assert.deepEqual(segmentation('hacer a propósito'), [ 'hacer', 'a', 'propósito' ]); assert.deepEqual(segmentation('nhà em có con mèo'), [ 'nhà', 'em', 'có', 'con', 'mèo' ]); }); it("should group periods", () =&gt; { assert.deepEqual(segmentation('So are ... the fishes.'), [ 'So', 'are', '...', 'the', 'fishes', '.' ]); assert.deepEqual(segmentation('So are ...... the fishes.'), [ 'So', 'are', '......', 'the', 'fishes', '.' ]); assert.deepEqual(segmentation('arriba arriba ja....'), [ 'arriba', 'arriba', 'ja', '....' ]); }); }); </code></pre> <p>Here is the equivalent expression in python:</p> <pre><code>class Segmentation(BaseNLPProcessor): pattern = re.compile('((?u)\w+|\.{2,}|[%s])' % string.punctuation) @classmethod def ignore_value(cls, value): # type: (str) -&gt; bool return negate(compose(is_empty, string.strip))(value) def split(self): # type: () -&gt; List[str] return filter(self.ignore_value, self.pattern.split(self.value())) </code></pre> <p>I want to write a equivalent function in python for javascript to split by unicoded words and punctuation, group by multiple dots ...</p> <pre><code>Segmentation("Hockey is a popular sport in Canada.").split() </code></pre>
2
2016-09-26T03:09:13Z
39,694,457
<p>I found the answer but is is complex. Does anyone have another simple answer for this</p> <pre><code>module.exports = (string) =&gt; { const segs = string.split(/(\.{2,}|!|"|#|$|%|&amp;|'|\(|\)|\*|\+|,|-|\.|\/|:|;|&lt;|=|&gt;|\?|¿|@|[|]|\\|^|_|`|{|\||}|~| )/); return segs.filter((seg) =&gt; seg.trim() !== ""); }; </code></pre>
1
2016-09-26T03:53:05Z
[ "javascript", "python", "regex", "unicode", "punctuation" ]
Using variables as arguments for a command called by subprocess in Python 2.7.x
39,694,163
<p>I'm trying to create a basic function that will pass a filename and arguments to a program using <code>call()</code> from the <code>subprocess</code> module. The filename and arguments are variables. When I use <code>call()</code> it takes the variables but the called program reads their strings with <code>"</code> included.</p> <p>Here's the code in question:</p> <pre><code>from subprocess import call def mednafen(): print "Loading "+romname+"..." call(["mednafen", args, romname]) print "Mednafen closed." romname="kirby.zip" args="-fs 1" mednafen() </code></pre> <p>I expected this would execute</p> <pre><code>mednafen -fs 1 kirby.zip </code></pre> <p>but instead it appears to interpret the variable's strings as this:</p> <pre><code>mednafen "-fs 1" "kirby.zip" </code></pre> <p>Because of this, mednafen isn't able to run because it can't parse an argument that starts with <code>"</code>. It works as expected if I use <code>shell=True</code> but that feature is apparently strongly discouraged because it's easy to exploit?</p> <pre><code>call("mednafen "+ args +" "+romname+"; exit", shell=True) </code></pre> <p>Is there a way to do this without using the <code>shell=True</code> format?</p>
0
2016-09-26T03:10:33Z
39,694,356
<p>Well, yes. That's exactly what the documentation says it does. Create and pass a list containing the command and all arguments instead.</p>
1
2016-09-26T03:40:35Z
[ "python", "python-2.7" ]
Using variables as arguments for a command called by subprocess in Python 2.7.x
39,694,163
<p>I'm trying to create a basic function that will pass a filename and arguments to a program using <code>call()</code> from the <code>subprocess</code> module. The filename and arguments are variables. When I use <code>call()</code> it takes the variables but the called program reads their strings with <code>"</code> included.</p> <p>Here's the code in question:</p> <pre><code>from subprocess import call def mednafen(): print "Loading "+romname+"..." call(["mednafen", args, romname]) print "Mednafen closed." romname="kirby.zip" args="-fs 1" mednafen() </code></pre> <p>I expected this would execute</p> <pre><code>mednafen -fs 1 kirby.zip </code></pre> <p>but instead it appears to interpret the variable's strings as this:</p> <pre><code>mednafen "-fs 1" "kirby.zip" </code></pre> <p>Because of this, mednafen isn't able to run because it can't parse an argument that starts with <code>"</code>. It works as expected if I use <code>shell=True</code> but that feature is apparently strongly discouraged because it's easy to exploit?</p> <pre><code>call("mednafen "+ args +" "+romname+"; exit", shell=True) </code></pre> <p>Is there a way to do this without using the <code>shell=True</code> format?</p>
0
2016-09-26T03:10:33Z
39,694,774
<p><strong>EDIT</strong>: The solution suggested by <a href="http://stackoverflow.com/users/1248008/jonas-wielicki">Jonas Wielicki</a> is to make sure every single string that would normally be separated by spaces in shell syntax is listed as a separate item; That way <code>call()</code> will read them properly. <code>shlex</code> is unnecessary.</p> <pre><code>args = ["-fs", "1"] call(['mednafen']+args+[rom]) </code></pre> <p><strong>My initial (less concise) solution:</strong> <code>shlex.split()</code> takes the variables/strings I feed it and converts them into a list of string literals, which in turn causes the called command to parse them correctly rather than interpreting the variables as strings within quotes. So instead of the argument being treated like <code>"-fs 0"</code> I'm getting <code>-fs 0</code> like I originally wanted.</p> <pre><code>import shlex call(shlex.split("mednafen "+args+" "+romname)) </code></pre>
1
2016-09-26T04:32:41Z
[ "python", "python-2.7" ]
Convert string column to integer
39,694,192
<p>I have a dataframe like below</p> <pre><code> a b 0 1 26190 1 5 python 2 5 580 </code></pre> <p>I want to make column <code>b</code> to host only integers, but as you can see <code>python</code> is not int convertible, so I want to delete the row at index <code>1</code>. My expected out put has to be like</p> <pre><code> a b 0 1 26190 1 5 580 </code></pre> <p>How to filter and remove using pandas in python?</p>
2
2016-09-26T03:15:04Z
39,694,974
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow"><code>to_numeric</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow"><code>notnull</code></a> and filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>print (pd.to_numeric(df.b, errors='coerce')) 0 26190.0 1 NaN 2 580.0 Name: b, dtype: float64 print (pd.to_numeric(df.b, errors='coerce').notnull()) 0 True 1 False 2 True Name: b, dtype: bool df = df[pd.to_numeric(df.b, errors='coerce').notnull()] print (df) a b 0 1 26190 2 5 580 </code></pre> <p>Another solution by comment of <a href="http://stackoverflow.com/questions/39694192/convert-string-column-to-integer/39694974#comment66688077_39694192">Boud</a> - use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow"><code>to_numeric</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow"><code>dropna</code></a> and last convert to <code>int</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>:</p> <pre><code>df.b = pd.to_numeric(df.b, errors='coerce') df = df.dropna(subset=['b']) df.b = df.b. astype(int) print (df) a b 0 1 26190 2 5 580 </code></pre> <hr> <p>If need check all rows with bad data use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow"><code>isnull</code></a> - filter all data where after applying function <code>to_numeric</code> get <code>NaN</code>:</p> <pre><code>print (pd.to_numeric(df.b, errors='coerce').isnull()) 0 False 1 True 2 False Name: b, dtype: bool print (df[pd.to_numeric(df.b, errors='coerce').isnull()]) a b 1 5 python </code></pre>
1
2016-09-26T04:59:13Z
[ "python", "string", "pandas", "numpy", "int" ]
Convert string column to integer
39,694,192
<p>I have a dataframe like below</p> <pre><code> a b 0 1 26190 1 5 python 2 5 580 </code></pre> <p>I want to make column <code>b</code> to host only integers, but as you can see <code>python</code> is not int convertible, so I want to delete the row at index <code>1</code>. My expected out put has to be like</p> <pre><code> a b 0 1 26190 1 5 580 </code></pre> <p>How to filter and remove using pandas in python?</p>
2
2016-09-26T03:15:04Z
39,700,526
<p>This should work</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'a' : [1, 5, 5], 'b' : [26190, 'python', 580]}) df a b 0 1 26190 1 5 python 2 5 580 df['b'] = np.where(df.b.str.contains('[a-z]') == True, np.NaN, df.b) df a b 0 1 26190 1 5 NaN 2 5 580 df = df.dropna() df a b 0 1 26190 2 5 580 </code></pre> <p>You use the regex to identify strings, then convert these to <code>np.NaN</code> using <code>np.where</code> then drop them from the df with <code>df.dropna()</code>. </p>
0
2016-09-26T10:32:40Z
[ "python", "string", "pandas", "numpy", "int" ]
Difference between single and double bracket Numpy array?
39,694,318
<p>What is the difference between these two numpy objects?</p> <pre><code>import numpy as np np.array([[0,0,0,0]]) np.array([0,0,0,0]) </code></pre>
-2
2016-09-26T03:34:28Z
39,694,589
<p>When you defined an array with two brackets, what you were really doing was declaring an array with an array with 4 0's inside. Therefore, if you wanted to access the first zero you would be accessing <code>your_array[0][0]</code> while in the second array you would just be accessing <code>your array[0]</code>. Perhaps a better way to visualize it is </p> <pre><code>array: [ [0,0,0,0], ] </code></pre> <p>vs </p> <pre><code>array: [0,0,0,0] </code></pre>
1
2016-09-26T04:08:52Z
[ "python", "numpy" ]
Difference between single and double bracket Numpy array?
39,694,318
<p>What is the difference between these two numpy objects?</p> <pre><code>import numpy as np np.array([[0,0,0,0]]) np.array([0,0,0,0]) </code></pre>
-2
2016-09-26T03:34:28Z
39,694,829
<pre><code>In [71]: np.array([[0,0,0,0]]).shape Out[71]: (1, 4) In [72]: np.array([0,0,0,0]).shape Out[72]: (4,) </code></pre> <p>The former is a 1 x 4 two-dimensional array, the latter a 4 element one dimensional array.</p>
2
2016-09-26T04:38:03Z
[ "python", "numpy" ]
Difference between single and double bracket Numpy array?
39,694,318
<p>What is the difference between these two numpy objects?</p> <pre><code>import numpy as np np.array([[0,0,0,0]]) np.array([0,0,0,0]) </code></pre>
-2
2016-09-26T03:34:28Z
39,707,119
<p>The difference between single and double brackets starts with lists:</p> <pre><code>In [91]: ll=[0,1,2] In [92]: ll1=[[0,1,2]] In [93]: len(ll) Out[93]: 3 In [94]: len(ll1) Out[94]: 1 In [95]: len(ll1[0]) Out[95]: 3 </code></pre> <p><code>ll</code> is a list of 3 items. <code>ll1</code> is a list of 1 item; that item is another list. Remember, a list can contain a variety of different objects, numbers, strings, other lists, etc.</p> <p>Your 2 expressions effectively make arrays from two such lists</p> <pre><code>In [96]: np.array(ll) Out[96]: array([0, 1, 2]) In [97]: _.shape Out[97]: (3,) In [98]: np.array(ll1) Out[98]: array([[0, 1, 2]]) In [99]: _.shape Out[99]: (1, 3) </code></pre> <p>Here the list of lists has been turned into a 2d array. In a subtle way <code>numpy</code> blurs the distinction between the list and the nested list, since the difference between the two arrays lies in their shape, not a fundamental structure. <code>array(ll)[None,:]</code> produces the <code>(1,3)</code> version, while <code>array(ll1).ravel()</code> produces a <code>(3,)</code> version.</p> <p>In the end result the difference between single and double brackets is a difference in the number of array dimensions, but we shouldn't loose sight of the fact that Python first creates different lists.</p>
0
2016-09-26T15:47:01Z
[ "python", "numpy" ]
connect Python to MYSQL, obtain SP500 symbols
39,694,339
<p>The code is below:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- # insert_symbols.py #table name should be 's_master', password should be '*******', user name should be 's_user' from __future__ import print_function import datetime from math import ceil import bs4 import MySQLdb as mdb import requests def obtain_parse_wiki_snp500(): """ Download and parse the Wikipedia list of S&amp;P500 constituents using requests and BeautifulSoup. Returns a list of tuples for to add to MySQL. """ # Stores the current time, for the created_at record now = datetime.datetime.utcnow() # Use requests and BeautifulSoup to download the # list of S&amp;P500 companies and obtain the symbol table response = requests.get( "http://en.wikipedia.org/wiki/List_of_S%26P_500_companies" ) # soup = bs4.BeautifulSoup(response.text) ///this is the original version, i replaced with the code below soup = bs4.BeautifulSoup(response.text, "html.parser") # This selects the first table, using CSS Selector syntax # and then ignores the header row ([1:]) symbolslist = soup.select('table')[0].select('tr')[1:] # Obtain the symbol information for each # row in the S&amp;P500 constituent table symbols = [] for i, symbol in enumerate(symbolslist): tds = symbol.select('td') symbols.append( ( tds[0].select('a')[0].text, # Ticker 'stock', tds[1].select('a')[0].text, # Name tds[3].text, # Sector 'USD', now, now ) ) return symbols def insert_snp500_symbols(symbols): """ Insert the S&amp;P500 symbols into the MySQL database. """ # Connect to the MySQL instance db_host = 'localhost' db_user = 's_user' db_pass = '*******' db_name = 's_master' con = mdb.connect( host=db_host, user=db_user, passwd=db_pass, db=db_name ) # Create the insert strings column_str = """ticker, instrument, name, sector, currency, created_date, last_updated_date """ insert_str = ("%s, " * 7)[:-2] final_str = "INSERT INTO symbol (%s) VALUES (%s)" % \ (column_str, insert_str) # Using the MySQL connection, carry out # an INSERT INTO for every symbol with con: cur = con.cursor() cur.executemany(final_str, symbols) if __name__ == "__main__": symbols = obtain_parse_wiki_snp500() insert_snp500_symbols(symbols) print("%s symbols were successfully added." % len(symbols)) </code></pre> <p>The error message I got is below:</p> <pre><code>Traceback (most recent call last): File "insert_symbols.py", line 86, in &lt;module&gt; insert_snp500_symbols(symbols) File "insert_symbols.py", line 81, in insert_snp500_symbols cur.executemany(final_str, symbols) File "/home/haolun/.local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 285, in executemany r = self._query(qs) File "/home/haolun/.local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 378, in _query rowcount = self._do_query(q) File "/home/haolun/.local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 341, in _do_query db.query(q) File "/home/haolun/.local/lib/python2.7/site-packages/MySQLdb/connections.py", line 280, in query _mysql.connection.query(self, query) _mysql_exceptions.ProgrammingError: (1146, "Table 's_master.symbol' doesn't exist") </code></pre> <p>I don't know why I am getting this _"mysql_exceptions.ProgrammingError: (1146, "Table 's_master.symbol' doesn't exist") message. I did create the s_master table. Is there anything wrong with beautifulsoup commend or anything else? </p>
0
2016-09-26T03:37:37Z
39,695,291
<p>I think you don't create the table correctly.I write a sql file <code>init.sql</code>, and import it to the mysql database by using the following command:</p> <pre><code>mysql -u root -p &lt; init.sql </code></pre> <p>This is the content of the init.sql</p> <pre><code>create database if not exists s_master default charset utf8 collate utf8_unicode_ci; -- chage the password to 123456 grant all on s_master.* to s_user@'localhost' identified by '123456'; use s_master; create table if not exists symbol( ticker varchar(40), instrument varchar(40), name varchar(40), sector varchar(40), currency varchar(40), created_date datetime, last_updated_date datetime ); </code></pre> <p>After that I was able to run your program correctly, the result of the program is:</p> <pre><code>➜ /tmp [sof]$ python yourprogram.py (u'MMM', 'stock', u'3M Company', u'Industrials', 'USD', datetime.datetime(2016, 9, 26, 5, 24, 11, 62336), datetime.datetime(2016, 9, 26, 5, 24, 11, 62336)) 505 symbols were successfully added. ➜ /tmp [sof]$ </code></pre>
0
2016-09-26T05:31:43Z
[ "python", "mysql", "web-scraping", "beautifulsoup" ]
loop through numpy arrays, plot all arrays to single figure (matplotlib)
39,694,357
<p>the functions below each plot a single numpy array<br /> plot1D, plot2D, and plot3D take arrays with 1, 2, and 3 columns, respectively</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def plot1D(data): x=np.arange(len(data)) plot2D(np.hstack((np.transpose(x), data))) def plot2D(data): # type: (object) -&gt; object #if 2d, make a scatter plt.plot(data[:,0], data[:,1], *args, **kwargs) def plot3D(data): #if 3d, make a 3d scatter fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot(data[:,0], data[:,1], data[:,2], *args, **kwargs) </code></pre> <p>I would like the ability to input a list of 1, 2, or 3d arrays and plot all arrays from the list onto one figure</p> <p>I have added the looping elements, but am unsure how hold a figure and add additional plots...</p> <pre><code>def plot1D_list(data): for i in range(0, len(data)): x=np.arange(len(data[i])) plot2D(np.hstack((np.transpose(x), data[i]))) def plot2D_list(data): # type: (object) -&gt; object #if 2d, make a scatter for i in range(0, len(data)): plt.plot(data[i][:,0], data[i][:,1], *args, **kwargs) def plot3D_list(data): #if 3d, make a 3d scatter for i in range(0, len(data)): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot(data[i][:,0], data[i][:,1], data[i][:,2], *args, **kwargs) </code></pre>
1
2016-09-26T03:40:44Z
39,696,016
<p>To plot multiple data sets on the same axes, you can do something like this:</p> <pre><code>def plot2D_list(data,*args,**kwargs): # type: (object) -&gt; object #if 2d, make a scatter n = len(data) fig,ax = plt.subplots() #create figure and axes for i in range(n): #now plot data set i ax.plot(data[i][:,0], data[i][:,1], *args, **kwargs) </code></pre> <p>Your other functions can be generalised in the same way. Here's an example of using the above function with a 5 sets of randomly generated x-y coordinates, each with length 100 (each of the 5 data sets appears as a different color):</p> <pre><code>import numpy as np X = np.random.randn(5,100,2) plot2D_list(X,'o') plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/gm2eK.png" rel="nofollow"><img src="http://i.stack.imgur.com/gm2eK.png" alt="enter image description here"></a></p>
0
2016-09-26T06:28:36Z
[ "python", "arrays", "numpy", "matplotlib" ]
Plot multivariate data in Python
39,694,360
<p>I have a data of human activity performing various leg movements. The data consists of X, Y, Z gyro sensor orientation. Data looks like below:</p> <p>Activity 1:</p> <p>timestamp, X rad/sec, y rad/sec, z rad/sec</p> <p>1474242172.0203, -0.440601, -2.377124 , -0.379635</p> <p>1474242172.09023, -0.402881, 0.03603, -0.436877</p> <p>1474242172.11018, -0.079664, 0.071131, -0.969909</p> <p>Activity 2:</p> <p>1474242172.13019, 0.504345, 0.21577, -1.171976</p> <p>1474242172.15017, 1.485681, 0.95263, -1.050102</p> <p>1474242172.32995, 2.162143, -2.888519, -1.274397</p> <p>1474242172.34995, 2.178419, -2.332485, -1.130116</p> <p>Activity 3:</p> <p>1474242172.27003, 2.71125, -0.618401, -0.394154</p> <p>1474242172.29002, 2.421668, -1.14887, -0.846701</p> <p>1474242172.30999, 2.212555, -2.497823, -1.096355</p> <p>I have collected for 3 activities for a 7 days. Each data is in separate csv file. I would like to plot this data in Python/R. I want to take avg of X value, y value and Z value for each activity for one day and plot them using parallel coordinates. Activity(1,2,3) on one coordinate, Day 1 through Day 7 on different coordinates. X,Y,Z being different colors flowing. My classification of activity is not present in data set. I have to program the ticks for Activity. </p> <p>Can any one suggest if parallel coordinates is the right way to show consistency of each activity over 7days? Or is their any appealing way to plot them in either surface plot or a 3D plot.</p> <p>Can anyone provide inputs? I greatly appreciate for any advice or example of similar situation. </p>
0
2016-09-26T03:40:52Z
39,694,622
<p>in python, you could use <a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html" rel="nofollow">pylab</a> to plot in 3d using something like: <code>plt.plot(x_vals_list,y_vals_list,z_vals_list)</code> . If you have more than 3 dimensions you can use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html" rel="nofollow">Principle Component Analysis</a> to break down those dimensions into 3 major components. </p>
1
2016-09-26T04:12:36Z
[ "python", "matplotlib", "plot", "plotly" ]
Deleting values from multiple arrays that have a particular value
39,694,363
<p>Lets say I have two arrays: <code>a = array([1,2,3,0,4,5,0])</code> and <code>b = array([1,2,3,4,0,5,6])</code>. I am interested in removing the instances where <code>a</code> and <code>b</code>are <code>0</code>. But I also want to remove the corresponding instances from both lists. Therefore what I want to end up with is <code>a = array([1,2,3,5])</code> and <code>b = array([1,2,3,5])</code>. This is because <code>a[3] == 0</code> and <code>a[6] == 0</code>, so both <code>b[3]</code> and <code>b[6]</code> are also deleted. Likewise, since <code>b[4] == 0</code>, <code>a[4]</code> is also deleted.Its simple to do this for say two arrays:</p> <pre><code>import numpy as np a = np.array([1,2,3,0,4,5,0]) b = np.array([1,2,3,4,0,5,6]) ix = np.where(b == 0) b = np.delete(b, ix) a = np.delete(a, ix) ix = np.where(a == 0) b = np.delete(b, ix) a = np.delete(a, ix) </code></pre> <p>However this solution doesnt scale up if I have many many arrays (which I do). What would be a more elegant way to do this?</p> <p>If I try the following:</p> <pre><code>import numpy as np a = np.array([1,2,3,0,4,5,0]) b = np.array([1,2,3,4,0,5,6]) arrays = [a,b] for array in arrays: ix = np.where(array == 0) b = np.delete(b, ix) a = np.delete(a, ix) </code></pre> <p>I get <code>a = array([1, 2, 3, 4])</code> and <code>b = array([1, 2, 3, 0])</code>, not the answers I need. Any idea where this is wrong?</p>
0
2016-09-26T03:41:29Z
39,694,557
<p>This is happening because when you return from np.delete, you get an array that is stored in b and a inside the loop. However, the arrays stored in the arrays variable are copies, not references. Hence, when you're updating the arrays by deleting them, it deletes with regard to the original arrays. The first loop will return the corrects indices of 0 in the array but the second loop will return ix as 4 (look at the original array).<br>Like if you display the arrays variable in each iteration, it is going to remain the same.<br><br> You need to reassign arrays once you are done processing one array so that it's taken into consideration the next iteration. Here's how you'd do it - </p> <pre><code>a = np.array([1, 2, 3, 0, 4, 5, 0]) b = np.array([1, 2, 3, 4, 0, 5, 6]) arrays = [a,b] for i in range(0, len(arrays)): ix = np.where(arrays[i] == 0) b = np.delete(b, ix) a = np.delete(a, ix) arrays = [a, b] </code></pre> <p>Of course you can automate what happens inside the loop. I just wanted to give an explanation of what was happening.</p>
1
2016-09-26T04:05:50Z
[ "python", "arrays", "numpy", "indexing" ]
Deleting values from multiple arrays that have a particular value
39,694,363
<p>Lets say I have two arrays: <code>a = array([1,2,3,0,4,5,0])</code> and <code>b = array([1,2,3,4,0,5,6])</code>. I am interested in removing the instances where <code>a</code> and <code>b</code>are <code>0</code>. But I also want to remove the corresponding instances from both lists. Therefore what I want to end up with is <code>a = array([1,2,3,5])</code> and <code>b = array([1,2,3,5])</code>. This is because <code>a[3] == 0</code> and <code>a[6] == 0</code>, so both <code>b[3]</code> and <code>b[6]</code> are also deleted. Likewise, since <code>b[4] == 0</code>, <code>a[4]</code> is also deleted.Its simple to do this for say two arrays:</p> <pre><code>import numpy as np a = np.array([1,2,3,0,4,5,0]) b = np.array([1,2,3,4,0,5,6]) ix = np.where(b == 0) b = np.delete(b, ix) a = np.delete(a, ix) ix = np.where(a == 0) b = np.delete(b, ix) a = np.delete(a, ix) </code></pre> <p>However this solution doesnt scale up if I have many many arrays (which I do). What would be a more elegant way to do this?</p> <p>If I try the following:</p> <pre><code>import numpy as np a = np.array([1,2,3,0,4,5,0]) b = np.array([1,2,3,4,0,5,6]) arrays = [a,b] for array in arrays: ix = np.where(array == 0) b = np.delete(b, ix) a = np.delete(a, ix) </code></pre> <p>I get <code>a = array([1, 2, 3, 4])</code> and <code>b = array([1, 2, 3, 0])</code>, not the answers I need. Any idea where this is wrong?</p>
0
2016-09-26T03:41:29Z
39,694,575
<p>A slow method involves operating over the whole list twice, first to build an intermediate list of indices to delete, and then second to delete all of the values at those indices:</p> <pre><code>import numpy as np a = np.array([1,2,3,0,4,5,0]) b = np.array([1,2,3,4,0,5,6]) arrays = [a, b] vals = [] for array in arrays: ix = np.where(array == 0) vals.extend([y for x in ix for y in x.tolist()]) vals = list(set(vals)) new_array = [] for array in arrays: new_array.append(np.delete(array, vals)) </code></pre>
0
2016-09-26T04:07:33Z
[ "python", "arrays", "numpy", "indexing" ]
Deleting values from multiple arrays that have a particular value
39,694,363
<p>Lets say I have two arrays: <code>a = array([1,2,3,0,4,5,0])</code> and <code>b = array([1,2,3,4,0,5,6])</code>. I am interested in removing the instances where <code>a</code> and <code>b</code>are <code>0</code>. But I also want to remove the corresponding instances from both lists. Therefore what I want to end up with is <code>a = array([1,2,3,5])</code> and <code>b = array([1,2,3,5])</code>. This is because <code>a[3] == 0</code> and <code>a[6] == 0</code>, so both <code>b[3]</code> and <code>b[6]</code> are also deleted. Likewise, since <code>b[4] == 0</code>, <code>a[4]</code> is also deleted.Its simple to do this for say two arrays:</p> <pre><code>import numpy as np a = np.array([1,2,3,0,4,5,0]) b = np.array([1,2,3,4,0,5,6]) ix = np.where(b == 0) b = np.delete(b, ix) a = np.delete(a, ix) ix = np.where(a == 0) b = np.delete(b, ix) a = np.delete(a, ix) </code></pre> <p>However this solution doesnt scale up if I have many many arrays (which I do). What would be a more elegant way to do this?</p> <p>If I try the following:</p> <pre><code>import numpy as np a = np.array([1,2,3,0,4,5,0]) b = np.array([1,2,3,4,0,5,6]) arrays = [a,b] for array in arrays: ix = np.where(array == 0) b = np.delete(b, ix) a = np.delete(a, ix) </code></pre> <p>I get <code>a = array([1, 2, 3, 4])</code> and <code>b = array([1, 2, 3, 0])</code>, not the answers I need. Any idea where this is wrong?</p>
0
2016-09-26T03:41:29Z
39,701,971
<p>Assuming both/all arrays always have the same length, you can use <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">masks</a>:</p> <pre><code>ma = a != 0 # mask elements which are not equal to zero in a mb = b != 0 # mask elements which are not equal to zero in b m = ma * mb # assign the intersection of ma and mb to m print a[m], b[m] # [1 2 3 5] [1 2 3 5] </code></pre> <p>You can of course also do it in one line</p> <pre><code>m = (a != 0) * (b != 0) </code></pre> <p>Or use the inverse</p> <pre><code>ma = a == 0 mb = b == 0 m = ~(ma + mb) # not the union of ma and mb </code></pre>
3
2016-09-26T11:45:48Z
[ "python", "arrays", "numpy", "indexing" ]
Deleting values from multiple arrays that have a particular value
39,694,363
<p>Lets say I have two arrays: <code>a = array([1,2,3,0,4,5,0])</code> and <code>b = array([1,2,3,4,0,5,6])</code>. I am interested in removing the instances where <code>a</code> and <code>b</code>are <code>0</code>. But I also want to remove the corresponding instances from both lists. Therefore what I want to end up with is <code>a = array([1,2,3,5])</code> and <code>b = array([1,2,3,5])</code>. This is because <code>a[3] == 0</code> and <code>a[6] == 0</code>, so both <code>b[3]</code> and <code>b[6]</code> are also deleted. Likewise, since <code>b[4] == 0</code>, <code>a[4]</code> is also deleted.Its simple to do this for say two arrays:</p> <pre><code>import numpy as np a = np.array([1,2,3,0,4,5,0]) b = np.array([1,2,3,4,0,5,6]) ix = np.where(b == 0) b = np.delete(b, ix) a = np.delete(a, ix) ix = np.where(a == 0) b = np.delete(b, ix) a = np.delete(a, ix) </code></pre> <p>However this solution doesnt scale up if I have many many arrays (which I do). What would be a more elegant way to do this?</p> <p>If I try the following:</p> <pre><code>import numpy as np a = np.array([1,2,3,0,4,5,0]) b = np.array([1,2,3,4,0,5,6]) arrays = [a,b] for array in arrays: ix = np.where(array == 0) b = np.delete(b, ix) a = np.delete(a, ix) </code></pre> <p>I get <code>a = array([1, 2, 3, 4])</code> and <code>b = array([1, 2, 3, 0])</code>, not the answers I need. Any idea where this is wrong?</p>
0
2016-09-26T03:41:29Z
39,708,622
<p>Building up on top of Christoph Terasa's answer, you can use array operations instead of for loops:</p> <pre><code>arrays = np.vstack([a,b]) # ...long list of arrays of equal length zeroind = (arrays==0).max(0) pos_arrays = arrays[:,~zeroind] # a 2d array only containing those columns where none of the lines contained zeros </code></pre>
0
2016-09-26T17:13:26Z
[ "python", "arrays", "numpy", "indexing" ]
Check for status of subprocess to kill audio playback in python
39,694,424
<p>Im currently using sox to apply effects to an audio file and play the file back. Currently I have the code set to create a new subprocess to play the file when button 1 is pressed and to kill the process when button 2 is pressed. </p> <p>What I want to do is change it so that if Button 1 is pressed multiple times it will check to see if a previous process is active and if so kill it and if not then just play as normal.</p> <p>My code as of now is:</p> <pre><code>def Button_1(): p = subprocess.Popen(['play','playback.wav']) def Button_2(): p.send_signal(signal.SIGNIT) </code></pre>
0
2016-09-26T03:47:59Z
39,695,058
<p>Use <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen.poll" rel="nofollow"><code>p.poll()</code></a> to check if the process is still running.</p> <p>The code will look something like this (untested):</p> <pre><code>def Button_1(): if p.poll(): p.send_signal(signal.SIGNIT) else: p = subprocess.Popen(['play','playback.wav']) def Button_2(): p.send_signal(signal.SIGNIT) </code></pre>
0
2016-09-26T05:08:07Z
[ "python", "subprocess", "kill", "sox" ]
Python requests caching authentication headers
39,694,438
<p>I have used python's requests module to do a POST call(within a loop) to a single URL with varying sets of data in each iteration. I have already used session reuse to use the underlying TCP connection for each call to the URL during the loop's iterations. </p> <p>However, I want to further speed up my processing by 1. caching the URL and the authentication values(user id and password) as they would remain the same in each call 2. Spawning multiple sub-processes which could take a certain number of calls and pass them as a group thus allowing for parallel processing of these smaller sub-processes</p> <p>Please note that I pass my authentication as headers in base64 format and a pseudo code of my post call would typically look like this:</p> <pre><code>S=requests.Session() url='https://example.net/' Loop through data records: headers={'authorization':authbase64string,'other headers'} data="data for this loop" #Post call r=s.post(url,data=data,headers=headers) response=r.json() #end of loop and program </code></pre> <p>Please review the scenario and suggest any techniques/tips which might be of help-</p> <p>Thanks in advance, Abhishek</p>
0
2016-09-26T03:49:24Z
39,698,040
<p>You can:</p> <ol> <li>do it as you described (if you want to make it faster then you can run it using multiprocessing) and e.g. add headers to session, not request.</li> <li>modify target server and allow to send one post request with multiple data (so you're going to limit time spent on connecting, etc)</li> <li>do some optimalizations on server side, so it's going to reply faster (or just store requests and send you response using some callback)</li> </ol> <p>It would be much easier if you described the use case :)</p>
0
2016-09-26T08:31:56Z
[ "python", "python-requests", "cache-control" ]
math.cos(x) not returning correct value?
39,694,465
<p>I just started using python, and am having difficulty with a very basic program. I want to calculate the cosine of -20 degrees. It is my understanding that the default value is in radians, so this is the following code i tried:</p> <pre><code>import math print math.cos(math.degrees(-20)) </code></pre> <p>This outputs (-.7208...), where the answer is actually (.9397...). I'm sure this has a pretty basic solution but I've tried so many different things and it will not output the correct results. Thanks in advance!</p>
0
2016-09-26T03:54:08Z
39,694,480
<p>You need to input in radians, so do </p> <pre><code>math.cos(math.radians(-20)) </code></pre> <p>math.radians(-20) converts -20 degrees to radians.</p>
0
2016-09-26T03:56:01Z
[ "python", "math", "trigonometry" ]
math.cos(x) not returning correct value?
39,694,465
<p>I just started using python, and am having difficulty with a very basic program. I want to calculate the cosine of -20 degrees. It is my understanding that the default value is in radians, so this is the following code i tried:</p> <pre><code>import math print math.cos(math.degrees(-20)) </code></pre> <p>This outputs (-.7208...), where the answer is actually (.9397...). I'm sure this has a pretty basic solution but I've tried so many different things and it will not output the correct results. Thanks in advance!</p>
0
2016-09-26T03:54:08Z
39,694,498
<p><code>math.degrees</code> takes a number of radians and <em>produces</em> a number of degrees. You need the opposite conversion - you have a number of degrees, and you need to produce a number of radians you can pass to <code>math.cos</code>. You need <code>math.radians</code>:</p> <pre><code>math.cos(math.radians(-20)) </code></pre>
0
2016-09-26T03:57:57Z
[ "python", "math", "trigonometry" ]
math.cos(x) not returning correct value?
39,694,465
<p>I just started using python, and am having difficulty with a very basic program. I want to calculate the cosine of -20 degrees. It is my understanding that the default value is in radians, so this is the following code i tried:</p> <pre><code>import math print math.cos(math.degrees(-20)) </code></pre> <p>This outputs (-.7208...), where the answer is actually (.9397...). I'm sure this has a pretty basic solution but I've tried so many different things and it will not output the correct results. Thanks in advance!</p>
0
2016-09-26T03:54:08Z
39,694,521
<p>Per the <a href="https://docs.python.org/3.5/library/math.html#angular-conversion" rel="nofollow">Python documentation</a>:</p> <blockquote> <p><strong><code>math.degrees(x)</code></strong></p> <p>Convert angle <em>x</em> from radians to degrees.</p> </blockquote> <p>That means you are attempting to convert -20 radians to degrees which isn't desired.</p> <p>Also per the documentation:</p> <blockquote> <p><strong><code>math.cos(x)</code></strong></p> <p>Return the cosine of <code>x</code> radians.</p> </blockquote> <p>This means <code>math.cos</code> finds the cosine of the passed argument in <em>radians</em>, not degrees. That means your code currently changes -20 radians to degrees, then finds the cosine of that as if it were radians... you can see why that's a problem.</p> <p>You need to convert -20 degrees to radians, and then find the cosine. Use <a href="https://docs.python.org/3.5/library/math.html#angular-conversion" rel="nofollow"><code>math.radians</code></a>:</p> <pre><code>math.cos(math.radians(-20)) </code></pre>
3
2016-09-26T04:00:20Z
[ "python", "math", "trigonometry" ]
Function returning false when it should be returning True. Encoding issue?
39,694,538
<p>I am currently working on a validation function that returns <code>True</code> or <code>False</code> based on an expression (if statement). The header is base64 decoded and then <code>json.loads</code> is used to convert it into a dict. Here is the method:</p> <pre><code> @staticmethod def verify(rel): if not('hello' in rel and rel['hello'] is 'blah' and 'alg' in rel and rel['alg'] is 'HS256'): return False return True </code></pre> <p>The check only fails if the parameter was base 64 decoded and converted to a dict. Why? Any help would be appreciated.</p> <p>Edit: As per request, here Is how I call the method. Python 3.5.2</p> <pre><code>p = {'hello': 'blah', 'alg': 'HS256'} f = urlsafe_b64encode(json.dumps(p).encode('utf-8')) h = json.loads(str(urlsafe_b64decode(f))[2:-1], 'utf-8') print(verify(h)) </code></pre>
1
2016-09-26T04:02:41Z
39,695,638
<p>The issue here is your use of the <code>is</code> operator to check the equality of the strings. The <code>is</code> operator checks if its two arguments refer to the same object, which is not the behavior you want here. To check if the strings are equal, use the equality operator:</p> <pre><code> def verify(rel): if not('hello' in rel and rel['hello'] == 'blah' and 'alg' in rel and rel['alg'] == 'HS256'): return False return True </code></pre>
2
2016-09-26T06:01:59Z
[ "python", "json", "base64" ]
GET and PUT operation on HTTPS (with certificate error) in python
39,694,594
<p>I'm very new to python. The job assigned to me was to perform a put and get operation on one of the products web ui using python. I tried with the following code,</p> <pre><code>import urllib2 import ssl try: response = urllib2.urlopen('https://the product web ui address') print 'response headers: "%s"' % response.info() except IOError, e: if hasattr(e, 'code'): # HTTPError print 'http error code: ', e.code elif hasattr(e, 'reason'): # URLError print "can't connect, reason: ", e.reason else: raise </code></pre> <p>This is raising an error:</p> <blockquote> <p>can't connect, reason: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)</p> </blockquote> <p>The url, while accessing through browser will show that it is having a certificate error. We need to click on proceed to go to the url. Can somebody help me with a way to perform put and get operation on such a uri. Sorry if this question seems dumb, thanks for the support.</p> <p>Also, i tried with requests. Attaching the code. It also gives the same error</p> <pre><code>import requests import sys try: r = requests.get("https://the product web ui address") data = r.content print r.status_code print data except: print "Error Occured ",sys.exc_info()[0] </code></pre> <p>The error is : </p> <blockquote> <p><strong>Error Occured class 'requests.exceptions.SSLError'</strong></p> </blockquote>
0
2016-09-26T04:09:20Z
39,694,768
<p>I got it. </p> <pre><code>import requests import sys try: r = requests.get("https://web ui address",verify=False) data = r.content f = open('myfile.xml','w') f.write(data) f.close() print "Status Code returned : " ,r.status_code except: print "Error Occured ",sys.exc_info()[0] </code></pre> <p>Adding <strong>verify=False</strong>, solved my problem.Now it throws a warning but no errors. Its working fine.</p>
0
2016-09-26T04:32:20Z
[ "python", "ssl", "get", "httprequest", "put" ]
Running a previous line?
39,694,636
<p>i have a while true so that if there is not enough seats on the plane you can't book a flight, but i want to go back to a previous line of code (line 8) because when i do this:</p> <pre><code>while True: if b == maxpass and booking == "b" or booking == "book": print ("Sorry but the flight you want is currently fully booked. Sorry for Inconviniance") print ("Welcome to Flight Booking Program") print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)") flight = input() </code></pre> <p>It keeps repeating.</p> <p>Here is the rest of the code:</p> <pre><code># b means bookings, fn means Flight Number b = 0 maxpass = 68 minpass = 0 fn = "FNO123" amount = 0 seatsremain = 68 - b print ("Welcome to Flight Booking Program") print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)") flight = input() while flight != "X": seatsremain = 68 - b while True: if flight == fn: print ("There are currently", seatsremain, "seats remaining") break else: print ("ERROR") print ("Not a valid flight number! Remember input is CASE SENSITIVE") print ("Welcome to Flight Booking Program") print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)") flight = input() print ("Would you like to book or cancel your flight?") booking = input().lower() while True: if b == maxpass and booking == "b" or booking == "book": print ("Sorry but the flight you want is currently fully booked. Sorry for Inconviniance") print ("Welcome to Flight Booking Program") print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)") flight = input() else: break if booking == "c" or booking == "b" or booking == "book" or booking == "cancel": if booking == "b" or booking == "book": print ("How many seats are you booking?") while True: try: amount = int(input()) if amount &lt;1 or amount &gt;seatsremain: print ("ERROR") print ("You must book at least 1 seat and not exceed the maximum amount of seats avaliable") print ("There are currently", seatsremain, "seats remaining") print ("How many seats are you booking?") else: b = b + amount print ("Your flight has been Booked!") print ("Welcome to Flight Booking Program") print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)") flight = input() break except ValueError: print ("You must enter a valid number!") else: if booking == "c" or booking == "cancel": print ("How many seats are you canceling?") while True: try: amount = int(input()) if amount &lt;1 or amount &gt;b: print ("ERROR") print ("You must cancel at least 1 seat and not exceed the minimum amount of seats avaliable") print ("There are currently", seatsremain, "seats remaining") print ("How many seats are you cancelling?") else: b = b - amount print ("Your flight has been Cancelled!") print ("Welcome to Flight Booking Program") print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)") flight = input() break except ValueError: print ("You must enter a valid number!") else: print ("Error") print ("Please only type book or cancel") print("There are", b, "people booked on flight", fn) </code></pre>
0
2016-09-26T04:14:20Z
39,694,769
<p>It's not 100% clear what you are asking, but I suspect you want something like this:</p> <pre><code>class MyOwnError(Exception): def __init__(self, message): self.message = message def __str__(self): return repr(self.message) while flight != "X": try: seatsremain = 68 - b if flight == fn: print ("There are currently", seatsremain, "seats remaining") else: raise MyOwnError("Not a valid flight number!") # etc... if amount &lt;1 or amount &gt;b: print ("ERROR") print ("You must cancel at least 1 seat and not exceed the minimum amount of seats avaliable") print ("There are currently", seatsremain, "seats remaining") print ("How many seats are you cancelling?") else: b = b - amount raise MyOwnError("Your flight has been Cancelled!") # etc... except MyOwnError as e: print (e.message) print ("Welcome to Flight Booking Program") print ("Please enter the flight number you want to book/cancel with? (Case Sensitve)") flight = input() </code></pre> <p>Here the exceptions force jumps out of all the loops, and can re-prompt for the input. You can expand this idea to handle the seat cancellation loop too, by using nested <code>try</code>/<code>except</code> statements.</p>
1
2016-09-26T04:32:21Z
[ "python" ]
Building Fortran extension for Python 3.5 or C extension for 2.7
39,694,646
<p>I have a Python 2.7 project that has thus far been using gfortran and MinGW to build extensions. I use MinGW because it seems to support write statements and allocatable arrays in the Fortran code while MSVC does not.</p> <p>There is another project I would like to incorporate into my own (Netgen) but it is currently set up for Python 3.5 using Boost.Python. I first tried to transfer my own program to Python 3.5 but that is where I was reminded of the MSVC issues and apparently MinGW is not supported. For that reason, I've been trying to think of a way to compile Netgen + Boost.Python for deployment in Python 2.7.</p> <p>I think the Boost part is straightforward, but it seems I need Visual C++ 2008 to get it integrated with Python 2.7. I have the Visual C++ Compiler for Python 2.7 from Microsoft, but I haven't gotten it to work inside the CMake build system. I point it to the cl.exe compilers in the VC for Python folders and CMake always tells me that building a simple test program fails. Since I don't actually have (and can't find) Visual Studio 2008, not sure how far I'd get anyway.</p> <p>There's a lot of places that could have issues here, but I'm just looking for a go/no-go answer if that's what it is. Any solutions would obviously be welcomed.</p> <p>I am running Windows 10 64-bit.</p> <p>I'm not a C/C++ expert, but it seems like I have all the tools I need to compile Netgen using the VC for Python tools (cl, link, etc). I just don't have/not sure how to put it all together into a project or something like that.</p>
2
2016-09-26T04:15:04Z
39,716,307
<p>I built Boost.Python libraries 1.61.0 from source for Python 2.7 using VC 14.0. Then used those in the build process for Netgen (again using VC 14.0) and pointed to the Python 2.7 library and include directories (as opposed to Python 3.5). This has thus far worked in Python 2.7 with my existing code.</p>
0
2016-09-27T05:01:23Z
[ "python", "c++", "boost", "fortran", "gfortran" ]
How to modify custom.xml within docx using python
39,694,652
<p>I've been using python-docx to programmatically change parts of a word document (*.docx) that needs to be updated monthly. My problem now lies with editing custom properties in the template, specifically the 'Date Completed' property.</p> <p><a href="http://i.stack.imgur.com/dAzdA.png" rel="nofollow">Custom template properties</a></p> <p>My current simplified python code is as follows:</p> <pre><code>import python-docx doc = docx.Document('MonthlyUpdate.docx') help(doc.core_properties) #only shows author, category, etc, but no 'Date Completed' </code></pre> <p>The relevant file appears to be in *.docx\docProps\<strong>custom.xml</strong>, but I'm unsure of how to edit that file within python 2.7. Is it possible through python-docx or would I need to dive into lxml/etree modules?</p>
0
2016-09-26T04:15:56Z
39,697,415
<p>This functionality hasn't been implemented yet. There's a feature request open for it and one user has done some work on it you can find linked to from there.</p> <p><a href="https://github.com/python-openxml/python-docx/issues/91" rel="nofollow">https://github.com/python-openxml/python-docx/issues/91</a></p> <p>I think this would require using his fork, so you might not get all the latest features, depending on the version the fork is based on.</p>
0
2016-09-26T07:54:29Z
[ "python", "xml", "lxml", "elementtree", "python-docx" ]
How to delete and return values from cursor in python
39,694,669
<p>PostgreSQL allows you to delete rows and return values of columns of the deleted rows using this syntax:</p> <pre><code>DELETE FROM [table_name] RETURNING [column_names] </code></pre> <p>I would like to use this syntax in Python with using <a href="https://github.com/psycopg/psycopg2" rel="nofollow">psycopg2</a> library. So I write:</p> <pre><code>cur = con.cursor() cur.execute('DELETE FROM [my_table_name] RETURNING [column_name, let's say id]') </code></pre> <p>Now I don't know what to write afterwards. Should it be:</p> <pre><code>con.commit() </code></pre> <p>But this alone does not return any values from cursor. Or should it be:</p> <pre><code>rows = cur.fetchall() </code></pre> <p>, and then iterating through the list of rows?</p> <p>But will this method actually delete the rows? It seems like commit is missing.</p> <p>Or may be I should write both, like so:</p> <pre><code>con.commit() rows = cur.fetchall() </code></pre> <p>But I'm not sure if this is correct. Trying it out could be an option, but if some of you guys know the answer, that would be safer to me. </p>
0
2016-09-26T04:18:41Z
39,699,523
<p>You query runs inside of transaction (but it's better to double check that <code>autocommit</code> is set to False), that means that all the changes you make are visible only for you (actually, it depends on other transactions settings) until you commit these changes.</p> <p>Both options work in that case:</p> <pre><code>&gt;&gt;&gt; con = db() &gt;&gt;&gt; cur = con.cursor() &gt;&gt;&gt; cur.execute("DELETE FROM tmp_delete_test WHERE id &lt; 3 RETURNING id;") &gt;&gt;&gt; result = cur.fetchall() &gt;&gt;&gt; result [(1,), (2,)] &gt;&gt;&gt; con.commit() &gt;&gt;&gt; cur.execute("DELETE FROM tmp_delete_test WHERE id &lt; 3 RETURNING id;") &gt;&gt;&gt; result = cur.fetchall() &gt;&gt;&gt; result [] </code></pre> <p>And commit, fetchall:</p> <pre><code>&gt;&gt;&gt; cur.execute("DELETE FROM tmp_delete_test WHERE id &lt; 4 RETURNING id;") &gt;&gt;&gt; con.commit() &gt;&gt;&gt; result = cur.fetchall() &gt;&gt;&gt; result [(3,)] </code></pre> <p>So, I'd suggest you to use the second option if you need no be sure that records actually have been deleted, but if you need to do something with that IDs within the same transaction, you need to use the first option.</p>
0
2016-09-26T09:45:08Z
[ "python", "postgresql", "cursor", "psycopg2", "delete-operator" ]
Queryset filter with three-deep nested models (multiple one-to-many relationships)
39,694,670
<p>I'm trying to figure out how to filter some queries in Django with my models setup something like this:</p> <pre><code>class Team(models.Model): name = models.CharField() class TeamPosition(models.Model): description = models.CharField() team = models.ForeignKey(Team) class Player(models.Model): teamposition = models.ForeignKey(TeamPosition) team = models.ForeignKey(Team) joined_date = models.DateField() left_date = models.DateField(blank=True, null=True) person = models.ForeignKey(Person) class Person(models.Model): name = models.CharField() </code></pre> <p>I'd like to find querysets that answer these questions (moved below for clarity):</p> <p>If I start at the TeamPosition objects it is much easier to figure out (but doesn't give me a queryset of Teams).</p> <p>Sample Data set:</p> <p>Object set 1:</p> <pre><code>Team(name="Apples") TeamPosition(team="Apples", description="Forward") Player(team="Apples", teamposition="Forward", joined_date="2014-01-01", left_date=null, person="Bob") TeamPosition(team="Apples", description="Defense") Player(team="Apples", teamposition="Defense", joined_date="2014-01-01", left_date=2015-01-01, person="John") Player(team="Apples", teamposition="Defense", joined_date="2015-01-01", left_date=2017-01-01, person="Paul") TeamPosition(team="Apples", description="Goalie") Player(team="Apples", teamposition="Goalie", joined_date="2014-01-01", left_date=2015-01-01, person="Jane") </code></pre> <p>Object set 2:</p> <pre><code>Team(name="Pears") TeamPosition(team="Pears", description="Forward") Player(team="Pears", teamposition="Forward", joined_date="2014-01-01", left_date=null, person="Carol") TeamPosition(team="Pears", description="Defense") Player(team="Pears", teamposition="Defense", joined_date="2015-01-01", left_date=2017-01-01, person="Bill") TeamPosition(team="Pears", description="Goalie") Player(team="Pears", teamposition="Goalie", joined_date="2014-01-01", left_date=null, person="Susan") </code></pre> <p>Object set 3:</p> <pre><code>Team(name="Oranges") TeamPosition(team="Oranges", description="Forward") TeamPosition(team="Oranges", description="Forward") TeamPosition(team="Oranges", description="Goalie") </code></pre> <p>Object set 4:</p> <pre><code>Team(name="Bananas") TeamPosition(team="Bananas", description="Forward") Player(team="Bananas", teamposition="Forward", joined_date="2014-01-01", left_date=null, person="Joe") TeamPosition(team="Bananas", description="Defense") Player(team="Bananas", teamposition="Defense", joined_date="2015-01-01", left_date=2017-01-01, person="Angela") TeamPosition(team="Bananas", description="Goalie") Player(team="Bananas", teamposition="Goalie", joined_date="2014-01-01", left_date="2016-09-30", person="Kelly") </code></pre> <p>So based on those objects, I'd expect the following results:</p> <ul> <li><p>Which Teams have available TeamPositions? (available meaning a TeamPosition without a current Player)</p> <p><code>Queryset should return Object 1 (Apples) and Object 3 (Oranges)</code></p></li> <li><p>Which Teams have all TeamPositions full with current Players? (the opposite of above) (current meaning a Player that has either no left_date or a left_date in the future)</p> <p><code>Queryset should return Object 2 (Pears) and Object 4 (Bananas)</code></p></li> <li><p>Which Teams will have an empty TeamPosition in 30 days?</p> <p><code>Queryset should return Object 4 (Bananas)</code></p></li> </ul> <p>Hopefully that makes it more clear.</p> <p>Note: Previously had a car example (hence first response), but it seemed unclear so created a better example</p>
2
2016-09-26T04:18:59Z
39,694,742
<p><strike>One question before answering: Is the line <code>carmodel = models.ForeignKey(Model)</code> ok? or should it be <code>ForeignKey(CarModel)</code> instead?</strike></p> <p>Try this query (this should give you all CarCompany objects whose CarModel's ModelYear's <code>last_availability</code> date is in the future:</p> <pre><code>from datetime import datetime CarCompany.objects.filter(carmodel__modelyear__last_availability__gte=datetime.now()) </code></pre> <p>In order to check both whether <code>last_availability</code> is in the future or blank/null I would use <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects" rel="nofollow">Q objects</a>:</p> <pre><code>from django.db.models import Q CarCompany.objects.filter(Q(carmodel__modelyear__last_availability__gte=datetime.now()) | Q(carmodel__modelyear__last_availability__isnull=True)) </code></pre> <p>For your second example, I can't think but in the same query (It answers your questions <code>Which Teams have open TeamPositions?</code> and <code>Which Teams will have an empty TeamPosition in 30 days</code>)</p> <p>But I'm not sure what do you mean by <code>Which Teams have no TeamPositions without current Players?</code> If you could explain it a bit...</p> <pre><code>Team.objects.filter(Q(teamposition__player__left_date__gte=datetime.now()) | Q(teamposition__player__left_date__isnull=True) | </code></pre>
0
2016-09-26T04:29:10Z
[ "python", "django", "database" ]
linked list output not expected in Python 2.7
39,695,046
<p>Implement a linked list and I expect output to be <code>0, -1, -2, -3, ... etc.</code>, but it is <code>-98, -98, -98, -98, ... etc.</code>, wondering what is wrong in my code? Thanks.</p> <pre><code>MAXSIZE = 100 freeListHead = None class StackNode: def __init__(self, value, nextNode): self.value = value self.nextNode = nextNode if __name__ == "__main__": # initialization for nodes and link them to be a free list nodes=[StackNode(-1, None)] * MAXSIZE freeListHead = nodes[0] for i in range(0, len(nodes)-1): nodes[i].nextNode = nodes[i+1] nodes[i].value = -i for node in nodes: # output -98, -98, -98, -98, ... etc. # exepcted output, 0, -1, -2, -3, ... etc. print node.value </code></pre>
2
2016-09-26T05:06:47Z
39,695,130
<p>This is the problem:</p> <pre class="lang-py prettyprint-override"><code># initialization for nodes and link them to be a free list nodes=[StackNode(-1, None)] * MAXSIZE </code></pre> <p>When you use the multiply operator, it will create multiple <em>references</em> to the <strong>same</strong> object, as noted <a href="http://stackoverflow.com/a/2785963/895932">in this StackOverflow answer</a>. So changing one node's value (as in <code>nodes[i].value = -i</code>) will affect every node since every item in the list points to the same object.</p> <p>In that same linked answer, the solution is to use <a class='doc-link' href="http://stackoverflow.com/documentation/python/5265/list-comprehensions#t=201609260515199970598&amp;a=syntax">list comprehension</a>, like this:</p> <pre class="lang-py prettyprint-override"><code>nodes = [StackNode(-1, None) for i in range(MAXSIZE)] </code></pre> <p>Also, note that you did not set the value of the last element, so the output (after the fix I suggested above) will be:</p> <pre> 0, -1, -2, ..., -98, -1 </pre>
10
2016-09-26T05:16:27Z
[ "python", "python-2.7" ]
Calling a method that have return value in Python
39,695,167
<p>I'm new to python and came into this piece of code. From my previous programming knowledge, I'm assuming this method should return something(<code>results</code>). But why do some statements like <code>self.children[0].query(rect, results)</code> don't assign the return value to any variable while recursively calling the method?</p> <pre><code>def query(self, rect, results=None): if results is None: rect = normalize_rect(rect) results = set() if len(self.children) &gt; 0: if rect[0] &lt;= self.center[0]: if rect[1] &lt;= self.center[1]: self.children[0].query(rect, results) if rect[3] &gt; self.center[1]: self.children[1].query(rect, results) if rect[2] &gt; self.center[0]: if rect[1] &lt;= self.center[1]: self.children[2].query(rect, results) if rect[3] &gt; self.center[1]: self.children[3].query(rect, results) for node in self.nodes: if (node.rect[2] &gt; rect[0] and node.rect[0] &lt;= rect[2] and node.rect[3] &gt; rect[1] and node.rect[1] &lt;= rect[3]): results.add(node.item) return results </code></pre>
1
2016-09-26T05:21:18Z
39,695,385
<p>You're right that the <code>query</code> function does return <code>results</code>, but it also <em>modifies</em> <code>results</code> on this line:</p> <pre><code>results.add(node.item) </code></pre> <p>A parameter used in this was is sometimes described as an "output parameter".</p> <p><code>query</code> is not a pure function. In those places where <code>query</code> is called without using its return value, <code>query</code> is being called for its side effects.</p>
2
2016-09-26T05:40:04Z
[ "python", "python-2.7", "python-3.x" ]
How print to printer with Popen and GUI tkinter
39,695,198
<p>I use code from <a href="http://stackoverflow.com/questions/12723818/print-to-standard-printer-from-python">this question</a> for printing to thermal EPSON TM-T82 printer but when I modified it with <code>tkinter</code> and <code>mainloop()</code> python not direcly printout my data until I close my layout GUI. I want this script can print out my data without I close layout GUI.</p> <p>This is my code:</p> <pre><code>import subprocess from Tkinter import * class tes_print: def __init__(self): self.printData() def printData(self): data = " MY TEXT " lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE, shell=True) lpr.stdin.write(data) root = Tk() app2 = tes_print() root.mainloop() </code></pre>
0
2016-09-26T05:23:52Z
39,695,826
<p>You are experiencing buffering. The <code>write</code> will write to a buffer which is not actually passed on to <code>lpr</code> until it fills up or you explicitly flush it.</p> <p>Running <code>lpr.communicate()</code> will flush it and allow <code>lpr</code> to run to completion.</p> <pre><code>lpr = subprocess.Popen(['lpr'], stdin=subprocess.PIPE) stdout, stderr = lpr.communicate(input=data) </code></pre>
0
2016-09-26T06:15:12Z
[ "python", "printing", "tkinter" ]
What is the easiest way to get a list of the keywords in a string?
39,695,240
<p>For example:</p> <pre><code>str = 'abc{text}ghi{num}' </code></pre> <p>I can then do</p> <pre><code>print(str.format(text='def',num=5)) &gt; abcdefghi5 </code></pre> <p>I would like to do something like</p> <pre><code>print(str.keywords) # function does not exist &gt; ['text','num'] </code></pre> <p>What is the easiest way to do this? I can search character-by-character for <code>{</code> and <code>}</code> but I wonder if there a built-in python function?</p> <p>Thank you.</p>
1
2016-09-26T05:27:32Z
39,695,322
<p>Check out the <a href="https://docs.python.org/3.5/library/string.html#string.Formatter" rel="nofollow"><code>string.Formatter</code> class</a>:</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; text = 'abc{text}ghi{num}' &gt;&gt;&gt; [t[1] for t in string.Formatter().parse(text)] ['text', 'num'] </code></pre>
3
2016-09-26T05:34:27Z
[ "python", "string", "python-3.x", "formatting" ]
How do I find the rates TP, TN, FP, FN and measure the quality of segmented algorithm?
39,695,241
<p>Currently I am implementing a system that counts the number of passengers crossing a line of interest in a subway station. To measure the quality of the segmentation algorithm, I installed a video camera on the ceiling of the subway station and I recorded a video of 13 seconds.</p> <p>The video of 13 seconds contains 412 frames.</p> <p>Below is my questions:</p> <ol> <li><p>To obtain the TPR (True Positive Rate) is necessary to analyze the frames manually, ie check every one of the 412 frames and count the times that were labeled correctly? While the FPR, is counted only the "false alarms"?</p></li> <li><p>To test each algorithm, should I use the correction filters? Or just analyze them raw form (no filters)?</p></li> <li><p>Detection of these rates cover when you're crossing the line or across your screen extension?</p></li> </ol> <p><a href="http://i.stack.imgur.com/oasmN.jpg" rel="nofollow">Here is a portion of the 412 frames</a></p> <p>I ask your help to solve this problem.</p>
0
2016-09-26T05:27:37Z
39,697,223
<p>The TP, TN, FP, FN in measure the quality of comparison between ground truth images and the output of your system. In your project you need to compare number of people who crossing a line and the computer by your program. </p>
0
2016-09-26T07:42:40Z
[ "python", "opencv", "computer-vision", "video-processing", "precision-recall" ]
How do I find the rates TP, TN, FP, FN and measure the quality of segmented algorithm?
39,695,241
<p>Currently I am implementing a system that counts the number of passengers crossing a line of interest in a subway station. To measure the quality of the segmentation algorithm, I installed a video camera on the ceiling of the subway station and I recorded a video of 13 seconds.</p> <p>The video of 13 seconds contains 412 frames.</p> <p>Below is my questions:</p> <ol> <li><p>To obtain the TPR (True Positive Rate) is necessary to analyze the frames manually, ie check every one of the 412 frames and count the times that were labeled correctly? While the FPR, is counted only the "false alarms"?</p></li> <li><p>To test each algorithm, should I use the correction filters? Or just analyze them raw form (no filters)?</p></li> <li><p>Detection of these rates cover when you're crossing the line or across your screen extension?</p></li> </ol> <p><a href="http://i.stack.imgur.com/oasmN.jpg" rel="nofollow">Here is a portion of the 412 frames</a></p> <p>I ask your help to solve this problem.</p>
0
2016-09-26T05:27:37Z
39,739,458
<p>You definitely have to manually tag each time a man is crossing the line. This part is crucial in order to be able to evaluate your algorithm correctly. </p> <p>I suggest you create a groundtruth file which list all frame indices when someone cross the line. Your algorithm output should be of the same type - frame indices where it detects line crossing (if you are using segmentation or other technique it shouldn't affect the evaluation process).</p> <p>The last thing you should do is to define a match criteria : if there is a real line crossing in frame_i and your algorithm detects a crossing in frame_j, then it will be count as true positive if abs(frame_i-frame_j) &lt; threshold, otherwise it will be count as false positive.</p>
1
2016-09-28T06:22:53Z
[ "python", "opencv", "computer-vision", "video-processing", "precision-recall" ]
confusion about a python recursion function
39,695,401
<p>I got a <code>print_backward</code> function code online, but I am so confusing about how it works and its output. </p> <p>The below is my code.</p> <pre><code>def print_backward(num): if num == 10: return num += 1 print(num) print_backward(num) print("yeah") print(num) print() print_backward(6) </code></pre> <p>The below is output.</p> <pre><code>7 8 9 10 yeah 10 yeah 9 yeah 8 yeah 7 </code></pre> <p>I can understand how it prints from 7 to 10, since each time it call recursively, num += 1.</p> <p>But I am confusing, once num achieves 10, the <code>print_backward</code> should return, then done. It should not print yeah 10, yeah 9, yeah 8, yeah 7. Why this code has called return, how it still can print? How this code works to print backward, which means why I called <code>print(num)</code>, it can print from 10 to 7? </p>
0
2016-09-26T05:41:52Z
39,695,439
<p>On the first runs, the code does not go further than the inner call to <code>print_backward(num)</code>, that is 4 times (like an infinite recursion)</p> <p>When the argument reaches 10, all the functions return and it goes further, printing the original <code>num</code>+1 with which they were called.</p> <p>The highest numbers are printed first because the calls where the number is higher return first.</p>
0
2016-09-26T05:45:51Z
[ "python", "recursion" ]
confusion about a python recursion function
39,695,401
<p>I got a <code>print_backward</code> function code online, but I am so confusing about how it works and its output. </p> <p>The below is my code.</p> <pre><code>def print_backward(num): if num == 10: return num += 1 print(num) print_backward(num) print("yeah") print(num) print() print_backward(6) </code></pre> <p>The below is output.</p> <pre><code>7 8 9 10 yeah 10 yeah 9 yeah 8 yeah 7 </code></pre> <p>I can understand how it prints from 7 to 10, since each time it call recursively, num += 1.</p> <p>But I am confusing, once num achieves 10, the <code>print_backward</code> should return, then done. It should not print yeah 10, yeah 9, yeah 8, yeah 7. Why this code has called return, how it still can print? How this code works to print backward, which means why I called <code>print(num)</code>, it can print from 10 to 7? </p>
0
2016-09-26T05:41:52Z
39,695,484
<p>The function calling happens through stack. </p> <p>You call print_backward on 6. So stack will have 6. <br> Now you call it on 7 ---> So stack has 6,7 where 7 is top. <br> Now you call it on 8 ----> So stack is 6,7,8 <br> Now on 9, So stack is 6,7,8,9 <br> Now on 10, So stack is 6,7,8,9,10. <br></p> <p>Now when function returns , it pops from stack. <br> So, you were in function with parameter 10. So, you called return and it gets popped from stack. Now stack is 6,7,8,9. <br> Now it prints "yeah" and 10 (because num is 9 and we did num = num + 1 before). Now it returns and pops 9. Now stack is 6,7,8 <br> Now it prints yeah and 9 because num is 8 and we did num = num +1 before).</p> <p>Similarly, it prints other as well.</p>
0
2016-09-26T05:49:31Z
[ "python", "recursion" ]
confusion about a python recursion function
39,695,401
<p>I got a <code>print_backward</code> function code online, but I am so confusing about how it works and its output. </p> <p>The below is my code.</p> <pre><code>def print_backward(num): if num == 10: return num += 1 print(num) print_backward(num) print("yeah") print(num) print() print_backward(6) </code></pre> <p>The below is output.</p> <pre><code>7 8 9 10 yeah 10 yeah 9 yeah 8 yeah 7 </code></pre> <p>I can understand how it prints from 7 to 10, since each time it call recursively, num += 1.</p> <p>But I am confusing, once num achieves 10, the <code>print_backward</code> should return, then done. It should not print yeah 10, yeah 9, yeah 8, yeah 7. Why this code has called return, how it still can print? How this code works to print backward, which means why I called <code>print(num)</code>, it can print from 10 to 7? </p>
0
2016-09-26T05:41:52Z
39,695,894
<p>Function call is actually a stack operation. And recursion is a special case of function call.</p> <p>Every time you call a function, the Return Address will be push into a stack, and when the function return, the program will pop the Return address from the top of stack, and program continue to execute from there. You can have a look at the official description about <code>call stack</code> in <a href="https://en.wikipedia.org/wiki/Call_stack" rel="nofollow">wikipedia</a>.</p> <p>For your example, <code>print_backward(7)</code> call first, and then the next command will push into the stack, and then when you call the <code>print_backward(8)</code>, the next command will be pushed into the stack again, so after 4 recursion call, the stack will be like this:</p> <pre><code>+-------------------------+ &lt;--- Stack top | num = 10, print("yeah") | \ | num = 9, print("yeah") | | | num = 8, print("yeah") | &gt; Call stack | num = 7, print("yeah") | | +-------------------------+ / </code></pre> <p>The criteria hit the if condition <code>num == 10:</code> when calling from <code>print_backward(10)</code>. The program execute <code>return</code> statement, the <code>Return address</code> from the stack top will be pop, and program starts from there, that means, <code>print('yeah')</code> for num = 10 will be execute. After finished call for <code>print_backward(10)</code>, the stack will pop another Return Address from the stack, and <code>print('yeah')</code> in <code>print_backward(9)</code> will be executed. This operation will be ended when the stack is empty, that means ,there is no more function return.</p>
1
2016-09-26T06:20:40Z
[ "python", "recursion" ]
confusion about a python recursion function
39,695,401
<p>I got a <code>print_backward</code> function code online, but I am so confusing about how it works and its output. </p> <p>The below is my code.</p> <pre><code>def print_backward(num): if num == 10: return num += 1 print(num) print_backward(num) print("yeah") print(num) print() print_backward(6) </code></pre> <p>The below is output.</p> <pre><code>7 8 9 10 yeah 10 yeah 9 yeah 8 yeah 7 </code></pre> <p>I can understand how it prints from 7 to 10, since each time it call recursively, num += 1.</p> <p>But I am confusing, once num achieves 10, the <code>print_backward</code> should return, then done. It should not print yeah 10, yeah 9, yeah 8, yeah 7. Why this code has called return, how it still can print? How this code works to print backward, which means why I called <code>print(num)</code>, it can print from 10 to 7? </p>
0
2016-09-26T05:41:52Z
39,696,575
<p>For your case - <code>print_backward(6)</code> it took 4 calls (recursively) to hit return criteria i.e. <code>if num == 10</code> - during those calls the function printed:</p> <pre><code>7 # print_backward(6) - first call we made 8 # print_backward(7) - recursive 9 # print_backward(8) - recursive 10 # print_backward(9) - recursive - inner most, where the return is executed </code></pre> <p>For next recursive call <code>print_backward(10)</code> the return condition gets true, and the function starts returning (starting from the inner most call) - as result the lines below the recursive call (line 6) get called i.e. </p> <pre><code>yeah # 4th call (inner most) returned 10 yeah # 3rd call returned 9 yeah # 2nd call returned 8 yeah # 1st call returned 7 </code></pre> <p>The call stack view visualization 'd be:</p> <pre><code>print_backward(6) | 7 # num += 1 and then print(num) | print_backward(7) | | 8 | | print_backward(8) | | | 9 | | | print_backward(9) | | | | 10 | | | | | print_backward(10) | | | | | | return | | | | yeah # print("yeah") | | | | 10 # print(num) | | | | () # print() | | | yeah | | | 9 | | | () | | yeah | | 8 | | () | yeah | 7 | () </code></pre>
0
2016-09-26T07:02:46Z
[ "python", "recursion" ]
confusion about a python recursion function
39,695,401
<p>I got a <code>print_backward</code> function code online, but I am so confusing about how it works and its output. </p> <p>The below is my code.</p> <pre><code>def print_backward(num): if num == 10: return num += 1 print(num) print_backward(num) print("yeah") print(num) print() print_backward(6) </code></pre> <p>The below is output.</p> <pre><code>7 8 9 10 yeah 10 yeah 9 yeah 8 yeah 7 </code></pre> <p>I can understand how it prints from 7 to 10, since each time it call recursively, num += 1.</p> <p>But I am confusing, once num achieves 10, the <code>print_backward</code> should return, then done. It should not print yeah 10, yeah 9, yeah 8, yeah 7. Why this code has called return, how it still can print? How this code works to print backward, which means why I called <code>print(num)</code>, it can print from 10 to 7? </p>
0
2016-09-26T05:41:52Z
39,697,202
<p>when print_backward(6) is called then</p> <pre><code>1 check for 10 2 increase 6 by one num = 7 3 print 7 4 call backward with 7 </code></pre> <p>for 6 print_backward is not completed yet and print_backward(7) is pushed on the top of stack. The remaining part</p> <pre><code>print("yeah") print(7) </code></pre> <p>will execute at last when the recursive call is completed. I am skipping check 10 in the below steps. Will include that in last steps.</p> <pre><code>5 increase 7 by one num = 8 6 print 8 7 call backward with 8 (7 not completed) 8 increase 8 by one num = 9 9 print 9 10 call backward with 9 (8 not completed) 11 increase 9 by one num = 10 12 print 10 return is encountered 13 call backward with 10 (9 not completed) 14 check for 10 and return. 9 will continue for the execution. 15 in the execution of 9 num is 10 so yeah is printed and then 10 is printed and print_backward for 9 is completed. Similarly for 8 num is 9 which print yeah followed by 9 and so on. </code></pre>
0
2016-09-26T07:41:31Z
[ "python", "recursion" ]
How do i transfer a value from transient object to a non transient object in openerp 6
39,695,405
<pre><code>class stock_transfer(osv.osv): _inherit="stock.transfer" _columns={ 'psd_allow_logo':fields.boolean('Alow Logo'), } stock_transfer() class indent_report(osv.osv_memory): _inherit = "indent.report" _columns = { 'psd_allow_logo':fields.boolean('Alow Logo'), } def write(self, cr, uid, ids, psd_allow_logo, context = None): res = super(indent_report, self).write(cr, uid, ids, values, context = active_ids) if 'psd_allow_logo' in values: for res in self.browse(cr, uid, ids, context = active_ids): self.pool.get('stock.transfer').write(cr, uid, [res.stock_transfer_id.id], {'psd_allow_logo': values['psd_allow_logo'],}, context = active_ids) return res # if rec.psd_allow_logo: # self.pool.get('stock.transfer').write(cr, uid, ids, {'psd_allow_logo' : True}, context=context) # else: # self.pool.get('stock.transfer').write(cr, uid, ids, {'psd_allow_logo' : False}, context=context) indent_report() </code></pre> <p>I am trying to change change the stock_transfer.psd_allow_logo when changed in indent_report.psd_allow_logo but the write isn't working &amp; i have even tried </p>
0
2016-09-26T05:42:23Z
39,695,795
<pre><code> self.pool.get('stock.transfer').write(cr,uid,active_ids[0],{'psd_allow_logo':rec.psd_allow_logo}) </code></pre> <p>adding that to indent.report solved the issue, i was missing active_ids</p>
0
2016-09-26T06:12:14Z
[ "python", "openerp-6" ]
Finding value of another attribute given an attribute
39,695,461
<p>I have a CSV that has multiple lines, and I am looking to find the <code>JobTitle</code> of a person, given their name. The CSV is now in a DataFrame <code>sal</code> as such:</p> <pre><code>id employee_name job_title 1 SOME NAME SOME TITLE </code></pre> <p>I'm trying to find the <code>JobTitle</code> of some given persons name, but am having a hard time doing this. I am currently trying to learn pandas by doing crash courses and I know I can get a list of job titles by using <code>sal['job_title']</code>, but that gives me an entire list of the job titles.</p> <p><strong>How can I find the value of a specific person?</strong></p>
2
2016-09-26T05:47:45Z
39,695,485
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>sal[sal.employee_name == 'name'] </code></pre> <p>If need select only some column, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> with <code>boolean indexing</code>:</p> <pre><code>sal.ix[sal.employee_name == 'name', 'job_title'] </code></pre> <p>Sample:</p> <pre><code>sal = pd.DataFrame({'id':[1,2,3], 'employee_name':['name','name1','name2'], 'job_title':['titleA','titleB','titleC']}, columns=['id','employee_name','job_title']) print (sal) id employee_name job_title 0 1 name titleA 1 2 name1 titleB 2 3 name2 titleC print (sal[sal.employee_name == 'name']) id employee_name job_title 0 1 name titleA print (sal.ix[sal.employee_name == 'name', 'job_title']) 0 titleA Name: job_title, dtype: object </code></pre>
2
2016-09-26T05:49:31Z
[ "python", "csv", "pandas" ]
Calculate the length of polyline from csv
39,695,481
<p>I'm still new to python. I need helps to calculate the length of polyline with simple distance calculation:</p> <pre><code> distance = sqrt( (x1 - x2)**2 + (y1 - y2)**2 ) </code></pre> <p>For instance my input csv looks like this. </p> <pre><code>id x y sequence 1 1.5 2.5 0 1 3.2 4.9 1 1 3.6 6.6 2 1 4.4 5.0 3 2 2.0 4.5 0 2 3.5 6.0 1 </code></pre> <p>I have 'id' and 'sequence' (sequence number of the line vertices). How read the csv file? if current 'id' has the same value as previous row 'id', then perform the distance calculation : sqrt( (x[i] - x[i-1])**2 + (y[i] - y[i-1])**2 ). After that, group by 'id' and sum their 'distance' value.</p> <p>The output csv would look like this:</p> <pre><code>id distance 1 ? 2 ? </code></pre> <p>Thanks in advance. </p>
-2
2016-09-26T05:48:51Z
39,699,432
<p>Polyline:</p> <p><a href="http://i.stack.imgur.com/vML5D.gif" rel="nofollow"><img src="http://i.stack.imgur.com/vML5D.gif" alt="enter image description here"></a></p> <p><strong>Distance between two points and the distance between a point and polyline:</strong></p> <pre><code>def lineMagnitude (x1, y1, x2, y2): lineMagnitude = math.sqrt(math.pow((x2 - x1), 2)+ math.pow((y2 - y1), 2)) return lineMagnitude #Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline). def DistancePointLine (px, py, x1, y1, x2, y2): #http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba LineMag = lineMagnitude(x1, y1, x2, y2) if LineMag &lt; 0.00000001: DistancePointLine = 9999 return DistancePointLine u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1))) u = u1 / (LineMag * LineMag) if (u &lt; 0.00001) or (u &gt; 1): #// closest point does not fall within the line segment, take the shorter distance #// to an endpoint ix = lineMagnitude(px, py, x1, y1) iy = lineMagnitude(px, py, x2, y2) if ix &gt; iy: DistancePointLine = iy else: DistancePointLine = ix else: # Intersecting point is on the line, use the formula ix = x1 + u * (x2 - x1) iy = y1 + u * (y2 - y1) DistancePointLine = lineMagnitude(px, py, ix, iy) return DistancePointLine </code></pre> <p>For more information visit: <a href="http://www.maprantala.com/2010/05/16/measuring-distance-from-a-point-to-a-line-segment/" rel="nofollow">http://www.maprantala.com/2010/05/16/measuring-distance-from-a-point-to-a-line-segment/</a></p>
0
2016-09-26T09:40:54Z
[ "python", "csv", "distance" ]
querying panda df to filter rows where a column is not Nan
39,695,606
<p>I am new to python and using pandas.</p> <p>I want to query a dataframe and filter the rows where one of the columns is not <code>NaN</code>.</p> <p>I have tried:</p> <pre><code>a=dictionarydf.label.isnull() </code></pre> <p>but a is populated with <code>true</code> or <code>false</code>. Tried this </p> <pre><code>dictionarydf.query(dictionarydf.label.isnull()) </code></pre> <p>but gave an error as I expected</p> <p>sample data:</p> <pre><code> reference_word all_matching_words label review 0 account fees - account NaN N 1 account mobile - account NaN N 2 account monthly - account NaN N 3 administration delivery - administration NaN N 4 administration fund - administration NaN N 5 advisor fees - advisor NaN N 6 advisor optimum - advisor NaN N 7 advisor sub - advisor NaN N 8 aichi delivery - aichi NaN N 9 aichi pref - aichi NaN N 10 airport biz - airport travel N 11 airport cfo - airport travel N 12 airport cfomtg - airport travel N 13 airport meeting - airport travel N 14 airport summit - airport travel N 15 airport taxi - airport travel N 16 airport train - airport travel N 17 airport transfer - airport travel N 18 airport trip - airport travel N 19 ais admin - ais NaN N 20 ais alpine - ais NaN N 21 ais fund - ais NaN N 22 allegiance custody - allegiance NaN N 23 allegiance fees - allegiance NaN N 24 alpha late - alpha NaN N 25 alpha meal - alpha NaN N 26 alpha taxi - alpha NaN N 27 alpine admin - alpine NaN N 28 alpine ais - alpine NaN N 29 alpine fund - alpine NaN N </code></pre> <p>I want to filter the data where label is not NaN</p> <p>expected output:</p> <pre><code> reference_word all_matching_words label review 0 airport biz - airport travel N 1 airport cfo - airport travel N 2 airport cfomtg - airport travel N 3 airport meeting - airport travel N 4 airport summit - airport travel N 5 airport taxi - airport travel N 6 airport train - airport travel N 7 airport transfer - airport travel N 8 airport trip - airport travel N </code></pre>
2
2016-09-26T05:59:32Z
39,695,625
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow"><code>dropna</code></a>:</p> <pre><code>df = df.dropna(subset=['label']) print (df) reference_word all_matching_words label review 10 airport biz - airport travel N 11 airport cfo - airport travel N 12 airport cfomtg - airport travel N 13 airport meeting - airport travel N 14 airport summit - airport travel N 15 airport taxi - airport travel N 16 airport train - airport travel N 17 airport transfer - airport travel N 18 airport trip - airport travel N </code></pre> <p>Another solution - <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow"><code>notnull</code></a>:</p> <pre><code>df = df[df.label.notnull()] print (df) reference_word all_matching_words label review 10 airport biz - airport travel N 11 airport cfo - airport travel N 12 airport cfomtg - airport travel N 13 airport meeting - airport travel N 14 airport summit - airport travel N 15 airport taxi - airport travel N 16 airport train - airport travel N 17 airport transfer - airport travel N 18 airport trip - airport travel N </code></pre>
2
2016-09-26T06:00:49Z
[ "python", "pandas", "indexing", null, "pandasql" ]
Scipy Write Audio Issue
39,695,645
<p>I'm doing an ICA application where I aim to separate signals from within a mixed signal observation. It seems to work in theory, when I look at the ICA recovered signal in numpy ndarray from, the signal is clearly visible. However, when I try to write this ndarray to a .wav for play back, the signal disappears altogether. This can be easily seen in the following picture: <a href="http://i.stack.imgur.com/hp2Gn.png" rel="nofollow"><img src="http://i.stack.imgur.com/hp2Gn.png" alt="enter image description here"></a></p> <p>The first graph shows the numpy ndarray signal of the ICA recovered signal. The second graph shows where I simply loaded the file that was supposedly written by scipy .wav write, as you can see it's silent.</p> <p>This behavior is puzzling because earlier on I used the exact same procedure in generating my mixed signal observations using a mixing matrix (also in the same format, numpy ndarrays). In the following picture, you'll notice every thing is exactly the same, and yet, for whatever reason, the scipy write .wav <em>worked</em> -- the second graph does verify the signal was loaded from the .wav that was written from the first graph (the numpy nd array).</p> <p><a href="http://i.stack.imgur.com/gQ2GG.png" rel="nofollow"><img src="http://i.stack.imgur.com/gQ2GG.png" alt="enter image description here"></a></p> <p>I'd like to know what's behind the conditional success for this. I know that floats and integers need to be handled carefully, but I'm pretty sure I have not overlooked anything. </p> <p>The pictures explain it pretty well, the only thing I'd like to clarify is what the <code>play_wav</code> function is doing, it basically just writes the .wav and creates an audio object:</p> <pre><code>def play_wav(file, fs, data): wavfile.write(file, fs, data.astype(np.dtype('i2'))) display(Audio(filename=file)) </code></pre> <p>imports:</p> <pre><code>import numpy as np from scipy.io import wavfile from IPython.display import display, Audio from sklearn.decomposition import FastICA </code></pre>
1
2016-09-26T06:02:11Z
39,712,587
<p>It looks as though the array you're trying to write contains values in the range [-0.02, 0.02]. When you cast the array to 16bit ints before writing it to the WAV file, all of these values will be truncated to zero!</p> <p><code>wavfile.write</code> supports float32 arrays, so you could just skip the casting step altogether. Alternatively, rescale the array to fall between 2<sup>15</sup> and -2<sup>15</sup> before casting it to int16, e.g.:</p> <pre><code>((data + data.min()) * (2 ** 15) / data.ptp()).astype(np.int16) </code></pre>
2
2016-09-26T21:19:30Z
[ "python", "audio", "scipy", "scikit-learn", "signal-processing" ]
Runge-Kutta 4th Order error approximation for varied time-steps
39,695,675
<pre><code>from __future__ import division import numpy as np import matplotlib.pyplot as plt def f(x, t): #function return -x def exact(t): #exact solution return np.exp(-t) def Rk4(x0, t0, dt): #Runge-Kutta Fourth Order Error t = np.arange(0, 1+dt, dt) n = len(t) x = np.array([x0]*n) x[0],t[0] = x0,t0 for i in range(n-1): h = t[i+1]-t[i] k1 = h*f(x[i], t[i]) k2 = h*f(x[i]+0.5*k1, t[i]+0.5*h) k3 = h*f(x[i]+0.5*k2, t[i]+0.5*h) k4 = h*f(x[i]+k3, t[i+1]) x[i+1] = x[i]+(k1+2.0*(k2+k3)+k4 )/6.0 E = abs(x[n-1]-exact(1)) return E vecRk4 = np.vectorize(Rk4) dt = 10e-4 dtime = [] delta = 10e-4 while dt &lt; 1: if Rk4(1.0,0.0,dt) &lt; Rk4(1.0,0.0,dt+delta): dtime.append(dt) S = vecRk4(1.0,0.0,dtime) dt = dt + delta plt.plot(dtime,S) plt.xlabel("dt (s)") plt.ylabel("Error") plt.show() </code></pre> <p>When I run the code, it results in a jagged plot with spikes that yield zero error at many values of dt, with positive error in-between. (sorry, I can't embed an image of the graph). These large spikes should not be occurring, as there should be a continuous decrease in error as the time-step dt is decreased. However, I'm not sure how to fix this nor do I know where the error results from. I tried eliminating the spikes by adding in the while loop, hoping to have it only add points to my dtime array if the error at dt is larger than the error at dt+delta, but it resulted in precisely the same graph.</p>
2
2016-09-26T06:04:14Z
39,696,192
<p>A short test demonstrates</p> <pre><code>In [104]: import numpy as np In [105]: dt = 0.6 In [106]: np.arange(0, 1+dt, dt) Out[106]: array([ 0. , 0.6, 1.2]) </code></pre> <p>Thus to get meaningful results, either set <code>t[n-1]=1</code> at the start or compute the error as </p> <pre><code>E = abs(x[n-1]-exact(t[n-1])) </code></pre>
1
2016-09-26T06:40:44Z
[ "python", "numerical-methods", "runge-kutta" ]
Python Flask app- leading zeros in TOTP error. (Python 2.7)
39,695,700
<p>I have written a python flask application in which app generate totp for validation. (Python 2.7)</p> <p>I use onetimepass library to validate totp against the application secret. code:</p> <pre><code> json_data=request.get_json() my_token=json_data['OTP'] is_valid = otp.valid_totp(token=my_token, secret=my_secret) </code></pre> <p>However the issue i am facing is whenever a totp comes with leading zeroes it turns into an Octal number. OTP is always treated as incorrect and user is unable to login.</p> <p>How can i preserve these leading zeroes in such case? any code snippets or guidance will be of much help.</p>
3
2016-09-26T06:06:25Z
39,924,574
<p>Answer was simple as my_token was coming as string and i was converting it to a number. Adding this before converting to a number did the trick:</p> <p><code>my_token.lstrip("0") #removes leading characters</code></p>
0
2016-10-07T19:31:18Z
[ "python", "python-2.7", "flask", "otp", "octal" ]
django two apps with same urls in each url's.py file
39,695,836
<p>I have two apps in my django project one is "home" and other is "administrator". I am using home app for frontend of the site and administrator app for admin panel and the urls' for accessing both frontend and admin panel respectively are :-</p> <pre><code>www.domainname.com/home www.domainname.com/administrator </code></pre> <p><strong>main urls.py file is :-</strong></p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^home/', include('home.urls')), url(r'^administrator/', include('administrator.urls')) ] </code></pre> <p><strong>Home's urls.py file is :-</strong></p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^sport$', views.sport, name='sport'), url(r'^register$', views.signup_signin, name='register'), url(r'^login$', views.login, name='login'), url(r'^signup$', views.signup, name='signup'), url(r'^registered-successfully$', views.registered_successfully, name='registered-successfully'), url(r'^logout$', views.logout_view, name='logout'), url(r'^dashboard$', views.dashboard, name='dashboard'), url(r'^create-new-event$', views.create_new_event, name='create-new-event'), url(r'^help$', views.help, name='help'), url(r'^account-settings$', views.account_settings, name='account-settings') ] </code></pre> <p><strong>Admin's urls.py file is :-</strong></p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^logout$', views.logout, name='logout'), url(r'^dashboard$', views.dashboard, name='dashboard'), url(r'^profile$', views.profile, name='profile'), url(r'^edit-profile$', views.edit_profile, name='edit-profile'), url(r'^check-password$', views.check_password, name='check-password'), url(r'^help$', views.faq_management, name='help') ] </code></pre> <p>As you can check that there are some common url's in both app's file, like index, dashboard, logout help.</p> <p>These urls are creating problem if i link them in href, for example if i link "help" url in frontend using</p> <pre><code>&lt;a href="{% url 'help' %}" &gt; </code></pre> <p>It tries to redirect me to admin panel's help url, and if i change the order of apps in main urls.py file than vice versa problem occurs. </p>
1
2016-09-26T06:16:35Z
39,695,902
<p>You can try adding a namespace to your urls</p> <pre><code>urlpatterns = [ url(r'^home/', include('home.urls', namespace='home')), url(r'^administrator/', include('administrator.urls', namespace='admin')) ] </code></pre> <p>Then you can access them like:</p> <pre><code>&lt;a href="{% url 'home:help' %}" &gt; &lt;a href="{% url 'admin:help' %}" &gt; </code></pre>
1
2016-09-26T06:21:24Z
[ "python", "django" ]
django two apps with same urls in each url's.py file
39,695,836
<p>I have two apps in my django project one is "home" and other is "administrator". I am using home app for frontend of the site and administrator app for admin panel and the urls' for accessing both frontend and admin panel respectively are :-</p> <pre><code>www.domainname.com/home www.domainname.com/administrator </code></pre> <p><strong>main urls.py file is :-</strong></p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^home/', include('home.urls')), url(r'^administrator/', include('administrator.urls')) ] </code></pre> <p><strong>Home's urls.py file is :-</strong></p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^sport$', views.sport, name='sport'), url(r'^register$', views.signup_signin, name='register'), url(r'^login$', views.login, name='login'), url(r'^signup$', views.signup, name='signup'), url(r'^registered-successfully$', views.registered_successfully, name='registered-successfully'), url(r'^logout$', views.logout_view, name='logout'), url(r'^dashboard$', views.dashboard, name='dashboard'), url(r'^create-new-event$', views.create_new_event, name='create-new-event'), url(r'^help$', views.help, name='help'), url(r'^account-settings$', views.account_settings, name='account-settings') ] </code></pre> <p><strong>Admin's urls.py file is :-</strong></p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^logout$', views.logout, name='logout'), url(r'^dashboard$', views.dashboard, name='dashboard'), url(r'^profile$', views.profile, name='profile'), url(r'^edit-profile$', views.edit_profile, name='edit-profile'), url(r'^check-password$', views.check_password, name='check-password'), url(r'^help$', views.faq_management, name='help') ] </code></pre> <p>As you can check that there are some common url's in both app's file, like index, dashboard, logout help.</p> <p>These urls are creating problem if i link them in href, for example if i link "help" url in frontend using</p> <pre><code>&lt;a href="{% url 'help' %}" &gt; </code></pre> <p>It tries to redirect me to admin panel's help url, and if i change the order of apps in main urls.py file than vice versa problem occurs. </p>
1
2016-09-26T06:16:35Z
39,696,227
<pre><code>urlpatterns = [ url(r'^home/', include('home.urls')), url(r'^administrator/', include('administrator.urls')) ] </code></pre> <p>My suggestion</p> <p>Set Site URL in Settings.py </p> <p>Example : </p> <pre><code>SITE_URL = "http://localhost:8000/" </code></pre> <p>in Template you can pass the URL regex directly.</p> <pre><code>&lt;a href="{{SITE_URL}}/home/help/" &gt; &lt;a href="{{SITE_URL}}/administrator/help/"&gt; </code></pre> <p>if you dont put the Site url , chances is there to get page not found error</p>
-1
2016-09-26T06:42:29Z
[ "python", "django" ]
unable to insert string or read-only buffer, not long
39,695,857
<p>I tried to venture off while following a python-flask tutorial and am having trouble figuring out an error. I tried browsing stack for 6 hours off and on and nothing out there related could help me out, possibly because I am a beginner...</p> <p>I gathered data from a form (all the data is passing through fine, I tested by printing to the console) and want to insert it into a mysql table.</p> <p>Here is the query code:</p> <pre><code>c.execute("INSERT INTO posts (post_count, seller, title, id, bus, condition, transType, post_description, trade, price) VALUES (%i, %s, %s, %s, %s, %s, %s, %s, %s, %i)", (thwart(postCount), thwart(seller), thwart(title), thwart(id), thwart(bus), thwart(condition), thwart(transType), thwart(description), thwart(tradeFor), thwart(price))) </code></pre> <p>The table description in MySql is:</p> <pre><code>+------------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+-------------+------+-----+---------+----------------+ | post_id | int(11) | NO | PRI | NULL | auto_increment | | post_count | int(11) | YES | | NULL | | | seller | varchar(60) | YES | | NULL | | | title | text | YES | | NULL | | | id | varchar(25) | YES | | NULL | | | bus | varchar(35) | YES | | NULL | | | condition | varchar(20) | YES | | NULL | | | transType | varchar(25) | YES | | NULL | | | post_description | text | YES | | NULL | | | trade | text | YES | | NULL | | | price | int(11) | YES | | NULL | | +------------------+-------------+------+-----+---------+----------------+ </code></pre> <p>The error I keep getting is: <code>must be string or read-only buffer, not long</code></p> <p>I don't see where the long is coming from...Not sure what else you may need to help me out so ask if there's more info I can add.</p> <p>much appreciated!</p>
1
2016-09-26T06:18:08Z
39,712,962
<p>Check all the variables <code>type</code> which are being inserted. </p> <p>I would guess one of them is suppose to be text or varchar, but is a <code>long</code>. </p> <p>Try converting the <code>long</code> to a <code>str</code> basically one of the numbers being inserted isnt text but might look like 37582L</p> <pre><code>print(type(post_count)) print(type(seller)) print(type(post_description)) if type(some_long) is long: do_insert(str(some_long)) </code></pre>
0
2016-09-26T21:49:44Z
[ "python", "mysql" ]
implement stack with freelist feature in Python 2.7
39,695,969
<p>Design a stack with free list feature (i.e. after a node is popped, its space is reusable by future push operation, and kept in free list). The code is simplified and does not make sense in some perspective, and I just use below code to show the general idea of stack with free list (as a prototype).</p> <p>My question is about how to design <code>pop</code> operation. My confusion is since a reference to a node is returned after <code>pop</code> operation, for example in my code there is <code>node1 = stack.pop()</code>, the reference to a node might be used by client who call <code>pop</code>, and the same node reference is reclaimed in free list and might be used by other <code>push</code> operation, how to resolve such conflict and wondering for general advice for design free list feature with stack, linked list or queue.</p> <pre><code>MAXSIZE = 100 freeListHead = None class StackNode: def __init__(self, value, nextNode): self.value = value self.nextNode = nextNode class Stack: def __init__(self): self.top = None self.size = 0 def peek(self): # return StackNode return self.top def push(self, value): global freeListHead if self.size &gt;= MAXSIZE: raise Exception('stack full') node = freeListHead node.value = value freeListHead = node.nextNode node.nextNode = self.top self.top = node self.size += 1 def pop(self): if self.size == 0: return None node = self.top self.top = self.top.nextNode self.size -= 1 return node if __name__ == "__main__": # initialization for nodes and link them to be a free list nodes = [StackNode(-1, None) for i in range(MAXSIZE)] freeListHead = nodes[0] for i in range(0, len(nodes)-1): nodes[i].nextNode = nodes[i+1] stack = Stack() stack.push(1) stack.push(50) stack.push(100) stack.push(200) print stack.peek().value node1 = stack.pop() print node1.value print stack.peek().value </code></pre>
-1
2016-09-26T06:25:19Z
39,697,103
<p>You could simplify your code by returning the <code>value</code> given to <code>push</code> instead of <code>StackNode</code> holding the value. There are no concerns of memory consumption since you can set <code>node.value</code> to <code>None</code> in <code>pop</code> before returning the result. Below is simple example on how this would work in the practice:</p> <pre><code>class Node: def __init__(self): self.nextNode = self.value = None class Stack: def __init__(self, maxSize): self.maxSize = maxSize self.size = 0 self.top = self.free = None def push(self, value): if self.size == self.maxSize: raise Exception('Stack full') if self.free: node = self.free self.free = node.next else: node = Node() node.value = value node.nextNode = self.top self.top = node self.size += 1 def pop(self): if not self.top: raise Exception('Stack empty'); node = self.top self.top = node.nextNode node.nextNode = self.free self.free = node self.size -= 1 result = node.value node.value = None return result stack = Stack(3) for i in range(3): stack.push(list(range(i + 1))) while stack.size: print(stack.pop()) </code></pre> <p>Output:</p> <pre><code>[0, 1, 2] [0, 1] [0] </code></pre>
1
2016-09-26T07:35:40Z
[ "python", "python-2.7", "stack" ]
What is the difference between calling a method from parent class using super() and using self?
39,696,077
<pre><code>class Car: def __init__(self, car_name, manufacturer, cost): self.__car_name=car_name self.__manufacturer=manufacturer self.__cost=cost def display_car_details(self): print(self.__car_name, self.__manufacturer, self.__cost) class Super_Car(Car): def __init__(self, car_name, manufacturer, cost, top_speed, material_used, engine_type): super().__init__(car_name, manufacturer, cost) self.__top_speed=top_speed self.__material_used=material_used self.__engine_type=engine_type def display_super_car_details(self): self.display_car_details() # this? super().display_car_details() # or that? print(self.__top_speed, self.__material_used, self.__engine_type) </code></pre> <p>Please tell me the difference between calling <code>display_car_details()</code> by using <code>self.…</code> and calling by <code>super().…</code>. The method which calls the above function is in <code>Super_car</code> class with name <code>display_super_car_details()</code>.</p>
1
2016-09-26T06:33:04Z
39,696,128
<p>In your specific case, there is no difference. If the methods had the <em>same name</em>, you would not be calling the parent class using <code>self.…</code>, but your own method again, creating infinite recursion.</p> <p>With <code>super()</code>, the call is always going to the method in the parent class in <a href="https://rhettinger.wordpress.com/2011/05/26/super-considered-super/" rel="nofollow">Method Resolution Order</a>, thus preventing the infinite recursion. More details on <code>super()</code> itself can also be found in the <a href="https://docs.python.org/3/library/functions.html#super" rel="nofollow">official documentation</a>.</p> <p>Generally, you only need <code>super()</code> if you really need the inherited method, such as when re-implementing that exact method.</p> <p>For example, running this code will lead to <code>RecursionError</code>, due to maximum recursion depth exceeded. The reason is that <code>Bar.method1()</code> calls <em>itself</em> over and over, because we are using <code>self.…</code> instead of <code>super().…</code>.</p> <pre><code>class Foo: def method1(self): print("I just want to be called") class Bar(Foo): def method1(self): self.method1() # oops b = Bar() b.method1() </code></pre> <p>This on the other hand has the intended effect:</p> <pre><code>class Foo: def method1(self): print("I just want to be called") class Bar(Foo): def method1(self): super().method1() # sweet b = Bar() b.method1() </code></pre> <p>Again, in your specific example it does not matter, because the other method (<code>display_car_details</code>) is <em>only</em> defined in the <em>parent class</em>, so it is unambiguous which method to call. If you had overridden <code>display_car_details</code> with something different, the use of <code>super()</code> and <code>self</code> would again yield different results:</p> <pre><code>class Bar(Foo): def method1(self): print("You are not supposed to call this") def method2(self): super().method1() def method3(self): self.method1() </code></pre> <p>Observe the difference in the interactive interpreter:</p> <pre><code>&gt;&gt;&gt; b = Bar() &gt;&gt;&gt; b.method1() You are not supposed to call this &gt;&gt;&gt; b.method2() I just want to be called &gt;&gt;&gt; b.method3() You are not supposed to call this </code></pre>
1
2016-09-26T06:36:52Z
[ "python", "python-3.x", "oop" ]
Boto3 and AWS Lambda - deleting snapshots older than
39,696,136
<p>I'm currently utilising AWS Lambda to create snapshots of my database and delete snapshots older than 6 days. I'm using the Boto3 library to interface with the AWS API. I'm using a CloudWatch rule to trigger the deletion code every day. </p> <p>Normally this is working fine, but I've come across an issue where at the start of the month (first 6 days) the delete script does not appear to delete any snapshots, even though snapshots older than 6 days exist. </p> <p>The code is below: </p> <pre><code>import json import boto3 from datetime import datetime, timedelta, tzinfo class Zone(tzinfo): def __init__(self,offset,isdst,name): self.offset = offset self.isdst = isdst self.name = name def utcoffset(self, dt): return timedelta(hours=self.offset) + self.dst(dt) def dst(self, dt): return timedelta(hours=1) if self.isdst else timedelta(0) def tzname(self,dt): return self.name UTC = Zone(10,False,'UTC') # Setting retention period of 6 days retentionDate = datetime.now(UTC) - timedelta(days=6) def lambda_handler(event, context): print("Connecting to RDS") rds = boto3.setup_default_session(region_name='ap-southeast-2') client = boto3.client('rds') snapshots = client.describe_db_snapshots(SnapshotType='manual') print('Deleting all DB Snapshots older than %s' % retentionDate) for i in snapshots['DBSnapshots']: if i['SnapshotCreateTime'] &lt; retentionDate: print ('Deleting snapshot %s' % i['DBSnapshotIdentifier']) client.delete_db_snapshot(DBSnapshotIdentifier=i['DBSnapshotIdentifier'] ) </code></pre>
0
2016-09-26T06:37:38Z
39,697,823
<p>Code looks perfectly fine and <a href="http://boto3.readthedocs.io/en/latest/reference/services/rds.html#RDS.Client.describe_db_snapshots" rel="nofollow">you are following the documentation</a></p> <p>I would simply add</p> <pre><code> print(i['SnapshotCreateTime'], retentionDate) </code></pre> <p>in the for loop, the logs will tell you quickly what's going on in the beginning of every month.</p> <p>Btw, are you using RDS from AWS? RDS supports automatic snapshot creation and you can also define a retention period. There is no need to create custom lambda scripts.</p>
1
2016-09-26T08:18:16Z
[ "python", "aws-lambda", "boto3" ]
Boto3 and AWS Lambda - deleting snapshots older than
39,696,136
<p>I'm currently utilising AWS Lambda to create snapshots of my database and delete snapshots older than 6 days. I'm using the Boto3 library to interface with the AWS API. I'm using a CloudWatch rule to trigger the deletion code every day. </p> <p>Normally this is working fine, but I've come across an issue where at the start of the month (first 6 days) the delete script does not appear to delete any snapshots, even though snapshots older than 6 days exist. </p> <p>The code is below: </p> <pre><code>import json import boto3 from datetime import datetime, timedelta, tzinfo class Zone(tzinfo): def __init__(self,offset,isdst,name): self.offset = offset self.isdst = isdst self.name = name def utcoffset(self, dt): return timedelta(hours=self.offset) + self.dst(dt) def dst(self, dt): return timedelta(hours=1) if self.isdst else timedelta(0) def tzname(self,dt): return self.name UTC = Zone(10,False,'UTC') # Setting retention period of 6 days retentionDate = datetime.now(UTC) - timedelta(days=6) def lambda_handler(event, context): print("Connecting to RDS") rds = boto3.setup_default_session(region_name='ap-southeast-2') client = boto3.client('rds') snapshots = client.describe_db_snapshots(SnapshotType='manual') print('Deleting all DB Snapshots older than %s' % retentionDate) for i in snapshots['DBSnapshots']: if i['SnapshotCreateTime'] &lt; retentionDate: print ('Deleting snapshot %s' % i['DBSnapshotIdentifier']) client.delete_db_snapshot(DBSnapshotIdentifier=i['DBSnapshotIdentifier'] ) </code></pre>
0
2016-09-26T06:37:38Z
39,714,087
<p>Due to the distributed nature of the CloudWatch Events and the target services, the delay between the time the scheduled rule is triggered and the time the target service honors the execution of the target resource might be several seconds. Your scheduled rule will be triggered within that minute but not on the precise 0th second.</p> <p>In that case, your utc now will may miss a few seconds during execution there by retention date also may miss a few seconds. This should be very minimal but still there is a chance for missed deletion. Going by that, the subsequent run should delete the missed ones in the earlier run.</p>
0
2016-09-26T23:56:16Z
[ "python", "aws-lambda", "boto3" ]
Django: no such table snippets_snippet
39,696,148
<p>I'm following this Django Rest tutorial on serialization: <a href="http://www.django-rest-framework.org/tutorial/1-serialization/#getting-started" rel="nofollow">http://www.django-rest-framework.org/tutorial/1-serialization/#getting-started</a></p> <p>I followed it pretty much to the letter. It gives the above error when I try to save a snippet.</p> <pre><code>from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser snippet = Snippet(code='foo = "bar"\n') snippet.save() </code></pre> <p>I'm working on Windows. The tutorial is made for Apple. I have had to enter some commands slightly differently for this reason. I have no idea if this has to do with what is wrong in this case. </p> <p>I don't know where to even start in figuring out the problem here, so I could use any help. Thanks.</p>
0
2016-09-26T06:38:18Z
39,697,724
<p>I believe the error refers to the models.py. Could you show the file so I can double check that too. Also there is a chance for unapllied migartions, double check if you've done this as well.</p>
0
2016-09-26T08:11:24Z
[ "python", "django", "serialization", "code-snippets" ]
Is there any Built in function for PHP Application same as compile() in python?
39,696,234
<p>I am looking for the builtin function or any integrated way in Apache or Php with same working as compile() in Python . for my PHP Application Is there any thing related to this ??</p>
3
2016-09-26T06:43:14Z
39,697,003
<p>First of all this is my first answer. :) </p> <p>As of I know, PHP is an interpreted language in which only that executable file(php.exe in your php installation directory) is compiled and your code is only interpreted and no inbuilt functions like python.</p> <p>If you still need compile as of in python, try <a href="http://hhvm.com/" rel="nofollow" title="HHVM">HHVM</a> a virtual machine</p> <p>(never used that)</p> <p>and there are some third party compilers like <a href="http://www.zzee.com/phpexe/" rel="nofollow">ZZEE</a> which compiles into a GUI exe</p>
1
2016-09-26T07:27:56Z
[ "php", "python", "apache", "yii2" ]
How to deploy Flask application in google app engine with core python packages?
39,696,378
<p>I want to deploy below python structure in google app engine I want to know how to configure .yaml files for below flask application with core python packages and please suggest a better way to deploy code in google app engine.(I want to deploy all the packages in one location/directory)</p> <p>Packages:</p> <pre><code> Model-Engine - api - api - __int__.py - view.py - utils.py - models.py - tests - runserver.py - setup.py - driver - driver - core - __init__.py - celery.py - celery_tasks.py - tests - setup.py Physics - core - core - __init__.py - base.py - pipe_line_simulation.py -tests - setup.py Gas-model - src - model - __init__.py - gas_model.py - converter - __init__.py - hdf5_to_csv.py - setup.py </code></pre>
0
2016-09-26T06:50:32Z
39,698,471
<h1>My suggestion.</h1> <p>1.Create application in Google admin console <a href="https://console.cloud.google.com/appengine?src=ac" rel="nofollow">google admin console</a></p> <ol start="2"> <li>Put app.yaml inside your project root directory </li> </ol> <p>sample code:</p> <pre><code>application: "Application name from google app engine" version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: / script: home.app - url: /index\.html script: home.app - url: /stylesheets static_dir: stylesheets - url: /(.*\.(gif|png|jpg))$ static_files: static/\1 upload: static/.*\.(gif|png|jpg)$ - url: /admin/.* script: admin.app login: admin </code></pre> <ol start="3"> <li><p>Make folder (<code>lib</code>) inside the root directory put all the dependencies inside the folder</p></li> <li><p>Create a file <code>appengine_config.py</code> inside the project directory and put the below codes.</p></li> </ol> <p><code>from google.appengine.ext import vendor</code></p> <p><code>vendor.add('lib')</code></p> <ol start="5"> <li><p>Run the app localy using this command - dev_appserver.py .</p></li> <li><p>Deploy the application.</p> <p><code>appcfg.py update -A {your-project-id} -V v1</code> .</p></li> </ol> <p>If this isn't your first deployment, you will need to set the new version as the default version with</p> <pre><code>appcfg.py set_default_version -V v1 -A {your-project-id} </code></pre> <p>Congratulations! Your application is now live at your-app-id.appspot.com</p>
0
2016-09-26T08:54:53Z
[ "python", "google-app-engine", "flask" ]
Flask-WTForms RadioField custom validator message doesn't work
39,696,563
<p>In <code>Flask-WTForms</code>, we can give a custom message for each validator for each field. But for <code>RadioField</code> it shows the default message only. Below is an example.</p> <pre><code>&gt;&gt;&gt; from wtforms import Form, RadioField, TextField &gt;&gt;&gt; from wtforms.validators import * </code></pre> <p><strong>TextField</strong></p> <pre><code>&gt;&gt;&gt; class MyForm(Form): x = TextField(u'Some text', validators = [Required(message="Hello")]) </code></pre> <p><strong>Error Message</strong></p> <pre><code>&gt;&gt;&gt; form = MyForm() &gt;&gt;&gt; form.x.data &gt;&gt;&gt; form.validate() False &gt;&gt;&gt; form.errors {'x': ['Hello']} </code></pre> <p>So for a <code>TextField</code> it shows the custom error message.</p> <p><strong>RadioField</strong></p> <pre><code>&gt;&gt;&gt; class MyForm(Form): x = RadioField(choices = [(1, '1'), (2, '2')], validators = [Required(message="Hello")]) </code></pre> <p><strong>Error Message</strong></p> <pre><code>&gt;&gt;&gt; form = MyForm() &gt;&gt;&gt; form.x.data u'None' &gt;&gt;&gt; form.validate() False &gt;&gt;&gt; form.errors {'x': [u'Not a valid choice']} </code></pre> <p>The custom error message is not there. I guess, validation for <code>TextField</code> and <code>RadioField</code> will be different process and may be that's why it's showing the default message.</p> <p>So my Question is How to show a custom message for the validation of a <code>RadioField</code>?</p>
1
2016-09-26T07:02:09Z
39,697,125
<p>You are right about that the process is different.</p> <p>So if you go do <a href="https://github.com/wtforms/wtforms/" rel="nofollow">source code</a> there is base <a href="https://github.com/wtforms/wtforms/blob/master/wtforms/fields/core.py#L23" rel="nofollow"><code>Field</code></a> class with <a href="https://github.com/wtforms/wtforms/blob/master/wtforms/fields/core.py#L178" rel="nofollow"><code>validate</code></a> method. It's said</p> <blockquote> <pre><code>""" Validates the field and returns True or False. `self.errors` will contain any errors raised during validation. This is usually only called by `Form.validate`. Subfields shouldn't override this, but rather override either `pre_validate`, `post_validate` or both, depending on needs.&gt; :param form: The form the field belongs to. :param extra_validators: A sequence of extra validators to run. """ </code></pre> </blockquote> <p>And the procedure of validation is <code>pre_validate()</code> -> <code>validate()</code> -> <code>post_validate()</code>(Call <code>pre_validate</code> -> Run validators -> Call <code>post_validate</code>)</p> <p>As you can guess, <code>RadioField</code> has it's own <code>pre_validate()</code> method, but basically <code>SelectField</code>'s one. And then when <code>RadioField</code> is inherit from <code>SelectField</code> it has it too.</p> <blockquote> <pre><code>def pre_validate(self, form): for v, _ in self.choices: if self.data == v: break else: raise ValueError(self.gettext('Not a valid choice')) </code></pre> </blockquote> <p>So that's why you get <code>'Not a valid choice'</code> error instead of your custom one, on <code>wtforms.validators.Required()</code> validator, <del>because it just didn't go through the <code>pre_validate()</code> and it stops.</del></p> <p><em>Note</em>: <code>Required</code> validator is depracated and will be removed in WTForms 3.0, and in <a href="https://github.com/wtforms/wtforms/pull/282" rel="nofollow">that</a> pull request they already removed it's usage. Instead of <code>Required()</code> validator, use <code>DataRequired()</code></p> <p><strong>UPDATE</strong>: Since you add your validator to field you still should be able to get your error. Because since <a href="https://github.com/wtforms/wtforms/blob/master/wtforms/fields/core.py#L470-L475" rel="nofollow"><code>pre_validate()</code></a> raises only <code>ValueError</code> it doesn't stop <a href="https://github.com/wtforms/wtforms/blob/master/wtforms/fields/core.py#L178-L214" rel="nofollow"><code>validate()</code></a></p> <blockquote> <pre><code># Call pre_validate try: self.pre_validate(form) except StopValidation as e: if e.args and e.args[0]: self.errors.append(e.args[0]) stop_validation = True except ValueError as e: self.errors.append(e.args[0]) </code></pre> </blockquote> <p>And then it goes to </p> <blockquote> <pre><code># Run validators if not stop_validation: chain = itertools.chain(self.validators, extra_validators) stop_validation = self._run_validation_chain(form, chain) </code></pre> </blockquote> <p>And here is your validator exists and should add new error to the list of errors(<code>form.x.error</code>), however it converts <code>None</code> to <code>'None'</code>, so your <code>form.x.data</code> becomes <code>'None'</code>(<code>str</code> type), and now it goes to <a href="https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py#L200-L208" rel="nofollow"><code>__call__</code></a></p> <blockquote> <pre><code>def __call__(self, form, field): if not field.data or isinstance(field.data, string_types) and not field.data.strip(): if self.message is None: message = field.gettext('This field is required.') else: message = self.message field.errors[:] = [] raise StopValidation(message) </code></pre> </blockquote> <p>And the condition <code>not field.data</code> is <code>False</code>, because <code>field.data</code> is <code>'None'</code>. Why data convert from <code>None</code> to <code>'None'</code> for <code>SelectField</code> and its related ones is explained in <a href="https://github.com/wtforms/wtforms/issues/289" rel="nofollow">Issue on GitHub</a> and probably be fixed when <a href="https://github.com/wtforms/wtforms/pull/288" rel="nofollow">Pull Request</a> will be merged in master.</p>
1
2016-09-26T07:36:53Z
[ "python", "flask", "flask-wtforms" ]
"PermissionError" thrown when typing "exit()" to leave the Python interpreter
39,696,606
<p>When I enter the python interpreter as a regular user with <code>python</code>. I see this:</p> <pre><code>Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 2 2016, 17:53:06) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux Type "help", "copyright", "credits" or "license" for more information. </code></pre> <p>I can immediately type <code>exit()</code> and this happens:</p> <pre><code>&gt;&gt;&gt; exit() Error in atexit._run_exitfuncs: PermissionError: [Errno 13] Permission denied </code></pre> <p>I think it may be related to the fact that running <code>sudo python3</code> gives: </p> <pre><code>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; </code></pre> <p>This looks to be a different python 3.5 install.</p> <p>If this is the issue I would like to have my anaconda python install run when I type <code>sudo python3</code>. How do I do this?</p>
3
2016-09-26T07:04:18Z
39,697,033
<p>Having googled the error message, I found this issue: <a href="http://bugs.python.org/issue19891" rel="nofollow">http://bugs.python.org/issue19891</a></p> <p>It seems that the problem often has to do with the current user not having a home directory (which I think is logical for a user called python) or not having the proper permissions on their home directory, but the issue is still open.</p>
2
2016-09-26T07:31:04Z
[ "python", "ubuntu", "anaconda", "sudo" ]
Passing variables between jython scripts and sharing SQL connection
39,696,692
<p>I have two jython scripts and I have created connection to Oracle database in the 1st script and declared some variables and I want to use that in 2nd script without having to write the getconnection string again in 2nd script and also have to use the data / variables from one script and pass it on to the other. Global keyword is not working. Thanks in advance .</p>
0
2016-09-26T07:09:05Z
39,867,205
<p>If all you want is sharing some common values e.g. target server name , you can </p> <p>1) create a new .py file which contains the variable</p> <pre><code># common.py DB=db.company.com </code></pre> <p>2) In your scripts, import the variable from the new .py file</p> <pre><code>from common import DB ... odbc.connect('SERVER=%s' % DB) </code></pre> <p>These code assumes you put all .py files in the same directory.</p>
0
2016-10-05T06:51:55Z
[ "python", "sql", "jython" ]
odoo is not recognizing python modules
39,696,708
<p>i have installed beautifulsoup4 using pip install BeautifulSoup and through normal python project it can import the module. (from bs4 import BeautifulSoup) but in odoo it get error no module name bs4 even though it is installed. does anyone have solution?</p>
0
2016-09-26T07:10:03Z
39,696,804
<p>Check to make sure odoo is using the Python installation you think it is (I'd guess it's not).</p> <pre><code>import sys print(sys.path) </code></pre> <p>Try that from a python prompt where <code>import bs4</code> works and from the odoo prompt where it doesn't. The difference should give you the answer.</p>
0
2016-09-26T07:15:58Z
[ "python", "windows", "openerp", "odoo-8" ]
How to pass an image to a subprocess in python
39,696,764
<p>The program is trying to read an image and then trying to pass the image to one of the subprocess for further preprocessing. I am trying to pass the image using subprocess args parameter.</p> <pre><code>import subprocess import base64 img =[] img.append(base64.b64encode(open('test.jpg', "rb").read())) output = subprocess.check_output(['python', 'test1.py',img]) print "output",output </code></pre> <p>In the code the image is being passed to test1.py, In test1.py i am manipulating the image and then trying to return it back to the main process.</p> <p>The current implementation is giving an error : <strong>The filename or extension is too long</strong></p> <p>so how can i pass this image from the main process to the subprocess and also how can i send back the image back from the subprocess to the main process?</p>
0
2016-09-26T07:13:29Z
39,699,195
<p>I do it by using the <code>subprocess.Popen</code>:</p> <p>This is my directory structure:</p> <pre><code>. ├── main.py ├── src.jpg └── test1.py </code></pre> <p>In the following code, I change the size of the src.jpg and save it as a new file called <code>src.thumbnail</code>.</p> <p>This is the <code>main.py</code>. In the <code>main.py</code> I open two files as input stream(the stream of the original picture) and output stream(the stream of the target picture).</p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import subprocess def main(): # args are python interpreter and python file args = ["/home/yundongx/.virtualenvs/read/bin/python", "/tmp/img/test1.py"] with open("src.thumbnail", "w+b") as outstream, \ open("src.jpg", "rb") as instream: ps = subprocess.Popen(args, stdin=instream, stdout=outstream) ps.wait() if __name__ == '__main__': main() </code></pre> <p>And this is the <code>test1.py</code></p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PIL import Image import sys import io size = (128, 128) def main(): try: im = Image.open(io.BytesIO(sys.stdin.buffer.read())) im.thumbnail(size) output = io.BytesIO() im.save(output, "JPEG") sys.stdout.buffer.write(output.getvalue()) except IOError as e: sys.stderr.write("Cannot read the data\n") raise e if __name__ == '__main__': main() </code></pre> <p>In the <code>test1.py</code>, The program read the img data from the stdin(you need to convert it to the BytesIO), write the img data(Saved into the BytesIO) to the stdout after processing it.</p>
1
2016-09-26T09:29:25Z
[ "python", "image-processing", "subprocess" ]
Which one is good practice about python formatted string?
39,696,818
<p>Suppose I have a file on <code>/home/ashraful/test.txt</code>. Simply I just want to open the file. Now my question is:</p> <p>which one is good practice?</p> <p><strong>Solution 1:</strong> </p> <pre><code>dir = "/home/ashraful/" fp = open("{0}{1}".format(dir, 'test.txt'), 'r') </code></pre> <p><strong>Solution 2:</strong> </p> <pre><code>dir = "/home/ashraful/" fp = open(dir + 'test.txt', 'r') </code></pre> <p>The both way I can open file. </p> <p>Thanks :) </p>
4
2016-09-26T07:16:31Z
39,696,863
<p>instead of concatenating string use <code>os.path.join</code> <code>os.path.expanduser</code> to generate the path and open the file. (assuming you are trying to open a file in your home directory)</p> <pre><code>with open(os.path.join(os.path.expanduser('~'), 'test.txt')) as fp: # do your stuff with file </code></pre>
14
2016-09-26T07:18:55Z
[ "python", "file" ]
Which one is good practice about python formatted string?
39,696,818
<p>Suppose I have a file on <code>/home/ashraful/test.txt</code>. Simply I just want to open the file. Now my question is:</p> <p>which one is good practice?</p> <p><strong>Solution 1:</strong> </p> <pre><code>dir = "/home/ashraful/" fp = open("{0}{1}".format(dir, 'test.txt'), 'r') </code></pre> <p><strong>Solution 2:</strong> </p> <pre><code>dir = "/home/ashraful/" fp = open(dir + 'test.txt', 'r') </code></pre> <p>The both way I can open file. </p> <p>Thanks :) </p>
4
2016-09-26T07:16:31Z
39,696,890
<p>I think the best way would be to us os.path.join() here</p> <pre><code>import os.path #… dir = '/home/ashraful/' fp = open(os.path.join(dir, 'test.txt'), 'r') </code></pre>
2
2016-09-26T07:21:10Z
[ "python", "file" ]
Which one is good practice about python formatted string?
39,696,818
<p>Suppose I have a file on <code>/home/ashraful/test.txt</code>. Simply I just want to open the file. Now my question is:</p> <p>which one is good practice?</p> <p><strong>Solution 1:</strong> </p> <pre><code>dir = "/home/ashraful/" fp = open("{0}{1}".format(dir, 'test.txt'), 'r') </code></pre> <p><strong>Solution 2:</strong> </p> <pre><code>dir = "/home/ashraful/" fp = open(dir + 'test.txt', 'r') </code></pre> <p>The both way I can open file. </p> <p>Thanks :) </p>
4
2016-09-26T07:16:31Z
39,696,960
<p>If your goal is to open files/directories, as others have mentioned, you should use the <code>os.path.join()</code> method. However, if you want to format string in Python -- as your question title suggests -- then your first approach should be preferred. To quote from <a href="https://www.python.org/dev/peps/pep-3101/" rel="nofollow">PEP 310</a>:</p> <blockquote> <p>This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator.</p> </blockquote>
4
2016-09-26T07:25:27Z
[ "python", "file" ]
Karger's min cut randomized contraction algorithm [implemented in Python]
39,696,923
<p>Here's my Python implementation for min cut algorithm-</p> <pre><code>def findMinCut(dict): replace_list = [] while len(dict.keys()) &gt; 2: #uniformly pick 2 values a,b= random.sample(dict.keys(),2) #keep record of all the replaced nodes replace_list.append(a) replace_list.append(b) if a in dict.keys() and b in dict.keys(): #always true if condition dict[a] += dict[b] while a in dict[a]: dict[a].remove(a) while b in dict[a]: dict[a].remove(b) del dict[b] key = dict.keys() l1 = dict[key[0]] l2 = dict[key[1]] for i in range(0,len(replace_list),2): for index_1 in range(0, len(l1)): if l1[index_1] == replace_list[i+1]: l1[index_1] = replace_list[i] for index_2 in range(0, len(l2)): if l2[index_2] == replace_list[i+1]: l2[index_2] = replace_list[i] i = 0 j = 0 len_key1 = 0 len_key2 = 0 while i &lt; len(l1): if key[1] == l1[i]: len_key1 += 1 i += 1 while j &lt; len(l2): if key[0] == l2[j]: len_key2 += 1 j += 1 #deliberate check to make sure both lengths are always equal if len_key1 == len_key2: return len_key1 else: print "unequal" + str(len_key2) + str(len_key1) def main(): filename = sys.argv[1] f = open(filename, 'rU') dict = {} for nums in f: nums = nums.split() dict[int(nums[0])] = map(int,nums[1:len(nums)]) N = (len(dict.keys())) #N = N*N #N = 1 N = int(math.ceil(N*N * math.log(N))) true_min = findMinCut(dict) for i in range(0,N): f = open(filename, 'rU') print i for nums in f: nums = nums.split() dict[int(nums[0])] = map(int, nums[1:len(nums)]) min_cut = findMinCut(dict) if true_min &gt; min_cut: true_min = min_cut print true_min </code></pre> <p>When I run this code of the following data set :</p> <pre><code>1 2 3 4 7 2 1 3 4 3 1 2 4 4 1 2 3 5 5 4 6 7 8 6 5 7 8 7 1 5 6 8 8 5 6 7 </code></pre> <p>I get the right min cut i.e., 2 but only after running for atleast N^2ln(N) times. However for larger data set, I'm not sure I get the right min cut value. </p> <p>I have following questions:</p> <ul> <li><p>Is this the right implementation of algorithm?</p></li> <li><p>Based on the results of above posted dataset and assuming the implementation is correct, how to determine the number of iterations after which the algorithm will compute the actual min cut?</p></li> </ul> <p>This is not for any college programming assignment. I'm trying to learn graph algorithms for knowledge purpose. Also, I'm new to Python, so any tips on the coding style and how can they be improved will be highly appreciated. </p>
0
2016-09-26T07:22:25Z
39,698,513
<p>You run the algorithm <strong>N^2ln(N)</strong> times because only after running the algorithm, <strong>N^2ln(N)</strong> times, the <strong>probability of success is >= (N - 1)/(N).</strong></p> <p>David Krager's algorithm cannot determine the number of iterations after which the right min-cut is found, becuase it is not deterministic.</p> <p>The Key Idea is that you have to run the algorithm <strong>N^2ln(N)</strong> times to ensure high probability of success.</p> <p>Its fairly simple to implement:</p> <pre><code>Repeat the following N^2ln(N) times { Start from a original graph. while there are more than 2 vertices { Pick a random edge with two vertices in different sets and contract it } X = The number of crossing edges Keep track of the minimum X found so far. } Min Cut = Minimum X found. </code></pre>
0
2016-09-26T08:56:22Z
[ "python", "algorithm", "minimum" ]
How to make a regular expression to take me href, src, css links python
39,697,024
<p>I need to take the links src, css, href, a html page and save them to a text file.</p> <p>I need to do with regular expressions (regex). Thanks!</p>
-2
2016-09-26T07:29:47Z
39,697,137
<pre><code>import re p = re.compile(ur'.*(src|css|href|a html).*') test_str1 = '&lt;a html&gt;' test_str2 = 'String without any tags' if re.match(p, test_str1) is not None: print test_str1 if re.match(p, test_str2) is not None: print test_str2 &gt;&gt; &lt;a html&gt; </code></pre> <p>Here is a solution for python 2.7, I assume that you understand the regex part but if not here is a good tutorial <a href="https://regex101.com/" rel="nofollow">site</a> that you can use to test your regex.</p>
0
2016-09-26T07:37:38Z
[ "python" ]
Python Dictionary counting the values against each key
39,697,145
<p>I have a list of dictionaries that looks like this:</p> <pre><code>[{'id':1,'name':'Foo','age':20},{'id':2,'name':'Bar'}] </code></pre> <p>How can I get count of total values against each key i.e 3 against id:1</p>
0
2016-09-26T07:38:05Z
39,697,221
<p>You can use <code>len()</code> on dictionaries to get the number of keys:</p> <pre><code>&gt;&gt;&gt; a = [{'id':1,'name':'Foo','age':20},{'id':2,'name':'Bar'}] &gt;&gt;&gt; len(a[0]) 3 &gt;&gt;&gt; len(a[1]) 2 </code></pre>
3
2016-09-26T07:42:26Z
[ "python", "dictionary" ]
Python Dictionary counting the values against each key
39,697,145
<p>I have a list of dictionaries that looks like this:</p> <pre><code>[{'id':1,'name':'Foo','age':20},{'id':2,'name':'Bar'}] </code></pre> <p>How can I get count of total values against each key i.e 3 against id:1</p>
0
2016-09-26T07:38:05Z
39,697,295
<p>A more detailed problem description would have been helpful. For now I assume that you want the length of each dictionary in the list keyed against the value of the <code>id</code> key. In which case something like</p> <pre><code>val_counts = {d['id']: len(d) for d in dlist} </code></pre> <p>should meet your needs. It's a dict comprehension whose keys are the <code>id</code> values and whose values are the lengths of each dictionary in the list. For your particular data the <code>val_counts</code> dictionary I get is</p> <pre><code>{1: 3, 2: 2} </code></pre>
1
2016-09-26T07:47:09Z
[ "python", "dictionary" ]
Append duplicate items at the end of list whithout changing the order
39,697,245
<p>I am new to python and was trying to Append duplicate items at the end of list whithout changing the order</p> <pre><code>testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56] def duplicate(alist): p = len(alist) duplicate = False for i in range(0, p): for j in range (i + 1, p): if alist[i] == alist[j]: b = alist.index(alist[j]) a = alist.pop(b) alist.append(a) p -= 1 duplicate = True print alist if duplicate == False: print "No duplicate item found" duplicate(testlist) </code></pre> <p>OUTPUT : <code>[32, 8, 1, 17, 5, 2, 42, 13, 56, 1, 2]</code></p> <p>DESIRED OUTPUT : <code>[1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]</code></p> <p>Any help what wrong I am doing here</p>
0
2016-09-26T07:44:07Z
39,697,655
<p>I think that in this case the creation of a new list is more efficient and clear in comparison with the permutations in the original list:</p> <pre><code>testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56] def duplicate(alist): filtered, duplicates = [], [] for element in alist: if element in filtered: duplicates.append(element) continue filtered.append(element) if not duplicates: print "No duplicate item found" return alist return filtered + duplicates new_list = duplicate(testlist) print new_list </code></pre>
2
2016-09-26T08:06:48Z
[ "python", "python-2.7", "scripting" ]
Append duplicate items at the end of list whithout changing the order
39,697,245
<p>I am new to python and was trying to Append duplicate items at the end of list whithout changing the order</p> <pre><code>testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56] def duplicate(alist): p = len(alist) duplicate = False for i in range(0, p): for j in range (i + 1, p): if alist[i] == alist[j]: b = alist.index(alist[j]) a = alist.pop(b) alist.append(a) p -= 1 duplicate = True print alist if duplicate == False: print "No duplicate item found" duplicate(testlist) </code></pre> <p>OUTPUT : <code>[32, 8, 1, 17, 5, 2, 42, 13, 56, 1, 2]</code></p> <p>DESIRED OUTPUT : <code>[1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]</code></p> <p>Any help what wrong I am doing here</p>
0
2016-09-26T07:44:07Z
39,697,684
<p>You may use the Collections module to get <code>OrderedDict</code> for maintaining the order of elements.</p> <p>The technique we use here is to create a dictionary to store the number of occurrences of each element in the array and use the <code>dict</code> to lookup the number of occurrences for later use.</p> <p>In the <code>for</code> loop we look up if there is already element present in the <code>dict</code> using the <code>get</code> method. If <code>true</code> then we increase the counter else initialize the counter to be zero.</p> <pre><code>import collections lst = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56] # Create a dictionary storing the the number of occurences occurences_dict = collections.OrderedDict() for i in lst: occurences_dict[i] = occurences_dict.get(i, 0) + 1 final = occurences_dict.keys() + [k for k, v in occurences_dict.items() if v&gt;1] print final &gt;&gt;&gt; [1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2] </code></pre>
0
2016-09-26T08:08:58Z
[ "python", "python-2.7", "scripting" ]
Append duplicate items at the end of list whithout changing the order
39,697,245
<p>I am new to python and was trying to Append duplicate items at the end of list whithout changing the order</p> <pre><code>testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56] def duplicate(alist): p = len(alist) duplicate = False for i in range(0, p): for j in range (i + 1, p): if alist[i] == alist[j]: b = alist.index(alist[j]) a = alist.pop(b) alist.append(a) p -= 1 duplicate = True print alist if duplicate == False: print "No duplicate item found" duplicate(testlist) </code></pre> <p>OUTPUT : <code>[32, 8, 1, 17, 5, 2, 42, 13, 56, 1, 2]</code></p> <p>DESIRED OUTPUT : <code>[1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]</code></p> <p>Any help what wrong I am doing here</p>
0
2016-09-26T07:44:07Z
39,697,692
<p>I solved it this way. I also made some changes to make the code a bit more Pythonic.</p> <pre><code>test_list = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56] def duplicate(a_list): list_length = len(a_list) duplicate = False checked = [] for i in range(list_length): if a_list.count(a_list[i]) &gt; 1: if a_list[i] not in checked: duplicate = True a_list.append(a_list[i]) checked.append(a_list[i]) if duplicate == False: print("No duplicate item found") return None return a_list print(duplicate(test_list)) </code></pre>
0
2016-09-26T08:09:14Z
[ "python", "python-2.7", "scripting" ]
Append duplicate items at the end of list whithout changing the order
39,697,245
<p>I am new to python and was trying to Append duplicate items at the end of list whithout changing the order</p> <pre><code>testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56] def duplicate(alist): p = len(alist) duplicate = False for i in range(0, p): for j in range (i + 1, p): if alist[i] == alist[j]: b = alist.index(alist[j]) a = alist.pop(b) alist.append(a) p -= 1 duplicate = True print alist if duplicate == False: print "No duplicate item found" duplicate(testlist) </code></pre> <p>OUTPUT : <code>[32, 8, 1, 17, 5, 2, 42, 13, 56, 1, 2]</code></p> <p>DESIRED OUTPUT : <code>[1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]</code></p> <p>Any help what wrong I am doing here</p>
0
2016-09-26T07:44:07Z
39,697,923
<p>Instead of checking values, compare on index.</p> <p>Please check this code:</p> <pre><code>testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56,32] print("Original list - ",testlist) tmp_list = [] exclude =[] for i in range(len(testlist)): if i == testlist.index(testlist[i]): tmp_list.append(testlist[i]) else: exclude.append(testlist[i]) tmp_list.extend(exclude) testlist = tmp_list print("Updated list - ",testlist) </code></pre> <p>Output:</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py Original list - [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56, 32] Updated list - [1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2, 32] C:\Users\dinesh_pundkar\Desktop&gt; </code></pre>
0
2016-09-26T08:25:53Z
[ "python", "python-2.7", "scripting" ]
Any way to get the references of an object with Python C API?
39,697,274
<p>I want to check the references of an PyObject in C++. Any way to get the references of an object with Python C API? Like: gc.get_referrers(), is there similar API in C lib?</p> <p>I'm using Python C APIs to run Python scripts. So I want to debug ref leak problem in my C++ code.</p>
-2
2016-09-26T07:45:39Z
39,697,471
<p>A similar question has been answered here: <a href="http://stackoverflow.com/questions/26134455/how-to-get-reference-count-of-a-pyobject">How to get reference count of a PyObject?</a></p>
-1
2016-09-26T07:58:27Z
[ "python", "c" ]
Count how many attributes have a word as a substring of longer text value
39,697,349
<p>For example, if I have a data frame that looks like this:</p> <pre><code>id title 1 assistant 2 chief executive officer 3 director 4 chief operations officer 5 assistant manager 6 producer </code></pre> <p>If I wanted to find how many <code>title</code> have the word <strong>assistant</strong> in them, the result should be <code>2</code>. If I wanted to find how many <code>title</code> have <strong>chief</strong> in them, the result should be <code>2</code> as well.</p> <p>Is there a fast way to do this using pandas?</p>
0
2016-09-26T07:51:10Z
39,697,392
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.count.html" rel="nofollow"><code>str.count</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="nofollow"><code>sum</code></a>:</p> <pre><code>print (df.title.str.count('chief')) 0 0 1 1 2 0 3 1 4 0 5 0 Name: title, dtype: int64 print (df.title.str.count('chief').sum()) 2 print (df.title.str.count('assistant').sum()) 2 </code></pre>
1
2016-09-26T07:52:48Z
[ "python", "string", "pandas", "dataframe", "count" ]
How do I check for an empty nested list in Python?
39,697,570
<p>Say I have a list like </p> <pre><code>cata = [["Shelf", 12, "furniture", [1,1]], ["Carpet", 50, "furnishing", []]] </code></pre> <p>and I want to find out in each nested list if it's empty or not.</p> <p>I am aware of using for loops to iterate through the lists, and if statements to verify as I have in a function</p> <pre><code>def myfunc(cata): for inner in cata: for inner_2 in inner[3]: if inner_2: return "True" else: return "False" </code></pre> <p>However instead of returning: </p> <pre><code>'True' 'False' </code></pre> <p>All I get is:</p> <pre><code>'False' </code></pre> <p>Is there some method of searching nested loops that I'm missing?</p>
0
2016-09-26T08:02:42Z
39,697,734
<p>You're <code>return</code>ing from the function, that essentially means that you don't evaluate every element.</p> <p>Apart from that <code>for inner_2 in inner[3]:</code> will not do what you want because it won't execute for empty lists (<em>it doesn't have elements to iterate though!</em>). What you could do is go through each list and <code>yield</code> the thuth-ness of <code>inner[3]</code>:</p> <pre><code>def myfunc(cata): for inner in cata: yield bool(inner[3]) </code></pre> <p><code>yield</code>ing will make the function a generator that can be iterated over and return your results:</p> <pre><code>for i in myfunc(cata): print(i) </code></pre> <p>Prints:</p> <pre><code>True False </code></pre> <p>Of course, this can easily be transformed to a list comprehension that stores the results:</p> <pre><code>r = [bool(x[3]) for x in cata] </code></pre> <p>With <code>r</code> now holding:</p> <pre><code>[True, False] </code></pre>
3
2016-09-26T08:11:46Z
[ "python", "list", "python-3.x", "if-statement", "for-loop" ]
how to iterate in a string in python?
39,697,591
<p>I want to make some montage in <code>ImageMagick</code> which is called by Python via <code>os.system()</code> with 100 jpegs files.</p> <p>Here's the command:</p> <pre><code>cmd='montage '+file[i]+' '+file[i+1]+' '+file[i+2]+' '+file[u+3]+' +file[i+4]+'...+file[i+99] </code></pre> <p>I would like to know how could I avoid to write all <code>file[i+x]</code> entries. Is this possible?</p>
0
2016-09-26T08:03:52Z
39,697,622
<p>To join 100 strings with a space starting at <code>i</code>th index:</p> <pre><code>cmd = "montage " + " ".join(file[i:i+100]) </code></pre> <p>.. where <code>file[i:i+100]</code> will return a sub-sequence starting at i, and ending at (i + 100 - 1)</p>
5
2016-09-26T08:05:15Z
[ "python" ]
AWS lambda_handler error for set_contents_from_string to upload in S3
39,697,604
<p>Recently started working on python scripting for encrypting the data and uploading to S3 using aws lambda_handler function. From local machine to S3 it was executing fine (note: Opens all permissions for anyone from bucket side) when the same script executing from aws Lambda_handler (note: Opens all permissions for anyone from bucket side) getting the below error.</p> <pre><code>{ "stackTrace": [ [ "/var/task/enc.py", 62, "lambda_handler", "up_key = up_bucket.new_key('enc.txt').set_contents_from_string(buf.readline(),replace=True,policy='public-read',encrypt_key=False)" ], [ "/var/task/boto/s3/key.py", 1426, "set_contents_from_string", "encrypt_key=encrypt_key)" ], [ "/var/task/boto/s3/key.py", 1293, "set_contents_from_file", "chunked_transfer=chunked_transfer, size=size)" ], [ "/var/task/boto/s3/key.py", 750, "send_file", "chunked_transfer=chunked_transfer, size=size)" ], [ "/var/task/boto/s3/key.py", 951, "_send_file_internal", "query_args=query_args" ], [ "/var/task/boto/s3/connection.py", 668, "make_request", "retry_handler=retry_handler" ], [ "/var/task/boto/connection.py", 1071, "make_request", "retry_handler=retry_handler)" ], [ "/var/task/boto/connection.py", 940, "_mexe", "request.body, request.headers)" ], [ "/var/task/boto/s3/key.py", 884, "sender", "response.status, response.reason, body)" ] ], "errorType": "S3ResponseError", "errorMessage": "S3ResponseError: 403 Forbidden\n&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;Error&gt;&lt;Code&gt;AccessDenied&lt;/Code&gt;&lt;Message&gt;Access Denied&lt;/Message&gt;&lt;RequestId&gt;4B09C24C4D79C147&lt;/RequestId&gt;&lt;HostId&gt;CzhDhtYDERh9E/e4tVHek35G3CEMh0qFifcnd06fKN/oyLHtj9bWg87zZOajBNQDfqIC2QrldsA=&lt;/HostId&gt;&lt;/Error&gt;" } </code></pre> <p>Here is the script i am executing</p> <pre><code>def lambda_handler(event, context): cipher = AESCipher(key='abcd') print "ready to connect S3" conn = boto.connect_s3() print "connected to download" bucket = conn.get_bucket('s3download') key = bucket.get_key("myinfo.json") s3file = key.get_contents_as_string() lencp = cipher.encrypt(s3file) buf = StringIO.StringIO(lencp) print lencp print "connected to upload" up_bucket = conn.get_bucket("s3upload") up_key = up_bucket.new_key('enc.txt').set_contents_from_string(buf.readline(),replace=True,policy='public-read') print "completed upload" return </code></pre>
1
2016-09-26T08:04:36Z
39,740,975
<p>Solved the problem it was due to policy='public-read' ,after removing this able to perform the upload and also a note if in IAM role if you still enable all S3 functions (i.e PutObject,getObject) upload can't work.Need to create a bucket policy for this particular role then only upload work smoothly.</p>
1
2016-09-28T07:38:08Z
[ "python", "amazon-web-services", "amazon-s3", "boto", "aws-lambda" ]
How do I correctly create a flask sqlalchemy many to many relationship with multiple foreign keys
39,697,616
<p>In the Flask sqlalchemy documentation an example of using a simple many to many relationship is given:</p> <pre><code>tags = db.Table('tags', db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')), db.Column('page_id', db.Integer, db.ForeignKey('page.id')) ) class Page(db.Model): id = db.Column(db.Integer, primary_key=True) tags = db.relationship('Tag', secondary=tags, backref=db.backref('pages', lazy='dynamic')) class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) </code></pre> <p>Where one can use the following syntax to reach out to the related objects:</p> <pre><code>Page.tags </code></pre> <p>What I am trying to accomplish is basically to add the relationship below to the one above: </p> <pre><code>tag_children = db.Table('tag_children,', db.Column('parent_id', db.Integer, db.ForeignKey('tags.tag_id')), db.Column('child_id', db.Integer, db.ForeignKey('tags.tag_id')) ) </code></pre> <p>So that each page has tags attached to it, but each tag can have multiple children in the scope of that page. I've made a show case for a Page called <strong>cars</strong> below where I have it's tags and their respective children tags.</p> <p>(Page) Cars:</p> <ul> <li>Mercedes <ul> <li>A-series</li> <li>B-series</li> <li>C-series</li> </ul></li> <li>Tesla <ul> <li>Tesla Roadster</li> <li>Model X</li> <li>Model S</li> <li>Model 3</li> </ul></li> </ul> <p><em>All the list items above are tag objects</em> </p> <p>I want to be able to use the following syntax bellow to get the related objects:</p> <pre><code>Page.tag.children </code></pre> <p>For instance (obvously dummy code below, but I want to be clear about what the intended purpose of the relationship is):</p> <pre><code>Cars.tesla.children </code></pre>
1
2016-09-26T08:05:07Z
39,706,002
<p>I think, you don't need another table for <code>tag_children</code>. Try to use <a href="http://docs.sqlalchemy.org/en/latest/orm/self_referential.html" rel="nofollow">SQLAlchemy</a> Adjacency Lists:</p> <pre><code>class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('tag.id')) children = relationship("Tag", backref=backref('parent', remote_side=[id]) ) </code></pre> <p>With this schema you may use syntax like:</p> <pre><code>for tag in page.tags: # where page is a Page instance received from db print tag.children </code></pre> <p>It is a common syntax for working with SQLAlchemy models. Try to use it instead of the proposed <code>Cars.tesla.children</code>. </p> <p>Something like <code>Cars['tesla'].children</code> may be implemented via <a href="https://docs.python.org/2/reference/datamodel.html#object.__getitem__" rel="nofollow"><strong>getitem</strong></a> method, but i think, it's very unclear way.</p> <p>Full code snippet:</p> <pre><code>class Page(Base): __tablename__ = 'page' id = Column(Integer, primary_key=True) name = Column(String(256)) tags = relationship('Tag', secondary='tags', backref=backref('pages', lazy='dynamic')) def __str__(self): return self.name class Tag(Base): __tablename__ = 'tag' id = Column(Integer, primary_key=True) name = Column(String(256)) parent_id = Column(Integer, ForeignKey('tag.id')) children = relationship( "Tag", backref=backref('parent', remote_side=[id]) ) def __str__(self): return self.name class Tags(Base): __tablename__ = 'tags' tag_id = Column(Integer, ForeignKey('tag.id'), primary_key=True) page_id = Column(Integer, ForeignKey('page.id'), primary_key=True) </code></pre> <p>And test case:</p> <pre><code># Create page and tags session.add(Page(id=1, name="cars")) session.add(Tag(id=1, name="Mercedes")) session.add(Tag(id=2, name="A-series", parent_id=1)) session.add(Tag(id=3, name="B-series", parent_id=1)) session.add(Tag(id=4, name="C-series", parent_id=1)) session.add(Tag(id=5, name="Tesla")) session.add(Tag(id=6, name="Tesla Roadster", parent_id=5)) session.add(Tag(id=7, name="Model X", parent_id=5)) session.add(Tag(id=8, name="Model S", parent_id=5)) session.add(Tag(id=9, name="Model 3", parent_id=5)) # Fill relation session.add(Tags(tag_id=1, page_id=1)) session.add(Tags(tag_id=5, page_id=1)) session.commit() print session.query(Page).get(1) # &gt;&gt;&gt; cars print session.query(Page).get(1).tags # &gt;&gt;&gt; Mercedes, Tesla print session.query(Page).get(1).tags[1].children # &gt;&gt;&gt; Tesla models </code></pre>
0
2016-09-26T14:52:42Z
[ "python", "sqlalchemy", "relational-database", "flask-sqlalchemy" ]
Python Turtle Wait for Click
39,697,634
<p>I'd like to be able to pause and contemplate each step of this program, and move on to the next step by clicking the screen. Initially I tried adding a bunch of events, but then my brain kicked in and reminded me that this is not a procedural program and the first binding would remain the only one(!). Main program below, any help much appreciated.</p> <pre><code> def tree(self, branchLen): if branchLen &gt; 5: self.screen.onscreenclick(lambda x,y: self.t.forward(branchLen)) self.screen.onscreenclick(lambda x,y: self.t.right(20)) self.tree(branchLen-15) self.screen.onscreenclick(lambda x,y: self.t.left(40)) self.tree(branchLen-15) self.screen.onscreenclick(lambda x,y: self.t.right(20)) self.screen.onscreenclick(lambda x,y: self.t.backward(branchLen)) </code></pre> <hr> <pre><code>import turtle class Tree(object): def __init__(self): self.t = turtle.Turtle() self.screen = turtle.Screen() self.t.left(90) self.t.up() self.t.backward(100) self.t.down() self.t.color("green") self.tree(75) def tree(self, branchLen): if branchLen &gt; 5: self.t.forward(branchLen) self.t.right(20) self.tree(branchLen-15) self.t.left(40) self.tree(branchLen-15) self.t.right(20) self.t.backward(branchLen) tree = Tree() </code></pre>
0
2016-09-26T08:05:48Z
39,713,672
<p>How about OOP to the rescue! We subclass Turtle to make one that queues everything it's asked to do. Then we set an <code>onclick()</code> handler that pops one item off that queue and executes it:</p> <pre><code>import sys import turtle class QueuedTurtle(turtle.RawTurtle): _queue = [] _pen = None _screen = None def __init__(self, shape=turtle._CFG["shape"], undobuffersize=turtle._CFG["undobuffersize"], visible=turtle._CFG["visible"]): if QueuedTurtle._screen is None: QueuedTurtle._screen = turtle.Screen() self._screen.onclick(lambda *args: self.queue_pop()) turtle.RawTurtle.__init__(self, QueuedTurtle._screen, shape=shape, undobuffersize=undobuffersize, visible=visible) def queue_pop(self): if self._queue: function, arguments = self._queue.pop(0) return function(*arguments) print("Empty queue popped!", file=sys.stderr) def backward(self, *args): self._queue.append((super().backward, args)) def forward(self, *args): self._queue.append((super().forward, args)) def right(self, *args): self._queue.append((super().right, args)) def left(self, *args): self._queue.append((super().left, args)) def up(self, *args): self._queue.append((super().up, args)) def down(self, *args): self._queue.append((super().down, args)) def color(self, *args): self._queue.append((super().color, args)) class Tree(object): def __init__(self): self.t = QueuedTurtle() self.t.left(90) self.t.up() self.t.backward(100) self.t.down() self.t.color("green") self.tree(75) def tree(self, branchLen): if branchLen &gt; 5: self.t.forward(branchLen) self.t.right(20) self.tree(branchLen - 15) self.t.left(40) self.tree(branchLen - 15) self.t.right(20) self.t.backward(branchLen) tree = Tree() tree.tree(10) turtle.mainloop() </code></pre> <p>This is a partial implementation with just enough code to make your example program work. Run it, and then start clicking your mouse.</p> <p>We can probably even programmatically generate the wrapper methods for QueuedTurtle.</p>
1
2016-09-26T23:03:26Z
[ "python", "events", "recursion", "turtle-graphics" ]