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
graphlab adding variable columns from existing sframe
39,189,416
<p>I have a SFrame e.g.</p> <pre><code>a | b ----- 2 | 31 4 5 0 | 1 9 1 | 2 84 </code></pre> <p>now i want to get following result</p> <pre><code>a | b | c | d | e ---------------------- 2 | 31 4 5 | 31|4 | 5 0 | 1 9 | 1 | 9 | 0 1 | 2 84 | 2 | 84 | 0 </code></pre> <p>any idea how to do it? or maybe i ha...
0
2016-08-28T08:36:20Z
39,189,659
<p>Using pandas:</p> <pre><code>In [409]: sf Out[409]: Columns: a int b str Rows: 3 Data: +---+--------+ | a | b | +---+--------+ | 2 | 31 4 5 | | 0 | 1 9 | | 1 | 2 84 | +---+--------+ [3 rows x 2 columns] In [410]: df = sf.to_dataframe() In [411]: newdf = pd.DataFrame(df.b.str.split().toli...
1
2016-08-28T09:10:58Z
[ "python", "pandas", "graphlab" ]
graphlab adding variable columns from existing sframe
39,189,416
<p>I have a SFrame e.g.</p> <pre><code>a | b ----- 2 | 31 4 5 0 | 1 9 1 | 2 84 </code></pre> <p>now i want to get following result</p> <pre><code>a | b | c | d | e ---------------------- 2 | 31 4 5 | 31|4 | 5 0 | 1 9 | 1 | 9 | 0 1 | 2 84 | 2 | 84 | 0 </code></pre> <p>any idea how to do it? or maybe i ha...
0
2016-08-28T08:36:20Z
39,189,808
<pre><code>def customsplit(string,column): val = string.split(' ') diff = column - len(val) val += ['0']*diff return val a = sf['b'].apply(lambda x: customsplit(x,3)) sf['c'] = [i[0] for i in a] sf['d'] = [i[1] for i in a] sf['e'] = [i[2] for i in a] sf </code></pre> <p>Output:</p> <pre><code>a |...
1
2016-08-28T09:26:40Z
[ "python", "pandas", "graphlab" ]
graphlab adding variable columns from existing sframe
39,189,416
<p>I have a SFrame e.g.</p> <pre><code>a | b ----- 2 | 31 4 5 0 | 1 9 1 | 2 84 </code></pre> <p>now i want to get following result</p> <pre><code>a | b | c | d | e ---------------------- 2 | 31 4 5 | 31|4 | 5 0 | 1 9 | 1 | 9 | 0 1 | 2 84 | 2 | 84 | 0 </code></pre> <p>any idea how to do it? or maybe i ha...
0
2016-08-28T08:36:20Z
39,197,008
<p>This can be done by SFrame itself not using Pandas. Just utilize '<strong><a href="https://turi.com/products/create/docs/generated/graphlab.SFrame.unpack.html?highlight=unpack#graphlab.SFrame.unpack" rel="nofollow">unpack</a></strong>' function. </p> <p>Pandas provides a variety of functions to handle dataset, but ...
0
2016-08-29T00:21:56Z
[ "python", "pandas", "graphlab" ]
Number of rows in 40GB tar.gz file without uncompressing it?
39,189,464
<p>I have over 40 gb tar.gz file at <a href="https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz" rel="nofollow">https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz</a> How can I find the number of rows in the CSV file that is compressed inside this tar.gz file without unco...
3
2016-08-28T08:43:35Z
39,189,614
<p>If there is only one csv file in that tar.gz, you could do this as a bash one-liner:</p> <p><code>tar -zxOf mysql-2016-06-16.tar.gz | wc -l</code></p> <p>It uses tar to extract all the files in the archive to standard output (-O, capital o, not zero), and wc to count the lines.</p> <p>If there is more files, and ...
3
2016-08-28T09:05:18Z
[ "python", "csv", "gzip", "tar" ]
Number of rows in 40GB tar.gz file without uncompressing it?
39,189,464
<p>I have over 40 gb tar.gz file at <a href="https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz" rel="nofollow">https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz</a> How can I find the number of rows in the CSV file that is compressed inside this tar.gz file without unco...
3
2016-08-28T08:43:35Z
39,189,631
<blockquote> <p>without uncompressing the entire file which might be in 100+ GBs</p> </blockquote> <p>I suppose you mean without extracting the file to disk first. Here's a Python approach to achieve this:</p> <pre><code>import tarfile as tf import gzip as gz from StringIO import StringIO infile = '/path/to/mysql-2...
1
2016-08-28T09:07:27Z
[ "python", "csv", "gzip", "tar" ]
Python function that takes one compulsory argument from two choices
39,189,472
<p>I have a function:</p> <pre><code>def delete(title=None, pageid=None): # Deletes the page given, either by its title or ID ... pass </code></pre> <p>However, my intention is for the function to take only one argument (either <code>title</code> OR <code>pageid</code>). For example, <code>delete(title="M...
1
2016-08-28T08:45:35Z
39,189,491
<p>There is no Python syntax that'll let you define exclusive-or arguments, no. You'd have to explicitly raise an exception is both or none are specified:</p> <pre><code>if (title and pageid) or not (title or pageid): raise ValueError('Can only delete by title OR pageid') </code></pre>
2
2016-08-28T08:47:51Z
[ "python", "function", "arguments" ]
Python function that takes one compulsory argument from two choices
39,189,472
<p>I have a function:</p> <pre><code>def delete(title=None, pageid=None): # Deletes the page given, either by its title or ID ... pass </code></pre> <p>However, my intention is for the function to take only one argument (either <code>title</code> OR <code>pageid</code>). For example, <code>delete(title="M...
1
2016-08-28T08:45:35Z
39,189,517
<p>I don't think there's any way to do this in the function signature itself. However, you could always have a check inside your function to see if both arguments are set</p> <pre><code>def delete(title=None, pageid=None): # Deletes the page given, either by its title or ID if title and pageid: # throw err...
1
2016-08-28T08:51:30Z
[ "python", "function", "arguments" ]
Python function that takes one compulsory argument from two choices
39,189,472
<p>I have a function:</p> <pre><code>def delete(title=None, pageid=None): # Deletes the page given, either by its title or ID ... pass </code></pre> <p>However, my intention is for the function to take only one argument (either <code>title</code> OR <code>pageid</code>). For example, <code>delete(title="M...
1
2016-08-28T08:45:35Z
39,189,525
<p>If both arguments can have any value, including <code>None</code>, then the solution is to use a sentinel object for them. Then you can calculate a sum over the number of arguments that are set to non-default value:</p> <pre><code>NOT_SET = object() def delete(title=NOT_SET, pageid=NOT_SET): if sum(i is not NO...
0
2016-08-28T08:52:43Z
[ "python", "function", "arguments" ]
cannot import name SQLALchemy
39,189,548
<p>I have installed flask-sqlalchemy via pip.But something wrong happened when I run the program,that is, "cannot import name SQLALchemy"At first,I thought the problem was the improper installation.However,I still couldn't solve the problem after several uninstall and installation.Then I change the first line into "fro...
1
2016-08-28T08:56:39Z
39,189,700
<p>Try to run your Python interpreter and then use:</p> <pre><code>&gt;&gt;&gt; from flask import Flask &gt;&gt;&gt; from flask_sqlalchemy import SQLAlchemy </code></pre> <p>this should work. Your original code has a typo </p>
0
2016-08-28T09:15:39Z
[ "python", "flask-sqlalchemy" ]
cannot import name SQLALchemy
39,189,548
<p>I have installed flask-sqlalchemy via pip.But something wrong happened when I run the program,that is, "cannot import name SQLALchemy"At first,I thought the problem was the improper installation.However,I still couldn't solve the problem after several uninstall and installation.Then I change the first line into "fro...
1
2016-08-28T08:56:39Z
39,189,711
<p>I believe that imports are case sensitive. </p> <p>Try <code>from flask_sqlalchemy import SQLAlchemy</code> instead of <code>SQLALchemy</code></p>
0
2016-08-28T09:16:38Z
[ "python", "flask-sqlalchemy" ]
OSX PyGame Failed loading libpng.dylib: dlopen(libpng.dylib, 2)
39,189,550
<p>I'm getting this error <code>pygame.error: Failed loading libpng.dylib: dlopen(libpng.dylib, 2): image not found</code> when running a program on OSX (10.11.6) using Python 2.7</p> <p>I've tried following <a href="http://stackoverflow.com/questions/38645391/python-pygame-error-failed-loading-libpng-dylib-dlopenlibp...
1
2016-08-28T08:56:52Z
39,425,882
<p>Use python3 interpreter in terminal e.g. python3 xx.py</p>
-1
2016-09-10T12:02:43Z
[ "python", "osx", "pygame" ]
Inheriting Base from C++ in Python, call abstract method using SWIG
39,189,594
<p>I'm having some trouble coupling C++ (98) with python 3. I have some base classes in C++ which I'd like to extend in Python. Some methods in question are pure virtual on the C++ side and will thus be implemented on the Python side.</p> <p>Currently, I can call the abstract methods from C++ and, over swig, the speci...
0
2016-08-28T09:02:12Z
39,230,663
<p>This is not really an answer, but I read the discussion <a href="https://bytes.com/topic/python/answers/38519-extending-classes-written-c-using-swig" rel="nofollow">Discussion from 2005</a> and it makes sense, that it shouldn't be possible. If you on the Python side, do the following, you get your enumeration 'deref...
1
2016-08-30T14:46:01Z
[ "python", "c++", "swig" ]
Inheriting Base from C++ in Python, call abstract method using SWIG
39,189,594
<p>I'm having some trouble coupling C++ (98) with python 3. I have some base classes in C++ which I'd like to extend in Python. Some methods in question are pure virtual on the C++ side and will thus be implemented on the Python side.</p> <p>Currently, I can call the abstract methods from C++ and, over swig, the speci...
0
2016-08-28T09:02:12Z
39,251,709
<p>It seems somebody else tried <a href="http://stackoverflow.com/questions/9040669/how-can-i-implement-a-c-class-in-python-to-be-called-by-c">the exact same thing</a> !</p> <p>What I did was compile the *.pyd with -DSWIG_TYPE_TABLE=iBase.</p> <p>Then I added this to the main application on the cpp side:</p> <pre><c...
0
2016-08-31T13:58:59Z
[ "python", "c++", "swig" ]
Conditional length of a binary data series in Pandas
39,189,605
<p>Having a DataFrame with the following column:</p> <pre><code>df['A'] = [1,1,1,0,1,1,1,1,0,1] </code></pre> <p>What would be the best vectorized way to control the length of "1"-series by some limiting value? Let's say the limit is 2, then the resulting column 'B' must look like:</p> <pre><code> A B 0 1 1 1 ...
0
2016-08-28T09:04:08Z
39,189,829
<p>One fully-vectorized solution is to use the <code>shift</code>-<code>groupby</code>-<code>cumsum</code>-<code>cumcount</code> combination<sup>1</sup> to indicate where consecutive runs are shorter than 2 (or whatever limiting value you like). Then, <code>&amp;</code> this new boolean Series with the original column:...
3
2016-08-28T09:28:21Z
[ "python", "pandas", "vectorization" ]
Conditional length of a binary data series in Pandas
39,189,605
<p>Having a DataFrame with the following column:</p> <pre><code>df['A'] = [1,1,1,0,1,1,1,1,0,1] </code></pre> <p>What would be the best vectorized way to control the length of "1"-series by some limiting value? Let's say the limit is 2, then the resulting column 'B' must look like:</p> <pre><code> A B 0 1 1 1 ...
0
2016-08-28T09:04:08Z
39,189,842
<p>Another way (checking if previous two are 1):</p> <pre><code>In [443]: df = pd.DataFrame({'A': [1,1,1,0,1,1,1,1,0,1]}) In [444]: limit = 2 In [445]: df['B'] = map(lambda x: df['A'][x] if x &lt; limit else int(not all(y == 1 for y in df['A'][x - limit:x])), range(len(df))) In [446]: df Out[446]: A B 0 1 1 ...
2
2016-08-28T09:30:03Z
[ "python", "pandas", "vectorization" ]
Conditional length of a binary data series in Pandas
39,189,605
<p>Having a DataFrame with the following column:</p> <pre><code>df['A'] = [1,1,1,0,1,1,1,1,0,1] </code></pre> <p>What would be the best vectorized way to control the length of "1"-series by some limiting value? Let's say the limit is 2, then the resulting column 'B' must look like:</p> <pre><code> A B 0 1 1 1 ...
0
2016-08-28T09:04:08Z
39,189,964
<p>If you know that the values in the series will all be either <code>0</code> or <code>1</code>, I think you can use a little trick involving convolution. Make a copy of your column (which need not be a Pandas object, it can just be a normal Numpy array)</p> <pre><code>a = df['A'].as_matrix() </code></pre> <p>and co...
2
2016-08-28T09:45:33Z
[ "python", "pandas", "vectorization" ]
Python calculate ageing of outlook mail items
39,189,689
<p>I am trying to develop an application in wxPython in which I will fetch all e-mails into a listctrl and sort them based on their remaining SLA (3 days) for further action. For this I will calculate the ageing of the items in the mailbox by deducting the receivedTime from current time. Below is my complete code:-</p>...
0
2016-08-28T09:14:38Z
39,224,240
<p>There are many ways to do this, here is one way.<br> Check what the structure of <code>msg.receivedtime</code> is and then convert it into seconds to be able to manipulate it. I am assuming the following structure of <code>msg.receivedtime</code> "2016-08-30 10:30:15"<br> Use <code>time.time()</code> rather than <co...
0
2016-08-30T09:51:05Z
[ "python", "email" ]
pandas groupby sort on summary statistics
39,189,722
<pre><code> date shown clicked converted avg_cost_per_click total_revenue ad 0 2015-10-01 65877 2339 43 0.90 641.62 ad_group_1 1 2015-10-02 65100 2498 38 0.94 756.37 ad_group_2 2 2015-10-03 70658 2313 49 0.86 970.90 ad_group_3 3 2015-10-04 69809 2833 51 1.01 ...
0
2016-08-28T09:17:31Z
39,190,210
<p>You need to aggregate the mean on every grouped key and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html#pandas.DataFrame.sort_values" rel="nofollow"><code>sort_values</code></a> to sort those output values.</p> <pre><code>df_grouped = df.groupby(['ad'])['shown']....
1
2016-08-28T10:12:27Z
[ "python", "pandas" ]
I got error while using "git push heroku master"
39,189,780
<p>I'm using the below given commands for push data to heroku app.</p> <pre><code>git clone https://git.heroku.com/bigpro.git cd bigpro git add . git commit . -m "my test on commit" git push heroku master </code></pre> <p>When I used <code>git push heroku master</code> I got something like this..</p> <pre><code>fat...
5
2016-08-28T09:23:13Z
39,189,821
<p>First, install the <a href="https://toolbelt.heroku.com" rel="nofollow">heroku toolbelt</a>, and then type <code>heroku login</code> to setup your account properly.</p> <p>Next, type <code>heroku git:clone -a myapp</code> where <code>myapp</code> is the name of your application in Heroku. This will pull the reposit...
2
2016-08-28T09:27:40Z
[ "python", "heroku", "github" ]
I got error while using "git push heroku master"
39,189,780
<p>I'm using the below given commands for push data to heroku app.</p> <pre><code>git clone https://git.heroku.com/bigpro.git cd bigpro git add . git commit . -m "my test on commit" git push heroku master </code></pre> <p>When I used <code>git push heroku master</code> I got something like this..</p> <pre><code>fat...
5
2016-08-28T09:23:13Z
40,142,561
<p>This happened to me after I cloned from heroku a second copy of my files. Suddenly <code>git push heroku master</code> wouldn't work and I'd get the same error as you. But when I tried <code>git push origin master</code>, it worked fine.</p>
1
2016-10-19T22:29:36Z
[ "python", "heroku", "github" ]
Conditional editing of strings in a Pandas DataFrame
39,189,794
<p>I am learning Pandas and have a DataFrame of strings which looks a little like this:</p> <pre><code>df = pd.DataFrame([['Apple', 'Med6g7867'], ['Orange', 'Med7g8976'], ['Banana', 'Signal'], ['Peach', 'Med8g8989'], ['Mango', 'Possible result %gggyy']], columns=['A', 'B']) df A B 0 Apple Med6g7867 1 O...
2
2016-08-28T09:24:59Z
39,189,946
<p>You can apply replace twice like this:</p> <pre><code>In [460]: df Out[460]: A B 0 Apple Med6g7867 1 Orange Med7g8976 2 Banana Signal 3 Peach Med8g8989 4 Mango Possible result %gggyy In [461]: df.replace(r'Med\dg\d{4...
2
2016-08-28T09:43:17Z
[ "python", "regex", "pandas" ]
Conditional editing of strings in a Pandas DataFrame
39,189,794
<p>I am learning Pandas and have a DataFrame of strings which looks a little like this:</p> <pre><code>df = pd.DataFrame([['Apple', 'Med6g7867'], ['Orange', 'Med7g8976'], ['Banana', 'Signal'], ['Peach', 'Med8g8989'], ['Mango', 'Possible result %gggyy']], columns=['A', 'B']) df A B 0 Apple Med6g7867 1 O...
2
2016-08-28T09:24:59Z
39,190,786
<pre><code>import pandas as pd df = pd.DataFrame([['Apple', 'Med6g7867'], ['Orange', 'Med7g8976'], ['Banana', 'Signal'], ['Peach', 'Med8g8989'], ['Mango', 'Possible result %gggyy']], columns=['A', 'B']) df['B'] = df['B'].str....
2
2016-08-28T11:28:45Z
[ "python", "regex", "pandas" ]
show price based on product selected in form box
39,189,811
<p>I have a model of product and sale. A product contains a list of product with name, price and quantity where a sales model has product(Foreign key), quantity and price. There is a form for sale which shows list of products, quantity and price. Whenever a user selects for the product, the price field should show the ...
0
2016-08-28T09:27:13Z
39,190,446
<p>Try this to disable a form field.</p> <pre><code>form = SaleForm() form.fields['price'].widget.attrs['disabled'] = True </code></pre> <p>This just disable it in front end only. You have to o validations in backend form validation because, in frontend anyone can do disable to enable.</p>
0
2016-08-28T10:44:21Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
show price based on product selected in form box
39,189,811
<p>I have a model of product and sale. A product contains a list of product with name, price and quantity where a sales model has product(Foreign key), quantity and price. There is a form for sale which shows list of products, quantity and price. Whenever a user selects for the product, the price field should show the ...
0
2016-08-28T09:27:13Z
39,190,518
<p>You should write javascript code to detect the <code>onchange</code> event of the <code>product</code> field. In the <code>onchange</code> event handler, you should fire the AJAX call to the backend to fetch the information for the selected product by passing the <code>product_id</code>. Typically, this is an anothe...
0
2016-08-28T10:53:50Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
Can't convert a Python List to timeSeries
39,189,876
<p>I tried to resolve this problem for more than a day. I have this type of list:</p> <pre><code>TempList[:5] [(datetime.datetime(2015, 11, 25, 7, 29, 28, 337000),), (datetime.datetime(2015, 9, 8, 7, 44, 55, 53000),), (datetime.datetime(2015, 9, 10, 5, 44, 51, 867000),), (datetime.datetime(2015, 9, 10, 1, 42, 15, 7400...
4
2016-08-28T09:33:51Z
39,189,948
<p>You have a list of tuples. Try converting that into a plain list, and then using <code>pd.to_datetime</code>. Something like (I do not have python right now)</p> <pre><code>tl2 = [ ti[0] for ti in TempList ] Dates = pd.to_datetime(tl2) </code></pre> <p>PS1: What else do you have in <code>TempList</code>? (you only...
3
2016-08-28T09:43:45Z
[ "python", "pandas", "time-series" ]
How to subclass list and trigger an event whenever the data change?
39,189,893
<p>I would like to subclass <code>list</code> and trigger an event (data checking) every time any change happens to the data. Here is an example subclass:</p> <pre><code>class MyList(list): def __init__(self, sequence): super().__init__(sequence) self._test() def __setitem__(self, key, value):...
12
2016-08-28T09:36:06Z
39,190,103
<p>As you say, this is not the best way to go about it. To correctly implement this, you'd need to know about every method that can change the list.</p> <p>The way to go is to implement your own list (or rather a mutable sequence). The best way to do this is to use the abstract base classes from Python which you find ...
7
2016-08-28T10:01:04Z
[ "python" ]
Python code won't run?
39,189,900
<p>Hello i was wondering why this code will not run,thanks.</p> <pre><code>count = 0 finished = False total = 0 while not finished: number = int(input("Enter a number(0 to finish)")) if number == 0: finished = True else: total = total + number count = count + 1 print("th...
-3
2016-08-28T09:37:04Z
39,189,916
<p>It does run, the only issue I can see is that your else is indented inside your if block. In Python, indentation is important in a way that curled brackets or keywords are important in other programming languages.</p> <pre><code>count = 0 finished = False total = 0 while not finished: number = int(input("Enter ...
0
2016-08-28T09:40:05Z
[ "python", "python-3.x" ]
Python code won't run?
39,189,900
<p>Hello i was wondering why this code will not run,thanks.</p> <pre><code>count = 0 finished = False total = 0 while not finished: number = int(input("Enter a number(0 to finish)")) if number == 0: finished = True else: total = total + number count = count + 1 print("th...
-3
2016-08-28T09:37:04Z
39,189,939
<p>Your script is alright, you haven't indented properly the <code>else</code>clause, here's a working example, also, you should cast to float your average:</p> <pre><code>count = 0 finished = False total = 0 while not finished: number = int(input("Enter a number(0 to finish)")) if number == 0: finish...
0
2016-08-28T09:42:54Z
[ "python", "python-3.x" ]
Unusual permutations
39,190,036
<p>I have few lists:</p> <pre><code>a = [1,2,3] b = [4,5,6] c = [7,8,9,10] </code></pre> <p>How do I generate all combinations like:</p> <pre><code>a[0], b[0] a[1], b[1] a[2], b[2] a[0], b[0], c[0] a[1], b[1], c[0] a[2], b[2], c[0] a[1], b[1], c[1] a[2], b[2], c[2] a[0], b[0], c[3] a[1], b[1], c[3] a[2], b[2], c[3] ...
0
2016-08-28T09:54:43Z
39,190,125
<p>Not sure whether I've understood correctly your question, but do you mean this?</p> <pre><code>from itertools import permutations my_list = ['a1', 'a2', 'a3', 'b1', 'b2', 'c1'] for i in range(len(my_list)): print(list(permutations(my_list, i))) </code></pre>
0
2016-08-28T10:03:37Z
[ "python", "algorithm", "combinations", "permutation" ]
Unusual permutations
39,190,036
<p>I have few lists:</p> <pre><code>a = [1,2,3] b = [4,5,6] c = [7,8,9,10] </code></pre> <p>How do I generate all combinations like:</p> <pre><code>a[0], b[0] a[1], b[1] a[2], b[2] a[0], b[0], c[0] a[1], b[1], c[0] a[2], b[2], c[0] a[1], b[1], c[1] a[2], b[2], c[2] a[0], b[0], c[3] a[1], b[1], c[3] a[2], b[2], c[3] ...
0
2016-08-28T09:54:43Z
39,190,403
<p>As per your example, you seem to want only <code>abc</code>-type permutations. So you either: 1) build your "permutations" explicitly, or 2) build all permutations and filter out those you do not want.</p> <p><strong>Explicit construction</strong></p> <ol> <li>Build your <code>list_of_lists</code>, i.e. <code>[['a...
1
2016-08-28T10:37:06Z
[ "python", "algorithm", "combinations", "permutation" ]
How can I do 'from foo import bar as b' with imp in Python2.7?
39,190,124
<p>I need to import a module without knowing it's location in advance; The user will specify the location as an argument to my script. </p> <p>I know I can use <code>imp</code> for imports, like </p> <pre><code>import imp foo = imp.load_source('foo', '/path/to/foo.py') </code></pre> <p>which is functionally equivale...
0
2016-08-28T10:03:31Z
39,192,327
<p>As I commented, you can use normal attribute access to get the <code>bar</code> object from the module object returned from <code>imp.load_source</code>, even within the same expression:</p> <pre><code>b = imp.load_source('foo', '/path/to/foo.py').bar </code></pre> <p>This isn't quite the same as <code>from foo im...
0
2016-08-28T14:30:18Z
[ "python", "python-2.7", "python-import" ]
django wsgi.py cannot recognize settings file
39,190,142
<p>A strange problem occured while trying to configure <code>apache2</code> to serve a Django project via <code>wsgi</code>.</p> <p>My project is a small to-do list implemented here. <a href="https://github.com/panospet/toDoList" rel="nofollow">https://github.com/panospet/toDoList</a></p> <p>When apache tries to run ...
-1
2016-08-28T10:05:10Z
39,190,363
<p>remove that space in sys.path.append</p> <pre><code>sys.path.append('/var/www/toDoList') sys.path.append('/var/www/toDoList/myToDoList') </code></pre>
1
2016-08-28T10:31:47Z
[ "python", "django", "apache", "mod-wsgi", "wsgi" ]
django wsgi.py cannot recognize settings file
39,190,142
<p>A strange problem occured while trying to configure <code>apache2</code> to serve a Django project via <code>wsgi</code>.</p> <p>My project is a small to-do list implemented here. <a href="https://github.com/panospet/toDoList" rel="nofollow">https://github.com/panospet/toDoList</a></p> <p>When apache tries to run ...
-1
2016-08-28T10:05:10Z
39,190,366
<p>Based on <a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/" rel="nofollow">Django documentation</a> You missed the <code>WSGIPythonPath</code>:</p> <pre><code>WSGIPythonPath /var/www/toDoList </code></pre> <p>This line ensures that your project package is available for import on the Py...
0
2016-08-28T10:31:55Z
[ "python", "django", "apache", "mod-wsgi", "wsgi" ]
Under what condition does a Python subprocess get a SIGPIPE?
39,190,250
<p>I am reading the the Python documentation on the Popen class in the subprocess module section and I came across the following code:</p> <pre><code>p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2....
0
2016-08-28T10:18:25Z
39,190,346
<p><code>SIGPIPE</code> is a signal that would be sent if <code>dmesg</code> tried to write to a closed pipe. Here, <code>dmesg</code> ends up with <em>two</em> targets to write to, your Python process and the <code>grep</code> process.</p> <p>That's because <code>subprocess</code> clones file handles (using the <a hr...
2
2016-08-28T10:29:41Z
[ "python", "pipe", "subprocess" ]
Development vs Release Python Code
39,190,274
<p>I am currently developing a Python application which I continually performance test, simply by recording the runtime of various parts.</p> <p>A lot of the code is related only to the testing environment and would not exist in the real world application, I have these separated into functions and at the moment I comm...
-4
2016-08-28T10:20:13Z
39,190,392
<p>There are libraries for testing like those in the <a href="https://docs.python.org/3/library/development.html" rel="nofollow">development-section</a> of the standard library. If you did not use such tools yet, you should start to do so - they help a lot with testing. (especially <code>unittest</code>).</p> <p>Norma...
0
2016-08-28T10:35:09Z
[ "python", "testing" ]
Development vs Release Python Code
39,190,274
<p>I am currently developing a Python application which I continually performance test, simply by recording the runtime of various parts.</p> <p>A lot of the code is related only to the testing environment and would not exist in the real world application, I have these separated into functions and at the moment I comm...
-4
2016-08-28T10:20:13Z
39,190,406
<p>I'd say if you're commenting out several parts of your code when switching between debug&amp;release mode I think <strong>you're doing wrong</strong>. Take a look for example to the <a href="https://docs.python.org/2/library/logging.html" rel="nofollow">logging library</a>, as you can see, with that library you can ...
0
2016-08-28T10:37:44Z
[ "python", "testing" ]
Concatenating two string columns of numpy array into single column in python
39,190,302
<p>I have a numpy array as following :</p> <pre><code>2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 17:01:34 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 16:59:52 2016-07-02 10:40:00 2016-07-02 12:01:14 </code></pre> <p>this are two col...
0
2016-08-28T10:24:02Z
39,190,375
<p>Insert the tabs <code>\t</code> into your array using <code>numpy.insert</code> and then do a <code>numpy.reshape</code> from n by 3 to n*3 by 1</p>
1
2016-08-28T10:33:02Z
[ "python", "arrays", "numpy" ]
Concatenating two string columns of numpy array into single column in python
39,190,302
<p>I have a numpy array as following :</p> <pre><code>2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 17:01:34 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 16:59:52 2016-07-02 10:40:00 2016-07-02 12:01:14 </code></pre> <p>this are two col...
0
2016-08-28T10:24:02Z
39,190,441
<p>Neat, but not more efficient than simple loop (as Praveen pointed out in comment):</p> <pre><code>import numpy as np np.apply_along_axis(lambda d: d[0] + '\t' + d[1], 1, arr) </code></pre>
2
2016-08-28T10:43:31Z
[ "python", "arrays", "numpy" ]
Concatenating two string columns of numpy array into single column in python
39,190,302
<p>I have a numpy array as following :</p> <pre><code>2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 17:01:34 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 16:59:52 2016-07-02 10:40:00 2016-07-02 12:01:14 </code></pre> <p>this are two col...
0
2016-08-28T10:24:02Z
39,191,110
<pre><code>import numpy as np a=[[1],[2],[3]] b=[[4],[5],[6]] np.concatenate((a,b),axis=1) </code></pre>
1
2016-08-28T12:08:38Z
[ "python", "arrays", "numpy" ]
Python json key error
39,190,351
<p>So I'm using the following simple snippet code to import a JSON object and then pull out specific fields into a list. Here it is:</p> <pre><code>#Set Observations URL request for all observations within the Osa Pennisula, Costa Rica query = urllib2.urlopen("http://api.inaturalist.org/v1/observations?nelat=8.60586&a...
-1
2016-08-28T10:30:21Z
39,190,376
<p>Because not every item in <code>obSet['results']</code> has key <code>item['taxon']['preferred_common_name']</code>.</p> <p>You can counteract that by catching these <code>KeyError</code>s and printing the offensive keys. It also seems like some items have <code>None</code> as value for <code>'taxon'</code> key, so...
2
2016-08-28T10:33:11Z
[ "python", "json" ]
How can I use Bokeh in an Azure ML notebook
39,190,415
<p>I can run the following code in a Jupyter notebook (Python 3.5) on my PC using Anaconda, and it works fine. But when I run the same code in an Azure ML notebook, I get the plot, but also the error message described below. Does anyone know how to use Bokeh in Azure ML notebooks ? Is there perhaps a way to import the ...
0
2016-08-28T10:39:24Z
39,195,345
<p>There are two options I think. In a notebook, I think you can use <code>conda</code> to install new packages in your AzureML environment, by executing a cell with the following:</p> <pre><code>!conda install ipykernel --yes </code></pre> <p>Note the <code>!</code> at the beginning. In Jupyter notebooks that means ...
2
2016-08-28T20:10:45Z
[ "python", "azure", "jupyter-notebook", "bokeh", "azure-ml" ]
How can I use Bokeh in an Azure ML notebook
39,190,415
<p>I can run the following code in a Jupyter notebook (Python 3.5) on my PC using Anaconda, and it works fine. But when I run the same code in an Azure ML notebook, I get the plot, but also the error message described below. Does anyone know how to use Bokeh in Azure ML notebooks ? Is there perhaps a way to import the ...
0
2016-08-28T10:39:24Z
39,328,659
<p>@MortenBunesGustavsen, As I known, there are two different versions of python for Azure ML notebook which include <code>python3.4</code> on the <code>env3</code> host and <code>python3.5</code> on the <code>anaconda3_410</code> host. You can directly access the url <code>http://notebooks.azure.com</code> to use the ...
1
2016-09-05T10:29:59Z
[ "python", "azure", "jupyter-notebook", "bokeh", "azure-ml" ]
how to add change language dropdown to Django(1.10) admin?
39,190,430
<p>I'm planning to add change language dropdown in my admin page. according to <a href="https://djangosnippets.org/snippets/751/" rel="nofollow">this code</a> and <a href="http://stackoverflow.com/questions/17978260/how-do-i-correctly-extend-the-django-admin-base-html-template">How to extend admin page</a>. <br/> I cop...
0
2016-08-28T10:40:43Z
39,191,836
<p>I guess you are mixing both answers that you've found on the internet. One of them copies and changes a couple of files from the admin template, effectively overriding them in your program's references. The second one extends admin's templates. You should completely implement just one of them.</p>
1
2016-08-28T13:36:31Z
[ "python", "django", "django-admin", "multilingual", "django-multilingual" ]
Show Django Model @property as a bool in model admin
39,190,445
<p>I have a model with a <code>property</code>, It returns boolean, I want to show it as icon in django model admin.</p> <h2>models.py</h2> <pre><code>class Foo(models.Model): bar = models.TextField("Title", null=True, blank=True) @property def is_new_bar(self): return bar == 'NEW' </code></pre> ...
0
2016-08-28T10:43:53Z
39,190,516
<p>Just add <code>is_new_bar.boolean = True</code> to your model. Also, remove the <code>property</code> decorator. Like this:</p> <pre><code>class Foo(models.Model): bar = models.TextField("Title", null=True, blank=True) def is_new_bar(self): return bar == 'NEW' is_new_bar.boolean = True </code><...
0
2016-08-28T10:53:05Z
[ "python", "django", "admin" ]
Show Django Model @property as a bool in model admin
39,190,445
<p>I have a model with a <code>property</code>, It returns boolean, I want to show it as icon in django model admin.</p> <h2>models.py</h2> <pre><code>class Foo(models.Model): bar = models.TextField("Title", null=True, blank=True) @property def is_new_bar(self): return bar == 'NEW' </code></pre> ...
0
2016-08-28T10:43:53Z
39,190,652
<p>Try this <code>property</code> use.</p> <pre><code>def is_new_bar(self): return bar == 'NEW' is_new_bar.boolean = True is_new_bar = property(is_new_bar) </code></pre>
1
2016-08-28T11:10:40Z
[ "python", "django", "admin" ]
Show Django Model @property as a bool in model admin
39,190,445
<p>I have a model with a <code>property</code>, It returns boolean, I want to show it as icon in django model admin.</p> <h2>models.py</h2> <pre><code>class Foo(models.Model): bar = models.TextField("Title", null=True, blank=True) @property def is_new_bar(self): return bar == 'NEW' </code></pre> ...
0
2016-08-28T10:43:53Z
39,190,681
<p>You can add method to your modeladmin that will return property value and set that it will return boolean:</p> <pre><code>class FooAdmin(admin.ModelAdmin): list_display = ('bar', 'get_is_new_bar') def get_is_new_bar(self, obj): return self.is_new_bar get_is_new_bar.boolean = True </code></p...
2
2016-08-28T11:13:56Z
[ "python", "django", "admin" ]
Python Pandas subsetting based on Dates
39,190,520
<p>I got a dataframe (using pandas) which contains the following fields:</p> <ol> <li>Datesf-----------Price</li> <li>02/08/16 17:28--10</li> <li>02/08/16 17:29--20</li> <li>02/08/16 17:30--30</li> <li>03/08/16 09:00--40</li> <li>04/08/16 09:00--50</li> </ol> <p>I am trying to subset the data frame into new dataframe...
0
2016-08-28T10:54:01Z
39,190,856
<p>This should do the work.</p> <pre><code>import pandas as pd df = pd.DataFrame([['02/08/16 17:28',1], ['02/08/16 17:28',10],['02/08/16 17:28',100],['03/08/16 17:28',101],['04/08/16 17:28',103]], columns=['Datesf', 'Price']) df.Datesf = pd.to_datetime(df.Datesf) unique_dates = df.Datesf.unique() data_frame_dict = {e...
1
2016-08-28T11:38:50Z
[ "python", "pandas", "subset" ]
Python, A class within a class, how to access variables from the upper class
39,190,547
<p>I have Qt <code>Gui</code> class that handles all the variables (<code>p1</code>, <code>p2</code>) adjustment with sliders and stuff. Inside this class, I have a OSC listener class that was supposed to listen to trigger signals and a variable <code>p3</code> from another device and use the parameters to trigger soun...
0
2016-08-28T10:57:51Z
39,190,588
<p>You could pass the<code>Ptsgui</code> to <code>OscListener</code> like this:</p> <pre><code>class Ptsgui(QtGui.QMainWindow): def __init__(self): super(Ptsgui, self).__init__() self.p1, self.p2, self.data = 0, 0, np.zeros(10) self.initUI() class OscListener(object): def __ini...
0
2016-08-28T11:02:39Z
[ "python", "class", "pyqt", "subclass", "osc" ]
Python, A class within a class, how to access variables from the upper class
39,190,547
<p>I have Qt <code>Gui</code> class that handles all the variables (<code>p1</code>, <code>p2</code>) adjustment with sliders and stuff. Inside this class, I have a OSC listener class that was supposed to listen to trigger signals and a variable <code>p3</code> from another device and use the parameters to trigger soun...
0
2016-08-28T10:57:51Z
39,190,683
<p>What you trying to achieve can be done like that:</p> <pre><code>class Ptsgui(QtGui.QMainWindow): def __init__(self): super(Ptsgui, self).__init__() self.p1, self.p2, self.data = 0, 0, np.zeros(10) self.initUI() def initUI(): """ Some sliders setup for change the p1 ...
0
2016-08-28T11:14:35Z
[ "python", "class", "pyqt", "subclass", "osc" ]
Generate a two dimensional array of complex numbers
39,190,567
<p>I want to generate a two dimensional array of a given size containing complex numbers like in this example:</p> <pre><code>&gt;&gt;&gt; generate_array((2, 3)) array([[ 0.+0.j, 1.+0.j, 2.+0.j], [ 0.+1.j, 1.+1.j, 2.+1.j]]) </code></pre>
-3
2016-08-28T11:00:13Z
39,190,625
<p>Here is a way to achieve this<br> using <code>np.indices()</code> engaged with <code>np.vectorize()</code>:</p> <pre><code>def generate_array(dim): X, Y = np.indices(dim) return np.array(np.vectorize(complex)(X, Y)) ar = generate_array((2, 3)) print(ar) </code></pre> <p>Output:</p> <pre><code>[[ 0.+0.j ...
2
2016-08-28T11:07:53Z
[ "python", "numpy" ]
Generate a two dimensional array of complex numbers
39,190,567
<p>I want to generate a two dimensional array of a given size containing complex numbers like in this example:</p> <pre><code>&gt;&gt;&gt; generate_array((2, 3)) array([[ 0.+0.j, 1.+0.j, 2.+0.j], [ 0.+1.j, 1.+1.j, 2.+1.j]]) </code></pre>
-3
2016-08-28T11:00:13Z
39,190,682
<pre><code>def generate_array(m, n): return (np.arange(m) * 1j)[:, None] + np.arange(n) generate_array(2, 3) Out: array([[ 0.+0.j, 1.+0.j, 2.+0.j], [ 0.+1.j, 1.+1.j, 2.+1.j]]) </code></pre>
2
2016-08-28T11:14:18Z
[ "python", "numpy" ]
django request.session throws Atrribute error
39,190,599
<p>I get this error <em>'WSGIRequest' object has no attribute 'session'</em> on the manage.py runserver. When I try to retrieve the session dict from request.session.</p> <p>Searches on this item say I need to put 'django.contrib.sessions.middleware.SessionMiddleware' on top of the MIDDLEWARE settings. However this do...
0
2016-08-28T11:04:14Z
39,190,674
<p>You are using Django version 1.9; the MIDDLEWARE setting was only introduced in version 1.10. For earlier versions like yours you should be using MIDDLEWARE_CLASSES - or upgrade to 1.10.</p>
0
2016-08-28T11:13:02Z
[ "python", "django", "session" ]
Pass username and password to Flask Oauth2 Server (password grant type)
39,190,622
<p>I'm implementing Flask REST API with Flask-Oauthlib and wondering is it ok to pass username and password in URL parameters? For example:</p> <pre><code>GET http://127.0.0.1:5000/api/token?client_id=CLIENT_ID&amp;grant_type=password&amp;username=myusername&amp;password=hopeudontseemypass </code></pre> <p>In my deve...
0
2016-08-28T11:06:49Z
39,190,696
<p>The OAuth protocol spec says that the parameters must be POST-ed to the token endpoint. By accepting them as query parameters the Authorization Server violates the spec. Better use POST to avoid the credentials ending up in log files.</p>
2
2016-08-28T11:15:45Z
[ "python", "authentication", "flask", "oauth-2.0", "flask-oauthlib" ]
Dates fill in for date range and fillna
39,190,701
<p>I am querying my database to show records from the past week. I am then aggregating the data and transposing it in python and pandas into a DataFrame. In this table I am attempting to show what occurred on each day in the past 7 week, however, on some days no events occur. In these cases, the date is missing altoget...
0
2016-08-28T11:16:04Z
39,190,940
<p>assuming you have the following DF:</p> <pre><code>In [93]: df Out[93]: name purchase send_back dates 2016-08-01 Michael 120 0 2016-08-02 Sarah 100 40 2016-08-04 Sarah 55 0 2016-08-05 Michael 80 20 2016-08-07 Sarah 130 ...
1
2016-08-28T11:48:31Z
[ "python", "pandas" ]
Dates fill in for date range and fillna
39,190,701
<p>I am querying my database to show records from the past week. I am then aggregating the data and transposing it in python and pandas into a DataFrame. In this table I am attempting to show what occurred on each day in the past 7 week, however, on some days no events occur. In these cases, the date is missing altoget...
0
2016-08-28T11:16:04Z
39,192,735
<p>Your index is of <code>object</code> type and you must convert it to <code>datetime</code> format.</p> <pre><code># Converting the object date to datetime.date df['dates'] = df['dates'].apply(lambda x: datetime.strptime(x, "%d.%m.%Y")) # Setting the index column df.set_index(['dates'], inplace=True) # Choosing a ...
1
2016-08-28T15:15:24Z
[ "python", "pandas" ]
Python - Intra-package importing when package modules are sometimes used as standalone?
39,190,714
<p>Sorry if this has already been answered using terminology I don't know to search for.</p> <p>I have one project:</p> <pre><code>project1/ class1.py class2.py </code></pre> <p>Where <code>class2</code> imports some things from <code>class1</code>, but each has its own <code>if __name__ == '__main__'</code>...
0
2016-08-28T11:18:03Z
39,190,943
<p>You could run <code>class2.py</code> from inside the <code>project2</code> folder, i.e. with the current working directory set to the <code>project2</code> folder:</p> <pre><code>user@host:.../project2$ python project1/class2.py </code></pre> <p>On windows that would look like this:</p> <pre><code>C:\...project2&...
0
2016-08-28T11:48:48Z
[ "python", "python-3.x", "package", "python-import" ]
Python - Intra-package importing when package modules are sometimes used as standalone?
39,190,714
<p>Sorry if this has already been answered using terminology I don't know to search for.</p> <p>I have one project:</p> <pre><code>project1/ class1.py class2.py </code></pre> <p>Where <code>class2</code> imports some things from <code>class1</code>, but each has its own <code>if __name__ == '__main__'</code>...
0
2016-08-28T11:18:03Z
39,191,012
<p>EDIT 2: Added code to class2.py to attach the parent directory to the PYTHONPATH to comply with how Python3 module imports work.</p> <pre><code>import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) </code></pre> <p>Removed relative import of Class1.</p> <p>Folder structure:</p> <pre><c...
1
2016-08-28T11:56:01Z
[ "python", "python-3.x", "package", "python-import" ]
Python 3.5.2 Non-Ascii Character Output
39,190,727
<p>I'm running Python 3.5.2 and am trying to do some basic stuff with unicode and UTF-8. I'm currently just trying to output non-ASCII characters and am unable to do so. For example, this:</p> <pre><code>ddd = '\u0144' print(ddd) </code></pre> <p>gives me a Unicode encode error, telling me that the character maps to ...
1
2016-08-28T11:20:40Z
39,190,905
<p>PM 2Ring, typing in <code>chcp 65001</code> in command prompt did the trick. Thanks!</p>
1
2016-08-28T11:45:03Z
[ "python", "unicode", "utf-8", "character-encoding", "non-ascii-characters" ]
SQLAlchemy / MySQL Deadlocks on serialized access
39,190,752
<p>I have a big problem with a deadlock in an InnoDB table used with sqlalchemy. </p> <blockquote> <p>sqlalchemy.exc.InternalError: (mysql.connector.errors.InternalError) 1213 (40001): Deadlock found when trying to get lock; try restarting transaction.</p> </blockquote> <p>I have already serialized the access, but ...
0
2016-08-28T11:24:33Z
39,231,620
<p>Finally I solved my problem. It's all in the documentation, but I have to understand it first. </p> <blockquote> <p>Always be prepared to re-issue a transaction if it fails due to deadlock. Deadlocks are not dangerous. Just try again.</p> <p>Source: <a href="http://dev.mysql.com/doc/refman/5.7/en/innodb-de...
0
2016-08-30T15:30:37Z
[ "python", "mysql", "sqlalchemy", "deadlock" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1...
0
2016-08-28T11:32:02Z
39,190,836
<p>IIRC, it's far easier to iteratively check "Does it have a square root? Does it have a cube root? Does it have a fourth root? ..." You will very quickly get to the point where putative roots have to be between <code>1</code> and <code>2</code>, at which point you can stop.</p>
5
2016-08-28T11:35:44Z
[ "python", "algorithm", "python-3.x" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1...
0
2016-08-28T11:32:02Z
39,191,055
<p>Try this Newton's method:</p> <pre><code>def NthRoot(k, num): i, j = num, num+1 while i &lt; j: j = i t = (k-1) * j + num // pow(j, k-1) i = t // k return j print(NthRoot(3,125)) </code></pre> <p><a href="https://en.wikipedia.org/wiki/Newton&#39;s_method" rel="nofollow">https:/...
0
2016-08-28T12:01:09Z
[ "python", "algorithm", "python-3.x" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1...
0
2016-08-28T11:32:02Z
39,191,074
<p>a relevant improvement would be:</p> <pre><code>import math def isPP(n): # first have a look at the length of n in binary representation ln = int(math.log(n)/math.log(2)) + 1 y = [] for i in range(n+1): if (i &lt;= 1): continue ...
0
2016-08-28T12:03:46Z
[ "python", "algorithm", "python-3.x" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1...
0
2016-08-28T11:32:02Z
39,191,163
<p>A number <em>n</em> is a perfect power if there exists a <em>b</em> and <em>e</em> for which <em>b</em>^<em>e</em> = <em>n</em>. For instance 216 = 6^3 = 2^3 * 3^3 is a perfect power, but 72 = 2^3 * 3^2 is not.</p> <p>The trick to determining if a number is a perfect power is to know that, if the number is a perfec...
0
2016-08-28T12:14:49Z
[ "python", "algorithm", "python-3.x" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1...
0
2016-08-28T11:32:02Z
39,197,064
<p>I think a better way would be implementing this "hack":</p> <pre><code>import math def isPP(n): range = math.log(n)/math.log(2) range = (int)(range) result = [] for i in xrange(n): if(i&lt;=1): continue exponent = (int)(math.log(n)/math.log(i)) for j in [exponent...
0
2016-08-29T00:32:53Z
[ "python", "algorithm", "python-3.x" ]
Use __init__ constructor as factory method
39,191,017
<p>I have a function which takes a factory method as an argument. Invoking the factory method will create an object. Now I thought that I could directly specify the constructor of the desired object/class <code>Fruit.__init__</code> as the factory method. But that does not work, since the <code>self</code> argument doe...
1
2016-08-28T11:56:29Z
39,191,060
<p>Just pass in the class itself:</p> <pre><code>&gt;&gt;&gt; make_snack_for_jim(Fruit) Making a fruit for Jim </code></pre> <p>This sets your <code>snack_factory</code> to <code>Fruit</code> inside of the <code>make_snack_for_jim</code>, which you then call with <code>snack_factory('Jim')</code></p>
4
2016-08-28T12:01:52Z
[ "python", "factory-pattern" ]
How to speed up a recursive algorithm
39,191,056
<p>I'm trying to solve the Hackerrank challenge <a href="https://www.hackerrank.com/challenges/game-of-stones-1">Game of Stones</a>, a (shortened) problem statement of which is copied below.</p> <p><a href="http://i.stack.imgur.com/Vqgl1.png"><img src="http://i.stack.imgur.com/Vqgl1.png" alt="enter image description h...
6
2016-08-28T12:01:10Z
39,191,123
<p>It seems from the problem description that you are able to keep the intermediate and final results from each calculation to use in later calculations. If that is so, a recursive algorithm is not optimal. Instead, use a dynamic programming style.</p> <p>In other words, keep a global array that stores the results fro...
6
2016-08-28T12:10:16Z
[ "python", "algorithm" ]
How to speed up a recursive algorithm
39,191,056
<p>I'm trying to solve the Hackerrank challenge <a href="https://www.hackerrank.com/challenges/game-of-stones-1">Game of Stones</a>, a (shortened) problem statement of which is copied below.</p> <p><a href="http://i.stack.imgur.com/Vqgl1.png"><img src="http://i.stack.imgur.com/Vqgl1.png" alt="enter image description h...
6
2016-08-28T12:01:10Z
39,191,528
<p>Following <a href="http://stackoverflow.com/users/6246044/rory-daulton">Rory Daulton</a>'s advice to use dynamic programming, I rewrote the <code>which_player_wins</code> method as follows:</p> <pre><code># The lines below are for the Hackerrank submission # T = int(raw_input().strip()) # ns = [int(raw_input().stri...
0
2016-08-28T12:59:10Z
[ "python", "algorithm" ]
How to speed up a recursive algorithm
39,191,056
<p>I'm trying to solve the Hackerrank challenge <a href="https://www.hackerrank.com/challenges/game-of-stones-1">Game of Stones</a>, a (shortened) problem statement of which is copied below.</p> <p><a href="http://i.stack.imgur.com/Vqgl1.png"><img src="http://i.stack.imgur.com/Vqgl1.png" alt="enter image description h...
6
2016-08-28T12:01:10Z
39,193,031
<p>Your solution would work (though very slowly) if you had infinite recursion levels available. But since you're not re-using already calculated results you are very quickly hitting Python's recursion limit. One good solution, as suggested above, is to re-write the code using a non-recursive algorithm. </p> <p>Alter...
2
2016-08-28T15:47:54Z
[ "python", "algorithm" ]
pandas merge columns in same dataframe
39,191,066
<p>I have dataframe with 4 columns. </p> <pre><code> Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5...
0
2016-08-28T12:02:33Z
39,191,125
<p>Okay, maybe this might help:</p> <pre><code>In [571]: df Out[571]: Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5 Item11 Value11 Item12 Valu...
2
2016-08-28T12:10:26Z
[ "python", "pandas" ]
pandas merge columns in same dataframe
39,191,066
<p>I have dataframe with 4 columns. </p> <pre><code> Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5...
0
2016-08-28T12:02:33Z
39,192,670
<pre><code>df.columns = pd.MultiIndex.from_product( [['One', 'Two'], ['Column1', 'Column2']]) df.stack(0).reset_index(drop=True) </code></pre> <p><a href="http://i.stack.imgur.com/Eb8GR.png" rel="nofollow"><img src="http://i.stack.imgur.com/Eb8GR.png" alt="enter image description here"></a></p>
1
2016-08-28T15:09:35Z
[ "python", "pandas" ]
pandas merge columns in same dataframe
39,191,066
<p>I have dataframe with 4 columns. </p> <pre><code> Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5...
0
2016-08-28T12:02:33Z
39,194,119
<p>You can also treat the two distinct groupings as separate DataFrames by using the subcolumns and renaming the Column3 and Column4 on the fly:</p> <pre><code>&gt;&gt;&gt; df Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value...
1
2016-08-28T17:44:26Z
[ "python", "pandas" ]
Complicated refer to another table
39,191,088
<p>I have dataframe shown in below: column name 'Types'shows each types dified </p> <p>I would like to add another column named 'number' defined as below.</p> <pre><code>df=pd.DataFrame({'Sex':['M','F','F','M'],'Age':[30,31,33,32],'Types':['A','C','B','D']}) Out[8]: Age Sex Types 0 30 M A 1 31 F ...
2
2016-08-28T12:05:43Z
39,191,227
<p>I suggest reshaping your male and female tables:</p> <pre><code>males = (table_M.stack().to_frame('number').assign(Sex='M').reset_index() .rename(columns={'Age(male)': 'Age', 'level_1': 'Types'})) females = (table_F.stack().to_frame('number').assign(Sex='F').reset_index() .rename(...
5
2016-08-28T12:22:44Z
[ "python", "pandas", "dataframe" ]
Complicated refer to another table
39,191,088
<p>I have dataframe shown in below: column name 'Types'shows each types dified </p> <p>I would like to add another column named 'number' defined as below.</p> <pre><code>df=pd.DataFrame({'Sex':['M','F','F','M'],'Age':[30,31,33,32],'Types':['A','C','B','D']}) Out[8]: Age Sex Types 0 30 M A 1 31 F ...
2
2016-08-28T12:05:43Z
39,191,401
<p>Another way to do this:</p> <pre><code>In [60]: df['numbers'] = df.apply(lambda x: table_F.loc[[x.Age]][x.Types].iloc[0] if x.Sex == 'F' else table_M.loc[[x.Age]][x.Types].iloc[0], axis = 1) In [60]: df Out[60]: Age Sex Types numbers 0 30 M A 0 1 31 F C 27 2 33 F B 3...
1
2016-08-28T12:44:09Z
[ "python", "pandas", "dataframe" ]
Complicated refer to another table
39,191,088
<p>I have dataframe shown in below: column name 'Types'shows each types dified </p> <p>I would like to add another column named 'number' defined as below.</p> <pre><code>df=pd.DataFrame({'Sex':['M','F','F','M'],'Age':[30,31,33,32],'Types':['A','C','B','D']}) Out[8]: Age Sex Types 0 30 M A 1 31 F ...
2
2016-08-28T12:05:43Z
39,192,535
<p>It's easier if you two tables are combined such that you can access the <code>'Sex'</code> via an <code>apply</code>.</p> <pre><code>table = pd.concat([table_F, table_M], axis=1, keys=['F', 'M']) accessor = lambda row: table.loc[row.Age, (row.Sex, row.Types)] df['number'] = df.apply(accessor, axis=1) df </code></p...
4
2016-08-28T14:54:41Z
[ "python", "pandas", "dataframe" ]
How to create Panda Dataframe from csv that is compressed in tar.gz?
39,191,111
<p>How can I create the pandas DataFrame from csv file that's compressed in tar.gz? I found this code which does that but with zip file. What should I change in the following code to make it work with tar.gz without downloading the tar.gz and csv file. </p> <pre><code>import pandas, requests, zipfile, StringIO r =req...
0
2016-08-28T12:08:47Z
39,191,292
<p>Try simply supply your <code>.tar.gz</code> file as the file name<br> to <code>read_csv</code> and it will automatically decompress and open it, <br> since this is the default behavior for <code>gz</code> files.</p> <p>Make sure the extension is in lower case.</p>
0
2016-08-28T12:30:29Z
[ "python", "csv", "pandas", "gzip", "tar" ]
How to create Panda Dataframe from csv that is compressed in tar.gz?
39,191,111
<p>How can I create the pandas DataFrame from csv file that's compressed in tar.gz? I found this code which does that but with zip file. What should I change in the following code to make it work with tar.gz without downloading the tar.gz and csv file. </p> <pre><code>import pandas, requests, zipfile, StringIO r =req...
0
2016-08-28T12:08:47Z
39,191,488
<p>Can you try below for extracting tar.gz as below :</p> <pre><code>import tarfile tar = tarfile.open(fname, "r:gz") tar.extractall() tar.close() </code></pre>
1
2016-08-28T12:55:11Z
[ "python", "csv", "pandas", "gzip", "tar" ]
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "story" does not exist
39,191,127
<p>So this is my code below. I'm trying to create a database, with one story table. The input comes from the html input part</p> <pre><code>from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy from flask import request, redirect, url_for app = Flask(__name__) password = input("Your databas...
-1
2016-08-28T12:10:44Z
39,191,197
<p>Have you followed the <a href="http://flask-sqlalchemy.pocoo.org/2.1/quickstart/" rel="nofollow">quickstart guide</a> for Flask and sqlalchemy? Anyway, on the guide you will notice that it says to do this:</p> <blockquote> <p>To create the initial database, just import the db object from an interactive Python ...
0
2016-08-28T12:19:07Z
[ "python", "flask", "flask-sqlalchemy" ]
Django Query - How to use the objects.filter results
39,191,168
<p>If I use the following code it works perfectly:</p> <pre><code>campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] for x in campaignnoquery: test2 = x.campaignno </code></pre> <p>However, when I try:</p> <pre><code>campaignnoquery = UserSelection.objects.filter(user=349).orde...
-1
2016-08-28T12:15:38Z
39,191,222
<p><code>campaignnoquery</code> is, as the error says, a <code>QuerySet</code> object (in this case it holds <code>UserSelection</code> instances). </p> <p>Your error is treating it as an instance of a single <code>UserSelection</code> object.</p> <p>Are you sure this <code>filter</code> will always return a single o...
1
2016-08-28T12:21:47Z
[ "python", "mysql", "django" ]
Django Query - How to use the objects.filter results
39,191,168
<p>If I use the following code it works perfectly:</p> <pre><code>campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] for x in campaignnoquery: test2 = x.campaignno </code></pre> <p>However, when I try:</p> <pre><code>campaignnoquery = UserSelection.objects.filter(user=349).orde...
-1
2016-08-28T12:15:38Z
39,191,224
<p>You are referencing the wrong object! </p> <p>When looping through campaignnoquery, <strong><em>x</em></strong> becomes campaignnoquery[0], campaignnoquery[1], etc... </p> <p>Try referencing it like this:</p> <pre><code>test1 = campaignnoquery[0].campaignno </code></pre>
1
2016-08-28T12:21:55Z
[ "python", "mysql", "django" ]
Sending nested json data with Python requests and in x-www-form-urlencoded
39,191,187
<p>I cannot figure out how to do this. Basically one particular API is asking for </p> <p><code>'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'</code></p> <p>yet they want the form data to be like this:</p> <pre><code>stockLevels=[ { "SKU": "sample string 1", "LocationId": "de0f1890-0c49...
0
2016-08-28T12:18:12Z
39,191,337
<p>After mining this <a href="https://github.com/LinnSystems/LinnworksNetSDK" rel="nofollow">GitHub repo's examples</a>, their approach seems to be the following:</p> <ol> <li>The body is, indeed, <code>x-www-form-urlencoded</code></li> <li>Complex parameters are JSON strings encoded for <code>x-www-form-urlencoded</c...
1
2016-08-28T12:35:31Z
[ "python", "json", "python-requests" ]
How to get random bounding boxes from image? (python)
39,191,221
<p>I have a batch of images and I open each one using the open function with mode 'rb' and then I read each one using read function. Now I want to get 50 random bounding boxes from each image and read each bounding box again with open and read functions. Is there any simple way to do it?</p>
0
2016-08-28T12:21:43Z
39,191,845
<p>Here's a possible solution:</p> <pre><code>from random import randint from PIL import Image def random_bbox(bbox): v = [randint(0, v) for v in bbox] left = min(v[0], v[2]) upper = min(v[1], v[3]) right = max(v[0], v[2]) lower = max(v[1], v[3]) return [left, upper, right, lower] filename =...
0
2016-08-28T13:37:06Z
[ "python", "image", "bounding-box" ]
Python assign value and use on same line
39,191,276
<p>I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: </p> <p><code>zip(l=[1,2,3,4,5],l[1:])</code> </p> <p>So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function c...
3
2016-08-28T12:28:43Z
39,191,350
<p>Here is one hack, but not pythonic. Actually since all you need is creating an object in global namespace you can simply update the namespace by your intended object.</p> <pre><code>&gt;&gt;&gt; zip(globals().update(a=[1, 2, 3]) or a, a[1:]) [(1, 2), (2, 3)] </code></pre> <p>Since the <code>update()</code> attribu...
1
2016-08-28T12:37:18Z
[ "python", "assign" ]
Python assign value and use on same line
39,191,276
<p>I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: </p> <p><code>zip(l=[1,2,3,4,5],l[1:])</code> </p> <p>So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function c...
3
2016-08-28T12:28:43Z
39,191,500
<p>If this is a code golf thing so it <strong>must</strong> be a single statement, then this works in Python 2:</p> <pre><code>print[zip(l,l[1:])for l in[[1,2,3,4,5]]][0] </code></pre> <p><strong>output</strong></p> <pre><code>[(1, 2), (2, 3), (3, 4), (4, 5)] </code></pre> <p>Otherwise, </p> <pre><code>l=[1,2,3,4,...
2
2016-08-28T12:56:03Z
[ "python", "assign" ]
Python assign value and use on same line
39,191,276
<p>I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: </p> <p><code>zip(l=[1,2,3,4,5],l[1:])</code> </p> <p>So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function c...
3
2016-08-28T12:28:43Z
39,191,611
<p>You can use lambdas and default arguments to code golf this. Stressing that this shouldn't be used in production code, but just demonstrating what is possible in python.</p> <pre><code>(lambda l=[1, 2, 3]: zip(l, l[1:]))() </code></pre>
2
2016-08-28T13:10:24Z
[ "python", "assign" ]
Python assign value and use on same line
39,191,276
<p>I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: </p> <p><code>zip(l=[1,2,3,4,5],l[1:])</code> </p> <p>So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function c...
3
2016-08-28T12:28:43Z
39,191,691
<p>Of course, you can always do this:</p> <pre><code>l = range(1, 6); zip(l, l[1:]) </code></pre> <p>but I guess that's not what you wanted. :-)</p> <p>There is a relatively clean way</p> <pre><code>(lambda l: zip(l, l[1:]))(range(1, 6)) </code></pre> <p>BTW that function is defined in <a href="https://docs.python...
1
2016-08-28T13:19:27Z
[ "python", "assign" ]
Python graph from txt(csv) file and there are 5 columns, How Can I pick 3rd or 4th columns for y axis?
39,191,448
<p><a href="http://i.stack.imgur.com/BCfNp.png" rel="nofollow">enter image description here</a>I am studying Python matplotlib. I have txt file which is including 4 columns.</p> <p>But I would like to select column 3rd or 4th one from txt.</p> <p>I tried and studied but there are so many errors in my coding. I am a...
0
2016-08-28T12:50:22Z
39,193,884
<p>Here is a working example of how you can do it. The data in <code>data.txt</code> is as in your first example. I use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow">np.loadtxt</a> to load the text file. The optional arguments I raise are: 1) <code>unpack=True</code>...
0
2016-08-28T17:18:33Z
[ "python", "mysql", "date", "matplotlib", "graph" ]
How to group a data frame while containing information about two rows?
39,191,508
<p>I'm new to Python and I hope someone can help me with this performance issue. My data looks like:</p> <pre><code> TIMESTAMP A 34 2050-09-08 03:00:00 EST 3.0 40 2050-09-08 07:00:00 EST 3.0 67 2050-09-08 17:00:00 EST 6.0 84 2050-09-08 23:00:00 EST 6.0 89 2050-09-09 01:00:00 EST ...
1
2016-08-28T12:56:58Z
39,192,395
<p>This should be helpful. Use lots of <code>shift</code> and then use <code>groupby</code> + <code>agg</code>.</p> <pre><code>df.loc[df.A &lt; df.A.shift(-1), 'State'] = 'I' df.loc[df.A &gt; df.A.shift(-1), 'State'] = 'D' df.loc[df.A == df.A.shift(-1).ffill(), 'State'] = 'S' df['StateGroup'] = (df.State != df.State....
0
2016-08-28T14:38:12Z
[ "python", "pandas", "dataframe", "timestamp", "group" ]
Page not found (404) error on django
39,191,613
<p>I am trying to get price value as soon as product is selected in sale form. There is a sale form which has field of price, quantity and product. When user selects for product, the price of that product should be shown to the input box of price. For that i have used ajax. </p> <blockquote> <p>But i am getting an e...
0
2016-08-28T13:10:43Z
39,191,759
<p>Your URL pattern doesn't end with a slash, but your Ajax request is for a URL that does end with a slash. Fix one or the other; probably better for consistency to ensure that the pattern has a slash.</p> <pre><code>r'^price/(?P&lt;pk&gt;\d+)/$' </code></pre>
2
2016-08-28T13:27:46Z
[ "javascript", "python", "ajax", "django", "django-views" ]
python bokeh, how to make a correlation plot?
39,191,653
<p>How can I make a correlation heatmap in Bokeh?</p> <pre><code>import pandas as pd import bokeh.charts df = pd.util.testing.makeTimeDataFrame(1000) c = df.corr() p = bokeh.charts.HeatMap(c) # not right # try to make it a long form # (and it's ugly in pandas to use 'index' in melt) c['x'] = c.index c = pd.melt(c,...
0
2016-08-28T13:15:50Z
39,195,150
<p>If you want that level of control, I have to suggest using the (only slightly) lower level <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/plotting.html" rel="nofollow"><code>bokeh.plotting</code> interface</a>. You can see an example of a categorical heatmap generated using this interface in the gallery:...
2
2016-08-28T19:46:46Z
[ "python", "heatmap", "bokeh" ]
I want to toggle a real pushbutton and display it on tkinter GUI
39,191,725
<p>I want to toggle a pushbutton and show its changes on a label using tkinter.</p> <p>If I press the button it shows "on" on the label and when I press again it shows "off" on the label</p> <p>So I try these codes and If I'm trying the wrong code please help me write the correct using tkinter.</p> <p>I have a probl...
0
2016-08-28T13:23:52Z
39,195,269
<p>Your problem is recognizing button down and button up events. Your OS mouse driver does this for your mouse buttons. If your GPIO module does not do this for you, you will have to detect these events by comparing the current state to the previous state. (I am ignoring here any possible need to 'de-bounce' the butt...
0
2016-08-28T20:00:54Z
[ "python", "python-2.7", "tkinter", "raspberry-pi", "raspberry-pi2" ]
flask - sqlalchemy execute update where id=3
39,191,853
<p>How can I update <strong>column email</strong> from user table <strong>where id=3</strong>?</p> <pre><code>from sqlalchemy import update @app.route('/testupdate/') def testupdate(): db.session.execute(update(user, values={user.email: "za@bcdef"})) db.session.commit() return 'done' </code></pre>
-1
2016-08-28T13:37:28Z
39,192,400
<pre><code>stmt = user.update().where(user.c.id==3).values(email="za@bcdef") db.session.execute(stmt) </code></pre> <p>see examples in <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/dml.html#sqlalchemy.sql.expression.update" rel="nofollow">documentation</a></p>
0
2016-08-28T14:38:26Z
[ "python", "orm", "sqlalchemy", "execute" ]
How to use TextInput widget with ModelChoiceField in Django forms?
39,191,861
<p>In Django, the <code>ChoiceField</code> or <code>ModelChoiceField</code> represent the data in a <code>Select</code> widget. This is helpful when the list of objects is small. However it is extremely difficult to manage (for the end-user) if the number of objects are in thousands.</p> <p>To eliminate the said probl...
0
2016-08-28T13:38:32Z
39,196,428
<p>You can easily do that in the form clean() method.</p> <p>I.e.</p> <pre><code>from django.shortcuts import get_object_or_404 class SkuForm(forms.Form): sku = forms.CharField(required=True) extra_field = forms.CharField(required=True) def clean(self): # If you're on Python 2.x, change super() ...
1
2016-08-28T22:38:34Z
[ "python", "django", "forms" ]
How to use TextInput widget with ModelChoiceField in Django forms?
39,191,861
<p>In Django, the <code>ChoiceField</code> or <code>ModelChoiceField</code> represent the data in a <code>Select</code> widget. This is helpful when the list of objects is small. However it is extremely difficult to manage (for the end-user) if the number of objects are in thousands.</p> <p>To eliminate the said probl...
0
2016-08-28T13:38:32Z
39,304,229
<p>In my case, I had to change the <code>sku_number</code> field to Product object's <code>id</code>. This had to be done before <code>clean()</code>. As seen in <a href="http://stackoverflow.com/a/11083656/433587">this answer</a>, <code>__init__()</code> should be used to modify data before it reaches <code>clean()</c...
0
2016-09-03T07:06:06Z
[ "python", "django", "forms" ]
Class object has no attribute tk?
39,191,892
<p>I am fairly new to python and with the help of tutorials I am trying to create a calculator but got stuck due to an error which I am unable to correct which occurs when I press a number button</p> <pre><code>from tkinter import * root=Tk() root.title("Yuvi's CAl") global char class cal(): def __init__(self): ...
1
2016-08-28T13:41:57Z
39,192,290
<p>There are several issues with your code first you should remove hiding your global vars within your <code>__init__</code> as it creates two windows and only running <code>mainloop</code> for one of them. In addition you overwrite <code>self.string</code> with the <code>StringVar</code> class object after first creat...
2
2016-08-28T14:25:31Z
[ "python", "tkinter", "python-3.4" ]
Reverse for 'detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/$']
39,191,917
<p>My traceback:</p> <pre><code>File "D:\virtualEnv\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) Fi...
-1
2016-08-28T13:44:02Z
39,191,959
<p>Your <code>get_absolute_url</code> method passes a <code>kwarg</code> called <code>pk</code>, but your URL pattern expects an argument called <code>album_id</code>. </p>
0
2016-08-28T13:49:18Z
[ "python", "django" ]
Mouse X & Y positions for get_rect.collidepoint in pygame
39,192,125
<p>I am trying to create a click event in PyGame but I am facing an error:</p> <pre class="lang-none prettyprint-override"><code>AttributeError: 'NoneType' object has no attribute 'get_rect' </code></pre> <p>The code:</p> <pre><code>mouse_pos = pygame.mouse.get_pos() mouse_pressed = pygame.mouse.get_pressed() if mo...
1
2016-08-28T14:06:47Z
39,192,933
<p>Based on the information provided, <code>button</code> doesn't return anything. It returns <code>None</code>.</p> <p>According to your previous <a href="http://stackoverflow.com/questions/39190253/pygame-button-cant-seek-in-this-data-source">question</a> your function <code>button</code> looks like this:</p> <pre>...
0
2016-08-28T15:37:11Z
[ "python", "pygame" ]
How to send a string with spaces from Python to Bash sub-process as a single value?
39,192,127
<p>I'm trying to send a variable from a python script to a bash script. I'm using <code>popen</code> like as shown below:</p> <pre><code>subprocess.Popen(["bash", "-c", ". mainGui_functions.sh %d %s" % (commandNum.get(), entryVal)]) </code></pre> <p>However, <code>entryVal</code> can sometimes contain one or more whi...
2
2016-08-28T14:07:02Z
39,192,204
<p>Simple solution #1: You do it the exact same way you'd do it if you were typing the input on the commandline; put it in quotes:</p> <pre><code>subprocess.Popen(["bash", "-c", ". mainGui_functions.sh {} '{}'".format(commandNum.get(), entryVal)]) </code></pre> <p>Simple solution #2: If <code>mainGui_functions.sh</co...
2
2016-08-28T14:17:09Z
[ "python", "bash", "subprocess" ]
How to send a string with spaces from Python to Bash sub-process as a single value?
39,192,127
<p>I'm trying to send a variable from a python script to a bash script. I'm using <code>popen</code> like as shown below:</p> <pre><code>subprocess.Popen(["bash", "-c", ". mainGui_functions.sh %d %s" % (commandNum.get(), entryVal)]) </code></pre> <p>However, <code>entryVal</code> can sometimes contain one or more whi...
2
2016-08-28T14:07:02Z
39,192,210
<p>Put quotes around it in your bash command line – e.g.,</p> <pre><code>subprocess.Popen(['bash', '-c', '. mainGui_functions.sh %d "%s"' % (commandNum.get(), entryVal)]) </code></pre>
0
2016-08-28T14:17:52Z
[ "python", "bash", "subprocess" ]
Scrape All External Links from Multiple URLs in a Text File with Scrapy
39,192,171
<p>I am new to Scrapy and Python and as such I am a beginner. I want to be able to have Scrapy read a text file with a seed list of around 100k urls, have Scrapy visit each URL, and extract all external URLs (URLs of Other Sites) found on each of those Seed URLs and export the results to a separate text file.</p> <p>S...
-1
2016-08-28T14:12:56Z
39,205,016
<p>You should use: <br> 1. start_requests function for reading list of urls. <br> 2. css or xpath selector for all "a" html elements.</p> <pre><code>from scrapy import Spider class YourSpider(Spider): name = "your_spider" def start_requests(self): with open('your_input.txt', 'r') as f: # read the li...
0
2016-08-29T11:19:47Z
[ "python", "url", "web-scraping", "scrapy", "web-crawler" ]
RTSP: cannot get session identifier
39,192,256
<p>I am trying to control an ip cam using a python script (I can see the stream with VLC or mplayer).</p> <p>After received OPTIONS and DESCRIBE informations, every SETUP I try give me an error:</p> <pre><code>SETUP rtsp://192.168.0.41:554/xxxxxx RTSP/1.0 CSeq: 3 Transport: RTP/AVP/UDP;unicast;client_port=3056-3057 ...
0
2016-08-28T14:22:03Z
39,212,075
<p>Example from RTSP rfc <a href="https://www.ietf.org/rfc/rfc2326.txt" rel="nofollow">https://www.ietf.org/rfc/rfc2326.txt</a>:</p> <pre><code>S-&gt;C RTSP/1.0 200 OK CSeq: 1 Content-base: rtsp://foo.com/test.wav/ Content-type: application/sdp Content-length: 48 v=0 o=- 872653257...
0
2016-08-29T17:40:32Z
[ "python", "streaming", "rtsp", "onvif" ]