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
Python2 - Summing "for" loop output
39,073,840
<p>I'm trying to make a script that takes a balances of multiple addresses from a json file and adds them together to make a final balance.</p> <p>This is the code so far -</p> <pre><code>import json from pprint import pprint with open('hd-wallet-addrs/addresses.json') as data_file: data = json.load(data_file) for balance in data: print balance['balance'] </code></pre> <p><br></p> <p><strong>This is what's in the json file:</strong></p> <pre><code>[ { "addr": "1ERDMDducUsmrajDpQjoKxAHCqbTMEU9R6", "balance": "21.00000000" }, { "addr": "1DvmasdbaFD7Tj6diu6D8WVc1Bkbj7jYRM", "balance": "0.30000000" }, { "addr": "18xkkUi7qagUuBAg572UsmDKcZTP5zxaDB", "balance": "0.80000000" }, { "addr": "1MmTDCsySdsWRVbNFwXBy2APW5kGsynkaA3", "balance": "0.005" }, ] </code></pre> <p>The output is like this:</p> <pre><code>21 0.3 0.8 0.005 </code></pre> <p>How should I edit my code to add the numbers together?</p>
0
2016-08-22T07:42:30Z
39,073,914
<p>Actually add them together...</p> <pre><code>total = 0 for balance in data: total += float(balance['balance']) print total </code></pre> <p>Or using <code>sum</code>:</p> <pre><code>print sum(float(temp_balance['balance']) for temp_balance in data) </code></pre>
2
2016-08-22T07:46:43Z
[ "python", "json", "python-2.7", "for-loop" ]
Python2 - Summing "for" loop output
39,073,840
<p>I'm trying to make a script that takes a balances of multiple addresses from a json file and adds them together to make a final balance.</p> <p>This is the code so far -</p> <pre><code>import json from pprint import pprint with open('hd-wallet-addrs/addresses.json') as data_file: data = json.load(data_file) for balance in data: print balance['balance'] </code></pre> <p><br></p> <p><strong>This is what's in the json file:</strong></p> <pre><code>[ { "addr": "1ERDMDducUsmrajDpQjoKxAHCqbTMEU9R6", "balance": "21.00000000" }, { "addr": "1DvmasdbaFD7Tj6diu6D8WVc1Bkbj7jYRM", "balance": "0.30000000" }, { "addr": "18xkkUi7qagUuBAg572UsmDKcZTP5zxaDB", "balance": "0.80000000" }, { "addr": "1MmTDCsySdsWRVbNFwXBy2APW5kGsynkaA3", "balance": "0.005" }, ] </code></pre> <p>The output is like this:</p> <pre><code>21 0.3 0.8 0.005 </code></pre> <p>How should I edit my code to add the numbers together?</p>
0
2016-08-22T07:42:30Z
39,074,111
<pre><code>balance_prev = 0 balance_sum = 0 for balance in data: balance_sum = float(balance_prev) + float(balance['balance']) balance_prev = balance_sum print balance['balance'] </code></pre> <p>hope this help!!</p>
0
2016-08-22T07:59:09Z
[ "python", "json", "python-2.7", "for-loop" ]
trying to support python code in tcl
39,073,847
<p>I'm new to all of this thing, and so please excuse me if i kinda did something stupid here. Treat me and explain to me as if i'm a total noob would be helpful.</p> <p>I have a simple function written in python, filename <code>a.pyx</code>:-</p> <pre><code>#!/usr/bin/env python import os import sys def get_syspath(): ret = sys.path print "Syspath:{}".format(ret) return ret </code></pre> <p>I want it to be able to be used by tcl.</p> <p>I read thru the cython page, and followed.</p> <p>I ran this:-</p> <pre><code>cython -o a.c a.pyx </code></pre> <p>I then ran this command to generate the object file <code>a.o</code>:-</p> <pre><code>gcc -fpic -c a.c -I/usr/local/include -I/tools/share/python/2.7.1/linux64/include/python2.7 </code></pre> <p>And then ran this to generate the so file <code>a.so</code>:-</p> <pre><code>gcc -shared a.o -o a.so </code></pre> <p>when i load it from a tclsh, it failed.</p> <pre><code>$tclsh % load ./a.so couldn't load file "./a.so": ./a.so: undefined symbol: PyExc_RuntimeError </code></pre> <p>Am i taking the correct path here? If not, can please explain to me what went wrong, and what should I be doing?</p> <p>Thanks in advance.</p>
1
2016-08-22T07:42:46Z
39,076,034
<p>The object code needs to be linked to the libraries it depends on when you're building the loadable library. This means adding appropriate <code>-l...</code> options and possibly some <code>-L...</code> options as well. I'm guessing that the option will be something like <code>-lpython27</code> or something like that (which links to a <code>libpython27.so</code> somewhere on your library search path; the library search path is modified with the <code>-L...</code> options), <strong><em>but I don't know</em></strong>. Paths will depend a lot on exactly how your system is set up and experimentation is likely required on your half.</p> <p>It still probably won't work as a loadable library in Tcl. Tcl expects there to be a library initialisation function (in your case, it will look for <code>A_Init</code>) that takes a <code>Tcl_Interp*</code> as its only argument so that the library can install the commands it defines into the Tcl interpreter context. I would be astonished if Python made such a thing by default. It's not failing with that for you yet because the failures are still happening during the internal <code>dlopen()</code> call and not the <code>dlsym()</code> call, but I can confidently predict that you'll still face them.</p> <p>The easiest way to “integrate” that sort of functionality is by running the command in a subprocess.</p> <p>Here's the Python code you might use:</p> <pre class="lang-python prettyprint-override"><code>import os import sys print sys.path </code></pre> <p>And here's the Tcl code to use it:</p> <pre class="lang-tcl prettyprint-override"><code>set syspath [exec python /path/to/yourcode.py] # If it is in the same directory as this script, use this: #set syspath [exec python [file join [file dirname [info script]] yourcode.py]] </code></pre> <p>It's not the most efficient way, but it's super-easy to make it work since you don't have to solve the compilation and linking of the two languages. It's <em>programmer-efficient</em>…</p>
2
2016-08-22T09:36:21Z
[ "python", "tcl", "cython", "swig" ]
trying to support python code in tcl
39,073,847
<p>I'm new to all of this thing, and so please excuse me if i kinda did something stupid here. Treat me and explain to me as if i'm a total noob would be helpful.</p> <p>I have a simple function written in python, filename <code>a.pyx</code>:-</p> <pre><code>#!/usr/bin/env python import os import sys def get_syspath(): ret = sys.path print "Syspath:{}".format(ret) return ret </code></pre> <p>I want it to be able to be used by tcl.</p> <p>I read thru the cython page, and followed.</p> <p>I ran this:-</p> <pre><code>cython -o a.c a.pyx </code></pre> <p>I then ran this command to generate the object file <code>a.o</code>:-</p> <pre><code>gcc -fpic -c a.c -I/usr/local/include -I/tools/share/python/2.7.1/linux64/include/python2.7 </code></pre> <p>And then ran this to generate the so file <code>a.so</code>:-</p> <pre><code>gcc -shared a.o -o a.so </code></pre> <p>when i load it from a tclsh, it failed.</p> <pre><code>$tclsh % load ./a.so couldn't load file "./a.so": ./a.so: undefined symbol: PyExc_RuntimeError </code></pre> <p>Am i taking the correct path here? If not, can please explain to me what went wrong, and what should I be doing?</p> <p>Thanks in advance.</p>
1
2016-08-22T07:42:46Z
39,107,455
<p>Maybe have a look at <a href="http://jfontain.free.fr/tclpython.htm" rel="nofollow" title="tclpython"><code>tclpython</code></a> or <a href="https://github.com/aidanhs/libtclpy" rel="nofollow" title="libtclpy"><code>libtclpy</code></a>.</p> <p>Both allow calling Python code from Tcl.</p> <p>But if you wanted to wrap things in a nicer way, e.g. have nicer already wrapped APIs, maybe you should also look at <a href="http://elmer.sourceforge.net/" rel="nofollow">Elmer</a>, which seems to aim at the task your attempting.</p>
1
2016-08-23T17:32:09Z
[ "python", "tcl", "cython", "swig" ]
_BaseServer__is_shut_down while running glass framework
39,073,853
<p>i am new to Glass framework i have installed glass server in in my ubuntu system when i run sample test application its return _BaseServer__is_shut_down error how can i resolve this issue and i already tried different port number but same issue .</p> <p>test.py</p> <pre><code>#!/usr/bin/env python from glass.HTTPServer import test try: print "Use Control-C to exit. In Windows, use Control-Break." test() except KeyboardInterrupt: pass </code></pre> <p>when i run this code i got error like </p> <pre><code>Serving HTTP on 0.0.0.0 port 8080 ... Traceback (most recent call last): File "HTTPServer.py", line 305, in &lt;module&gt; test() File "HTTPServer.py", line 300, in test httpd.serve_forever() File "/usr/lib/python2.7/SocketServer.py", line 223, in serve_forever self.__is_shut_down.clear() File "HTTPServer.py", line 265, in __getattr__ raise AttributeError(attr) AttributeError: _BaseServer__is_shut_down </code></pre>
3
2016-08-22T07:43:06Z
39,148,518
<p>I was not able to fix that issue, but the framework seems really old. I can reditect you to the simplest HTTP server existant, and easy too:</p> <p>Python 3 (prefered) using <a href="https://docs.python.org/3/library/http.server.html" rel="nofollow">http.server</a>:</p> <pre><code>import http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler httpd = socketserver.TCPServer(('', PORT), Handler) print('serving at port', PORT) httpd.serve_forever() </code></pre> <p>Python 2 using <a href="https://docs.python.org/2/library/simplehttpserver.html" rel="nofollow">SimpleHTTPServer</a>:</p> <pre><code>import SimpleHTTPServer import SocketServer PORT = 8000 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(('', PORT), Handler) print 'serving at port', PORT httpd.serve_forever() </code></pre>
0
2016-08-25T14:53:12Z
[ "python" ]
_BaseServer__is_shut_down while running glass framework
39,073,853
<p>i am new to Glass framework i have installed glass server in in my ubuntu system when i run sample test application its return _BaseServer__is_shut_down error how can i resolve this issue and i already tried different port number but same issue .</p> <p>test.py</p> <pre><code>#!/usr/bin/env python from glass.HTTPServer import test try: print "Use Control-C to exit. In Windows, use Control-Break." test() except KeyboardInterrupt: pass </code></pre> <p>when i run this code i got error like </p> <pre><code>Serving HTTP on 0.0.0.0 port 8080 ... Traceback (most recent call last): File "HTTPServer.py", line 305, in &lt;module&gt; test() File "HTTPServer.py", line 300, in test httpd.serve_forever() File "/usr/lib/python2.7/SocketServer.py", line 223, in serve_forever self.__is_shut_down.clear() File "HTTPServer.py", line 265, in __getattr__ raise AttributeError(attr) AttributeError: _BaseServer__is_shut_down </code></pre>
3
2016-08-22T07:43:06Z
39,223,671
<p>After doing some research inside the framework code I have found the next:</p> <p>The HTTPServer inside the package is a custom one with a <code>__getattr__</code> built-in set that is rising exceptions when an attribute that is not "is_secure" is accessed.</p> <pre><code># Code from HTTPServer.py def __getattr__(self, attr): if attr == "is_secure": return getattr(self.servertype.create_socket, "is_secure", False) raise AttributeError(attr) # This is the buggy statement </code></pre> <p>So in plain, any HTTPServer attribute (except "is_secure") which is accessed will irremediably raise an exception.</p> <p>I guess you have three options:</p> <ol> <li>Fix the test function in order to make it work properly</li> <li>Keep going without using the test function and trying to make that framework work</li> <li>Follow the Tiger-222 solution and stick to the <em>SimpleHTTPServer</em></li> </ol>
0
2016-08-30T09:27:09Z
[ "python" ]
Why Python script has to be executed 2 times to get complete output in the CSV file
39,073,877
<p>I have a simple Python script that writes a sub(CSV)file after reading a large CSV file.</p> <pre><code>import csv import os large_file = "D:\Total_data.csv" with open(large_file, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter='|') path = "D:/CSV_Files/" if not os.path.exists(path): os.makedirs(path) writer1 = csv.writer(open(path+"A1_subfile"+".csv", 'wb'), delimiter = '|') #writing data to the CSV file only if first column has value 'A1' for row in reader: if (row[0]=='A1'): writer1.writerow(row) csvfile.close() </code></pre> <p>The problem I am facing is that when I run the script for first time, some rows don't come in A1_subfile.csv file(say only 96 or 97 rows are shown out of 100 rows).</p> <p>When I run the exact SAME script for the second time, then all rows are shown in the subfile(now all 100 rows can be seen).</p> <p>Even if I wait for some minutes after executing for the first time, I don't get complete output in new CSV file. And if I simply execute code 2 times, I can see complete output immediately.</p> <p>I have searched, but couldn't get over this issue. Please help to overcome this.</p>
2
2016-08-22T07:44:25Z
39,076,047
<p>I was randomly trying many different ways to solve this issue, and interestingly I found that if we define a function for this code, and then call the function, the issue gets resolved.</p> <pre><code>def create_subfile(): """ now same code as in question""" create_subfile(); </code></pre> <p>Does anyone know the reason why a piece of code works fine when executed through a function call, and doesn't work when executed directly ?</p>
-1
2016-08-22T09:36:47Z
[ "python", "csv" ]
Template displays foreign key instead of CharField for disabled field
39,073,885
<p>I am using Django 1.97 and have the following models:</p> <pre><code>class Symbol(models.Model): symbol = models.CharField(max_length=15) # more fields class Position(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) symbol = models.ForeignKey(Symbol) # more fields def get_user_positions_qs(self, user): positions = Position.objects.all().select_related('symbol').filter(user=user).order_by('symbol') return positions </code></pre> <p>I need to display a modelform in a template for the logged in user's positions, but the <code>symbol</code> field needs to be disabled. So far I have the following in my view:</p> <pre><code>position = Position() form_class = PortfolioForm PositionModelFormSet = modelformset_factory(Position, fields=('symbol', 'various_other_fields'), form=form_class) def get(self, request): positions = self.position.get_user_positions_qs(user=request.user) position_formset = self.PositionModelFormSet(queryset=positions) return render(request, 'template.html', {'position_formset': position_formset}) </code></pre> <p>And the form:</p> <pre><code>class PortfolioForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PortfolioForm, self).__init__(*args, **kwargs) self.fields['symbol'].widget = forms.TextInput(attrs={'disabled': True}) class Meta: model = Position fields = ['symbol', 'various other fields'] </code></pre> <p>The problem is that when displaying the form, the <code>symbol</code> field only contains the foreign key id instead of the actual <code>symbol CharField</code> from the <code>symbol model</code>. If I change the form so that the <code>symbol</code> field is not disabled, then the <code>symbol</code> field in the template displays the correct value, however it then has a dropdown allowing the user to change the symbol which is not allowed.</p> <p>So my question is, how do I disable the <code>symbol</code> field in the template while continuing to display the <code>symbol</code> value found in the <code>CharField</code> from the <code>symbol model</code> (ie: not just the foreign key id pointing to that record). It appears that if you have a form that includes a field from another model, then trying to make that field disabled results in the field only displaying a foreign key instead of the actual value from the other table.</p>
0
2016-08-22T07:44:44Z
39,074,267
<p>The problem is that you are using a Textinput widget for a FKey field, which is treated as a lookup field by default. Why not just have it be a disabled dropdown field?</p> <pre><code>self.fields['symbol'].widget.attrs['disabled'] = 'disabled' </code></pre> <p><strong>Edit: Alternative solution</strong></p> <p>Based on your comment, here's another solution that <em>I think</em> should work:</p> <pre><code>class PortfolioForm(forms.ModelForm): symbol_text = forms.CharField() class Meta: fields = ('symbol', 'other fields') model = Position def __init__(self, *args, **kwargs): super(PortfolioForm, self).__init__(*args, **kwargs) self.fields['symbol_text'].widget.attrs['value'] = self.instance.symbol self.fields['symbol_text'].widget.attrs['disabled'] = 'disabled' </code></pre>
1
2016-08-22T08:08:33Z
[ "python", "django", "django-forms" ]
How to generate a matrix with circle of ones in numpy/scipy
39,073,973
<p>There are some signal generation helper functions in <a href="http://docs.scipy.org/doc/scipy/reference/signal.html#waveforms" rel="nofollow">python's scipy</a>, but these are only for 1 dimensional signal.</p> <p>I want to generate a 2-D ideal bandpass filter, which is a matrix of all zeros, with a circle of ones to remove some periodic noise from my image.</p> <p>I am now doing with:</p> <pre><code>def unit_circle(r): def distance(x1, y1, x2, y2): return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) d = 2*r + 1 mat = np.zeros((d, d)) rx , ry = d/2, d/2 for row in range(d): for col in range(d): dist = distance(rx, ry, row, col) if abs(dist - r) &lt; 0.5: mat[row, col] = 1 return mat </code></pre> <p>result:</p> <pre><code>In [18]: unit_circle(6) Out[18]: array([[ 0., 0., 0., 0., 1., 1., 1., 1., 1., 0., 0., 0., 0.], [ 0., 0., 1., 1., 0., 0., 0., 0., 0., 1., 1., 0., 0.], [ 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0.], [ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [ 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0.], [ 0., 0., 1., 1., 0., 0., 0., 0., 0., 1., 1., 0., 0.], [ 0., 0., 0., 0., 1., 1., 1., 1., 1., 0., 0., 0., 0.]]) </code></pre> <p>Is there a more direct way to generate a <code>matrix of circle of ones, all else zeros</code>?</p> <p>Edit: Python 2.7.12</p>
3
2016-08-22T07:50:22Z
39,074,620
<p>Here is a pure NumPy alternative that should run significantly faster and looks cleaner, imho. Basically, we vectorise your code by replacing built-in <code>sqrt</code> and <code>abs</code> with their NumPy alternatives and working on matrices of indices. </p> <p><strong>Updated</strong> to replace <code>distance</code> with <code>np.hypot</code>(courtesy of James K)</p> <pre><code>In [5]: import numpy as np In [6]: def my_unit_circle(r): ...: d = 2*r + 1 ...: rx, ry = d/2, d/2 ...: x, y = np.indices((d, d)) ...: return (np.abs(np.hypot(rx - x, ry - y)-r) &lt; 0.5).astype(int) ...: In [7]: my_unit_circle(6) Out[7]: array([[ 0., 0., 0., 0., 1., 1., 1., 1., 1., 0., 0., 0., 0.], [ 0., 0., 1., 1., 0., 0., 0., 0., 0., 1., 1., 0., 0.], [ 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0.], [ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [ 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0.], [ 0., 0., 1., 1., 0., 0., 0., 0., 0., 1., 1., 0., 0.], [ 0., 0., 0., 0., 1., 1., 1., 1., 1., 0., 0., 0., 0.]]) </code></pre> <p>Benchmarks</p> <pre><code>In [12]: %timeit unit_circle(100) 100 loops, best of 3: 17.7 ms per loop In [13]: %timeit my_unit_circle(100) 1000 loops, best of 3: 480 µs per loop </code></pre>
3
2016-08-22T08:27:50Z
[ "python", "numpy", "scipy", "signal-processing", "python-2.x" ]
How to generate a matrix with circle of ones in numpy/scipy
39,073,973
<p>There are some signal generation helper functions in <a href="http://docs.scipy.org/doc/scipy/reference/signal.html#waveforms" rel="nofollow">python's scipy</a>, but these are only for 1 dimensional signal.</p> <p>I want to generate a 2-D ideal bandpass filter, which is a matrix of all zeros, with a circle of ones to remove some periodic noise from my image.</p> <p>I am now doing with:</p> <pre><code>def unit_circle(r): def distance(x1, y1, x2, y2): return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) d = 2*r + 1 mat = np.zeros((d, d)) rx , ry = d/2, d/2 for row in range(d): for col in range(d): dist = distance(rx, ry, row, col) if abs(dist - r) &lt; 0.5: mat[row, col] = 1 return mat </code></pre> <p>result:</p> <pre><code>In [18]: unit_circle(6) Out[18]: array([[ 0., 0., 0., 0., 1., 1., 1., 1., 1., 0., 0., 0., 0.], [ 0., 0., 1., 1., 0., 0., 0., 0., 0., 1., 1., 0., 0.], [ 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0.], [ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [ 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0.], [ 0., 0., 1., 1., 0., 0., 0., 0., 0., 1., 1., 0., 0.], [ 0., 0., 0., 0., 1., 1., 1., 1., 1., 0., 0., 0., 0.]]) </code></pre> <p>Is there a more direct way to generate a <code>matrix of circle of ones, all else zeros</code>?</p> <p>Edit: Python 2.7.12</p>
3
2016-08-22T07:50:22Z
39,082,209
<p>Here's a vectorized approach -</p> <pre><code>def unit_circle_vectorized(r): A = np.arange(-r,r+1)**2 dists = np.sqrt(A[:,None] + A) return (np.abs(dists-r)&lt;0.5).astype(int) </code></pre> <p>Runtime test -</p> <pre><code>In [165]: %timeit unit_circle(100) # Original soln 10 loops, best of 3: 31.1 ms per loop In [166]: %timeit my_unit_circle(100) #@Eli Korvigo's soln 100 loops, best of 3: 2.68 ms per loop In [167]: %timeit unit_circle_vectorized(100) 1000 loops, best of 3: 582 µs per loop </code></pre>
2
2016-08-22T14:31:22Z
[ "python", "numpy", "scipy", "signal-processing", "python-2.x" ]
Weblogic WSLT in modular python script
39,074,123
<p>I'm creating a script to automate creation of JMS resources in a declarative way using <code>wslt.sh</code>. This way I just need to run <code>wslt.sh create_resources.py planned_resources.properties</code></p> <p>create_resources.py imports another module of mine <code>import include.jms as nmjms</code>. This include/jms.py calls <code>cd</code> and <code>cmo</code> of the WSLT.</p> <p>The problem is, calling <code>cd</code> doesn't change the state of <code>cmo</code> in the jms.py module, so that I can't execute context related commands on <code>cmo</code> after the <code>cd</code> invocation. This is frustating... </p>
0
2016-08-22T07:59:43Z
39,076,103
<p>First, create a module wl.py with the folowing code : </p> <pre><code># Caution: This file is part of the command scripting implementation. # Do not edit or move this file because this may cause commands and scripts to fail. # Do not try to reuse the logic in this file or keep copies of this file because this # could cause your scripts to fail when you upgrade to a different version. # Copyright (c) 2004,2014, Oracle and/or its affiliates. All rights reserved. """ This is WLST Module that a user can import into other Jython Modules """ from weblogic.management.scripting.utils import WLSTUtil import sys origPrompt = sys.ps1 theInterpreter = WLSTUtil.ensureInterpreter(); WLSTUtil.ensureWLCtx(theInterpreter) execfile(WLSTUtil.getWLSTCoreScriptPath()) execfile(WLSTUtil.getWLSTNMScriptPath()) execfile(WLSTUtil.getWLSTScriptPath()) execfile(WLSTUtil.getOfflineWLSTScriptPath()) exec(WLSTUtil.getOfflineWLSTScriptForModule()) execfile(WLSTUtil.getWLSTCommonModulePath()) theInterpreter = None sys.ps1 = origPrompt modules = WLSTUtil.getWLSTModules() for mods in modules: execfile(mods.getAbsolutePath()) jmodules = WLSTUtil.getWLSTJarModules() for jmods in jmodules: fis = jmods.openStream() execfile(fis, jmods.getFile()) fis.close() wlstPrompt = "false" </code></pre> <p>Next, import this module in your jms.py module and call wlst commands like this : wl.cd('...')</p>
1
2016-08-22T09:39:14Z
[ "python", "weblogic", "weblogic-10.x" ]
Django 1.10 Translation
39,074,285
<p>I was trying internationalization/localization in django. I am getting an error while i am trying to make the '.po' files using the command </p> <blockquote> <p>./manage.py makemessages</p> </blockquote> <p>relevant parts from settings.py</p> <pre><code>import os from django.utils.translation import ugettext_lazy as _ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'sampleproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n' ], }, }, ] WSGI_APPLICATION = 'sampleproject.wsgi.application' LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('fi-FI', _('Finnish')), ('en', _('English')), ] LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] </code></pre> <p>relevant parts from urls.py</p> <pre><code>urlpatterns += i18n_patterns( url(r'^$', home, name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^polls/', include('polls.urls')), ) </code></pre> <p>here is the traceback.</p> <pre><code>Traceback (most recent call last): File "./manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 361, in handle potfiles = self.build_potfiles() File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 393, in build_potfiles self.process_files(file_list) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 488, in process_files self.process_locale_dir(locale_dir, files) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 507, in process_locale_dir build_file.preprocess() File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 113, in preprocess content = templatize(src_data, self.path[2:]) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/utils/translation/__init__.py", line 214, in templatize return _trans.templatize(src, origin) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/utils/translation/trans_real.py", line 670, in templatize "%s (%sline %d)" % (t.contents, filemsg, t.lineno) SyntaxError: Translation blocks must not include other block tags: blocktrans count var|length as count (file htmlcov/_project_Myapps_for_sample_lib_python3_4_site-packages_django_templatetags_i18n_py.html, line 1073) </code></pre> <p>Dev Setup: Django 1.10 Python 3.4.5</p> <p>As this is my first question in SO, pardon me if there's any mistake :) Thanks in advance :)</p>
2
2016-08-22T08:09:37Z
39,092,078
<p>The error occurred because of the htmlcov folder which was generated while running the coverage script. </p> <p>Removed that folder and executed the following commands to generate the '.po' files.</p> <blockquote> <p>./manage.py makemessages -l fi</p> </blockquote> <p>and the following command to generate the '.mo' files.</p> <blockquote> <p>./manage.py compilemessages</p> </blockquote>
1
2016-08-23T03:54:11Z
[ "python", "django", "translation" ]
When overwriting __init__ will I call __init__ of base class at the beginning or end?
39,074,292
<p>I have the following short example where I inherit a class <code>A</code> from <code>Base</code> and overwrite <code>__init__</code>. In the <code>__init__</code> the <code>Base.__init__</code> is called. </p> <pre><code>class A(Base): def __init__(self): super(A, self).__init__() ... my initialisation ... </code></pre> <p><strong>Is there a rule to call <code>__init__</code> of Base (when needed) first and then initialise the rest or should it be the other way round?</strong></p> <p>Sometimes I need to call <code>__init__</code> and then do the rest and other times I need it the other way round. There are also occasions where I have to write some initialisation, then call <code>__init__</code> of the base class and then do some final initialisation.</p> <p>Maybe giving an answer to myself: Read the documentation of the base class or if not available study the code.</p> <p><strong>Is there a way it should be or how do you document this?</strong></p>
0
2016-08-22T08:09:51Z
39,074,333
<p>No, there is no rule as to where to call it, or if you call it at all. Call it wherever it makes sense <em>to your specific situation</em>.</p> <p>Put differently, <code>super(A, self).__init__()</code> is <em>just another method call</em>, albeit one that specifically uses a method looked up from a base class. Treat it like any other method call you make, so call it <em>when you need to</em>.</p>
4
2016-08-22T08:11:39Z
[ "python", "oop", "override" ]
Kivy Gallary programm doesn't work when compiled as apk
39,074,335
<p>I wanted to make an kivy app, with a button, that opens the android gallary, when the button is clicked. So I wrote to code, that you can see down there, on qpython, and it worked. But when I wanted to ran it on my PC, I got the error message:</p> <pre><code> Traceback (most recent call last): File "main.py", line 35, in &lt;module&gt; from gallery import Gallary File "/home/gilgamesch/Apps/event/gallery.py", line 14, in &lt;module&gt; from android import activity ImportError: No module named android </code></pre> <p>(Yes, this is the whole error message)</p> <p>But I decided to give it a try anyway. So I compiled it with buildozer, installed and started it on my android phone, and the application started. It opened, I clicked on he button, and the gallary opened too, but as soon, as I choose an image, the programm crashed.</p> <p>Here is the main.py:</p> <pre><code>#-*-coding:utf8;-*- #qpy:2 #qpy:kivy from kivy.app import App from kivy.uix.button import Button from kivy.properties import StringProperty from gallery import Gallary class TestApp(App): path = StringProperty() def build(self): return Button(text='Hello QPython', on_release=self.open_g) def open_g(self, *args): self.g = Gallary() path = self.g.make_gallary(self.getstr) def getstr(self, path): self.path = path print self.path + 'in Gallary class' def on_pause(self): return True def on_resume(self): pass TestApp().run() </code></pre> <p>And here is my self made Gallary module:</p> <pre><code>#-*-coding:utf8;-*- #qpy:2 #qpy:kivy from jnius import autoclass from jnius import cast from android import activity class Gallary(object): def __init__(self, *args): self.mypath = '' # import the needed Java class self.PythonActivity = autoclass ('org.renpy.android.PythonActivity') self.Activity = autoclass('android.app.Activity') self.uri = autoclass('android.net.Uri') self.intent = autoclass('android.content.Intent') self.MediaStore = autoclass('android.provider.MediaStore') self.Cursor = autoclass('android.database.Cursor') # Value of MediaStore.Images.Media.DATA self.MediaStore_Images_Media_DATA = "_data" self.gallerie = self.intent() self.gallerie.setType("image/*") self.gallerie.setAction(self.intent.ACTION_GET_CONTENT) def getPath(self, Iuri, *args): if Iuri == None: return '' self.projektion = [self.MediaStore_Images_Media_DATA] self.cursor = self.currentActivity.getContentResolver().query(Iuri, self.projektion, None, None, None) if self.cursor != None: cindex = self.cursor.getColumnIndexOrThrow(self.MediaStore_Images_Media_DATA) self.cursor.moveToFirst() return self.cursor.getString(cindex) return Iuri.getPath() def on_activity_result(self, requestCode, resultCode, data): print "### ACTIVITY CALLBACK ###" if resultCode == self.PythonActivity.RESULT_OK: if requestCode == 1: myuri = data.getData() self.mypath = self.getPath(myuri) self.give(self.mypath) #print self.mypath def make_gallary(self, give): self.currentActivity = cast('android.app.Activity', self.PythonActivity.mActivity) self.currentActivity.startActivityForResult(self.intent.createChooser(self.gallerie, "Choose Image"), 1) #print 'made gallery' self.give = give activity.bind(on_activity_result=self.on_activity_result) return self.mypath def get_str(self): return self.mypath def give(self): pass </code></pre> <p>And Here are the permissions, I gave the App in the buildozer.spec file:</p> <pre><code># (list) Permissions android.permissions = INTERNET,ACCESS_WIFI_STATE,READ_PHONE_STATE,ACCESS_NETWORK_STATE,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE </code></pre> <p>And Here is the part of the logicat, that says something with gallary:</p> <pre><code>D/GalleryActivityLifecycleCallback(15128): destroyed : count 1 D/ThumbnailProxy(15128): stop() D/ThumbnailProxy(15128): stop() D/ThumbnailProxy(15128): stop() D/KeyguardUpdateMonitor( 1015): sendKeyguardVisibilityChanged(true) D/KeyguardUpdateMonitor( 1015): handleKeyguardVisibilityChanged(1) D/CustomFrequencyManagerService( 785): acquireDVFSLockLocked : type : DVFS_MIN_LIMIT frequency : 1190400 uid : 1000 pid : 785 pkgName : ACTIVITY_RESUME_BOOSTER@9 D/NearbyUtils(15128): clear nearby caches E/cutils ( 213): Failed to mkdirat(/storage/extSdCard/Android): Read-only file system W/Vold ( 213): Returning OperationFailed - no handler for errno 30 D/KeyguardUpdateMonitor( 1015): sendKeyguardVisibilityChanged(true) D/KeyguardUpdateMonitor( 1015): handleKeyguardVisibilityChanged(1) W/ContextImpl(15128): Failed to ensure directory: /storage/extSdCard/Android/data/com.sec.android.gallery3d/cache I/Gallery_Performance(15128): Gallery onDestroy End </code></pre>
0
2016-08-22T08:11:46Z
39,078,648
<p>Try adding <code>android</code> to your requirements.</p>
0
2016-08-22T11:42:33Z
[ "android", "python", "kivy", "android-gallery", "pyjnius" ]
How can I strip html with BeautifulSoup, keeping newlines like textContent?
39,074,337
<p>This is what I've got:</p> <pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; BeautifulSoup("&lt;p&gt;Hello&lt;/p&gt;\n\n&lt;p&gt;World&lt;/p&gt;").get_text() u'Hello\nWorld' </code></pre> <p>Whitespace is mostly preserved but, as in the example above, newlines aren't. I'd like to strip HTML without any whitespace normalisation, matching javascript's <code>textContent</code>. Can <code>BeautifulSoup</code> do this?</p>
1
2016-08-22T08:11:55Z
39,074,338
<p>Rather than the default parser, <code>html.parser</code>, installing <code>html5lib</code> did the trick:</p> <pre><code>pip install html5lib ... &gt;&gt;&gt; BeautifulSoup("&lt;p&gt;Hello&lt;/p&gt;\n\n&lt;p&gt;World&lt;/p&gt;", "html.parser").get_text() u'Hello\nWorld' &gt;&gt;&gt; BeautifulSoup("&lt;p&gt;Hello&lt;/p&gt;\n\n&lt;p&gt;World&lt;/p&gt;", "html5lib").get_text() u'Hello\n\nWorld' </code></pre> <p>See <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow">installing-a-parser</a>.</p>
1
2016-08-22T08:11:55Z
[ "python", "beautifulsoup", "newline", "whitespace" ]
Creating dicts from file in python
39,074,367
<p>For example, I've got file with multilines like</p> <pre><code>&lt;&lt;something&gt;&gt; 1, 5, 8 &lt;&lt;somethingelse&gt;&gt; hello &lt;&lt;somethingelseelse&gt;&gt; 1,5,6 </code></pre> <p>I need to create dict with keys</p> <pre><code>dict = { "something":[1,5,8], "somethingelse": "hello" ...} </code></pre> <p>I need to somehow read what is inside &lt;&lt; >> and put it as a key, and also I need to check if there are a lot of elements or only 1. If only one then I put it as string. If more then one then I need to put it as a list of elements. Any ideas how to help me? Maybe regEx's but I'm not great with them.</p> <p>I easily created def which is reading a file lines, but don't know how to separate those values:</p> <pre><code>f = open('something.txt', 'r') lines = f.readlines() f.close() def finding_path(): for line in lines: print line finding_path() f.close() </code></pre> <p>Any ideas? Thanks :)</p>
0
2016-08-22T08:14:01Z
39,074,527
<p>Assuming that your keys will always be single words, you can play with <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow">split(char, maxSplits)</a>. Something like below</p> <pre><code>import sys def finding_path(file_name): f = open(file_name, 'r') my_dict = {} for line in f: # split on first occurance of space key_val_pair = line.split(' ', 1) # if we do have a key seprated by a space if len(key_val_pair) &gt; 1: key = key_val_pair[0] # proceed only if the key is enclosed within '&lt;&lt;' and '&gt;&gt;' if key.startswith('&lt;&lt;') and key.endswith('&gt;&gt;'): key = key[2:-2] # put more than one value in list, otherwise directly a string literal val = key_val_pair[1].split(',') if ',' in key_val_pair[1] else key_val_pair[1] my_dict[key] = val print my_dict f.close() if __name__ == '__main__': finding_path(sys.argv[1]) </code></pre> <p>Using a file like below</p> <pre><code>&lt;&lt;one&gt;&gt; 1, 5, 8 &lt;&lt;two&gt;&gt; hello // this is a comment, it will be skipped &lt;&lt;three&gt;&gt; 1,5,6 </code></pre> <p>I get the output </p> <pre><code>{'three': ['1', '5', '6\n'], 'two': 'hello\n', 'one': ['1', ' 5', ' 8\n']} </code></pre>
1
2016-08-22T08:22:30Z
[ "python", "python-2.7", "file", "input" ]
Creating dicts from file in python
39,074,367
<p>For example, I've got file with multilines like</p> <pre><code>&lt;&lt;something&gt;&gt; 1, 5, 8 &lt;&lt;somethingelse&gt;&gt; hello &lt;&lt;somethingelseelse&gt;&gt; 1,5,6 </code></pre> <p>I need to create dict with keys</p> <pre><code>dict = { "something":[1,5,8], "somethingelse": "hello" ...} </code></pre> <p>I need to somehow read what is inside &lt;&lt; >> and put it as a key, and also I need to check if there are a lot of elements or only 1. If only one then I put it as string. If more then one then I need to put it as a list of elements. Any ideas how to help me? Maybe regEx's but I'm not great with them.</p> <p>I easily created def which is reading a file lines, but don't know how to separate those values:</p> <pre><code>f = open('something.txt', 'r') lines = f.readlines() f.close() def finding_path(): for line in lines: print line finding_path() f.close() </code></pre> <p>Any ideas? Thanks :)</p>
0
2016-08-22T08:14:01Z
39,074,552
<p>Please check the below code:</p> <ul> <li><p>Used regex to get key and value</p></li> <li><p>If the length of value list is 1, then converting it into string.</p></li> </ul> <pre><code>import re demo_dict = {} with open("val.txt",'r') as f: for line in f: m= re.search(r"&lt;&lt;(.*?)&gt;&gt;(.*)",line) if m is not None: k = m.group(1) v = m.group(2).strip().split(',') if len(v) == 1: v = v[0] demo_dict[k]=v print demo_dict </code></pre> <p>Output:</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python demo.Py {'somethingelseelse': [' 1', '5', '6'], 'somethingelse': 'hello', 'something': [ ' 1', ' 5', ' 8']} </code></pre>
1
2016-08-22T08:23:54Z
[ "python", "python-2.7", "file", "input" ]
Creating dicts from file in python
39,074,367
<p>For example, I've got file with multilines like</p> <pre><code>&lt;&lt;something&gt;&gt; 1, 5, 8 &lt;&lt;somethingelse&gt;&gt; hello &lt;&lt;somethingelseelse&gt;&gt; 1,5,6 </code></pre> <p>I need to create dict with keys</p> <pre><code>dict = { "something":[1,5,8], "somethingelse": "hello" ...} </code></pre> <p>I need to somehow read what is inside &lt;&lt; >> and put it as a key, and also I need to check if there are a lot of elements or only 1. If only one then I put it as string. If more then one then I need to put it as a list of elements. Any ideas how to help me? Maybe regEx's but I'm not great with them.</p> <p>I easily created def which is reading a file lines, but don't know how to separate those values:</p> <pre><code>f = open('something.txt', 'r') lines = f.readlines() f.close() def finding_path(): for line in lines: print line finding_path() f.close() </code></pre> <p>Any ideas? Thanks :)</p>
0
2016-08-22T08:14:01Z
39,075,331
<p>My answer is similar to Dinesh's. I've added a function to convert the values in the list to numbers if possible, and some error handling so that if a line doesn't match, a useful warning is given.</p> <pre><code>import re import warnings regexp =re.compile(r'&lt;&lt;(\w+)&gt;&gt;\s+(.*)') lines = ["&lt;&lt;something&gt;&gt; 1, 5, 8\n", "&lt;&lt;somethingelse&gt;&gt; hello\n", "&lt;&lt;somethingelseelse&gt;&gt; 1,5,6\n"] #In real use use a file descriptor instead of the list #lines = open('something.txt','r') def get_value(obj): """Converts an object to a number if possible, or a string if not possible""" try: return int(obj) except ValueError: pass try: return float(obj) except ValueError: return str(obj) dictionary = {} for line in lines: line = line.strip() m = re.search(regexp, line) if m is None: warnings.warn("Match failed on \n {}".format(line)) continue key = m.group(1) value = [get_value(x) for x in m.group(2).split(',')] if len(value) == 1: value = value[0] dictionary[key] = value print(dictionary) </code></pre> <p>output</p> <pre><code>{'something': [1, 5, 8], 'somethingelse': 'hello', 'somethingelseelse': [1, 5, 6]} </code></pre>
1
2016-08-22T09:03:47Z
[ "python", "python-2.7", "file", "input" ]
Plot list of lists as bar graph Python Matplotlib
39,074,422
<p>I have a list of lists that looks as follows:</p> <pre><code>[[1,100.1],[2,133.222],[3,198.0]] </code></pre> <p>I'm trying to use this data to draw a bar graph in matplotlib, where the first element in each element of the list is the x-axis (it's always an integer between 1-1000, no repeats) and the second element is the y-axis value. </p> <p>I'm using Python 3. How would I plot this?</p>
0
2016-08-22T08:16:51Z
39,074,593
<p>You need to separate the x values from the y values. This can be done by <code>zip</code>:</p> <p>First:</p> <pre><code>import numpy as np import matplotlib.pypl as plt </code></pre> <p>Now:</p> <pre><code>In [263]: lst = [[1,100.1],[2,133.222],[3,198.0]] In [264]: xs, ys = [*zip(*lst)] In [265]: xs Out[265]: (1, 2, 3) In [266]: ys Out[266]: (100.1, 133.222, 198.0) </code></pre> <p>Now draw the bars:</p> <pre><code>In [267]: plt.bar(xs, ys) </code></pre> <p>Bar graphs do not set the bars widths automatically. In the current case the width turned out to be fine, but a more systematic way would be to take the differences between the x values, like this:</p> <pre><code>In [269]: np.diff(xs) Out[269]: array([1, 1]) </code></pre> <p>Usually you have an equally spaced x values, but this need not be the case. You might want to set the width to the minimum difference between the x values, so the bar graph might be generated like this:</p> <pre><code>In [268]: plt.bar(xs, ys, width=0.9 * np.min(np.diff(xs))) </code></pre>
3
2016-08-22T08:26:12Z
[ "python", "matplotlib", "plot" ]
Plot list of lists as bar graph Python Matplotlib
39,074,422
<p>I have a list of lists that looks as follows:</p> <pre><code>[[1,100.1],[2,133.222],[3,198.0]] </code></pre> <p>I'm trying to use this data to draw a bar graph in matplotlib, where the first element in each element of the list is the x-axis (it's always an integer between 1-1000, no repeats) and the second element is the y-axis value. </p> <p>I'm using Python 3. How would I plot this?</p>
0
2016-08-22T08:16:51Z
39,074,643
<p>I would go for something like this:</p> <pre><code>import matplotlib.pyplot as plt data = [[1,100.1],[2,133.222],[3,198.0]] x = map(lambda x: x[0], data) y = map(lambda x: x[1], data) plt.bar(x,y) </code></pre>
0
2016-08-22T08:29:02Z
[ "python", "matplotlib", "plot" ]
Accessing entire string in Python using Negative indices
39,074,498
<p>Here is a Python oddity that I discovered while teaching students.</p> <p>If negative indexing should work right, then for a string m='string', I did the following steps.</p> <pre><code>&gt;&gt;&gt; m='string' &gt;&gt;&gt; m[:-1] 'strin' &gt;&gt;&gt; m[:0] '' &gt;&gt;&gt; m[-1] 'g' &gt;&gt;&gt; m[0:] 'string' &gt;&gt;&gt; m[:-1] 'strin' &gt;&gt;&gt; m[:0] '' &gt;&gt;&gt; </code></pre> <p>I want to know how to access the entire string using the negative index?</p>
2
2016-08-22T08:21:15Z
39,074,556
<pre><code>&gt;&gt;&gt; m='string' &gt;&gt;&gt; m[-len(m):] 'string' </code></pre> <p>Just as positive indices count forward from the beginning of a string, negative indices count back from the end. Thus, we have to count back by <code>len(m)</code> to get back to the beginning of <code>m</code>.</p>
7
2016-08-22T08:24:05Z
[ "python", "python-2.7" ]
Accessing entire string in Python using Negative indices
39,074,498
<p>Here is a Python oddity that I discovered while teaching students.</p> <p>If negative indexing should work right, then for a string m='string', I did the following steps.</p> <pre><code>&gt;&gt;&gt; m='string' &gt;&gt;&gt; m[:-1] 'strin' &gt;&gt;&gt; m[:0] '' &gt;&gt;&gt; m[-1] 'g' &gt;&gt;&gt; m[0:] 'string' &gt;&gt;&gt; m[:-1] 'strin' &gt;&gt;&gt; m[:0] '' &gt;&gt;&gt; </code></pre> <p>I want to know how to access the entire string using the negative index?</p>
2
2016-08-22T08:21:15Z
39,078,477
<p>I'm guessing you don't actually mean an answer like suggested by anyone else. What you want to know is why <code>m[:-N]</code> returns all characters in <em>m</em> except for the last <em>N</em>, <strong>unless N is zero</strong>, because -0 is equal to 0, and <code>m[:0]</code> should, of course, return an empty string.</p> <p>Unfortunately, this is an insurmountable quirk of the language.</p> <p>As a cop-out, I'll offer this: <code>m[:None]</code>, or <code>m[:(None if N==0 else -N)]</code>.</p>
0
2016-08-22T11:34:21Z
[ "python", "python-2.7" ]
Python - Kivy: AttributeError: 'super' object has no attribute '__getattr__' when trying to get self.ids
39,074,550
<p>I wrote a code for a kind of android lock thing, whenever I try to get an specific ClickableImage using the id it raises the following error:</p> <pre><code>AttributeError: 'super' object has no attribute '__getattr__' </code></pre> <p>I've spent hours trying to look for a solution for this problem, I looked other people with the same issue, and people told them to change the site of the builder, because it needed to be called first to get the ids attribute or something like that, but everytime I move the builder, it raises the error "class not defined". Any clues?</p> <p>Here is my code:</p> <pre><code>from kivy.app import App from kivy.config import Config from kivy.lang import Builder from kivy.graphics import Line from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.widget import Widget from kivy.uix.image import Image from kivy.uix.floatlayout import FloatLayout from kivy.uix.behaviors import ButtonBehavior #Variables cords = () bld = Builder.load_file('conf.kv') class Manager(ScreenManager): pass class Principal(Screen): pass class ClickableImage(ButtonBehavior, Image): def on_press(self): self.source = 'button_press.png' def on_release(self): self.source = 'button.png' self.ids.uno.source = 'button_press.png' class canva(Widget): def on_touch_down(self, touch): global cords with self.canvas: touch.ud['line'] = Line(points=(touch.x, touch.y), width=1.5) cords = (touch.x, touch.y) def on_touch_move(self,touch): global cords touch.ud['line'].points = cords + (touch.x, touch.y) def on_touch_up(self,touch): self.canvas.clear() class Api(App): def build(self): return bld if __name__ == '__main__': Api().run() </code></pre> <p>and here is my .kv file:</p> <pre><code># conf to file: test.py &lt;Manager&gt;: Principal: &lt;Principal&gt;: GridLayout: size_hint_x: 0.5 size_hint_y: 0.6 width: self.minimum_width cols: 3 ClickableImage: id: 'uno' size: 10,10 source: 'button.png' allow_strech: True ClickableImage: id: 'dos' size: 30,30 source: 'button.png' allow_strech: True canva: </code></pre>
2
2016-08-22T08:23:48Z
39,152,510
<p>Let's look at the output:</p> <pre><code>'super' object has no attribute '__getattr__' </code></pre> <p>In kv language <code>id</code> is set in a special way(up to 1.9.2 now), its value is not a string, because it's not a casual variable. You can't access it with <code>&lt;widget&gt;.id</code>.</p> <p>I'd say it's similar to <code>canvas</code>, which is not a widget, yet it may look like that(which is why I was confused by your code :P). You've already noticed <code>something: &lt;some object&gt;</code> is like Python's <code>something = &lt;object&gt;</code> and that's (at least what I think) is the whole point of <code>id</code>'s value not being a string(which to some is odd). If <code>id</code> was a string, there'd probably be needed a check to exclude it somehow from casual assigning values. Maybe it's because of performance or just simplicity.</p> <p>Therefore let's say <code>id</code> is a keyword for a future keyword. In fact, it is, because the characters assigned to <code>id</code> will become a string key with a value of object got from WeakProxy, to the object WeakProxy points to. Or better said:</p> <pre><code>id: value </code></pre> <p>becomes</p> <pre><code>&lt;some_root_widget&gt;.ids[str(value)] = weakref.proxy(value) </code></pre> <p>where <code>value</code> becomes an <em>object</em>(what <code>print(self)</code> would return)</p> <p>I suspect(not sure) that if you use string as the value for <code>id</code>, you'll end up with <a href="http://stackoverflow.com/a/36789779/5994041">weakref</a> / <a href="https://github.com/kivy/kivy/blob/master/kivy/weakproxy.pyx" rel="nofollow">WeakProxy</a> pointing to a string. I use the word <code>point</code> as it reminds me pointers, don't get confused with C pointers.</p> <p>Now if you look again at the output:</p> <ul> <li><p><a class='doc-link' href="http://stackoverflow.com/documentation/python/809/compatibility-between-python-3-and-python-2/9712/compatible-subclassing-with-super#t=201608251807170382088">super</a> gives you an access to a class you inherit from</p></li> <li><p><code>print('string id'.__getattr__)</code> will give you the same error, but <code>'super'</code> is substituted with the real value, because well... it doesn't have <code>__getattr__</code></p></li> </ul> <p>Therefore <em>if</em> you assign a <em>string</em> value to <code>id</code>, you'll get into this situation:</p> <pre><code>&lt;some_root_widget&gt;.ids[str('value')] = weakref.proxy('value') # + little bit of magic </code></pre> <p>Although <code>str('value')</code> isn't necessarily wrong, by default you can't create weakref.proxy for a string. I'm not sure how Kivy handles this with WeakProxies, but if you assign a string to <code>id</code>, roughly this is what you get.</p> <p>(Please correct me if I'm wrong)</p>
1
2016-08-25T18:35:45Z
[ "python", "kivy", "kivy-language" ]
python try and exception
39,074,635
<p>I am not a python geek but have tried to solve this problem using information from several answers to similar questions but none seem to really work in my case. Here it is:</p> <p>I am calling a function from a python script: Here is the function:</p> <pre><code>def getsom(X): #some codes try: st = get data from site 1 using X except: print "not available from site 1, getting from site 2" st = get data from site 2 using X #some codes that depend on st </code></pre> <p>I am calling this from a python script as such:</p> <pre><code>#some codes for yr in range(min_yr,max_yr+1): day=1 while day&lt;max_day: st1 = getsom(X) #some code that depends on st1 day+=1 </code></pre> <p>This works fine when data is available on either site 1 or 2 for a particular day, but breaks down when it is unavailable on both sites for another day.</p> <p>I want to be able to check for the next day if data is unavailable for a particular day for both sites. I have tried different configurations of try and except with no success and would appreciate any help on the most efficient way to do this.</p> <p>Thanks!</p> <p>***Edits Final version that worked:</p> <p>in the function part:</p> <pre><code>def getsom(X): #some codes try: st = get data from site 1 using X except: print "not available from site 1, getting from site 2" st = get data from site 2 using X try: st = get data from site 2 using X except: print "data not available from sites 1 and 2" st=None if st is not None: #some codes that depend on st </code></pre> <p>In order to iterate to the next day on the script side, I had to handle the none case from the function with another try/except block:</p> <pre><code>#some codes for yr in range(min_yr,max_yr+1): day=1 while day&lt;max_day: try: st=getsom(X) except: st=None if st is not None: #some codes that depend </code></pre>
-3
2016-08-22T08:28:37Z
39,075,274
<p>As mentioned in the comments you seem like you want to catch the exception <em>in</em> first-level exception handler. You can do it like this:</p> <pre><code>def getsom(X): #some codes try: st = get data from site 1 using X except: print "not available from site 1, getting from site 2" try: st = get data from site 2 using X except: print "Not available from site 2 as well." # Here you can assign some arbitrary value to your variable (like None for example) or return from function. #some codes that depend on st </code></pre> <p>If data is not available on neither of the sites you can assign some arbitrary value to your variable <code>st</code> or simply return from the function.</p> <p>Is this what you are looking for? Also, you shouldn't simply write <code>except</code> without specifying the type of exception you expect - look here for more info: <a href="http://stackoverflow.com/questions/14797375/should-i-always-specify-an-exception-type-in-except-statements">Should I always specify an exception type in `except` statements?</a> </p> <p>Edit to answer the problem in comment:</p> <p>If you have no data about certain day you can just <code>return None</code> and handle it like this:</p> <pre><code>#some codes for yr in range(min_yr,max_yr+1): day=1 while day&lt;max_day: st1 = getsom(X) if st1 is not None: #some code that depends on st1 day+=1 </code></pre>
2
2016-08-22T09:01:27Z
[ "python" ]
python try and exception
39,074,635
<p>I am not a python geek but have tried to solve this problem using information from several answers to similar questions but none seem to really work in my case. Here it is:</p> <p>I am calling a function from a python script: Here is the function:</p> <pre><code>def getsom(X): #some codes try: st = get data from site 1 using X except: print "not available from site 1, getting from site 2" st = get data from site 2 using X #some codes that depend on st </code></pre> <p>I am calling this from a python script as such:</p> <pre><code>#some codes for yr in range(min_yr,max_yr+1): day=1 while day&lt;max_day: st1 = getsom(X) #some code that depends on st1 day+=1 </code></pre> <p>This works fine when data is available on either site 1 or 2 for a particular day, but breaks down when it is unavailable on both sites for another day.</p> <p>I want to be able to check for the next day if data is unavailable for a particular day for both sites. I have tried different configurations of try and except with no success and would appreciate any help on the most efficient way to do this.</p> <p>Thanks!</p> <p>***Edits Final version that worked:</p> <p>in the function part:</p> <pre><code>def getsom(X): #some codes try: st = get data from site 1 using X except: print "not available from site 1, getting from site 2" st = get data from site 2 using X try: st = get data from site 2 using X except: print "data not available from sites 1 and 2" st=None if st is not None: #some codes that depend on st </code></pre> <p>In order to iterate to the next day on the script side, I had to handle the none case from the function with another try/except block:</p> <pre><code>#some codes for yr in range(min_yr,max_yr+1): day=1 while day&lt;max_day: try: st=getsom(X) except: st=None if st is not None: #some codes that depend </code></pre>
-3
2016-08-22T08:28:37Z
39,075,464
<p>Why don't you create a separate function for it?</p> <pre class="lang-py prettyprint-override"><code>def getdata(X): for site in [site1, site2]: # possibly more try: return get_data_from_site_using_X() except: print "not available in %s" % site print "couldn't find data anywhere" </code></pre> <p>Then <code>getsom</code> becomes:</p> <pre class="lang-py prettyprint-override"><code>def getsom(X): #some codes st = getdata(X) #some codes that depend on st </code></pre>
0
2016-08-22T09:10:20Z
[ "python" ]
Can OpenWhisk trigger Docker actions in my Bluemix registry?
39,074,638
<p>I pushed my Docker image to my Bluemix registry; I ran the container on Bluemix just fine; I have also set up a skeleton OpenWhisk rule which triggers a sample Python action but wish to trigger the image in my Bluemix registry as the action. </p> <p>But, as far as I can see from the OpenWhisk documents, it is only possible to trigger Docker actions hosted on Docker Hub. (Per the <code>wsk idk install docker</code> skeleton).</p> <p>Can OpenWhisk trigger Docker actions in my Bluemix registry?</p>
1
2016-08-22T08:28:47Z
39,074,811
<p>This is not currently possible. </p> <p>OpenWhisk can only create Actions from Docker images stored in the external Docker Hub registry. </p>
1
2016-08-22T08:38:27Z
[ "python", "ibm-bluemix", "openwhisk" ]
How can I get the radio button in Matplotlib to update 4 subplots together?
39,074,930
<p>I would highly appreciate your help here. I have 3 .csv files with some data in them. Each .csv file creates 4 histograms. I have created 4 subplots for each histogram.</p> <p>I have also created a radio button with the 3 data sets as variables. I would like the subplots to be updated with the data set I click on in the radio button tab. However, I am unable to do that.</p> <p>I am new to programming and learning as I progress with this. Here's the code that I created</p> <pre><code>import csv import numpy as np from scipy.stats import norm, lognorm import matplotlib.pyplot as plt import matplotlib.mlab as mlab from matplotlib.widgets import Slider, Button, RadioButtons #####Importing Data from csv file##### dataset1 = np.genfromtxt('dataSet1.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0']) dataset2 = np.genfromtxt('dataSet2.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0']) dataset3 = np.genfromtxt('dataSet3.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0']) #####_____##### #####Creating Subplots##### fig = plt.figure() plt.subplots_adjust(left=0.15, bottom=0.1) ax1 = fig.add_subplot(321) #Subplot 1 ax1.set_xlabel('a', fontsize = 14) #ax1.set_ylabel('PDF', fontsize = 14) ##ax1.set_title('Probability Density Function', fontsize = 10) ##ax1.text(-2, 0.4, r'$\mu=0,\ \sigma^2=1$') ax1.grid(True) ax2 = fig.add_subplot(323) #Subplot 2 ax2.set_xlabel('b', fontsize = 14) #ax2.set_ylabel('PDF', fontsize = 14) ##ax2.set_title('Probability Density Function', fontsize = 10) ##ax2.text(-2, 0.4, r'$\mu=0,\ \sigma^2=1$') ax2.grid(True) ax3 = fig.add_subplot(325) #Subplot 3 ax3.set_xlabel('c', fontsize = 14) #ax3.set_ylabel('PDF', fontsize = 14) ##ax3.set_title('Probability Density Function', fontsize = 10) ##ax3.text(-2, 0.4, r'$\mu=0,\ \sigma^2=1$') ax3.grid(True) ax4 = fig.add_subplot(122) #Subplot 4 ax4.set_xlabel('x0', fontsize = 14) ax4.set_ylabel('PDF', fontsize = 14) ##ax4.set_title('Probability Density Function', fontsize = 10) ##ax4.text(-2, 0.4, r'$\mu=0,\ \sigma^2=1$') ax4.grid(True) #####_____##### #####Plotting Distributions##### ax1 = ax1.hist(dataset1['a'], bins=50, color = 'red',alpha = 0.5, normed = True) ax2 = ax2.hist(dataset1['b'], bins=50, color = 'red',alpha = 0.5, normed = True) ax3 = ax3.hist(dataset1['c'], bins=50, color = 'red',alpha = 0.5, normed = True) ax4 = ax4.hist(dataset1['x0'], bins=50, color = 'red',alpha = 0.5, normed = True) #####_____##### #######Creating Radio Button##### axcolor = 'lightgoldenrodyellow' rax = plt.axes([0.03, 0.48, 0.06, 0.09], axisbg=axcolor) radio = RadioButtons(rax, ('Data Set1', 'Data Set2', 'Data Set3')) #####_____##### #####Updating Radio Button##### radio_label = 'Data Set1' func = {'Data Set1': dataset1, 'Data Set2': dataset2, 'Data Set3': dataset3} axcl = {'Data Set1': 'red', 'Data Set2': 'blue', 'Data Set3': 'green'} def update_radio(label): global radio_label #so we can overwrite the variable defined above and not create a local one radio_label = label print radio_label if label == 'Data Set2': plt.hist(func[radio_label]['a'], bins=50, color = 'red',alpha = 0.5) plt.hist(func[radio_label]['b'], bins=50, color = 'red',alpha = 0.5) plt.hist(func[radio_label]['c'], bins=50, color = 'red',alpha = 0.5) plt.hist(func[radio_label]['x0'], bins=50, color = 'red',alpha = 0.5) elif label == 'Data Set3': plt.hist(func[radio_label]['a'], bins=50, color = 'red',alpha = 0.5) plt.hist(func[radio_label]['b'], bins=50, color = 'red',alpha = 0.5) plt.hist(func[radio_label]['c'], bins=50, color = 'red',alpha = 0.5) plt.hist(func[radio_label]['x0'], bins=50, color = 'red',alpha = 0.5) plt.draw() radio.on_clicked(update_radio) #####_____##### plt.show() </code></pre> <p>Data in the .csv files look like this:</p> <p>[(1.0876, 10.44, -14.036, -10.795) (0.89453, 8.0052, -13.198, -10.372) (0.8199, 8.0609, -11.475, -11.093) ..., (1.2176, 10.45, -13.828, -9.7473) (0.94211, 11.82, -7.7689, -13.173) (0.83588, 11.882, -13.807, -15.295)]</p>
0
2016-08-22T08:44:31Z
39,077,643
<pre><code>import csv import numpy as np from scipy.stats import norm, lognorm import matplotlib.pyplot as plt import matplotlib.mlab as mlab from matplotlib.widgets import Slider, Button, RadioButtons #####Importing Data from csv file##### dataset1 = np.genfromtxt('dataSet1.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0']) dataset2 = np.genfromtxt('dataSet2.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0']) dataset3 = np.genfromtxt('dataSet3.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0']) #####_____##### #####Creating Subplots##### fig = plt.figure() plt.subplots_adjust(left=0.15, bottom=0.1) ax1 = fig.add_subplot(321) #Subplot 1 ax1.set_xlabel('a', fontsize = 14) #ax1.set_ylabel('PDF', fontsize = 14) ##ax1.set_title('Probability Density Function', fontsize = 10) ##ax1.text(-2, 0.4, r'$\mu=0,\ \sigma^2=1$') ax1.grid(True) ax2 = fig.add_subplot(323) #Subplot 2 ax2.set_xlabel('b', fontsize = 14) #ax2.set_ylabel('PDF', fontsize = 14) ##ax2.set_title('Probability Density Function', fontsize = 10) ##ax2.text(-2, 0.4, r'$\mu=0,\ \sigma^2=1$') ax2.grid(True) ax3 = fig.add_subplot(325) #Subplot 3 ax3.set_xlabel('c', fontsize = 14) #ax3.set_ylabel('PDF', fontsize = 14) ##ax3.set_title('Probability Density Function', fontsize = 10) ##ax3.text(-2, 0.4, r'$\mu=0,\ \sigma^2=1$') ax3.grid(True) ax4 = fig.add_subplot(122) #Subplot 4 ax4.set_xlabel('x0', fontsize = 14) ax4.set_ylabel('PDF', fontsize = 14) ##ax4.set_title('Probability Density Function', fontsize = 10) ##ax4.text(-2, 0.4, r'$\mu=0,\ \sigma^2=1$') ax4.grid(True) #####_____##### #####Plotting Distributions##### ax1.hist(dataset1['a'], bins=50, color = 'red',alpha = 0.5, normed = True) ax2.hist(dataset1['b'], bins=50, color = 'red',alpha = 0.5, normed = True) ax3.hist(dataset1['c'], bins=50, color = 'red',alpha = 0.5, normed = True) ax4.hist(dataset1['x0'], bins=50, color = 'red',alpha = 0.5, normed = True) #####_____##### #######Creating Radio Button##### axcolor = 'lightgoldenrodyellow' rax = plt.axes([0.03, 0.48, 0.06, 0.09], axisbg=axcolor) radio = RadioButtons(rax, ('Data Set1', 'Data Set2', 'Data Set3')) #####_____##### #####Updating Radio Button##### radio_label = 'Data Set1' func = {'Data Set1': dataset1, 'Data Set2': dataset2, 'Data Set3': dataset3} axcl = {'Data Set1': 'red', 'Data Set2': 'blue', 'Data Set3': 'green'} def update_radio(label): global radio_label #so we can overwrite the variable defined above and not create a local one radio_label = label print(radio_label) ax1.clear() ax2.clear() ax3.clear() ax4.clear() ax1.hist(func[radio_label]['a'], bins=50, color = 'red',alpha = 0.5) ax2.hist(func[radio_label]['b'], bins=50, color = 'red',alpha = 0.5) ax3.hist(func[radio_label]['c'], bins=50, color = 'red',alpha = 0.5) ax4.hist(func[radio_label]['x0'], bins=50, color = 'red',alpha = 0.5) ax1.grid(True) ax2.grid(True) ax3.grid(True) ax4.grid(True) plt.draw() radio.on_clicked(update_radio) #####_____##### plt.show() </code></pre>
0
2016-08-22T10:51:12Z
[ "python", "python-2.7", "python-3.x", "csv", "matplotlib" ]
SettingWithCopyWarning unsual behavior in Pandas
39,074,931
<p>I have a dataframe say <strong>release_dates</strong></p> <p><strong>release_dates</strong></p> <p><a href="http://i.stack.imgur.com/U3tq0.png" rel="nofollow"><img src="http://i.stack.imgur.com/U3tq0.png" alt="enter image description here"></a> </p> <p>I did the filtering using some conditions and called it <strong>b</strong></p> <pre><code>b = release_dates[(release_dates.title.str.startswith('The Hobbit')) &amp; (release_dates.country =='USA')] </code></pre> <p><a href="http://i.stack.imgur.com/8ssec.png" rel="nofollow"><img src="http://i.stack.imgur.com/8ssec.png" alt="enter image description here"></a></p> <p>Now I want other column that display month by extracting it from date column. I used the below command which worked fine but threw an error </p> <pre><code>b['month'] = b['date'].dt.month #code1 C:\Users\user110244\Anaconda3\lib\site-packages\pandas\core\indexing.py:288: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead </code></pre> <p><a href="http://i.stack.imgur.com/86P2j.png" rel="nofollow"><img src="http://i.stack.imgur.com/86P2j.png" alt="enter image description here"></a></p> <p>I read the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">documentation</a> as suggested by the code and from my understanding I came to know that I should use the <strong>below command</strong> (in case of chain indexing) because using the <strong>above command</strong> makes it very hard to predict whether it will return a view or a copy (it depends on the memory layout of the array, about which pandas makes no guarantees) and code2 is much more efficient than code1 as per documentation.</p> <pre><code>b.loc[:,'month']=b.loc[:,'date'].dt.month #code2 </code></pre> <p>But using this also throwing the same error.</p> <p><strong>Can someone please explain why this is happening and How do I am assured that my code is correct in both the cases 'a' and 'b'?</strong> <strong>How do I turn this warning off ?</strong></p> <p>One more thing I want to point out i.e. I used the same code with different condition and didn't get any error</p> <pre><code>a =release_dates[(release_dates.title.str.contains('Christmas'))&amp; (release_dates.country =='USA')].sort_values('year') a['month'] = a['date'].dt.month a.head() </code></pre>
1
2016-08-22T08:44:33Z
39,078,218
<p>As Edchum explained it clearly in his comments that you used <strong>.sort()</strong> in the first code which lets python know that user know, it is a copy rather than a view.</p> <p>Whenever we perform slicing or filtering We get either a View or a copy.However, Pandas docs do not specify any rules about what you should expect a View or a Copy. </p> <p>Let me try to expand it a bit. One simple way to avoid such warning is to use <strong>.copy()</strong></p> <pre><code>b = (release_dates.title.str.startswith('The Hobbit')) &amp; (release_dates.country =='USA') b1 = b.copy() b1['month'] = b1['date'].dt.month #code1 </code></pre> <p>By doing this you are explicitly telling Python that you what you are working on i.e. on a view or on a copy and Python will not display warning. </p> <p>But please keep in mind that making copy every time consumes lot of memory. So do it whenever it is necessary. </p> <p>You can also check whether two objects are pointing out to the same memory or not by using </p> <pre><code>np.may_share_memory(b,b1) False </code></pre> <p>One other way of turning the warning off for a particular object is using <strong>.is_copy()=False</strong> In this case we can use </p> <pre><code>b.is_copy()= False </code></pre>
1
2016-08-22T11:20:43Z
[ "python", "python-3.x", "pandas" ]
How to deal with string format in python pandas?
39,074,991
<p>I have a data frame like following:</p> <pre><code> pop state country num_1 num_2 0 1.8 Ohio China 1 4 1 1.9 Ohio China 1 5 2 3.9 Nevada Britain 1 6 3 2.9 Nevada Germany 1 2 4 2.0 Nevada Japan 1 7 </code></pre> <p>You can see in this data frame, df['country'] have 4 different values. I can use 00=China,01=Britain,10=Germany,11=Japan to mean its values. And df['num_1 '],df['num_2'] have 1, 5 different values. I can also mean it value as binary num.</p> <p>So I want to condense this data frame to a small data frame as following:</p> <pre><code> pop state value 0 1.8 Ohio 000000 1 1.9 Ohio 000001 2 3.9 Nevada 010010 3 2.9 Nevada 100011 4 2.0 Nevada 110100 </code></pre> <p>My problem is how can I write code to compress this data frame and uncompress it. </p>
-4
2016-08-22T08:47:34Z
39,080,571
<p>OK let's start with a random DataFrame:</p> <pre><code>np.random.seed(0) df = pd.DataFrame({'A': np.random.choice(list('ABC'), 10**7), 'B': 1, 'C': np.random.choice(list('xyztq'), 10**7)}) df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 10000000 entries, 0 to 9999999 Data columns (total 3 columns): A object B int64 C object dtypes: int64(1), object(2) memory usage: 228.9+ MB </code></pre> <p>What happens if you use categoricals:</p> <pre><code>for col in df: df[col] = df[col].astype('category') df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 10000000 entries, 0 to 9999999 Data columns (total 3 columns): A category B category C category dtypes: category(3) memory usage: 28.6 MB </code></pre> <p>With binary representations:</p> <pre><code>df['A'] = df['A'].cat.codes.apply(lambda x: np.binary_repr(x, 2)) df['B'] = df['B'].cat.codes.apply(lambda x: np.binary_repr(x)) df['C'] = df['C'].cat.codes.apply(lambda x: np.binary_repr(x, 3)) df.head() Out: A B C 0 00 0 010 1 01 0 001 2 00 0 100 3 01 0 001 4 01 0 001 </code></pre> <p>And the memory usage:</p> <pre><code>ser = df.apply(''.join, axis=1) ser.to_frame().info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 10000000 entries, 0 to 9999999 Data columns (total 1 columns): 0 object dtypes: object(1) memory usage: 76.3+ MB </code></pre>
1
2016-08-22T13:13:57Z
[ "python", "pandas" ]
Django rq scheduler can not enqueue same task twice
39,075,059
<p>I am using <a href="https://github.com/ui/rq-scheduler" rel="nofollow">rq scheduler</a>. I want to remind users to verify their email after 2 mins and 10 mins. So I use post_save signal to schedule these tasks. I have set up task like this:</p> <pre><code>from datetime import timedelta import django_rq def send_verification_email(user): """Remind signed up user to verify email.""" if not user.is_email_verified: context = get_email_context(user) context['first_name'] = user.first_name context['url'] = django_settings.ACTIVATION_URL.format(**context) # below line sends email VerifyEmailReminderNotification(user.email, context=context).send() @receiver(post_save) def remind_to_verify_email(sender, created, instance, **kwargs): """Send verify email for the new user.""" list_of_models = ('Person', 'Company') scheduler = django_rq.get_scheduler("default") if sender.__name__ in list_of_models: if created: scheduler.enqueue_in(timedelta(minutes=2), send_verification_email, instance) # if I move below enqueue to "send_verification_email" method it will go to recursion. scheduler.enqueue_in(timedelta(minutes=10), send_verification_email, instance) </code></pre> <p>Problem is: I am getting one mail after 2 mins but not second mail after 10 mins. Any help appreciated.</p>
0
2016-08-22T08:51:53Z
39,075,324
<p>Run first task with delta 2 minutes and when it executes, it should run another one with delta 8 minutes. Hope that helps.</p>
1
2016-08-22T09:03:28Z
[ "python", "django", "django-rq" ]
Pandas: create a table using groupby
39,075,173
<p>I have dataframe </p> <pre><code>ID subdomain search_engine search_term code category term_code 0120bc30e78ba5582617a9f3d6dfd8ca yandex.ru 0 None 1 поисковая машина 1 0120bc30e78ba5582617a9f3d6dfd8ca my-shop.ru 0 None 5 интернет-магазин 1 0120bc30e78ba5582617a9f3d6dfd8ca ru.tele2.ru 0 None 10 Телеком-провайдеры 1 0120bc30e78ba5582617a9f3d6dfd8ca yandex.com yandex алиэкспресс 1 поисковая машина 6 0120bc30e78ba5582617a9f3d6dfd8ca fb.ru 0 None 3 информационный ресурс 1 0120bc30e78ba5582617a9f3d6dfd8ca shopotam.ru 0 None 4 интернет-агрегатор 1 031ce36695306ac09ae905927a753f33 ya.ru 0 None 1 поисковая машина 1 031ce36695306ac09ae905927a753f33 cyberforum.ru 0 None 3 информационный ресурс 1 031ce36695306ac09ae905927a753f33 fixim.ru 0 None 8 запчасти и ремонт 1 031ce36695306ac09ae905927a753f33 microsoft.com 0 None 9 сайты производителей с возможностью купить 1 031ce36695306ac09ae905927a753f33 market.yandex.ru 0 None 4 интернет-агрегатор 1 </code></pre> <p>I need to get </p> <pre><code>ID, path 0120bc30e78ba5582617a9f3d6dfd8ca, поисковая машина -&gt; интернет-магазин -&gt; Телеком-провайдеры -&gt; поисковая машина -&gt; информационный ресурс -&gt; интернет-агрегатор 031ce36695306ac09ae905927a753f33, поисковая машина -&gt; информационный ресурс -&gt; запчасти и ремонт -&gt; сайты производителей с возможностью купить -&gt; интернет-агрегатор </code></pre> <p>I mean I want to get column <code>term_code</code> and convert it to string with delimiter <code>-&gt;</code> to every <code>ID</code> How can I do that?</p>
-4
2016-08-22T08:57:28Z
39,075,295
<p>try this:</p> <pre><code>df.groupby('ID')['category'].apply(lambda x: ' -&gt; '.join(list(x))) </code></pre> <p>Demo:</p> <pre><code>In [14]: df.groupby('ID')['category'].apply(lambda x: ' -&gt; '.join(list(x))) Out[14]: ID 0120bc30e78ba5582617a9f3d6dfd8ca поисковая машина -&gt; интернет-магазин -&gt; Телеком-провайдеры -&gt; 6 -&gt; информационный ресурс -&gt; интернет-агрегатор 031ce36695306ac09ae905927a753f33 поисковая машина -&gt; информационный ресурс -&gt; запчасти и ремонт -&gt; сайты производителей с возможностью купить -&gt; интернет-агрегатор Name: category, dtype: object </code></pre>
1
2016-08-22T09:02:24Z
[ "python", "pandas" ]
Install Python 2.7.* in Windows 10
39,075,184
<p>I am using Windows 10. Just now, have installed Python 3.5 64 bit successfully. However, when I want to install Python 2.7.*, the following error is shown.</p> <p><a href="http://i.stack.imgur.com/P6L6u.png" rel="nofollow"><img src="http://i.stack.imgur.com/P6L6u.png" alt=""></a></p> <p>I even uninstalled Python 3.5, but no luck. Anyone know how to fix this?</p>
-1
2016-08-22T08:57:52Z
39,202,386
<p>OK. I solved the problem by installing a 32-bit version.</p>
0
2016-08-29T09:07:55Z
[ "python", "windows" ]
How to make it so a list is chosen and then an image will be drawn in that location?
39,075,271
<p>I have these 4 lists:</p> <pre><code>attempt_01 = [['Piece A', 'In box']] attempt_02 = [['Piece B', 'In box']] attempt_03 = [['Piece C', 'In box']] attempt_04 = [['Piece D', 'In box']] </code></pre> <p>and I need to create a function being </p> <pre><code>def attempt(attempt_number): </code></pre> <p>so that images that I have created go to these points and start drawing. </p> <p>So let's say <code>attempt_01</code> has been chosen then only the first piece of my image will be drawn. Due to the large amount of code that has been written I cannot post my image that has been drawn using turtle.</p> <p>I have tried this code below so that when the first attempt is put in the function, only A will be drawn, but I do not know how to get only A to draw.</p> <pre><code>def draw_attempt(attempt_number): if 'Piece A' and 'In box': x = 0, 350 elif 'Piece B' and 'In box': y = 0, 350 elif 'Piece C' and 'In box': z = 0, 350 elif 'Piece D' and 'In box': p = 0, 350 goto(x) #STARTS DRAWING FOR IMAGE A(PIECE A CODE IS HERE) goto(y) #STARTS DRAWING FOR IMAGE A(PIECE B CODE IS HERE) goto(z) #STARTS DRAWING FOR IMAGE A(PIECE C CODE IS HERE) goto(p) #STARTS DRAWING FOR IMAGE A(PIECE D CODE IS HERE) </code></pre>
-2
2016-08-22T09:01:24Z
39,077,051
<p>It seems that you need something like this:</p> <pre><code>def draw_attempt(attempt_number): if 'In box': x = 0, 350 elif 'Top_Right': x = 350, 350 elif 'Bottom_Left': x = -350, -350 goto(x) if 'Piece A': #STARTS DRAWING FOR IMAGE A(PIECE A CODE IS HERE) elif 'Piece B': #STARTS DRAWING FOR IMAGE B(PIECE B CODE IS HERE) elif 'Piece C': #STARTS DRAWING FOR IMAGE C(PIECE C CODE IS HERE) </code></pre>
0
2016-08-22T10:23:04Z
[ "python", "python-2.7" ]
Why can't I pass the code test in python3?
39,075,309
<p>what I met is a code question below: <a href="https://www.patest.cn/contests/pat-a-practise/1001" rel="nofollow">https://www.patest.cn/contests/pat-a-practise/1001</a></p> <blockquote> <p>Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).</p> <p>Input</p> <p>Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 &lt;= a, b &lt;= 1000000. The numbers are separated by a space.</p> <p>Output</p> <p>For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.</p> <p>Sample Input</p> <p>-1000000 9</p> <p>Sample Output</p> <p>-999,991</p> </blockquote> <p>This is my code below:</p> <pre><code>if __name__ == "__main__": aline = input() astr,bstr = aline.strip().split() a,b = int(astr),int(bstr) sum = a + b sumstr= str(sum) result = '' while sumstr: sumstr, aslice = sumstr[:-3], sumstr[-3:] if sumstr: result = ',' + aslice + result else: result = aslice + result print(result) </code></pre> <p>And the test result turn out to be :</p> <blockquote> <p>时间(Time) 结果(test result) 得分(score) 题目(question number) </p> <p>语言(programe language) 用时(ms)[time consume] 内存(kB)[memory] 用户[user]</p> <p>8月22日 15:46 <strong>部分正确[Partial Correct]</strong>(Why?!!!) 11 1001 </p> <p>Python (python3 3.4.2) 25 3184 polar9527</p> <p>测试点[test point] 结果[result] 用时(ms)[time consume] 内存(kB)[memory] 得分[score]/满分[full credit]</p> <p>0 答案错误[wrong] 25 3056 0/9</p> <p>1 答案正确[correct] 19 3056 1/1</p> <p>10 答案正确[correct] 18 3184 1/1</p> <p>11 答案正确[correct] 19 3176 1/1</p> <p>2 答案正确[correct] 17 3180 1/1</p> <p>3 答案正确[correct] 16 3056 1/1</p> <p>4 答案正确[correct] 14 3184 1/1</p> <p>5 答案正确[correct] 17 3056 1/1</p> <p>6 答案正确[correct] 19 3168 1/1</p> <p>7 答案正确[correct] 22 3184 1/1</p> <p>8 答案正确[correct] 21 3164 1/1</p> <p>9 答案正确[correct] 15 3184 1/1</p> </blockquote>
1
2016-08-22T09:02:54Z
39,076,525
<p>I can give you a simple that doesn't match answer, when you enter -1000000, 9 as a, b in your input, you'll get -,999,991.which is wrong.</p> <p>To get the right answer, you really should get to know format in python.</p> <p>To solve this question, you can just write your code like this.</p> <p><code>if __name__ == "__main__": aline = input() astr,bstr = aline.strip().split() a,b = int(astr),int(bstr) sum = a + b print('{:,}'.format(sum))</code></p>
3
2016-08-22T09:59:20Z
[ "python", "python-3.x" ]
Why can't I pass the code test in python3?
39,075,309
<p>what I met is a code question below: <a href="https://www.patest.cn/contests/pat-a-practise/1001" rel="nofollow">https://www.patest.cn/contests/pat-a-practise/1001</a></p> <blockquote> <p>Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).</p> <p>Input</p> <p>Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 &lt;= a, b &lt;= 1000000. The numbers are separated by a space.</p> <p>Output</p> <p>For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.</p> <p>Sample Input</p> <p>-1000000 9</p> <p>Sample Output</p> <p>-999,991</p> </blockquote> <p>This is my code below:</p> <pre><code>if __name__ == "__main__": aline = input() astr,bstr = aline.strip().split() a,b = int(astr),int(bstr) sum = a + b sumstr= str(sum) result = '' while sumstr: sumstr, aslice = sumstr[:-3], sumstr[-3:] if sumstr: result = ',' + aslice + result else: result = aslice + result print(result) </code></pre> <p>And the test result turn out to be :</p> <blockquote> <p>时间(Time) 结果(test result) 得分(score) 题目(question number) </p> <p>语言(programe language) 用时(ms)[time consume] 内存(kB)[memory] 用户[user]</p> <p>8月22日 15:46 <strong>部分正确[Partial Correct]</strong>(Why?!!!) 11 1001 </p> <p>Python (python3 3.4.2) 25 3184 polar9527</p> <p>测试点[test point] 结果[result] 用时(ms)[time consume] 内存(kB)[memory] 得分[score]/满分[full credit]</p> <p>0 答案错误[wrong] 25 3056 0/9</p> <p>1 答案正确[correct] 19 3056 1/1</p> <p>10 答案正确[correct] 18 3184 1/1</p> <p>11 答案正确[correct] 19 3176 1/1</p> <p>2 答案正确[correct] 17 3180 1/1</p> <p>3 答案正确[correct] 16 3056 1/1</p> <p>4 答案正确[correct] 14 3184 1/1</p> <p>5 答案正确[correct] 17 3056 1/1</p> <p>6 答案正确[correct] 19 3168 1/1</p> <p>7 答案正确[correct] 22 3184 1/1</p> <p>8 答案正确[correct] 21 3164 1/1</p> <p>9 答案正确[correct] 15 3184 1/1</p> </blockquote>
1
2016-08-22T09:02:54Z
39,076,548
<p>Notice the behavior of your code when you input -1000 and 1. You need to handle the minus sign, because it is not a digit.</p>
1
2016-08-22T10:00:06Z
[ "python", "python-3.x" ]
Color time-series based on column values in pandas
39,075,325
<p>I have a time-series in a pandas DataFrame (<code>df.data</code> in the example) and want to color the plot based on the values of another column (<code>df.colors</code>in the example; values are 0, 1, and 2 in this case, but it would be good / more portable if it would also work with <code>float</code>s).</p> <pre><code>import pandas as pd n = 10 seed(1) df = pd.DataFrame(data={"data":randn(n), "colors":randint(0,3,n)}, index=pd.date_range(start="2016-01-01", periods=n)) df.data.plot(style=".", ms=10) </code></pre> <p><a href="http://i.stack.imgur.com/rkP5P.png" rel="nofollow"><img src="http://i.stack.imgur.com/rkP5P.png" alt="Uncolored time-series plot"></a></p> <p>What I am looking for is something like </p> <pre><code>df.data.plot(style=".", color=df.colors) </code></pre> <p>(which does not work), in order to produce a plot like this:</p> <p><a href="http://i.stack.imgur.com/qix8Z.png" rel="nofollow"><img src="http://i.stack.imgur.com/qix8Z.png" alt="Colored time-series plot"></a></p> <p>Here the markers are colored red, orange, and green, for <code>colors==0</code>, <code>1</code>, and <code>2</code>, respectively. It's relatively easy to do this manually for few data and few colors, but is there a straightforward way to do this automatically? </p> <p>There seems to be a solution using <code>plt.scatter</code> and colormaps, as shown in the answer to <a href="http://stackoverflow.com/questions/25741214/how-to-use-colormaps-to-color-plots-of-pandas-dataframes">How to use colormaps to color plots of Pandas DataFrames</a>, but using <code>plt.scatter</code> with a datetime index destroys the convenient automatic axis scaling of using <code>df.data.plot(...)</code>. Is there a way using this notation?</p>
1
2016-08-22T09:03:30Z
39,076,655
<p>One way to achieve this would be to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>DF.replace</code></a> and create a nested <code>dictionary</code> to specify the color values for the <code>int/float</code> values to be mapped against.</p> <pre><code>plt.style.use('seaborn-white') df.replace({'colors':{0:'red',1:'orange',2:'green'}}, inplace=True) </code></pre> <p>You could then perform <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>DF.groupby</code></a> on it to keep the colors same for each subgroup of the <code>groupby</code> object on every iteration step.</p> <pre><code>for index, group in df.groupby('colors'): group['data'].plot(style=".", x_compat=True, ms=10, color=index, grid=True) </code></pre> <p><a href="http://i.stack.imgur.com/7bell.png" rel="nofollow"><img src="http://i.stack.imgur.com/7bell.png" alt="Image"></a></p>
2
2016-08-22T10:05:09Z
[ "python", "pandas", "matplotlib" ]
Syntaxnet / Parsey McParseface python API
39,075,339
<p>I've installed syntaxnet and am able to run the parser with the provided demo script. Ideally, I would like to run it directly from python. The only code I found was this:</p> <pre><code>import subprocess import os os.chdir(r"../models/syntaxnet") subprocess.call([ "echo 'Bob brought the pizza to Alice.' | syntaxnet/demo.sh" ], shell = True) </code></pre> <p>which is a complete disaster - inefficient and over-complex (calling python from python should be done with python).</p> <p>How can I call the python APIs directly, without going through shell scripts, standard I/O, etc?</p> <p>EDIT - <strong>Why isn't this as easy as opening syntaxnet/demo.sh and reading it?</strong></p> <p>This shell script calls two python scripts (parser_eval and conll2tree) which are written as python scripts and can't be imported into a python module without causing multiple errors. A closer look yields additional script-like layers and native code. These upper layers need to be refactored in order to run the whole thing in a python context. Hasn't anyone forked syntaxnet with such a modification or intend to do so?</p>
4
2016-08-22T09:04:15Z
39,815,499
<p>All in all it doesn't look like it would be a problem to refactor the two scripts demo.sh runs (<a href="https://github.com/tensorflow/models/blob/master/syntaxnet/syntaxnet/parser_eval.py" rel="nofollow">https://github.com/tensorflow/models/blob/master/syntaxnet/syntaxnet/parser_eval.py</a> and <a href="https://github.com/tensorflow/models/blob/master/syntaxnet/syntaxnet/conll2tree.py" rel="nofollow">https://github.com/tensorflow/models/blob/master/syntaxnet/syntaxnet/conll2tree.py</a>) into a Python module that exposes a Python API you can call.</p> <p>Both scripts use Tensorflow's tf.app.flags API (described here in this SO question: <a href="http://stackoverflow.com/questions/33932901/whats-the-purpose-of-tf-app-flags-in-tensorflow">What&#39;s the purpose of tf.app.flags in TensorFlow?</a>), so those would have to be refactored out to regular arguments, as <code>tf.app.flags</code> is a process-level singleton.</p> <p>So yeah, you'd just have to do the work to make these callable as a Python API :) </p>
1
2016-10-02T09:08:53Z
[ "python", "nlp", "syntaxnet", "parsey-mcparseface" ]
Python: Scale each row of 2d array to values that sum to 1. Each row contains some negative values
39,075,390
<p>Let's say I have an array:</p> <pre><code>myArray = [[-1.58, -1.09, -0.41, 0.22, -0.95], [-1.16, -1.27, -1.89, -1.01, 1.11], [-0.73, -0.81, -0.47, -0.46, -0.04], [-1.46, -0.82, 0.40, -0.22, -1.82], [-1.12 , -0.97, -0.89, -0.18, 0.06]] </code></pre> <p>I wish to convert each line of this array into values that sum to 1 for each row.</p> <p>Is this easily possible?</p> <p>My actual array is several thousand lines long, so I would like a solution that optimizes well if possible. Thank you very much!</p> <p>I realize that I'm not being clear. I want the resulting values to be <strong>positive</strong> and <strong>sum to 1</strong>. Sorry.</p> <p>I can give you a sample using positive values (That's total at the end):</p> <p><br>Row1 1.10 2.20 3.30 4.40 5.50 (Total = 16.50) <br>Row2 2.20 3.30 4.40 5.50 6.60 (Total = 22.00) <br>Row3 4.20 5.01 2.50 3.30 1.10 (Total = 16.11)</p> <p>to (again total at the end)::</p> <p><br>Row1 0.07 0.13 0.20 0.27 0.33 (Total = 1.00) <br>Row2 0.10 0.15 0.20 0.25 0.30 (Total = 1.00) <br>Row3 0.26 0.31 0.16 0.20 0.07 (Total = 1.00)</p> <p>And i achieve this by simply adding a row, then diving each cell in each row by the total of that row. I don't know how to achieve this in python with an array, with negative values.</p>
0
2016-08-22T09:06:35Z
39,075,479
<p>Is it what you're asking for:</p> <pre><code>myArray = [[-1.58, -1.09, -0.41, 0.22, -0.95], [-1.16, -1.27, -1.89, -1.01, 1.11], [-0.73, -0.81, -0.47, -0.46, -0.04], [-1.46, -0.82, 0.40, -0.22, -1.82], [-1.12 , -0.97, -0.89, -0.18, 0.06]] print [sum(_list) for _list in myArray] </code></pre> <p>?</p> <pre><code>[-3.8099999999999996, -4.219999999999999, -2.51, -3.92, -3.1] </code></pre>
0
2016-08-22T09:10:53Z
[ "python", "multidimensional-array", "probability" ]
Python: Scale each row of 2d array to values that sum to 1. Each row contains some negative values
39,075,390
<p>Let's say I have an array:</p> <pre><code>myArray = [[-1.58, -1.09, -0.41, 0.22, -0.95], [-1.16, -1.27, -1.89, -1.01, 1.11], [-0.73, -0.81, -0.47, -0.46, -0.04], [-1.46, -0.82, 0.40, -0.22, -1.82], [-1.12 , -0.97, -0.89, -0.18, 0.06]] </code></pre> <p>I wish to convert each line of this array into values that sum to 1 for each row.</p> <p>Is this easily possible?</p> <p>My actual array is several thousand lines long, so I would like a solution that optimizes well if possible. Thank you very much!</p> <p>I realize that I'm not being clear. I want the resulting values to be <strong>positive</strong> and <strong>sum to 1</strong>. Sorry.</p> <p>I can give you a sample using positive values (That's total at the end):</p> <p><br>Row1 1.10 2.20 3.30 4.40 5.50 (Total = 16.50) <br>Row2 2.20 3.30 4.40 5.50 6.60 (Total = 22.00) <br>Row3 4.20 5.01 2.50 3.30 1.10 (Total = 16.11)</p> <p>to (again total at the end)::</p> <p><br>Row1 0.07 0.13 0.20 0.27 0.33 (Total = 1.00) <br>Row2 0.10 0.15 0.20 0.25 0.30 (Total = 1.00) <br>Row3 0.26 0.31 0.16 0.20 0.07 (Total = 1.00)</p> <p>And i achieve this by simply adding a row, then diving each cell in each row by the total of that row. I don't know how to achieve this in python with an array, with negative values.</p>
0
2016-08-22T09:06:35Z
39,076,004
<p>First using min-max normalization to transform original data, this could be one approach:</p> <pre><code>myArray = [[-1.58, -1.09, -0.41, 0.22, -0.95], [-1.16, -1.27, -1.89, -1.01, 1.11], [-0.73, -0.81, -0.47, -0.46, -0.04], [-1.46, -0.82, 0.40, -0.22, -1.82], [-1.12 , -0.97, -0.89, -0.18, 0.06]] #Transform data normalizedArray = [] for row in range(0, len(myArray)): list = [] Min = min(myArray[row]) Max = max(myArray[row]) for element in myArray[row]: list.append( float(element-Min)/float(Max- Min) ) normalizedArray.append(list) #Normalize to 1 newArray = [] for row in range(0, len(normalizedArray)): list = [x / sum(normalizedArray[row]) for x in normalizedArray[row]] newArray.append(list) </code></pre>
1
2016-08-22T09:35:10Z
[ "python", "multidimensional-array", "probability" ]
Python: Scale each row of 2d array to values that sum to 1. Each row contains some negative values
39,075,390
<p>Let's say I have an array:</p> <pre><code>myArray = [[-1.58, -1.09, -0.41, 0.22, -0.95], [-1.16, -1.27, -1.89, -1.01, 1.11], [-0.73, -0.81, -0.47, -0.46, -0.04], [-1.46, -0.82, 0.40, -0.22, -1.82], [-1.12 , -0.97, -0.89, -0.18, 0.06]] </code></pre> <p>I wish to convert each line of this array into values that sum to 1 for each row.</p> <p>Is this easily possible?</p> <p>My actual array is several thousand lines long, so I would like a solution that optimizes well if possible. Thank you very much!</p> <p>I realize that I'm not being clear. I want the resulting values to be <strong>positive</strong> and <strong>sum to 1</strong>. Sorry.</p> <p>I can give you a sample using positive values (That's total at the end):</p> <p><br>Row1 1.10 2.20 3.30 4.40 5.50 (Total = 16.50) <br>Row2 2.20 3.30 4.40 5.50 6.60 (Total = 22.00) <br>Row3 4.20 5.01 2.50 3.30 1.10 (Total = 16.11)</p> <p>to (again total at the end)::</p> <p><br>Row1 0.07 0.13 0.20 0.27 0.33 (Total = 1.00) <br>Row2 0.10 0.15 0.20 0.25 0.30 (Total = 1.00) <br>Row3 0.26 0.31 0.16 0.20 0.07 (Total = 1.00)</p> <p>And i achieve this by simply adding a row, then diving each cell in each row by the total of that row. I don't know how to achieve this in python with an array, with negative values.</p>
0
2016-08-22T09:06:35Z
39,076,167
<p>As I say, I don't think you can achieve exactly what you need (because if you have a mix of positive and negative values, you'll always have a mix of positive and negative values in the ratio of the value to the sum of the row). But this gets close, I think.</p> <pre><code>import numpy as np myArray = [[-1.58, -1.09, -0.41, 0.22, -0.95], [-1.16, -1.27, -1.89, -1.01, 1.11], [-0.73, -0.81, -0.47, -0.46, -0.04], [-1.46, -0.82, 0.40, -0.22, -1.82], [-1.12 , -0.97, -0.89, -0.18, 0.06]] new_array = abs(np.asarray(new_array)) ratio_array = np.divide(new_array, new_array.sum(axis=1)) </code></pre> <p>EDIT: I've used <code>%timeit</code>, and a <code>numpy</code> method is 10x faster than the looping method above.</p> <pre><code>new_array = np.asarray(myArray) transformed_array = new_array + (np.min(new_array, axis=1) * -1)[:, None] ratio_matrix = transformed_array / np.sum(transformed_array, axis=1)[:, None] </code></pre>
1
2016-08-22T09:41:59Z
[ "python", "multidimensional-array", "probability" ]
Python: Scale each row of 2d array to values that sum to 1. Each row contains some negative values
39,075,390
<p>Let's say I have an array:</p> <pre><code>myArray = [[-1.58, -1.09, -0.41, 0.22, -0.95], [-1.16, -1.27, -1.89, -1.01, 1.11], [-0.73, -0.81, -0.47, -0.46, -0.04], [-1.46, -0.82, 0.40, -0.22, -1.82], [-1.12 , -0.97, -0.89, -0.18, 0.06]] </code></pre> <p>I wish to convert each line of this array into values that sum to 1 for each row.</p> <p>Is this easily possible?</p> <p>My actual array is several thousand lines long, so I would like a solution that optimizes well if possible. Thank you very much!</p> <p>I realize that I'm not being clear. I want the resulting values to be <strong>positive</strong> and <strong>sum to 1</strong>. Sorry.</p> <p>I can give you a sample using positive values (That's total at the end):</p> <p><br>Row1 1.10 2.20 3.30 4.40 5.50 (Total = 16.50) <br>Row2 2.20 3.30 4.40 5.50 6.60 (Total = 22.00) <br>Row3 4.20 5.01 2.50 3.30 1.10 (Total = 16.11)</p> <p>to (again total at the end)::</p> <p><br>Row1 0.07 0.13 0.20 0.27 0.33 (Total = 1.00) <br>Row2 0.10 0.15 0.20 0.25 0.30 (Total = 1.00) <br>Row3 0.26 0.31 0.16 0.20 0.07 (Total = 1.00)</p> <p>And i achieve this by simply adding a row, then diving each cell in each row by the total of that row. I don't know how to achieve this in python with an array, with negative values.</p>
0
2016-08-22T09:06:35Z
39,076,603
<p>Here's a working example:</p> <pre><code>data = [[-1.58, -1.09, -0.41, 0.22, -0.95], [-1.16, -1.27, -1.89, -1.01, 1.11], [-0.73, -0.81, -0.47, -0.46, -0.04], [-1.46, -0.82, 0.40, -0.22, -1.82], [-1.12, -0.97, -0.89, -0.18, 0.06]] print[[x / sum(data[r]) for x in data[r]] for r in range(0, len(data))] </code></pre>
0
2016-08-22T10:02:34Z
[ "python", "multidimensional-array", "probability" ]
Python matplotlib blit and update a text
39,075,454
<p>I know that this topic is often popping out, but after many tries, searches and give-ups, I am bringing it back to you.</p> <p>I have a class, which contains a matplotlib figure. In this figure, I want a text, and when the user hits some key, the text is updated to something, without drawing all the heavy stuff in the axis. It looks like I need to blit someone here, but how? Here is a working example, the best I could get to until now.</p> <pre><code>import matplotlib as mpl mpl.use('TkAgg') import matplotlib.pyplot as plt import numpy as np class textUpdater: def __init__(self): self.fig, self.ax = plt.subplots() # self.text = plt.figtext(.02, .14, 'Blibli') self.text = self.ax.text(0, .5, 'Blabla')#, transform = self.ax.transAxes)#, animated=True) self.fig.canvas.mpl_connect('key_press_event', self.action) self.fig.canvas.draw() plt.show() def action(self, event): if event.key == 'z': self.text.set_text('Blooooo') self.ax.draw_artist(self.text) self.fig.canvas.blit(self.text.get_window_extent()) textUpdater() </code></pre> <p>First question: when bliting the thing, the previous text appears behind. I want it gone!</p> <p>And second: I would in fact prefer to have it as a fig text, out of any axes. Does it sound feasible?</p> <p>Your are the bests, thanks a lot.</p>
0
2016-08-22T09:09:46Z
39,076,800
<p>The previous text still stays behind, because you never removed it - you just drew on top of it. To prevent this, you should save the piece of figure where the text will be, then show the text, then, when the text has changed, restore the saved background and reshow the text.</p> <p><a href="http://matplotlib.org/api/animation_api.html#matplotlib.animation.ArtistAnimation" rel="nofollow">matplotlib.ArtistAnimation</a> already does all this for you, so you can just use it:</p> <pre><code>import matplotlib as mpl mpl.use('TkAgg') import matplotlib.pyplot as plt from matplotlib.animation import ArtistAnimation import numpy as np class textUpdater: def __init__(self): self.fig, self.ax = plt.subplots() self.text = self.ax.text(.5, .5, 'Blabla') self.fig.canvas.mpl_connect('key_press_event', self.action) self.fig.canvas.draw() self.animation = ArtistAnimation(self.fig, [(self.text,)]) plt.show() def action(self, event): if event.key == 'z': self.text.set_text('Blooooo') textUpdater() </code></pre> <p>Now, to your second question, <a href="http://matplotlib.org/api/figure_api.html?highlight=figure.text#matplotlib.figure.Figure.text" rel="nofollow">Figure.text</a> will create a text that belongs just to the figure, but <code>ArtistAnimation</code> does not support artists that do not belong to any axes, so in this case you might want to redefine <code>ArtistAnimation</code> to support this.</p>
1
2016-08-22T10:11:36Z
[ "python", "matplotlib", "blit" ]
python __delete__ not working
39,075,469
<p>I'm trying this simple python code:</p> <pre><code>class A: def __init__( self ): self.a = { 'k' : 'kk' } def __delete__( self, key ): del self.a[key] </code></pre> <p>This simple class doesn't work.</p> <pre><code>&gt;&gt;&gt; a = A() &gt;&gt;&gt; del a['k'] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'A' object does not support item deletion </code></pre> <p>So how should I proper implement item deletion in python ? Thank you for your help.</p>
-3
2016-08-22T09:10:37Z
39,075,586
<p>In order to achieve the behavior of <code>del a['k']</code> (i.e. deleting an item by index) you should implement the <a href="https://docs.python.org/3/reference/datamodel.html#object.__delitem__" rel="nofollow"><code>__delitem__</code></a> magic method:</p> <pre><code>In [1]: class A: ...: def __init__(self): ...: self.a = {'k': 'kk' } ...: def __delitem__(self, key): ...: del self.a[key] ...: In [2]: a = A() In [3]: a.a Out[3]: {'k': 'kk'} In [4]: del a['k'] In [5]: a.a Out[5]: {} </code></pre>
3
2016-08-22T09:16:01Z
[ "python", "python-3.x" ]
RadioSelect with image
39,075,520
<p>Is it possible for Pmw.RadioSelect's buttons to have an icon next to the text? Supposing we have a few buttons added in a Frame, each one of them has different icon on left or right side of text.</p>
-2
2016-08-22T09:12:58Z
39,076,027
<p>You can add images to RadioButton widgets by doing this:</p> <pre><code>from tkinter import * root = Tk() radiobtn = Radiobutton(root) # Image location (add "/" not "\") img = PhotoImage(file="C:/path to image/image.png") # Applying image to the Radiobutton radiobtn.config(image=img) # Display Radiobutton radiobtn.pack() root.mainloop() </code></pre> <p>Check out <a href="http://effbot.org/tkinterbook/radiobutton.htm" rel="nofollow">Radiobutton documentation</a> for more info.</p>
1
2016-08-22T09:36:10Z
[ "python", "tkinter" ]
IndexError: list index out of range python 3.4
39,075,601
<p>Trying to run this code :</p> <pre><code>sorted_by_name = sorted(sort_array,key=lambda x:x[0])) </code></pre> <p>I get: </p> <blockquote> <p>IndexError: list index out of range</p> </blockquote> <p>How do I resolve this?</p> <p>Thanks</p>
1
2016-08-22T09:16:35Z
39,077,609
<p>Well one of element in the <code>sort_array</code> should be either empty or null string. See the below examples</p> <p>Example #1:</p> <pre><code>sort_array = ['abc', 'acd', 'abcd', ''] sort_array ['abc', 'acd', 'abcd', ''] sorted(sort_array, key=lambda student: student[0]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; IndexError: string index out of range </code></pre> <p>For example #2, i will take sort_array as list of lists, which matches more to your example of <code>sorted_by_name</code></p> <pre><code>&gt;&gt;&gt; student_tuples = [ ... ['john', 'A', 15], ... [] ... ] &gt;&gt;&gt; sorted_by_name = sorted(student_tuples,key=lambda x:x[0]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; IndexError: list index out of range </code></pre> <p>Hence I request you to please check your input <code>sort_array</code> once, if it has any empty lists</p>
1
2016-08-22T10:49:14Z
[ "python", "python-3.x", "lambda" ]
IndexError: list index out of range python 3.4
39,075,601
<p>Trying to run this code :</p> <pre><code>sorted_by_name = sorted(sort_array,key=lambda x:x[0])) </code></pre> <p>I get: </p> <blockquote> <p>IndexError: list index out of range</p> </blockquote> <p>How do I resolve this?</p> <p>Thanks</p>
1
2016-08-22T09:16:35Z
39,077,916
<p>That means that at least one thing in your list is empty so doesn't have a first element. The fix is simple, don't pass a key:</p> <pre><code>sorted_by_name = sorted(sort_array) </code></pre> <p>The default implementation of <code>sorted</code> already tries the first item, then the second item, the third item, etc. When you pass it a key, it first tries your key, the first item. If it finds that two are the same, it does its own check. It checks the first item (again), the second item, the third item, etc. In other words, both are the same except that supplying a key might mean that the first item is checked twice, and of course the default implementation doesn't error on an empty list.</p>
0
2016-08-22T11:04:32Z
[ "python", "python-3.x", "lambda" ]
gae intermittent import error (SignedSerializer)
39,075,984
<p>I have a Pyramid app that I'm running on GAE. It works great most of the time but sometimes when I deploy (<code>appcfg.py update ...</code>) things just break. I start getting 500s when I try to access the app. Then if I make absolutely no changes to my code and deploy it again it works. I want the deploy to work every time.</p> <p>Here's the traceback:</p> <pre><code>Traceback (most recent call last): File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = __import__(path[0]) File "/base/data/home/apps/s~projectwaxed/1.395098752063981059/waxed_backend/__init__.py", line 11, in &lt;module&gt; from pyramid.config import Configurator File "libs/pyramid/config/__init__.py", line 73, in &lt;module&gt; from pyramid.config.routes import RoutesConfiguratorMixin File "libs/pyramid/config/routes.py", line 21, in &lt;module&gt; import pyramid.config.predicates File "libs/pyramid/config/predicates.py", line 15, in &lt;module&gt; from pyramid.session import check_csrf_token File "libs/pyramid/session.py", line 11, in &lt;module&gt; from webob.cookies import SignedSerializer ImportError: cannot import name SignedSerializer </code></pre> <p>Has anyone experienced this? Is there a known fix?</p>
0
2016-08-22T09:34:17Z
39,099,313
<p>The problem was that I was pushing webob 1.6.1 to appengine while deploying my app. At the same time I had this in my app.yaml:</p> <pre><code>libraries: - name: webob version: latest </code></pre> <p>What ended up working was just removing webob from app.yaml (I tried different versions supported by gae but no dice...)</p>
0
2016-08-23T10:59:19Z
[ "python", "google-app-engine", "importerror", "intermittent" ]
Asynchronious email sending using celery doesn't work
39,076,025
<p>I'm trying to make Django not to wait until an email is sent. I've decided to use Celery to do that. Unfortunately I can't figure out how to make it work asynchronously. </p> <p>I've created a file <code>tasks.py</code>:</p> <pre><code># -*- coding: utf-8 -*- from __future__ import absolute_import from .notifications import CustomerNotifications from celery import shared_task @shared_task def prereservation_has_been_confirmed(reservation): CustomerNotifications.prereservation_has_been_confirmed(reservation) </code></pre> <p>The <code>CustomerNotifications.prereservation_has_been_confirmed(reservation)</code> method sends an email to customer. </p> <p>Email sending works but it still waits until the email is sent. (the view is called by <code>AJAX</code>).</p> <p>Do you know what to do?</p> <p><strong>EDIT</strong></p> <p>This is how the function is being called:</p> <pre><code>@csrf_exempt def reservation_confirm(request): if request.method == 'POST': reservation_id = request.POST.get('reservation_id', False) reservation = get_object_or_404(dolava_models.Reservation, id=reservation_id) reservation.confirmed = True reservation.save() tasks.prereservation_has_been_confirmed(reservation) return JsonResponse({}) raise Http404(u'...') </code></pre> <p>I tried <code>tasks.prereservation_has_been_confirmed.delay(reservation)</code> but it returns that connection has been refused.</p> <p><strong>SETTINGS.PY</strong> - added <code>BROKER_URL = 'django://'</code>, <code>'kombu.transport.django'</code> and migrated.</p> <pre><code># -*- coding: utf-8 -*- """ Django settings for dolava project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret_key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'admin_interface', 'flat', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', # 'djcelery_email', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dolava_app', # 'constance', # 'constance.backends.database', 'solo', 'django_extensions', 'django_tables2', 'django_countries', 'kombu.transport.django' ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dolava.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'dolava.wsgi.application' BROKER_URL = 'django://' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') # CELERY_ALWAYS_EAGER = True # SMTP SETTINGS # EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # EMAIL_BACKEND = "mailer.backend.DbBackend" EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxx@gmail.com' EMAIL_HOST_PASSWORD = 'pass' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' </code></pre>
0
2016-08-22T09:36:04Z
39,077,043
<p>You are not making async call to <code>prereservation_has_been_confirmed()</code> in order to delay function execution use <code>prereservation_has_been_confirmed.delay(...)</code></p> <pre><code>@csrf_exempt def reservation_confirm(request): if request.method == 'POST': reservation_id = request.POST.get('reservation_id', False) reservation = get_object_or_404(dolava_models.Reservation, id=reservation_id) reservation.confirmed = True reservation.save() # change HERE, you are calling your function directly not asynchronously tasks.prereservation_has_been_confirmed(reservation) # change to below # tasks.prereservation_has_been_confirmed.delay(reservation) return JsonResponse({}) raise Http404(u'...') </code></pre> <p>Other than that, you have not configured Celery properly to use in Django app. See <a href="http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html" rel="nofollow">Django celery first steps</a></p>
1
2016-08-22T10:22:34Z
[ "python", "django", "celery", "django-celery" ]
Asynchronious email sending using celery doesn't work
39,076,025
<p>I'm trying to make Django not to wait until an email is sent. I've decided to use Celery to do that. Unfortunately I can't figure out how to make it work asynchronously. </p> <p>I've created a file <code>tasks.py</code>:</p> <pre><code># -*- coding: utf-8 -*- from __future__ import absolute_import from .notifications import CustomerNotifications from celery import shared_task @shared_task def prereservation_has_been_confirmed(reservation): CustomerNotifications.prereservation_has_been_confirmed(reservation) </code></pre> <p>The <code>CustomerNotifications.prereservation_has_been_confirmed(reservation)</code> method sends an email to customer. </p> <p>Email sending works but it still waits until the email is sent. (the view is called by <code>AJAX</code>).</p> <p>Do you know what to do?</p> <p><strong>EDIT</strong></p> <p>This is how the function is being called:</p> <pre><code>@csrf_exempt def reservation_confirm(request): if request.method == 'POST': reservation_id = request.POST.get('reservation_id', False) reservation = get_object_or_404(dolava_models.Reservation, id=reservation_id) reservation.confirmed = True reservation.save() tasks.prereservation_has_been_confirmed(reservation) return JsonResponse({}) raise Http404(u'...') </code></pre> <p>I tried <code>tasks.prereservation_has_been_confirmed.delay(reservation)</code> but it returns that connection has been refused.</p> <p><strong>SETTINGS.PY</strong> - added <code>BROKER_URL = 'django://'</code>, <code>'kombu.transport.django'</code> and migrated.</p> <pre><code># -*- coding: utf-8 -*- """ Django settings for dolava project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret_key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'admin_interface', 'flat', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', # 'djcelery_email', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dolava_app', # 'constance', # 'constance.backends.database', 'solo', 'django_extensions', 'django_tables2', 'django_countries', 'kombu.transport.django' ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dolava.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'dolava.wsgi.application' BROKER_URL = 'django://' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') # CELERY_ALWAYS_EAGER = True # SMTP SETTINGS # EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # EMAIL_BACKEND = "mailer.backend.DbBackend" EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxx@gmail.com' EMAIL_HOST_PASSWORD = 'pass' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' </code></pre>
0
2016-08-22T09:36:04Z
39,077,246
<p>[Following the comments] your task was correctly sent to the broker (to the database in your case) you can probably check that your pending task is there.</p> <p>you don't see anything in the console because you must launch a celery worker that will read all the pending tasks on the broker and will execute them. <a href="http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#starting-the-worker-process" rel="nofollow">have you started the worker process</a>? there you'll see the tasks that are being called and the results or traceback if something fails</p>
2
2016-08-22T10:31:57Z
[ "python", "django", "celery", "django-celery" ]
How do I add the wires.exe directory to the system environment variables
39,076,079
<p>I have a python program that uses the marionette driver for firefox and for it to work the directory of the driver must be added to PATH. I've packaged the driver with the program and I want the python script to automatically add the driver directory to the system PATH. Is it possible to do that in python?</p>
0
2016-08-22T09:38:19Z
39,076,149
<p>Yes, it's possible :) </p> <pre><code>import sys sys.path.insert(0, "C:/path/to/your/driver") </code></pre> <p>This adds to PATH only temporarily. If you want more permanent change, take a look at <a href="http://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath">Permanently add a directory to PYTHONPATH</a> </p>
0
2016-08-22T09:41:13Z
[ "python", "windows", "selenium" ]
returning multiple values in view django
39,076,112
<p>I'm having some difficulty returning multiple values in my view. I can create a model, store the values in the model, and then return it, but this approach is not what I'm looking for because these values will be used once only.</p> <p>Is it possible to return multiple values without storing them in a model?</p> <p>For example, view.py:</p> <pre><code>loanAmount = request.GET.get('desired_loan') repaymentTime = request.GET.get('repayment_time') return render(request, 'blog/draw.html', "I want to return loanAmount and repaymentTime") </code></pre> <p>and then in Template, simply:</p> <pre><code>{{ loanAmount }} </code></pre> <p>How do I go about this? Any direction or help will be appreciated. </p> <p>Thanks,</p>
1
2016-08-22T09:39:50Z
39,076,254
<p>I don't understand your sample code here. The third parameter to <code>render</code> is a dictionary, and you can have as many items as you like in it.</p> <pre><code>return render(request, 'blog/draw.html', {'loanAmount': loanAmount, 'repaymentTime': repaymentTime}) </code></pre>
4
2016-08-22T09:46:09Z
[ "python", "django" ]
if statement always takes first condition python
39,076,133
<p>I am working on a basic python programme where I input a recipe I want to make and the quantity I want to make and the programme should calculate how much of each ingredient I need based on an excel file with the quantities per liter and subtracts the amounts I used from another excel file which contains a list of ingredients I have at home. this should be usable for multiple recipes and I tried this using a raw input and an if statement as can be seen below. However, the programme always uses the first recipe. Also when my input asks for the second recipe.</p> <pre><code>recipe = raw_input("give recipe ") quantity = input("give quantity ") print if recipe == 'recipe1': wb1 = load_workbook('recipe1.xlsx') elif recipe == 'recipe2': wb1 = load_workbook('recipe2.xlsx') </code></pre> <p>any help would be greatly appreciated!</p> <p>!! adittion: I mad this quick translation in English because I am writing my programme in Dutch and I forgot to implement something of which I now see that I causes my problem. recipe = raw_input("give recipe ") quantity = input("give quantity ") print</p> <pre><code>if recipe == 'recipe1' or 'RECIPE1': wb1 = load_workbook('recipe1.xlsx') elif recipe == 'recipe2' or 'RECIPE2': wb1 = load_workbook('recipe2.xlsx') </code></pre> <p>not that the difference is that I also check for writing in capitals only. This seems to cause my problem because when I leave it out it works fine. Sorry for the mistake!</p>
0
2016-08-22T09:40:18Z
39,076,255
<p>Which version of Python do you use?</p> <p>Possibly, you would have to write <code>input()</code> instead of <code>raw_input()</code> (which would result in a non-string variable)? What is the <code>print</code> statement used for?</p>
1
2016-08-22T09:46:10Z
[ "python", "excel", "if-statement", "condition" ]
if statement always takes first condition python
39,076,133
<p>I am working on a basic python programme where I input a recipe I want to make and the quantity I want to make and the programme should calculate how much of each ingredient I need based on an excel file with the quantities per liter and subtracts the amounts I used from another excel file which contains a list of ingredients I have at home. this should be usable for multiple recipes and I tried this using a raw input and an if statement as can be seen below. However, the programme always uses the first recipe. Also when my input asks for the second recipe.</p> <pre><code>recipe = raw_input("give recipe ") quantity = input("give quantity ") print if recipe == 'recipe1': wb1 = load_workbook('recipe1.xlsx') elif recipe == 'recipe2': wb1 = load_workbook('recipe2.xlsx') </code></pre> <p>any help would be greatly appreciated!</p> <p>!! adittion: I mad this quick translation in English because I am writing my programme in Dutch and I forgot to implement something of which I now see that I causes my problem. recipe = raw_input("give recipe ") quantity = input("give quantity ") print</p> <pre><code>if recipe == 'recipe1' or 'RECIPE1': wb1 = load_workbook('recipe1.xlsx') elif recipe == 'recipe2' or 'RECIPE2': wb1 = load_workbook('recipe2.xlsx') </code></pre> <p>not that the difference is that I also check for writing in capitals only. This seems to cause my problem because when I leave it out it works fine. Sorry for the mistake!</p>
0
2016-08-22T09:40:18Z
39,077,846
<p>I found my mistake: it should be </p> <pre><code>if recipe == 'recipe1' or recipe == 'RECIPE1': wb1 = load_workbook('recipe1.xlsx') elif recipe == 'recipe2' or recipe == 'RECIPE2': wb1 = load_workbook('recipe2.xlsx') </code></pre> <p>thank you all for taking the time to help me!</p>
0
2016-08-22T11:01:37Z
[ "python", "excel", "if-statement", "condition" ]
Python2 + 3 : How to install modules for Python3 installed from sources and offline?
39,076,141
<p>I'm using RedHat Linux 6 and currently I only have 2.6.X version available from internal Linux repository. So I installed <strong>Python2 package(s) from repository</strong> and in parallel I installed <strong>python3 from sources into /opt directory</strong> :</p> <pre><code>$ ll /usr/bin/python3 lrwxrwxrwx. 1 root root 29 Jul 4 15:04 /usr/bin/python3 -&gt; /opt/python-3.5.2/bin/python3 </code></pre> <p>Problem is now that I don't know <strong>how to install modules for Python3 installed from sources and so not in default directory</strong> (modules for Python2 are installed from internal repository) without breaking Python 2 install.</p> <p>Moreover <strong>the server does not have access to internet</strong>.</p> <p>How could I manage my Python 3 install to get modules ? I read multiple docs but I cannot figure out how to proceed.</p> <p>Thx, Tom</p>
0
2016-08-22T09:40:50Z
39,076,413
<p>You can use virtualenv to built individual enviroment for different python version, then install thirdparty libraries with offline install package.</p>
0
2016-08-22T09:54:11Z
[ "python", "linux", "install", "offline", "python-module" ]
Python2 + 3 : How to install modules for Python3 installed from sources and offline?
39,076,141
<p>I'm using RedHat Linux 6 and currently I only have 2.6.X version available from internal Linux repository. So I installed <strong>Python2 package(s) from repository</strong> and in parallel I installed <strong>python3 from sources into /opt directory</strong> :</p> <pre><code>$ ll /usr/bin/python3 lrwxrwxrwx. 1 root root 29 Jul 4 15:04 /usr/bin/python3 -&gt; /opt/python-3.5.2/bin/python3 </code></pre> <p>Problem is now that I don't know <strong>how to install modules for Python3 installed from sources and so not in default directory</strong> (modules for Python2 are installed from internal repository) without breaking Python 2 install.</p> <p>Moreover <strong>the server does not have access to internet</strong>.</p> <p>How could I manage my Python 3 install to get modules ? I read multiple docs but I cannot figure out how to proceed.</p> <p>Thx, Tom</p>
0
2016-08-22T09:40:50Z
39,076,656
<ol> <li><p>Change your "python.exe" in your python3 install folder into "python3.exe". Make sure you can use "python" to start Python2 and "pyhton3" to start python3.</p></li> <li><p>For Python3, use the command <code>python3 -m pip</code></p></li> </ol>
1
2016-08-22T10:05:13Z
[ "python", "linux", "install", "offline", "python-module" ]
Generating a image with a List in python Pillow doesnt work
39,076,165
<p>I recently started using pillow for some project but I can't manage to generate a image with a list object. Every int in the list has a value between 0 and 255. So this is my relevant code:</p> <pre><code> img = Image.new('L',(width,height)) img.putdata(pixel) img.save('img.png') </code></pre> <p>The output is always a completely black picture, even when I change every element in pixel to 0. I also tried using 'RGB' mode istead of 'L' mode, but then I get this error:</p> <blockquote> <p>SystemError: new style getargs format but argument is not a tuple</p> </blockquote> <p>I don't really undestand the error, I also changed the list, so that It holds all 3 RGB values as tuples.</p> <p>Any idea what the problems might be?</p> <p>Thanks in advance!</p>
1
2016-08-22T09:41:56Z
39,076,537
<p>Use like this:</p> <pre><code>from PIL import Image pixel = [] for i in range(300*100): pixel.append((255,0,0)) for i in range(300*100): pixel.append((0,255,0)) for i in range(300*100): pixel.append((0,0,255)) img = Image.new('RGB',(300,300)) img.putdata(pixel) img.show() </code></pre> <p>Then you get:</p> <p><a href="http://i.stack.imgur.com/cjzmU.png" rel="nofollow"><img src="http://i.stack.imgur.com/cjzmU.png" alt="enter image description here"></a></p> <blockquote> <p>SystemError: new style getargs format but argument is not a tuple</p> </blockquote> <p>means you should use rgb like the "(R,G,B)" (a <a href="https://docs.python.org/2/library/functions.html?highlight=tuple#tuple" rel="nofollow">tuple</a>).</p>
1
2016-08-22T09:59:42Z
[ "python", "python-imaging-library", "pillow" ]
Sort list of key value pairs in python dictionary
39,076,314
<p>How can I sort an adjacency list in python that is store as a dictionary?</p> <pre><code>Adjacency List: 0: [(7, 0.16), (4, 0.38), (2, 0.26), (6, 0.58)] 1: [(5, 0.32), (7, 0.19), (2, 0.36), (3, 0.29)] 2: [(3, 0.17), (0, 0.26), (1, 0.36), (7, 0.34), (6, 0.4)] 3: [(2, 0.17), (1, 0.29), (6, 0.52)] 4: [(5, 0.35), (7, 0.37), (0, 0.38), (6, 0.93)] 5: [(4, 0.35), (7, 0.28), (1, 0.32)] 6: [(2, 0.4), (3, 0.52), (0, 0.58), (4, 0.93)] 7: [(4, 0.37), (5, 0.28), (0, 0.16), (1, 0.19), (2, 0.34)] </code></pre> <p>I would like each row to be sorted by the floating point number.</p> <p>This is how the values were added but with a loop and reading from stdin rather than manually:</p> <pre><code>adjList = defaultdict(list) adjList[0].append((7, 0.16)) </code></pre> <p>I understand I have to use sorted() and I've tried stuff like this:</p> <pre><code>sorted(adjList) </code></pre> <p>or</p> <pre><code>for i in adjList: sorted(adjList[i]) </code></pre> <p>or</p> <pre><code>value for (key, value) in sorted(adjList[0]) </code></pre>
1
2016-08-22T09:49:25Z
39,076,389
<p><a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a> returns a new sorted list given an iterable. If you want to sort in-place, use <a href="https://docs.python.org/3/library/stdtypes.html?highlight=sort#list.sort" rel="nofollow"><code>list.sort()</code></a>:</p> <pre><code>from operator import itemgetter for k in adjList: adjList[k].sort(key=itemgetter(1)) </code></pre> <p>The <code>key=itemgetter(1)</code> makes sure it is sorted on the second element of the tuple, alternatively you could also write <code>key=lambda x: x[1]</code>.</p> <p>If you want to sort in decreasing order instead, use <code>key=itemgetter(1), reverse=True</code>.</p>
4
2016-08-22T09:53:08Z
[ "python", "list", "sorting", "dictionary", "adjacency-list" ]
Sort list of key value pairs in python dictionary
39,076,314
<p>How can I sort an adjacency list in python that is store as a dictionary?</p> <pre><code>Adjacency List: 0: [(7, 0.16), (4, 0.38), (2, 0.26), (6, 0.58)] 1: [(5, 0.32), (7, 0.19), (2, 0.36), (3, 0.29)] 2: [(3, 0.17), (0, 0.26), (1, 0.36), (7, 0.34), (6, 0.4)] 3: [(2, 0.17), (1, 0.29), (6, 0.52)] 4: [(5, 0.35), (7, 0.37), (0, 0.38), (6, 0.93)] 5: [(4, 0.35), (7, 0.28), (1, 0.32)] 6: [(2, 0.4), (3, 0.52), (0, 0.58), (4, 0.93)] 7: [(4, 0.37), (5, 0.28), (0, 0.16), (1, 0.19), (2, 0.34)] </code></pre> <p>I would like each row to be sorted by the floating point number.</p> <p>This is how the values were added but with a loop and reading from stdin rather than manually:</p> <pre><code>adjList = defaultdict(list) adjList[0].append((7, 0.16)) </code></pre> <p>I understand I have to use sorted() and I've tried stuff like this:</p> <pre><code>sorted(adjList) </code></pre> <p>or</p> <pre><code>for i in adjList: sorted(adjList[i]) </code></pre> <p>or</p> <pre><code>value for (key, value) in sorted(adjList[0]) </code></pre>
1
2016-08-22T09:49:25Z
39,076,435
<p>Here's a working example:</p> <pre><code>my_dict = { 0: [(7, 0.16), (4, 0.38), (2, 0.26), (6, 0.58)], 1: [(5, 0.32), (7, 0.19), (2, 0.36), (3, 0.29)], 2: [(3, 0.17), (0, 0.26), (1, 0.36), (7, 0.34), (6, 0.4)], 3: [(2, 0.17), (1, 0.29), (6, 0.52)], 4: [(5, 0.35), (7, 0.37), (0, 0.38), (6, 0.93)], 5: [(4, 0.35), (7, 0.28), (1, 0.32)], 6: [(2, 0.4), (3, 0.52), (0, 0.58), (4, 0.93)], 7: [(4, 0.37), (5, 0.28), (0, 0.16), (1, 0.19), (2, 0.34)] } out = {k: sorted(v, key=lambda x: x[1]) for k, v in my_dict.iteritems()} print out </code></pre>
1
2016-08-22T09:55:13Z
[ "python", "list", "sorting", "dictionary", "adjacency-list" ]
Sort list of key value pairs in python dictionary
39,076,314
<p>How can I sort an adjacency list in python that is store as a dictionary?</p> <pre><code>Adjacency List: 0: [(7, 0.16), (4, 0.38), (2, 0.26), (6, 0.58)] 1: [(5, 0.32), (7, 0.19), (2, 0.36), (3, 0.29)] 2: [(3, 0.17), (0, 0.26), (1, 0.36), (7, 0.34), (6, 0.4)] 3: [(2, 0.17), (1, 0.29), (6, 0.52)] 4: [(5, 0.35), (7, 0.37), (0, 0.38), (6, 0.93)] 5: [(4, 0.35), (7, 0.28), (1, 0.32)] 6: [(2, 0.4), (3, 0.52), (0, 0.58), (4, 0.93)] 7: [(4, 0.37), (5, 0.28), (0, 0.16), (1, 0.19), (2, 0.34)] </code></pre> <p>I would like each row to be sorted by the floating point number.</p> <p>This is how the values were added but with a loop and reading from stdin rather than manually:</p> <pre><code>adjList = defaultdict(list) adjList[0].append((7, 0.16)) </code></pre> <p>I understand I have to use sorted() and I've tried stuff like this:</p> <pre><code>sorted(adjList) </code></pre> <p>or</p> <pre><code>for i in adjList: sorted(adjList[i]) </code></pre> <p>or</p> <pre><code>value for (key, value) in sorted(adjList[0]) </code></pre>
1
2016-08-22T09:49:25Z
39,076,523
<p>You can use <a href="https://docs.python.org/3/library/stdtypes.html?highlight=sort#list.sort" rel="nofollow"><code>list.sort()</code></a> with a key function. Since you want to sort by the second element of each tuple, the key function must select the second item (<code>t[1]</code> below) from each tuple, <code>t</code>:</p> <pre><code>for key in adjList: d[key].sort(key=lambda t: t[1]) </code></pre> <p><code>list.sort()</code> will sort the list in place no rebinding of variables is required.</p>
1
2016-08-22T09:59:15Z
[ "python", "list", "sorting", "dictionary", "adjacency-list" ]
How to get all key combinations after groupby in Python Pandas
39,076,360
<p>I would like to have all combination of keys after a groupby so if <code>a</code> has <code>na</code> unique values and <code>b</code> has <code>nb</code> unique values than the number of output rows should be <code>na*nb</code>. I have tried <code>reindex</code> and <code>reindex_axis</code> but it didn't work:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'a': [1,1,2,3],'b':[1, 2, 3,4], 'c':[1,2,3,4]}) &gt;&gt;&gt; df.groupby(['a','b']).count() c a b 1 1 1 2 1 2 3 1 3 4 1 </code></pre> <p>I would like to get:</p> <pre><code>a b 1 1 1 2 1 3 None 4 None 2 1 None 2 None 3 1 4 None 3 1 None 2 None 3 None 4 1 </code></pre>
0
2016-08-22T09:51:51Z
39,076,442
<p>You can use reindex:</p> <pre><code>idx = pd.MultiIndex.from_product((df['a'].unique(), df['b'].unique())) df.groupby(['a','b']).count().reindex(idx) Out: c 1 1 1.0 2 1.0 3 NaN 4 NaN 2 1 NaN 2 NaN 3 1.0 4 NaN 3 1 NaN 2 NaN 3 NaN 4 1.0 </code></pre>
4
2016-08-22T09:55:45Z
[ "python", "pandas", "group-by" ]
Tensorflow Deep MNIST: Resource exhausted: OOM when allocating tensor with shape[10000,32,28,28]
39,076,388
<p>This is the sample MNIST code I am running:</p> <pre><code>from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import tensorflow as tf sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x,W) + b) def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) x_image = tf.reshape(x, [-1,28,28,1]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) init = tf.initialize_all_variables() config = tf.ConfigProto() config.gpu_options.allocator_type = 'BFC' with tf.Session(config = config) as s: sess.run(init) for i in range(20000): batch = mnist.train.next_batch(50) if i%100 == 0: train_accuracy = accuracy.eval(feed_dict={ x:batch[0], y_: batch[1], keep_prob: 1.0}) print("step %d, training accuracy %g"%(i, train_accuracy)) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) print("test accuracy %g"%accuracy.eval(feed_dict={ x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) </code></pre> <p>The GPU I am using is: <code>GeForce GTX 750 Ti</code></p> <p>Error:</p> <pre><code>... ... ... step 19900, training accuracy 1 I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (256): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (512): Total Chunks: 1, Chunks in use: 0 768B allocated for chunks. 1.20MiB client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (1024): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (2048): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (4096): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (8192): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (16384): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (32768): Total Chunks: 1, Chunks in use: 0 36.8KiB allocated for chunks. 4.79MiB client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (65536): Total Chunks: 1, Chunks in use: 0 78.5KiB allocated for chunks. 4.79MiB client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (131072): Total Chunks: 1, Chunks in use: 0 200.0KiB allocated for chunks. 153.1KiB client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (262144): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (524288): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (1048576): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (2097152): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (4194304): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (8388608): Total Chunks: 1, Chunks in use: 0 11.86MiB allocated for chunks. 390.6KiB client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (16777216): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (33554432): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (67108864): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (134217728): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:639] Bin (268435456): Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin. I tensorflow/core/common_runtime/bfc_allocator.cc:656] Bin for 957.03MiB was 256.00MiB, Chunk State: I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a40000 of size 1280 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a40500 of size 1280 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a40a00 of size 31488 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a48500 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a48600 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a48700 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a48800 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a48900 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a48a00 of size 4096 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a49a00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a49b00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a49c00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a49d00 of size 3328 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a4aa00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a4ab00 of size 204800 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a7cb00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x601a7cc00 of size 12845056 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026bcc00 of size 4096 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026bdc00 of size 40960 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026c7c00 of size 31488 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026cf700 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026cf800 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026cf900 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026cfa00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026cfb00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026cfc00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026cfd00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026cfe00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026cff00 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026d0000 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026d0100 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026d0500 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026d0600 of size 3328 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026d1300 of size 40960 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6026db300 of size 80128 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x602702600 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x602734700 of size 204800 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x603342700 of size 4096 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x603343700 of size 3328 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x60334d700 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x60334d800 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x60334d900 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x60334da00 of size 3328 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x60334e700 of size 3328 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x60334f400 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x60334f500 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x60334f600 of size 204800 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x603381600 of size 204800 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6033b3600 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6033b3700 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6033b3800 of size 12845056 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x603ff3800 of size 12845056 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x604c33800 of size 4096 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x604c34800 of size 4096 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x604c35800 of size 40960 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x604c3f800 of size 40960 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x604c49800 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x604c49900 of size 256 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x604c49a00 of size 13053184 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6058bc700 of size 31360000 I tensorflow/core/common_runtime/bfc_allocator.cc:674] Chunk at 0x6076a4b00 of size 1801385216 I tensorflow/core/common_runtime/bfc_allocator.cc:683] Free at 0x6026d0200 of size 768 I tensorflow/core/common_runtime/bfc_allocator.cc:683] Free at 0x6026eec00 of size 80384 I tensorflow/core/common_runtime/bfc_allocator.cc:683] Free at 0x602702700 of size 204800 I tensorflow/core/common_runtime/bfc_allocator.cc:683] Free at 0x602766700 of size 12435456 I tensorflow/core/common_runtime/bfc_allocator.cc:683] Free at 0x603344400 of size 37632 I tensorflow/core/common_runtime/bfc_allocator.cc:689] Summary of in-use Chunks by size: I tensorflow/core/common_runtime/bfc_allocator.cc:692] 32 Chunks of size 256 totalling 8.0KiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 2 Chunks of size 1280 totalling 2.5KiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 5 Chunks of size 3328 totalling 16.2KiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 5 Chunks of size 4096 totalling 20.0KiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 2 Chunks of size 31488 totalling 61.5KiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 4 Chunks of size 40960 totalling 160.0KiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 1 Chunks of size 80128 totalling 78.2KiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 4 Chunks of size 204800 totalling 800.0KiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 3 Chunks of size 12845056 totalling 36.75MiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 1 Chunks of size 13053184 totalling 12.45MiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 1 Chunks of size 31360000 totalling 29.91MiB I tensorflow/core/common_runtime/bfc_allocator.cc:692] 1 Chunks of size 1801385216 totalling 1.68GiB I tensorflow/core/common_runtime/bfc_allocator.cc:696] Sum Total of in-use chunks: 1.76GiB I tensorflow/core/common_runtime/bfc_allocator.cc:698] Stats: Limit: 1898266624 InUse: 1885507584 MaxInUse: 1885907712 NumAllocs: 2387902 MaxAllocSize: 1801385216 W tensorflow/core/common_runtime/bfc_allocator.cc:270] **********************************************************xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx W tensorflow/core/common_runtime/bfc_allocator.cc:271] Ran out of memory trying to allocate 957.03MiB. See logs for memory state. W tensorflow/core/framework/op_kernel.cc:968] Resource exhausted: OOM when allocating tensor with shape[10000,32,28,28] Traceback (most recent call last): File "trainer_deepMnist.py", line 109, in &lt;module&gt; x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 559, in eval return _eval_using_default_session(self, feed_dict, self.graph, session) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3648, in _eval_using_default_session return session.run(tensors, feed_dict) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 710, in run run_metadata_ptr) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 908, in _run feed_dict_string, options, run_metadata) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 958, in _do_run target_list, options, run_metadata) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 978, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors.ResourceExhaustedError: OOM when allocating tensor with shape[10000,32,28,28] [[Node: Conv2D = Conv2D[T=DT_FLOAT, data_format="NHWC", padding="SAME", strides=[1, 1, 1, 1], use_cudnn_on_gpu=true, _device="/job:localhost/replica:0/task:0/gpu:0"](Reshape, Variable_2/read)]] Caused by op u'Conv2D', defined at: File "trainer_deepMnist.py", line 61, in &lt;module&gt; h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) File "trainer_deepMnist.py", line 46, in conv2d return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_nn_ops.py", line 394, in conv2d data_format=data_format, name=name) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 703, in apply_op op_def=op_def) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2320, in create_op original_op=self._default_original_op, op_def=op_def) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1239, in __init__ self._traceback = _extract_stack() </code></pre> <p>I read some github issues (<a href="https://github.com/tensorflow/tensorflow/issues/136" rel="nofollow">here</a>, <a href="https://github.com/tensorflow/tensorflow/issues/609" rel="nofollow">here</a>) related to the same problem but could not understand how I should change my code to solve this problem.</p>
0
2016-08-22T09:53:01Z
39,080,568
<p>Here is how I solved this problem: the error means that the GPU runs out of memory during accuracy evaluation. Hence it needs a smaller sized dataset, which can be achieved by using data in batches. So, instead of running the code on the whole test dataset it needs to be run in batches as mentioned in this post: <a href="http://stackoverflow.com/questions/37126108/how-to-read-data-into-tensorflow-batches-from-example-queue">How to read data in batches when using TensorFlow</a></p> <p>Hence, for accuracy evaluation on test dataset, instead of this loc :</p> <pre><code>print("test accuracy %g"%accuracy.eval(feed_dict={ x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) </code></pre> <p>this can be used :</p> <pre><code>for i in xrange(10): testSet = mnist.test.next_batch(50) print("test accuracy %g"%accuracy.eval(feed_dict={ x: testSet[0], y_: testSet[1], keep_prob: 1.0})) </code></pre> <p>When i ran <code>1000 epochs</code> for <code>training</code> and used <code>10 batches</code> of <code>batch_size = 50</code> for <code>accuracy evaluation</code>, I got the following results:</p> <pre><code>step 0, training accuracy 0.04 step 100, training accuracy 0.88 step 200, training accuracy 0.9 step 300, training accuracy 0.88 step 400, training accuracy 0.94 step 500, training accuracy 0.96 step 600, training accuracy 0.94 step 700, training accuracy 0.96 step 800, training accuracy 0.9 step 900, training accuracy 1 test accuracy 1 test accuracy 0.92 test accuracy 1 test accuracy 1 test accuracy 0.94 test accuracy 0.96 test accuracy 0.92 test accuracy 0.96 test accuracy 0.92 test accuracy 0.94 </code></pre>
0
2016-08-22T13:13:49Z
[ "python", "tensorflow", "gpu", "mnist" ]
Python 2.7.8 for line iteration error
39,076,390
<p>I want to iterate over all lines in a file with the following script</p> <pre><code>import sys infile = open("test.txt") infile.read() for line in infile if line.find("This") != -1 print line infile.close() </code></pre> <p>Unfortunately, I am getting this error message:</p> <pre><code> File "getRes.py", line 6 for line in infile ^ SyntaxError: invalid syntax </code></pre> <p>I've been trying for an hour to figure out what is the error and I am still not able to find it. Can you tell me what is wrong and how to fix it?</p> <p>PS: I am using Python 2.7.8, I would like to use this old version instead of a more recent version.</p>
-3
2016-08-22T09:53:09Z
39,076,411
<p>You need a colon after any line that introduces a block in Python.</p> <pre><code>for line in infile: if line.find("This") != -1: </code></pre>
2
2016-08-22T09:54:07Z
[ "python", "python-2.7" ]
Python 2.7.8 for line iteration error
39,076,390
<p>I want to iterate over all lines in a file with the following script</p> <pre><code>import sys infile = open("test.txt") infile.read() for line in infile if line.find("This") != -1 print line infile.close() </code></pre> <p>Unfortunately, I am getting this error message:</p> <pre><code> File "getRes.py", line 6 for line in infile ^ SyntaxError: invalid syntax </code></pre> <p>I've been trying for an hour to figure out what is the error and I am still not able to find it. Can you tell me what is wrong and how to fix it?</p> <p>PS: I am using Python 2.7.8, I would like to use this old version instead of a more recent version.</p>
-3
2016-08-22T09:53:09Z
39,082,348
<p>There's another mistake in your code, you don't need:</p> <pre><code>infile.read() </code></pre> <p>Because it reads all contens of infile and doesn't save it to any variable. And what is more important it moves you to the end of file, so there's no more lines to read.</p> <p>In addition there's no need to manualy close file, it's better to use with statement:</p> <pre><code>with open("test.txt") as infile: for line in infile: # do what you want # here file will be close automaticaly, when we exit "with" scope. </code></pre>
0
2016-08-22T14:38:27Z
[ "python", "python-2.7" ]
How to configure an external package into Apache Spark?
39,076,553
<p>I am building a python script executed using <strong>spark-submit</strong> command to retrieve data from <strong>MongoDB</strong> collection and process fetched data to generate analytics. I am utilizing MongoDB Spark connector to query a MongoDB collection using <strong>--packages</strong> option.</p> <p>But I need to configure package into Apache spark and execute python script using spark submit command without <strong>--packages</strong> option.</p> <p>Please suggest me appropriate solution</p>
0
2016-08-22T10:00:12Z
39,078,268
<p>From <a href="http://spark.apache.org/docs/latest/submitting-applications.html" rel="nofollow">http://spark.apache.org/docs/latest/submitting-applications.html</a>:</p> <blockquote> <p>For Python, you can use the --py-files argument of spark-submit to add .py, .zip or .egg files to be distributed with your application. If you depend on multiple Python files we recommend packaging them into a .zip or .egg.</p> </blockquote> <p>So you could write your own layer of data loading logic. However, using a ready-made package has lots of advantages. Maybe you could explain why you cannot use <code>--packages</code>?</p> <p>EDIT</p> <p>Based on the chat, the only reason PO couldn't use <code>--packages</code> is his <code>jar</code> for mongodb is stored locally (and of course not in <code>$PATH</code>). In this case, providing <code>--repositories /PATH/TO/JAR</code> should fix the problem.</p>
1
2016-08-22T11:22:37Z
[ "python", "mongodb", "apache-spark", "pyspark" ]
Required and optional arguments in function
39,076,601
<p>I have a problem with using optional and required arguments in a function.</p> <pre><code>def process_data(*stock, currency) </code></pre> <p>With the arguments</p> <pre><code>process_data('IVV', 'QQQ', 'USD') </code></pre> <p>Yields the error "TypeError: process_data() missing 1 required keyword-only argument: 'currency'"</p>
-1
2016-08-22T10:02:31Z
39,076,681
<p>You need to tell Python that USD is the currency as it has no other way of knowing how to assign values to your variables:</p> <pre><code>process_data('IVV', 'QQQ', currency='USD') </code></pre>
2
2016-08-22T10:06:08Z
[ "python", "python-3.x" ]
Required and optional arguments in function
39,076,601
<p>I have a problem with using optional and required arguments in a function.</p> <pre><code>def process_data(*stock, currency) </code></pre> <p>With the arguments</p> <pre><code>process_data('IVV', 'QQQ', 'USD') </code></pre> <p>Yields the error "TypeError: process_data() missing 1 required keyword-only argument: 'currency'"</p>
-1
2016-08-22T10:02:31Z
39,076,727
<p>Using <code>*params</code> in a function <em>definition</em> groups all positional arguments as a tuple when that function is called. In order to catch any extra arguments you'll need to supply them in keyword form; i.e supply their name:</p> <pre><code>process_data('IVV', 'QQQ', currency='USD') </code></pre> <p>You could alternatively specify <code>currency</code> with a default value of <code>USD</code>:</p> <pre><code>def process_data(*stock, currency='USD') </code></pre> <p>and not need to specify the currency when calling unless you require a different currency:</p> <pre><code>process_data('IVV', 'QQQ') </code></pre>
0
2016-08-22T10:08:21Z
[ "python", "python-3.x" ]
Error using numpy.polyfit in a cx_freezed program
39,076,682
<p>I'm trying to build a standalone program using <code>cx_freeze</code> in Python 3.4.</p> <p>When I execute my program through Python there is absolutely no problems (0 errors, everything works), but when I open the <code>.exe</code> file created with <code>cx_freeze</code>, my GUI (Qt) just closes when I'm calling the <code>polyfit</code> function frin <code>numpy</code>.</p> <p>I think that it's not just an error of importation, because when I try something like "numpy.pi + 2" after <code>cx_freeze</code>, it works fine.</p> <p>Any ideas?</p> <p><em>Notes:</em> </p> <ul> <li>I though it was because my function was a bit complicated, but when I tried <code>polyfit([1,2,3], [4,5,6], 2)</code>, I encounter the same problem</li> <li>Using <code>scipy.polyfit</code> result in the same problem</li> </ul>
0
2016-08-22T10:06:09Z
39,098,331
<p>I solved my problem with :</p> <ul> <li><p>uninstalling all the packages numpy/scipy</p></li> <li><p>reinstall the whl with pip (numpy-1.11.1+mkl-cp34-cp34m-win32.whl and scipy-0.18.0-cp34-cp34m-win32.whl)</p></li> <li><p>install numpy-1.9.2-win32-superpack-python3.4.exe from <a href="https://sourceforge.net/projects/numpy/files/NumPy/1.9.2/" rel="nofollow">https://sourceforge.net/projects/numpy/files/NumPy/1.9.2/</a></p></li> </ul> <p>And now everything works :)</p>
0
2016-08-23T10:13:39Z
[ "python", "python-3.x", "numpy", "cx-freeze" ]
How do I make the code return the text using xpath?
39,076,965
<pre><code>from lxml import html import requests import time #Gets prices page = requests.get('https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&amp;field-keywords=hi') tree = html.fromstring(page.content) price = tree.xpath('//h2[@data-attribute="Hi Guess the Food - What’s the Food Brand in the Picture"]/text()') print(price) </code></pre> <p>This only returns []</p> <p>When looking into page.content, it shows the amazon anti bot stuff. How can I bypass this?</p>
-1
2016-08-22T10:18:47Z
39,077,212
<p>One general advice when you're trying to scrap something from some website. Take a look first to the returned content, in this case <code>page.content</code> before trying anything. You're assuming wrongly amazon is allowing you nicely to fetch their data, when they don't.</p>
0
2016-08-22T10:30:41Z
[ "python", "python-3.x", "parsing", "xpath" ]
How do I make the code return the text using xpath?
39,076,965
<pre><code>from lxml import html import requests import time #Gets prices page = requests.get('https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&amp;field-keywords=hi') tree = html.fromstring(page.content) price = tree.xpath('//h2[@data-attribute="Hi Guess the Food - What’s the Food Brand in the Picture"]/text()') print(price) </code></pre> <p>This only returns []</p> <p>When looking into page.content, it shows the amazon anti bot stuff. How can I bypass this?</p>
-1
2016-08-22T10:18:47Z
39,077,970
<p>I think urllib2 is better, and xpath could be: </p> <pre><code>price = c.xpath('//div[@class="s-item-container"]//h2')[0] print price.text </code></pre> <p>After all, long string may contains strange characters.</p>
0
2016-08-22T11:07:14Z
[ "python", "python-3.x", "parsing", "xpath" ]
Can't Open Word File With Space
39,076,967
<p>I use sikuli to open doc file </p> <pre><code>cmd = r"C:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE c:\report\Monthly report 2016.doc" openApp(cmd) </code></pre> <p>It can't be opened but when i renamed no space to Monthly.doc it can be opened</p>
1
2016-08-22T10:18:55Z
39,077,017
<p>try insert '\' before the space..</p>
0
2016-08-22T10:21:33Z
[ "python", "sikuli", "sikuli-script" ]
Can't Open Word File With Space
39,076,967
<p>I use sikuli to open doc file </p> <pre><code>cmd = r"C:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE c:\report\Monthly report 2016.doc" openApp(cmd) </code></pre> <p>It can't be opened but when i renamed no space to Monthly.doc it can be opened</p>
1
2016-08-22T10:18:55Z
39,097,697
<p>First, App.open is advised as openApp is deprecated. Regardless though this is a command line type problem. It is all about wrapping the quotes. Both should work:</p> <pre><code>App.open(r'"C:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE" "c:\report\Monthly report 2016.doc"') openApp(r'"C:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE" "c:\report\Monthly report 2016.doc"') </code></pre> <p>Small reference on quoting:<br> <a href="https://answers.launchpad.net/sikuli/+faq/1739" rel="nofollow">https://answers.launchpad.net/sikuli/+faq/1739</a></p>
1
2016-08-23T09:43:10Z
[ "python", "sikuli", "sikuli-script" ]
How to print upto n elements in a list
39,077,005
<p>I want to print upto 50 elements in a list</p> <p>i.e If there are 100 elements in the list I need first 50 alone. My current code for the above is 'Filter':switcheroo.get(zaxis,["None Selected"])[zaxis]<strong>.unique().tolist()[:50]</strong></p> <p>If there are 25 elements in the list I need 25 alone. I get an error when the above code is used. from other posts I understand that the below code is the solution, but I cant understand how to implement it with my current code.'</p> <pre><code>[x for _, x in zip(range(n), records)] </code></pre> <p><a href="http://stackoverflow.com/questions/5234090/how-to-take-the-first-n-items-from-a-generator-or-list-in-python">How to take the first N items from a generator or list in Python?</a></p>
-2
2016-08-22T10:20:39Z
39,077,159
<p>first 50 elements of a list:</p> <pre><code> print mylist[:50] </code></pre> <p>as an iterable:</p> <pre><code> print [x for x in mylist[:50]] </code></pre> <p>Test:</p> <pre><code>newlist = [x for x in xrange(10)] newlist2 = [x for x in xrange(100)] print [x for x in newlist[:50]] &gt;[1,2,3,4,5,6,7,8,9] print [x for x in newlist2[:50]] &gt;[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] </code></pre>
2
2016-08-22T10:28:29Z
[ "python" ]
Set a Python indent in Anaconda
39,077,179
<p>So I've got a problem. I installed Anaconda with Python 3.5.2 and when I go for <code>cmd&gt;python</code> then interpreter is on, and then when I try:</p> <pre><code>for i in range(10): print(i) </code></pre> <p>Then a message pops out (when I press TAB):</p> <pre><code>Readline internal error Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\pyreadline\console\console.py", line 768, in hook_wrapper_23 res = ensure_str(readline_hook(prompt)) File "C:\Anaconda3\lib\site-packages\pyreadline\rlmain.py", line 571, in readline self._readline_from_keyboard() File "C:\Anaconda3\lib\site-packages\pyreadline\rlmain.py", line 536, in _readline_from_keyboard if self._readline_from_keyboard_poll(): File "C:\Anaconda3\lib\site-packages\pyreadline\rlmain.py", line 556, in _readline_from_keyboard_poll result = self.mode.process_keyevent(event.keyinfo) File "C:\Anaconda3\lib\site-packages\pyreadline\modes\emacs.py", line 243, in process_keyevent r = self.process_keyevent_queue[-1](keyinfo) File "C:\Anaconda3\lib\site-packages\pyreadline\modes\emacs.py", line 286, in _process_keyevent r = dispatch_func(keyinfo) File "C:\Anaconda3\lib\site-packages\pyreadline\modes\basemode.py", line 257, in complete completions = self._get_completions() File "C:\Anaconda3\lib\site-packages\pyreadline\modes\basemode.py", line 200, in _get_completions r = self.completer(ensure_unicode(text), i) File "C:\Anaconda3\lib\rlcompleter.py", line 80, in complete readline.redisplay() AttributeError: module 'readline' has no attribute 'redisplay' </code></pre> <p>It's okay when I go for 2 spaces though. Can I set Anaconda to accept TAB indents as well?</p>
0
2016-08-22T10:29:11Z
39,078,259
<p>I think it's not a problem with Anaconda but with your Windows console.</p>
0
2016-08-22T11:22:24Z
[ "python", "anaconda" ]
Matplotlib animation: how to make some lines not visible
39,077,240
<p>I am reading some sensors values by serial port.<br> I would like to be able to show/hide the respective lines according to key presses.</p> <p>Here is the code: it has been overly simplified (sorry it is long anyway). I would like to make ALL blue lines in the 3 subplots show/hide by pressing <kbd>1</kbd>; all red lines show/hide by pressing <kbd>2</kbd>. </p> <p>I can only "freeze" the lines but not hide them.<br> What am I missing? </p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from time import sleep # arrays of last 100 data (range 0.-1.) # read from serial port in a dedicated thread val1 = np.zeros(100) val2 = np.zeros(100) speed1=[] # speed of change of val1 and val2 speed2=[] accel1=[] # speed of change of speed1 and speed2 accel2=[] # initial level for each channel level1 = 0.2 level2 = 0.8 fig, ax = plt.subplots() ax = plt.subplot2grid((3,1),(0,0)) lineVal1, = ax.plot(np.zeros(100)) lineVal2, = ax.plot(np.zeros(100), color = "r") ax.set_ylim(-0.5, 1.5) axSpeed = plt.subplot2grid((3,1),(1,0)) lineSpeed1, = axSpeed.plot(np.zeros(99)) lineSpeed2, = axSpeed.plot(np.zeros(99), color = "r") axSpeed.set_ylim(-.1, +.1) axAccel = plt.subplot2grid((3,1),(2,0)) lineAccel1, = axAccel.plot(np.zeros(98)) lineAccel2, = axAccel.plot(np.zeros(98), color = "r") axAccel.set_ylim(-.1, +.1) showLines1 = True showLines2 = True def onKeyPress(event): global showLines1, showLines2 if event.key == "1": showLines1 ^= True if event.key == "2": showLines2 ^= True def updateData(): global level1, level2 global val1, val2 global speed1, speed2 global accel1, accel2 clamp = lambda n, minn, maxn: max(min(maxn, n), minn) # level1 and level2 are really read from serial port in a separate thread # here we simulate them level1 = clamp(level1 + (np.random.random()-.5)/20.0, 0.0, 1.0) level2 = clamp(level2 + (np.random.random()-.5)/20.0, 0.0, 1.0) # last reads are appended to data arrays val1 = np.append(val1, level1)[-100:] val2 = np.append(val2, level2)[-100:] # as an example we calculate speed and acceleration on received data speed1=val1[1:]-val1[:-1] speed2=val2[1:]-val2[:-1] accel1=speed1[1:]-speed1[:-1] accel2=speed2[1:]-speed2[:-1] yield 1 # FuncAnimation expects an iterator def visualize(i): if showLines1: lineVal1.set_ydata(val1) lineSpeed1.set_ydata(speed1) lineAccel1.set_ydata(accel1) if showLines2: lineVal2.set_ydata(val2) lineSpeed2.set_ydata(speed2) lineAccel2.set_ydata(accel2) return lineVal1,lineVal2, lineSpeed1, lineSpeed2, lineAccel1, lineAccel2 fig.canvas.mpl_connect('key_press_event', onKeyPress) ani = animation.FuncAnimation(fig, visualize, updateData, interval=50) plt.show() </code></pre>
1
2016-08-22T10:31:48Z
39,077,335
<p>You should hide/show the lines:</p> <pre><code>lineVal1.set_visible(showLines1) lineSpeed1.set_visible(showLines1) lineAccel1.set_visible(showLines1) lineVal2.set_visible(showLines2) lineSpeed2.set_visible(showLines2) lineAccel2.set_visible(showLines2) </code></pre>
1
2016-08-22T10:36:32Z
[ "python", "animation", "matplotlib", "keyboard" ]
Why does this variable does not update
39,077,265
<p>I'm working on a card game. The point is that when the user clicks on two cards, they turn face up. If they're not the same, when they click on the third one, the first two disappear (this has not been implemented yet).</p> <p>I'm trying to use to variables: <strong>first_card</strong> and <strong>second_card</strong> to keep track of the cards, that have been clicked on. I'm also using a list <strong>"exposed"</strong> to change the values from False to True when the user clicks on a card.</p> <p>The problem is, that the list is updated, but the variables don't update. I mean, when I click on the second card, the <strong>first_card</strong> has a value of <strong>None</strong>, which is the value I initialized the variable with. Why is this happening?</p> <p>Anyway, here's the code (it won't work unless you run it in CodeSkulptor): <a href="http://www.codeskulptor.org/#user41_RwBwWy2tSI_2.py" rel="nofollow">http://www.codeskulptor.org/#user41_RwBwWy2tSI_2.py</a></p> <pre><code># implementation of card game - Memory import simplegui import random deck = range(0, 8)* 2 exposed = [False] * len(deck) print exposed w = 50 h = 100 WIDTH = w * 16 + 2 HEIGHT = 102 first_card = 0 second_card = 0 # helper function to initialize globals def new_game(): global exposed, state random.shuffle(deck) exposed = [False] * len(deck) state = 0 print deck print exposed # define event handlers def mouseclick(pos): global state, exposed, first_card, second_card first_card = None second_card = None position = pos[0] // 50 for index in range(len(deck)): if position == index and exposed[index] != True: if state == 0: #exposed = [False] * len(deck) exposed[position] = True first_card = position state = 1 elif state == 1: #exposed = [False] * len(deck) exposed[index] = True second_card = index state = 2 elif state == 2: #exposed = [False] * len(deck) exposed[index] = True second_card = first_card first_card = index state = 1 print state print "first card", first_card print "second card", second_card print exposed # cards are logically 50x100 pixels in size def draw(canvas): line = 1 x = 1 y = 1 for i in range(len(deck)): if exposed[i] == True: canvas.draw_text(str(deck[i]), [(0.3* w) + w * i, (y + h) * 0.66], 40, "Black") else: canvas.draw_polygon([[x, y], [x + w, y], [x + w, y + h], [x, y + h]], line, "White", '#55aa55') x += w # create frame and add a button and labels frame = simplegui.create_frame("Memory", WIDTH, HEIGHT) frame.add_button("Reset", new_game) label = frame.add_label("Turns = " ) frame.set_canvas_background("White") # register event handlers frame.set_mouseclick_handler(mouseclick) frame.set_draw_handler(draw) # get things rolling new_game() frame.start() </code></pre>
-2
2016-08-22T10:32:50Z
39,077,461
<p>You need to define the global state variable, that code is crashing and probably it isnt updating the first_card value</p> <pre><code>import random state = 0 deck = range(0, 8)* 2 exposed = [False] * len(deck) print exposed w = 50 h = 100 WIDTH = w * 16 + 2 HEIGHT = 102 first_card = 0 second_card = 0 </code></pre>
0
2016-08-22T10:42:04Z
[ "python", "for-loop", "global-variables" ]
Why does this variable does not update
39,077,265
<p>I'm working on a card game. The point is that when the user clicks on two cards, they turn face up. If they're not the same, when they click on the third one, the first two disappear (this has not been implemented yet).</p> <p>I'm trying to use to variables: <strong>first_card</strong> and <strong>second_card</strong> to keep track of the cards, that have been clicked on. I'm also using a list <strong>"exposed"</strong> to change the values from False to True when the user clicks on a card.</p> <p>The problem is, that the list is updated, but the variables don't update. I mean, when I click on the second card, the <strong>first_card</strong> has a value of <strong>None</strong>, which is the value I initialized the variable with. Why is this happening?</p> <p>Anyway, here's the code (it won't work unless you run it in CodeSkulptor): <a href="http://www.codeskulptor.org/#user41_RwBwWy2tSI_2.py" rel="nofollow">http://www.codeskulptor.org/#user41_RwBwWy2tSI_2.py</a></p> <pre><code># implementation of card game - Memory import simplegui import random deck = range(0, 8)* 2 exposed = [False] * len(deck) print exposed w = 50 h = 100 WIDTH = w * 16 + 2 HEIGHT = 102 first_card = 0 second_card = 0 # helper function to initialize globals def new_game(): global exposed, state random.shuffle(deck) exposed = [False] * len(deck) state = 0 print deck print exposed # define event handlers def mouseclick(pos): global state, exposed, first_card, second_card first_card = None second_card = None position = pos[0] // 50 for index in range(len(deck)): if position == index and exposed[index] != True: if state == 0: #exposed = [False] * len(deck) exposed[position] = True first_card = position state = 1 elif state == 1: #exposed = [False] * len(deck) exposed[index] = True second_card = index state = 2 elif state == 2: #exposed = [False] * len(deck) exposed[index] = True second_card = first_card first_card = index state = 1 print state print "first card", first_card print "second card", second_card print exposed # cards are logically 50x100 pixels in size def draw(canvas): line = 1 x = 1 y = 1 for i in range(len(deck)): if exposed[i] == True: canvas.draw_text(str(deck[i]), [(0.3* w) + w * i, (y + h) * 0.66], 40, "Black") else: canvas.draw_polygon([[x, y], [x + w, y], [x + w, y + h], [x, y + h]], line, "White", '#55aa55') x += w # create frame and add a button and labels frame = simplegui.create_frame("Memory", WIDTH, HEIGHT) frame.add_button("Reset", new_game) label = frame.add_label("Turns = " ) frame.set_canvas_background("White") # register event handlers frame.set_mouseclick_handler(mouseclick) frame.set_draw_handler(draw) # get things rolling new_game() frame.start() </code></pre>
-2
2016-08-22T10:32:50Z
39,078,726
<p>First of all, it's not true your statement of <code>it won't work unless you run it in CodeSkulptor</code>, you can find simplegui on pip and everybody can run your code without using CodeSkulptor. I'm wondering what's the reason for getting downvotes, so don't get bothered by them.</p> <p>Now, about your bug... Let's think about the mouseclick logic, let's assume first_card and second_card are both hide (value=-1) at the beginning of the game. And let's think about a simple game's logic where there are 2 possible states:</p> <ul> <li>State0, both cards hide: If you click on a card you expose card1</li> <li>State1, when first card is exposed: If you click on a card, you need to check whether this new exposed card is equal to the first card, if it's so, the Player has guessed alright so you should return to state0 and keeping exposed both cards. If not, the Player has missed, so you shouldn't expose card2 and hide card1. In this state you could also record how many attempts the player has tried.</li> </ul> <p>You're assigning None <code>first_card = None</code> and <code>second_card = None</code> over and over, and that's not correct.</p> <p>Try to give it another shot following these hints and if you're still struggling I'll post you a possible solution.</p>
0
2016-08-22T11:46:46Z
[ "python", "for-loop", "global-variables" ]
Insert paragraph from Python Flask to HTML
39,077,355
<p>I'm new to Flask in Python. I've managed to transfer values from my python code to an HTML page. I'm trying to transfer one value which is actually a long paragraph. I have a loop creating this long text: </p> <pre><code>google_str += num + '. ' + title + '\n' + url + '\n' </code></pre> <p>I want this to eventually look like this in HTML:</p> <blockquote> <ol> <li>Title1<br> URL1</li> <li>Title2<br> URL2</li> </ol> </blockquote> <p>etc. </p> <p>I'm sending it to HTML like this:</p> <pre><code>return render_template('searchtool.html', google_str = google_str) </code></pre> <p>But then I see the text as one big paragraph without the new lines. How can this be solved?</p>
1
2016-08-22T10:37:28Z
39,077,453
<p>Found what I was looking for.</p> <p>First, I had to use "&lt; br >" instead of '/n'. Second, use this in my HTML:</p> <pre><code>{{google_str|safe}} </code></pre> <p><a href="http://stackoverflow.com/questions/12253259/new-lines-in-flask-within-block-content">This is where I found the answer.</a></p>
0
2016-08-22T10:41:44Z
[ "python", "html", "python-2.7", "flask" ]
Python, take value of a list from an input
39,077,499
<p>Hi guys i'm Learning python, i have this problem, for not create 1000 "if" function i would did that:</p> <pre><code>#Vari flag print "choose flag" print "(1) Syn" print "(2) Ack" print "(3) Push" print "(4) Fin" print "(5) Urg" print "(6) Rst" flag-list = ["--syn","--ack","--push","--fin","--urg","--rst"] flag = raw_input(write number separated by comma: ) </code></pre> <p>now i would take writed number and transform them in the text of "flag-list".</p>
-7
2016-08-22T10:43:48Z
39,077,549
<pre><code># Note that variable names cannot contain hyphens flag_list = ["--syn","--ack","--push","--fin","--urg","--rst"] # This clearly has to be in quotes user_input = raw_input("Enter numbers separated by comma:" ) # Split the user input string at the commas, and turn each element into an integer. flag_nums = map(int, flag_num.split(',')) # List indexes start at 0, so subtract 1. # Use brackets to access the Nth item in the list. # This is a list comprehension. flags = [flag_list[n - 1] for n in flag_nums] </code></pre>
1
2016-08-22T10:46:23Z
[ "python" ]
python dataframe to excel
39,077,566
<p>At this moment i'm trying to convert a dataframe into excel file, using <code>df.to_excel</code>. I've already done it with an older project before but now I have a dataframe which contains more than one value in some cases of the table.<br> For example there is a little part on my dataframe; we can see that the 2 last rows of <code>column2</code> countains two values :</p> <pre><code>----------column 1--------------column 2-------------- 2016-08-05 20:57:58----[2016-08-05 21:03:24] 2016-08-05 21:03:29----[2016-08-05 21:03:41] 2016-08-05 21:04:27----[2016-08-06 02:03:11] 2016-08-06 02:03:16----[2016-08-06 02:03:27, 2016-08-06 02:12:08] 2016-08-06 02:12:53----[2016-08-06 02:13:04, 2016-08-06 02:13:12] </code></pre> <p>I want to know if it is possible to convert that kind of stuff into an excel file, because I tried but it seems like these multiple values prevent to do that convertion.<br> I thought about converting each value into strings and then concatenate them into a unique string, but if someone knows another easier way to answer this problem, I'm listening! </p> <p>Thank you and have a nice day all.</p>
2
2016-08-22T10:47:05Z
39,078,510
<p>Have you tried setting merge_cells=True?</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html</a></p>
0
2016-08-22T11:35:50Z
[ "python", "excel", "pandas", "dataframe" ]
Can a Python inner class be a subclass of its own outer class?
39,077,623
<p>This...</p> <pre><code>class A(object): class B(A): def __init__(self): pass </code></pre> <p>... throws "NameError: name 'A' is not defined".</p> <p>Is there proper syntax to accomplish this, or must I use workarounds, like this?</p> <pre><code>class A(object): pass class _B(A): pass A.B = _B </code></pre> <p>The prior is strongly preferable. Thank you.</p>
0
2016-08-22T10:50:01Z
39,077,925
<p>As per OPs request, posting as an answer.</p> <ol> <li><p>That's an inner class, not a subclass.</p></li> <li><p>No, an inner class can't inherit (not extend) its outer class because the outer class is not fully defined while defining the inner class.</p></li> <li><p>Your workaround is not a work around, as it doesn't have an inner class. You are confusing subclasses and inner classes</p></li> </ol>
1
2016-08-22T11:04:52Z
[ "python", "python-2.7", "inheritance", "subclass" ]
Can a Python inner class be a subclass of its own outer class?
39,077,623
<p>This...</p> <pre><code>class A(object): class B(A): def __init__(self): pass </code></pre> <p>... throws "NameError: name 'A' is not defined".</p> <p>Is there proper syntax to accomplish this, or must I use workarounds, like this?</p> <pre><code>class A(object): pass class _B(A): pass A.B = _B </code></pre> <p>The prior is strongly preferable. Thank you.</p>
0
2016-08-22T10:50:01Z
39,078,040
<p>You can not do this the normal way and probably should not do this.</p> <p>For those who have a valid reason to attempt something similar, there is a workaround by dynamically changing the superclass of <code>A.B</code> after <code>A</code> is fully defined (see <a href="http://stackoverflow.com/a/9639512/5069869">http://stackoverflow.com/a/9639512/5069869</a>).</p> <p>This is probably terrible code, a big hack and should not be done, but it works under certain conditions (see linked answer)</p> <pre><code>class T: pass class A(object): def a(self): return "Hallo a" class B(T): def b(self): return "Hallo b" A.B.__bases__ = (A,) b=A.B() assert isinstance(b, A) assert b.a()=="Hallo a" </code></pre> <p>Now you can even do something weird like <code>x = A.B.B.B.B()</code></p>
1
2016-08-22T11:10:47Z
[ "python", "python-2.7", "inheritance", "subclass" ]
Gzip compression and http post from python to java
39,077,711
<p>I want to http post a gzip compressed data from python to java and I want to store it as a BLOB in database. Then I want to gzip decompress that BLOB in java. So I want to know howto post a BLOB in python and how to read a BLOB in java. I have given my python and java code below. In my code I gzip compress a string in python and store that compressed data in a file. Then I read that file in java and decompress it using GZIPInputStream. But I'm getting the below exception.</p> <pre><code>java.io.IOException: Not in GZIP format at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:154) at java.util.zip.GZIPInputStream.&lt;init&gt;(GZIPInputStream.java:75) at java.util.zip.GZIPInputStream.&lt;init&gt;(GZIPInputStream.java:85) at GZipFile.gunzipIt(GZipFile.java:60) at GZipFile.main(GZipFile.java:43) </code></pre> <p>If I print the byte array of the compressed data in python I get </p> <p>[31, 139, 8, 0, 254, 213, 186, 87, 2, 255, 203, 72, 205, 201, 201, 231, 229, 42, 207, 47, 202, 73, 1, 0, 66, 102, 86, 48, 12, 0, 0, 0]</p> <p>If I read and print that compressed data from that file in java I get as </p> <p>[31, -17, -65, -67, 8, 0, -17, -65, -67, -42, -70, 87, 2, -17, -65, -67, -17, -65, -67, 72, -17, -65, -67, -17, -65, -67, -17, -65, -67, -17, -65, -67, -17, -65, -67, 42, -17, -65, -67, 47, -17, -65, -67, 73, 1, 0, 66, 102, 86, 48, 12, 0, 0, 0]</p> <p>Has you can see there is difference. If I give the printed byte array in python as input to the java code it works fine. So please help me to know how to post a blob(the compressed data) in python and how to read that compressed data in java to decompress it.</p> <p><strong>This is the compression code in python:</strong></p> <pre><code>import StringIO import gzip import base64 import os m='hello'+'\r\n'+'world' out = StringIO.StringIO() with gzip.GzipFile(fileobj=out, mode="wb") as f: f.write(m.encode('utf-8')) print list(array.array('B',out.getvalue())[:]) f=open('comp_dump','wb') f.write(out.getvalue()) f.close() </code></pre> <p><strong>This is the decompression code in java:</strong></p> <pre><code>//$Id$ import java.io.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import javax.xml.bind.DatatypeConverter; import java.util.Arrays; public class GZipFile { public static String readCompressedData()throws Exception { String compressedStr =""; String nextLine; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("comp_dump"))); try { while((nextLine=reader.readLine())!=null) { compressedStr += nextLine; } } finally { reader.close(); } return compressedStr; } public static void main( String[] args ) throws Exception { GZipFile gZip = new GZipFile(); byte[] contentInBytes = readCompressedData().getBytes("UTF-8"); System.out.println(Arrays.toString(contentInBytes)); String decomp = gZip.gunzipIt(contentInBytes); System.out.println(decomp); } /** * GunZip it */ public static String gunzipIt(final byte[] compressed){ byte[] buffer = new byte[1024]; StringBuilder decomp = new StringBuilder() ; try{ GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(compressed)); int len; while ((len = gzis.read(buffer)) &gt; 0) { decomp.append(new String(buffer, 0, len)); } gzis.close(); }catch(IOException ex){ ex.printStackTrace(); } return decomp.toString(); } } </code></pre>
0
2016-08-22T10:55:21Z
39,078,035
<p>Have you checked this: <a href="http://stackoverflow.com/questions/8156707/gzip-a-file-in-python">gzip a file in Python</a> ?</p> <p>My guess is that your string </p> <pre><code>m='hello'+'\r\n'+'world' </code></pre> <p>is possibly causing some issues with the whole process...</p> <p>Have you considered replacing it with m="hello\r\nworld", using double quotes instead?</p>
0
2016-08-22T11:10:27Z
[ "java", "python", "http-post", "gzip", "decompression" ]
Gzip compression and http post from python to java
39,077,711
<p>I want to http post a gzip compressed data from python to java and I want to store it as a BLOB in database. Then I want to gzip decompress that BLOB in java. So I want to know howto post a BLOB in python and how to read a BLOB in java. I have given my python and java code below. In my code I gzip compress a string in python and store that compressed data in a file. Then I read that file in java and decompress it using GZIPInputStream. But I'm getting the below exception.</p> <pre><code>java.io.IOException: Not in GZIP format at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:154) at java.util.zip.GZIPInputStream.&lt;init&gt;(GZIPInputStream.java:75) at java.util.zip.GZIPInputStream.&lt;init&gt;(GZIPInputStream.java:85) at GZipFile.gunzipIt(GZipFile.java:60) at GZipFile.main(GZipFile.java:43) </code></pre> <p>If I print the byte array of the compressed data in python I get </p> <p>[31, 139, 8, 0, 254, 213, 186, 87, 2, 255, 203, 72, 205, 201, 201, 231, 229, 42, 207, 47, 202, 73, 1, 0, 66, 102, 86, 48, 12, 0, 0, 0]</p> <p>If I read and print that compressed data from that file in java I get as </p> <p>[31, -17, -65, -67, 8, 0, -17, -65, -67, -42, -70, 87, 2, -17, -65, -67, -17, -65, -67, 72, -17, -65, -67, -17, -65, -67, -17, -65, -67, -17, -65, -67, -17, -65, -67, 42, -17, -65, -67, 47, -17, -65, -67, 73, 1, 0, 66, 102, 86, 48, 12, 0, 0, 0]</p> <p>Has you can see there is difference. If I give the printed byte array in python as input to the java code it works fine. So please help me to know how to post a blob(the compressed data) in python and how to read that compressed data in java to decompress it.</p> <p><strong>This is the compression code in python:</strong></p> <pre><code>import StringIO import gzip import base64 import os m='hello'+'\r\n'+'world' out = StringIO.StringIO() with gzip.GzipFile(fileobj=out, mode="wb") as f: f.write(m.encode('utf-8')) print list(array.array('B',out.getvalue())[:]) f=open('comp_dump','wb') f.write(out.getvalue()) f.close() </code></pre> <p><strong>This is the decompression code in java:</strong></p> <pre><code>//$Id$ import java.io.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import javax.xml.bind.DatatypeConverter; import java.util.Arrays; public class GZipFile { public static String readCompressedData()throws Exception { String compressedStr =""; String nextLine; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("comp_dump"))); try { while((nextLine=reader.readLine())!=null) { compressedStr += nextLine; } } finally { reader.close(); } return compressedStr; } public static void main( String[] args ) throws Exception { GZipFile gZip = new GZipFile(); byte[] contentInBytes = readCompressedData().getBytes("UTF-8"); System.out.println(Arrays.toString(contentInBytes)); String decomp = gZip.gunzipIt(contentInBytes); System.out.println(decomp); } /** * GunZip it */ public static String gunzipIt(final byte[] compressed){ byte[] buffer = new byte[1024]; StringBuilder decomp = new StringBuilder() ; try{ GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(compressed)); int len; while ((len = gzis.read(buffer)) &gt; 0) { decomp.append(new String(buffer, 0, len)); } gzis.close(); }catch(IOException ex){ ex.printStackTrace(); } return decomp.toString(); } } </code></pre>
0
2016-08-22T10:55:21Z
39,091,858
<p>You can't read the compressed data to string directly.What you have done in <code>readCompressedData</code> method is reading the compressed data to literal(which lead to a wrong string) and then get it's bytes(in method main).After you doing this,the <code>contentInBytes</code> is not really the bytes stored in the file. </p> <p>When you try to make a string with bytes that can't be transformed into <code>String</code>. The bytes that represent the string is different.</p> <p>For example:</p> <pre><code> byte bytesBefore[] = {-1,-2,65,76,79,80}; try { String str = new String(bytesBefore); byte bytesAfter[] = str.getBytes(); System.out.println("str is " + str); System.out.println("after"); for(Byte b : bytesAfter){ System.out.print(" " + b); } } catch (Exception e) { e.printStackTrace(); } </code></pre> <p>OUTPUT:</p> <pre><code>str is ��ALOP after -17 -65 -67 -17 -65 -67 65 76 79 80 </code></pre> <p>Because bytes -1 and -2 here can't be transformed into string,when you new the string with bytesBefore,the bytes that stored in memory for str is bytesAfter,which change the -1 and -2 to -17 -65 -67 -17 -65 -67 .</p> <p>Actually, the <code>GZIPInputStream</code> can be built with a <code>FileInputStream</code>,no need to get the bytes first.Just use the <code>BufferedReader</code> to read the <code>GZIPInputStream</code> which is built with a <code>FileInputStream</code>.</p> <p>There is a solution:</p> <pre><code>import java.io.*; import java.util.zip.GZIPInputStream; public class GZipFile { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader( new GZIPInputStream(new FileInputStream( "comp_dump")), "UTF-8")); StringBuffer sb = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\r\n"); } System.out.println(sb.toString()); } } </code></pre> <p>OUTPUT:</p> <pre><code>hello world </code></pre>
0
2016-08-23T03:27:31Z
[ "java", "python", "http-post", "gzip", "decompression" ]
Sending values from one python script to another to another
39,077,812
<p>so i've got some values coming in from an Arduino to my Raspberry Pi via an RF transceiver (NRF24L01) and i can display the integers when the program runs (Python). Now i want to display those integer values in my GUI that i've written in a seperate python script. I'm having trouble doing so. I've tried importing them from the GUI but it isn't working and i couldn't figure out why..</p> <p>So now i've gone with the option of writing the value into a text file in the transmission script and then attempting to read the value from the text file in the GUI script but it still dosent work completely. </p> <p>Can anyone help me update the text file from the transmission script and read it from the GUI script? Can you write to a text file from one script and read the text file from another script at the same time?</p> <p>ANY help will be greatly appreciated. Thanks!</p> <p>ps. If iv'e missed out on anything that you need to know just ask. It's a little hard to explain everything!</p> <p><strong>GUI CODE</strong></p> <pre><code># -*- coding: utf-8 -*- """ Created on Sat Aug 6 20:05:30 2016 @author: s """ import sys if sys.version_info[0] &lt; 3: import Tkinter as tk else: import tkinter as tk def clear(): pass def exit_(): root.quit() root.withdraw() #water_amount = 0 water_cost = 0 total_water_amount = 0 total_water_cost = 0 def show_data(): while True: text_file = open("Output.txt", "r") water_amount = text_file.readlines() text_file.close() tk.Label(root, text='Water Amount: ' + str(water_amount)).pack() tk.Label(root, text='Water Cost: ' + str(water_cost)).pack() separator = tk.Frame(height=2, bd=10, relief=tk.SUNKEN) separator.pack(fill=tk.X, padx=5, pady=5) tk.Label(root, text='Total Water Amount: ' + str(total_water_amount)).pack() tk.Label(root, text='Total Water Cost: ' + str(total_water_cost)).pack() separator = tk.Frame(height=2, bd=10, relief=tk.SUNKEN) separator.pack(fill=tk.X, padx=5, pady=5) #show_data() def get_rate(): import random for i in range(100): flow_rate.append(random.randint(20, 60)) # print(flow_rate) # def draw_plot(flow_rate): # import matplotlib.pyplot as plt # conda install matplotlib # print(flow_rate) # plt.plot(flow_rate, label='Flow rate ml/sec') # plt.xlabel('Time(sec)') # plt.ylabel('Flow Rate(ml)') # plt.title("Flow Rate Chart") # # plt.legend() # plt.show() root = tk.Tk(className='Water') flow_rate = [] get_rate() show_data() tk.Button(root, text='Clear', command=clear).pack(side='left') tk.Button(root, text='Exit', command=exit_).pack(side='left') #tk.Button(root, text='Draw', command=draw_plot(flow_rate)).pack_forget() root.mainloop() </code></pre> <p><strong><em>CODE RECEIVING VALUES</em></strong></p> <pre><code>import RPi.GPIO as GPIO from lib_nrf24 import NRF24 import time import spidev GPIO.setmode(GPIO.BCM) pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]] radio = NRF24(GPIO, spidev.SpiDev()) radio.begin(0,17) radio.setPayloadSize(32) #can have maximum 32 radio.setChannel(0x76) radio.setDataRate(NRF24.BR_1MBPS) #Slower since it is secure radio.setPALevel(NRF24.PA_MIN) # Minimum to save battery radio.setAutoAck(True) radio.enableDynamicPayloads() radio.enableAckPayload() #Acknowledgement Payload : Can verify if data received radio.openReadingPipe(1, pipes[1]) radio.printDetails() radio.startListening() while True: # Waits to recieve data, if no data is recieved then goes into sleep mode while not radio.available(0): time.sleep(1/100) receivedMessage = [] #Populates the message radio.read(receivedMessage, radio.getDynamicPayloadSize()) #------------------------------------------------------- raw = int(receivedMessage[1]) * 256 total = raw + int(receivedMessage[0]) print ("total equals:" + str(int(total))) text_file = open("Output.txt", "w") text_file.write("%s" % total) text_file.close() </code></pre>
2
2016-08-22T10:59:49Z
39,079,116
<p>You should try to combine the data-receiving code and data-displaying code with <code>threading</code> library.</p> <p>In the <code>while True</code> loop in the data-receiving script, it should check for new result and notify the GUI thread somehow (eg. store it in a global variable and use the <code>threading.Condition</code> object), or change the GUI directly.</p> <p>For example:</p> <pre><code>from tkinter import * import threading tk=Tk() result=StringVar() Label(tk,textvariable=result).pack() def update_result(): import RPi.GPIO as GPIO from lib_nrf24 import NRF24 import time import spidev GPIO.setmode(GPIO.BCM) pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]] radio = NRF24(GPIO, spidev.SpiDev()) radio.begin(0,17) radio.setPayloadSize(32) #can have maximum 32 radio.setChannel(0x76) radio.setDataRate(NRF24.BR_1MBPS) #Slower since it is secure radio.setPALevel(NRF24.PA_MIN) # Minimum to save battery radio.setAutoAck(True) radio.enableDynamicPayloads() radio.enableAckPayload() #Acknowledgement Payload : Can verify if data received radio.openReadingPipe(1, pipes[1]) radio.printDetails() radio.startListening() while True: while not radio.available(0): time.sleep(1/100) receivedMessage = [] #Populates the message radio.read(receivedMessage, radio.getDynamicPayloadSize()) #------------------------------------------------------- raw = int(receivedMessage[1]) * 256 total = raw + int(receivedMessage[0]) result.set(total) threading.Thread(target=update_result).start() mainloop() </code></pre> <p>(I didn't test this program because I don't have the environment, but I think that should work. Please comment if it's not working.)</p>
1
2016-08-22T12:06:07Z
[ "python", "tkinter" ]
Unable to crawl some href in a webpage using python and beautifulsoup
39,077,890
<p>I am currently crawling a web page using Python 3.4 and bs4 in order to collect the match results played by Serbia in Rio2016. So the url <a href="http://rio2016.fivb.com/en/volleyball/women/teams/srb-serbia#wcbody_0_wcgridpadgridpad1_1_wcmenucontent_3_Schedule" rel="nofollow">here</a> contains links to all the match results she played, for example <a href="http://rio2016.fivb.com/en/volleyball/women/7168-serbia-italy/post" rel="nofollow">this</a>.</p> <p>Then I found that the link is located in the html source like this:</p> <pre><code>&lt;a href="/en/volleyball/women/7168-serbia-italy/post" ng-href="/en/volleyball/women/7168-serbia-italy/post"&gt; &lt;span class="score ng-binding"&gt;3 - 0&lt;/span&gt; &lt;/a&gt; </code></pre> <p>But after several trials, this <code>href="/en/volleyball/women/7168-serbia-italy/post"</code> never show up. Then I tried to run the following code to get all the href from the url:</p> <pre><code>from bs4 import BeautifulSoup import requests Countryr = requests.get('http://rio2016.fivb.com/en/volleyball/women/teams/srb-serbia#wcbody_0_wcgridpadgridpad1_1_wcmenucontent_3_Schedule') countrySoup = BeautifulSoup(Countryr.text) for link in countrySoup.find_all('a'): print(link.get('href')) </code></pre> <p>Then a strange thing happened. The <code>href="/en/volleyball/women/7168-serbia-italy/post"</code> is not included in the output at all.</p> <p>I found that this href is located in one of the tab pages <code>href="#scheduldedOver"</code> in side this url, and it is controlled by the following HTML code:</p> <pre><code>&lt;nav class="tabnav"&gt; &lt;a href="#schedulded" ng-class="{selected: chosenStatus == 'Pre' }" ng-click="setStatus('Pre')" ng-href="#schedulded"&gt;Scheduled&lt;/a&gt; &lt;a href="#scheduldedLive" ng-class="{selected: chosenStatus == 'Live' }" ng-click="setStatus('Live')" ng-href="#scheduldedLive"&gt;Live&lt;/a&gt; &lt;a href="#scheduldedOver" class="selected" ng-class="{selected: chosenStatus == 'Over' }" ng-click="setStatus('Over')" ng-href="#scheduldedOver"&gt;Complete&lt;/a&gt; &lt;/nav&gt; </code></pre> <p>Then how should I get the href using BeautifulSoup inside a tab page?</p>
3
2016-08-22T11:03:14Z
39,079,215
<p>The data is created dynamically, if you look at the actual source you can see <a href="https://docs.angularjs.org/tutorial/step_02" rel="nofollow">Angularjs</a> templating.</p> <p>You can still get all the info in json format by mimicking an ajax call, in the source yuuuuou can also see a div like:</p> <pre><code>&lt;div id="AngularPanel" class="main-wrapper" ng-app="fivb" data-servicematchcenterbar="/en/api/volley/matches/341/en/user/lives" data-serviceteammatches="/en/api/volley/matches/WOG2016/en/user/team/3017" data-servicelabels="/en/api/labels/Volley/en" data-servicelive="/en/api/volley/matches/WOG2016/en/user/live/"&gt; </code></pre> <p>Using the <code>data-servicematchcenterbar</code> href will give you all the info:</p> <pre><code>from bs4 import BeautifulSoup import requests from urlparse import urljoin r = requests.get('http://rio2016.fivb.com/en/volleyball/women/teams/srb-serbia#wcbody_0_wcgridpadgridpad1_1_wcmenucontent_3_Schedule') soup = BeautifulSoup(r.content) base = "http://rio2016.fivb.com/" json = requests.get(urljoin(base, soup.select_one("#AngularPanel")["data-serviceteammatches"])).json() </code></pre> <p>In json you will see output like:</p> <pre><code>{"Id": 7168, "MatchNumber": "006", "TournamentCode": "WOG2016", "TournamentName": "Women's Olympic Games 2016", "TournamentGroupName": "", "Gender": "", "LocalDateTime": "2016-08-06T22:35:00", "UtcDateTime": "2016-08-07T01:35:00+00:00", "CalculatedMatchDate": "2016-08-07T03:35:00+02:00", "CalculatedMatchDateType": "user", "LocalDateTimeText": "August 06 2016", "Pool": {"Code": "B", "Name": "Pool B", "Url": "/en/volleyball/women/results and ranking/round1#anchorB"}, "Round": 68, "Location": {"Arena": "Maracanãzinho", "City": "Maracanãzinho", "CityUrl": "", "Country": "Brazil"}, "TeamA": {"Code": "SRB", "Name": "Serbia", "Url": "/en/volleyball/women/teams/srb-serbia", "FlagUrl": "/~/media/flags/flag_SRB.png?h=60&amp;w=60"}, "TeamB": {"Code": "ITA", "Name": "Italy", "Url": "/en/volleyball/women/teams/ita-italy", "FlagUrl": "/~/media/flags/flag_ITA.png?h=60&amp;w=60"}, "Url": "/en/volleyball/women/7168-serbia-italy/post", "TicketUrl": "", "Status": "Over", "MatchPointsA": 3, "MatchPointsB": 0, "Sets": [{"Number": 1, "PointsA": 27, "PointsB": 25, "Hours": 0, "Minutes": "28"}, {"Number": 2, "PointsA": 25, "PointsB": 20, "Hours": 0, "Minutes": "25"}, {"Number": 3, "PointsA": 25, "PointsB": 23, "Hours": 0, "Minutes": "27"}], "PoolRoundName": "Preliminary Round", "DayInfo": "Weekend Day", "WeekInfo": {"Number": 31, "Start": 7, "End": 13}, "LiveStreamUri": ""}, </code></pre> <p>You can parse whatever you need from those.</p>
1
2016-08-22T12:11:26Z
[ "python", "html", "beautifulsoup", "tabpage" ]
Unable to crawl some href in a webpage using python and beautifulsoup
39,077,890
<p>I am currently crawling a web page using Python 3.4 and bs4 in order to collect the match results played by Serbia in Rio2016. So the url <a href="http://rio2016.fivb.com/en/volleyball/women/teams/srb-serbia#wcbody_0_wcgridpadgridpad1_1_wcmenucontent_3_Schedule" rel="nofollow">here</a> contains links to all the match results she played, for example <a href="http://rio2016.fivb.com/en/volleyball/women/7168-serbia-italy/post" rel="nofollow">this</a>.</p> <p>Then I found that the link is located in the html source like this:</p> <pre><code>&lt;a href="/en/volleyball/women/7168-serbia-italy/post" ng-href="/en/volleyball/women/7168-serbia-italy/post"&gt; &lt;span class="score ng-binding"&gt;3 - 0&lt;/span&gt; &lt;/a&gt; </code></pre> <p>But after several trials, this <code>href="/en/volleyball/women/7168-serbia-italy/post"</code> never show up. Then I tried to run the following code to get all the href from the url:</p> <pre><code>from bs4 import BeautifulSoup import requests Countryr = requests.get('http://rio2016.fivb.com/en/volleyball/women/teams/srb-serbia#wcbody_0_wcgridpadgridpad1_1_wcmenucontent_3_Schedule') countrySoup = BeautifulSoup(Countryr.text) for link in countrySoup.find_all('a'): print(link.get('href')) </code></pre> <p>Then a strange thing happened. The <code>href="/en/volleyball/women/7168-serbia-italy/post"</code> is not included in the output at all.</p> <p>I found that this href is located in one of the tab pages <code>href="#scheduldedOver"</code> in side this url, and it is controlled by the following HTML code:</p> <pre><code>&lt;nav class="tabnav"&gt; &lt;a href="#schedulded" ng-class="{selected: chosenStatus == 'Pre' }" ng-click="setStatus('Pre')" ng-href="#schedulded"&gt;Scheduled&lt;/a&gt; &lt;a href="#scheduldedLive" ng-class="{selected: chosenStatus == 'Live' }" ng-click="setStatus('Live')" ng-href="#scheduldedLive"&gt;Live&lt;/a&gt; &lt;a href="#scheduldedOver" class="selected" ng-class="{selected: chosenStatus == 'Over' }" ng-click="setStatus('Over')" ng-href="#scheduldedOver"&gt;Complete&lt;/a&gt; &lt;/nav&gt; </code></pre> <p>Then how should I get the href using BeautifulSoup inside a tab page?</p>
3
2016-08-22T11:03:14Z
39,081,222
<p>Thanks for all your help now I can get the correct url. It is a good learning experience for me. Thanks a lot :)</p> <pre><code>from bs4 import BeautifulSoup import requests Countryr = requests.get('http://rio2016.fivb.com/en/volleyball/women/teams/srb-serbia#wcbody_0_wcgridpadgridpad1_1_wcmenucontent_3_Schedule') countrySoup = BeautifulSoup(Countryr.text) for link in countrySoup.find_all('div', {'id': 'AngularPanel'}): linkUrl = link.get('data-serviceteammatches') json = requests.get('http://rio2016.fivb.com' + linkUrl).json() for item in json: print(item.get('Url')) </code></pre> <p>output:</p> <pre><code>/en/volleyball/women/7168-serbia-italy/post /en/volleyball/women/7172-serbia-puerto rico/post /en/volleyball/women/7177-usa-serbia/post /en/volleyball/women/7181-china-serbia/post /en/volleyball/women/7187-serbia-netherlands/post /en/volleyball/women/7195-russia-serbia/post /en/volleyball/women/7198-serbia-usa/post /en/volleyball/women/7200-china-serbia/post </code></pre>
1
2016-08-22T13:44:35Z
[ "python", "html", "beautifulsoup", "tabpage" ]
IPython.display.Audio cannot correctly handle `.ogg` file type?
39,077,987
<p>I was doing some audio analysis stuff with Jupyter and tried to play <code>.ogg</code> files with <code>IPython.display.Audio</code>. Since PyCharm often failed to open big <code>.ipynb</code> files, I mostly used web browser to view my Notebook files at <code>localhost:8888</code>.</p> <p><a href="http://i.stack.imgur.com/s6hw7.png" rel="nofollow"><img src="http://i.stack.imgur.com/s6hw7.png" alt="enter image description here"></a></p> <p>This picture is what I get with Chrome. As you can see, <strong>FailToDisplay.ogg</strong> is taken from my work, the audio play bar is not activated. <strong>File-ACDC_-_Back_In_Black-sample.ogg</strong> and <strong>song sample.mp3</strong> are all downloaded from Internet. The integrity of 3 files are all validated, i.e., they can all be played correctly with audio players.</p> <p>I also tested it with Microsoft Edge and Firefox, and the results are mostly the same. 2 <code>.ogg</code> playbars are all inactive while <code>.mp3</code> playbar is active and works perfectly. So I guess the problem is not web browser dependent.</p> <p>I checked the html source code of these 3 audio playbars with Chrome Developer Tool, they are all like:</p> <pre><code>&lt;audio controls="controls"&gt; &lt;source src="data:None;base64,VERYLONGTEXT" type="None"&gt; Your browser does not support the audio element. &lt;/audio&gt; </code></pre> <p>The <code>type</code> for mp3 is <code>audio/mpeg</code> and <code>type</code> for ogg is <code>None</code>. After some google search, I guess this has something to do with <strong>MIME</strong> type. So I inspected 3 audio files with command <code>mimetype</code>:</p> <pre><code>$ mimetype ./* ./AudioDisplayErrorTest.ipynb: text/plain ./FailToDisplay.ogg: audio/x-vorbis+ogg ./File-ACDC_-_Back_In_Black-sample.ogg: video/x-theora+ogg ./song sample.mp3: audio/mpeg </code></pre> <p>Not very strange. Then I find this blog post <a href="https://www.pythonanywhere.com/forums/topic/333/" rel="nofollow">How to set MIMETYPES on server : Forums : PythonAnywhere</a> and tested my python MIME type settings:</p> <pre><code>&gt;&gt;&gt; import mimetypes &gt;&gt;&gt; mimetypes.guess_type("foo.ogg") (None, None) </code></pre> <p>Now I don't know what to do next with this kind of situation. Is this just a bug of Jupyter or IPython or system-wide? Where can I change this behavior?</p> <p>My Python environment settings are</p> <pre><code>audioread==2.1.4 ipykernel==4.4.1 ipython==5.1.0 ipython-genutils==0.1.0 ipywidgets==4.1.1 jupyter==1.0.0 jupyter-client==4.3.0 jupyter-console==5.0.0 jupyter-core==4.1.1 librosa==0.4.3 nbconvert==4.2.0 nbformat==4.0.1 notebook==4.2.2 numpy==1.11.1 openpyxl==2.3.2 pydub==0.16.5 </code></pre>
2
2016-08-22T11:07:57Z
39,084,114
<p>Since no one gives a hint, I guess I'll have to work alone...</p> <p>First look into the source code of <code>IPython.display.audio</code>: <a href="https://github.com/ipython/ipython/blob/48b01aadcbb6a53d2c77fa250c8a4344931c357c/IPython/lib/display.py" rel="nofollow">ipython/display.py at 48b01aadcbb6a53d2c77fa250c8a4344931c357c · ipython/ipython</a></p> <pre><code>def _repr_html_(self): src = """ &lt;audio controls="controls" {autoplay}&gt; &lt;source src="{src}" type="{type}" /&gt; Your browser does not support the audio element. &lt;/audio&gt; """ return src.format(src=self.src_attr(),type=self.mimetype, autoplay=self.autoplay_attr()) </code></pre> <p>This is the code that generates html source code of audio control block, <code>type</code> is assigned from <code>self.mimetype</code>. And <code>self.mimetype</code> is derived from <code>reload()</code>:</p> <pre><code> if self.filename is not None: self.mimetype = mimetypes.guess_type(self.filename)[0] elif self.url is not None: self.mimetype = mimetypes.guess_type(self.url)[0] else: self.mimetype = "audio/wav" </code></pre> <p>It's obvious if <code>mimetypes.guess_type("filename.ogg")[0]</code> gets <code>None</code>, then we have <code>type == None</code>, which results an inactive audio control block.</p> <p>From <a href="https://docs.python.org/2/library/mimetypes.html" rel="nofollow">18.7. mimetypes — Map filenames to MIME types — Python 2.7.12 documentation</a> I learned that MIME types can be loaded from file or dynamically added with <code>mimetypes.add_type()</code>. It also said by default <code>mimetypes</code> will load from Windows registry. I tried to modify system-wide MIME type settings of <code>.ogg</code> with one small utility <a href="http://www.nirsoft.net/utils/file_types_manager.html" rel="nofollow">FileTypesMan - Alternative to 'File Types' manager of Windows</a> but it did not reflect on <code>mimetypes</code>, so I guess I'll have to let it go.</p> <p>At last I realized that a monkey patch before <code>IPython.display.Audio</code> was used will possibly work and it really does:</p> <p><a href="http://i.stack.imgur.com/utV1N.png" rel="nofollow"><img src="http://i.stack.imgur.com/utV1N.png" alt="enter image description here"></a></p> <p>It may not be perfect to solve the problem, but at least it works. So be it for now.</p>
2
2016-08-22T16:07:36Z
[ "python", "ipython", "mime", "jupyter", "ogg" ]
How to find closest elements in two array?
39,078,043
<p>I have two numpy arrays, like <code>X=[x1,x2,x3,x4], y=[y1,y2,y3,y4]</code>. Three of the elements are close and the fourth of them maybe close or not.</p> <p>Like:</p> <pre><code>X [ 84.04467948 52.42447842 39.13555678 21.99846595] y [ 78.86529444 52.42447842 38.74910101 21.99846595] </code></pre> <p>Or it can be:</p> <pre><code>X [ 84.04467948 60 52.42447842 39.13555678] y [ 78.86529444 52.42447842 38.74910101 21.99846595] </code></pre> <p>I want to define a function to find the the corresponding index in the two arrays, like in first case:</p> <ul> <li><code>y[0]</code> correspond to <code>X[0]</code>,</li> <li><code>y[1]</code> correspond to <code>X[1]</code>,</li> <li><code>y[2]</code> correspond to <code>X[2]</code>,</li> <li><code>y[3]</code> correspond to <code>X[3]</code></li> </ul> <p>And in second case:</p> <ul> <li><code>y[0]</code> correspond to <code>X[0]</code>,</li> <li><code>y[1]</code> correspond to <code>X[2]</code>,</li> <li><code>y[2]</code> correspond to <code>X[3]</code> </li> <li>and <code>y[3]</code> correspond to <code>X[1]</code>.</li> </ul> <p>I can't write a function to solve the problem completely, please help.</p>
5
2016-08-22T11:10:53Z
39,078,294
<p>Seems like best approach would be to pre-sort both array (n<em>log(n)) and then perform merge-like traverse through both arrays. It's definitely faster than n</em>n which you indicated in comment.</p>
2
2016-08-22T11:24:11Z
[ "python", "python-2.7" ]
How to find closest elements in two array?
39,078,043
<p>I have two numpy arrays, like <code>X=[x1,x2,x3,x4], y=[y1,y2,y3,y4]</code>. Three of the elements are close and the fourth of them maybe close or not.</p> <p>Like:</p> <pre><code>X [ 84.04467948 52.42447842 39.13555678 21.99846595] y [ 78.86529444 52.42447842 38.74910101 21.99846595] </code></pre> <p>Or it can be:</p> <pre><code>X [ 84.04467948 60 52.42447842 39.13555678] y [ 78.86529444 52.42447842 38.74910101 21.99846595] </code></pre> <p>I want to define a function to find the the corresponding index in the two arrays, like in first case:</p> <ul> <li><code>y[0]</code> correspond to <code>X[0]</code>,</li> <li><code>y[1]</code> correspond to <code>X[1]</code>,</li> <li><code>y[2]</code> correspond to <code>X[2]</code>,</li> <li><code>y[3]</code> correspond to <code>X[3]</code></li> </ul> <p>And in second case:</p> <ul> <li><code>y[0]</code> correspond to <code>X[0]</code>,</li> <li><code>y[1]</code> correspond to <code>X[2]</code>,</li> <li><code>y[2]</code> correspond to <code>X[3]</code> </li> <li>and <code>y[3]</code> correspond to <code>X[1]</code>.</li> </ul> <p>I can't write a function to solve the problem completely, please help.</p>
5
2016-08-22T11:10:53Z
39,078,582
<p>Using this answer <a href="http://stackoverflow.com/a/8929827/3627387">http://stackoverflow.com/a/8929827/3627387</a> and <a href="http://stackoverflow.com/a/12141207/3627387">http://stackoverflow.com/a/12141207/3627387</a></p> <p><strong>FIXED</strong></p> <pre><code>def find_closest(alist, target): return min(alist, key=lambda x:abs(x-target)) X = [ 84.04467948, 52.42447842, 39.13555678, 21.99846595] Y = [ 78.86529444, 52.42447842, 38.74910101, 21.99846595] def list_matching(list1, list2): list1_copy = list1[:] pairs = [] for i, e in enumerate(list2): elem = find_closest(list1_copy, e) pairs.append([i, list1.index(elem)]) list1_copy.remove(elem) return pairs </code></pre>
3
2016-08-22T11:39:32Z
[ "python", "python-2.7" ]
How to find closest elements in two array?
39,078,043
<p>I have two numpy arrays, like <code>X=[x1,x2,x3,x4], y=[y1,y2,y3,y4]</code>. Three of the elements are close and the fourth of them maybe close or not.</p> <p>Like:</p> <pre><code>X [ 84.04467948 52.42447842 39.13555678 21.99846595] y [ 78.86529444 52.42447842 38.74910101 21.99846595] </code></pre> <p>Or it can be:</p> <pre><code>X [ 84.04467948 60 52.42447842 39.13555678] y [ 78.86529444 52.42447842 38.74910101 21.99846595] </code></pre> <p>I want to define a function to find the the corresponding index in the two arrays, like in first case:</p> <ul> <li><code>y[0]</code> correspond to <code>X[0]</code>,</li> <li><code>y[1]</code> correspond to <code>X[1]</code>,</li> <li><code>y[2]</code> correspond to <code>X[2]</code>,</li> <li><code>y[3]</code> correspond to <code>X[3]</code></li> </ul> <p>And in second case:</p> <ul> <li><code>y[0]</code> correspond to <code>X[0]</code>,</li> <li><code>y[1]</code> correspond to <code>X[2]</code>,</li> <li><code>y[2]</code> correspond to <code>X[3]</code> </li> <li>and <code>y[3]</code> correspond to <code>X[1]</code>.</li> </ul> <p>I can't write a function to solve the problem completely, please help.</p>
5
2016-08-22T11:10:53Z
39,079,552
<p>You can start by precomputing the distance matrix as show in this <a href="http://stackoverflow.com/a/9704775/6614295">answer</a>:</p> <pre><code>import numpy as np X = np.array([84.04467948,60.,52.42447842,39.13555678]) Y = np.array([78.86529444,52.42447842,38.74910101,21.99846595]) dist = np.abs(X[:, np.newaxis] - Y) </code></pre> <p>Now you can compute the minimums along one axis (I chose <code>1</code> corresponding to finding the closest element of <code>Y</code> for every <code>X</code>):</p> <pre><code>potentialClosest = dist.argmin(axis=1) </code></pre> <p>This still may contain duplicates (in your case 2). To check for that, you can find find all <code>Y</code> indices that appear in <code>potentialClosest</code> by use of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>np.unique</code></a>:</p> <pre><code>closestFound, closestCounts = np.unique(potentialClosest, return_counts=True) </code></pre> <p>Now you can check for duplicates by checking if <code>closestFound.shape[0] == X.shape[0]</code>. If so, you're golden and <code>potentialClosest</code> will contain your partners for every element in <code>X</code>. In your case 2 though, one element will occur twice and therefore <code>closestFound</code> will only have <code>X.shape[0]-1</code> elements whereas <code>closestCounts</code> will not contain only <code>1</code>s but one <code>2</code>. For all elements with count <code>1</code> the partner is already found. For the two candidates with count <code>2</code>, though you will have to choose the closer one while the partner of the one with the larger distance will be the one element of <code>Y</code> which is not in <code>closestFound</code>. This can be found as:</p> <pre><code>missingPartnerIndex = np.where( np.in1d(np.arange(Y.shape[0]), closestFound)==False )[0][0] </code></pre> <p>You can do the matchin in a loop (even though there might be some nicer way using <code>numpy</code>). This solution is rather ugly but works. Any suggestions for improvements are very appreciated:</p> <pre><code>partners = np.empty_like(X, dtype=int) nonClosePartnerFound = False for i in np.arange(X.shape[0]): if closestCounts[closestFound==potentialClosest[i]][0]==1: # A unique partner was found partners[i] = potentialClosest[i] else: # Partner is not unique if nonClosePartnerFound: partners[i] = potentialClosest[i] else: if np.argmin(dist[:, potentialClosest[i]]) == i: partners[i] = potentialClosest[i] else: partners[i] = missingPartnerIndex nonClosePartnerFound = True print(partners) </code></pre> <p>This answer will only work if only one pair is not close. If that is not the case, you will have to define how to find the correct partner for multiple non-close elements. Sadly it's neither a very generic nor a very nice solution, but hopefully you will find it a helpful starting point.</p>
1
2016-08-22T12:27:10Z
[ "python", "python-2.7" ]
How to find closest elements in two array?
39,078,043
<p>I have two numpy arrays, like <code>X=[x1,x2,x3,x4], y=[y1,y2,y3,y4]</code>. Three of the elements are close and the fourth of them maybe close or not.</p> <p>Like:</p> <pre><code>X [ 84.04467948 52.42447842 39.13555678 21.99846595] y [ 78.86529444 52.42447842 38.74910101 21.99846595] </code></pre> <p>Or it can be:</p> <pre><code>X [ 84.04467948 60 52.42447842 39.13555678] y [ 78.86529444 52.42447842 38.74910101 21.99846595] </code></pre> <p>I want to define a function to find the the corresponding index in the two arrays, like in first case:</p> <ul> <li><code>y[0]</code> correspond to <code>X[0]</code>,</li> <li><code>y[1]</code> correspond to <code>X[1]</code>,</li> <li><code>y[2]</code> correspond to <code>X[2]</code>,</li> <li><code>y[3]</code> correspond to <code>X[3]</code></li> </ul> <p>And in second case:</p> <ul> <li><code>y[0]</code> correspond to <code>X[0]</code>,</li> <li><code>y[1]</code> correspond to <code>X[2]</code>,</li> <li><code>y[2]</code> correspond to <code>X[3]</code> </li> <li>and <code>y[3]</code> correspond to <code>X[1]</code>.</li> </ul> <p>I can't write a function to solve the problem completely, please help.</p>
5
2016-08-22T11:10:53Z
39,097,490
<p>The below simply prints the corresponding indexes of the two arrays as you have done in your question as I'm not sure what output you want your function to give.</p> <pre><code>X1 = [84.04467948, 52.42447842, 39.13555678, 21.99846595] Y1 = [78.86529444, 52.42447842, 38.74910101, 21.99846595] X2 = [84.04467948, 60, 52.42447842, 39.13555678] Y2 = [78.86529444, 52.42447842, 38.74910101, 21.99846595] def find_closest(x_array, y_array): # Copy x_array as we will later remove an item with each iteration and # require the original later remaining_x_array = x_array[:] for y in y_array: differences = [] for x in remaining_x_array: differences.append(abs(y - x)) # min_index_remaining is the index position of the closest x value # to the given y in remaining_x_array min_index_remaining = differences.index(min(differences)) # related_x is the closest x value of the given y related_x = remaining_x_array[min_index_remaining] print 'Y[%s] corresponds to X[%s]' % (y_array.index(y), x_array.index(related_x)) # Remove the corresponding x value in remaining_x_array so it # cannot be selected twice remaining_x_array.pop(min_index_remaining) </code></pre> <p>This then outputs the following</p> <pre><code>find_closest(X1,Y1) Y[0] corresponds to X[0] Y[1] corresponds to X[1] Y[2] corresponds to X[2] Y[3] corresponds to X[3] </code></pre> <p>and</p> <pre><code>find_closest(X2,Y2) Y[0] corresponds to X[0] Y[1] corresponds to X[2] Y[2] corresponds to X[3] Y[3] corresponds to X[1] </code></pre> <p>Hope this helps.</p>
0
2016-08-23T09:32:40Z
[ "python", "python-2.7" ]
Converting a dataframe to dictionary with multiple values
39,078,078
<p>I have a dataframe like</p> <pre><code>Sr.No ID A B C D 1 Tom Earth English BMW 2 Tom Mars Spanish BMW Green 3 Michael Mercury Hindi Audi Yellow 4 John Venus Portugese Mercedes Blue 5 John German Audi Red </code></pre> <p>I am trying to convert this to a dictionary by ID like :</p> <pre><code>{'ID' : 'Tom', 'A' : ['Earth', 'Mars'], 'B' : ['English', 'Spanish'], 'C' : ['BMW', 'BMW'], 'D':['Green'] }, {'ID' : 'Michael', 'A' : ['Mercury'], 'B' : ['Hindi'], 'C' : ['Audi'], 'D':['Yellow']}, {'ID' : 'John', 'A' : ['Venus'], 'B' : ['Portugese', 'German'], 'C' : ['Mercedes', 'Audi'], 'D':['Blue', 'Red'] } </code></pre> <p><a href="http://stackoverflow.com/questions/20112760/python-pandas-convert-dataframe-to-dictionary-with-multiple-values">This</a> is somewhat similar to what I want. </p> <p>I also tried , </p> <pre><code>df.set_index('ID').to_dict() </code></pre> <p>but this gives me dictionary of length 5 instead of 3. Any help would be appreciated. </p>
2
2016-08-22T11:13:00Z
39,078,825
<p>You can use <code>groupby</code> with orient of <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.to_dict.html" rel="nofollow"><code>to_dict</code></a> as <code>list</code> and convert the resultant series to a <code>dictionary</code>.</p> <pre><code>df.set_index('Sr.No', inplace=True) df.groupby('ID').apply(lambda x: x.to_dict('list')).reset_index(drop=True).to_dict() {0: {'C': ['Mercedes', 'Audi'], 'ID': ['John', 'John'], 'A': ['Venus', nan], 'B': ['Portugese', 'German'], 'D': ['Blue', 'Red']}, 1: {'C': ['Audi'], 'ID': ['Michael'], 'A': ['Mercury'], 'B': ['Hindi'], 'D': ['Yellow']}, 2: {'C': ['BMW', 'BMW'], 'ID': ['Tom', 'Tom'], 'A': ['Earth', 'Mars'], 'B': ['English', 'Spanish'], 'D': [nan, 'Green']}} </code></pre> <hr> <p>Inorder to remove <code>ID</code>, you can also do:</p> <pre><code>df.groupby('ID')['A','B','C','D'].apply(lambda x: x.to_dict('list')) \ .reset_index(drop=True).to_dict() </code></pre>
2
2016-08-22T11:51:54Z
[ "python", "pandas", "dictionary", "dataframe" ]
Converting a dataframe to dictionary with multiple values
39,078,078
<p>I have a dataframe like</p> <pre><code>Sr.No ID A B C D 1 Tom Earth English BMW 2 Tom Mars Spanish BMW Green 3 Michael Mercury Hindi Audi Yellow 4 John Venus Portugese Mercedes Blue 5 John German Audi Red </code></pre> <p>I am trying to convert this to a dictionary by ID like :</p> <pre><code>{'ID' : 'Tom', 'A' : ['Earth', 'Mars'], 'B' : ['English', 'Spanish'], 'C' : ['BMW', 'BMW'], 'D':['Green'] }, {'ID' : 'Michael', 'A' : ['Mercury'], 'B' : ['Hindi'], 'C' : ['Audi'], 'D':['Yellow']}, {'ID' : 'John', 'A' : ['Venus'], 'B' : ['Portugese', 'German'], 'C' : ['Mercedes', 'Audi'], 'D':['Blue', 'Red'] } </code></pre> <p><a href="http://stackoverflow.com/questions/20112760/python-pandas-convert-dataframe-to-dictionary-with-multiple-values">This</a> is somewhat similar to what I want. </p> <p>I also tried , </p> <pre><code>df.set_index('ID').to_dict() </code></pre> <p>but this gives me dictionary of length 5 instead of 3. Any help would be appreciated. </p>
2
2016-08-22T11:13:00Z
39,078,846
<p>Grouping by <code>'ID'</code> and apply <code>to_dict</code> to each group with <code>orient='list'</code> comes pretty close:</p> <pre><code>df.groupby('ID').apply(lambda dfg: dfg.to_dict(orient='list')).to_dict() Out[25]: {'John': {'A': ['Venus', nan], 'B': ['Portugese', 'German'], 'C': ['Mercedes', 'Audi'], 'D': ['Blue', 'Red'], 'ID': ['John', 'John'], 'Sr.No': [4, 5]}, 'Michael': {'A': ['Mercury'], 'B': ['Hindi'], 'C': ['Audi'], 'D': ['Yellow'], 'ID': ['Michael'], 'Sr.No': [3]}, 'Tom': {'A': ['Earth', 'Mars'], 'B': ['English', 'Spanish'], 'C': ['BMW', 'BMW'], 'D': [nan, 'Green'], 'ID': ['Tom', 'Tom'], 'Sr.No': [1, 2]}} </code></pre> <p>It should just be a matter of formatting the result slightly.</p> <p><strong>Edit:</strong> to remove <code>'ID'</code> from the dictionaries:</p> <pre><code>df.groupby('ID').apply(lambda dfg: dfg.drop('ID', axis=1).to_dict(orient='list')).to_dict() Out[5]: {'John': {'A': ['Venus', nan], 'B': ['Portugese', 'German'], 'C': ['Mercedes', 'Audi'], 'D': ['Blue', 'Red'], 'Sr.No': [4, 5]}, 'Michael': {'A': ['Mercury'], 'B': ['Hindi'], 'C': ['Audi'], 'D': ['Yellow'], 'Sr.No': [3]}, 'Tom': {'A': ['Earth', 'Mars'], 'B': ['English', 'Spanish'], 'C': ['BMW', 'BMW'], 'D': [nan, 'Green'], 'Sr.No': [1, 2]}} </code></pre>
2
2016-08-22T11:52:26Z
[ "python", "pandas", "dictionary", "dataframe" ]
central path for python modules
39,078,177
<p>I am starting to convert a lot of C stuff in python 3.</p> <p>In C I defined a directory called "Toolbox", where i put all my functions i needed in different programs, so called libraries.</p> <p>To use a specific library i had just to add the line</p> <pre><code>#include "/home/User/Toolbox/VectorFunctions.h" </code></pre> <p>into my source. So i was able to use the same library in different sources. </p> <p>In python i tried to write some Toolbox functions and implement them into the source with import VectorFunctions, which works, as long as the file VectorFunctions.py is in the same directory as the source.</p> <p>I there a way (I think there must be one...) telling python that VectorFunctions.py is located in a different directory, e.g. /home/User/Python_Toolbox?</p> <p>Thanks for any comment!</p>
1
2016-08-22T11:18:32Z
39,078,449
<p>You can use python path. Writing this code beginning of your program :</p> <pre><code>import sys sys.path.append('/home/User/Python_Toolbox') </code></pre> <p>If you have <code>VectorFunctions.py</code> in this folder you can import it :</p> <pre><code>import VectorFunctions </code></pre>
1
2016-08-22T11:32:54Z
[ "python" ]
central path for python modules
39,078,177
<p>I am starting to convert a lot of C stuff in python 3.</p> <p>In C I defined a directory called "Toolbox", where i put all my functions i needed in different programs, so called libraries.</p> <p>To use a specific library i had just to add the line</p> <pre><code>#include "/home/User/Toolbox/VectorFunctions.h" </code></pre> <p>into my source. So i was able to use the same library in different sources. </p> <p>In python i tried to write some Toolbox functions and implement them into the source with import VectorFunctions, which works, as long as the file VectorFunctions.py is in the same directory as the source.</p> <p>I there a way (I think there must be one...) telling python that VectorFunctions.py is located in a different directory, e.g. /home/User/Python_Toolbox?</p> <p>Thanks for any comment!</p>
1
2016-08-22T11:18:32Z
39,078,643
<p>What I would do is to organize these toolbox functions into one installable Python package <code>bruno_toolbox</code>, with its <code>setup.py</code>, and then install it into development mode to system site packages, using <code>python setup.py develop</code>, and then use the <code>bruno_toolbox</code> like any other package on the system, everywhere. Then if that package feels useful, I'd publish it to PyPI for the benefit of everyone.</p>
3
2016-08-22T11:42:25Z
[ "python" ]
How to form clusters from a list of related ordered pairs (lists)? Please read the details
39,078,251
<p>Suppose we have a list of lists, <code>master = [[1,2], [2,5], [3,5], [7,8], [11,8], [11,12]]</code> where each ordered-pair is related, meaning <strong>1,2 are related and so are 2,5</strong> and they follow <em>Transitive</em> <em>property</em>, implies, <code>1,2,5</code> belong to the same cluster. </p> <p>The question is how do we cluster the above list into related elements?</p> <p>master's clusters would be: <code>{1,2,3,5} and {7,8,11,12}</code> </p> <p>I am using Python and thinking in terms of graphs. The efficient, the better. </p>
-3
2016-08-22T11:22:11Z
39,078,341
<p>Scipy has an implementation of connected components that look suitable for this problem, see <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.connected_components.html" rel="nofollow">scipy.sparse.csgraph.connected_components</a>.</p>
0
2016-08-22T11:26:39Z
[ "python", "graph" ]
How to form clusters from a list of related ordered pairs (lists)? Please read the details
39,078,251
<p>Suppose we have a list of lists, <code>master = [[1,2], [2,5], [3,5], [7,8], [11,8], [11,12]]</code> where each ordered-pair is related, meaning <strong>1,2 are related and so are 2,5</strong> and they follow <em>Transitive</em> <em>property</em>, implies, <code>1,2,5</code> belong to the same cluster. </p> <p>The question is how do we cluster the above list into related elements?</p> <p>master's clusters would be: <code>{1,2,3,5} and {7,8,11,12}</code> </p> <p>I am using Python and thinking in terms of graphs. The efficient, the better. </p>
-3
2016-08-22T11:22:11Z
39,080,512
<p>Let regard the master list as a record of points and edges between them. Which means there are 8 points 1, 2, 3, 5, 7, 8, 11, 12, and 6 edges between them. Following code may give you what you want.</p> <pre><code>import networkx from networkx.algorithms.components.connected import connected_components def to_graph(CL, edge): G = networkx.Graph() for part in CL: G.add_nodes_from(part) G.add_edges_from(edge) return G master = [[1,2], [2,5], [3,5], [7,8], [11,8], [11,12]] G = to_graph(master, master) for se in connected_components(G): print list(se) </code></pre> <blockquote> <p>[1, 2, 3, 5] [8, 11, 12, 7]</p> </blockquote> <p>and you can directly have your graph</p> <pre><code>import matplotlib.pyplot as plt pos = networkx.shell_layout(G) networkx.draw(G, pos) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/maX7Q.png" rel="nofollow"><img src="http://i.stack.imgur.com/maX7Q.png" alt="enter image description here"></a></p>
0
2016-08-22T13:11:35Z
[ "python", "graph" ]
normalizing data by duplication
39,078,282
<p><em>note: this question is indeed a duplicate of <a href="http://stackoverflow.com/questions/12680754/split-pandas-dataframe-string-entry-to-separate-rows">Split pandas dataframe string entry to separate rows</a>, but the answer provided here is more generic and informative, so with all respect due, I chose not to delete the thread</em></p> <hr> <p>I have a 'dataset' with the following format:</p> <pre><code> id | value | ... --------|-------|------ a | 156 | ... b,c | 457 | ... e,g,f,h | 346 | ... ... | ... | ... </code></pre> <p>and I would like to normalize it by duplicating all values for each ids:</p> <pre><code> id | value | ... --------|-------|------ a | 156 | ... b | 457 | ... c | 457 | ... e | 346 | ... g | 346 | ... f | 346 | ... h | 346 | ... ... | ... | ... </code></pre> <p>What I'm doing is applying the split-apply-combine principle of <code>pandas</code> using <code>.groupby</code> that creates a <code>tuple</code> for each group <code>(groupby value, pd.DataFrame())</code></p> <p>I created a column to group by that simply counts the ids in the row:</p> <pre><code>df['count_ids'] = df['id'].str.split(',').apply(lambda x: len(x)) id | value | count_ids --------|-------|------ a | 156 | 1 b,c | 457 | 2 e,g,f,h | 346 | 4 ... | ... | ... </code></pre> <p>The way I'm duplicating the rows is as follows:</p> <pre><code>pd.DataFrame().append([group]*count_ids) </code></pre> <p>I'm slowly progressing, but it is really complex, and I would appreciate any best practice or recommendation you can share with this type of problems.</p>
1
2016-08-22T11:23:29Z
39,078,508
<p>try this:</p> <pre><code>In [44]: df Out[44]: id value 0 a 156 1 b,c 457 2 e,g,f,h 346 In [45]: (df['id'].str.split(',', expand=True) ....: .stack() ....: .reset_index(level=0) ....: .set_index('level_0') ....: .rename(columns={0:'id'}) ....: .join(df.drop('id',1), how='left') ....: ) Out[45]: id value 0 a 156 1 b 457 1 c 457 2 e 346 2 g 346 2 f 346 2 h 346 </code></pre> <p>Explanation:</p> <pre><code>In [48]: df['id'].str.split(',', expand=True).stack() Out[48]: 0 0 a 1 0 b 1 c 2 0 e 1 g 2 f 3 h dtype: object In [49]: df['id'].str.split(',', expand=True).stack().reset_index(level=0) Out[49]: level_0 0 0 0 a 0 1 b 1 1 c 0 2 e 1 2 g 2 2 f 3 2 h In [50]: df['id'].str.split(',', expand=True).stack().reset_index(level=0).set_index('level_0') Out[50]: 0 level_0 0 a 1 b 1 c 2 e 2 g 2 f 2 h In [51]: df['id'].str.split(',', expand=True).stack().reset_index(level=0).set_index('level_0').rename(columns={0:'id'}) Out[51]: id level_0 0 a 1 b 1 c 2 e 2 g 2 f 2 h In [52]: df.drop('id',1) Out[52]: value 0 156 1 457 2 346 </code></pre>
2
2016-08-22T11:35:38Z
[ "python", "pandas", "split-apply-combine" ]
Python how to get the calling function (not just its name)?
39,078,467
<p>I want to write a function which returns the calling function:</p> <pre class="lang-py prettyprint-override"><code>def foo(): return get_calling_function() #should return 'foo' function object </code></pre> <p>There's numerous examples online how to get the calling function's <em>name</em>, but not how to get the actual object. I've come up with the following solution which gets the name, then looks it up in the calling function's global namespace. However this doesn't work for class functions since there you need the class name as well, and I image there's a bunch of other edge cases as well. </p> <pre class="lang-py prettyprint-override"><code>from inspect import stack def get_calling_function(): return stack()[2][0].f_globals[stack()[1][3]] </code></pre> <p>So any advice how or if its possible to write this function so that it works generically (on Python 3, btw)? Thanks. </p>
2
2016-08-22T11:33:53Z
39,079,070
<p>Calling can happen from any code object (and from an extension module/builtin): from <code>exec</code>, <code>execfile</code>, from module name space (during import), from within a class definition, from within a method / classmethod / staticmethod, from a decorated function/method, from within a nested function, ... - so there is no "calling function" in general, and the difficulty to do anything good with that.</p> <p>The stack frames and their code objects are the most general you can get - and examine the attributes.</p> <hr> <p>This one finds the calling function in many cases:</p> <pre><code>import sys, inspect def get_calling_function(): """finds the calling function in many decent cases.""" fr = sys._getframe(1) # inspect.stack()[1][0] co = fr.f_code for get in ( lambda:fr.f_globals[co.co_name], lambda:getattr(fr.f_locals['self'], co.co_name), lambda:getattr(fr.f_locals['cls'], co.co_name), lambda:fr.f_back.f_locals[co.co_name], # nested lambda:fr.f_back.f_locals['func'], # decorators lambda:fr.f_back.f_locals['meth'], lambda:fr.f_back.f_locals['f'], ): try: func = get() except (KeyError, AttributeError): pass else: if func.__code__ == co: return func raise AttributeError("func not found") # Usage def f(): def nested_func(): print get_calling_function() print get_calling_function() nested_func() class Y: def meth(self, a, b=10, c=11): print get_calling_function() class Z: def methz(self): print get_calling_function() z = Z() z.methz() return z @classmethod def clsmeth(cls): print get_calling_function() @staticmethod def staticmeth(): print get_calling_function() f() y = Y() z = y.meth(7) z.methz() y.clsmeth() ##y.staticmeth() # would fail </code></pre> <p>It finds:</p> <pre><code>&lt;function f at 0x012E5670&gt; &lt;function nested_func at 0x012E51F0&gt; &lt;bound method Y.meth of &lt;__main__.Y instance at 0x01E41580&gt;&gt; &lt;bound method Z.methz of &lt;__main__.Z instance at 0x01E63EE0&gt;&gt; &lt;bound method Z.methz of &lt;__main__.Z instance at 0x01E63EE0&gt;&gt; &lt;bound method classobj.clsmeth of &lt;class __main__.Y at 0x01F3CF10&gt;&gt; </code></pre>
1
2016-08-22T12:03:27Z
[ "python", "function", "python-3.x", "inspect" ]
How to access parent abstract class of model in Django
39,078,490
<p><em>(using dajngo 1.9 and python 2.7)</em></p> <p>So I have an abstract class with a few child classes. It looks like this :</p> <pre><code>class Node(models.Model): [...] class Meta: abstract = True class Individual(Node): [...] class Company(Node): [...] class Media(Node): [...] class Share(models.Model): share = models.FloatField(null=True) child_content_type = models.ForeignKey(ContentType, related_name='child') child_object_id = models.PositiveIntegerField() child = GenericForeignKey('child_content_type', 'child_object_id') parent_content_type = models.ForeignKey(ContentType, related_name='parent') parent_object_id = models.PositiveIntegerField() parent = GenericForeignKey('parent_content_type', 'parent_object_id') </code></pre> <p>The thing is that, virtually, the Share's child and parent can take any model in. So I want to implement an extended save() method (for Share) that will check that both the child and the parent inherit from Node. </p> <p>I'm looking for something that could look like this :</p> <pre><code>assert child.inherited_class.name == 'node' assert parent.inherited_class.name == 'node' </code></pre> <p>(or with <code>child_content_type</code> of ocurse)</p>
0
2016-08-22T11:34:48Z
39,078,579
<p>Use <a href="https://docs.python.org/2/library/functions.html#isinstance" rel="nofollow"><code>isinstance</code></a>:</p> <pre><code>assert isinstance(child, Node) assert isinstance(parent, Node) </code></pre>
1
2016-08-22T11:39:20Z
[ "python", "django", "class", "inheritance" ]