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
How do I find the first occurrence of a vowel and move it behind the original word (pig latin)?
39,730,254
<p>I need to find the first vowel of a string in python, and I'm a beginner. I'm instructed to move the characters before the first vowel to the end of the word and add '-ay'. For example "big" becomes "ig-bay" and "string" becomes "ing-stray" (piglatin, basically).</p> <p>This is what I have so far:</p> <pre><code>d...
2
2016-09-27T16:50:44Z
39,730,323
<p>Python has the <code>break</code> and <code>continue</code>statements for loop control. You can set a boolean that you trigger such that: </p> <pre><code>if flag: break #do code #set flag </code></pre>
0
2016-09-27T16:54:00Z
[ "python", "findfirst" ]
How do I find the first occurrence of a vowel and move it behind the original word (pig latin)?
39,730,254
<p>I need to find the first vowel of a string in python, and I'm a beginner. I'm instructed to move the characters before the first vowel to the end of the word and add '-ay'. For example "big" becomes "ig-bay" and "string" becomes "ing-stray" (piglatin, basically).</p> <p>This is what I have so far:</p> <pre><code>d...
2
2016-09-27T16:50:44Z
39,730,383
<p>You can use a <code>break</code> statement as soon as you found a vowel. You also do not need to use any <code>split()</code> functions. One big mistake you did was using <code>char</code> to get the <code>SubString</code>. You need to use the index of that char to get the <code>SubString</code> instead.</p> <p>Ta...
0
2016-09-27T16:57:09Z
[ "python", "findfirst" ]
How do I find the first occurrence of a vowel and move it behind the original word (pig latin)?
39,730,254
<p>I need to find the first vowel of a string in python, and I'm a beginner. I'm instructed to move the characters before the first vowel to the end of the word and add '-ay'. For example "big" becomes "ig-bay" and "string" becomes "ing-stray" (piglatin, basically).</p> <p>This is what I have so far:</p> <pre><code>d...
2
2016-09-27T16:50:44Z
39,730,704
<p>Break things down one step at a time.</p> <p>Your first task is to find the first vowel. Let's do that:</p> <pre><code>def first_vowel(s): for index, char in enumerate(s): if char in 'aeiou': return index raise Error('No vowel found') </code></pre> <p>Then you need to use that first vo...
1
2016-09-27T17:16:53Z
[ "python", "findfirst" ]
How do I find the first occurrence of a vowel and move it behind the original word (pig latin)?
39,730,254
<p>I need to find the first vowel of a string in python, and I'm a beginner. I'm instructed to move the characters before the first vowel to the end of the word and add '-ay'. For example "big" becomes "ig-bay" and "string" becomes "ing-stray" (piglatin, basically).</p> <p>This is what I have so far:</p> <pre><code>d...
2
2016-09-27T16:50:44Z
39,730,922
<p>Side note. You can use a regex:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; cases=['big','string'] &gt;&gt;&gt; for case in cases: ... print case+'=&gt;', re.sub(r'^([^aeiou]*)(\w*)', '\\2-\\1ay', case) ... big=&gt; ig-bay string=&gt; ing-stray </code></pre>
0
2016-09-27T17:29:34Z
[ "python", "findfirst" ]
How can I get the actual axis limits when using ax.axis('equal')?
39,730,467
<p>I am using <code>ax.axes('equal')</code> to make the axis spacing equal on X and Y, and also setting <code>xlim</code> and <code>ylim</code>. This over-constrains the problem and the actual limits are not what I set in <code>ax.set_xlim()</code> or <code>ax.set_ylim()</code>. Using <code>ax.get_xlim()</code> just re...
2
2016-09-27T17:02:07Z
39,845,124
<p>The actual limits are not known until the figure is drawn. By adding a canvas draw after setting the <code>xlim</code> and <code>ylim</code>, but before obtaining the <code>xlim</code> and <code>ylim</code>, then one can get the desired limits.</p> <pre><code>f,ax=plt.subplots(1) #open a figure ax.axis('equal') #m...
1
2016-10-04T05:59:20Z
[ "python", "python-2.7", "matplotlib", "plot" ]
How can I get the actual axis limits when using ax.axis('equal')?
39,730,467
<p>I am using <code>ax.axes('equal')</code> to make the axis spacing equal on X and Y, and also setting <code>xlim</code> and <code>ylim</code>. This over-constrains the problem and the actual limits are not what I set in <code>ax.set_xlim()</code> or <code>ax.set_ylim()</code>. Using <code>ax.get_xlim()</code> just re...
2
2016-09-27T17:02:07Z
40,049,860
<p>Not to detract from the accepted answer, which does solve the problem of getting updated axis limits, but is this perhaps an example of the XY problem? If what you want to do is draw a box around the axes, then you don't actually <em>need</em> the <code>xlim</code> and <code>ylim</code> in data coordinates. Inste...
1
2016-10-14T18:29:40Z
[ "python", "python-2.7", "matplotlib", "plot" ]
Convert column's data to enumerated dictionary key-value
39,730,468
<p>Is there a better way (in the sense of minimal code) that can do the followings: convert a column to enumerated numerical values so it should go somewhat this way:</p> <ol> <li>get a <strong>set</strong> of items in a columns </li> <li>make a <strong>enumrated dictionary</strong> with key value</li> <li>revert the ...
2
2016-09-27T17:02:16Z
39,730,516
<p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow">pd.factorize()</a> in this case:</p> <pre><code>In [8]: cars['color_val'] = pd.factorize(cars.color)[0] In [9]: cars Out[9]: car_name color color_val 0 BMW RED 0 1 BMW RED ...
3
2016-09-27T17:05:17Z
[ "python", "pandas", "dictionary", "dataframe", "enumeration" ]
python sorting error: TypeError: 'list' object is not callable
39,730,477
<p>I am trying to sort a list of list based on the first item of each element:</p> <pre><code>def getKey(item): return item[0] def myFun(x): return sorted(x, key= getKey(x)) my_x = [[1,100], [5,200], [3,30]] myFun(my_x) </code></pre> <p>I want the sorting based on the first item of each element, i.e. 1...
-3
2016-09-27T17:02:41Z
39,730,492
<p><strong>UPDATE</strong></p> <p><code>sorted</code>'s <code>key</code> attribute should be callable, so instead of assigning <code>key=getKey()</code> you need to <code>key=getKey</code></p> <p><strong>INITIAL ANSWER</strong>(could be useful if you want to make code look better):</p> <p><del>There is no such metho...
-1
2016-09-27T17:03:43Z
[ "python", "list", "python-2.7", "sorting" ]
python sorting error: TypeError: 'list' object is not callable
39,730,477
<p>I am trying to sort a list of list based on the first item of each element:</p> <pre><code>def getKey(item): return item[0] def myFun(x): return sorted(x, key= getKey(x)) my_x = [[1,100], [5,200], [3,30]] myFun(my_x) </code></pre> <p>I want the sorting based on the first item of each element, i.e. 1...
-3
2016-09-27T17:02:41Z
39,730,625
<p>You don't need to call the function <code>getKey</code>. The signature of <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a> requires you pass the <code>key</code> argument as a callable:</p> <pre><code>sorted(x, key=getKey) </code></pre>
2
2016-09-27T17:11:39Z
[ "python", "list", "python-2.7", "sorting" ]
python sorting error: TypeError: 'list' object is not callable
39,730,477
<p>I am trying to sort a list of list based on the first item of each element:</p> <pre><code>def getKey(item): return item[0] def myFun(x): return sorted(x, key= getKey(x)) my_x = [[1,100], [5,200], [3,30]] myFun(my_x) </code></pre> <p>I want the sorting based on the first item of each element, i.e. 1...
-3
2016-09-27T17:02:41Z
39,730,628
<p>The problem is that you're assigning the result of <code>getKey(x)</code> to <code>key=getKey(x)</code>. You want to assign the function pointer.</p> <pre><code>def getKey(item): return item[0] def myFun(x): return sorted(x, key=getKey) my_x = [[1,100], [5,200], [3,30]] myFun(my_x) </code></pre> <p>...
3
2016-09-27T17:11:54Z
[ "python", "list", "python-2.7", "sorting" ]
python sorting error: TypeError: 'list' object is not callable
39,730,477
<p>I am trying to sort a list of list based on the first item of each element:</p> <pre><code>def getKey(item): return item[0] def myFun(x): return sorted(x, key= getKey(x)) my_x = [[1,100], [5,200], [3,30]] myFun(my_x) </code></pre> <p>I want the sorting based on the first item of each element, i.e. 1...
-3
2016-09-27T17:02:41Z
39,730,750
<p><code>getKey</code> is a function, (a type of "callable" object). Its output, <code>getKey(x)</code>, on the other hand, is a <code>list</code> object which is <em>not</em> callable. Your mistake is that you're setting <code>key=getKey(x)</code> and hence assigning a <code>list</code> object to the argument <code>...
1
2016-09-27T17:20:19Z
[ "python", "list", "python-2.7", "sorting" ]
import python packages from another directory into a Django project
39,730,489
<p>I have a Django project where a user uploads some images and I have some image processing routines which I write and they reside in a completely different folder in my hard drive (on the same machine).</p> <p>Now, I plan to use something like celery to process these images. So, the idea would be that as soon as the...
0
2016-09-27T17:03:18Z
39,730,605
<p>You must append the folder to your python path using <code>sys.path.append()</code> then import using the module name as normal</p> <p><a href="http://www.johnny-lin.com/cdat_tips/tips_pylang/path.html" rel="nofollow">Credit</a></p>
2
2016-09-27T17:09:59Z
[ "python", "django" ]
Create a subclass of list without deep copy
39,730,524
<p>I want to subclass <code>list</code> to add some function to it, for example, <code>my_func</code>. </p> <p>Is there a way to do this without copying the whole list, i.e. make a shallow copy, on the creation of the <code>MyList</code> object and let <code>MyList</code> reference the same list as the one used to con...
4
2016-09-27T17:05:40Z
39,730,690
<p>Pretty sure this isn't possible with a <code>list</code> subclass. It <em>is</em> possible with a <strong><a href="https://docs.python.org/3/library/collections.html#collections.UserList" rel="nofollow"><code>collections.UserList</code></a></strong> subclass (simply <em><a href="https://docs.python.org/2.7/library/u...
4
2016-09-27T17:15:56Z
[ "python", "list", "python-3.x", "oop", "inheritance" ]
TypeError: Signature mismatch. Keys must be dtype <dtype: 'string'>, got <dtype:'int64'>
39,730,528
<p>While running the wide_n_deep_tutorial program from TensorFlow <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py</a> on my dataset, the ...
0
2016-09-27T17:05:54Z
39,747,378
<p>would help to see the output prior to the error message to determine which part of the process this error tripped out at, but, the message says quite clearly that the key is expected to be a string whereas an integer was given instead. I am only guessing, but are the column names set out correctly in the earlier par...
0
2016-09-28T12:21:50Z
[ "python", "pandas", "tensorflow" ]
TypeError: Signature mismatch. Keys must be dtype <dtype: 'string'>, got <dtype:'int64'>
39,730,528
<p>While running the wide_n_deep_tutorial program from TensorFlow <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py</a> on my dataset, the ...
0
2016-09-27T17:05:54Z
39,837,247
<p>Judging by <a href="http://i.stack.imgur.com/aqs3x.png" rel="nofollow">your traceback</a>, the problem you're having is caused by your inputs to feature columns, or the output of your <code>input_fn</code>. Your sparse tensors are most likely being fed non-string dtypes for the <code>values</code> parameter; sparse ...
0
2016-10-03T17:33:03Z
[ "python", "pandas", "tensorflow" ]
Scrapy - Filtered duplicate request
39,730,566
<p>I'm working with scrapy. I want to loop through a db table and grab the starting page for each scrape (random_form_page), then yield a request for each start page. Please note that I am hitting an api to get a proxy with the initial request. I want to set up each request to have its own proxy, so using the callback ...
0
2016-09-27T17:07:54Z
39,731,805
<p>use </p> <blockquote> <p>dont_filter = True in Request object</p> </blockquote> <pre><code>def start_requests(self): for x in xrange(8): random_form_page = session.query(.... PR = Request( 'htp://my-api', headers=self.headers, meta={'newrequest': Request(...
1
2016-09-27T18:24:41Z
[ "python", "scrapy" ]
Trying to Remove for-Loops from Python code, Performing Operations with a Look-up Table On Matrices
39,730,616
<p>I feel like this is a similar problem to the one I asked before, but I can't figure it out. How can I convert these two lines of code into one line with no for-loop?</p> <pre><code>for i in xrange(X.shape[0]): dW[:,y[i]] -= X[i] </code></pre> <p>In English, every row in matrix X should be subtracted from a corre...
0
2016-09-27T17:10:47Z
39,730,962
<p><strong>Approach #1</strong> Here's a one-liner vectorized approach with <code>matrix-multiplication</code> using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow"><code>np.dot</code></a> and <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofoll...
1
2016-09-27T17:31:37Z
[ "python", "numpy", "matrix", "indexing", "vectorization" ]
Trying to Remove for-Loops from Python code, Performing Operations with a Look-up Table On Matrices
39,730,616
<p>I feel like this is a similar problem to the one I asked before, but I can't figure it out. How can I convert these two lines of code into one line with no for-loop?</p> <pre><code>for i in xrange(X.shape[0]): dW[:,y[i]] -= X[i] </code></pre> <p>In English, every row in matrix X should be subtracted from a corre...
0
2016-09-27T17:10:47Z
39,732,328
<p>The straightforward way to vectorize would be:</p> <pre><code>dW[:,y] -= X.T </code></pre> <p>Except, though not very obvious or well-documented, this will give problems with repeated indices in <code>y</code>. For these situations there is the <code>ufunc.at</code> method (elementwise operations in numpy are impl...
1
2016-09-27T18:55:55Z
[ "python", "numpy", "matrix", "indexing", "vectorization" ]
How to change PyCharms doctring autocomplete
39,730,701
<p>I have been programming in PyCharm for a little while now and I like it just fine however there is one little thing that is nagging at me, when I go to generate a new docstring for a function that I have defined PyCharm will autocomplete the docstring using what I believe is sphinx style formatting. Example in pictu...
0
2016-09-27T17:16:42Z
39,730,865
<p>You can adjust this by going to the <a href="https://www.jetbrains.com/help/pycharm/2016.1/python-integrated-tools.html" rel="nofollow">Python Integrated Tools</a> settings.</p> <h3>On Windows/Linux</h3> <pre><code>File -&gt; Settings -&gt; Tools -&gt; Python Integrated Tools </code></pre> <h3>On OS X</h3> <pre...
3
2016-09-27T17:26:51Z
[ "python", "python-3.x", "pycharm", "jetbrains" ]
Panda group dataframe based on datetime type into different period ignoring date part
39,730,737
<p>I want to group the rows into groups, based on variable time interval. However, when doing grouping, I want to ignore the date part, only group based on the time date. </p> <p>Say I want to group every 5 minutes.</p> <pre><code> timestampe val 0 2016-08-11 11:03:00 0.1 1 2016-08-13 11:06:...
2
2016-09-27T17:18:55Z
39,731,398
<p>This is assuming you split the day up into 5 minute windows</p> <pre><code>df.groupby(df.timestampe.dt.hour.mul(60) \ .add(df.timestampe.dt.minute) // 5) \ .apply(pd.DataFrame.reset_index) </code></pre> <p><a href="http://i.stack.imgur.com/7Y76B.png" rel="nofollow"><img src="http://i.stack.imgur.com...
3
2016-09-27T17:59:58Z
[ "python", "datetime", "pandas", "numpy", "scipy" ]
Panda group dataframe based on datetime type into different period ignoring date part
39,730,737
<p>I want to group the rows into groups, based on variable time interval. However, when doing grouping, I want to ignore the date part, only group based on the time date. </p> <p>Say I want to group every 5 minutes.</p> <pre><code> timestampe val 0 2016-08-11 11:03:00 0.1 1 2016-08-13 11:06:...
2
2016-09-27T17:18:55Z
39,731,526
<p>Since you do not care about the <code>date</code> part of your <code>datetime</code> object, I think that make all <code>date</code> equal is a good trick.</p> <pre><code>df['time'] = df['timestamp'].apply(lambda x: x.replace(year=2000, month=1, day=1)) </code></pre> <p>You get:</p> <pre><code> timesta...
0
2016-09-27T18:07:19Z
[ "python", "datetime", "pandas", "numpy", "scipy" ]
ModelSelect2MultipleField not defined
39,730,764
<p>Does anybody know where ModelSelect2MultipleField is imported from? I've been trying to import it into a file that I need, and I thought that I could do it with</p> <pre><code>from django_select2.fields import ModelSelect2MultipleField </code></pre> <p>but I keep getting errors. Before when I had it </p> <pre><co...
0
2016-09-27T17:21:07Z
39,730,849
<p>You need to use <code>from django_select2.forms import ModelSelect2MultipleWidget</code>. I found this by looking at the test application <a href="https://github.com/applegrew/django-select2/blob/master/tests/testapp/forms.py" rel="nofollow">here</a>.</p> <p>There is no ModelSelect2MultipleField there is however a ...
0
2016-09-27T17:25:52Z
[ "python", "django" ]
ModelSelect2MultipleField not defined
39,730,764
<p>Does anybody know where ModelSelect2MultipleField is imported from? I've been trying to import it into a file that I need, and I thought that I could do it with</p> <pre><code>from django_select2.fields import ModelSelect2MultipleField </code></pre> <p>but I keep getting errors. Before when I had it </p> <pre><co...
0
2016-09-27T17:21:07Z
39,731,927
<p>You must initialise the form field as a Django widget and then specify the add-on widget in the parameters like so:</p> <p>clients = ModelMultipleChoiceField(required=False, queryset=Contact.objects, widget=Select2MultipleWidget())</p>
0
2016-09-27T18:31:26Z
[ "python", "django" ]
Paypal Transactions: How to receive and send funds with PayPal API and Django?
39,730,787
<p>i've been wondering to make payment system for my Django website, but with PayPal it seems to be easier for users, i've heard there is special API for python, so it can be used with Django.</p> <hr> <p>So for example, There is user account and my account, i make a receiver function, which listens to the payment ga...
2
2016-09-27T17:22:39Z
39,731,776
<p>Have you considered using django-paypal as one of your installed apps?</p> <p>It looks fit for purpose and may provide what you require. </p> <p>Take a look:</p> <p><a href="https://github.com/spookylukey/django-paypal" rel="nofollow">https://github.com/spookylukey/django-paypal</a> <a href="https://django-paypal...
1
2016-09-27T18:23:07Z
[ "python", "django", "paypal", "django-paypal" ]
Paypal Transactions: How to receive and send funds with PayPal API and Django?
39,730,787
<p>i've been wondering to make payment system for my Django website, but with PayPal it seems to be easier for users, i've heard there is special API for python, so it can be used with Django.</p> <hr> <p>So for example, There is user account and my account, i make a receiver function, which listens to the payment ga...
2
2016-09-27T17:22:39Z
39,731,854
<p>I am not sure about email, but if you want to access paypal ammounts, this might help. <a href="http://stackoverflow.com/questions/34379905/get-amount-from-django-paypal?rq=1">Get amount from django-paypal</a></p>
1
2016-09-27T18:27:15Z
[ "python", "django", "paypal", "django-paypal" ]
Pandas return column value if other column value is equal
39,730,906
<p>so recentyl im trying to get data from CSV file using python and pandas. Code should return or print data from colum 1 if data from column 2 is equal to some string. </p> <pre><code> import pandas as pd df = pd.read_csv('alerts.csv', sep=';', encoding='latin1') print(df[['color']['item']].loc[['color']=='red'])...
0
2016-09-27T17:28:50Z
39,730,997
<p>you are not using .loc correctly</p> <p>.loc need an indexer, and columns such has</p> <pre><code>indexer = df[df['color']=='red'].index print(df.loc[indexer,'item']) </code></pre>
0
2016-09-27T17:33:35Z
[ "python", "csv", "pandas" ]
Trying to return number of items in a list as a column in a dataframe
39,730,951
<p>I have a pandas dataframe, 'df', like the following:</p> <pre><code> name things_in_bag 0 Don [orange, pear, apple] 1 Tommy [banana, pear, apple, watermelon] 2 Larry [cucumber] . . 1084 Jen [pear, baseball] </code></pre> <p>I want to add a column called 'number_things' that totals...
1
2016-09-27T17:31:01Z
39,731,042
<p>you can use apply and look at the len of the list such as</p> <pre><code>df['things_in_bag'].apply(len) </code></pre> <p>if you want to populate a new columns with that data you can then do</p> <pre><code>df['newcol'] = df['things_in_bag'].apply(len) </code></pre>
1
2016-09-27T17:37:02Z
[ "python", "pandas", "dataframe" ]
Grouping values in an array
39,730,970
<p>I have a numpy array of size a*2. (Typical size of a is 100). In the first column are values between x_smallest and x_largest. In the second column are the corresponding y values. Now almost all x values are unique, so I want to group them. Like the first group goes from values x_smallest to x_1. The second group fr...
0
2016-09-27T17:32:05Z
39,732,864
<p>Okay, I think I solved it by myself. Here is the solution in case someone has a similiar problem and find this question:</p> <pre><code>numgroup = 5 # Number of Groups dmimax = numpy.amax(dmivsstasta[:, 0]) # Gets x_largest dmimin = numpy.amin(dmivsstasta[:, 0]) # Gets x_smallest stamax = numpy.amax(dmivsstasta[...
0
2016-09-27T19:30:52Z
[ "python", "arrays", "numpy" ]
What is the frontend language/platform of api.ai and wit.ai?
39,731,005
<p>I am trying to develop a web application like wit.ai or api.ai. I am not sure what would be the best frontend language/platform/technology for such a web applications. In api.ai and wit.ai you create chat robots. For each robot the user define a bunch of keywords as entity. For example</p> <p><code>Entity: Pizza -&...
0
2016-09-27T17:34:14Z
39,793,723
<p>While questions about technology are typically subjective and have no 'right' answer, a 'frontend' esque language will do you a lot of good here.</p> <p>Something like JS, nodejs etc.. You need to be able to highlight the words on the client side and not make any request to the server yet until the user specifies w...
0
2016-09-30T14:20:32Z
[ "python", "django", "frontend", "chatbot" ]
Python If Variable in Variable
39,731,026
<p>I Have Made A File Called <code>helloworld.simon</code>. In There I Have Written:</p> <pre><code>Public class helloworld { main = (main.method()); main { console.print("Hello World"); } </code></pre> <p>And I Have Written This Code:</p> <pre><code>Public = ("Public") Private = ("Private") code = open('he...
-1
2016-09-27T17:35:44Z
39,731,141
<p>Change this line:</p> <p><code>code = open('helloworld.simon' , 'r')</code></p> <p>To this:</p> <pre><code>with open('helloworld.simon' , 'r') as f: lines = f.readlines() if any([line for line in lines if Public in line]): print("Pub") else: print("J") </code></pre>
0
2016-09-27T17:43:41Z
[ "python", "file", "filereader" ]
Python If Variable in Variable
39,731,026
<p>I Have Made A File Called <code>helloworld.simon</code>. In There I Have Written:</p> <pre><code>Public class helloworld { main = (main.method()); main { console.print("Hello World"); } </code></pre> <p>And I Have Written This Code:</p> <pre><code>Public = ("Public") Private = ("Private") code = open('he...
-1
2016-09-27T17:35:44Z
39,731,267
<p>File reading is sequential. Once you read a file (with <code>print(code.read())</code> you cant read back again, unless restart reading with <code>code.seek(0)</code></p> <pre><code>Public = ("Public") Private = ("Private") code = open('helloworld.simon' , 'r') print(code.read()) code.seek(0) if Public in code.read...
1
2016-09-27T17:51:56Z
[ "python", "file", "filereader" ]
Application of Removing Items from Dictionaries
39,731,032
<p>Suppose I have a dictionary that contains instances of kinematic objects. Each kinematic object has a position, velocity, etc. On each timestep update for the program, I want to check to see if two active objects (not the same object, mind you) occupy the same position in the reference frame. If they do, this would ...
0
2016-09-27T17:36:23Z
39,731,085
<p>Simple solution, add the keys you want to remove to a list and then remove them after looping through all elements:</p> <pre><code>dict actives{ 'missile' : object_c(x1, y1, z1), 'target' : object_c(x2, y2, z2), 'clutter' : object_c(x3, y3, z3), ... } to_...
1
2016-09-27T17:40:12Z
[ "python", "dictionary" ]
Application of Removing Items from Dictionaries
39,731,032
<p>Suppose I have a dictionary that contains instances of kinematic objects. Each kinematic object has a position, velocity, etc. On each timestep update for the program, I want to check to see if two active objects (not the same object, mind you) occupy the same position in the reference frame. If they do, this would ...
0
2016-09-27T17:36:23Z
39,731,126
<p>As you're looping, you can double-check that the key is still present:</p> <pre><code>for key1 in self.actives.keys(): if key1 not in self.actives: continue for key2 in self.actives.keys(): if key2 not in self.actives: continue # okay, both keys are still here. go do...
1
2016-09-27T17:42:19Z
[ "python", "dictionary" ]
Application of Removing Items from Dictionaries
39,731,032
<p>Suppose I have a dictionary that contains instances of kinematic objects. Each kinematic object has a position, velocity, etc. On each timestep update for the program, I want to check to see if two active objects (not the same object, mind you) occupy the same position in the reference frame. If they do, this would ...
0
2016-09-27T17:36:23Z
39,732,307
<p>I think Maximilian Peters had the right basic idea, but the items to be removed should be kept in a <code>set</code> rather than a <code>list</code> to avoid issues with an active key being in it multiple times. To further hasten the collision detection process, I changed the comparison loop to use the <a href="http...
1
2016-09-27T18:54:21Z
[ "python", "dictionary" ]
iterate over GroupBy object in dask
39,731,098
<p>Is it possible, to iterate over a dask GroupBy object to get access to the underlying dataframes? I tried:</p> <pre><code>import dask.dataframe as dd import pandas as pd pdf = pd.DataFrame({'A':[1,2,3,4,5], 'B':['1','1','a','a','a']}) ddf = dd.from_pandas(pdf, npartitions = 3) groups = ddf.groupby('B') for name, df...
1
2016-09-27T17:40:48Z
39,732,788
<p>you could iterate through groups doing this with dask, maybe there is a better way but this works for me.</p> <pre><code>import dask.dataframe as dd import pandas as pd pdf = pd.DataFrame({'A':[1, 2, 3, 4, 5], 'B':['1','1','a','a','a']}) ddf = dd.from_pandas(pdf, npartitions = 3) groups = ddf.groupby('B') for grou...
1
2016-09-27T19:26:31Z
[ "python", "pandas", "dask" ]
iterate over GroupBy object in dask
39,731,098
<p>Is it possible, to iterate over a dask GroupBy object to get access to the underlying dataframes? I tried:</p> <pre><code>import dask.dataframe as dd import pandas as pd pdf = pd.DataFrame({'A':[1,2,3,4,5], 'B':['1','1','a','a','a']}) ddf = dd.from_pandas(pdf, npartitions = 3) groups = ddf.groupby('B') for name, df...
1
2016-09-27T17:40:48Z
39,831,940
<p>Generally iterating over Dask.dataframe objects is not recommended. It is inefficient. Instead you might want to try constructing a function and mapping that function over the resulting groups using <code>groupby.apply</code></p>
0
2016-10-03T12:41:55Z
[ "python", "pandas", "dask" ]
Matching entities with Google AppEngine MapReduce
39,731,109
<p>I have the following problem: I am using Google Datastore to store two kinds, <strong>Companies</strong> and <strong>Applicants</strong>, both of them come from different data sources so there is no way to link them directly (no common ID).</p> <p>What I am trying to achieve is to compare the <strong>name</strong>...
0
2016-09-27T17:41:23Z
39,735,436
<p>I can think of minor tips that could optimize what you do such as:</p> <p>Instead of fetching all the results, iterate and bail fast if c.dissolved != True (e.g. starts with is_potential = True, set it to True in iterator or return if c.dissolved != True)</p> <p>However, understanding the data model and what you a...
0
2016-09-27T22:41:35Z
[ "python", "google-app-engine", "mapreduce", "google-cloud-datastore" ]
What does {:4} mean in this matrix printing solution in python?
39,731,205
<p>In the solution to the question proposed here <a href="http://stackoverflow.com/questions/17870612/printing-a-two-dimensional-array-in-python">printing a two dimensional array in python</a> I'm not able to figure out what the {:4} part of the solution means exactly. I've tried this print statement and it seems to wo...
0
2016-09-27T17:48:00Z
39,731,279
<p>It has to do with padding and alignment in output. It is similar to padding in the <code>printf</code> function found in <code>c</code> or <code>awk</code>, etc. It gives each printed element a width of <code>n</code> where <code>n</code> is <code>{:n}</code>.</p> <pre><code>''.join('{:3}'.format(x) for x in range(...
2
2016-09-27T17:52:41Z
[ "python", "arrays", "matrix", "printing", "slice" ]
How to build python matrix (multidimensional array) based on number of rows and colums received from input
39,731,262
<p>Given rectangular array (matrix) MxN with integer elements. M &amp; N are the number of rows and columns of the rectangular matrix, received from input in one line separated by speces. Next, N lines with M numbers each, separated by a space – the elements of the matrix, integers, not exceeding 100 by absolute valu...
0
2016-09-27T17:51:33Z
39,731,523
<p>First of all based on sample output, I saw that rows and cols should be interchanged and second use split by cols [:cols] as shown in the code below</p> <pre><code>rows, cols = [int(i) for i in input().split(" ")] l = [map(int, input().split(" ")[:cols]) for i in range(rows)] </code></pre>
0
2016-09-27T18:06:54Z
[ "python", "arrays", "python-3.x", "matrix", "input" ]
Manipulating pandas series - empty rows in a column
39,731,313
<p>I apologize in advance for what I guess is a basic dataframe / series selection issue, but I am a newbie and a bit stuck.</p> <p>I have the following data:</p> <pre><code>seas off 2000 ARI 0.569369 ATL 0.553398 BAL 0.554404 BUF 0.571429 CAR 0.600000 CHI 0.560886 ...
-1
2016-09-27T17:55:00Z
39,731,502
<p>My guess is that you don't have a DataFrame, but a Series with a MultiIndex.</p> <pre><code>import io import pandas as pd data = io.StringIO('''\ seas off value 2000 ARI 0.569369 2000 ATL 0.553398 2000 BAL 0.554404 2000 BUF 0.571429 2000 CAR 0.600000 2000 CHI 0.560886 2000 CIN 0....
1
2016-09-27T18:05:49Z
[ "python", "pandas", "dataframe", "series" ]
Authentication Error when using Flask to connect to ParseServer
39,731,315
<p>What I am trying to achieve is pretty simple.</p> <p>I want to use Flask to create a web app that connects to a remote Server via API calls (specifically ParseServer). I am using a third-party library to achieve this and everything works perfectly when I am running my code in a stand-alone script. But when I add my...
0
2016-09-27T17:55:03Z
39,751,964
<p>Parse requires keys and env variables. Check this line:</p> <p><code>API_ROOT = os.environ.get('PARSE_API_ROOT') or 'https://api.parse.com/1'</code></p> <p>Your error is in line 102 at:</p> <p><code>https://github.com/milesrichardson/ParsePy/blob/master/parse_rest/connection.py</code></p> <p>Before you can pars...
1
2016-09-28T15:36:15Z
[ "python", "google-app-engine", "parse.com", "flask", "parse-server" ]
Selenium python- how can I fill all input fields at once
39,731,338
<p>Is it possible to fill all the fields on the page at once instead of one by one?</p> <p>Right now I have</p> <pre><code>driver.find_element_by_id('1').send_keys(input1) driver.find_element_by_id('2').send_keys(input2) driver.find_element_by_id('3').send_keys(input3) </code></pre> <p>and it goes one by one taking ...
0
2016-09-27T17:56:56Z
39,731,393
<p>You may construct a <code>dict</code> in python to store the values corresponding to id and Iterate over it to fill up the corresponding data.</p> <pre><code>input_mapping = {"1": "input1", "2": "input2", "3": "input3"} for key, value in input_mapping.items(): driver.find_element_by_id(key).send_keys(value) </...
0
2016-09-27T17:59:36Z
[ "python", "selenium", "webdriver" ]
Can't access blob storage via azure-storage package in Python WebJob
39,731,370
<p>I am trying to read/write from blob storage using a Python WebJob on an Azure App Service. My App Service's requirements.txt file includes the azure-storage package name: the package is successfully installed via pip during App Service deployment. However, when I include the following in my WebJob's run.py file:</p>...
0
2016-09-27T17:58:36Z
39,779,590
<p>Looks like six module is missing. This issue is also tracked via this thread: <a href="https://github.com/Azure/azure-storage-python/issues/22" rel="nofollow">https://github.com/Azure/azure-storage-python/issues/22</a>. You can fix issue by adding the six module to requirements.txt or manually installing six module...
1
2016-09-29T20:39:49Z
[ "python", "azure", "windows-azure-storage", "azure-storage-blobs", "azure-webjobs" ]
dataframe column slices excluding specific columns
39,731,395
<p>How will i slice pandas dataframe with large number of columns, where I do not wish to select specific and non-sequentially positioned columns? One option is to drop the specific columns, but can i do something like:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,100,(2,10)),columns=list('abcdefghij')) df.il...
1
2016-09-27T17:59:46Z
39,731,653
<p>you can do it this way:</p> <pre><code>In [66]: cols2exclude = [1,4,9] In [67]: df.ix[:, df.columns.difference(df.columns[cols2exclude])] Out[67]: a c d f g h i 0 12 37 39 46 22 71 37 1 72 3 17 30 11 26 73 </code></pre> <p>or:</p> <pre><code>In [68]: df.ix[:, ~df.columns.isin(df.co...
1
2016-09-27T18:15:46Z
[ "python", "pandas", "dataframe", "slice" ]
python pandas summarizing nominal variables (counting)
39,731,396
<p>I have following data frame:</p> <pre class="lang-none prettyprint-override"><code>KEY PROD PARAMETER Y/N 1 AAA PARAM1 Y 1 AAA PARAM2 N 1 AAA PARAM3 N 2 AAA PARAM1 N 2 AAA PARAM2 Y 2 AAA PARAM3 Y 3 CCC PARAM1 Y 3 CCC PARAM2 Y 3 CCC PARAM3 Y </c...
2
2016-09-27T17:59:57Z
39,731,740
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> by creating an additional column with the value 1 as it doesn't matter either ways (You are only counting them)</p> <pre><code>df['Y/Ncount'] = 1 df = df.pivot_table(ind...
3
2016-09-27T18:20:50Z
[ "python", "pandas", "dataframe", "summarize" ]
python pandas summarizing nominal variables (counting)
39,731,396
<p>I have following data frame:</p> <pre class="lang-none prettyprint-override"><code>KEY PROD PARAMETER Y/N 1 AAA PARAM1 Y 1 AAA PARAM2 N 1 AAA PARAM3 N 2 AAA PARAM1 N 2 AAA PARAM2 Y 2 AAA PARAM3 Y 3 CCC PARAM1 Y 3 CCC PARAM2 Y 3 CCC PARAM3 Y </c...
2
2016-09-27T17:59:57Z
39,731,750
<p>You want to get the counts of the values in the <code>Y/N</code> column, grouped by <code>PROD</code> and <code>PARAMETER</code>.</p> <pre><code>import io import pandas as pd data = io.StringIO('''\ KEY PROD PARAMETER Y/N 1 AAA PARAM1 Y 1 AAA PARAM2 N 1 AAA PARAM3 N 2 AAA PARAM1 N 2...
2
2016-09-27T18:21:30Z
[ "python", "pandas", "dataframe", "summarize" ]
Python reading data from input file
39,731,431
<p>I want to read specific data from an input file. How can I read it?</p> <p>For example my file has data like:</p> <pre class="lang-none prettyprint-override"><code>this is my first line this is my second line. </code></pre> <p>So I just want to read <code>first</code> from the first line and <code>secon</code> fr...
-6
2016-09-27T18:01:48Z
39,732,061
<p>Try the following code for your needs but please read the comments above.</p> <pre><code># ---------------------------------------- # open text file and write reduced lines # ---------------------------------------- #this is my first line #this is my second line. pathnameIn = "D:/_working" filenameIn = "foobar.txt"...
0
2016-09-27T18:39:35Z
[ "python", "python-3.x" ]
Math operations on multi-dimensional Python dicts
39,731,477
<p>I am porting over some code from PHP that iterates through some database results and builds a two-dimensional array of wins and losses for teams in a baseball league. Here's the code in question in PHP</p> <pre><code> foreach ($results as $result) { $home_team = $result['Game']['home_team_id']; $...
2
2016-09-27T18:04:27Z
39,731,664
<p>I think I would probably use namedtuples here, but it's hard to tell from just this snippet.</p> <p>If you'd like material on how to write more Pythonic code, I recommend checking out Raymond Hettinger's videos, particularly</p> <p>"Best practices for beautiful intelligible code" and "Transforming Code into Beauti...
1
2016-09-27T18:16:05Z
[ "python", "dictionary" ]
Math operations on multi-dimensional Python dicts
39,731,477
<p>I am porting over some code from PHP that iterates through some database results and builds a two-dimensional array of wins and losses for teams in a baseball league. Here's the code in question in PHP</p> <pre><code> foreach ($results as $result) { $home_team = $result['Game']['home_team_id']; $...
2
2016-09-27T18:04:27Z
39,731,744
<p>This question has many interpretations. For example I would simulate results with the following dictionary:</p> <pre><code>&gt;&gt;&gt; result = {'Game':{'home_team':{'score':20,'id':1}, 'away_team':{'score':15,'id':2}}} &gt;&gt;&gt; print result['Game'] {'home_team': {'score': 20, 'id': 1}, 'away_team': {'score': ...
1
2016-09-27T18:21:09Z
[ "python", "dictionary" ]
Math operations on multi-dimensional Python dicts
39,731,477
<p>I am porting over some code from PHP that iterates through some database results and builds a two-dimensional array of wins and losses for teams in a baseball league. Here's the code in question in PHP</p> <pre><code> foreach ($results as $result) { $home_team = $result['Game']['home_team_id']; $...
2
2016-09-27T18:04:27Z
39,733,881
<p><a href="https://en.wikipedia.org/wiki/Autovivification#Python" rel="nofollow">Python's built-in dict class can be subclassed to implement autovivificious dictionaries simply by overriding the <strong>missing</strong>() method </a>, but that's only part of the solution. If you were to simply implement the <code>Tree...
2
2016-09-27T20:38:12Z
[ "python", "dictionary" ]
How to Login to a Page Where Logins are Optional
39,731,667
<p>I'm trying to login to a webpage however, the problem--as far as I cant tell--is that my username and password aren't getting passed by <code>post</code> request. </p> <p>So far I've tried: </p> <pre><code>with requests.Session() as s: p = s.post('http://www.marinetraffic.com/en/users/ajax_user_menu?', headers...
1
2016-09-27T18:16:15Z
39,731,873
<p><strong>try this:</strong></p> <pre><code>payload={ '_method':'POST', 'email':your email, 'password':your passwd, 'is_ajax':True } p = s.post('http://www.marinetraffic.com/en/users/ajax_login', headers=user_agent1, data=payload) </code></pre>
-1
2016-09-27T18:28:21Z
[ "python", "python-requests" ]
How to Login to a Page Where Logins are Optional
39,731,667
<p>I'm trying to login to a webpage however, the problem--as far as I cant tell--is that my username and password aren't getting passed by <code>post</code> request. </p> <p>So far I've tried: </p> <pre><code>with requests.Session() as s: p = s.post('http://www.marinetraffic.com/en/users/ajax_user_menu?', headers...
1
2016-09-27T18:16:15Z
39,732,053
<p>It is actually completely the wrong url you posted, you need to post to <em><a href="https://www.marinetraffic.com/en/users/ajax_login" rel="nofollow">https://www.marinetraffic.com/en/users/ajax_login</a></em> and set the correct headers:</p> <pre><code>data = [("_method", (None, "POST")), ("data[email]", (None, "y...
1
2016-09-27T18:39:18Z
[ "python", "python-requests" ]
Merge Variables in Keras
39,731,669
<p>I'm building a convolutional neural network with Keras and would like to add a single node with the standard deviation of my data before the last fully connected layer.</p> <p>Here's a minimum code to reproduce the error:</p> <pre><code>from keras.layers import merge, Input, Dense from keras.layers import Convolut...
3
2016-09-27T18:16:22Z
39,750,977
<p><code>std</code> is no Keras layer so it does not satisfy the layer input/output shape interface. The solution to this is to use a <a href="https://keras.io/layers/core/#lambda" rel="nofollow"><code>Lambda</code></a> layer wrapping <code>K.std</code>:</p> <pre><code>from keras.layers import merge, Input, Dense, Lam...
1
2016-09-28T14:51:45Z
[ "python", "tensorflow", "keras" ]
Id isn't returning anything in the Google App Engine datastore
39,731,674
<p>I tried select * from post which returns all posts. How can I do a select just for one post using the post_id? I've tried </p> <pre><code>Select * from post where id='5629499534213120' select * from post where post_id='5629499534213120' select * from post where NAME/ID='5629499534213120' </code></pre> <p>and it ...
1
2016-09-27T18:16:36Z
39,731,861
<p>Generally speaking, you probably want to be doing a query with a key literal:</p> <pre><code>SELECT * FROM Post WHERE __key__ = KEY('Post', 5629499534213120) </code></pre> <p>An additional thing to note -- Keys can have either string or integer ids. By default, the IDs are integers so I used an integer in the que...
3
2016-09-27T18:27:35Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
Id isn't returning anything in the Google App Engine datastore
39,731,674
<p>I tried select * from post which returns all posts. How can I do a select just for one post using the post_id? I've tried </p> <pre><code>Select * from post where id='5629499534213120' select * from post where post_id='5629499534213120' select * from post where NAME/ID='5629499534213120' </code></pre> <p>and it ...
1
2016-09-27T18:16:36Z
39,732,516
<p>Thanks I was able to get it working using</p> <pre><code>SELECT * FROM Post WHERE __key__ = Key(blogs, 'default', Post, 5629499534213120) </code></pre>
0
2016-09-27T19:08:21Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
Replicating elements in numpy array
39,731,771
<p>I have a numpy array say</p> <pre><code>a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) </code></pre> <p>I have an array 'replication' of the same size where replication[i,j](>=0) denotes how many times a[i][j] should be repeated along the row. Obiviously, replication array follows the invariant...
1
2016-09-27T18:22:55Z
39,732,014
<p>You can flatten out your <code>replication</code> array, then use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.repeat.html" rel="nofollow"><code>.repeat()</code></a> method of <code>a</code>:</p> <pre><code>import numpy as np a = array([[1, 2, 3], [4, 5, 6], ...
3
2016-09-27T18:36:30Z
[ "python", "arrays", "numpy", "replicate" ]
Scrapy - iterate over object
39,731,804
<p>this is how I'm running <code>scrapy</code> from a <code>Python</code> script:</p> <pre><code>def iterate(): process = CrawlerProcess(get_project_settings()) tracks = process.crawl('pitchfork_tracks', domain='pitchfork.com') process.start() </code></pre> <p>however, I can't seem to <code>iterate</c...
0
2016-09-27T18:24:34Z
39,732,758
<p>You should follow the work flow of Scrapy Framework. Spider handles how requests are built and responses are parsed. ItemPipeline handles how items are operated.</p> <p>From your code:</p> <pre><code>tracks = process.crawl('pitchfork_tracks', domain='pitchfork.com') </code></pre> <p><code>pitchfork_tracks</code> ...
0
2016-09-27T19:24:45Z
[ "python", "scrapy", "iteration" ]
Python import error: 'Cannot import name'
39,731,807
<p>Im having trouble importing a class on a python module.</p> <p>Here are my directory structure:</p> <pre><code>_wikiSpider +scrapy.cfg _wikiSpider +__init__.py +items.py +items.pyc +settings.py +settings.pyc +pipelines.py _spiders +__init__.py +__init__.pyc +articleSp...
0
2016-09-27T18:24:50Z
39,731,967
<p>You have an items.py in both your root and _spiders folder. To reference a file in a subfolder you need the folder name and the file.</p> <p>from _spiders.items import Article </p> <p>assuming the file that imports this code is in your root directory. Python uses a you are here, to current file location, for it'...
1
2016-09-27T18:33:43Z
[ "python", "import", "scrapy" ]
Q: OpenPyxl checking for existing row and then updating cell
39,731,903
<p>I want to check for a name column in an existing spreadsheet and if it exists I want to update a specific column with a time stamp for that row. I'm in a rut because I can't figure out how to go about this with out a for loop. The for loop will append more rows for the ones it didnt match and nothing shows up in col...
0
2016-09-27T18:30:02Z
39,798,105
<p>Figured it out</p> <pre><code> name_text = raw_input("Please enter name: ") matching_row_nbr = None for rowNum in range(2, ws1.max_row + 1 ): log_name = ws1.cell(row=rowNum,column=1).value if log_name == name_text: # Checks for a matching row and remembers the row number ...
0
2016-09-30T18:42:12Z
[ "python", "openpyxl" ]
python's `timeit` doesn't always scale linearly with number?
39,732,027
<p>I'm running Python 2.7.10 on a 16GB, 2.7GHz i5, OSX 10.11.5 machine. </p> <p>I've observed this phenomenon many times in many different types of examples, so the example below, though a bit contrived, is representative. It's just what I happened to be working on earlier today when my curiosity finally piqued. </p>...
9
2016-09-27T18:37:25Z
39,732,127
<p>This has to do with a smaller number of runs not being accurate enough to get the timing resolution you want.</p> <p>As you increase the number of runs, the ratio between the times approaches the ratio between the number of runs:</p> <pre><code>&gt;&gt;&gt; def timeit_ratio(a, b): ... return timeit('unicodedat...
8
2016-09-27T18:43:06Z
[ "python", "performance", "optimization", "timeit" ]
Will file be closed after "open(file_name, 'w+').write(somestr)"
39,732,042
<p>I'm new to python.</p> <p>I wonder if I write:</p> <pre><code>open('/tmp/xxx.txt', 'w+').write('aabb') </code></pre> <p>Will the file be still opened or closed?</p> <p>In another word, what's the difference between the above and</p> <pre><code>with open('/tmp/xxx.txt', 'w+') as f: f.write('aabb') </code></pre...
1
2016-09-27T18:38:40Z
39,732,059
<p>The file might stay open.</p> <p>Keep in mind that it <strong>will</strong> be automatically closed upon garbage collection or software termination but it's a bad practice to count on it as exceptions, frames or even delayed GC might keep it open.</p> <p>Also, you might lose data if the program terminated unexpect...
1
2016-09-27T18:39:31Z
[ "python" ]
Calculating average and outputting number of cases which were more than and less than average from a list
39,732,096
<p>Task: Write an algorithm to allow a user to input the maximum and minimum daily temperatures for a number of days until a maximum temperature of 999 is entered.</p> <p>The program then calculates the average temperature and outputs the number of days that the temperature was above average. It also outputs the numbe...
-2
2016-09-27T18:41:32Z
39,732,166
<p><code>input</code> returns a string. To make it an integer do <code>int( input('Enter temperature: '))</code></p>
0
2016-09-27T18:45:52Z
[ "python" ]
Calculating average and outputting number of cases which were more than and less than average from a list
39,732,096
<p>Task: Write an algorithm to allow a user to input the maximum and minimum daily temperatures for a number of days until a maximum temperature of 999 is entered.</p> <p>The program then calculates the average temperature and outputs the number of days that the temperature was above average. It also outputs the numbe...
-2
2016-09-27T18:41:32Z
39,732,286
<p>Reading through the code in the image that you posted and assuming that your algorithm is correct, the following code does what you want (Python 2.7):</p> <pre><code>import numpy as np temperatures = [] total = 0 maxtemp = 999 while total &lt; maxtemp: data = input("What is your temperature: ") temperature...
0
2016-09-27T18:52:50Z
[ "python" ]
Subclassing numpy.ndarray - why is __array_finalize__ not being called twice here?
39,732,213
<p>According to <a href="http://docs.scipy.org/doc/numpy/user/basics.subclassing.html" rel="nofollow">this</a> primer on subclassing <code>ndarray</code>, the <code>__array_finalize__</code> method is guaranteed to be called, no matter if the subclass is instantiated directly, casted as a view or created from a templat...
3
2016-09-27T18:48:35Z
39,733,070
<p>In the documentation you link to, it describes how <code>ndarray.__new__</code> will call <code>__array_finalize__</code> on the arrays it constructs. And your class's <code>__new__</code> method is causing that to happen when you create your instance as a <code>view</code> of an existing array. The <code>view</code...
1
2016-09-27T19:44:27Z
[ "python", "numpy", "inheritance" ]
Python 3: Traceback : TypeError
39,732,281
<p>I'm new in python 3 and I don't understand why I get a Type Error (this is a guess a number game for numbers between 0-100):</p> <pre><code>print("Please think of a number between 0 and 100!") low = 0 high = 100 check = False while True : guess = (low + high)/2 print("Enter 'h' to indicate the guess is too...
-1
2016-09-27T18:52:34Z
39,732,418
<p>On the line <code>low = ans</code> you set low to be a string value, the string value "h"</p> <p>Then on the second time you pass through the loop, you try to calculate <code>(low + high</code>)/2` You can't calculate ("h" + 100)/2 because you cant add the string to the integer. This is a "type error"</p> <p>For...
0
2016-09-27T19:01:46Z
[ "python", "typeerror", "traceback" ]
Python 3: Traceback : TypeError
39,732,281
<p>I'm new in python 3 and I don't understand why I get a Type Error (this is a guess a number game for numbers between 0-100):</p> <pre><code>print("Please think of a number between 0 and 100!") low = 0 high = 100 check = False while True : guess = (low + high)/2 print("Enter 'h' to indicate the guess is too...
-1
2016-09-27T18:52:34Z
39,732,459
<p>A couple of things. </p> <ol> <li>You should probably print the guess so that the user knows whether it is too high or too low</li> <li><code>low==ans</code> doesn't make any sense. <code>ans</code> will either be "h", "l", or "c", assuming the user follows the rules. <code>low</code> and <code>high</code> need to ...
0
2016-09-27T19:04:04Z
[ "python", "typeerror", "traceback" ]
Pandas: how to plot a line in a scatter and bring it to the back/front?
39,732,288
<p>I have checked to the best of my capabilities but haven't found any <code>kwds</code> that allow you to draw a line (such as <code>y=a-x</code>) on a <code>pandas</code> scatter plot (not necessarily the line of best fit) and bring it to the back (or to the front).</p> <pre><code>#the data frame ax=df.plot(kind='sc...
0
2016-09-27T18:53:06Z
39,742,812
<p>You need to define an axis, and then pass the pandas plot to that axis. You then plot whatever line to that previously defined axis. Here is a solution.</p> <pre><code>x = np.random.randn(100) y = np.random.randn(100) line = 0.5*np.linspace(-4, 4, 100) x_line = np.linspace(-4, 4, 100) fig, ax = plt.subplots(figsiz...
1
2016-09-28T09:08:03Z
[ "python", "pandas", "matplotlib" ]
python remove last comma
39,732,409
<p>I have some thing like this in output.txt file</p> <pre><code>Service1:Aborted Service2:failed Service3:failed Service4:Aborted Service5:failed </code></pre> <p>output in 2nd file(output2.txt) :</p> <pre><code> Service1 Service2 Servive3 Service4 Service5 Aborted failed failed Abor...
1
2016-09-27T19:01:01Z
39,732,619
<p>I found a simple way to do it, you can of course minimize the steps, but the idea is the same, take a string, reverse it. Then use string replace with a limit of one replacement to replace all commas, this will replace the first comma it encounters in the reversed string. Then, reverse the string with the comma remo...
-1
2016-09-27T19:15:47Z
[ "python", "python-2.7", "python-3.x" ]
python remove last comma
39,732,409
<p>I have some thing like this in output.txt file</p> <pre><code>Service1:Aborted Service2:failed Service3:failed Service4:Aborted Service5:failed </code></pre> <p>output in 2nd file(output2.txt) :</p> <pre><code> Service1 Service2 Servive3 Service4 Service5 Aborted failed failed Abor...
1
2016-09-27T19:01:01Z
39,732,926
<p>Use a list and append the items to it. Accessing parts[-1] returns the last item from the splitted parts. Then use <code>join()</code> to put the commas in between all collected states:</p> <pre><code>states = [] for line in file.readlines(): parts=line.strip().split(':') states.append(parts[-1]) print(','....
0
2016-09-27T19:34:25Z
[ "python", "python-2.7", "python-3.x" ]
python remove last comma
39,732,409
<p>I have some thing like this in output.txt file</p> <pre><code>Service1:Aborted Service2:failed Service3:failed Service4:Aborted Service5:failed </code></pre> <p>output in 2nd file(output2.txt) :</p> <pre><code> Service1 Service2 Servive3 Service4 Service5 Aborted failed failed Abor...
1
2016-09-27T19:01:01Z
39,733,876
<p>This makes the output you originally requested:</p> <pre><code>file=open('output.txt','r') target=open('output2.txt','w') states = [line.strip().split(':')[-1] for line in file.readlines()] target.write(','.join(states)) target.close() </code></pre> <p>That is, the output of this code is:</p> <pre><code>Aborted,f...
0
2016-09-27T20:37:51Z
[ "python", "python-2.7", "python-3.x" ]
Why does Pandas skip first set of chunks when iterating over csv in my code
39,732,421
<p>I have a very large CSV file that I read via iteration with pandas' chunks function. The problem: If e.g. chunksize=2, it skips the first 2 rows and the first chunks I receive are row 3-4.</p> <p>Basically, if I read the CSV with nrows=4, I get the first 4 rows while chunking the same file with chunksize=2 gets me ...
1
2016-09-27T19:02:03Z
39,733,348
<p>Don't call <code>get_chunk</code>. You already have your chunk since you're iterating over the reader, i.e. <code>chunk</code> is your DataFrame. Call <code>print(chunk)</code> in your loop, and you should see the expected output.</p> <p>As @MaxU points out in the comments, you want to use <code>get_chunk</code> ...
1
2016-09-27T20:02:23Z
[ "python", "csv", "pandas", "chunks" ]
Python redmine api: journals.filter usage
39,732,493
<p>For example I have an issue:</p> <pre><code>issue = redmine.issue.get(100) </code></pre> <p>It is possible to get the notes of particular user for this issue?</p> <p>I found journals.filter method:</p> <pre><code>issue.journals.filter() </code></pre> <p>But I don't know syntax for filter() method.</p> <p>Can s...
0
2016-09-27T19:06:20Z
39,741,119
<p>Redmine API doesn't allow you to do that via direct API calls, so you have to first include journals (otherwise you'll make 2 API calls instead of one) and then iterate over them and check if that record belongs to the needed user, e.g.:</p> <pre><code>issue = redmine.issue.get(ISSUE_ID, include='journals') for re...
0
2016-09-28T07:46:02Z
[ "python", "python-redmine" ]
Pillow handles PNG files incorrectly
39,732,548
<p>I can successfully convert a rectangular image into a png with transparent rounded corners like this: </p> <p><a href="http://i.stack.imgur.com/phKNv.png" rel="nofollow"><img src="http://i.stack.imgur.com/phKNv.png" alt=".png image with transparent corners"></a></p> <p>However, when I take this transparent cornere...
1
2016-09-27T19:10:44Z
39,819,047
<p>If you paste an image with transparent pixels onto another image, the transparent pixels are just copied as well. It looks like you only want to paste the non-transparent pixels. In that case, you need a mask for the <code>paste</code> function.</p> <pre><code>image_bg.paste(image_fg, (20, 20), mask=image_fg) </cod...
0
2016-10-02T16:20:33Z
[ "python", "pillow" ]
HTTP post Json 400 Error
39,732,571
<p>I am trying to post data to my server from my microcontroller. I need to send raw http data from my controller and this is what I am sending below:</p> <pre><code>POST /postpage HTTP/1.1 Host: https://example.com Accept: */* Content-Length: 18 Content-Type: application/json {"cage":"abcdefg"} </code></pre> <p>My ...
0
2016-09-27T19:12:26Z
39,732,678
<p>HTTP specifies the separator between headers as a single newline, and requires a double newline before the content:</p> <pre><code>POST /postpage HTTP/1.1 Host: https://example.com Accept: */* Content-Length: 18 Content-Type: application/json {"cage":"abcdefg"} </code></pre> <hr> <p>If you don’t think you’ve...
0
2016-09-27T19:20:01Z
[ "python", "json", "http-post" ]
Why is my stack buffer overflow exploit not working?
39,732,600
<p>So I have a really simple stackoverflow:</p> <pre><code>#include &lt;stdio.h&gt; int main(int argc, char *argv[]) { char buf[256]; memcpy(buf, argv[1],strlen(argv[1])); printf(buf); } </code></pre> <p>I'm trying to overflow with this code:</p> <pre><code>$(python -c "print '\x31\xc0\x50\x68\x2f\x2f...
5
2016-09-27T19:14:19Z
39,737,987
<p>This isn't going to work too well [as written]. However, it <em>is</em> possible, so read on ...</p> <hr> <p>It helps to know what the actual stack layout is when the <code>main</code> function is called. It's a bit more complicated than most people realize.</p> <p>Assuming a POSIX OS (e.g. linux), the kernel wil...
0
2016-09-28T04:20:11Z
[ "python", "c", "stack-overflow", "buffer-overflow" ]
Why is my stack buffer overflow exploit not working?
39,732,600
<p>So I have a really simple stackoverflow:</p> <pre><code>#include &lt;stdio.h&gt; int main(int argc, char *argv[]) { char buf[256]; memcpy(buf, argv[1],strlen(argv[1])); printf(buf); } </code></pre> <p>I'm trying to overflow with this code:</p> <pre><code>$(python -c "print '\x31\xc0\x50\x68\x2f\x2f...
5
2016-09-27T19:14:19Z
39,738,856
<p>There are several protections, for the attack straight from the compiler. For example your stack may not be executable.</p> <p><code>readelf -l &lt;filename&gt;</code> </p> <p>if your output contains something like this:</p> <p><code>GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4</code></p...
2
2016-09-28T05:41:21Z
[ "python", "c", "stack-overflow", "buffer-overflow" ]
Why is my stack buffer overflow exploit not working?
39,732,600
<p>So I have a really simple stackoverflow:</p> <pre><code>#include &lt;stdio.h&gt; int main(int argc, char *argv[]) { char buf[256]; memcpy(buf, argv[1],strlen(argv[1])); printf(buf); } </code></pre> <p>I'm trying to overflow with this code:</p> <pre><code>$(python -c "print '\x31\xc0\x50\x68\x2f\x2f...
5
2016-09-27T19:14:19Z
39,783,069
<p>I was having similar problems when trying to perform a stack buffer overflow. I found that my return address in GDB was different than that in a normal process. What I did was add the following:</p> <pre><code>unsigned long printesp(void){ __asm__("movl %esp,%eax"); } </code></pre> <p>And called it at the end ...
0
2016-09-30T03:12:14Z
[ "python", "c", "stack-overflow", "buffer-overflow" ]
Can't a list have symbols in it?
39,732,608
<p>I have not done python before (only javascript). I am finding the docs alien and the other stackoverflow posts on <code>list.pop()</code> even more cryptic!</p> <p>my args are <code>'0','0','0','0','0000'</code></p> <p>here's my code:</p> <pre><code>i=['.','.','.',':',''] host='' for v in sys.argv[1:]: host=...
3
2016-09-27T19:14:46Z
39,732,652
<p>You <em>can</em> put pretty much whatever you want in a list. It's likely that your <code>sys.argv</code> is too long (even after slicing off the first element).</p> <p>e.g. if <code>len(sys.argv[1:]) == 6</code> and <code>len(i) == 5</code> than by the time you get to the last element in the <code>for</code> loop...
4
2016-09-27T19:18:28Z
[ "python" ]
Can't a list have symbols in it?
39,732,608
<p>I have not done python before (only javascript). I am finding the docs alien and the other stackoverflow posts on <code>list.pop()</code> even more cryptic!</p> <p>my args are <code>'0','0','0','0','0000'</code></p> <p>here's my code:</p> <pre><code>i=['.','.','.',':',''] host='' for v in sys.argv[1:]: host=...
3
2016-09-27T19:14:46Z
39,732,686
<pre><code>a=['script','location','00','11','22','33','4444'] i=['.','.','.',':','',''] # added an extra '' host='' for v in a[1:]: host=host+str(v)+i.pop(0) print (host) </code></pre> <p>Something like this? Changed pop(0) cause you want the start not the end. Your issue was you were trying to pop more than th...
2
2016-09-27T19:20:17Z
[ "python" ]
Can't a list have symbols in it?
39,732,608
<p>I have not done python before (only javascript). I am finding the docs alien and the other stackoverflow posts on <code>list.pop()</code> even more cryptic!</p> <p>my args are <code>'0','0','0','0','0000'</code></p> <p>here's my code:</p> <pre><code>i=['.','.','.',':',''] host='' for v in sys.argv[1:]: host=...
3
2016-09-27T19:14:46Z
39,733,220
<p>It seems what you want is simple: join everything using the dot, but the last part, the port number must be joined by colon. Here is another way to do it:</p> <pre><code>port = sys.argv.pop() host = '{}:{}'.format('.'.join(sys.argv[1:]), port) </code></pre>
0
2016-09-27T19:54:00Z
[ "python" ]
Atom editor - linter-flake8: how to specify global "builtins" to ignore
39,732,615
<p>I've installed the <a href="https://atom.io/packages/linter-flake8" rel="nofollow">linter-flake8</a> Atom package, and keep getting the following warnings:</p> <pre><code>F821 — undefined name 'self' at line __ col _ </code></pre> <p>Following <a href="http://stackoverflow.com/questions/37840142/how-to-avoid-fla...
1
2016-09-27T19:15:29Z
39,732,679
<p>there is a special file which you require in your home directory (or per project basis) called a flake8 file.</p> <p>For a global version, if not already existing create a file located at ~/.config/flake8</p> <p>Within this directory add all your customizations, my flake8 file looks like this for example:</p> <pr...
0
2016-09-27T19:20:07Z
[ "python", "atom-editor", "flake8" ]
Pandas - how to filter rows base on regular expresion
39,732,661
<p>Can you please let me know how to filter rows using Pandas base on character range like [0-9] or [A-Z].</p> <p>case like this where all the column types are objects</p> <pre><code>A B 2.3 234 4.5 4b6 7b 275 </code></pre> <p>I would like to check if all the values in the column A are floats m...
1
2016-09-27T19:18:56Z
39,732,839
<p>try this:</p> <pre><code>In [8]: df Out[8]: A B 0 2.3 234 1 4.5 4b6 2 7b 275 3 11 11 In [9]: df.A.str.match(r'^\d*\.*\d*$') Out[9]: 0 True 1 True 2 False 3 True Name: A, dtype: bool In [10]: df.ix[df.A.str.match(r'^\d*\.*\d*$')] Out[10]: A B 0 2.3 234 1 4.5 4b6 3 11...
0
2016-09-27T19:29:13Z
[ "python", "pandas", "dataframe" ]
Python scipy.interpolate.interp1d not working with large float values
39,732,724
<p>I am trying to use <code>scipy.interpolate.interp1d</code>to plot longitude and latitude values to x-coordinate and y-coordinate pixels of a map image. I have sample values:</p> <pre><code>y = [0, 256, 512, 768, 1024, 1280, 1536] lat = [615436414755, 615226949459, 615017342897, 614807595000, 614597705702, 61438767...
0
2016-09-27T19:22:16Z
39,734,259
<p>From <code>interp1d</code> <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow">docs</a>:</p> <blockquote> <p>bounds_error : bool, optional If True, a ValueError is raised any time interpolation is attempted on a value outside of the range of x (whe...
1
2016-09-27T21:02:26Z
[ "python", "scipy", "interpolation" ]
Pythonl lxml adding linebreak between specific nodes when creating xml file
39,732,757
<p>I am writing an XML file using lxml. I am able to write the entire XML file to one line:</p> <pre><code>&lt;FIXML&gt;&lt;Batch Total="3"&gt;&lt;Hdr SendTime="2016-09-27T13:32:19-05:00"/&gt;&lt;RepeatingNode Price="0.99" RptID="1"&gt;&lt;Date Dt="2016-09-20"/&gt;&lt;/RepeatingNode&gt;&lt;RepeatingNode Price="2.49" R...
0
2016-09-27T19:24:42Z
39,734,229
<p>My solution is to ignore the pretty_print param and add a text or tail with a linebreak where applicable. New code below:</p> <pre><code>import lxml.etree as et fixml_node = et.Element("FIXML") fixml_node.text = "\n" batch_node = et.SubElement(fixml_node, "Batch") batch_node.text = "\n" batch_node.tail = "\n" he...
0
2016-09-27T21:00:51Z
[ "python", "xml", "lxml" ]
No confirmation link in flask security
39,732,768
<p>I am using flask_security to do registration in a flask app. When registering an email address an confirmation mail is sent, but it does not include a confirmation link.</p> <p>I did not find an option to activate this and there is not much documentation about it.</p> <p>The current configuration is</p> <pre><cod...
0
2016-09-27T19:25:20Z
39,733,031
<p>You've not set all the settings that should. From the <a href="https://pythonhosted.org/Flask-Security/configuration.html#feature-flags" rel="nofollow">docs</a></p> <blockquote> <p><code>SECURITY_CONFIRMABLE</code></p> <p>Specifies if users are required to confirm their email address when registering a new a...
1
2016-09-27T19:41:43Z
[ "python", "flask", "flask-security" ]
Selenium Python : Unable to get element by id/name/css selector
39,732,777
<p>For a school project, I'm trying to create a Python Script which is able to fill in different forms, from different websites.</p> <p>Here is the thing, for some kinds of website, I'm not able to catch the form elements which Selenium. E.g. in this website : <a href="http://www.top-office.com/jeu" rel="nofollow">htt...
1
2016-09-27T19:26:11Z
39,732,968
<p>The element that you are trying to interact with is inside of an iframe. You need to use the <code>driver.switch_to_frame()</code> method in order to switch the driver to focus on that iframe. Only when it has switched into that iframe can it interact with its elements. </p> <p>See <a href="http://stackoverflow.com...
1
2016-09-27T19:37:19Z
[ "javascript", "jquery", "python", "selenium" ]
Python Bokeh table columns and headers don't line up
39,732,842
<p>I am trying to display a table in a jupyter notebook using python and the visualization library <a href="http://bokeh.pydata.org/en/0.10.0/index.html">Bokeh</a>. I use the following code to display my table in an jupyter notebook where <strong>result</strong> is a dataframe:</p> <pre><code>source = ColumnDataSource...
7
2016-09-27T19:29:22Z
39,897,690
<p>The css styling of Bokeh widgets for Jupyter notebooks is in <a href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.css" rel="nofollow">http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.css</a>, where <code>height:16px</code> for elements <code>.bk-root .bk-slick-header-column.bk-ui-state-d...
2
2016-10-06T13:43:39Z
[ "python", "ipython", "jupyter", "bokeh" ]
Numpy array manipulation within range of columns and rows
39,732,957
<p>I have a numpy boolean 2D array that represents a grayscale image which is essentially an unfilled shape (triangle, square, circle) consisting of <code>True</code> for white pixels, and <code>False</code> for black pixels. I would like to add a black fill by modifying the white pixels to black pixels.</p> <pre><cod...
2
2016-09-27T19:36:24Z
39,733,198
<p>Based on your logic, you can replace all values between the first False and the last False with False:</p> <pre><code>def mutate(A): ind = np.where(~A)[0] if len(ind) != 0: A[ind.min():ind.max()] = False return A np.apply_along_axis(mutate, 1, arr) # array([[ True, True, True, False, False,...
0
2016-09-27T19:52:00Z
[ "python", "arrays", "performance", "numpy" ]
Numpy array manipulation within range of columns and rows
39,732,957
<p>I have a numpy boolean 2D array that represents a grayscale image which is essentially an unfilled shape (triangle, square, circle) consisting of <code>True</code> for white pixels, and <code>False</code> for black pixels. I would like to add a black fill by modifying the white pixels to black pixels.</p> <pre><cod...
2
2016-09-27T19:36:24Z
39,733,436
<p>Here one idea that's easy to implement and should perform reasonably quickly.</p> <p>I'll use 0s and 1s so it's a little clearer to look at.</p> <p>Here's the starting array:</p> <pre><code>&gt;&gt;&gt; a array([[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 1, 1,...
1
2016-09-27T20:08:52Z
[ "python", "arrays", "performance", "numpy" ]
Celery Beat - Worker Consuming Messages, But Never Acks. Them
39,732,967
<p>I've got a simple Django site that I'd like to add some scheduled tasks to via Celery / RabbitMQ. I'm stuck, because, while the beat scheduler pumps out tasks with no issues, the worker fails to consume them. The worker never marks them as acknowledged in RabbitMQ.</p> <p>Here's my Celery configuration from <code>e...
0
2016-09-27T19:37:09Z
39,734,068
<p>I've found the solution! It's the <code>--autoreload</code> flag. Don't use it.</p> <p>Lesson #2: Run celery by hand, not via invoke as I was doing. This just makes your life harder by doing bad things to the log output.</p> <p>It seems the <code>--autoreload</code> flag causes the worker to break for some reason....
0
2016-09-27T20:49:38Z
[ "python", "django", "celery" ]
Python parse string into Python dictionary of list
39,732,970
<p>There are two parts to this question:</p> <p><strong>I. I'd like to parse Python string into a list of dictionary.</strong> </p> <p>****Here is the Python String****</p> <pre><code>../Data.py:92 final computing result as shown below: [historic_list {id: 'A(long) 11A' startdate: 42521 numvaluelist: 0.106559956676...
0
2016-09-27T19:37:24Z
39,735,003
<p>Your input raw text looks pretty predictable, try this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; raw = "[historic_list {id: 'A(long) 11A' startdate: 42521 numvaluelist: 0.1065599566767107 datelist: 42521}historic_list {id: 'A(short) 11B' startdate: 42521 numvaluelist: 0.0038113334533441123 datelist: 4252...
1
2016-09-27T21:59:57Z
[ "python", "list", "loops", "dictionary" ]
python - nested class access modifier
39,732,985
<p>I'm trying to make an instance of a <code>__Profile</code> class in the constructor of the <code>__Team</code> class, but I can't get access to <code>__Profile</code>. How should I do it?</p> <p>This is my code</p> <pre><code>class SlackApi: # my work class __Team: class __Profile: def ...
0
2016-09-27T19:38:24Z
39,733,109
<p>You MAY access like so:</p> <pre><code>SlackApi._SlackApi__Team._Team__Profile </code></pre> <p>or like so:</p> <pre><code>self._Team__Profile </code></pre> <p>But that's just wrong. For your own convenience, don't make them a private class.</p>
0
2016-09-27T19:47:14Z
[ "python", "nested", "private", "python-3.5" ]
python - nested class access modifier
39,732,985
<p>I'm trying to make an instance of a <code>__Profile</code> class in the constructor of the <code>__Team</code> class, but I can't get access to <code>__Profile</code>. How should I do it?</p> <p>This is my code</p> <pre><code>class SlackApi: # my work class __Team: class __Profile: def ...
0
2016-09-27T19:38:24Z
39,733,134
<p>Python does not have access modifiers. If you try to treat <code>__</code> like a traditional <code>private</code> access modifier, this is one of the problems you get. Leading double underscores cause name mangling - a name <code>__bar</code> inside a <code>class Foo</code> (or <code>class __Foo</code>, or any numb...
1
2016-09-27T19:48:36Z
[ "python", "nested", "private", "python-3.5" ]
setup a database in django
39,733,082
<p>I followed the django doc and went through the polls example. I have a sqlite db 'nameinfodb'. I want to access it by search last name online. I setup models.py as </p> <pre><code>class Infotable(models.Model): pid_text = models.CharField(max_length=200) lname_text = models.CharField(max_length=200) fna...
1
2016-09-27T19:45:33Z
39,733,136
<p>You need to do it the other way around:</p> <pre><code>python manage.py makemigrations pidb python manage.py migrate </code></pre> <p><a href="https://docs.djangoproject.com/en/1.10/intro/tutorial02/#activating-models" rel="nofollow">See this part</a> of the tutorial for more information</p>
3
2016-09-27T19:48:38Z
[ "python", "django", "database" ]
While loop decorator
39,733,131
<p>I am using the <code>ftp</code> library which is incredibly finicky when downloading a bunch of files. This will error about once every 20 tries:</p> <pre><code>ftp.cwd(locale_dir) </code></pre> <p>So, what I do which fixes it is:</p> <pre><code>while True: try: ftp.cwd(locale_dir) except: ...
1
2016-09-27T19:48:30Z
39,733,234
<p>You may create decorator as:</p> <pre><code>def retry_on_failure(count=10): # &lt;- default count as 10 def retry_function(function): def wrapper(*args, **kwargs): while count &gt; 0: try: func_response = function(view, request, *args, **kwargs) ...
2
2016-09-27T19:55:01Z
[ "python" ]
While loop decorator
39,733,131
<p>I am using the <code>ftp</code> library which is incredibly finicky when downloading a bunch of files. This will error about once every 20 tries:</p> <pre><code>ftp.cwd(locale_dir) </code></pre> <p>So, what I do which fixes it is:</p> <pre><code>while True: try: ftp.cwd(locale_dir) except: ...
1
2016-09-27T19:48:30Z
39,733,451
<p>You can't use the syntax you want, because in that code <code>ftp.cwd(locale_dir)</code> gets called before <code>retry_on_failure</code>, so any exception it raises will prevent the <code>retry</code> function from running. You could separate the function and its arguments, however, and call something like <code>re...
1
2016-09-27T20:09:25Z
[ "python" ]
How to drop columns with empty headers in Pandas?
39,733,141
<p>If I have a DF: </p> <pre><code>Name1 Name2 NUll Name3 NULL Name4 abc abc null abc abc abc null abc abc abc null abc abc abc null abc </code></pre> <p>Can I use dropna, to keep Name3 as a column with all empty values? Yet still drop both Null columns. Th...
-1
2016-09-27T19:48:48Z
39,733,278
<p>What about using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>DataFrame.drop</code></a>?</p> <pre><code>In [3]: df = pd.read_clipboard() Out[3]: Name1 Name2 NUll Name3 NULL Name4 0 abc abc null abc 1 abc abc null...
0
2016-09-27T19:58:08Z
[ "python", "pandas" ]
Add a new column to a csv file in python
39,733,158
<p>I am trying to add a column to a csv file that combines strings from two other columns. Whenever I try this I either get an output csv with only the new column or an output with all of the original data and not the new column. </p> <p>This is what I have so far:</p> <pre><code>with open(filename) as csvin: rea...
2
2016-09-27T19:49:28Z
39,733,317
<p>No input to test, but try this. Your current approach doesn't include the existing data for each row that already exists in your input data. <code>extend</code> will take the list that represents each row and then add another item to that list... equivalent to adding a column.</p> <pre><code>import CSV with open(fi...
2
2016-09-27T20:00:20Z
[ "python", "python-2.7", "csv" ]
Add a new column to a csv file in python
39,733,158
<p>I am trying to add a column to a csv file that combines strings from two other columns. Whenever I try this I either get an output csv with only the new column or an output with all of the original data and not the new column. </p> <p>This is what I have so far:</p> <pre><code>with open(filename) as csvin: rea...
2
2016-09-27T19:49:28Z
39,733,574
<p>I assume that glayne wants to combine column 10 and 11 into one. In my approach, I concentrate on how to transform a single row first:</p> <pre><code>def transform_row(input_row): output_row = input_row[:] output_row[10:12] = [' '.join(output_row[10:12])] return output_row </code></pre> <p>Once tested ...
0
2016-09-27T20:17:16Z
[ "python", "python-2.7", "csv" ]
Add a new column to a csv file in python
39,733,158
<p>I am trying to add a column to a csv file that combines strings from two other columns. Whenever I try this I either get an output csv with only the new column or an output with all of the original data and not the new column. </p> <p>This is what I have so far:</p> <pre><code>with open(filename) as csvin: rea...
2
2016-09-27T19:49:28Z
39,734,557
<p>Each row is read as a list, so you can append to it by adding another list (e.g. the new column value). Your current code is simply writing the new column value.</p> <pre><code>with open('data.csv') as fin, open('out.csv', 'wb') as fout: reader = csv.reader(fin) writer = csv.writer(fout) for row in rea...
0
2016-09-27T21:26:03Z
[ "python", "python-2.7", "csv" ]