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 |
|---|---|---|---|---|---|---|---|---|---|
object has no attributes. New to classes in python | 37,871,095 | <pre><code>import praw
import time
class getPms():
r = praw.Reddit(user_agent="Test Bot By /u/TheC4T")
r.login(username='*************', password='***************')
cache = []
inboxMessage = []
file = 'cache.txt'
def __init__(self):
cache = self.cacheRead(self, self.file)
sel... | 0 | 2016-06-16T23:48:17Z | 37,871,253 | <p>Here are few points:</p>
<ol>
<li>Unless you're explicitly inheriting from some specific class, you can omit parenthesis:</li>
</ol>
<p><code>class A(object):</code>, <code>class A():</code>, <code>class A:</code> are equivalent.</p>
<ol start="2">
<li><p>Your class name and class method have the same name. I'm n... | 0 | 2016-06-17T00:12:30Z | [
"python",
"class"
] |
Python - What's wrong with my code? | 37,871,294 | <p>So, i know this is so basic, but i'm getting this error:
What can i do to repair this? y.y </p>
<blockquote>
<p>Traceback (most recent call last): File
"/home/coding/Documents/Python Repository/2 - Numbers & math (Loan
Calclator).py", line 40, in
monthly_payment = float(loan_amount) * [0.05 * (1.... | 0 | 2016-06-17T00:18:16Z | 37,871,311 | <p>In your line:</p>
<pre><code> monthly_payment = float(loan_amount) * [0.05 * (1.0 + 0.05) * float(num_of_payments)] / [(1.0 + 0.05) * float(num_of_payments) - 1.0]
</code></pre>
<p>You are using square brackets (in this case used to create a list) as a means of specifying order of operations. This should be <co... | 6 | 2016-06-17T00:20:59Z | [
"python",
"python-2.7",
"python-3.x"
] |
Replace values in column of Pandas DataFrame using a Series lookup table | 37,871,386 | <p>I want to replace a column of values in a DataFrame with a more accurate/complete set of values generated by a look-up table in the form of a Series that I have prepared.</p>
<p>I thought I could do it this way but the result is not as expected.</p>
<p>Here is the DataFrame I want to fix:</p>
<pre><code>In [6]: d... | 1 | 2016-06-17T00:31:52Z | 37,871,710 | <p>This works. However, I'm pretty sure there must be a simpler way of doing this.</p>
<pre><code>In [50]: df_normalised.name = pd.Series(names[df_normalised.code].values)
In [51]: df_normalised.head(10)
Out[51]:
code name
0 8 Human developme... | 0 | 2016-06-17T01:22:55Z | [
"python",
"pandas",
"dataframe"
] |
Replace values in column of Pandas DataFrame using a Series lookup table | 37,871,386 | <p>I want to replace a column of values in a DataFrame with a more accurate/complete set of values generated by a look-up table in the form of a Series that I have prepared.</p>
<p>I thought I could do it this way but the result is not as expected.</p>
<p>Here is the DataFrame I want to fix:</p>
<pre><code>In [6]: d... | 1 | 2016-06-17T00:31:52Z | 37,876,121 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map()</a> function for that:</p>
<pre><code>In [38]: df_normalised['name'] = df_normalised['code'].map(name)
In [39]: df_normalised
Out[39]:
code name
0 ... | 1 | 2016-06-17T07:56:32Z | [
"python",
"pandas",
"dataframe"
] |
unable to cleanly close the QDialog in PyQT using Esc Key | 37,871,414 | <p>I have a simple login application which prompts user for username and password.
there are 2 buttons, one for logging in and other for cancel.</p>
<p>in the slot for the cancel button, I have the following code</p>
<pre><code>self.cancelbutton.clicked.connect(self.closeIt)
def closeIt(self):
self.close()
</co... | -1 | 2016-06-17T00:36:53Z | 37,871,493 | <p>You're calling <code>sys.exit()</code>. That will immediately exit out of python. Also, it doesn't really make much sense to call <code>form.exec_()</code> and then call <code>app.exec_()</code></p>
<p>You should only need the <code>app.exec_()</code></p>
<pre><code>app = QApplication(sys.argv)
form = x_LoginFor... | 1 | 2016-06-17T00:50:43Z | [
"python",
"pyqt4"
] |
How can I install BeautifulSoup in a Digital Ocean droplet? | 37,871,418 | <p>I'm using the most basic service, running with Ubuntu (the standard config), I have developed some python scripts in my own PC that uses bs4, when I upload them it says the classical error:</p>
<p><code>bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: xml. Do you need to install a ... | 0 | 2016-06-17T00:38:10Z | 37,871,468 | <p>If you're using <code>ubuntu</code>, it's way easier to install the pre-packaged version using <code>apt-get install python-bs4</code>or <code>apt-get install python3-bs4</code></p>
| 1 | 2016-06-17T00:46:35Z | [
"python",
"beautifulsoup",
"digital-ocean"
] |
How to pass a Mongo Cursor object to a Jinja template? | 37,871,497 | <p>I have a Mongo database and I'd like to make a script that performs a query and passes the results to an html file. </p>
<p>This rendered html file will be used as the html body of an email I will send to my colleagues.</p>
<p>However the template is not rendered, here is what I've got</p>
<p>My html looks someth... | 0 | 2016-06-17T00:51:01Z | 37,889,204 | <p>Ok I realized it was a syntax error in the for statement, It should be:</p>
<pre><code>{% for q in query %}
{% endfor %}}
</code></pre>
| 0 | 2016-06-17T19:39:44Z | [
"python",
"mongodb",
"python-2.7",
"jinja2",
"pymongo"
] |
How can I do computations on dataframes or series that have different indexes in PANDAS? | 37,871,511 | <p>I have two Series that are of the same length and datatype. Both are float64. The only difference are the indexes both are dates but one date is at the beginnning of the month and the other is at the end of the month. How can I do computations like correlation or covariance on Series or dataframes that have differ... | 1 | 2016-06-17T00:53:12Z | 37,871,631 | <p><code>reset_index(drop=True)</code> for the things you want to correlate then concat.</p>
<pre><code>s1 = pd.DataFrame(np.random.rand(10), list('abcdefghij'), columns=['s1'])
s2 = pd.DataFrame(np.random.rand(10), list('ABCDEFGHIJ'), columns=['s2'])
print pd.concat([s.reset_index(drop=True) for s in [s1, s2]], axis... | 0 | 2016-06-17T01:11:33Z | [
"python",
"pandas",
"dataframe",
"series",
"quandl"
] |
How can I do computations on dataframes or series that have different indexes in PANDAS? | 37,871,511 | <p>I have two Series that are of the same length and datatype. Both are float64. The only difference are the indexes both are dates but one date is at the beginnning of the month and the other is at the end of the month. How can I do computations like correlation or covariance on Series or dataframes that have differ... | 1 | 2016-06-17T00:53:12Z | 37,876,357 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow">resample()</a> function in order to resample one of your indices (our goal is have either both indices BoM or EoM):</p>
<p><strong>data:</strong></p>
<pre><code>In [63]: df_bom
Out[63]:
... | 0 | 2016-06-17T08:09:55Z | [
"python",
"pandas",
"dataframe",
"series",
"quandl"
] |
Faster way of removing items from list | 37,871,524 | <p>I have a list that is around 10M in length. Each index contains a dictionary</p>
<p>so for instance...</p>
<pre><code>l = [{'id': 'y'}, {'id', 'x'}, {'id', 'z'} ... ]
</code></pre>
<p>I have another list with items that I want to remove</p>
<pre><code>m = ['y', 'z']
</code></pre>
<p>I tried</p>
<pre><code>l = ... | 0 | 2016-06-17T00:54:46Z | 37,871,670 | <p>I doubt you'll get much better than:</p>
<pre><code>s = set(m)
l = [i for i in l if i['id'] not in s]
</code></pre>
<p>This would likely be much quicker then creating a loop and deleting items one at a time. There is usually a tradeoff though between memory and speed - this should be reasonably fast, but will use... | 2 | 2016-06-17T01:18:05Z | [
"python",
"list",
"memory",
"time",
"big-o"
] |
Faster way of removing items from list | 37,871,524 | <p>I have a list that is around 10M in length. Each index contains a dictionary</p>
<p>so for instance...</p>
<pre><code>l = [{'id': 'y'}, {'id', 'x'}, {'id', 'z'} ... ]
</code></pre>
<p>I have another list with items that I want to remove</p>
<pre><code>m = ['y', 'z']
</code></pre>
<p>I tried</p>
<pre><code>l = ... | 0 | 2016-06-17T00:54:46Z | 37,871,714 | <p>if you can store only the indices to be deleted in the list temp</p>
<pre><code>temp = [0,2,...]
</code></pre>
<p>then this could work faster</p>
<pre><code>np.delete(l,temp)
</code></pre>
| 1 | 2016-06-17T01:23:43Z | [
"python",
"list",
"memory",
"time",
"big-o"
] |
Python Query From Teradata pyodbc Module | 37,871,607 | <pre><code>import pyodbc
conn = pyodbc.connect('DRIVER={Teradata};DBCNAME=<DATABASE_NAME>;UID=<UID>;PWD=<UID>;QUIETMODE=YES;')
</code></pre>
<p>What actually goes in the Driver={} part? Is this where I put the teradata <code>.jar</code> file such as <code>terajdbc4.jar</code>? </p>
<p>But this doe... | 0 | 2016-06-17T01:07:17Z | 37,871,676 | <p>try <a href="https://pypi.python.org/pypi/JayDeBeApi/" rel="nofollow">jaydebeapi</a> if you want to use the jdbc drivers, pyodbc will only work with the traditional odbc drivers as far as i know.</p>
<pre><code>import jaydebeapi
conn = jaydebeapi.connect('com.teradata.jdbc.TeraDriver',
['j... | 0 | 2016-06-17T01:18:59Z | [
"python",
"teradata",
"pyodbc"
] |
Python Query From Teradata pyodbc Module | 37,871,607 | <pre><code>import pyodbc
conn = pyodbc.connect('DRIVER={Teradata};DBCNAME=<DATABASE_NAME>;UID=<UID>;PWD=<UID>;QUIETMODE=YES;')
</code></pre>
<p>What actually goes in the Driver={} part? Is this where I put the teradata <code>.jar</code> file such as <code>terajdbc4.jar</code>? </p>
<p>But this doe... | 0 | 2016-06-17T01:07:17Z | 37,988,076 | <p>There seem to be two issues here:</p>
<ol>
<li><p>As <code>fivetentaylor</code> mentioned, you're trying to use ODBC with a JDBC driver - and they don't work together. To use ODBC you need an ODBC driver - for Teradata on Linux I think <a href="http://downloads.teradata.com/download/connectivity/odbc-driver/linux" ... | 0 | 2016-06-23T09:48:59Z | [
"python",
"teradata",
"pyodbc"
] |
Easiest way to select the subset of 2-d array by 2 corners | 37,871,625 | <p>With an global distributed variable in the shape of (len(latitude), len(longitude)), I want to get an subset corresponding to the area of interest. </p>
<p>The specific area is defined by 2 corners(left-low latitude/longitude, right-top latitude/longitude). So, this array is what I have now: </p>
<ul>
<li><p>... | 0 | 2016-06-17T01:10:42Z | 37,872,024 | <p>That find_nearest + np.where is a whole lot of computational work that is completely unneeded if the values are evenly distributed. Do you really understand what that code is doing? Read up on each of those functions. You're doing a subtraction on every value in an array, and then finding the index of the minimum of... | 1 | 2016-06-17T02:06:23Z | [
"python",
"arrays",
"numpy"
] |
Plot list of lists in histogram - x and y values | 37,871,683 | <p>I have a list of lists:</p>
<pre><code>[[Decimal('3.69578'), Decimal('5.12519')], [Decimal('3.69586'),Decimal('2.50457468')], [Decimal('3.69587'), Decimal('72.33894358')], [Decimal('3.69629'), Decimal('54.2359599')], ...]
</code></pre>
<p>and I would like to plot it in a histogram with matplotlib using one of the ... | 2 | 2016-06-17T01:19:23Z | 37,871,889 | <p>You could plot them as floats with</p>
<pre><code>plt.hist([[float(x) for x in y] for y in list])
</code></pre>
| 2 | 2016-06-17T01:48:13Z | [
"python",
"matplotlib"
] |
Failing to import class from models.py | 37,871,945 | <p>So I just migrated my little app to a blueprint with two blueprints defined.</p>
<p>I'm getting this error: <code>ImportError: cannot import name User</code></p>
<p>I have no idea what's going wrong here. I'm relatively confident that there is no circular import, or if there is what exactly to do with it. I'm pret... | 1 | 2016-06-17T01:56:04Z | 37,872,050 | <p>You have a <a href="http://effbot.org/zone/import-confusion.htm#circular-imports" rel="nofollow">circular import</a>:</p>
<p><code>models.py</code> is importing <code>db</code> from core, and <code>core.py</code> is importing <code>User</code> from models</p>
<p>You should move this line:</p>
<pre><code>from user... | 3 | 2016-06-17T02:10:41Z | [
"python",
"flask"
] |
wxPython: Refresh a Frame with Updated Table | 37,871,974 | <p>I'm using pyodbc to make a GUI for viewing table info from my SQL database, currently my code kills the frame and regenerates it with the updated info. Here's an example of what it does when performing a search:</p>
<pre><code>def nctDialog(self):
global nct, frame, table
dlg = wx.TextEntryDialog(
... | 0 | 2016-06-17T01:59:23Z | 37,872,746 | <p>First off, I have to say that <a href="http://c2.com/cgi/wiki?GlobalVariablesAreBad" rel="nofollow">using</a> <a href="http://programmers.stackexchange.com/questions/148108/why-is-global-state-so-evil">globals</a> is <a href="http://stackoverflow.com/questions/19158339/why-are-global-variables-evil">generally frowne... | 0 | 2016-06-17T03:40:44Z | [
"python",
"user-interface",
"wxpython",
"refresh"
] |
wxPython: Refresh a Frame with Updated Table | 37,871,974 | <p>I'm using pyodbc to make a GUI for viewing table info from my SQL database, currently my code kills the frame and regenerates it with the updated info. Here's an example of what it does when performing a search:</p>
<pre><code>def nctDialog(self):
global nct, frame, table
dlg = wx.TextEntryDialog(
... | 0 | 2016-06-17T01:59:23Z | 37,874,466 | <p>In the place of:</p>
<pre><code>frame.Destroy()
frame = TestFrame(None, sys.stdout)
frame.Show(True)
</code></pre>
<p>I put:</p>
<pre><code> table.data[:] = [] #clear all prior data in the table
table.nctCall() #puts in the new data/performs nct query
grid.ForceRefresh() ... | 0 | 2016-06-17T06:19:47Z | [
"python",
"user-interface",
"wxpython",
"refresh"
] |
Using dpkt to parse through pcap files | 37,872,140 | <p>I'm doing an assignment where I have to parse through a pcap file and I am using dpkt to do so. I'm new to networking so I'm having a really hard time debugging the code / getting started.</p>
<p>First set of code:</p>
<pre><code>import dpkt
filename='test.pcap'
f = open(filename)
pcap = dpkt.pcap.Reader(f)
for ... | 0 | 2016-06-17T02:23:46Z | 37,930,066 | <p>This typically happens on Windows. On windows, you should open the pcap file in binary mode:</p>
<blockquote>
<p>f = open('test.pcap','rb')</p>
</blockquote>
| 0 | 2016-06-20T19:10:07Z | [
"python",
"python-2.7",
"networking",
"pcap",
"dpkt"
] |
Using dpkt to parse through pcap files | 37,872,140 | <p>I'm doing an assignment where I have to parse through a pcap file and I am using dpkt to do so. I'm new to networking so I'm having a really hard time debugging the code / getting started.</p>
<p>First set of code:</p>
<pre><code>import dpkt
filename='test.pcap'
f = open(filename)
pcap = dpkt.pcap.Reader(f)
for ... | 0 | 2016-06-17T02:23:46Z | 38,022,391 | <p>I had this same problem for traces I took on my phone.</p>
<p>This was due to ethernet being replaced by Linux Cooked Capture. If you're traces are encapsulated similarly, you'll have to use dpkt.sll.SLL(buff) rather than dpkt.ethernet.Ethernet(buf). Here's an example: </p>
<pre><code>import dpkt
filename='a_... | 0 | 2016-06-24T21:30:37Z | [
"python",
"python-2.7",
"networking",
"pcap",
"dpkt"
] |
error occur when installing package under python 3 | 37,872,169 | <p>I'm trying to install a package under python 3.4 with <code>python3.4 -m pip install jieba</code> while I already have 2.7.</p>
<p>Then I have this error</p>
<pre><code>> Collecting jieba
Using cached jieba-0.38.zip
Building wheels for collected packages: jieba
Exception:
Traceback (most recent call last):
... | 0 | 2016-06-17T02:27:39Z | 37,872,320 | <p>I got it, an easy way to do it is to install pip under python3.4</p>
<pre><code>$ curl -O https://bootstrap.pypa.io/get-pip.py
$ sudo python3.4 get-pip.py
</code></pre>
| 0 | 2016-06-17T02:45:39Z | [
"python",
"install"
] |
How can I perform two-dimensional interpolation using scipy? | 37,872,171 | <blockquote>
<p><strong>This Q&A is intended as a canonical(-ish) concerning two-dimensional (and multi-dimensional) interpolation using scipy. There are often questions concerning the basic syntax of various multidimensional interpolation methods, I hope to set these straight too.</strong></p>
</blockquote>
<p>... | 29 | 2016-06-17T02:27:48Z | 37,872,172 | <p>Disclaimer: I'm mostly writing this post with syntactical considerations and general behaviour in mind. I'm not familiar with the memory and CPU aspect of the methods described, and I aim this answer at those who have reasonably small sets of data, such that the quality of the interpolation can be the main aspect to... | 35 | 2016-06-17T02:27:48Z | [
"python",
"scipy",
"interpolation"
] |
Python Tkinter using frame and canvas | 37,872,272 | <p>I am trying to use Tkinter to present an image then, when clicked or when a key is pressed, change to another image. I have been able to make images using canvas and process clicks and key events using frame but I cannot figure out how to either use both at the same time or use one to do both of these things. Any as... | -3 | 2016-06-17T02:39:07Z | 37,903,199 | <p>Convert your bitmap image files to <a href="https://en.wikipedia.org/wiki/X_BitMap" rel="nofollow">.xbm</a> format. Use <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/images.html" rel="nofollow">BitmapImage</a> to create an image object from the file. Perhaps you can find examples.</p>
<p>Use one Butto... | 0 | 2016-06-19T01:40:56Z | [
"python",
"tkinter"
] |
Flask mail does not send mail when DEBUG=False | 37,872,346 | <p>I am writing a little web application based on Miguel Grinberg's <a href="https://github.com/miguelgrinberg/flasky" rel="nofollow">Flasky</a>. I use the exact same code for user confirmation emails. When DEBUG=True (for Flask), everything works like a charm. When DEBUG=False, however, I get the following error: </p>... | 1 | 2016-06-17T02:49:39Z | 37,904,404 | <p>Couldn't figure out where you went wrong but can you try to match this </p>
<pre><code>from flask import Flask, current_app
from flask_mail import Mail, Message
import threading
#mail = Mail()
app = Flask(__name__)
#DEBUG = True
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT']= 587
app.config... | 1 | 2016-06-19T05:59:10Z | [
"python",
"email",
"flask"
] |
How to format a multi line string with triple quotes inside using Python? | 37,872,349 | <p>I couldn't find this online but basically I have a string like this:</p>
<pre><code>s = "name={0},
address={1},
nickname={2},
age={3},
comments=
"""
{4}
"""
"
</code></pre>
<p>and I need to format this string as is using variables like so:</p>
<pre><code>s.format("alice", "N/A", "alice", 18, "missing person")
</c... | 3 | 2016-06-17T02:50:22Z | 37,872,417 | <p>You could use triple single quotes for the string:</p>
<pre><code>s = '''name={0},
address={1},
nickname={2},
age={3},
comments=
"""
{4}
"""
'''
print s.format("alice", "N/A", "alice", 18, "missing person")
</code></pre>
<p>Output:</p>
<pre><code>name=alice,
address=N/A,
nickname=alice,
age=18,
comments=
"""
mis... | 3 | 2016-06-17T02:58:52Z | [
"python",
"string",
"formatting",
"escaping",
"string-formatting"
] |
How to format a multi line string with triple quotes inside using Python? | 37,872,349 | <p>I couldn't find this online but basically I have a string like this:</p>
<pre><code>s = "name={0},
address={1},
nickname={2},
age={3},
comments=
"""
{4}
"""
"
</code></pre>
<p>and I need to format this string as is using variables like so:</p>
<pre><code>s.format("alice", "N/A", "alice", 18, "missing person")
</c... | 3 | 2016-06-17T02:50:22Z | 37,872,471 | <p>You can use @niemmi's approach, which works perfectly well. You can also add a backward slash at the end of each line to indicate you're going to continue on the next line:</p>
<pre><code>s = 'name={0},\
address={1},\
nickname={2},\
age={3},\
comments=\
"""\
{4}\
"""\
'
</code></pre>
| 0 | 2016-06-17T03:08:36Z | [
"python",
"string",
"formatting",
"escaping",
"string-formatting"
] |
How to format a multi line string with triple quotes inside using Python? | 37,872,349 | <p>I couldn't find this online but basically I have a string like this:</p>
<pre><code>s = "name={0},
address={1},
nickname={2},
age={3},
comments=
"""
{4}
"""
"
</code></pre>
<p>and I need to format this string as is using variables like so:</p>
<pre><code>s.format("alice", "N/A", "alice", 18, "missing person")
</c... | 3 | 2016-06-17T02:50:22Z | 37,872,992 | <p>You can escape triple-quotes inside a string the same way you can escape any other quote character, with a <code>\</code>:</p>
<pre><code>s = """name={0},
address={1},
nickname={2},
age={3},
comments=
\"\"\"
{4}
\"\"\"
"""
</code></pre>
<p>Strictly speaking, you only have to escape <em>one</em> of the <code>"</c... | 3 | 2016-06-17T04:11:26Z | [
"python",
"string",
"formatting",
"escaping",
"string-formatting"
] |
scrapy error ImportError: No module named items | 37,872,397 | <p>i want to crawler website <a href="http://www.metacritic.com/browse/games/title/pc?page=0" rel="nofollow">this link</a>
but when i crawler using command </p>
<pre><code>scrapy crawl metacritic -o metacritic.json -t json
</code></pre>
<p>its says <code>ImportError: No module named items</code>
does anybody can help... | -1 | 2016-06-17T02:56:48Z | 37,873,390 | <p>move your <code>item.py</code> into the second <code>metacritic</code> folder.</p>
| 0 | 2016-06-17T04:53:59Z | [
"python",
"linux",
"terminal",
"scrapy",
"web-crawler"
] |
Pandas: to_excel(): How can I express Time as a format to TimeSeries index? | 37,872,414 | <p>I have a DataFrame with an <code>index</code> as:</p>
<pre><code>Index([00:00:00, 00:05:00, 00:10:00, 00:15:00, 00:20:00, 00:25:00, 00:30:00,
00:35:00, 00:40:00, 00:45:00,
...
23:10:00, 23:15:00, 23:20:00, 23:25:00, 23:30:00, 23:35:00, 23:40:00,
23:45:00, 23:50:00, 23:55:00],
dtype='object', length=28... | 3 | 2016-06-17T02:58:28Z | 37,875,294 | <p>If you use XlsxWriter as your engine for Pandas, you can set the formatting of specific columns in this way:</p>
<pre><code>workbook = writer.book
worksheet = writer.sheets['Days']
timeFormat = workbook.add_format({'num_format': 'h:mm:ss'})
worksheet.set_column('A:A', None, timeFormat)
</code></pre>
<p><a href="ht... | 1 | 2016-06-17T07:13:18Z | [
"python",
"excel",
"pandas",
"export-to-excel"
] |
Pandas: to_excel(): How can I express Time as a format to TimeSeries index? | 37,872,414 | <p>I have a DataFrame with an <code>index</code> as:</p>
<pre><code>Index([00:00:00, 00:05:00, 00:10:00, 00:15:00, 00:20:00, 00:25:00, 00:30:00,
00:35:00, 00:40:00, 00:45:00,
...
23:10:00, 23:15:00, 23:20:00, 23:25:00, 23:30:00, 23:35:00, 23:40:00,
23:45:00, 23:50:00, 23:55:00],
dtype='object', length=28... | 3 | 2016-06-17T02:58:28Z | 37,876,858 | <p>You can do it using <code>datetime_format</code> argument of the <code>pandas.ExcelWriter()</code> function, but you would need to cast your index to <code>datetime</code> type first:</p>
<pre><code>In [104]: df
Out[104]:
val
00:00:00 4
00:05:00 9
00:10:00 7
00:15:00 7
00:20:00 7
00:25:00 ... | 1 | 2016-06-17T08:38:06Z | [
"python",
"excel",
"pandas",
"export-to-excel"
] |
Why the auc is so different from logistic regression of sklearn and R | 37,872,536 | <p>I use a same dataset to train logistic regression model both in R and python sklearn. The dataset is unbalanced.
And I find that the auc is quite different.
This is the code of python:</p>
<pre><code>model_logistic = linear_model.LogisticRegression() #auc 0.623
model_logistic.fit(train_x, train_y)
pred_logistic = m... | 3 | 2016-06-17T03:17:54Z | 37,884,259 | <p>In the python script, you should use <code>predict_proba</code> to get the probability estimates for both classes and take the second column for the positive class as the input for <code>roc_auc_score</code> because ROC curve is plotted by varying the probability thresholds. </p>
<pre><code>pred_logistic = model_lo... | 1 | 2016-06-17T14:34:56Z | [
"python",
"scikit-learn",
"logistic-regression",
"glm"
] |
Is there a Python API for submitting batch get requests to AWS DynamoDB? | 37,872,542 | <p>The package <code>boto3</code> - Amazon's official AWS API wrapper for python - has great support for uploading items to DynamoDB in bulk. It looks like this:</p>
<pre><code>db = boto3.resource("dynamodb", region_name = "my_region").Table("my_table")
with db.batch_writer() as batch:
for item in my_items:
... | 0 | 2016-06-17T03:18:31Z | 37,880,172 | <p>This might help you , please follow this github implementation </p>
<p><a href="https://github.com/google/gdata-python-client" rel="nofollow">https://github.com/google/gdata-python-client</a></p>
<p>This shows the way to process batch requests </p>
| 0 | 2016-06-17T11:14:36Z | [
"python",
"amazon-web-services"
] |
Reversed cumulative sum of a column in pandas.DataFrame | 37,872,565 | <p>I've got a pandas DataFrame with boolean column, sorted by another column and need to calculate reverse cumulative sum, that is, amount of true values from current row to bottom.</p>
<p>Example</p>
<pre><code>In [13]: df = pd.DataFrame({'A': [True] * 3 + [False] * 5, 'B': np.random.rand(8) })
In [15]: df = df.sor... | 0 | 2016-06-17T03:20:30Z | 37,872,823 | <p>Reverse column A, take the cumsum, then reverse again:</p>
<pre><code>df['C'] = df.ix[::-1, 'A'].cumsum()[::-1]
</code></pre>
<hr>
<pre><code>import pandas as pd
df = pd.DataFrame(
{'A': [False, True, False, False, False, True, False, True],
'B': [0.03771, 0.315414, 0.33248, 0.445505, 0.580156, 0.741551,... | 2 | 2016-06-17T03:48:45Z | [
"python",
"pandas",
"dataframe",
"reverse"
] |
Reversed cumulative sum of a column in pandas.DataFrame | 37,872,565 | <p>I've got a pandas DataFrame with boolean column, sorted by another column and need to calculate reverse cumulative sum, that is, amount of true values from current row to bottom.</p>
<p>Example</p>
<pre><code>In [13]: df = pd.DataFrame({'A': [True] * 3 + [False] * 5, 'B': np.random.rand(8) })
In [15]: df = df.sor... | 0 | 2016-06-17T03:20:30Z | 37,873,252 | <p>This works but is slow... like @unutbu answer. True resolves to 1. Fails on False, or any other value though. </p>
<pre><code>df[2] = df.groupby('A').cumcount(ascending=False)+1
df[1] = np.where(df['A']==True,df[2],None)
df[1] = df[1].fillna(method='bfill').fillna(0)
del df[2]
A B 1
# 3 False ... | 0 | 2016-06-17T04:40:15Z | [
"python",
"pandas",
"dataframe",
"reverse"
] |
Find latest two element revisions using SQLAlchemy | 37,872,600 | <p>I have a single table that contains a number of revisions for an entity in another table (Tasks). So each TaskRevision row has a unique autoincremented id and a reference to the Task id.</p>
<p>I can find the latest revision of all tasks using:</p>
<pre>
subq = session.query(TaskRevision.task_id, func.max(TaskRevi... | 0 | 2016-06-17T03:24:47Z | 37,873,475 | <p>The working SQL is pretty much:</p>
<pre><code>select task_id, id from TaskRevisions where (
select count(*) from TaskRevisions as t
where t.task_id = TaskRevisions.task_id and t.id <= TaskRevisions.id
) <= 2
</code></pre>
<p>After much work, this is the answer in SQLAlchemy:</p>
<pre><code>tr = alia... | 0 | 2016-06-17T05:01:08Z | [
"python",
"sqlalchemy"
] |
django channels not working how does it work i have read docs | 37,872,611 | <p>iam trying to use channels but not working
here is consumer.py</p>
<pre><code>def ws_connect(message, cat_id):
try:
cat = Categories.objects.get(pk=cat_id)
except Categories.DoesNotExist:
pass
Group('cat-1').add(message.reply_channel)
def ws_diconnect(message, cat_id):
try:
... | -1 | 2016-06-17T03:25:52Z | 37,873,585 | <p>Instead of <strong>websocket.receive</strong> use <strong>websocket.connect</strong>. Receive is used when client is sending data to server.</p>
<pre><code>route('websocket.connect', ws_connect, path=r'^/liveupdate/(?P<cat_id>\d+)/'),
</code></pre>
<p>When are you sending data instead of tender use <strong>t... | 2 | 2016-06-17T05:13:52Z | [
"javascript",
"python",
"django",
"django-models",
"websocket"
] |
Given a filename get its absolute path | 37,872,703 | <p>I am developing a python library and the end-user who uses my library in their respective application should be able to provide a configuration file in the root path of their application which my library will read in run-time. The end-user's application can be any Project like a Simple Python Project, Django, Flask ... | -1 | 2016-06-17T03:34:39Z | 37,874,906 | <p>I think you may want to rethink your approach.</p>
<p>I don't think its going to be possible to dynamically retrieve a base directory easily, but then you may not have to. Instead of relying on a settings file, make your app have its own settings static class that you can retrieve any configurations you need. If an... | 2 | 2016-06-17T06:48:54Z | [
"python",
"django",
"python-2.7",
"maven",
"python-3.x"
] |
Python: How to count average length of lines in a text file | 37,872,758 | <p>I'm having trouble defining a function that takes a filename as a parameter and returns the average line length. Particularly having trouble removing the "\n" in the file. </p>
<p>This is what I have so far:</p>
<pre><code> def averageLineLength(fn):
fn = open("Ex_file.txt", "r")
lines = fn.read... | 0 | 2016-06-17T03:41:38Z | 37,872,869 | <p>You can use <code>strip()</code> to remove preceding and trailing <code>\n</code> from the line and minor modification to your own code should be sufficient</p>
<pre><code> def averageLineLength(fn):
fn = open("Ex_file.txt", "r")
lines = fn.readlines()
return sum([len(line.strip('\n')) for... | 1 | 2016-06-17T03:54:35Z | [
"python"
] |
Python: How to count average length of lines in a text file | 37,872,758 | <p>I'm having trouble defining a function that takes a filename as a parameter and returns the average line length. Particularly having trouble removing the "\n" in the file. </p>
<p>This is what I have so far:</p>
<pre><code> def averageLineLength(fn):
fn = open("Ex_file.txt", "r")
lines = fn.read... | 0 | 2016-06-17T03:41:38Z | 37,872,891 | <p>The common way to get rid of whitespace (such as newlines) in python is <code>strip</code>. There's also <code>rstrip</code> if you want to preserve the left side, and you can give any of them an argument if you only want to target newlines specifically:</p>
<pre><code>>>> ' Hello, world \n'.strip()... | 0 | 2016-06-17T03:56:27Z | [
"python"
] |
Python: How to count average length of lines in a text file | 37,872,758 | <p>I'm having trouble defining a function that takes a filename as a parameter and returns the average line length. Particularly having trouble removing the "\n" in the file. </p>
<p>This is what I have so far:</p>
<pre><code> def averageLineLength(fn):
fn = open("Ex_file.txt", "r")
lines = fn.read... | 0 | 2016-06-17T03:41:38Z | 37,872,933 | <p>What you have already will tell you the average line length.</p>
<p>There are a few different methods for handling removal of the '\n'. </p>
<p>The simplest is to just use the "strip" method. This will remove all leading and trailing whitespace from each line.</p>
<p>If you want to remove only the trailing '\n'... | 0 | 2016-06-17T04:02:55Z | [
"python"
] |
Python: How to count average length of lines in a text file | 37,872,758 | <p>I'm having trouble defining a function that takes a filename as a parameter and returns the average line length. Particularly having trouble removing the "\n" in the file. </p>
<p>This is what I have so far:</p>
<pre><code> def averageLineLength(fn):
fn = open("Ex_file.txt", "r")
lines = fn.read... | 0 | 2016-06-17T03:41:38Z | 37,873,572 | <p>This solution should solve the problem as well:</p>
<pre><code>def averageLineLength(fn):
with open('Ex_file.txt".txt', 'r') as fn:
lst = fn.readlines()
return sum([len(line.strip()) for line in lst]) / len(lst)
</code></pre>
| 0 | 2016-06-17T05:11:39Z | [
"python"
] |
Python is unable to import library compiled with boost_python | 37,872,830 | <p>I have the following sample program:</p>
<pre><code>// src/main.cpp
#include <boost/python.hpp>
char const* func()
{
return "String";
}
BOOST_PYTHON_MODULE(bridge)
{
boost::python::def("func", func);
}
</code></pre>
<p>When built using the following CMakeLists.txt, no compiler errors are given:</p>
... | 0 | 2016-06-17T03:49:20Z | 37,892,447 | <p>I have found a solution. The problem is due to Python version mismatch inside Boost. I decided to compile everything in Python 3 and it solves the problem. I proceeded as follows:</p>
<ol>
<li><p>I uncommented the following line to the auto-generated <code>user-config.jam</code> located in <code>$BOOST_ROOT/tools/b... | 0 | 2016-06-18T01:29:09Z | [
"python",
"c++",
"boost",
"boost-python"
] |
A combination algorithm in python | 37,872,856 | <pre><code>import copy
def combine(l, n):
answers = []
one = [0] * n
def next_c(li = 0, ni = 0):
if ni == n:
answers.append(copy.copy(one))
return
for k in range(li, len(l)):
one[ni] = l[k]
next_c(k+1, ni+1)
next_c()
return answers
pr... | 0 | 2016-06-17T03:52:57Z | 37,873,469 | <p>As @AChampion said, You could also get the combinations with the itertools library, which is much easier to understand:</p>
<pre><code>import itertools
def combine2(lst, n):
return [list(x) for x in itertools.combinations(lst, n)]
</code></pre>
<p>Output:</p>
<pre><code>>>> combine2([1,2,3,4],2)
[[1... | 1 | 2016-06-17T05:00:41Z | [
"python",
"python-3.x",
"combinations"
] |
Stop Inserting into Table when Duplicate Value Detected Flask SQLAlchemy | 37,872,863 | <p>I able to get data from tweets and store them into MySQL table.
but the problem is sometimes a tweet has duplicate tweets with same value.
I want to know if it's possible to stop inserting into table when duplicate value detected using Flask-SQLAlchemy.</p>
<pre><code>from tweepy import Stream
from tweepy import OA... | 0 | 2016-06-17T03:54:06Z | 37,873,725 | <p>Your model should have unique indexes for some criteria to remove duplicates on. <code>Column</code>s are not unique by default, which you seem to assume (<code>unique=False</code> in a column and the comments). You should either instead of an auto incrementing surrogate key use some "natural" key such as the id pro... | 1 | 2016-06-17T05:27:18Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy",
"tweepy"
] |
Python: Syntax error:Invalid token | 37,872,872 | <p>I just started learning pyhton and while working with comparison operators,i got this error when i executed the following code with '==' operator,</p>
<pre><code>40 == 0040.0
</code></pre>
<p>resulted into True,from the interpreter,and also </p>
<pre><code>40 == 40.0
</code></pre>
<p>resulted in True</p>
<p>bu... | 1 | 2016-06-17T03:54:40Z | 37,872,907 | <p>Python 3 doesn't allow numbers with leading zeroes to prevent confusion with octal values. If you must have leading zeroes, use <code>format()</code>.</p>
<p>It's clearer in Python 2 where <code>40 == 0040</code> evaluates to <code>False</code>.</p>
<p>EDIT: Example taken from link in comment:</p>
<p><code>>&g... | 0 | 2016-06-17T03:59:08Z | [
"python",
"python-3.x"
] |
Python: Syntax error:Invalid token | 37,872,872 | <p>I just started learning pyhton and while working with comparison operators,i got this error when i executed the following code with '==' operator,</p>
<pre><code>40 == 0040.0
</code></pre>
<p>resulted into True,from the interpreter,and also </p>
<pre><code>40 == 40.0
</code></pre>
<p>resulted in True</p>
<p>bu... | 1 | 2016-06-17T03:54:40Z | 37,872,935 | <p>For floating point numbers, leading zeros are accepted, and them simply ignored (since they don't contribute anything but readability).
Thus, <code>0040.0</code> is the floating point number <code>40.0</code>.</p>
<p>For integer numbers, the zero at the start of a number takes on a different meaning: depending on t... | 0 | 2016-06-17T04:03:04Z | [
"python",
"python-3.x"
] |
TypeError: a bytes-like object is required, not 'str' for Python Code | 37,872,880 | <p>I get this when I try to run a code called NUT_check.py and this comes from line 69. I'm very unsure of what is happening as I didn't make this code myself, nor have I really used Python extensively. Line 69 is ending with a line of hyphens to mark it</p>
<pre><code>import sys
import struct
from struct import pack
... | 1 | 2016-06-17T03:55:15Z | 37,873,068 | <p>I suspect you're using python3 instead of python2. If you continue to use python3, trying change the binary-ish string constants to be prefixed with <code>b</code>:</p>
<pre><code>>>> outfile = open("/tmp/foo", "wb")
>>> outfile.write("\x47\x66\x78\x32\x00\x00\x00\x20\x00\x00\x00\x07\x00\x00\x00\... | 0 | 2016-06-17T04:19:52Z | [
"python",
"string",
"object"
] |
Python script for extract test from log files | 37,872,941 | <p>The problem statement as follows, There is log file contains logs related to testing results. For example it is contains text like testcase1 followed by logs for test case and testcase2 followed by logs for the test case and so on.</p>
<p>If user want to extract log for testcase1 and testcase3, script should read i... | -4 | 2016-06-17T04:03:49Z | 37,873,263 | <p>Here you have to go through an assumption that all the testcase logs are in separate lines, which means you are having '\n' after every log line.</p>
<p>Then you can read the files from linecache module.
Now again you should have your logs in a particular format. Here you have mentioned it as [testcaseN] [Log messa... | 0 | 2016-06-17T04:41:20Z | [
"python"
] |
Python script for extract test from log files | 37,872,941 | <p>The problem statement as follows, There is log file contains logs related to testing results. For example it is contains text like testcase1 followed by logs for test case and testcase2 followed by logs for the test case and so on.</p>
<p>If user want to extract log for testcase1 and testcase3, script should read i... | -4 | 2016-06-17T04:03:49Z | 37,878,376 | <h2> Here is my code . But output.txt file didnot write anything :(</h2>
<pre><code> # Read particular line from the text file
# For example in the program we are readin file and print only lines under the Title 2 and title 4
# log file may contain empty lines as weel
# Example log file
# Title
# 1
# dklfjsdk... | 0 | 2016-06-17T09:46:59Z | [
"python"
] |
Python script for extract test from log files | 37,872,941 | <p>The problem statement as follows, There is log file contains logs related to testing results. For example it is contains text like testcase1 followed by logs for test case and testcase2 followed by logs for the test case and so on.</p>
<p>If user want to extract log for testcase1 and testcase3, script should read i... | -4 | 2016-06-17T04:03:49Z | 37,881,465 | <p>Finally got the woking script to extract the text </p>
<p># Read particular line from the text file
# For example in the program we are readin file and print only lines under the Title 2 and title 4
# log file may contain empty lines as weel
# Example log file
# Title
# 1
# dklfjsdkl;
... | 0 | 2016-06-17T12:21:30Z | [
"python"
] |
Provide vocaburary of word with space to scikit-learn CountVectorizer | 37,873,007 | <p>Referring to this <a href="http://stackoverflow.com/questions/22920801/can-i-use-countvectorizer-in-scikit-learn-to-count-frequency-of-documents-that-w">post</a>. I am wondering how we provide vocabulary of word with space to <code>CountVectorizer</code> model e.g. <code>distributed systems</code> or <code>machine l... | 0 | 2016-06-17T04:13:05Z | 37,884,104 | <p>I think essentially you have already pre-defined your vocabularies to analyze and you want to tokenize your tags by splitting ', '.</p>
<p>You can trick the <code>CountVectorizer</code> to do that by:</p>
<pre><code>from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer(vocabulary=vocabu... | 1 | 2016-06-17T14:26:48Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Get text with BeautifulSoup CSS Selector | 37,873,059 | <p>Example HTML</p>
<pre><code><h2 id="name">
ABC
<span class="numbers">123</span>
<span class="lower">abc</span>
</h2>
</code></pre>
<p>I can get the numbers with something like:</p>
<pre><code>soup.select('#name > span.numbers')[0].text
</code></pre>
<p>How do I ... | 2 | 2016-06-17T04:18:55Z | 37,873,100 | <p>In the first case, get the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling" rel="nofollow">previous sibling</a>:</p>
<pre><code>soup.select_one('#name > span.numbers').previous_sibling
</code></pre>
<p>In the second case, get the <a href="https://www.crummy.com/... | 2 | 2016-06-17T04:22:39Z | [
"python",
"python-2.7",
"css-selectors",
"beautifulsoup",
"html-parsing"
] |
Not understanding some composition aspects | 37,873,064 | <p>I am brushing up on some data structures and algorithms with Python, so I am implementing an Unordered Linked list. Within the same file I first wrote a Node class followed by a List class. What I don't get is how the "current" variable in my search_item() method seems to be a node object or at least able to access ... | -1 | 2016-06-17T04:19:41Z | 37,873,461 | <p>Well if you comment out <code>add_node</code> then you do not add nodes to your linked list any longer therefore <code>search_item</code> will always see the initial value of <code>self.head</code> which is <code>None</code>. </p>
<p>Calling <code>current.get_next()</code> just works because via <code>add_node</co... | 0 | 2016-06-17T04:59:58Z | [
"python",
"oop",
"composition"
] |
For loop for finding concordance is taking a lot of time for large data. (14+hrs for 0.15mln * 36k rows) | 37,873,223 | <p>I am running this code in python3.5 to find Concordance (logistic regression).</p>
<pre><code>for i in (ones2.index):
for j in (zeros2.index):
pairs_tested = pairs_tested+1
if(ones2.iloc[i,1] > zeros2.iloc[j,1]):
conc = conc+1
elif(ones2.iloc[i,1]==zeros2.iloc[j,1]):
tie... | 0 | 2016-06-17T04:36:30Z | 37,873,377 | <p>Your code is doing 5.4 billion calculations due to the two for loops (0.15 mil * 36k):</p>
<p>I would do something like this: (Thanks to @Leon for helping me make this answer better)</p>
<pre><code>from bisect import bisect_left, bisect_right
zeros_list = sorted([zeros2.iloc[j,1] for j in zeros2.index])
zeros2_le... | 5 | 2016-06-17T04:52:37Z | [
"python",
"performance",
"python-3.x",
"for-loop"
] |
H5py store list of list of strings | 37,873,311 | <p>Is there a possibility in h5py to create a dataset which consists of lists of strings. I tried to create a nested datatype of variable length, but this results in segmentation fault in my python interpreter. </p>
<pre><code>def create_dataset(h5py_file):
data = [['I', 'am', 'a', 'sentecne'], ['another', 'sen... | 1 | 2016-06-17T04:46:15Z | 38,465,587 | <p>You should be able to get the functionality you want if you define your data as a numpy array of dtype=object as suggested in this <a href="http://stackoverflow.com/questions/14639496/python-numpy-array-of-arbitrary-length-strings">post</a>, rather than a list of lists.</p>
<pre><code>def create_dataset(h5py_file):... | 0 | 2016-07-19T18:07:16Z | [
"python",
"hdf5",
"h5py"
] |
Cannot Enable Autoexposure via V4L2 | 37,873,331 | <p>I am using an ELP-USBFHD01M-L21 camera. It claims to have autoexposure support and when I plug it into my Mac it appears to be so. I downloaded a sample application on OS X that someone wrote that uses the USB Video Class commands to enable/disable autoexposure and it seems fine.</p>
<p>On a Debian 8.5 system I am ... | 0 | 2016-06-17T04:48:15Z | 37,874,735 | <p>I got a bit fixated on making <code>camera.set_exposure_auto(0)</code> work. It turns out a value of 3 is auto exposure with manual iris adjustment. This camera doesn't have an iris (at least not a mechanical one) and this does appear to activate a form of auto exposure that works for me.</p>
<p>A value of 0 is aut... | 0 | 2016-06-17T06:38:16Z | [
"python",
"v4l2"
] |
Get return value for multi-processing functions in python | 37,873,501 | <p>I have two functions to run in parallel and each of them returns a value. I need to wait for both functions to finish and then process the returns from them. How could I achieve this in python. Assume</p>
<pre><code>def fun1():
#do some calculation#
return val1
def fun2():
#do some calculation#
return ... | 2 | 2016-06-17T05:03:34Z | 37,873,950 | <p>Using <code>concurrent.futures</code>:</p>
<pre><code>from concurrent.futures import ProcessPoolExecutor as Executor
#from concurrent.futures import ThreadPoolExecutor as Executor # to use threads
with Executor() as executor:
future1 = executor.submit(fun1, arg1, arg2, ...)
future2 = executor.submit(fun2, ... | 1 | 2016-06-17T05:42:52Z | [
"python",
"python-multithreading",
"python-multiprocessing"
] |
Logistic regression results different in Scikit python and R? | 37,873,564 | <p>I was running logistic regression on iris dataset on both R and Python.But both are giving different results(coefficients,intercept and scores).</p>
<pre><code>#Python codes.
In[23]: iris_df.head(5)
Out[23]:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
0 5.1 3.5... | 1 | 2016-06-17T05:10:57Z | 37,873,734 | <p>UPDATED
The problem is that there exists perfect separation along the petal width variable. In other words, this variable can be used to perfectly predict whether a sample in the given dataset is setosa or versicolor. This breaks the loglikelihood maximization estimation used in logistic regression in R. The problem... | 2 | 2016-06-17T05:28:05Z | [
"python",
"machine-learning",
"regression",
"logistic-regression"
] |
How do I create a 'urlpattern' with an indefinite amount of 'named regex groups' | 37,873,568 | <h2>Explanation</h2>
<p>I want to have a folder type structure with my website urls, like this example:</p>
<pre><code>www.sitename.com/catagory/sub-catagory/another-catagory/yet-another
</code></pre>
<p>currently inside my urls.py I have the following <code>urlpattern</code> to begin to describe this:</p>
<pre><co... | 2 | 2016-06-17T05:11:33Z | 37,873,651 | <p>This seems to work correctly </p>
<pre><code># urls.py
url(r'^(?P<slug>[a-zA-Z0-9-\/]+)/', views.page_view)
# views.py
def page_view(request, slug):
slug #
</code></pre>
<p>For a url <code>www.example.com/a/b/c/d</code> it'll capture <code>a/b/c</code> which can be split at <code>/</code>. </p>
<p>F... | 2 | 2016-06-17T05:20:39Z | [
"python",
"django",
"django-views"
] |
Dynamically update variables used in a For statement in python | 37,873,673 | <p>I want to update the list used in the for loop statement as it is being appended with new values within the loop.I know this code wont update the list but I am not able to find a way to do so. I hope to required output might explain it better</p>
<h1>INPUT</h1>
<pre><code>list=[1,2,3]
count=0
for x in list:
if... | 1 | 2016-06-17T05:22:47Z | 37,873,914 | <p>I suggest you use a <code>while</code> loop instead of a <code>for</code>, which saves the need of the <code>break</code> keyword :</p>
<pre><code>l=[1,2,3]
count = len(l) # There are already len(l) elements in the list
pos = 0
while len(l) < 10:
count += 1
x = l[pos]
l.append(x+10)
pos += 1... | 0 | 2016-06-17T05:39:57Z | [
"python",
"for-loop"
] |
Dynamically update variables used in a For statement in python | 37,873,673 | <p>I want to update the list used in the for loop statement as it is being appended with new values within the loop.I know this code wont update the list but I am not able to find a way to do so. I hope to required output might explain it better</p>
<h1>INPUT</h1>
<pre><code>list=[1,2,3]
count=0
for x in list:
if... | 1 | 2016-06-17T05:22:47Z | 37,874,087 | <p>two problems here:</p>
<p>first: the <code>if x>3:</code> test. (Why did you include that?)</p>
<p>second when you have a <code>for</code> statement, it loops on the values present initially only.</p>
<p>This should work:</p>
<pre><code>l = [1,2,3]
count = 0
while len(l) < 10:
l.append(l[count]+10)
... | 0 | 2016-06-17T05:54:17Z | [
"python",
"for-loop"
] |
String binary operations | 37,873,736 | <p>I want to do OR operation on binaries. I have the binaries in strings.
E.g</p>
<pre><code>>>> 110 | 001
111
</code></pre>
<p>I have these binaries as strings. LIke this:
'110100' and '001011'</p>
<p>For the above inputs, I want an output : 111111</p>
| 0 | 2016-06-17T05:28:06Z | 37,873,737 | <p>I could do what I want like this. May be there are simpler ideas. </p>
<pre><code>>>> eval('0b' + '110100') | eval('0b' + '001011')
63
>>> bin(63)
'0b111111'
</code></pre>
| 0 | 2016-06-17T05:28:06Z | [
"python"
] |
String binary operations | 37,873,736 | <p>I want to do OR operation on binaries. I have the binaries in strings.
E.g</p>
<pre><code>>>> 110 | 001
111
</code></pre>
<p>I have these binaries as strings. LIke this:
'110100' and '001011'</p>
<p>For the above inputs, I want an output : 111111</p>
| 0 | 2016-06-17T05:28:06Z | 37,874,306 | <p>If you have two strings with a binary number inside them, you can simply convert them to base 10 integers and then do your binary operations inside a bin().</p>
<pre><code>num1 = int("110", 2)
num2 = int("001", 2)
print(bin(num1 | num2))
# Prints 0b111
</code></pre>
<p>Or for your second example:</p>
<pre><code>... | 1 | 2016-06-17T06:10:38Z | [
"python"
] |
How to get an index of list? | 37,873,738 | <pre><code>>>> ohlc = [(735981.0, 74.25, 77.25, 73.75, 75.75),
(735982.0, 76.5, 77.0, 75.0, 75.25),
(735983.0, 75.75, 75.75, 74.25, 75.0),
(735984.0, 75.0, 76.25, 74.5, 75.5)]
>>> print (ohlc.index("735982.0"))
>>> ValueError: '735982.0' is not in list
</c... | 0 | 2016-06-17T05:28:06Z | 37,873,812 | <p>Do you want something like </p>
<pre><code>[idx for idx,o in enumerate(ohlc) if o[0]==735982.0][0]
> 1
</code></pre>
<p>P.S. Make sure you add a try/catch in case the element does not exist in the list</p>
| 1 | 2016-06-17T05:33:07Z | [
"python"
] |
How to get an index of list? | 37,873,738 | <pre><code>>>> ohlc = [(735981.0, 74.25, 77.25, 73.75, 75.75),
(735982.0, 76.5, 77.0, 75.0, 75.25),
(735983.0, 75.75, 75.75, 74.25, 75.0),
(735984.0, 75.0, 76.25, 74.5, 75.5)]
>>> print (ohlc.index("735982.0"))
>>> ValueError: '735982.0' is not in list
</c... | 0 | 2016-06-17T05:28:06Z | 37,873,818 | <p>Your <code>ohlc</code> list is a list of tuple. So you have to give tuple to find the index value like this.</p>
<pre><code>In [1]: ohlc = [(735981.0, 74.25, 77.25, 73.75, 75.75),
.....: (735982.0, 76.5, 77.0, 75.0, 75.25),
.....: (735983.0, 75.75, 75.75, 74.25, 75.0),
.....: ... | 1 | 2016-06-17T05:33:14Z | [
"python"
] |
How to get an index of list? | 37,873,738 | <pre><code>>>> ohlc = [(735981.0, 74.25, 77.25, 73.75, 75.75),
(735982.0, 76.5, 77.0, 75.0, 75.25),
(735983.0, 75.75, 75.75, 74.25, 75.0),
(735984.0, 75.0, 76.25, 74.5, 75.5)]
>>> print (ohlc.index("735982.0"))
>>> ValueError: '735982.0' is not in list
</c... | 0 | 2016-06-17T05:28:06Z | 37,873,821 | <p><code>ohlc</code> is a list of tuples so,</p>
<p>You may do something like this to match only the first element of the tuples:</p>
<pre><code>ohlc = [(735981.0, 74.25, 77.25, 73.75, 75.75),(735982.0, 76.5, 77.0, 75.0, 75.25),(735983.0, 75.75, 75.75, 74.25, 75.0),(735984.0, 75.0, 76.25, 74.5, 75.5)]
a=[ohlc.index(i... | 1 | 2016-06-17T05:33:33Z | [
"python"
] |
Different search results in different environments | 37,873,759 | <p>I am learning Data science and while doing a problem, I came across a weird observation. The problem was to print the number of occurrences of the string 'Soup' on the Beautiful Soup home page, using python. The weird part is, <em>the number of occurrences varies in the iPython notebook and in Python</em> and when I... | 1 | 2016-06-17T05:29:32Z | 37,873,893 | <p>I think <code>Python</code> found only <code>39</code>, because <code>2</code> missing are in <code><head></code>:</p>
<pre><code><title>Beautiful Soup: We called him Tortoise because he taught us.</title>
<meta name="Description" content="Beautiful Soup: a library designed for screen-scraping ... | 2 | 2016-06-17T05:38:41Z | [
"python",
"pandas",
"search",
"ipython",
"data-science"
] |
Open url in IE Then Scrape the same using python | 37,873,802 | <p>I am novice in python (c++ developer), I am trying to do some hands-on on web scraping on windows IE.</p>
<p>The problem which I am facing is, when I open a URL using "requests" library the server sends me a login page always. I figured out the problem. Its actually doing it because it presumes you are coming throu... | 0 | 2016-06-17T05:32:29Z | 37,875,324 | <p>The <code>webbrowser</code> module doesn't allow to do that. The <code>get</code> function you mentioned is to retrieve registered web browsers not to scrap a HTTP GET request.</p>
<p>I don't know what is triggering the behavior you described with IE, have you tried to change your <code>User-Agent</code> with <a hr... | 1 | 2016-06-17T07:14:44Z | [
"python",
"windows",
"internet-explorer",
"web-scraping"
] |
What are python's equivalents of std::lower_bound and std::upper_bound C++ algorithms? | 37,873,954 | <p>Does python provide functions for performing binary search on sorted lists, analogous to the <code>std::lower_bound</code> and <code>std::upper_bound</code> algorithms of the C++ Standard Library?</p>
| 1 | 2016-06-17T05:43:03Z | 37,873,955 | <p>Those functions are located in the <a href="https://docs.python.org/2/library/bisect.html" rel="nofollow">bisect</a> module:</p>
<ul>
<li><p>bisect.<strong>bisect_left</strong>(<em>a</em>, <em>x</em>, <em>lo=0</em>, <em>hi=len(a)</em>) is the analog of <code>std::lower_bound()</code>.</p></li>
<li><p>bisect.<strong... | 1 | 2016-06-17T05:43:03Z | [
"python",
"binary-search"
] |
How to print 'ON' for once if at least 1 'ON' of last 5 (ON/OFF) status? | 37,873,986 | <p>I'm trying to see if machine is working or not. I made a circuit to see current on the cable but sometimes I see 'OFF' on the screen even machine does not stop. I decided to change code instead of the circuit. So I want to see 'ON' on the screen if there is 'ON' for once in the last 5 status.</p>
<p>My code is like... | -1 | 2016-06-17T05:46:04Z | 37,874,118 | <p>Your current implementation holds a single previous state and cannot do what you want. A <a href="https://docs.python.org/3/library/collections.html#collections.deque" rel="nofollow"><code>deque()</code></a> is a nice fit for this task: it can be limited to a maximum size and it has fast appends and pops:</p>
<pre>... | 2 | 2016-06-17T05:55:56Z | [
"python",
"if-statement"
] |
How to print 'ON' for once if at least 1 'ON' of last 5 (ON/OFF) status? | 37,873,986 | <p>I'm trying to see if machine is working or not. I made a circuit to see current on the cable but sometimes I see 'OFF' on the screen even machine does not stop. I decided to change code instead of the circuit. So I want to see 'ON' on the screen if there is 'ON' for once in the last 5 status.</p>
<p>My code is like... | -1 | 2016-06-17T05:46:04Z | 37,874,132 | <p>Use an array to keep track of the last 5 statuses maybe? (Untested)</p>
<pre><code>prev_Status = ['None']
while True:
if sensor > 1.60:
Status = 'ON'
else:
Status = 'OFF'
if Status not in prev_Status:
print("Status : {}".format(Status))
prev_Status.append(Status)
if... | 0 | 2016-06-17T05:56:55Z | [
"python",
"if-statement"
] |
Can't load all friend Facebook API python | 37,874,200 | <p>I'm new to Facebook API. I try the below code but it shows only 27 friends in my list friend(I have about 200). Why? Thanks for your help.</p>
<pre><code>import facebook
token = 'my_token'
graph = facebook.GraphAPI(token)
friends = graph.get_connections(id='me', connection_name='friends')
numberOfFriends = len(frie... | 0 | 2016-06-17T06:02:33Z | 37,874,628 | <p>Only friends who authorized your app will show up. If you did not select your own app in the explorer, it will be the friends who authorized the explorer app with the user_friends permission.</p>
| 0 | 2016-06-17T06:31:24Z | [
"python",
"facebook-graph-api"
] |
How to combine many "x AND y" conditions with OR for WHERE clause | 37,874,212 | <p>I have a many to many junction table similar to the following:</p>
<pre><code> FooBar
-----------------------
id | foo_id | bar_id
1 | 1 | 1
2 | 1 | 2
3 | 2 | 3
4 | 3 | 4
</code></pre>
<p>and a list of <code>(foo_id, bar_id)</code>, such as:</p>
<pre><code... | 1 | 2016-06-17T06:03:21Z | 37,874,925 | <p>The problem is that a call to <code>or_()</code> with a single expression is basically just the expression, as there's nothing to OR with. Repeated calls to <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.filter" rel="nofollow"><code>Query.filter()</code></a> append new predic... | 1 | 2016-06-17T06:49:37Z | [
"python",
"sqlalchemy"
] |
Take an action each time a log is rotated in python | 37,874,217 | <p>I want to log a line describing the logging information for each log file created by the logger.</p>
<p>Currently I'm using a separate logger process which will be running all the time. It receives the information from a queue and writes it to the log. A lot of modules will be passing information to this logging qu... | 0 | 2016-06-17T06:03:50Z | 37,875,337 | <p>Maybe you can simply override the doRollover method from TimedRotatingFileHandler ?</p>
<pre><code>class CustomFileHandler(TimedRotatingFileHandler):
def doRollover(self):
super().doRollover()
self.stream.write(desc_string)
# to use it
handler = CustomFileHandler("log/info.log", when="D", interval=30,... | 1 | 2016-06-17T07:15:25Z | [
"python",
"logging",
"log-rotation"
] |
Raspberry Pi camera recording video lag but CPU usage is low | 37,874,284 | <p>I am developing a device with raspberryPi which can record the 6-axis acceleration and angular speed(MPU9250 though i2c), and filming the environment by Picamera at the same time. </p>
<p>But when I saving the 6-axis data to memory and filming the video, my QT4 GUI become very slow and after I stop the recording an... | 0 | 2016-06-17T06:08:58Z | 37,875,519 | <p>OK, I am silly lol</p>
<p>I found if I add one line "time.sleep(0.0001)" in "while True" function and everything will be ok </p>
| 0 | 2016-06-17T07:24:03Z | [
"python",
"python-2.7",
"pyqt",
"raspberry-pi"
] |
is it possible to execute a bash script on remote machine using python pexpect | 37,874,412 | <p>I connected to remote system using Python Pexpect, Now I want to execute some script(available on remote machine) on remote system is it possible?</p>
| 0 | 2016-06-17T06:16:26Z | 37,877,514 | <p>Yes,
you can do it by adding <code>\n</code> between the commands</p>
<p>Or, </p>
<pre><code>child = pexpect.spawn('ssh MACHINE')
child.sendline('command1')
child.sendline('command2')
child.sendline('command3')
child.close()
</code></pre>
<p>I would advice you reading this <a href="http://pexpect.readthedocs.i... | 2 | 2016-06-17T09:09:29Z | [
"python",
"shell",
"unix",
"pexpect"
] |
Override the shebang mangling in python setuptools | 37,874,445 | <h2>Background</h2>
<p>I write small python packages for a system that uses modules (<a href="https://luarocks.org/" rel="nofollow">https://luarocks.org/</a>) to manage packages. For those of you who don't know it, you can run <code>module load x</code> and a small script is run that modifies various environmental var... | 3 | 2016-06-17T06:18:35Z | 37,891,966 |
<p>I accidentally stumbled onto a workaround while trying to write a custom install script.</p>
<pre class="lang-py prettyprint-override"><code>import os
from setuptools import setup
from setuptools.command.install import install
here = os.path.abspath(os.path.dirname(__file__))
# Generate a list of python scripts... | 0 | 2016-06-18T00:01:14Z | [
"python",
"linux",
"setuptools"
] |
Extracting entries from a line into a list in Python Regex | 37,874,448 | <p>I have the following string:</p>
<pre><code>myst="Cluster 2 0 13aa,>FZGRY:07872:11201...*1 13aa,>FZGRY:08793:13012...at100.00%2 13aa,>FZGRY:04065:08067...at100.00%"
</code></pre>
<p>What I want to do is to extract content bounded by <code>></code> and <code>...</code>. into a list.
yielding:<... | 0 | 2016-06-17T06:18:53Z | 37,874,517 | <p>You can use look arounds to do this.</p>
<pre><code>>>> re.findall(r'(?<=>)[^.]+(?=[.]{3})', myst)
['FZGRY:07872:11201', 'FZGRY:08793:13012', 'FZGRY:04065:08067']
</code></pre>
<p><strong>Regex</strong></p>
<ul>
<li><p><code>(?<=>)</code> Positive look behind. Checks if the string is preceded... | 3 | 2016-06-17T06:23:23Z | [
"python",
"regex"
] |
forking a python process after loading TensorFlow | 37,874,838 | <p><code>tf.Session()</code> is not <code>fork</code> safe which means that the behavior of the system after forking a process while <code>TensorFlow</code> is loaded into the memory is unknown.</p>
<p>is there any work around for sharing multiple devices (on a single machine), between multiple processes?</p>
| 1 | 2016-06-17T06:45:38Z | 37,875,056 | <p>The standard way to share a TensorFlow runtime between multiple processes is to use the <a href="https://www.tensorflow.org/versions/r0.9/how_tos/distributed/index.html#distributed-tensorflow" rel="nofollow">distributed TensorFlow support</a>, which also works on a single machine.</p>
<p>In one process, you can sta... | 1 | 2016-06-17T06:58:35Z | [
"python",
"fork",
"tensorflow"
] |
Copy a range of text from csv column in pandas and python | 37,874,928 | <p>I have a csv file that I have imported into Pandas. Now it has almost 45 columns of data and each column has more than 100 lines of information. Now I need to select only the range of text that starts with a Date Stamp at the start and ends with a Date Stamp.</p>
<p>Ex : </p>
<pre><code><GMT2015-09-01 00:03:29G... | 1 | 2016-06-17T06:49:51Z | 37,875,123 | <p>I think you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> data in column <code>Ticket Description</code> by <code><></code> and then select output <code>DataFrame</code> by <a href="http://pandas.pydata.org/pandas-docs/st... | 0 | 2016-06-17T07:02:22Z | [
"python",
"csv",
"pandas",
"dataframe",
"filtering"
] |
Copy a range of text from csv column in pandas and python | 37,874,928 | <p>I have a csv file that I have imported into Pandas. Now it has almost 45 columns of data and each column has more than 100 lines of information. Now I need to select only the range of text that starts with a Date Stamp at the start and ends with a Date Stamp.</p>
<p>Ex : </p>
<pre><code><GMT2015-09-01 00:03:29G... | 1 | 2016-06-17T06:49:51Z | 37,893,352 | <p>Regex and pandas apply should achieve what you want. I'm assuming u want only the text between the very first and second timestamp. I have created a dataframe with your message, except the second one starts with 2. <code>>(.+?)<</code> in the regex searches for the any number of characters surrounded by a <cod... | 0 | 2016-06-18T04:47:40Z | [
"python",
"csv",
"pandas",
"dataframe",
"filtering"
] |
How to check empty gzip file in Python | 37,874,936 | <p>I don't want to use OS commands as that makes it is OS dependent.</p>
<p>This is available in <code>tarfile</code>, <code>tarfile.is_tarfile(filename)</code>, to check if a file is a tar file or not.</p>
<p>I am not able to find any relevant commands in the <code>gzip</code> module.</p>
<hr>
<p><strong>EDIT</str... | 10 | 2016-06-17T06:50:06Z | 37,875,319 | <p>Try something like this:</p>
<pre><code>def is_empty(gzfile):
size = gzfile.read().
if len(size) > 0:
gzfile.rewind()
return False
else:
return True
</code></pre>
| 1 | 2016-06-17T07:14:32Z | [
"python",
"python-2.7",
"file",
"pandas",
"gzip"
] |
How to check empty gzip file in Python | 37,874,936 | <p>I don't want to use OS commands as that makes it is OS dependent.</p>
<p>This is available in <code>tarfile</code>, <code>tarfile.is_tarfile(filename)</code>, to check if a file is a tar file or not.</p>
<p>I am not able to find any relevant commands in the <code>gzip</code> module.</p>
<hr>
<p><strong>EDIT</str... | 10 | 2016-06-17T06:50:06Z | 37,875,919 | <p>Unfortunately, the <code>gzip</code> module does not expose any functionality equivalent to the <code>-l</code> list option of the <code>gzip</code> program. But in Python 3 you can easily get the size of the uncompressed data by calling the <code>.seek</code> method with a <code>whence</code> argument of 2, which s... | 5 | 2016-06-17T07:46:09Z | [
"python",
"python-2.7",
"file",
"pandas",
"gzip"
] |
How to check empty gzip file in Python | 37,874,936 | <p>I don't want to use OS commands as that makes it is OS dependent.</p>
<p>This is available in <code>tarfile</code>, <code>tarfile.is_tarfile(filename)</code>, to check if a file is a tar file or not.</p>
<p>I am not able to find any relevant commands in the <code>gzip</code> module.</p>
<hr>
<p><strong>EDIT</str... | 10 | 2016-06-17T06:50:06Z | 37,878,550 | <p>If you want to check whether a file is a valid Gzip file, you can open it and read one byte from it. If it succeeds, the file is quite probably a gzip file, with one caveat: an <em>empty</em> file also succeeds this test.</p>
<p>Thus we get</p>
<pre><code>def is_gz_file(name):
with gzip.open(name, 'rb') as f:
... | 3 | 2016-06-17T09:55:54Z | [
"python",
"python-2.7",
"file",
"pandas",
"gzip"
] |
How to check empty gzip file in Python | 37,874,936 | <p>I don't want to use OS commands as that makes it is OS dependent.</p>
<p>This is available in <code>tarfile</code>, <code>tarfile.is_tarfile(filename)</code>, to check if a file is a tar file or not.</p>
<p>I am not able to find any relevant commands in the <code>gzip</code> module.</p>
<hr>
<p><strong>EDIT</str... | 10 | 2016-06-17T06:50:06Z | 38,048,084 | <pre><code>import gzip
with gzip.open("pCSV.csv.gz", 'r') as f:
f.seek(3)
couterA = f.tell()
f.seek(2,0)
counterB = f.tell()
if(couterA > counterB):
print "NOT EMPTY"
else:
print "EMPTY"
</code></pre>
<p>This should do it without reading the file.</p>
| 1 | 2016-06-27T07:24:04Z | [
"python",
"python-2.7",
"file",
"pandas",
"gzip"
] |
How to check empty gzip file in Python | 37,874,936 | <p>I don't want to use OS commands as that makes it is OS dependent.</p>
<p>This is available in <code>tarfile</code>, <code>tarfile.is_tarfile(filename)</code>, to check if a file is a tar file or not.</p>
<p>I am not able to find any relevant commands in the <code>gzip</code> module.</p>
<hr>
<p><strong>EDIT</str... | 10 | 2016-06-17T06:50:06Z | 38,161,367 | <p>Looking through the <a href="https://github.com/python/cpython/blob/2.7/Lib/gzip.py" rel="nofollow">source code</a> for the Python 2.7 version of the <code>gzip</code> module, it seems to immediately return EOF, not only in the case where the gzipped file is zero bytes, but also in the case that the gzip file is zer... | 1 | 2016-07-02T14:49:43Z | [
"python",
"python-2.7",
"file",
"pandas",
"gzip"
] |
How to check empty gzip file in Python | 37,874,936 | <p>I don't want to use OS commands as that makes it is OS dependent.</p>
<p>This is available in <code>tarfile</code>, <code>tarfile.is_tarfile(filename)</code>, to check if a file is a tar file or not.</p>
<p>I am not able to find any relevant commands in the <code>gzip</code> module.</p>
<hr>
<p><strong>EDIT</str... | 10 | 2016-06-17T06:50:06Z | 38,161,406 | <p><strong>UPDATE:</strong></p>
<p>i would strongly recommend to upgrade to pandas 0.18.1 (currently the latest version), as each new version of pandas introduces nice new features and fixes tons of old bugs. And the actual version (0.18.1) will process your empty files just out of the box (see demo below).</p>
<p>If... | 3 | 2016-07-02T14:54:02Z | [
"python",
"python-2.7",
"file",
"pandas",
"gzip"
] |
How to check empty gzip file in Python | 37,874,936 | <p>I don't want to use OS commands as that makes it is OS dependent.</p>
<p>This is available in <code>tarfile</code>, <code>tarfile.is_tarfile(filename)</code>, to check if a file is a tar file or not.</p>
<p>I am not able to find any relevant commands in the <code>gzip</code> module.</p>
<hr>
<p><strong>EDIT</str... | 10 | 2016-06-17T06:50:06Z | 38,164,965 | <p>Unfortunately, any such attempt will likely have a fair bit of overhead, it would likely be cheaper to catch the exception, such as users commented above. A <a href="http://www.zlib.org/rfc-gzip.html#member-format" rel="nofollow">gzip</a> file defines a few fixed size regions, as follows:</p>
<p><strong>Fixed Regio... | 1 | 2016-07-02T22:27:18Z | [
"python",
"python-2.7",
"file",
"pandas",
"gzip"
] |
Setup.py not including bs4.py | 37,875,021 | <p>I am trying to create a .exe using py2exe. I am using python 2.17.10. My setup.py is as follows: </p>
<pre><code>from distutils.core import setup
import bs4, py2exe, HTMLParser
setup(
console=["Report.py"],
zipfile = None,
author='author',
py_modules =['bs4', 'HTMLParser'],
options = {"py2exe":... | 1 | 2016-06-17T06:56:05Z | 37,941,904 | <p>I was able to solve the problem. My main problem was with the implementation of py2exe with bs4. I had a line of code: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>soup = BeautifulS... | 0 | 2016-06-21T10:27:07Z | [
"python",
"html-parsing",
"executable",
"os.walk",
"bs4"
] |
Python pass more than one arguments to tcl proc using Tkinter tcl.eval | 37,875,115 | <p>how to pass more than one arguments to tcl proc using Tkinter. i want to pass 3 args to tcl proc tableParser from python proc validate_op which has 3 args...</p>
<pre><code>from Tkinter import Tcl
import os
tcl = Tcl()
def validate_op(fetch, header, value):
tcl.eval('source tcl_proc.tcl')
tcl.eval('set o... | 2 | 2016-06-17T07:01:45Z | 37,876,735 | <p>The simplest way to handle this is to use the <code>_stringify</code> function in the Tkinter module.</p>
<pre><code>def validate_op(fetch, header, value):
tcl.eval('source tcl_proc.tcl')
f = tkinter._stringify(fetch)
h = tkinter._stringify(header)
v = tkinter._stringify(value)
tcl.eval('set op... | 1 | 2016-06-17T08:31:36Z | [
"python",
"tkinter",
"tcl"
] |
Python pass more than one arguments to tcl proc using Tkinter tcl.eval | 37,875,115 | <p>how to pass more than one arguments to tcl proc using Tkinter. i want to pass 3 args to tcl proc tableParser from python proc validate_op which has 3 args...</p>
<pre><code>from Tkinter import Tcl
import os
tcl = Tcl()
def validate_op(fetch, header, value):
tcl.eval('source tcl_proc.tcl')
tcl.eval('set o... | 2 | 2016-06-17T07:01:45Z | 37,887,247 | <p>If you do not insist on eval, you can also do it like this:</p>
<pre><code>def validate_op(fetch, header, value):
tcl.eval('source tcl_proc.tcl')
# create a Tcl string variable op to hold the result
op = tkinter.StringVar(name='op')
# call the Tcl code and store the result in the string var
op.s... | 0 | 2016-06-17T17:35:25Z | [
"python",
"tkinter",
"tcl"
] |
Rock, Paper, Scissors Python 2 Game Statistics | 37,875,206 | <p>I am a beginner with Python attempting to create a RPS game with Python 2. I believe that I have the basic game and rules coded myself, however as I have browsed around different RPS python code posts I have confused myself and do not know how to continue using the def style I have already and fulfill my requiremen... | 0 | 2016-06-17T07:07:29Z | 37,875,537 | <ol>
<li>You will need at least one, or perhaps more, data structures / variables to hold that data. Considering how your code is structured, it seems like they could easily be created on main() and kept there (that is, you won't even need to pass em to other functions). What data structures (if any) to use to hold tha... | 0 | 2016-06-17T07:25:08Z | [
"python",
"python-2.7"
] |
How does Python's .join work? | 37,875,274 | <p>I was suggested the below solution but I didn't understand this line <code>cmd += "("+ ",".join(args) +")"</code> of the below code.
I got frustated because of this.Can someone please help me</p>
<p>Question is Reading an input like this </p>
<pre><code>12
insert 0 5
insert 1 10
insert 0 6
print
remove ... | 1 | 2016-06-17T07:12:01Z | 37,875,446 | <p>Consider the following input line:</p>
<pre><code>insert 1 10
</code></pre>
<p>So <code>s</code> is the list <code>["insert", "1", "10"]</code>. Note that the list elements are all strings.</p>
<p>So <code>cmd</code> is <code>"insert"</code> and <code>args</code> is <code>["1", "10"]</code>.</p>
<p>Now here's t... | 1 | 2016-06-17T07:21:03Z | [
"python"
] |
How does Python's .join work? | 37,875,274 | <p>I was suggested the below solution but I didn't understand this line <code>cmd += "("+ ",".join(args) +")"</code> of the below code.
I got frustated because of this.Can someone please help me</p>
<p>Question is Reading an input like this </p>
<pre><code>12
insert 0 5
insert 1 10
insert 0 6
print
remove ... | 1 | 2016-06-17T07:12:01Z | 37,875,570 | <p>Your question is what does the following line mean:</p>
<pre><code>cmd += "("+ ",".join(args) +")"
</code></pre>
<p><code>cmd</code> is a variable (with a string).</p>
<p><code>+=</code> is an operator which adds the right side to the left side.</p>
<p><code>"("</code> is a string containing a left parens.</p>
... | 1 | 2016-06-17T07:26:43Z | [
"python"
] |
How does Python's .join work? | 37,875,274 | <p>I was suggested the below solution but I didn't understand this line <code>cmd += "("+ ",".join(args) +")"</code> of the below code.
I got frustated because of this.Can someone please help me</p>
<p>Question is Reading an input like this </p>
<pre><code>12
insert 0 5
insert 1 10
insert 0 6
print
remove ... | 1 | 2016-06-17T07:12:01Z | 37,875,906 | <p>This line is there to ensure that your command is in the right syntax and has brackets and comma when you call it! I wrote it clearer in the code below:</p>
<pre><code>cmd = 'insert'
arg1 = '1'
arg2 = '3'
arg3 = '10'
cmd = cmd + "(" + ",".join((arg1, arg2, arg3)) + ")"
print cmd
</code></pre>
<p>Output:</p>
<pre... | 1 | 2016-06-17T07:45:34Z | [
"python"
] |
How do you search for characters in csv.reader() object? | 37,875,367 | <p>I'm trying to look for a character/word in an csv.reader() object.</p>
<p>I was sure this would work:</p>
<pre><code>freader = csv.reader(f)
z = freader.next()
print z
if "EE" in z:
print "Found"
else:
print "NOPE"
</code></pre>
<p>but it doesn't..
Here's the output:</p>
<pre><code>['1 EE-43-JT-32439 T... | 0 | 2016-06-17T07:17:08Z | 37,875,484 | <p>Check inside the list.</p>
<pre><code>for item in z:
if "EE" in item:
print "Found"
break # You can break the loop if the item is exits.
else:
print "NOPE"
</code></pre>
<p>You can understand the real difference here. </p>
<pre><code>In [196]: 'EE' in ['1 EE-43-JT-32439 Time;"1 EE-43... | 2 | 2016-06-17T07:22:15Z | [
"python",
"python-2.7",
"csv"
] |
Python: Referring to single labels in a Pmw RadioSelect | 37,875,456 | <p>I would like to create a hover box (or info box) which opens up when the user places the mouse cursor on top of a Pmw RadioSelect <em>label</em>. For example, when the cursor is placed on top of "Primary" the program opens an info box explaining what "Primary" means.</p>
<p><a href="http://i.stack.imgur.com/HvJ0n.p... | 3 | 2016-06-17T07:21:13Z | 37,879,099 | <p>If I understand well your problem, I think you are looking for:</p>
<ol>
<li>To rely on Pmw to draw the widgets (unlike what I did with Tkinter previously)</li>
<li><em>when the cursor is placed on top of "Primary" the program opens an info box explaining what "Primary" means.</em> (the effect I produced on the dem... | 2 | 2016-06-17T10:22:16Z | [
"python",
"tkinter",
"pmw"
] |
Python - I dont know how to x works in this code | 37,875,500 | <pre><code>def test(x):
def add(y):
return x+y
def mul(y):
return x*y
return "test"
</code></pre>
<p>will var <code>x</code> go to GC?</p>
| -1 | 2016-06-17T07:23:01Z | 37,875,613 | <p>Python uses reference counting to manage <em>objects</em>, not variables. If you want to know when the object referenced by <code>x</code> is cleared from memory, you need to keep track of how many references there are to it. <code>x</code> is just one such reference.</p>
<p>But, if there are <em>no other reference... | 1 | 2016-06-17T07:29:15Z | [
"python",
"garbage-collection"
] |
I need to create a list by extracting information out of a dict | 37,875,526 | <p>I have written a code which extracts all running public IP's from AWS . This returns the data in the form of a dict. The code runs as follows:</p>
<pre><code>for region in regions:
instance_information = {}
ip_dict = {}
client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRE... | 0 | 2016-06-17T07:24:16Z | 37,876,450 | <p>If i[0] is indeed IP, i[1] is Tag and i[3] is Region, you can use this function:</p>
<pre><code>def dict_to_list(dict_in):
ip_list = [i[0] for i in dict_in.values()]
tag_list = [i[1] for i in dict_in.values()]
region_list = []
for i in dict_in.values():
try:
region_list.append(i[... | 0 | 2016-06-17T08:15:41Z | [
"python",
"dictionary"
] |
Python Social Address Book | 37,875,633 | <p>I am having a bit of trouble with this question:</p>
<blockquote>
<p>Consider an address book that, besides addresses, keeps track of
someoneâs friends. The address book allows to query friends of friends
(like LinkedIn does with connections): a friend of degree 1 is a
direct friend, a friend of degree 2 ... | -3 | 2016-06-17T07:30:24Z | 37,875,921 | <p>Consider creating a class which holds a list which contains all the direct friends of that person. Then what you do is you search through the list when finding certain degrees of friends e.g. a friend of degree 2 is any friend which is not the person or any of his direct friends but another person. Continue adding t... | 0 | 2016-06-17T07:46:15Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.