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 Python equivalent of close() in Java? | 38,745,269 | <p>In Java, using the <code>close()</code> method frees resources by removing out of scope objects. I am confused as to what is the Python equivalent for this? </p>
<ul>
<li>Does Python's garbage collector automatically do this?</li>
<li>Is it the <code>del</code> method?</li>
<li>Should I use the <code>with</code> st... | 3 | 2016-08-03T13:37:09Z | 38,745,393 | <blockquote>
<p>Should I use the with statement?</p>
</blockquote>
<p>Yes, according to <a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">the documentation</a>:</p>
<blockquote>
<p>It is good practice to use the with keyword when dealing with file objects. This h... | 0 | 2016-08-03T13:43:33Z | [
"java",
"python",
"python-2.7",
"python-3.x",
"resources"
] |
What is the Python equivalent of close() in Java? | 38,745,269 | <p>In Java, using the <code>close()</code> method frees resources by removing out of scope objects. I am confused as to what is the Python equivalent for this? </p>
<ul>
<li>Does Python's garbage collector automatically do this?</li>
<li>Is it the <code>del</code> method?</li>
<li>Should I use the <code>with</code> st... | 3 | 2016-08-03T13:37:09Z | 38,745,426 | <p>You will find your answer <a href="http://stackoverflow.com/questions/1316767/how-can-i-explicitly-free-memory-in-python">here</a>: place gc.collect() before your code.</p>
| 0 | 2016-08-03T13:44:43Z | [
"java",
"python",
"python-2.7",
"python-3.x",
"resources"
] |
What is the Python equivalent of close() in Java? | 38,745,269 | <p>In Java, using the <code>close()</code> method frees resources by removing out of scope objects. I am confused as to what is the Python equivalent for this? </p>
<ul>
<li>Does Python's garbage collector automatically do this?</li>
<li>Is it the <code>del</code> method?</li>
<li>Should I use the <code>with</code> st... | 3 | 2016-08-03T13:37:09Z | 38,745,600 | <p>ICart's comment is spot on for many different situations. However, regarding the creation and disposal of objects in general, I think <a href="http://stackoverflow.com/questions/6315244/how-to-give-object-away-to-python-garbage-collection">this other thread</a> provides a pretty good explanation of how python handle... | 0 | 2016-08-03T13:52:29Z | [
"java",
"python",
"python-2.7",
"python-3.x",
"resources"
] |
In DRF(django-rest-framework), null value in column "author_id" violates not-null constraint. What should i do? | 38,745,280 | <p>I made django project through DRF.
<a href="http://i.stack.imgur.com/g2cxY.png" rel="nofollow">enter image description here</a></p>
<p>From that window, i clicked post so then it did not worked.</p>
<p><strong>traceback</strong></p>
<pre><code>#I almost omitted other codes
Environment:
Request Method: POST
Reque... | 1 | 2016-08-03T13:37:52Z | 38,745,996 | <p>You could not create Comment instance with null in <code>author</code> field.
For fix it you can add author when you create new comment </p>
<pre><code>class CommentSerializer(serializers.HyperlinkedModelSerializer):
...................
def create(self, validated_data):
validated_data['author'] = self.context... | 0 | 2016-08-03T14:08:55Z | [
"python",
"django",
"django-rest-framework"
] |
concatenating 2 list in python | 38,745,327 | <p>this is what I have. I want to concatenate this 2 list together</p>
<pre><code>first_name = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie',
'Carl', 'Ned', 'Barney', 'Lenny', 'Otto', 'Seymour']
last_name = ['Simpson', 'Simpson', 'Simpson', 'Simpson', 'Simpson',
'Carlson', 'Flanders', 'Gumble', 'Leonard', 'Mann', 'Skin... | -1 | 2016-08-03T13:39:45Z | 38,745,346 | <p>your loop actually iterates through the elements, not the indices</p>
<pre><code>for (f, l) in zip(first_name, last_name):
print (f + " " + l)
</code></pre>
| 6 | 2016-08-03T13:40:46Z | [
"python",
"string",
"list"
] |
concatenating 2 list in python | 38,745,327 | <p>this is what I have. I want to concatenate this 2 list together</p>
<pre><code>first_name = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie',
'Carl', 'Ned', 'Barney', 'Lenny', 'Otto', 'Seymour']
last_name = ['Simpson', 'Simpson', 'Simpson', 'Simpson', 'Simpson',
'Carlson', 'Flanders', 'Gumble', 'Leonard', 'Mann', 'Skin... | -1 | 2016-08-03T13:39:45Z | 38,745,458 | <p><strong>EDIT:</strong> in case of using indexes, but iterating through elemenets is better</p>
<p>The two lists have same length so:</p>
<pre><code>for i in range(len(first_name)):
print(first_name[i] + " " + last_name[j])
</code></pre>
| 0 | 2016-08-03T13:45:58Z | [
"python",
"string",
"list"
] |
concatenating 2 list in python | 38,745,327 | <p>this is what I have. I want to concatenate this 2 list together</p>
<pre><code>first_name = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie',
'Carl', 'Ned', 'Barney', 'Lenny', 'Otto', 'Seymour']
last_name = ['Simpson', 'Simpson', 'Simpson', 'Simpson', 'Simpson',
'Carlson', 'Flanders', 'Gumble', 'Leonard', 'Mann', 'Skin... | -1 | 2016-08-03T13:39:45Z | 38,745,825 | <p>You can use Python <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow">map function</a> in the following way to get the output you want:</p>
<pre><code>print(map(lambda f,l: f + " " + l, first_name, last_name))
</code></pre>
| 0 | 2016-08-03T14:01:19Z | [
"python",
"string",
"list"
] |
Saving a list of UUID numbers to a .csv file in python | 38,745,365 | <p>I am trying to create a .csv file of UUID numbers. I see how to make a single UUID number in python but can't get the correct syntax to make 50 numbers and save them to a .csv file. I've googled and found many ways to create .csv files and how to use For loop but none seem to pertain to this particular application... | 2 | 2016-08-03T13:41:50Z | 38,745,428 | <p>Just combine <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">a csv writer</a> with <a href="https://docs.python.org/2/library/uuid.html" rel="nofollow">an uuid generator</a></p>
<pre><code>import csv
import uuid
with open('uuids.csv', 'w') as csvfile:
uuidwriter = csv.writer(csvfile)
for... | -1 | 2016-08-03T13:44:47Z | [
"python",
"csv",
"for-loop",
"uuid"
] |
Saving a list of UUID numbers to a .csv file in python | 38,745,365 | <p>I am trying to create a .csv file of UUID numbers. I see how to make a single UUID number in python but can't get the correct syntax to make 50 numbers and save them to a .csv file. I've googled and found many ways to create .csv files and how to use For loop but none seem to pertain to this particular application... | 2 | 2016-08-03T13:41:50Z | 38,745,728 | <p>a csv is basically a text file, and since yours have only one column you won't need separators :</p>
<pre><code>import uuid
with open('uuids.csv', 'w') as f:
f.writelines(str(uuid.uuid1()) + "\n" for i in range(50))
</code></pre>
| -1 | 2016-08-03T13:57:28Z | [
"python",
"csv",
"for-loop",
"uuid"
] |
facebook integration error, django-allauth | 38,745,579 | <p>I want to integrante django allauth to my website, I followed the tutorial but I am facing an error while I use ElasticBeanStalk servers but not on localhost.</p>
<pre><code>Reverse for 'facebook_login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
</code></pre>
<p>Here is my <st... | 0 | 2016-08-03T13:51:12Z | 38,751,004 | <p>Found the answer on another post : Facebook SDK egg which allauth relies on was missing on the webserver ElasticBeanStalk.</p>
<p>You can learn more on this post : <a href="http://stackoverflow.com/questions/11065610/using-django-allauth?rq=1">using django-allauth</a></p>
| 0 | 2016-08-03T18:21:50Z | [
"python",
"django",
"django-allauth"
] |
simplest python equivalent to R's grepl | 38,745,710 | <p>Is there a simple/one-line python equivalent to R's <code>grepl</code> function?</p>
<pre><code>strings = c("aString", "yetAnotherString", "evenAnotherOne")
grepl(pattern = "String", x = strings) #[1] TRUE TRUE FALSE
</code></pre>
| 4 | 2016-08-03T13:56:45Z | 38,745,802 | <p>You can use list comprehension:</p>
<pre><code>strings = ["aString", "yetAnotherString", "evenAnotherOne"]
["String" in i for i in strings]
#Out[76]: [True, True, False]
</code></pre>
<p>Or use <code>re</code> module:</p>
<pre><code>import re
[bool(re.search("String", i)) for i in strings]
#Out[77]: [True, True... | 9 | 2016-08-03T14:00:27Z | [
"python",
"python-2.7"
] |
simplest python equivalent to R's grepl | 38,745,710 | <p>Is there a simple/one-line python equivalent to R's <code>grepl</code> function?</p>
<pre><code>strings = c("aString", "yetAnotherString", "evenAnotherOne")
grepl(pattern = "String", x = strings) #[1] TRUE TRUE FALSE
</code></pre>
| 4 | 2016-08-03T13:56:45Z | 38,745,835 | <p>A one-line equivalent is possible, using <code>re</code>:</p>
<pre><code>import re
strings = ['aString', 'yetAnotherString', 'evenAnotherOne']
[re.search('String', x) for x in strings]
</code></pre>
<p>This wonât give you boolean values, but truthy results that are just as good.</p>
| 2 | 2016-08-03T14:01:44Z | [
"python",
"python-2.7"
] |
simplest python equivalent to R's grepl | 38,745,710 | <p>Is there a simple/one-line python equivalent to R's <code>grepl</code> function?</p>
<pre><code>strings = c("aString", "yetAnotherString", "evenAnotherOne")
grepl(pattern = "String", x = strings) #[1] TRUE TRUE FALSE
</code></pre>
| 4 | 2016-08-03T13:56:45Z | 38,746,108 | <p>If you do not need a regular expression, but are just testing for the existence of a susbtring in a string:</p>
<pre><code>["String" in x for x in strings]
</code></pre>
| 1 | 2016-08-03T14:13:40Z | [
"python",
"python-2.7"
] |
How to merge/join two resultset/table in django? | 38,745,759 | <p>I'm trying to display a list of employees that are part of the same company. So for example with the given URL localhost/app/company-slug/ I'd like to show a list of rows where there are the details of all three models:</p>
<p>| first_name | last_name | company-slug | employee_status | employee_type |</p>
<p>With ... | 0 | 2016-08-03T13:59:06Z | 38,745,985 | <p>do you have a views.py which serves these models? you could easily use the django <a href="https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#render" rel="nofollow">render</a> function to serve all three of these models to the dom. this is a rather comprehensive, all encompassing process but I'd be more th... | 1 | 2016-08-03T14:08:21Z | [
"python",
"django",
"join",
"orm",
"merge"
] |
How to merge/join two resultset/table in django? | 38,745,759 | <p>I'm trying to display a list of employees that are part of the same company. So for example with the given URL localhost/app/company-slug/ I'd like to show a list of rows where there are the details of all three models:</p>
<p>| first_name | last_name | company-slug | employee_status | employee_type |</p>
<p>With ... | 0 | 2016-08-03T13:59:06Z | 38,746,000 | <p>I assume you already had an object for <code>company</code> in current page, getting the employees is really easy:</p>
<pre><code>employees = Employee.objects.filter(company=company)
for employee in employees:
print employee.employeeprofile.first_name
print employee.employeeprofile.last_name
print emplo... | 1 | 2016-08-03T14:09:07Z | [
"python",
"django",
"join",
"orm",
"merge"
] |
Unable to handle "HTTP Badstatus line" exception | 38,745,812 | <p>I want to handle <code>http.client.BadStatusLine: ''</code> exception.
I am on python3. My code is </p>
<pre><code>import http.client
try:
req = urllib.request.Request(url, headers={'User-Agent': 'Chrome/51'})
html = urllib.request.urlopen(req).read()
soup = BeautifulSoup(html,"html.parser")
return... | -1 | 2016-08-03T14:00:49Z | 38,746,006 | <p>You need to make up your mind :-). You can either use <code>http.client</code> or <code>urllib.request</code>, but you should not use one and then try to catch errors from the other. If you want to stick with urllib.request, the class to catch is <code>urllib.error.HTTPError</code>.</p>
<p>Perhaps it may be more op... | 0 | 2016-08-03T14:09:17Z | [
"python",
"python-3.x"
] |
Prompting with previous input from sys.stdin | 38,745,956 | <p>I have a standard server-client TCP setup. The basic idea is a chat system. Looking at only the client's side of the conversation, the client prompts the user for input with:</p>
<pre><code>sys.stdout.write('<%s> ' % username)
sys.stdout.flush()
</code></pre>
<p>using the following logic:</p>
<pre><code>whi... | 1 | 2016-08-03T14:07:19Z | 38,891,727 | <p>As an alternative to implementing your own editing line input function as discussed in the question's comments, consider this approach: Change the scrolling region to leave out the screen's bottom line (the user input line) and enter the scrolling region only temporarily to output incoming server messages. <a href="... | 0 | 2016-08-11T08:57:32Z | [
"python",
"sockets",
"io",
"buffer",
"stdin"
] |
Prompting with previous input from sys.stdin | 38,745,956 | <p>I have a standard server-client TCP setup. The basic idea is a chat system. Looking at only the client's side of the conversation, the client prompts the user for input with:</p>
<pre><code>sys.stdout.write('<%s> ' % username)
sys.stdout.flush()
</code></pre>
<p>using the following logic:</p>
<pre><code>whi... | 1 | 2016-08-03T14:07:19Z | 38,906,306 | <p>The problem seems to be that you are letting the messages from the other user interrupt the typing. I recommend you either only listen to one thing at a time (when the user is typing you let him finish and press enter before listening for remote messages) <em>or</em> you listen for the user's input one key at a tim... | 0 | 2016-08-11T21:18:08Z | [
"python",
"sockets",
"io",
"buffer",
"stdin"
] |
Prompting with previous input from sys.stdin | 38,745,956 | <p>I have a standard server-client TCP setup. The basic idea is a chat system. Looking at only the client's side of the conversation, the client prompts the user for input with:</p>
<pre><code>sys.stdout.write('<%s> ' % username)
sys.stdout.flush()
</code></pre>
<p>using the following logic:</p>
<pre><code>whi... | 1 | 2016-08-03T14:07:19Z | 38,907,018 | <p>To implement your solution, you will have to read from stdin in an unbuffered way. readline() and read() block until an EOL or EOF. You need the data from stdin BEFORE the return key is pressed. To achieve that, this might prove helpful: <a href="http://code.activestate.com/recipes/134892-getch-like-unbuffered-chara... | 1 | 2016-08-11T22:22:51Z | [
"python",
"sockets",
"io",
"buffer",
"stdin"
] |
Embedding python in C++, Segmentation fault | 38,745,999 | <p>I am trying to embed python script in a c++ application.
To try out the integration, I made a pilot code:</p>
<pre><code>// c++ code
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
if (argc < 3)
{
printf("Usage: exe_name python_source function_name\n"... | 0 | 2016-08-03T14:09:02Z | 38,791,595 | <p>It might be easier to use <code>boost::python</code> or the code generated by cython.</p>
<p>The main culprit seems to be the missing </p>
<pre><code>PySys_SetArgv(argc, wargs);
</code></pre>
<p>where <code>wargs</code> contains the arguments as wide character strings. Without it, relative imports do not work.</p... | 0 | 2016-08-05T14:23:55Z | [
"python",
"c++",
"embedding"
] |
Strange Python numpy array indexing behaviour | 38,746,001 | <p>I have the following array</p>
<pre><code>[0. 100. 200. 300. 400. -500. -400. -300. -200. -100.]
</code></pre>
<p>which I'm trying to rearrange to be from smallest to largest.</p>
<p>I find the turning point from pos to neg which is stored in j.</p>
<p>If I print the following I get </p>
<pre><code>>>prin... | -3 | 2016-08-03T14:09:09Z | 38,746,049 | <p>Almost everywhere through Python the behavior is <code>[)</code>, meaning the left (or start) argument is inclusive and the right (or end) argument is exclusive. Be it list slicing, string slicing, the <code>range</code> function,
etc.</p>
<p>It only makes sense for <code>numpy</code> to follow this convention.</p... | 3 | 2016-08-03T14:11:07Z | [
"python",
"arrays",
"numpy"
] |
PyQt - QFileDialog - directly browse to a folder? | 38,746,002 | <p>Is there any way to directly browse to a folder using QFileDialog?</p>
<p>Meaning, instead of double clicking on each folder while navigating to the destination folder, simply enter the path somewhere or use a hotkey like the one (Shift+Command+G) in Finder on Mac OS X.</p>
<p>Thanks!</p>
<p><strong>EDIT:</strong... | 2 | 2016-08-03T14:09:10Z | 38,746,444 | <p>Below you'll find a simple test which opens directly the dialog at a certain path, in this case will be the current working directory. If you want to open directly another path you can just use python's directory functions included in os.path module:</p>
<pre><code> import sys
import os
from PyQt4 import QtGui
... | 0 | 2016-08-03T14:27:28Z | [
"python",
"qt",
"pyqt"
] |
PyQt - QFileDialog - directly browse to a folder? | 38,746,002 | <p>Is there any way to directly browse to a folder using QFileDialog?</p>
<p>Meaning, instead of double clicking on each folder while navigating to the destination folder, simply enter the path somewhere or use a hotkey like the one (Shift+Command+G) in Finder on Mac OS X.</p>
<p>Thanks!</p>
<p><strong>EDIT:</strong... | 2 | 2016-08-03T14:09:10Z | 38,746,526 | <p>In <code>PyQt 4</code>, you're able to just add a <code>QFileDialog</code> to construct a window that has a path textfield embedded inside of the dialog. You can paste your path in here.</p>
<pre><code>QtGui.QFileDialog.getOpenFileName(self, 'Select file') # For file.
</code></pre>
<p>For selecting a directory: <... | 1 | 2016-08-03T14:31:30Z | [
"python",
"qt",
"pyqt"
] |
PyQt - QFileDialog - directly browse to a folder? | 38,746,002 | <p>Is there any way to directly browse to a folder using QFileDialog?</p>
<p>Meaning, instead of double clicking on each folder while navigating to the destination folder, simply enter the path somewhere or use a hotkey like the one (Shift+Command+G) in Finder on Mac OS X.</p>
<p>Thanks!</p>
<p><strong>EDIT:</strong... | 2 | 2016-08-03T14:09:10Z | 38,748,766 | <p>If you use the static <code>QFileDialog</code> functions, you'll get a <em>native</em> file-dialog, and so you'll be limited to the functionality provided by the platform. You can consult the documentation for your platform to see if the functionality you want is available.</p>
<p>If it's not available, you'll have... | 1 | 2016-08-03T16:12:32Z | [
"python",
"qt",
"pyqt"
] |
Error: error during read: Connection reset by peer | 38,746,042 | <p>I have openocd running and am sending a simple reset command to my board.
However I am getting this error:</p>
<p><strong>Info : accepting 'telnet' connection from 4444</strong></p>
<p><strong>Error: error during read: Connection reset by peer</strong></p>
<p><strong>Info : dropped 'telnet' connection</strong></p... | 0 | 2016-08-03T14:10:48Z | 38,890,971 | <p>Your try using a here document on the command line works fine because the <code>reset</code> command is followed by a <code>\n</code> character, which the <code>send('reset')</code> lacks. Correct: <code>send('reset\n')</code>.</p>
| 0 | 2016-08-11T08:21:35Z | [
"python",
"sockets",
"telnet",
"netcat"
] |
openpyxl trendline and R-squared value | 38,746,053 | <p>I'm trying to add "linear" trend-line to my excel chart and display R-squared value using openpyxl, but i cannot find any example. </p>
<p>Below is python code that generates chart shown on image without trend-line and R-squared formula <a href="http://i.stack.imgur.com/8H3MH.jpg" rel="nofollow">chart image</a>.</p... | 0 | 2016-08-03T14:11:22Z | 38,750,136 | <p>It's basically impossible to document all the possibilities for charts so you will occasionally have to dive into the XML of a relevant chart to find out how it's done. That said, trendlines are pretty easy to do.</p>
<pre><code>from openpyxl.chart.trendline import Trendline
line.trendline = Trendline()
</code></pr... | 1 | 2016-08-03T17:27:49Z | [
"python",
"excel",
"openpyxl"
] |
Vectorizing a Nested Loop | 38,746,087 | <p>I am looking to vectorize a nested loop, which will work on a list of 300,000 lists, with each of these lists containing 3 values. The nested loop compares the values of each of the lists with the corresponding values in the other lists, and will only append the list indices which have corresponding values having a ... | 5 | 2016-08-03T14:12:51Z | 38,746,251 | <p>Convert to NumPy array to make it easier to use NumPy funcs thereafter. Then, two approaches could be suggested. </p>
<p><strong>Approach #1</strong></p>
<p>NumPy broadcasting could be used to extend those to 3D arrays and perform the operations in a vectorized manner. Thus, we would have an implementation like so... | 3 | 2016-08-03T14:19:34Z | [
"python",
"numpy",
"vectorization"
] |
Vectorizing a Nested Loop | 38,746,087 | <p>I am looking to vectorize a nested loop, which will work on a list of 300,000 lists, with each of these lists containing 3 values. The nested loop compares the values of each of the lists with the corresponding values in the other lists, and will only append the list indices which have corresponding values having a ... | 5 | 2016-08-03T14:12:51Z | 38,746,508 | <p>Look into scipy.spatial; it has a lot of functionality for solving such spatial queries efficiently; <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query_pairs.html#scipy.spatial.cKDTree.query_pairs" rel="nofollow">KDTrees</a> in particular, ie:</p>
<pre><code>import scipy.spatia... | 2 | 2016-08-03T14:30:44Z | [
"python",
"numpy",
"vectorization"
] |
Get attribute using xpath | 38,746,090 | <p>Given HTML structure like so:</p>
<pre><code><dd itemprop="actors">
<span itemscope="" itemtype="http://schema.org/Person">
<a itemprop="name">Yumi Kazama</a>, </span>
<span itemscope="" itemtype="http://schema.org/Person">
<a itemprop="name"&g... | -1 | 2016-08-03T14:12:58Z | 38,751,978 | <p>Assuming your html file is <strong>test.html</strong> the following should work:</p>
<pre><code>from lxml import html
with open(r'E:/backup/GoogleDrive/py/scrapy/test.html', "r") as f:
page = f.read()
tree = html.fromstring(page)
names = tree.xpath("//a[@itemprop='name']//text()")
print names
</code></pre>
| 1 | 2016-08-03T19:19:10Z | [
"python",
"xpath",
"scrapy"
] |
Django WhiteNoise collectstatic repeatedly post-processes CSS files | 38,746,109 | <p>I am successfully using WhiteNoise in my Django project.</p>
<p>My problem is when running the <code>collectstatic</code> command. WhiteNoise post-processes all my .css files, even when they have not changed. It does not unnecessarily post-process .js or .png files, only .css files.</p>
<p>This seems like a bug in... | 0 | 2016-08-03T14:13:41Z | 38,748,935 | <p>This is a feature of Django, rather than a bug in WhiteNoise: CSS files can contain references to other static files (usually images) and the cache-busting mechanism causes the names of these image files to change whenever their contents change. So the processed output of the CSS file can change even if the original... | 1 | 2016-08-03T16:21:06Z | [
"python",
"django",
"static-files"
] |
Removing objects that have changed from a Python set | 38,746,185 | <p>Given this program:</p>
<pre><code>class Obj:
def __init__(self, a, b):
self.a = a
self.b = b
def __hash__(self):
return hash((self.a, self.b))
class Collection:
def __init__(self):
self.objs = set()
def add(self, obj):
self.objs.add(obj)
def find(self... | 1 | 2016-08-03T14:17:12Z | 38,746,264 | <p>You are changing the objects (ie changing the objects' hash) <em>after</em> they were added to the set. </p>
<p>When <code>remove</code> is called, it can't find that hash in the set because it was changed after it was calculated (when the objects were originally added to the set). </p>
| 3 | 2016-08-03T14:19:54Z | [
"python",
"python-3.x"
] |
Removing objects that have changed from a Python set | 38,746,185 | <p>Given this program:</p>
<pre><code>class Obj:
def __init__(self, a, b):
self.a = a
self.b = b
def __hash__(self):
return hash((self.a, self.b))
class Collection:
def __init__(self):
self.objs = set()
def add(self, obj):
self.objs.add(obj)
def find(self... | 1 | 2016-08-03T14:17:12Z | 38,746,268 | <p>This is not a bug in Python, your code is violating a principle of sets: that the <em>hash value must not change</em>. By mutating your object attributes, the hash changes and the set can no longer reliably locate the object in the set.</p>
<p>From the <a href="https://docs.python.org/3/reference/datamodel.html#obj... | 5 | 2016-08-03T14:20:03Z | [
"python",
"python-3.x"
] |
Python: use of same IV for encryption and decryption in AES | 38,746,213 | <p>I struggle to understand the correct use of an IV (Initialization Vector) when encrypting data in AES.</p>
<p>Precisely, I'm not sure where to store my randomly generated IV: in my script, the data will be encrypted, then saved to a file, then the program will terminate. During the next session, the previously save... | 0 | 2016-08-03T14:18:27Z | 38,746,551 | <p>The IV itself is not sensitive data; its just used to scramble the state of the first cipher-text block and the scrambling is not recoverable from the IV itself (the key adds in the "secret" factor). </p>
<p>For "proper" chaining modes the IV is separate from the cipher text (you need the initial IV for both encryp... | -2 | 2016-08-03T14:32:33Z | [
"python",
"encryption",
"aes",
"initialization-vector"
] |
Python Celery subtask group not executing | 38,746,257 | <p>I'm trying to use Celery to handle background tasks. I currently have the following setup:</p>
<pre><code>@app.task
def test_subtask(id):
print('test_st:', id)
@app.task
def test_maintask():
print('test_maintask')
g = group(test_subtask.s(id) for id in range(10))
g.delay()
</code></pre>
<p><code>... | 0 | 2016-08-03T14:19:42Z | 38,752,053 | <p>Sigh... just found out the answer, I used the following to configure my Celery app:</p>
<pre><code>app = Celery('celery_app', broker='<my_broker_here>')
</code></pre>
<p>Strangely enough, this is not being picked up in the task itself... that is, </p>
<pre><code>print('test_maintask using broker', app.conf.... | 0 | 2016-08-03T19:24:38Z | [
"python",
"celery"
] |
Why is this xpath expression not working? | 38,746,273 | <p>Scrapy is a web crawler and I have created a spider.
I want the spider to create 2 html files with the body of the 2 links.
The html files created are empty.</p>
<pre><code> import scrapy
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
class DmozSpider(scrapy.Spider):
... | -4 | 2016-08-03T14:20:10Z | 38,746,874 | <p>Please revisit the <a href="http://doc.scrapy.org/en/1.1/intro/tutorial.html" rel="nofollow">Scrapy tutorial</a> and double-check; your example is basically a verbatim copy of <code>dmoz_spider.py</code>.</p>
<p>First of all, note that <code>xpath()</code> returns a selector list. Calling <code>extract()</code> on ... | -1 | 2016-08-03T14:45:35Z | [
"python",
"xpath",
"scrapy"
] |
Ansible mysql_user with Percona 57 and RHEL7 | 38,746,361 | <p>I am trying to use ansible mysql_user module on RHEL7 with Percona 57 though
but it fails on</p>
<blockquote>
<p>the python mysqldb module is required</p>
</blockquote>
<p>I have installed full Percona 57
I`ve also tried to install yum install MySQL-python. (1.2.3)
but in Python when i try to import MySQLdb i ... | 0 | 2016-08-03T14:24:17Z | 38,758,674 | <p>so finally i've found out it was SELinux blocking ports ><</p>
| 0 | 2016-08-04T04:48:39Z | [
"python",
"mysql",
"ansible",
"percona",
"rhel7"
] |
Most efficient way to write to file conditionally? | 38,746,421 | <p>I would like to write a string to a file only if it's not presently in the file.</p>
<p>My first thought was to do something like this, however it's not writing anything to the file.</p>
<pre><code>with open("FILE PATH", "a+") as database:
for lines in database.read():
if 'MY STRING' in lines:
... | 1 | 2016-08-03T14:26:44Z | 38,746,697 | <p>Using <code>database.read()</code> will read your text file and return a single string containing the entire file. Looping over this string will return each character within that string individually, so you won't find <code>'MY STRING'</code> in it. Simply look for <code>'MY STRING'</code> within the file as a whole... | 1 | 2016-08-03T14:38:19Z | [
"python"
] |
How come when I import of two functions from the same module, the import works only for one the two? | 38,746,450 | <p><strong>Intro</strong><br>
I am running a python script on an cluster. I run everything in virtualenv and in the code I am importing two functions from the same module (written in SC_module.py):</p>
<p>ex. SC_module.py</p>
<pre><code>def funA():
def funB():
</code></pre>
<p>In the script script.py I have the fo... | -1 | 2016-08-03T14:27:53Z | 38,747,175 | <p>Remove file: <code>SC_module.pyc</code>, and try run it again.</p>
| 0 | 2016-08-03T14:59:27Z | [
"python",
"virtualenv",
"hpc"
] |
How come when I import of two functions from the same module, the import works only for one the two? | 38,746,450 | <p><strong>Intro</strong><br>
I am running a python script on an cluster. I run everything in virtualenv and in the code I am importing two functions from the same module (written in SC_module.py):</p>
<p>ex. SC_module.py</p>
<pre><code>def funA():
def funB():
</code></pre>
<p>In the script script.py I have the fo... | -1 | 2016-08-03T14:27:53Z | 38,748,821 | <p>I suggest that you print out your import path list and check that they match what you think they are, in both environments:</p>
<pre><code>>>> import sys
>>> for d in sys.path:
... print d
</code></pre>
<p>Plus: </p>
<pre><code>import SC_module
print dir(SC_module)
</code></pre>
<p>to see w... | 0 | 2016-08-03T16:15:03Z | [
"python",
"virtualenv",
"hpc"
] |
Django: 'BaseTable' object does not support indexing | 38,746,460 | <p>I'm migrating my project to Django 1.8 and I am receiving an error related to 'johnny cache. Specifically in 'johnny/cache.py/'.</p>
<p><strong>Error:</strong> lib/python2.7/site-packages/johnny/cache.py", line 87, in get_tables_for_query
tables = set([v[0] for v in getattr(query, 'alias_map', {}).values()])</p... | 0 | 2016-08-03T14:28:28Z | 38,748,073 | <p>Found your problem when I looked a bit further into your library.</p>
<p>From the <a href="https://pythonhosted.org/johnny-cache/" rel="nofollow">Johnny Cache documentation</a>:</p>
<blockquote>
<p>It works with Django 1.1 thru 1.4 and python 2.4 thru 2.7.</p>
</blockquote>
<p>From your question:</p>
<blockquo... | 1 | 2016-08-03T15:38:28Z | [
"python",
"django",
"indexing",
"django-1.8",
"django-johnny-cache"
] |
How to correctly install pyinstaller | 38,746,462 | <p>I have attempted to install pyinstaller (on Ubuntu 16.0.4) using pip:</p>
<pre><code>pip3 install pyinstaller
Collecting pyinstaller
Using cached PyInstaller-3.2.tar.gz
Collecting setuptools (from pyinstaller)
Using cached setuptools-25.1.3-py2.py3-none-any.whl
Building wheels for collected packages: pyinstall... | 0 | 2016-08-03T14:28:29Z | 38,747,467 | <p>You may check if your PATH contains site-packages directory.</p>
<p>In Windows, this is the path.</p>
<p><strong>C:\Python27\Lib\site-packages.</strong> </p>
<p>You can do the equivalent for ubuntu. Let me know if it works.</p>
| -1 | 2016-08-03T15:12:54Z | [
"python",
"pip",
"pyinstaller"
] |
How to correctly install pyinstaller | 38,746,462 | <p>I have attempted to install pyinstaller (on Ubuntu 16.0.4) using pip:</p>
<pre><code>pip3 install pyinstaller
Collecting pyinstaller
Using cached PyInstaller-3.2.tar.gz
Collecting setuptools (from pyinstaller)
Using cached setuptools-25.1.3-py2.py3-none-any.whl
Building wheels for collected packages: pyinstall... | 0 | 2016-08-03T14:28:29Z | 38,748,447 | <p><code>pyinstaller</code> appears to have installed correctly, but the command is not available on <code>PATH</code>. You need to locate where the executable was placed. This will depend on your system configuration, if you're using virtualenv, and other system and usage dependent factors.</p>
<p>One thing you could... | 0 | 2016-08-03T15:56:38Z | [
"python",
"pip",
"pyinstaller"
] |
Create variations of a string | 38,746,525 | <p>I generated random strings of 16-characters each and added them to a list using the following:</p>
<pre><code>import random
strings = []
for x in range(0, 99):
strings.append(''.join(random.choice('0123456789ABCDEF') for i in range(16)))
</code></pre>
<p>This worked as expected. Now, for each generated string, I... | 0 | 2016-08-03T14:31:30Z | 38,747,794 | <p>Create an iterator for the indices of the two characters you want to stay the same using <code>itertools.combinations</code></p>
<pre><code>>>> from itertools import combinations
>>> s = 'ABC123'
>>> for indices in combinations(range(len(s)), 2):
... print ''.join([s[x] if x in indice... | 1 | 2016-08-03T15:26:42Z | [
"python",
"string",
"itertools"
] |
Automatic Code Update for Exception Handling in Python | 38,746,545 | <p>This older syntax was removed in Python 3:</p>
<pre><code>try:
...
except MyException, exc: # Don't do that!
...
</code></pre>
<p>New</p>
<pre><code>try:
...
except MyException as exc:
...
</code></pre>
<p>I checked how many times the old syntax gets used in the code I work on:</p>
<pre><code... | 0 | 2016-08-03T14:32:26Z | 38,746,546 | <p>... answering my own question. I found the <code>futurize</code> from <a href="http://python-future.org/automatic_conversion.html" rel="nofollow">python-future</a>:</p>
<pre><code>futurize --write --nobackups --fix lib2to3.fixes.fix_except src/mylib/
</code></pre>
<p>It supports a lot of other fixes, but today I w... | 1 | 2016-08-03T14:32:26Z | [
"python",
"python-3.x"
] |
Reading from a file deletes the last letter of the last string in the document? | 38,746,561 | <p>I am writing code which take a .txt doc and stores each word on each line of that .txt file in a list of strings. However my code decides it wants to delete the last letter of the last string for some random reason, can anyone tell me why?</p>
<p>My code: </p>
<pre><code>import sys
listofStr = []
print (" ")
fn... | 1 | 2016-08-03T14:33:08Z | 38,746,592 | <p>The last line doesn't have a linebreak in it, so when you do</p>
<pre><code> strings = myLine[:-1]
</code></pre>
<p>you strip off the last char in the line, no matter what it is, and you kill off an actual character.</p>
| 1 | 2016-08-03T14:34:26Z | [
"python",
"file",
"python-3.x"
] |
Reading from a file deletes the last letter of the last string in the document? | 38,746,561 | <p>I am writing code which take a .txt doc and stores each word on each line of that .txt file in a list of strings. However my code decides it wants to delete the last letter of the last string for some random reason, can anyone tell me why?</p>
<p>My code: </p>
<pre><code>import sys
listofStr = []
print (" ")
fn... | 1 | 2016-08-03T14:33:08Z | 38,746,656 | <p>You are missing the final newline on your file, so the <code>strings = myLine[:-1]</code> removes the final character. If you replace this with <code>strings = myLine.rstrip()</code> that will remove any trailing whitespace on the line but won't remove that final character.</p>
| 1 | 2016-08-03T14:37:05Z | [
"python",
"file",
"python-3.x"
] |
Reading from a file deletes the last letter of the last string in the document? | 38,746,561 | <p>I am writing code which take a .txt doc and stores each word on each line of that .txt file in a list of strings. However my code decides it wants to delete the last letter of the last string for some random reason, can anyone tell me why?</p>
<p>My code: </p>
<pre><code>import sys
listofStr = []
print (" ")
fn... | 1 | 2016-08-03T14:33:08Z | 38,746,677 | <p>Change this:</p>
<pre><code>while (len(myLine)>0) :
strings = myLine[:-1]
listofStr.append(strings)
myLine = f.readline()
</code></pre>
<p>to this:</p>
<pre><code>while myLine.strip() :
strings = myLine.strip()
listofStr.append(strings)
myLine = f.readline()
</code></pre>
| 1 | 2016-08-03T14:37:45Z | [
"python",
"file",
"python-3.x"
] |
Reading from a file deletes the last letter of the last string in the document? | 38,746,561 | <p>I am writing code which take a .txt doc and stores each word on each line of that .txt file in a list of strings. However my code decides it wants to delete the last letter of the last string for some random reason, can anyone tell me why?</p>
<p>My code: </p>
<pre><code>import sys
listofStr = []
print (" ")
fn... | 1 | 2016-08-03T14:33:08Z | 38,746,689 | <p>You're slicing the last line which doesn't have the newline character:</p>
<pre><code>strings = myLine[:-1]
</code></pre>
<p>To fix this you can just manually go to your file and append an extra line. Or change said line to <code>strings = myLine.strip()</code>. There is no need to slice the string manually since ... | 2 | 2016-08-03T14:38:03Z | [
"python",
"file",
"python-3.x"
] |
Using variables from other python files | 38,746,578 | <p>I'm having some problems with this:</p>
<p>I have two files: random and random2</p>
<p>random has this:</p>
<pre><code> import random2
print(random2.verb_list)
print(random2.x)
</code></pre>
<p>random2 has this:</p>
<pre><code> verb_list = ['x', 'y', 'z']
other_list = ['1', '2', '3']
somet... | -1 | 2016-08-03T14:33:59Z | 38,747,012 | <p>The variable <code>x</code> is not created until the <code>Main()</code> function is run. Importing a module means that <code>__name__</code> isn't set to <code>__main__</code>, so the function is never executed.</p>
<p>You must execute the Main() function. Put <code>random2.Main()</code> in the file <code>random.p... | 1 | 2016-08-03T14:51:49Z | [
"python"
] |
pyplot axes title not showing | 38,746,759 | <p>I have written this code to check object bounding box but when I give <code>title</code> to the <code>axes</code>, it doesn't show up. (I was going to give the file number as title).</p>
<pre><code>#!/home/ckim/anaconda2/bin/python
#%pylab
import os.path as osp
import sys
import cv2
import matplotlib
import matplot... | 0 | 2016-08-03T14:40:55Z | 38,748,790 | <p>There is a call to <code>plt.show()</code> in <code>move_figure</code> which means the figure is shown. As this is a <a href="http://matplotlib.org/faq/howto_faq.html#use-show" rel="nofollow">blocking command</a>, no further code will be run until you close this figure. As a result, the title is not set until the f... | 0 | 2016-08-03T16:13:37Z | [
"python",
"matplotlib",
"pycaffe"
] |
concurrent.futures.ThreadPoolExecutor max_workers can't be 0 | 38,746,782 | <p>If I spin up a <code>ThreadPoolExecutor(max_workers=0)</code> it works with Python3.4 and Python2.7 but raises an error with Python3.5 and Python3.6. I'm trying to create a <code>ThreadPoolExecutor</code> where I want to ensure that no task gets added to the threadpool. Currently, I created a subclass from <code>Thr... | 0 | 2016-08-03T14:41:36Z | 39,059,864 | <p>Simply put, with Python3.5 and 3.6, the <code>max_workers</code> argument is not allowed to be <code>0</code> for sanity reasons. So my solution was to make a more "mocky" version of the ThreadPoolExecutor that would record the activity of the ThreadPool in case something is added to the queue and then make assertio... | 0 | 2016-08-21T00:29:51Z | [
"python",
"python-3.x",
"concurrent.futures"
] |
How to parse rss using beautifulsoup? | 38,746,838 | <p>I have this rss: <a href="http://socialminisite.com/tnuvabot/?cat=190&feed=rss2" rel="nofollow">http://socialminisite.com/tnuvabot/?cat=190&feed=rss2</a> .</p>
<p>How can I get this value:</p>
<pre><code><div class="title">×צר×××:</div>
</code></pre>
<p>From this RSS:</p>
<pre><code><... | 0 | 2016-08-03T14:43:45Z | 38,754,022 | <p>To get what you want, all you need is a simple select using <em>lxml</em> or <em>html5lib</em> as the parser:</p>
<pre><code>In [6]: import requests
In [7]: from bs4 import BeautifulSoup
In [8]: url = "http://socialminisite.com/tnuvabot/?cat=190&feed=rss2"
In [9]: soup = BeautifulSoup(requests.get(url).cont... | 0 | 2016-08-03T21:35:08Z | [
"python",
"xml",
"beautifulsoup"
] |
Why do I keep getting TypeError? | 38,746,845 | <p>This is the error I am getting, but only when I try to run the code using <code>argparse</code></p>
<p>Error:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "portscanner.py", line 63, in <module>
Main()
File "http://portscanner.py", line 58, in Main
... | -1 | 2016-08-03T14:44:05Z | 38,746,976 | <p>You are passing in a <code>dst=</code> keyword argument to the <code>IPy.IP()</code> class:</p>
<pre><code>from IPy import IP
# ...
IP(dst=ip_addr)
</code></pre>
<p>That class doesn't define such a keyword argument. Looking at the <a href="https://github.com/autocracy/python-ipy/" rel="nofollow">project document... | 0 | 2016-08-03T14:50:18Z | [
"python",
"init",
"scapy"
] |
Plotting of MFCC power spectrogram Python | 38,746,889 | <p>Can anyone help me plot a <code>mfcc</code> feature as a power spectrogram! I am only able to plot <code>mfcc</code> coefficients which is not represented in time domain. I want to plot <code>mfcc</code> feature in time domain. I also tried applying DCT to convert it into time domain! </p>
<pre><code>from python_sp... | 0 | 2016-08-03T14:46:15Z | 38,783,427 | <p>Pxx, freqs, bins, im = plt.specgram(signal, NFFT=NFFT, Fs=2,noverlap=100, cmap=None) #signal is 1D array of .wav file</p>
| 0 | 2016-08-05T07:20:44Z | [
"python",
"python-2.7",
"matplotlib",
"scipy"
] |
Should put in requirements.txt dependency targeting packege in pypi or github repo? | 38,747,052 | <p>Are there any technical indications to prefer referencing a package on PyPI over the original source on GitHub in <code>requirements.txt</code>?</p>
<p>Only thing that comes to my mind is that freezing a package on a certain version is very cumbersome with GitHub (<code>package==1.0.0</code> vs <code>git://github.c... | -1 | 2016-08-03T14:53:49Z | 38,748,416 | <p>PyPI is the accepted defacto location for distributing <em>released versions</em> of a package, and it could be that not all Python packaging tools support installing from GitHub.</p>
<p>And as you already noticed, for <code>pip</code> to support GitHub you must have <code>git</code> installed; this limits portabil... | 1 | 2016-08-03T15:55:10Z | [
"python",
"github",
"pypi"
] |
Portable python script: Is it possible to include third party libraries in script? | 38,747,073 | <p>I have a Python script which uses open source third party libraries for geoprocessing (OGR and Shapely). My plan is to execute this script on a computer without having to install the required libraries.</p>
<p>I know that there are tools such as py2exe available for this purpose. However, compiling an executable fi... | 0 | 2016-08-03T14:54:46Z | 38,747,314 | <p>You can export your libraries using pip and embbed them into your application.</p>
<p>pip wheel requires the wheel package to be installed, which provides the "bdist_wheel" setuptools extension that it uses.</p>
<p>To build wheels for your requirements and all their dependencies to a local directory:</p>
<pre><co... | 0 | 2016-08-03T15:05:49Z | [
"python"
] |
Portable python script: Is it possible to include third party libraries in script? | 38,747,073 | <p>I have a Python script which uses open source third party libraries for geoprocessing (OGR and Shapely). My plan is to execute this script on a computer without having to install the required libraries.</p>
<p>I know that there are tools such as py2exe available for this purpose. However, compiling an executable fi... | 0 | 2016-08-03T14:54:46Z | 38,747,336 | <p>If your third party lib does not have any dependencies you can get the source files (.py) put into your project folder and use it as package by using import, else it has dependencies your project size grow more better create exe for your script. </p>
| 0 | 2016-08-03T15:06:49Z | [
"python"
] |
how to find if an element from an array is a substring of a string? | 38,747,178 | <p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p>
<pre><code>s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]
if any(surnames) in s:
print("We've got a famous mathematician!")
</code>... | 0 | 2016-08-03T14:59:38Z | 38,747,260 | <p>Consider <code>if any(i in surnames for i in s.split()):</code>.</p>
<p>This will work for both <code>s = "Leonhard Euler"</code> and <code>s = "Euler Leonhard"</code>.</p>
| 5 | 2016-08-03T15:03:10Z | [
"python"
] |
how to find if an element from an array is a substring of a string? | 38,747,178 | <p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p>
<pre><code>s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]
if any(surnames) in s:
print("We've got a famous mathematician!")
</code>... | 0 | 2016-08-03T14:59:38Z | 38,747,285 | <pre><code>s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]
for surname in surnames:
if(surname in s):
print("We've got a famous mathematician!")
</code></pre>
<p>Loops through each string in surnames and checks if its a substring of s</p>
| 1 | 2016-08-03T15:04:22Z | [
"python"
] |
how to find if an element from an array is a substring of a string? | 38,747,178 | <p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p>
<pre><code>s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]
if any(surnames) in s:
print("We've got a famous mathematician!")
</code>... | 0 | 2016-08-03T14:59:38Z | 38,747,299 | <p>Actually I didn't test the the code but should be something like this (if I understood the question):</p>
<pre><code>for surname in surnames:
if surname in s:
print("We've got a famous mathematician!")
</code></pre>
| 0 | 2016-08-03T15:04:59Z | [
"python"
] |
how to find if an element from an array is a substring of a string? | 38,747,178 | <p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p>
<pre><code>s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]
if any(surnames) in s:
print("We've got a famous mathematician!")
</code>... | 0 | 2016-08-03T14:59:38Z | 38,747,342 | <p>If you don't need to know which surname is in s you can do that using any and list comprehension:</p>
<pre><code>if any(surname in s for surname in surnames):
print("We've got a famous mathematician!")
</code></pre>
| 1 | 2016-08-03T15:07:04Z | [
"python"
] |
how to find if an element from an array is a substring of a string? | 38,747,178 | <p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p>
<pre><code>s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]
if any(surnames) in s:
print("We've got a famous mathematician!")
</code>... | 0 | 2016-08-03T14:59:38Z | 38,747,444 | <p>You can use isdisjoint attribute of sets after splitting the string to list to check if the two lists casted to sets have any elements in common.</p>
<pre><code>s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]
strlist = s.split()
if not set(strlist).isdisjoint(surnames):
... | 2 | 2016-08-03T15:11:52Z | [
"python"
] |
How to create a symmetric matrix from a numpy 1D array the most efficient way | 38,747,311 | <p>I have a 1d <code>np.array</code>. Its length may vary according to user input, but it will always stay single-dimesional.
Please advise if there is an efficient way to create a symmetric 2d <code>np.array</code> from it? By 'symmetric' I mean that its elements will be according to the rule k[i, j] = k[j, i].</p>
<... | 0 | 2016-08-03T15:05:36Z | 38,747,900 | <p><strong>Interpretation #1</strong></p>
<p>Seems like you are reusing elements at each row. So, with that sort of idea, an implementation using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> would be -</p>
<pre><code>def symmetricize(arr1D):
... | 1 | 2016-08-03T15:31:08Z | [
"python",
"arrays",
"numpy",
"matrix",
"linear-algebra"
] |
How to create a symmetric matrix from a numpy 1D array the most efficient way | 38,747,311 | <p>I have a 1d <code>np.array</code>. Its length may vary according to user input, but it will always stay single-dimesional.
Please advise if there is an efficient way to create a symmetric 2d <code>np.array</code> from it? By 'symmetric' I mean that its elements will be according to the rule k[i, j] = k[j, i].</p>
<... | 0 | 2016-08-03T15:05:36Z | 38,750,253 | <p>What you're looking for is a special Toeplitz matrix and easy to generate with scipy</p>
<pre><code>from numpy import concatenate, zeros
from scipy.linalg import toeplitz
toeplitz([1,2,3])
array([[1, 2, 3],
[2, 1, 2],
[3, 2, 1]])
</code></pre>
<p>another special matrix interpretation can be using H... | 4 | 2016-08-03T17:34:19Z | [
"python",
"arrays",
"numpy",
"matrix",
"linear-algebra"
] |
Return Function description as string? | 38,747,526 | <p>Is it possible to output the content of a user-defined function as a string (not the enumeration, but just the function call):</p>
<p>Function:</p>
<pre><code>def sum(x,y):
return x+y
</code></pre>
<p>Function content as a string:</p>
<pre><code>"sum(), return x+y"
</code></pre>
<p>The inspect function migh... | 0 | 2016-08-03T15:15:23Z | 38,747,679 | <p>The <a href="https://docs.python.org/2/library/inspect.html#retrieving-source-code" rel="nofollow"><code>inspect</code> module</a> works just fine for retrieving source code, this is not limited to older Python versions.</p>
<p>Provided the source is available (e.g. the function is not defined in C code or the inte... | 2 | 2016-08-03T15:21:36Z | [
"python",
"python-2.7",
"function",
"introspection"
] |
Is there an analogue of a MATLAB function `mscohere` in Python? | 38,747,539 | <p>In MATLAB have a function <code>mscohere</code> me it needs to be implemented in Python.
The MATLAB code is as follows:</p>
<pre><code>[Cxy,~] = mscohere(LS,RS);
</code></pre>
<p>LS,RS - Arrays type float.</p>
<p>Do modules to the calculation of coherence? Or can anyone have expected it in Python?</p>
<p><a href... | 1 | 2016-08-03T15:16:01Z | 38,747,938 | <p>Yes, it has one in the scipy module:</p>
<pre><code>scipy.signal.coherence(x, y, fs=1.0, window='hann', nperseg=256, noverlap=None, nfft=None, detrend='constant', axis=-1)
</code></pre>
<p>Detailed documentation with examples can be found <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.co... | 2 | 2016-08-03T15:32:42Z | [
"python",
"matlab"
] |
Console tool for python type hint checking | 38,747,565 | <p>I have a project with type hints (Python 3.5.2). I would like to run the static checker to verify that the constraints specified in the type hints are being respected. What tools are available for this? I have been unable to find a reference in the <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">c... | 0 | 2016-08-03T15:17:36Z | 38,935,096 | <p><a href="http://mypy-lang.org/" rel="nofollow">Mypy</a> is probably what you're looking for. It's a console-based tool that can typecheck your Python code using PEP 484 type annotations. The reason why it isn't mentioned in PEP 484 is because there's no inherent reason why mypy would be the only possible typechecker... | 1 | 2016-08-13T17:06:16Z | [
"python",
"type-hinting"
] |
Numpy array to csv | 38,747,682 | <p>I have a np array with 1000 rows, and 4608 columns each rows</p>
<p>I try to save a csv file with:</p>
<pre><code>myfile = open('dataset.csv', 'wb')
wr = csv.writer(myfile,delimiter='\n')
wr.writerow(Prueba[0])
</code></pre>
<p>But if I open the csv file with LibreOffice this:</p>
<pre><code>[153 147 147 ..., 14... | 0 | 2016-08-03T15:21:44Z | 38,747,765 | <p>Try this.</p>
<pre><code>numpy.savetxt("FILENAME.csv", a, delimiter=",")
</code></pre>
<p>Where filename is your filename and a is your array.</p>
| 3 | 2016-08-03T15:25:29Z | [
"python",
"arrays",
"csv",
"numpy"
] |
Numpy array to csv | 38,747,682 | <p>I have a np array with 1000 rows, and 4608 columns each rows</p>
<p>I try to save a csv file with:</p>
<pre><code>myfile = open('dataset.csv', 'wb')
wr = csv.writer(myfile,delimiter='\n')
wr.writerow(Prueba[0])
</code></pre>
<p>But if I open the csv file with LibreOffice this:</p>
<pre><code>[153 147 147 ..., 14... | 0 | 2016-08-03T15:21:44Z | 38,748,140 | <p>The type of the <code>array</code> and the <code>fmt</code> option must match. Try:</p>
<pre><code>import numpy as np
np.savetxt('dataset.csv', array.astype(np.int), fmt='%d', delimiter=',')
</code></pre>
<p>where <code>array</code> is your numpy array.</p>
| 0 | 2016-08-03T15:41:42Z | [
"python",
"arrays",
"csv",
"numpy"
] |
Reshape (M, N, 3) numpy array to (M*N, 3) | 38,747,683 | <p>Suppose I have an RGB (or HSV) image represented by an (M, N, 3) numpy array wherein each dimension (<code>[x, y, 0]</code> or <code>[x, y, 1]</code>) represents a color channel value at a specific pixel. I want to reshape the array to (M*N, 3) where the color channels are combined (<code>[R1, G1, B1], [R2, G2, B2]<... | 0 | 2016-08-03T15:21:46Z | 38,748,018 | <p>If I understood you correctly, then, I would do something like this:</p>
<pre><code>## loading the image...
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread("my_image.jpg")
## extracting R, G, B and flatten them separately and then make
## an array out of them.
res = np... | 1 | 2016-08-03T15:36:22Z | [
"python",
"arrays",
"numpy"
] |
Reshape (M, N, 3) numpy array to (M*N, 3) | 38,747,683 | <p>Suppose I have an RGB (or HSV) image represented by an (M, N, 3) numpy array wherein each dimension (<code>[x, y, 0]</code> or <code>[x, y, 1]</code>) represents a color channel value at a specific pixel. I want to reshape the array to (M*N, 3) where the color channels are combined (<code>[R1, G1, B1], [R2, G2, B2]<... | 0 | 2016-08-03T15:21:46Z | 38,748,129 | <p>If <code>img</code> is your array, you can use <code>img.reshape(-1, 3)</code>.</p>
<p>For example,</p>
<pre><code>In [50]: img.shape
Out[50]: (5, 2, 3)
In [51]: img
Out[51]:
array([[[2, 0, 4],
[1, 4, 3]],
[[2, 1, 4],
[3, 2, 2]],
[[2, 4, 1],
[4, 0, 2]],
[[1, 4, 2],... | 3 | 2016-08-03T15:41:14Z | [
"python",
"arrays",
"numpy"
] |
Django rest framework filter by datetime field | 38,747,697 | <p>In <code>django-rest-framework</code> how can I filter a <code>datetimefield</code> using greater than filters.</p>
<pre><code>class RestaurantList(generics.ListAPIView):
serializer_class = RestaurantSerializer
def get_queryset(self):
#This returns equals but if I use the > sign it does not work... | 0 | 2016-08-03T15:22:28Z | 38,752,616 | <p>You can use <code>gt</code> statement like this:</p>
<pre><code>def get_queryset(self):
return Restaurant.objects.filter(last_update_time__gt=datetime(2016, 08, 03)
</code></pre>
<p>For more information see <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#gt" rel="nofollow">doc</a></p>
| 1 | 2016-08-03T20:01:32Z | [
"python",
"django-models",
"django-views",
"django-rest-framework",
"django-serializer"
] |
Create QIcon from resources.qrc file | 38,747,744 | <p>I have a <code>resources.qrc</code> file that looks like this:</p>
<pre><code><RCC>
<qresource prefix="/plugins/fw_einsatz">
<file>base_aerial.png</file>
<file>base_alkis.png</file>
<file>adr.png</file>
<file>gps_coord.png</file>
<... | 0 | 2016-08-03T15:24:39Z | 38,748,033 | <p>Your path is wrong, try this instead :</p>
<pre><code>icon = QIcon(":/plugins/fw_einsatz/route.png");
</code></pre>
| 2 | 2016-08-03T15:36:52Z | [
"python",
"qt",
"resources",
"pyqt4",
"qicon"
] |
How to set request args with Flask test_client? | 38,747,784 | <p>I have to test out a certain view that gets certain information from request.args.</p>
<p>I can't mock this since a lot of stuff in the view uses the request object.
The only alternative I can think of is to manually set request.args.</p>
<p>I can do that with he test_request_context(), e.g:</p>
<pre><code>with s... | 1 | 2016-08-03T15:26:19Z | 38,748,102 | <p>Pass the <code>query_string</code> argument to <code>c.get</code>, which can either be a <code>dict</code>, a <code>MultiDict</code>, or an already encoded string.</p>
<pre><code>with app.test_client() as c:
r = c.get('/', query_string={'name': 'davidism'})
</code></pre>
<p>The <a href="http://werkzeug.pocoo.o... | 2 | 2016-08-03T15:40:02Z | [
"python",
"unit-testing",
"testing",
"flask",
"flask-testing"
] |
Reindexing stacked DataFrame | 38,747,804 | <p>I would like to stack a dataframe and reindex. </p>
<p>Initial dataframe looks like this:</p>
<pre><code> 00:00 00:30 01:00 01:30 02:00 02:30 03:00 03:30 04:00
Date
2015-09-30 1.18 1.18 1.21 1.20 1.14 1.22 1.17... | 0 | 2016-08-03T15:27:09Z | 38,751,540 | <p>Let us create a dataframe that looks like what the OP has, </p>
<pre><code>import pandas as pd
cols = ['00:00', '00:30', '01:00', '01:30', '02:00', '02:30', '03:00', '03:30', '04:00']
df = pd.DataFrame(columns = cols)
df.ix['2015-09-30'] = [1.18, 1.18, 1.21, 1.20, 1.14, 1.22, 1.17, 1.16, 1.18]
df.ix['2015-01-10'] =... | 2 | 2016-08-03T18:53:13Z | [
"python",
"pandas"
] |
Django Static Url Error, Not Loading | 38,747,850 | <p>I'm currently mad at Django (1.9) right now! The saddest thing is 'Static URL' is the one giving me problem. 'Media URL' is working fine, no problem, but the static url is giving a huge headache.</p>
<p>in my settings_dev.py</p>
<pre><code>import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file... | 0 | 2016-08-03T15:28:56Z | 38,748,202 | <pre><code>STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),]
</code></pre>
<p>That line is enough for serving your project <code>static</code> folder files... And you have to set this in your urls.py </p>
<pre><code>urlpatterns = [
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</co... | 1 | 2016-08-03T15:45:05Z | [
"python",
"django"
] |
Django Static Url Error, Not Loading | 38,747,850 | <p>I'm currently mad at Django (1.9) right now! The saddest thing is 'Static URL' is the one giving me problem. 'Media URL' is working fine, no problem, but the static url is giving a huge headache.</p>
<p>in my settings_dev.py</p>
<pre><code>import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file... | 0 | 2016-08-03T15:28:56Z | 38,748,791 | <p>Okay to make things clear for you.</p>
<p>STATIC_ROOT is that directory where all your static data gets collected when you want to serve your files on another server, say <strong>APACHE or NGINX or maybe on Heroku</strong> or so.</p>
<p>If don't want just want to run your web-app on your local development server, ... | 1 | 2016-08-03T16:13:38Z | [
"python",
"django"
] |
python runtime version statistics | 38,747,864 | <p>Is there any breakdown of how many devices have python 2.6, 2.7, 3.*?</p>
<p>I'm spoiled by OS install statistics, like <a href="https://developer.android.com/about/dashboards/index.html" rel="nofollow">Android's</a>. Of course, the collection methods used there aren't available to Python. For Java, I found <a href... | 0 | 2016-08-03T15:29:34Z | 38,748,469 | <p>There was a survey in 2014 on usage statistics, mostly on 2.x vs 3.x. But not including platforms/devices.</p>
<p><a href="http://www.randalolson.com/2015/01/30/python-usage-survey-2014/" rel="nofollow">The python usage survey</a> includes a more thorough breakdown:
<a href="http://i.stack.imgur.com/Jqi6q.png" rel=... | 1 | 2016-08-03T15:58:08Z | [
"python"
] |
How do I prevent my medians from being rounded? | 38,747,952 | <p>I have code which calculates the median of z-scores, which range from 0 to 1. Python is rounding all these numbers to 0. How would I make sure these numbers are not rounded?</p>
<p>Here's the line of code in which I calculate the medians:</p>
<pre><code>gene_medians = GCT_object.data_df.median(axis=1)
</code></pre... | 0 | 2016-08-03T15:33:22Z | 38,748,349 | <p>If you are using pandas data frame (data_df) then you can use median function form numpy package. </p>
<pre><code>gene_medians = numpy.median(GCT_object.data_df[[1]])
</code></pre>
<p>or </p>
<pre><code>gene_medians = GCT_object.data_df[[1]].apply(numpy.median)
</code></pre>
| 0 | 2016-08-03T15:51:51Z | [
"python",
"rounding",
"median"
] |
Why does this return None? | 38,747,994 | <p>I'm testing out <a href="https://repl.it/languages/python3" rel="nofollow">repl.it</a> (running Python 3.5.1) and I noticed that after every line of input into the console, the console replies with <code>None</code>. I'm not using any fancy definitions with forgotten return values, this happens even after assignment... | 0 | 2016-08-03T15:35:05Z | 38,748,258 | <p>None is the default return value of statements that do not have a return value. Some interpreter shells display it, some don't.</p>
<p>It's perfectly normal, don't worry about it.</p>
| 2 | 2016-08-03T15:47:57Z | [
"python",
"python-3.5"
] |
Passing data from a method to a class then returning value in another method | 38,748,010 | <p>Question how can I pass the value from get_sheet_header class into another method basically I want to the set a HTML response header and my pk then drop it down into another method I use any help would be greatly appreciated and any questions please let me know. </p>
<p>Here is what I have so far </p>
<p>views.py ... | -2 | 2016-08-03T15:35:57Z | 38,748,221 | <p>Just create direct instance of your class and then call method.</p>
<pre><code>tmp_obj = get_sheet_header(obj)
pk = tmp_obj.sheet_reader()
</code></pre>
| 0 | 2016-08-03T15:46:05Z | [
"python",
"django",
"python-2.7"
] |
Passing data from a method to a class then returning value in another method | 38,748,010 | <p>Question how can I pass the value from get_sheet_header class into another method basically I want to the set a HTML response header and my pk then drop it down into another method I use any help would be greatly appreciated and any questions please let me know. </p>
<p>Here is what I have so far </p>
<p>views.py ... | -2 | 2016-08-03T15:35:57Z | 38,749,049 | <p>So instead of making this overly complicated like I was doing. I decided to dumb it down and do it this way and it works :).</p>
<pre><code>def update_sheet(request, pk=None):
blahh blah...
global = SHEET_HEADER_ID
SHEET_HEADER_ID = pk
def add_dimension(request, pk):
pk = SHEET_HEADER_ID
</code></pre>... | -1 | 2016-08-03T16:27:32Z | [
"python",
"django",
"python-2.7"
] |
change column values (and type) to a pandas Dataframe | 38,748,026 | <p>I am trying to rename a column in a pandas dataframes, but different dataframes have different types of columns and I need an help. An easy example will clarify you my issue.</p>
<pre><code>import pandas as pd
dic1 = {'a': [4, 1, 3, 1], 'b': [4, 2, 1, 4], 'c': [5, 7, 9, 1]}
dic2 = {1: [4, 1, 3, 1], 2: [4, 2, 1, 4],... | 2 | 2016-08-03T15:36:40Z | 38,748,104 | <p>This isn't the normal method to rename a column, you should use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="nofollow"><code>rename</code></a> to do this:</p>
<pre><code>In [95]:
df2.rename(columns={df2.columns[-1]:'newName'}, inplace=True)
df2
Out[95]:
1 2 ... | 3 | 2016-08-03T15:40:11Z | [
"python",
"pandas"
] |
Remove or empty all data from a pandas dataframe | 38,748,032 | <p>I have a dataframe (df) which I would like to recycle. Its full of data and I would like to remove everything from this dataframe. Would df.drop() work?</p>
<p>Thanks</p>
| 1 | 2016-08-03T15:36:48Z | 38,749,922 | <p>if you want to free some space</p>
<pre><code>import gc
del adios_df
gc.collect()
</code></pre>
| 1 | 2016-08-03T17:15:40Z | [
"python",
"pandas"
] |
How to migrate the local database on heroku with new tables? | 38,748,038 | <p>I get the error:</p>
<pre><code>Exception Value:
no such table: hello_surname
</code></pre>
<p>when i try to show a view that accesses the Surname model</p>
<p>in my models.py</p>
<pre><code>class Surname(models.Model):
created = models.DateTimeField('date created', auto_now_add=True)
name = models.C... | 1 | 2016-08-03T15:37:17Z | 38,748,138 | <p>You <strong>must</strong> run make migrations <em>locally</em>, commit the results, then run migrate on Heroku.</p>
| 0 | 2016-08-03T15:41:37Z | [
"python",
"django",
"heroku"
] |
Functions on groups in pandas with range selected by label | 38,748,191 | <p>Consider the following Multiindex Pandas Seires:</p>
<pre><code>import pandas as pd
import numpy as np
val = np.array([ 0.4, -0.6, 0.6, 0.5, -0.4, 0.2, 0.6, 1.2, -0.4])
inds = [(-1000, 1921.6), (-1000, 1922.3), (-1000, 1923.0), (-500, 1921.6),
(-500, 1922.3), (-500, 1923.0), (-400, 1921.6), (-400, 1922... | 1 | 2016-08-03T15:44:25Z | 38,748,745 | <p>I'd skip the <code>groupby</code></p>
<pre><code>example.unstack(0).ix[1922:1924].sum()
pp_delay
-1000 0.0
-500 -0.2
-400 0.8
dtype: float64
</code></pre>
| 3 | 2016-08-03T16:11:22Z | [
"python",
"pandas"
] |
Checking and accessing array element without error | 38,748,252 | <p>I have array, which I want to validate, 2nd item of that array. There are 2 ways which comes to my mind</p>
<ol>
<li><p>Check for <code>array</code> length</p>
<pre><code>if len(array) > 1:
# Process for array[1]
</code></pre></li>
<li><p>Catch <code>IndexError</code> and process in <code>else</code> block.... | 1 | 2016-08-03T15:47:43Z | 38,748,438 | <p>Python encourages <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow">EAFP coding style</a>:</p>
<blockquote>
<p><strong>EAFP</strong><br>
Easier to ask for forgiveness than permission. This common Python
coding style assumes the existence of valid keys or attributes and
catches excep... | 4 | 2016-08-03T15:56:20Z | [
"python",
"if-statement",
"exception"
] |
Checking and accessing array element without error | 38,748,252 | <p>I have array, which I want to validate, 2nd item of that array. There are 2 ways which comes to my mind</p>
<ol>
<li><p>Check for <code>array</code> length</p>
<pre><code>if len(array) > 1:
# Process for array[1]
</code></pre></li>
<li><p>Catch <code>IndexError</code> and process in <code>else</code> block.... | 1 | 2016-08-03T15:47:43Z | 38,748,500 | <p>If your array should have at least 2 items, I would do an assert:</p>
<pre><code>assert len(array) > 1, "Array should have at least 2 items"
</code></pre>
<p>If your array could have 2 items I would use the first form:</p>
<pre><code>if len(array) > 1:
# Process for array[1]
</code></pre>
<p>For me the... | 1 | 2016-08-03T15:59:19Z | [
"python",
"if-statement",
"exception"
] |
Disable autouse fixtures on specific pytest marks | 38,748,257 | <p>Is it possible to prevent the execution of "function scoped" fixtures with <code>autouse=True</code> on specific marks only?</p>
<p>I have the following fixture set to autouse so that all outgoing requests are automatically mocked out:</p>
<pre><code>@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
... | 0 | 2016-08-03T15:47:56Z | 38,750,332 | <p>I wasn't able to find a way to disable fixtures with <code>autouse=True</code>, but I did find a way to revert the changes made in my <code>no_requests</code> fixture. <a href="http://doc.pytest.org/en/latest/monkeypatch.html" rel="nofollow"><code>monkeypatch</code></a> has a method <code>undo</code> that reverts al... | 0 | 2016-08-03T17:39:12Z | [
"python",
"py.test",
"pytest-django"
] |
Disable autouse fixtures on specific pytest marks | 38,748,257 | <p>Is it possible to prevent the execution of "function scoped" fixtures with <code>autouse=True</code> on specific marks only?</p>
<p>I have the following fixture set to autouse so that all outgoing requests are automatically mocked out:</p>
<pre><code>@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
... | 0 | 2016-08-03T15:47:56Z | 38,754,249 | <p><strong>It would be difficult and probably not possible to cancel or change the autouse</strong></p>
<p>You can't canel an autouse, being as it's <strong>auto</strong>use. Maybe you could do something to change the autouse fixture based on a mark's condition. But this would be hackish and difficult.</p>
<p>possibl... | 0 | 2016-08-03T21:52:37Z | [
"python",
"py.test",
"pytest-django"
] |
Disable autouse fixtures on specific pytest marks | 38,748,257 | <p>Is it possible to prevent the execution of "function scoped" fixtures with <code>autouse=True</code> on specific marks only?</p>
<p>I have the following fixture set to autouse so that all outgoing requests are automatically mocked out:</p>
<pre><code>@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
... | 0 | 2016-08-03T15:47:56Z | 38,763,328 | <p>You can also use the <a href="http://docs.pytest.org/en/latest/fixture.html#fixtures-can-introspect-the-requesting-test-context" rel="nofollow"><code>request</code> object</a> in your fixture to check the markers used on the test, and don't do anything if a specific marker is set:</p>
<pre><code>import pytest
@pyt... | 2 | 2016-08-04T09:19:41Z | [
"python",
"py.test",
"pytest-django"
] |
Trying to convert all values in a dictionary to int through dictionary comprehension | 38,748,420 | <p>I have a dictionary like this:</p>
<pre><code>{1: 'rattle', 2: '204', 3: 'three', 4: 404, 5: '104', 6: 'pythonic'}
</code></pre>
<p>And I want to convert all values to integer, wherever possible, through dictionary comprehension. So I want this:</p>
<pre><code>{1: 'rattle', 2: 204, 3: 'three', 4: 404, 5: 104, 6: ... | 0 | 2016-08-03T15:55:23Z | 38,748,461 | <p>By adding an <code>if</code> to the end of your loop, you are <em>filtering</em>, limiting your output to key-value pairs where the value is a string and consists of digits.</p>
<p>Use a conditional expression in the value expression instead; that way you keep <em>all</em> key-value pairs but only apply <code>int()... | 2 | 2016-08-03T15:57:37Z | [
"python",
"dictionary",
"dictionary-comprehension"
] |
Trying to convert all values in a dictionary to int through dictionary comprehension | 38,748,420 | <p>I have a dictionary like this:</p>
<pre><code>{1: 'rattle', 2: '204', 3: 'three', 4: 404, 5: '104', 6: 'pythonic'}
</code></pre>
<p>And I want to convert all values to integer, wherever possible, through dictionary comprehension. So I want this:</p>
<pre><code>{1: 'rattle', 2: 204, 3: 'three', 4: 404, 5: 104, 6: ... | 0 | 2016-08-03T15:55:23Z | 38,748,518 | <pre><code>{k: int(v) if str(v).isdigit() else v for k, v in m.items()}
</code></pre>
| 1 | 2016-08-03T16:00:23Z | [
"python",
"dictionary",
"dictionary-comprehension"
] |
Can't run script from another script | 38,748,435 | <p>I'd like to end a process after certain conditions are met within a script.
like this:</p>
<pre><code>import psutil
PROCNAME = "standard.exe"
for proc in psutil.process_iter():
if proc.name() == PROCNAME:
proc.kill()
</code></pre>
<p>I can run this standalone script (processkiller.py) in S... | 0 | 2016-08-03T15:56:16Z | 38,748,494 | <p>Use:</p>
<pre><code>os.system("python C:\\Users\\s086372\\Desktop\\results\ProcessKiller.py")
</code></pre>
<p>You have to pass the .py to the python interpreter.</p>
| 2 | 2016-08-03T15:59:08Z | [
"python",
"abaqus"
] |
Can't run script from another script | 38,748,435 | <p>I'd like to end a process after certain conditions are met within a script.
like this:</p>
<pre><code>import psutil
PROCNAME = "standard.exe"
for proc in psutil.process_iter():
if proc.name() == PROCNAME:
proc.kill()
</code></pre>
<p>I can run this standalone script (processkiller.py) in S... | 0 | 2016-08-03T15:56:16Z | 38,754,053 | <p>This isn't an answer, but I have to use this since I want to make clear my block of code and I can't in the comments</p>
<pre><code>PROCNAME = "standard.exe"
for proc in psutil.process_iter():
print ('Entered the for loop')
if proc.name() == PROCNAME:
print ('Entered the IF statement')
proc.... | 0 | 2016-08-03T21:38:01Z | [
"python",
"abaqus"
] |
How do you concatenate two (or more) dataframes into a panel | 38,748,446 | <p>I was recently trying to concatenate two dataframes into a panel and I tried to use <code>pd.concat</code> with <code>axis=2</code></p>
<p>Consider the dataframes <code>df1</code> and <code>df2</code></p>
<pre><code>df1 = pd.DataFrame(np.random.rand(3, 3), list('abc'), list('def'))
df2 = pd.DataFrame(np.random.ran... | 1 | 2016-08-03T15:56:37Z | 38,748,564 | <p>You can use the <code>pd.Panel</code> constructor and pass a dictionary of dataframes.</p>
<pre><code>def concat2(dfs, keys=None):
if keys is None:
keys = range(len(dfs))
return pd.Panel({k:v for k, v in zip(keys, dfs)})
</code></pre>
<p>This feels like what a <code>pd.concat(dfs, axis=1, keys=keys... | 1 | 2016-08-03T16:02:39Z | [
"python",
"pandas"
] |
How do you concatenate two (or more) dataframes into a panel | 38,748,446 | <p>I was recently trying to concatenate two dataframes into a panel and I tried to use <code>pd.concat</code> with <code>axis=2</code></p>
<p>Consider the dataframes <code>df1</code> and <code>df2</code></p>
<pre><code>df1 = pd.DataFrame(np.random.rand(3, 3), list('abc'), list('def'))
df2 = pd.DataFrame(np.random.ran... | 1 | 2016-08-03T15:56:37Z | 38,750,028 | <p>Not sure what you are looking for, but: </p>
<pre><code>pd.Panel(np.stack([df1, df2]), major_axis=df1.index, minor_axis=df2.columns ).to_frame()
0 1
major minor
a d 0.630339 0.020119
e 0.736730 0.874750
f 0.530833 0.637081
b d ... | 1 | 2016-08-03T17:21:23Z | [
"python",
"pandas"
] |
Increment and while loop | 38,748,472 | <p>Following is the code I'm executing in IDLE for Python 3.5.2 on Windows 10:</p>
<pre><code>spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
</code></pre>
<p>I can see Hello World printed 5 times however when entering spam in IDLE, I can see the integer 5.
Shouldn't this be logically int 6... | 0 | 2016-08-03T15:58:14Z | 38,748,540 | <p>Your while loop is "while spam is <strong>less than</strong> 5", not "while spam is <strong>less than or equal</strong> to 5". The last iteration occurs when spam is 4, and then it gets incremented one last time to 5.</p>
<p>If spam equals 5, it is <strong>not</strong> less than 5, so the while loop stops iterating... | 2 | 2016-08-03T16:01:38Z | [
"python",
"python-3.x"
] |
Increment and while loop | 38,748,472 | <p>Following is the code I'm executing in IDLE for Python 3.5.2 on Windows 10:</p>
<pre><code>spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
</code></pre>
<p>I can see Hello World printed 5 times however when entering spam in IDLE, I can see the integer 5.
Shouldn't this be logically int 6... | 0 | 2016-08-03T15:58:14Z | 38,748,549 | <p><code>spam < 5</code> can be read as spam is less than 5, so it'll only increment from 0 to 4. In the 4th (last) iteration, <code>spam = 4</code> so it prints 'Hello, world' and then <code>spam + 1 = 5</code>. At that point it will attempt another iteration, but <code>spam < 5</code> is no longer true and ther... | 3 | 2016-08-03T16:01:52Z | [
"python",
"python-3.x"
] |
Increment and while loop | 38,748,472 | <p>Following is the code I'm executing in IDLE for Python 3.5.2 on Windows 10:</p>
<pre><code>spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
</code></pre>
<p>I can see Hello World printed 5 times however when entering spam in IDLE, I can see the integer 5.
Shouldn't this be logically int 6... | 0 | 2016-08-03T15:58:14Z | 38,748,829 | <p>I added a print statement to illustrate what is happening:</p>
<pre><code>spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
print(spam, 'spam is < 5?', spam < 5, "\n")
</code></pre>
<p>The output is:</p>
<pre><code>Hello, world.
1 spam is < 5? True
Hello, world.
2 spam is &... | 0 | 2016-08-03T16:15:28Z | [
"python",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.