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 |
|---|---|---|---|---|---|---|---|---|---|
Pandas + SQLite "cannot use index" error | 38,579,515 | <p>I am using pandas, sqlite, and sqlalchemy to search a bunch of strings for substrings. This project is inspired by <a href="https://plot.ly/python/big-data-analytics-with-pandas-and-sqlite/" rel="nofollow">this tutorial.</a></p>
<p>First, I create a sqlite database with one column of strings. Then I iterate through... | 1 | 2016-07-26T00:50:16Z | 38,580,088 | <p>That error message "cannot use index" seems to relate to the <code>pd.read_sql_query()</code> call and not the part where you create the index directly using the sqlite3 module.</p>
<p>A query with <code>some_col LIKE '%[some term]%'</code> cannot use an index on <code>some_col</code>. Queries with <code>some_col L... | 1 | 2016-07-26T02:16:42Z | [
"python",
"sqlite",
"pandas",
"sqlite3"
] |
nested dictionary sorting | 38,579,518 | <p>I've been trying to figure out how to sort these dictionaries: <code>d1</code> and <code>d2</code>inside the dictionary <code>d3</code>.</p>
<pre><code>d1 = {'eggs':1, 'cheese':1}
d2 = {'cake':1, 'cream':1}
d3 = {'breakfast':{},'dessert':{}}
d3['breakfast'] = d1
d3['dessert'] = d2
for k,v in sorted(d3.items()):
... | 0 | 2016-07-26T00:50:32Z | 38,579,555 | <p>So your algorithm has a few problems, mostly that you're nesting way too many times and looping over the same thing each time. Here's a better algorithm:</p>
<pre><code>for k,v in sorted(d3.items()):
print(k + ":")
for k2,v2 in sorted(v.items()):
print("\t" + k2 + ", " + str(v2))
</code></pre>
<p>I... | 2 | 2016-07-26T00:55:48Z | [
"python",
"sorting",
"python-3.x",
"dictionary"
] |
nested dictionary sorting | 38,579,518 | <p>I've been trying to figure out how to sort these dictionaries: <code>d1</code> and <code>d2</code>inside the dictionary <code>d3</code>.</p>
<pre><code>d1 = {'eggs':1, 'cheese':1}
d2 = {'cake':1, 'cream':1}
d3 = {'breakfast':{},'dessert':{}}
d3['breakfast'] = d1
d3['dessert'] = d2
for k,v in sorted(d3.items()):
... | 0 | 2016-07-26T00:50:32Z | 38,581,095 | <pre><code>d1 = {'eggs':1, 'cheese':1}
d2 = {'cake':1, 'cream':1}
d3 = {'breakfast':{},'dessert':{}}
d3['breakfast'] = d1
d3['dessert'] = d2
for key,val in sorted(d3.items()):
print(key,val)
</code></pre>
| 0 | 2016-07-26T04:37:06Z | [
"python",
"sorting",
"python-3.x",
"dictionary"
] |
pandas equivalent of np.where | 38,579,532 | <p><code>np.where</code> has the semantics of a vectorized if/else (similar to Apache Spark's <code>when</code>/<code>otherwise</code> DataFrame method). I know that I can use <code>np.where</code> on pandas <code>Series</code>, but <code>pandas</code> often defines its own API to use instead of raw <code>numpy</code> ... | 6 | 2016-07-26T00:52:45Z | 38,579,700 | <p>Try:</p>
<pre><code>(df['A'] + df['B']).where((df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
</code></pre>
<p>The difference between the <code>numpy</code> <code>where</code> and <code>DataFrame</code> <code>where</code> is that the default values are supplied by the <code>DataFrame</code> that the <code>... | 7 | 2016-07-26T01:15:44Z | [
"python",
"numpy",
"pandas"
] |
How to supply a mock class method for python unit test? | 38,579,535 | <p>Let's say I have a class like this.</p>
<pre><code> class SomeProductionProcess(CustomCachedSingleTon):
def loaddata():
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
</code></pre>
<p>Now at test time I want to change the ... | 2 | 2016-07-26T00:53:00Z | 38,579,804 | <p>Lets say you have a module named <strong>awesome.py</strong> and in it, you had:</p>
<pre><code>import time
class SomeProductionProcess(CustomCachedSingleTon):
def loaddata(self):
time.sleep(30) # simulating a long running process
return 2
</code></pre>
<p>Then your unittest where you mock <c... | 0 | 2016-07-26T01:34:20Z | [
"python",
"unit-testing",
"mocking"
] |
How to supply a mock class method for python unit test? | 38,579,535 | <p>Let's say I have a class like this.</p>
<pre><code> class SomeProductionProcess(CustomCachedSingleTon):
def loaddata():
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
</code></pre>
<p>Now at test time I want to change the ... | 2 | 2016-07-26T00:53:00Z | 38,579,823 | <p>To easily mock out a class method with a structured return_value, can use <code>unittest.mock.Mock</code>.</p>
<pre><code>from unittest.mock import Mock
mockObject = SomeProductionProcess
mockObject.loaddata = Mock(return_value=True)
</code></pre>
<p>EDIT:</p>
<p>Since you want to mock out the method with a cust... | 0 | 2016-07-26T01:37:05Z | [
"python",
"unit-testing",
"mocking"
] |
How to supply a mock class method for python unit test? | 38,579,535 | <p>Let's say I have a class like this.</p>
<pre><code> class SomeProductionProcess(CustomCachedSingleTon):
def loaddata():
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
</code></pre>
<p>Now at test time I want to change the ... | 2 | 2016-07-26T00:53:00Z | 38,579,854 | <p>Here is a simple way to do it using mock</p>
<pre><code>import mock
def new_loaddata(cls, *args, **kwargs):
# Your custom testing override
return 1
def test_SomeProductionProcess():
with mock.patch.object(SomeProductionProcess, 'loaddata', new=new_loaddata):
obj = SomeProductionProcess()
... | 0 | 2016-07-26T01:41:43Z | [
"python",
"unit-testing",
"mocking"
] |
Python 3 Dice Sim issue | 38,579,560 | <p>I am BRAND new to python because my new school requires it. I am used to c++ so I'm still learning the ropes. I'm trying to make a dice rolling simulator and I thought i was doing everything right but my code just won't work. Any tips or guides to help me learn would be greatly appreciated. Here is my code:</p>
<pr... | 0 | 2016-07-26T00:56:19Z | 38,579,603 | <p>For the first issue...</p>
<pre><code>num_rolled = random.randint(l,sides)
</code></pre>
<p><code>l != 1</code>. You put an "l" instead of the number 1. Python thinks this is a variable which you haven't defined anywhere -> the error you get.</p>
<p>From the <a href="https://docs.python.org/3/library/random.html"... | 1 | 2016-07-26T01:01:23Z | [
"python",
"python-3.x"
] |
Trying to create a login page using tkinter in python, doesn't seem to work | 38,579,711 | <p>The below code is what i am working on, I am trying to create a login page and validate username and password. Ideally loginValidate function should be invoked when i click on the submit button, but it is invoked even before i do so. Also the user_login and pwd_login values doesn't seems to be passed to the function... | 0 | 2016-07-26T01:17:23Z | 38,579,723 | <p>Look at what you've passed for the command:</p>
<pre><code>loginValidate(usr_login.get(),pwd_login.get())
</code></pre>
<p>You're <em>calling</em> the function and passing what this function <em>returns</em> as the command.</p>
<p>Simple fix = use <code>lambda</code></p>
<pre><code>lambda: loginValidate(usr_logi... | 0 | 2016-07-26T01:19:03Z | [
"python",
"class",
"object",
"tkinter",
"call-by-value"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</cod... | 1 | 2016-07-26T01:19:34Z | 38,579,772 | <p>You can do:</p>
<pre><code>x = re.findall('\d+', text)
result = x[0] if len(x) > 0 else ''
</code></pre>
<p>Note that your question isn't exactly related to regex. Rather, how do you safely find an element from an array, if it has none.</p>
| 1 | 2016-07-26T01:28:53Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</cod... | 1 | 2016-07-26T01:19:34Z | 38,579,778 | <p>Maybe this would perform a bit better in case greater amount of input data does not contain your wanted piece because except has greater cost. </p>
<pre><code>def return_first_match(text):
result = re.findall('\d+',text)
result = result[0] if result else ""
return result
</code></pre>
| 1 | 2016-07-26T01:29:37Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</cod... | 1 | 2016-07-26T01:19:34Z | 38,579,881 | <p>You could embed the <code>''</code> default in your regex by adding <code>|$</code>:</p>
<pre><code>>>> re.findall('\d+|$', 'aa33bbb44')[0]
'33'
>>> re.findall('\d+|$', 'aazzzbbb')[0]
''
>>> re.findall('\d+|$', '')[0]
''
</code></pre>
<p>Also works with <code>re.search</code> pointed out... | 3 | 2016-07-26T01:46:47Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</cod... | 1 | 2016-07-26T01:19:34Z | 38,579,883 | <p>If you only need the first match, then use <a href="https://docs.python.org/3.4/library/re.html#re.regex.search" rel="nofollow"><code>re.search</code></a> instead of <code>re.findall</code>:</p>
<pre><code>>>> m = re.search('\d+',text)
>>> m.group()
'33'
>>> m = re.search('\d+','aazzzbbb'... | 3 | 2016-07-26T01:47:19Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</cod... | 1 | 2016-07-26T01:19:34Z | 38,579,898 | <p>You shouldn't be using <code>.findall()</code> at all - <code>.search()</code> is what you want. It finds the leftmost match, which is what you want (or returns <code>None</code> if no match exists).</p>
<pre><code>m = re.search(pattern, text)
result = m.group(0) if m else ""
</code></pre>
<p>Whether you want to ... | 1 | 2016-07-26T01:48:58Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</cod... | 1 | 2016-07-26T01:19:34Z | 38,579,905 | <p>I'd go with:</p>
<pre><code> r = re.search("\d+", ch)
result = return r.group(0) if r else ""
</code></pre>
<p>re.search only looks for the first match in the string anyway, so I think it makes your intent slightly more clear than using findall.</p>
| 1 | 2016-07-26T01:49:48Z | [
"python",
"regex"
] |
Could I get [variable name, value] table from javascript code using python? | 38,579,757 | <p>I have a JavaScript file called <code>index.js</code>.
I'm developing a tool, written in Python, that it navigates JavaScript code statically to check if a certain API is defined or not.
In order to develop it, I need a data structure (table) which stores
<code>[variable, value]</code>.</p>
<p>Here is the example ... | 0 | 2016-07-26T01:27:12Z | 38,580,323 | <p>Yes, there is a popular parser for JavaScript written in JavaScript. Its called <a href="http://esprima.org" rel="nofollow">Esprima</a></p>
<p>It helps you obtain the full syntax tree.</p>
<p>I found a port of it in Python. It is not popular, but you can check it out.</p>
<p><a href="https://github.com/int3/pyesp... | 2 | 2016-07-26T02:55:04Z | [
"javascript",
"python",
"lexer"
] |
Python & Pandas: How to return a copy of a dataframe? | 38,579,921 | <p>Here is the problem. I use a function to return a randomized data, </p>
<pre><code>data1 = [3,5,7,3,2,6,1,6,7,8]
data2 = [1,5,2,1,6,4,3,2,7,8]
df = pd.DataFrame(data1, columns = ['c1'])
df['c2'] = data2
def randomize_data(df):
df['c1_ran'] = df['c1'].apply(lambda x: (x + np.random.uniform(0,1)))
df['c1']=d... | 1 | 2016-07-26T01:52:51Z | 38,579,987 | <p>I think you are right, and DataFrame.copy() have an optional argument 'deep'. You can find details in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html</a></p>
| 0 | 2016-07-26T02:02:31Z | [
"python",
"pandas"
] |
Python & Pandas: How to return a copy of a dataframe? | 38,579,921 | <p>Here is the problem. I use a function to return a randomized data, </p>
<pre><code>data1 = [3,5,7,3,2,6,1,6,7,8]
data2 = [1,5,2,1,6,4,3,2,7,8]
df = pd.DataFrame(data1, columns = ['c1'])
df['c2'] = data2
def randomize_data(df):
df['c1_ran'] = df['c1'].apply(lambda x: (x + np.random.uniform(0,1)))
df['c1']=d... | 1 | 2016-07-26T01:52:51Z | 38,669,915 | <p>Use <code>DataFrame.assign()</code>: </p>
<pre><code>def randomize_data(df):
return df.assign(c1=df.c1 + np.random.uniform(0, 1, df.shape[0]))
</code></pre>
| 2 | 2016-07-30T02:48:46Z | [
"python",
"pandas"
] |
pygame - blitting a moving background image causes extreme fps drop? | 38,579,948 | <p>I'm making a Flappy Bird clone in PyGame and I'm trying to add a moving background image. I'm using a 800x600 image right now, and for some reason, when I blit the image, the performance suffers terribly. Is there something I'm doing wrong that is taking up a lot of resources?</p>
<pre><code>import pygame, sys
impo... | 0 | 2016-07-26T01:56:11Z | 38,580,417 | <p>Typically, this should not be a problem. You should try to set the FPS manually and see if there is a difference</p>
<pre><code># Create a clock
clock = pygame.time.Clock()
# Set FPS (frames per second)
clock.tick(50)
</code></pre>
| 0 | 2016-07-26T03:07:32Z | [
"python",
"pygame"
] |
Flask error when connecting to mysql using pymysql | 38,579,992 | <p>So I am using pymysql to conenct mysql to flask. When I was developing a website on my local computer everything was fine, later when I uploaded my website to digital ocean trying to connect gives me an error:</p>
<blockquote>
<p>'NoneType' object is not iterable</p>
</blockquote>
<p>The view I get the error in:... | 2 | 2016-07-26T02:03:49Z | 38,582,050 | <p>Your pymysql.connection is trying to connect to a database running on the local machine.</p>
<p>Evidently there is no database on your Digital Ocean server, or if there is it's not accessible on port 3306 with the credentials provided.</p>
| 0 | 2016-07-26T05:59:47Z | [
"python",
"mysql",
"flask",
"pymysql"
] |
Flask error when connecting to mysql using pymysql | 38,579,992 | <p>So I am using pymysql to conenct mysql to flask. When I was developing a website on my local computer everything was fine, later when I uploaded my website to digital ocean trying to connect gives me an error:</p>
<blockquote>
<p>'NoneType' object is not iterable</p>
</blockquote>
<p>The view I get the error in:... | 2 | 2016-07-26T02:03:49Z | 38,587,412 | <p>Found a mistake. All I need was a fresh reinstall of mysql :)</p>
| 0 | 2016-07-26T10:31:13Z | [
"python",
"mysql",
"flask",
"pymysql"
] |
Transfer files with sockets in Python 3 | 38,580,012 | <p>I have the following client-server socket app to upload a file to a server. </p>
<h2>Server code:</h2>
<pre><code> import socket,sys,SocketServer
class EchoRequestHandler(SocketServer.BaseRequestHandler):
def setup(self):
print self.client_address, 'connected!'
self.request.send... | 1 | 2016-07-26T02:05:48Z | 38,580,113 | <p>You could improve your loop quite a bit.</p>
<ol>
<li>Use <code>while True</code> rather than <code>while 1</code>. Sure it works and is less typing, but if you really wanted less typing then you should be using Perl. <code>while True</code> is easy enough that nearly anyone could guess at the meaning - <code>while... | 1 | 2016-07-26T02:20:43Z | [
"python",
"sockets",
"python-sockets"
] |
Vectorizing with variable array indices | 38,580,015 | <p>I'm running python with numpy, and I have a loop which, stripped down, looks like this:</p>
<pre><code>result = np.zeros(bins)
for i in xrange(bins):
result[f(i)] += source[i]
</code></pre>
<p>Here, both result and source are numpy arrays, and f is a mildly complicated set of arithmetic operations. For example... | 1 | 2016-07-26T02:06:19Z | 38,580,354 | <p>To vectorize <code>f</code>
the main idea is to replace scalar operations with numpy vector-based functions.
For example, if originally we have</p>
<pre><code>def f(x):
return min(int(width*pow(x, 3)), bins-1)
</code></pre>
<p>then we could instead use </p>
<pre><code>def fvec(x):
return np.minimum((width... | 3 | 2016-07-26T02:58:36Z | [
"python",
"numpy",
"vectorization"
] |
Initializing form input fields from url parameters in Django | 38,580,058 | <p>I am building my own projects based on the instructions from 'Django by Example' book. </p>
<p>However I got stuck on <strong>how does django initialize input form fields using URL parameters</strong>?</p>
<pre><code>#models.py
class Image(models.Model):
title = models.CharField(max_length=200)
descripti... | 0 | 2016-07-26T02:12:56Z | 38,581,673 | <p>1) Yes - request.GET is simply a fancy dictionary (technically a QueryDict), and the form "data" argument expects a dict with keys corresponding to the fields in the form. You could technically pass the form any dictionary if it had the right keys representing the fields. </p>
<p>2) Generally speaking, there is no... | 0 | 2016-07-26T05:30:34Z | [
"python",
"django",
"forms",
"django-forms"
] |
Getting the desired datetime value from x axis in bokeh | 38,580,063 | <p>I have read the documentation and have searched Google and StackOverflow for answers but none the wiser yet. </p>
<p>I have a bokeh graph with circle glyphs for two variables 'score' and 'stress', and a third variable 'date' as a datetime x axis (picture <a href="http://i.stack.imgur.com/EYgKY.png" rel="nofollow">h... | 2 | 2016-07-26T02:13:33Z | 38,585,825 | <p>A simple workaround would be to provide date in string format in addition.</p>
<pre><code>dateStr= {'dateStr': [x.isoformat() for x in data['date']]}
data.update(dateStr)
</code></pre>
<p>then, you can use dateStr in your hover.tooltips and to generate the url</p>
<pre><code>hover.tooltips = [
("score", "@sco... | 0 | 2016-07-26T09:19:11Z | [
"python",
"datetime",
"bokeh"
] |
How to get indexes of values in a Pandas DataFrame? | 38,580,073 | <p>I am sure there must be a very simple solution to this problem, but I am failing to find it (and browsing through previously asked questions, I didn't find the answer I wanted or didn't understand it).</p>
<p>I have a dataframe similar to this (just much bigger, with many more rows and columns):</p>
<pre><code> ... | 4 | 2016-07-26T02:15:13Z | 38,580,158 | <p>To calculate dVal/dX:</p>
<pre><code>dVal = df.iloc[:, 1:].diff() # `x` is in column 0.
dX = df['x'].diff()
>>> dVal.apply(lambda series: series / dX)
val1 val2 val3
0 NaN NaN NaN
1 1 NaN NaN
2 1 NaN NaN
3 1 NaN NaN
4 1 NaN 0.96
5 1 NaN 0.96
6 ... | 3 | 2016-07-26T02:28:35Z | [
"python",
"numpy",
"pandas"
] |
Threads stops at Beautifulsoup command - unable to interrupt | 38,580,110 | <p>I'm working on a python code to scrape a blog that looks a bit like this:</p>
<pre><code>def main():
thread=threading.Thread(target=blogthread,args=(path,username))
thread.start()
threads.append(thread)
...
def blogthread(path,username,steem):
s=site_scraper.userposts(username)
...
def use... | 1 | 2016-07-26T02:20:00Z | 38,580,465 | <p>The main thread finishes but the other threads are still running. I dont know why they get stuck at the BeautifulSoup line. However you can fix it by exiting the program if the main thread is done. Simply do a "quit(0)" command at the end of the main thread. </p>
| -1 | 2016-07-26T03:15:28Z | [
"python",
"multithreading",
"web-scraping",
"beautifulsoup"
] |
IndexError: string index out of range python | 38,580,148 | <p>I have the following list: </p>
<pre><code>url_sims1=[('http://bp.velocityfrequentflyer.com/',
[(2, 0.90452874),
(1, 0.83522302),
(4, 0.77591574),
(0, 0.72705799),
(3, 0.52282226)]),
('http://cartrawler.virginaustralia.com/',
[(3, 0.79298556),
(1, 0.78112978),
(2, 0.76006395),
(0, 0.585707... | 1 | 2016-07-26T02:26:14Z | 38,580,252 | <p>Given that you have <code>url_sims1</code> and <code>categories</code>, then try:</p>
<pre><code>In [4]: [(url, [(categories[i], x) for i,x in lst]) for url,lst in url_sims1]
Out[4]:
[('http://bp.velocityfrequentflyer.com/',
[('active lifestyle', 0.9045),
('points of passion', 0.8352),
('travel savvy', 0.7... | 1 | 2016-07-26T02:42:32Z | [
"python",
"for-loop",
"indexing"
] |
Python: string in string check fails | 38,580,272 | <p>I've been banging my head against this for hours, researching and refactoring, but I cannot get it to work.</p>
<pre><code>import paramiko
import sys
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh.connect(switch, username='user',
password='pass')
stdin,stdout,stde... | 0 | 2016-07-26T02:45:48Z | 38,580,341 | <p>Sometimes there are small differences between strings that can't easily be seen in the console. Try this:</p>
<pre><code>print('SwitchPort: {!r}'.format(switchPort))
print('line: {!r}'.format(line))
</code></pre>
<p>It will likely make the difference easier to spot.</p>
<p>Per discussion above, the actual issue h... | 0 | 2016-07-26T02:56:57Z | [
"python",
"string",
"compare"
] |
How to Save file names and their directories path in a text file using Python | 38,580,290 | <p>I am trying to find a string that is contained in files under a directory. Then make it to store it's file names and directories under a new text file or something.
I got upto where it is going through a directory and finding a string, then printing a result. But not sure of the next step. </p>
<p>Please help, I'm... | 0 | 2016-07-26T02:48:32Z | 38,580,414 | <p>Don't do a string comparison if your looking for a dictionary. Instead use the json module. Like this.</p>
<pre><code>import json
import os
filesFound = []
def searchDir(dirName):
for name in os.listdir(dirName):
# If it is a file.
if os.isfile(dirName+name):
try:
f... | 0 | 2016-07-26T03:07:09Z | [
"python",
"string-comparison",
"file-comparison"
] |
How to Save file names and their directories path in a text file using Python | 38,580,290 | <p>I am trying to find a string that is contained in files under a directory. Then make it to store it's file names and directories under a new text file or something.
I got upto where it is going through a directory and finding a string, then printing a result. But not sure of the next step. </p>
<p>Please help, I'm... | 0 | 2016-07-26T02:48:32Z | 38,580,422 | <p>This should write the output to a csv file</p>
<pre><code>import csv
import os
with open('target.txt') as infile: source = infile.read()
with open("output.csv", 'w') as fout:
outfile = csv.writer(fout)
outfile.writerow("Directory FileName FilePath".split())
for root, dirnames, fnames in os.walk("/User... | 0 | 2016-07-26T03:08:11Z | [
"python",
"string-comparison",
"file-comparison"
] |
pandas calculate the counts and sum group by each category | 38,580,327 | <p>i have a dataframe:</p>
<pre><code> category num1 num2 mark
1 A 2 2 0
2 B 3 3 1
3 C 4 2 2
4 C 3 5 2
5 D 6 8 0
6 E 7 5 1
7 D 8 1 1
</code></pre>
<p>i want to calculate the counts number for each category group by the mark(as the columns), like:</p>... | 2 | 2016-07-26T02:55:39Z | 38,580,452 | <pre><code>>>> pd.pivot_table(df,index=['category'],columns=['mark'],aggfunc=len).fillna(0)
num
mark 0 1 2
category
A 1.0 0.0 0.0
B 0.0 1.0 0.0
C 0.0 0.0 2.0
D 1.0 1.0 0.0
E 0.0 1.0 0.0
>>> pd.pivot_table(df,index=['category'],c... | 3 | 2016-07-26T03:13:25Z | [
"python",
"pandas"
] |
pandas calculate the counts and sum group by each category | 38,580,327 | <p>i have a dataframe:</p>
<pre><code> category num1 num2 mark
1 A 2 2 0
2 B 3 3 1
3 C 4 2 2
4 C 3 5 2
5 D 6 8 0
6 E 7 5 1
7 D 8 1 1
</code></pre>
<p>i want to calculate the counts number for each category group by the mark(as the columns), like:</p>... | 2 | 2016-07-26T02:55:39Z | 38,580,643 | <p>Use <code>agg</code>.</p>
<pre><code>idx_cols = ['category', 'mark']
agg_dict = {'num1': {'Sum': 'sum'}, 'num2': {'Count': 'count'}}
df.set_index(idx_cols).groupby(level=[0, 1]).agg(agg_dict).unstack()
</code></pre>
<p><a href="http://i.stack.imgur.com/i0zwv.png" rel="nofollow"><img src="http://i.stack.imgur.com/... | 3 | 2016-07-26T03:40:04Z | [
"python",
"pandas"
] |
To remove an element and assign the list in one line | 38,580,337 | <p>So as the question says, is it possible to remove an element and return the list in one line?</p>
<p>So if lets say</p>
<pre><code>a = [1, 3, 2, 4]
b = a.remove(1)
</code></pre>
<p>This would set b to be NoneType, so I was wondering if there's a way to do this.</p>
| -1 | 2016-07-26T02:56:40Z | 38,580,371 | <p>I suppose this would work:</p>
<pre><code>a = [1, 3, 2, 4]
b = (a.remove(1), a)[1]
</code></pre>
<p>This is assuming that you want to do both things:</p>
<ol>
<li>Modify the original list by removing the element, and</li>
<li>Return the (now modified) list.</li>
</ol>
<p><strong>EDIT</strong></p>
<p>Another alt... | 2 | 2016-07-26T03:01:15Z | [
"python",
"list"
] |
To remove an element and assign the list in one line | 38,580,337 | <p>So as the question says, is it possible to remove an element and return the list in one line?</p>
<p>So if lets say</p>
<pre><code>a = [1, 3, 2, 4]
b = a.remove(1)
</code></pre>
<p>This would set b to be NoneType, so I was wondering if there's a way to do this.</p>
| -1 | 2016-07-26T02:56:40Z | 38,580,386 | <p>Since <code>remove</code> returns <code>None</code>, you could just <code>or a</code> to it:</p>
<pre><code>>>> a = [1, 3, 2, 4]
>>> a.remove(1) or a
[3, 2, 4]
</code></pre>
| 2 | 2016-07-26T03:02:29Z | [
"python",
"list"
] |
To remove an element and assign the list in one line | 38,580,337 | <p>So as the question says, is it possible to remove an element and return the list in one line?</p>
<p>So if lets say</p>
<pre><code>a = [1, 3, 2, 4]
b = a.remove(1)
</code></pre>
<p>This would set b to be NoneType, so I was wondering if there's a way to do this.</p>
| -1 | 2016-07-26T02:56:40Z | 38,580,875 | <p>List <code>a</code> assign to <code>b</code>:</p>
<pre><code>b = a.remove(1) or a
a is b # True
</code></pre>
<p>Using <code>b</code> is the same to use <code>a</code>, and it's dangerous if you get a final object like <code>[b, c, d]</code>, because if you update one of this list element, the all elements ... | 0 | 2016-07-26T04:09:59Z | [
"python",
"list"
] |
Python - TypeError: Error when calling the metaclass bases int() takes at most 2 arguments (3 given) | 38,580,579 | <p>My code doesn't work in Sublime Text 3 and the error is shown below. However, it does work in IDLE and so I am rather confused. I have read similar questions but it seems that they are not exactly the same as my problem. Could anyone tell me what have I done wrong? Thank you.</p>
<pre><code>class Animal(object):
... | -1 | 2016-07-26T03:32:11Z | 38,580,984 | <p>I suspect you had redefined <code>object</code> when you were getting the error. If <code>object</code> was bound to an integer (e.g. after <code>object = 3</code> or similar), any <code>class</code> statement that explicitly names <code>object</code> as a base will cause exactly the exception you describe.</p>
<p>... | 0 | 2016-07-26T04:24:06Z | [
"python",
"sublimetext3"
] |
CanWeMakeIt function python, it doesn´t return anything | 38,580,602 | <p>I have to write a function that should return the bool value True if you can spell out myWord using only the letters in myLetters, and return the bool value False if it cannot.<br>
To do this I need my letterPoints dictionary which is:</p>
<pre><code>global letterPoints
letterPoints = {"A": 1, "B": 3, "C": 3, "D": ... | -3 | 2016-07-26T03:34:07Z | 38,580,726 | <p>Here is your function</p>
<pre><code>def canWeMakeIt(my_word, letters):
allowed = list(letters):
for i in my_word:
if i not in allowed:
return False
return True
#NOTICE HOW YOU MUST CALL IT TO DO SOMETHING
print(canWeMakeIt("cat","tack"))
</code></pre>
<p>Now let's analize your code : ... | 1 | 2016-07-26T03:49:51Z | [
"python"
] |
CanWeMakeIt function python, it doesn´t return anything | 38,580,602 | <p>I have to write a function that should return the bool value True if you can spell out myWord using only the letters in myLetters, and return the bool value False if it cannot.<br>
To do this I need my letterPoints dictionary which is:</p>
<pre><code>global letterPoints
letterPoints = {"A": 1, "B": 3, "C": 3, "D": ... | -3 | 2016-07-26T03:34:07Z | 38,586,434 | <p>You could count the letters in <code>word</code> through a <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> and then compare those letters and the number of occurrences to the keys and values of the dictionary <code>available_letters... | 0 | 2016-07-26T09:45:22Z | [
"python"
] |
Checking if Pyro remote objects are reachable | 38,580,646 | <p>I have a one Pyro server running in each of my VMs. These are all the same objects, and I'm just running them to ensure reliability. I'd like to be able to monitor whether these objects are "alive" and reachable or not. </p>
<p>Assuming I have their URIs, how can I check that without trying to run a method of the a... | 0 | 2016-07-26T03:40:37Z | 38,674,487 | <p>You don't have to add a <code>noop</code> / <code>ping</code> method to your objects, because you can use the <code>_pyroBind()</code> method on a proxy object for this. It will raise a CommunicationError if the object is not reachable. For example to see if the name server is running on port 9999:</p>
<pre><code>i... | 1 | 2016-07-30T13:32:02Z | [
"python",
"pyro"
] |
Synchronize two element values in PyQt5 | 38,580,702 | <p>I have a slider and a text box that contains an integer (is there a dedicated integer box?) in PyQt5 shown side by side.</p>
<p>I need these two values to be synchronized, and the way I am doing it right now is with a QtTimer and if statements detecting if one value has changed more recently than the other, and the... | 0 | 2016-07-26T03:46:41Z | 38,584,101 | <p>You can just connect each of the sliders to the other one, straight-forward. I don't know the exact connection you want between the sliders, but it could look something like this.</p>
<pre><code>max_player_slider.valueChanged.connect(self.slider1_fu)
npc_stream_slider.valueChanged.conenct(self.slider2_fu)
def slid... | 1 | 2016-07-26T07:55:31Z | [
"python",
"python-3.x",
"pyqt",
"synchronization",
"pyqt5"
] |
Synchronize two element values in PyQt5 | 38,580,702 | <p>I have a slider and a text box that contains an integer (is there a dedicated integer box?) in PyQt5 shown side by side.</p>
<p>I need these two values to be synchronized, and the way I am doing it right now is with a QtTimer and if statements detecting if one value has changed more recently than the other, and the... | 0 | 2016-07-26T03:46:41Z | 38,589,896 | <p>The simple solution is to connect the <code>valueChanged</code> for each slider/number box to a slot which synchronises the values</p>
<pre><code>self.slider1.valueChanged.connect(self.handleSlider1ValueChange)
self.numbox1.valueChanged.connect(self.handleNumbox1ValueChange)
@QtCore.pyqtSlot(int)
def handleSlider1... | 2 | 2016-07-26T12:26:40Z | [
"python",
"python-3.x",
"pyqt",
"synchronization",
"pyqt5"
] |
redirect in loadhook in web.py | 38,580,816 | <p>I'm making a web.py app. I'm using a unloadhook function to check if a certain var is in the session for each call.</p>
<p>I need to redirect (to index) if it's not there. However, firefox gives me the message that the redirect will never terminate when I call web.seeother in the unloadhook function. I can correctl... | 0 | 2016-07-26T04:00:53Z | 38,581,743 | <p>I think redirection is in dead loop. Maybe your certain <code>var</code> doesn't be saved in session after calling <code>web.seeother</code></p>
| 0 | 2016-07-26T05:35:39Z | [
"python",
"http",
"web.py"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.some... | 0 | 2016-07-26T04:04:57Z | 38,580,914 | <p>As the error stated, Your <code>csvFile</code> is a <code>file</code> object, it is not a <code>dict</code> object, so you can't get an item out of it.</p>
<p>if your <code>csvFile</code> is in CSV format, you can use the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow" title="csv">csv</a> module... | 0 | 2016-07-26T04:14:51Z | [
"python",
"json"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.some... | 0 | 2016-07-26T04:04:57Z | 38,580,936 | <p>If your input file is JSON why not just use the JSON library to parse it and then run a for loop over that data. Then it is just a matter of iterating over the keys and extracting data.</p>
<pre><code>import json
from pprint import pprint
with open('data.json') as data_file:
data = json.load(data_file)
pp... | 0 | 2016-07-26T04:18:25Z | [
"python",
"json"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.some... | 0 | 2016-07-26T04:04:57Z | 38,580,958 | <p>Parsing values from a JSON file in Python , this link has it all @ <a href="http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python">Parsing values from a JSON file in Python</a> via stackoverflow.</p>
| 0 | 2016-07-26T04:21:19Z | [
"python",
"json"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.some... | 0 | 2016-07-26T04:04:57Z | 38,581,307 | <p>Here is a shell one-liner, should solve your problem, though it's not python.</p>
<pre><code>egrep -o '"(?:totalReplyCount|id)":(.*?)$' filename | awk '/totalReplyCount/ {if ($2+0 > 0) {getline; print}}' | cut -d: -f2
</code></pre>
<p>output:
</p>
<pre><code>"kjsdbesd2wd2eedd23rf3r3r2e2dwe2edsd"
</code></pre... | 0 | 2016-07-26T04:59:26Z | [
"python",
"json"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.some... | 0 | 2016-07-26T04:04:57Z | 38,581,394 | <p>After reading the question and all the above answers, please check if this is useful to you.</p>
<p>I have considered input file as simple file not as csv or json file.</p>
<p>Flow of code is as follow:</p>
<ul>
<li>Open and read a file in reverse order.</li>
<li>Search for ID in line. Extract ID and store in tem... | 1 | 2016-07-26T05:07:09Z | [
"python",
"json"
] |
Need help on a program that generate 1000 random integers between 0 and 9 and use count | 38,580,845 | <p>How to code a program that will generate 1000 random integers between 0 and 9 and displays the count for each # say counts, to store the counts for the number 0s 1s ...... 9s</p>
<p>Here's my code</p>
<pre><code>i = list(range(0,1000,9))
print (i)
i = len(i)
print (i)
</code></pre>
| -6 | 2016-07-26T04:05:53Z | 38,580,889 | <p>Use the <code>randint</code> function from random to generate an integer and store it in a <code>Counter</code>.</p>
<p>Documentation on the <code>Counter</code> collection is here: <a href="https://docs.python.org/2/library/collections.html" rel="nofollow">https://docs.python.org/2/library/collections.html</a></p>... | 1 | 2016-07-26T04:10:52Z | [
"python"
] |
Need help on a program that generate 1000 random integers between 0 and 9 and use count | 38,580,845 | <p>How to code a program that will generate 1000 random integers between 0 and 9 and displays the count for each # say counts, to store the counts for the number 0s 1s ...... 9s</p>
<p>Here's my code</p>
<pre><code>i = list(range(0,1000,9))
print (i)
i = len(i)
print (i)
</code></pre>
| -6 | 2016-07-26T04:05:53Z | 38,583,385 | <pre><code>from random import randint
dic = {k: 0 for k in range(10)}
for i in range(1000):
num = randint(0, 9)
dic[num] += 1
print dic
</code></pre>
<p>You can use a dictionary to keep the count as well</p>
| 0 | 2016-07-26T07:15:58Z | [
"python"
] |
How can I get around this try except block? | 38,580,881 | <p>I wrote a try except block that I now realize was a bad idea because it keep throwing 'blind' exceptions that are hard to debug. The problem is that I do not know how to go about writing it another way besides going through each of the methods that are called and manually reading all the exceptions and making a case... | -2 | 2016-07-26T04:10:30Z | 38,580,911 | <p>Often, exceptions come with error strings which can be used to pinpoint the problem. You can access this value like so:</p>
<pre><code>try:
# code block
except Exception as e:
print str(e)
</code></pre>
<p>You can also print what class of exception it is along with any error messages by using the <code>rep... | 1 | 2016-07-26T04:13:57Z | [
"python",
"django"
] |
How can I get around this try except block? | 38,580,881 | <p>I wrote a try except block that I now realize was a bad idea because it keep throwing 'blind' exceptions that are hard to debug. The problem is that I do not know how to go about writing it another way besides going through each of the methods that are called and manually reading all the exceptions and making a case... | -2 | 2016-07-26T04:10:30Z | 38,581,017 | <p>First your code is un-pythonic. You are using <code>'self'</code> for a function. "<code>self"</code> is usually reserved for a class. So in reading your code, it feels unnatural. Second, my style is to line up <code>"="</code> signs for readability. My advice is to start over -- Use standard pythonic conventions. ... | -1 | 2016-07-26T04:27:31Z | [
"python",
"django"
] |
How can I get around this try except block? | 38,580,881 | <p>I wrote a try except block that I now realize was a bad idea because it keep throwing 'blind' exceptions that are hard to debug. The problem is that I do not know how to go about writing it another way besides going through each of the methods that are called and manually reading all the exceptions and making a case... | -2 | 2016-07-26T04:10:30Z | 38,581,156 | <p>One way I like to go about it is configure Python logging and log the output. This gives you a lot of flexibility in what you do with the log output. The below example logs the exception traceback. </p>
<pre><code>import traceback
import logging
logger = logging.getLogger(__name__)
try:
...
except Exception ... | 0 | 2016-07-26T04:44:39Z | [
"python",
"django"
] |
The comments argument of genfromtxt in numpy | 38,580,927 | <p>I am learning the I/O functions of genfromtxt in numpy.
I tried an example from the user guide of numpy. It is about the comments argument of genfromtxt.</p>
<p><strong>Here is the example from the user guide of numpy:</strong></p>
<pre><code>>>> data = """#
... # Skip me !
... # Skip me too !
... 1, 2
..... | 1 | 2016-07-26T04:16:32Z | 38,581,134 | <p>Try below. First, dont use <code>"\"</code>. Second, why are you using <code>.BytesIO()</code> use <code>StringIO()</code></p>
<pre><code>import numpy as np
from StringIO import StringIO
data = """#
# Skip me !
# Skip me too !
1, 2
3, 4
... | 0 | 2016-07-26T04:41:22Z | [
"python",
"python-3.x",
"numpy",
"genfromtxt"
] |
The comments argument of genfromtxt in numpy | 38,580,927 | <p>I am learning the I/O functions of genfromtxt in numpy.
I tried an example from the user guide of numpy. It is about the comments argument of genfromtxt.</p>
<p><strong>Here is the example from the user guide of numpy:</strong></p>
<pre><code>>>> data = """#
... # Skip me !
... # Skip me too !
... 1, 2
..... | 1 | 2016-07-26T04:16:32Z | 38,581,227 | <p>In a <code>ipython3</code> (py3) interactive session I can do:</p>
<pre><code>In [326]: data = b"""#
...: ... # Skip me !
...: ... # Skip me too !
...: ... 1, 2
...: ... 3, 4
...: ... 5, 6 #This is the third line of the data
...: ... 7, 8
...: ... # And here comes the last line
... | 0 | 2016-07-26T04:51:31Z | [
"python",
"python-3.x",
"numpy",
"genfromtxt"
] |
how to know if https server is one way ssl or two way ssl | 38,581,008 | <p>Since I am new to this SSL I am asking this question. I googled and got this below mentioned HTTPS server python script. May I please know if its one way SSL or Two way SSL? And also how do I take dump to see the communication between client and server?</p>
<p>My requirement is to have one way SSL.</p>
<pre><code>... | 0 | 2016-07-26T04:26:44Z | 38,582,081 | <blockquote>
<p>May I please know if its one way SSL or Two way SSL</p>
</blockquote>
<p>This is one-way, i.e. the server is sending its certificate but not requesting a certificate from the client. The server could request a client certificate by adding <code>cert_reqs=ssl.CERT_REQUIRED</code> to the call of <code>... | 0 | 2016-07-26T06:01:45Z | [
"java",
"python",
"ssl",
"https",
"openssl"
] |
how to make srollable candelstick plot in Python? | 38,581,078 | <p>I have following candlestick plot. I want to make it scrollable so that I can see more details. The current plot is too long to see details.
I have found examples for making a line plot scrollable at here:
<a href="http://stackoverflow.com/questions/38559270/matplotlib-scrolling-plot">Matplotlib: scrolling plot</a>... | 1 | 2016-07-26T04:35:16Z | 38,680,083 | <p>For what you want, I'd recommend using Plotly, which allows for interactive data visualization (including scroll, zoom, panning, etc), and has a nice Python API.</p>
<p>Here are two different ways to do it (in both cases, you will need to <code>pip install plotly</code>)</p>
<ol>
<li><p>Using the Plotly website AP... | 1 | 2016-07-31T01:57:22Z | [
"python",
"matplotlib",
"scroll",
"finance",
"candlestick-chart"
] |
how to make srollable candelstick plot in Python? | 38,581,078 | <p>I have following candlestick plot. I want to make it scrollable so that I can see more details. The current plot is too long to see details.
I have found examples for making a line plot scrollable at here:
<a href="http://stackoverflow.com/questions/38559270/matplotlib-scrolling-plot">Matplotlib: scrolling plot</a>... | 1 | 2016-07-26T04:35:16Z | 38,718,928 | <p>You can plot the whole plot, and then use the slider widget to modify the axes area.</p>
<p>I couldn't reproduce your data because I don't have the <code>pandas.io.data</code> library, so I modified <a href="http://matplotlib.org/examples/pylab_examples/finance_demo.html" rel="nofollow">the candlestick example from... | 1 | 2016-08-02T11:16:00Z | [
"python",
"matplotlib",
"scroll",
"finance",
"candlestick-chart"
] |
Tkinter Gui stops while copying files with shutil | 38,581,084 | <p>My tkinter GUI program runs fine until it reaches to the funtion that copies specified files to destination. After that it freezes and I can't do anything with my program until the copying finishes. It works fine for small files but irritates for larger files. </p>
<p>How can I make my GUI respond while copying fil... | -2 | 2016-07-26T04:35:44Z | 38,583,138 | <p>Pff, hard to tell without real code, but it seems that your problem is that tkinter GUIs usually need their mainloop running to be fully operational.
When you use a heavy callback, tkinter stops event-loop waiting for callback to return, and file copying is heavy and long-taking operation.</p>
<p>So the solution is... | 0 | 2016-07-26T07:03:57Z | [
"python",
"tkinter"
] |
parsing the output of an executable | 38,581,152 | <p>I am trying to run an executable and parse its output,match the line with <code>QDLoader 9008</code> and then get the COM port value,output of the script should be<code>COM75</code> .
My script below doesn't print the line with matched string,why is that?</p>
<pre><code>import os
import re
import subprocess
'''
C:... | 0 | 2016-07-26T04:44:01Z | 38,581,276 | <p><code>re.search</code> returns a <a href="https://docs.python.org/2/library/re.html#match-objects" rel="nofollow">match object</a>, not a string. Even if it <em>did</em> return a string, it couldn't possibly return <code>COM75</code> - regex can't read your mind, how is it supposed to know what output you're expecti... | 2 | 2016-07-26T04:56:44Z | [
"python"
] |
Avoiding creating new method object | 38,581,161 | <p>According to the Python 2.7.12 Documentation,</p>
<blockquote>
<p>When the attribute is a user-defined method object, a new method
object is only created if the class from which it is being retrieved
is the same as, or a derived class of, the class stored in the
original method object; <strong>otherwise, th... | 2 | 2016-07-26T04:45:03Z | 38,581,377 | <p>Every time you write <code>Parent.func</code>, you are getting a new unbound method object. So <code>AnotherClass.func</code> never changes, but <code>Parent.func</code> does. You can see this if you do something like this:</p>
<pre><code>a = Parent.func
a2 = Parent.func
b = Parent.func2
c = Child.func
d = Anothe... | 3 | 2016-07-26T05:05:45Z | [
"python",
"python-2.7",
"object",
"inheritance",
"methods"
] |
Tkinter : How to bind parentheses key | 38,581,279 | <p>I have a program that needs to handle whenever the user enter a parentheses. I have tried:</p>
<pre><code>root.bind("<Shift-KP_9>")
</code></pre>
<p>But it didn't work, the same with </p>
<pre><code>root.bind("<Shift-9>")
</code></pre>
<p>How can I bind parentheses events into Tkinter ? Please help m... | 1 | 2016-07-26T04:56:53Z | 38,581,366 | <p>No need to overthink it. <code>root.bind("<(>")</code> will work just fine.</p>
| 1 | 2016-07-26T05:05:08Z | [
"python",
"tkinter",
"bind",
"parentheses"
] |
Problems with creating a python function "getWordPoints" --Python | 38,581,387 | <p>Alright, so I need help, because i need to créate a function that calculates and returns the total point value (as an int) of myWord using the letterPoints dictionary which consists of letter:pointValue pairs. Its for a Scrabble Word Finder. I already created a dictionary with the letters. The function needs one pa... | -5 | 2016-07-26T05:06:33Z | 38,581,652 | <pre><code>global letterPoints
letterPoints = {"A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J":8, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}
def GetValues( MyWord ):
total = 0
for letter in MyWord... | 0 | 2016-07-26T05:28:36Z | [
"python",
"function",
"variables",
"global"
] |
Using multiprocessing on a function fails with - string indices must be integers | 38,581,389 | <p>I have a function, that works in a single thread. Here's a simplified example. Basically I'm wanting to verify a few dead links and store the result in each item in a list of dictionaries.</p>
<pre><code>import requests
import sys
import logging
def main():
urls_to_check = [{'url': 'http://example.com'},
... | 0 | 2016-07-26T05:06:38Z | 38,581,559 | <p>You need to change your "check for 404's" function to accept a single url rather than a list; the map function passes the list elements in one at a time (to separate subprocesses in the pool), then reassembles them back into a list at the end:</p>
<pre><code>def check_for_404(item):
r = requests.get(item['url']... | 2 | 2016-07-26T05:20:19Z | [
"python",
"multithreading"
] |
boto3 Get a resource from a client | 38,581,465 | <p>The AWS Library for python (boto) has two different types of interfaces for working with AWS, a low level <code>client</code> and a higher level more pythonic <code>resource</code>.</p>
<p>Parts of my code use one, while other parts use the other.</p>
<p>Getting a <code>resource</code> from a <code>client</code> i... | 0 | 2016-07-26T05:12:31Z | 38,581,635 | <p>I think you should create resource and client separately as below:</p>
<pre><code>import boto3
sqs_resource = boto3.resource("sqs")
sqs_client = boto3.client("sqs")
print dir(sqs_resource)
print dir(sqs_client)
</code></pre>
<p>Output:</p>
<pre><code>[u'Message', u'Queue', '__class__', '__delattr__', '__dict__',... | 1 | 2016-07-26T05:27:13Z | [
"python",
"amazon-web-services",
"boto3"
] |
boto3 Get a resource from a client | 38,581,465 | <p>The AWS Library for python (boto) has two different types of interfaces for working with AWS, a low level <code>client</code> and a higher level more pythonic <code>resource</code>.</p>
<p>Parts of my code use one, while other parts use the other.</p>
<p>Getting a <code>resource</code> from a <code>client</code> i... | 0 | 2016-07-26T05:12:31Z | 38,595,104 | <p>There is no way to do this. If you want to use both, you should create a resource and use the embedded client. You can instantiate a resource with the exact same configuration as a client. The underlying client for the resource is created in the exact same way. The only difference between a resource's client and a c... | 2 | 2016-07-26T16:19:16Z | [
"python",
"amazon-web-services",
"boto3"
] |
Issue with null character in Cython | 38,581,589 | <p>The following Cython code is not working as expected. </p>
<pre><code>cdef char* char_tester():
py_str = "a\0b\0c".encode("UTF-8")
cdef char* c_str = py_str
return c_str
def test():
print(char_tester())
cdef char* my_str = char_tester()
for i in range(5):
print(my_str[i])
>&g... | 1 | 2016-07-26T05:22:40Z | 38,583,006 | <p>Assigment <code>cdef char * s = py_str</code> points to a memory location that is invalid after <code>char_tester()</code> returns. It is like a the case when a C function returns an address to local stack allocated variable, undefined behaviour.</p>
<p>With the following function</p>
<pre><code>from libc.stdlib c... | 2 | 2016-07-26T06:57:22Z | [
"python",
"cython"
] |
Spline interpolation over 3 variables for scattered data in Python? | 38,581,649 | <p>With other words I got a set of data-points (x,y,z) associated to a value b and I would like to interpolate this data as accurate as possible.
Scipy.interpolate.griddata only can do a linear interpolation, what are the other options?</p>
| 0 | 2016-07-26T05:28:31Z | 38,605,726 | <p>How about interpolating x, y, z separatly? I modified <a href="http://matplotlib.org/mpl_examples/mplot3d/lines3d_demo.py" rel="nofollow">this</a> tutorial example and added interpolation to it:</p>
<pre class="lang-python prettyprint-override"><code>import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
... | 0 | 2016-07-27T06:52:54Z | [
"python",
"scipy",
"interpolation",
"n-dimensional"
] |
Django Cannot find module i'm importing my model from | 38,581,952 | <p>I'm trying to import a model from another Django app in my project. However, when I try to import, I keep getting an error for: </p>
<blockquote>
<p>ImportError No module named trunk.profiles.models.</p>
</blockquote>
<p>However, when I cmnd click on the model on my IDE it takes me to the model. So it recognizes... | -1 | 2016-07-26T05:53:02Z | 38,582,656 | <p>Add <code>trunk.profiles</code> to Your <code>INSTALLED_APPS</code></p>
<p><strong>settings.py</strong></p>
<pre><code>INSTALLED_APPS = [
...
'trunk.profiles'
]
</code></pre>
<p><strong>TIP</strong></p>
<p>Instead of import model, specify a model with the full application label</p>
<pre><code>from djang... | 1 | 2016-07-26T06:38:53Z | [
"python",
"django",
"module",
"models"
] |
Python insert node function | 38,582,008 | <p>I am having a really hard time understanding how to properly fix my insert node function. I am not receiving any errors but I am also not displaying the list.</p>
<pre><code>class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
... | 0 | 2016-07-26T05:56:53Z | 38,582,102 | <p>Your insert() didn't return anything. So head will be None if you assign returned value to it.</p>
| 0 | 2016-07-26T06:03:32Z | [
"python",
"python-2.7"
] |
Python insert node function | 38,582,008 | <p>I am having a really hard time understanding how to properly fix my insert node function. I am not receiving any errors but I am also not displaying the list.</p>
<pre><code>class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
... | 0 | 2016-07-26T05:56:53Z | 38,582,233 | <p>I think this is you want</p>
<pre><code>class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def __init__(self):
self.head = None
def display(self):
current = self.head
while current:
print current.data,
... | 0 | 2016-07-26T06:12:59Z | [
"python",
"python-2.7"
] |
How to get contents of file in Sublime Text 3 Python API | 38,582,019 | <p>I'm very new to Python and Sublime Text API dev... so this may be easy?</p>
<p>I want to display the contents of a file (that sits next to the currently open file) to a new panel window. </p>
<p>I can create a new panel no problem and get it to display a string using </p>
<pre><code>def newLogWindow(self, output)... | 0 | 2016-07-26T05:57:35Z | 38,582,451 | <p>In Sublime Text, the built in API to open a file is tied to the <code>Window</code> and will return a <code>View</code> that corresponds to a tab. In your case, you want to update a panel (an existing <code>View</code> that doesn't relate to a tab) with the contents of the file, so the Sublime Text API can't be used... | 2 | 2016-07-26T06:27:00Z | [
"python",
"sublimetext3",
"sublimetext",
"sublime-text-plugin"
] |
How to filter data from a data frame when the number of columns are dynamic? | 38,582,127 | <p>I have a data frame like below </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
0 AA X1 1.2 0.5 -1.3 ......
1 BB Y1 0.76 -0.7 0.8 ......
2 CC Z1 0.7 -1.3 2.5 ......
3 DD L1 0.9 -0.5 0.4 ... | 4 | 2016-07-26T06:05:23Z | 38,582,173 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.abs.html" rel="nofollow"><code>abs</code></a> and <a href="http://pandas.pydata.org/pandas-docs/... | 4 | 2016-07-26T06:08:53Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How to filter data from a data frame when the number of columns are dynamic? | 38,582,127 | <p>I have a data frame like below </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
0 AA X1 1.2 0.5 -1.3 ......
1 BB Y1 0.76 -0.7 0.8 ......
2 CC Z1 0.7 -1.3 2.5 ......
3 DD L1 0.9 -0.5 0.4 ... | 4 | 2016-07-26T06:05:23Z | 38,582,185 | <ul>
<li>Use <code>filter</code> to get the columns you care about.</li>
<li><code>abs().lt(1)</code> to get find cells less than 1.</li>
<li><code>all(1)</code> to find rows where all <code>Value</code>'s are less than 1.</li>
</ul>
<hr>
<pre><code>df[df.filter(regex=r'Value').abs().lt(1).all(1)]
</code></pre>
<p><... | 5 | 2016-07-26T06:09:35Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How to filter data from a data frame when the number of columns are dynamic? | 38,582,127 | <p>I have a data frame like below </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
0 AA X1 1.2 0.5 -1.3 ......
1 BB Y1 0.76 -0.7 0.8 ......
2 CC Z1 0.7 -1.3 2.5 ......
3 DD L1 0.9 -0.5 0.4 ... | 4 | 2016-07-26T06:05:23Z | 38,582,662 | <p>In case you don't want to filter on the column name (even if they're prefixed), you can also use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> :</p>
<pre><code>>>> df[df.ix[:,2:].abs().lt(1).all(1)]
A_Name B_Detail Value_B... | 0 | 2016-07-26T06:39:19Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How to filter data from a data frame when the number of columns are dynamic? | 38,582,127 | <p>I have a data frame like below </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
0 AA X1 1.2 0.5 -1.3 ......
1 BB Y1 0.76 -0.7 0.8 ......
2 CC Z1 0.7 -1.3 2.5 ......
3 DD L1 0.9 -0.5 0.4 ... | 4 | 2016-07-26T06:05:23Z | 38,583,338 | <p>You can match the columns using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow">str.contains</a> then use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.apply.html" rel="nofollow">apply()</a> with <code>lambda</code>... | 0 | 2016-07-26T07:14:06Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How to write to file the values returned by a function | 38,582,238 | <p>Here;s the <code>calc_property_statistics</code> function which returns maximum, minimum, and average values. I need to write them to a file. </p>
<pre><code>def calc_property_statistics(prop, realisation=0):
values = prop.get_values(realisation)
maximum = np.max(values)
minimum = np.min(values)
... | -4 | 2016-07-26T06:13:34Z | 38,582,377 | <p>this is the example of function to write return values from other function to file:</p>
<pre><code>def my_func():
"""
this function return some value
:return:
"""
return 'This is some value'
def write_file(data):
"""
this function write data to file
:param data:
:return:
""... | 1 | 2016-07-26T06:22:54Z | [
"python"
] |
How to write to file the values returned by a function | 38,582,238 | <p>Here;s the <code>calc_property_statistics</code> function which returns maximum, minimum, and average values. I need to write them to a file. </p>
<pre><code>def calc_property_statistics(prop, realisation=0):
values = prop.get_values(realisation)
maximum = np.max(values)
minimum = np.min(values)
... | -4 | 2016-07-26T06:13:34Z | 38,582,827 | <pre><code>f=open('abc.txt','w')
def calc_property_statistics(prop, realisation=0):
values = prop.get_values(realisation)
maximum = np.max(values)
minimum = np.min(values)
average = np.average(values)
return (maximum, minimum, average)
#-------------------------------------------------------------... | -1 | 2016-07-26T06:48:15Z | [
"python"
] |
How to write to file the values returned by a function | 38,582,238 | <p>Here;s the <code>calc_property_statistics</code> function which returns maximum, minimum, and average values. I need to write them to a file. </p>
<pre><code>def calc_property_statistics(prop, realisation=0):
values = prop.get_values(realisation)
maximum = np.max(values)
minimum = np.min(values)
... | -4 | 2016-07-26T06:13:34Z | 38,583,519 | <p>at first it depends from format of file you need to use.</p>
<p>this is example how to write into simple text file with values separated by newline.</p>
<pre><code>x = calc_property_statistics(prop, realisation)
out_file = open('results.txt', 'wb')
out_file.write(x[0]) # maximum
out_file.write('\n')
out_file.write... | 0 | 2016-07-26T07:23:14Z | [
"python"
] |
Game doesn't stop from event-loop | 38,582,285 | <p>I got this far and it kind of got all confusing and I can't figure out one simple problem with the code.</p>
<pre><code>while not gameExit:
while gameOver == True:
pygame.display.flip()
gameDisplay.fill(white)
display_message("OVER. C to continue, Q to quit", red)
for event in p... | -2 | 2016-07-26T06:16:25Z | 38,582,440 | <p>Move: </p>
<pre><code>if ( lead_x < 0 ) or (lead_x >= 600) or ( lead_y < 0 ) or ( lead_y >= 800):
gameOver = True
</code></pre>
<p>out of the <code>pygame.event.get</code>-loop because it will only run if events have taken place (mouse moved, key pressed). Otherwise the code will not reach the... | 0 | 2016-07-26T06:26:03Z | [
"python",
"pygame"
] |
Pandas concatenate alternating columns | 38,582,356 | <p>I have two dataframes as follows:</p>
<pre><code>df2 = pd.DataFrame(np.random.randn(5,2),columns=['A','C'])
df3 = pd.DataFrame(np.random.randn(5,2),columns=['B','D'])
</code></pre>
<p>I wish to get the columns in an alternating fashion such that I get the result below:</p>
<pre><code>df4 = pd.DataFrame()
for i in... | 3 | 2016-07-26T06:21:04Z | 38,582,428 | <p>How about this?</p>
<pre><code>df4 = pd.concat([df2, df3], axis=1)
</code></pre>
<p>Or do they have to be in a specific order? Anyway, you can always reorder them:</p>
<pre><code>df4 = df4[['A','B','C','D']]
</code></pre>
<p>And without writing out the columns:</p>
<pre><code>df4 = df4[[item for items in zip(df... | 1 | 2016-07-26T06:25:21Z | [
"python",
"pandas"
] |
Pandas concatenate alternating columns | 38,582,356 | <p>I have two dataframes as follows:</p>
<pre><code>df2 = pd.DataFrame(np.random.randn(5,2),columns=['A','C'])
df3 = pd.DataFrame(np.random.randn(5,2),columns=['B','D'])
</code></pre>
<p>I wish to get the columns in an alternating fashion such that I get the result below:</p>
<pre><code>df4 = pd.DataFrame()
for i in... | 3 | 2016-07-26T06:21:04Z | 38,582,575 | <p>If you need something more dynamic, first zip both columns names of both DataFrames and then flat it:</p>
<pre><code>df5 = pd.concat([df2, df3], axis=1)
print (df5)
A C B D
0 0.874226 -0.764478 1.022128 -1.209092
1 1.411708 -0.395135 -0.223004 0.124689
2 1.515223 -2.184020 0.... | 5 | 2016-07-26T06:33:23Z | [
"python",
"pandas"
] |
Pandas concatenate alternating columns | 38,582,356 | <p>I have two dataframes as follows:</p>
<pre><code>df2 = pd.DataFrame(np.random.randn(5,2),columns=['A','C'])
df3 = pd.DataFrame(np.random.randn(5,2),columns=['B','D'])
</code></pre>
<p>I wish to get the columns in an alternating fashion such that I get the result below:</p>
<pre><code>df4 = pd.DataFrame()
for i in... | 3 | 2016-07-26T06:21:04Z | 38,582,597 | <p>Append even indices to <code>df2</code> columns and odd indices to <code>df3</code> columns. Use these new levels to sort.</p>
<pre><code>df2_ = df2.T.set_index(np.arange(len(df2.columns)) * 2, append=True).T
df3_ = df3.T.set_index(np.arange(len(df3.columns)) * 2 + 1, append=True).T
df = pd.concat([df2_, df3_], a... | 2 | 2016-07-26T06:35:01Z | [
"python",
"pandas"
] |
Pandas concatenate alternating columns | 38,582,356 | <p>I have two dataframes as follows:</p>
<pre><code>df2 = pd.DataFrame(np.random.randn(5,2),columns=['A','C'])
df3 = pd.DataFrame(np.random.randn(5,2),columns=['B','D'])
</code></pre>
<p>I wish to get the columns in an alternating fashion such that I get the result below:</p>
<pre><code>df4 = pd.DataFrame()
for i in... | 3 | 2016-07-26T06:21:04Z | 38,583,754 | <p>You could <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex_axis.html" rel="nofollow"><code>reindex_axis</code></a>.</p>
<pre><code>df = pd.concat(... | 2 | 2016-07-26T07:37:27Z | [
"python",
"pandas"
] |
How to save a global variable in flask? | 38,582,400 | <p>I want to save a global variable in flask, and after reading some documentation I know that 'flask.g' can do what I want, but during the test I found that the variable 'g' can't be saved like session, if I change the page in the same application, the variable 'g' miss it's attribute, after reading some documents, I ... | 0 | 2016-07-26T06:23:59Z | 38,586,105 | <p>You can save those type of variables in a separate config.py in the form of class variable and access that variable in any page by simply importing that class variable</p>
<p>app.py</p>
<pre><code>from config import GetConfig
print GetConfig.var
</code></pre>
<p>config.py</p>
<pre><code>class GetConfig:
var... | 0 | 2016-07-26T09:30:58Z | [
"python",
"flask"
] |
How to save a global variable in flask? | 38,582,400 | <p>I want to save a global variable in flask, and after reading some documentation I know that 'flask.g' can do what I want, but during the test I found that the variable 'g' can't be saved like session, if I change the page in the same application, the variable 'g' miss it's attribute, after reading some documents, I ... | 0 | 2016-07-26T06:23:59Z | 38,586,116 | <p>An alternative you could use is browser caching, you should keep you web server as stateless as possible meaning each request to the server should be totally independent hence not sharing any state.</p>
| 0 | 2016-07-26T09:31:21Z | [
"python",
"flask"
] |
Autoreconf failing when installing (py)COMPSs in a clusters | 38,582,513 | <p>I tried to install pyCOMPSs (v1.4) on a Cluster system using the
installation script for Supercomputers.
The script terminates with the following error:</p>
<pre><code>libtool: link: ranlib .libs/libcbindings.a
libtool: link: ( cd ".libs" && rm -f "libcbindings.la" && ln -s
"../libcbindings.la" "lib... | 5 | 2016-07-26T06:30:15Z | 38,582,647 | <p>Seems the error is due to the package includes a previous configuration
and in your case the autoreconf is not overwritting the Makefile and
other files produced by autotools. try with
running </p>
<pre><code>cd /home/xxx/repos/pycompss/COMPSs/Bindings/c/src/bindinglib
make maintainer-clean
</code></pre>
<p>Afte... | 5 | 2016-07-26T06:38:17Z | [
"java",
"python",
"distributed-computing",
"compss",
"pycompss"
] |
How not to choose blank rows in python? | 38,582,579 | <p>I wrote the following code in python to choose only selected rows. However 'activity_url.csv' has blank rows. Hence it is giving me an error. So how do I skip the blank rows?</p>
<pre><code>data = pd.read_csv('activity_url.csv', delimiter=';')
x="http"
url_data=np.array(data[data.iloc[:,1].str.contains(x, na=False)... | 0 | 2016-07-26T06:33:32Z | 38,586,795 | <p>you can try this code:</p>
<pre><code>import pandas as pd
df=pd.read_csv('activity_url.csv')
df=df.dropna()
</code></pre>
<p>After execution, you will get dataframe without any blank row.</p>
| 0 | 2016-07-26T10:01:32Z | [
"python",
"csv",
"pandas",
"blank-line"
] |
Python: Not all environment variables present in os.environ | 38,582,598 | <p>In the python shell, using </p>
<pre><code>import os
print os.environ
</code></pre>
<p>prints the complete list of environment variables with nothing missing. However when I call the interpreter with a filename: </p>
<pre><code>sudo python file.py
</code></pre>
<p>and use </p>
<pre><code>import os
print os.... | 0 | 2016-07-26T06:35:03Z | 38,604,229 | <p> I realised that the difference was because I was using sudo during the execution for the second where the environment was not preserved. I need to add
those environment variables to my sudoers file or preserve them during execution. </p>
| 0 | 2016-07-27T05:15:36Z | [
"python",
"environment"
] |
Editing a Row using Django Forms | 38,582,695 | <p>I wanted to edit a row in Django 1.9 using Django forms:</p>
<p>So what I did is</p>
<p>For the get request I initialized the form instance (views.py)</p>
<pre><code>def get(self, request):
myModel = model.myModel.objects.get(user=request.user)
form_instance = MyForm(initial=myModel.__dict__)
return r... | 1 | 2016-07-26T06:41:54Z | 38,583,704 | <p>Doing this bit wrong</p>
<pre><code>form_instance = MyForm(initial=myModel.__dict__)
</code></pre>
<p>it should be</p>
<pre><code>form_instance = MyForm(instance=myModel)
</code></pre>
<p>Oops, forgot to add, in order to handle the situation where the form validation fails, your post meethod might need something... | 0 | 2016-07-26T07:34:13Z | [
"python",
"django",
"django-models",
"django-forms"
] |
Delete points in scatter plot | 38,582,947 | <p>I plotted a scatter plot using python by importing data from text files and I want to delete points with x axis values 0. This is the program I have written</p>
<pre><code>mat0 = genfromtxt("herbig0.txt");
mat1 = genfromtxt("coup1.txt");
pyplot.xlim([-2,6])
pyplot.ylim([26,33])
colors=['red', 'blue','green']
pyplot... | 1 | 2016-07-26T06:54:32Z | 38,583,201 | <p>As your data is stored in <code>numpy</code> arrays you could always just filter them out:</p>
<p>Using either <code>nonzero</code>, or setting some small threshhold value that you filter out:</p>
<pre><code>#Either
mat_filter = np.nonzero(mat1[:,2])
#or
mat_filter = np.abs(mat1[:,2])>1e-12
</code></pre>
<p>Th... | 3 | 2016-07-26T07:07:04Z | [
"python",
"matplotlib"
] |
gaierror: [Errno 8] nodename nor servname provided, or not known | 38,582,990 | <p>Hello I am new to python , I am writing a code which generates dns requests </p>
<pre><code> from socket import error as socket_error
import threading
from random import randint
from time import sleep
def task(number):
try :
HOST = Random_website.random_website().rstrip() # fetc... | 0 | 2016-07-26T06:56:32Z | 38,583,829 | <p><strong>Like this:</strong></p>
<pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(("www.google.com",80))... | 1 | 2016-07-26T07:41:54Z | [
"python",
"sockets"
] |
Using any and all (euler # 7) | 38,583,167 | <p>Trying to find the 10,001st prime. This is what I had:</p>
<pre><code>def seven(count):
desired_count = count
actual_count = 6
number = 15
while desired_count > actual_count:
factors_in_number = range(int((number**.5)+1))
_factors_in_number = factors_in_number[2:]
prin... | 0 | 2016-07-26T07:05:00Z | 38,583,293 | <p>You do not get the <code>actual_count</code> because your <code>any</code> and <code>all</code> were not used as intended. In fact, the following <code>elif</code> block is never executed:</p>
<pre><code>elif number % all(_factors_in_number) != 0:
actual_count += 1
number += 2
</code></pre>
<p>Because ... | 4 | 2016-07-26T07:11:41Z | [
"python",
"python-2.7"
] |
Using any and all (euler # 7) | 38,583,167 | <p>Trying to find the 10,001st prime. This is what I had:</p>
<pre><code>def seven(count):
desired_count = count
actual_count = 6
number = 15
while desired_count > actual_count:
factors_in_number = range(int((number**.5)+1))
_factors_in_number = factors_in_number[2:]
prin... | 0 | 2016-07-26T07:05:00Z | 38,583,335 | <p>Using <code>all(_factors_in_number)</code> or <code>any(_factors_in_number)</code> is definitely not giving the result you are thinking it is:</p>
<pre><code>>>> any([1,2,3,4])
True
>>> 7 % any([1,2,3,4]) #True is treated like 1
0
</code></pre>
<p>Prehaps take a look at <code>help(any)</code> to ... | 2 | 2016-07-26T07:14:04Z | [
"python",
"python-2.7"
] |
Extracting data with BeautifulSoup and output to CSV | 38,583,263 | <p>As mentioned in the previous questions, I am using Beautiful soup with python to retrieve weather data from a website.</p>
<p>Here's how the website looks like:</p>
<pre><code><channel>
<title>2 Hour Forecast</title>
<source>Meteorological Services Singapore</source>
<description&g... | 0 | 2016-07-26T07:09:56Z | 38,583,912 | <p>EDIT 1 -Topic:</p>
<p>You're missing escape characters: </p>
<pre><code>C:\scripts>python neaweather.py
File "neaweather.py", line 30
writer.writerow( ('time', 'element['date']', 'element['time']', 'area_attrs_li') )
writer.writerow( ('time', 'element[\'date\']', 'element[\'time\']', 'area_attrs_li')
... | 1 | 2016-07-26T07:46:14Z | [
"python",
"csv"
] |
Odoo Missing Error while running a cron job for sending scheduled mail | 38,583,288 | <p>I have the following code. When the scheduler runs I am getting the error message. Some one help me to resolve the error in the code</p>
<blockquote>
<p>MissingError
One of the documents you are trying to access has been deleted, please try again after refreshing.</p>
</blockquote>
<pre><code>def send_foll... | 0 | 2016-07-26T07:11:25Z | 38,585,798 | <p>First of all write code using <strong>new api</strong>.</p>
<p>For getting template use <code>obj = self.env.ref('template_record_id')</code> then send <code>obj.send_mail(model.obj.id, force_send=True)</code>, if you want to set mail then before send <code>obj.email_to = 'test@example.com'</code></p>
<p>Final cod... | 0 | 2016-07-26T09:17:43Z | [
"python",
"cron",
"openerp",
"scheduler",
"odoo-8"
] |
Odoo Missing Error while running a cron job for sending scheduled mail | 38,583,288 | <p>I have the following code. When the scheduler runs I am getting the error message. Some one help me to resolve the error in the code</p>
<blockquote>
<p>MissingError
One of the documents you are trying to access has been deleted, please try again after refreshing.</p>
</blockquote>
<pre><code>def send_foll... | 0 | 2016-07-26T07:11:25Z | 38,587,657 | <p>This is the modified code and works fine</p>
<pre><code>def send_followup_mail(self, cr, uid, context=None):
quot_ids=self.search(cr, uid, [('state','=','amend_quote')])
for quot_id in quot_ids:
if quot_id:
quot_obj=self.browse(cr, uid, quot_id ,context=co... | 0 | 2016-07-26T10:41:23Z | [
"python",
"cron",
"openerp",
"scheduler",
"odoo-8"
] |
Django's NotImplementedError: annotate() + distinct(fields) is not implemented | 38,583,295 | <p>There are 2 simple models:</p>
<pre><code>class Question(TimeStampedModel):
text = models.CharField(max_length=40)
class Answer(TimeStampedModel):
question = models.ForeignKey(Question, related_name='answers')
is_agreed = models.BooleanField()
author = models.ForeingKey(User, related_name='answers'... | 1 | 2016-07-26T07:11:42Z | 38,586,709 | <p>Try this:</p>
<pre><code>Question.objects.annotate(
answer_amount=Count('answers'),
is_user_agreed=F('answers__is_agreed'),
).order_by('id', '-answers__is_agreed').distinct('id')
</code></pre>
<p>If <code>question</code> has no <code>answers</code>, then <code>question.is_user_agreed</code> is <code>None</... | 1 | 2016-07-26T09:57:46Z | [
"python",
"django",
"postgresql"
] |
How do I Login to A site using Python for scraping purposes | 38,583,357 | <p>I'm relatively new to python and programming generally. I've tried to follow steps provided from similar questions here but My program is unable to successfully Log in. The latest code I got from <a href="http://stackoverflow.com/questions/23102833/how-to-scrape-a-website-which-requires-login-using-python-and-beauti... | 2 | 2016-07-26T07:14:54Z | 38,585,838 | <p>You just need to post to the correct url, once successfully logged in you will be able to get whatever page you like, this is a working example using <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a>:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
post = "http://www.bb... | 0 | 2016-07-26T09:19:42Z | [
"python",
"beautifulsoup"
] |
Timer without threading in python? | 38,583,559 | <p>I am new to programming and would like to add a counter that deducts 1 from your score every two seconds. (so that I have to answer quickly to make my score increase)</p>
<pre><code>chr
import random
import time
radians2 = None
ans = None
score = 0
radians1 = ['0', 'Ï/6', 'Ï/3', 'Ï/4', 'Ï/2', '2Ï/3', '3Ï/4',... | 3 | 2016-07-26T07:25:12Z | 38,583,933 | <p>You can start new thread , by using following code and write whatever your functional logic in it's run() method.</p>
<pre><code>import threading
import time
class RepeatEvery(threading.Thread):
def __init__(self, interval):
threading.Thread.__init__(self)
self.interval = interval # seco... | 1 | 2016-07-26T07:47:07Z | [
"python",
"multithreading"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.