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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Not sure why I'm getting this attribute error | 38,464,911 | <p>The assertEqual tests are from a module that just calls a function, runs some data through it, computes the result of that processed data, and compares it to my predicted answer. For example, my predicted answer for <code>total_test</code> was 6.0.
When I run my code (below being the troubled part), I get this erro... | 1 | 2016-07-19T17:28:09Z | 38,465,905 | <p>Your test code passes a list of three <code>float</code> instances, <code>[1.0,2.0,3.0]</code>, as the <code>purchases</code> argument to <code>Transaction</code>'s initializer. However, the other <code>Transaction</code> methods try to call various methods (e.g. <code>cost()</code> and <code>item()</code>) on the v... | 0 | 2016-07-19T18:26:12Z | [
"python",
"python-3.x",
"oop"
] |
Having trouble with beautifulsoup in python | 38,464,934 | <p>I am very new to python and have trouble with the code below. I am trying to get either the temperature or the date on the website, but can't seem to get an output. I have tried many variations, but still can't seem to get it right..</p>
<p>Thank you for your help!</p>
<pre><code>#Code below:
import requests,bs4
... | 4 | 2016-07-19T17:29:19Z | 38,466,076 | <p>I was able to get the dates:</p>
<pre><code>>>> import requests,bs4
>>> r = requests.get('http://www.hko.gov.hk/contente.htm')
>>> hkweather = bs4.BeautifulSoup(r.text)
>>> print hkweather.select('div[class="fnd_date"]')
# [<div class="fnd_date"></div>, <div class=... | 0 | 2016-07-19T18:36:09Z | [
"python",
"beautifulsoup"
] |
Having trouble with beautifulsoup in python | 38,464,934 | <p>I am very new to python and have trouble with the code below. I am trying to get either the temperature or the date on the website, but can't seem to get an output. I have tried many variations, but still can't seem to get it right..</p>
<p>Thank you for your help!</p>
<pre><code>#Code below:
import requests,bs4
... | 4 | 2016-07-19T17:29:19Z | 38,466,851 | <p>Your css selector is incorrect, you should use <code>.</code> between the tag and css classes, the tags you want are in the divs with the <code>fnd_day</code> class inside the div with the id <em>fnd_content</em></p>
<pre><code>divs = soup.select("#fnd_content div.fnd_day")
</code></pre>
<p>But that still won't g... | 1 | 2016-07-19T19:22:01Z | [
"python",
"beautifulsoup"
] |
Jupyter notebook doesn't execute | 38,464,968 | <p>I am following <a href="http://blog.yhat.com/posts/predicting-customer-churn-with-sklearn.html" rel="nofollow">yhat's tutorial on predictive analytics</a>, but I ran into some trouble when I reached the cross-validation step. Whenever I try to execute these two pieces of code, Jupyter is stuck in the execution step.... | 0 | 2016-07-19T17:30:48Z | 38,476,198 | <p>Just created a dataset of around 54k rows and 3 features and run the same yhat tutorial you have. Took around 30 secs to run, on a 2016 macbook pro.</p>
<p>Don't think there is anything wrong with your code, it just takes a while to run.</p>
<p>To test it, you could limit the size of your dataset and do a test run... | 1 | 2016-07-20T08:31:37Z | [
"python",
"machine-learning",
"scikit-learn"
] |
python "No module named site" | 38,465,049 | <p>So I have searched this question before, and it's been answered satisfactorily for other users on stackoverflow (<a href="http://stackoverflow.com/questions/5599872/python-windows-importerror-no-module-named-site">Python (Windows) - ImportError: No module named site</a>). stackoverflow says I should avoid asking a ... | 0 | 2016-07-19T17:36:02Z | 38,465,190 | <p>Here is what i have come up with my search :</p>
<p><strong>Possible causes</strong>
Squish source build without Python</p>
<p>This typically occurs with Squish source builds that have Python configured.</p>
<p><strong>Solution:</strong></p>
<p>Either set the environment variable PYTHONHOME to the path of the Py... | 0 | 2016-07-19T17:45:07Z | [
"python",
"windows-7-x64",
"python-module"
] |
Write output of for loop in python | 38,465,097 | <p>I am trying to write each iterated output of for loop for further operations.
Here is my code</p>
<pre><code>#!/usr/bin/python
import io
from operator import itemgetter
with open('test.in') as f:
content = f.readlines()
content = [int(x) for x in content]
content = tuple(content)
nClus = input("Num... | -1 | 2016-07-19T17:38:25Z | 38,465,907 | <p>Why not just save them to an array (<code>mydata</code> below)? I don't see where <code>j</code> stops (<code>other_dimension</code>, you can probably just delete it if you only have 1 dimension of results, I don't know your array size), but you can follow this format to get a numpy array to save data to:</p>
<pre... | 0 | 2016-07-19T18:26:23Z | [
"python",
"for-loop",
"output"
] |
Merge multiple images matplotlib | 38,465,144 | <p>My for loop creates 99 images. I want to display all these images into one image, not 99 separate files.
Currently, it will only show the last image created. However, I want one image all merged together)</p>
<pre><code>For track in c:
plt.imshow(k.getCookie(track,50))
plt.show()
</code></pre>
| 1 | 2016-07-19T17:41:18Z | 38,465,203 | <p>like this</p>
<p>If you for example want a grid of 11x9 elements</p>
<pre><code>for i,track in enumerate(c):
plt.subplot(11,9,i+1)
plt.imshow(k.getCookie(track,50))
</code></pre>
| 1 | 2016-07-19T17:45:41Z | [
"python"
] |
Django REST Framework: Provide QuerySet to Renderer | 38,465,175 | <p>We would like to use the Django REST framework to render the model data (with the filtering specified via the Django REST framework API) as plots. Our plotting engine directly works with Django <code>QuerySets</code>.</p>
<p>The question is: How is it possible serialize the model data as Django <code>QuerySets</cod... | -1 | 2016-07-19T17:43:25Z | 38,465,658 | <p>Do you mean doing something like this?</p>
<pre><code>from rest_framework import generics, serializers
from .models import Foo
class QuerySetSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = ('id', 'field1', 'field2',)
class QuerySetList(generics.ListAPIView):
se... | 0 | 2016-07-19T18:10:49Z | [
"python",
"django",
"django-rest-framework",
"django-queryset"
] |
Python3 and ASCII | 38,465,194 | <p>I am learning python, and I am a bit confused about contents.encode() in init() in the following code. </p>
<pre><code>PY3 = sys.version_info[0] > 2
class Test:
def __init__(self):
self.contents = ''
if PY3:
self.contents = self.contents.encode('ascii')
</code></pre>
| 0 | 2016-07-19T17:45:12Z | 38,465,288 | <p>Python 3 strings are Unicode strings. There are situations where you want data in a byte string, where (typically) every character is a single byte. <code>"string".encode('ascii')</code> creates a byte string containing the six ASCII characters s, t, r, i, n, g out of the Unicode string containing these characters a... | 1 | 2016-07-19T17:50:37Z | [
"python",
"python-3.x",
"character-encoding",
"ascii"
] |
Validating sqlalchemy relationships | 38,465,197 | <p>I have a model like this:</p>
<pre><code>class Widget(Base):
obj_id = db.Column(db.Integer, db.ForeignKey("obj.id"))
obj = db.relationship("Obj", back_populates="widgets")
@validates("obj_id")
def validate_obj_id(self, key, obj_id):
return obj_id
@validates("obj")
def validate_obj... | 0 | 2016-07-19T17:45:24Z | 38,470,232 | <p>You can use the 'set' event:</p>
<pre><code>from sqlalchemy import event
@event.listens_for(Widget.obj, 'set', retval=True)
def validate_obj(target, value, oldvalue, initiator):
print('event fired for validate_obj')
return value
</code></pre>
| 1 | 2016-07-19T23:43:44Z | [
"python",
"sqlalchemy"
] |
Add dimensions to an array from a list | 38,465,199 | <p>The structure of my array 'cama' is the following:</p>
<pre><code>shape(cama)
>>>(365, 720, 1440)
</code></pre>
<p>And the shape of my 'lon_list' is the following:</p>
<pre><code>shape(lon_list)
>>>(1440,)
</code></pre>
<p>What I want is to add or append lon_list to cama. So that I end up with ... | -3 | 2016-07-19T17:45:33Z | 38,465,426 | <p>Dimensions are <em>multiplicative</em>. This means if you have:</p>
<pre><code>a = [[1, 2, 3], [4, 5, 6]]
</code></pre>
<p>You have a <code>(2 x 3)</code> array of 6 elements. If you want to add another dimension, say <code>b=[10, 20, 30, 40]</code>, you will end up with an array of <code>(2 x 3 x 4) = 24</code> e... | 0 | 2016-07-19T17:57:09Z | [
"python",
"arrays"
] |
GmailUserSocialAuth email message returns empty message but has snippet | 38,465,286 | <p>I'm working with the Gmail API in python, getting a request with:</p>
<pre><code>gmail_auth = GmailUserSocialAuth.objects.filter(uid='...')[0]
response = gmail_auth.request('get', '...')
data = response.json()
response - gmail_auth.request('get', '/%s' % data['messages'][0]['id']
message = response.json()
</code><... | 0 | 2016-07-19T17:50:34Z | 38,478,749 | <p>Try to use the <strong><em>get</em></strong> method as stated in the <a href="https://developers.google.com/gmail/api/v1/reference/users/messages/get#examples" rel="nofollow">Python sample code</a>.
Here's a snippet:</p>
<pre><code>def GetMimeMessage(service, user_id, msg_id):
"""Get a Message and use it to creat... | 1 | 2016-07-20T10:27:08Z | [
"python",
"email",
"gmail",
"gmail-api"
] |
column width - beginner python | 38,465,368 | <p>I'm currently working on this quick project to learn and I semi-successfully finished printing each list into a column but I'm having troubles printing the correct column width.</p>
<pre><code>fruitNamePets = [ ['apples', 'oranges', 'cherries', 'bananas', 'pineapples', 'mangos'],
['Alice', 'Bo... | 2 | 2016-07-19T17:54:44Z | 38,465,526 | <p>The issue is this line:</p>
<pre><code>colWidths[j] = len(max(tableName[j])) + 2
</code></pre>
<p><code>max(tableName[j])</code> returns you the "biggest" value in <code>tableName[j]</code>. In the case of a list of strings, this means the one that sorts the highest alphabetically. So "pineapples" in the first col... | 2 | 2016-07-19T18:03:08Z | [
"python"
] |
Python NamedTemporaryFile - ValueError When Reading | 38,465,418 | <p>I am having an issue writing to a NamedTemporaryFile in Python and then reading it back. The function downloads a file via tftpy to the temp file, reads it, hashes the contents, and then compares the hash digest to the original file. The function in question is below:</p>
<pre><code>def verify_upload(self, image,... | 1 | 2016-07-19T17:56:51Z | 38,465,567 | <p>TFTPy is closing the file. When you were looking at the source, you missed the following code path:</p>
<pre><code>class TftpClient(TftpSession):
...
def download(self, filename, output, packethook=None, timeout=SOCK_TIMEOUT):
...
self.context = TftpContextClientDownload(self.host,
... | 2 | 2016-07-19T18:05:59Z | [
"python",
"temporary-files",
"tftp",
"hashlib"
] |
how to parallelize cached functions using joblib | 38,465,445 | <p>I would like to paralellize a function that is cached with joblib.Memory
however I get the following error:</p>
<pre><code>TypeError: can't pickle function objects
</code></pre>
<p>Here is the code:</p>
<pre><code>import joblib
mem = joblib.Memory(cachedir='/tmp')
@mem.cache
def foo(x):
# do some complicat... | 2 | 2016-07-19T17:58:34Z | 38,469,184 | <p>Try using different name for the decorated function like <code>foo_cached = mem.cache(foo)</code> instead of decorator. See also <a href="https://github.com/joblib/joblib/issues/226" rel="nofollow">https://github.com/joblib/joblib/issues/226</a></p>
| 1 | 2016-07-19T21:56:35Z | [
"python",
"multiprocessing",
"joblib"
] |
Select values in a column based on multiple rows in a different column | 38,465,520 | <p>I have a dataframe with sales orders that have multiple products (original dataframe below). I need create a second dataframe showing the sales orders, whether the sales order has only one product or not (standalone), and the name of the product. Any help on how to accomplish this would be greatly appreciated. Thank... | 0 | 2016-07-19T18:02:47Z | 38,465,928 | <p>So your starting DataFrame looks like:</p>
<pre><code> Sales Order Product
0 1111 Software
1 1111 Support
2 2222 Hardware
3 3333 Software
4 4444 Hardware
5 4444 Software
</code></pre>
<p>First <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.... | 0 | 2016-07-19T18:27:13Z | [
"python",
"pandas"
] |
Creating dictionary from CSV file, | 38,465,579 | <p>For the following CSV File:</p>
<pre><code>A,B,C
A1,B1,C1
A1,B2,C2
A2,B3,C3
A2,B4,C4
</code></pre>
<p>How do I get my dictionary to look like this:</p>
<pre><code>{'A1': {'B1': 'C1', 'B2' : 'C2'}, 'A2': {'B3': 'C3', 'B4' : 'C4'}}
</code></pre>
<p>I'm using the following code:-</p>
<pre><code>EgDict = {}
with o... | 0 | 2016-07-19T18:06:47Z | 38,465,759 | <pre><code>res = {}
with open('foo.csv') as f:
reader = csv.reader(f)
for i,item in enumerate(reader):
if i == 0: continue
a,b = item[0],item[1:]
if a not in res:
res[a] = {}
res[a].update( {b[0]:b[1]} )
</code></pre>
| 0 | 2016-07-19T18:16:59Z | [
"python",
"csv",
"dictionary",
"append",
"attributeerror"
] |
Creating dictionary from CSV file, | 38,465,579 | <p>For the following CSV File:</p>
<pre><code>A,B,C
A1,B1,C1
A1,B2,C2
A2,B3,C3
A2,B4,C4
</code></pre>
<p>How do I get my dictionary to look like this:</p>
<pre><code>{'A1': {'B1': 'C1', 'B2' : 'C2'}, 'A2': {'B3': 'C3', 'B4' : 'C4'}}
</code></pre>
<p>I'm using the following code:-</p>
<pre><code>EgDict = {}
with o... | 0 | 2016-07-19T18:06:47Z | 38,465,771 | <p>A dictionary has no <code>append</code> method. That will be for lists.</p>
<p>You may consider using the following code instead:</p>
<pre><code>d = {}
with open('foo.csv') as f:
reader = csv.DictReader(f)
for row in reader:
d.setdefault(row['A'], {}).update({row['B']: row['C']})
print(d)
# {'A1': ... | 2 | 2016-07-19T18:17:27Z | [
"python",
"csv",
"dictionary",
"append",
"attributeerror"
] |
Is there any way to input in Python that is analogous to simple input in Java using Scanner class? | 38,465,604 | <p>I am new to python and had a problem, wherein input from the online judge is supposed to be in the form] of a horizontal row of integers.
I am trying to store them as a list.
input format: 5 4 4 2 2 8
But every time I type in horizontal row of characters I get the error :
unexpected EOF while parsing</p>
<p... | 0 | 2016-07-19T18:08:19Z | 38,465,774 | <p>A convenient way to read input from <code>stdin</code> when using online judges is to iterate through the input lines like this:</p>
<pre><code>for line in sys.stdin:
inp_array = line.split() # split the line
a = int(inp-array[0])
b = float(inp_array[1])
</code></pre>
<p>This would result in that the i... | 0 | 2016-07-19T18:17:33Z | [
"java",
"python",
"input"
] |
Is there any way to input in Python that is analogous to simple input in Java using Scanner class? | 38,465,604 | <p>I am new to python and had a problem, wherein input from the online judge is supposed to be in the form] of a horizontal row of integers.
I am trying to store them as a list.
input format: 5 4 4 2 2 8
But every time I type in horizontal row of characters I get the error :
unexpected EOF while parsing</p>
<p... | 0 | 2016-07-19T18:08:19Z | 38,465,929 | <p>See <a href="http://stackoverflow.com/questions/70797/python-user-input-and-commandline-arguments">this</a> post to take user input like scanner and more.</p>
<p>See <a href="http://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python">this</a> post to determine data type.</p>
| 0 | 2016-07-19T18:27:20Z | [
"java",
"python",
"input"
] |
Looking for an efficient way to store history data | 38,465,620 | <p>The data is a python dict representing a state of something that changes slowly over the time. Values change often, usually one or two items at a time. The keys can change too, but that's a rare event. After each change the new data set is remembered for future examination.</p>
<p>The result is a long sequence with... | 4 | 2016-07-19T18:08:59Z | 38,465,941 | <p>A more space-efficient approach is to keep a set for each "column" of data. That is, we keep a set for columns <code>a</code>, <code>b</code>, and <code>c</code>. The set keeps track of the timestamps for which the column's value is <code>True</code>. For instance, for the data:</p>
<pre><code>(timestamp1, {'a':Fal... | 3 | 2016-07-19T18:27:53Z | [
"python",
"storage"
] |
Looking for an efficient way to store history data | 38,465,620 | <p>The data is a python dict representing a state of something that changes slowly over the time. Values change often, usually one or two items at a time. The keys can change too, but that's a rare event. After each change the new data set is remembered for future examination.</p>
<p>The result is a long sequence with... | 4 | 2016-07-19T18:08:59Z | 38,466,085 | <p>I would use pickle to store the dictionary content depending on the timestamp. You simply generate pickled files with the timestamp as their name. You can also compress the files using pickle. Pickle should be implemented in a way that you won't easily be able to compress the content any better manually.</p>
<p>If ... | 0 | 2016-07-19T18:36:35Z | [
"python",
"storage"
] |
Looking for an efficient way to store history data | 38,465,620 | <p>The data is a python dict representing a state of something that changes slowly over the time. Values change often, usually one or two items at a time. The keys can change too, but that's a rare event. After each change the new data set is remembered for future examination.</p>
<p>The result is a long sequence with... | 4 | 2016-07-19T18:08:59Z | 38,466,500 | <p>You might want to look at PeopleSoft's EFFDT system for inspiration. It's intended for storage and querying with a database, but the principles remain.</p>
<p>Each item is stored separately, with a key, a time-of-effect (EFFDT) and the various values.</p>
<p>So, taking 'a' and 'b', you would have this type of sto... | 1 | 2016-07-19T19:00:14Z | [
"python",
"storage"
] |
Get etree Element with attribute, or containing subelement with attribute | 38,465,690 | <p>I have an XML file to parse, and I need to find elements by id.</p>
<p>In the example code, I need to find the name of the <code>driver</code>, but I don't know whether my id is for the <code>vehicle</code>, <code>engine</code>, or <code>block</code>. I would like a solution which would work with arbitrary xml insi... | 1 | 2016-07-19T18:12:25Z | 38,465,868 | <p><strong>Note</strong>: All the snippets below use <code>lxml</code> library. To install, run: <code>pip install lxml</code>.</p>
<p>You should use <code>root.xpath(..)</code> not <code>root.findall(..)</code>.</p>
<pre><code>>>> root.xpath("//vehicle/driver/text()")
['Bob Johnson', 'Dave Edwards']
</code>... | 1 | 2016-07-19T18:24:11Z | [
"python",
"xml",
"elementtree"
] |
Get etree Element with attribute, or containing subelement with attribute | 38,465,690 | <p>I have an XML file to parse, and I need to find elements by id.</p>
<p>In the example code, I need to find the name of the <code>driver</code>, but I don't know whether my id is for the <code>vehicle</code>, <code>engine</code>, or <code>block</code>. I would like a solution which would work with arbitrary xml insi... | 1 | 2016-07-19T18:12:25Z | 38,465,968 | <p>If you know the <code>id</code>, but don't know if this <code>id</code> is from vehicle, engine or block, you can approach it with an XPath expression, but you would have to use <a href="http://lxml.de/tutorial.html" rel="nofollow"><code>lxml.etree</code></a> instead of <code>xml.etree.ElementTree</code> (it has ver... | 1 | 2016-07-19T18:29:42Z | [
"python",
"xml",
"elementtree"
] |
Reading/Writing Header Strings and Numerical Arrays | 38,465,773 | <p>I'm really new to Python and I'm unable to do something really simple. I see examples here for dealing with strings and numbers, but not how to deal with one character-string header of a few rows followed by arrays of numbers. I've found a partial solution, but the first row of data is partly chopped off. This i... | 0 | 2016-07-19T18:17:31Z | 38,531,563 | <p>Yes! Solved it! Although the solution is INelegant. The problem was to have an output file with many rows of properly formatted data following 3 rows of header. The first 1.5 rows of data were cut off with the algorithm above. The solution I give below does work, but it's not elegant because I use a temporary ... | 0 | 2016-07-22T16:42:48Z | [
"python",
"arrays",
"numpy"
] |
Reading/Writing Header Strings and Numerical Arrays | 38,465,773 | <p>I'm really new to Python and I'm unable to do something really simple. I see examples here for dealing with strings and numbers, but not how to deal with one character-string header of a few rows followed by arrays of numbers. I've found a partial solution, but the first row of data is partly chopped off. This i... | 0 | 2016-07-19T18:17:31Z | 38,551,713 | <p>I want to add a maybe more elegant solution:
<code>np.savetxt</code> accepts a header string that is written to the file prior to the data. With this you really don't need that temporary file:</p>
<p><code>np.savetxt(filename, data, header="my header\nand a second line")</code></p>
| 0 | 2016-07-24T11:54:14Z | [
"python",
"arrays",
"numpy"
] |
Find Repeating Substring In a List | 38,465,867 | <p>I have a long list of sub-strings (close to 16000) that I want to find where the repeating cycle starts/stops. I have come up with this code as a starting point:</p>
<pre><code>strings= ['1100100100000010',
'1001001000000110',
'0010010000001100',
'0100100000011011',
'1001000000110110... | 2 | 2016-07-19T18:24:11Z | 38,466,045 | <p>Here's something that will find all subarrays that match within the strings array.</p>
<pre><code>strings = ['A', 'B', 'C', 'D', 'Z', 'B', 'B', 'C', 'A', 'B', 'C']
pat = ['A', 'B', 'C', 'D']
i = 0
while i < len(strings):
if strings[i] not in pat:
i += 1
continue
matches = 0
for j in... | 0 | 2016-07-19T18:34:08Z | [
"python",
"string",
"list",
"for-loop",
"sequence"
] |
Find Repeating Substring In a List | 38,465,867 | <p>I have a long list of sub-strings (close to 16000) that I want to find where the repeating cycle starts/stops. I have come up with this code as a starting point:</p>
<pre><code>strings= ['1100100100000010',
'1001001000000110',
'0010010000001100',
'0100100000011011',
'1001000000110110... | 2 | 2016-07-19T18:24:11Z | 38,466,321 | <p>Here's a reasonably simple way that finds all matches of all lengths >= 1:</p>
<pre><code>def findall(xs):
from itertools import combinations
# x2i maps each member of xs to a list of all the
# indices at which that member appears.
x2i = {}
for i, x in enumerate(xs):
x2i.setdefault(x, []... | 0 | 2016-07-19T18:49:18Z | [
"python",
"string",
"list",
"for-loop",
"sequence"
] |
Find Repeating Substring In a List | 38,465,867 | <p>I have a long list of sub-strings (close to 16000) that I want to find where the repeating cycle starts/stops. I have come up with this code as a starting point:</p>
<pre><code>strings= ['1100100100000010',
'1001001000000110',
'0010010000001100',
'0100100000011011',
'1001000000110110... | 2 | 2016-07-19T18:24:11Z | 38,466,475 | <pre><code>strings= ['1100100100000010',
'1001001000000110',
'0010010000001100',
'0100100000011011',
'1001000000110110',
'0010000001101101',
'1100100100000010',
'1001001000000110',
'0010010000001100',
'0100100000011011',]
n = 3
patt_dict = {}
fo... | 1 | 2016-07-19T18:58:41Z | [
"python",
"string",
"list",
"for-loop",
"sequence"
] |
Python PIL/imagemagick merge gradient over the base image | 38,465,906 | <p>I already know how to get a gradient image but how can I merge the gradient image and the base image so that it looks something like this:
<a href="https://1drv.ms/i/s!Aoi-6MWkMNN4kGLYNmqN9dm1nrOD" rel="nofollow">link</a></p>
<pre><code>convert -size 1327x1327 xc:transparent gradient: grad_image.png
</code></pre>
... | 0 | 2016-07-19T18:26:17Z | 38,475,751 | <p>I can only guess what you are trying to do, so my first attempt would be this:</p>
<pre><code>convert jelly.jpg \( -size 1140x100! gradient:none-black \) -gravity south -composite -pointsize 36 -fill white -annotate +0+20 "Title Treatment" result.png
</code></pre>
<p><a href="http://i.stack.imgur.com/4TECp.jpg" re... | 1 | 2016-07-20T08:07:55Z | [
"python",
"image-processing",
"imagemagick",
"python-imaging-library",
"imagemagick-convert"
] |
How to make user defined classes in web2py | 38,465,935 | <p>I am trying to make a class within a module, import that module file in my controller, and then reference the class that is defined within that module, but I keep getting a message that reads <code>NameError("name 'self' is not defined")</code></p>
<p>Here is my code in my created module:</p>
<pre><code>from gluon... | 0 | 2016-07-19T18:27:32Z | 38,466,248 | <p>As stated, just move <code>self.info = {}</code> into <code>__init__()</code>. </p>
<p><code>__init__()</code> is essentially a constructor that you are familiar with from java. It <em>initializes</em> an instance object of that class when called. I haven't used Java in some time, but I don't think you should be be... | 2 | 2016-07-19T18:45:36Z | [
"python",
"python-2.7",
"web2py",
"web2py-modules"
] |
SciPy minimize with gradient | 38,465,959 | <p>This is an implementation of logistic regression, using a toy data set. Some feedback from <a href="https://stackoverflow.com/users/2077270/dermen">@dermen</a> helped me fix a basic problem with how I was using <code>scipy.optimize.minimize</code> but even after fixing that issue, optimize fails to converge, even ju... | 0 | 2016-07-19T18:29:17Z | 38,525,804 | <p>There was overflow occurring in the calls to <code>np.power</code> inside the <code>sigma</code> function. I added debugging messages into the <code>cost</code> function and saw the following:</p>
<pre><code>theta: [ 0. 0. 0.]
--
X: [[ 1. 34.62365962 78.02469282]
[ 1. 30.28671077 43.8949975... | 1 | 2016-07-22T11:54:05Z | [
"python",
"numpy",
"scipy",
"minimization"
] |
Zipline: using pandas-datareader to feed in Google Finance dataframe for non-US based financial markets | 38,466,000 | <p><strong>PLEASE NOTE:</strong> This question was successfully answered ptrj below. I have also written a blog post on my blog about my experiences with zipline which you can find here: <a href="https://financialzipline.wordpress.com" rel="nofollow">https://financialzipline.wordpress.com</a></p>
<hr>
<p>I'm based in... | 8 | 2016-07-19T18:31:43Z | 38,624,965 | <p>I followed tutorials on <a href="http://www.zipline.io/" rel="nofollow">http://www.zipline.io/</a> and I made it work with the following steps:</p>
<ol>
<li><p>Prepare an ingestion function for google equities.</p>
<p>The same code you pasted (based on file <a href="http://www.zipline.io/_modules/zipline/data/bund... | 5 | 2016-07-27T23:48:25Z | [
"python",
"pandas",
"zipline",
"pandas-datareader"
] |
obtaining the url of a video with its blob key | 38,466,078 | <p>I tried the code below to get the serving url for a video saved on app engine's cloud storage. It threw <code>TransformationError</code>. </p>
<pre><code>public_url = images.get_serving_url(blob_key)
</code></pre>
<p>I'm using python 2.7. Is there a solution?</p>
| 0 | 2016-07-19T18:36:10Z | 38,469,027 | <p>The <a href="https://cloud.google.com/appengine/docs/python/images/" rel="nofollow">images</a> API is for processing photos/still images, not videos. Feeding it a video is very likely the reason why you're getting <code>TransformationError</code>.</p>
<p>It is possible to serve/stream videos as well, plenty of rela... | 1 | 2016-07-19T21:43:47Z | [
"python",
"python-2.7",
"google-app-engine",
"google-cloud-storage"
] |
splitting a string(Using reg. exp.) appropriately to extract out some info in Python | 38,466,131 | <p>I have a string like this</p>
<pre><code>s = "CITY_NAME == 'Pune' & GENRE in ['$SPORTS$','$CLASSICAL$']$#$CITY_NAME == 'Pune' & GENRE == 'ROMANCE' & QUANTITY >= 25$#$CITY_NAME == 'Pune' & GENRE in ['$ACTION$','$DRAMA$'] & LANGUAGE == 'Hindi'$#$CITY_NAME == 'Pune' & GENRE in ['$MUSICAL$','... | 1 | 2016-07-19T18:38:42Z | 38,467,084 | <pre><code>import re
s = ...
fields = set()
for word in s.split():
if re.match(r'^[A-Z_]*$', word):
fields.add(word)
fields = list(fields)
print fields
</code></pre>
<p>This yields: <code>['CITY_NAME', 'GENRE', 'EVENT_NAME', 'LANGUAGE', 'QUANTITY']</code></p>
<p>The reason it separates out your fields is ... | 1 | 2016-07-19T19:35:59Z | [
"python",
"string"
] |
splitting a string(Using reg. exp.) appropriately to extract out some info in Python | 38,466,131 | <p>I have a string like this</p>
<pre><code>s = "CITY_NAME == 'Pune' & GENRE in ['$SPORTS$','$CLASSICAL$']$#$CITY_NAME == 'Pune' & GENRE == 'ROMANCE' & QUANTITY >= 25$#$CITY_NAME == 'Pune' & GENRE in ['$ACTION$','$DRAMA$'] & LANGUAGE == 'Hindi'$#$CITY_NAME == 'Pune' & GENRE in ['$MUSICAL$','... | 1 | 2016-07-19T18:38:42Z | 38,467,761 | <p>yes a parser makes sense here .. here is what i have tried to do that(can be include in a function definition later ..)</p>
<pre><code>lst = list() ###empty list to store parsed results
for i in s.split('$#$'):
#print(i)
for j in i.split('&'):
#print(j)
word = re.split(r'[(==)(>=)(&... | 1 | 2016-07-19T20:19:02Z | [
"python",
"string"
] |
How to find unique non-degenerate equations in a system of linear equations | 38,466,138 | <p>I am using sympy to produce symbolic polynomial equations. I have roughly 30 variables and roughly 20 constant variables. The highest power that my equations reach is a squared term. </p>
<p>I need to take 2^13 of these equations and figure out how many of them are unique (i.e., not linear combinations of each o... | 2 | 2016-07-19T18:39:21Z | 38,466,661 | <p>Sympy has a <code>Matrix</code> class with a <code>rank</code> method:</p>
<pre><code>In [1]: x, y = symbols('x y')
In [2]: M = Matrix([[x, y], [2*x, 2*y]])
In [3]: M
Out[3]:
â¡ x y â¤
⢠â¥
â£2â
x 2â
yâ¦
In [4]: M.rank()
Out[4]: 1
</code></pre>
<p>I do not know the implementation, and it mi... | 2 | 2016-07-19T19:09:30Z | [
"python",
"numpy",
"sympy"
] |
Python - Cannot Kill Process | 38,466,157 | <p>I'm using Python 3.5 and Windows 7. I'm trying to open an exe file and then terminate it. I've succeeded in opening it, but I can't close it. Here's an abbreviated version of my code:</p>
<pre><code>from subprocess import Popen
open = Popen(["filename"], shell = True, cwd = "path\to\file")
open.terminate()
</code>... | 2 | 2016-07-19T18:40:02Z | 38,513,769 | <p>It turns out shell = False is necessary for this to work. Here is my successful code:</p>
<pre><code>open = Popen(["path\to\file\filename"])
open.terminate()
</code></pre>
| 1 | 2016-07-21T20:27:33Z | [
"python",
"subprocess",
"popen",
"kill",
"terminate"
] |
Microservice in Google App engine | 38,466,167 | <p>I plan to switch from a single app on a project to multiple apps on a project.
One being the current non-UI app and one will be based on Django.
I'm writing the code in Python2.7</p>
<p>I saw google example of app.yaml, but there is no examples for 2 or more apps.
There is already a similar question. but still with... | 0 | 2016-07-19T18:40:31Z | 38,477,839 | <p>You cannot have 2 or more apps in a single App Engine project but you can have 2 or more modules/services within a single App Engine app. See here for details: </p>
<p><a href="https://cloud.google.com/appengine/docs/python/modules/converting" rel="nofollow">https://cloud.google.com/appengine/docs/python/modules/co... | 1 | 2016-07-20T09:48:35Z | [
"python",
"google-app-engine",
"google-cloud-platform",
"microservices"
] |
Python if statement failing to match words from array 'in' string | 38,466,222 | <p>So I'm playing with a reddit API to monitor a sales subreddit, and I have this section of code:</p>
<pre><code>if(any(w.lower() in re.search('%s(.*)%s' % ("[h]", "[w]"), i['data']['title'].lower()).group(1).lower() for w in wants)
and i['data']['id'] not in urls):
... | 0 | 2016-07-19T18:43:59Z | 38,466,421 | <p>Try doing <code>w.strip().lower()</code> to clear the variable of unwanted spaces and linebreaks.</p>
<p>effectively:</p>
<pre><code>for w in wants:
if w.strip().lower() in i['data']['title'].lower() and i['data']['id'] not in urls:
urls[i['data']['id']] = [[i['data']['title'],i['data']['url']]
</code></pr... | 1 | 2016-07-19T18:55:47Z | [
"python",
"python-2.7",
"reddit-api"
] |
How to print generator object yielded value? | 38,466,232 | <p>I'm trying to make a class I created into an infinite series generator.</p>
<p>The class is basically like this (I omitted the other methods as it is large):</p>
<pre><code>class Step(object):
''' A Step taken through a field. '''
def __init__(self, step_id, offset, danger,
danger_limit=None, is_en... | 0 | 2016-07-19T18:44:26Z | 38,466,250 | <p>A <code>next()</code> method must return <strong>one</strong> value in the sequence the iterable represents. You returned a generator for each step.</p>
<p>Simply return the next value, there is no need to use a loop here:</p>
<pre><code>def next(self):
''' Yields next step in sequence. '''
return self.adv... | 2 | 2016-07-19T18:45:48Z | [
"python",
"python-2.7",
"generator",
"yield"
] |
Python3 tuple and list, print out string comma-seperated | 38,466,367 | <p>How do I print out my first three elemets in my tuple in a comma-seprated string (Im trying to learn: Dictionaries and Tuples, so I'm just playing around with it, thats why I've been converting it :) )</p>
<pre><code>tup = ("snake", 89, 9.63, "bookshelf", 1)
list(tup)
tup[1] = "cow"
tuple(tup)
</code></pre>
| 0 | 2016-07-19T18:52:24Z | 38,466,396 | <p>You <em>slice</em> the tuple then <em>unpack</em> it using <code>*</code>. Pass the <code>sep</code> parameter to <code>print</code> as comma <code>','</code></p>
<p>This does it:</p>
<pre><code>>>> tup = ("snake", 89, 9.63, "bookshelf", 1)
>>> print(*tup[:3], sep=',')
snake,89,9.63
</code></pre>... | 4 | 2016-07-19T18:53:59Z | [
"python",
"python-3.x",
"tuples"
] |
Python3 tuple and list, print out string comma-seperated | 38,466,367 | <p>How do I print out my first three elemets in my tuple in a comma-seprated string (Im trying to learn: Dictionaries and Tuples, so I'm just playing around with it, thats why I've been converting it :) )</p>
<pre><code>tup = ("snake", 89, 9.63, "bookshelf", 1)
list(tup)
tup[1] = "cow"
tuple(tup)
</code></pre>
| 0 | 2016-07-19T18:52:24Z | 38,467,134 | <p>Okey it dont quite work for me , I have a python file that have diffrent assignments where I learn dictionaries and tuples, and we answer by putting our answer in a variable called ANSWER and when I run the file it say if i completed the task or not.</p>
<p>This is what my answer looks like:</p>
<pre><code>null &l... | 0 | 2016-07-19T19:40:07Z | [
"python",
"python-3.x",
"tuples"
] |
web.py with FastCGI and lighttpd in windows | 38,466,392 | <p>I'm trying to make my web.py app in python 2.7 to production level as described in this <a href="http://webpy.org/install" rel="nofollow">document</a> in a <strong>windows</strong> environment. So I referred the </p>
<blockquote>
<p>Production --> LightTPD --> .. with FastCGI</p>
</blockquote>
<p>section in the ... | 0 | 2016-07-19T18:53:41Z | 38,473,134 | <p>Please try lighttpd 1.4.40, released earlier this week. It works much better on Windows than previous versions. You'll need a cygwin environment to build it from source, but then the executable can run outside the cygwin environment.</p>
| 0 | 2016-07-20T05:44:03Z | [
"python",
"windows",
"fastcgi",
"lighttpd",
"web.py"
] |
Python reading string into json | 38,466,457 | <p>I have this string </p>
<pre><code>"{u'Status': u'Up About an hour', u'Created': 1468874455, u'Image': u'instavote/vote', u'Labels': {u'com.docker.compose.service': u'webapp', u'com.docker.compose.config-hash': u'01e63b02746f28876c67969a7dfb39cd68ee598b8edc062a00a2812114c660a1', u'com.docker.compose.project': u'vot... | 0 | 2016-07-19T18:57:54Z | 38,466,730 | <p>You can use <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval()</code></a>:</p>
<pre><code>from ast import literal_eval
with open("input.txt") as f:
for line in f:
d = literal_eval(line)
print(d)
</code></pre>
| 1 | 2016-07-19T19:14:46Z | [
"python",
"json"
] |
Python, how to handle the "ValueError: unsupported pickle protocol: 4" error? | 38,466,523 | <p>I'm new to Python.
I've to run this <a href="https://github.com/shwhalen/targetfinder#custom-analyses" rel="nofollow">TargetFinder script ("Custom Analyses")</a>.</p>
<p>I installed all the required python packages, and copied the code into a script I named <code>main.py</code>, and ran it.
I got this error:</p>
<... | 0 | 2016-07-19T19:01:01Z | 38,466,878 | <p>The Pickle protocol is basically the file format. From the <a href="https://docs.python.org/3/library/pickle.html#pickle-protocols" rel="nofollow">documentation</a>,
<em>The higher the protocol used, the more recent the version of Python needed to read the pickle produced.</em> ... <em>Pickle protocol version 4 was... | 0 | 2016-07-19T19:23:28Z | [
"python",
"centos",
"pickle"
] |
Angular-cli with any other server | 38,466,529 | <p>I'm relatively new to Angular 2, and I'm trying to build an app using the angular-cli system. This works and I can ng-serve and the application comes up. However, it seems like a huge pain in the ass to try and serve the application with anything other than the ng-serve system. In particular I'm trying to serve the ... | 1 | 2016-07-19T19:01:16Z | 38,466,908 | <p>There's no requirement that Flask serves the frontend application.</p>
<p>Really all Flask would be doing with an Angular app is serving static files, something that is better handled by a web server like Nginx in production, or the framework's tools like ng-serve in development.</p>
<p>Meanwhile, Flask would act ... | 1 | 2016-07-19T19:25:35Z | [
"python",
"flask",
"angular2",
"angular-cli"
] |
Angular-cli with any other server | 38,466,529 | <p>I'm relatively new to Angular 2, and I'm trying to build an app using the angular-cli system. This works and I can ng-serve and the application comes up. However, it seems like a huge pain in the ass to try and serve the application with anything other than the ng-serve system. In particular I'm trying to serve the ... | 1 | 2016-07-19T19:01:16Z | 38,508,477 | <p>I've actually "sorta" solved the problem. I have a directory named "smoke" (short for smoke and mirrors ), and inside there I ran the angular-cli command:</p>
<pre><code>ng new static
</code></pre>
<p>This created the angular-cli start out application in the static directory. Then I created this (simplified) Pytho... | 0 | 2016-07-21T15:34:37Z | [
"python",
"flask",
"angular2",
"angular-cli"
] |
Python using int funtion | 38,466,542 | <p>I can't run the code below because of the 7th line <code>value = int(qty)*int(price)</code>. I can only run it if I use the <code>int()</code> function inside the <code>print()</code> function. Is there a way I can define it's an integer before I ask it to print? The same for <strong>float</strong>?</p>
<pre><code>... | 0 | 2016-07-19T19:02:15Z | 38,466,733 | <p>What's happening is that one of your items has either its price or quantity set to 0. When it's read in your code strips that 0 leaving you with an empty string, raising a ValueError when it is converted to an int.</p>
<p>You should probably remove the lstrips. At worst you will get numbers like "04" which the int ... | 0 | 2016-07-19T19:15:00Z | [
"python",
"integer"
] |
Python using int funtion | 38,466,542 | <p>I can't run the code below because of the 7th line <code>value = int(qty)*int(price)</code>. I can only run it if I use the <code>int()</code> function inside the <code>print()</code> function. Is there a way I can define it's an integer before I ask it to print? The same for <strong>float</strong>?</p>
<pre><code>... | 0 | 2016-07-19T19:02:15Z | 38,466,831 | <p>The following function return the integer value or None in case the string is not valid integer:</p>
<pre><code>def parseInt(ss):
try:
return int(ss)
except:
return None
</code></pre>
<p>Use this function to check if the string is an integer:</p>
<pre><code>for mid in file:
qty = mid[3... | 0 | 2016-07-19T19:20:58Z | [
"python",
"integer"
] |
Django Admin not saving data to the Database | 38,466,554 | <p>I am trying to save data from my Django Admin to my database but somehow it is not happening. I have created a form in one of my apps which my admin uses.I am new to Django and any help would be greatly appreciated.
Below is the relevant code:</p>
<h3>models.py</h3>
<pre><code>from __future__ import unicode_liter... | 1 | 2016-07-19T19:02:40Z | 38,468,898 | <pre><code>def save(self, commit=True):
# here you define `mentor_name`. OK.
mentor_name = self.cleaned_data.get('mentor_name', None)
# here you redefine `mentor_name`. I guess it is a typo and should be `mentee_name`.
mentor_name = self.cleaned_data.get('mentee_name', None)
# And... you don't do an... | 0 | 2016-07-19T21:33:30Z | [
"python",
"django",
"django-admin",
"django-database"
] |
Twisted Klein: Synchronous behavior | 38,466,624 | <p>I am using Twisted Klein because one of the promise of the framework is it is Asynchronous, but i tested that app i develop and a little code for testing and the framework behavior seems to be synchronous.</p>
<p>The test server code is:</p>
<pre><code># -*- encoding: utf-8 -*-
import json
import time
from datetim... | 2 | 2016-07-19T19:07:05Z | 38,506,826 | <p>You're missing many significant concepts of Twisted. In regards to synchronous behavior, you're absolutely correct, Klein behaves like synchronous frameworks, like Flask or Bottle, if you don't explicitly use async functions (ie. <a href="https://twistedmatrix.com/documents/current/core/howto/defer.html" rel="nofol... | 0 | 2016-07-21T14:21:36Z | [
"python",
"asynchronous",
"twisted",
"synchronous",
"klein-mvc"
] |
Pandas: replace column values based on match from another column | 38,466,682 | <p>I've a column in first data-frame <code>df1["ItemType"]</code> as below,</p>
<p><strong>Dataframe1</strong></p>
<pre><code>ItemType1
redTomato
whitePotato
yellowPotato
greenCauliflower
yellowCauliflower
yelloSquash
redOnions
YellowOnions
WhiteOnions
yellowCabbage
GreenCabbage
</code></pre>
<p>I need to replace th... | 2 | 2016-07-19T19:11:04Z | 38,466,774 | <p>This method requires you set your column names to 'type', then you can set off using merge and np.where </p>
<pre><code>df3 = df1.merge(df2,how='inner',on='type')['type','newType']
df3['newType'] = np.where(df['newType'].isnull(),df['type'],df['newType'])
</code></pre>
| 2 | 2016-07-19T19:17:32Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Pandas: replace column values based on match from another column | 38,466,682 | <p>I've a column in first data-frame <code>df1["ItemType"]</code> as below,</p>
<p><strong>Dataframe1</strong></p>
<pre><code>ItemType1
redTomato
whitePotato
yellowPotato
greenCauliflower
yellowCauliflower
yelloSquash
redOnions
YellowOnions
WhiteOnions
yellowCabbage
GreenCabbage
</code></pre>
<p>I need to replace th... | 2 | 2016-07-19T19:11:04Z | 38,466,941 | <p>You can convert <code>df2</code> into a Series indexed by <code>'ItemType2'</code>, and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a> on <code>df1</code>:</p>
<pre><code># Make df2 a Series indexed by 'ItemType'.
df2 = df2... | 2 | 2016-07-19T19:28:10Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Pandas: replace column values based on match from another column | 38,466,682 | <p>I've a column in first data-frame <code>df1["ItemType"]</code> as below,</p>
<p><strong>Dataframe1</strong></p>
<pre><code>ItemType1
redTomato
whitePotato
yellowPotato
greenCauliflower
yellowCauliflower
yelloSquash
redOnions
YellowOnions
WhiteOnions
yellowCabbage
GreenCabbage
</code></pre>
<p>I need to replace th... | 2 | 2016-07-19T19:11:04Z | 38,467,173 | <p>Use <code>map</code></p>
<p>All the logic you need:</p>
<pre><code>def update_type(t1, t2, dropna=False):
return t1.map(t2).dropna() if dropna else t1.map(t2).fillna(t1)
</code></pre>
<p>Let's make <code>'ItemType2'</code> the index of <code>Dataframe2</code></p>
<pre><code>update_type(Dataframe1.ItemType1,
... | 2 | 2016-07-19T19:42:25Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
opencv user drawing rectangle to crop | 38,466,701 | <p>I am trying to get a user to be able to draw a rectangle around an object and crop it-</p>
<p>with this code--</p>
<pre><code>def click_and_crop(event, x, y, flags, param):
global refPt, drawing, cropping
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
refPt = [(x, y)]
cropping = True
elif event =... | 0 | 2016-07-19T19:12:53Z | 38,466,867 | <p>You have to draw the image each time at the start of your event hanling routine instead of inside the last if condition.
THEN draw the sizer rectangle. Otherwise the previous rectangle is not deleted. Image is progressively destroyed.
The higher the refresh rate, the greener your image becomes.</p>
<p>A possible op... | 2 | 2016-07-19T19:22:56Z | [
"python",
"opencv"
] |
What is the time complexity of Python's search operation "some_element in some_list"? | 38,466,721 | <p>For example, I have a list l of n numbers, what is the time complexity for the search operation:</p>
<pre><code>if 35 in l:
# ......
</code></pre>
<p>Is it O(1) or O(n)?</p>
| -2 | 2016-07-19T19:14:11Z | 38,466,766 | <p>In CPython, O(n). <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">https://wiki.python.org/moin/TimeComplexity</a> see the third entry from the bottom in the "list" table.</p>
| 1 | 2016-07-19T19:17:01Z | [
"python",
"python-3.x"
] |
What is the time complexity of Python's search operation "some_element in some_list"? | 38,466,721 | <p>For example, I have a list l of n numbers, what is the time complexity for the search operation:</p>
<pre><code>if 35 in l:
# ......
</code></pre>
<p>Is it O(1) or O(n)?</p>
| -2 | 2016-07-19T19:14:11Z | 38,466,809 | <p>The <code>x in y</code> syntax works for many things, so it depends on the type of <code>y</code>.</p>
<p>For instance, if <code>y</code> is a <code>dict</code> or <code>set</code>, then the average case is O(1).
Where as if <code>y</code> is a list, then the time complexity is O(n). </p>
<p>As mentioned before, t... | 1 | 2016-07-19T19:19:54Z | [
"python",
"python-3.x"
] |
how to read many images in python and enumerate at the same time | 38,466,782 | <p>I am trying to read many images at the same time and enumerating them.
Here the values of the first image will be image[0] and the second is image[1]</p>
<pre><code>import mahotas as mh
filelist = ["khkg.png", "sss.png", "skh.png", "syiy.png"]
image = []
for imagefile in filelist:
for i in range(len(filelist)... | 1 | 2016-07-19T19:17:51Z | 38,466,828 | <p>If you want to set up the list beforehand, you'd have to use:</p>
<pre><code>image = [[] for x in range(len(filelist))]
</code></pre>
<p>when you call the storage list. </p>
| 0 | 2016-07-19T19:20:52Z | [
"python",
"arrays",
"image",
"loops",
"image-processing"
] |
how to read many images in python and enumerate at the same time | 38,466,782 | <p>I am trying to read many images at the same time and enumerating them.
Here the values of the first image will be image[0] and the second is image[1]</p>
<pre><code>import mahotas as mh
filelist = ["khkg.png", "sss.png", "skh.png", "syiy.png"]
image = []
for imagefile in filelist:
for i in range(len(filelist)... | 1 | 2016-07-19T19:17:51Z | 38,469,558 | <p>You can just append to the list as you move over the files.</p>
<pre><code>import mahotas as mh
filelist = ["khkg.png", "sss.png", "skh.png", "syiy.png"]
image = []
for imagefile in filelist:
for i in range(len(filelist)):
image.append(mh.imread(imagefile, as_grey=True))
</code></pre>
| 0 | 2016-07-19T22:30:34Z | [
"python",
"arrays",
"image",
"loops",
"image-processing"
] |
How can launch phantomJS with arguments in selenium with python? | 38,466,792 | <pre><code>service_args = ['--cookies-file=C:\\cookie\\cookies.txt']
driver = webdriver.PhantomJS(executable_path='Z:\\Win7\\python\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe',service_args=service_args)
</code></pre>
<p>This is my code.I want to enable cookiesfile in phantomJS.But it didn't work.There is no file in... | 0 | 2016-07-19T19:18:44Z | 38,472,047 | <p>Cookie file indeed is not created when PhantomJS's launched with --webdriver option. Seems it's a known bug: <a href="https://github.com/SeleniumHQ/selenium/issues/1911" rel="nofollow">https://github.com/SeleniumHQ/selenium/issues/1911</a></p>
| 1 | 2016-07-20T03:53:56Z | [
"python",
"selenium",
"phantomjs"
] |
How to implement heap traversal in Python | 38,466,796 | <p>I just made a heap class in python and am still working in Tree traversal. When I invoked <code>inoder function</code>, I got error said <code>None is not in the list</code>. In my three traversal functions, they all need <code>left</code> and <code>right</code> function. I assume that the problem is in these two fu... | 0 | 2016-07-19T19:19:03Z | 38,467,247 | <p>When you follow the tree to its left child, and there is no left child, then you should be done with that path. You are guaranteed to eventually get to None left child, which should be your base case to end recursion.</p>
<p>Instead you look up the value of the left child (using its index), then you reverse compute... | 0 | 2016-07-19T19:47:00Z | [
"python",
"heap",
"binary-tree",
"tree-traversal"
] |
How to implement heap traversal in Python | 38,466,796 | <p>I just made a heap class in python and am still working in Tree traversal. When I invoked <code>inoder function</code>, I got error said <code>None is not in the list</code>. In my three traversal functions, they all need <code>left</code> and <code>right</code> function. I assume that the problem is in these two fu... | 0 | 2016-07-19T19:19:03Z | 38,467,303 | <p>Imagine what happens when you call inorder on a leaf node. It enters the body of the if statement and tries to get the left and right children of the leaf node-- but there are no children-- so it chokes when <code>self.left(i)</code> evaluates to None and is fed into the <code>index</code> method. You need to revise... | 0 | 2016-07-19T19:50:30Z | [
"python",
"heap",
"binary-tree",
"tree-traversal"
] |
How to correctly take input using raw_input in python in below given conditions? | 38,466,799 | <p>I tried using <code>raw_input</code> for taking input of a large string in python interpreter, It works fine.</p>
<p>But when I tried doing the same by writing the <code>raw_input</code> in file. the received variable is not equal to the input.
I tried to print the length of the variable in both the scenario. Why i... | -1 | 2016-07-19T19:19:22Z | 38,467,397 | <p>This is a limit imposed by the environment in which you run the program. Your shell is only allocating 4096 characters for a single line of input. The python interactive interpreter allocates more, which is why it can accomodate a longer line. On my laptop, trying to enter that much text in one line seems to freeze... | 2 | 2016-07-19T19:56:13Z | [
"python",
"raw-input"
] |
Cloud9 IDE: postgres table does not exist | 38,466,834 | <p>I'm very new to cloud9 IDE, I followed <a href="https://community.c9.io/t/setting-up-postgresql/1573" rel="nofollow">this</a> tutorial to setup postgres. I used python pandas to load <code>csv</code> file into postgres. </p>
<pre><code>import pandas as pd
from sqlalchemy import create_engine
df = pd.read_csv('../fe... | 0 | 2016-07-19T19:21:01Z | 38,466,946 | <p>You're getting that error because you're trying to select from a table, when you're not connected to the database yet</p>
<p>connect to your database first with</p>
<p><code>\connect db</code> or <code>\c db</code></p>
<p>running the query should work now</p>
| 1 | 2016-07-19T19:28:34Z | [
"python",
"postgresql"
] |
asyncio. dynamically add coroutines to loop | 38,466,930 | <p>I'm writing app, which scans directory every second, checks for new files, and if they appeared - sends them via POST request and performs archiving. Assuming that number of files, which can appear in directory can be from 10 to 100 - I decided to use asyncio and aiohttp, to send requests concurrently.</p>
<p>Code:... | 1 | 2016-07-19T19:27:23Z | 38,469,406 | <p>Yes, it's correct.</p>
<p>P.S. Better to share the same session (perhaps with limited amount of parallel connections) than recreate a connection pool on every post request:</p>
<pre><code>session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=10))
</code></pre>
| 4 | 2016-07-19T22:15:40Z | [
"python",
"python-3.5",
"python-asyncio",
"aiohttp"
] |
How do i use time.sleep , and do something different each second | 38,466,931 | <p>I am making a PyQt5 splash screen in PyQt that creates a countdown within a splash picture, but the script isn't behaving right and it has different result each time.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet... | 0 | 2016-07-19T19:27:25Z | 38,466,968 | <p>Does this do what you want it to do? </p>
<pre><code>import time
for i in range(10):
time.sleep(1)
print(i)
time.sleep(1)
print("New command; Iteration:", i)
time.sleep(1)
print("New new command; Iteration:", i)
</code></pre>
| 0 | 2016-07-19T19:29:29Z | [
"python",
"time",
"process",
"pyqt5"
] |
How do i use time.sleep , and do something different each second | 38,466,931 | <p>I am making a PyQt5 splash screen in PyQt that creates a countdown within a splash picture, but the script isn't behaving right and it has different result each time.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet... | 0 | 2016-07-19T19:27:25Z | 38,466,992 | <p>You can</p>
<pre><code>import time
for i in range(0, 10):
time.sleep(0)
print i
</code></pre>
<p>Or in your example...</p>
<pre><code>for i in range(0, 10):
time.sleep(1)
splash = QtWidgets.QSplashScreen(QtGui.QPixmap("22.png"))
splash.showMessage(str(count[i]), QtCore.Qt.AlignHCenter | QtCor... | 0 | 2016-07-19T19:30:59Z | [
"python",
"time",
"process",
"pyqt5"
] |
Can one delete a specific document in Elastic Search using Python | 38,466,938 | <p>I know that each document in my database has a unique '_id'. Is it possible to delete a specific document using its _id attribute? If so, how?</p>
| 1 | 2016-07-19T19:27:50Z | 38,467,063 | <p>Yes, you can achieve that using the <a href="https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.delete" rel="nofollow"><code>delete</code> method</a></p>
<pre><code>es.delete(index = "my_index", doc_type = "my_type", id = "1234")
</code></pre>
| 1 | 2016-07-19T19:34:32Z | [
"python",
"elasticsearch"
] |
Python: Searching a binary file (.PLM) for unicode string | 38,467,071 | <p>I'm trying to extract a directory name from a .PLM file using <strong>Python 2.7</strong> on Windows 10. A .PLM file is a proprietary file format used for Panasonic voice recorders, which stores the name of the directory for the voice recordings.</p>
<p>(example: say I have a voice recording, which I'd like to save... | 2 | 2016-07-19T19:35:03Z | 38,467,888 | <p>In Python 2, reading from a binary file returns a string, so there's no need to use <code>str</code> on it. Also if for some reason the file is ill-formed and there's no zero byte in it, <code>read</code> will return an empty string. You can check for both conditions with a small modification to your test.</p>
<pre... | 1 | 2016-07-19T20:26:34Z | [
"python"
] |
Numpy reading data from '.npy' file directly into arrays | 38,467,091 | <p>This might be a silly question, but I can't seem to find an answer for it. I have a large array that I've previously saved using <code>np.save</code>, and now I'd like to load the data into a new file, creating a separate list from each column. The only issue is that some of the rows in my large array only have a si... | 0 | 2016-07-19T19:36:40Z | 38,469,377 | <p>With varying length sub arrays, this is dtype=object array. For most purposes this is the same as a list of these subarrays. So most actions will require iteration.</p>
<p>A variant on your action would be a list comprehension</p>
<pre><code>In [61]: dd=[[nan,nan,nan] if len(i)==1 else i for i in d]
In [62]: dd... | 1 | 2016-07-19T22:12:09Z | [
"python",
"arrays",
"numpy"
] |
Numpy reading data from '.npy' file directly into arrays | 38,467,091 | <p>This might be a silly question, but I can't seem to find an answer for it. I have a large array that I've previously saved using <code>np.save</code>, and now I'd like to load the data into a new file, creating a separate list from each column. The only issue is that some of the rows in my large array only have a si... | 0 | 2016-07-19T19:36:40Z | 38,478,801 | <p>A shorter way using pandas:</p>
<pre><code>import numpy as np
import pandas as pd
data = np.array([[5,12,3], [np.nan], [10,13,9], [np.nan], [np.nan]])
df = pd.DataFrame.from_records(data.tolist())
df.columns = ['depth','upper','lower']
</code></pre>
<p>Output:</p>
<pre><code>>>> df
depth upper lowe... | 1 | 2016-07-20T10:29:43Z | [
"python",
"arrays",
"numpy"
] |
Converting string values inside a dictionary to int | 38,467,108 | <p>I have a dictionary of dictionaries as follows:</p>
<pre><code>MyDict = {'A1': {'B1': '1', 'B2' : '2'}, 'A2': {'B3': '3', 'B4' : '4'}}
</code></pre>
<p>How do I convert the values inside the dictionary to int, as my script currently reads these numbers in as strings. I want to use the numbers in calculations.</p>
... | 1 | 2016-07-19T19:38:28Z | 38,467,162 | <p>You can use a nested dictionary comprehension where you call <code>int()</code> on each of the inner values (represented here by <code>v2</code>):</p>
<pre><code>my_dict = {'A1': {'B1': '1', 'B2' : '2'}, 'A2': {'B3': '3', 'B4' : '4'}}
my_converted_dict = {k1: {k2: int(v2) for k2, v2 in v1.items()}
... | 1 | 2016-07-19T19:41:43Z | [
"python",
"dictionary",
"int"
] |
SCP Through python is not transferring file | 38,467,156 | <p>I have two Raspberry Pi's. I am trying to transfer files from one Pi to the other using scp. I am trying to do this through Python because the program that will be transferring files is a python file.</p>
<p>below is the shell script I have for the SCP part (Blurred out the pass and IP):</p>
<pre><code>#!/bin/sh
s... | 0 | 2016-07-19T19:41:23Z | 38,468,485 | <p><strong>For the first query</strong></p>
<p>You can use 'subprocess.popen' to get output(STDOUT) and error(STDERR) for the executed command.</p>
<pre><code>import subprocess
cmd = 'sshpass -p ****** scp dinesh.txt root@256.219.210.135:/root'
p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subproce... | 0 | 2016-07-19T21:03:04Z | [
"python",
"shell",
"raspberry-pi",
"scp"
] |
SCP Through python is not transferring file | 38,467,156 | <p>I have two Raspberry Pi's. I am trying to transfer files from one Pi to the other using scp. I am trying to do this through Python because the program that will be transferring files is a python file.</p>
<p>below is the shell script I have for the SCP part (Blurred out the pass and IP):</p>
<pre><code>#!/bin/sh
s... | 0 | 2016-07-19T19:41:23Z | 38,468,545 | <p>I found a much easier way of tackling all of this</p>
<pre><code>sshpass -p ###### scp -o StrictHostKeyChecking=no test.txt pi@IP:/home/pi
</code></pre>
<p>The -o switch allows me to auto store the IP into known hosts thus I do not need to communicate with the shell at all. The interaction from Python to Shell wo... | 0 | 2016-07-19T21:07:11Z | [
"python",
"shell",
"raspberry-pi",
"scp"
] |
SCP Through python is not transferring file | 38,467,156 | <p>I have two Raspberry Pi's. I am trying to transfer files from one Pi to the other using scp. I am trying to do this through Python because the program that will be transferring files is a python file.</p>
<p>below is the shell script I have for the SCP part (Blurred out the pass and IP):</p>
<pre><code>#!/bin/sh
s... | 0 | 2016-07-19T19:41:23Z | 40,128,330 | <p>If you don't mind to try other approaches it worth to use SCPClient from scp import. </p>
| 0 | 2016-10-19T10:10:18Z | [
"python",
"shell",
"raspberry-pi",
"scp"
] |
Exclude deleted objects from Django inline formset | 38,467,184 | <p>I need a for loop condition for my Django inline formset for a particular reason. But I want to exclude deleted objects from that loop. </p>
<pre><code>def my_fun(request, pk):
instance = get_object_or_404(Sale.objects.filter(pk=pk, is_deleted=False))
SaleItemFormset = inlineformset_factory(
Sale,
S... | 0 | 2016-07-19T19:43:29Z | 38,467,874 | <p><code>Formset</code> has a <code>deleted_forms</code> prop You can use it to exclude them.</p>
<pre><code>if sale_item_formset.is_valid():
deleted_forms = sale_item_formset.deleted_forms
for form in sale_item_formset:
if form not in deleted_forms:
#do some staff
</code></pre>
| 2 | 2016-07-19T20:25:45Z | [
"python",
"django"
] |
Python: substring existence | 38,467,187 | <p>I have an HTML scraper that parses a particular set of sites to get the names of products being sold. If the product is in our whitelist, we process it differently than a product that isn't.
Now the scraper returns the whole name of the product. It could be 'Nike Air Jordan' or 'Air Jordan by Nike' or 'LunarEpic by ... | 1 | 2016-07-19T19:43:56Z | 38,467,248 | <p>You can use the builtin <code>any</code> function:</p>
<pre><code>products = ['Nike', 'Reebok', 'Adidas', ...]
if any(product in product_name for product in products):
...
</code></pre>
<p>The other alternative is to use regular expressions:</p>
<pre><code>regex = '|'.join(re.escape(product) for product in pr... | 4 | 2016-07-19T19:47:07Z | [
"python",
"string",
"list"
] |
Python: substring existence | 38,467,187 | <p>I have an HTML scraper that parses a particular set of sites to get the names of products being sold. If the product is in our whitelist, we process it differently than a product that isn't.
Now the scraper returns the whole name of the product. It could be 'Nike Air Jordan' or 'Air Jordan by Nike' or 'LunarEpic by ... | 1 | 2016-07-19T19:43:56Z | 38,467,274 | <p>you may be looking for the <code>any()</code> function with a generator comprehension</p>
<pre><code>if any(product in product_name for product in ['Nike', 'Reebok', 'Adidas']):
</code></pre>
| 2 | 2016-07-19T19:48:43Z | [
"python",
"string",
"list"
] |
Merging multiple dataframes on column | 38,467,193 | <p>I am trying to merge/join multiple <code>Dataframe</code>s and so far I have no luck. I've found <code>merge</code> method, but it works only with two Dataframes. I also found this SO <a href="http://stackoverflow.com/a/23671390/1080517">answer</a> suggesting to do something like that:</p>
<pre><code>df1.merge(df2,... | 3 | 2016-07-19T19:44:12Z | 38,467,413 | <p>use <code>pd.concat</code></p>
<pre><code>dflist = [df1, df2]
keys = ["%d" % i for i in range(1, len(dflist) + 1)]
merged = pd.concat([df.set_index('name') for df in dflist], axis=1, keys=keys)
merged.columns = merged.swaplevel(0, 1, 1).columns.to_series().str.join('_')
merged
</code></pre>
<p><a href="http://i.... | 7 | 2016-07-19T19:57:14Z | [
"python",
"pandas",
"dataframe"
] |
Merging multiple dataframes on column | 38,467,193 | <p>I am trying to merge/join multiple <code>Dataframe</code>s and so far I have no luck. I've found <code>merge</code> method, but it works only with two Dataframes. I also found this SO <a href="http://stackoverflow.com/a/23671390/1080517">answer</a> suggesting to do something like that:</p>
<pre><code>df1.merge(df2,... | 3 | 2016-07-19T19:44:12Z | 38,467,793 | <p>The solution of @piRSquared works for 20+ dataframes, see the following script for creating 20+ example dataframes:</p>
<pre><code>N = 25
dflist = []
for d in range(N):
df = pd.DataFrame(np.random.rand(3,2))
df.columns = ['attr1', 'attr2']
df['name'] = ['a', 'b', 'c']
dflist.append(df)
</code></p... | -1 | 2016-07-19T20:20:53Z | [
"python",
"pandas",
"dataframe"
] |
Merging multiple dataframes on column | 38,467,193 | <p>I am trying to merge/join multiple <code>Dataframe</code>s and so far I have no luck. I've found <code>merge</code> method, but it works only with two Dataframes. I also found this SO <a href="http://stackoverflow.com/a/23671390/1080517">answer</a> suggesting to do something like that:</p>
<pre><code>df1.merge(df2,... | 3 | 2016-07-19T19:44:12Z | 38,468,037 | <p>use reduce:</p>
<pre><code>def my_merge(df1, df2):
return df1.merge(df2,on='name')
final_df = reduce(my_merge, df_list)
</code></pre>
<p>considering df_list to be a list of your dataframes </p>
| 1 | 2016-07-19T20:35:12Z | [
"python",
"pandas",
"dataframe"
] |
moving a file in python using shutil | 38,467,380 | <p>I know there have been some posts on how to move a file in python but I am a little confused. I am working on a program that has a file called test.txt</p>
<p>The file path is this: <code>C:\Users\user\Desktop\Project1\Project1</code> <br>
I want to move it to: <code>C:\Users\user\Documents\ProjectMoved</code> <br>... | 1 | 2016-07-19T19:55:23Z | 38,467,461 | <p>Might be worth checking the file exists and then trying to specify paths using <code>os.path.join</code>:</p>
<pre><code>import shutil
import os
from os.path import join
src = join('/', 'Users', 'username', 'Desktop', 'a.pdf')
dst = join('/', 'Users', 'username', 'Documents', 'a.pdf')
shutil.move(src, dst)
</code... | 1 | 2016-07-19T20:00:34Z | [
"python",
"shutil"
] |
moving a file in python using shutil | 38,467,380 | <p>I know there have been some posts on how to move a file in python but I am a little confused. I am working on a program that has a file called test.txt</p>
<p>The file path is this: <code>C:\Users\user\Desktop\Project1\Project1</code> <br>
I want to move it to: <code>C:\Users\user\Documents\ProjectMoved</code> <br>... | 1 | 2016-07-19T19:55:23Z | 39,088,715 | <p>This problem can also be solved this way if your trying to move multiple .txt files from Folder A to folder B. This principle can be applied to your problem since your moving .txt file. </p>
<pre><code>import os
import shutil
os.chdir('C:\\')
dir_src = ("C:\\Folder A\\")
dir_dst = ("C:\\Folder B\\")
for filenam... | 0 | 2016-08-22T21:03:57Z | [
"python",
"shutil"
] |
How can I send elements in csv file to variables in Python? | 38,467,442 | <p>I have an excel/csv file containing information in the following format: </p>
<pre><code> A B C
1 3 A T
2 5 T G
3 100 A C
4 101 A A
</code></pre>
<p>I would like to set var1 to 3, var2 to A, and var3 to T, run some operations with these variables, and do the same on... | 1 | 2016-07-19T19:59:36Z | 38,467,518 | <p>Open the CSV and then take advantage of the fact that everything is separated by commas. Note how we use <code>[1:]</code> to ignore the first line.</p>
<pre><code>f = open("yourcsv.csv","r")
lines = f.readlines()
for i in lines[1:]:
split_line = i.split()
var1 = split_line[1]
var2 = split_line[2]
... | 0 | 2016-07-19T20:03:52Z | [
"python",
"excel",
"csv"
] |
How can I send elements in csv file to variables in Python? | 38,467,442 | <p>I have an excel/csv file containing information in the following format: </p>
<pre><code> A B C
1 3 A T
2 5 T G
3 100 A C
4 101 A A
</code></pre>
<p>I would like to set var1 to 3, var2 to A, and var3 to T, run some operations with these variables, and do the same on... | 1 | 2016-07-19T19:59:36Z | 38,467,622 | <p>you can use dict to achieve the request</p>
<pre><code>import csv
varLst = [var1,var2,var3]
with open(filepath,'r') as f:
r = csv.reader(f)
for line in r:
varDict = { v: varLst[i] for i,v in enumerate(line) }
# do something
# if you want call var1 ==> varDict['3'] for first line of data
</code... | 0 | 2016-07-19T20:10:10Z | [
"python",
"excel",
"csv"
] |
How can I send elements in csv file to variables in Python? | 38,467,442 | <p>I have an excel/csv file containing information in the following format: </p>
<pre><code> A B C
1 3 A T
2 5 T G
3 100 A C
4 101 A A
</code></pre>
<p>I would like to set var1 to 3, var2 to A, and var3 to T, run some operations with these variables, and do the same on... | 1 | 2016-07-19T19:59:36Z | 38,467,710 | <p>Managed to work out an inelegant solution myself while I was waiting for responses and I figured I'd offer my own approach of the problem in case it can help someone in the future or to get feedback on it. Both methods suggested above worked as well!</p>
<pre><code>import csv
with open('scz.csv', newline='') as csv... | 0 | 2016-07-19T20:15:45Z | [
"python",
"excel",
"csv"
] |
Python: Passing column data from pandas df to bokeh plotting function | 38,467,455 | <p>I'm working on automating plotting functions for metabolomics data with bokeh. Currently, I'm trying to read in my dataframe from CSV and iterate through the columns generating box plots for each metabolite (column).</p>
<p>I have an example df that looks like this:</p>
<pre><code>Sample Group AMP ADP A... | 0 | 2016-07-19T20:00:14Z | 38,470,419 | <p>If you want to organize them horizontally, you can create different graphs, and then you could use for instance hplot from bokeh.io as follows:</p>
<pre><code>import pandas
from bokeh.plotting import figure, output_file, show, save
from bokeh.charts import BoxPlot
from bokeh.io import hplot
df = pandas.read_csv("t... | 1 | 2016-07-20T00:09:21Z | [
"python",
"pandas",
"plot",
"boxplot",
"bokeh"
] |
How to get particular Column of DataFrame in pandas? | 38,467,470 | <p>I have a data frame name it <strong>df</strong> I want to have like its first and second colums(series) in variable <strong>x</strong> and <strong>y</strong>.</p>
<p>I would have done that by name of the column like <code>df['A']</code> or <code>df['B']</code> or something like that.</p>
<p>But problem here is tha... | 1 | 2016-07-19T20:00:56Z | 38,467,566 | <p>You might want to read the
<a href="http://pandas-docs.github.io/pandas-docs-travis/indexing.html" rel="nofollow">documentation on indexing</a>. </p>
<p>For what you specified in the question, you can use</p>
<pre><code>x, y = df.iloc[:, [0]], df.iloc[:, [1]]
</code></pre>
| 0 | 2016-07-19T20:06:58Z | [
"python",
"pandas"
] |
How to get particular Column of DataFrame in pandas? | 38,467,470 | <p>I have a data frame name it <strong>df</strong> I want to have like its first and second colums(series) in variable <strong>x</strong> and <strong>y</strong>.</p>
<p>I would have done that by name of the column like <code>df['A']</code> or <code>df['B']</code> or something like that.</p>
<p>But problem here is tha... | 1 | 2016-07-19T20:00:56Z | 38,467,594 | <p>Set the <code>names</code> kwarg when reading the DataFrame (see the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code> docs</a>.</p>
<p>So instead of <code>pd.read_csv('kndkma')</code> use <code>pd.read_csv('kndkma', names=['a', 'b', ...])</cod... | 2 | 2016-07-19T20:08:57Z | [
"python",
"pandas"
] |
How to get particular Column of DataFrame in pandas? | 38,467,470 | <p>I have a data frame name it <strong>df</strong> I want to have like its first and second colums(series) in variable <strong>x</strong> and <strong>y</strong>.</p>
<p>I would have done that by name of the column like <code>df['A']</code> or <code>df['B']</code> or something like that.</p>
<p>But problem here is tha... | 1 | 2016-07-19T20:00:56Z | 38,467,704 | <p>It is usually easier to name the columns when you read or create the DataFrame, but you can also name (or rename) the columns afterwards with something like:</p>
<pre><code>df.columns = ['A','B', ...]
</code></pre>
| 0 | 2016-07-19T20:15:12Z | [
"python",
"pandas"
] |
Should I use class based or function based views for this? | 38,467,480 | <p>This will be a long post so bear with me. I think I came to the realization that I have to re-write a lot of code that I previously wrote in my models. </p>
<p>my models look like this:</p>
<pre><code>class Word(models.Model):
'''Word table for word, and frequency data'''
language = models.ForeignKey(Lang... | 1 | 2016-07-19T20:01:21Z | 38,467,737 | <ol>
<li><p>You can use what you want, the benefit of <a href="https://docs.djangoproject.com/en/1.9/topics/class-based-views/" rel="nofollow">Class Based Views</a> is inheritance. You can extend your base <code>View</code> class and use it throughout your project. Also, it's quite fast to get operations working with <... | 2 | 2016-07-19T20:17:16Z | [
"python",
"django"
] |
How to put a Tkinter Image into background? keep getting same error msg no matter the file type: | 38,467,545 | <blockquote>
<p>Message File Name<br>
Syntax Error<br>
(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: >truncated \UXXXXXXXX escape C:\visualexample.py </p>
</blockquote>
<p>I've Imported PIL and tkinter, and tried a few different things, but the one I see mostly suggested is:</p>... | 0 | 2016-07-19T20:05:41Z | 38,468,747 | <p>It seems like PIL has serious problems. I think it doesn't support Python 3 yet at all (<a href="https://mail.python.org/pipermail/image-sig/2009-March/005498.html" rel="nofollow">https://mail.python.org/pipermail/image-sig/2009-March/005498.html</a>). But I also tried it on Python 2.7.11, and couldn't show any imag... | 0 | 2016-07-19T21:21:02Z | [
"python",
"image",
"tkinter"
] |
How to put a Tkinter Image into background? keep getting same error msg no matter the file type: | 38,467,545 | <blockquote>
<p>Message File Name<br>
Syntax Error<br>
(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: >truncated \UXXXXXXXX escape C:\visualexample.py </p>
</blockquote>
<p>I've Imported PIL and tkinter, and tried a few different things, but the one I see mostly suggested is:</p>... | 0 | 2016-07-19T20:05:41Z | 38,476,831 | <p>I had also problems with PIL and Tkinter Images... I had been searching for hours when I found a solution. Try this, I hope it will help you, this simple program runs a label with an image on it:</p>
<pre><code>from tkinter import *
import PIL.Image
import PIL.ImageTk
root = Tk()
image = PIL.ImageTk.PhotoImage(PI... | 0 | 2016-07-20T09:02:54Z | [
"python",
"image",
"tkinter"
] |
python, suds and client certificate: SAXParseException: not well-formed (invalid token) | 38,467,546 | <p>I have implementing a SOAP client with python (2.6.6) and suds. The server needs a certificate from the client for authentication. For implementing this in python and with suds I have use <a href="http://stackoverflow.com/a/21109050/1465758">this answer from Andre Miras</a>. This seem's also to work because I can ac... | 0 | 2016-07-19T20:05:46Z | 38,489,118 | <p>I'm a beginner with python and so I must play around with the code for several hours (without really understanding what I'm doing ... ;-) ) but I found the solution: I have replace the following lines (the comment is the old code, uncomment line the new new code:</p>
<pre><code>#import io
import StringIO
...
# ... | 0 | 2016-07-20T19:20:42Z | [
"python",
"soap",
"wsdl",
"suds"
] |
extracting information after keyword python regex | 38,467,552 | <p>I am reading in a file with lines of data that look like this:</p>
<pre><code>ifgfilename: 150304SN.0045; Channel: 1; Name of location: Boulder; Latitude of location: 40.038; Longitude of location: -105.243;
</code></pre>
<p>I need to extract the information so I wrote a regex code like this:</p>
<pre><code>impor... | 1 | 2016-07-19T20:06:11Z | 38,467,679 | <p>It seems you are unnecessarily including <code>^</code> at the start of each regex which means start of line. Also change the <code>.*</code> to a set of all characters but semicolon (<code>[^;]+</code>) to match the value you want. In my tests I had the casing wrong, you might be getting None for the same reason, ... | 1 | 2016-07-19T20:13:59Z | [
"python",
"regex"
] |
How can I rewrite my conditional statement to don't print -1? | 38,467,560 | <p>My if statement looks weird, but I can't think of how I prevent of -1 value from printing :</p>
<pre><code>### script counts the number of times that a key string appears in target string
from string import *
def countSubStringMatch(target,key):
value = target.find(key, 0)
print value
while value &g... | -3 | 2016-07-19T20:06:44Z | 38,467,647 | <p>You can remove the initial print statement, and instead print the value at the beginning of the body of your loop, rather than at the end.</p>
<pre><code>def countSubStringMatch(target,key):
value = target.find(key, 0)
while value > -1:
print value
value = value + 1
value = targ... | 2 | 2016-07-19T20:11:43Z | [
"python"
] |
How can I rewrite my conditional statement to don't print -1? | 38,467,560 | <p>My if statement looks weird, but I can't think of how I prevent of -1 value from printing :</p>
<pre><code>### script counts the number of times that a key string appears in target string
from string import *
def countSubStringMatch(target,key):
value = target.find(key, 0)
print value
while value &g... | -3 | 2016-07-19T20:06:44Z | 38,467,878 | <p>Please use as much as possible the code, other people have already written. Based on <a href="http://stackoverflow.com/questions/4664850/find-all-occurrences-of-a-substring-in-python">Find all occurrences of a substring in Python</a>:</p>
<pre><code>string = "atgacatgcacaagtatgcat"
print [i for i in range(len(strin... | 2 | 2016-07-19T20:25:55Z | [
"python"
] |
How can I rewrite my conditional statement to don't print -1? | 38,467,560 | <p>My if statement looks weird, but I can't think of how I prevent of -1 value from printing :</p>
<pre><code>### script counts the number of times that a key string appears in target string
from string import *
def countSubStringMatch(target,key):
value = target.find(key, 0)
print value
while value &g... | -3 | 2016-07-19T20:06:44Z | 38,467,914 | <pre><code>def countSubStringMatch(target,key):
res = set( [ data.find('atg',i) for i in range(len(data)) ] )
res.remove(-1)
print res
countSubStringMatch("atgacatgcacaagtatgcat","atg")
set([0, 5, 15])
</code></pre>
| 1 | 2016-07-19T20:27:41Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.