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 |
---|---|---|---|---|---|---|---|---|---|
Logical operations with array of strings in Python
| 39,666,136 |
<p>I know the following logical operation works with numpy: </p>
<pre><code>A = np.array([True, False, True])
B = np.array([1.0, 2.0, 3.0])
C = A*B = array([1.0, 0.0, 3.0])
</code></pre>
<p>But the same isn't true if B is an array of strings. Is it possible to do the following: </p>
<pre><code>A = np.array([True, False, True])
B = np.array(['eggs', 'milk', 'cheese'])
C = A*B = array(['eggs', '', 'cheese'])
</code></pre>
<p>That is a string multiplied with False should equal an empty string. Can this be done without a loop in Python (doesn't have to use numpy)?</p>
<p>Thanks!</p>
| 2 |
2016-09-23T17:08:51Z
| 39,666,179 |
<p>Since strings may be multiplied by integers, and booleans are integers:</p>
<pre><code>A = [True, False, True]
B = ['eggs', 'milk', 'cheese']
C = [a*b for a, b in zip(A, B)]
# C = ['eggs', '', 'cheese']
</code></pre>
<p>I still uses some kind of loop (same as numpy solution), but it's hidden in concise list comprehension.</p>
<p>Alternatively:</p>
<pre><code>C = [a if b else '' for a, b in zip(A, B)] # explicit loop may be clearer than multiply-sequence trick
</code></pre>
| 1 |
2016-09-23T17:11:35Z
|
[
"python",
"string",
"numpy",
"logical-operators"
] |
Logical operations with array of strings in Python
| 39,666,136 |
<p>I know the following logical operation works with numpy: </p>
<pre><code>A = np.array([True, False, True])
B = np.array([1.0, 2.0, 3.0])
C = A*B = array([1.0, 0.0, 3.0])
</code></pre>
<p>But the same isn't true if B is an array of strings. Is it possible to do the following: </p>
<pre><code>A = np.array([True, False, True])
B = np.array(['eggs', 'milk', 'cheese'])
C = A*B = array(['eggs', '', 'cheese'])
</code></pre>
<p>That is a string multiplied with False should equal an empty string. Can this be done without a loop in Python (doesn't have to use numpy)?</p>
<p>Thanks!</p>
| 2 |
2016-09-23T17:08:51Z
| 39,667,515 |
<p><code>np.char</code> applies string methods to elements of an array:</p>
<pre><code>In [301]: np.char.multiply(B, A.astype(int))
Out[301]:
array(['eggs', '', 'cheese'],
dtype='<U6')
</code></pre>
<p>I had to convert the boolean to integer, and place it second.</p>
<p>Timing in other questions indicates that <code>np.char</code> iterates and applies the Python methods. Speed's about the same as for list comprehension.</p>
<p>For in-place change, use masked assignment instead of <code>where</code></p>
<pre><code>In [306]: B[~A]=''
In [307]: B
Out[307]:
array(['eggs', '', 'cheese'],
dtype='<U6')
</code></pre>
| 1 |
2016-09-23T18:38:32Z
|
[
"python",
"string",
"numpy",
"logical-operators"
] |
Html missing when using View page source
| 39,666,183 |
<p>Im trying to extract all the images from a page. I have used Mechanize Urllib and selenium to extract the Html but the part i want to extract is never there. Also when i view the page source im not able to view the part i want to extract. Instead of the Description i want to extract there is this: </p>
<pre><code> <div class="loading32"></div>
</div>
</div>
</div>
</code></pre>
<p>But if i try to view it using the inspect element option its there.
Is there a easy way to figure out what this script does without any java knowledge? So i can bypass it. or is there a way to get an equivalent of inspect element using selenium in python 2.7? What is the difference between View page source and inspect element anyway? </p>
| -1 |
2016-09-23T17:11:51Z
| 39,666,291 |
<p>Possibly you're trying to get elements that are created with a client sided script. I don't think javascript elements run when you just send a GET/POST request (which is what I'm assuming you mean by "view source").</p>
| 0 |
2016-09-23T17:18:21Z
|
[
"java",
"python",
"html",
"selenium",
"web-scraping"
] |
Function pointer across classes and threads
| 39,666,221 |
<p>Here is my QT code</p>
<pre><code>from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QTime
from PyQt4.QtGui import QApplication
from keithley.PS2231A import PS2231A
class A(QtGui.QMainWindow, gui.Ui_MainWindow):
def __init__(self, parent=None):
super(A, self).__init__(parent)
self.setupUi(self)
ps = PS2231A(port='COM8')
self.refresh.clicked.connect(self.get_data)
def get_data(self):
data = ps.read_current()
self.current_measurement.setText(str(data))
def main():
app = QtGui.QApplication([])
form = A()
form.show()
app.exec()
if __name__ == '__main__':
main()
</code></pre>
<p>Now here is my PS2231A library</p>
<pre><code>class PS2231A:
def __init__(self, port: str):
self._port = port
self._dev = serial.Serial()
self._dev.port = self._port
self._dev.timeout = 5
self._dev.baudrate = 9600
self.connect()
self._dev.open()
def read_current(self):
self._dev.write('MEAS:CURR?')
current = self._dev.readline()
return float(current)
</code></pre>
<p>Here is what I would like to achieve:
The power supply provides emergency messages like over current. It essentially ends up writing that message to serial port without any command requesting data. As soon as that message is received, I would want the GUI to change.</p>
<p>Scope:
Here I am writing the library for PS2231A, and a user will be writing a GUI around it. I would like a library side solution to propagate the message to GUI, here is how I envision it:</p>
<p>Step 1: When an object of PS2231A is created, start a thread, which will read the serial port (poll it) for messages. Once the emergency message is read, it calls a function in the library.
Step 2: The function being called by the thread, should execute any function that the user wants, i.e. if the user wants to turn the GUI background to red, the user writes the code in a function named turn_background_red, passes the function name to the library function. Then the library function executes the code whenever the emergency message is called. </p>
<p>I think the code below will explain this well (I want this to happen, so some code will not work):</p>
<p>QT Code</p>
<pre><code>from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QTime
from PyQt4.QtGui import QApplication
from keithley.PS2231A import PS2231A
class A(QtGui.QMainWindow, gui.Ui_MainWindow):
def __init__(self, parent=None):
super(A, self).__init__(parent)
self.setupUi(self)
ps = PS2231A(port='COM8')
ps.set_over_current_callback(self.warn_user)
self.refresh.clicked.connect(self.get_data)
def warn_user(self):
# manipulate some GUI element
# implemented by user
def get_data(self):
data = ps.read_current()
self.current_measurement.setText(str(data))
def main():
app = QtGui.QApplication([])
form = A()
form.show()
app.exec()
if __name__ == '__main__':
main()
</code></pre>
<p>Class code implementation</p>
<pre><code>class PS2231A:
def __init__(self, port: str):
self._port = port
self._dev = serial.Serial()
self._dev.port = self._port
self._dev.timeout = 5
self._dev.baudrate = 9600
self.connect()
self._dev.open()
def read_current(self):
self._dev.write('MEAS:CURR?')
current = self._dev.readline()
return float(current)
def set_over_current_callback(self, function_name):
# write some code to run the function name passed to this function
# This is the code I am not sure how to go ahead with
# This function will be executed if an emergency message is received
# on serial port
</code></pre>
<p>Some critical challenges I faced when thinking about this were that the function to be executed is in different class. </p>
| 0 |
2016-09-23T17:13:43Z
| 39,672,550 |
<p>You really should revise your question more (see <a href="http://stackoverflow.com/help/mcve">Minimal, Complete and Verifiable</a>), but here is one solution, that should work for at least for both Python 2.7 and 3.5:</p>
<pre><code>import types
class PS2231A:
# Rest of your class
def set_over_current_callback(self, function_name):
func = getattr(self, function_name, None)
if isinstance(func, types.MethodType):
func()
return
</code></pre>
<p>This checks if the instance of class <code>PS2231A</code> has an attribute with the name <code>function_name</code> and if it's type is method, it gets called. </p>
<p>Let me know if I made some mistake, typed this on a phone.</p>
| 0 |
2016-09-24T04:36:50Z
|
[
"python",
"qt",
"python-3.x"
] |
matplotlib. legend for one curve
| 39,666,246 |
<p>I am trying to make a label for a curve</p>
<pre><code>plt.plot([1,2],[1,8])
plt.legend("some text")
plt.show()
</code></pre>
<p>However, there is only one first letter of my text in the graph:
<a href="http://i.stack.imgur.com/rXHsf.png" rel="nofollow"><img src="http://i.stack.imgur.com/rXHsf.png" alt="enter image description here"></a> </p>
<p>What am I doing wrong?</p>
| 0 |
2016-09-23T17:15:17Z
| 39,666,481 |
<p><code>
plt.plot([1,2],[1,8], label="some text")
plt.legend()
plt.show()</code></p>
| 0 |
2016-09-23T17:31:04Z
|
[
"python",
"matplotlib",
"plot",
"label"
] |
matplotlib. legend for one curve
| 39,666,246 |
<p>I am trying to make a label for a curve</p>
<pre><code>plt.plot([1,2],[1,8])
plt.legend("some text")
plt.show()
</code></pre>
<p>However, there is only one first letter of my text in the graph:
<a href="http://i.stack.imgur.com/rXHsf.png" rel="nofollow"><img src="http://i.stack.imgur.com/rXHsf.png" alt="enter image description here"></a> </p>
<p>What am I doing wrong?</p>
| 0 |
2016-09-23T17:15:17Z
| 39,666,656 |
<p>You can achieve this with out passing any arguments to the <code>legend</code> function by passing a value to the label property of the plot function:</p>
<pre><code>plt.plot([1,2],[1,8],label='some text')
plt.plot([1,2],[1,4],label='some other text')
plt.legend()
plt.show()
</code></pre>
<p>You can find more details on how to use <code>matplotlib</code> legends in the <a href="http://matplotlib.org/users/legend_guide.html" rel="nofollow">legends guide</a></p>
| 1 |
2016-09-23T17:44:08Z
|
[
"python",
"matplotlib",
"plot",
"label"
] |
How to run python scripts and do CMD in Dockerfile for the docker container
| 39,666,270 |
<p>I have an image with a custom Dockerfile. When I start the container, I want to run <code>CMD ["npm, "start"]</code> but right before that, I need to run three scripts.</p>
<p>I've tried:</p>
<p>1)putting the python scripts followed by npm start in a .sh script, and running <code>CMD ["script-location/script.sh"]</code></p>
<p>2) calling <code>CMD ["script", "npm", "start"]</code></p>
<p>none of this is working, and after the python scripts run, the container shuts down instead of running npm start and listening at a port. Not sure how to fix this.</p>
<p>the bash script I have is:</p>
<pre><code>#!/bin/bash
echo starting to run runtime_properties...
python /var/first_script.py
echo finished runtime_properties
echo starting to run runtime_properties...
python /var/second_script.py
echo finished runtime_files
echo starting to run config-dns-props...
python /var/third_script.py
echo finishing config runtime files
echo starting to run npm start...
npm start
</code></pre>
| 0 |
2016-09-23T17:16:54Z
| 39,666,587 |
<p>Had to run <code>ENTRYPOINT ["script-path/script.sh"]</code></p>
| 0 |
2016-09-23T17:39:25Z
|
[
"python",
"docker",
"npm",
"dockerfile"
] |
pd.read_csv by default treats integers like floats
| 39,666,308 |
<p>I have a <code>csv</code> that looks like (headers = first row):</p>
<pre><code>name,a,a1,b,b1
arnold,300311,arnld01,300311,arnld01
sam,300713,sam01,300713,sam01
</code></pre>
<p>When I run:</p>
<pre><code>df = pd.read_csv('file.csv')
</code></pre>
<p>Columns <code>a</code> and <code>b</code> have a <code>.0</code> attached to the end like so:</p>
<pre><code>df.head()
name,a,a1,b,b1
arnold,300311.0,arnld01,300311.0,arnld01
sam,300713.0,sam01,300713.0,sam01
</code></pre>
<p>Columns <code>a</code> and <code>b</code> are integers or blanks so why does <code>pd.read_csv()</code> treat them like floats and how do I ensure they are integers on the read? </p>
| 1 |
2016-09-23T17:19:38Z
| 39,666,666 |
<p>As <a href="http://stackoverflow.com/questions/39666308/pd-read-csv-by-default-treats-integers-like-floats#comment66634324_39666308">root</a> mentioned in the comments, this is a limitation of Pandas (and Numpy). <code>NaN</code> is a float and the empty values you have in your CSV are NaN.</p>
<p>This is listed in the <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#na-type-promotions" rel="nofollow">gotchas</a> of pandas as well. </p>
<p>You can work around this in a few ways. </p>
<p>For the examples below I used the following to import the data - note that I added a row with an empty value in columns <code>a</code> and <code>b</code></p>
<pre><code>import pandas as pd
from StringIO import StringIO
data = """name,a,a1,b,b1
arnold,300311,arnld01,300311,arnld01
sam,300713,sam01,300713,sam01
test,,test01,,test01"""
df = pd.read_csv(StringIO(data), sep=",")
</code></pre>
<h3>Drop NaN rows</h3>
<p>Your first option is to drop rows that contain this <code>NaN</code> value. The downside of this, is that you lose the entire row. After getting your data into a dataframe, run this:</p>
<pre><code>df.dropna(inplace=True)
df.a = df.a.astype(int)
df.b = df.b.astype(int)
</code></pre>
<p>This drops all <code>NaN</code> rows from the dataframe, then it converts column <code>a</code> and column <code>b</code> to an <code>int</code></p>
<pre><code>>>> df.dtypes
name object
a int32
a1 object
b int32
b1 object
dtype: object
>>> df
name a a1 b b1
0 arnold 300311 arnld01 300311 arnld01
1 sam 300713 sam01 300713 sam01
</code></pre>
<h3>Fill <code>NaN</code> with placeholder data</h3>
<p>This option will replace all your <code>NaN</code> values with a throw away value. That value is something you need to determine. For this test, I made it <code>-999999</code>. This will allow use to keep the rest of the data, convert it to an int, and make it obvious what data is invalid. You'll be able to filter these rows out if you are making calculations based on the columns later. </p>
<pre><code>df.fillna(-999999, inplace=True)
df.a = df.a.astype(int)
df.b = df.b.astype(int)
</code></pre>
<p>This produces a dataframe like so:</p>
<pre><code>>>> df.dtypes
name object
a int32
a1 object
b int32
b1 object
dtype: object
>>> df
name a a1 b b1
0 arnold 300311 arnld01 300311 arnld01
1 sam 300713 sam01 300713 sam01
2 test -999999 test01 -999999 test01
</code></pre>
<h3>Leave the float values</h3>
<p>Finally, another choice is to leave the float values (and <code>NaN</code>) and not worry about the non-integer data type. </p>
| 1 |
2016-09-23T17:45:09Z
|
[
"python",
"csv",
"pandas",
"integer"
] |
Port sweep with python
| 39,666,387 |
<p>Well im trying to do something really simpale but from some reason i just can't understand how to do it.</p>
<p>Im trying to write a simple port sweep
let's say i have a gateway address of 192.168.1.1 all i want to do is to create a for loop to run between 1 to 254 and test what ip address there are over the network </p>
<p>The for loop is really easy:</p>
<pre><code>for i in range(1,254,1):
</code></pre>
<p>I need that i will change everytime at 192.168.1.i</p>
<p>How can i do that?</p>
| 0 |
2016-09-23T17:25:06Z
| 39,666,488 |
<p>There's a way of doing this in the standard library:</p>
<pre><code>>>> import ipaddress
>>> for addr in ipaddress.IPv4Network('192.168.1.0/24'):
... print(addr)
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
#more addresses
192.168.1.254
192.168.1.255
</code></pre>
| 0 |
2016-09-23T17:31:36Z
|
[
"python",
"for-loop",
"networking",
"ping"
] |
Port sweep with python
| 39,666,387 |
<p>Well im trying to do something really simpale but from some reason i just can't understand how to do it.</p>
<p>Im trying to write a simple port sweep
let's say i have a gateway address of 192.168.1.1 all i want to do is to create a for loop to run between 1 to 254 and test what ip address there are over the network </p>
<p>The for loop is really easy:</p>
<pre><code>for i in range(1,254,1):
</code></pre>
<p>I need that i will change everytime at 192.168.1.i</p>
<p>How can i do that?</p>
| 0 |
2016-09-23T17:25:06Z
| 39,666,496 |
<p>Use string formatting to accomplish that</p>
<pre><code>'192.168.1.{0}'.format(i)
</code></pre>
<p>Or be a brute and do concatenation</p>
<pre><code>'192.168.1.' + str(i)
</code></pre>
| 1 |
2016-09-23T17:32:03Z
|
[
"python",
"for-loop",
"networking",
"ping"
] |
Keep the subprocess run
| 39,666,405 |
<p>I have an exe file build from C++ to get the mouse shape in two states: hand or arrow. But in code it only detects one current time (run in only time and close), the output is state.
I call it in python to get the output in the Windows shell:</p>
<pre><code>output = subprocess.check_output([r'C:\Users\TomCang\Desktop\tim voi tu khoa\mouse_detect.exe'])
</code></pre>
<p>It runs 1 time, gives me the state and stops.<br>
I tried to make it run forever with:</p>
<pre><code>while(True):
output = subprocess.check_output([r'C:\Users\TomCang\Desktop\tim voi tu khoa\mouse_detect.exe'])
sleep(1)
print(output)
</code></pre>
<p>Every second it checks once, but when called once is the one time the Windows shell appears. How can I call it only once and run as long as I want with only one Windows shell appearing?</p>
<p>P.S.: I can't edit my C++ function because I lost the source.</p>
| 0 |
2016-09-23T17:26:07Z
| 39,666,615 |
<p>Yes you can. Instead of using the convenient function <code>check_output</code>, you would construct a <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="nofollow"><code>Popen</code> object</a>. This will start the process and let you control it while running. One possibility is to capture the output into a file object (usually known as "pipe" the output):</p>
<pre><code>program = r'C:\Users\TomCang\Desktop\tim voi tu khoa\mouse_detect.exe'
with subprocess.Popen([program], stdout=subprocess.PIPE, universal_newlines=True) as p:
for line in p.stdout:
print(line)
</code></pre>
<ul>
<li><code>stdout=subprocess.PIPE</code> â Pipe the stdout into the file object <code>p.stdout</code></li>
<li><code>universal_newlines=True</code> â Make the file be read as a text instead of binary</li>
</ul>
<p>The inner <code>for</code> loop will wait until there is output available from the program. So you don't need that <code>time.sleep(1)</code>.</p>
| 0 |
2016-09-23T17:41:12Z
|
[
"python",
"cursor"
] |
Python - concatenating byte to string cutting off some bytes in string
| 39,666,422 |
<p>I'm trying to decrypt an image file using Python with the AES cipher. We've been given a key with 15 bytes, and it's our job to decrypt the image running through the first byte. </p>
<p>and what I have so far is:</p>
<pre><code>fifteenbytes = b'\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
for i in range(0, 256):
ipack = pack('B', i)
key = ipack + fifteenbytes
</code></pre>
<p>I was hoping I'd be getting key as something like:</p>
<pre><code>\x00\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c
</code></pre>
<p>for iterations 0 - 255, but I end up with:</p>
<pre><code>b'\x00~\x15\x16(\xae\xd2\xa6\xab\xf7\x15\x88\t\xcfO<'
</code></pre>
<p>or sometimes exit characters and ascii values like:</p>
<pre><code>b'\t~\x15\x16(\xae\xd2\xa6\xab\xf7\x15\x88\t\xcfO<'
b'%~\x15\x16(\xae\xd2\xa6\xab\xf7\x15\x88\t\xcfO<'
</code></pre>
<p>Can someone please explain why this happens?</p>
| 1 |
2016-09-23T17:27:06Z
| 39,666,543 |
<p>You are getting correct output, but you appear to be confused by the <code>repr()</code> output for a <code>bytes</code> value.</p>
<p>Python gives you a value that can safely be copied and pasted back into a Python session. This aids debugging. This display uses ASCII printable text where possible to represent the value, but the value can be exactly reproduced with what is displayed.</p>
<p>Your expected value <code>b'\x00\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'</code> contains several ASCII characters that are printable, so Python shows those instead of the <code>\xhh</code> byte value:</p>
<pre><code>>>> output = b'\x00\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
>>> output
b'\x00~\x15\x16(\xae\xd2\xa6\xab\xf7\x15\x88\t\xcfO<'
>>> output == b'\x00\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
True
</code></pre>
<p>The bytestring is still 16 bytes long:</p>
<pre><code>>>> len(output)
16
</code></pre>
<p>That <code>~</code> is ASCII codepoint 126, or 0x7E in hexadecimal:</p>
<pre><code>>>> output[1]
126
>>> hex(output[1])
'0x7e'
</code></pre>
<p>The same applies to <code>\x28</code> and <code>(</code>, <code>\x09</code> and <code>\t</code> (the tab character escape sequence), <code>\x4f</code> and <code>O</code>, and <code>\x3c</code> and <code><</code>.</p>
<p>The <code>\xhh</code> escape sequence is just notation in a <code>bytes</code> object literal to define a given byte value, but you can produce the exact same value with <code>~</code>. Ditto for <code>\t</code>, you can express that same value as <code>\x09</code>, but Python prefers using the <code>\t</code> sequence when showing the representation.</p>
| 1 |
2016-09-23T17:35:31Z
|
[
"python",
"byte",
"aes",
"pycrypto"
] |
Cannot get gcloud to work with Python and Pycharm
| 39,666,449 |
<p>I am trying to connect to the Google App Engine Datastore from my local machine. I have spent all day digging in to this without any luck.</p>
<p>I have tried the approach here (as well as alot of other suggestions from SO such as <a href="http://stackoverflow.com/questions/27057935/using-gcloud-python-in-gae">Using gcloud-python in GAE</a> and <a href="http://stackoverflow.com/questions/34584937/unable-to-run-dev-appserver-py-with-gcloud">Unable to run dev_appserver.py with gcloud</a>):</p>
<p><a href="http://stackoverflow.com/questions/34572330/how-to-access-a-remote-datastore-when-running-dev-appserver-py/34575005#34575005">How to access a remote datastore when running dev_appserver.py?</a></p>
<p>I first installed gcloud based on this description from google:
<a href="https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27" rel="nofollow">https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27</a> </p>
<p>According to the description I should add the following to my appengine_config.py:</p>
<pre><code>from google.appengine.ext import vendor
vendor.add('lib')
</code></pre>
<p>If I do that I get an error saying <code>ImportError: No module named gcloud</code></p>
<p>If I then move the code to my main.py it seems to pickup the lib-folder and the modules there. That seems a bit strange to me, since I thought appengine_config was being run first to make sure things were initialised.
But now I am getting the following stack trace:</p>
<pre><code>ERROR 2016-09-23 17:22:30,623 cgi.py:122] Traceback (most recent call last):
File "/Users/thomasd/Documents/github/myapp/main.py", line 10, in <module>
from gcloud import datastore
File "/Users/thomasd/Documents/github/myapp/lib/gcloud/__init__.py", line 17, in <module>
from pkg_resources import get_distribution
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2985, in <module>
@_call_aside
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2971, in _call_aside
f(*args, **kwargs)
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 3013, in _initialize_master_working_set
dist.activate(replace=False)
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2544, in activate
declare_namespace(pkg)
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2118, in declare_namespace
_handle_ns(packageName, path_item)
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2057, in _handle_ns
loader.load_module(packageName)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 246, in load_module
mod = imp.load_module(fullname, self.file, self.filename, self.etc)
File "/Library/Python/2.7/site-packages/google/cloud/logging/__init__.py", line 18, in <module>
File "/usr/local/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 999, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named google.cloud.logging.client
</code></pre>
<p>What am I doing wrong here?</p>
| 1 |
2016-09-23T17:28:42Z
| 39,823,292 |
<p>The <code>google-cloud</code> library is <a href="https://github.com/GoogleCloudPlatform/google-cloud-python/issues/1893" rel="nofollow">not working on App Engine</a> and most likely you don't even have to since you can use the build in functionality.</p>
<p>From the <a href="https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/read-write-to-cloud-storage" rel="nofollow">official docs</a> you can use it like this:</p>
<pre><code>import cloudstorage as gcs
</code></pre>
| 1 |
2016-10-03T01:04:55Z
|
[
"python",
"google-app-engine",
"gcloud-python",
"google-cloud-python"
] |
Cannot get gcloud to work with Python and Pycharm
| 39,666,449 |
<p>I am trying to connect to the Google App Engine Datastore from my local machine. I have spent all day digging in to this without any luck.</p>
<p>I have tried the approach here (as well as alot of other suggestions from SO such as <a href="http://stackoverflow.com/questions/27057935/using-gcloud-python-in-gae">Using gcloud-python in GAE</a> and <a href="http://stackoverflow.com/questions/34584937/unable-to-run-dev-appserver-py-with-gcloud">Unable to run dev_appserver.py with gcloud</a>):</p>
<p><a href="http://stackoverflow.com/questions/34572330/how-to-access-a-remote-datastore-when-running-dev-appserver-py/34575005#34575005">How to access a remote datastore when running dev_appserver.py?</a></p>
<p>I first installed gcloud based on this description from google:
<a href="https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27" rel="nofollow">https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27</a> </p>
<p>According to the description I should add the following to my appengine_config.py:</p>
<pre><code>from google.appengine.ext import vendor
vendor.add('lib')
</code></pre>
<p>If I do that I get an error saying <code>ImportError: No module named gcloud</code></p>
<p>If I then move the code to my main.py it seems to pickup the lib-folder and the modules there. That seems a bit strange to me, since I thought appengine_config was being run first to make sure things were initialised.
But now I am getting the following stack trace:</p>
<pre><code>ERROR 2016-09-23 17:22:30,623 cgi.py:122] Traceback (most recent call last):
File "/Users/thomasd/Documents/github/myapp/main.py", line 10, in <module>
from gcloud import datastore
File "/Users/thomasd/Documents/github/myapp/lib/gcloud/__init__.py", line 17, in <module>
from pkg_resources import get_distribution
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2985, in <module>
@_call_aside
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2971, in _call_aside
f(*args, **kwargs)
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 3013, in _initialize_master_working_set
dist.activate(replace=False)
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2544, in activate
declare_namespace(pkg)
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2118, in declare_namespace
_handle_ns(packageName, path_item)
File "/Users/thomasd/Documents/github/myapp/lib/pkg_resources/__init__.py", line 2057, in _handle_ns
loader.load_module(packageName)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 246, in load_module
mod = imp.load_module(fullname, self.file, self.filename, self.etc)
File "/Library/Python/2.7/site-packages/google/cloud/logging/__init__.py", line 18, in <module>
File "/usr/local/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 999, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named google.cloud.logging.client
</code></pre>
<p>What am I doing wrong here?</p>
| 1 |
2016-09-23T17:28:42Z
| 40,041,928 |
<p>I solved it this way:- </p>
<p>1.) Create a lib folder in your project path.</p>
<p>2.) Install gcloud libraries by running following command into terminal from your project path:-</p>
<pre><code> pip install -t lib gcloud
</code></pre>
<p>3.) Create an appengine_config.py module in your project and add following lines of code:-</p>
<pre><code> import sys
import os.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))
</code></pre>
<p>4.) After this, you can import like this:-</p>
<pre><code> from gcloud import datastore
</code></pre>
<p>5.) To save data into live google datastore from local:-</p>
<pre><code> client = datastore.Client("project-id")
key = client.key('Person')
entity = datastore.Entity(key=key)
entity['name'] = ashish
entity['age'] = 23
client.put(entity)
</code></pre>
<p>It will save an entity named Person having properties name and age. Do not forget to specify your correct project id.</p>
| 0 |
2016-10-14T11:20:27Z
|
[
"python",
"google-app-engine",
"gcloud-python",
"google-cloud-python"
] |
python dash button trigger not working
| 39,666,459 |
<p>this is my script to see if the amazon dash button is pressed:</p>
<pre><code>from scapy.all import *
def udp_filter(pkt):
options = pkt[DHCP].options
for option in options:
if isinstance(option, tuple):
if 'requested_addr' in option:
print('button pressed')
break
print('Waiting for a button press...')
sniff(prn=udp_filter, store=0, count=0, filter="udp", lfilter=lambda d: d.src == '8c:xx:xx:xx:xx:xx')
if __name__ == "__main__":
main()
</code></pre>
<p>but i got the following error message:</p>
<pre><code>Traceback (most recent call last):
File "short.py", line 12, in <module>
sniff(prn=udp_filter, store=0, count=0, filter="udp", lfilter=lambda d: d.src == '8c:xx:xx:xx:xx:xx')
File "/usr/local/lib/python3.4/dist-packages/scapy/sendrecv.py", line 597, in sniff
r = prn(p)
File "dash.py", line 4, in udp_filter
options = pkt[DHCP].options
File "/usr/local/lib/python3.4/dist-packages/scapy/packet.py", line 814, in __getitem__
raise IndexError("Layer [%s] not found" % lname)
IndexError: Layer [DHCP] not found
</code></pre>
<p>has someone a idea how to fix it and get it working under python3.4?</p>
| 0 |
2016-09-23T17:29:31Z
| 39,667,162 |
<p>It looks like the error is saying it can't find a DHCP Layer in the packet. Could you add <code>if pkt.haslayer(DHCP):</code> just above <code>options = pkt[DHCP].options</code> like this:</p>
<p><code>def udp_filter(pkt):
if pkt.haslayer(DHCP):
options = pkt[DHCP].options
for option in options:
if isinstance(option, tuple):
if 'requested_addr' in option:
print('button pressed')
break
else: pass</code><br>
That way it will check for DHCP before looking for pkt[DHCP].options.</p>
| 0 |
2016-09-23T18:15:37Z
|
[
"python",
"python-3.x"
] |
Using multiple levels of inheritance with sqlalchemy declarative base
| 39,666,510 |
<p>I have many tables with identical columns. The difference is the table names themselves. I want to set up a inheritance chain to minimize code duplication. The following single layer inheritance works the way I want it to:</p>
<pre><code>from sqlalchemy import Column, Integer, Text
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import sessionmaker
engine = sqlalchemy.create_engine('sqlite:///monDom5.db')
class Base(object):
"""base for all table classes"""
__abstract__ = True
__table_args__ = {'autoload': True, 'autoload_with': engine}
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
Base = declarative_base(cls=Base)
class TransMap_HgmIntronVector(Base):
AlignmentId = Column(Text, primary_key=True)
</code></pre>
<p>But requires me to specify the <code>AlignmentId</code> column for every instance of the <code>Hgm</code> base. I would instead like to do this, but get a <code>sqlalchemy.exc.InvalidRequestError</code> when I try to actually use it:</p>
<pre><code>from sqlalchemy import Column, Integer, Text
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import sessionmaker
engine = sqlalchemy.create_engine('sqlite:///monDom5.db')
class Base(object):
"""base for all table classes"""
__abstract__ = True
__table_args__ = {'autoload': True, 'autoload_with': engine}
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
# model for all Hgm tables
class Hgm(Base):
__abstract__ = True
AlignmentId = Column(Text, primary_key=True)
Base = declarative_base(cls=Hgm)
class TransMap_HgmIntronVector(Hgm):
pass
metadata = Base.metadata
Session = sessionmaker(bind=engine)
session = Session()
</code></pre>
<p>Leads to the error</p>
<pre><code>>>> metadata = Base.metadata
>>> Session = sessionmaker(bind=engine)
>>> session = Session()
>>> session.query(TransMap_HgmIntronVector).all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/cluster/home/ifiddes/anaconda2/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1260, in query
return self._query_cls(entities, self, **kwargs)
File "/cluster/home/ifiddes/anaconda2/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 110, in __init__
self._set_entities(entities)
File "/cluster/home/ifiddes/anaconda2/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 118, in _set_entities
entity_wrapper(self, ent)
File "/cluster/home/ifiddes/anaconda2/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 3829, in __init__
"expected - got '%r'" % (column, )
sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '<class '__main__.TransMap_HgmIntronVector'>'
</code></pre>
| 0 |
2016-09-23T17:33:07Z
| 39,667,190 |
<p>An example is in the <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html#augmenting-the-base" rel="nofollow">docs</a>. In particular, <code>__abstract__ = True</code> is not necessary. This works fine:</p>
<pre><code>class Base(object):
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
class Hgm(Base):
AlignmentId = Column(Text, primary_key=True)
Base = declarative_base(cls=Hgm)
class TransMap_HgmIntronVector(Base):
pass
</code></pre>
<p>Note that it may be simpler to just use a mixin for the identical columns instead.</p>
| 1 |
2016-09-23T18:17:26Z
|
[
"python",
"sqlalchemy"
] |
How to make requests.post not to wrap dict values in arrays in python?
| 39,666,570 |
<p>I use python requests.post function to send json queries to my django app.</p>
<pre><code>r = requests.post(EXTERNAL_SERVER_ADDRESS, data={'123':'456', '456':'789'})
</code></pre>
<p>But on the external server request.POST object looks like this:</p>
<p><code><QueryDict: {'123': ['456'], '456': ['789']}></code></p>
<p>Why does it happen? How can I just send a dict?</p>
| 0 |
2016-09-23T17:38:21Z
| 39,666,715 |
<p>requests is not doing anything here. Presumably your receiving server is Django; that's just how it represents data from a request. <code>request.POST['123']</code> would still give '456'.</p>
| 1 |
2016-09-23T17:47:43Z
|
[
"python",
"json",
"python-requests"
] |
How to make requests.post not to wrap dict values in arrays in python?
| 39,666,570 |
<p>I use python requests.post function to send json queries to my django app.</p>
<pre><code>r = requests.post(EXTERNAL_SERVER_ADDRESS, data={'123':'456', '456':'789'})
</code></pre>
<p>But on the external server request.POST object looks like this:</p>
<p><code><QueryDict: {'123': ['456'], '456': ['789']}></code></p>
<p>Why does it happen? How can I just send a dict?</p>
| 0 |
2016-09-23T17:38:21Z
| 39,666,727 |
<p>You are sending a dict, Django transform this JSON in this QueryDict objetc automatically when it receives the message. If you want to parse it to an dict, do:</p>
<pre><code>myDict = dict(queryDict.iterlists())
</code></pre>
| 1 |
2016-09-23T17:48:30Z
|
[
"python",
"json",
"python-requests"
] |
How to extract x,y data from kdensity plot from matplotlib for python
| 39,666,591 |
<p>I am trying to figure out how to make a 3d figure of uni-variate kdensity plots as they change over time (since they pull from a sliding time window of data over time). </p>
<p>Since I can't figure out how to do that directly, I am first trying to get the x,y plotting data for kdensity plots of matplotlib in python. I hope after I extract them I can use them along with a time variable to make a three dimensional plot. </p>
<p>I see several posts telling how to do this in Matlab. All reference getting <code>Xdata</code> and <code>Ydata</code> from the underlying figure:</p>
<pre><code>x=get(h,'Xdata')
y=get(h,'Ydata')
</code></pre>
<p>How about in python?</p>
| 0 |
2016-09-23T17:39:35Z
| 39,668,247 |
<p>Not sure how kdensity plots work, but note that <code>matplotlib.pyplot.plot</code> returns a list of the added <code>Line2D</code> objects, which are, in fact, where the X and Y data are stored. I suspect they did that to make it work similarly to MATLAB.</p>
<pre><code>import matplotlib.pyplot as plt
h = plt.plot([1,2,3],[2,4,6]) # [<matplotlib.lines.Line2D object at 0x021DA9F0>]
x = h[0].get_xdata() # [1,2,3]
y = h[0].get_ydata() # [2,4,6]
</code></pre>
| 0 |
2016-09-23T19:28:45Z
|
[
"python",
"matplotlib",
"distribution"
] |
How to extract x,y data from kdensity plot from matplotlib for python
| 39,666,591 |
<p>I am trying to figure out how to make a 3d figure of uni-variate kdensity plots as they change over time (since they pull from a sliding time window of data over time). </p>
<p>Since I can't figure out how to do that directly, I am first trying to get the x,y plotting data for kdensity plots of matplotlib in python. I hope after I extract them I can use them along with a time variable to make a three dimensional plot. </p>
<p>I see several posts telling how to do this in Matlab. All reference getting <code>Xdata</code> and <code>Ydata</code> from the underlying figure:</p>
<pre><code>x=get(h,'Xdata')
y=get(h,'Ydata')
</code></pre>
<p>How about in python?</p>
| 0 |
2016-09-23T17:39:35Z
| 39,676,657 |
<p>The answer was already contained in another thread (<a href="http://stackoverflow.com/questions/4150171/how-to-create-a-density-plot-in-matplotlib">How to create a density plot in matplotlib?</a>). It is pretty easy to get a set of kdensity x's and y's from a set of data. </p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 # data is a set of univariate data
xs = np.linspace(0,max(data),200) # This 200 sets the # of x (and so also y) points of the kdensity plot
density = gaussian_kde(data)
density.covariance_factor = lambda : .25
density._compute_covariance()
ys = density(xs)
plt.plot(xs,ys)
</code></pre>
<p>And there you have it. Both the kdensity plot and it's underlying x,y data.</p>
| 0 |
2016-09-24T13:06:44Z
|
[
"python",
"matplotlib",
"distribution"
] |
re.compile only takes two arguments, is there a way to make it take more? Or another way around that?
| 39,666,617 |
<p>I am able to access an email in txt file form on my computer, and now my goal is to scrape specific data out of it. I have utilized <code>re.compile</code> and <code>enumerate</code> to parse through the email looking for matching words (in my case, fish species such as GOM Cod), and then printing them. But there are 100's more emails I will need to parse thru, each with several different fish species listed in them....so my question is: what is the best way to go about this? I can't put all 17 different possible fish species into one <code>re.compile</code> function so should I just have 17 different blocks of the same code with just the fish species changed in each? Is that the most efficient way? My code is below. </p>
<pre><code>import os
import email
import re
path = 'Z:\\folderwithemail'
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
if os.path.isfile(file_path):
with open(file_path, 'r') as f:
sector_result = []
pattern = re.compile("GOM Cod", re.IGNORECASE)
for linenum, line in enumerate(f):
if pattern.search(line) != None:
sector_result.append((linenum, line.rstrip('\n')))
for linenum, line in sector_result:
print ("Fish Species:", line)
</code></pre>
| 0 |
2016-09-23T17:41:24Z
| 39,666,675 |
<p>You can <em>alternate</em> between fish species using the vertical bar <code>|</code>:</p>
<blockquote>
<p><code>A|B</code>, where A and B can be arbitrary REs, creates a regular expression
that will match either A or B</p>
</blockquote>
<pre><code>pattern = re.compile(r"GOM Cod|Salmon|Tuna", re.IGNORECASE)
</code></pre>
| 1 |
2016-09-23T17:45:33Z
|
[
"python",
"screen-scraping",
"enumerate"
] |
Difference between numpy.float and numpy.float64
| 39,666,638 |
<p>There seems to be a subtle difference between numpy.float and numpy.float64.</p>
<pre><code>>>> import numpy as np
>>> isinstance(2.0, np.float)
True
>>> isinstance(2.0, np.float64)
False
</code></pre>
<p>Can someone clarify this? Thanks</p>
| 1 |
2016-09-23T17:42:43Z
| 39,666,701 |
<p>This would seem to be the difference between a 32-bit floating point number and a 64-bit floating point number (in C, a float vs. a double), and 2.0 ends up being a 32-bit floating point number.</p>
| -1 |
2016-09-23T17:46:55Z
|
[
"python",
"numpy",
"types"
] |
Difference between numpy.float and numpy.float64
| 39,666,638 |
<p>There seems to be a subtle difference between numpy.float and numpy.float64.</p>
<pre><code>>>> import numpy as np
>>> isinstance(2.0, np.float)
True
>>> isinstance(2.0, np.float64)
False
</code></pre>
<p>Can someone clarify this? Thanks</p>
| 1 |
2016-09-23T17:42:43Z
| 39,667,343 |
<p><code>np.float</code> is an alias for python <code>float</code> type.
<code>np.float32</code> and <code>np.float64</code> are numpy specific 32 and 64-bit float types.</p>
<pre><code>float?
Init signature: float(self, /, *args, **kwargs)
Docstring:
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
Type: type
np.float?
Init signature: np.float(self, /, *args, **kwargs)
Docstring:
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
Type: type
np.float32?
Init signature: np.float32(self, /, *args, **kwargs)
Docstring: 32-bit floating-point number. Character code 'f'. C float compatible.
File: c:\python\lib\site-packages\numpy\__init__.py
Type: type
np.float64?
Init signature: np.float64(self, /, *args, **kwargs)
Docstring: 64-bit floating-point number. Character code 'd'. Python float compatible.
File: c:\python\lib\site-packages\numpy\__init__.py
Type: type
</code></pre>
<p>Thus, when you do <code>isinstance(2.0, np.float)</code>, it is equivalent to <code>isinstance(2.0, float)</code> as 2.0 is a plain python built-in float type... and not the numpy type.</p>
<p><code>isinstance(np.float64(2.0), np.float64)</code> would obviously be <code>True</code>.</p>
| 4 |
2016-09-23T18:27:04Z
|
[
"python",
"numpy",
"types"
] |
Buildozer, How to add external python packages?
| 39,666,644 |
<p>I have built a kivy app using Python 2.7. I have used the import statements</p>
<pre><code>from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.properties import *
from kivy.uix.textinput import TextInput
from kivy.uix.image import Image
from kivy.uix.image import AsyncImage
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy import Config
import sqlite3
import webbrowser
from kivy.lang import Builder
import re
from bs4 import BeautifulSoup
import unicodedata
from threading import Thread
import requests`
</code></pre>
<p>In my Buildozer.spec file</p>
<pre><code>requirements = kivy,requests,bs4
</code></pre>
<p>I have set the requirements to use these, as the rest of the packages are inbuilt in Python. I did not specify them. The APK Gets built and I run it on my android phone and the app crashes without any error. I dont understand where the problem lies. If it is my buildozer spec requirements or improper usage of packages.</p>
<p>I have been searching all over the internet , and I have read the Buildozer docs, But I haven't been able to find a good tutorial on how to use Buildozer . I am using it on Linux. Can someone explain what is going wrong?</p>
| 0 |
2016-09-23T17:43:09Z
| 39,965,942 |
<p>I have been having the same problem. I've narrowed it down to the bs4 library, at the moment i havent got to the bottom of it but i think it is something to do with mixing python 2.7 ans python 3. Anyway the first link is to my (so far) unsolved question.</p>
<p><a href="http://stackoverflow.com/questions/39880264/kivy-app-build-with-buildozer-apk-crash">Kivy App build with Buildozer. APK crash</a></p>
<p>The following link is to a set of instructions that may help you find your problem.</p>
<p><strong>adb install instructions:-</strong></p>
<p><a href="http://lifehacker.com/the-easiest-way-to-install-androids-adb-and-fastboot-to-1586992378" rel="nofollow">http://lifehacker.com/the-easiest-way-to-install-androids-adb-and-fastboot-to-1586992378</a></p>
<p><strong>adb logcat fault finding:-</strong></p>
<p><a href="http://stackoverflow.com/questions/10005509/adb-logcat-hangs-with-waiting-for-device-message">adb logcat hangs with "waiting for device" message</a></p>
<p>Hope this helps.</p>
| 0 |
2016-10-10T20:05:31Z
|
[
"java",
"android",
"python",
"python-2.7",
"import"
] |
Python: Animating a vector using mplot3d and animation
| 39,666,721 |
<p>I'm trying to make a 3d plot with Matplotlib and the animation package from matplotlib. In addition, the animation should be a part of a Gui generated using PyQt and Qt-Designer. Currently I'm stuck on using the "animation.Funcnimation()" correctly, at least i think so...
So here is my code:</p>
<pre><code>import sys
from PyQt4.uic import loadUiType
from PyQt4 import QtGui
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib import animation
import numpy as np
import Quaternion as qt
Ui_MainWindow, QMainWindow = loadUiType('Newsphere.ui')
class Kinematic(Ui_MainWindow, QMainWindow):
def __init__(self):
super(Kinematic, self).__init__()
self.setupUi(self)
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111,projection = '3d')
self.fig.tight_layout()
self.ani = animation.FuncAnimation(self.fig, self.update,
init_func=self.setup_plot, blit=True)
self.canvas = FigureCanvas(self.fig)
self.mplvl.addWidget(self.canvas)
self.canvas.draw()
def setup_plot(self):
self.ax.view_init(40, 45)
self.ax.set_xlabel('X')
self.ax.set_ylabel('Y')
self.ax.set_zlabel('Z')
self.ax.set_xlim3d(-1,1)
self.ax.set_ylim3d(-1,1)
self.ax.set_zlim3d(-1,1)
g_x = np.matrix([[1.0],[0.0],[0.0]])
g_y = np.matrix([[0.0],[1.0],[0.0]])
g_z = np.matrix([[0.0],[0.0],[1.0]])
self.ax.plot([0,g_x[0]], [0,g_x[1]], [0,g_x[2]], label='$X_0$')
self.ax.plot([0,g_y[0]], [0,g_y[1]], [0,g_y[2]], label='$Y_0$')
self.ax.plot([0,g_z[0]], [0,g_z[1]], [0,g_z[2]], label='$Z_0$')
self.vek, = self.ax.plot([0,-1], [0,0], [0,0], label='$g \cdot R$', animated=True)
self.ax.legend(loc='best')
self.ax.scatter(0,0,0, color='k')
return self.vek,
def update(self, i):
b = self.bslider.value() / 100
g = np.matrix([[1.0],[0.0],[0.0]])
q = np.array([0,b,0.5,0])
R = qt.QtoR(q)
x, y, z = R*g
self.vek, = self.ax.plot([0,x], [0,y], [0,z], label='$g \cdot R$', animated=True) #the rotated vector
return self.vek,
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Kinematic()
main.show()
sys.exit(app.exec_())
</code></pre>
<p>You won't be able to run it by just copy-paste because you don't have the file "Newsphere.ui" (Line 13) and the Quaternion.py (Line 11). So when I run it, I get the following (actually like I wish!):
<a href="http://i.stack.imgur.com/yavp5.png" rel="nofollow">Coordinate system</a> </p>
<p>My goal is now to draw a vector (Line 50) and animate it (Line 66) using data which I get from the Gui-slider (Line 58). Can anyone help me with this? I'm stuck with this for days!</p>
| 0 |
2016-09-23T17:48:05Z
| 39,679,617 |
<p>Since your problem is with the animation part, below you can see a snippet that animate an arrow that is rotating.</p>
<pre><code>import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def data_gen(num):
"""Data generation"""
angle = num * np.pi/36
vx, vy, vz = np.cos(angle), np.sin(angle), 1
ax.cla()
ax.quiver(0, 0, 0, vx, vy, vz, pivot="tail", color="black")
ax.quiver(0, 0, 0, vx, vy, 0, pivot="tail", color="black",
linestyle="dashed")
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_zlim(-1, 1)
ax.view_init(elev=30, azim=60)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
data_gen(0)
ani = animation.FuncAnimation(fig, data_gen, range(72), blit=False)
plt.show()
</code></pre>
<p>The documentation on animations might not be the best. But there are several examples out there, for example, this one animates the <a href="https://jakevdp.github.io/blog/2013/02/16/animating-the-lorentz-system-in-3d/" rel="nofollow">Lorenz attractor</a>.</p>
| 1 |
2016-09-24T18:24:22Z
|
[
"python",
"qt",
"animation",
"matplotlib"
] |
Python: Animating a vector using mplot3d and animation
| 39,666,721 |
<p>I'm trying to make a 3d plot with Matplotlib and the animation package from matplotlib. In addition, the animation should be a part of a Gui generated using PyQt and Qt-Designer. Currently I'm stuck on using the "animation.Funcnimation()" correctly, at least i think so...
So here is my code:</p>
<pre><code>import sys
from PyQt4.uic import loadUiType
from PyQt4 import QtGui
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib import animation
import numpy as np
import Quaternion as qt
Ui_MainWindow, QMainWindow = loadUiType('Newsphere.ui')
class Kinematic(Ui_MainWindow, QMainWindow):
def __init__(self):
super(Kinematic, self).__init__()
self.setupUi(self)
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111,projection = '3d')
self.fig.tight_layout()
self.ani = animation.FuncAnimation(self.fig, self.update,
init_func=self.setup_plot, blit=True)
self.canvas = FigureCanvas(self.fig)
self.mplvl.addWidget(self.canvas)
self.canvas.draw()
def setup_plot(self):
self.ax.view_init(40, 45)
self.ax.set_xlabel('X')
self.ax.set_ylabel('Y')
self.ax.set_zlabel('Z')
self.ax.set_xlim3d(-1,1)
self.ax.set_ylim3d(-1,1)
self.ax.set_zlim3d(-1,1)
g_x = np.matrix([[1.0],[0.0],[0.0]])
g_y = np.matrix([[0.0],[1.0],[0.0]])
g_z = np.matrix([[0.0],[0.0],[1.0]])
self.ax.plot([0,g_x[0]], [0,g_x[1]], [0,g_x[2]], label='$X_0$')
self.ax.plot([0,g_y[0]], [0,g_y[1]], [0,g_y[2]], label='$Y_0$')
self.ax.plot([0,g_z[0]], [0,g_z[1]], [0,g_z[2]], label='$Z_0$')
self.vek, = self.ax.plot([0,-1], [0,0], [0,0], label='$g \cdot R$', animated=True)
self.ax.legend(loc='best')
self.ax.scatter(0,0,0, color='k')
return self.vek,
def update(self, i):
b = self.bslider.value() / 100
g = np.matrix([[1.0],[0.0],[0.0]])
q = np.array([0,b,0.5,0])
R = qt.QtoR(q)
x, y, z = R*g
self.vek, = self.ax.plot([0,x], [0,y], [0,z], label='$g \cdot R$', animated=True) #the rotated vector
return self.vek,
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Kinematic()
main.show()
sys.exit(app.exec_())
</code></pre>
<p>You won't be able to run it by just copy-paste because you don't have the file "Newsphere.ui" (Line 13) and the Quaternion.py (Line 11). So when I run it, I get the following (actually like I wish!):
<a href="http://i.stack.imgur.com/yavp5.png" rel="nofollow">Coordinate system</a> </p>
<p>My goal is now to draw a vector (Line 50) and animate it (Line 66) using data which I get from the Gui-slider (Line 58). Can anyone help me with this? I'm stuck with this for days!</p>
| 0 |
2016-09-23T17:48:05Z
| 39,795,232 |
<p>So if someone is interested in a solution of the mentioned problem, here we go: (again it is not a code for copy-paste because of the missing 'Newsphere.ui', but I try to explain the important snippets)</p>
<pre><code>import sys
from PyQt4.uic import loadUiType
from PyQt4 import QtGui
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib import animation
import numpy as np
Ui_MainWindow, QMainWindow = loadUiType('Newsphere.ui')
class Kinematic(Ui_MainWindow, QMainWindow):
def __init__(self):
super(Kinematic, self).__init__()
self.setupUi(self)
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111,projection = '3d')
self.fig.tight_layout()
self.ax.view_init(40, -45)
# dashed coordinate system
self.ax.plot([0,1], [0,0], [0,0], label='$X_0$', linestyle="dashed")
self.ax.plot([0,0], [0,-1], [0,0], label='$Y_0$', linestyle="dashed")
self.ax.plot([0,0], [0,0], [0,1], label='$Z_0$', linestyle="dashed")
self.ax.set_xlim3d(-1,1)
self.ax.set_ylim3d(-1,1)
self.ax.set_zlim3d(-1,1)
self.ax.set_xlabel('X')
self.ax.set_ylabel('Y')
self.ax.set_zlabel('Z')
self.ax.scatter(0,0,0, color='k') # black origin dot
self.canvas = FigureCanvas(self.fig)
self.mplvl.addWidget(self.canvas)
self.ani = animation.FuncAnimation(self.fig, self.data_gen, init_func=self.setup_plot, blit=True)
def setup_plot(self):
self.ax.legend(loc='best')
self.vek = self.ax.quiver(0, 0, 0, 0, 0, 0, label='$g \cdot R$', pivot="tail", color="black")
return self.vek,
def data_gen(self, i):
b = self.bslider.value() / 100
vx, vy, vz = np.cos(b), np.sin(b), 0
self.vek = self.ax.quiver(0, 0, 0, vx, vy, vz, label='$g \cdot R$', pivot="tail", color="black")
self.canvas.draw()
return self.vek,
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Kinematic()
main.show()
sys.exit(app.exec_())
</code></pre>
<p>By running the code I get </p>
<p><a href="http://i.stack.imgur.com/kGb5J.png" rel="nofollow"><img src="http://i.stack.imgur.com/kGb5J.png" alt="enter image description here"></a></p>
<p>(These are two pictures combined in one showing the same process) </p>
<p>I generated a GUI file named <code>Newsphere.ui</code> following <a href="http://blog.rcnelson.com/building-a-matplotlib-gui-with-qt-designer-part-1/" rel="nofollow">this tutorial</a>. Basically it contains just a Widget, a QSlider and a QSpinBox. The Widget has the layout-name "mplvl", which occures in line 41. This adds the generated figure to the widget (I think so...). The QSlider is connected with the QSpinBox (done in QtDesigner) and has the name "bslider", line 55. So in this line the slider-value gets divided by 100 because I didn't found a slider that generates me a float-value. The key-line for me was line 61, where the canvas is drawn. Now the <code>animation.FuncAnimation</code> (line 43) draws a new vector when I change the slider value, compare the pics. Also it is important to draw the changing vector as a <code>ax.quiver</code> and not as a <code>ax.plot</code> like in my previous attempt.</p>
<p>If there are questions or suggestions for improvement please ask/post.</p>
| 0 |
2016-09-30T15:40:17Z
|
[
"python",
"qt",
"animation",
"matplotlib"
] |
invalid literal for int() with base 10: '' for map(int, str(num))
| 39,666,826 |
<p>I am running a recursive function that takes in a positive integer and a list (that is updated as it runs through the function):</p>
<pre><code>def happy_number(num, tracking_list = []):
if (num == 1):
print 1
else:
digit_list = map(int, str(num))
digit_sum = 0
for n in digit_list:
digit_sum = (n ** 2) + digit_sum
if digit_sum in tracking_list:
print 0
else:
tracking_list.append(digit_sum)
happy_number(digit_sum, tracking_list)
</code></pre>
<p>When running this, it complains about:</p>
<pre><code>digit_list = map(int, str(num))
</code></pre>
<p>it gives the error:</p>
<pre><code>ValueError: invalid literal for int() with base 10: ''
</code></pre>
<p>What is happening here? </p>
| 0 |
2016-09-23T17:55:21Z
| 39,667,150 |
<p>It sounds like you are parsing your numbers from a file, and when a space <code>' '</code> or a newline <code>'\n'</code> shows up (or anything that is not a string digit for that matter), your script will fail. You can try:</p>
<pre><code>def happy_number(num, tracking_list = []):
if (num == 1):
print 1
else:
digit_list = map(int, str(num if num.isdigit() else ''))
digit_sum = 0
for n in digit_list:
digit_sum = (n ** 2) + digit_sum
if digit_sum in tracking_list:
print 0
else:
tracking_list.append(digit_sum)
happy_number(digit_sum, tracking_list)
</code></pre>
<p>The line:</p>
<pre><code>digit_list = map(int, str(num if num.isdigit() else ''))
</code></pre>
<p>Will do the same thing as what you had before, except will be an empty list <code>[]</code> if you pass <code>num</code> is not a string digit. Replace the <code>''</code> at the end with another default to if you wish. </p>
| 0 |
2016-09-23T18:14:29Z
|
[
"python"
] |
How does "tf.train.replica_device_setter" work?
| 39,666,845 |
<p>I understood that <code>tf.train.replica_device_setter</code> can be used for automatically assigning the variables always on the same parameter server (PS) (using round-robin) and the compute intensive nodes on one worker.</p>
<p>How do the same variables get reused across multiple graph replicas, build up by different workers? Does the parameter server only look at the name of the variable that a worker asks for? </p>
<p>Does this mean that tasks should not be used parallel for the execution of two different graphs if in both graphs the variables are named the same?</p>
| 0 |
2016-09-23T17:56:29Z
| 39,681,502 |
<p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#replica_device_setter" rel="nofollow"><code>tf.train.replica_device_setter()</code></a> is quite simple in its behavior: it makes a purely local decision to assign a device to each <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#Variable" rel="nofollow"><code>tf.Variable</code></a> as it is created—in a round-robin fashion across the parameter server tasks.</p>
<p>In the distributed version of TensorFlow, each <em>device</em> (e.g. <code>"/job:ps/task:17/cpu:0"</code>) maintains a map from variable names to variables that is shared between all sessions that use this device. This means that when different worker replicas create a session using that device, if they assign the same symbolic variable (having the same <code>Variable.name</code> property) to the same device, they will see each other's updates.</p>
<p>When you do <a href="https://www.tensorflow.org/versions/r0.10/how_tos/distributed/index.html#replicated-training" rel="nofollow">"between-graph replication"</a> across multiple replicas, the <code>tf.train.replica_device_setter()</code> provides a simple, deterministic way to assign variables to devices. If you build an identical graph on each worker replica, each variable will be assigned to the same device and successfully shared, without any external coordination.</p>
<p><strong>Caveat:</strong> With this scheme, your worker replicas must create an identical graph*, and there must be no randomness in how the graph is constructed. I once saw an issue where the order of creating variables was determined by iterating over the keys of a Python <code>dict</code>, which is <a href="http://stackoverflow.com/questions/4458169/in-what-order-does-python-display-dictionary-keys">not guaranteed to happen in the same order</a> across processes. This led to variables being assigned to different PS devices by different workers....</p>
<p>As to your other question, you do need to be careful about variable name clashes when training multiple models using the same processes. By default all variables are shared in a global namespace, so two variables from different networks with the same name will clash. One way to mitigate this problem is to wrap each model in a <a href="https://www.tensorflow.org/versions/master/api_docs/python/framework.html#container" rel="nofollow"><code>with tf.container(name):</code></a> block (with different values for <code>name</code>, e.g. <code>"model_1"</code> and <code>"model_2"</code>)
to put your variables in a different namespace, which is called a "container" in the TensorFlow jargon. You can think of a container as a prefix that is added to the name of all of your variables when they are looked up on the device. The support for containers in the API is still quite preliminary, but there are plans to make them more useful in future.</p>
<hr>
<p> * Technically, they only need to create their <code>tf.Variable</code> objects in the same sequence.</p>
| 1 |
2016-09-24T22:26:09Z
|
[
"python",
"tensorflow"
] |
Extracting a row from a table from a url
| 39,666,890 |
<p>I want to download EPS value for all years (Under Annual Trends) from the below link.
<a href="http://www.bseindia.com/stock-share-price/stockreach_financials.aspx?scripcode=500180&expandable=0" rel="nofollow">http://www.bseindia.com/stock-share-price/stockreach_financials.aspx?scripcode=500180&expandable=0</a></p>
<p>I tried using Beautiful Soup as mentioned in the below answer.
<a href="http://stackoverflow.com/questions/17196018/extracting-table-contents-from-html-with-python-and-beautifulsoup">Extracting table contents from html with python and BeautifulSoup</a>
But couldn't proceed after the below code. I feel I am very close to my answer. Any help will be greatly appreciated.</p>
<pre><code>from bs4 import BeautifulSoup
import urllib2
html = urllib2.urlopen("http://www.bseindia.com/stock-share-price/stockreach_financials.aspx?scripcode=500180&expandable=0").read()
soup=BeautifulSoup(html)
table = soup.find('table',{'id' :'acr'})
#the below code wasn't working as I expected it to be
tr = table.find('tr', text='EPS')
</code></pre>
<p>I am open to using any other language to get this done</p>
| 2 |
2016-09-23T17:58:57Z
| 39,667,197 |
<p>The text is in the <em>td</em> not the <em>tr</em> so get the <em>td</em> using the text and then call <em>.parent</em> to get the <em>tr</em>:</p>
<pre><code>In [12]: table = soup.find('table',{'id' :'acr'})
In [13]: tr = table.find('td', text='EPS').parent
In [14]: print(tr)
<tr><td class="TTRow_left" style="padding-left: 30px;">EPS</td><td class="TTRow_right">48.80</td>
<td class="TTRow_right">42.10</td>
<td class="TTRow_right">35.50</td>
<td class="TTRow_right">28.50</td>
<td class="TTRow_right">22.10</td>
</tr>
In [15]: [td.text for td in tr.select("td + td")]
Out[15]: [u'48.80', u'42.10', u'35.50', u'28.50', u'22.10']
</code></pre>
<p>Which you will see exactly matches what is on the page.</p>
<p>Another approach would be to call <em>find_next_siblings</em>:</p>
<pre><code>In [17]: tds = table.find('td', text='EPS').find_next_siblings("td")
In [18]: tds
Out[19]:
[<td class="TTRow_right">48.80</td>,
<td class="TTRow_right">42.10</td>,
<td class="TTRow_right">35.50</td>,
<td class="TTRow_right">28.50</td>,
<td class="TTRow_right">22.10</td>]
In [20]: [td.text for td in tds]
Out[20]: [u'48.80', u'42.10', u'35.50', u'28.50', u'22.10']
</code></pre>
| 2 |
2016-09-23T18:17:56Z
|
[
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Creating a Quote form in Django
| 39,667,031 |
<p>i am creating a django powered website. Specifically, a courier website. I need to create an application that serves as a quoting app. The user will type in the dimensions of the package into a form and after submitting the form, a price/quote will be returned , based on the dimensions inputted.</p>
<p>I have done this so far
(views.py)</p>
<pre><code>from django.shortcuts import render, redirect
from quote.forms import QuoteForm
def quoting(request):
if request.method == 'GET':
form = QuoteForm()
else:
form = QuoteForm(request.POST)
if form.is_valid():
Length = form.cleaned_data['Length']
Breadth = form.cleaned_data['Breadth']
Height = form.cleaned_data['Height']
return redirect('thanks')
return render(request, "quote/quote.html", {'form': form})
</code></pre>
<p>(forms.py)</p>
<pre><code>from django import forms
class QuoteForm(forms.Form):
Length = forms.Integer()
Breadth = forms.Integer()
Height= forms.Integer()
</code></pre>
<p>(quote.html)</p>
<pre><code>{% extends "shop/base.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
{% endblock %}
</code></pre>
<p>Then i am aware i am lacking an html that would display the answer. I am not sure how to do this.</p>
<p>The price is determined by:</p>
<p>price= Shipping weight X distance
shipping weight= (length X breadth X height) / 5000</p>
<p>Thanks in advance :)</p>
| 0 |
2016-09-23T18:06:56Z
| 39,668,357 |
<p>You have redirected to a 'thanks' page after the input is received. You should not have to return anything at this point.</p>
<p>After you have the input of length, breadth and height. You can calculate the price by doing: (Length * Breadth * Height )/ 5000.</p>
<p>This can be stored into a variable 'total_price'. Then, add 'total_price' to your context when rendering. </p>
<p>Finally, in the HTML, you can add a Django template tag like </p>
<pre><code>{% if total_price %}
{{ total_price }}
{{ else }}
{{ form }}
</code></pre>
<p>Hope this helps!</p>
| 0 |
2016-09-23T19:36:59Z
|
[
"python",
"html",
"django",
"rest"
] |
Creating a Quote form in Django
| 39,667,031 |
<p>i am creating a django powered website. Specifically, a courier website. I need to create an application that serves as a quoting app. The user will type in the dimensions of the package into a form and after submitting the form, a price/quote will be returned , based on the dimensions inputted.</p>
<p>I have done this so far
(views.py)</p>
<pre><code>from django.shortcuts import render, redirect
from quote.forms import QuoteForm
def quoting(request):
if request.method == 'GET':
form = QuoteForm()
else:
form = QuoteForm(request.POST)
if form.is_valid():
Length = form.cleaned_data['Length']
Breadth = form.cleaned_data['Breadth']
Height = form.cleaned_data['Height']
return redirect('thanks')
return render(request, "quote/quote.html", {'form': form})
</code></pre>
<p>(forms.py)</p>
<pre><code>from django import forms
class QuoteForm(forms.Form):
Length = forms.Integer()
Breadth = forms.Integer()
Height= forms.Integer()
</code></pre>
<p>(quote.html)</p>
<pre><code>{% extends "shop/base.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
{% endblock %}
</code></pre>
<p>Then i am aware i am lacking an html that would display the answer. I am not sure how to do this.</p>
<p>The price is determined by:</p>
<p>price= Shipping weight X distance
shipping weight= (length X breadth X height) / 5000</p>
<p>Thanks in advance :)</p>
| 0 |
2016-09-23T18:06:56Z
| 39,674,292 |
<p>When i submit the form it returns to just the form with my inputs</p>
<p>(views.py)</p>
<pre><code>from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from quote.forms import QuoteForm
def quoting(request):
if request.method == 'GET':
form = QuoteForm()
else:
form = QuoteForm(request.POST)
if form.is_valid():
Length = form.cleaned_data['Length']
Breadth = form.cleaned_data['Breadth']
Height = form.cleaned_data['Height']
totalprice=((Length*Breadth*Height)/5000)
return render(request, "quote/quote.html", {'form': form})
def answer(request):
return render(request,"quote/out.html")
</code></pre>
<p>(quote.html)</p>
<pre><code>{% extends "shop/base.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit" action='/quote/out.html/'>Send</button>
</div>
</form>
{% endblock %}
</code></pre>
<p>(out.html)</p>
<pre><code> {% extends "shop/base.html" %}
{% block content %}
{% if totalprice %}
{{ totalprice }}
{{ else }}
{{form}}
{% endblock %}
</code></pre>
<p>(forms.py)</p>
<pre><code>from django import forms
class ContactForm(forms.Form):
Length = forms.IntegerField(required=True)
Breadth = forms.IntegerField(required=True)
Height = forms.IntegerField()
</code></pre>
<p>(urls.py ( the app))</p>
<pre><code>from django.conf.urls import patterns, url
from django.views.generic import TemplateView
url(r'^quoting/$',
'quote.views.quoting',
name='quoting'
),
url(r'^answer/$',
'quote.views.answer',
name='answer'
)
</code></pre>
| 0 |
2016-09-24T08:34:56Z
|
[
"python",
"html",
"django",
"rest"
] |
Accessing data from a JSON file
| 39,667,039 |
<p>I am quite new with JSON. My code consists in extracting data from a website wich requires a API key. Having extracted the information. I am trying to reach the information which is encoded in son through this format (here is a sample):</p>
<pre><code>[{"number":31705,"name":"31705 - CHAMPEAUX (BAGNOLET)","address":"RUE DES CHAMPEAUX (PRES DE LA GARE ROUTIERE) - 93170 BAGNOLET","latitude":48.8645278209514,"longitude":2.416170724425901},{"number":10042,"name":"10042 - POISSONNIÃRE - ENGHIEN","address":"52 RUE D'ENGHIEN / ANGLE RUE DU FAUBOURG POISSONIERE - 75010 PARIS","latitude":48.87242006305313,"longitude":2.348395236282807}]
</code></pre>
<p>How do i access the different data in the json code ? This is the code i have come up with:</p>
<pre><code>import requests
reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{station_number}?contract={contract_name}&api_key HTTP/1.1')
</code></pre>
<p>I Believe that my request has formulated a response which lies in the "response" "folder" that has been sent by the website to my computer:</p>
<pre><code>print(reponse.headers)
print(reponse(2,/'latitude')
</code></pre>
<p>I am trying to access the information of lattitude in every element of the json code - the 2 represents the second element of the list and lattitude the name of the value i am trying to access within the element of the json list. But i can't manage to do it. The error I get is a syntax error. </p>
<p>How do I fix it? I would like to access to all the value of each string of each member of the object 'response'.</p>
<p>UPDATE n°1:</p>
<p>My new code is:</p>
<pre><code>import json
import requests
reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{31705}?contract={Paris}&apiKey={0617697a9795f803697de4b9abf9759d5406b3a0} HTTP/1.1')
data = json.loads(response.content)
print(data)
</code></pre>
<p>However i get the error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/someone/Desktop/TIPE 2016:17/Programme TIPE 2016:2017.py", line 27, in <module>
data = json.loads(response.content)
File "/Users/someone/miniconda3/lib/python3.5/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
</code></pre>
<p>UPDATE n°2:</p>
<p>my new code is : </p>
<pre><code>import json
import requests
reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{31705}?contract={Paris}&apiKey={0617697a9795f803697de4b9abf9759d5406b3a0} HTTP/1.1')
data = response.json()
latitude = data[2]['latitude']
</code></pre>
<p>However i get the error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/someone/Desktop/TIPE 2016:17/Programme TIPE 2016:2017.py", line 30, in <module>
latitude = data[2]['latitude']
KeyError: 2
</code></pre>
<p>Does it mean that response is empty ?</p>
<p>UPDATE n°3:</p>
<pre><code>reponse.content
</code></pre>
<p>the answer is the following:</p>
<pre><code>b'{ "error" : "Unauthorized" }'
</code></pre>
<p>What is the problem ?</p>
<p>UPDATE n°4:</p>
<p>my new code is :</p>
<pre><code>reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{31705}?contract={Paris}&apiKey={0617697a9795f803697de4b9abf9759d5406b3a0} HTTP/1.1')
data = json.loads(response.content.decode('utf-8'))
print(reponse.headers)
print(reponse.content)
</code></pre>
<p>the result is :</p>
<pre><code>{'Content-Length': '48', 'Content-Encoding': 'gzip', 'Server': 'Apache-Coyote/1.1', 'Date': 'Fri, 23 Sep 2016 19:39:25 GMT', 'Connection': 'close', 'Content-Type': 'application/json'}
b'{ "error" : "Unauthorized" }'
</code></pre>
<p>so the answer to my request is not empty but i do not have the authorization to access it. How can I solve this ?</p>
<p>FINAL UPDATE:</p>
<p>The new and working code is :</p>
<pre><code>import json
import requests
r = requests.get('https://api.jcdecaux.com/vls/v1/stations/31705?contract=Paris&apiKey=0617697a9795f803697de4b9abf9759d5406b3a0')
response_json = r.json()
print (response_json['name'])
</code></pre>
<p>and the result is:</p>
<pre><code>31705 - CHAMPEAUX (BAGNOLET)
</code></pre>
| -1 |
2016-09-23T18:07:23Z
| 39,667,093 |
<p>you could convert your <code>json</code> data to dict and then access it like dictionary.
I believe it should be something like</p>
<p><code>data = json.loads(response.content.decode('utf-8'))</code></p>
| 1 |
2016-09-23T18:10:15Z
|
[
"python",
"json",
"extract"
] |
Accessing data from a JSON file
| 39,667,039 |
<p>I am quite new with JSON. My code consists in extracting data from a website wich requires a API key. Having extracted the information. I am trying to reach the information which is encoded in son through this format (here is a sample):</p>
<pre><code>[{"number":31705,"name":"31705 - CHAMPEAUX (BAGNOLET)","address":"RUE DES CHAMPEAUX (PRES DE LA GARE ROUTIERE) - 93170 BAGNOLET","latitude":48.8645278209514,"longitude":2.416170724425901},{"number":10042,"name":"10042 - POISSONNIÃRE - ENGHIEN","address":"52 RUE D'ENGHIEN / ANGLE RUE DU FAUBOURG POISSONIERE - 75010 PARIS","latitude":48.87242006305313,"longitude":2.348395236282807}]
</code></pre>
<p>How do i access the different data in the json code ? This is the code i have come up with:</p>
<pre><code>import requests
reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{station_number}?contract={contract_name}&api_key HTTP/1.1')
</code></pre>
<p>I Believe that my request has formulated a response which lies in the "response" "folder" that has been sent by the website to my computer:</p>
<pre><code>print(reponse.headers)
print(reponse(2,/'latitude')
</code></pre>
<p>I am trying to access the information of lattitude in every element of the json code - the 2 represents the second element of the list and lattitude the name of the value i am trying to access within the element of the json list. But i can't manage to do it. The error I get is a syntax error. </p>
<p>How do I fix it? I would like to access to all the value of each string of each member of the object 'response'.</p>
<p>UPDATE n°1:</p>
<p>My new code is:</p>
<pre><code>import json
import requests
reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{31705}?contract={Paris}&apiKey={0617697a9795f803697de4b9abf9759d5406b3a0} HTTP/1.1')
data = json.loads(response.content)
print(data)
</code></pre>
<p>However i get the error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/someone/Desktop/TIPE 2016:17/Programme TIPE 2016:2017.py", line 27, in <module>
data = json.loads(response.content)
File "/Users/someone/miniconda3/lib/python3.5/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
</code></pre>
<p>UPDATE n°2:</p>
<p>my new code is : </p>
<pre><code>import json
import requests
reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{31705}?contract={Paris}&apiKey={0617697a9795f803697de4b9abf9759d5406b3a0} HTTP/1.1')
data = response.json()
latitude = data[2]['latitude']
</code></pre>
<p>However i get the error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/someone/Desktop/TIPE 2016:17/Programme TIPE 2016:2017.py", line 30, in <module>
latitude = data[2]['latitude']
KeyError: 2
</code></pre>
<p>Does it mean that response is empty ?</p>
<p>UPDATE n°3:</p>
<pre><code>reponse.content
</code></pre>
<p>the answer is the following:</p>
<pre><code>b'{ "error" : "Unauthorized" }'
</code></pre>
<p>What is the problem ?</p>
<p>UPDATE n°4:</p>
<p>my new code is :</p>
<pre><code>reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{31705}?contract={Paris}&apiKey={0617697a9795f803697de4b9abf9759d5406b3a0} HTTP/1.1')
data = json.loads(response.content.decode('utf-8'))
print(reponse.headers)
print(reponse.content)
</code></pre>
<p>the result is :</p>
<pre><code>{'Content-Length': '48', 'Content-Encoding': 'gzip', 'Server': 'Apache-Coyote/1.1', 'Date': 'Fri, 23 Sep 2016 19:39:25 GMT', 'Connection': 'close', 'Content-Type': 'application/json'}
b'{ "error" : "Unauthorized" }'
</code></pre>
<p>so the answer to my request is not empty but i do not have the authorization to access it. How can I solve this ?</p>
<p>FINAL UPDATE:</p>
<p>The new and working code is :</p>
<pre><code>import json
import requests
r = requests.get('https://api.jcdecaux.com/vls/v1/stations/31705?contract=Paris&apiKey=0617697a9795f803697de4b9abf9759d5406b3a0')
response_json = r.json()
print (response_json['name'])
</code></pre>
<p>and the result is:</p>
<pre><code>31705 - CHAMPEAUX (BAGNOLET)
</code></pre>
| -1 |
2016-09-23T18:07:23Z
| 39,667,397 |
<p>Requests has a builtin JSON decoder, so there's no need to use the json library:</p>
<pre><code>import requests
response = requests.get(url)
data = response.json()
</code></pre>
<p>Based on the details in your question, "data" <em>might</em> be a list of dicts that contain latitude. So to extract the first one might be:</p>
<pre><code>latitude = data[0]['latitude']
</code></pre>
<p>But you'll probably want to play with the response interactively first to make sure.</p>
| 0 |
2016-09-23T18:30:35Z
|
[
"python",
"json",
"extract"
] |
Accessing data from a JSON file
| 39,667,039 |
<p>I am quite new with JSON. My code consists in extracting data from a website wich requires a API key. Having extracted the information. I am trying to reach the information which is encoded in son through this format (here is a sample):</p>
<pre><code>[{"number":31705,"name":"31705 - CHAMPEAUX (BAGNOLET)","address":"RUE DES CHAMPEAUX (PRES DE LA GARE ROUTIERE) - 93170 BAGNOLET","latitude":48.8645278209514,"longitude":2.416170724425901},{"number":10042,"name":"10042 - POISSONNIÃRE - ENGHIEN","address":"52 RUE D'ENGHIEN / ANGLE RUE DU FAUBOURG POISSONIERE - 75010 PARIS","latitude":48.87242006305313,"longitude":2.348395236282807}]
</code></pre>
<p>How do i access the different data in the json code ? This is the code i have come up with:</p>
<pre><code>import requests
reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{station_number}?contract={contract_name}&api_key HTTP/1.1')
</code></pre>
<p>I Believe that my request has formulated a response which lies in the "response" "folder" that has been sent by the website to my computer:</p>
<pre><code>print(reponse.headers)
print(reponse(2,/'latitude')
</code></pre>
<p>I am trying to access the information of lattitude in every element of the json code - the 2 represents the second element of the list and lattitude the name of the value i am trying to access within the element of the json list. But i can't manage to do it. The error I get is a syntax error. </p>
<p>How do I fix it? I would like to access to all the value of each string of each member of the object 'response'.</p>
<p>UPDATE n°1:</p>
<p>My new code is:</p>
<pre><code>import json
import requests
reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{31705}?contract={Paris}&apiKey={0617697a9795f803697de4b9abf9759d5406b3a0} HTTP/1.1')
data = json.loads(response.content)
print(data)
</code></pre>
<p>However i get the error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/someone/Desktop/TIPE 2016:17/Programme TIPE 2016:2017.py", line 27, in <module>
data = json.loads(response.content)
File "/Users/someone/miniconda3/lib/python3.5/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
</code></pre>
<p>UPDATE n°2:</p>
<p>my new code is : </p>
<pre><code>import json
import requests
reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{31705}?contract={Paris}&apiKey={0617697a9795f803697de4b9abf9759d5406b3a0} HTTP/1.1')
data = response.json()
latitude = data[2]['latitude']
</code></pre>
<p>However i get the error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/someone/Desktop/TIPE 2016:17/Programme TIPE 2016:2017.py", line 30, in <module>
latitude = data[2]['latitude']
KeyError: 2
</code></pre>
<p>Does it mean that response is empty ?</p>
<p>UPDATE n°3:</p>
<pre><code>reponse.content
</code></pre>
<p>the answer is the following:</p>
<pre><code>b'{ "error" : "Unauthorized" }'
</code></pre>
<p>What is the problem ?</p>
<p>UPDATE n°4:</p>
<p>my new code is :</p>
<pre><code>reponse=requests.get('https://api.jcdecaux.com/vls/v1/stations/{31705}?contract={Paris}&apiKey={0617697a9795f803697de4b9abf9759d5406b3a0} HTTP/1.1')
data = json.loads(response.content.decode('utf-8'))
print(reponse.headers)
print(reponse.content)
</code></pre>
<p>the result is :</p>
<pre><code>{'Content-Length': '48', 'Content-Encoding': 'gzip', 'Server': 'Apache-Coyote/1.1', 'Date': 'Fri, 23 Sep 2016 19:39:25 GMT', 'Connection': 'close', 'Content-Type': 'application/json'}
b'{ "error" : "Unauthorized" }'
</code></pre>
<p>so the answer to my request is not empty but i do not have the authorization to access it. How can I solve this ?</p>
<p>FINAL UPDATE:</p>
<p>The new and working code is :</p>
<pre><code>import json
import requests
r = requests.get('https://api.jcdecaux.com/vls/v1/stations/31705?contract=Paris&apiKey=0617697a9795f803697de4b9abf9759d5406b3a0')
response_json = r.json()
print (response_json['name'])
</code></pre>
<p>and the result is:</p>
<pre><code>31705 - CHAMPEAUX (BAGNOLET)
</code></pre>
| -1 |
2016-09-23T18:07:23Z
| 39,668,529 |
<p>You've messed up your url. I'm not sure what's about <code>HTTP/1.1</code> suffix, but id definitely does not belong here. Also, all parameters in curled brackets looks off.</p>
<pre><code>import requests
r = requests.get('https://api.jcdecaux.com/vls/v1/stations/31705?contract=Paris&apiKey=0617697a9795f803697de4b9abf9759d5406b3a0')
response_json = r.json()
print response_json
</code></pre>
<p>This code snippet prints:</p>
<pre><code>{u'status': u'OPEN', u'contract_name': u'Paris', u'name': u'31705 - CHAMPEAUX (BAGNOLET)', u'bonus': True, u'bike_stands': 50, u'number': 31705, u'last_update': 1474660046000, u'available_bike_stands': 49, u'banking': True, u'available_bikes': 1, u'address': u'RUE DES CHAMPEAUX (PRES DE LA GARE ROUTIERE) - 93170 BAGNOLET', u'position': {u'lat': 48.8645278209514, u'lng': 2.416170724425901}}
</code></pre>
<p>To sum up, <code>response_json</code> is now a standard Python dict, from which data may be accessed using standard dict protocol.</p>
<pre><code>print response_json['status'] # prints OPEN
</code></pre>
| 1 |
2016-09-23T19:50:42Z
|
[
"python",
"json",
"extract"
] |
Python vectorizing nested for loops
| 39,667,089 |
<p>I'd appreciate some help in finding and understanding a pythonic way to optimize the following array manipulations in nested for loops:</p>
<pre><code>def _func(a, b, radius):
"Return 0 if a>b, otherwise return 1"
if distance.euclidean(a, b) < radius:
return 1
else:
return 0
def _make_mask(volume, roi, radius):
mask = numpy.zeros(volume.shape)
for x in range(volume.shape[0]):
for y in range(volume.shape[1]):
for z in range(volume.shape[2]):
mask[x, y, z] = _func((x, y, z), roi, radius)
return mask
</code></pre>
<p>Where <code>volume.shape</code> (182, 218, 200) and <code>roi.shape</code> (3,) are both <code>ndarray</code> types; and <code>radius</code> is an <code>int</code> </p>
| 11 |
2016-09-23T18:10:01Z
| 39,667,248 |
<p>Say you first build an <code>xyzy</code> array:</p>
<pre><code>import itertools
xyz = [np.array(p) for p in itertools.product(range(volume.shape[0]), range(volume.shape[1]), range(volume.shape[2]))]
</code></pre>
<p>Now, using <a href="http://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.linalg.norm.html"><code>numpy.linalg.norm</code></a>, </p>
<pre><code>np.linalg.norm(xyz - roi, axis=1) < radius
</code></pre>
<p>checks whether the distance for each tuple from <code>roi</code> is smaller than radius.</p>
<p>Finally, just <code>reshape</code> the result to the dimensions you need.</p>
| 5 |
2016-09-23T18:21:10Z
|
[
"python",
"numpy",
"vectorization"
] |
Python vectorizing nested for loops
| 39,667,089 |
<p>I'd appreciate some help in finding and understanding a pythonic way to optimize the following array manipulations in nested for loops:</p>
<pre><code>def _func(a, b, radius):
"Return 0 if a>b, otherwise return 1"
if distance.euclidean(a, b) < radius:
return 1
else:
return 0
def _make_mask(volume, roi, radius):
mask = numpy.zeros(volume.shape)
for x in range(volume.shape[0]):
for y in range(volume.shape[1]):
for z in range(volume.shape[2]):
mask[x, y, z] = _func((x, y, z), roi, radius)
return mask
</code></pre>
<p>Where <code>volume.shape</code> (182, 218, 200) and <code>roi.shape</code> (3,) are both <code>ndarray</code> types; and <code>radius</code> is an <code>int</code> </p>
| 11 |
2016-09-23T18:10:01Z
| 39,667,342 |
<p><strong>Approach #1</strong></p>
<p>Here's a vectorized approach -</p>
<pre><code>m,n,r = volume.shape
x,y,z = np.mgrid[0:m,0:n,0:r]
X = x - roi[0]
Y = y - roi[1]
Z = z - roi[2]
mask = X**2 + Y**2 + Z**2 < radius**2
</code></pre>
<p>Possible improvement : We can probably speedup the last step with <code>numexpr</code> module -</p>
<pre><code>import numexpr as ne
mask = ne.evaluate('X**2 + Y**2 + Z**2 < radius**2')
</code></pre>
<p><strong>Approach #2</strong></p>
<p>We can also gradually build the three ranges corresponding to the shape parameters and perform the subtraction against the three elements of <code>roi</code> on the fly without actually creating the meshes as done earlier with <code>np.mgrid</code>. This would be benefited by the use of <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html"><code>broadcasting</code></a> for efficiency purposes. The implementation would look like this -</p>
<pre><code>m,n,r = volume.shape
vals = ((np.arange(m)-roi[0])**2)[:,None,None] + \
((np.arange(n)-roi[1])**2)[:,None] + ((np.arange(r)-roi[2])**2)
mask = vals < radius**2
</code></pre>
<p>Simplified version : Thanks to @Bi Rico for suggesting an improvement here as we can use <code>np.ogrid</code> to perform those operations in a bit more concise manner, like so -</p>
<pre><code>m,n,r = volume.shape
x,y,z = np.ogrid[0:m,0:n,0:r]-roi
mask = (x**2+y**2+z**2) < radius**2
</code></pre>
<hr>
<p><strong>Runtime test</strong></p>
<p>Function definitions -</p>
<pre><code>def vectorized_app1(volume, roi, radius):
m,n,r = volume.shape
x,y,z = np.mgrid[0:m,0:n,0:r]
X = x - roi[0]
Y = y - roi[1]
Z = z - roi[2]
return X**2 + Y**2 + Z**2 < radius**2
def vectorized_app1_improved(volume, roi, radius):
m,n,r = volume.shape
x,y,z = np.mgrid[0:m,0:n,0:r]
X = x - roi[0]
Y = y - roi[1]
Z = z - roi[2]
return ne.evaluate('X**2 + Y**2 + Z**2 < radius**2')
def vectorized_app2(volume, roi, radius):
m,n,r = volume.shape
vals = ((np.arange(m)-roi[0])**2)[:,None,None] + \
((np.arange(n)-roi[1])**2)[:,None] + ((np.arange(r)-roi[2])**2)
return vals < radius**2
def vectorized_app2_simplified(volume, roi, radius):
m,n,r = volume.shape
x,y,z = np.ogrid[0:m,0:n,0:r]-roi
return (x**2+y**2+z**2) < radius**2
</code></pre>
<p>Timings -</p>
<pre><code>In [106]: # Setup input arrays
...: volume = np.random.rand(90,110,100) # Half of original input sizes
...: roi = np.random.rand(3)
...: radius = 3.4
...:
In [107]: %timeit _make_mask(volume, roi, radius)
1 loops, best of 3: 41.4 s per loop
In [108]: %timeit vectorized_app1(volume, roi, radius)
10 loops, best of 3: 62.3 ms per loop
In [109]: %timeit vectorized_app1_improved(volume, roi, radius)
10 loops, best of 3: 47 ms per loop
In [110]: %timeit vectorized_app2(volume, roi, radius)
100 loops, best of 3: 4.26 ms per loop
In [139]: %timeit vectorized_app2_simplified(volume, roi, radius)
100 loops, best of 3: 4.36 ms per loop
</code></pre>
<p>So, as always <code>broadcasting</code> showing its magic for a crazy almost <strong><code>10,000x</code></strong> speedup over the original code and more than <strong><code>10x</code></strong> better than creating meshes by using on-the-fly broadcasted operations!</p>
| 14 |
2016-09-23T18:26:59Z
|
[
"python",
"numpy",
"vectorization"
] |
Serperate user input into numeric and alpha charaters
| 39,667,123 |
<p>I want to take a user input like "3M" or "3 M" and have it print 3000000</p>
<p>where M = 10**6</p>
| -8 |
2016-09-23T18:12:30Z
| 39,667,148 |
<pre><code>import humanfriendly
user_input = raw_input("Enter a readable file size: ")
Enter a readable file size: 16G
num_bytes = humanfriendly.parse_size(user_input)
print num_bytes
17179869184
print "You entered:", humanfriendly.format_size(num_bytes)
You entered: 16 GB
</code></pre>
<p>I hope this is what you are looking for. </p>
| -1 |
2016-09-23T18:14:24Z
|
[
"python",
"arrays",
"split"
] |
Using the "i-=smallest" statement in the code below, I intend to alter my original array arr, but that isn't happening. What do I do?
| 39,667,130 |
<p>Here's the code:</p>
<pre><code>n = int(input())
arr = input().split()
arr = [int(x) for x in arr]
smallest = 1001
while(True):
if smallest==0:
break
arr.sort()
count = 0
smallest = arr[0]
for i in arr:
if i==0:
arr.remove(i)
i-=smallest #This statement.
count+=1
print(count)
</code></pre>
<p>For input:
(n=)6 and
(arr=)5 4 4 2 2 8
The output I'm getting is:
6
6
6...
However, according to me, if my logic works (and the aforementioned statement actually edits my original array elements), the output should turn out to be
6
4
2
1
instead.</p>
<p>I might have got whole of the thing wrong. I'm an amateur. Any sort of help is appreciated.</p>
| 1 |
2016-09-23T18:12:53Z
| 39,667,464 |
<p>Let's look at the inside loop</p>
<pre><code>for i in arr:
if i==0:
arr.remove(i)
i-=smallest
count+=1
</code></pre>
<p>It assigns the first value in <code>arr</code> to <code>i</code>. Since no value of the array is zero, it doesn't remove anything from the list. </p>
<p>It then reassigns the value of i by subtracting the smallest value. For the first time through the loop it assigns the value of zero to i. Then it increments count. The list <code>arr</code> is unchanged. The line <code>i=-smallest</code> has no effect since <code>i</code> is reassigned to the next value of the list.</p>
<p>So, with the values 5 4 4 2 8 8 (none of which are zero) that loop is equivalent to</p>
<pre><code>for i in arr:
count+=1
</code></pre>
<p>Which is why it always prints 6. I'm not sure why you think it should print 6 4 2 1. I suspect you think the list is being changed, but that the line <code>if i==0</code> is always false.</p>
<p>Changing the object being iterated over in a for loop is guaranteed to confuse you. There is almost certainly a better way to achieve what you want. See for example <a href="http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python">Remove items from a list while iterating in Python</a></p>
| 2 |
2016-09-23T18:35:20Z
|
[
"python",
"arrays",
"python-3.x"
] |
Popup in Kivy Python - show in front
| 39,667,142 |
<pre><code>from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
from kivy.uix.modalview import ModalView
from kivy.config import Config
from ai import Ai
from random import randint
class TicTacToe(StackLayout): #StackLayout explanation: https://kivy.org/docs/api-kivy.uix.stacklayout.html
states = [1, 2, 3, 4, 5, 6, 7, 8, 9]
choices = ["X","O"]
def __init__(self, **kwargs):
super(TicTacToe, self).__init__(**kwargs)
self.init_players();
for x in range(9): # range() explanation: http://pythoncentral.io/pythons-range-function-explained/
bt = Button(text=' ', font_size=200, width=200, height=200, size_hint=(None, None), id=str(x+1))
bt.bind(on_release=self.btn_pressed)
self.add_widget(bt)
view = ModalView(auto_dismiss=False)
view.add_widget(Label(text='Hello world'))
view.open()
def init_players(self):
rand_choice = randint(0,1);
self.bot = Ai(self.choices[rand_choice]);
self.player = self.choices[0] if rand_choice == 1 else self.choices[1]
def btn_pressed(self, button):
button.text="X"
self.states[int(button.id)-1] = "X"
print(self.states)
class MyApp(App):
title = 'Tic Tac Toe'
def build(self):
Config.set('graphics', 'width', '600')
Config.set('graphics', 'height', '600')
return TicTacToe()
if __name__ == '__main__':
MyApp().run()
</code></pre>
<p>This is my simple code, what I am trying to do is, instead of ModalView to have a Popup saying "Hello, you started this game with X". The problem is that when I use Popup (with ModalView too), the window is being displayed behind every button. When I call the Popup after a click though, the Popup is shown properly, but I want to do this on Window initialization.</p>
| 0 |
2016-09-23T18:14:05Z
| 39,668,689 |
<p>I suggest you simply open the pop-up after opening your view like</p>
<pre><code>view = ModalView(auto_dismiss=False)
view.add_widget(Label(text='Hello world'))
view.open()
popup = Popup(
title=title,
content=content,
auto_dismiss=True)
popup.open()
</code></pre>
| 0 |
2016-09-23T20:02:14Z
|
[
"python",
"popup",
"kivy"
] |
How to query for SQLite database column names in Python/Django?
| 39,667,191 |
<p>I can get all the values from the database for a particular Django model in Python using something like</p>
<pre><code>a = Attorney.objects.all().values_list()
print(a)
</code></pre>
<p>What command would I use to make a similar query but for all the column names in the database?
Also, how would I append all the values returned by <code>Attorney.objects.all().values_list()</code> to a list that I could then iterate over?</p>
| 0 |
2016-09-23T18:17:35Z
| 39,668,198 |
<p>If I understand correctly, I think something like the following would do what you're asking about.</p>
<pre><code>import django.apps
models = django.apps.apps.get_models()
for model in models:
field_names = [f.attname for f in model._meta.get_fields()]
for fields in model.objects.values_list(*field_names):
do_something_with_the_fields(fields)
</code></pre>
<p>This seems like an odd thing to want Django to do for you. What are you trying to accomplish by getting all the tables and field names django is aware of?</p>
<h2>Edit based on further explanation in comments</h2>
<p>To dump a table all columns of a table to a CSV, it's probably easiest to introspect the cursor's returned column metadata from the database. There's not much reason to use Django's model definitions in this case:</p>
<pre><code>import csv
from django.db import connection
def dump_table_to_csv(db_table, io):
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM %s" % db_table, [])
rows = cursor.fetchall()
writer = csv.writer(io)
writer.writerow([i[0] for i in cursor.description]) # http://stackoverflow.com/a/9752485
for row in rows:
writer.writerow(row)
witb open('path/to/myfile.csv', 'wb') as f:
dump_table_to_csv(django_model._meta.db_table, f)
</code></pre>
| 0 |
2016-09-23T19:25:40Z
|
[
"python",
"django",
"sqlite",
"django-queryset"
] |
printing out date in uniform order and a counter
| 39,667,257 |
<p>I have been doing these for hours! please help! New to python</p>
<p>example 1990 for input year
and 2000 for end year.</p>
<p>basically i want the output to be </p>
<blockquote>
<p>the years are 1992 1996 2000 </p>
<p>there are 3 counts</p>
</blockquote>
<p>I thought of converting them to a list and using len() but i do not know how</p>
<pre><code>#inputs
year = int(raw_input("Input year: "))
endyear = int(raw_input("Input end year:"))
print "The number of leap years are "
counter = 0
for x in range(year,endyear+1):
if x % 4 == 0 and (x % 100 != 0 or x % 400 == 0):
counter +=1
print x
print counter
</code></pre>
<blockquote>
<p>heres the current result :(</p>
</blockquote>
<p>The number of leap years are </p>
<pre><code>1900
0
1901
0
1902
0
1903
0
</code></pre>
| 0 |
2016-09-23T18:21:48Z
| 39,667,363 |
<p>The problem was when needed year occur, the <code>break</code> stopped your loop.</p>
<pre><code>year = int(raw_input("Input year: "))
end_year = int(raw_input("Input end year:"))
print "The number of leap years are "
counter = 0
temp = []
for x in range(year, end_year+1):
if x % 4 == 0 and (x % 100 != 0 or x % 400 == 0):
counter +=1
temp.append(x)
print('the years are {}'.format(temp))
print('there are {} counts'.format(counter))
</code></pre>
<p>You also might want to remove brackets in <em>"the years are []"</em>, you can do that with </p>
<pre><code>print('the years are ', ' '.join(map(str, temp)))
</code></pre>
| 1 |
2016-09-23T18:28:29Z
|
[
"python"
] |
printing out date in uniform order and a counter
| 39,667,257 |
<p>I have been doing these for hours! please help! New to python</p>
<p>example 1990 for input year
and 2000 for end year.</p>
<p>basically i want the output to be </p>
<blockquote>
<p>the years are 1992 1996 2000 </p>
<p>there are 3 counts</p>
</blockquote>
<p>I thought of converting them to a list and using len() but i do not know how</p>
<pre><code>#inputs
year = int(raw_input("Input year: "))
endyear = int(raw_input("Input end year:"))
print "The number of leap years are "
counter = 0
for x in range(year,endyear+1):
if x % 4 == 0 and (x % 100 != 0 or x % 400 == 0):
counter +=1
print x
print counter
</code></pre>
<blockquote>
<p>heres the current result :(</p>
</blockquote>
<p>The number of leap years are </p>
<pre><code>1900
0
1901
0
1902
0
1903
0
</code></pre>
| 0 |
2016-09-23T18:21:48Z
| 39,667,405 |
<p>You can use the <code>calendar.isleap</code> to count the number of leap years between given years.</p>
<pre><code>from calendar import isleap
year = int(raw_input("Input year: "))
endyear = int(raw_input("Input end year:"))
print "The number of leap years are "
counter = 0
years = []
for x in range(year,endyear+1):
if isleap(x):
counter +=1
print x
print counter
</code></pre>
| 1 |
2016-09-23T18:30:58Z
|
[
"python"
] |
printing out date in uniform order and a counter
| 39,667,257 |
<p>I have been doing these for hours! please help! New to python</p>
<p>example 1990 for input year
and 2000 for end year.</p>
<p>basically i want the output to be </p>
<blockquote>
<p>the years are 1992 1996 2000 </p>
<p>there are 3 counts</p>
</blockquote>
<p>I thought of converting them to a list and using len() but i do not know how</p>
<pre><code>#inputs
year = int(raw_input("Input year: "))
endyear = int(raw_input("Input end year:"))
print "The number of leap years are "
counter = 0
for x in range(year,endyear+1):
if x % 4 == 0 and (x % 100 != 0 or x % 400 == 0):
counter +=1
print x
print counter
</code></pre>
<blockquote>
<p>heres the current result :(</p>
</blockquote>
<p>The number of leap years are </p>
<pre><code>1900
0
1901
0
1902
0
1903
0
</code></pre>
| 0 |
2016-09-23T18:21:48Z
| 39,667,523 |
<p>you can do it in a shorter way:</p>
<pre><code>from calendar import isleap
years = [ str(x) for x in range(year,endyear+1) if isleap(x)]
print "the years are ", ''.join(elem + " " for elem in years)
print "there are ", len(years), "counts"
</code></pre>
| 0 |
2016-09-23T18:39:04Z
|
[
"python"
] |
Pandas slicing by element in cell
| 39,667,277 |
<p>What is the best way to slice by looking for a single element within a cell? I know how to do it with the .isin() function where the cell element is in a list. But I am actually looking for the reverse:</p>
<pre><code>id vals
1 ['wow', 'very', 'such']
2 ['wow', 'such']
3 ['very', 'such']
</code></pre>
<p>I wanted something like this (but this doesn't work): </p>
<pre><code>df['very' in df['vals']]
id vals
1 ['wow', 'very', 'such']
3 ['very', 'such']
</code></pre>
<p>I think an alternative is to use apply(), matching on the value, but it seems a little inelegant.</p>
| 1 |
2016-09-23T18:22:56Z
| 39,667,418 |
<p>A <code>list-comprehension</code> to select rows which contain only the string <em>very</em> could be used:</p>
<pre><code>df[['very' in x for x in df['vals'].values]]
</code></pre>
<p><a href="http://i.stack.imgur.com/CwrgU.png" rel="nofollow"><img src="http://i.stack.imgur.com/CwrgU.png" alt="Image"></a></p>
| 2 |
2016-09-23T18:31:37Z
|
[
"python",
"pandas",
"slice"
] |
Pandas slicing by element in cell
| 39,667,277 |
<p>What is the best way to slice by looking for a single element within a cell? I know how to do it with the .isin() function where the cell element is in a list. But I am actually looking for the reverse:</p>
<pre><code>id vals
1 ['wow', 'very', 'such']
2 ['wow', 'such']
3 ['very', 'such']
</code></pre>
<p>I wanted something like this (but this doesn't work): </p>
<pre><code>df['very' in df['vals']]
id vals
1 ['wow', 'very', 'such']
3 ['very', 'such']
</code></pre>
<p>I think an alternative is to use apply(), matching on the value, but it seems a little inelegant.</p>
| 1 |
2016-09-23T18:22:56Z
| 39,667,525 |
<pre><code>df[df.vals.apply(lambda x: 'very' in x)]
Out[9]:
vals
0 [wow, very, such]
2 [very, such]
</code></pre>
| 1 |
2016-09-23T18:39:11Z
|
[
"python",
"pandas",
"slice"
] |
elif raises a syntax error, but if does not
| 39,667,333 |
<p>I get an error when I try to change an "if" to an "elif." The code works perfectly when I'm using an if, but raises a syntax error if I try to use "elif" instead. I need to use "elif" because I only want one of the if statements to run, not both. This code works fine:</p>
<pre><code>guess_row=0
guess_col=0
ship_location=0
number_of_attempts=3
guess_location = input("Guess :").split(",")
guess_row,guess_col = int(guess_location[0]),int(guess_location[1])
if guess_row not in range(1,6):
print("Out of range1.")
print(guess_location)
print(ship_location)
if guess_col not in range(1,6):
print("Out of range2.")
print(guess_location)
print(ship_location)
if ship_location == guess_location:
print("You sunk my battleship! You win!")
else:
print ("You missed!")
print ("You have " + str(number_of_attempts-1) + " attempt(s) left!")
print ("Try again!")
number_of_attempts-=1
</code></pre>
<p>But if I change the 2nd or 3rd "if" to "elif":</p>
<pre><code>guess_row=0
guess_col=0
ship_location=0
number_of_attempts=3
guess_location = input("Guess :").split(",")
guess_row,guess_col = int(guess_location[0]),int(guess_location[1])
if guess_row not in range(1,6):
print("Out of range1.")
print(guess_location)
print(ship_location)
elif guess_col not in range(1,6):
print("Out of range2.")
print(guess_location)
print(ship_location)
elif ship_location == guess_location:
print("You sunk my battleship! You win!")
else:
print ("You missed!")
print ("You have " + str(number_of_attempts-1) + " attempt(s) left!")
print ("Try again!")
number_of_attempts-=1
</code></pre>
<p>I get a syntax error. Help?</p>
| 0 |
2016-09-23T18:26:26Z
| 39,667,408 |
<p><code>elif</code> is not a separate statement. <code>elif</code> is an option part of an existing <code>if</code> statement.</p>
<p>As such, you can only use <code>elif</code> <em>directly</em> after an <code>if</code> block:</p>
<pre><code>if sometest:
indented lines
forming a block
elif anothertest:
another block
</code></pre>
<p>In your code, however, the <code>elif</code> does <em>not</em> directly follow a block already part of the <code>if</code> statement. You have lines in between that are no longer part of the block because they are not indented to the <code>if</code> block level anymore:</p>
<pre><code>if guess_row not in range(1,6):
print("Out of range1.") # part of the block
print(guess_location) # NOT part of the block, so the block ended
print(ship_location)
elif guess_col not in range(1,6):
</code></pre>
<p>This doesn't matter to <em>separate</em> <code>if</code> statements; the un-indented <code>print()</code> statements are executed between the <code>if</code> blocks.</p>
<p>You'll need to move those <code>print()</code> functions to be run <em>after</em> the <code>if...elif...else</code> statemement:</p>
<pre><code>if guess_row not in range(1,6):
print("Out of range1.")
elif guess_col not in range(1,6):
print("Out of range2.")
elif ship_location == guess_location:
print("You sunk my battleship! You win!")
else:
print ("You missed!")
print ("You have " + str(number_of_attempts-1) + " attempt(s) left!")
print ("Try again!")
number_of_attempts-=1
print(guess_location)
print(ship_location)
</code></pre>
<p>or fix their indentation to be part of the <code>if</code> and <code>elif</code> blocks.</p>
| 4 |
2016-09-23T18:31:08Z
|
[
"python",
"python-3.x"
] |
how to compare list to text file and delete missing entries
| 39,667,383 |
<p>If I have a list with different values like <code>Eind, Shf, Asuf</code>.
And a text file with</p>
<pre><code>20:36:00 - Baarn
20:36:00 - Enschede
20:37:00 - Eindhoven
20:37:00 - Eind
20:37:00 - Shf
20:37:00 - Asuf
20:38:00 - Nijmegen
</code></pre>
<p>How do I delete the values in the list from the text file but delete the whole line.</p>
| -1 |
2016-09-23T18:29:40Z
| 39,667,462 |
<p>I would create a new file:</p>
<p>Given that you have a list like this</p>
<pre><code>to_delete = ['Eind', 'Shf', 'Asuf']
</code></pre>
<p>you can open both your current file and a new file and create a new version</p>
<pre><code>in_file = open('input.txt')
out_file = open('output.txt')
for line in in_file:
last_word = line.split(' ')[-1]
if not last_word in to_delete:
out_file.write(line)
in_file.close()
out_file.close()
</code></pre>
<p>in this way, the new file has only the entries that don't match with the itemes in your list. In the code above I assume that your file has to check only the last word with whatever is in the list.</p>
| 1 |
2016-09-23T18:35:15Z
|
[
"python",
"list",
"text-files"
] |
how to compare list to text file and delete missing entries
| 39,667,383 |
<p>If I have a list with different values like <code>Eind, Shf, Asuf</code>.
And a text file with</p>
<pre><code>20:36:00 - Baarn
20:36:00 - Enschede
20:37:00 - Eindhoven
20:37:00 - Eind
20:37:00 - Shf
20:37:00 - Asuf
20:38:00 - Nijmegen
</code></pre>
<p>How do I delete the values in the list from the text file but delete the whole line.</p>
| -1 |
2016-09-23T18:29:40Z
| 39,667,553 |
<p>This is your list:</p>
<pre><code>deletion_list = ["Eind", "Shf", "Asuf"]
</code></pre>
<p>First convert into a set in order to make faster searches:</p>
<pre><code>deletion_set = set(deletion_list)
</code></pre>
<p>Then filter it out:</p>
<pre><code># Open the file in a with statement to make sure it closes correctly
with open("input.txt") as input_file, open("output.txt", "w") as output_file:
# Write to new file
list(map(output_file.write,
# Iterates over all lines in file and take those in set
(line for line in input_file
# Checks if line is in set
if line.rpartition(" ")[-1] in deletion_set))
</code></pre>
<p>This is probably the best way. It's efficient and bug-less (with statements prevent unknown exceptions from keeping files open)</p>
| 0 |
2016-09-23T18:41:28Z
|
[
"python",
"list",
"text-files"
] |
PyQt5 Attribute Error: 'GUI' object has no attribute 'setLayout'
| 39,667,545 |
<p>There seems to be an attribute error when I run my code. Specifically, the error I encounter is:</p>
<pre><code>AttributeError: 'GUI' object has no attribute 'setLayout'
</code></pre>
<p>The code I'm currently using:</p>
<pre><code>class GUI(object):
def __init__(self):
super(GUI,self).__init__()
self.initUI()
def initUI(self):
review = QtWidgets.QLabel('Review')
reviewEdit = QtWidgets.QTextEdit()
grid = QtWidgets.QGridLayout()
grid.addWidget(review, 3, 0)
grid.addWidget(reviewEdit, 3, 1, 5, 1)
self.setLayout(grid)
self.setGeometry(300,300,350,300)
self.setWindowTitle('Sentiment Analysis')
self.show()
</code></pre>
| 0 |
2016-09-23T18:41:07Z
| 39,667,642 |
<p>You get an attribute error because neither your class nor <code>object</code> defines the methods you try to access through <code>self</code>. You need to inherit these from a <code>Qt</code> class that defines them. For example, inheriting from <code>QWidget</code>.</p>
<pre><code>from PyQt5 import QtWidgets
class GUI(QtWidgets.QWidget):
...
</code></pre>
<p>will makes these available for your class. Substitute the appropriate <code>PyQt</code> base class for your use case to get the functionality.</p>
| 1 |
2016-09-23T18:48:02Z
|
[
"python",
"python-3.x",
"pyqt5"
] |
Why does the result variable update itself?
| 39,667,572 |
<p>I have the following code:</p>
<p><code>result = datetime.datetime.now() - datetime.timedelta(seconds=60)</code></p>
<pre><code>>>> result.utcnow().isoformat()
'2016-09-23T18:39:34.174406'
>>> result.utcnow().isoformat()
'2016-09-23T18:40:18.240571'
</code></pre>
<p>Somehow the variable is being updated... and I have no clue as to how or how to stop it. What is this called? How do I prevent it?</p>
<p>Thank you!</p>
| 2 |
2016-09-23T18:42:19Z
| 39,667,609 |
<p><code>result</code> is a <code>datetime</code> object</p>
<p><code>datetime.utcnow()</code> is a class method of all <code>datetime</code> objects. </p>
<p><code>result</code> is not changing at all. <code>utcnow()</code> is </p>
| 8 |
2016-09-23T18:45:19Z
|
[
"python",
"datetime"
] |
translate SQL query to flask-sqlalchemy statements
| 39,667,585 |
<p>I am changing my old SQL implementations of a web app to flask-alchemy and having some difficulties about the correspondence.</p>
<p>The old code looks like this. It does the name query about some properties and returns a csv style text. </p>
<pre><code>header = 'id,display_name,city,state,latitude,longitude\n'
base_query = '''SELECT id, bbs_id, city, state,
latitude, longitude FROM mytable'''
conn = sqlite3.connect(path.join(ROOT,'db.sqlite'))
c = conn.execute(base_query+'WHERE name=?', (name,))
results = c.fetchall()
conn.close()
rows = [','.join(map(str, row)) for row in results]
return header + rows
</code></pre>
<p>The new code</p>
<pre><code>header = 'id,display_name,city,state,latitude,longitude\n'
cols = ['id', 'bbs_id', 'city', 'state', 'latitude', 'longitude']
users = User.query.filter_by(name=name).all()
rows = ''
for user in users:
rows += ','.join([user.id, user.bbs_id, user.city, user.state, user.latitude, user.longitude]) + '\n'
return header + rows
</code></pre>
<p>I am not happy with the new code since it's so verbose. </p>
<ul>
<li>Is there a way to select only the ones in <code>cols</code> instead of query all columns and then pick the needed columns? </li>
<li>If not, is it possible to write the <code>','.join()</code> more succinctly? It seems <code>user['id']</code> does not work and I have to do <code>user.id</code>.</li>
</ul>
| 0 |
2016-09-23T18:43:17Z
| 39,667,708 |
<p>If you just want a result set as before, you can do:</p>
<pre><code>results = db.session.query(*(getattr(User, col) for col in cols)).filter_by(...)
</code></pre>
<p>and then you can use <code>results</code> as you did before.</p>
<p>If, OTOH, you want to use the ORM, you can use <a href="http://docs.sqlalchemy.org/en/latest/orm/loading_columns.html#sqlalchemy.orm.load_only" rel="nofollow"><code>load_only</code></a>:</p>
<pre><code>users = User.query.options(*(load_only(col) for col in cols)).filter_by(...)
rows = "".join(",".join(*(getattr(u, col) for col in cols)) + "\n" for u in users)
</code></pre>
| 1 |
2016-09-23T18:52:55Z
|
[
"python",
"sql",
"sqlalchemy",
"flask-sqlalchemy"
] |
translate SQL query to flask-sqlalchemy statements
| 39,667,585 |
<p>I am changing my old SQL implementations of a web app to flask-alchemy and having some difficulties about the correspondence.</p>
<p>The old code looks like this. It does the name query about some properties and returns a csv style text. </p>
<pre><code>header = 'id,display_name,city,state,latitude,longitude\n'
base_query = '''SELECT id, bbs_id, city, state,
latitude, longitude FROM mytable'''
conn = sqlite3.connect(path.join(ROOT,'db.sqlite'))
c = conn.execute(base_query+'WHERE name=?', (name,))
results = c.fetchall()
conn.close()
rows = [','.join(map(str, row)) for row in results]
return header + rows
</code></pre>
<p>The new code</p>
<pre><code>header = 'id,display_name,city,state,latitude,longitude\n'
cols = ['id', 'bbs_id', 'city', 'state', 'latitude', 'longitude']
users = User.query.filter_by(name=name).all()
rows = ''
for user in users:
rows += ','.join([user.id, user.bbs_id, user.city, user.state, user.latitude, user.longitude]) + '\n'
return header + rows
</code></pre>
<p>I am not happy with the new code since it's so verbose. </p>
<ul>
<li>Is there a way to select only the ones in <code>cols</code> instead of query all columns and then pick the needed columns? </li>
<li>If not, is it possible to write the <code>','.join()</code> more succinctly? It seems <code>user['id']</code> does not work and I have to do <code>user.id</code>.</li>
</ul>
| 0 |
2016-09-23T18:43:17Z
| 39,667,839 |
<p>As it seems that you want to output comma separated values, use the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">proper module</a> for that. You can override the query's entities with <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.with_entities" rel="nofollow">with_entities</a>:</p>
<pre><code>import csv
import io
...
output = io.StringIO()
writer = csv.writer(output)
headers = ['id', 'bbs_id', 'city', 'state', 'latitude', 'longitude']
writer.writerow(headers)
# The other option is to db.session.query(...)
users = User.query.with_entities(
*(getattr(User, hdr) for hdr in headers)
).filter_by(name=name)
writer.writerows(users)
return output.getvalue()
</code></pre>
<p>If you're still on python 2, <a href="http://stackoverflow.com/questions/13120127/how-can-i-use-io-stringio-with-the-csv-module">replace <code>io.StringIO</code> with <code>io.BytesIO</code></a>.</p>
| 1 |
2016-09-23T19:01:45Z
|
[
"python",
"sql",
"sqlalchemy",
"flask-sqlalchemy"
] |
How would I create a form for a foreign key field that has a drop down menu with an 'add item' option in django?
| 39,667,610 |
<p>I'll start with my model fields: </p>
<pre><code>class Store(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return self.name
class Product(models.Model):
type = models.CharField(max_length=250)
def __str__(self):
return self.type
class Receipt(models.Model):
store = models.ForeignKey(Store)
date = models.DateField()
line_items = models.ManyToManyField(Product, through='ReceiptProduct')
def __str__(self):
return self.store.name + ': ' + str(self.date)
class ReceiptProduct(models.Model):
receipt = models.ForeignKey(Receipt)
product = models.ForeignKey(Product)
price = models.FloatField()
description = models.CharField(max_length=500, null=True, blank=True)
def __str__(self):
return self.product.type
</code></pre>
<p>What I would like to do is create a form for the ReceiptProduct model. </p>
<pre><code>class AddItemForm(ModelForm):
class Meta:
model = ReceiptProduct
fields = ['product', 'price', 'description']
</code></pre>
<p>Done. And the view? </p>
<pre><code>def add_receipt_product(request, receipt_id):
current_receipt = Receipt.objects.get(id=receipt_id)
if request.method != 'POST':
# No data submitted; create a blank form.
form = AddItemForm(initial={'receipt': current_receipt})
else:
# POST data submitted; process data.
form = AddItemForm(data=request.POST)
if form.is_valid():
new_product = form.save(commit=False)
new_product.receipt = current_receipt
new_product.save()
return HttpResponseRedirect(reverse('purchase_log:receipt_details', args=[receipt_id]))
context = {'current_receipt': current_receipt, 'form': form}
return render(request, 'purchase_log/add_receipt_product_form.html', context)
</code></pre>
<p>Okay, so what I would like to do is, under the 'product' field (which is a drop down menu populated by the Product model), have an option called, maybe, 'custom product' or something, that the user can select to add an item to the Product model and will then appear in future drop down menus. Is this do-able?<br>
Thank you all in advanced!!</p>
| 0 |
2016-09-23T18:45:20Z
| 39,668,094 |
<p>Django implements this in terms of <a href="https://docs.djangoproject.com/en/1.10/topics/forms/formsets/" rel="nofollow">a "formset"</a>. Check out this tutorial for additional information: <a href="http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html" rel="nofollow">http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html</a> I think the example there is fairly similar to yours.</p>
<p>In the Django admin interface, things are somewhat easier, and you can use an <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.TabularInline" rel="nofollow"><code>Inline</code></a>. </p>
| 1 |
2016-09-23T19:18:29Z
|
[
"python",
"django",
"django-forms",
"foreign-keys",
"modelform"
] |
Python 2.7 BeautifulSoup email scraping stops before end of full database
| 39,667,624 |
<p>Hope you are all well! I'm new and using Python 2.7! I'm tring to extract emails from a public available directory website that does not seems to have API: this is the site: <a href="http://www.tecomdirectory.com/companies.php?segment=&activity=&search=category&submit=Search" rel="nofollow">http://www.tecomdirectory.com/companies.php?segment=&activity=&search=category&submit=Search</a><br>
, the code stop gathering email where on the page at the bottom where it says "load more"!
Here is my code:</p>
<pre><code>import requests
import re
from bs4 import BeautifulSoup
file_handler = open('mail.txt','w')
soup = BeautifulSoup(requests.get('http://www.tecomdirectory.com/companies.php?segment=&activity=&search=category&submit=Search').content)
tags = soup('a')
list_new =[]
for tag in tags:
if (re.findall(r'href="mailto:([^"@]+@[^"]+)">\1</a>',('%s'%tag))): list_new = list_new +(re.findall(r'href="mailto:([^"@]+@[^"]+)">\1</a>', ('%s'%tag)))
for x in list_new:
file_handler.write('%s\n'%x)
file_handler.close()
</code></pre>
<p>How can i make sure that the code goes till the end of the directory and does not stop where it shows load more?
Thanks.
Warmest regards</p>
| 0 |
2016-09-23T18:46:26Z
| 39,668,546 |
<p>You just need to post some data, in particular incrementing <code>group_no</code> to simulate clicking the load more button:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
# you can set whatever here to influence the results
data = {"group_no": "1",
"search": "category",
"segment": "",
"activity": "",
"retail": "",
"category": "",
"Bpark": "",
"alpha": ""}
post = "http://www.tecomdirectory.com/getautocomplete_keyword.php"
with requests.Session() as s:
soup = BeautifulSoup(
s.get("http://www.tecomdirectory.com/companies.php?segment=&activity=&search=category&submit=Search").content,
"html.parser")
print([a["href"] for a in soup.select("a[href^=mailto:]")])
for i in range(1, 5):
data["group_no"] = str(i)
soup = BeautifulSoup(s.post(post, data=data).content, "html.parser")
print([a["href"] for a in soup.select("a[href^=mailto:]")])
</code></pre>
<p>To go until the end, you can loop until the post returns no html, that signifies we cannot load any more pages:</p>
<pre><code>def yield_all_mails():
data = {"group_no": "1",
"search": "category",
"segment": "",
"activity": "",
"retail": "",
"category": "",
"Bpark": "",
"alpha": ""}
post = "http://www.tecomdirectory.com/getautocomplete_keyword.php"
start = "http://www.tecomdirectory.com/companies.php?segment=&activity=&search=category&submit=Search"
with requests.Session() as s:
resp = s.get(start)
soup = BeautifulSoup(s.get(start).content, "html.parser")
yield (a["href"] for a in soup.select("a[href^=mailto:]"))
i = 1
while resp.content.strip():
data["group_no"] = str(i)
resp = s.post(post, data=data)
soup = BeautifulSoup(resp.content, "html.parser")
yield (a["href"] for a in soup.select("a[href^=mailto:]"))
i += 1
</code></pre>
<p>So if we ran the function like below setting <code>"alpha": "Z"</code> to just iterate over the Z's:</p>
<pre><code>from itertools import chain
for mail in chain.from_iterable(yield_all_mails()):
print(mail)
</code></pre>
<p>We would get:</p>
<pre><code>mailto:info@10pearls.com
mailto:fady@24group.ae
mailto:pepe@2heads.tv
mailto:2interact@2interact.us
mailto:gc@worldig.com
mailto:marilyn.pais@3i-infotech.com
mailto:3mgulf@mmm.com
mailto:venkat@4gid.com
mailto:info@4power.biz
mailto:info@4sstudyabroad.com
mailto:fouad@622agency.com
mailto:sahar@7quality.com
mailto:mike.atack@8ack.com
mailto:zyara@emirates.net.ae
mailto:aokasha@zynx.com
Process finished with exit code 0
</code></pre>
<p>You should put a sleep in between requests so you don't hammer the server and get yourself blocked.</p>
| 1 |
2016-09-23T19:51:59Z
|
[
"python",
"python-2.7",
"web-scraping",
"beautifulsoup"
] |
Need help adding API PUT method to Python script
| 39,667,630 |
<p>I am using the script below to collect inventory information from servers and send it to a product called Device42. The script currently works however one of the APIs that I'm trying to add uses PUT instead of POST. I'm not a programmer and just started using python with this script. This script is using iron python. Can the PUT method be used in this script?</p>
<pre><code>"""
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
##################################################
# a sample script to show how to use
# /api/ip/add-or-update
# /api/device/add-or-update
#
# requires ironPython (http://ironpython.codeplex.com/) and
# powershell (http://support.microsoft.com/kb/968929)
##################################################
import clr
clr.AddReference('System.Management.Automation')
from System.Management.Automation import (
PSMethod, RunspaceInvoke
)
RUNSPACE = RunspaceInvoke()
import urllib
import urllib2
import traceback
import base64
import math
import ssl
import functools
BASE_URL='https://device42_URL'
API_DEVICE_URL=BASE_URL+'/api/1.0/devices/'
API_IP_URL =BASE_URL+'/api/1.0/ips/'
API_PART_URL=BASE_URL+'/api/1.0/parts/'
API_MOUNTPOINT_URL=BASE_URL+'/api/1.0/device/mountpoints/'
API_CUSTOMFIELD_URL=BASE_URL+'/api/1.0/device/custom_field/'
USER ='usernme'
PASSWORD ='password'
old_init = ssl.SSLSocket.__init__
@functools.wraps(old_init)
def init_with_tls1(self, *args, **kwargs):
kwargs['ssl_version'] = ssl.PROTOCOL_TLSv1
old_init(self, *args, **kwargs)
ssl.SSLSocket.__init__ = init_with_tls1
def post(url, params):
"""
http post with basic-auth
params is dict like object
"""
try:
data= urllib.urlencode(params) # convert to ascii chars
headers = {
'Authorization' : 'Basic '+ base64.b64encode(USER + ':' + PASSWORD),
'Content-Type' : 'application/x-www-form-urlencoded'
}
req = urllib2.Request(url, data, headers)
print '---REQUEST---',req.get_full_url()
print req.headers
print req.data
reponse = urllib2.urlopen(req)
print '---RESPONSE---'
print reponse.getcode()
print reponse.info()
print reponse.read()
except urllib2.HTTPError as err:
print '---RESPONSE---'
print err.getcode()
print err.info()
print err.read()
except urllib2.URLError as err:
print '---RESPONSE---'
print err
def to_ascii(s):
# ignore non-ascii chars
return s.encode('ascii','ignore')
def wmi(query):
return [dict([(prop.Name, prop.Value) for prop in psobj.Properties]) for psobj in RUNSPACE.Invoke(query)]
def closest_memory_assumption(v):
return int(256 * math.ceil(v / 256.0))
def add_or_update_device():
computer_system = wmi('Get-WmiObject Win32_ComputerSystem -Namespace "root\CIMV2"')[0] # take first
bios = wmi('Get-WmiObject Win32_BIOS -Namespace "root\CIMV2"')[0]
operating_system = wmi('Get-WmiObject Win32_OperatingSystem -Namespace "root\CIMV2"')[0]
environment = wmi('Get-WmiObject Win32Reg_ESFFarmNode -Namespace "root\CIMV2"')[0]
mem = closest_memory_assumption(int(computer_system.get('TotalPhysicalMemory')) / 1047552)
dev_name = to_ascii(computer_system.get('Name')).upper()
fqdn_name = to_ascii(computer_system.get('Name')).upper() + '.' + to_ascii(computer_system.get('Domain')).lower()
device = {
'memory' : mem,
'os' : to_ascii(operating_system.get('Caption')),
'osver' : operating_system.get('OSArchitecture'),
'osmanufacturer': to_ascii(operating_system.get('Manufacturer')),
'osserial' : operating_system.get('SerialNumber'),
'osverno' : operating_system.get('Version'),
'service_level' : environment.get('Environment'),
'notes' : 'Test w/ Change to Device name collection'
}
devicedmn = ''
for dmn in ['Domain1', 'Domain2', 'Domain3', 'Domain4', 'Domain5']:
if dmn == to_ascii(computer_system.get('Domain')).strip():
devicedmn = 'Domain'
device.update({ 'name' : fqdn_name, })
break
if devicedmn != 'Domain':
device.update({
'name': dev_name,
})
manufacturer = ''
for mftr in ['VMware, Inc.', 'Bochs', 'KVM', 'QEMU', 'Microsoft Corporation', 'Xen']:
if mftr == to_ascii(computer_system.get('Manufacturer')).strip():
manufacturer = 'virtual'
device.update({ 'manufacturer' : 'vmware', })
break
if manufacturer != 'virtual':
device.update({
'manufacturer': to_ascii(computer_system.get('Manufacturer')).strip(),
'hardware': to_ascii(computer_system.get('Model')).strip(),
'serial_no': to_ascii(bios.get('SerialNumber')).strip(),
'type': 'Physical',
})
cpucount = 0
for cpu in wmi('Get-WmiObject Win32_Processor -Namespace "root\CIMV2"'):
cpucount += 1
cpuspeed = cpu.get('MaxClockSpeed')
cpucores = cpu.get('NumberOfCores')
if cpucount > 0:
device.update({
'cpucount': cpucount,
'cpupower': cpuspeed,
'cpucore': cpucores,
})
hddcount = 0
hddsize = 0
for hdd in wmi('Get-WmiObject Win32_LogicalDisk -Namespace "root\CIMV2" | where{$_.Size -gt 1}'):
hddcount += 1
hddsize += hdd.get('Size') / 1073741742
if hddcount > 0:
device.update({
'hddcount': hddcount,
'hddsize': hddsize,
})
post(API_DEVICE_URL, device)
for hdd in wmi('Get-WmiObject Win32_LogicalDisk -Namespace "root\CIMV2" | where{$_.Size -gt 1}'):
mountpoint = {
'mountpoint' : hdd.get('Name'),
'label' : hdd.get('Caption'),
'fstype' : hdd.get('FileSystem'),
'capacity' : hdd.get('Size') / 1024 / 1024,
'free_capacity' : hdd.get('FreeSpace') / 1024 / 1024,
'device' : dev_name,
'assignment' : 'Device',
}
post(API_MOUNTPOINT_URL, mountpoint)
network_adapter_configuration = wmi('Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace "root\CIMV2" | where{$_.IPEnabled -eq "True"}')
for ntwk in network_adapter_configuration:
for ipaddr in ntwk.get('IPAddress'):
ip = {
'ipaddress' : ipaddr,
'macaddress' : ntwk.get('MACAddress'),
'label' : ntwk.get('Description'),
'device' : dev_name,
}
post(API_IP_URL, ip)
def main():
try:
add_or_update_device()
except:
traceback.print_exc()
if __name__ == "__main__":
main()
</code></pre>
| 0 |
2016-09-23T18:46:59Z
| 39,667,874 |
<p>My standard answer would be to replace urllib2 with the <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a> package. It makes doing HTTP work a lot easier.</p>
<p>But take a look at <a href="http://stackoverflow.com/a/111988/63802">this SO answer</a> for a 'hack' to get PUT working.</p>
| 0 |
2016-09-23T19:04:10Z
|
[
"python",
"api",
"put"
] |
Need help adding API PUT method to Python script
| 39,667,630 |
<p>I am using the script below to collect inventory information from servers and send it to a product called Device42. The script currently works however one of the APIs that I'm trying to add uses PUT instead of POST. I'm not a programmer and just started using python with this script. This script is using iron python. Can the PUT method be used in this script?</p>
<pre><code>"""
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
##################################################
# a sample script to show how to use
# /api/ip/add-or-update
# /api/device/add-or-update
#
# requires ironPython (http://ironpython.codeplex.com/) and
# powershell (http://support.microsoft.com/kb/968929)
##################################################
import clr
clr.AddReference('System.Management.Automation')
from System.Management.Automation import (
PSMethod, RunspaceInvoke
)
RUNSPACE = RunspaceInvoke()
import urllib
import urllib2
import traceback
import base64
import math
import ssl
import functools
BASE_URL='https://device42_URL'
API_DEVICE_URL=BASE_URL+'/api/1.0/devices/'
API_IP_URL =BASE_URL+'/api/1.0/ips/'
API_PART_URL=BASE_URL+'/api/1.0/parts/'
API_MOUNTPOINT_URL=BASE_URL+'/api/1.0/device/mountpoints/'
API_CUSTOMFIELD_URL=BASE_URL+'/api/1.0/device/custom_field/'
USER ='usernme'
PASSWORD ='password'
old_init = ssl.SSLSocket.__init__
@functools.wraps(old_init)
def init_with_tls1(self, *args, **kwargs):
kwargs['ssl_version'] = ssl.PROTOCOL_TLSv1
old_init(self, *args, **kwargs)
ssl.SSLSocket.__init__ = init_with_tls1
def post(url, params):
"""
http post with basic-auth
params is dict like object
"""
try:
data= urllib.urlencode(params) # convert to ascii chars
headers = {
'Authorization' : 'Basic '+ base64.b64encode(USER + ':' + PASSWORD),
'Content-Type' : 'application/x-www-form-urlencoded'
}
req = urllib2.Request(url, data, headers)
print '---REQUEST---',req.get_full_url()
print req.headers
print req.data
reponse = urllib2.urlopen(req)
print '---RESPONSE---'
print reponse.getcode()
print reponse.info()
print reponse.read()
except urllib2.HTTPError as err:
print '---RESPONSE---'
print err.getcode()
print err.info()
print err.read()
except urllib2.URLError as err:
print '---RESPONSE---'
print err
def to_ascii(s):
# ignore non-ascii chars
return s.encode('ascii','ignore')
def wmi(query):
return [dict([(prop.Name, prop.Value) for prop in psobj.Properties]) for psobj in RUNSPACE.Invoke(query)]
def closest_memory_assumption(v):
return int(256 * math.ceil(v / 256.0))
def add_or_update_device():
computer_system = wmi('Get-WmiObject Win32_ComputerSystem -Namespace "root\CIMV2"')[0] # take first
bios = wmi('Get-WmiObject Win32_BIOS -Namespace "root\CIMV2"')[0]
operating_system = wmi('Get-WmiObject Win32_OperatingSystem -Namespace "root\CIMV2"')[0]
environment = wmi('Get-WmiObject Win32Reg_ESFFarmNode -Namespace "root\CIMV2"')[0]
mem = closest_memory_assumption(int(computer_system.get('TotalPhysicalMemory')) / 1047552)
dev_name = to_ascii(computer_system.get('Name')).upper()
fqdn_name = to_ascii(computer_system.get('Name')).upper() + '.' + to_ascii(computer_system.get('Domain')).lower()
device = {
'memory' : mem,
'os' : to_ascii(operating_system.get('Caption')),
'osver' : operating_system.get('OSArchitecture'),
'osmanufacturer': to_ascii(operating_system.get('Manufacturer')),
'osserial' : operating_system.get('SerialNumber'),
'osverno' : operating_system.get('Version'),
'service_level' : environment.get('Environment'),
'notes' : 'Test w/ Change to Device name collection'
}
devicedmn = ''
for dmn in ['Domain1', 'Domain2', 'Domain3', 'Domain4', 'Domain5']:
if dmn == to_ascii(computer_system.get('Domain')).strip():
devicedmn = 'Domain'
device.update({ 'name' : fqdn_name, })
break
if devicedmn != 'Domain':
device.update({
'name': dev_name,
})
manufacturer = ''
for mftr in ['VMware, Inc.', 'Bochs', 'KVM', 'QEMU', 'Microsoft Corporation', 'Xen']:
if mftr == to_ascii(computer_system.get('Manufacturer')).strip():
manufacturer = 'virtual'
device.update({ 'manufacturer' : 'vmware', })
break
if manufacturer != 'virtual':
device.update({
'manufacturer': to_ascii(computer_system.get('Manufacturer')).strip(),
'hardware': to_ascii(computer_system.get('Model')).strip(),
'serial_no': to_ascii(bios.get('SerialNumber')).strip(),
'type': 'Physical',
})
cpucount = 0
for cpu in wmi('Get-WmiObject Win32_Processor -Namespace "root\CIMV2"'):
cpucount += 1
cpuspeed = cpu.get('MaxClockSpeed')
cpucores = cpu.get('NumberOfCores')
if cpucount > 0:
device.update({
'cpucount': cpucount,
'cpupower': cpuspeed,
'cpucore': cpucores,
})
hddcount = 0
hddsize = 0
for hdd in wmi('Get-WmiObject Win32_LogicalDisk -Namespace "root\CIMV2" | where{$_.Size -gt 1}'):
hddcount += 1
hddsize += hdd.get('Size') / 1073741742
if hddcount > 0:
device.update({
'hddcount': hddcount,
'hddsize': hddsize,
})
post(API_DEVICE_URL, device)
for hdd in wmi('Get-WmiObject Win32_LogicalDisk -Namespace "root\CIMV2" | where{$_.Size -gt 1}'):
mountpoint = {
'mountpoint' : hdd.get('Name'),
'label' : hdd.get('Caption'),
'fstype' : hdd.get('FileSystem'),
'capacity' : hdd.get('Size') / 1024 / 1024,
'free_capacity' : hdd.get('FreeSpace') / 1024 / 1024,
'device' : dev_name,
'assignment' : 'Device',
}
post(API_MOUNTPOINT_URL, mountpoint)
network_adapter_configuration = wmi('Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace "root\CIMV2" | where{$_.IPEnabled -eq "True"}')
for ntwk in network_adapter_configuration:
for ipaddr in ntwk.get('IPAddress'):
ip = {
'ipaddress' : ipaddr,
'macaddress' : ntwk.get('MACAddress'),
'label' : ntwk.get('Description'),
'device' : dev_name,
}
post(API_IP_URL, ip)
def main():
try:
add_or_update_device()
except:
traceback.print_exc()
if __name__ == "__main__":
main()
</code></pre>
| 0 |
2016-09-23T18:46:59Z
| 39,667,889 |
<p>Ok first things first you need to understand the difference between PUT and POST. I would write it out but another member of the community gave a very good description of the two <a href="http://stackoverflow.com/questions/107390/whats-the-difference-between-a-post-and-a-put-http-request">here</a>.</p>
<p>Now, yes you can use requests with that script. Here is an example of using the requests library by python, in order to install requests if you have pip installed install it like this:</p>
<pre><code>pip install requests
</code></pre>
<p>Now, lest go through some examples of using the Requests library, the documentation can be found <a href="http://docs.python-requests.org/en/master/" rel="nofollow">here</a>.</p>
<p>HTTP Get Request. So for this example, you call the get function from the request library, give the url as parameter, then you can print out the text from the touple that is returned. Since GET will return something, it will generally be in the text portion of the touple allowing you to print it.</p>
<pre><code>r = requests.get('http://urlhere.com/apistuffhere')
print(r.text)
</code></pre>
<p>HTTP POST: Posting to a url, depending on how the API was set up will return something, it generally does for error handling, but you also have to pass in parameters. Here is an example for a POST request to a new user entry. And again, you can print the text from the touple to check the response from the API</p>
<pre><code>payload = {'username': 'myloginname', 'password': 'passwordhere'}
r = requests.post('https://testlogin.com/newuserEntry', params=payload)
print(r.text)
</code></pre>
<p>Alternatively you can print just r and it should return you a response 200 which should be successful. </p>
<p>For PUT: You have to keep in mind put responses can not be cacheable, so you can post data to the PUT url, but you will not know if there is an error or not but use the same syntax as POST. I have not tried to print out the text response in a PUT request using the Request library as I don't use PUT in any API I write. </p>
<pre><code>requests.put('http://urlhere.com/putextension')
</code></pre>
<p>Now for implementing this into your code, you already have the base of the url, in your post for the login just do:</p>
<pre><code>payload = {'username': USERNAME, 'passwd':PASSWORD}
r = requests.post('https://loginurlhere.com/', params=payload)
#check response by printing text
print (r.text)
</code></pre>
<p>As for putting data to an extension of your api, let us assume you already have a payload variable ready with the info you need, for example the API device extension:</p>
<pre><code>requests.put(API_DEVICE, params=payload)
</code></pre>
<p>And that should PUT to the url. If you have any questions comment below and I can answer them if you would like. </p>
| 1 |
2016-09-23T19:05:08Z
|
[
"python",
"api",
"put"
] |
Getting 403 (Forbidden) when trying to send POST to set_language view in Django
| 39,667,647 |
<p>I'm new to Django and am trying to create a small website where I click on a flag and the language changes. I'm using django i18n for that:</p>
<p><strong>urls.py</strong></p>
<pre><code>from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [url(r'^i18n/', include('django.conf.urls.i18n'))]
urlpatterns += i18n_patterns(
url(r'^$', views.home, name='home'),
)
</code></pre>
<p>The problem is, when I run the following code:</p>
<p><strong>templetatags.py</strong></p>
<pre><code>@register.simple_tag
def test():
r = requests.post('http://localhost:8000/i18n/setlang/', data = {'lang':'en', 'next' : '/'})
print r.status_code
</code></pre>
<p><strong>home.html</strong></p>
<pre><code><div id='country_flags'>
<a hreflang="en" href="{% test %}"><img id='en' src='{% static "mysyte/images/gb.png" %}'></a>
</div>
</code></pre>
<p>the result of r.status_code is 403.</p>
<p>What am I doing wrong?</p>
| -1 |
2016-09-23T18:48:26Z
| 39,676,214 |
<p>Any POST request in django requires you to send the CSRF-Cookie by default. Your options around this:</p>
<ul>
<li>Don't use a POST request. Use GET instead.</li>
<li>Send the CSRF-Token with the request. <a href="https://docs.djangoproject.com/en/1.9/ref/csrf/" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/csrf/</a></li>
<li>use the decorator <code>@csrf_exempt</code> to remove any csrf-protection from a view (in your case the view for <code>http://localhost:8000/i18n/setlang/</code>)</li>
<li>don't send a request to your own app. use a link for the user to click on. probably your best option.</li>
</ul>
<blockquote>
<p>Note:
if you want to use the decorator w/ a class-based view, decorate the dispatch() function of that view</p>
</blockquote>
| 0 |
2016-09-24T12:14:36Z
|
[
"python",
"django",
"internationalization",
"django-i18n"
] |
profiler: can I find what calls my function?
| 39,667,657 |
<p>I'm working on a tool to visualize Python profile traces, and to do that, it would be useful to know what line a function is called from.</p>
<p>Suppose I have the following simple program:</p>
<pre><code>import time
def my_sleep(x):
time.sleep(x)
def main():
my_sleep(1)
my_sleep(2)
main()
</code></pre>
<p>If I run cProfile on it (<code>python -m cProfile -o a.data a.py</code>), I get a marshaled file containing the following data structure:</p>
<pre><code> ('a.py', 3, 'my_sleep'): (2,
2,
1.4999999999999999e-05,
3.00576,
{('a.py', 6, 'main'): (2,
2,
1.4999999999999999e-05,
3.00576)}),
</code></pre>
<p>Essentially, this says that <code>my_sleep()</code> is called twice by <code>main()</code> on line 6, and this adds up to slightly over 3 seconds.</p>
<p>Is there any way to find out what line it's being called from, and not just what function? So in this case, <code>my_sleep()</code> is called on line 7 for 1 second, and line 8 for 2 seconds.</p>
| 0 |
2016-09-23T18:49:10Z
| 39,667,800 |
<p>You may use <a href="https://docs.python.org/3/library/sys.html#sys._getframe" rel="nofollow"><code>sys._getframe(1)</code></a> in order to know the caller like so:</p>
<pre><code>import sys
def my_sleep():
print("Line #" + str(sys._getframe(1).f_lineno))
time.sleep(x)
</code></pre>
<p>Keep in mind doing things like that are usually not encouraged but if it's just temporary that's fine I guess.</p>
| 0 |
2016-09-23T18:58:53Z
|
[
"python",
"performance",
"profiling"
] |
How to resolve ImportError: no module named tarfile
| 39,667,732 |
<p>I am not able to use tarfile module in my python script.</p>
<p>When i run the script i am getting error "ImportError: no module named tarfile"</p>
<p>if i remove "import tarfile" then its failing at tarfile.open;
Error says--NameError: tarfile</p>
<pre><code>def make_tarfile(output_filename, source_dir):
tar = tarfile.open(output_filename, "w:gz")
#tar.add(source_dir, arcname=os.path.basename(source_dir))
tar.add(source_dir)
tar.close()
</code></pre>
<p>The same thing happening for subprocess module also.
I have verified the modules and they exists. Note that all the modules are working in python console or at command line</p>
<p>Python Version#2.6</p>
<p>==code==</p>
<h1>!usr/bin/python</h1>
<pre><code>from java.io import FileInputStream
#import subprocess
import os
import time as systime
import datetime
import shutil
import sys
print sys.path
import tarfile
import socket
def weblogicPassChange(dName,aUrl,aUser,aServerName,mServerName,aPort,oAdminPassword,nAdminPassword):
print '############################################################'
print ' Changing the admin password for :', dName
print '############################################################'
print ' '
print '####'
print 'dname : =',dName
print 'aUrl :=',aUrl
print 'aUser :=',aUser
print 'aServerName :=',aServerName
print 'mServerName :=',mServerName
print 'aPort :=',aPort
print 'oAdminPassword :=',oAdminPassword
print 'nAdminPassword :=',nAdminPassword
print '####'
connect(aUser,oAdminPassword,aUrl+':'+aPort)
cd('/SecurityConfiguration/'+dName+'/Realms/myrealm/AuthenticationProviders/DefaultAuthenticator')
cmo.resetUserPassword(aUser,nAdminPassword)
print '++++++++++++ +++++++++++ +++++++++++ +++++++++++ +++++++++++ +++++++++++ +++++++++++'
print '******* Congrates!!! ', dName , ' Admin Password Changed Successfully ********'
print '++++++++++++ +++++++++++ +++++++++++ +++++++++++ +++++++++++ +++++++++++ +++++++++++'
print ' '
disconnect()
print ' '
print '#### Connecting Using New Credentials..... ####'
print ' '
connect(aUser,nAdminPassword,aUrl+':'+aPort)
print '#### Successfully Connected Using New Credentials !!!! ####'
print ' '
domainRuntime()
bean =getMBean('ServerRuntimes/' + mServerName)
if bean:
print ' '
print 'Shutting down the Manage Server: osb_server1'
shutdown(mServerName,'Server')
else:
print ' '
print 'Server ',mServerName,' is not running'
print ' '
disconnect()
print ' '
print '#### Changing Admin Password in boot.properties file ####'
print ' '
text_file=open('/oraapp/config/domains/'+dName+'/servers/'+aServerName+'/security/boot.properties','w')
text_file.write('#' + systime.strftime("%a")+' ' +systime.strftime("%b")+' '+systime.strftime("%d")+' '+systime.strftime("%H")+':'+systime.strftime("%M")+':'+systime.strftime("%S")+' '+systime.strftime("%Z")+' '+systime.strftime("%Y")+"\n")
text_file.write("username" +"=" + aUser + "\n")
text_file.write("password"+"=" + nAdminPassword)
text_file.close()
print ' '
print '#### username and password updated in boot.properties ####'
print ' '
shutil.copyfile('/oraapp/config/domains/'+dName+'/servers/'+aServerName+'/security/boot.properties','/oraapp/config/domains/'+dName+'/servers/'+mServerName+'/data/nodemanager/boot.properties')
print ' '
print 'Copied boot.properties to manage server location ManageServerHome/date/nodemanager'
print ' '
print '### Calling stopWeblogic.sh file.....!!!!!! ######'
print ' '
os.system('.././config/domains/eapdomain/bin/stopWebLogic.sh')
print ' '
print 'Successfully changed weblogic password to',nAdminPassword
print ' '
print 'Test copy SCP function'
print ' '
string = 'scp /oraapp/config/domains/'+dName+'/servers/'+aServerName+'/security/test.properties'+' '+'s-fmwadmin@gaxgpoa163vd:/oraapp/config/domains/osbdomain1/servers/AdminServer/security'
print 'string value is = ',string
os.system('scp /oraapp/config/domains/'+dName+'/servers/'+aServerName+'/security/test.properties'+' '+'s-fmwadmin@gaxgpoa163vd:/oraapp/config/domains/osbdomain1/servers/AdminServer/security')
print ' '
print 'Copied successfully'
def envDetail(eName):
propInputStream = FileInputStream(eName+'_'+'domainDetails.properties')
configProps = Properties()
configProps.load(propInputStream)
domainName=configProps.get("domain.name")
adminUrl = configProps.get("domain.admin.url")
adminUser = configProps.get("domain.admin.username")
adminPort = configProps.get("domain.admin.port")
adminServerName = configProps.get("domain.adminServer.name")
mgrServerName = configProps.get("domain.mgrServer.name")
oldAdminPassword = configProps.get("domain.admin.OLD.password")
newAdminPassword = configProps.get("domain.admin.NEW.password")
fmw_home = configProps.get("domain.middlehome")
filename='/oraapp/backup/EAP_PRODUCT'+'_'+socket.gethostname()+'_'+systime.strftime("%d")+'-'+systime.strftime("%B")+'-'+systime.strftime("%Y")+'-'+systime.strftime("%T")+'.tar.gz'
make_tarfile(filename,fmw_home)
print 'Calling function weblogicPassChange()'
print ' '
weblogicPassChange(domainName,adminUrl,adminUser,adminServerName,mgrServerName,adminPort,oldAdminPassword,newAdminPassword)
def make_tarfile(output_filename, source_dir):
tar = tarfile.open(output_filename, "w:gz")
#tar.add(source_dir, arcname=os.path.basename(source_dir))
tar.add(source_dir)
tar.close()
print '#########################################################################################'
print ' Enter the name of the environment as given below to change the password :'
print '#########################################################################################'
print 'For EAPDOMAIN enter EAP'
print 'For SOCODEV/QA enter QA'
print 'For SOCOUA/UAT enter UAT'
print 'For PRODUCTION enter PROD'
print '############################################################'
print ' '
env = raw_input('Please enter your name: ')
if env == 'EAP':
print 'EAPDOMAIN'
print env
envDetail(env)
elif env == 'QA':
print 'SOCODEV'
elif env == 'UAT':
print 'SOCOUA'
elif env == 'PROD':
print 'PRODUCTION'
print ' '
print 'Kindly Restart the Admin and Manager servers of ',env,' Domain'
</code></pre>
<p>Regards,
TJ</p>
| 0 |
2016-09-23T18:54:20Z
| 39,669,613 |
<p>I need 50 reputation to comment, so I'll leave an answer instead:</p>
<p>Could you add the following line to your script:</p>
<pre><code>print sys.version
</code></pre>
<p>Just to make absolutely sure the Python version running the script is the same as the one you use as an interpreter. Like people said, maybe an environment variable is overwritten somewhere, causing a wrong version of Python to run the script.</p>
| 1 |
2016-09-23T21:10:55Z
|
[
"python",
"jython"
] |
How can I use descriptors for non-static methods?
| 39,667,904 |
<p>I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.</p>
<p>If I have</p>
<p>Normal use, considering that the method(param) returns an object</p>
<pre><code>class SomeClass():
property = method(param)
</code></pre>
<p>I can then do:</p>
<pre><code>instance = SomeClass()
instance.property = 3
</code></pre>
<p>and be able to have that setting handled by the the class of which property is an instance.</p>
<p>Now, if I instead have</p>
<pre><code>class SomeClass():
def__init__(self):
self.property = method(param)
</code></pre>
<p>and I do:</p>
<pre><code>instance = SomeClass()
instance.property = 3
</code></pre>
<p>That code does not work, and I overwrite the reference to the object created by method(param) with 3, instead of having that setting handled by the descriptor.</p>
<p>Is there a way I can use descriptors without static methods? In essence, I need to be able to create several instances of the class, each with its own unique properties that can be altered using the convenient descriptor method. Is that possible?</p>
<p>Python version: 2.7</p>
<p>Thanks!</p>
| 0 |
2016-09-23T19:06:06Z
| 39,668,135 |
<p>Considering <code>method(param)</code> returns a descriptor, you may invoke it manually with a property like so:</p>
<pre><code>class SomeClass(object):
def __init__(self):
self._descriptor = method(param)
@property
def my_attribute(self):
return self._descriptor.__get__(self, self.__class__)
@my_attribute.setter
def my_attribute(self, value):
self._descriptor.__set__(self, value)
</code></pre>
<p>This will allow you to create instance-specific descriptors instead of class-level descriptors.</p>
<p>I still do not see the reason for you to do that as descriptors should usuallty be class-level. That's their point. Else they are just regular objects which you can call using properties.</p>
| 0 |
2016-09-23T19:21:24Z
|
[
"python",
"python-2.7"
] |
How can I use descriptors for non-static methods?
| 39,667,904 |
<p>I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.</p>
<p>If I have</p>
<p>Normal use, considering that the method(param) returns an object</p>
<pre><code>class SomeClass():
property = method(param)
</code></pre>
<p>I can then do:</p>
<pre><code>instance = SomeClass()
instance.property = 3
</code></pre>
<p>and be able to have that setting handled by the the class of which property is an instance.</p>
<p>Now, if I instead have</p>
<pre><code>class SomeClass():
def__init__(self):
self.property = method(param)
</code></pre>
<p>and I do:</p>
<pre><code>instance = SomeClass()
instance.property = 3
</code></pre>
<p>That code does not work, and I overwrite the reference to the object created by method(param) with 3, instead of having that setting handled by the descriptor.</p>
<p>Is there a way I can use descriptors without static methods? In essence, I need to be able to create several instances of the class, each with its own unique properties that can be altered using the convenient descriptor method. Is that possible?</p>
<p>Python version: 2.7</p>
<p>Thanks!</p>
| 0 |
2016-09-23T19:06:06Z
| 39,668,294 |
<p>Descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods.</p>
<p>To recap, functions have a <code>__get__()</code> method so that they can be converted to a method when accessed as attributes. The non-data descriptor transforms an <code>obj.f(*args)</code> call into <code>f(obj, *args)</code>. Calling <code>klass.f(*args)</code> becomes <code>f(*args)</code>.</p>
<p>This chart summarizes the binding and its two most useful variants:</p>
<pre class="lang-none prettyprint-override"><code>Transformation Called from an Object Called from a Class
function f(obj, *args) f(*args)
staticmethod f(*args) f(*args)
classmethod f(type(obj), *args) f(klass, *args)
</code></pre>
<p>Static methods return the underlying function without changes. Calling either c.f or C.f is the equivalent of a direct lookup into</p>
<p><code>object.__getattribute__(c, "f") or object.__getattribute__(C, "f").</code>
As a result, the function becomes identically accessible from either an object or a class.</p>
<p>Good candidates for static methods are methods that do not reference the self variable.</p>
<pre><code>class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print 'Retrieving', self.name
return self.val
def __set__(self, obj, val):
print 'Updating', self.name
self.val = val
>>> class MyClass(object):
... x = RevealAccess(10, 'var "x"')
... y = 5
...
>>> m = MyClass()
>>> m.x
Retrieving var "x"
10
>>> m.x = 20
Updating var "x"
>>> m.x
Retrieving var "x"
20
>>> m.y
5
</code></pre>
| 1 |
2016-09-23T19:32:07Z
|
[
"python",
"python-2.7"
] |
How can I use descriptors for non-static methods?
| 39,667,904 |
<p>I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.</p>
<p>If I have</p>
<p>Normal use, considering that the method(param) returns an object</p>
<pre><code>class SomeClass():
property = method(param)
</code></pre>
<p>I can then do:</p>
<pre><code>instance = SomeClass()
instance.property = 3
</code></pre>
<p>and be able to have that setting handled by the the class of which property is an instance.</p>
<p>Now, if I instead have</p>
<pre><code>class SomeClass():
def__init__(self):
self.property = method(param)
</code></pre>
<p>and I do:</p>
<pre><code>instance = SomeClass()
instance.property = 3
</code></pre>
<p>That code does not work, and I overwrite the reference to the object created by method(param) with 3, instead of having that setting handled by the descriptor.</p>
<p>Is there a way I can use descriptors without static methods? In essence, I need to be able to create several instances of the class, each with its own unique properties that can be altered using the convenient descriptor method. Is that possible?</p>
<p>Python version: 2.7</p>
<p>Thanks!</p>
| 0 |
2016-09-23T19:06:06Z
| 39,669,564 |
<p>Properties are "computed attributes". Properties are implemented using descriptors. If an object's attribute is looked up and a descriptor object is found, the descriptor's getter function will compute the value. </p>
<p><strong>This special rule is valid only at the class level</strong>.</p>
<p>That's why:</p>
<pre><code>class SomeClass():
property = <a property object here>
</code></pre>
<p>defines a property (computed attribute) for all <code>SomeClass</code> instances, but:</p>
<pre><code>class SomeClass():
def__init__(self):
self.property = <a property object here>
</code></pre>
<p>defines an ordinary attribute which happens to be of property object type, but is not treated specially in any way. Its getters and setters are ignored (unless called explicitely by the user code, of course).</p>
<hr>
<p>There is no other way of using descriptors and properties as setting them in the class and not in an instance.</p>
<p>UPDATE - Example:</p>
<p>Small example: instead of creating several instances each with its own descriptor (approach which does not work), a new subclass is instantiated every time.</p>
<pre><code>class BaseClass:
pass
_class_number = 0
def class_factory(prop):
global _class_number
_class_number += 1
return type('Class' + str(_class_number), (BaseClass,), dict(prop=prop))
c1 = class_factory(property(fget=lambda self: "property1"))()
print(c1.prop)
c2 = class_factory(property(fget=lambda self: "property2"))()
print(c2.prop)
</code></pre>
| 0 |
2016-09-23T21:06:45Z
|
[
"python",
"python-2.7"
] |
How can I use descriptors for non-static methods?
| 39,667,904 |
<p>I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.</p>
<p>If I have</p>
<p>Normal use, considering that the method(param) returns an object</p>
<pre><code>class SomeClass():
property = method(param)
</code></pre>
<p>I can then do:</p>
<pre><code>instance = SomeClass()
instance.property = 3
</code></pre>
<p>and be able to have that setting handled by the the class of which property is an instance.</p>
<p>Now, if I instead have</p>
<pre><code>class SomeClass():
def__init__(self):
self.property = method(param)
</code></pre>
<p>and I do:</p>
<pre><code>instance = SomeClass()
instance.property = 3
</code></pre>
<p>That code does not work, and I overwrite the reference to the object created by method(param) with 3, instead of having that setting handled by the descriptor.</p>
<p>Is there a way I can use descriptors without static methods? In essence, I need to be able to create several instances of the class, each with its own unique properties that can be altered using the convenient descriptor method. Is that possible?</p>
<p>Python version: 2.7</p>
<p>Thanks!</p>
| 0 |
2016-09-23T19:06:06Z
| 39,693,584 |
<p>guys,</p>
<p>Thanks for the help. Out of many great suggestions, I decided to wrap the <strong>set</strong> and <strong>get</strong> methods, thus losing the practicality of descriptors, while keeping the practicality of having a module completely programmed for me. I simply extended the class "PageElement" and created two new methods get() and set(), which call their correspondent implementations:</p>
<pre><code>def get(self):
return self.__get__(self.owner_page, self.owner_page.__class__)
def set(self, value):
self.__set__(self.owner_page, value)
</code></pre>
<p>Thanks for the help! I opened up my eyes to a lot of details in the language that I still do not know. And I will keep digging.</p>
| 0 |
2016-09-26T01:38:39Z
|
[
"python",
"python-2.7"
] |
Sum even and odd number output not correct
| 39,667,976 |
<blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest number is 5 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 6 6 <strong>[x]</strong></li>
</ul>
</blockquote>
<p><strong>INPUT 2</strong></p>
<p>1 2 3 4 </p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 6 and 4 <strong>[â]</strong></li>
<li>The difference between biggest and smallest number is 3 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 4 4 <strong>[X]</strong></li>
</ul>
</blockquote>
</blockquote>
<p>what is wrong with my code? can someone enlighten me???</p>
<pre><code>even_sum, odd_sum = 0,0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
for num in numbers:
if num%2 ==0:
evencount = len(numbers)
even_sum += num
else:
oddcount = len(numbers)
odd_sum += num
max = max(numbers)
min = min(numbers)
difference = max - min
print numbers
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " " + str(oddcount)
</code></pre>
| -3 |
2016-09-23T19:10:41Z
| 39,668,030 |
<p>Your <code>else</code> is aligned directly under the <code>for</code> which can also take an <code>else</code>, so the sum of even numbers is taken correctly while the sum of odd numbers is the last value of <code>num</code> in the for loop. You should move your <code>else</code> block to align with the <code>if</code>.</p>
| 4 |
2016-09-23T19:14:02Z
|
[
"python"
] |
Sum even and odd number output not correct
| 39,667,976 |
<blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest number is 5 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 6 6 <strong>[x]</strong></li>
</ul>
</blockquote>
<p><strong>INPUT 2</strong></p>
<p>1 2 3 4 </p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 6 and 4 <strong>[â]</strong></li>
<li>The difference between biggest and smallest number is 3 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 4 4 <strong>[X]</strong></li>
</ul>
</blockquote>
</blockquote>
<p>what is wrong with my code? can someone enlighten me???</p>
<pre><code>even_sum, odd_sum = 0,0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
for num in numbers:
if num%2 ==0:
evencount = len(numbers)
even_sum += num
else:
oddcount = len(numbers)
odd_sum += num
max = max(numbers)
min = min(numbers)
difference = max - min
print numbers
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " " + str(oddcount)
</code></pre>
| -3 |
2016-09-23T19:10:41Z
| 39,668,050 |
<p>dont have enough rep to comment, but I think the answer is probalby that your else statement is not properly indented...</p>
<p>Also I think the logic on your even and odd count is off, I think it should be something more like:</p>
<p><code>evencount = evencount+1</code></p>
<p>Try this:</p>
<pre><code>even_sum, odd_sum = 0,0
evencount, oddcount = 0,0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
for num in numbers:
if num%2 ==0:
evencount = evencount +1# len(numbers)
even_sum += num
else:
oddcount = oddcount+1#len(numbers)
odd_sum += num
max = max(numbers)
min = min(numbers)
difference = max - min
print numbers
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " " + str(oddcount)
</code></pre>
| 1 |
2016-09-23T19:15:42Z
|
[
"python"
] |
Sum even and odd number output not correct
| 39,667,976 |
<blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest number is 5 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 6 6 <strong>[x]</strong></li>
</ul>
</blockquote>
<p><strong>INPUT 2</strong></p>
<p>1 2 3 4 </p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 6 and 4 <strong>[â]</strong></li>
<li>The difference between biggest and smallest number is 3 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 4 4 <strong>[X]</strong></li>
</ul>
</blockquote>
</blockquote>
<p>what is wrong with my code? can someone enlighten me???</p>
<pre><code>even_sum, odd_sum = 0,0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
for num in numbers:
if num%2 ==0:
evencount = len(numbers)
even_sum += num
else:
oddcount = len(numbers)
odd_sum += num
max = max(numbers)
min = min(numbers)
difference = max - min
print numbers
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " " + str(oddcount)
</code></pre>
| -3 |
2016-09-23T19:10:41Z
| 39,668,069 |
<p>Your problem is in these lines</p>
<pre><code>evencount = len(numbers)
oddcount = len(numbers)
</code></pre>
<p>In both cases, you end up saying </p>
<pre><code>evencount = all numbers i've encountered
oddcount = all numbers i've encountered
</code></pre>
<p>that is why you get <code>4,4</code> for evencount and oddcount, since you have 4 numbers as input.</p>
<p>change it to</p>
<pre><code>evencount = 0
oddcount = 0
for num in numbers:
if num % 2 ==0:
evencount += 1
even_sum += num
else:
oddcount += 1
odd_sum += num
</code></pre>
| 3 |
2016-09-23T19:16:45Z
|
[
"python"
] |
Sum even and odd number output not correct
| 39,667,976 |
<blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest number is 5 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 6 6 <strong>[x]</strong></li>
</ul>
</blockquote>
<p><strong>INPUT 2</strong></p>
<p>1 2 3 4 </p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 6 and 4 <strong>[â]</strong></li>
<li>The difference between biggest and smallest number is 3 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 4 4 <strong>[X]</strong></li>
</ul>
</blockquote>
</blockquote>
<p>what is wrong with my code? can someone enlighten me???</p>
<pre><code>even_sum, odd_sum = 0,0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
for num in numbers:
if num%2 ==0:
evencount = len(numbers)
even_sum += num
else:
oddcount = len(numbers)
odd_sum += num
max = max(numbers)
min = min(numbers)
difference = max - min
print numbers
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " " + str(oddcount)
</code></pre>
| -3 |
2016-09-23T19:10:41Z
| 39,668,880 |
<p>You've received corrections to your code from other answers (namely <code>evencount += 1</code>), but just for some potential further investigations into the capabilities of the language here's another approach to the solution.</p>
<p>Python has a strong iterator algebra and in the itertools recipes is <code>partition</code> which splits a list into parts based on the condition, in fact the example given is splitting odd from even: <a href="https://docs.python.org/3.5/library/itertools.html#itertools-recipes" rel="nofollow">Itertools Recipes</a></p>
<p>So using this would look like:</p>
<pre><code>import itertools as it
s = "1 2 3 4 5 6"
numbers = list(map(int, s.split())) # Need `list` in Py3 okay to skip in Py2
# See itertools recipes
def partition(pred, iterable):
t1, t2 = it.tee(iterable)
return it.filterfalse(pred, t1), filter(pred, t2)
is_odd = lambda x: x%2
even, odd = map(list, partition(is_odd, numbers))
print("The summation of even and odd numbers are {} and {}".format(sum(even), sum(odd)))
print("The difference between biggest and smallest number is {}".format(max(numbers)-min(numbers)))
print("The count of even numbers and odd numbers are {} {}".format(len(even), len(odd)))
</code></pre>
<p>Result:</p>
<pre><code>The summation of even and odd numbers are 12 and 9
The difference between biggest and smallest number is 5
The count of even numbers and odd numbers are 3 3
</code></pre>
| 0 |
2016-09-23T20:16:45Z
|
[
"python"
] |
Sum even and odd number output not correct
| 39,667,976 |
<blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest number is 5 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 6 6 <strong>[x]</strong></li>
</ul>
</blockquote>
<p><strong>INPUT 2</strong></p>
<p>1 2 3 4 </p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 6 and 4 <strong>[â]</strong></li>
<li>The difference between biggest and smallest number is 3 <strong>[â]</strong></li>
<li>The count of even numbers and odd numbers are 4 4 <strong>[X]</strong></li>
</ul>
</blockquote>
</blockquote>
<p>what is wrong with my code? can someone enlighten me???</p>
<pre><code>even_sum, odd_sum = 0,0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
for num in numbers:
if num%2 ==0:
evencount = len(numbers)
even_sum += num
else:
oddcount = len(numbers)
odd_sum += num
max = max(numbers)
min = min(numbers)
difference = max - min
print numbers
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " " + str(oddcount)
</code></pre>
| -3 |
2016-09-23T19:10:41Z
| 39,672,378 |
<p>Problem is with following statements :</p>
<ul>
<li>evencount = len(numbers)</li>
<li>oddcount = len(numbers)</li>
<li>else indentation</li>
</ul>
<p>Solution is ::</p>
<pre><code>even_sum, odd_sum = 0,0
even_count,odd_count = 0,0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
for num in numbers:
if num%2 == 0:
even_sum = even_sum + num
even_count = even_count + 1
else:
odd_sum = odd_sum + num
odd_count = odd_count + 1
mx = max(numbers)
mn = min(numbers)
difference = mx - mn
print 'The summation of even %d and odd numbers are %d ' % (even_sum,odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(even_count) + " " + str(odd_count)
</code></pre>
| 0 |
2016-09-24T04:07:40Z
|
[
"python"
] |
Define a Django model that is shared among many apps
| 39,668,055 |
<p>How to define a generic Django model (that would perfectly fit in utility/common module), that is going to be used by many apps? I would prefer to define it outside an app, because semantically it does not belong to any of them.
Is it possible? How to deal with the migration of it outside the app?</p>
<p>More specifically, a Model for assigning the country of the user or organization:</p>
<pre><code>class Country(models.Model):
name = models.CharField(max_lenght=200)
</code></pre>
| -1 |
2016-09-23T19:15:50Z
| 39,668,238 |
<p>If the models don't belong to any app, they can certainly be declared in a separate app. I would create a 'global' app with models and views that you might use from other apps. Migrations would function as usual as long as you declare the new app with 'startapp newapp' etc.</p>
| 1 |
2016-09-23T19:28:17Z
|
[
"python",
"django",
"model-view-controller",
"model"
] |
Define a Django model that is shared among many apps
| 39,668,055 |
<p>How to define a generic Django model (that would perfectly fit in utility/common module), that is going to be used by many apps? I would prefer to define it outside an app, because semantically it does not belong to any of them.
Is it possible? How to deal with the migration of it outside the app?</p>
<p>More specifically, a Model for assigning the country of the user or organization:</p>
<pre><code>class Country(models.Model):
name = models.CharField(max_lenght=200)
</code></pre>
| -1 |
2016-09-23T19:15:50Z
| 39,669,373 |
<p>If it's something based on the users like in your example, consider <a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model" rel="nofollow">extending the user model</a>.</p>
| 0 |
2016-09-23T20:53:14Z
|
[
"python",
"django",
"model-view-controller",
"model"
] |
determine length (or number of digits) of every row in column
| 39,668,138 |
<p>I have a dataframe with columns that are <code>floats</code>. Some rows have <code>NaN</code> values.</p>
<p>I want to find rows where the length (or number of digits) of the number is <code>!=6</code>. </p>
<p>I tried the following:</p>
<pre><code>len(str(df['a'])) != 6
</code></pre>
<p>But this seems to only return only one Boolean value and not a Boolean for every row in the dataframe. </p>
<p>What is the correct way to do this? </p>
<p><strong>UPDATE</strong>:</p>
<p>Someone made a post with an answer similar to:</p>
<pre><code>df.query('a <= 10**5')
</code></pre>
<p>That seemed to work nicely. Now, I want to add an additional condition where column b is not null. How do I do that in the query() function. </p>
| 0 |
2016-09-23T19:21:32Z
| 39,668,323 |
<p>Cast it to a string and then use the string ops.</p>
<pre><code>df['a'].astype(str).str.len()
</code></pre>
<p>EDIT: To your more complete version, you might just go with:</p>
<pre><code>df[(df['a'].fillna(0) < 100000) & (pd.notnull(df[b]))]
</code></pre>
| 3 |
2016-09-23T19:34:45Z
|
[
"python",
"pandas"
] |
Python regex not matching
| 39,668,156 |
<p>I am trying to extract a file name using regex. File names are in the list <code>files</code> , the pattern to be matched is <code>songTitle</code>. </p>
<pre><code> files = listdir(curdir)
print("Pattern : %s" % songTitle)
for songs in files:
print(songs)
re_found = re.match(re.escape(songTitle) + r'.*\.mp3$', songs)
if re_found:
FileName = re_found.group()
print(FileName)
break
</code></pre>
<p>In this example </p>
<p><code>files</code> contains :</p>
<pre><code>['.DS_Store', '__init__.py', 'command_line.py', "Skrillex & Diplo - 'Mind' feat. Kai (Official Video)-fDrTbLXHKu8.mp3"]
</code></pre>
<p><code>songTitle</code> (Pattern to be matched) : <code>Skrillex & Diplo - 'Mind' feat. Kai (Official Video)</code></p>
<p>Output : </p>
<pre><code>Pattern : Jack à - Take à There feat. Kiesza [OFFICIAL VIDEO]
.DS_Store
__init__.py
command_line.py
Jack à - Take à There feat. Kiesza [OFFICIAL VIDEO]-C9slkeFXogU.mp3
Skrillex & Diplo - 'Mind' feat. Kai (Official Video)-fDrTbLXHKu8.mp3
</code></pre>
<p><strong>EDIT:</strong></p>
<p>I ran some tests and realised that the problem occurs due to non ascii characters. Such as the 'Ã' in this case.</p>
| 0 |
2016-09-23T19:23:22Z
| 39,668,250 |
<p>The regular expression actually looks fine, but the problem is in your indentation and in the if statement. Try this:</p>
<pre><code>files = listdir(curdir)
print(files)
print("Pattern : %s" %songTitle)
for songs in files:
re_found = re.match(re.escape(songTitle) + r'.*\.mp3$', songs)
if re_found:
FileName = re_found.group()
print(FileName)
break
</code></pre>
<p>Also, when writing regular expression literals, you should generally put an 'r' before the literal otherwise you'll need to escape the backslashes.</p>
| 0 |
2016-09-23T19:28:52Z
|
[
"python",
"regex"
] |
Python regex not matching
| 39,668,156 |
<p>I am trying to extract a file name using regex. File names are in the list <code>files</code> , the pattern to be matched is <code>songTitle</code>. </p>
<pre><code> files = listdir(curdir)
print("Pattern : %s" % songTitle)
for songs in files:
print(songs)
re_found = re.match(re.escape(songTitle) + r'.*\.mp3$', songs)
if re_found:
FileName = re_found.group()
print(FileName)
break
</code></pre>
<p>In this example </p>
<p><code>files</code> contains :</p>
<pre><code>['.DS_Store', '__init__.py', 'command_line.py', "Skrillex & Diplo - 'Mind' feat. Kai (Official Video)-fDrTbLXHKu8.mp3"]
</code></pre>
<p><code>songTitle</code> (Pattern to be matched) : <code>Skrillex & Diplo - 'Mind' feat. Kai (Official Video)</code></p>
<p>Output : </p>
<pre><code>Pattern : Jack à - Take à There feat. Kiesza [OFFICIAL VIDEO]
.DS_Store
__init__.py
command_line.py
Jack à - Take à There feat. Kiesza [OFFICIAL VIDEO]-C9slkeFXogU.mp3
Skrillex & Diplo - 'Mind' feat. Kai (Official Video)-fDrTbLXHKu8.mp3
</code></pre>
<p><strong>EDIT:</strong></p>
<p>I ran some tests and realised that the problem occurs due to non ascii characters. Such as the 'Ã' in this case.</p>
| 0 |
2016-09-23T19:23:22Z
| 39,668,625 |
<p>This works:</p>
<pre><code>files = listdir(curdir)
print("Pattern : %s" % songTitle)
for songs in files:
re_found = re.match(re.escape(songTitle) + r'.*\.mp3$', songs)
if re_found:
FileName = re_found.group()
print(FileName)
break
</code></pre>
| 0 |
2016-09-23T19:56:49Z
|
[
"python",
"regex"
] |
homography and image scaling in opencv
| 39,668,174 |
<p>I am calculating an homography between two images <code>img1</code> and <code>img2</code> (the images contain mostly one planar object, so the homography works well between them) using standard methods in OpenCV in python. Namely, I compute point matches between the images using sift and then call <code>cv2.findHomography</code>.</p>
<p>To make the computation faster I scale down the two images into <code>small1</code> and <code>small2</code> and perform the calculations on these smaller copies, so I calculate the homography matrix <code>H</code>, which maps <code>small1</code> into <code>small2</code>.
However, at the end, I would like to use calculate the homography matrix to project one full-size image <code>img1</code> onto the other the full-size image <code>img2</code>. </p>
<p>I thought I could simply transform the homography matrix <code>H</code> in the following way <code>H_full_size = A * H * A_inverse</code> where <code>A</code> is the matrix representing the scaling from <code>img1</code> to <code>small1</code> and <code>A_inverse</code> is its inverse.
However, that does not work. If I apply <code>cv2.warpPerspective</code> to the scaled down image <code>small1</code> with <code>H</code>, everything goes as expected and the result (largely) overlaps with <code>small2</code>. If I apply <code>cv2.warpPerspective</code> to the full size image <code>img1</code> with <code>H_full_size</code> the result does not map to <code>img2</code>.</p>
<p>However, if I project the point matches (detected on the scaled down images) using <code>A</code> (using something like <code>projected_pts = cv2.perspectiveTransform(pts, A)</code>) and then I calculate <code>H_full_size</code> from these, everything works fine. </p>
<p>Any idea what I could be doing wrong here?</p>
| 0 |
2016-09-23T19:24:26Z
| 39,668,864 |
<p>The way I see it, the problem is that homography applies a perspective projection which is a non linear transformation (it is linear only while homogeneous coordinates are being used) that cannot be represented as a normal transformation matrix. Multiplying such perspective projection matrix with some other transformations therefore produces undesirable results.</p>
<p>You can try multiplying your original matrix H element wise with:</p>
<p>S = [1,1,scale ; 1,1,scale ; 1/scale, 1/scale, 1]</p>
<p>H_full_size = S * H</p>
<p>where scale is for example 2, if you decreased the size of original image by 2.</p>
| 0 |
2016-09-23T20:14:59Z
|
[
"python",
"opencv",
"coordinate-transformation",
"homography"
] |
homography and image scaling in opencv
| 39,668,174 |
<p>I am calculating an homography between two images <code>img1</code> and <code>img2</code> (the images contain mostly one planar object, so the homography works well between them) using standard methods in OpenCV in python. Namely, I compute point matches between the images using sift and then call <code>cv2.findHomography</code>.</p>
<p>To make the computation faster I scale down the two images into <code>small1</code> and <code>small2</code> and perform the calculations on these smaller copies, so I calculate the homography matrix <code>H</code>, which maps <code>small1</code> into <code>small2</code>.
However, at the end, I would like to use calculate the homography matrix to project one full-size image <code>img1</code> onto the other the full-size image <code>img2</code>. </p>
<p>I thought I could simply transform the homography matrix <code>H</code> in the following way <code>H_full_size = A * H * A_inverse</code> where <code>A</code> is the matrix representing the scaling from <code>img1</code> to <code>small1</code> and <code>A_inverse</code> is its inverse.
However, that does not work. If I apply <code>cv2.warpPerspective</code> to the scaled down image <code>small1</code> with <code>H</code>, everything goes as expected and the result (largely) overlaps with <code>small2</code>. If I apply <code>cv2.warpPerspective</code> to the full size image <code>img1</code> with <code>H_full_size</code> the result does not map to <code>img2</code>.</p>
<p>However, if I project the point matches (detected on the scaled down images) using <code>A</code> (using something like <code>projected_pts = cv2.perspectiveTransform(pts, A)</code>) and then I calculate <code>H_full_size</code> from these, everything works fine. </p>
<p>Any idea what I could be doing wrong here?</p>
| 0 |
2016-09-23T19:24:26Z
| 39,674,477 |
<p>I think your wrong assumption in this passage </p>
<blockquote>
<p><code>H_full_size = A * H * A_inverse</code> where <code>A</code> is the matrix representing the scaling from img1 to small1</p>
</blockquote>
<p>derives from humans "love" from symmetry. Out of the joke, your formula is correct after introducing an hypotesis that I am going to expose.
If I start from this consideration (this is quite equivalent of the cv2 function cv2,warpPerspective - the formula is true with respect to a scale factor)</p>
<pre><code>img2 = H_fullsize*img1
</code></pre>
<p>you can derive your own formula. </p>
<pre><code>small2 = B*img2
small1 = A*img1
small2 = H*small1
B*img2 = H*A*img1
</code></pre>
<p>that is quite equivalent (if B is invertible)</p>
<pre><code>img2 = B_inverse*H*A*img1
</code></pre>
<p>and the question became</p>
<pre><code>H_fullsize = B_inverse*H*A
</code></pre>
<p>So the question became: are you sure that the scale matrix from <code>img1</code> to <code>small1</code> is equal to the scale matrix from <code>img2</code> to <code>small2</code>? (or at least they differs of a constant scale factor value) ?</p>
<p>If it is your case, remember that, as you write, homograpy works <strong>only</strong> between planar images (or in a case of pure rotation). Assuming you have 80% SIFT points on a plane and 20% points out of this plane, the homograpy considers all this points as they were in a plane and find the transformation H that minimize errors (<em>and not the perfect one only for the 80% points in a plane</em>).
Also errors that are evident in a 1080p resolution image could be not so evident in a 320p resolution image (you do not specify <strong>how much</strong> you reduce the images!) </p>
| 0 |
2016-09-24T08:55:45Z
|
[
"python",
"opencv",
"coordinate-transformation",
"homography"
] |
Dataframe column showing half hour intervals
| 39,668,193 |
<p>I can create an hour of day column in pandas as follows:</p>
<pre><code>data['hod'] = [r.hour for r in data.index]
</code></pre>
<p>This allows me to easily check stats on my data based on the time of day. How can I create a similar column showing every half hour? </p>
<p>Example data:</p>
<pre><code> Low High Open hod
Timestamp
2014-03-04 09:30:00 1783.50 1786.75 1783.50 9
2014-03-04 09:45:00 1784.50 1788.75 1784.50 9
2014-03-04 10:00:00 1785.75 1789.50 1788.25 10
2014-03-04 10:15:00 1787.75 1789.50 1788.50 10
2014-03-04 10:30:00 1788.25 1791.25 1789.00 10
... ... ... ... ...
2016-06-10 15:00:00 2079.50 2082.00 2082.00 15
2016-06-10 15:15:00 2079.50 2083.00 2079.75 15
2016-06-10 15:30:00 2082.50 2084.25 2082.75 15
2016-06-10 15:45:00 2083.50 2088.25 2083.50 15
2016-06-10 16:00:00 2085.75 2088.25 2086.25 16
</code></pre>
<p><strong>Desired output.</strong></p>
<p>I would like a new column 'hod2' showing times every half hour as follows:</p>
<pre><code> Low High Open hod2
Timestamp
2014-03-04 09:30:00 1783.50 1786.75 1783.50 9:30
2014-03-04 09:45:00 1784.50 1788.75 1784.50 9:30
2014-03-04 10:00:00 1785.75 1789.50 1788.25 10:00
2014-03-04 10:15:00 1787.75 1789.50 1788.50 10:00
2014-03-04 10:30:00 1788.25 1791.25 1789.00 10:30
</code></pre>
| 1 |
2016-09-23T19:25:26Z
| 39,668,441 |
<p>Since your index is a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow"><code>DatetimeIndex</code></a>, it has certain attributes that we can access like <code>hour</code>. Another attribute you may find useful for your task is <code>minute</code>. Something like this should work for displaying half-hour increments.</p>
<pre><code>data['hod2'] = ['{0}:{1}'.format(r.hour, '30' if round(float(r.minute)/60) == 1 else '00') for r in data.index]
</code></pre>
<h1>EDIT</h1>
<p>A much cleaner version of this was suggested by <a href="http://stackoverflow.com/users/509824/alberto-garcia-raboso">Alberto Garcia-Raboso</a> in the comments below:</p>
<pre><code>data['hod2'] = ['{}:{:02d}'.format(r.hour, (r.minute//30)*30) for r in data.index]
</code></pre>
| 2 |
2016-09-23T19:43:56Z
|
[
"python",
"pandas"
] |
pandas: sort alphabetically if rows have same rank
| 39,668,202 |
<p>Say I have a dataframe with two rows that have the same value:</p>
<pre><code>testdf = pd.DataFrame({'a': ['alpha','beta','theta','delta','epsilon'],'b':[1,2,3,3,4]})
a b
0 alpha 1
1 beta 2
2 theta 3
3 delta 3
4 epsilon 4
</code></pre>
<p>Now I want to sort them based on column B:</p>
<pre><code>testdf['rank'] = testdf['b'].rank(ascending=False)
a b rank
0 alpha 1 5.0
1 beta 2 4.0
2 theta 3 2.5
3 delta 3 2.5
4 epsilon 4 1.0
</code></pre>
<p>Since rows 2 and 3 have the same rank, I'd like to arrange them in alphabetical order for the viewer:</p>
<pre><code> a b rank
0 alpha 1 5.0
1 beta 2 4.0
3 delta 3 2.5
2 theta 3 2.5
4 epsilon 4 1.0
</code></pre>
<p>But I'm not sure how to do this. Maybe I could group them by rank and order them...? I'm not sure how to do that in-place, though.</p>
| 1 |
2016-09-23T19:25:50Z
| 39,668,293 |
<p>It's possible to sort by more than one column using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a>, what you want is to sort by <code>rank</code> first, then by the <code>a</code> column, and if you want it to happen inplace, we use <code>inplace=True</code> like below:</p>
<pre><code>In [14]: testdf.sort_values(['rank', 'a'], ascending=[False, True], inplace=True)
In [15]: testdf
Out[15]:
a b rank
0 alpha 1 5.0
1 beta 2 4.0
3 delta 3 2.5
2 theta 3 2.5
4 epsilon 4 1.0
</code></pre>
<p>Which is the result you want and inplace, if you don't use <code>inplace=True</code> the resulting dataframe will be returned from the operation.</p>
| 1 |
2016-09-23T19:32:06Z
|
[
"python",
"pandas"
] |
python: regex - catch variable number of groups
| 39,668,228 |
<p>I have a string that looks like:</p>
<pre><code>TABLE_ENTRY.0[hex_number]= <FIELD_1=hex_number, FIELD_2=hex_number..FIELD_X=hex>
TABLE_ENTRY.1[hex_number]= <FIELD_1=hex_number, FIELD_2=hex_number..FIELD_Y=hex>
</code></pre>
<p>number of fields is unknown and varies from entry to entry, I want to capture
each entry separately with all of its fields and their values.</p>
<p>I came up with:</p>
<pre><code>([A-Z_0-9\.]+\[0x[0-9]+\]=)(0x[0-9]+|0):\s+<(([A-Z_0-9]+)=(0x[0-9]+|0))
</code></pre>
<p>which matches the table entry and the first field, but I dont know how to account for variable number of fields.</p>
<p>for input:</p>
<pre><code>ENTRY_0[0x130]=0: <FIELD_0=0, FIELD_1=0x140... FIELD_2=0xff3>
</code></pre>
<p>output should be:</p>
<pre><code>ENTRY 0:
FIELD_0=0
FIELD_1=0x140
FIELD_2=ff3
ENTRY 1:
...
</code></pre>
| 0 |
2016-09-23T19:27:17Z
| 39,668,332 |
<p>Use a capture group for match unfit lengths:</p>
<pre><code>([A-Z_0-9\.]+\[0x[0-9]+\]=)\s+<(([A-Z_0-9]+)=(0x[0-9]+|0),\s?)*([A-Z_0-9]+)=(0x[0-9]+|0)
</code></pre>
<p>The following part matches every number of fields with trailing comma and whitespace</p>
<pre><code>(([A-Z_0-9]+)=(0x[0-9]+|0),\s?)*
</code></pre>
<p>And <code>([A-Z_0-9]+)=(0x[0-9]+|0)</code> will match the latest field.</p>
<p>Demo: <a href="https://regex101.com/r/gP3oO6/1" rel="nofollow">https://regex101.com/r/gP3oO6/1</a></p>
<p>Note: If you don't want some groups you better to use non-capturing groups by adding <code>?:</code> at the leading of capture groups.(<code>(?: ...)</code>), and note that <code>(0x[0-9]+|0):\s+</code> as extra in your regex (based on your input pattern)</p>
| 1 |
2016-09-23T19:35:42Z
|
[
"python",
"regex"
] |
python: regex - catch variable number of groups
| 39,668,228 |
<p>I have a string that looks like:</p>
<pre><code>TABLE_ENTRY.0[hex_number]= <FIELD_1=hex_number, FIELD_2=hex_number..FIELD_X=hex>
TABLE_ENTRY.1[hex_number]= <FIELD_1=hex_number, FIELD_2=hex_number..FIELD_Y=hex>
</code></pre>
<p>number of fields is unknown and varies from entry to entry, I want to capture
each entry separately with all of its fields and their values.</p>
<p>I came up with:</p>
<pre><code>([A-Z_0-9\.]+\[0x[0-9]+\]=)(0x[0-9]+|0):\s+<(([A-Z_0-9]+)=(0x[0-9]+|0))
</code></pre>
<p>which matches the table entry and the first field, but I dont know how to account for variable number of fields.</p>
<p>for input:</p>
<pre><code>ENTRY_0[0x130]=0: <FIELD_0=0, FIELD_1=0x140... FIELD_2=0xff3>
</code></pre>
<p>output should be:</p>
<pre><code>ENTRY 0:
FIELD_0=0
FIELD_1=0x140
FIELD_2=ff3
ENTRY 1:
...
</code></pre>
| 0 |
2016-09-23T19:27:17Z
| 39,668,425 |
<p>In short, it's impossible to do all of this in the <code>re</code> engine. You cannot generate more groups dynamically. It will all put it in one group. You should re-parse the results like so:</p>
<pre><code>import re
input_str = ("TABLE_ENTRY.0[0x1234]= <FIELD_1=0x1234, FIELD_2=0x1234, FIELD_3=0x1234>\n"
"TABLE_ENTRY.1[0x1235]= <FIELD_1=0x1235, FIELD_2=0x1235, FIELD_3=0x1235>")
results = {}
for match in re.finditer(r"([A-Z_0-9\.]+\[0x[0-9A-F]+\])=\s+<([^>]*)>", input_str):
fields = match.group(2).split(", ")
results[match.group(1)] = dict(f.split("=") for f in fields)
>>> results
{'TABLE_ENTRY.0[0x1234]': {'FIELD_2': '0x1234', 'FIELD_1': '0x1234', 'FIELD_3': '0x1234'}, 'TABLE_ENTRY.1[0x1235]': {'FIELD_2': '0x1235', 'FIELD_1': '0x1235', 'FIELD_3': '0x1235'}}
</code></pre>
<p>The output will just be a large dict consisting of a table entry, to a dict of it's fields.</p>
<p>It's also rather convinient as you may do this:</p>
<pre><code>>>> results["TABLE_ENTRY.0[0x1234]"]["FIELD_2"]
'0x1234'
</code></pre>
<p>I personally suggest stripping off "TABLE_ENTRY" as it's repetative but as you wish.</p>
| 2 |
2016-09-23T19:42:26Z
|
[
"python",
"regex"
] |
SQLAlchemy - given a Query object, can you determine if limit has already been applied?
| 39,668,254 |
<p>If you do a query like this:</p>
<pre><code>models.Article.query.limit(5).limit(10)
</code></pre>
<p>The limit will actually be 10, the 5 is overridden. </p>
<p>I have some code that wants to apply a limit to a <code>Query</code>, but only if one hasn't already been applied. Is there a way to determine if there is a limit already, short of <code>if 'LIMIT' in str(query):</code> ?</p>
| 1 |
2016-09-23T19:29:16Z
| 39,668,326 |
<p>From what I understand, you can check if there is a <code>_limit</code> private attribute set:</p>
<pre><code>query = models.Article.query.limit(5)
print(query._limit) # prints 5
query = models.Article.query
print(query._limit) # prints None
</code></pre>
<p>This is probably the most direct way to check the presence of an applied limit since the <a href="https://github.com/zzzeek/sqlalchemy/blob/6deb514992ce7d84196fedc191672eae8cc6dc37/lib/sqlalchemy/orm/query.py#L2536" rel="nofollow"><code>limit()</code> method</a> itself is doing exactly that:</p>
<pre><code>@_generative(_no_statement_condition)
def limit(self, limit):
"""Apply a ``LIMIT`` to the query and return the newly resulting
``Query``.
"""
self._limit = limit
</code></pre>
<hr>
<p>You can also do the substring in string check - see if <code>LIMIT</code> is inside the query statement, but this can easily fail if "limit" is used accidentally as a part of column/table name or being a literal "limit" or is present in any other way except having a special meaning.</p>
| 6 |
2016-09-23T19:34:50Z
|
[
"python",
"sqlalchemy"
] |
Flask redirect with uploaded file - I/O operation on closed file
| 39,668,362 |
<p>This app should allow a user to upload a file and then depending on the file type it would perform a save task. If it's a PDF file a new selection page loads prompting the user to select a folder. Once selected the error: <strong>ValueError: I/O operation on closed file</strong> pops up and an <strong>empty PDF</strong> file is saved in the selected location.</p>
<p>".mxd" files process with no issues. It seems to be because I have redirected to the selection template, but I'm not sure how else I would be able to use the folder selection.</p>
<p>Much code has been omitted to keep things simple. Any help would be greatly appreciated. </p>
<pre><code>@app.route("/", methods=['GET', 'POST'])
def upload_file():
form = ReusableForm(request.form) # calls on form
if request.method == 'POST':
global folderout
folderout = request.form['folderout']
global file
file = request.files['file']
if filename.endswith((".pdf")): # For PDF files only
return redirect("/selection")
return redirect("/editor")
if filename.endswith((".mxd")):
MXDfull.savemxd()
MXDfull.pdf()
MXDfull.thumb()
return redirect("/editor")
@app.route("/selection", methods=['GET', 'POST'])
def selection1():
form = SelectionForm(request.form)
if request.method == 'POST':
global selection
selection = request.form['selection']
pdffilesave.savepdf()
return render_template("selection.html", form=form)
class PDFFile:
def savepdf(self):
self.pdffolder = os.path.join(folderout,selection)
self.pdffilename = "K" + Fnum + ".pdf"
file.save(os.path.join(self.pdffolder, self.pdffilename))
return
pdffilesave = PDFFile()
</code></pre>
<p>Page 1:</p>
<p><a href="http://i.stack.imgur.com/ChE5F.png" rel="nofollow"><img src="http://i.stack.imgur.com/ChE5F.png" alt="Upload file"></a></p>
<p>Page 2:</p>
<p><a href="http://i.stack.imgur.com/7NiJP.png" rel="nofollow"><img src="http://i.stack.imgur.com/7NiJP.png" alt="enter image description here"></a></p>
<p>Page 3:</p>
<p><a href="http://i.stack.imgur.com/MZSE1.png" rel="nofollow"><img src="http://i.stack.imgur.com/MZSE1.png" alt="enter image description here"></a></p>
| 1 |
2016-09-23T19:37:16Z
| 39,675,271 |
<p>Flask creates a <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage.save" rel="nofollow">FileStorage</a> object which is a thin wrapper over incoming files.</p>
<p>The stream attribute of this object usually points to an open temporary file (according to the documentation). I'm guessing that as soon as the request is served, this temporary file is closed and hence the reference to this stream from your global object <code>file</code> points to a closed file. You must have got this error
<code>ValueError: I/O operation on closed file.</code></p>
<p>One work around would be to save the file in <code>upload_file</code> method in a temporary location and store the location of this file in a global variable <code>filename</code>.</p>
<pre><code>@app.route("/", methods=['GET', 'POST'])
def upload_file():
....
file = request.files['file']
global file_name = '/tmp/' + file.filename
file.save(file_name)
if file.filename.endswith((".pdf")): # For PDF files only
return redirect("/selection")
return redirect("/editor")
...
</code></pre>
<p>In the selection method, you can move the file from temporary location to the desired location.</p>
<pre><code>@app.route("/selection", methods=['GET', 'POST'])
def selection1():
....
os.rename(file_name, dest_file_name)
...
</code></pre>
| 1 |
2016-09-24T10:20:55Z
|
[
"python",
"flask",
"werkzeug"
] |
Creating a new Qapplication from Qapplication event loop
| 39,668,472 |
<p>I have rewritten the question so that it is more clear.</p>
<p>In my code I created a QApplication, connected a slot to the application using QTimer.singleShot(), then executed my application.</p>
<p>Now in this slot I want to create another QApplication in another process, I used multiprocessing.Process Class and from inside the process I try to start another QApplication and execute it, but I have an error because an event loop is already running!, I know I can't run two event loops but I am running the new QApplication in another process so it should run.</p>
<p>I know this is not a common implementation but it would be much easier to get this running in my case.</p>
<p>Here is a code example:
The error I get is "QCoreApplication::exec: The event loop is already running"</p>
<pre><code>import multiprocessing
from PyQt4 import QtCore,QtGui
def first_app_slot():
mProcess = multiprocessing.Process(target = run_another_app)
mProcess.start()
mProcess.join()
def run_another_app():
second_app = QtGui.QApplication([])
second_app.exec_()
if __name__ == "__main__":
first_app = QtGui.QApplication([])
QtCore.QTimer.singleShot(0,first_app_slot)
first_app.exec_()
</code></pre>
| -1 |
2016-09-23T19:45:49Z
| 39,670,396 |
<p>A few problems</p>
<ol>
<li><p>In your code, you're not calling any of the multiprocessing code (maybe a typo)?</p></li>
<li><p>Don't create the first <code>QApplication</code> in the global scope, put it inside a function. Before creating a new process, <code>multiprocessing</code> will copy the global state to the new process, which includes <code>first_app</code> in this case. </p></li>
</ol>
<p>Ex.</p>
<pre><code>def main():
first_app = QtGui.QApplication(sys.argv)
...
if __name__ == '__main__':
main()
</code></pre>
| 0 |
2016-09-23T22:26:25Z
|
[
"python",
"qt",
"pyqt",
"multiprocessing",
"qapplication"
] |
How do I store class data in an array and recall this data as needed?
| 39,668,488 |
<p>I'm trying to create a version of the game Snakeeyes, which will take in n at the start of the program, n being the number of players.<br>
So far, I have managed to get this far:</p>
<pre><code>import random
def rollDice():
dice = random.randint(1, 6)
print "You rolled a", dice
return dice
def addUser(name):
name = player()
print name, "is a player"
class player():
score = 0
players = []
def __init__(self):
score = 0
player.score = score
def addScore(self, dice1, dice2):
if dice1 == 1 or dice2 == 1:
player.score = 0
if dice1 == 1 and dice2 == 1:
print "SNAKE EYES"
else:
player.score += dice1
player.score += dice2
return player.score
def dispScore(self):
return player.score
numbp = int(input("Please enter number of players \n"))
plyarr = dict()
for x in range(numbp):
plyarr[x] = player()
plyarr[x].addScore(rollDice(),rollDice())
for x in range(numbp):
print plyarr[x].score
</code></pre>
<p>However,I can't get it to work because of my naivety with how python works and how classes (etc) can be used to speed this sort of programming up. The main issue is that often it overwrites the same spot in the dictionary (if I use a dictionary).</p>
| 0 |
2016-09-23T19:46:49Z
| 39,668,623 |
<p>Re written player class:</p>
<pre><code>class player():
def __init__(self):
self.score = 0
self.players = []
def addScore(self, dice1, dice2):
if dice1 == 1 or dice2 == 1:
player.score = 0
if dice1 == 1 and dice2 == 1:
print "SNAKE EYES"
else:
self.score += dice1
self.score += dice2
return self.score
def dispScore(self):
return self.score
def __str__(self):
return '<a description of the current object>'
</code></pre>
<p>From your comment, I assume you are inquring about the way to store the players in a dictionary; you could do it as follows (did a small change to your original code)</p>
<pre><code>numbp = int(input("Please enter number of players \n"))
plyarr = dict()
for x in range(numbp):
current_player = player()
current_player.addScore(rollDice(),rollDice())
playarr[x] = current_player
</code></pre>
<p>And finally, display your players' scores:</p>
<pre><code>for player_id, player in plyarr.items():
print player.dispScore()
</code></pre>
| 0 |
2016-09-23T19:56:29Z
|
[
"python"
] |
Compose for Elasticsearch Authentication in Python
| 39,668,569 |
<p>I am having issues getting the Python Elasticsearch library working with the Compose for Elasticsearch offering from Bluemix. When I use the following code against an Elasticsearch cluster I created using IBM containers it connects just fine. </p>
<h3>IBM Container Cluster running Elasticsearch with the Shield Plugin for user authentication</h3>
<pre><code>(venv) ⯠python
>>> import requests
>>> import elasticsearch
>>> from elasticsearch import Elasticsearch, RequestsHttpConnection
>>> es = Elasticsearch(
... host='clustertestv5.mybluemix.net',
... port=80,
... http_auth=('es_admin', 'REDACTED'),
... timeout=60)
>>> es.info()
{u'cluster_name': u'elasticsearch', u'tagline': u'You Know, for Search', u'version': {u'lucene_version': u'5.5.0', u'build_hash': u'218bdf10790eef486ff2c41a3df5cfa32dadcfde', u'number': u'2.3.3', u'build_timestamp': u'2016-05-17T15:40:04Z', u'build_snapshot': False}, u'name': u'Forgotten One'}
</code></pre>
<p>When I try to use the same code but authenticate against the Elasticsearch cluster provided by Bluemix it fails with a <code>ConnectionError</code> response. </p>
<pre><code>(venv) ⯠python
>>> import requests
>>> import elasticsearch
>>> from elasticsearch import Elasticsearch, RequestsHttpConnection
>>> es1 = Elasticsearch(
... host='bluemix-sandbox-dal-9-portal.3.dblayer.com',
... port=15206,
... http_auth=('admin', 'REDACTED'),
... timeout=60)
>>> es1.info()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryan/Desktop/deltaNiner/venv/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped
return func(*args, params=params, **kwargs)
File "/Users/ryan/Desktop/deltaNiner/venv/lib/python2.7/site-packages/elasticsearch/client/__init__.py", line 220, in info
return self.transport.perform_request('GET', '/', params=params)
File "/Users/ryan/Desktop/deltaNiner/venv/lib/python2.7/site-packages/elasticsearch/transport.py", line 327, in perform_request
status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
File "/Users/ryan/Desktop/deltaNiner/venv/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 105, in perform_request
raise ConnectionError('N/A', str(e), e)
elasticsearch.exceptions.ConnectionError: ConnectionError(('Connection aborted.', BadStatusLine("''",))) caused by: ProtocolError(('Connection aborted.', BadStatusLine("''",)))
>>> quit()
</code></pre>
<p>A straight curl against the Compose cluster shows that the username and password are correct so I know that is not causing the Connection issue. </p>
<pre><code>(venv) ⯠curl -k 'https://bluemix-sandbox-dal-9-portal.3.dblayer.com:15206/'
<html><body><h1>401 Unauthorized</h1>
You need a valid user and password to access this content.
</body></html>
(venv) ⯠curl -k -u admin:REDACTED 'https://bluemix-sandbox-dal-9-portal.3.dblayer.com:15206/'
{
"name" : "elastic_search56_bluemix_sandbox_dal_9_data_2_dblayer_com",
"cluster_name" : "bmix_dal_yp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"version" : {
"number" : "2.4.0",
"build_hash" : "ce9f0c7394dee074091dd1bc4e9469251181fc55",
"build_timestamp" : "2016-08-29T09:14:17Z",
"build_snapshot" : false,
"lucene_version" : "5.5.2"
},
"tagline" : "You Know, for Search"
}
</code></pre>
<p>For reference here is the Elasticsearch python library - <a href="https://elasticsearch-py.readthedocs.io/en/master/" rel="nofollow">https://elasticsearch-py.readthedocs.io/en/master/</a></p>
| 0 |
2016-09-23T19:53:48Z
| 39,709,295 |
<p>in your python code that creates the ES connection you're missing an option.</p>
<p>Add: <code>use_ssl=True</code></p>
<p>It is going to complain at that point about missing certificate validation, but will proceed. To round it out you should use the certificate provided in the VCAP connection info, along with the <code>verify_ssl=True</code> option. That option is <code>False</code> by default. Note: default behavior is equivalent to your use of the <code>-k</code> option with curl.</p>
| 1 |
2016-09-26T17:52:24Z
|
[
"python",
"elasticsearch",
"ibm-bluemix",
"compose"
] |
Object order in StackLayout (Kivy)
| 39,668,662 |
<p>I have a </p>
<pre><code>layout = StackLayout()
</code></pre>
<p>now I put buttons like this</p>
<pre><code>for x in range(9): # range() explanation: http://pythoncentral.io/pythons-range-function-explained/
bt = Button(text=' ', font_size=200, width=200, height=200, size_hint=(None, None), id=str(x+1))
bt.bind(on_release=self.btn_pressed)
layout.add_widget(bt)
</code></pre>
<p>the problem is that when I go through layout.children array and show the ids they come in order <code>9,8,7,6,5,4,3,2,1</code> which is reversed and not what I want. How do I get them in proper order? (Reversing the array is not a solution)</p>
<p>Another example</p>
<p>I have:</p>
<pre><code> self.layout = StackLayout()
bt = Button(text='1', font_size=200, width=200, height=200, size_hint=(None, None), id="1")
bt1 = Button(text='2', font_size=200, width=200, height=200, size_hint=(None, None), id="2")
bt2 = Button(text='3', font_size=200, width=200, height=200, size_hint=(None, None), id="3")
bt3 = Button(text='4', font_size=200, width=200, height=200, size_hint=(None, None), id="4")
bt4 = Button(text='5', font_size=200, width=200, height=200, size_hint=(None, None), id="5")
bt5 = Button(text='6', font_size=200, width=200, height=200, size_hint=(None, None), id="6")
self.layout.add_widget(bt, 1)
self.layout.add_widget(bt1, 2)
self.layout.add_widget(bt2, 3)
self.layout.add_widget(bt3, 4)
self.layout.add_widget(bt4, 5)
self.layout.add_widget(bt5, 6)
</code></pre>
<p>And this shows me this: <img src="http://i.stack.imgur.com/1hgV2.png" alt="enter image description here"></p>
| 0 |
2016-09-23T19:59:46Z
| 39,669,089 |
<p>a possible trick would be:</p>
<pre><code>y = 10
for x in range(y):
bt = Button(text=' ', font_size=200, width=200, height=200, size_hint=(None, None), id=str(y-x))
bt.bind(on_release=self.btn_pressed)
layout.add_widget(bt)
</code></pre>
| 0 |
2016-09-23T20:33:06Z
|
[
"python",
"layout",
"order",
"kivy"
] |
Object order in StackLayout (Kivy)
| 39,668,662 |
<p>I have a </p>
<pre><code>layout = StackLayout()
</code></pre>
<p>now I put buttons like this</p>
<pre><code>for x in range(9): # range() explanation: http://pythoncentral.io/pythons-range-function-explained/
bt = Button(text=' ', font_size=200, width=200, height=200, size_hint=(None, None), id=str(x+1))
bt.bind(on_release=self.btn_pressed)
layout.add_widget(bt)
</code></pre>
<p>the problem is that when I go through layout.children array and show the ids they come in order <code>9,8,7,6,5,4,3,2,1</code> which is reversed and not what I want. How do I get them in proper order? (Reversing the array is not a solution)</p>
<p>Another example</p>
<p>I have:</p>
<pre><code> self.layout = StackLayout()
bt = Button(text='1', font_size=200, width=200, height=200, size_hint=(None, None), id="1")
bt1 = Button(text='2', font_size=200, width=200, height=200, size_hint=(None, None), id="2")
bt2 = Button(text='3', font_size=200, width=200, height=200, size_hint=(None, None), id="3")
bt3 = Button(text='4', font_size=200, width=200, height=200, size_hint=(None, None), id="4")
bt4 = Button(text='5', font_size=200, width=200, height=200, size_hint=(None, None), id="5")
bt5 = Button(text='6', font_size=200, width=200, height=200, size_hint=(None, None), id="6")
self.layout.add_widget(bt, 1)
self.layout.add_widget(bt1, 2)
self.layout.add_widget(bt2, 3)
self.layout.add_widget(bt3, 4)
self.layout.add_widget(bt4, 5)
self.layout.add_widget(bt5, 6)
</code></pre>
<p>And this shows me this: <img src="http://i.stack.imgur.com/1hgV2.png" alt="enter image description here"></p>
| 0 |
2016-09-23T19:59:46Z
| 39,669,259 |
<p>Kivy reverses the order here for reasons to do with internal dispatching order. It doesn't have to, but it's a design decision.</p>
<p>However, this really doesn't matter at all. If you want to store your objects in some particular structure, do that yourself.</p>
| 2 |
2016-09-23T20:44:27Z
|
[
"python",
"layout",
"order",
"kivy"
] |
Format a table that was added to a plot using pandas.DataFrame.plot
| 39,668,665 |
<p>I'm producing a bar graph with a table using pandas.DataFrame.plot.</p>
<p>Is there a way to format the table size and/or font size in the table to make it more readable?</p>
<p>My DataFrame (dfexe):</p>
<pre><code>City State Waterfalls Lakes Rivers
LA CA 2 3 1
SF CA 4 9 0
Dallas TX 5 6 0
</code></pre>
<p>Create a bar chart with a table:</p>
<pre><code>myplot = dfex.plot(x=['City','State'],kind='bar',stacked='True',table=True)
myplot.axes.get_xaxis().set_visible(False)
</code></pre>
<p>Output:
<a href="http://i.stack.imgur.com/qNGUx.png" rel="nofollow"><img src="http://i.stack.imgur.com/qNGUx.png" alt="enter image description here"></a></p>
| 0 |
2016-09-23T20:00:00Z
| 39,669,727 |
<p>Here is an answer.</p>
<pre><code># Test data
dfex = DataFrame({'City': ['LA', 'SF', 'Dallas'],
'Lakes': [3, 9, 6],
'Rivers': [1, 0, 0],
'State': ['CA', 'CA', 'TX'],
'Waterfalls': [2, 4, 5]})
myplot = dfex.plot(x=['City','State'],kind='bar',stacked='True',table=True)
myplot.axes.get_xaxis().set_visible(False)
# Getting the table created by pandas and matplotlib
table = myplot.tables[0]
# Setting the font size
table.set_fontsize(12)
# Rescaling the rows to be more readable
table.scale(1,2)
</code></pre>
<p><a href="http://i.stack.imgur.com/gigvi.png" rel="nofollow"><img src="http://i.stack.imgur.com/gigvi.png" alt="enter image description here"></a></p>
<p>Note: Check also <a href="http://stackoverflow.com/questions/15514005/how-to-change-the-tables-fontsize-with-matplotlib-pyplot">this</a> answer for more information. </p>
| 1 |
2016-09-23T21:21:13Z
|
[
"python",
"pandas",
"matplotlib"
] |
Python - Multiple line printed image not displaying correctly issues
| 39,668,683 |
<p>I am having some issues with displaying images for Rock - Paper - Scissors. I'm very new to python (3 weeks) and I am trying to print a multiple line 'image'.<br>
Please excuse my terrible art!</p>
<pre><code>import random
def Display_Rock():
print ("""\n
_---___
/ .#.... \
/ .$../\.. \
|_________/
""")
def Display_Paper():
print ("""\n
__________
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|__________|
""")
def Display_Scissors():
print ("""\n
_----_
/ /--\ \
| \__/ \_________________
\____ \
/ ------------------\
/ /--\ _________________/
| \__/ /
\-____-/
""")
Display_Rock()
Display_Scissors()
Display_Paper()
</code></pre>
<p>This displays the following - </p>
<pre><code> _---___
/ .#.... / .$../\.. |_________/
----_
/ /--\ \
| \__/ \_________________
\____ / ------------------ / /--\
_________________/
| \__/ /
\-____-/
__________
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|__________|
</code></pre>
<p>Thank you for reading and for any comments in advance!</p>
| 1 |
2016-09-23T20:01:48Z
| 39,668,772 |
<p>Use <code>r</code> before of your strings like so:</p>
<pre><code>def Display_Rock():
print (r"""
_---___
/ .#.... \
/ .$../\.. \
|_________/
""")
>>> Display_Rock()
_---___
/ .#.... \
/ .$../\.. \
|_________/
</code></pre>
<p>Python treats your <code>\</code> as escape chars.</p>
| 0 |
2016-09-23T20:07:39Z
|
[
"python",
"printing"
] |
Python - Multiple line printed image not displaying correctly issues
| 39,668,683 |
<p>I am having some issues with displaying images for Rock - Paper - Scissors. I'm very new to python (3 weeks) and I am trying to print a multiple line 'image'.<br>
Please excuse my terrible art!</p>
<pre><code>import random
def Display_Rock():
print ("""\n
_---___
/ .#.... \
/ .$../\.. \
|_________/
""")
def Display_Paper():
print ("""\n
__________
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|__________|
""")
def Display_Scissors():
print ("""\n
_----_
/ /--\ \
| \__/ \_________________
\____ \
/ ------------------\
/ /--\ _________________/
| \__/ /
\-____-/
""")
Display_Rock()
Display_Scissors()
Display_Paper()
</code></pre>
<p>This displays the following - </p>
<pre><code> _---___
/ .#.... / .$../\.. |_________/
----_
/ /--\ \
| \__/ \_________________
\____ / ------------------ / /--\
_________________/
| \__/ /
\-____-/
__________
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|__________|
</code></pre>
<p>Thank you for reading and for any comments in advance!</p>
| 1 |
2016-09-23T20:01:48Z
| 39,669,096 |
<p>While the others are correct, you can also escape the <code>\</code> so that it is not treated specially by adding another <code>\</code>: </p>
<pre><code>print ("""\n
_----_
/ /--\ \\
| \__/ \_________________
\____ \\
/ ------------------\\
/ /--\ _________________/
| \__/ /
\-____-/
""")
</code></pre>
<p>In future Python versions the <code>\</code> cannot be used unescaped, so starting from 3.6 a warning will be emitted for <code>\_</code>, <code>\-</code> and <code>\</code>, so from there on you must always use <code>\\</code> to mean <code>\</code>; alternatively you can use the <code>r''</code> raw strings; though then you cannot use <code>\n</code> for newline.</p>
| 0 |
2016-09-23T20:33:45Z
|
[
"python",
"printing"
] |
how to install python module via terminal?
| 39,668,695 |
<p>Recently while doing a webcrawler project in python, I was using PyCharm and had to download and install an external module.</p>
<p><a href="http://i.stack.imgur.com/gl6He.png" rel="nofollow">Installing on PyCharm</a></p>
<p>Does anyone knows how to install those modules using unix terminal?</p>
| 1 |
2016-09-23T20:02:24Z
| 39,668,873 |
<p>Pycharm uses pip underneath. If you have pip installed you just type on the terminal:</p>
<pre><code>pip install "module name"
</code></pre>
| 2 |
2016-09-23T20:15:54Z
|
[
"python",
"pycharm"
] |
Shell restarting rather than running code
| 39,668,751 |
<p>Trying to draw a straight line using</p>
<pre><code>import turtle
def draw_line():
window =turtle.Screen()
window.bgcolor("blue")
animal=turtle.Turtle ()
animal.forward(100)
window.exitonclick()
draw_line()
</code></pre>
<p>but the shell keeps restarting and doesn't run the code.
Help!</p>
| -1 |
2016-09-23T20:06:11Z
| 39,668,956 |
<p>I tried to run your code as follows:</p>
<pre><code>import turtle
def draw_line():
window = turtle.Screen()
window.bgcolor('blue')
animal = turtle.Turtle()
animal.forward(100)
window.exitonclick()
draw_line()
</code></pre>
<p>And I can successfully run it.</p>
<p>I saved the above code in a file called <code>turtle_test.py</code> and ran it on the command line like this:</p>
<pre><code>python turtle_test.py
</code></pre>
<p>For me that opens a new window with the expected output and it closes on click.</p>
<p>I tried it with both Python 2.6 and Python 3.5. Neither version had a problem with this script. One thing I have to mention though is that the window created by this script did not get focus automatically. I had to find it by Alt-Tab'ing, maybe that's your problem as well?</p>
<p>Also sorry for answering without a definitive answer, but it seems I need 'points' to be able to post a comment.. </p>
| 1 |
2016-09-23T20:23:06Z
|
[
"python",
"class"
] |
Python: how to check whether Google street view API returns no image or the API key is expired?
| 39,668,776 |
<p>I want to use <a href="https://developers.google.com/maps/documentation/streetview/" rel="nofollow">Google Street View API</a> to download some images in python.</p>
<p>Sometimes there is no image return in one area, but the API key can be <strong>used</strong>. </p>
<p><a href="http://i.stack.imgur.com/pXSWd.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/pXSWd.jpg" alt="enter image description here"></a></p>
<p>Other time API key is <strong>expired</strong> or <strong>invalid</strong>, and also cannot return image. </p>
<pre><code>The Google Maps API server rejected your request. The provided API key is expired.
</code></pre>
<p>How to distinguish these two situations with code in Python?</p>
<p>Thank you very much.</p>
| 0 |
2016-09-23T20:07:59Z
| 39,669,215 |
<p>One way to do this would be to make an api call with the <code>requests</code> library, and parse the JSON response:</p>
<pre><code>import requests
url = 'https://maps.googleapis.com/maps/api/streetview?size=600x300&location=46.414382,10.013988&heading=151.78&pitch=-0.76&key=YOUR_API_KEY'
r = requests.get(url)
results = r.json()
error_message = results.get('error_message')
</code></pre>
<p>Now <code>error_message</code> will be the text of the error message (e.g., <code>'The provided API key is expired.'</code>), or will be <code>None</code> if there is no error message. So later in your code you can check if there is an error message, and do things based on the content of the message:</p>
<pre><code>if error_message and 'The provided API key is invalid.' in error_message:
do_something()
elif ...:
do_something_else()
</code></pre>
<p>You could also check the key <code>'status'</code> if you just want to see if the request was successful or not:</p>
<pre><code>status = results.get('status')
</code></pre>
| 1 |
2016-09-23T20:41:47Z
|
[
"python",
"api",
"google-maps",
"google-maps-api-3",
"google-street-view"
] |
python ctypes array will not return properly
| 39,668,820 |
<p>This does not work:</p>
<pre><code>def CopyExportVars(self, n_export):
export_array = (ctypes.c_double * n_export)()
self.dll_handle.vs_copy_export_vars(ctypes.cast(export_array, ctypes.POINTER(ctypes.c_double)))
return export_array().contents
</code></pre>
<p>I get this error (<code>n_export</code> is 3):</p>
<pre><code>TypeError: 'c_double_Array_3' object is not callable
</code></pre>
| 0 |
2016-09-23T20:11:15Z
| 39,669,034 |
<p>Error is pretty self-explainatory. <code>export_array</code> is not a callable object, but you try to call it in last line of function. Also, you try to use pointer-related interface ('.contents') to retrieve value from array, not pointer to it.</p>
<p>Simplest way to make it work would be to convert <code>ctypes</code> result array to pure Python object and return it: </p>
<pre><code>def CopyExportVars(self, n_export):
export_array = (ctypes.c_double * n_export)()
self.dll_handle.vs_copy_export_vars(ctypes.cast(export_array, ctypes.POINTER(ctypes.c_double)))
return list(export_array)
</code></pre>
| 0 |
2016-09-23T20:28:49Z
|
[
"python",
"arrays",
"ctypes"
] |
cx_Oracle returning varchar columns with HTML entities
| 39,668,841 |
<p>When using cx_Oracle to query a database, I have a a column storing text as varchar2. For some reason, if I have "<" or ">" or characters like those stored in the table, then when I query the table it replaces those values with their HTML entity equivalent (ex: "<" becomes "&lt;"). For example:</p>
<p>If I have the following data in my table:</p>
<pre><code>ID | VARCHAR2_DATA
----|-----------------
1 | <span>hi1</span>
2 | <span>hi2</span>
</code></pre>
<p>and then I run the following code:</p>
<pre><code>import cx_Oracle
conn = cx_Oracle.connect(DATABASE_CONNECTION_STRING)
cursor = conn.cursor()
cursor.execute("SELECT * FROM TABLE")
ret_data = cursor.fetchall()
</code></pre>
<p>ret_data will contain:</p>
<pre><code>[1, "&lt;span&gt;hi1&lt;/span&gt;"],
[2, "&lt;span&gt;hi2&lt;/span&gt;"]
</code></pre>
<p>Why does this happen? How can I stop it from happening other than iterating through each column/row and doing a find/replace?</p>
| 0 |
2016-09-23T20:12:41Z
| 39,704,817 |
<p>You must have some sort of code that is coming between cx_Oracle and your code in order to do this. cx_Oracle returns tuples, not lists, when returning data. As in the following:</p>
<pre><code>[(1, '<span>hi1</span>'), (2, '<span>hi2</span>')]
</code></pre>
<p>Try using python at the command prompt without any additional modules being imported. You can check to see what modules are being imported by using the command</p>
<pre><code>python -v
</code></pre>
| 0 |
2016-09-26T13:54:08Z
|
[
"python",
"oracle",
"cx-oracle"
] |
How to create a pandas "link" (href) style?
| 39,668,851 |
<p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">documentation</a> I realize that it is possible to create styles over pandas dataframes. However, I would like to know if it is possible to create a link style. So far this is what I tried:</p>
<pre><code>def linkify(data_frame_col):
list_words = ['<a href="http://this_is_url_{}">{}</a>'.format(a,a) for a in data_frame_col]
return list_words
</code></pre>
<p>The problem is that when I visualize the pandas dataframe into a flask website I get the following style:</p>
<pre><code>['<a href="http://this_is_url_hi">hi</a>',
'<a href="http://this_is_url_quick fox brown">quick fox brown</a>',
'<a href="http://this_is_url_fall apart">fall apart</a>',
'<a href="http://this_is_url_hi">hi</a>',
'<a href="http://this_is_url_no">no</a>']
</code></pre>
<p>Instead of links. Any idea of how to get hrefs like this stye: <a href="http://link.com" rel="nofollow">this</a> inside the pandas dataframe?.</p>
<p><strong>Update</strong></p>
<p>My template looks like this:</p>
<p>view.html:</p>
<pre><code><!doctype html>
<title>title</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h1>Title</h1>
{% for table in tables %}
<h2>{{titles[loop.index]}}</h2>
{{ table|safe }}
{% endfor %}
</div>
</code></pre>
| 0 |
2016-09-23T20:13:51Z
| 39,669,278 |
<p>You can use the IPython's display.HTML type</p>
<pre><code>from IPython.display import HTML
import pandas as pd
df = pd.DataFrame(['<a href="http://example.com">example.com</a>'])
HTML(df.to_html(escape=False))
</code></pre>
| 0 |
2016-09-23T20:45:44Z
|
[
"python",
"html",
"python-3.x",
"pandas",
"flask"
] |
Bokeh (Python) Figure.vbar() vs Bar()
| 39,668,868 |
<p>I'm just starting to take a look at Bokeh for data visualization and am wondering the advantage/disadvantage to using <code>Figure.vbar()</code> vs <code>Bar()</code> if someone could clarify. </p>
| 1 |
2016-09-23T20:15:23Z
| 39,824,201 |
<p><code>bar</code> is from the high level <strong>Charts</strong> interface. It gives you quick, easy access to bar charts with limited control.</p>
<p><code>vbar</code> is from the mid level <strong>Plotting</strong> interface and gives you more control over the layout of your bar chart. Alternatives to <code>vbar</code> would be <code>rect</code> and <code>quad</code>, both from the <strong>Plotting</strong> interface. They give a few distinctive options for bar shape, location, etc.</p>
<blockquote>
<p><code>bar</code> is much easier if you don't need to do anything fancy. If you decide you want more control over your plot (like <code>HoverTool</code> etc) you will have to instantiate a <code>Figure</code> and use one of it's methods.</p>
</blockquote>
<hr>
<p><code>bar</code> docs <a href="http://bokeh.pydata.org/en/0.11.0/docs/reference/charts.html#bar" rel="nofollow">Here</a></p>
<p>and </p>
<p><code>vbar</code> docs <a href="http://bokeh.pydata.org/en/latest/docs/reference/plotting.html#bokeh.plotting.figure.Figure.vbar" rel="nofollow">Here</a></p>
<p>I use both, depending on my needs.</p>
| 2 |
2016-10-03T03:28:45Z
|
[
"python",
"bokeh"
] |
read the file and prduce sorted dictionary
| 39,668,933 |
<p>Create a file with contents: </p>
<pre><code>Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5
</code></pre>
<p>Read this file and create a dictionary with keys of the type tuple and values of the type float i.e., an item of the dictionary should look like this: </p>
<pre><code>(âMaryâ,âJaneâ) : 5.8
</code></pre>
<p>Convert this dictionary into a list of tuples. Sort them in decreasing order and print them. </p>
<p>my code is: </p>
<pre><code>f = open('sam.txt', 'r')
answer = {}
tuple(answer.keys())
for i in answer:
print tuple(answer.keys())
for line in f:
k, v = ((line.strip()).split(':'))
answer[((k.strip()))] = float(v.strip())
print answer
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()
</code></pre>
<p>Here I am getting keys of dictionary as string not tuple as prescribed please tell me my mistake and please do some fine tunes to my regarding problem.</p>
| 1 |
2016-09-23T20:20:51Z
| 39,668,963 |
<p>You should also <em>split</em> the keys on comma <code>','</code> and not only <em>strip</em>:</p>
<pre><code>answer[tuple(k.strip().split(','))] = float(v.strip())
</code></pre>
<p>On a side note, you don't need that initial dict stunt code:</p>
<pre><code>answer = {}
with open('sam.txt') as f: # open with context manager does auto close
for line in f:
k, v = line.strip().split(':')
answer[tuple(k.strip().split(','))] = float(v.strip())
</code></pre>
| 0 |
2016-09-23T20:23:40Z
|
[
"python",
"dictionary"
] |
read the file and prduce sorted dictionary
| 39,668,933 |
<p>Create a file with contents: </p>
<pre><code>Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5
</code></pre>
<p>Read this file and create a dictionary with keys of the type tuple and values of the type float i.e., an item of the dictionary should look like this: </p>
<pre><code>(âMaryâ,âJaneâ) : 5.8
</code></pre>
<p>Convert this dictionary into a list of tuples. Sort them in decreasing order and print them. </p>
<p>my code is: </p>
<pre><code>f = open('sam.txt', 'r')
answer = {}
tuple(answer.keys())
for i in answer:
print tuple(answer.keys())
for line in f:
k, v = ((line.strip()).split(':'))
answer[((k.strip()))] = float(v.strip())
print answer
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()
</code></pre>
<p>Here I am getting keys of dictionary as string not tuple as prescribed please tell me my mistake and please do some fine tunes to my regarding problem.</p>
| 1 |
2016-09-23T20:20:51Z
| 39,669,193 |
<p>Its much easier if you have your data in new lines like this:</p>
<pre><code>Mary,Jane : 5.8
Mary,Doe : 6.0
John,Doe : 6.3
John,Muller : 5.6
Mary,Muller : 6.5
</code></pre>
<p>and then the code would be :</p>
<pre><code>f = open('data.txt', 'r')
answer = {}
for line in f:
k, v = ((line.strip()).split(':'))
key1, key2 = k.split(',')
answer[(key1, key2)] = float(v.strip())
print answer
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()
</code></pre>
| 0 |
2016-09-23T20:40:19Z
|
[
"python",
"dictionary"
] |
read the file and prduce sorted dictionary
| 39,668,933 |
<p>Create a file with contents: </p>
<pre><code>Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5
</code></pre>
<p>Read this file and create a dictionary with keys of the type tuple and values of the type float i.e., an item of the dictionary should look like this: </p>
<pre><code>(âMaryâ,âJaneâ) : 5.8
</code></pre>
<p>Convert this dictionary into a list of tuples. Sort them in decreasing order and print them. </p>
<p>my code is: </p>
<pre><code>f = open('sam.txt', 'r')
answer = {}
tuple(answer.keys())
for i in answer:
print tuple(answer.keys())
for line in f:
k, v = ((line.strip()).split(':'))
answer[((k.strip()))] = float(v.strip())
print answer
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()
</code></pre>
<p>Here I am getting keys of dictionary as string not tuple as prescribed please tell me my mistake and please do some fine tunes to my regarding problem.</p>
| 1 |
2016-09-23T20:20:51Z
| 39,674,414 |
<p>I did answer like this may i know is there any further upgrade needed to it to make it more efficient</p>
<pre><code>f = open('sam.txt')
answer = {tuple(x.split(':')[0].strip().split(',')): float(x.split('[1].strip()) for x in f}
print "\ndictionary taken from file is:\n"
print answer
c = answer.items()
d = sorted(c)
print "\nafter sorted and converted into tuples the output is:\n"
print tuple(reversed(sorted(c)))
f.close()
</code></pre>
| 0 |
2016-09-24T08:49:40Z
|
[
"python",
"dictionary"
] |
read the file and prduce sorted dictionary
| 39,668,933 |
<p>Create a file with contents: </p>
<pre><code>Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5
</code></pre>
<p>Read this file and create a dictionary with keys of the type tuple and values of the type float i.e., an item of the dictionary should look like this: </p>
<pre><code>(âMaryâ,âJaneâ) : 5.8
</code></pre>
<p>Convert this dictionary into a list of tuples. Sort them in decreasing order and print them. </p>
<p>my code is: </p>
<pre><code>f = open('sam.txt', 'r')
answer = {}
tuple(answer.keys())
for i in answer:
print tuple(answer.keys())
for line in f:
k, v = ((line.strip()).split(':'))
answer[((k.strip()))] = float(v.strip())
print answer
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()
</code></pre>
<p>Here I am getting keys of dictionary as string not tuple as prescribed please tell me my mistake and please do some fine tunes to my regarding problem.</p>
| 1 |
2016-09-23T20:20:51Z
| 39,674,647 |
<p>Built-in functions are often useful, but sometimes all you need is a simple regular expression:</p>
<pre><code># Generate file
txt = "Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5"
with open("out.txt","w+") as FILE: FILE.write(txt)
# Read file and grab content
content= [ re.findall(r"([A-Za-z]+),([A-Za-z]+)\s:\s([0-9]\.[0-9])",line) for line in tuple(open("out.txt","r")) ]
# Make dictionary
dct = {(k1,k2):float(v) for (k1,k2,v) in reduce(lambda x,y: x+y, content)}
print(dct)
</code></pre>
| 0 |
2016-09-24T09:14:26Z
|
[
"python",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.