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 |
|---|---|---|---|---|---|---|---|---|---|
What is the quickest way to ensure a specific column is last (or first) in a dataframe | 38,601,841 | <p>given <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
</code></pre>
<p><a href="http://i.stack.imgur.com/UXlIN.png" rel="nofollow"><img src="http://i.stack.imgur.com/UXlIN.png" alt="enter image description here"></a></p>
<p>Suppose I need column <code>'b'</code> ... | 3 | 2016-07-27T00:18:38Z | 38,602,096 | <p>I would rearrange the list of columns, rather than removing and appending one of them:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
def put_me_last(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def put... | 3 | 2016-07-27T00:57:32Z | [
"python",
"pandas"
] |
What is the quickest way to ensure a specific column is last (or first) in a dataframe | 38,601,841 | <p>given <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
</code></pre>
<p><a href="http://i.stack.imgur.com/UXlIN.png" rel="nofollow"><img src="http://i.stack.imgur.com/UXlIN.png" alt="enter image description here"></a></p>
<p>Suppose I need column <code>'b'</code> ... | 3 | 2016-07-27T00:18:38Z | 38,602,109 | <p>How about this one:</p>
<pre><code>df.reindex(columns=df.columns.drop(col).append(pd.Index([col])))
</code></pre>
<p>(<code>.append([col])</code> doesn't work - might be a bug. <strong>Edit</strong>: use of <code>.append(pd.Index([col])</code> is probably the safest option in append.)</p>
<p>Comment on testing: ... | 2 | 2016-07-27T00:59:12Z | [
"python",
"pandas"
] |
What is the quickest way to ensure a specific column is last (or first) in a dataframe | 38,601,841 | <p>given <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
</code></pre>
<p><a href="http://i.stack.imgur.com/UXlIN.png" rel="nofollow"><img src="http://i.stack.imgur.com/UXlIN.png" alt="enter image description here"></a></p>
<p>Suppose I need column <code>'b'</code> ... | 3 | 2016-07-27T00:18:38Z | 38,602,601 | <p>Starting with this:</p>
<pre><code> df.columns
Index([u'a', u'b', u'c', u'd'], dtype='object')
</code></pre>
<p><strong>Dont do this, looks like a bug.</strong> </p>
<pre><code> df.columns.drop(["b"]).insert(-1, 'b')
Index([u'a', u'c', u'b', u'd'], dtype='object')
df.columns.drop(["b"]).insert(-1, 'x')
Index... | 0 | 2016-07-27T02:12:25Z | [
"python",
"pandas"
] |
What is the quickest way to ensure a specific column is last (or first) in a dataframe | 38,601,841 | <p>given <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
</code></pre>
<p><a href="http://i.stack.imgur.com/UXlIN.png" rel="nofollow"><img src="http://i.stack.imgur.com/UXlIN.png" alt="enter image description here"></a></p>
<p>Suppose I need column <code>'b'</code> ... | 3 | 2016-07-27T00:18:38Z | 38,605,142 | <p>It's not the fastest though:</p>
<pre><code>def put_me_last(df,column):
column_list=list(df)
column_list.remove(column)
column_list.append(column)
return df[column_list]
%timeit put_me_last(df,'b')
1000 loops, best of 3: 391 µs per loop
</code></pre>
| 1 | 2016-07-27T06:20:01Z | [
"python",
"pandas"
] |
Pyinstaller on Kali to create exe for Windows XP | 38,601,919 | <p>I am using Pyinstaller on Kali Linux 2 to create .exe to run on Windows XP.</p>
<p>So far, pyinstaller is successful at creating .exe that works on Kali Linux, but not Windows</p>
<p>Here is the python code</p>
<pre><code>import webbrowser
webbrowser.open('http://www.cnn.com')
</code></pre>
<p>This is the comma... | -1 | 2016-07-27T00:28:45Z | 38,601,937 | <p>Windows Defender assumes that externally sourced executables, especially those without cryptographic signature, may be malware. Try clicking "Open."</p>
| 1 | 2016-07-27T00:31:05Z | [
"python",
"linux",
"windows",
"exe"
] |
Pyinstaller on Kali to create exe for Windows XP | 38,601,919 | <p>I am using Pyinstaller on Kali Linux 2 to create .exe to run on Windows XP.</p>
<p>So far, pyinstaller is successful at creating .exe that works on Kali Linux, but not Windows</p>
<p>Here is the python code</p>
<pre><code>import webbrowser
webbrowser.open('http://www.cnn.com')
</code></pre>
<p>This is the comma... | -1 | 2016-07-27T00:28:45Z | 38,601,974 | <p>From the <a href="https://pyinstaller.readthedocs.io/en/stable/usage.html#supporting-multiple-operating-systems" rel="nofollow">PyInstaller documentation</a>:</p>
<blockquote>
<p>If you need to distribute your application for more than one OS, for example both Windows and Mac OS X, you must install PyInstaller on... | 3 | 2016-07-27T00:37:56Z | [
"python",
"linux",
"windows",
"exe"
] |
Pyinstaller on Kali to create exe for Windows XP | 38,601,919 | <p>I am using Pyinstaller on Kali Linux 2 to create .exe to run on Windows XP.</p>
<p>So far, pyinstaller is successful at creating .exe that works on Kali Linux, but not Windows</p>
<p>Here is the python code</p>
<pre><code>import webbrowser
webbrowser.open('http://www.cnn.com')
</code></pre>
<p>This is the comma... | -1 | 2016-07-27T00:28:45Z | 38,602,272 | <p>Rafalmp is correct you must use a Windows machine to compile it. Alternatively you can use Wine, if you didn't have access to a Windows machine. </p>
<p>For more info please refer to <a href="https://github.com/pyinstaller/pyinstaller/wiki/FAQ" rel="nofollow">Pyinstaller FAQ</a></p>
| 2 | 2016-07-27T01:25:00Z | [
"python",
"linux",
"windows",
"exe"
] |
Ordering a Django queryset based on the sorting of a sorted set from redis | 38,602,115 | <p>I have a sorted set from redis. The sorted set contains both ids of objects and their sorting scores.</p>
<p>Next, I have a Django queryset, consisting of objects whose sorted ids were contained in the aforementioned redis sorted set. </p>
<p>I need to sort this Django queryset according to the placement of ids in... | 1 | 2016-07-27T01:00:07Z | 38,602,462 | <p>Replace your for loop with:</p>
<pre><code>result = sorted(queryset, key=lambda item: dictionary[item.pk], reverse=True)
</code></pre>
<p>This will exception out if anything in the qs is not in the redis result - use <code>dictionary.get(item.pk, ...)</code> with some sane default instead of <code>dictionary[item.... | 1 | 2016-07-27T01:53:33Z | [
"python",
"django",
"sorting",
"redis"
] |
How to install Numpy & pip3 for python3.x when they were installed in python2.7? Using Conda? | 38,602,185 | <p>I want to write program in python3 (3.5), hence I installed python3 next to the pre-installed python2 (2.7) on Mac OS X El Captian.</p>
<p>Since my terminal runs python2.7 by default and Numpy is already installed for it, I put <code>alias python=python3</code> and expected to be able to install Numpy for python3. ... | 0 | 2016-07-27T01:10:42Z | 38,602,204 | <p>The simplest way on a Mac is with Homebrew:</p>
<p><a href="http://brew.sh/" rel="nofollow">http://brew.sh/</a></p>
<p>Install Homebrew, then run:</p>
<p><code>brew install python3 pip3</code></p>
<p>Edit --</p>
<p>Python3 includes pip3, but Homebrew occasionally has trouble linking to the correct versions, dep... | 1 | 2016-07-27T01:13:45Z | [
"python",
"python-2.7",
"python-3.x",
"pip",
"conda"
] |
How to install Numpy & pip3 for python3.x when they were installed in python2.7? Using Conda? | 38,602,185 | <p>I want to write program in python3 (3.5), hence I installed python3 next to the pre-installed python2 (2.7) on Mac OS X El Captian.</p>
<p>Since my terminal runs python2.7 by default and Numpy is already installed for it, I put <code>alias python=python3</code> and expected to be able to install Numpy for python3. ... | 0 | 2016-07-27T01:10:42Z | 38,602,775 | <p>I would recommend using the Anaconda Python distribution.</p>
<p>The main reasons are as such:</p>
<ol>
<li>You will have a Python distribution that comes with <code>numpy</code> and the rest of the <a href="http://scipy.org" rel="nofollow">Scientific Python</a> stack.</li>
<li>The Anaconda Python will be installe... | 2 | 2016-07-27T02:34:37Z | [
"python",
"python-2.7",
"python-3.x",
"pip",
"conda"
] |
how to make x,y axis appear in an axes in python matplotlib | 38,602,216 | <p>I have a text file (which I extracted during run using np.savetxt function) _anchors.out</p>
<pre><code>-84 -40 99 55
-176 -88 191 103
-360 -184 375 199
-56 -56 71 71
-120 -120 135 135
-248 -248 263 263
-36 -80 51 95
-80 -168 95 183
-168 -344 183 359
</code></pre>
<p>These are 9 boxes centered around point 7.5. I ... | 2 | 2016-07-27T01:14:51Z | 38,602,748 | <p>You can use this alternative that plots dashed lines:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
b = np.loadtxt('_anchors.out','int')
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.set_xbound(-400,400)
ax1.set_ybound(-400,400)
for x1,... | 2 | 2016-07-27T02:30:58Z | [
"python",
"matplotlib"
] |
how to make x,y axis appear in an axes in python matplotlib | 38,602,216 | <p>I have a text file (which I extracted during run using np.savetxt function) _anchors.out</p>
<pre><code>-84 -40 99 55
-176 -88 191 103
-360 -184 375 199
-56 -56 71 71
-120 -120 135 135
-248 -248 263 263
-36 -80 51 95
-80 -168 95 183
-168 -344 183 359
</code></pre>
<p>These are 9 boxes centered around point 7.5. I ... | 2 | 2016-07-27T01:14:51Z | 38,603,189 | <pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
b = np.loadtxt('./_anchors.out','int')
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.set_xbound(-400,400)
ax1.set_ybound(-400,400)
for x1,y1,x2,y2 in b:
ax1.add_patch(patches.Rectangle((x1,y1), ... | 3 | 2016-07-27T03:25:49Z | [
"python",
"matplotlib"
] |
how to make x,y axis appear in an axes in python matplotlib | 38,602,216 | <p>I have a text file (which I extracted during run using np.savetxt function) _anchors.out</p>
<pre><code>-84 -40 99 55
-176 -88 191 103
-360 -184 375 199
-56 -56 71 71
-120 -120 135 135
-248 -248 263 263
-36 -80 51 95
-80 -168 95 183
-168 -344 183 359
</code></pre>
<p>These are 9 boxes centered around point 7.5. I ... | 2 | 2016-07-27T01:14:51Z | 38,603,218 | <p>Following the documentation <a href="http://matplotlib.org/examples/pylab_examples/spine_placement_demo.html" rel="nofollow">here</a> you can achieve this with the following code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
b = np.loadtxt('_anchors.out','i... | 3 | 2016-07-27T03:28:56Z | [
"python",
"matplotlib"
] |
python tornado json render to html script | 38,602,219 | <p>I want to render json file to html script part. In the tornado part, No1 is sendering json data to html. And, No2 part is received the json data from No1. However this code is not working. I found that html script doesn't allow the form of {{ }}. How I send the json data to part of html ?</p>
<p>[ python - tornado ... | 0 | 2016-07-27T01:15:07Z | 38,602,647 | <p>The {{ }} in your index.html template will be autoescaped for html. You want raw output because in this case you're outputting javascript rather than html. You also want to make sure you're actually letting python convert your data object to correctly formatted json.</p>
<p>Import the json library and add a call ... | 1 | 2016-07-27T02:17:34Z | [
"javascript",
"python",
"html",
"json",
"tornado"
] |
python tornado json render to html script | 38,602,219 | <p>I want to render json file to html script part. In the tornado part, No1 is sendering json data to html. And, No2 part is received the json data from No1. However this code is not working. I found that html script doesn't allow the form of {{ }}. How I send the json data to part of html ?</p>
<p>[ python - tornado ... | 0 | 2016-07-27T01:15:07Z | 38,602,913 | <p>The key point is that string will be autoescaped by template engine. So we need to decode it before parsing it as a json.</p>
<p><code>{% raw %}</code> directive mentioned by @clockwatcher is one solution. But it may cause error if the variable <code>text</code> is double-quoted since <code>json.dumps(data)</code> ... | 0 | 2016-07-27T02:51:20Z | [
"javascript",
"python",
"html",
"json",
"tornado"
] |
Python- checking a number to see if it's a prime number by using divisors | 38,602,221 | <p>I have to write a program that checks if a number is a prime number by going through divisors in the range(1,num). (For ex. if the input is 5, the program will check if 2 is a divisor, then 3, then 4). Can someone explain how I can put the last expression in my program (the "this is a prime number" print function), ... | 0 | 2016-07-27T01:15:13Z | 38,602,259 | <p>There are many ways to do this:</p>
<h2>Set a flag!</h2>
<pre><code>is_prime = True # a boolean flag
for num1 in range(2,num):
div = num%num1
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
is_prime = False
break
else:
... | 1 | 2016-07-27T01:22:16Z | [
"python"
] |
Python- checking a number to see if it's a prime number by using divisors | 38,602,221 | <p>I have to write a program that checks if a number is a prime number by going through divisors in the range(1,num). (For ex. if the input is 5, the program will check if 2 is a divisor, then 3, then 4). Can someone explain how I can put the last expression in my program (the "this is a prime number" print function), ... | 0 | 2016-07-27T01:15:13Z | 38,602,270 | <p>Python's <code>for</code> expression has <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">an optional <code>else</code> clause</a>:</p>
<blockquote>
<p>Loop statements may have an else clause; it is executed when the loop terminat... | 1 | 2016-07-27T01:24:36Z | [
"python"
] |
Python- checking a number to see if it's a prime number by using divisors | 38,602,221 | <p>I have to write a program that checks if a number is a prime number by going through divisors in the range(1,num). (For ex. if the input is 5, the program will check if 2 is a divisor, then 3, then 4). Can someone explain how I can put the last expression in my program (the "this is a prime number" print function), ... | 0 | 2016-07-27T01:15:13Z | 38,602,279 | <p>Given that you have already covered a division by 1, all you have to do is count if there is only one more divisor (the number itself). So to keep your code structure I added a counter.</p>
<pre><code>while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
... | 0 | 2016-07-27T01:25:59Z | [
"python"
] |
Python- checking a number to see if it's a prime number by using divisors | 38,602,221 | <p>I have to write a program that checks if a number is a prime number by going through divisors in the range(1,num). (For ex. if the input is 5, the program will check if 2 is a divisor, then 3, then 4). Can someone explain how I can put the last expression in my program (the "this is a prime number" print function), ... | 0 | 2016-07-27T01:15:13Z | 38,602,325 | <p>I added one line sys.exit()</p>
<pre><code>while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
break
elif num == 1:
print("1 is technically not a prime number.")
else:
print("Number cannot be negative- try again.")
for num1 in range(2,num):
div = num%n... | 0 | 2016-07-27T01:34:01Z | [
"python"
] |
text game if check1 and check2 and check3 statment | 38,602,286 | <p>So this is the beginning of a simple text game im working on.
When I run the program it will run through them multiple times before it can get to done. Not just one for each like I want. But I still want it to pick them at random, so I'm not sure if there is a better way to do this? Could someone tell me what I did ... | 0 | 2016-07-27T01:26:49Z | 38,602,369 | <p>You can move the part </p>
<pre><code>awnser = ((Blist), (Dictionary), (Tup))
</code></pre>
<p>outside the <em>question</em> function.</p>
<p>Then in the if where you check if it is the correct answer, remove the possibility from awnser fx:</p>
<pre><code> if x == 'list' and newawn == Blist:
gl... | 0 | 2016-07-27T01:41:27Z | [
"python",
"python-3.x"
] |
text game if check1 and check2 and check3 statment | 38,602,286 | <p>So this is the beginning of a simple text game im working on.
When I run the program it will run through them multiple times before it can get to done. Not just one for each like I want. But I still want it to pick them at random, so I'm not sure if there is a better way to do this? Could someone tell me what I did ... | 0 | 2016-07-27T01:26:49Z | 38,602,572 | <p>You can move your first line within your function outside of the function. For now, make it a list:</p>
<pre><code>awnser = [(Blist), (Dictionary), (Tup)]
def question():
...
</code></pre>
<p>Then choose one of them at random within the function:</p>
<pre><code>def question():
newawn = (random.choice(awnser)... | 0 | 2016-07-27T02:08:52Z | [
"python",
"python-3.x"
] |
text game if check1 and check2 and check3 statment | 38,602,286 | <p>So this is the beginning of a simple text game im working on.
When I run the program it will run through them multiple times before it can get to done. Not just one for each like I want. But I still want it to pick them at random, so I'm not sure if there is a better way to do this? Could someone tell me what I did ... | 0 | 2016-07-27T01:26:49Z | 38,602,796 | <p>You can do it by putting the types in a list and removing each one when it is correctly identified. The logic as a while can be simplified by using a loop and not having <code>question()</code> call itself recursively. You also don't need those global <code>check#</code> variables because you can just see there is a... | 0 | 2016-07-27T02:36:38Z | [
"python",
"python-3.x"
] |
Pandas Slicing by given row AND columns indices | 38,602,288 | <p>I have the following dataframe:</p>
<pre><code>df1 = pd.DataFrame(np.random.randn(4,2),columns=["A","B"], index=["mon","tue","wed","thu"])
df1
A B
mon -1.903218 0.084362
tue -0.071207 -1.324411
wed -0.866212 -0.311787
thu -0.267956 0.802968
</code></pre>
<p>If I do the following slicing o... | 1 | 2016-07-27T01:26:59Z | 38,602,314 | <p>Instead of:</p>
<pre><code>df1.ix[["mon","tue"],["A","B"]]
</code></pre>
<p>Try:</p>
<pre><code>df1['A']['mon']
df1['B']['tue']
</code></pre>
<p>This will give you:</p>
<ul>
<li>the value located at column A, index mon</li>
<li>the value located at column B, index tue</li>
</ul>
<p>Based on this, ou can create... | 1 | 2016-07-27T01:32:10Z | [
"python",
"pandas"
] |
Pandas Slicing by given row AND columns indices | 38,602,288 | <p>I have the following dataframe:</p>
<pre><code>df1 = pd.DataFrame(np.random.randn(4,2),columns=["A","B"], index=["mon","tue","wed","thu"])
df1
A B
mon -1.903218 0.084362
tue -0.071207 -1.324411
wed -0.866212 -0.311787
thu -0.267956 0.802968
</code></pre>
<p>If I do the following slicing o... | 1 | 2016-07-27T01:26:59Z | 38,602,380 | <p>You probably want a <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-lookup-method" rel="nofollow"><code>lookup</code> method</a></p>
<pre><code>df1.lookup(["mon", "tue"], ["A", "B"])
Out[42]: array([-1.903218, -1.324411])
</code></pre>
| 4 | 2016-07-27T01:42:33Z | [
"python",
"pandas"
] |
Can open a program in IDLE but not in Terminal,Atom etc | 38,602,360 | <p>Hi I'm new to python and pygame but I am using Atom but I can't solve this problem. When I open my script in IDLE it works but I can't make it work on Atom (specifically terminal-plus) and Terminal. My error message is </p>
<pre><code>Traceback (most recent call last):
File "cargame.py", line 32, in <module>... | 2 | 2016-07-27T01:40:18Z | 38,602,396 | <p>Perhaps the reason why pygame can't load the image is because it has no context of where the module is being loaded from. Make sure the module (<em>essentially the file where your source code exists</em>), and image file exist in the same environment on disk (<em>the same folder</em>). Otherwise pass an absolute pat... | 1 | 2016-07-27T01:44:42Z | [
"python",
"pygame"
] |
Unicode-Ascii mixed string in python | 38,602,376 | <p>I have a string that is stored in DB as:</p>
<pre><code>FB (\u30a8\u30a2\u30eb\u30fc)
</code></pre>
<p>when I load this row from python code, I am unable to format it correctly.</p>
<pre><code># x = load that string
print x # returns u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
</code></pre>
<p>Notice two "\" This messe... | 1 | 2016-07-27T01:42:08Z | 38,603,534 | <pre><code>raw_string = '\u30a8\u30a2\u30eb\u30fc'
string = ''.join([unichr(int(r, 16)) for r in raw_string.split('\\u') if r])
print(string)
</code></pre>
<p>A way to solve this, expecting a better answer.</p>
| 0 | 2016-07-27T04:04:44Z | [
"python",
"string",
"unicode"
] |
Unicode-Ascii mixed string in python | 38,602,376 | <p>I have a string that is stored in DB as:</p>
<pre><code>FB (\u30a8\u30a2\u30eb\u30fc)
</code></pre>
<p>when I load this row from python code, I am unable to format it correctly.</p>
<pre><code># x = load that string
print x # returns u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
</code></pre>
<p>Notice two "\" This messe... | 1 | 2016-07-27T01:42:08Z | 38,605,537 | <p>Since you already have a Unicode string, encode it back to ASCII and decode it with the <code>unicode_escape</code> codec:</p>
<pre><code>>>> s = u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
>>> s
u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
>>> print s
FB (\u30a8\u30a2\u30eb\u30fc)
>>> s.encode... | 3 | 2016-07-27T06:43:08Z | [
"python",
"string",
"unicode"
] |
Bad Color String Error in Python Using Turtle | 38,602,434 | <p>In my python program I am reading from a file and storing the contents in a list. I checked each index of the list so I know it was stored correctly.
I am then passing a specific index to a class which contains the color blue.
Whenever it gets to the <code>turtle.color</code>I get an error <strong>bad color string... | 0 | 2016-07-27T01:50:52Z | 38,602,814 | <p>It might be because your colour string also contains unwanted white spaces. Change the 3rd line to <code>self.color = Rcolor.strip()</code> for example to see if it fixes the problem.</p>
| 1 | 2016-07-27T02:39:49Z | [
"python",
"python-3.x",
"colors",
"turtle-graphics"
] |
How to perform a OLS regression on dynamic data frame and estimate the slope coefficient? | 38,602,446 | <p>I have a data frame like below and it's structure is not fixed, it can have different number of column at different moment.</p>
<pre><code> A_Name B_Info Value_Yn Value_Yn-1 Value_Yn-2 ...... Value_Y1
0 AA X1 0.9 0.8 0.7 ...... 0.1
1 BB Y1 0.1 ... | 2 | 2016-07-27T01:51:55Z | 38,604,192 | <p>This problem can be solved with numpy and linear algebra. The basic idea is that because you are reusing the same x values over and over again, we can reuse intermediate computations.</p>
<h2><b>The derivation.</b></h2>
<p>Linear regression is usually solved like this: </p>
<ol>
<li>Given a dataset (x_1, y_1) ...... | 2 | 2016-07-27T05:12:04Z | [
"python",
"numpy",
"pandas",
"regression"
] |
Python - NameError: name 'PROTOCOL_SSLv3' is not defined, when using gevent | 38,602,466 | <p>So I had a Flask app on one machine in a virtualenv (raspberry pi running raspbian) and everything worked just fine, however when I ported it to another raspberry pi, also running raspbian, and set up a new virtualenv to the exact same specifications, running the app throws this:</p>
<p>The Flask app is a socket-io... | 0 | 2016-07-27T01:54:02Z | 39,496,050 | <p>I solved this problem by replacing PROTOCOL_SSLv3 = PROTOCOL_SSLv23 , thank to answer of <strong>mgogoulos</strong> , link here: <a href="https://github.com/mistio/mist.io/issues/434" rel="nofollow">https://github.com/mistio/mist.io/issues/434</a></p>
| 0 | 2016-09-14T17:04:20Z | [
"python",
"flask",
"socket.io",
"virtualenv",
"gevent"
] |
Why doesn't Spyder obey my IPython config file? | 38,602,507 | <p>This used to work, but now it doesn't, in IPython 4.2.0 and Spyder 2.3.9 from Anaconda. Argh.</p>
<p>If I get the IPython config it looks correct, as though it read the file correctly:</p>
<pre><code>get_ipython().config
Out[1]:
{'IPCompleter': {'greedy': True},
'IPKernelApp': {'exec_lines': ['%pylab qt']},
'In... | 13 | 2016-07-27T02:00:38Z | 39,629,910 | <p>im not sure what is the problem either
I was having the same issue</p>
<p>but mine was fixed when I uninstalled anaconda with EVERYTHING including its python bit
granted I saved the settings and profile and stuff</p>
<p>and reinstalled</p>
<p>Hope that helps, if its an option at all</p>
| 0 | 2016-09-22T03:46:58Z | [
"python",
"numpy",
"ipython",
"anaconda",
"spyder"
] |
Python: Shorten concatenation by using inline conditionals | 38,602,574 | <p>If the title is a bit obscure, an example of what I would like to do is:</p>
<p><code>print("Status: " + if serverIsOnline: "Online" else: "Offline")</code></p>
<p>I know this is improper, but what I am trying to do is check if <code>serverIsOnline</code> is <code>True</code> then print <code>Status: Online</code>... | 0 | 2016-07-27T02:08:54Z | 38,602,588 | <p>Python allows inline <code>if/else</code> as long as an <code>else</code> is specified (<code>if</code> only is a SyntaxError). Most Python programmers refer to this as its ternary:</p>
<pre><code>>>> server_online = True
>>> print('Status: ' + ('Online' if server_online else 'Offline'))
Status: O... | 1 | 2016-07-27T02:10:53Z | [
"python",
"python-3.x",
"if-statement",
"printing",
"concatenation"
] |
Python: Shorten concatenation by using inline conditionals | 38,602,574 | <p>If the title is a bit obscure, an example of what I would like to do is:</p>
<p><code>print("Status: " + if serverIsOnline: "Online" else: "Offline")</code></p>
<p>I know this is improper, but what I am trying to do is check if <code>serverIsOnline</code> is <code>True</code> then print <code>Status: Online</code>... | 0 | 2016-07-27T02:08:54Z | 38,602,589 | <p>What you're looking for is a <a href="http://book.pythontips.com/en/latest/ternary_operators.html" rel="nofollow">conditional expression</a> (<em>also known as a 'ternary' expression, usually with a</em> <code>?</code> <em>operator, used by many other languages</em>).</p>
<pre><code>print("Status: " + "Online" if s... | 4 | 2016-07-27T02:11:03Z | [
"python",
"python-3.x",
"if-statement",
"printing",
"concatenation"
] |
How do I fix the "image "pyimage10" doesn't exist" error, and why does it happen? | 38,602,594 | <p>I am making a tkiner application and that shows a user a page with some basic information and a picture before allowing them to click a button to view live Bitcoin price data. However, when I added the image to the 'start up' page, I got this error from my IDE:</p>
<pre><code> BTC_img_label = tk.Label(self, image=B... | 1 | 2016-07-27T02:11:40Z | 38,603,572 | <p>You can not load a <strong>.png</strong> format with tkinter. You rather need to use the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a> library for that:</p>
<pre><code>import PIL
image = PIL.Image.open("bitcoin.png")
BTC_img = PIL.ImageTk.PhotoImage(image)
BTC_img_label = tk.Label(self, ... | 1 | 2016-07-27T04:10:04Z | [
"python",
"image-processing",
"tkinter"
] |
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-5: ordinal not in range(256) | 38,602,628 | <p>everyone!
I use python3(pycharm),and my codes are like these:</p>
<pre><code># -*- coding: utf-8 -*-
import numpy
c=numpy.loadtxt('test.csv',dtype="str_",delimiter=',',usecols=(6,),unpack=True)
</code></pre>
<p>when I have some Chinese words in test.csv,I got a error like this:</p>
<pre><code>UnicodeEncodeError:... | 0 | 2016-07-27T02:15:12Z | 38,603,675 | <pre><code>with open('test.csv', encoding='utf-8') as fh:
numpy.loadtxt(fh, dtype="str_", delimiter=',', usecols=(6,), unpack=True)
</code></pre>
| 0 | 2016-07-27T04:23:21Z | [
"python"
] |
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-5: ordinal not in range(256) | 38,602,628 | <p>everyone!
I use python3(pycharm),and my codes are like these:</p>
<pre><code># -*- coding: utf-8 -*-
import numpy
c=numpy.loadtxt('test.csv',dtype="str_",delimiter=',',usecols=(6,),unpack=True)
</code></pre>
<p>when I have some Chinese words in test.csv,I got a error like this:</p>
<pre><code>UnicodeEncodeError:... | 0 | 2016-07-27T02:15:12Z | 38,603,745 | <p>When we read the Chinese character to numpy, the data type cannot be a simple string because it treats the character as ASCII which is not long enough to hold the UTF-8 character.</p>
<p>So what I have done here is to let numpy knows we are reading a 4-byte character instead which is sufficient to hold an unicode c... | 0 | 2016-07-27T04:29:51Z | [
"python"
] |
confused value scope in python | 38,602,718 | <p>Hi I have staring programming with c and I conld'nt understand value scope in python.</p>
<p>here is my code</p>
<pre><code>class ScenarioEnvironment():
def __init__(self):
print(self)
class report():
config = ScenarioEnvironment()
def __init__(self):
self.config = ScenarioEnvironment... | 1 | 2016-07-27T02:27:29Z | 38,602,809 | <p>Since your question seems a bit ambiguous, I'll just comment/fix your code:</p>
<pre><code>class ScenarioEnvironment():
def __init__(self,x):
self.x = x # Assigning instance variable x to constructor parameter x.
print(self) # You're printing the object instance.
class report():
# Static ... | 1 | 2016-07-27T02:39:15Z | [
"python"
] |
confused value scope in python | 38,602,718 | <p>Hi I have staring programming with c and I conld'nt understand value scope in python.</p>
<p>here is my code</p>
<pre><code>class ScenarioEnvironment():
def __init__(self):
print(self)
class report():
config = ScenarioEnvironment()
def __init__(self):
self.config = ScenarioEnvironment... | 1 | 2016-07-27T02:27:29Z | 38,602,876 | <p>You need to know the differences between class attribute and instance object attribute.
Maybe these codes will help you:</p>
<pre><code>class TestConfig1(object):
config = 1
def __init__(self):
self.config = 2
class TestConfig2(object):
config = 1
def __init__(self):
self.config2... | 2 | 2016-07-27T02:46:16Z | [
"python"
] |
Conditional URL scraping with Scrapy | 38,602,790 | <p>I am trying to use Scrapy on a site which I do not know the URL structure of.</p>
<p>I would like to:</p>
<ul>
<li><p><strong>only</strong> extract data from pages which contain Xpath "//div[@class="product-view"]".</p></li>
<li><p>extract print (in CSV) the URL, the name and price Xpaths</p></li>
</ul>
<p>When I... | 0 | 2016-07-27T02:36:04Z | 38,606,431 | <p>What you are lookin here is for <a href="http://doc.scrapy.org/en/latest/topics/spiders.html?#crawlspider" rel="nofollow">scrapy.spiders.Crawlspider</a>. </p>
<p>However you almost got it with your own approach. Here's the fixed version.</p>
<pre><code>from scrapy.linkextractors import LinkExtractor
def parse(self... | 1 | 2016-07-27T07:24:37Z | [
"python",
"xpath",
"scrapy"
] |
Python sorting dictionary | 38,602,843 | <p>I want to sort the following <strong>dictionary</strong> by the keys <code>score</code>, which is an array.</p>
<pre><code>student = {"name" : [["Peter"], ["May"], ["Sharon"]],
"score" : [[1,5,3], [3,2,6], [5,9,2]]}
</code></pre>
<p>For a better representation:</p>
<pre><code>Peter ---- [1,5,3]
May ---... | 0 | 2016-07-27T02:42:31Z | 38,602,969 | <p>First zip the students name and score use <code>zip</code>.</p>
<pre><code>zip(student["name"], student["score"])
</code></pre>
<p>you will get better representation:</p>
<pre><code>[(['May'], [3, 2, 6]),
(['Peter'], [1, 5, 3]),
(['Sharon'], [5, 9, 2])]
</code></pre>
<p>then sort this list and get the studen... | 3 | 2016-07-27T02:58:31Z | [
"python"
] |
Python sorting dictionary | 38,602,843 | <p>I want to sort the following <strong>dictionary</strong> by the keys <code>score</code>, which is an array.</p>
<pre><code>student = {"name" : [["Peter"], ["May"], ["Sharon"]],
"score" : [[1,5,3], [3,2,6], [5,9,2]]}
</code></pre>
<p>For a better representation:</p>
<pre><code>Peter ---- [1,5,3]
May ---... | 0 | 2016-07-27T02:42:31Z | 38,602,997 | <p>This would probably work for you:</p>
<pre><code>student = {
"name": [["Peter"], ["May"], ["Sharon"]],
"score": [[1,5,3], [3,2,6], [5,9,2]]
}
# pair up the names and scores
# this gives one tuple for each student:
# the first item is their name as a 1-item list
# the second item is their list of scores
pai... | 1 | 2016-07-27T03:03:00Z | [
"python"
] |
Python sorting dictionary | 38,602,843 | <p>I want to sort the following <strong>dictionary</strong> by the keys <code>score</code>, which is an array.</p>
<pre><code>student = {"name" : [["Peter"], ["May"], ["Sharon"]],
"score" : [[1,5,3], [3,2,6], [5,9,2]]}
</code></pre>
<p>For a better representation:</p>
<pre><code>Peter ---- [1,5,3]
May ---... | 0 | 2016-07-27T02:42:31Z | 38,603,098 | <p>If you want to use dictionaries, I suggest using <code>OrderedDict</code>:</p>
<pre><code>name = ["Peter", "May", "Sharon"]
score = [[1,5,3], [3,2,6], [5,9,2]]
d = {n: s for (n, s) in zip(name, score)}
from collections import OrderedDict
ordered = OrderedDict(sorted(d.items(), key=lambda t: t[1][1]))
list(ordered)... | 0 | 2016-07-27T03:14:31Z | [
"python"
] |
Max Drawdown with Minimum Window Length | 38,602,884 | <p>For a given time series of floats, it is pretty easy to calculate an unconstrained maximum drawdown in <code>O(n)</code> time, where max drawdown is defined as </p>
<pre><code>\min_{i,j, i<j}(x_j - x_i)
</code></pre>
<p>In python, we the calculation is <code>min(x - numpy.expanding_max(x))</code>, but to get a ... | 1 | 2016-07-27T02:47:28Z | 38,612,201 | <p>The modifications are quite small compared to your <code>max_drawdown</code> function. The current algorithm can be written in pseudocode </p>
<pre><code>Iterate over list
if (current_element > maximum)
maximum = current_element
if (current element - maximum < drawdn)
drawdn = current_element-maxi... | 1 | 2016-07-27T11:52:57Z | [
"python",
"algorithm"
] |
Python - listing prime numbers from 1 to 1000 including 1 | 38,602,892 | <p>This program is for listing all the prime numbers between 1 and 1000, but my teacher would like me to include 1 in the results. </p>
<p>I tried to change it to say <code>if num >= 1:</code> and <code>for i in range(1,num)</code>, but then when I ran it, the only result was <code>1 is a prime number!</code>. Than... | 0 | 2016-07-27T02:48:29Z | 38,603,027 | <p>You should not write <code>for i in range(1, num):</code>, because <code>(any number) % 1 == 0</code>. <code>if num >= 1:</code> can also be removed, because it's always true.</p>
<p>Try the following code:</p>
<pre><code>for num in range(1, 1001):
for i in range(2, num):
if num % i == 0:
... | 1 | 2016-07-27T03:05:50Z | [
"python"
] |
Python - listing prime numbers from 1 to 1000 including 1 | 38,602,892 | <p>This program is for listing all the prime numbers between 1 and 1000, but my teacher would like me to include 1 in the results. </p>
<p>I tried to change it to say <code>if num >= 1:</code> and <code>for i in range(1,num)</code>, but then when I ran it, the only result was <code>1 is a prime number!</code>. Than... | 0 | 2016-07-27T02:48:29Z | 38,605,733 | <p>Leave your code as is and above the main for loop add:</p>
<pre><code>print("1 is a prime number")
</code></pre>
| 0 | 2016-07-27T06:53:19Z | [
"python"
] |
In PyQt4 how do i initiate a window | 38,602,951 | <p>Hello I am a student that is experimenting with GUI's and I was working in python making a simple log-in form and as I made the base layout I encountered an error where I could not solve the variables. This is the code: </p>
<pre><code>try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, ... | 0 | 2016-07-27T02:56:57Z | 38,638,767 | <p>Try making your <code>__init__</code> function in your <code>Ui_Dialog</code> class this:</p>
<pre><code>def __init__(self, window, parent=None):
self.addWidgets()
self.setupUi(self)
window.show()
</code></pre>
<p>Then, in your <code>main()</code> function, </p>
<pre><code>def main():
app = QtGui... | 0 | 2016-07-28T14:03:06Z | [
"python",
"user-interface",
"pyqt4"
] |
Python Class Method Error -- unbound requires instance | 38,602,963 | <p>I'm calling </p>
<pre><code>Hardware.gpio_active(True)
</code></pre>
<p>This is my Hardware class:</p>
<pre><code>import os
import glob
import time
import RPi.GPIO as GPIO
#class to manage hardware -- sensors, pumps, etc
class Hardware(object):
#global vars for sensor
base_dir = '/sys/bus/w1/devices/'
... | 0 | 2016-07-27T02:58:05Z | 38,602,987 | <p>Just replace <code>def gpio_active(active)</code> to <code>def gpio_active(cls, active)</code>.</p>
<p>Read more about <code>@classmethod</code> here: <a href="https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods" rel="nofollow">https://julien.danjou.info/blog/2013/guide-python-static-cla... | 1 | 2016-07-27T03:01:26Z | [
"python",
"class",
"static-methods"
] |
Python Class Method Error -- unbound requires instance | 38,602,963 | <p>I'm calling </p>
<pre><code>Hardware.gpio_active(True)
</code></pre>
<p>This is my Hardware class:</p>
<pre><code>import os
import glob
import time
import RPi.GPIO as GPIO
#class to manage hardware -- sensors, pumps, etc
class Hardware(object):
#global vars for sensor
base_dir = '/sys/bus/w1/devices/'
... | 0 | 2016-07-27T02:58:05Z | 38,602,998 | <p>You can use a <code>staticmethod</code>:</p>
<pre><code>@staticmethod
def gpio_active(active):
...
</code></pre>
<p>But it looks like you should be using a <code>classmethod</code> so you have access to other static/class methods for that class, or access to the class-level variables:</p>
<pre><code>@classme... | 1 | 2016-07-27T03:03:06Z | [
"python",
"class",
"static-methods"
] |
Getting a value from DataFrame based on other column value (PySpark) | 38,602,973 | <p>I have a Spark dataframe which I want to get the statistics</p>
<pre><code>stats_df = df.describe(['mycol'])
stats_df.show()
+-------+------------------+
|summary| mycol|
+-------+------------------+
| count| 300|
| mean| 2243|
| stddev| 319.419860456123|
| min| ... | 0 | 2016-07-27T02:59:00Z | 38,605,754 | <p>Ok let's consider the following example : </p>
<pre><code>from pyspark.sql.functions import rand, randn
df = sqlContext.range(1, 1000).toDF('mycol')
df.describe().show()
# +-------+-----------------+
# |summary| mycol|
# +-------+-----------------+
# | count| 999|
# | mean| 500... | 1 | 2016-07-27T06:54:42Z | [
"python",
"apache-spark",
"dataframe",
"pyspark",
"spark-dataframe"
] |
Print without unneeded Spaces | 38,602,982 | <p>I have just started out with Python, and am using Idle.</p>
<p>I put in:</p>
<pre><code>print("Professor Redwood: Right! So your name is",name,"!")
</code></pre>
<p>And got this in the console:</p>
<pre><code>Professor Redwood: Right! So your name is Chase !
</code></pre>
<p>Notice the spaces around the name <c... | 0 | 2016-07-27T03:00:20Z | 38,603,003 | <p>By default, the Python <code>print</code> function uses a separation set to a single space when printing arguments; you can easily override this by defining <code>sep=''</code> (i.e empty space):</p>
<pre><code>print("Professor Redwood: Right! So your name is",name,"!", sep='')
</code></pre>
<p>Which will now <cod... | 4 | 2016-07-27T03:03:29Z | [
"python"
] |
Print without unneeded Spaces | 38,602,982 | <p>I have just started out with Python, and am using Idle.</p>
<p>I put in:</p>
<pre><code>print("Professor Redwood: Right! So your name is",name,"!")
</code></pre>
<p>And got this in the console:</p>
<pre><code>Professor Redwood: Right! So your name is Chase !
</code></pre>
<p>Notice the spaces around the name <c... | 0 | 2016-07-27T03:00:20Z | 38,603,036 | <p>Another option using string concatenation:</p>
<pre><code>print("Professor Redwood: Right! So your name is"+ name + "!")
</code></pre>
<p>You could also do the following using string formatting</p>
<pre><code>print("Professor Redwood: Right! So your name is {0} !".format(name))
</code></pre>
| 3 | 2016-07-27T03:07:16Z | [
"python"
] |
Print without unneeded Spaces | 38,602,982 | <p>I have just started out with Python, and am using Idle.</p>
<p>I put in:</p>
<pre><code>print("Professor Redwood: Right! So your name is",name,"!")
</code></pre>
<p>And got this in the console:</p>
<pre><code>Professor Redwood: Right! So your name is Chase !
</code></pre>
<p>Notice the spaces around the name <c... | 0 | 2016-07-27T03:00:20Z | 38,603,080 | <p>What you're trying to do is concatenate strings which isn't exactly what commas in the <code>print</code> statement do. Instead, concatenation can be achieved several ways, the most common of which is to use the <code>+</code> operator.</p>
<pre><code>print("Professor Redwood: Right! So your name is " + name + "!")... | 1 | 2016-07-27T03:12:38Z | [
"python"
] |
Verify all character sequences exist in a string (Python 2+) | 38,603,046 | <p>So to verify a string is a subset of another, with python, you can either use the <code>set/frozensets</code> class and the <code>issubset</code> method - only works for single characters, or you can use a regular expression, which would basically be multiple lookahead assertions from the start of the line. I want t... | 1 | 2016-07-27T03:08:39Z | 38,603,152 | <p>So let's say you have two strings -- <code>userInput</code>, which might be very large, and <code>listOfChars</code>, which is relatively small. You want to check whether each element of <code>listOfChars</code> exists in <code>userInput</code>, without converting <code>userInput</code> into a <code>set</code>.</p>
... | 0 | 2016-07-27T03:20:52Z | [
"python",
"regex"
] |
Verify all character sequences exist in a string (Python 2+) | 38,603,046 | <p>So to verify a string is a subset of another, with python, you can either use the <code>set/frozensets</code> class and the <code>issubset</code> method - only works for single characters, or you can use a regular expression, which would basically be multiple lookahead assertions from the start of the line. I want t... | 1 | 2016-07-27T03:08:39Z | 38,603,156 | <p>If you want to verify that all character sequences in a collection are present in a given string, use <code>all()</code> with a generator expression:</p>
<pre><code>answer = all(word in string for word in bag)
</code></pre>
| 3 | 2016-07-27T03:21:25Z | [
"python",
"regex"
] |
Why my CreateAPIView does not show Product and store category field? | 38,603,154 | <p>I am designing an API for listing stores and create store. I could list store but while designing for creating store I am not getting product and store category field inspite of calling all Product and Store category serializer in Store Serializer.</p>
<p><strong>My shortened models look like</strong></p>
<pre><co... | 1 | 2016-07-27T03:21:03Z | 38,604,280 | <p>Remove <code>read_only=True</code> from the serializers that you wanna create entry of.
Like:</p>
<pre><code>product = ProductSerializers(read_only=True)
</code></pre>
<p>should be </p>
<pre><code>product = ProductSerializers()
</code></pre>
<p><code>read_only</code> will prevent it from written therefore i wont... | 2 | 2016-07-27T05:19:10Z | [
"python",
"django",
"api",
"python-3.x",
"django-rest-framework"
] |
Assign model method's return value to model attribute | 38,603,292 | <p>I have a class similar to this:</p>
<pre><code>class X(models.Model):
def hello(self):
return "Humpty Dumpty"
name = (hello,)
age = models.IntegerField()
</code></pre>
<p>now when I run in the console: <code>y.name</code> being <code>y</code> an instance, I get the following:</p>
<blockquote>
<p>(pro... | -1 | 2016-07-27T03:36:40Z | 38,603,359 | <p>That's invalid syntax. You need to do something like this:</p>
<pre><code>class X:
def __init__(self):
self.name = self.hello()
def hello(self):
return "Humpty Dumpty"
test = X()
print(test.name) # prints "Humpty Dumpty"
</code></pre>
| 0 | 2016-07-27T03:45:09Z | [
"python",
"django"
] |
Assign model method's return value to model attribute | 38,603,292 | <p>I have a class similar to this:</p>
<pre><code>class X(models.Model):
def hello(self):
return "Humpty Dumpty"
name = (hello,)
age = models.IntegerField()
</code></pre>
<p>now when I run in the console: <code>y.name</code> being <code>y</code> an instance, I get the following:</p>
<blockquote>
<p>(pro... | -1 | 2016-07-27T03:36:40Z | 38,603,371 | <p>If you just want to get the function called on attribute access, define name as property and provide your function <code>foo</code> to it:</p>
<pre><code>name = property(hello)
</code></pre>
<p>This will set the <code>fget</code> inside the property to your function <code>hello</code>. </p>
<pre><code>y = X()
y.n... | 2 | 2016-07-27T03:46:13Z | [
"python",
"django"
] |
Applying iterative function to every group in pandas DataFrame | 38,603,344 | <p>I have large pandas DataFrame with following format: </p>
<pre><code> prod_id timestamp text
150523 0006641040 9.393408e+08 text_1
150500 0006641040 9.408096e+08 text_2
150499 0006641041 1.009325e+09 text_3
150508 0006641041 1.018397e+09 text_4
150524 0006641042 1.025482e+09 text_5... | 2 | 2016-07-27T03:42:52Z | 38,603,385 | <p><strong>UPDATE:</strong></p>
<pre><code>In [324]: df
Out[324]:
prod_id timestamp text
150523 6641040 9.393408e+08 text_1
150500 6641040 9.408096e+08 text_2
150501 6641040 9.408096e+08 text_3
150499 6641041 1.009325e+09 text_3
150508 6641041 1.018397e+09 text_4
150524 6641042 1.025482... | 3 | 2016-07-27T03:46:57Z | [
"python",
"pandas",
"dataframe",
"functional-programming"
] |
historical stock price ten days before holidays for the past twenty years | 38,603,360 | <p>even though still as a noob, I have been enthusiastically learning Python for a while and here's a project I'm working on. I need to collect historical stock price ten days before US public holidays in the past twenty years and here's what I've done: (I used pandas_datareader and holidays here)</p>
<pre><code>start... | 2 | 2016-07-27T03:45:11Z | 38,603,568 | <p>This uses a dictionary and list comprehension to generate a set of ten U.S. workdays preceding each holiday. The stock prices for those days are then stored in a dictionary (keyed on holiday) as a list of prices, most recent first (h-1) and oldes last (h-10).</p>
<pre><code>from pandas.tseries.holiday import USFed... | 0 | 2016-07-27T04:09:38Z | [
"python",
"dictionary",
"yahoo-finance"
] |
Getting error in taking command line arguments in python | 38,603,427 | <p>I am using windows with python2.7. My program is quite simple. Taking an input via command line and checking if it is '5'. </p>
<p>Code:</p>
<pre><code>import unittest
import sys
a=sys.argv[1]
print a
class TestCase(unittest.TestCase):
"""My tests"""
def test_is_number_is_five(self):
self.ass... | 1 | 2016-07-27T03:53:50Z | 38,603,516 | <p><a href="https://docs.python.org/2/library/unittest.html#unittest.main" rel="nofollow"><code>unittest.main()</code></a> will obtain a list of tests to run from the command line. Hence it is trying to find a test named <code>5</code> in your module, but it fails because there is no such test.</p>
<p>To work around t... | 3 | 2016-07-27T04:03:01Z | [
"python"
] |
There is some advantage in accessing a text file in binary mode? | 38,603,477 | <p>We have a text file with several lines. The lines could end in CR+LF or LF. Each line have several fields separated by a field_separator (one or more characters). </p>
<p><strong>Sample 1:</strong></p>
<pre><code>field_separator = '\n'
with open('data.txt','r') as f:
for line in f:
line = line.split(fi... | 1 | 2016-07-27T03:58:13Z | 38,603,894 | <p>If you need to preserve the line ending style, you <em>must</em> use binary mode. Text mode will always translate line endings to be consistent.</p>
<p>If you're using Python 3 and you don't know the character encoding mode of the file, you can use binary mode to read the file without triggering decode errors. Deco... | 4 | 2016-07-27T04:44:21Z | [
"python",
"file-io"
] |
PyInstaller/Py2exe - include os.system call with third party scripts in single file compilation | 38,603,480 | <p>I'm using tkinter and pyinstaller/py2exe (either one would be fine), to create an executable as a single file from my python script. I can create the executable, and it runs as desired when not using the bundle option with py2exe or -F option with pyinstaller. I'm running third party python scripts within my code wi... | 2 | 2016-07-27T03:59:09Z | 38,665,906 | <p>After a couple of days of some tests, I was able to figure out how to work around this problem. Instead of <code>os.system</code>, I am using <code>subprocess.call("script.py arg1 arg2 ..., shell=True)</code> for each script I need to run. Also, I used <code>chmod +x</code> (in linux) before transferring the scripts... | 0 | 2016-07-29T19:04:19Z | [
"python",
"import",
"py2exe",
"pyinstaller",
"os.system"
] |
How to remove lines in a text file containing three columns based on a number in the third column? | 38,603,497 | <p>I am new to coding this kind of problem, I am open to the simplest tool or solution. None of the tools I know how to use seem to be able to open the file. I would prefer to avoid excel as I would like to eventually batch the process. I have tried for some time and been unable to do this simple task automatically. I ... | 0 | 2016-07-27T04:01:19Z | 38,603,660 | <p><strong>It is not clear whether you need a scripted answer to rerun the process or can use a manual process to do the manipulation</strong> (re-read your post and see that you would like to eventually script this out...regex should still give you a starting point even if you move past notepad++), but here is a quick... | 0 | 2016-07-27T04:21:17Z | [
"python",
"text",
"notepad++",
"batch-processing"
] |
How to remove lines in a text file containing three columns based on a number in the third column? | 38,603,497 | <p>I am new to coding this kind of problem, I am open to the simplest tool or solution. None of the tools I know how to use seem to be able to open the file. I would prefer to avoid excel as I would like to eventually batch the process. I have tried for some time and been unable to do this simple task automatically. I ... | 0 | 2016-07-27T04:01:19Z | 38,617,493 | <p>If you're looking to do this in python here is a starting point:</p>
<pre><code>linesWith3 = [] # Store lines with 3 in last column
with open("file.txt", "r") as f: # Open file
for line in f.readlines():
cols = line.split() # Split into array of columns
if "3" in cols[2]:
line... | 0 | 2016-07-27T15:35:32Z | [
"python",
"text",
"notepad++",
"batch-processing"
] |
Python -- how do I give a string value after I read the file | 38,603,522 | <p>I'm new to this community and this computer language. Recently I'm working on some practice and a question has bugged me for several days. Here is the question:
Read file test.txt(index: "CDEF","ABC","FIJK") in python, and re-align it into "ABC","CDEF","FIJK" , and given each character a value based on alphabet orde... | 2 | 2016-07-27T04:03:42Z | 38,603,637 | <p>You could use a nested comprehension:</p>
<pre><code>>>> lst = ["ABC", "CDEF", "FIJK"]
>>> sum((idx + 1) * sum(ord(letter) - 64 for letter in item) for idx, item in enumerate(lst))
150
</code></pre>
<p>If you want to use a regular for loop with an accumulator:</p>
<pre><code>total_sum = 0
for i... | 0 | 2016-07-27T04:18:54Z | [
"python",
"linux",
"python-2.7",
"ipython"
] |
Python -- how do I give a string value after I read the file | 38,603,522 | <p>I'm new to this community and this computer language. Recently I'm working on some practice and a question has bugged me for several days. Here is the question:
Read file test.txt(index: "CDEF","ABC","FIJK") in python, and re-align it into "ABC","CDEF","FIJK" , and given each character a value based on alphabet orde... | 2 | 2016-07-27T04:03:42Z | 38,607,152 | <p>First, let's assume that you have a file called <code>sample.txt</code> containing the following:</p>
<pre><code>CDEF
ABC
FIJK
</code></pre>
<p><strong>SCRIPT</strong></p>
<p>Here is the script to accomplish what (I think) you are after:</p>
<pre><code>with open('so.txt', 'r') as file:
lines = [x.replace('\n... | 1 | 2016-07-27T08:00:48Z | [
"python",
"linux",
"python-2.7",
"ipython"
] |
Using regex with fileinput gives error in Python | 38,603,532 | <p>Here is my code that I am using to replace some text in a file:</p>
<pre><code>for line in fileinput.input(the_file,inplace=True):
sys.stdout.write(line.re.sub('Begin.*?end', new_data))
</code></pre>
<p>This gives me the following error:</p>
<blockquote>
<p>AttributeError: 'str' object has no attribute 're'... | 1 | 2016-07-27T04:04:35Z | 38,603,564 | <p>Just do</p>
<pre><code>sys.stdout.write(re.sub('Begin.*?end', new_data, line))
</code></pre>
<p>The signature for <a href="https://docs.python.org/3.5/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a> is <code>re.sub(pattern, repl, string, count=0, flags=0)</code></p>
| 1 | 2016-07-27T04:08:58Z | [
"python",
"regex",
"python-3.x",
"python-3.5"
] |
Regex failing to search a string | 38,603,611 | <p>I am trying to do a regex search for <code>Location:</code> and get its location as follows,can anyone help to figure out why it doesn't print the location,expected output is shown below?</p>
<pre><code>output = """
Build: BOOT.FAN.1.2-00179-M1234LAB-1
Location: \\location\builds678\INTEGRATION\BOOT.... | 0 | 2016-07-27T04:15:11Z | 38,603,754 | <p>Your string appears to contain special characters such as backspace (<code>\b</code>). You probably need to escape the backslashes, or use a raw string:</p>
<pre><code>output = r"""
Build: BOOT.FAN.1.2-00179-M1234LAB-1
Location: \\location\builds678\INTEGRATION\BOOT.FAN.1.2-00179-M1234LAB-1
Comments:... | 1 | 2016-07-27T04:30:36Z | [
"python"
] |
Cannot run robotframework-hub | 38,603,653 | <p>I followed the installation instructions here <a href="https://github.com/boakley/robotframework-hub" rel="nofollow">robotframework-hub</a> and after running this command <code>python -m rfhub</code>
I get the following error <code>/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS... | 0 | 2016-07-27T04:20:27Z | 38,617,948 | <p>The issue was that I had a folder called 'robot' where I placed all my robot scripts. Once I renamed that folder the hub worked like a charm. Thank you @Bryan Oakley for the clues provided.</p>
| 1 | 2016-07-27T15:57:52Z | [
"python",
"robotframework"
] |
Django: trying to understand how the queryset attribute works in class-based generic views | 38,603,768 | <p>When using class-based generic views in Django, having a <code>queryset</code> attribute means to "restrict" the collection of object the view will operate on, right? </p>
<blockquote>
<p>If queryset is provided, that queryset will be used as the source of objects. (<a href="https://docs.djangoproject.com/en/1.9/... | 0 | 2016-07-27T04:31:51Z | 38,626,819 | <p>Yes, this is exactly what happens. Your queryset is used as the base queryset by the view's <code>get_object</code> method. It then applies an <a href="https://github.com/django/django/blob/master/django/views/generic/detail.py#L38" rel="nofollow">additional filter</a> to get a specific object (e.g., by ID):</p>
<p... | 2 | 2016-07-28T03:53:44Z | [
"python",
"django",
"generics"
] |
Trying to find the 1000th prime number | 38,603,777 | <p>I am trying to write a script in python to find the 1000th prime number. I don't understand why this isn't working here. Basically while the mod is less than the square root of the number and still has a remainder, the mod goes up by one. This should continue until the mod equals the square root of the number. Then ... | 1 | 2016-07-27T04:32:58Z | 38,604,053 | <p>I understand what you are trying to do, but unfortunately there were too many things wrong with your program. Here is a working version. I made minimal changes. Hopefully you can compare the below version with your own and see where you went wrong.</p>
<pre><code>import math
count=2
next_odd=3
next_prime=1
while ... | 2 | 2016-07-27T04:58:49Z | [
"python",
"primes"
] |
Trying to find the 1000th prime number | 38,603,777 | <p>I am trying to write a script in python to find the 1000th prime number. I don't understand why this isn't working here. Basically while the mod is less than the square root of the number and still has a remainder, the mod goes up by one. This should continue until the mod equals the square root of the number. Then ... | 1 | 2016-07-27T04:32:58Z | 38,604,072 | <p>(first, I assume the tick on the end of your code is a typo in your stack overflow post, not the code itself)</p>
<p>Consider what happens when <code>next_odd</code> is prime. This block:</p>
<pre><code>while b<float(math.sqrt(next_odd)):
if next_odd%b>0:
b+=1
if next_odd%b == 0:
... | 2 | 2016-07-27T05:01:00Z | [
"python",
"primes"
] |
KeyError exception type Django template tag | 38,603,924 | <p>I am trying to implement a template tag into my django project, and I a Key Error. I believe the has to do with getting context in the template tag under load_menu.py.</p>
<pre><code>Exception Type: KeyError
Exception Value:'request'
Error during template rendering
In template C:\Users\Eric Franzen\PycharmProjects... | 0 | 2016-07-27T04:47:09Z | 38,604,239 | <p>You are loading the tag, in the same template that is rendering the tag. This is why there is no context anymore.</p>
<p>The template that the tag renders <code>app/TikSys/sidenavbar.html</code>, should only have this:</p>
<pre><code><div class="col-md-2 NavBar">
{% for item in menus %}
<ul cl... | 1 | 2016-07-27T05:16:25Z | [
"python",
"django"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example... | 1 | 2016-07-27T04:49:28Z | 38,604,104 | <p>Does this work for you?</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
lines = ("a is a ", "a is not e","b is b", "b is not f")
for keyword in keywords:
for line in lines:
if keyword in line:
keyword2_exist = False
for keyword2 in keywords2:
... | 0 | 2016-07-27T05:03:02Z | [
"python",
"if-statement"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example... | 1 | 2016-07-27T04:49:28Z | 38,604,172 | <p>@joon answers with an answer in the style of your question; here's a couple of other ideas:</p>
<p>Loop over the <em>lines</em> first, because the code should work like the question "should I print this line?" for each line.</p>
<pre><code>keywords = ("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a... | 1 | 2016-07-27T05:09:42Z | [
"python",
"if-statement"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example... | 1 | 2016-07-27T04:49:28Z | 38,604,194 | <p>If I understand correctly, you want only "lines" that have a value from <code>keywords</code>, but not <code>keywords2</code>. In that case simply do:</p>
<pre><code>for line in a:
if [x for x in keywords if x in line] and not [x for x in keywords2 if x in line]:
print line
</code></pre>
<p><code>[x fo... | 2 | 2016-07-27T05:12:26Z | [
"python",
"if-statement"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example... | 1 | 2016-07-27T04:49:28Z | 38,604,261 | <p>This could probably work better for you:</p>
<pre><code>import re
keywords =("a","b","c","d")
keywords2 = ("e","f","g")
pattern = re.compile(r'^(\w+)\s+is\s+(?:not\s+)?(\w+)')
for line in ("a is a", "a is not e","b is b", "b is not f"):
for key1, key2 in pattern.findall(line):
if key1 in keywords and... | 0 | 2016-07-27T05:17:48Z | [
"python",
"if-statement"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example... | 1 | 2016-07-27T04:49:28Z | 38,604,428 | <p>You should learn some functional programming, Try this:</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a is not e","b is b", "b is not f")
for line in a:
if not any(map(lambda x: x in line, keywords2)):
if any(map(lambda x: x in line, keywords)):
prin... | 0 | 2016-07-27T05:30:22Z | [
"python",
"if-statement"
] |
Weird behavior with numpy arrays of arrays in typing | 38,604,045 | <p>Why is the first array being converted entirely to string type, while the individual types of the second array remain the same? How would I force the first array (<code>np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])</code>) to consist of a <code>dtype = np.int64</code> array and a <code>dtype = np.str_<... | 2 | 2016-07-27T04:58:21Z | 38,604,226 | <p>The reason is that if the sub-arrays have compatible shapes, numpy creates an extra dimension for their shared shape. This is the case in your first example, and if you check the <code>shape</code> of that object you will see it is <code>(2, 3)</code>. In your second example the sub-array shapes cannot be reconcil... | 1 | 2016-07-27T05:15:14Z | [
"python",
"numpy"
] |
Weird behavior with numpy arrays of arrays in typing | 38,604,045 | <p>Why is the first array being converted entirely to string type, while the individual types of the second array remain the same? How would I force the first array (<code>np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])</code>) to consist of a <code>dtype = np.int64</code> array and a <code>dtype = np.str_<... | 2 | 2016-07-27T04:58:21Z | 38,604,232 | <p>Look at the outputs:</p>
<pre><code>>>> np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])
array([['1', '2', '3'],
['a', 'bb', 'ccc']],
dtype='<U11')
>>> np.array([np.array([1,2,3,4]), np.array(["a", "bb", "ccc"])])
array([array([1, 2, 3, 4]), array(['a', 'bb', 'ccc'],
... | 1 | 2016-07-27T05:15:55Z | [
"python",
"numpy"
] |
Weird behavior with numpy arrays of arrays in typing | 38,604,045 | <p>Why is the first array being converted entirely to string type, while the individual types of the second array remain the same? How would I force the first array (<code>np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])</code>) to consist of a <code>dtype = np.int64</code> array and a <code>dtype = np.str_<... | 2 | 2016-07-27T04:58:21Z | 38,604,272 | <p><code>np.array</code> sometimes tries to be 'too smart'. But the basic principle is that it tries to create the highest dimensional array that can with the input. Only when it fails does it resort to making a simpler array of dtype=object. Remember, the original intent was to produce a multidimensional array of n... | 2 | 2016-07-27T05:18:49Z | [
"python",
"numpy"
] |
custom authentication not working in django-tastypie | 38,604,125 | <p>My question is, how do i write my own custom authentication correctly??</p>
<p>i have tried to follow this:
<a href="http://django-tastypie.readthedocs.org/en/latest/authentication.html#implementing-your-own-authentication-authorization" rel="nofollow">http://django-tastypie.readthedocs.org/en/latest/authenticatio... | 0 | 2016-07-27T05:05:44Z | 38,605,062 | <p>You missed <code>return</code> and You don't call parent <code>is_authenticated</code> function:</p>
<pre><code>def is_authenticated(self, request, **kwargs):
super(CustomBasicAuthentication, self).is_authenticated(request, **kwargs)
if 'admin' == request.user.username:
return prepareResponce({'log... | 1 | 2016-07-27T06:14:30Z | [
"python",
"django",
"authentication",
"tastypie"
] |
How to startup my python script automatically in ubuntu | 38,604,386 | <p><strong><em>I need my own gnome applet python program to run automatically when system starts.</em></strong></p>
| -2 | 2016-07-27T05:27:17Z | 38,605,773 | <p>All you need to do is put a script in <code>/etc/init.d/</code> and it will run on startup.</p>
<p>Also, be sure to put the interpreter at the top of the file, such as <code>#! /bin/bash</code>, and be sure to make it executable with <code>chmod +x /etc/init.d/myscript</code></p>
<p><strong>Example file</strong></... | 0 | 2016-07-27T06:55:47Z | [
"python",
"linux"
] |
Is there any way to check from url if that file is already downloaded? | 38,604,499 | <blockquote>
<p>Suppose I have two urls which redirect to same file(hosted on 2 servers separately) and I've downloaded the file from one of the url. Is it possible to avoid downloading the same file again when I click the other url (checking in the system, if the file exists)?</p>
<p>The main aim is to optimize... | 0 | 2016-07-27T05:35:44Z | 38,604,591 | <p>It's not possible to calculate a md5 hash without downloading the file, no.</p>
<p>What you can do though, is to check if the redirected url is the same, using the <a href="https://docs.python.org/2.6/library/urllib.html#urllib.urlopen" rel="nofollow"><code>geturl()</code></a> method:</p>
<pre><code>if urlopen(url... | 1 | 2016-07-27T05:42:33Z | [
"python",
"md5"
] |
Is there any way to check from url if that file is already downloaded? | 38,604,499 | <blockquote>
<p>Suppose I have two urls which redirect to same file(hosted on 2 servers separately) and I've downloaded the file from one of the url. Is it possible to avoid downloading the same file again when I click the other url (checking in the system, if the file exists)?</p>
<p>The main aim is to optimize... | 0 | 2016-07-27T05:35:44Z | 38,604,631 | <p>You can make use of the <a href="https://en.wikipedia.org/wiki/HTTP_ETag" rel="nofollow"><strong>Etag</strong></a> HTTP header.</p>
<blockquote>
<p>An ETag is an opaque identifier assigned by a web server to a specific
version of a resource found at a URL. If the resource representation
at that URL ever chang... | 2 | 2016-07-27T05:45:19Z | [
"python",
"md5"
] |
Scraping Yahoo Finance Balance Sheet with Python | 38,604,506 | <p>My question is a follow-up question to one asked <a href="http://stackoverflow.com/questions/35439105/scrape-yahoo-finance-income-statement-with-python">here</a>.</p>
<p>The function: </p>
<blockquote>
<p>periodic_figure_values()</p>
</blockquote>
<p>seems to work fine except in the case where the name of a lin... | 3 | 2016-07-27T05:36:11Z | 38,604,725 | <p>You could change the function so that it accepts a regular expression instead of a plain string. Then you can search for <code>^Long Term Debt</code> to make sure there's no text before that. All you need to do is to change</p>
<pre><code>if cell.text.strip() != yahoo_figure:
</code></pre>
<p>to</p>
<pre><code>if... | 0 | 2016-07-27T05:52:24Z | [
"python",
"regex",
"web-scraping",
"beautifulsoup",
"python-requests"
] |
Scraping Yahoo Finance Balance Sheet with Python | 38,604,506 | <p>My question is a follow-up question to one asked <a href="http://stackoverflow.com/questions/35439105/scrape-yahoo-finance-income-statement-with-python">here</a>.</p>
<p>The function: </p>
<blockquote>
<p>periodic_figure_values()</p>
</blockquote>
<p>seems to work fine except in the case where the name of a lin... | 3 | 2016-07-27T05:36:11Z | 38,604,731 | <p>The easiest would be to use a <strong><code>try/except</code></strong> combination using the raised <code>ValueError</code>:</p>
<pre><code>import requests, bs4, re
def periodic_figure_values(soup, yahoo_figure):
values = []
pattern = re.compile(yahoo_figure)
title = soup.find("strong", text=pattern) ... | 1 | 2016-07-27T05:52:53Z | [
"python",
"regex",
"web-scraping",
"beautifulsoup",
"python-requests"
] |
Error during XML parsing | 38,604,551 | <p>I am trying to do XML parsing and get the data for <code>file_name</code> and <code>file_path</code> but running into below error ,can anyone help to figure out why and how to resolve it?</p>
<p>INPUT XML:-</p>
<pre><code><?xml version="1.0" ?>
<contents>
<build>
<name>modem&l... | 2 | 2016-07-27T05:39:21Z | 38,605,345 | <p>From the documentation:</p>
<blockquote>
<p>Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the elementâs text content. Element.get() accesses the elementâs attributes:</p>
... | 1 | 2016-07-27T06:32:27Z | [
"python",
"xml"
] |
Error during XML parsing | 38,604,551 | <p>I am trying to do XML parsing and get the data for <code>file_name</code> and <code>file_path</code> but running into below error ,can anyone help to figure out why and how to resolve it?</p>
<p>INPUT XML:-</p>
<pre><code><?xml version="1.0" ?>
<contents>
<build>
<name>modem&l... | 2 | 2016-07-27T05:39:21Z | 38,606,489 | <p>Since <code>device_programmer</code> is not direct child of the root element, you need to add <code>.//</code> at the beginning. The <code>.</code> indicates that the XPath is relative to the context element (the root element in this case), and <code>//</code> is abbreviated syntax for <code>descendant-or-self</code... | 0 | 2016-07-27T07:27:04Z | [
"python",
"xml"
] |
black box script execution? | 38,604,598 | <p>I have a client that would like to examine results of a script I have written. I don't want the client to see the inner workings of the script or I lose my value to them but I want them to be able to run it as many times as they want and observe the results. </p>
<p>I am not sure if there is a general solution to t... | 1 | 2016-07-27T05:43:00Z | 38,605,047 | <p>How about writing scripts outputs to files ,and construct a web interface that consumes this files and displays them in read-only mode? </p>
<p>For example in R you can use
sink()
to route the output messages to a file, you then construct a web interface that simply displays this file.</p>
| 2 | 2016-07-27T06:13:08Z | [
"python",
"machine-learning",
"simulation"
] |
black box script execution? | 38,604,598 | <p>I have a client that would like to examine results of a script I have written. I don't want the client to see the inner workings of the script or I lose my value to them but I want them to be able to run it as many times as they want and observe the results. </p>
<p>I am not sure if there is a general solution to t... | 1 | 2016-07-27T05:43:00Z | 38,605,152 | <p>In Python you can easily use Flask to provide a restful API that the client can send their HTTP request with their parameters and you can provide them with the results.</p>
<p>It is very easy to convert a Python function into a web server. It is as easy as this function:</p>
<pre><code>@app.route('/geo', methods=[... | 1 | 2016-07-27T06:20:40Z | [
"python",
"machine-learning",
"simulation"
] |
Unicode() in python 3 | 38,604,655 | <p>I have python 2x code which uses unicode() function before searching ascii strings in unicode list. Short of exception catching or evaluating python version, what is the best way to port this code so it works in both python 2 and 3? </p>
| 0 | 2016-07-27T05:47:04Z | 38,605,313 | <p>Sometimes this dirty hack is enough</p>
<pre><code>try:
unicode
except NameError:
unicode = str
</code></pre>
<p>@honi wrote good advice, use <a href="https://pypi.python.org/pypi/six" rel="nofollow">six</a>.</p>
| 2 | 2016-07-27T06:29:57Z | [
"python",
"unicode"
] |
for loop is run more times then specified. | 38,604,673 | <p>I have been trying to make a drop down menu in pygame. I have a method that that takes a list of strings and renders them to the screen using a for loop. The for loop is shown below.</p>
<pre><code> spacer = 0
for text in range(5):
spacer += 30
rect = pygame.Rect(0, spacer, 10... | 0 | 2016-07-27T05:48:40Z | 38,605,055 | <p>Every time your menu is rendered, you're appending to <code>menu_items_rect_list</code>. Whatever you put in that list will stay there indefinitely. If you want the list to be empty at the start of the frame, you need to clear it yourself.</p>
| 1 | 2016-07-27T06:13:39Z | [
"python",
"for-loop",
"methods",
"pygame"
] |
for loop is run more times then specified. | 38,604,673 | <p>I have been trying to make a drop down menu in pygame. I have a method that that takes a list of strings and renders them to the screen using a for loop. The for loop is shown below.</p>
<pre><code> spacer = 0
for text in range(5):
spacer += 30
rect = pygame.Rect(0, spacer, 10... | 0 | 2016-07-27T05:48:40Z | 38,837,126 | <p>The answer to my question is very obvious once I really thought about what was happing. Since I'm calling the method that contains the for-loop in a while loop, the for-loop is being run multiple times. The two solutions I've used for this problem are:
1. setting a limit to how many items can be in the list:</p>
<... | 0 | 2016-08-08T19:31:13Z | [
"python",
"for-loop",
"methods",
"pygame"
] |
Convert list into list of lists | 38,604,805 | <p>I want to convert list into list of list. Example:</p>
<pre><code>my_list = ['banana', 'mango', 'apple']
</code></pre>
<p>I want:</p>
<pre><code>my_list = [['banana'], ['mango'], ['apple']]
</code></pre>
<p>I tried:</p>
<pre><code>list(list(my_list))
</code></pre>
| -3 | 2016-07-27T05:57:34Z | 38,604,810 | <p>Use list comprehension</p>
<pre><code>[[i] for i in lst]
</code></pre>
<p>It iterates over each item in the list and put that item into a new list.</p>
<p><em>Example:</em></p>
<pre><code>>>> lst = ['banana', 'mango', 'apple']
>>> [[i] for i in lst]
[['banana'], ['mango'], ['apple']]
</code></p... | 6 | 2016-07-27T05:58:13Z | [
"python",
"list"
] |
Convert list into list of lists | 38,604,805 | <p>I want to convert list into list of list. Example:</p>
<pre><code>my_list = ['banana', 'mango', 'apple']
</code></pre>
<p>I want:</p>
<pre><code>my_list = [['banana'], ['mango'], ['apple']]
</code></pre>
<p>I tried:</p>
<pre><code>list(list(my_list))
</code></pre>
| -3 | 2016-07-27T05:57:34Z | 38,604,912 | <p>Try This one Liner:-</p>
<pre><code>map(lambda x:[x], my_list)
</code></pre>
<p><strong>Result</strong></p>
<pre><code>In [1]: map(lambda x:[x], my_list)
Out[1]: [['banana'], ['mango'], ['apple']]
</code></pre>
| 2 | 2016-07-27T06:04:36Z | [
"python",
"list"
] |
Which Exception class is the most suitable for flagging excess number of calls to a function? | 38,604,885 | <p>I have a database connection object, and I want to restrict/enforce max number of calls to it's write operation (function). I have mocked it in tests, and have overridden the write method to monitor calls to it.</p>
<p>However, I am confused about what error to raise when it's called more than the max number allowe... | 0 | 2016-07-27T06:02:39Z | 38,605,509 | <p>If you supply too many arguments to a function you get something like this:</p>
<pre><code>TypeError: function-name takes exactly n arguments (m given)
</code></pre>
<p>So you could do the same to mirror Python. You should probably be careful when you call <code>raise</code> to ensure that your exception string i... | 0 | 2016-07-27T06:41:50Z | [
"python",
"python-2.7",
"exception",
"semantics"
] |
Pandas indexing after grouping | 38,604,953 | <p>that might be a very simple question, but I am trying to understand how grouping and indexing works in pandas. </p>
<p>Let's say, I have a DataFrame with following data: </p>
<pre><code>df = pd.DataFrame(data={
'p_id': [1, 1, 1, 2, 3, 3, 3, 4, 4],
'rating': [5, 3, 2, 2, 5, 1, 3, 4, 5]
})
</code></pre>
<p>... | 2 | 2016-07-27T06:07:40Z | 38,605,016 | <p>It's just an index name...</p>
<p>Demo:</p>
<pre><code>In [46]: df
Out[46]:
p_id rating
0 1 5
1 1 3
2 1 2
3 2 2
4 3 5
5 3 1
6 3 3
7 4 4
8 4 5
In [47]: df.index.name = 'AAA'
</code></pre>
<p>pay attention at the index na... | 2 | 2016-07-27T06:11:06Z | [
"python",
"pandas",
"dataframe"
] |
python pandas from itemset to dataframe | 38,604,963 | <p>What is the more scalable way to go from an itemset list::</p>
<pre><code>itemset = [['a', 'b'],
['b', 'c', 'd'],
['a', 'c', 'd', 'e'],
['d'],
['a', 'b', 'c'],
['a', 'b', 'c', 'd']]
</code></pre>
<p>To a dataframe of this kind ::</p>
<pre><code>>>> d... | 2 | 2016-07-27T06:08:04Z | 38,605,085 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>get_dummies</code></a>:</p>
<pre><code>print (pd.DataFrame(itemset))
0 1 2 3
0 a b None None
1 b c d None
2 a c d e
3 d None None None
4 a b ... | 2 | 2016-07-27T06:16:45Z | [
"python",
"numpy",
"pandas"
] |
python pandas from itemset to dataframe | 38,604,963 | <p>What is the more scalable way to go from an itemset list::</p>
<pre><code>itemset = [['a', 'b'],
['b', 'c', 'd'],
['a', 'c', 'd', 'e'],
['d'],
['a', 'b', 'c'],
['a', 'b', 'c', 'd']]
</code></pre>
<p>To a dataframe of this kind ::</p>
<pre><code>>>> d... | 2 | 2016-07-27T06:08:04Z | 38,607,800 | <p>Here's an almost vectorized approach -</p>
<pre><code>items = np.concatenate(itemset)
col_idx = np.fromstring(items, dtype=np.uint8)-97
lens = np.array([len(item) for item in itemset])
row_idx = np.repeat(np.arange(lens.size),lens)
out = np.zeros((lens.size,lens.max()+1),dtype=int)
out[row_idx,col_idx] ... | 0 | 2016-07-27T08:33:41Z | [
"python",
"numpy",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.