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 |
|---|---|---|---|---|---|---|---|---|---|
Extract first number in a sequence of identical numbers in a pandas groupby | 39,086,281 | <p>I would like to group a dataframe by a column 'type', and get the first number from each sequence of identical numbers. The following example illustrates:</p>
<pre><code>A = pd.DataFrame({'type':['A','A','A','A','A','A','A','A','A','B','B','B','B','B'], 'value':[1,1,1,1,8,8,8,1,1,2,2,3,3,2]})
</code></pre>
<p>For ... | 3 | 2016-08-22T18:24:04Z | 39,087,192 | <pre><code>def first_contiguous(s):
return s.groupby(s.ne(s.shift()).cumsum()).head(1)
A.groupby('type').value.apply(first_contiguous).reset_index('type')
</code></pre>
<p><a href="http://i.stack.imgur.com/6SU68.png" rel="nofollow"><img src="http://i.stack.imgur.com/6SU68.png" alt="enter image description here"><... | 2 | 2016-08-22T19:19:58Z | [
"python",
"pandas"
] |
Spotipy: How to read more than 100 tracks from a playlist | 39,086,287 | <p>I'm trying to pull all tracks in a certain playlist using the <a href="https://spotipy.readthedocs.io/en/latest/#more-examples" rel="nofollow">Spotipy library</a> for python. </p>
<p>The user_playlist_tracks function is limited to 100 tracks, regardless of the parameter limit. The Spotipy documentation describes it... | 0 | 2016-08-22T18:24:26Z | 39,087,769 | <p>Below is the <code>user_playlist_tracks</code> module used in spotipy. (notice it defaults to 100 limit). </p>
<p>Try setting the limit to 200. </p>
<pre><code>def user_playlist_tracks(self, user, playlist_id = None, fields=None,
limit=100, offset=0):
''' Get full details of the tracks of a playlist o... | 0 | 2016-08-22T20:00:38Z | [
"python",
"spotipy"
] |
Spotipy: How to read more than 100 tracks from a playlist | 39,086,287 | <p>I'm trying to pull all tracks in a certain playlist using the <a href="https://spotipy.readthedocs.io/en/latest/#more-examples" rel="nofollow">Spotipy library</a> for python. </p>
<p>The user_playlist_tracks function is limited to 100 tracks, regardless of the parameter limit. The Spotipy documentation describes it... | 0 | 2016-08-22T18:24:26Z | 39,113,522 | <p>Many of the spotipy methods return paginated results, so you will have to scroll through them to view more than just the max limit. I've encountered this most often when collecting a playlist's full track listing and consequently created a custom method to handle this:</p>
<pre><code>def get_playlist_tracks(usernam... | 0 | 2016-08-24T02:33:30Z | [
"python",
"spotipy"
] |
How to count number of occurences of permutation (overlapping) in large text in python3? | 39,086,310 | <p>I am having a list of words and I'd like to find out how many time each permutation occurs in this list of word.
And I'd like to count overlapping permutation also. So count() doesn't seem to be appropriate.
for example: the permutation aba appears twice in this string:</p>
<p>ababa</p>
<p>However count() would sa... | 1 | 2016-08-22T18:25:42Z | 39,086,441 | <p>You can use <code>re</code> module to count overlapping match.</p>
<pre><code>import re
print len(re.findall(r'(?=(aba))','ababa'))
</code></pre>
<p>Output:</p>
<pre><code>2
</code></pre>
<p>More generally,</p>
<pre><code>print len(re.findall(r'(?=(<pattern>))','<input_string>'))
</code></pre>
| 0 | 2016-08-22T18:33:32Z | [
"python",
"arrays",
"string",
"algorithm",
"count"
] |
How to count number of occurences of permutation (overlapping) in large text in python3? | 39,086,310 | <p>I am having a list of words and I'd like to find out how many time each permutation occurs in this list of word.
And I'd like to count overlapping permutation also. So count() doesn't seem to be appropriate.
for example: the permutation aba appears twice in this string:</p>
<p>ababa</p>
<p>However count() would sa... | 1 | 2016-08-22T18:25:42Z | 39,087,419 | <p>Very simple: count only what you need to count.</p>
<pre><code>from collections import defaultdict
quadrigrams = defaultdict(lambda: 0)
for word in arrayofWords:
for i in range(len(word) - 3):
quadrigrams[word[i:i+4]] += 1
</code></pre>
| 2 | 2016-08-22T19:37:15Z | [
"python",
"arrays",
"string",
"algorithm",
"count"
] |
python: read beyond end of file | 39,086,368 | <p>I'm trying to read beyond the EOF in Python, but so far I'm failing (also tried to work with seek to position and read fixed size).</p>
<p>I've found a workaround which only works on Linux (and is quite slow, too) by working with debugfs and subprocess, but this is to slow and does not work on windows.</p>
<p>My Q... | 0 | 2016-08-22T18:29:11Z | 39,086,415 | <p>You can't read more bytes than is in the file. "End of file" literally means exactly that. </p>
| 4 | 2016-08-22T18:32:23Z | [
"python"
] |
python: read beyond end of file | 39,086,368 | <p>I'm trying to read beyond the EOF in Python, but so far I'm failing (also tried to work with seek to position and read fixed size).</p>
<p>I've found a workaround which only works on Linux (and is quite slow, too) by working with debugfs and subprocess, but this is to slow and does not work on windows.</p>
<p>My Q... | 0 | 2016-08-22T18:29:11Z | 39,086,475 | <p>You can only move to the end using:</p>
<pre><code>file.seek(0, 2)
</code></pre>
<p>Is that you're trying to do?</p>
| 0 | 2016-08-22T18:35:48Z | [
"python"
] |
Running Python scripts on Amazon Web Services? Do I need to use Boto? | 39,086,388 | <p>Maybe this is a silly question, I just set up free Amazon Linux instance according to the tutorial, what I want to do is simply running python scripts.</p>
<p>Then I googled AWS and Python, Amazon mentioned Boto.</p>
<p>I don't know why using Boto. Because if I type python, it already installed.</p>
<p>What I wan... | 1 | 2016-08-22T18:30:28Z | 39,086,443 | <p>Boto is a python interface to Amazon Services (like copying to S3, etc).</p>
<p>You don't need it to just run regular python as you would on any linux instance with python installed, except to access AWS services from your EC2 instance.</p>
| 3 | 2016-08-22T18:33:44Z | [
"python",
"amazon-web-services"
] |
Running Python scripts on Amazon Web Services? Do I need to use Boto? | 39,086,388 | <p>Maybe this is a silly question, I just set up free Amazon Linux instance according to the tutorial, what I want to do is simply running python scripts.</p>
<p>Then I googled AWS and Python, Amazon mentioned Boto.</p>
<p>I don't know why using Boto. Because if I type python, it already installed.</p>
<p>What I wan... | 1 | 2016-08-22T18:30:28Z | 39,086,478 | <p>Boto is a <strong>Python wrappe</strong>r for <strong>AWS APIs</strong>. If you want to interact with AWS using its published APIs, you need boto/boto3 library installed. Boto will not be supported for long. So if you are starting to use Boto, use <strong>Boto3</strong> which is much simpler than Boto.</p>
<p>Boto3... | 2 | 2016-08-22T18:36:09Z | [
"python",
"amazon-web-services"
] |
Using requests package to make request | 39,086,420 | <p>I have an application (spark based service), which when starts..works like following.</p>
<p>At <code>localhost:9000</code></p>
<p>if I do <code>nc -lk localhost 9000</code>
and then start entering the text.. it takes the text entered in terminal as an input and do a simple wordcount computation on it.
how do i u... | 0 | 2016-08-22T18:32:39Z | 39,086,692 | <p>requests is a HTTP request library, while Spark's wordcount example provides a raw socket server, so no, requests is not the right package to communicate with your Spark app.</p>
| 1 | 2016-08-22T18:48:01Z | [
"python",
"python-requests"
] |
django testing without email backend | 39,086,434 | <p>I want to test a view in my Django application. So I open the python shell by typing <code>pyton</code> and then I type <code>from django.test.utils import setup_test_environment</code>. It seems to work fine. Then I type <code>setup_test_environment()</code> and it says </p>
<blockquote>
<p>django.core.exception... | 0 | 2016-08-22T18:33:08Z | 39,087,027 | <p>You don't need to define the <code>EMAIL_BACKEND</code> setting (it has a default), but you do need to define a setting module. You can set the <code>DJANGO_SETTINGS_MODULE</code> in your shell environment, or set <code>os.environ['DJANGO_SETTINGS_MODULE']</code> to point to your settings module.</p>
<p>Note that c... | 0 | 2016-08-22T19:08:42Z | [
"python",
"django",
"email",
"testing"
] |
Extracting infromation from multiple JSON files to single CSV file in python | 39,086,440 | <p>I have a JSON file with multiple dictionaries:</p>
<pre><code>{"team1participants":
[ {
"stats": {
"item1": 3153,
"totalScore": 0,
...
}
},
{
"stats": {
"item1": 2123,
"totalScore": 5,
...
}
},
{... | 2 | 2016-08-22T18:33:30Z | 39,086,846 | <p>You can make your data tidy so that each row is a unique observation.</p>
<pre><code>teams = []
items = []
scores = []
for team in d:
for item in d[team]:
teams.append(team)
items.append(item['stats']['item1'])
scores.append(item['stats']['totalScore'])
# Using Pandas.
import pandas as... | 2 | 2016-08-22T18:57:31Z | [
"python",
"json",
"python-2.7",
"csv",
"pandas"
] |
NoReverseMatch at / Python Django | 39,086,484 | <p>I'm taking a Django course, and I'm having the next error:</p>
<blockquote>
<p>Reverse for 'products.views.product_detail' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []</p>
</blockquote>
<p>I'm trying to send an argument to a view from a file that is called index.html</p>
<p... | 3 | 2016-08-22T18:36:28Z | 39,086,891 | <p>From <a href="https://docs.djangoproject.com/en/1.10/releases/1.10/#features-removed-in-1-10">"Features to be removed in 1.10"</a>:</p>
<blockquote>
<ul>
<li>The ability to reverse() URLs using a dotted Python path is removed.</li>
</ul>
</blockquote>
<p>The <code>{% url %}</code> tag uses <code>reverse()</c... | 5 | 2016-08-22T19:00:25Z | [
"python",
"django"
] |
Making a nested dictionary with lists and arrays | 39,086,485 | <p>I have two lists and an array:</p>
<pre><code>owners = [ 'Bill', 'Ann', 'Sarah']
dog = ['shepherd', 'collie', 'poodle', 'terrier']
totals = [[5, 15, 3, 20],[3,2,16,16],[20,35,1,2]]
</code></pre>
<p>I want to make a nested dictionary out of these.</p>
<pre><code> dict1 = {'Bill': {'shepherd': 5, 'collie': 15, '... | 0 | 2016-08-22T18:36:31Z | 39,086,604 | <pre><code>main_dict = {}
for owner, total in zip(owners, totals):
main_dict[owner] = {}
for key, value in zip(dog, total):
main_dict[owner][key] = value
</code></pre>
<p>You may also write it in one line using <code>dict comprehension</code> as:</p>
<pre><code>main_dict = {owner: dict(zip(dog, total)... | 5 | 2016-08-22T18:43:39Z | [
"python",
"arrays",
"list",
"dictionary"
] |
Using xlwt, create a new sheet anytime xls row limit is reached | 39,086,502 | <p>I'm currently writing a python script that will take an arbitrary number of csv files and create .xls files from them. Unfortunately, some of these csv files have row counts greater than 65536, which means that they can't exist on one .xls sheet. What I would like to do is come up with a way to generate a new shee... | 1 | 2016-08-22T18:37:17Z | 39,087,611 | <p>xlwt is </p>
<blockquote>
<p>a library for developers to use to generate spreadsheet files
compatible with Microsoft Excel versions 95 to 2003.
(see <a href="https://pypi.python.org/pypi/xlwt" rel="nofollow">here</a>)</p>
</blockquote>
<p>In those excel versions the maximal number of rows is limited by 65536... | 1 | 2016-08-22T19:50:10Z | [
"python",
"xlwt"
] |
Using xlwt, create a new sheet anytime xls row limit is reached | 39,086,502 | <p>I'm currently writing a python script that will take an arbitrary number of csv files and create .xls files from them. Unfortunately, some of these csv files have row counts greater than 65536, which means that they can't exist on one .xls sheet. What I would like to do is come up with a way to generate a new shee... | 1 | 2016-08-22T18:37:17Z | 39,125,194 | <p>The problem with your solution is that you are trying to reset <code>rowi</code> (which comes from your <code>enumerate()</code> statement) back to 1, but it is reset on the next loop.</p>
<p>The easiest way to achieve what you want, I think, is to change the way you reference rows and sheets. You can use the <a hr... | 1 | 2016-08-24T13:50:44Z | [
"python",
"xlwt"
] |
Dict in loop for pd.DataFrame | 39,086,512 | <p>I have many columns in my dataset & i need to change values in some of the variables. I do as below </p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'one':['a' , 'b']*5, 'two':['c' , 'd']*5, 'three':['a' , 'd']*5})
</code></pre>
<p>select</p>
<pre><code>df1 = df[['one', 'two']]
</code... | 3 | 2016-08-22T18:37:45Z | 39,086,953 | <p>You can use <code>Series.map()</code> iterating over columns:</p>
<pre><code>cols = ['one', 'two']
mapd = { 'a' : 'd', 'b' : 'c', 'c' : 'b', 'd' : 'a'}
for col in cols:
df[col] = df[col].map(mapd).fillna(df[col])
df
Out:
one three two
0 d a b
1 c d a
2 d a b
3 c d a
4 d ... | 2 | 2016-08-22T19:03:49Z | [
"python",
"pandas",
"for-loop",
"dictionary"
] |
Dict in loop for pd.DataFrame | 39,086,512 | <p>I have many columns in my dataset & i need to change values in some of the variables. I do as below </p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'one':['a' , 'b']*5, 'two':['c' , 'd']*5, 'three':['a' , 'd']*5})
</code></pre>
<p>select</p>
<pre><code>df1 = df[['one', 'two']]
</code... | 3 | 2016-08-22T18:37:45Z | 39,087,664 | <p>Passing whole map for col with only 'a','b' values is not efficient. At first check what values are in df col. Then map only for them, as here:</p>
<pre><code>>>> cols = ['one', 'two'];
>>> map = { 'a' : 'd', 'b' : 'c', 'c' : 'b', 'd' : 'a'};
>>> for col in cols:
... colSet = set(df[col... | 2 | 2016-08-22T19:53:49Z | [
"python",
"pandas",
"for-loop",
"dictionary"
] |
Dict in loop for pd.DataFrame | 39,086,512 | <p>I have many columns in my dataset & i need to change values in some of the variables. I do as below </p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'one':['a' , 'b']*5, 'two':['c' , 'd']*5, 'three':['a' , 'd']*5})
</code></pre>
<p>select</p>
<pre><code>df1 = df[['one', 'two']]
</code... | 3 | 2016-08-22T18:37:45Z | 39,087,782 | <pre><code>df = pd.DataFrame({'one':['a' , 'b']*5, 'two':['c' , 'd']*5, 'three':['a' , 'd']*5})
m = { 'a' : 'd', 'b' : 'c', 'c' : 'b', 'd' : 'a'}
cols = ['one', 'two']
df[cols] = df[cols].stack().map(m).unstack()
df
</code></pre>
<p><a href="http://i.stack.imgur.com/FacmA.png" rel="nofollow"><img src="http://i.stack.... | 2 | 2016-08-22T20:01:29Z | [
"python",
"pandas",
"for-loop",
"dictionary"
] |
MySQL ProgrammingError 1064 with SELECT statement | 39,086,676 | <pre><code>table = "tbl_" + platform + "_chks"
search = "%" + search + "%"
cur.execute('''SELECT check_id,check_name,%s, FROM %s WHERE %s LIKE %s;''', (field,table,field,search))
</code></pre>
<p>I'm getting the following error:</p>
<blockquote>
<p>ProgrammingError: (1064, "You have an error in your SQL syntax; ch... | 1 | 2016-08-22T18:47:25Z | 39,086,797 | <p>Try this:</p>
<pre><code>cur.execute("""SELECT check_id,check_name,{}
FROM tbl_{}_chks
WHERE {} LIKE '%%{}%%'
""".format(field,platform,field,search))
</code></pre>
<p>The reason this driver developers separate arguments from query is security. So you should take care... | 0 | 2016-08-22T18:54:25Z | [
"python",
"mysql"
] |
MySQL ProgrammingError 1064 with SELECT statement | 39,086,676 | <pre><code>table = "tbl_" + platform + "_chks"
search = "%" + search + "%"
cur.execute('''SELECT check_id,check_name,%s, FROM %s WHERE %s LIKE %s;''', (field,table,field,search))
</code></pre>
<p>I'm getting the following error:</p>
<blockquote>
<p>ProgrammingError: (1064, "You have an error in your SQL syntax; ch... | 1 | 2016-08-22T18:47:25Z | 39,095,634 | <p><code>%s</code> query parameter placeholders can only be used for that, query parameters, not for identifiers like table or column names. When query parameters are used, strings are automatically quoted and escaped before inserted in a query, but quoting for table and column names is different.</p>
<p>MySQL uses si... | 0 | 2016-08-23T08:05:53Z | [
"python",
"mysql"
] |
Performing arithmetic on pandas columns based on a different column's value being referenced against a dictionary | 39,086,698 | <p>I have a df</p>
<pre><code> product currency price
a USD 2
b AUD 3
c GBP 9
....
</code></pre>
<p>and I have a dict:</p>
<pre><code>cc={"USD": 1, "AUD":.75, "GBP: 1.13}
</code></pre>
<p>I want to change the price by multiplying the price times the value corr... | 1 | 2016-08-22T18:48:16Z | 39,086,770 | <p>You can use map (make sure all values in that Series are also in the dict):</p>
<pre><code>df['currency'].map(cc) * df['price']
Out:
0 2.00
1 2.25
2 10.17
dtype: float64
</code></pre>
<p>If you want to change the price column, assign it back:</p>
<pre><code>df['price'] = df['currency'].map(cc) * df['p... | 2 | 2016-08-22T18:52:22Z | [
"python",
"pandas"
] |
Performing arithmetic on pandas columns based on a different column's value being referenced against a dictionary | 39,086,698 | <p>I have a df</p>
<pre><code> product currency price
a USD 2
b AUD 3
c GBP 9
....
</code></pre>
<p>and I have a dict:</p>
<pre><code>cc={"USD": 1, "AUD":.75, "GBP: 1.13}
</code></pre>
<p>I want to change the price by multiplying the price times the value corr... | 1 | 2016-08-22T18:48:16Z | 39,087,629 | <pre><code>df = pd.DataFrame([['a', 'USD', 2L],
['b', 'AUD', 3L],
['c', 'GBP', 9L]],
columns=['product', 'currency', 'price'])
cc = pd.Series({"USD": 1, "AUD":.75, "GBP": 1.13})
df.price *= cc.ix[df.currency].values
df
</code></pre>
<p><a href="http://i.stack.... | 1 | 2016-08-22T19:51:30Z | [
"python",
"pandas"
] |
Python bs4 module | 39,086,728 | <pre><code>import requests
from bs4 import BeautifulSoup
'''
It's a web crawler working in ebay, collecting every single item data
'''
def ebay_spider(max_pages):
page = 1
while page <= max_pages:
url = 'http://www.ebay.co.uk/sch/Apple-Laptops/111422/i.html?_pgn=' \
+ str(page)
... | -2 | 2016-08-22T18:49:47Z | 39,086,831 | <p>This is entirely unrelated to the requests module. AS Jean-Francois stated, do what it tells you and move along.</p>
<p><code>soup = BeautifulSoup(plain_text,"html.parser",markup_type=markup_tyââpe)</code></p>
| 0 | 2016-08-22T18:56:35Z | [
"python",
"module",
"bs4",
"user-warning"
] |
Python bs4 module | 39,086,728 | <pre><code>import requests
from bs4 import BeautifulSoup
'''
It's a web crawler working in ebay, collecting every single item data
'''
def ebay_spider(max_pages):
page = 1
while page <= max_pages:
url = 'http://www.ebay.co.uk/sch/Apple-Laptops/111422/i.html?_pgn=' \
+ str(page)
... | -2 | 2016-08-22T18:49:47Z | 39,086,850 | <p>When you're trying to make a BeatifulSoup object in line, do instead this:</p>
<pre><code>soup = BeautifulSoup(plain_text)
</code></pre>
<p>This:</p>
<pre><code>soup = BeautifulSoup(plain_text, 'html.parser')
</code></pre>
<p>Note: your problem refers to bs4 module, not requests.</p>
| 1 | 2016-08-22T18:57:50Z | [
"python",
"module",
"bs4",
"user-warning"
] |
Get DLL to communicate with dependencies | 39,086,807 | <p>I am trying to load a DLL from Python, but get <code>WindowsError: [Error 126] The specified module could not be found.</code></p>
<pre><code>import ctypes
my_dll = "C:/smt/toolbox/dlls/NMSim_Libraries.dll"
nmsim = ctypes.cdll.LoadLibrary(my_dll)
</code></pre>
<p>When I used <a href="http://www.dependencywalker.co... | 2 | 2016-08-22T18:55:10Z | 39,087,537 | <p>The problem was solved by re-installing Anaconda <a href="https://www.continuum.io/downloads" rel="nofollow">https://www.continuum.io/downloads</a>.</p>
<p>I still have no idea what the specific problem was.</p>
| 0 | 2016-08-22T19:45:41Z | [
"python",
"dll"
] |
Get the running time of python script | 39,086,813 | <p>I wrote set of python scripts which runs as my back end. User have to upload a file using the web page that I have provided to them. I that web page there is a progress bar which shows the user how mach of processing done to there video file. Because this video file break into frames and identify objects and save in... | 0 | 2016-08-22T18:55:21Z | 39,086,931 | <p>A progress bar would require async or threading. Research these and give it a go. You can't be actively performing tasks while a progress bar is being rendered unless you are ticking the progress bar up in a loop. Which would be a better way to go about this. </p>
<p><a href="https://docs.python.org/2/library/threa... | 0 | 2016-08-22T19:02:47Z | [
"javascript",
"php",
"python",
"html",
"ajax"
] |
QDockWidget, place the tabs on top and insert text | 39,086,899 | <p>Are there any methods to make the tabs be placed on top? I think it's more suitable. And is there an easy way to name the tabs, maybe add a QLabel.</p>
<p>Below is a picture of how it looks now.</p>
<p><a href="http://i.stack.imgur.com/XNU3g.png" rel="nofollow"><img src="http://i.stack.imgur.com/XNU3g.png" alt="en... | 0 | 2016-08-22T19:00:48Z | 39,090,128 | <p>Use <a href="http://doc.qt.io/qt-4.8/qmainwindow.html#setTabPosition" rel="nofollow">setTabPosition</a> to put the tabs at the top for the relevant dock-areas:</p>
<pre><code>mainwindow.setTabPosition(QtCore.Qt.AllDockWidgetAreas, QtGui.QTabWidget.North)
</code></pre>
<p>The tab text is taken from the window title... | 1 | 2016-08-22T23:17:05Z | [
"python",
"pyqt"
] |
decorator to track number function calls - not working | 39,086,948 | <p>Why does the <code>count_calls_bad</code> version not retain the added function attribute (decorator adds <code>.calls</code> to the passed in func) after it returns? I understand the second (good) version is binding inside of the inner function versus the bad version which tries to create a closure where the func a... | 1 | 2016-08-22T19:03:33Z | 39,087,069 | <p>You never defined <code>recur_n</code>, at least not in the posted code. You applied the decorator to <code>recur_10</code>.</p>
| 1 | 2016-08-22T19:11:24Z | [
"python",
"debugging",
"decorator"
] |
decorator to track number function calls - not working | 39,086,948 | <p>Why does the <code>count_calls_bad</code> version not retain the added function attribute (decorator adds <code>.calls</code> to the passed in func) after it returns? I understand the second (good) version is binding inside of the inner function versus the bad version which tries to create a closure where the func a... | 1 | 2016-08-22T19:03:33Z | 39,088,955 | <p>As you've discovered, the reason you can't see the count is because the <code>recur_n</code> name at the top level of your module refers to the wrapper function <code>inner</code> returned from the decorator. It doesn't refer to the original <code>recur_n</code> function (though you can get access to that function v... | 0 | 2016-08-22T21:23:14Z | [
"python",
"debugging",
"decorator"
] |
Implement hashid in django | 39,086,950 | <p>I've been trying to implement <a href="https://github.com/davidaurelio/hashids-python" rel="nofollow">hashids</a> in django models. I want to acquire hashid based on model's <code>id</code> like when model's <code>id=3</code> then hash encoding should be like this: <code>hashid.encode(id)</code>. The thing is i can ... | 2 | 2016-08-22T19:03:43Z | 39,087,005 | <p>I would only tell it to save if there is no ID yet, so it doesn't run the code every time. You can do this using a TimeStampedModel inheritance, which is actually great to use in any project.</p>
<pre><code>from hashids import Hashids
hashids = Hashids(salt='thismysalt', min_length=4)
class TimeStampedModel(mod... | 1 | 2016-08-22T19:07:04Z | [
"python",
"django",
"hashids"
] |
Efficient way to find particular rows with Blaze package? | 39,086,967 | <p>I have a data table that has ~74 million lines that I used blaze to load it.</p>
<pre><code>from blaze import CSV, data
csv = CSV('train.csv')
t = data(csv)
</code></pre>
<p>It has fields these: A, B, C, D, E, F, G</p>
<p>Since this is such a large dataframe, how can I efficiently output rows that fit specific ... | 3 | 2016-08-22T19:04:26Z | 39,087,356 | <p>Your selection criteria is quite simple:</p>
<pre><code>t[(t.A == 4) & (t.B == 8) & (t.E == 10)]
</code></pre>
<p>Using the readily available <code>iris</code> sample dataset as an example:</p>
<pre><code>from blaze import data
from blaze.utils import example
iris = data(example('iris.csv'))
iris[(iris.s... | 1 | 2016-08-22T19:31:05Z | [
"python",
"multithreading",
"pandas",
"parallel-processing",
"blaze"
] |
Alternative to this python code? | 39,087,013 | <p>I have a line of code from class that I don't understand fully and want some easier alternative to. What this does is , uses weightList, which is a list of edges that's connected to each other, and returns the edgelists with lowest corresponding value from the graph (adjacency matrix). This is for a Prim's Minimum S... | 0 | 2016-08-22T19:07:44Z | 39,087,155 | <p>Breaking it up a little bit could be enough. How about this? </p>
<pre><code>get_edge_weight = lambda e: graph[e[0]][e[1]]
sorted_weights = sorted(weightList, key=get_edge_weight)
edge = sorted_weights[0]
</code></pre>
| 3 | 2016-08-22T19:17:27Z | [
"python",
"sorting",
"minimum-spanning-tree",
"prims-algorithm"
] |
Alternative to this python code? | 39,087,013 | <p>I have a line of code from class that I don't understand fully and want some easier alternative to. What this does is , uses weightList, which is a list of edges that's connected to each other, and returns the edgelists with lowest corresponding value from the graph (adjacency matrix). This is for a Prim's Minimum S... | 0 | 2016-08-22T19:07:44Z | 39,087,219 | <p>Do exactly as you said: for all edges, find the value in the graph which is the lowest.</p>
<pre><code>i, j = current_edge = weightList[0]
current_min = graph[i][j]
for edge in weightList[1:]:
i, j = edge
if graph[i][j] < current_min:
current_min = graph[i][j]
current_edge = edge
</code... | 0 | 2016-08-22T19:22:25Z | [
"python",
"sorting",
"minimum-spanning-tree",
"prims-algorithm"
] |
Alternative to this python code? | 39,087,013 | <p>I have a line of code from class that I don't understand fully and want some easier alternative to. What this does is , uses weightList, which is a list of edges that's connected to each other, and returns the edgelists with lowest corresponding value from the graph (adjacency matrix). This is for a Prim's Minimum S... | 0 | 2016-08-22T19:07:44Z | 39,087,261 | <p>If you want the code to be a little less "compact", this should do the trick:</p>
<pre><code>shortest = weightList[0]
for edge in weightList:
if graph[edge[0]][edge[1]] < graph[shortest[0]][shortest[1]]:
shortest = edge
</code></pre>
<p>Set the shortest edge to be equal to the first edge in the wei... | 0 | 2016-08-22T19:25:08Z | [
"python",
"sorting",
"minimum-spanning-tree",
"prims-algorithm"
] |
Alternative to this python code? | 39,087,013 | <p>I have a line of code from class that I don't understand fully and want some easier alternative to. What this does is , uses weightList, which is a list of edges that's connected to each other, and returns the edgelists with lowest corresponding value from the graph (adjacency matrix). This is for a Prim's Minimum S... | 0 | 2016-08-22T19:07:44Z | 39,087,363 | <p>When trying to reduce complexity, I always look for ways to break things out into self explanatory, modular functions:</p>
<pre><code>def distance(adjacency_matrix, start_node, end_node):
return adjacency_matrix[start_node][end_node]
sorted_edges = sorted(weightList, key=lambda e: distance(graph, e[0], e[1]))
... | 0 | 2016-08-22T19:32:09Z | [
"python",
"sorting",
"minimum-spanning-tree",
"prims-algorithm"
] |
Trying to calculate multiple line intersections using lists of tuples python | 39,087,113 | <p><strong>EDIT: Git Repo for sample files</strong> <a href="https://github.com/tpubben/lineIntersect" rel="nofollow">https://github.com/tpubben/lineIntersect</a></p>
<p>I am trying to calculate the line intersection points in x,y coordinates based on a set of intersecting lines crossing one continuous line made up of... | 0 | 2016-08-22T19:14:26Z | 39,088,007 | <p>Your code looks like it's dealing with a specific set of data (i.e. I have no idea what the "startsWith('N')" and the like are referring to) so I can only answer this question in the abstract.</p>
<p>Try splitting the code into multiple functions that do one specific task, rather than one big function that tries to... | -1 | 2016-08-22T20:16:41Z | [
"python",
"line-intersection"
] |
build a DataFrame with columns from tuple of arrays | 39,087,136 | <p>I am struggling with the basic task of constructing a DataFrame of counts by value from a tuple produced by <code>np.unique(arr, return_counts=True)</code>, such as:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(123)
birds=np.random.choice(['African Swallow','Dead Parrot','Exploding Pengui... | 7 | 2016-08-22T19:16:09Z | 39,087,184 | <p>You could use Counter.</p>
<pre><code>from collections import Counter
c = Counter(birds)
>>> pd.Series(c)
African Swallow 16510
Dead Parrot 16570
Exploding Penguin 16920
dtype: int64
</code></pre>
<p>You could also use <code>value_counts</code> on the series.</p>
<pre><code>>>>... | 2 | 2016-08-22T19:19:28Z | [
"python",
"pandas",
"numpy"
] |
build a DataFrame with columns from tuple of arrays | 39,087,136 | <p>I am struggling with the basic task of constructing a DataFrame of counts by value from a tuple produced by <code>np.unique(arr, return_counts=True)</code>, such as:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(123)
birds=np.random.choice(['African Swallow','Dead Parrot','Exploding Pengui... | 7 | 2016-08-22T19:16:09Z | 39,087,200 | <p>Using your tuple, you can do the following:</p>
<pre><code>In [4]: pd.DataFrame(list(zip(*someTuple)), columns = ['Bird', 'BirdCount'])
Out[4]:
Bird BirdCount
0 African Swallow 16510
1 Dead Parrot 16570
2 Exploding Penguin 16920
</code></pre>
| 3 | 2016-08-22T19:20:42Z | [
"python",
"pandas",
"numpy"
] |
build a DataFrame with columns from tuple of arrays | 39,087,136 | <p>I am struggling with the basic task of constructing a DataFrame of counts by value from a tuple produced by <code>np.unique(arr, return_counts=True)</code>, such as:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(123)
birds=np.random.choice(['African Swallow','Dead Parrot','Exploding Pengui... | 7 | 2016-08-22T19:16:09Z | 39,087,209 | <p>Here's one NumPy based solution with <a href="http://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.column_stack.html" rel="nofollow"><code>np.column_stack</code></a> -</p>
<pre><code>pd.DataFrame(np.column_stack(someTuple),columns=['birdType','birdCount'])
</code></pre>
<p>Or with <a href="http://docs.... | 3 | 2016-08-22T19:21:35Z | [
"python",
"pandas",
"numpy"
] |
build a DataFrame with columns from tuple of arrays | 39,087,136 | <p>I am struggling with the basic task of constructing a DataFrame of counts by value from a tuple produced by <code>np.unique(arr, return_counts=True)</code>, such as:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(123)
birds=np.random.choice(['African Swallow','Dead Parrot','Exploding Pengui... | 7 | 2016-08-22T19:16:09Z | 39,087,321 | <p>create a dictionary</p>
<pre><code>pd.DataFrame(dict(birdType=someTuple[0], birdCount=someTuple[1]))
</code></pre>
<p><a href="http://i.stack.imgur.com/VQ1E1.png"><img src="http://i.stack.imgur.com/VQ1E1.png" alt="enter image description here"></a></p>
| 5 | 2016-08-22T19:28:47Z | [
"python",
"pandas",
"numpy"
] |
Tkinter, Label/Text in canvas.rectangle [python] | 39,087,139 | <p>I need to place a text/label centred in a canvas rectangle in tkinter.</p>
<p>First I have a canvas covering the whole screen(800, 600).
And then I have a couple of rectangles which I made using the:</p>
<pre><code>create_rectangle(...)
</code></pre>
<p>The first X of the first rectangle is 275 and the second X i... | 0 | 2016-08-22T19:16:17Z | 39,087,525 | <p>You should use <a href="http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_text-method" rel="nofollow">create_text</a>. As it says in the link in the description of the position parameter:</p>
<blockquote>
<p>By default, the text
is centered on this position. You can override this with the anchor
... | 3 | 2016-08-22T19:44:58Z | [
"python",
"tkinter",
"tkinter-canvas"
] |
python polynomial curve fit - coefficients not right | 39,087,204 | <p>I have the following x, y data (in green). I would like to obtain a polynomial function that fits my curve. The curve that is fitted within python looks ok (in blue).
When I use the coefficients of the polynomial and I build the function by myself the results are not on the blue curve. For small values of X, this... | 0 | 2016-08-22T19:21:09Z | 39,088,235 | <p>In my opinion, the way you are using the <code>poyval</code> doesn't look right to me. Try to generate you X axis with <code>numpy.linspace</code> and then apply the <code>polyval</code> on it.
Something like the code below.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('fig3... | 0 | 2016-08-22T20:31:44Z | [
"python",
"curve-fitting"
] |
python polynomial curve fit - coefficients not right | 39,087,204 | <p>I have the following x, y data (in green). I would like to obtain a polynomial function that fits my curve. The curve that is fitted within python looks ok (in blue).
When I use the coefficients of the polynomial and I build the function by myself the results are not on the blue curve. For small values of X, this... | 0 | 2016-08-22T19:21:09Z | 39,088,763 | <p>Your algorithm seems to be working fine. You should just instead of:</p>
<pre><code>coefs = poly.polyfit(x, y, 10)
ffit = poly.polyval(x, coefs)
</code></pre>
<p>This:</p>
<pre><code>coefs = poly.polyfit(x, y, 10) # fit data to the polynomial
new_x = np.linspace(0, 30, 50) # new x values to evaluate
ffit = poly.p... | 0 | 2016-08-22T21:07:34Z | [
"python",
"curve-fitting"
] |
python polynomial curve fit - coefficients not right | 39,087,204 | <p>I have the following x, y data (in green). I would like to obtain a polynomial function that fits my curve. The curve that is fitted within python looks ok (in blue).
When I use the coefficients of the polynomial and I build the function by myself the results are not on the blue curve. For small values of X, this... | 0 | 2016-08-22T19:21:09Z | 39,213,466 | <p>Thank you very much for answering my question.</p>
<p>Both the solution provided by silgon and RicLeal work.</p>
<p>At the end, since I had several curves I have applied the solution given by RicLeal.</p>
<p>My data were log on the x-axis. I just modified the code given by RicLeal, and I am happy with the outcome... | 0 | 2016-08-29T19:08:59Z | [
"python",
"curve-fitting"
] |
How to convert a string into an integer in python 3 | 39,087,245 | <p>How can I convert this list into a list that does not have '-' in it and they are all integers?</p>
<pre><code>List1 = ['978-0262133838','978-0262201-629','978-0321758927']
</code></pre>
<p>So the list will be something like</p>
<pre><code>List1 = [9780262133838, 9780262201629, 9780321758927]
</code></pre>
| -1 | 2016-08-22T19:23:42Z | 39,089,076 | <p>Use a simple list comprehension with <code>.replace('-', '')</code>:</p>
<pre><code>List1 = ['978-0262133838','978-0262201-629','978-0321758927']
print([x.replace('-','') for x in List1])
# => ['9780262133838', '9780262201629', '9780321758927']
</code></pre>
<p>See the <a href="http://ideone.com/rMk8GF" rel="n... | 0 | 2016-08-22T21:33:37Z | [
"python",
"string",
"python-3.5"
] |
How to convert a string into an integer in python 3 | 39,087,245 | <p>How can I convert this list into a list that does not have '-' in it and they are all integers?</p>
<pre><code>List1 = ['978-0262133838','978-0262201-629','978-0321758927']
</code></pre>
<p>So the list will be something like</p>
<pre><code>List1 = [9780262133838, 9780262201629, 9780321758927]
</code></pre>
| -1 | 2016-08-22T19:23:42Z | 39,089,276 | <p>Most Pythonic way to achieve this is by using <code>map</code> with <code>lambda</code> function (to replace '-' with '' and then converting it into <code>int</code>):</p>
<pre><code>>>> my_list = ['978-0262133838','978-0262201-629','978-0321758927']
>>> map(lambda x: int(x.replace('-', '')), my_l... | 0 | 2016-08-22T21:51:03Z | [
"python",
"string",
"python-3.5"
] |
How to convert a string into an integer in python 3 | 39,087,245 | <p>How can I convert this list into a list that does not have '-' in it and they are all integers?</p>
<pre><code>List1 = ['978-0262133838','978-0262201-629','978-0321758927']
</code></pre>
<p>So the list will be something like</p>
<pre><code>List1 = [9780262133838, 9780262201629, 9780321758927]
</code></pre>
| -1 | 2016-08-22T19:23:42Z | 39,176,291 | <p>maybe this can help. if your list is:</p>
<pre><code>List1 = ['978-0262133838','978-0262201-629','978-0321758927']
</code></pre>
<p>You can use a for loop like this one, and create a new list to keep the new numbers:</p>
<pre><code>List2=[] #it is very important to have this list outside the for loop
For number i... | 0 | 2016-08-27T00:24:18Z | [
"python",
"string",
"python-3.5"
] |
Python loop benchmark with timeit | 39,087,249 | <p>I would like to benchmark a specific code segment inside a for loop in pytohn. I am using timeit as follows:</p>
<pre><code>def createTokens():
keypath=('./pickles/key.pickle')
path="./data/"
directory = os.listdir(path)
tok={}
print('create tokens..')
t=[2**4,2**5,2**6,2**7,2**8,2**9,2**10,... | 1 | 2016-08-22T19:23:55Z | 39,087,642 | <p>Try this:</p>
<pre><code>code='etok=utils.token("%s","%s","%s")' % (filename, keypath, i)
</code></pre>
<p>This will allow you to create a code string that has the values you want. Also, by using the <code>%s</code> conversion, <code>i</code> is coerced into a <code>str</code> type for you.</p>
<p><strong>Edit:</... | 1 | 2016-08-22T19:52:09Z | [
"python",
"timeit"
] |
Python loop benchmark with timeit | 39,087,249 | <p>I would like to benchmark a specific code segment inside a for loop in pytohn. I am using timeit as follows:</p>
<pre><code>def createTokens():
keypath=('./pickles/key.pickle')
path="./data/"
directory = os.listdir(path)
tok={}
print('create tokens..')
t=[2**4,2**5,2**6,2**7,2**8,2**9,2**10,... | 1 | 2016-08-22T19:23:55Z | 39,087,657 | <p><code>filename</code> isn't defined in the scope of the code in the <code>timeit</code> block. I don't know what <code>utils</code> is in your code, but assuming it expects <code>filename</code> and <code>keypath</code> as strings just replace your</p>
<pre><code> code='etok=utils.token(filename,keypath,str(i))'... | 1 | 2016-08-22T19:53:12Z | [
"python",
"timeit"
] |
App in Docker does not update | 39,087,257 | <p>I am trying to run a simple Flask application inside docker. But it seems like even when I update my app.py code and restart the docker container nothing updates.</p>
<p>I am running docker on OS X. IS this something simple I am missing or this is an expected behavior?</p>
<p>This is what my docerfile looks like:<... | 0 | 2016-08-22T19:24:46Z | 39,087,697 | <p>Docker <em>images</em> (what you get after <code>docker build -t app .</code>) is a "frozen" snapshot. Its not editable; its a snapshot of whatever you add to the image at that point in time.</p>
<p>Now, once you run an image, the contents are expanded (think of it like the archive is unzipped) and then the process... | 3 | 2016-08-22T19:56:32Z | [
"python",
"docker"
] |
AttributeError: 'module' object has no attribute 'Fib' | 39,087,287 | <p>I have just started programming in python and have the following problem: I have written an simple function abc.py: </p>
<pre><code>def Fib(n):
if n<2:
return n
else:
return Fib(n-1) + Fib(n-2)
</code></pre>
<p>which I would like to import in another python file hi.py:</p>
<pre><code>im... | -2 | 2016-08-22T19:26:29Z | 39,087,343 | <p>Oops, it's a typo!</p>
<pre><code> x=abx.Fib(4)
</code></pre>
<p>should be:</p>
<pre><code> x=abc.Fib(4)
</code></pre>
<p>The lesson here is to proofread a little more closely, and pay attention to those pesky error messages :)</p>
| -1 | 2016-08-22T19:30:09Z | [
"python"
] |
Python: Unpack a list of objects to Dictionary | 39,087,402 | <p>I have a list of objects that need to be unpacked to a dictionary efficiently. There are more than 2,000,000 objects in the list. The operation takes more than 1.5 hours complete. I would like to know if this can be done more efficiently.
The objects in the list is based on this class. </p>
<pre><code>class ResObj... | 0 | 2016-08-22T19:35:39Z | 39,087,568 | <p>Remove some indentation to make your loops non-nested:</p>
<pre><code>for obj in list_of_results:
i = obj.loc
result = obj.res
for var in no_sub_result_variables:
final_result[var][i] = result[var]
for var in sub_result_variables:
for name in sub_value_variables:
try:
... | 0 | 2016-08-22T19:47:06Z | [
"python",
"numpy",
"dictionary",
"multiprocessing"
] |
Python: Unpack a list of objects to Dictionary | 39,087,402 | <p>I have a list of objects that need to be unpacked to a dictionary efficiently. There are more than 2,000,000 objects in the list. The operation takes more than 1.5 hours complete. I would like to know if this can be done more efficiently.
The objects in the list is based on this class. </p>
<pre><code>class ResObj... | 0 | 2016-08-22T19:35:39Z | 39,088,347 | <p>Having nested numpy arrays doesn't seem the best way to structure your data. You can use numpy's <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow">structured arrays</a> to create a more intuitive data structure.</p>
<pre><code>import numpy as np
# example values
values = [
{
... | 2 | 2016-08-22T20:39:22Z | [
"python",
"numpy",
"dictionary",
"multiprocessing"
] |
Python: Unpack a list of objects to Dictionary | 39,087,402 | <p>I have a list of objects that need to be unpacked to a dictionary efficiently. There are more than 2,000,000 objects in the list. The operation takes more than 1.5 hours complete. I would like to know if this can be done more efficiently.
The objects in the list is based on this class. </p>
<pre><code>class ResObj... | 0 | 2016-08-22T19:35:39Z | 39,092,539 | <p>You you can distribute the work among processes by key names.<br>
Here I create a pool of workers and pass to them var and optional subvar names.<br>
The huge dataset is shared with workers using cheap <code>fork</code>.<br>
<code>Unpacker.unpack</code> picks the specified vars from ResObj and returns them as an np.... | 1 | 2016-08-23T04:47:40Z | [
"python",
"numpy",
"dictionary",
"multiprocessing"
] |
Apply regex to every row of a spark dataframe and save it as a new column in the same dataframe | 39,087,515 | <p>Suppose I have a spark dataframe,</p>
<p>data.show()</p>
<pre><code>ID URL
1 https://www.sitename.com/&q=To+Be+Parsed+out&oq=Dont+Need+to+be+parsed
2 https://www.sitename.com/&q=To+Be+Parsed+out&oq=Dont+Need+to+be+parsed
3 https://www.sitename.com/... | 0 | 2016-08-22T19:44:08Z | 39,097,961 | <p>As mentioned by @David in the comment, you could use <code>udf</code> and <code>withColumn</code>:</p>
<p><strong>Scala code:</strong></p>
<pre><code>import org.apache.spark.sql.functions._
val getWord: (String => String) = (url: String) => {
if (url != null) {
"""/?q=([^&]*)""".r
.findFirst... | 0 | 2016-08-23T09:56:18Z | [
"python",
"python-2.7",
"apache-spark",
"pyspark",
"pyspark-sql"
] |
Detecting when code is run on Travis CI | 39,087,544 | <p>I have a nose test that uses a pathname to a png file in the tests directory. One path works in local testing, one path works on Travis. How do I check when the code is run on Travis?</p>
<p>Edit: Here is the <a href="https://github.com/construct/construct/commit/839877318559aa2971194836105430aa54d2c43f" rel="nofol... | 2 | 2016-08-22T19:46:04Z | 39,088,539 | <p>You could check for the existence (or value) of an environment variable. It looks like Travis defines several by default (see <a href="https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables" rel="nofollow">here</a>).</p>
<p>For example:</p>
<pre><code>import os
istravis = os.environ.... | 1 | 2016-08-22T20:52:06Z | [
"python",
"continuous-integration",
"travis-ci",
"nose"
] |
Detecting when code is run on Travis CI | 39,087,544 | <p>I have a nose test that uses a pathname to a png file in the tests directory. One path works in local testing, one path works on Travis. How do I check when the code is run on Travis?</p>
<p>Edit: Here is the <a href="https://github.com/construct/construct/commit/839877318559aa2971194836105430aa54d2c43f" rel="nofol... | 2 | 2016-08-22T19:46:04Z | 39,089,212 | <p>To check the existence of TRAVIS:</p>
<pre><code>import os
is_travis = 'TRAVIS' in os.environ
</code></pre>
| 2 | 2016-08-22T21:45:32Z | [
"python",
"continuous-integration",
"travis-ci",
"nose"
] |
Shortcut to creating an adjacency matrix | 39,087,559 | <p>I need a short and sweet version of the python code I wrote. So basically what I have is a text file with values such as below:</p>
<pre><code>x
a b c
d e f
</code></pre>
<p>First line is the number of nodes. From second line, the values are read into NODE1, NODE2, Weight. I am taking these values and creating an ... | 0 | 2016-08-22T19:46:46Z | 39,087,676 | <pre><code>with open(filename, 'r') as textfile:
file_lines = text_file.readlines()
# Initialize graph with -1 value, i.e. path do not exists representing infinite
# Note: If negative weight is allowed, use the value which you want to symbolize infinte
total_node = int(file_lines[0])
my_graph = [[-... | 1 | 2016-08-22T19:54:47Z | [
"python",
"adjacency-matrix",
"minimum-spanning-tree"
] |
Shortcut to creating an adjacency matrix | 39,087,559 | <p>I need a short and sweet version of the python code I wrote. So basically what I have is a text file with values such as below:</p>
<pre><code>x
a b c
d e f
</code></pre>
<p>First line is the number of nodes. From second line, the values are read into NODE1, NODE2, Weight. I am taking these values and creating an ... | 0 | 2016-08-22T19:46:46Z | 39,087,879 | <p>I'm not sure simpler, but with numpy reshape you can create the default matrix before you populate with the weights without explicit loops. Here <code>n</code> is the size.</p>
<pre><code>In [20]: n=4; np.reshape(np.array(([0]+[float("inf")]*n)*(n-1)+[0]),[n,n])
Out[20]:
array([[ 0., inf, inf, inf],
[ i... | 0 | 2016-08-22T20:08:30Z | [
"python",
"adjacency-matrix",
"minimum-spanning-tree"
] |
How to trigger a variable/method in python from a html file with javascript | 39,087,614 | <p>I want to have a hyperlink on a html page run a variable that is defined in my python file. The variable is going to clear my database. Here is the code I am trying to use. </p>
<p><strong>Python</strong></p>
<pre><code>@app.route('/log')
def log():
cleardb = db.session.delete()
return render_template('log.html', ... | 2 | 2016-08-22T19:50:30Z | 39,103,218 | <p>You need to make an ajax request with javascript to /log, it would look something like this:</p>
<pre><code>function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
... | 1 | 2016-08-23T13:55:31Z | [
"javascript",
"python",
"html",
"flask-sqlalchemy"
] |
How to add threads depending on a number | 39,087,647 | <p>In a part of my software code written with python, I have a list of items where it size can vary greatly from 12 to only one item . For each item in this list I'm doing some processing (sending an HTTP request related to the given item, parse results and many other operations . I'd like to speed up my code using thr... | 0 | 2016-08-22T19:52:32Z | 39,087,707 | <p>You might rather implement it using shared queues
<a href="https://docs.python.org/3/library/queue.html#queue-objects" rel="nofollow">https://docs.python.org/3/library/queue.html#queue-objects</a></p>
<pre><code>import queue
import threading
def worker():
while True:
item = q.get()
if item is N... | 2 | 2016-08-22T19:57:02Z | [
"python",
"multithreading",
"python-multithreading"
] |
How to add threads depending on a number | 39,087,647 | <p>In a part of my software code written with python, I have a list of items where it size can vary greatly from 12 to only one item . For each item in this list I'm doing some processing (sending an HTTP request related to the given item, parse results and many other operations . I'd like to speed up my code using thr... | 0 | 2016-08-22T19:52:32Z | 39,088,097 | <p>You can use the <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" rel="nofollow"><code>ThreadPoolExecutor</code></a> class from the <a href="https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures" rel="nofollow"><code>concurrent.fut... | 1 | 2016-08-22T20:22:24Z | [
"python",
"multithreading",
"python-multithreading"
] |
Python Tornado don't load images from html | 39,087,666 | <p>I have a html page that when loaded from firefox it works, but when it is send from tornado server it don't show the images.
My tornado server:</p>
<pre><code>import tornado.ioloop
import tornado.web
class mainHandler(tornado.web.RequestHandler):
def get(self):
self.render('./prop.html')
application = ... | 0 | 2016-08-22T19:54:10Z | 39,087,794 | <p>Tornado doesn't treat images specially.</p>
<p><code>/fig1.jpg</code> is a resource and since you haven't defined a handler for it, Tornado will not generate a response. For production, you should be using a webserver better optimized for serving static files, like nginx. For development, however, you can tell Torn... | 0 | 2016-08-22T20:02:01Z | [
"python",
"tornado"
] |
Using Taggit with custom view Django | 39,087,671 | <p>I am currently trying to implement a tag system into my Django project. I am trying to add the tags within each post, and have a category on the right hand side that displays maybe 10-20 of the tags. I am trying to implement this into the feed view, but i am unsure of how to call the slug for each tag in order to do... | 0 | 2016-08-22T19:54:31Z | 39,108,489 | <p>Just copy and paste these.</p>
<p>Change the urls.py entry to this:</p>
<pre><code>url(r'^tag/(?P<pk>[-\w]+)/$', tag_list, name='tagged'),
</code></pre>
<p>Your post_feed function to this (views.py):</p>
<pre><code>def post_feed(request):
if not request.user.is_staff or not request.user.is_superuser:
... | 0 | 2016-08-23T18:39:22Z | [
"python",
"django",
"tags"
] |
python: how to count number in one file? | 39,087,678 | <p>I need to write a Python program to read the values in a file, one per line, such as file: test.txt</p>
<pre><code>1
2
3
4
5
6
7
8
9
10
</code></pre>
<p>Denoting these as <strong>j1, j2, j3, ... jn</strong>,
I need to sum the differences of consecutive values: </p>
<pre><code>a=(j2-j1)+(j3-j2)+...+(jn-j[n-1])
</c... | -1 | 2016-08-22T19:54:58Z | 39,087,888 | <p><strong>Solution (Python 3)</strong></p>
<pre><code>res = 0
with open("test.txt","r") as fp:
lines = list(map(int,fp.readlines()))
for i in range(1,len(lines)):
res += lines[i]-lines[i-1]
print(res)
</code></pre>
<p><strong>Output</strong>: <code>9</code></p>
<p><code>test.text</code> contains:</p... | 0 | 2016-08-22T20:09:12Z | [
"python",
"ubuntu"
] |
python: how to count number in one file? | 39,087,678 | <p>I need to write a Python program to read the values in a file, one per line, such as file: test.txt</p>
<pre><code>1
2
3
4
5
6
7
8
9
10
</code></pre>
<p>Denoting these as <strong>j1, j2, j3, ... jn</strong>,
I need to sum the differences of consecutive values: </p>
<pre><code>a=(j2-j1)+(j3-j2)+...+(jn-j[n-1])
</c... | -1 | 2016-08-22T19:54:58Z | 39,087,913 | <p>I'm not even sure if I understand the question, but here's my best attempt at solving what I think is your problem:</p>
<ol>
<li><p>To read values from a file, use "with open()" in read mode ('r'):</p>
<p><code>with open('test.txt', 'r') as f:
-your code here-</code></p></li>
<li><p>"as f" means that "f" will ... | 0 | 2016-08-22T20:10:43Z | [
"python",
"ubuntu"
] |
python: how to count number in one file? | 39,087,678 | <p>I need to write a Python program to read the values in a file, one per line, such as file: test.txt</p>
<pre><code>1
2
3
4
5
6
7
8
9
10
</code></pre>
<p>Denoting these as <strong>j1, j2, j3, ... jn</strong>,
I need to sum the differences of consecutive values: </p>
<pre><code>a=(j2-j1)+(j3-j2)+...+(jn-j[n-1])
</c... | -1 | 2016-08-22T19:54:58Z | 39,088,088 | <p>The correct answer is 9 : </p>
<pre><code>with open("data.txt") as f:
# set prev to first number in the file
prev = int(next(f))
sm = 0
# iterate over the remaining numbers
for j in f:
j = int(j)
sm += j - prev
# update prev
prev = j
print(sm)
</code></pre>
... | 0 | 2016-08-22T20:21:44Z | [
"python",
"ubuntu"
] |
python: how to count number in one file? | 39,087,678 | <p>I need to write a Python program to read the values in a file, one per line, such as file: test.txt</p>
<pre><code>1
2
3
4
5
6
7
8
9
10
</code></pre>
<p>Denoting these as <strong>j1, j2, j3, ... jn</strong>,
I need to sum the differences of consecutive values: </p>
<pre><code>a=(j2-j1)+(j3-j2)+...+(jn-j[n-1])
</c... | -1 | 2016-08-22T19:54:58Z | 39,088,108 | <p>If I understand correctly, the following equation;</p>
<pre><code>a = (j2-j1) + (j3-j2) + ... + (jn-(jn-1))
</code></pre>
<p>As you iterate over the file, it will subtract the value in the previous line from the value in the current line and then add all those differences.</p>
<pre><code>a = 0
with open("test.tx... | 0 | 2016-08-22T20:23:28Z | [
"python",
"ubuntu"
] |
How I fix "Couldn't find a distribution for 'ploneconf.site'" in Mastering Plone Training | 39,087,745 | <p>I'm learning create custom products for plone (4.3.10) using Mastering Plone, and I stop in the <a href="https://training.plone.org/4/eggs1.html#including-the-egg-in-plone" rel="nofollow">section</a> when I install the newly package created with mrbob.</p>
<p><a href="http://paster.org/m/bkfydi/" rel="nofollow">Her... | 1 | 2016-08-22T19:59:13Z | 39,123,663 | <p>I insert in [buildout] section after eggs and zcml this:</p>
<pre><code>develop =
src/ploneconf.site
</code></pre>
<p>As seen in <a href="http://docs.plone.org/4/en/old-reference-manuals/buildout/creatingpackage.html" rel="nofollow">Plone Docs</a>, the way teaching in training <a href="https://training.plone.o... | 1 | 2016-08-24T12:42:26Z | [
"python",
"plone",
"plone-4.x"
] |
How should print all the indices of a matrix which are the maximum number of that matrix? | 39,087,857 | <p>Like we can consider following matrix:
<a href="http://i.stack.imgur.com/BkWrY.jpg" rel="nofollow">enter image description here</a></p>
<p>Now I want to display all the indices of the maximum no of the matrix and not just only one indices of the max of the matrix.</p>
| -4 | 2016-08-22T20:06:32Z | 39,088,141 | <pre class="lang-python prettyprint-override"><code>import numpy as np
mat = np.array([[2,3,2], [7,7,6], [2,7,3]])
print(mat)
max_indices = np.where(mat == np.amax(mat))
print(max_indices)
index_max = mat[max_indices]
print(index_max)
</code></pre>
<p>Output:</p>
<pre><code>[[2 3 2]
[7 7 6]
[2 7 3]]
(array([1, 1... | 1 | 2016-08-22T20:25:50Z | [
"python",
"numpy",
"matrix"
] |
Canonical way to run Flask app locally | 39,087,917 | <p>The official <a href="http://flask.pocoo.org/docs/0.11/quickstart/" rel="nofollow">Flask documentation</a> uses <code>flask run</code> or <code>python -m flask run</code>, both of which require that <code>FLASK_APP</code> be set. Most other tutorials I've seen, however, simply use <code>python app.py</code>, which d... | 0 | 2016-08-22T20:11:03Z | 39,088,836 | <p>Unless you have a reason not to (and you probably don't), use <code>flask run</code> to run the development server. It is what is supported going forward. Paraphrasing from the <a href="http://flask.pocoo.org/docs/0.11/server/#in-code" rel="nofollow">docs</a>:</p>
<blockquote>
<p>from Flask 0.11 onward the <cod... | 2 | 2016-08-22T21:15:41Z | [
"python",
"flask"
] |
Xlsxwriter - Writing a string to a cell given parameters | 39,087,975 | <p>I am looking to write a string to a cell using Xlsxwriter, however, it seems that I can only write to a specific cell in the following formats:</p>
<pre><code>worksheet.write(0, 0, 'I like pie')
worksheet.write('A1', 'I like pie')
</code></pre>
<p>I am first writing a dataframe to the excel worksheet and then add... | 1 | 2016-08-22T20:14:32Z | 39,088,677 | <p>Use <code>df.shape</code> to get the number of rows for your dataframe, then use this number to specify the row for your footer:</p>
<pre><code>nrows = df.shape[0]
worksheet.write(nrows, 0, 'I like pie')
# or: worksheet.write('A{}'.format(nrows+1), 'I like pie')
</code></pre>
| 2 | 2016-08-22T21:01:02Z | [
"python",
"pandas",
"xlsxwriter"
] |
Flask application cannot find gpg | 39,088,048 | <p>I'm interfacing gpg in a flask application with python-gnupg. The module is installed in a virtualenv together with the rest of my application. When running I receive a 500 internal server error, and the exception is:</p>
<pre><code>File "./myproject/views/settings.py", line 257, in settings_keys_add
gpg = gnup... | 1 | 2016-08-22T20:18:59Z | 39,088,161 | <p>you override (not append to) the PATH variable with this line:</p>
<pre><code>Environment="PATH=/home/path"
</code></pre>
<p>change it to</p>
<pre><code>Environment="PATH=/home/path:/usr/bin:/bin"
</code></pre>
<p>to be able to use standard commands.</p>
<p>BTW check if /home/path exists, I suppose not, in that... | 1 | 2016-08-22T20:27:05Z | [
"python",
"nginx",
"flask",
"gnupg",
"ubuntu-server"
] |
get stacktrace of a python program for debugging | 39,088,101 | <p>In order to get the stacktrace of a python program, I am trying to follow <a href="http://grapsus.net/blog/post/Low-level-Python-debugging-with-GDB" rel="nofollow">this example</a>. In the article, the author invokes the gdb as follows. However, the python version of my environment is <code>python 3.4.4</code>. When... | 0 | 2016-08-22T20:22:47Z | 39,088,207 | <p>What OS are you on? It looks like you need to install python3.4-dbg. If you are on Linux, you will need to enter:</p>
<p>sudo apt-get install python3.4-dbg</p>
| 1 | 2016-08-22T20:30:00Z | [
"python",
"python-3.x",
"gdb"
] |
get stacktrace of a python program for debugging | 39,088,101 | <p>In order to get the stacktrace of a python program, I am trying to follow <a href="http://grapsus.net/blog/post/Low-level-Python-debugging-with-GDB" rel="nofollow">this example</a>. In the article, the author invokes the gdb as follows. However, the python version of my environment is <code>python 3.4.4</code>. When... | 0 | 2016-08-22T20:22:47Z | 39,088,457 | <p>GDB is excellent program for debugging, but if printing traceback is the only reason you are installing GDB, do not do it, that is waay overkill. You can just <code>import traceback</code> and </p>
<ol>
<li>use <code>traceback.format_stack()</code> to get an array of calls that lead to the location in program</li>
... | 0 | 2016-08-22T20:46:09Z | [
"python",
"python-3.x",
"gdb"
] |
Using webdriver execute-script on jquery does not work | 39,088,119 | <p>I was trying to use webdriver's execute_script() to run a jquery, but without luck. Below are the steps I performed:</p>
<ol>
<li><p>From Selenium/Webdriver, run execute_script() as below:</p>
<pre><code>jquery_string = 'return $(\'[id="ClusterMembers:ClusterMembersScreen:ttlBar"]\')'
web_element = driver.exec... | 0 | 2016-08-22T20:24:03Z | 39,110,153 | <p>Instead of using $ try using this:</p>
<pre><code>jquery_string = "jQuery('[id*=ClusterMembers][id*=ClusterMembersScreen][id*=ttlBar]');"
</code></pre>
<p>try to avoid using ':' in selectors, it might result in errors.</p>
| 0 | 2016-08-23T20:30:37Z | [
"javascript",
"jquery",
"python",
"selenium",
"webdriver"
] |
Changes in Django View Lagging | 39,088,151 | <p>I'm a fairly new to web development so this might actually be normal behavior - but when I make logic changes in my views, it can take about an hour for those changes to show up on my production site.</p>
<p>The changes are instant if I fire up the localhost. Server is Windows IIS 7.5. HTML, CSS, and JS changes sho... | 0 | 2016-08-22T20:26:27Z | 39,088,264 | <p>Have you tried doing a manual reboot of the application pool where the site is sitting in IIS? Documentation might not be exact for the version but it should explain it well enough to give you an idea about what's going:</p>
<p><a href="https://technet.microsoft.com/en-us/library/cc753179(v=ws.10).aspx" rel="nofol... | 1 | 2016-08-22T20:33:56Z | [
"python",
"django"
] |
FutureWarning when comparing a NumPy object to "None" | 39,088,173 | <p>I have a function that receives some arguments, plus some optional arguments. In it, the action taken is dependent upon whether the optional argument <code>c</code> was filled:</p>
<pre><code>def func(a, b, c = None):
doStuff()
if c != None:
doOtherStuff()
</code></pre>
<p>If <code>c</code> is no... | 5 | 2016-08-22T20:27:41Z | 39,088,194 | <p>Use <code>if c is not None</code> instead. In addition to avoiding the warning, this is <a href="https://www.python.org/dev/peps/pep-0008/#programming-recommendations">generally considered best-practice</a>.</p>
| 10 | 2016-08-22T20:29:11Z | [
"python",
"arrays",
"numpy"
] |
how to integrate pyspark on jupyter notebook | 39,088,189 | <p>i have followed instructions to integrate pyspark with jupyter but after i was done i was only able to run pyspark on the command prompt . </p>
<p>Basically when i am using ipython in my command it is working but when i change to jupyter it says </p>
<pre><code>'"Jupyter "' is not recognized as an internal or exte... | 0 | 2016-08-22T20:28:51Z | 39,088,446 | <p>Windows <code>set</code> command does not accept spaces before the <code>=</code> sign.</p>
<p>fix this like that:</p>
<pre><code>set PYSPARK_DRIVER_PYTHON=ipython
set PYSPARK_DRIVER_PYTHON_OPTS=notebook
pyspark
</code></pre>
<p>The system wants to run the <code>"Jupyter %PYSPARK_DRIVER_PYTHON_OPTS%"</code> exe... | 1 | 2016-08-22T20:45:32Z | [
"python",
"pyspark"
] |
print full item in multiple lists | 39,088,219 | <p>I'm trying to print two lists, but it only prints the first letter of each item in the lists;</p>
<pre><code>lst1 = ['hello', 'hi', 'sup']
lst2 = ['bye', 'cya', 'goodbye']
for item in [lst1, lst2]:
print 'Your options are: ' + ' '.join(['-{0}'.format(*x) for x in item])
</code></pre>
<p>Result;</p>
<pre><cod... | 0 | 2016-08-22T20:30:57Z | 39,088,280 | <p>Removing <code>*</code> from <code>format</code> will work for you:</p>
<pre><code>>>> for item in [lst1, lst2]:
... print 'Your options are: ' + ' '.join(['-{0}'.format(x) for x in item])
...
Your options are: -hello -hi -sup
Your options are: -bye -cya -goodbye
</code></pre>
<p><strong>Explaination... | 4 | 2016-08-22T20:34:44Z | [
"python",
"string",
"list"
] |
print full item in multiple lists | 39,088,219 | <p>I'm trying to print two lists, but it only prints the first letter of each item in the lists;</p>
<pre><code>lst1 = ['hello', 'hi', 'sup']
lst2 = ['bye', 'cya', 'goodbye']
for item in [lst1, lst2]:
print 'Your options are: ' + ' '.join(['-{0}'.format(*x) for x in item])
</code></pre>
<p>Result;</p>
<pre><cod... | 0 | 2016-08-22T20:30:57Z | 39,088,556 | <p>Alternative;</p>
<pre><code>>>> print '\n'.join('Your options are: -%s' % ' -'.join(x) for x in (lst1, lst2))
Your options are: -hello -hi -sup
Your options are: -bye -cya -goodbye
</code></pre>
<h3>How it works</h3>
<p>To generate a line of output:</p>
<pre><code>>>> 'Your options are: -%s' % ... | 0 | 2016-08-22T20:52:50Z | [
"python",
"string",
"list"
] |
Python with Selenium - selecting a button or text action | 39,088,244 | <p>I am, poorly, trying to 1. Click a button or 2. Check for text and then execute an action. I think I am just not coding this correctly.</p>
<p>eg</p>
<pre><code>if driver.find_element_by_class_name('classOne').click()
elif:
"No Item" in driver.find_element_by_class_name('classTwo').driver.get(self_base_url)
</... | 0 | 2016-08-22T20:32:07Z | 39,088,393 | <p>If the <code>driver</code> can't find an element, it will raise <a href="http://selenium-python.readthedocs.io/api.html#selenium.common.exceptions.NoSuchElementException" rel="nofollow"><code>NoSuchElementException</code></a>.</p>
<p>In your case, you can do:</p>
<pre><code>x = driver.find_elements_by_class_name('... | 2 | 2016-08-22T20:42:42Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Strange Logic Behavior with Variable and Number | 39,088,311 | <p>Say I define <code>a</code> and <code>b</code> as follows:</p>
<pre><code>a = 1
b = 1
</code></pre>
<p>Then I test:</p>
<pre><code>a == 1
#True
5>4
#True
a==1 & b==1
#True
5>4 & 4>3
#True
a==1 & 5>4
#False
</code></pre>
<p>What is going on with the last one? I would like to be able to... | 0 | 2016-08-22T20:37:04Z | 39,088,339 | <p>In Python <code>&</code> is for bit operations with numbers, not logic. Use <code>and</code> and <code>or</code> instead.</p>
| 6 | 2016-08-22T20:38:53Z | [
"python",
"logic",
"boolean-logic",
"inequality"
] |
Strange Logic Behavior with Variable and Number | 39,088,311 | <p>Say I define <code>a</code> and <code>b</code> as follows:</p>
<pre><code>a = 1
b = 1
</code></pre>
<p>Then I test:</p>
<pre><code>a == 1
#True
5>4
#True
a==1 & b==1
#True
5>4 & 4>3
#True
a==1 & 5>4
#False
</code></pre>
<p>What is going on with the last one? I would like to be able to... | 0 | 2016-08-22T20:37:04Z | 39,088,938 | <blockquote>
<p>Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:</p>
</blockquote>
<p>Which means:</p>
<pre><co... | -1 | 2016-08-22T21:22:12Z | [
"python",
"logic",
"boolean-logic",
"inequality"
] |
Python 3.5 regular expression matching for directories | 39,088,415 | <p>I am using the Python 3.5 <code>re</code> module with this code:</p>
<pre><code>>>> test
'\\\\192.168.1.2\\shared\\Department\\Travel\\FY 2015\\Travel Expense Statement Jul 25 2019.pdf'
</code></pre>
<p>I want to return <code>Department\Travel\FY 2015\Travel Expense Statement Jul 25 2019.pdf</code>. I hav... | 2 | 2016-08-22T20:43:45Z | 39,088,485 | <p>The problem with your <em>regular expression</em> is very simple, remove the <code>?</code> character in your second regular expression. You just need <code>.*</code> that matches zero or more characters. </p>
<p><code>*?</code> together means a lazy quantifier that matches as little as possible, so if you use <cod... | 2 | 2016-08-22T20:47:40Z | [
"python",
"regex"
] |
Python 3.5 regular expression matching for directories | 39,088,415 | <p>I am using the Python 3.5 <code>re</code> module with this code:</p>
<pre><code>>>> test
'\\\\192.168.1.2\\shared\\Department\\Travel\\FY 2015\\Travel Expense Statement Jul 25 2019.pdf'
</code></pre>
<p>I want to return <code>Department\Travel\FY 2015\Travel Expense Statement Jul 25 2019.pdf</code>. I hav... | 2 | 2016-08-22T20:43:45Z | 39,088,502 | <p>You shouldn't use regex for this. Instead, use the <a href="https://docs.python.org/3/library/os.path.html#os.path.splitdrive" rel="nofollow"><code>ntpath</code> module</a> (or <code>os.path</code> if you are sure the script will only run on Windows):</p>
<pre><code>>>> s = '\\\\192.168.1.2\\shared\\Depart... | 3 | 2016-08-22T20:48:48Z | [
"python",
"regex"
] |
tensorflow periodic padding | 39,088,489 | <p>In tensorflow I cannot find a straightforward possibility to do a convolution (<a href="https://www.tensorflow.org/versions/master/api_docs/python/nn.html#conv2d" rel="nofollow">tf.nn.conv2d</a>) with periodic boundary conditions.</p>
<p>E.g. take the tensor</p>
<pre><code>[[1,2,3],
[4,5,6],
[7,8,9]]
</code></pr... | 0 | 2016-08-22T20:47:54Z | 39,088,910 | <p>The following should work for your case :</p>
<pre><code>import tensorflow as tf
a = tf.constant([[1,2,3],[4,5,6],[7,8,9]])
b = tf.tile(a, [3, 3])
result = b[2:7, 2:7]
sess = tf.InteractiveSession()
print(result.eval())
# prints the following
array([[9, 7, 8, 9, 7],
[3, 1, 2, 3, 1],
[6, 4, 5, 6, 4],... | 2 | 2016-08-22T21:20:25Z | [
"python",
"tensorflow"
] |
repetition in regular expression in python | 39,088,522 | <p>I've got a file with lines for example:</p>
<pre><code>aaa$bb$ccc$ddd$eee
fff$ggg$hh$iii$jj
</code></pre>
<p>I need to take what is inside $$ so expected result is:</p>
<pre><code> $bb$
$ddd$
$ggg$
$iii$
</code></pre>
<p>My result:</p>
<pre><code>$bb$
$ggg$
</code></pre>
<p>My solution:</p>
<pre><code>m = ... | 2 | 2016-08-22T20:50:30Z | 39,088,553 | <p>You can use <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow"><strong><code>re.findall</code></strong></a> with <code>r'\$[^$]+\$'</code> regex: </p>
<pre><code>import re
line = """aaa$bb$ccc$ddd$eee
fff$ggg$hh$iii$jj"""
m = re.findall(r'\$[^$]+\$', line)
print(m)
# => ['$bb$', '$ddd$... | 6 | 2016-08-22T20:52:47Z | [
"python",
"regex",
"python-2.7"
] |
repetition in regular expression in python | 39,088,522 | <p>I've got a file with lines for example:</p>
<pre><code>aaa$bb$ccc$ddd$eee
fff$ggg$hh$iii$jj
</code></pre>
<p>I need to take what is inside $$ so expected result is:</p>
<pre><code> $bb$
$ddd$
$ggg$
$iii$
</code></pre>
<p>My result:</p>
<pre><code>$bb$
$ggg$
</code></pre>
<p>My solution:</p>
<pre><code>m = ... | 2 | 2016-08-22T20:50:30Z | 39,088,568 | <p><code>re.search</code> finds only the first match. Perhaps you'd want <code>re.findall</code>, which returns list of strings, or <code>re.finditer</code> that returns iterator of match objects. Additionally, you must escape <code>$</code> to <code>\$</code>, as unescaped <code>$</code> means "end of line".</p>
<hr>... | 3 | 2016-08-22T20:53:17Z | [
"python",
"regex",
"python-2.7"
] |
repetition in regular expression in python | 39,088,522 | <p>I've got a file with lines for example:</p>
<pre><code>aaa$bb$ccc$ddd$eee
fff$ggg$hh$iii$jj
</code></pre>
<p>I need to take what is inside $$ so expected result is:</p>
<pre><code> $bb$
$ddd$
$ggg$
$iii$
</code></pre>
<p>My result:</p>
<pre><code>$bb$
$ggg$
</code></pre>
<p>My solution:</p>
<pre><code>m = ... | 2 | 2016-08-22T20:50:30Z | 39,088,578 | <p>Your regex is fine. <a href="https://docs.python.org/3/library/re.html#re.search" rel="nofollow"><code>re.search</code></a> only finds the first match in a line. You are looking for <a href="https://docs.python.org/3/library/re.html#re.findall" rel="nofollow"><code>re.findall</code></a>, which finds all non-overlapp... | 1 | 2016-08-22T20:54:11Z | [
"python",
"regex",
"python-2.7"
] |
Python Subtracting Elements in a Lists from Previous Element | 39,088,546 | <p>I have a loop that produces multiple lists such as these:</p>
<pre><code> [1,6,2,8,3,4]
[8,1,2,3,7,2]
[9,2,5,6,1,4]
</code></pre>
<p><em>For each list, I want to subtract the first two elements, and then use that value to then subtract the third element from.</em> </p>
<p>For example, the first list should... | -1 | 2016-08-22T20:52:22Z | 39,088,785 | <p>From your updated example, it seems like, given a list <code>[a, b, c, d, ...]</code> you want <code>[a-b, b-c, c-d, d-e, ...]</code> as a result. For this, you should <code>zip</code> the list with itself, offset by one position, and subtract the elements in the pairs.</p>
<pre><code>lst = [1,6,2,8,3,4]
res = [x-y... | 3 | 2016-08-22T21:10:06Z | [
"python",
"list",
"loops"
] |
Python Subtracting Elements in a Lists from Previous Element | 39,088,546 | <p>I have a loop that produces multiple lists such as these:</p>
<pre><code> [1,6,2,8,3,4]
[8,1,2,3,7,2]
[9,2,5,6,1,4]
</code></pre>
<p><em>For each list, I want to subtract the first two elements, and then use that value to then subtract the third element from.</em> </p>
<p>For example, the first list should... | -1 | 2016-08-22T20:52:22Z | 39,088,859 | <p>If I understand you correctly, you want to optimize your code, so it runs faster. Reducing the lines of code wont improve this since you are looping through lists. </p>
<p>From what I can tell, your problem can't be solved in under n-1 subtractions (where n is the number of input values). However there might be a m... | -1 | 2016-08-22T21:17:02Z | [
"python",
"list",
"loops"
] |
Python Subtracting Elements in a Lists from Previous Element | 39,088,546 | <p>I have a loop that produces multiple lists such as these:</p>
<pre><code> [1,6,2,8,3,4]
[8,1,2,3,7,2]
[9,2,5,6,1,4]
</code></pre>
<p><em>For each list, I want to subtract the first two elements, and then use that value to then subtract the third element from.</em> </p>
<p>For example, the first list should... | -1 | 2016-08-22T20:52:22Z | 39,089,035 | <pre><code>>>> my_list = [1,6,2,8,3,4]
>>> [my_list[i] - my_list[i+1] for i in range(len(my_list) -1)]
[-5, 4, -6, 5, -1]
</code></pre>
| 0 | 2016-08-22T21:29:53Z | [
"python",
"list",
"loops"
] |
Reboot Raspberry Pi if service not running | 39,088,552 | <p>I am running Bitorrent Sync from my Raspberry Pi. Very occasionally it will- for some reason- go offline. I am trying to run <a href="http://weworkweplay.com/play/rebooting-the-raspberry-pi-when-it-loses-wireless-connection-wifi/" rel="nofollow">a script from crontab that will check the connection</a> but I also wan... | 1 | 2016-08-22T20:52:44Z | 39,088,852 | <p>Check if process is running, with <code>ps aux</code>. Name the below script as <strong>btsync_reboot.sh</strong> and <code>chown</code> it to user running cron.</p>
<pre><code>#!/bin/sh
echo "check service $(date)" >> /var/log/btsync-check.log
ps auxw | grep btsync | grep -v grep > /dev/null
if [ $? != 0... | 1 | 2016-08-22T21:16:34Z | [
"python",
"raspberry-pi",
"crontab"
] |
Reboot Raspberry Pi if service not running | 39,088,552 | <p>I am running Bitorrent Sync from my Raspberry Pi. Very occasionally it will- for some reason- go offline. I am trying to run <a href="http://weworkweplay.com/play/rebooting-the-raspberry-pi-when-it-loses-wireless-connection-wifi/" rel="nofollow">a script from crontab that will check the connection</a> but I also wan... | 1 | 2016-08-22T20:52:44Z | 39,088,887 | <p>You could follow the same steps as you do for checkwifi.sh, but make it checkbtsync.sh</p>
<p>Something along these lines should work:</p>
<pre><code>#!/bin/sh
btsyncResult=$(sudo service btsync status)
if [[ $btsyncResult != *"is running"* ]]
then
sudo /sbin/shutdown -r now
fi
</code></pre>
<p>Theoreti... | 3 | 2016-08-22T21:18:43Z | [
"python",
"raspberry-pi",
"crontab"
] |
Pymongo $currentDate is not valid for storage | 39,088,579 | <p>This is my first time using pymongo. I have a method that updates Users data in a document. For example, when you log in, it should update the lastLog field, which indicates the last time that user logged in.</p>
<p>This is the method</p>
<pre><code> def update_user(self, mongo, field, value=None):
print se... | 0 | 2016-08-22T20:54:13Z | 39,089,450 | <p>I fixed it. I was doing it wrong. Te code inside the else now looks like this</p>
<pre><code> else:
result = mongo.db.Users.update_one(
{'username': self.username},
{
'$currentDate': {
'lastLog': {'$type': 'timestamp'}
... | 0 | 2016-08-22T22:05:24Z | [
"python",
"mongodb",
"pymongo"
] |
conditionally write in array | 39,088,649 | <p>I have a piece of code that goes through and open several tab-delimited files. Each time the first tab of the line of this opened file starts with four numbers (ex. 0012) I would like to write this line in an array (cell-by-cell).</p>
<p>A sample line that I would like to transfer to an array is shown below:</p>
<... | -2 | 2016-08-22T20:59:44Z | 39,091,046 | <p>Use <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">the <code>csv</code> module</a>; it <a href="https://docs.python.org/3/library/csv.html#csv.excel_tab" rel="nofollow">supports tab separated dialects</a> just fine. For example:</p>
<pre><code>import csv
with open(each_file, newline='') as f:
... | 1 | 2016-08-23T01:37:37Z | [
"python",
"python-3.x",
"csv"
] |
Python: recursive isinstance checking | 39,088,748 | <p>How can one check a complete type signature of a nested abstract class? In this example </p>
<pre><code>In [4]: from typing import Sequence
In [5]: IntSeq = Sequence[int]
In [6]: isinstance([1], IntSeq)
Out[6]: True
In [7]: isinstance([1.0], IntSeq)
Out[7]: True
</code></pre>
<p>I want the last <code>isinstance... | 4 | 2016-08-22T21:06:05Z | 39,098,131 | <p>I see you're trying to implement something using a module that is still provisional; you're bound to encounter a changing interface if you do this.</p>
<p>Blender noticed that the <code>__parameters__</code> argument holds the parameters to the type; this was true until, I believe <code>3.5.1</code>. In my git clon... | 2 | 2016-08-23T10:04:21Z | [
"python",
"python-3.x",
"oop",
"python-3.5",
"type-hinting"
] |
Error: etheruem-serpent; version conflict | 39,088,812 | <p>After installing pythereum and ethereum serpent, I ran a test using: <code>$ pytest -m test_contracts.py</code> I got the following error, and I can't seem to figure out what the real issue is:</p>
<p>================================================================================ test session starts ==============... | 0 | 2016-08-22T21:13:01Z | 39,095,973 | <p>This error seems to be specific with ethereum-serpent-1.6.7 This error was solved by upgrading to the latest ethereum-serpent(2.02.), through:</p>
<pre><code>pip install --upgrade ethereum-setpent
</code></pre>
| 0 | 2016-08-23T08:23:09Z | [
"python",
"python-2.7",
"testing",
"py.test",
"ethereum"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.