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 |
---|---|---|---|---|---|---|---|---|---|
Can't combine two strings togetger
| 39,423,462 |
<p>When I was doing some tricks with strings,I can't combine the string <code>word[0]</code> with word. I thought this is because they are from the same string. If so, what can I do? </p>
<pre><code>def pig_it(text):
l1 = text.split(' ')
l2 =[]
for word in l1:
first_letter = word[0]
new = word + first_letter +'ay'
new = new.replace(new[0], '')
l2.append(new)
return ' '.join(l2)
print pig_it(('my name is frankling'))
</code></pre>
| -3 |
2016-09-10T06:54:36Z
| 39,423,523 |
<p>Its a little unclear about what you want to achieve with the above code but I rand it anyways and the code works according to the logic you have written the code</p>
<p>My out put was:</p>
<p>yay ameay say ranklingay </p>
<p>In case you want to do some thing specific, update the question and make it a little clear then probably i can help better.</p>
| -1 |
2016-09-10T07:04:29Z
|
[
"python",
"string",
"python-2.7"
] |
How to configure Atom to autocomplete Django templates
| 39,423,531 |
<p>I need to find a way/package to make Atom use autocomplete for Django projects, especially Django templates.
I found this <a href="https://atom.io/packages/django-templates" rel="nofollow">package</a> in Atom's installer, but it doesn't include a shortcut for auto completion of this syntax {% %}, {{ }} which I need the most.
Any help will be appreciated </p>
| -1 |
2016-09-10T07:06:05Z
| 39,423,607 |
<p>You could make your own snippets in Atom.</p>
<p>To do that go to <strong>Edit > Snippets</strong></p>
<p>In the document that open's you can paste this bit:</p>
<pre><code>'.html.django':
'Example snippet':
'prefix': '%%'
'body': '{% $1 %}$2'
</code></pre>
<p>This example would expand to <code>{% %}</code>, placing your cursor inside. To trigger it you type <code>%%</code> and hit <code>tab</code>. A second <code>tab</code> would place the cursor after the closing bracket.</p>
<p>The <code>.html.django</code> part means this snippet is active only in documents that are marked as <code>HTML (Django)</code></p>
<p>I don't see why you would need a snippet for <code>{{ }}</code> as Atom auto-close's the brackets.</p>
<p>For more information read this - <a href="http://flight-manual.atom.io/using-atom/sections/snippets/" rel="nofollow">http://flight-manual.atom.io/using-atom/sections/snippets/</a></p>
| 0 |
2016-09-10T07:14:50Z
|
[
"python",
"django",
"atom-editor"
] |
Python : error with importing md5
| 39,423,542 |
<p>I have problem with importing md5 library
I just use the code below:</p>
<pre><code>import md5
filemd5 = md5.new(password.strip()).hexdigest()
</code></pre>
<p>I also have tried this code :</p>
<pre><code>from hashlib import md5
filemd5 = md5.new(password.strip()).hexdigest()
</code></pre>
<p>also this code :</p>
<pre><code>from md5 import md5
</code></pre>
<p>But none of them are working !
when I run the code,it gives me this error:</p>
<pre><code>11.py", line 1, in <module>
import md5
ImportError: No module named 'md5'
</code></pre>
<p>What Should I Do ?
Am I Importing The Wrong Library ?</p>
| 1 |
2016-09-10T07:07:44Z
| 39,423,562 |
<p><code>md5</code> is not a module, it is an object. But it has no <code>new</code> method. It just has to be built, like any object.</p>
<p>Use as follows:</p>
<pre><code>import hashlib
m=hashlib.md5(bytes("text","ascii")) # python 3
m=hashlib.md5("text") # python 2
print(m.hexdigest())
</code></pre>
<p>results in:</p>
<pre><code>1cb251ec0d568de6a929b520c4aed8d1
</code></pre>
<p>You can also create the object empty and update it afterwards (more than once!)</p>
<pre><code>m=hashlib.md5()
m.update("text") # python 2
m.update(bytes("text","ascii")) # python 3
</code></pre>
<p>note that Python 3 requires an encoded <code>bytes</code> object, not <code>string</code>, because Python 3 makes a difference between string and binary data. MD5 is useful on binary and strings.</p>
| 0 |
2016-09-10T07:10:18Z
|
[
"python",
"md5"
] |
Writing specific value back to .csv, Python
| 39,423,635 |
<p>I have a .<code>csv</code> file with some data that i would like to change.
It looks like this:</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,r
item 2,411.21,3,r
item 3,40.0,1,r,c
</code></pre>
<p>My code runs most of what i need but i am unsure of how to write back on my <code>.csv</code> to produce this result</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,x
item 2,411.21,3,r
item 3,40.0,1,r,c
</code></pre>
<p><strong>My code:</strong></p>
<pre><code>print("Enter the item number:")
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for line in reader:
if line["item_required"] == 'r':
line_count += 1
if marked_item == line_count:
new_list = line
print(new_list)
for key, value in new_list.items():
if value == "r":
new_list['item_required'] = "x"
print(new_list)
with open("items.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(new_list.values())
</code></pre>
| 3 |
2016-09-10T07:18:08Z
| 39,423,802 |
<p>There are several problems here</p>
<ul>
<li>you're using a <code>DictReader</code>, which is good to read data, but not as good to read and write data as the original file, since dictionaries do not ensure column order (unless you don't care, but most of the time people don't want columns to be swapped). I just read the title, find the index of the column title, and use this index in the rest of the code (no dicts = faster)</li>
<li>when you write you append to the csv. You have to delete old contents, not append. And use <code>newline=''</code> or you get a lot of blank lines (python 3) or <code>"wb"</code> (python 2)</li>
<li>when you read, you need to store all values, not only the one you want to change, or you won't be able to write back all the data (since you're replacing the original file)</li>
<li>when you modify, you do overcomplex stuff I just replaced by a simple replace in list at the given index (after all you want to change <code>r</code> to <code>x</code> at a given row)</li>
</ul>
<p>Here's the fixed code taking all aforementioned remarks into account</p>
<p>EDIT: added the feature you request after: add a <code>c</code> after <code>x</code> if not already there, extending the row if needed</p>
<pre><code>import csv
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.reader(f, delimiter=',')
title = next(reader) # title
idx = title.index("item_required") # index of the column we target
lines=[]
for line in reader:
if line[idx] == 'r':
line_count += 1
if marked_item == line_count:
line[idx] = 'x'
# add 'c' after x (or replace if column exists)
if len(line)>idx+1: # check len
line[idx+1] = 'c'
else:
line.append('c')
lines.append(line)
with open("items.csv", 'w',newline='') as f:
writer = csv.writer(f,delimiter=',')
writer.writerow(title)
writer.writerows(lines)
</code></pre>
| 1 |
2016-09-10T07:37:43Z
|
[
"python",
"csv",
"dictionary"
] |
Writing specific value back to .csv, Python
| 39,423,635 |
<p>I have a .<code>csv</code> file with some data that i would like to change.
It looks like this:</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,r
item 2,411.21,3,r
item 3,40.0,1,r,c
</code></pre>
<p>My code runs most of what i need but i am unsure of how to write back on my <code>.csv</code> to produce this result</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,x
item 2,411.21,3,r
item 3,40.0,1,r,c
</code></pre>
<p><strong>My code:</strong></p>
<pre><code>print("Enter the item number:")
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for line in reader:
if line["item_required"] == 'r':
line_count += 1
if marked_item == line_count:
new_list = line
print(new_list)
for key, value in new_list.items():
if value == "r":
new_list['item_required'] = "x"
print(new_list)
with open("items.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(new_list.values())
</code></pre>
| 3 |
2016-09-10T07:18:08Z
| 39,423,829 |
<p>I guess this should do the trick:</p>
<ol>
<li>Open a file which can read and written to update it (use "+r" for that)</li>
<li>instead of opening it again write it right there using csvfilewriter, which we create at the start.</li>
</ol>
<p>file.py</p>
<pre><code>import csv
fieldnames = ["item_name","item_cost","item_priority","item_required","item_completed"]
csvfile = open("items.csv", 'r+')
csvfilewriter = csv.DictWriter(csvfile, fieldnames=fieldnames,dialect='excel', delimiter=',')
csvfilewriter.writeheader()
print("Enter the item number:")
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for line in reader:
if line["item_required"] == 'r':
line_count += 1
if marked_item == line_count:
new_list = line
print(new_list)
for key, value in new_list.items():
if value == "r":
new_list['item_required'] = "x"
print(new_list)
csvfilewriter.writerow(new_list)
</code></pre>
<p>If you don't want to update the csv but want to write a new one, below is the code:</p>
<pre><code>import csv
fieldnames = ["item_name","item_cost","item_priority","item_required","item_completed"]
csvfile = open("items_new.csv", 'w')
csvfilewriter = csv.DictWriter(csvfile, fieldnames=fieldnames,dialect='excel', delimiter=',')
csvfilewriter.writeheader()
print("Enter the item number:")
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for line in reader:
if line["item_required"] == 'r':
line_count += 1
if marked_item == line_count:
new_list = line
print(new_list)
for key, value in new_list.items():
if value == "r":
new_list['item_required'] = "x"
print(new_list)
csvfilewriter.writerow(new_list)
else:
csvfilewriter.writerow(line)
</code></pre>
| 0 |
2016-09-10T07:42:24Z
|
[
"python",
"csv",
"dictionary"
] |
Writing specific value back to .csv, Python
| 39,423,635 |
<p>I have a .<code>csv</code> file with some data that i would like to change.
It looks like this:</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,r
item 2,411.21,3,r
item 3,40.0,1,r,c
</code></pre>
<p>My code runs most of what i need but i am unsure of how to write back on my <code>.csv</code> to produce this result</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,x
item 2,411.21,3,r
item 3,40.0,1,r,c
</code></pre>
<p><strong>My code:</strong></p>
<pre><code>print("Enter the item number:")
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for line in reader:
if line["item_required"] == 'r':
line_count += 1
if marked_item == line_count:
new_list = line
print(new_list)
for key, value in new_list.items():
if value == "r":
new_list['item_required'] = "x"
print(new_list)
with open("items.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(new_list.values())
</code></pre>
| 3 |
2016-09-10T07:18:08Z
| 39,427,445 |
<p>Using <code>pandas</code>:</p>
<pre><code>import pandas as pd
df = pd.read_csv("items.csv")
print("Enter the item number:")
marked_item = int(input())
df.set_value(marked_item - 1, 'item_required', 'x')
# This is the extra feature you required:
df.set_value(marked_item - 1, 'item_completed', 'c')
df.to_csv("items.csv", index = False)
</code></pre>
<p>Result when marked_item = 1:</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,x,c
item 2,411.21,3,r,
item 3,40.0,1,r,c
</code></pre>
<p>Note that according to <a href="https://tools.ietf.org/html/rfc4180" rel="nofollow">RFC4180</a> you should keep the trailing commas.</p>
| 1 |
2016-09-10T15:13:32Z
|
[
"python",
"csv",
"dictionary"
] |
flask socketio emit to specific user
| 39,423,646 |
<p>I see there is a question about this topic, but the specific code is not outlined. Say I want to emit only to the first client.</p>
<p>For example (in events.py):</p>
<pre><code>clients = []
@socketio.on('joined', namespace='/chat')
def joined(message):
"""Sent by clients when they enter a room.
A status message is broadcast to all people in the room."""
#Add client to client list
clients.append([session.get('name'), request.namespace])
room = session.get('room')
join_room(room)
emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)
#I want to do something like this, emit message to the first client
clients[0].emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)
</code></pre>
<p>How is this done properly?</p>
<p>Thanks</p>
| 1 |
2016-09-10T07:19:27Z
| 39,431,811 |
<p>I'm not sure I understand the logic behind emitting to the first client, but anyway, this is how to do it:</p>
<pre><code>clients = []
@socketio.on('joined', namespace='/chat')
def joined(message):
"""Sent by clients when they enter a room.
A status message is broadcast to all people in the room."""
# Add client to client list
clients.append(request.sid)
room = session.get('room')
join_room(room)
# emit to the first client that joined the room
emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=clients[0])
</code></pre>
<p>As you can see, each client has a room for itself. The name of that room is the Socket.IO session id, which you can get as <code>request.sid</code> when you are handling an event from that client. So all you need to do is store this <code>sid</code> value for all your clients, and then use the desired one as room name in the <code>emit</code> call.</p>
| 1 |
2016-09-11T00:34:34Z
|
[
"python",
"flask",
"flask-socketio"
] |
Unable to run Python interpreter in terminal, through Anaconda3
| 39,423,671 |
<p>When I try the "python" or "python3" command to run the interpreter, this is the error am getting.</p>
<pre><code>[sidgupta234@sidgupta234-Lenovo-G580 Downloads]$ python
Failed to import the site module
Traceback (most recent call last):
File "/usr/lib/python3.5/site.py", line 580, in <module>
main()
File "/usr/lib/python3.5/site.py", line 566, in main
known_paths = addusersitepackages(known_paths)
File "/usr/lib/python3.5/site.py", line 287, in addusersitepackages
user_site = getusersitepackages()
File "/usr/lib/python3.5/site.py", line 263, in getusersitepackages
user_base = getuserbase() # this will also set USER_BASE
File "/usr/lib/python3.5/site.py", line 253, in getuserbase
USER_BASE = get_config_var('userbase')
File "/usr/lib/python3.5/sysconfig.py", line 595, in get_config_var
return get_config_vars().get(name)
File "/usr/lib/python3.5/sysconfig.py", line 538, in get_config_vars
_init_posix(_CONFIG_VARS)
File "/usr/lib/python3.5/sysconfig.py", line 410, in _init_posix
from _sysconfigdata import build_time_vars
File "/usr/lib/python3.5/_sysconfigdata.py", line 6, in <module>
from _sysconfigdata_m import *
ImportError: No module named '_sysconfigdata_m'
</code></pre>
<p>Output to <code>which python</code></p>
<pre><code>[sidgupta234@sidgupta234-Lenovo-G580 Downloads]$ which python
/usr/bin/python
</code></pre>
<p>Output to <code>python -V</code></p>
<pre><code>[sidgupta234@sidgupta234-Lenovo-G580 Downloads]$ python -V
Python 3.5.2 :: Continuum Analytics, Inc.
</code></pre>
<p><br><br>
Could you tell me the reason of this error and how can I remove it?
I found this <a href="https://forum.siduction.org/index.php?topic=5489.0" rel="nofollow">link</a> while looking for the solution, but it didnt make any difference.</p>
| 0 |
2016-09-10T07:23:12Z
| 39,424,039 |
<p>I guess <a href="https://ostrokach.github.io/posts/configuring_apache_django_anaconda/" rel="nofollow">configuring_apache_django_anaconda</a> is relevant, if you look at the troubleshooting section. </p>
<blockquote>
<p>This means that apache is using Python 2 instead of Python 3 to run a program that is designed for Python 3 only, and fails because Python 2 does not have the _sysconfigdata_m module. The solution is to add the following file to your apache envvar file (/etc/apache2/envvar):
export PATH=/opt/anaconda3/bin:$PATH</p>
</blockquote>
<p>So maybe check which version of python anaconda is running?</p>
<p>Also these two might be related:<a href="http://stackoverflow.com/questions/21446220/linux-weird-python-output">Linux - Weird Python Output</a></p>
<p><a href="https://bugs.launchpad.net/command-not-found/+bug/1480388" rel="nofollow">ubuntu anaconda suggested fix</a></p>
<p>I would suggest you print your PATH variable to see if you have several python3 entries in there, and try to specify explicity which one to run.</p>
| 0 |
2016-09-10T08:11:40Z
|
[
"python",
"anaconda"
] |
Unable to run Python interpreter in terminal, through Anaconda3
| 39,423,671 |
<p>When I try the "python" or "python3" command to run the interpreter, this is the error am getting.</p>
<pre><code>[sidgupta234@sidgupta234-Lenovo-G580 Downloads]$ python
Failed to import the site module
Traceback (most recent call last):
File "/usr/lib/python3.5/site.py", line 580, in <module>
main()
File "/usr/lib/python3.5/site.py", line 566, in main
known_paths = addusersitepackages(known_paths)
File "/usr/lib/python3.5/site.py", line 287, in addusersitepackages
user_site = getusersitepackages()
File "/usr/lib/python3.5/site.py", line 263, in getusersitepackages
user_base = getuserbase() # this will also set USER_BASE
File "/usr/lib/python3.5/site.py", line 253, in getuserbase
USER_BASE = get_config_var('userbase')
File "/usr/lib/python3.5/sysconfig.py", line 595, in get_config_var
return get_config_vars().get(name)
File "/usr/lib/python3.5/sysconfig.py", line 538, in get_config_vars
_init_posix(_CONFIG_VARS)
File "/usr/lib/python3.5/sysconfig.py", line 410, in _init_posix
from _sysconfigdata import build_time_vars
File "/usr/lib/python3.5/_sysconfigdata.py", line 6, in <module>
from _sysconfigdata_m import *
ImportError: No module named '_sysconfigdata_m'
</code></pre>
<p>Output to <code>which python</code></p>
<pre><code>[sidgupta234@sidgupta234-Lenovo-G580 Downloads]$ which python
/usr/bin/python
</code></pre>
<p>Output to <code>python -V</code></p>
<pre><code>[sidgupta234@sidgupta234-Lenovo-G580 Downloads]$ python -V
Python 3.5.2 :: Continuum Analytics, Inc.
</code></pre>
<p><br><br>
Could you tell me the reason of this error and how can I remove it?
I found this <a href="https://forum.siduction.org/index.php?topic=5489.0" rel="nofollow">link</a> while looking for the solution, but it didnt make any difference.</p>
| 0 |
2016-09-10T07:23:12Z
| 39,470,583 |
<p>That is an strange situation you have gotten yourself into, and if Continuum had any part of it (where I'm an engineer) we'd like to understand what we did that led to it so we can avoid it in the future.</p>
<p>Where did you try installing Anaconda? Did you set any environment variables?</p>
<p>The "easiest-to-resolve" cause of this problem is that you have set some environment variables that are mixing system Python libraries and Anaconda Python libraries. You should look at the output of:</p>
<pre><code>env | grep -i anaconda
</code></pre>
<p>and see if anything comes up that specifies a path to Anaconda. The only one that should appear is an entry in <code>PATH</code>. If there are any <code>LD_LIBRARY_PATH</code>, <code>PYTHONPATH</code>, <code>PYTHONHOME</code> or similar environment variables that point to Anaconda then that is going to be a problem.</p>
<p>The only other thing I can think of is that you specified <code>/usr</code> as the install path for Anaconda. If that is the case you are probably in for a world of pain: you have just replaced your system Python with Anaconda. You should investigate how to force-reinstall whichever Python package comes with your *nix distribution, but even that might be tricky: tools such as <code>yum</code> are written in Python and will need a working system Python interpreter to work. But RPM is binary (if you're on a RedHat or derivative distro), so maybe you can <code>wget</code> or <code>curl</code> the necessary system Python packages and force-install them to try and fix things.</p>
<p>Let us know if that is enough information for you to fix things or at least identify the source of the problem a little better.</p>
| 0 |
2016-09-13T12:51:37Z
|
[
"python",
"anaconda"
] |
Why the argument of recursive code in 8th line is 'string[:i] + string[i + 1:]' but not 'string'
| 39,423,683 |
<p>It's about a permutation problem. I tried to understand the code below but feel a little confusing finally.</p>
<p>Why the argument of recursive code in 8th line is 'string[:i] + string[i + 1:]' but not 'string'.</p>
<p>I know that 'string' argument to recursive will return RuntimeError.</p>
<p>But why?</p>
<p>permutation link: <a href="https://www.codewars.com/kata/permutations/python" rel="nofollow">https://www.codewars.com/kata/permutations/python</a></p>
<pre><code>def permutations(string):
result = set([string])
if len(string) == 2:
result.add(string[1] + string[0])
elif len(string) > 2:
for i, c in enumerate(string):
print "1.c = %s and i is %d"%(c,i)
for s in permutations(string[:i] + string[i + 1:]):
print "2.string[:i] + string[i + 1:] is %s and i is %d"%((string[:i] + string[i + 1:]),i)
result.add(c + s)
print "3.result is %s"%result
return list(result)
</code></pre>
| 0 |
2016-09-10T07:24:19Z
| 39,423,749 |
<p>Note that <code>string[a:b]</code> means a <code>[a b)</code> (including <code>a</code> and excluding <code>b</code>) substring of the string. So <code>string[:i] + string[i + 1:]</code> means the whole string without <code>i</code>th character.</p>
| 1 |
2016-09-10T07:30:38Z
|
[
"python",
"algorithm",
"recursion"
] |
Why would I prefer metaclass over inheritance from a superclass in Python
| 39,423,702 |
<p>From what I've learned so far, metaclass and inheritance from superclass in Python serve a very similar purpose, but superclass inheritance is more powerful.</p>
<p>Why would I prefer metaclass over superclass inheritance? In what kind of case metaclass would be helpful?</p>
<p>Sorry if there is any wrong assumption. I just learned metaclass today. </p>
| 0 |
2016-09-10T07:25:43Z
| 39,423,820 |
<p>I think you've misunderstood. Inheritance is the classic object oriented technique of reusing code by putting the commonly used stuff in a base class and deriving from that. </p>
<p>Metaclasses in a nutshell) allow you to customise the process of creation of a class (specifically the <code>__new__</code> method) so that you can dynamically add attributes and things like that. It's a little complicated and in most cases, you won't need this. There are some details over at this answer <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python#6581949">What is a metaclass in Python?</a></p>
| 1 |
2016-09-10T07:41:06Z
|
[
"python",
"class",
"inheritance",
"superclass",
"metaclass"
] |
How do you control user access to records in a key-value database?
| 39,423,756 |
<p>I have a web application that accesses large amounts of JSON data.</p>
<p>I want to use a key value database for storing JSON data owned/shared by different users of the web application (not users of the database). Each user should only be able to access the records they own or share.</p>
<p>In a relational database, I would add a column <code>Owner</code> to the record table, or manage shared ownerships in a separate table, and check access on the application side (Python). For key value stores, two approaches come to mind.</p>
<h2>User ID as part of the key</h2>
<p>What if I use keys like <code>USERID_RECORDID</code> and then write code to check the <code>USERID</code> before accessing the record? Is that a good idea? It wouldn't work with records that are shared between users.</p>
<h2>User ID as part of the value</h2>
<p>I could store one or more <code>USERIDs</code> in the value data and check if the data contains the ID of the user trying to access the record. Performance is probably slower than having the user ID as part of the key, but shared ownerships are possible.</p>
<h2>What are typical patterns to do what I am trying to do?</h2>
| 7 |
2016-09-10T07:31:40Z
| 39,518,000 |
<p>Both of the solutions you described have some limitations.</p>
<ul>
<li><p>You point yourself that including the owner ID in the key does not solve the problem of shared data. However, this solution may be acceptable, if you add another key/value pair, containing the IDs of the contents shared with this user <code>(key: userId:shared, value: [id1, id2, id3...])</code>.</p></li>
<li><p>Your second proposal, in which you include the list of users who were granted access to a given content, is OK if and only if you application needs to make a query to retrieve the list of users who have access to a particular content. If your need is to list all contents a given user can access, this design will lead you to poor performances, as the K/V store will have to scan all records -and this type of database engine usually don't allow you to create an index to optimise this kind of request.</p></li>
</ul>
<p>From a more general point of view, with NoSQL databases and especially Key/Value stores, the model has to be defined according to the requests to be made by the application. It may lead you to duplicate some information. The application has the responsibility of maintaining the consistency of the data.</p>
<p>By example, if you need to get all contents for a given user, whether this user is the owner of the content or these contents were shared with him, I suggest you to create a key for the user, containing the list of content Ids for that user, as I already said. But if your app also needs to get the list of users allowed to access a given content, you should add their IDs in a field of this content. This would result in something like :
<code>key: contentID, value: { ..., [userId1, userID2...]}</code></p>
<p>When you remove the access to a given content for a user, your app (and not the datastore) have to remove the userId from the content value, and the contentId from the list of contents for this user.</p>
<p>This design may imply for your app to make multiple requests: by example one to get the list of userIDs allowed to access a given content, and one or more to get these user profiles. However, this should not really be a problem as K/V stores usually have very high performances.</p>
| 2 |
2016-09-15T18:28:42Z
|
[
"python",
"database",
"nosql",
"authorization",
"key-value"
] |
Delete a file after reading
| 39,423,763 |
<p>In my code, user uploads file which is saved on server and read using the server path. I'm trying to delete the file from that path after I'm done reading it. But it gives me following error instead:</p>
<p><code>An error occurred while reading file. [WinError 32] The process cannot access the file because it is being used by another process</code></p>
<p>I'm reading file using <code>with</code>, and I've tried <code>f.close()</code> and also <code>f.closed</code> but its the same error every time.</p>
<p>This is my code:</p>
<pre><code>f = open(filePath)
with f:
line = f.readline().strip()
tempLst = line.split(fileSeparator)
if(len(lstHeader) != len(tempLst)):
headerErrorMsg = "invalid headers"
hjsonObj["Line No."] = 1
hjsonObj["Error Detail"] = headerErrorMsg
data['lstErrorData'].append(hjsonObj)
data["status"] = True
f.closed
return data
f.closed
</code></pre>
<p>after this code I call the remove function:</p>
<pre><code>os.remove(filePath)
</code></pre>
<p><strong>Edit:</strong> using <code>with open(filePath) as f:</code> and then trying to remove the file gives the same error. </p>
| 0 |
2016-09-10T07:32:39Z
| 39,423,793 |
<p>Instead of:</p>
<pre><code> f.closed
</code></pre>
<p>You need to say:</p>
<pre><code>f.close()
</code></pre>
<p><code>closed</code> is just a boolean property on the file object to indicate if the file is actually closed.</p>
<p><code>close()</code> is method on the file object that actually closes the file.</p>
<p>Side note: attempting a file delete after closing a file handle is not 100% reliable. The file might still be getting scanned by the virus scanner or indexer. Or some other system hook is holding on to the file reference, etc... If the delete fails, wait a second and try again.</p>
| 2 |
2016-09-10T07:37:03Z
|
[
"python",
"file"
] |
Delete a file after reading
| 39,423,763 |
<p>In my code, user uploads file which is saved on server and read using the server path. I'm trying to delete the file from that path after I'm done reading it. But it gives me following error instead:</p>
<p><code>An error occurred while reading file. [WinError 32] The process cannot access the file because it is being used by another process</code></p>
<p>I'm reading file using <code>with</code>, and I've tried <code>f.close()</code> and also <code>f.closed</code> but its the same error every time.</p>
<p>This is my code:</p>
<pre><code>f = open(filePath)
with f:
line = f.readline().strip()
tempLst = line.split(fileSeparator)
if(len(lstHeader) != len(tempLst)):
headerErrorMsg = "invalid headers"
hjsonObj["Line No."] = 1
hjsonObj["Error Detail"] = headerErrorMsg
data['lstErrorData'].append(hjsonObj)
data["status"] = True
f.closed
return data
f.closed
</code></pre>
<p>after this code I call the remove function:</p>
<pre><code>os.remove(filePath)
</code></pre>
<p><strong>Edit:</strong> using <code>with open(filePath) as f:</code> and then trying to remove the file gives the same error. </p>
| 0 |
2016-09-10T07:32:39Z
| 39,423,869 |
<p>This</p>
<pre><code>import os
path = 'path/to/file'
with open(path) as f:
for l in f:
print l,
os.remove(path)
</code></pre>
<p>should work, with statement will automatically close the file after the nested block of code</p>
<p>if it fails, File could be in use by some external factor. you can use Redo pattern.</p>
<pre><code>while True:
try:
os.remove(path)
break
except:
time.sleep(1)
</code></pre>
| 1 |
2016-09-10T07:47:10Z
|
[
"python",
"file"
] |
Python: Issue with POST data in Requests
| 39,423,868 |
<p>I'm trying to use the <strong>Requests 2.9.1</strong> in <strong>Python 2.7</strong> to learn how to send <strong>POST</strong> data. However I feel that I'm missing something in the data I'm providing to <strong>requests</strong>, or somehow misformating something and have been banging my head at it all night.</p>
<p>The site I'm basing the form data off of is : <a href="http://qpublic9.qpublic.net/la_orleans_address.php" rel="nofollow">http://qpublic9.qpublic.net/la_orleans_address.php</a></p>
<p>I used Charles (<a href="https://www.charlesproxy.com" rel="nofollow">https://www.charlesproxy.com</a>) to see the actual content of the POST data, and here is what I saw. The data I entered was <strong>1013</strong> for the <strong>Street Number</strong> (field is <strong>streetNumber</strong>) and ST ANN (relying on the autocomplete) for the *Street Name** (<strong>streetName</strong> is the field here). This is all I needed to enter on the website manually, and I received this POST data from Charles:</p>
<pre><code>BEGIN=0&searchType=address_search&streetNumber=1013&streetName=ST+ANN&streetType=&streetDirection=&streetUnit=&Address+Search=Address+Search
</code></pre>
<p>Originally I was trying with just the <strong>streetNumber</strong> and <strong>streetName</strong>, since that was the only data I input when testing from the website, but this produced an error. Now I'm entering null fields for the data that has nothing entered, I'm guessing this might be causing the problem but I'm not sure. Below is what I'm using for code, followed by the error message I'm receiving (which is an SQL error message, making me think there's something wrong with the way I'm formatting the data payload perhaps).</p>
<pre><code>import requests
payload = {'searchType': 'address_search', 'streetNumber': '1013', \
'streetName': 'ST+ANN', 'streetType': '', 'streetDirection': '', \
'streetUnit': '', 'Address+Search': 'Address+Search' }
response = requests.post("http://qpublic9.qpublic.net/la_orleans_alsearch.php", \
data=payload)
print response.text
</code></pre>
<p>The output and error:</p>
<pre><code><LINK REL=stylesheet HREF="http://www.qpublic.net/la/neworleans/sytle.css"
TYPE="text/css">
Could Not Read Data:You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near ' 100' at line 1
</code></pre>
<p>Since I'm just a user, and not a developer for the site, I don't have access to see what their backend code looks like, but since it works from the site in my browser I'm guessing it's something to do with my <strong>payload</strong> formatting rather than their code.</p>
<p>Any suggestions on what I might be missing? Or any experience with similar problems? No matter how many empty fields I remove I end up with that same error.</p>
<p>Thanks!</p>
<p><strong>EDIT:</strong> In my code I'm not using the backslashes for the python code, I'm using that here for easier reading. Also the error message doesn't have line breaks in it, again just for readability. Since I'm not familiar with the structure of POST data I'm leaving that as is from Charles in case changing something might cause a miscommunication.</p>
<p><strong>EDIT 2:</strong> Also I'm receiving a response code of 200 (<strong></strong>) when I test for that, so it doesn't appear to be an error with the connection over HTTP, so again that makes me think I'm missing something with the POST data.</p>
| 0 |
2016-09-10T07:47:09Z
| 39,423,960 |
<p>Take out all the <code>+</code> characters that you put between words. That's the URL-encoded representation of space, but the <code>requests</code> module does that for you. If you use it explicitly, it will re-encode the <code>+</code>, so the server script will see it as a literal <code>+</code>, not the space that it should be decoded to.</p>
<p>You're also missing the <code>BEGIN=0</code> parameter in <code>payload</code>. In my tests, that seems to be the cause of the error you're getting.</p>
<pre><code>payload = {'BEGIN': '0', 'searchType': 'address_search', 'streetNumber': '1013', \
'streetName': 'ST ANN', 'streetType': '', 'streetDirection': '',
'streetUnit': '', 'Address Search': 'Address Search' }
</code></pre>
<p>If you look in the web page source, that's one of the hidden inputs:</p>
<pre><code><INPUT TYPE=HIDDEN NAME=BEGIN VALUE="0">
<INPUT TYPE=HIDDEN NAME="searchType" VALUE="address_search">
</code></pre>
| 0 |
2016-09-10T08:00:24Z
|
[
"python",
"python-2.7",
"http-post",
"python-requests"
] |
ImportError: No module named scrapyproject.settings
| 39,423,917 |
<p>I have a scrapy project, the idea is to execute crawler and get the result back. I am using Flask as api end application and also using virtualenvironment.</p>
<pre><code>from scrapy.spiderloader import SpiderLoader
from scrapy.utils.project import get_project_settings
@app.route("/")
def hello():
settings = get_project_settings()
loader = SpiderLoader(settings)
spiders = loader.list()
// validate spider
cmd = "scrapy crawl test --nolog --output-format=json -o -"
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output = proc.stdout.read()
return Response(output, mimetype='application/json')
</code></pre>
<p>The problem is when the lines below are used inside executing the subprocess</p>
<pre><code>settings = get_project_settings()
loader = SpiderLoader(settings)
spiders = loader.list()
</code></pre>
<p>the result is empty and it throws exceptions</p>
<pre><code>Traceback (most recent call last):
File "/var/www/projects/ENV/bin/scrapy", line 11, in <module>
sys.exit(execute())
File "/var/www/projects/ENV/local/lib/python2.7/site-packages/scrapy/cmdline.py", line 108, in execute
settings = get_project_settings()
File "/var/www/projects/ENV/local/lib/python2.7/site-packages/scrapy/utils/project.py", line 60, in get_project_settings
settings.setmodule(settings_module_path, priority='project')
File "/var/www/projects/ENV/local/lib/python2.7/site-packages/scrapy/settings/__init__.py", line 282, in setmodule
module = import_module(module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named scrapyproject.settings
</code></pre>
<p>When the code to get the spiders list is commented it executes the test spider without any issues.</p>
<p>It is worth to note that the code to get all the spiders works fine.</p>
<pre><code>@app.route("/spiders")
def spiders():
settings = get_project_settings()
loader = SpiderLoader(settings)
jsonify(loader.list())
</code></pre>
<p>I have also looked into a few questions / answers mentioning it may be problem with virtualenvironment. But wondering why it only behaves when certain code is executed.</p>
<p>If you are wondering why I have not used / executed <a href="http://doc.scrapy.org/en/latest/topics/practices.html#run-scrapy-from-a-script" rel="nofollow">scrapy via script</a> . What I need is to get the output without saving to any file system or db or anything via pipeline.</p>
| 0 |
2016-09-10T07:54:07Z
| 39,452,811 |
<p><a href="https://twitter.com/chrisguitarguy/status/775155136452624384" rel="nofollow">Christopher Davis</a> mentioned to pass the environment copy to subprocess.</p>
<pre><code>proc = subprocess.Popen(..., env=os.environ.copy())
</code></pre>
<p>Which actually opened my eye to notice the introduction of <code>SCRAPY_SETTINGS_MODULE</code> once the <code>get_project_settings()</code> is called, which in turn when running the command to execute <code>scrapy</code> feels it is loaded. But not truly loaded. </p>
<p>So the solution is remove the environment variable as </p>
<pre><code>del os.environ['SCRAPY_SETTINGS_MODULE']
</code></pre>
<p>before you call the subprocess. </p>
<p>Hope that will help someone and save their time.</p>
<p>Thank you</p>
| 0 |
2016-09-12T14:33:12Z
|
[
"python",
"scrapy",
"scrapy-spider"
] |
More precise time for python-bunyan logger?
| 39,423,954 |
<p>I've been using <code>bunyan</code> logger for <code>nodejs</code>, so when I had to program in <code>python</code> again I went out and found a compatible logger for <code>python</code>.</p>
<p><a href="https://github.com/Sagacify/logger-python" rel="nofollow">https://github.com/Sagacify/logger-python</a></p>
<p><a href="https://pypi.python.org/pypi/bunyan/0.1.2" rel="nofollow">https://pypi.python.org/pypi/bunyan/0.1.2</a></p>
<p>The problem is, this formatter only log time to second but I need at least millisecond precision. What would be the easiest way of achieving this?</p>
| 0 |
2016-09-10T07:59:22Z
| 39,464,009 |
<p>Milliseconds would be a bit of a hack, but you can add microseconds really easily.</p>
<p>Here:</p>
<p><a href="https://github.com/Sagacify/logger-python/blob/master/bunyan/formatter.py#L106" rel="nofollow">https://github.com/Sagacify/logger-python/blob/master/bunyan/formatter.py#L106</a></p>
<p>You would need to replace "%Y-%m-%dT%H:%M:%SZ" by "%Y-%m-%dT%H:%M:%S%fZ"</p>
<p>Notice the added %f .
(I'm actually the maintainer of saga-logger and we should be doing this as well but I haven't had the time to do it as of now.)</p>
| 0 |
2016-09-13T07:03:19Z
|
[
"python",
"logging",
"bunyan"
] |
Order of comparison for heap elements in python
| 39,423,979 |
<p>I'm using a heap to make a priority queue using heapq.</p>
<p>I insert an item into the queue using</p>
<p><code>heapq.heappush(h, (cost, node))</code></p>
<p>where <code>h</code> is the heap object, <code>cost</code> is the item by which I order my heap and <code>node</code> is an object of a custom defined class. </p>
<p>When I run the code, I get the following error when I insert two different items in <code>h</code> with the same <code>cost</code></p>
<blockquote>
<p>TypeError: unorderable types: SearchNode() < SearchNode()</p>
</blockquote>
<p>where <code>SearchNode()</code> is the class of <code>node</code></p>
<p>The error makes it clear that Python is comparing the second item.</p>
<p><strong>Is there an order of comparison for the heap elements?</strong> If yes, how can I resolve ties in the algorithm such that it does not start comparing the second item. One possible solution that comes to my mind is to overload the comparison operators for the <code>SearchNode()</code> class. </p>
<p>I'm very new to python so feel free to point out if I am missing something very obvious. </p>
| 2 |
2016-09-10T08:02:58Z
| 39,424,139 |
<p>Introduce a small class that doesn't include the node in the comparison:</p>
<pre><code>class CostAndNode:
def __init__(self, cost, node):
self.cost = cost
self.node = node
# do not compare nodes
def __lt__(self, other):
return self.cost < other.cost
h = []
heapq.heappush(h, CostAndNode(1, node1))
heapq.heappush(h, CostAndNode(1, node2))
</code></pre>
| 2 |
2016-09-10T08:25:36Z
|
[
"python",
"algorithm",
"python-3.x",
"sorting",
"heap"
] |
Order of comparison for heap elements in python
| 39,423,979 |
<p>I'm using a heap to make a priority queue using heapq.</p>
<p>I insert an item into the queue using</p>
<p><code>heapq.heappush(h, (cost, node))</code></p>
<p>where <code>h</code> is the heap object, <code>cost</code> is the item by which I order my heap and <code>node</code> is an object of a custom defined class. </p>
<p>When I run the code, I get the following error when I insert two different items in <code>h</code> with the same <code>cost</code></p>
<blockquote>
<p>TypeError: unorderable types: SearchNode() < SearchNode()</p>
</blockquote>
<p>where <code>SearchNode()</code> is the class of <code>node</code></p>
<p>The error makes it clear that Python is comparing the second item.</p>
<p><strong>Is there an order of comparison for the heap elements?</strong> If yes, how can I resolve ties in the algorithm such that it does not start comparing the second item. One possible solution that comes to my mind is to overload the comparison operators for the <code>SearchNode()</code> class. </p>
<p>I'm very new to python so feel free to point out if I am missing something very obvious. </p>
| 2 |
2016-09-10T08:02:58Z
| 39,424,234 |
<p>If you can sensibly decide on a way to compare nodes, you could use this to break ties. For example, each node may be assigned a "label", which you can guarantee to be unique. You could break ties by comparing labels lexicographically.#</p>
<pre><code>class SearchNode:
def __init__(self, label):
self.label = label
#etc
def __lt__(self, other):
return self.label < other.label
</code></pre>
<p>This would ensure that comparisons of <code>(cost, node)</code> is deterministic.</p>
| 2 |
2016-09-10T08:36:32Z
|
[
"python",
"algorithm",
"python-3.x",
"sorting",
"heap"
] |
Order of comparison for heap elements in python
| 39,423,979 |
<p>I'm using a heap to make a priority queue using heapq.</p>
<p>I insert an item into the queue using</p>
<p><code>heapq.heappush(h, (cost, node))</code></p>
<p>where <code>h</code> is the heap object, <code>cost</code> is the item by which I order my heap and <code>node</code> is an object of a custom defined class. </p>
<p>When I run the code, I get the following error when I insert two different items in <code>h</code> with the same <code>cost</code></p>
<blockquote>
<p>TypeError: unorderable types: SearchNode() < SearchNode()</p>
</blockquote>
<p>where <code>SearchNode()</code> is the class of <code>node</code></p>
<p>The error makes it clear that Python is comparing the second item.</p>
<p><strong>Is there an order of comparison for the heap elements?</strong> If yes, how can I resolve ties in the algorithm such that it does not start comparing the second item. One possible solution that comes to my mind is to overload the comparison operators for the <code>SearchNode()</code> class. </p>
<p>I'm very new to python so feel free to point out if I am missing something very obvious. </p>
| 2 |
2016-09-10T08:02:58Z
| 39,425,025 |
<p>PQ with list and <code>bisect</code>, strings as stored objects for example. No changes in stored object required. Just construct <code>item = (cost, object)</code> and insert it in PQ.</p>
<pre><code>import bisect
# PQ of items
PQ = [
(10, 'aaa'),
(30, 'cccc'),
(40, 'dddd'),
]
def pq_insert(pq, item):
keys = [e[0] for e in pq]
i = bisect.bisect(keys, item[0])
pq.insert(i, item)
e = (20, 'bbbb')
pq_insert(PQ, e)
</code></pre>
<p>Some REPL output</p>
<pre><code>>>> print PQ
[(10, 'aaa'), (30, 'cccc'), (40, 'dddd')]
>>> e = (20, 'bbbb')
>>> pq_insert(PQ, e)
>>> print PQ
[(10, 'aaa'), (20, 'bbbb'), (30, 'cccc'), (40, 'dddd')]
>>>
</code></pre>
| -1 |
2016-09-10T10:14:50Z
|
[
"python",
"algorithm",
"python-3.x",
"sorting",
"heap"
] |
TypeError: list indicies must be integers, not str
| 39,424,037 |
<pre><code>foo = ("PandaBears")
l = list(foo)
random.shuffle(l)
Output = ''.join(l)
print(Output)
</code></pre>
<p>I have been at this code for ages trying to figure out the problem but I have had no luck. A few hours before it was working perfectly with absolutely no trouble - <code>I haven't even changed / upgraded python either.</code> </p>
<p>The error is coming from </p>
<blockquote>
<p>l = list(idf) </p>
</blockquote>
<p>and I have tried using <code>[]</code> instead of <code>()</code>. </p>
<p>Any improvements on this code would be appreciated</p>
| -4 |
2016-09-10T08:11:13Z
| 39,424,130 |
<p>The parenthesis are useless here:</p>
<pre><code>foo = ("PandaBears")
</code></pre>
<p>Just write:</p>
<pre><code>foo = "PandaBears" # str
</code></pre>
<p>If you want a singleton <code>tuple</code>, add a trailing comma:</p>
<pre><code>foo = ("PandaBears",) # tuple
</code></pre>
<p>If <code>foo</code> is a string, the following statement construct a list of letters:</p>
<pre><code>l = list(foo)
</code></pre>
<p>Don't know what is <code>diff</code>. </p>
| 1 |
2016-09-10T08:24:28Z
|
[
"python",
"list",
"python-3.x"
] |
How to set coordinates when cropping an image with PIL?
| 39,424,052 |
<p>I don't know how to set the coordinates to crop an image in <code>PIL</code>s <code>crop()</code>:</p>
<pre><code>from PIL import Image
img = Image.open("Supernatural.xlsxscreenshot.png")
img2 = img.crop((0, 0, 201, 335))
img2.save("img2.jpg")
</code></pre>
<p>I tried with <code>gThumb</code> to get coordinates, but if I take an area which I would like to crop, I can only find position 194 336. Could someone help me please?</p>
<p>This is my picture:</p>
<p><a href="http://i.stack.imgur.com/1twQc.png" rel="nofollow"><img src="http://i.stack.imgur.com/1twQc.png" alt="enter image description here"></a></p>
<p>I wish to crop to this:</p>
<p><a href="http://i.stack.imgur.com/hxqTZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/hxqTZ.png" alt="enter image description here"></a></p>
| 1 |
2016-09-10T08:13:11Z
| 39,424,357 |
<h3>How to set the coordinates to crop</h3>
<p>In the line:</p>
<pre><code>img2 = img.crop((0, 0, 201, 335))
</code></pre>
<p>the first two numbers define the <em>top-left</em> coordinates of the outtake (x,y), while the last two define the <em>right-bottom</em> coordinates of the outtake.</p>
<h3>Cropping your image</h3>
<p>To crop your image like you show, I found the following coordinates: top-left: <code>(200, 330)</code>, and right-bottom: <code>(730, 606)</code>. Subsequently, I cropped your image with:</p>
<pre><code>img2 = img.crop((200, 330, 730, 606))
</code></pre>
<p><a href="http://i.stack.imgur.com/UB7ho.png" rel="nofollow"><img src="http://i.stack.imgur.com/UB7ho.png" alt="enter image description here"></a></p>
<p>with the result:</p>
<p><a href="http://i.stack.imgur.com/GKMIR.png" rel="nofollow"><img src="http://i.stack.imgur.com/GKMIR.png" alt="enter image description here"></a></p>
| 1 |
2016-09-10T08:53:38Z
|
[
"python",
"image",
"python-2.7",
"python-3.x",
"image-processing"
] |
How to get an outgoing message ID in telepot module?
| 39,424,071 |
<p>I'm using telepot module to create a telegram bot using python.
I need to get the message Id of an outgoing message to be able to check if the user will reply to that message or not. The piece of code below clarifies what I want to do:</p>
<pre><code>import telepot
bot = telepot.Bot('Some Token')
def handle(msg):
chat_id = msg['chat']['id']
message_id = msg['message_id'] # I can get Id of incoming messages here
command = msg['text']
if command == '/command': # Message (incoming) 1 sent by user
bot.sendMessage(chat_id, 'Some message') # Message (outgoing) 2 sent by bot
elif ('''msg was in reply of message 2'''): # Message (incoming) 3 sent by user (MY PROBLEM IS HERE!!!)
# Do something
pass
bot.message_loop(handle, run_forever = 'Running ...')
</code></pre>
<p>So as you can see in the code above I need to check if message 3 was in reply to message 2. However, I can't get the ID of message 2 because it's an outgoing message from bot (Not an incoming message by user which I can get it's ID).
So how can I achieve that?</p>
<p>thanks.</p>
| 0 |
2016-09-10T08:16:39Z
| 39,432,838 |
<p>You should be able to get <code>message_id</code> of the sent message:</p>
<pre><code>>>> import telepot
>>> from pprint import pprint
>>> bot = telepot.Bot('TOKEN')
>>> sent = bot.sendMessage(9999999, 'Hello')
>>> pprint(sent)
{u'chat': {u'first_name': u'Nick', u'id': 9999999, u'type': u'private'},
u'date': 1473567584,
u'from': {u'first_name': u'My Bot',
u'id': 111111111,
u'username': u'MyBot'},
u'message_id': 21756,
u'text': u'Hello'}
</code></pre>
| 1 |
2016-09-11T04:24:20Z
|
[
"python",
"telegram",
"telegram-bot",
"python-telegram-bot"
] |
read yelp api response
| 39,424,127 |
<p>Iam new to python & API searches. I am having issues reading yelp API responses in python. any help would be great. thanks.</p>
<pre><code>> params = {
> 'term': 'lunch,pancakes' }
> response=client.search('Los Angeles',**params)
</code></pre>
<p>Here is the output:</p>
<pre><code><yelp.obj.search_response.SearchResponse object at 0x138ad7a58>
</code></pre>
| 0 |
2016-09-10T08:23:55Z
| 39,425,466 |
<p><code>SearchResponse</code> contains the <code>businesses</code> list that will match your term [1].</p>
<p>Try this:</p>
<pre><code>for business in response['businesses']:
print(business['name'])
</code></pre>
<p>[1] <a href="https://www.yelp.com/developers/documentation/v2/search_api" rel="nofollow">https://www.yelp.com/developers/documentation/v2/search_api</a></p>
| 0 |
2016-09-10T11:14:05Z
|
[
"python",
"api",
"yelp"
] |
Splitting strings inside a pandas dataframe
| 39,424,131 |
<p>I have a dataframe with one row that has a list like structure</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'Name':['Stooge, Nick','Dick, Tracy','Rick, Nike','Maw','El','Paw, Maw, Haw','Caw', 'Greep'],
'key':[2,2,2,1,1,3,1,1,],
'Lastname':['Smith, Foo','Johnson, Macy','Johnson, Sike','Simpson','Diablo','Simpson, Sampson, Simmons','Simpson', 'Mortimer']
})
df.ix[df['key'] == 2, 'Full'] = df['Name']+', ' + df['Lastname']
df.ix[df['key'] == 1, 'Full'] = df['Name']+' ' + df['Lastname']
print(df)
</code></pre>
<p>Output:</p>
<pre><code> Lastname Name key Full
0 Smith, Foo Stooge, Nick 2 Stooge, Nick, Smith, Foo
1 Johnson, Macy Dick, Tracy 2 Dick, Tracy, Johnson, Macy
2 Johnson, Sike Rick, Nike 2 Rick, Nike, Johnson, Sike
3 Simpson Maw 1 Maw Simpson
4 Diablo El 1 El Diablo
5 Simpson, Sampson, Simmons Paw, Maw, Haw 3 NaN
6 Simpson Caw 1 Caw Simpson
7 Mortimer Greep 1 Greep Mortimer
</code></pre>
<p>Is there a way manipulate or split the string inside the dataframe by the comma so it produces results like:</p>
<pre><code> Lastname Name key Full
0 Smith, Foo Stooge, Nick 2 Stooge Smith and Nick Foo
1 Johnson, Macy Dick, Tracy 2 Dick Johnson and Tracy Macy
2 Johnson, Sike Rick, Nike 2 Rick Johnson and Nike Sike
3 Simpson Maw 1 Maw Simpson
4 Diablo El 1 El Diablo
5 Simpson, Sampson, Simmons Paw, Maw, Haw 3 NaN
6 Simpson Caw 1 Caw Simpson
7 Mortimer Greep 1 Greep Mortimer
</code></pre>
| 2 |
2016-09-10T08:24:38Z
| 39,424,376 |
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">apply()</a>:</p>
<pre><code>In [63]: df
Out[63]:
Lastname Name key Full
0 Smith, Foo Stooge, Nick 2 Stooge, Nick, Smith, Foo
1 Johnson, Macy Dick, Tracy 2 Dick, Tracy, Johnson, Macy
2 Johnson, Sike Rick, Nike 2 Rick, Nike, Johnson, Sike
3 Simpson Maw 1 Maw Simpson
4 Diablo El 1 El Diablo
5 Simpson, Sampson, Simmons Paw, Maw, Haw 3 NaN
6 Simpson Caw 1 Caw Simpson
7 Mortimer Greep 1 Greep Mortimer
In [64]: def get_full_name(row):
...: if ',' in str(row.Full):
...: z = row.Full.split(',')
...: x = z[::2]
...: y = z[1::2]
...: return ' and '.join(map(lambda(first, last): ' '.join([first, last]), zip(z, y)))
...: return row.Full
...:
In [65]: df['Full'] = df.apply(get_full_name, axis = 1)
In [66]: df
Out[66]:
Lastname Name key Full
0 Smith, Foo Stooge, Nick 2 Stooge Nick and Nick Foo
1 Johnson, Macy Dick, Tracy 2 Dick Tracy and Tracy Macy
2 Johnson, Sike Rick, Nike 2 Rick Nike and Nike Sike
3 Simpson Maw 1 Maw Simpson
4 Diablo El 1 El Diablo
5 Simpson, Sampson, Simmons Paw, Maw, Haw 3 NaN
6 Simpson Caw 1 Caw Simpson
7 Mortimer Greep 1 Greep Mortimer
</code></pre>
| 0 |
2016-09-10T08:56:19Z
|
[
"python",
"pandas"
] |
Splitting strings inside a pandas dataframe
| 39,424,131 |
<p>I have a dataframe with one row that has a list like structure</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'Name':['Stooge, Nick','Dick, Tracy','Rick, Nike','Maw','El','Paw, Maw, Haw','Caw', 'Greep'],
'key':[2,2,2,1,1,3,1,1,],
'Lastname':['Smith, Foo','Johnson, Macy','Johnson, Sike','Simpson','Diablo','Simpson, Sampson, Simmons','Simpson', 'Mortimer']
})
df.ix[df['key'] == 2, 'Full'] = df['Name']+', ' + df['Lastname']
df.ix[df['key'] == 1, 'Full'] = df['Name']+' ' + df['Lastname']
print(df)
</code></pre>
<p>Output:</p>
<pre><code> Lastname Name key Full
0 Smith, Foo Stooge, Nick 2 Stooge, Nick, Smith, Foo
1 Johnson, Macy Dick, Tracy 2 Dick, Tracy, Johnson, Macy
2 Johnson, Sike Rick, Nike 2 Rick, Nike, Johnson, Sike
3 Simpson Maw 1 Maw Simpson
4 Diablo El 1 El Diablo
5 Simpson, Sampson, Simmons Paw, Maw, Haw 3 NaN
6 Simpson Caw 1 Caw Simpson
7 Mortimer Greep 1 Greep Mortimer
</code></pre>
<p>Is there a way manipulate or split the string inside the dataframe by the comma so it produces results like:</p>
<pre><code> Lastname Name key Full
0 Smith, Foo Stooge, Nick 2 Stooge Smith and Nick Foo
1 Johnson, Macy Dick, Tracy 2 Dick Johnson and Tracy Macy
2 Johnson, Sike Rick, Nike 2 Rick Johnson and Nike Sike
3 Simpson Maw 1 Maw Simpson
4 Diablo El 1 El Diablo
5 Simpson, Sampson, Simmons Paw, Maw, Haw 3 NaN
6 Simpson Caw 1 Caw Simpson
7 Mortimer Greep 1 Greep Mortimer
</code></pre>
| 2 |
2016-09-10T08:24:38Z
| 39,433,920 |
<pre><code>ln = df.Lastname.str.split(r',\s*', expand=True).stack()
fn = df.Name.str.split(r',\s*', expand=True).stack()
df['full'] = fn.add(' ').add(ln).groupby(level=0).apply(tuple).str.join(' and ')
df
</code></pre>
<p><a href="http://i.stack.imgur.com/wLaOT.png" rel="nofollow"><img src="http://i.stack.imgur.com/wLaOT.png" alt="enter image description here"></a></p>
| 3 |
2016-09-11T07:43:27Z
|
[
"python",
"pandas"
] |
Python: Elegant way to increment a global variable
| 39,424,184 |
<blockquote>
<p>Elegant way to increment a global variable in Python:</p>
</blockquote>
<p>This is what I have so far:</p>
<pre><code>my_i = -1
def get_next_i():
global my_i
my_i += 1
return my_i
</code></pre>
<p>with generator:</p>
<pre><code>my_iter = iter(range(100000000))
def get_next_i():
return next(my_iter)
</code></pre>
<p>with class:</p>
<pre><code>class MyI:
MyI.my_i = -1
@staticmethod
def next():
MyI.my_i += 1
return MyI.my_i
</code></pre>
<ul>
<li>The first one is long and I don't consider it as a better way to code .</li>
<li>The second one is a bit more elegant, but have an upper limit.</li>
<li>The third one is long, but at least have no global variable to work with.</li>
</ul>
<p><strong>What would be the best alternative to those?</strong></p>
<blockquote>
<p>The purpose of these functions is to assign a unique number to a specific event in my code. The code is not just a single loop, so using <code>for i in range(...):</code> is not suitable here. A later version might use multiple indices assigned to different events. The first code would require duplication to solve such an issue. (<code>get_next_i()</code>, <code>get_next_j()</code>, ...)</p>
</blockquote>
<p>Thank You.</p>
| 2 |
2016-09-10T08:31:46Z
| 39,424,305 |
<p>You can create a generator that has an infinite loop. Each call of <code>next(generator)</code> will return a next value, without limit. See <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python?rq=1">What does the "yield" keyword do in Python?</a> </p>
<pre><code>def create_generator()
i=0
while True:
i+=1
yield i
generator = create_generator()
print(next(generator))
print(next(generator))
</code></pre>
| 2 |
2016-09-10T08:45:51Z
|
[
"python",
"python-3.x",
"for-loop",
"iterator",
"generator"
] |
Python: Elegant way to increment a global variable
| 39,424,184 |
<blockquote>
<p>Elegant way to increment a global variable in Python:</p>
</blockquote>
<p>This is what I have so far:</p>
<pre><code>my_i = -1
def get_next_i():
global my_i
my_i += 1
return my_i
</code></pre>
<p>with generator:</p>
<pre><code>my_iter = iter(range(100000000))
def get_next_i():
return next(my_iter)
</code></pre>
<p>with class:</p>
<pre><code>class MyI:
MyI.my_i = -1
@staticmethod
def next():
MyI.my_i += 1
return MyI.my_i
</code></pre>
<ul>
<li>The first one is long and I don't consider it as a better way to code .</li>
<li>The second one is a bit more elegant, but have an upper limit.</li>
<li>The third one is long, but at least have no global variable to work with.</li>
</ul>
<p><strong>What would be the best alternative to those?</strong></p>
<blockquote>
<p>The purpose of these functions is to assign a unique number to a specific event in my code. The code is not just a single loop, so using <code>for i in range(...):</code> is not suitable here. A later version might use multiple indices assigned to different events. The first code would require duplication to solve such an issue. (<code>get_next_i()</code>, <code>get_next_j()</code>, ...)</p>
</blockquote>
<p>Thank You.</p>
| 2 |
2016-09-10T08:31:46Z
| 39,424,883 |
<p>As others suggested, <code>itertools.count()</code> is the best option, e.g.</p>
<pre><code>import itertools
global_counter1 = itertools.count()
global_counter2 = itertools.count()
# etc.
</code></pre>
<p>And then, when you need it, simply call <code>next</code>:</p>
<pre><code>def some_func():
next_id = global_counter1.next()
</code></pre>
| 1 |
2016-09-10T09:55:34Z
|
[
"python",
"python-3.x",
"for-loop",
"iterator",
"generator"
] |
python problam subprocess fore rub script bash
| 39,424,275 |
<p>i have problem in subprocess
i have this script bash which good work and is name kamel.sh</p>
<pre><code>to=$1
subject=$1
/root/Desktop/telegram/tg/bin/./telegram-cli -k /root/Desktop/telegram/tg/tg-server.pub -WR -e "msg $to $subject"
</code></pre>
<p>but i want use python fore work.is 1.sh give 2 argv fore work and argv1 = user and argv2 = hello
but is have problem </p>
<pre><code>import subprocess
subprocess.call("1.sh", user, hello, shell=True )
</code></pre>
<p>and i see this eroore</p>
<pre><code>Traceback (most recent call last):
File "/root/Desktop/telegram-log/kamel.py", line 27, in <module>
subprocess.call("kamel.sh testt",kol,shell=True )
File "/usr/lib/python2.7/subprocess.py", line 523, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 660, in __init__
raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer
</code></pre>
| -1 |
2016-09-10T08:41:12Z
| 39,424,304 |
<pre><code>import subprocess
subprocess.call("1.sh user hello", shell=True)
</code></pre>
<p>or</p>
<pre><code>import subprocess
subprocess.call(["1.sh", "user", "hello"])
</code></pre>
| 0 |
2016-09-10T08:45:36Z
|
[
"python"
] |
How would I make this code run completely without error so that age is assigned correctly according to the date they enter?
| 39,424,329 |
<pre><code>from random import randint
def main():
dob = int(input("Please enter the year you were born"))
if dob > (2005):
main()
elif dob < (2004):
main()
else:
def mob():
if dob == (2004):
month = input("Please enter the first three letters of the month you were born")
if month == ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul"):
age = 12
elif month == ("Aug","AUG","aug"):
day = int(input("Please input the day you were born"))
if day < 28:
age = 12
elif day == ("29","30","31"):
age = 11
else:
age = 12
else:
age = 11
if dob == (2005):
age = 11
mob()
main()
</code></pre>
<p>If I were to enter 2004 and then 'aug', it would not ask the day of birth.The code would stop. I also want the code to run so that if I were to enter 2005, it would assign age to 11</p>
| -3 |
2016-09-10T08:49:53Z
| 39,424,680 |
<p>Something like this does what you need, I think, though you could tidy it further to give the actual age, by using datetime.</p>
<pre><code>def main():
yob = int(input("Please enter the year you were born"))
if yob > 2005:
return "Under 11"
elif yob < 2004:
return "Over 12"
elif yob == 2004:
return 12
else:
mob = input("Enter a three letter abbreviation for your month of birth: "
if mob.lower() in ("jan", "feb", "mar", "apr", "may", "jun", "jul"):
return 12
elif mob.lower() == "aug":
dob = int(input("Enter your day of birth"))
if dob < 28:
return 12
elif dob > 28:
return 11
else:
return 11
age = main()
</code></pre>
<p>Better alternative, covers most eventualities I think</p>
<pre><code>from datetime import datetime
def give_age():
today = datetime.today()
dob = input("Enter your date of birth (DD/MM/YYYY): ")
try:
dob_datetime = datetime.strptime(dob, "%d/%m/%Y")
age = (today - dob_datetime).days / 365
return age
except ValueError:
print("Your date of birth was not in the required format")
give_age()
age = give_age()
</code></pre>
| 2 |
2016-09-10T09:32:48Z
|
[
"python",
"python-3.x"
] |
nested directory appear while creating zip file
| 39,424,402 |
<p>I am quite new to python.Here i am trying to create zip file of "diveintomark-diveintopython3-793871b' directory.I changed the current working directory using os.chdir() function.The zip file is created but the problem is when i extract the zip file i get the the following directory</p>
<pre><code>Users/laiba/Desktop/diveintomark-diveintopython3-793871b
</code></pre>
<p>but i only want <strong>diveintomark-diveintopython3-793871b</strong> folder inside my zip folder not the whole nested directory created .Why is this happening and how i can solve this?</p>
<pre><code>import zipfile, os
os.chdir('c:\\Users\\laiba\\Desktop')
myzip=zipfile.ZipFile('diveZip.zip','w',zipfile.ZIP_DEFLATED)
for folder,subfolder,file in os.walk('diveintomark-diveintopython3-793871b'):
myzip.write(folder)
for each in subfolder:
myzip.write(os.path.abspath(os.path.join(folder,each)))
for each in file:
myzip.write(os.path.abspath(os.path.join(folder,each)))
</code></pre>
| 0 |
2016-09-10T08:59:57Z
| 39,424,500 |
<p>you could use argument <code>arcname</code>: name of the item in the archive as opposed to the full path name. But here you don't need it because you already are in the correct directory. Just drop the <code>abspath</code> and you're done (and also the duplicate folder entry)</p>
<pre><code>import zipfile, os
os.chdir('c:\\Users\\laiba\\Desktop')
myzip=zipfile.ZipFile('diveZip.zip','w',zipfile.ZIP_DEFLATED)
for folder,subfolder,file in os.walk('diveintomark-diveintopython3-793871b'):
for each in subfolder+file:
myzip.write(os.path.join(folder,each))
myzip.close()
</code></pre>
<p>This is possible to do without changing directories but more complex, also more elegant since you don't have to chdir</p>
<pre><code>import zipfile, os
root_dir = r"c:\Users\laiba\Desktop"
myzip=zipfile.ZipFile(os.path.join(root_dir,'diveZip.zip'),'w',zipfile.ZIP_DEFLATED)
for folder,subfolder,file in os.walk(os.path.join(root_dir,'diveintomark-diveintopython3-793871b')):
for each in subfolder+file:
source = os.path.join(folder,each)
# remove the absolute path to compose arcname
# also handles the remaining leading path separator with lstrip
arcname = source[len(root_dir):].lstrip(os.sep)
# write the file under a different name in the archive
myzip.write(source,arcname=arcname)
myzip.close()
</code></pre>
| 1 |
2016-09-10T09:09:44Z
|
[
"python",
"zipfile"
] |
multi column search in django using ajax
| 39,424,489 |
<p>I am working on a listing in django project. The scenario is that When i click on FAQ listing page then it redirects me to the listings where i get all faq. Now i have to search using different keywords. There is total five keywords through which i can search for particular results. Code is</p>
<pre><code>questions = Help.objects.all().filter().values('id','question','description','status','created','modified').order_by('-id')
if 'question' in ajax_data:
#add filter for question
if 'description' in ajax_data:
#add filter for description
if 'status' in ajax_data:
#add filter for status
if 'created' in ajax_data:
#add filter for created
if 'modified' in ajax_data:
#add filter for modified
questions = Help.objects.all().filter(#add all conditions here dynamically after applying filters).values('id','question','description','status','created','modified').order_by('-id')
</code></pre>
<p>First when page refresh it executes first query which returns all data, now using ajax filters have to be applied, i have done all ajax code just want logic of this search. Search should perform like if i enter question only it should filter according to question, but if i search using question, status and created filed it should apply filter for all these three keywords.</p>
| 0 |
2016-09-10T09:08:32Z
| 39,424,568 |
<p>You can use <code>request.GET.get('filter_name')</code></p>
<p>e.g if you have a filter by title:</p>
<pre><code>query = Model.objects.all()
title = request.GET.get('title')
if title:
query = query.filter(title__icontains=title)
...and so on
</code></pre>
<p>note that your url should contain get parameters like <code>http://myurl.com/?title=abc</code></p>
<p><strong>EDIT</strong>
for one query filter you can use <code>Q</code> object from <code>django.db.models</code> </p>
<pre><code>filter = Q()
if title:
filter &= Q(title__icontains=title)
if category:
filter &= Q(category__icontains=category)
query = query.filter(filter)
</code></pre>
| 0 |
2016-09-10T09:17:35Z
|
[
"python",
"django"
] |
multi column search in django using ajax
| 39,424,489 |
<p>I am working on a listing in django project. The scenario is that When i click on FAQ listing page then it redirects me to the listings where i get all faq. Now i have to search using different keywords. There is total five keywords through which i can search for particular results. Code is</p>
<pre><code>questions = Help.objects.all().filter().values('id','question','description','status','created','modified').order_by('-id')
if 'question' in ajax_data:
#add filter for question
if 'description' in ajax_data:
#add filter for description
if 'status' in ajax_data:
#add filter for status
if 'created' in ajax_data:
#add filter for created
if 'modified' in ajax_data:
#add filter for modified
questions = Help.objects.all().filter(#add all conditions here dynamically after applying filters).values('id','question','description','status','created','modified').order_by('-id')
</code></pre>
<p>First when page refresh it executes first query which returns all data, now using ajax filters have to be applied, i have done all ajax code just want logic of this search. Search should perform like if i enter question only it should filter according to question, but if i search using question, status and created filed it should apply filter for all these three keywords.</p>
| 0 |
2016-09-10T09:08:32Z
| 39,424,694 |
<pre><code>questions = Help.objects.all()
filters = {}
if 'question' in ajax_data:
filters['question'] = ajax_data.get('question')
if 'description' in ajax_data:
filters['description'] = ajax_data.get('description')
if 'status' in ajax_data:
filters['status'] = ajax_data.get('status')
if 'created' in ajax_data:
filters['created'] = ajax_data.get('created')
if 'modified' in ajax_data:
filters['modified'] = ajax_data.get('modified')
questions = questions.filter(**filters).values('id','question','description','status','created','modified').order_by('-id')
</code></pre>
<p>Check this link <a href="https://docs.python.org/3/glossary.html#term-argument" rel="nofollow">https://docs.python.org/3/glossary.html#term-argument</a></p>
| 3 |
2016-09-10T09:34:20Z
|
[
"python",
"django"
] |
See what Python module instantised a class?
| 39,424,591 |
<p>Is it possible in a Python class to see the name (or other identifier) of the class or module that instantises it?</p>
<p>For example:</p>
<pre><code># mymodule.py
class MyClass():
def __init__(self):
print(instantised_by)
#main.py
from mymodule import MyClass
instance = MyClass()
</code></pre>
<p>Running <code>main.py</code> should print:</p>
<pre><code>main
</code></pre>
<p>or something like that.</p>
<p>Is this possible?</p>
| 1 |
2016-09-10T09:20:25Z
| 39,424,655 |
<p>You can inspect the stack informations with <code>inspect</code> to get the caller stack from <code>__init__</code> (remember, it's just a function). From that you can get informations such as the caller function name, module name etc.</p>
<p>See this question: <a href="http://stackoverflow.com/questions/1095543/get-name-of-calling-functions-module-in-python">Get __name__ of calling function's module in Python</a>.</p>
| 0 |
2016-09-10T09:29:40Z
|
[
"python"
] |
See what Python module instantised a class?
| 39,424,591 |
<p>Is it possible in a Python class to see the name (or other identifier) of the class or module that instantises it?</p>
<p>For example:</p>
<pre><code># mymodule.py
class MyClass():
def __init__(self):
print(instantised_by)
#main.py
from mymodule import MyClass
instance = MyClass()
</code></pre>
<p>Running <code>main.py</code> should print:</p>
<pre><code>main
</code></pre>
<p>or something like that.</p>
<p>Is this possible?</p>
| 1 |
2016-09-10T09:20:25Z
| 39,424,669 |
<p>With <code>traceback</code> module:</p>
<pre><code>import traceback
class MyClass():
def __init__(self):
file,line,w1,w2 = traceback.extract_stack()[1]
print(w1)
</code></pre>
| 0 |
2016-09-10T09:31:04Z
|
[
"python"
] |
Replace input strings and integers
| 39,424,693 |
<p>I need to write a function that takes a string (str), and two other strings (call it replace1 and replace2), and an integer (n). The function shall return a new string, where all the string inputs from replace1 in the first string (str) and replace the new string with replace1 depending on where you want the new input. I am not supposed to use built-in functions, but I can use lens (we can suppose that replace1 has the length 1). Example ( call it replaceChoice):</p>
<pre><code>>>> replaceChoice(âMississippiâ, âsâ, âlâ, 2)
'Mislissippi'
</code></pre>
<p>I hope that I explained it well. Here is my attempt:</p>
<pre><code>def replaceChoice(str1, replace1,n):
newString=""
for x in str:
if x=="str1":
newString=newString+replace
else:
newString=newString+x
return newString
</code></pre>
| 0 |
2016-09-10T09:34:12Z
| 39,424,786 |
<p>I assume from your question that you want to replace the nth occurrence of r1 with r2.
Is this what you want?</p>
<pre><code>>>> def replaceChoice(str1, r1, r2, n):
... new_str = ""
... replaced = False
... for i in str1:
... if i==r1:
... n-=1
... if n==0 and not replaced:
... replaced = True
... new_str+=r2
... else:
... new_str+=i
... return new_str
...
>>> replaceChoice("Mississippi", "s", "l", 2)
'Mislissippi'
</code></pre>
| 1 |
2016-09-10T09:44:59Z
|
[
"python"
] |
How to click a button to vote with python
| 39,424,703 |
<p>I'm practicing with web scraping in python. I'd like to press a button on a site that votes an item.
Here is the code</p>
<pre><code><html>
<head></head>
<body role="document">
<div id="static page" class="container-fluid">
<div id="page" class="row"></div>
<div id="faucets-list">
<tbody>
<tr class=""></tr>
<tr class=""></tr>
<tr class=""></tr>
<tr class=""></tr>
# an infinite number of nodes, until there's mine
<tr class="">
<td class="vote-col">
<div class="vote-box">
<div class="vote-links">
<a class="vote-link up" data-original-title="I like this faucet" href="#" data-faucet"39274" data-vote"up" data-toggle"tooltip" data-placement="top" title=""></a>
</code></pre>
<p>And this it the final part but when I manually click on the button:</p>
<pre><code><a data-original-title="I&nbsp;like&nbsp;this&nbsp;faucet" href="#" class="vote-link up voted" data-faucet="39274" data-vote="up" data-toggle="tooltip" data-placement="top" title=""></a>
</code></pre>
<p>Can i simulate it with a script in python? I'm still a newbie and I've started learning python recently. P.S: the site is in https. And I cant's use http cause it force to redirect in https.</p>
<p>--UDPATE--
I'm trying with selenium.. </p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://faucetbox.com/en/list/BTC")
element = driver.find_element_by_css_selector(".vote-link.up")
element_attribute_value = element.get_attribute("data-faucet")
if element_attribute_value == "39274":
print ("Value: {0}".format(element_attribute_value))
driver.quit()
</code></pre>
<p>But since there are multiple number for each vote, it always shows the first one... so it never prints that print... How can I do to select my line of html sourcecode end replace it to a line I want?</p>
| 0 |
2016-09-10T09:35:22Z
| 39,424,766 |
<p>You might want to check out <a href="http://selenium-python.readthedocs.io/" rel="nofollow">Selenium</a>. It is a module for python that allows you to automate tasks like the one you have mentioned above. Try something like this:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://faucetbox.com/en/list/BTC")
elements = driver.find_elements_by_css_selector(".vote-link.up")
for element in elements:
element_attribute_value = element.get_attribute("data-faucet")
if element_attribute_value == "39274":
print("Value: {0}".format(element_attribute_value))
element.click()
break
driver.quit()
</code></pre>
<p>The difference between what you did and what I did is that I used the <code>find_elements_by_css_selector</code> method instead of <code>find_element_by_css_selector</code>. The former returns a list of all elements that match the css selector while the latter returns only the first matching element. Then I just iterated through that list with a simple <code>for</code> loop and used the same check that you did. I also clicked the element in the loop. Hope this helps!</p>
| -1 |
2016-09-10T09:42:54Z
|
[
"python",
"python-3.x",
"web-scraping"
] |
which code remove the duplicate combination in permutation
| 39,424,739 |
<p>I didn't find the obvious difference between two functions below . So the question is , how the second funtion compare and remove duplicate characters .</p>
<p>permutation for non-duplicate characters</p>
<pre><code>def perms(s):
if(len(s)==1): return [s]
result=[]
for i,v in enumerate(s):
result += [v+p for p in perms(s[:i]+s[i+1:])]
return result
perms('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
</code></pre>
<p>permutation for duplicate characters</p>
<pre><code>def permutations(string):
result = set([string])
if len(string) == 2:
result.add(string[1] + string[0])
elif len(string) > 2:
for i, c in enumerate(string):
for s in permutations(string[:i] + string[i + 1:]):
result.add(c + s)
return list(result)
permutations('aabb');
['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa']
</code></pre>
<p><strong>EDIT:</strong></p>
<p>The function return different results when input contains duplicates:</p>
<pre><code>>>> permutations('aabb')
['abab', 'baba', 'bbaa', 'abba', 'aabb', 'baab']
>>> perms('aabb')
['aabb', 'aabb', 'abab', 'abba', 'abab', 'abba', 'aabb', 'aabb', 'abab',
'abba', 'abab', 'abba', 'baab', 'baba', 'baab', 'baba', 'bbaa', 'bbaa',
'baab', 'baba', 'baab', 'baba', 'bbaa', 'bbaa']
</code></pre>
| 0 |
2016-09-10T09:39:41Z
| 39,424,818 |
<p>The difference is very simple. The second function stores results in a set:</p>
<pre><code>result = set([string])
</code></pre>
<p>A set never contains duplicates. If you add a duplicate value to a set, noting happens:</p>
<pre><code>>>> set([1, 2, 3, 2, 3, 2, 1])
set([1, 2, 3])
</code></pre>
<p>In the end, the function creates a list from the set, so the set is not visible from the outside:</p>
<pre><code>return list(result)
</code></pre>
| 2 |
2016-09-10T09:48:41Z
|
[
"python",
"algorithm",
"recursion"
] |
Python/Numpy array dimension confusion
| 39,424,776 |
<p>Suppose <code>batch_size = 64</code>.
I created a batch : <code>batch = np.zeros((self._batch_size,), dtype=np.int64)</code>. Suppose I have batch of chars such that <code>batch = ['o', 'w', ....'s']</code> of 64 size and <code>'o'</code> will be represented as <code>[0,0, .... 0]</code> 1-hot vector of size 27.
So, is there any way such that batch will still have shape of batch_size and not batch_size x vocabulary_size?
Code is as follows :</p>
<pre><code>batch = np.zeros((self._batch_size,), dtype=np.int64)
temp1 = list()
for b in range(self._batch_size):
temp = np.zeros(shape=(vocabulary_size), dtype=np.int64)
temp[char2id(self._text[self._cursor[b]])] = 1.0
temp1.append(temp)
self._cursor[b] = (self._cursor[b] + 1) % self._text_size
batch = np.asarray(list)
return batch
</code></pre>
<p>This return batch as dimension of batch_size x vocabulary_size.</p>
<pre><code>batch = np.zeros((self._batch_size,), dtype=np.int64)
for b in range(self._batch_size):
batch[b, char2id(self._text[self._cursor[b]])] = 1.0
self._cursor[b] = (self._cursor[b] + 1) % self._text_size
return batch
</code></pre>
<p>This code returns an error of too many few indices.<br>
Is there any way of specifying array size as <code>[batch_size :, None]</code>?</p>
| 0 |
2016-09-10T09:44:02Z
| 39,426,000 |
<p>In the 1st block the initialization of <code>batch</code> to <code>zeros</code> does nothing for you, because <code>batch</code> is replaced with the <code>asarray(temp1)</code> later. (Note my correction). <code>temp1</code> is a list of 1d arrays (<code>temp</code>), and produces a 2d arrray.</p>
<p>In the 2nd if you start with <code>batch=np.zeros((batch_size, vocab_size))</code> you would avoid the index number error.</p>
<p>You can't use <code>None</code> instead of a real integer. <code>None</code> does not work like a broadcasting <code>newaxis</code> here. Arrays don't grow by assigning a new larger index. Even when used in indexing <code>np.zeros((batchsize,))[:,None]</code> the result is 2d, shape (batchsize,1).</p>
<p>Why do you want a 1d array? It's possible to construct a 1d array of dtype object that contains arrays (or any other object), but for many purposes it is just a glorified list.</p>
| 1 |
2016-09-10T12:18:23Z
|
[
"python",
"numpy"
] |
invalid request block size 21573
| 39,424,823 |
<p>I was reading the tutorial provided in
<a href="http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html" rel="nofollow">http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html</a>
This very tutorial is a great tutorial. I have been able to configure django server on my raspberry pi raspbian system, on my Ubuntu Desktop too.<br>
Now I am trying to do the same on a Virtual Machine, Ubuntu 16.04, nginx server.
On the line, <br>
uwsgi --socket :8001 --wsgi-file test.py
<br>
I get an error saying
<em>invalid request block size 21573</em> on the terminal
I went through the uwsgi tutorial that said not to use --http for --socket;
Either way I have not been able to get my webserver running.<br> Please help.
Nginx is currently serving a wordpress site on start. </p>
| 0 |
2016-09-10T09:49:16Z
| 39,454,292 |
<p>With <code>--socket</code> option you have to use <a href="http://nginx.org/en/docs/http/ngx_http_uwsgi_module.html" rel="nofollow">uwsgi module</a> in nginx instead of proxy.</p>
| 0 |
2016-09-12T15:53:03Z
|
[
"python",
"django",
"nginx",
"uwsgi"
] |
Accessing dynamically created buttons in PyQT5
| 39,424,826 |
<p>Sirs.</p>
<p>I have pretty much simple PyQT5 app.
I have dynamically created buttons and connected to some function.</p>
<pre><code> class App(QWidget):
...
def createButtons(self):
...
for param in params:
print("placing button "+param)
button = QPushButton(param, checkable=True)
button.clicked.connect(lambda: self.commander())
</code></pre>
<p>And I have the commander method:</p>
<pre><code> def commander(self):
print(self.sender().text())
</code></pre>
<p>So I have access to clicked button.
But what if I want to access previously clicked button? Or another element in main window? How to do it?</p>
<p>What I want:</p>
<pre><code> def commander(self):
print(self.sender().text())
pressedbutton = self.findButtonByText("testbutton")
pressedbutton.setChecked(False)
</code></pre>
<p>Or</p>
<pre><code> pressedbutton = self.findButtonBySomeKindOfID(3)
pressedbutton.setChecked(False)
</code></pre>
<p>Any help will be appreciated! </p>
| 2 |
2016-09-10T09:49:33Z
| 39,424,884 |
<p>You can use a map and save the instances of your buttons.
You can use the button text as key or the id if you want.
If you use the button text as key you cannot have two buttons with the same label.</p>
<pre><code>class App(QWidget):
def __init__(self):
super(App,self).__init__()
button_map = {}
self.createButtons()
def createButtons(self):
...
for param in params:
print("placing button "+param)
button = QPushButton(param, checkable=True)
button.clicked.connect(lambda: self.commander())
# Save each button in the map after the setting of the button text property
self.saveButton(button)
def saveButton(self,obj):
"""
Saves the button in the map
:param obj: the QPushButton object
"""
button_map[obj.text()] = obj
def findButtonByText(self,text)
"""
Returns the QPushButton instance
:param text: the button text
:return the QPushButton object
"""
return button_map[text]
</code></pre>
| 0 |
2016-09-10T09:55:37Z
|
[
"python",
"pyqt5",
"qpushbutton"
] |
Chat-robot that will take input and response in Python
| 39,424,853 |
<p>I'm currently trying to create a small version of a chat robot that will respond to different keyword inputs in a terminal. For example, if I write <code>inv</code> it will print out its current inventory and it can look like this:</p>
<pre><code>Item: sword
Place in inventory: 1
Item: axe
Place in inventory: 2
Item: shield
Place in inventory: 3
Item: bow
Place in inventory: 4
Item: flower
Place in inventory: 5
</code></pre>
<p>And that part I have solved. The problem occurs when I'm going to give an input like <code>inv pick hammer</code> or <code>inv drop hammer</code>. Now I have to handle somehow that the same start keyword can occur in multiple cases.</p>
<p>I have created some kind of handler that takes a argument (the input from user) and splits it into a list. Looks something like this:</p>
<pre><code>def splitIntoWords(argOne):
"""
Function that splits list into words
"""
#list to keep and split up the user input
inputList = []
inputList = argOne.split()
#print(str(inputList) + "splitIntoWords")
#term we want to search for
term = "citat"
quitOne = "q"
replyHej = "hej"
replyLunch = "lunch"
inventory = "inv"
invPick = "pick"
#invDrop = "drop"
lenght = len(inputList)
nextWord = inputList[lenght-1]
if term in inputList:
return term
elif quitOne in inputList:
return quitOne
elif replyHej in inputList:
return replyHej
elif replyLunch in inputList:
return replyLunch
elif inventory in inputList:
if invPick in inputList:
return ("q")
else:
return inventory
else:
return result
</code></pre>
<p>As you can see I have started to do and if inside an elif and tried to do multiple checks on the same list, but it doesn't work for me.
Is there any other way I can do check to see it that more than one keyword appears in the list?</p>
| 1 |
2016-09-10T09:52:31Z
| 39,425,187 |
<p>I formatted and tested the code and it works. </p>
<pre><code>def splitIntoWords( argOne):
result = "hej"
"""
Function that splits list into words
"""
# list to keep and split up the user input
inputList = []
inputList = argOne.split()
print(str(inputList) + "splitIntoWords")
# term we want to search for
term = "citat"
quitOne = "q"
replyHej = "hej"
replyLunch = "lunch"
inventory = "inv"
invPick = "pick"
# invDrop = "drop"
lenght = len(inputList)
nextWord = inputList[lenght - 1]
if term in inputList:
return term
elif quitOne in inputList:
return quitOne
elif replyHej in inputList:
return replyHej
elif replyLunch in inputList:
return replyLunch
elif inventory in inputList:
if invPick in inputList:
return ("q")
else:
return inventory
else:
return result
print splitIntoWords("inv pick sword")
</code></pre>
<p>Test</p>
<pre><code>python inventory.py
['inv', 'pick', 'sword']splitIntoWords
q
</code></pre>
<p>The <code>q</code> above is the expected result. </p>
| 0 |
2016-09-10T10:36:11Z
|
[
"python",
"list",
"python-3.x"
] |
Extracting JS variable information inside script tag
| 39,424,854 |
<p>I'm retrieving an HTML page from a URL and want to extract information from a <code>script</code> tag within that HTML. I am specifically looking for this particular <code>script</code> tag:</p>
<pre><code><script type="text/javascript">
var zomato = zomato || {};
zomato.menuPages = [{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/4bab50546bf3314e25dea4310ddf524e.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/4bab50546bf3314e25dea4310ddf524e.jpg","filename":"4bab50546bf3314e25dea4310ddf524e.jpg","url_master":"menus_original\/705\/51705\/4bab50546bf3314e25dea4310ddf524e.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/4bab50546bf3314e25dea4310ddf524e.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344370},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0a284792e41edbb5ba5bbc7b0cde26db.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0a284792e41edbb5ba5bbc7b0cde26db.jpg","filename":"0a284792e41edbb5ba5bbc7b0cde26db.jpg","url_master":"menus_original\/705\/51705\/0a284792e41edbb5ba5bbc7b0cde26db.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/0a284792e41edbb5ba5bbc7b0cde26db.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344371},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/6ff338c3891bca1cc61574e9864b15ae.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/6ff338c3891bca1cc61574e9864b15ae.jpg","filename":"6ff338c3891bca1cc61574e9864b15ae.jpg","url_master":"menus_original\/705\/51705\/6ff338c3891bca1cc61574e9864b15ae.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/6ff338c3891bca1cc61574e9864b15ae.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344365},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/ff5a5ea0945782ad1d82102461a39b52.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/ff5a5ea0945782ad1d82102461a39b52.jpg","filename":"ff5a5ea0945782ad1d82102461a39b52.jpg","url_master":"menus_original\/705\/51705\/ff5a5ea0945782ad1d82102461a39b52.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/ff5a5ea0945782ad1d82102461a39b52.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344366},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/3cb04e221c4db345ceb41b638d9faa6a.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/3cb04e221c4db345ceb41b638d9faa6a.jpg","filename":"3cb04e221c4db345ceb41b638d9faa6a.jpg","url_master":"menus_original\/705\/51705\/3cb04e221c4db345ceb41b638d9faa6a.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/3cb04e221c4db345ceb41b638d9faa6a.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344367},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/733759862d474dfd8e710fa08e78849b.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/733759862d474dfd8e710fa08e78849b.jpg","filename":"733759862d474dfd8e710fa08e78849b.jpg","url_master":"menus_original\/705\/51705\/733759862d474dfd8e710fa08e78849b.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/733759862d474dfd8e710fa08e78849b.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344368},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/69144be9b82cbba9adcc9de35003522d.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/69144be9b82cbba9adcc9de35003522d.jpg","filename":"69144be9b82cbba9adcc9de35003522d.jpg","url_master":"menus_original\/705\/51705\/69144be9b82cbba9adcc9de35003522d.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/69144be9b82cbba9adcc9de35003522d.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344369},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/9dfd7dcc0e45639acbde792781012e0d.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/9dfd7dcc0e45639acbde792781012e0d.jpg","filename":"9dfd7dcc0e45639acbde792781012e0d.jpg","url_master":"menus_original\/705\/51705\/9dfd7dcc0e45639acbde792781012e0d.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/9dfd7dcc0e45639acbde792781012e0d.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344483},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/b89c707ff99087cd8098ddaf3b5f1346.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/b89c707ff99087cd8098ddaf3b5f1346.jpg","filename":"b89c707ff99087cd8098ddaf3b5f1346.jpg","url_master":"menus_original\/705\/51705\/b89c707ff99087cd8098ddaf3b5f1346.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/b89c707ff99087cd8098ddaf3b5f1346.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344484},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/439bf88da8bfce35ba44c6f206360a90.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/439bf88da8bfce35ba44c6f206360a90.jpg","filename":"439bf88da8bfce35ba44c6f206360a90.jpg","url_master":"menus_original\/705\/51705\/439bf88da8bfce35ba44c6f206360a90.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/439bf88da8bfce35ba44c6f206360a90.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344485},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/854abd602c815f84dcaa2fdea1c22f81.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/854abd602c815f84dcaa2fdea1c22f81.jpg","filename":"854abd602c815f84dcaa2fdea1c22f81.jpg","url_master":"menus_original\/705\/51705\/854abd602c815f84dcaa2fdea1c22f81.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/854abd602c815f84dcaa2fdea1c22f81.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344486},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/7670f299fd8f065252b94665df390790.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/7670f299fd8f065252b94665df390790.jpg","filename":"7670f299fd8f065252b94665df390790.jpg","url_master":"menus_original\/705\/51705\/7670f299fd8f065252b94665df390790.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/7670f299fd8f065252b94665df390790.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344487},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/f308c376afe08aed9b4ccf38eb0d6652.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/f308c376afe08aed9b4ccf38eb0d6652.jpg","filename":"f308c376afe08aed9b4ccf38eb0d6652.jpg","url_master":"menus_original\/705\/51705\/f308c376afe08aed9b4ccf38eb0d6652.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/f308c376afe08aed9b4ccf38eb0d6652.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344488},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","filename":"c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","url_master":"menus_original\/705\/51705\/c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344489},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0cbe5c590f3d5312238de6b00cc9b0a9.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0cbe5c590f3d5312238de6b00cc9b0a9.jpg","filename":"0cbe5c590f3d5312238de6b00cc9b0a9.jpg","url_master":"menus_original\/705\/51705\/0cbe5c590f3d5312238de6b00cc9b0a9.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/0cbe5c590f3d5312238de6b00cc9b0a9.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344490},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/3db4f82866e075bb1852990a0cdbe30a.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/3db4f82866e075bb1852990a0cdbe30a.jpg","filename":"3db4f82866e075bb1852990a0cdbe30a.jpg","url_master":"menus_original\/705\/51705\/3db4f82866e075bb1852990a0cdbe30a.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/3db4f82866e075bb1852990a0cdbe30a.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344477},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/1e0df9160c02273466e96239eae1a555.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/1e0df9160c02273466e96239eae1a555.jpg","filename":"1e0df9160c02273466e96239eae1a555.jpg","url_master":"menus_original\/705\/51705\/1e0df9160c02273466e96239eae1a555.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/1e0df9160c02273466e96239eae1a555.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344478},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0d7fd654ec9f090883fa428df0f1ebb2.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0d7fd654ec9f090883fa428df0f1ebb2.jpg","filename":"0d7fd654ec9f090883fa428df0f1ebb2.jpg","url_master":"menus_original\/705\/51705\/0d7fd654ec9f090883fa428df0f1ebb2.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/0d7fd654ec9f090883fa428df0f1ebb2.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344479},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/da16fc1d8d9641581fca258cbcb99f80.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/da16fc1d8d9641581fca258cbcb99f80.jpg","filename":"da16fc1d8d9641581fca258cbcb99f80.jpg","url_master":"menus_original\/705\/51705\/da16fc1d8d9641581fca258cbcb99f80.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/da16fc1d8d9641581fca258cbcb99f80.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344480},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","filename":"5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","url_master":"menus_original\/705\/51705\/5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344481},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/c96e340be834ecf086536234a56e7626.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/c96e340be834ecf086536234a56e7626.jpg","filename":"c96e340be834ecf086536234a56e7626.jpg","url_master":"menus_original\/705\/51705\/c96e340be834ecf086536234a56e7626.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/c96e340be834ecf086536234a56e7626.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344482}];
zomato.menuTypes = ["DEFAULT","FOOD","BAR","DELIVERY","SPECIAL","TAKEAWAY","INTERNAL"];
zomato.currentMenuPage = 1;
</script>
</code></pre>
<p>That list goes on for quite a while. I am using <a href="/questions/tagged/beautifulsoup" class="post-tag" title="show questions tagged 'beautifulsoup'" rel="tag">beautifulsoup</a>. This:</p>
<pre><code>soup.find_all('script')[14]
</code></pre>
<p>gives me the exact <code>script</code> tag I want. However, once I have done that, I am not sure how to parse further.</p>
<p>Is there a way I can access <code>zomato.menuPages</code> as a python list and then access its elements? If there are no decent Python solutions, maybe something in JS?</p>
| 2 |
2016-09-10T09:52:39Z
| 39,425,950 |
<p>Well, a way to do that is to make use of <strong>regular expressions</strong> which of course is not the most easy thing to do but comes in handy sometimes. So what I tried is the following:</p>
<pre><code>#!/usr/bin/env python
from BeautifulSoup import BeautifulSoup
import requests
import re
# I didn't post the url for typical reasons
url = "the_url"
r = requests.get(url)
response = r.text
soup = BeautifulSoup(response)
x = soup.findAll(name = 'script')[14]
# use regular expression
values = re.findall(r'zomato..*?=\s*(.*?);', str(x), re.DOTALL | re.MULTILINE)
</code></pre>
<p>So what this regular expression will do in this case is to give you
a list consisted of 4 elements - for example the 2nd element will be
<code>zomato.menuPages</code> as you asked for.
Then you can process <code>zomato.menuPages</code> a bit more, like:</p>
<pre><code>k = ''.join(values[1])
w = k[1:-1]
list = w.split("{",21)
print list[1]
</code></pre>
<p>Then you could try to convert the items of the <code>list</code> from string -> dictionary to be able to parse them more easily(using json or ast maybe).</p>
<p>Also you could parse each of these values(I refer to the values list) using another regular expression.
Also using the <code>groupdict</code> function from the regex module you could create a dictionary from each element of the list based on certain regex rules.
Well, I hope it will be of some help!</p>
| 1 |
2016-09-10T12:11:24Z
|
[
"javascript",
"python",
"beautifulsoup",
"html-parsing"
] |
Extracting JS variable information inside script tag
| 39,424,854 |
<p>I'm retrieving an HTML page from a URL and want to extract information from a <code>script</code> tag within that HTML. I am specifically looking for this particular <code>script</code> tag:</p>
<pre><code><script type="text/javascript">
var zomato = zomato || {};
zomato.menuPages = [{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/4bab50546bf3314e25dea4310ddf524e.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/4bab50546bf3314e25dea4310ddf524e.jpg","filename":"4bab50546bf3314e25dea4310ddf524e.jpg","url_master":"menus_original\/705\/51705\/4bab50546bf3314e25dea4310ddf524e.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/4bab50546bf3314e25dea4310ddf524e.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344370},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0a284792e41edbb5ba5bbc7b0cde26db.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0a284792e41edbb5ba5bbc7b0cde26db.jpg","filename":"0a284792e41edbb5ba5bbc7b0cde26db.jpg","url_master":"menus_original\/705\/51705\/0a284792e41edbb5ba5bbc7b0cde26db.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/0a284792e41edbb5ba5bbc7b0cde26db.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344371},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/6ff338c3891bca1cc61574e9864b15ae.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/6ff338c3891bca1cc61574e9864b15ae.jpg","filename":"6ff338c3891bca1cc61574e9864b15ae.jpg","url_master":"menus_original\/705\/51705\/6ff338c3891bca1cc61574e9864b15ae.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/6ff338c3891bca1cc61574e9864b15ae.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344365},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/ff5a5ea0945782ad1d82102461a39b52.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/ff5a5ea0945782ad1d82102461a39b52.jpg","filename":"ff5a5ea0945782ad1d82102461a39b52.jpg","url_master":"menus_original\/705\/51705\/ff5a5ea0945782ad1d82102461a39b52.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/ff5a5ea0945782ad1d82102461a39b52.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344366},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/3cb04e221c4db345ceb41b638d9faa6a.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/3cb04e221c4db345ceb41b638d9faa6a.jpg","filename":"3cb04e221c4db345ceb41b638d9faa6a.jpg","url_master":"menus_original\/705\/51705\/3cb04e221c4db345ceb41b638d9faa6a.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/3cb04e221c4db345ceb41b638d9faa6a.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344367},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/733759862d474dfd8e710fa08e78849b.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/733759862d474dfd8e710fa08e78849b.jpg","filename":"733759862d474dfd8e710fa08e78849b.jpg","url_master":"menus_original\/705\/51705\/733759862d474dfd8e710fa08e78849b.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/733759862d474dfd8e710fa08e78849b.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344368},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/69144be9b82cbba9adcc9de35003522d.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/69144be9b82cbba9adcc9de35003522d.jpg","filename":"69144be9b82cbba9adcc9de35003522d.jpg","url_master":"menus_original\/705\/51705\/69144be9b82cbba9adcc9de35003522d.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/69144be9b82cbba9adcc9de35003522d.jpg","data_center":"sng","menu_type":"FOOD","title":"FOOD","menu_type_class":"FOOD","real_menu_type":"FOOD","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344369},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/9dfd7dcc0e45639acbde792781012e0d.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/9dfd7dcc0e45639acbde792781012e0d.jpg","filename":"9dfd7dcc0e45639acbde792781012e0d.jpg","url_master":"menus_original\/705\/51705\/9dfd7dcc0e45639acbde792781012e0d.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/9dfd7dcc0e45639acbde792781012e0d.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344483},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/b89c707ff99087cd8098ddaf3b5f1346.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/b89c707ff99087cd8098ddaf3b5f1346.jpg","filename":"b89c707ff99087cd8098ddaf3b5f1346.jpg","url_master":"menus_original\/705\/51705\/b89c707ff99087cd8098ddaf3b5f1346.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/b89c707ff99087cd8098ddaf3b5f1346.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344484},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/439bf88da8bfce35ba44c6f206360a90.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/439bf88da8bfce35ba44c6f206360a90.jpg","filename":"439bf88da8bfce35ba44c6f206360a90.jpg","url_master":"menus_original\/705\/51705\/439bf88da8bfce35ba44c6f206360a90.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/439bf88da8bfce35ba44c6f206360a90.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344485},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/854abd602c815f84dcaa2fdea1c22f81.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/854abd602c815f84dcaa2fdea1c22f81.jpg","filename":"854abd602c815f84dcaa2fdea1c22f81.jpg","url_master":"menus_original\/705\/51705\/854abd602c815f84dcaa2fdea1c22f81.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/854abd602c815f84dcaa2fdea1c22f81.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344486},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/7670f299fd8f065252b94665df390790.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/7670f299fd8f065252b94665df390790.jpg","filename":"7670f299fd8f065252b94665df390790.jpg","url_master":"menus_original\/705\/51705\/7670f299fd8f065252b94665df390790.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/7670f299fd8f065252b94665df390790.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344487},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/f308c376afe08aed9b4ccf38eb0d6652.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/f308c376afe08aed9b4ccf38eb0d6652.jpg","filename":"f308c376afe08aed9b4ccf38eb0d6652.jpg","url_master":"menus_original\/705\/51705\/f308c376afe08aed9b4ccf38eb0d6652.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/f308c376afe08aed9b4ccf38eb0d6652.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344488},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","filename":"c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","url_master":"menus_original\/705\/51705\/c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/c734ed73e8e5f15f2e3ef9e287bf86f7.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344489},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0cbe5c590f3d5312238de6b00cc9b0a9.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0cbe5c590f3d5312238de6b00cc9b0a9.jpg","filename":"0cbe5c590f3d5312238de6b00cc9b0a9.jpg","url_master":"menus_original\/705\/51705\/0cbe5c590f3d5312238de6b00cc9b0a9.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/0cbe5c590f3d5312238de6b00cc9b0a9.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344490},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/3db4f82866e075bb1852990a0cdbe30a.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/3db4f82866e075bb1852990a0cdbe30a.jpg","filename":"3db4f82866e075bb1852990a0cdbe30a.jpg","url_master":"menus_original\/705\/51705\/3db4f82866e075bb1852990a0cdbe30a.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/3db4f82866e075bb1852990a0cdbe30a.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344477},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/1e0df9160c02273466e96239eae1a555.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/1e0df9160c02273466e96239eae1a555.jpg","filename":"1e0df9160c02273466e96239eae1a555.jpg","url_master":"menus_original\/705\/51705\/1e0df9160c02273466e96239eae1a555.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/1e0df9160c02273466e96239eae1a555.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344478},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0d7fd654ec9f090883fa428df0f1ebb2.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/0d7fd654ec9f090883fa428df0f1ebb2.jpg","filename":"0d7fd654ec9f090883fa428df0f1ebb2.jpg","url_master":"menus_original\/705\/51705\/0d7fd654ec9f090883fa428df0f1ebb2.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/0d7fd654ec9f090883fa428df0f1ebb2.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344479},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/da16fc1d8d9641581fca258cbcb99f80.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/da16fc1d8d9641581fca258cbcb99f80.jpg","filename":"da16fc1d8d9641581fca258cbcb99f80.jpg","url_master":"menus_original\/705\/51705\/da16fc1d8d9641581fca258cbcb99f80.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/da16fc1d8d9641581fca258cbcb99f80.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344480},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","filename":"5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","url_master":"menus_original\/705\/51705\/5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/5336b40a11d4486db5e3a4bcfb0e9ae8.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344481},{"url":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/c96e340be834ecf086536234a56e7626.jpg","href":"https:\/\/b.zmtcdn.com\/data\/menus\/705\/51705\/c96e340be834ecf086536234a56e7626.jpg","filename":"c96e340be834ecf086536234a56e7626.jpg","url_master":"menus_original\/705\/51705\/c96e340be834ecf086536234a56e7626.jpg","path_master":"\/home\/foodie\/zomato_data\/menus_original\/705\/51705\/c96e340be834ecf086536234a56e7626.jpg","data_center":"sng","menu_type":"BAR","title":"BAR","menu_type_class":"BAR","real_menu_type":"BAR","is_salt_special_menu":0,"start_date":"","consumer_upload":0,"start_date_formatted":"","end_date":"","end_date_formatted":"","id":129344482}];
zomato.menuTypes = ["DEFAULT","FOOD","BAR","DELIVERY","SPECIAL","TAKEAWAY","INTERNAL"];
zomato.currentMenuPage = 1;
</script>
</code></pre>
<p>That list goes on for quite a while. I am using <a href="/questions/tagged/beautifulsoup" class="post-tag" title="show questions tagged 'beautifulsoup'" rel="tag">beautifulsoup</a>. This:</p>
<pre><code>soup.find_all('script')[14]
</code></pre>
<p>gives me the exact <code>script</code> tag I want. However, once I have done that, I am not sure how to parse further.</p>
<p>Is there a way I can access <code>zomato.menuPages</code> as a python list and then access its elements? If there are no decent Python solutions, maybe something in JS?</p>
| 2 |
2016-09-10T09:52:39Z
| 39,426,481 |
<p>I have found <a href="https://github.com/scrapinghub/js2xml" rel="nofollow">jsxml</a> pretty effective, it parses <em>javascript</em> properties/functions into xml trees:</p>
<pre><code>import js2xml
import re
soup = BeautifulSoup(the_html,"html.parser")
tree = js2xml.parse(soup.find("script", text=re.compile("zomato.menuPages\s+=")).text)
print(js2xml.pretty_print(tree))
</code></pre>
<p>In the middle of the tree you will see:</p>
<pre><code> <assign operator="=">
<left>
<dotaccessor>
<object>
<identifier name="zomato"/>
</object>
<property>
<identifier name="menuTypes"/>
</property>
</dotaccessor>
</left>
<right>
<array>
<string>DEFAULT</string>
<string>FOOD</string>
<string>BAR</string>
<string>DELIVERY</string>
<string>SPECIAL</string>
<string>TAKEAWAY</string>
<string>INTERNAL</string>
</array>
</right>
</code></pre>
<p>There you have the assign node, with the <code>operator="="</code> inside the <em>left</em> node, then you have the <code>dotaccessor</code> node which contains the <code>object</code> and <code>property</code> childs nodes, so basically we just need to find the correct left assign using the <em>object/property</em> inside the <em>dotproperty</em> node and get the following array, a quick example of using the tree to get the array and the content:</p>
<pre><code>In [5]: from bs4 import BeautifulSoup
In [6]: soup = BeautifulSoup(s,"html.parser")
In [7]: tree = js2xml.parse(soup.script.text)
In [8]: array = tree.xpath("//left[./dotaccessor/property/identifier[@name='menuPages']]/following::array[1]")[0]
In [9]: for node in array.xpath(".//object/*"):
...: print(node.xpath("@name"), node.xpath(".//text()") or node.xpath(".//@value") )
...:
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/4bab50546bf3314e25dea4310ddf524e.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/4bab50546bf3314e25dea4310ddf524e.jpg'])
(['filename'], ['4bab50546bf3314e25dea4310ddf524e.jpg'])
(['url_master'], ['menus_original/705/51705/4bab50546bf3314e25dea4310ddf524e.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/4bab50546bf3314e25dea4310ddf524e.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['FOOD'])
(['title'], ['FOOD'])
(['menu_type_class'], ['FOOD'])
(['real_menu_type'], ['FOOD'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344370'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/0a284792e41edbb5ba5bbc7b0cde26db.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/0a284792e41edbb5ba5bbc7b0cde26db.jpg'])
(['filename'], ['0a284792e41edbb5ba5bbc7b0cde26db.jpg'])
(['url_master'], ['menus_original/705/51705/0a284792e41edbb5ba5bbc7b0cde26db.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/0a284792e41edbb5ba5bbc7b0cde26db.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['FOOD'])
(['title'], ['FOOD'])
(['menu_type_class'], ['FOOD'])
(['real_menu_type'], ['FOOD'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344371'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/6ff338c3891bca1cc61574e9864b15ae.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/6ff338c3891bca1cc61574e9864b15ae.jpg'])
(['filename'], ['6ff338c3891bca1cc61574e9864b15ae.jpg'])
(['url_master'], ['menus_original/705/51705/6ff338c3891bca1cc61574e9864b15ae.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/6ff338c3891bca1cc61574e9864b15ae.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['FOOD'])
(['title'], ['FOOD'])
(['menu_type_class'], ['FOOD'])
(['real_menu_type'], ['FOOD'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344365'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/ff5a5ea0945782ad1d82102461a39b52.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/ff5a5ea0945782ad1d82102461a39b52.jpg'])
(['filename'], ['ff5a5ea0945782ad1d82102461a39b52.jpg'])
(['url_master'], ['menus_original/705/51705/ff5a5ea0945782ad1d82102461a39b52.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/ff5a5ea0945782ad1d82102461a39b52.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['FOOD'])
(['title'], ['FOOD'])
(['menu_type_class'], ['FOOD'])
(['real_menu_type'], ['FOOD'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344366'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/3cb04e221c4db345ceb41b638d9faa6a.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/3cb04e221c4db345ceb41b638d9faa6a.jpg'])
(['filename'], ['3cb04e221c4db345ceb41b638d9faa6a.jpg'])
(['url_master'], ['menus_original/705/51705/3cb04e221c4db345ceb41b638d9faa6a.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/3cb04e221c4db345ceb41b638d9faa6a.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['FOOD'])
(['title'], ['FOOD'])
(['menu_type_class'], ['FOOD'])
(['real_menu_type'], ['FOOD'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344367'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/733759862d474dfd8e710fa08e78849b.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/733759862d474dfd8e710fa08e78849b.jpg'])
(['filename'], ['733759862d474dfd8e710fa08e78849b.jpg'])
(['url_master'], ['menus_original/705/51705/733759862d474dfd8e710fa08e78849b.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/733759862d474dfd8e710fa08e78849b.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['FOOD'])
(['title'], ['FOOD'])
(['menu_type_class'], ['FOOD'])
(['real_menu_type'], ['FOOD'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344368'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/69144be9b82cbba9adcc9de35003522d.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/69144be9b82cbba9adcc9de35003522d.jpg'])
(['filename'], ['69144be9b82cbba9adcc9de35003522d.jpg'])
(['url_master'], ['menus_original/705/51705/69144be9b82cbba9adcc9de35003522d.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/69144be9b82cbba9adcc9de35003522d.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['FOOD'])
(['title'], ['FOOD'])
(['menu_type_class'], ['FOOD'])
(['real_menu_type'], ['FOOD'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344369'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/9dfd7dcc0e45639acbde792781012e0d.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/9dfd7dcc0e45639acbde792781012e0d.jpg'])
(['filename'], ['9dfd7dcc0e45639acbde792781012e0d.jpg'])
(['url_master'], ['menus_original/705/51705/9dfd7dcc0e45639acbde792781012e0d.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/9dfd7dcc0e45639acbde792781012e0d.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['BAR'])
(['title'], ['BAR'])
(['menu_type_class'], ['BAR'])
(['real_menu_type'], ['BAR'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344483'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/b89c707ff99087cd8098ddaf3b5f1346.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/b89c707ff99087cd8098ddaf3b5f1346.jpg'])
(['filename'], ['b89c707ff99087cd8098ddaf3b5f1346.jpg'])
(['url_master'], ['menus_original/705/51705/b89c707ff99087cd8098ddaf3b5f1346.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/b89c707ff99087cd8098ddaf3b5f1346.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['BAR'])
(['title'], ['BAR'])
(['menu_type_class'], ['BAR'])
(['real_menu_type'], ['BAR'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344484'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/439bf88da8bfce35ba44c6f206360a90.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/439bf88da8bfce35ba44c6f206360a90.jpg'])
(['filename'], ['439bf88da8bfce35ba44c6f206360a90.jpg'])
(['url_master'], ['menus_original/705/51705/439bf88da8bfce35ba44c6f206360a90.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/439bf88da8bfce35ba44c6f206360a90.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['BAR'])
(['title'], ['BAR'])
(['menu_type_class'], ['BAR'])
(['real_menu_type'], ['BAR'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344485'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/854abd602c815f84dcaa2fdea1c22f81.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/854abd602c815f84dcaa2fdea1c22f81.jpg'])
(['filename'], ['854abd602c815f84dcaa2fdea1c22f81.jpg'])
(['url_master'], ['menus_original/705/51705/854abd602c815f84dcaa2fdea1c22f81.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/854abd602c815f84dcaa2fdea1c22f81.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['BAR'])
(['title'], ['BAR'])
(['menu_type_class'], ['BAR'])
(['real_menu_type'], ['BAR'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344486'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/7670f299fd8f065252b94665df390790.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/7670f299fd8f065252b94665df390790.jpg'])
(['filename'], ['7670f299fd8f065252b94665df390790.jpg'])
(['url_master'], ['menus_original/705/51705/7670f299fd8f065252b94665df390790.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/7670f299fd8f065252b94665df390790.jpg'])
(['data_center'], ['sng'])
(['menu_type'], ['BAR'])
(['title'], ['BAR'])
(['menu_type_class'], ['BAR'])
(['real_menu_type'], ['BAR'])
(['is_salt_special_menu'], ['0'])
(['start_date'], [''])
(['consumer_upload'], ['0'])
(['start_date_formatted'], [''])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344487'])
(['url'], ['https://b.zmtcdn.com/data/menus/705/51705/f308c376afe08aed9b4ccf38eb0d6652.jpg'])
(['href'], ['https://b.zmtcdn.com/data/menus/705/51705/f308c376afe08aed9b4ccf38eb0d6652.jpg'])
(['filename'], ['f308c376afe08aed9b4ccf38eb0d6652.jpg'])
(['url_master'], ['menus_original/705/51705/f308c376afe08aed9b4ccf38eb0d6652.jpg'])
(['path_master'], ['/home/foodie/zomato_data/menus_original/705/51705/f308c376afe08aed9b4ccf38eb0d6652.jpg'])
.........................................................
(['data_center'], ['sng'])
(['menu_type'], ['BAR'])
(['end_date'], [''])
(['end_date_formatted'], [''])
(['id'], ['129344482'])
</code></pre>
<p>The output is truncated as there is way too much, you can find specific <em>properties/values</em> with your <em>xpaths</em> as you would with any tree.</p>
| 2 |
2016-09-10T13:20:44Z
|
[
"javascript",
"python",
"beautifulsoup",
"html-parsing"
] |
Sending string to serial.to_bytes not working
| 39,424,865 |
<p>I am trying to send a string variable contains the command.</p>
<p>Like this:</p>
<pre><code>value="[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
self.s.write(serial.to_bytes(value))
</code></pre>
<p>The above one fails. Won't give any error.</p>
<p>But it's working when I send a value like this:</p>
<pre><code>self.s.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))
</code></pre>
<p>I also tried sending string like this:</p>
<pre><code>self.s.write(serial.to_bytes(str(value)))
</code></pre>
<p>Still not working. Can someone please let me know how to send the value by storing in string?</p>
<p>I want to do this thing:</p>
<pre><code>value="[0x"+anotherstring+",0x"+string2+"0x33, 0x0a]"
</code></pre>
<p>and send the value.</p>
<p>Thanks!</p>
| 1 |
2016-09-10T09:54:04Z
| 39,425,136 |
<p><a href="https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.to_bytes" rel="nofollow">serial.to_bytes</a> takes a sequence as input. You should remove double quotes around <code>value</code> to pass a sequence of integers instead of a <code>str</code> representing the sequence you want to pass:</p>
<pre><code>value = [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]
self.s.write(serial.to_bytes(value)) # works now
</code></pre>
<p>In the first case, you sent a sequence of bytes representing <code>"[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"</code>. Now, you will send the sequence <code>[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]</code> as expected.</p>
<hr>
<p>If you want to send a string, just send it as <code>bytes</code>:</p>
<pre><code># Python 2
self.s.write('this is my string')
text = 'a string'
self.s.write(text)
# Python 3
self.s.write(b'this is my string')
text = 'a string'
self.s.write(text.encode())
</code></pre>
<p>And for a sequence:</p>
<pre><code>for value in values:
# Python 2
self.s.write(value)
# Python 3
self.s.write(value.encode())
</code></pre>
| 4 |
2016-09-10T10:29:21Z
|
[
"python",
"pyserial"
] |
Sending string to serial.to_bytes not working
| 39,424,865 |
<p>I am trying to send a string variable contains the command.</p>
<p>Like this:</p>
<pre><code>value="[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
self.s.write(serial.to_bytes(value))
</code></pre>
<p>The above one fails. Won't give any error.</p>
<p>But it's working when I send a value like this:</p>
<pre><code>self.s.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))
</code></pre>
<p>I also tried sending string like this:</p>
<pre><code>self.s.write(serial.to_bytes(str(value)))
</code></pre>
<p>Still not working. Can someone please let me know how to send the value by storing in string?</p>
<p>I want to do this thing:</p>
<pre><code>value="[0x"+anotherstring+",0x"+string2+"0x33, 0x0a]"
</code></pre>
<p>and send the value.</p>
<p>Thanks!</p>
| 1 |
2016-09-10T09:54:04Z
| 39,519,016 |
<p>If passing a list of integers works for you then just convert your hexadecimal representations into integers and put them in a list.</p>
<p>Detailed steps:</p>
<ol>
<li><p>Open a python interpreter</p></li>
<li><p>Import <code>serial</code>and open a serial port, call it <code>ser</code>.</p></li>
<li><p>Copy the code below and paste it in the python interpreter:</p></li>
</ol>
<p>The code:</p>
<pre><code>command = '310a320a330a'
hex_values = ['0x' + command[0:2], '0x' + command[2:4],
'0x' + command[4:6], '0x' + command[6:8],
'0x' + command[8:10], '0x' + command[10:12]]
int_values = [int(h, base=16) for h in hex_values]
ser.write(serial.to_bytes(int_values))
</code></pre>
<p>It will have the same effect that just this:</p>
<pre><code>ser.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))
</code></pre>
<p>actually you can test that <code>int_values == [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]</code> is <code>True</code> so you are writing exactly the same thing.</p>
| 2 |
2016-09-15T19:35:01Z
|
[
"python",
"pyserial"
] |
Manually set models.DateTimeField
| 39,424,903 |
<p>I've created a Transaction table which I want to test, one of the most important field of this table is:</p>
<pre><code>models.DateTimeField(
default=timezone.now)
</code></pre>
<p>In order to test my app with the database, I need historical data. Currently when I create a transaction, it sets the date and time automatically, so it is always current.</p>
<p>I need previous month data and I'm wondering if I can manually set the above field when I create a transaction?</p>
| 0 |
2016-09-10T09:58:12Z
| 39,424,924 |
<blockquote>
<p>Currently when I create a transaction, it sets the date and time automatically</p>
</blockquote>
<p>You can always override that default value before you save the model instance, for the example below let's assume your <code>DateTimeField</code> with the default value is called <code>timestamp</code>:</p>
<pre><code>import datetime
transaction = Transaction()
transaction.timestamp = timestamp # Overrides the default
# You can use a datetime.datetime
# instance as value
# transaction.timestamp = datetime.datetime(year, month, day, hour, minute, second)
transaction.save()
</code></pre>
<p>"Override" is a big word, since the default is only used when you don't provide a value.</p>
<blockquote>
<p>and what is the format of the timestamp? is it timestamp = datetime (year, month, day, hour..)?</p>
</blockquote>
<p>Yes the <code>DateTimeField</code> field will accept a <a href="https://docs.python.org/2/library/datetime.html#datetime-objects" rel="nofollow"><code>datetime.datetime</code> object</a>.</p>
| 1 |
2016-09-10T10:00:41Z
|
[
"python",
"django"
] |
WSGI module and Django settings locations
| 39,425,092 |
<p>I'm using Django with uWSGI and trying to organise my web server config files as follow:</p>
<pre><code>/proj/
web_config/
docker-compose.py
...
prod/
nginx.conf
wsgi.py
uwsgi_params
uwsgi.ini
...
app/
__init__.py
settings.py
</code></pre>
<p>My problem is I don't know how to reference the final django settings module from my WSGI module:</p>
<p><strong>uwsgi.ini</strong></p>
<pre><code>[uwsgi]
# ...
module = wsgi
env = DJANGO_SETTINGS_MODULE=(../../)app.settings # <- Problem here
</code></pre>
<p><strong>wsgi.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import os
from django.core.wsgi import get_wsgi_application
# v- Or problem here -v
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "(../../)app.settings")
application = get_wsgi_application()
</code></pre>
<p>Is there a way to point to the right <code>app.settings</code><br>
without placing <code>wsgi.py</code> in <code>/proj/</code> or <code>/proj/app</code> ?</p>
| 0 |
2016-09-10T10:24:39Z
| 39,430,165 |
<p>In this case, to reference to django settings, all you need to do is chdir from your <code>uwsgi.ini</code> to <code>/proj/</code> directory. Now load your <code>wsgi.py</code> file (you can keep it in your <code>app/</code> subdirectory, it doesn't contain any settings) from it using <code>module</code> uWSGI setting and set <code>DJANGO_SETTINGS_MODULE</code> to <code>app.settings</code>, without anything else (it is enough to set it only in <code>wsgi.py</code> file).</p>
<p>It should look like this (if you've moved your <code>wsgi.py</code> back to <code>app/</code>):</p>
<p>uwsgi.ini:</p>
<pre><code>[uwsgi]
# ...
chdir = /proj/
module = app.wsgi
</code></pre>
<p>wsgi.py</p>
<pre><code>import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
application = get_wsgi_application()
</code></pre>
<p>If you don't want (for some reason) to keep your <code>wsgi.py</code> file in <code>app/</code>, your <code>uwsgi.py</code> should have:</p>
<pre><code>[uwsgi]
# ...
chdir = /proj/
module = web_config.prod.wsgi
</code></pre>
<p>But <code>web_config</code> and <code>prod</code> should be proper python modules (in python 2 they must have <code>__init__.py</code> file inside). Content of <code>wsgi.py</code> doesn't change.</p>
| 1 |
2016-09-10T20:10:03Z
|
[
"python",
"django",
"wsgi",
"uwsgi"
] |
Break a shapely Linestring at multiple points
| 39,425,093 |
<p>This code below was modified from the one I found <a href="http://stackoverflow.com/questions/21407233/get-the-vertices-on-a-linestring-either-side-of-a-point/21419035#21419035">here</a> which splits a shapely Linestring into two segments at a point defined along the line. I have also checked other questions but they don't address my query directly. However I will like to extend it to split the line into multiple segments (at multiple points), all my attempts to do that so far has failed. How can it be modified to split the string into any given number of segments or at multiple points say ((4,5),(9,18) and (6,5)). </p>
<pre><code>input:
line = LineString([(1,2),(8,7),(4,5),(2,4),(4,7),(8,5),(9,18),(1,2),(12,7),(4,5),(6,5),(4,9)])
breakPoint = Point(2,4)
from shapely.geometry import Point,LineString
def make_line_segment(line_string, breakPoint):
geoLoc = line_string.coords
j = None
for i in range(len(geoLoc) - 1):
if LineString(geoLoc[i:i + 2]).intersects(breakPoint):
j = i
break
assert j is not None
# Make sure to always include the point in the first group
if Point(geoLoc[j + 1:j + 2]).equals(breakPoint):
return geoLoc[:j + 2], geoLoc[j + 1:]
else:
return geoLoc[:j + 1], geoLoc[j:]
line1,line2 = make_line_segment(line,breakPoint)
line1 = LineString(line1)
line2 = LineString(line2)
print line1, line2
output: `LINESTRING (1 2, 8 7, 4 5, 2 4) LINESTRING (2 4, 4 7, 8 5, 9 18, 1 2, 12 7, 4 5, 6 5, 4 9)`
</code></pre>
| 0 |
2016-09-10T10:24:44Z
| 39,574,007 |
<p>The <code>projection</code> and <code>interpolate</code> lineString methods are usually handy for this kind of operations.</p>
<pre><code>from shapely.geometry import Point, LineString
def cut(line, distance):
# Cuts a line in two at a distance from its starting point
# This is taken from shapely manual
if distance <= 0.0 or distance >= line.length:
return [LineString(line)]
coords = list(line.coords)
for i, p in enumerate(coords):
pd = line.project(Point(p))
if pd == distance:
return [
LineString(coords[:i+1]),
LineString(coords[i:])]
if pd > distance:
cp = line.interpolate(distance)
return [
LineString(coords[:i] + [(cp.x, cp.y)]),
LineString([(cp.x, cp.y)] + coords[i:])]
def split_line_with_points(line, points):
"""Splits a line string in several segments considering a list of points.
The points used to cut the line are assumed to be in the line string
and given in the order of appearance they have in the line string.
>>> line = LineString( [(1,2), (8,7), (4,5), (2,4), (4,7), (8,5), (9,18),
... (1,2),(12,7),(4,5),(6,5),(4,9)] )
>>> points = [Point(2,4), Point(9,18), Point(6,5)]
>>> [str(s) for s in split_line_with_points(line, points)]
['LINESTRING (1 2, 8 7, 4 5, 2 4)', 'LINESTRING (2 4, 4 7, 8 5, 9 18)', 'LINESTRING (9 18, 1 2, 12 7, 4 5, 6 5)', 'LINESTRING (6 5, 4 9)']
"""
segments = []
current_line = line
for p in points:
d = current_line.project(p)
seg, current_line = cut(current_line, d)
segments.append(seg)
segments.append(current_line)
return segments
if __name__ == "__main__":
import doctest
doctest.testmod()
</code></pre>
| 1 |
2016-09-19T13:07:28Z
|
[
"python",
"shapely"
] |
Pandas naming multiple sheets according to list of lists
| 39,425,111 |
<p>First time I post here and I am rather a newbie. </p>
<p>Anyhow, I have been playing around with Pandas and Numpy to make some calculations from Excel.</p>
<p>Now I want to create an .xlsx file to which I can output my results and I want each sheet to be named after the name of the dataframe that is being outputted.</p>
<p>This is my code, I tried a couple of different solutions but I can't figure how to write it. </p>
<p>In the code you can see that save_excel just makes numbered sheets (and it works great) and save_excelB tries to do what I am describing it but I can't get it to work.</p>
<pre><code>from generate import A,b,L,dr,dx
from pandas import DataFrame as df
from pandas import ExcelWriter as ew
A=df(A) #turning numpy arrays into dataframes
b=df(b)
L=df(L)
dr=df(dr)
dx=df(dx)
C=[A,b,L,dr,dx] #making a list of the dataframes to iterate through
def save_excel(filename, item):
w=ew(filename)
for n, i in enumerate(item):
i.to_excel(w, "sheet%s" % n, index=False, header=False)
w.save()
def save_excelB(filename, item):
w=ew(filename)
for name in item:
i=globals()[name]
i.to_excel(w, sheet_name=name, index=False, header=False)
w.save()
</code></pre>
<p>I run both in the same way I call the function and I add the file name and for item I insert the list C I have made. </p>
<p>So it would be: </p>
<pre><code>save_excelB("file.xlsx", C)
</code></pre>
<p>and this is what I get </p>
<pre><code>TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed
</code></pre>
| 0 |
2016-09-10T10:26:52Z
| 39,428,340 |
<p>You need to pass string literals of data frame names in your function and not actual data frame objects:</p>
<pre><code>C = ['A', 'b', 'L', 'dr', 'dx']
def save_excelB(filename, item):
w=ew(filename)
for name in item:
i=globals()[name]
i.to_excel(w, sheet_name=name, index=False, header=False)
w.save()
save_excelB("file.xlsx", C)
</code></pre>
<p>You can even dynamically create <em>C</em> with all dataframes currently in global environment by checking items that are pandas data frame class type:</p>
<pre><code>import pandas as pd
...
C = [i for i in globals() if type(globals()[i]) is pd.core.frame.DataFrame]
</code></pre>
| 0 |
2016-09-10T16:45:17Z
|
[
"python",
"excel",
"pandas"
] |
Django heroku uploading files
| 39,425,217 |
<blockquote>
<p>[Errno 30] Read-only file system: '/static_in_env'</p>
</blockquote>
<p>I am new to heroku, when I push my django application on heroku, I can't upload files, yet it is working properly in local computer! </p>
<p>Here is the error:</p>
<pre><code>OSError at /admin/products/product/add/
[Errno 30] Read-only file system: '/static_in_env'
Request Method: POST
Django Version: 1.8
Exception Type: OSError
Exception Value:
[Errno 30] Read-only file system: '/static_in_env'
Exception Location: /app/.heroku/python/lib/python2.7/os.py in makedirs, line 157
Python Executable: /app/.heroku/python/bin/python
Python Version: 2.7.12
Python Path:
['/app',
'/app/.heroku/python/bin',
'/app',
'/app/.heroku/python/lib/python27.zip',
'/app/.heroku/python/lib/python2.7',
'/app/.heroku/python/lib/python2.7/plat-linux2',
'/app/.heroku/python/lib/python2.7/lib-tk',
'/app/.heroku/python/lib/python2.7/lib-old',
'/app/.heroku/python/lib/python2.7/lib-dynload',
'/app/.heroku/python/lib/python2.7/site-packages',
'/app/.heroku/python/lib/python2.7/site-packages/setuptools-25.2.0-py2.7.egg',
'/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg']
Server time: Sat, 10 Sep 2016 10:14:54 +0000
</code></pre>
| -1 |
2016-09-10T10:40:31Z
| 39,425,651 |
<p>Unfortunately, Heroku does not host your application Media files. So what you need is to pick up a third party service like AWS S3 to store data in the cloud. </p>
<p>Below is the official guide of how you can deal with Django applications media files on Heroku.</p>
<p><a href="https://devcenter.heroku.com/articles/s3-upload-python" rel="nofollow">https://devcenter.heroku.com/articles/s3-upload-python</a></p>
<p>Reminder: Django "media" files are files that have been uploaded by web site users, that then need to be served from your site.</p>
| 0 |
2016-09-10T11:38:53Z
|
[
"python",
"html",
"css",
"django",
"heroku"
] |
Stop Scrapy spider when it meets a specified URL
| 39,425,456 |
<p>This question is very similar to <a href="http://stackoverflow.com/questions/4448724/force-my-scrapy-spider-to-stop-crawling">Force my scrapy spider to stop crawling</a> and some others asked several years ago. However, the suggested solutions there are either dated for Scrapy 1.1.1 or not precisely relevant. <strong>The task is to close the spider when it reaches a certain URL.</strong> You definitely need this when crawling a news website for your media project, for instance.</p>
<p>Among the settings <code>CLOSESPIDER_TIMEOUT</code> <code>CLOSESPIDER_ITEMCOUNT</code> <code>CLOSESPIDER_PAGECOUNT</code> <code>CLOSESPIDER_ERRORCOUNT</code>, item count and page count options are close but not enough since you never know the number of pages or items.</p>
<p>The <code>raise CloseSpider(reason='some reason')</code> exception seems to do the job but so far it does it in a bit weird way. I follow the <a href="https://www.packtpub.com/big-data-and-business-intelligence/learning-scrapy" rel="nofollow">âLearning Scrapyâ</a> textbook and the structure of my code looks like the one in the book.</p>
<p>In <code>items.py</code> I make a list of items:</p>
<pre><code>class MyProjectItem(scrapy.Item):
Headline = scrapy.Field()
URL = scrapy.Field()
PublishDate = scrapy.Field()
Author = scrapy.Field()
pass
</code></pre>
<p>In <code>myspider.py</code> I use the <code>def start_requests()</code> method where the spider takes the pages to process, parse each index page in <code>def parse()</code>, and specify the XPath for each item in <code>def parse_item()</code>:</p>
<pre><code>class MyProjectSpider(scrapy.Spider):
name = 'spidername'
allowed_domains = ['domain.name.com']
def start_requests(self):
for i in range(1,3000):
yield scrapy.Request('http://domain.name.com/news/index.page'+str(i)+'.html', self.parse)
def parse(self, response):
urls = response.xpath('XPath for the URLs on index page').extract()
for url in urls:
# The urls are absolute in this case. Thereâs no need to use urllib.parse.urljoin()
yield scrapy.Request(url, callback=self.parse_item)
def parse_item(self, response):
l = ItemLoader(item=MyProjectItem(), response=response)
l.add_xpath('Headline', 'XPath for Headline')
l.add_value('URL', response.url)
l.add_xpath ('PublishDate', 'XPath for PublishDate')
l.add_xpath('Author', 'XPath for Author')
return l.load_item()
</code></pre>
<p>If <code>raise CloseSpider(reason='some reason')</code> exception is placed in <code>def parse_item()</code>, it still scrapes a number of items before it finally stops:</p>
<pre><code>if l.get_output_value('URL') == 'http://domain.name.com/news/1234567.html':
raise CloseSpider('No more news items.')
</code></pre>
<p>If itâs placed in <code>def parse()</code> method to stop when the specific URL is reached, it stops after grabbing only the first item from the index page which contains that specific URL: </p>
<pre><code>def parse(self, response):
most_recent_url_in_db = 'http://domain.name.com/news/1234567.html '
urls = response.xpath('XPath for the URLs on index page').extract()
if most_recent_url_in_db not in urls:
for url in urls:
yield scrapy.Request(url, callback=self.parse_item)
else:
for url in urls[:urls.index(most_recent_url_in_db)]:
yield scrapy.Request(url, callback=self.parse_item)
raise CloseSpider('No more news items.')
</code></pre>
<p>For example, if you have 5 index pages (each of them has 25 item URLs) and <code>most_recent_url_in_db</code> is on page 4, it means that youâll have all items from pages 1-3 and only the first item from page 4. Then the spider stops. If <code>most_recent_url_in_db</code> is number 10 in the list, items 2-9 from index page 4 wonât appear in your database.</p>
<p>The âhackyâ tricks with <code>crawler.engine.close_spider()</code> suggested in many cases or the ones shared in <a href="http://stackoverflow.com/questions/9699049/how-do-i-stop-all-spiders-and-the-engine-immediately-after-a-condition-in-a-pipe">How do I stop all spiders and the engine immediately after a condition in a pipeline is met?</a> donât seem to work.</p>
<p>What should be the method to properly complete this task?</p>
| 1 |
2016-09-10T11:13:11Z
| 39,436,631 |
<p>When you raise <code>close_spider() exception</code>, ideal assumption is that scrapy should stop immediately, abandoning all other activity (any future page requests, any processing in pipeline ..etc)</p>
<p>but this is not the case, When you raise <code>close_spider() exception</code>, scrapy will try to close it's current operation's <strong>gracefully</strong> , meaning it will stop the current request but it will wait for any other request pending in any of the queues( there are multiple queues!)</p>
<p>(i.e. if you are not overriding default settings and have more than 16 start urls, scrapy make 16 requests at a time)</p>
<p>Now if you want to stop spider as soon as you Raise <code>close_spider() exception</code>, you will want to clear three Queues</p>
<p>-- At spider middleware level ---</p>
<ul>
<li>spider.crawler.engine.slot.scheduler.mqs -> Memory Queue future request</li>
<li>spider.crawler.engine.slot.inprogress -> Any In-progress Request</li>
</ul>
<p>-- download middleware level ---</p>
<ul>
<li>spider.requests_queue -> pending Request in Request queue</li>
</ul>
<p>flush all this queues by overriding proper middle-ware to prevent scrapy from visiting any further pages</p>
| 0 |
2016-09-11T13:32:43Z
|
[
"python",
"scrapy"
] |
Stop Scrapy spider when it meets a specified URL
| 39,425,456 |
<p>This question is very similar to <a href="http://stackoverflow.com/questions/4448724/force-my-scrapy-spider-to-stop-crawling">Force my scrapy spider to stop crawling</a> and some others asked several years ago. However, the suggested solutions there are either dated for Scrapy 1.1.1 or not precisely relevant. <strong>The task is to close the spider when it reaches a certain URL.</strong> You definitely need this when crawling a news website for your media project, for instance.</p>
<p>Among the settings <code>CLOSESPIDER_TIMEOUT</code> <code>CLOSESPIDER_ITEMCOUNT</code> <code>CLOSESPIDER_PAGECOUNT</code> <code>CLOSESPIDER_ERRORCOUNT</code>, item count and page count options are close but not enough since you never know the number of pages or items.</p>
<p>The <code>raise CloseSpider(reason='some reason')</code> exception seems to do the job but so far it does it in a bit weird way. I follow the <a href="https://www.packtpub.com/big-data-and-business-intelligence/learning-scrapy" rel="nofollow">âLearning Scrapyâ</a> textbook and the structure of my code looks like the one in the book.</p>
<p>In <code>items.py</code> I make a list of items:</p>
<pre><code>class MyProjectItem(scrapy.Item):
Headline = scrapy.Field()
URL = scrapy.Field()
PublishDate = scrapy.Field()
Author = scrapy.Field()
pass
</code></pre>
<p>In <code>myspider.py</code> I use the <code>def start_requests()</code> method where the spider takes the pages to process, parse each index page in <code>def parse()</code>, and specify the XPath for each item in <code>def parse_item()</code>:</p>
<pre><code>class MyProjectSpider(scrapy.Spider):
name = 'spidername'
allowed_domains = ['domain.name.com']
def start_requests(self):
for i in range(1,3000):
yield scrapy.Request('http://domain.name.com/news/index.page'+str(i)+'.html', self.parse)
def parse(self, response):
urls = response.xpath('XPath for the URLs on index page').extract()
for url in urls:
# The urls are absolute in this case. Thereâs no need to use urllib.parse.urljoin()
yield scrapy.Request(url, callback=self.parse_item)
def parse_item(self, response):
l = ItemLoader(item=MyProjectItem(), response=response)
l.add_xpath('Headline', 'XPath for Headline')
l.add_value('URL', response.url)
l.add_xpath ('PublishDate', 'XPath for PublishDate')
l.add_xpath('Author', 'XPath for Author')
return l.load_item()
</code></pre>
<p>If <code>raise CloseSpider(reason='some reason')</code> exception is placed in <code>def parse_item()</code>, it still scrapes a number of items before it finally stops:</p>
<pre><code>if l.get_output_value('URL') == 'http://domain.name.com/news/1234567.html':
raise CloseSpider('No more news items.')
</code></pre>
<p>If itâs placed in <code>def parse()</code> method to stop when the specific URL is reached, it stops after grabbing only the first item from the index page which contains that specific URL: </p>
<pre><code>def parse(self, response):
most_recent_url_in_db = 'http://domain.name.com/news/1234567.html '
urls = response.xpath('XPath for the URLs on index page').extract()
if most_recent_url_in_db not in urls:
for url in urls:
yield scrapy.Request(url, callback=self.parse_item)
else:
for url in urls[:urls.index(most_recent_url_in_db)]:
yield scrapy.Request(url, callback=self.parse_item)
raise CloseSpider('No more news items.')
</code></pre>
<p>For example, if you have 5 index pages (each of them has 25 item URLs) and <code>most_recent_url_in_db</code> is on page 4, it means that youâll have all items from pages 1-3 and only the first item from page 4. Then the spider stops. If <code>most_recent_url_in_db</code> is number 10 in the list, items 2-9 from index page 4 wonât appear in your database.</p>
<p>The âhackyâ tricks with <code>crawler.engine.close_spider()</code> suggested in many cases or the ones shared in <a href="http://stackoverflow.com/questions/9699049/how-do-i-stop-all-spiders-and-the-engine-immediately-after-a-condition-in-a-pipe">How do I stop all spiders and the engine immediately after a condition in a pipeline is met?</a> donât seem to work.</p>
<p>What should be the method to properly complete this task?</p>
| 1 |
2016-09-10T11:13:11Z
| 39,554,040 |
<p>I'd recommend to change your approach. Scrapy crawls many requests concurrently without a linear order, that's why closing the spider when you find what you're looking for won't do, since a request after that could already be processed.</p>
<p>To tackle this you could make Scrapy crawl sequentially, meaning a request at a time in a fixed order. This can be achieved in different ways, here's an example about how I would go about it.</p>
<p>First of all, you should crawl a single page at a time. This could be done like this:</p>
<pre><code>class MyProjectSpider(scrapy.Spider):
pagination_url = 'http://domain.name.com/news/index.page{}.html'
def start_requests(self):
yield scrapy.Request(
self.pagination_url.format(1),
meta={'page_number': 1},
)
def parse(self, response):
# code handling item links
...
page_number = response.meta['page_number']
next_page_number = page_number + 1
if next_page_number <= 3000:
yield scrapy.Request(
self.pagination_url.format(next_page_number),
meta={'page_number': next_page_number},
)
</code></pre>
<p>Once that's implemented, you could do something similar with the links in each page. However, since you can filter them without downloading their content, you could do something like this:</p>
<pre><code>class MyProjectSpider(scrapy.Spider):
most_recent_url_in_db = 'http://domain.name.com/news/1234567.html '
def parse(self, response):
url_found = False
urls = response.xpath('XPath for the URLs on index page').extract()
for url in urls:
if url == self.most_recent_url_in_db:
url_found = True
break
yield scrapy.Request(url, callback=self.parse_item)
page_number = response.meta['page_number']
next_page_number = page_number + 1
if not url_found:
yield scrapy.Request(
self.pagination_url.format(next_page_number),
meta={'page_number': next_page_number},
)
</code></pre>
<p>Putting all together you'll have:</p>
<pre><code>class MyProjectSpider(scrapy.Spider):
name = 'spidername'
allowed_domains = ['domain.name.com']
pagination_url = 'http://domain.name.com/news/index.page{}.html'
most_recent_url_in_db = 'http://domain.name.com/news/1234567.html '
def start_requests(self):
yield scrapy.Request(
self.pagination_url.format(1),
meta={'page_number': 1}
)
def parse(self, response):
url_found = False
urls = response.xpath('XPath for the URLs on index page').extract()
for url in urls:
if url == self.most_recent_url_in_db:
url_found = True
break
yield scrapy.Request(url, callback=self.parse_item)
page_number = response.meta['page_number']
next_page_number = page_number + 1
if next_page_number <= 3000 and not url_found:
yield scrapy.Request(
self.pagination_url.format(next_page_number),
meta={'page_number': next_page_number},
)
def parse_item(self, response):
l = ItemLoader(item=MyProjectItem(), response=response)
l.add_xpath('Headline', 'XPath for Headline')
l.add_value('URL', response.url)
l.add_xpath ('PublishDate', 'XPath for PublishDate')
l.add_xpath('Author', 'XPath for Author')
return l.load_item()
</code></pre>
<p>Hope that gives you an idea on how to accomplish what you're looking for, good luck!</p>
| 1 |
2016-09-18T04:17:34Z
|
[
"python",
"scrapy"
] |
How to identify and switch to the frame source in Selenium?
| 39,425,541 |
<p>I have been using the Selenium and Python2.7, on Firefox.</p>
<p>I would like it to work like the following, but I do not know how to write code.</p>
<pre><code>Driver.get('https://video-download.online')
Url='https://www.youtube.com/watch?v=waQlR8W8aTA'
Driver.find_element_by_id("link").send_keys(Url)
Driver.find_element_by_id("submit").click()
time.sleep(5)
#[Click]lowermost(highest quality) radio button
#[Click]Proceed button
</code></pre>
| 0 |
2016-09-10T11:23:23Z
| 39,426,014 |
<p>You are able to get frame locator value in HTML code which is specified in iframes tag. u can move up from where your locator value is existed in HTML code.</p>
<p>This function is suitable:</p>
<pre><code>def frame_switch(css_selector):
driver.switch_to.frame(driver.find_element_by_css_selector(css_selector))
</code></pre>
<p>If you are just trying to switch to the frame based on the <code>name</code> attribute, then you can use this:</p>
<pre><code>def frame_switch(name):
driver.switch_to.frame(driver.find_element_by_name(name))
</code></pre>
| 0 |
2016-09-10T12:19:36Z
|
[
"python",
"selenium",
"firefox"
] |
Receive data from client without using "dataReceived" function in Twisted
| 39,425,606 |
<p>How to receive the data from the client, bypassing the standard class function Protocol? For example,</p>
<pre><code>class TW(protocol.Protocol):
def get_data(delim = '\n'):
#some code
return data
</code></pre>
<p>I.e, without using the function "dataReceived", and not freezing all other the server clients?</p>
| 0 |
2016-09-10T11:33:42Z
| 39,475,696 |
<p>You can't bypass <code>dataReceived</code> unless you like doing things the hard way :D. You can do what ever you're doing in <code>get_data()</code> in <code>dataReceived()</code>. Alternatively, you could add a <code>data</code> param in your <code>get_data()</code> and do a callback form <code>dataReceived</code>.</p>
<pre><code>class TW(Protocol):
def get_data(data, delim='\n'):
# some code
return result
def dataReceived(self, data):
result = self.get_data(data, delim='\r\n')
# do some more stuff
</code></pre>
| 0 |
2016-09-13T17:21:08Z
|
[
"python",
"server",
"twisted",
"twisted.internet"
] |
Columns to row in python
| 39,425,618 |
<p>Do we have sas equivalent of proc transpose. i have the following variables</p>
<pre><code> a b c d e f g
1 3 4 5 3 2 2
2 3 3 3 2 4 2
</code></pre>
<p>i want to transpose, across columns a and b , dummy out put below:</p>
<pre><code> a b tranposed_columns transposed_value
1 3 c 4
1 3 d 5
1 3 e 3
1 3 f 2
1 3 g 2
2 3 c 3
2 3 d 3
2 3 e 2
2 3 f 4
2 3 g 2
</code></pre>
<p>How can i do this in python, in sas i would have written</p>
<pre><code> proc transpose data=Dummy_data
out=ouput_data (rename=(col1=transposed_value _name_=tranposed_columns));
by a b;
run;
</code></pre>
<p>i tried dummy_data.T , but it tranposes all the data, also tried hands with pivot data, but its not repeating the rows.</p>
<pre><code>dummy_data.pivot_table(index=['a','b'],values=['c','d','e','f','g'], aggfunc='sum', fill_value=0)
</code></pre>
| 0 |
2016-09-10T11:34:38Z
| 39,425,783 |
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>pd.melt</code></a> to coalesce columns into a single column. Use the <code>id_vars</code> parameter to "protect" certain columns from participating in the melt:</p>
<pre><code>In [11]: pd.melt(df, id_vars=['a','b'], var_name='transposed_columns', value_name='transposed_value')
Out[11]:
a b transposed_columns transposed_value
0 1 3 c 4
1 2 3 c 3
2 1 3 d 5
3 2 3 d 3
4 1 3 e 3
5 2 3 e 2
6 1 3 f 2
7 2 3 f 4
8 1 3 g 2
9 2 3 g 2
</code></pre>
| 2 |
2016-09-10T11:52:56Z
|
[
"python",
"pandas",
"python-3.4",
"transpose"
] |
Writing Non-Data Descriptor in Python
| 39,425,643 |
<p>I am learning about descriptors in python. I want to write a non-data descriptor but the class having the descriptor as its classmethod doesn't call the <code>__get__</code> spacial method when i call the classmethod. This is my example (without the <code>__set__</code>):</p>
<pre><code>class D(object):
"The Descriptor"
def __init__(self, x = 1395):
self.x = x
def __get__(self, instance, owner):
print "getting", self.x
return self.x
class C(object):
d = D()
def __init__(self, d):
self.d = d
</code></pre>
<p>And here is how i call it:</p>
<pre><code>>>>c = C(4)
>>>c.d
4
</code></pre>
<p>The <code>__get__</code> of the descriptor class gets no call. But when i also set a <code>__set__</code> the descriptor seems to get activated:</p>
<pre><code>class D(object):
"The Descriptor"
def __init__(self, x = 1395):
self.x = x
def __get__(self, instance, owner):
print "getting", self.x
return self.x
def __set__(self, instance, value):
print "setting", self.x
self.x = value
class C(object):
d = D()
def __init__(self, d):
self.d = d
</code></pre>
<p>Now i create a <code>C</code> instance:</p>
<pre><code>>>> c=C(4)
setting 1395
>>> c.d
getting 4
4
</code></pre>
<p>and both of <code>__get__, __set__</code> are present. It seems that i am missing some basic concepts about descriptors and how they can be used. Can anyone explain this behavior of <code>__get__, __set__</code>?</p>
| 2 |
2016-09-10T11:38:25Z
| 39,425,675 |
<p>You successfully created a proper non-data descriptor, but you then <em>mask</em> the <code>d</code> attribute by setting an instance attribute.</p>
<p>Because it is a <em>non</em>-data descriptor, the instance attribute wins in this case. When you add a <code>__set__</code> method, you turn your descriptor into a data descriptor, and data descriptors are always applied even if there is an instance attribute.</p>
<p>From the <a href="https://docs.python.org/2/howto/descriptor.html" rel="nofollow"><em>Descriptor Howto</em></a>:</p>
<blockquote>
<p>The default behavior for attribute access is to get, set, or delete the attribute from an objectâs dictionary. For instance, <code>a.x</code> has a lookup chain starting with <code>a.__dict__['x']</code>, then <code>type(a).__dict__['x']</code>, and continuing through the base classes of <code>type(a)</code> excluding metaclasses. If the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>If an object defines both <code>__get__()</code> and <code>__set__()</code>, it is considered a data descriptor. Descriptors that only define <code>__get__()</code> are called non-data descriptors (they are typically used for methods but other uses are possible).</p>
<p>Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instanceâs dictionary. If an instanceâs dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instanceâs dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.</p>
</blockquote>
<p>If you <em>remove</em> the <code>d</code> instance attribute (never set it or delete it from the instance), the descriptor object gets invoked:</p>
<pre><code>>>> class D(object):
... def __init__(self, x = 1395):
... self.x = x
... def __get__(self, instance, owner):
... print "getting", self.x
... return self.x
...
>>> class C(object):
... d = D()
...
>>> c = C()
>>> c.d
getting 1395
1395
</code></pre>
<p>Add an instance attribute again and the descriptor is ignored because the instance attribute wins:</p>
<pre><code>>>> c.d = 42 # setting an instance attribute
>>> c.d
42
>>> del c.d # deleting it again
>>> c.d
getting 1395
1395
</code></pre>
<p>Also see the <a href="https://docs.python.org/2/reference/datamodel.html#invoking-descriptors" rel="nofollow"><em>Invoking Descriptors</em> documentation</a> in the Python <em>Datamodel</em> reference.</p>
| 4 |
2016-09-10T11:41:44Z
|
[
"python",
"python-2.7",
"descriptor"
] |
How to modify variables in another python file?
| 39,425,762 |
<p><strong>windows 10 - python 3.5.2</strong></p>
<p>Hi, I have the two following python files, and I want to edit the second file's variables using the code in the first python file.</p>
<p><strong>firstfile.py</strong></p>
<pre><code>from X.secondfile import *
def edit():
#editing second file's variables by user input
if Language == 'en-US':
print('language is English-us')
elif Language == 'en-UK':
print('language is English-uk')
</code></pre>
<p><strong>secondfile.py</strong></p>
<pre><code>Language = 'en-US'
</code></pre>
<p>i can add some variables to it by following code, but how can i edit one ?</p>
<pre><code>with open("secondfile.py","a") as f:
f.write("Language = 'en-US'")
</code></pre>
<p>Any ideas how to do that?</p>
| 1 |
2016-09-10T11:51:03Z
| 39,425,879 |
<p>You can embed the <code>Language</code> in a class in the second file that has a method to change it.</p>
<h3>Module 2</h3>
<pre><code>class Language:
def __init__(self):
self.language = 'en-US'
def __str__(self):
return self.language
def change(self, lang):
assert isinstance(lang, str)
self.language = lang
language = Language()
</code></pre>
<p>Then import the "language," and change it with the change method.</p>
<h3>Module 1</h3>
<pre><code>from module2 import language
print(language)
language.change("test")
print(language)
</code></pre>
| 1 |
2016-09-10T12:02:33Z
|
[
"python",
"variables",
"module"
] |
How to modify variables in another python file?
| 39,425,762 |
<p><strong>windows 10 - python 3.5.2</strong></p>
<p>Hi, I have the two following python files, and I want to edit the second file's variables using the code in the first python file.</p>
<p><strong>firstfile.py</strong></p>
<pre><code>from X.secondfile import *
def edit():
#editing second file's variables by user input
if Language == 'en-US':
print('language is English-us')
elif Language == 'en-UK':
print('language is English-uk')
</code></pre>
<p><strong>secondfile.py</strong></p>
<pre><code>Language = 'en-US'
</code></pre>
<p>i can add some variables to it by following code, but how can i edit one ?</p>
<pre><code>with open("secondfile.py","a") as f:
f.write("Language = 'en-US'")
</code></pre>
<p>Any ideas how to do that?</p>
| 1 |
2016-09-10T11:51:03Z
| 39,425,960 |
<p>This can be done to edit a variable in another file:</p>
<pre><code>import X.secondfile
X.secondfile.Language = 'en-UK'
</code></pre>
<p>However, I have two suggestions:</p>
<ol>
<li><p>Don't use <code>import *</code> - it pollutes the namespace with unexpected
names</p></li>
<li><p>Don't use such global variables, if they are not constants. Some code will read the value before it is changed and some afterwards. And none will expect it to change.</p></li>
</ol>
<p>So, rather than this, create a class in the other file.</p>
<pre><code>class LanguagePreferences(object):
def __init__(self, langcode):
self.langcode = langcode
language_preferences = LanguagePreferences('en-UK')
</code></pre>
| 1 |
2016-09-10T12:12:32Z
|
[
"python",
"variables",
"module"
] |
Reverse accessor clashes in Django
| 39,425,863 |
<p>Error :
1) user.Login.password: (fields.E304) Reverse accessor for 'Login.password' clashes with reverse accessor for 'Login.username'.
2) user.Login.username: (fields.E304) Reverse accessor for 'Login.username' clashes with reverse accessor for 'Login.password'.</p>
<p>models.py</p>
<pre><code>from django.db import models
from django.core.urlresolvers import reverse
class User(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
confirm_password = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
position = models.CharField(max_length=50)
def get_absolute_url(self):
return reverse('user:register', kwargs={'pk': self.pk})
class Login(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE)
password = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
login = {'username': self.username, 'password': self.password}
return login
</code></pre>
| 0 |
2016-09-10T12:00:45Z
| 39,426,136 |
<p>You can solve the issue by using <code>related_name</code> attribute:</p>
<pre><code>class Login(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE, related_name="username_users")
password = models.ForeignKey(User, on_delete=models.CASCADE, related_name="password_users")
</code></pre>
<p>But I am not getting the reason for you having both password and username having fk relation with User!!!</p>
| 1 |
2016-09-10T12:35:19Z
|
[
"python",
"django"
] |
Project Euler 23 - No matter what I do, my answer is far too big
| 39,425,877 |
<p>Problem 23 asks for the sum of all numbers "not the sum of two abundant numers". We need only check numbers smaller than 28123. An integer n is abundant if its proper divisors sum to an integer greater than n - 12 is the first abundant number since 1+2+3+4+6 = 16 > 12. This makes 24 the smallest number which is a sum of 2 abundant numbers, so we want to exclude it from the sum.</p>
<p>Here's my python code, which I've tried many variations of, but using the same idea:</p>
<pre><code>import math
def divisors_of(n):
divs=[1]
for i in range(2,int(math.sqrt(n))+1):
if i**2 == n:
divs.append(i)
elif n%i == 0:
divs.append(i)
divs.append(n//i)
return divs
def is_abun(n):
return sum(divisors_of(n))>n
numbers=[i for i in range(1,28123)]
for i in numbers:
for j in range(1,i):
if is_abun(j) and is_abun(i-j):
numbers.remove(i)
break
print(sum(numbers))
</code></pre>
<p>The idea is simply that if j and i-j are abundant numbers, then of course j + (i-j) = i is a sum of abundant numbers, so I remove it from my list of numbers. Then I sum over all remaining numbers. I don't see how this could possibly fail. However, the result should be (gotten from another source) 4179871, while I always get something in the ballpark of 197711987, which is over 47 times too large. </p>
<p>I really cannot understand how this fails to generate the correct result. There must be some line which isn't doing what I think it is, but everything here is just <em>too simple</em> for me to be suspicious of them. I thought the most likely error would be in calculating the abundant numbers, but I am almost completely sure that part's correct (if I get the code as is to generate a list of abundant numbers less than 28123, I get a list of length 6965, which is how many abundant numbers less than 28123 WolframAlpha claims).</p>
| 0 |
2016-09-10T12:02:14Z
| 39,425,946 |
<p>The problem is that you are modifying the list <code>numbers</code> while you are iterating over it. This results in you removing less numbers than what you expect.</p>
<p>You should iterate over a copy of it:</p>
<pre><code>for i in list(numbers):
for j in range(1,i):
if is_abun(j) and is_abun(i-j):
numbers.remove(i)
break
</code></pre>
<p>To understand what's happening consider this:</p>
<pre><code>>>> numbers = list(range(10))
>>> for i in numbers:
... if i%2 == 0:
... numbers.remove(i)
... print(i)
...
0
2
4
6
8
</code></pre>
<p>As you can see the <code>for</code> loop only iterates over even numbers. That's because the <code>for</code> loop above is <em>roughly</em> equivalent to the following:</p>
<pre><code>i = 0
while i < len(numbers):
number = numbers[i]
if number % 2 == 0:
numbers.remove(number)
print(number)
i += 1
</code></pre>
<p>So the first time you have <code>i = 0</code> and thus <code>number = 0</code>, you remove the <code>0</code> from <code>numbers</code> so now you have <code>numbers = [1,2,3,4,..., 9]</code>. Note how the value <code>1</code> ended up in position <code>0</code>, so the next iteration we have <code>i = 1</code> and <code>numbers[1] == [1,2,3,4,...,9][1] == 2</code> so we have skipped the number <code>1</code>!</p>
<p>Everytime you remove a number the list is modified and if this modification leads to the items being shifted to the left you are effectively skipping them. That's why you want to iterate over a <em>copy</em> of the list: in this way the modifications to the original list do not affect the numbers "yielded" during iteration..</p>
| 3 |
2016-09-10T12:10:48Z
|
[
"python"
] |
How to fork a python script in different terminal
| 39,425,940 |
<p>I want to fork a new process in a script, but how to interactive with the subprocess in a new terminal?
For example:</p>
<pre><code>#python
a='a'
b='b'
if os.fork():
print a
a = input('a?')
print 'a:',a
else:
print b
b = input('b?')
print 'b:',b
</code></pre>
<p>The script should print a/b and ask for a new value. But these two process share a same terminal, and that makes it confused.</p>
<p>How can I open a new terminal and let the subprocess run in the new terminal?</p>
<hr>
<p>I've thought about to use <code>subprocess.Popen('gnome-terminal',shell=True)</code> and communicate with the new terminal. But <code>gnome-terminal</code> will open bash on default, how can i open a terminal only for input and output?</p>
| 0 |
2016-09-10T12:10:00Z
| 39,426,304 |
<p>Its probably bad practice to open a new terminal like that from a command line application, but <code>gnome-terminal</code> has an <code>-e</code> flag. E.g. <code>gnome-terminal -e python</code> will open a python interpreter.</p>
| 0 |
2016-09-10T12:58:14Z
|
[
"python",
"linux",
"bash",
"shell",
"subprocess"
] |
How to fork a python script in different terminal
| 39,425,940 |
<p>I want to fork a new process in a script, but how to interactive with the subprocess in a new terminal?
For example:</p>
<pre><code>#python
a='a'
b='b'
if os.fork():
print a
a = input('a?')
print 'a:',a
else:
print b
b = input('b?')
print 'b:',b
</code></pre>
<p>The script should print a/b and ask for a new value. But these two process share a same terminal, and that makes it confused.</p>
<p>How can I open a new terminal and let the subprocess run in the new terminal?</p>
<hr>
<p>I've thought about to use <code>subprocess.Popen('gnome-terminal',shell=True)</code> and communicate with the new terminal. But <code>gnome-terminal</code> will open bash on default, how can i open a terminal only for input and output?</p>
| 0 |
2016-09-10T12:10:00Z
| 39,427,040 |
<h2>I finally implement it in a(maybe ugly) way.</h2>
<p>Inspired by <a href="http://unix.stackexchange.com/questions/256480/how-do-i-run-a-command-in-a-new-terminal-window-in-the-same-process-as-the-origi">http://unix.stackexchange.com/questions/256480/how-do-i-run-a-command-in-a-new-terminal-window-in-the-same-process-as-the-origi</a>
I'v solve most of the problem:</p>
<pre><code>#python
import sys,os,subprocess
a='a'
b='b'
if os.fork():
print a
a = raw_input('a?')
print 'a:',a
else:
p = subprocess.Popen("xterm -e 'tty >&3; exec sleep 99999999' 3>&1",
shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
tty_path = p.stdout.readline().strip()
tty = open(tty_path,'r+')
sys.stdout=tty
sys.stderr=tty
sys.stdin=tty
print b
b = raw_input('b?')
print 'b:',b
</code></pre>
<p>The only problem is that the prompt: 'b?' will still show in the former terminal. So the new question is: where does prompt belongs?</p>
<hr>
<p>Despite that, another way to solve this prompt problem:</p>
<pre><code>_r_i = raw_input
def raw_input(prompt):
print prompt,
return _r_i('')
</code></pre>
<hr>
<p>I'm a little strange and, mad... I know...</p>
| 0 |
2016-09-10T14:30:26Z
|
[
"python",
"linux",
"bash",
"shell",
"subprocess"
] |
Count up and down from a given letter
| 39,425,966 |
<p>I need to write a function "alphabet" that takes a string (n), and counts up and then down in the alphabet. I tried to solve it, but I could only write the code where it counts down and then up in integers. Somehow, these integers are supposed to represent a letter. I know that I should use char() and ord(), but I don't know how. Here is what I've done so far:</p>
<pre><code> letter= ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''t''u''v''w''x''y''z']
numbers = ['1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24']
index=0
def alphabet('n')
while index < len(letter):
print(count[index], end=' ')
for n in range(0,count[index]):
print(line[index]-numbers,end='')
print()
index = index + 1
for n in range(0,count[index]):
print(line[index]+1,end='')
print()
index = index + numbers
</code></pre>
<p>I am aware that this is wrong, but a little guidance would be nice :) </p>
| -1 |
2016-09-10T12:13:38Z
| 39,426,009 |
<p>I think ord() gives back the ascii code in consecutive order, for instance ord('a') gives 97 and ord('b') 98 and so on, i would work on converting one from another and adding +1 in each loop</p>
| 1 |
2016-09-10T12:19:16Z
|
[
"python"
] |
python list columns split
| 39,426,003 |
<p>Could anyone help me please? It is complicated question but i will try explain it. I need interpolate two values Depths(Z) to Speed(v) for all data </p>
<pre><code>x= [55,55,55,,44,44,44,,33,33,33,] (coordinates)
z =[10,5,0,10,7,0,10,9,0] (depths)
v= [20,21,22=,23,24,25,26,27,28] (speed)
</code></pre>
<p>And result </p>
<pre><code>DEPTHS SPEED(55) SPEED(44) SPEED(33)
10 20 23 26
6 21.5(interp) 24.5(interp) 27.5 (interp)
0 22 25 28
</code></pre>
<p>What I did:</p>
<pre><code>import numpy as np
X_list=[55,55,55,44,44,44,33,33,33]
Z_list=[10,5,0,10,7,0 10,9,0]
V_list=[20,21,22,23,24,25,26,27,28]
x = np.linspace(min(Z_list),max(Z_list),num = 3) #(Find min and max values in all list, and put step
d=np.interp(x, Z_list, V_list) # interpolation for interesting depths
zipped = list(zip(x,d))
print (*zipped, sep="\n")
</code></pre>
<p>And actually I got information from first cordinate</p>
<pre><code> DEPTHS SPEED(55) SPEED (44) SPEED(33)
(10 20) ? ?
(6 21.5) ? ?
(0 22) ? ?
</code></pre>
<p>But I dont't know how to get other values from another cordinates.
I haven't got any idea how link coordinates to speeds and depths and put it to columns. </p>
| 1 |
2016-09-10T12:18:38Z
| 39,426,830 |
<p>One possibility is to create a dictionary that maps each X coord to the list of tuples with that X coord:</p>
<pre><code>>>> tupus = [ (1,0,1), (1,13,4), (2,11,2), (2,14,5) ]
>>> from collections import defaultdict
>>> tupudict = defaultdict( lambda: [] ) # default val for a key is empty list
>>> for tupu in tupus: tupudict[tupu[0]].append(tupu)
...
>>> tupudict[1]
[(1, 0, 1), (1, 13, 4)]
>>> tupudict[2]
[(2, 11, 2), (2, 14, 5)]
</code></pre>
<p>Then you process the dict key by key, or dump the values into a list of lists of tuples, or whatever.</p>
<p>Edited to add an answer to your comment about just splitting a list:</p>
<pre><code>>>> from collections import defaultdict
>>> mylist = [11,11,11,11,12,12,15,15,15,15,15,15,20,20,20]
>>> uniquedict = defaultdict( lambda: [] )
>>> for n in mylist: uniquedict[n].append(n)
...
>>> uniquedict
defaultdict(<function <lambda> at 0x00000000033092E8>, {20: [20, 20, 20], 11: [11, 11, 11, 11], 12: [12, 12], 15: [15, 15, 15, 15, 15, 15]})
>>> uniquedict[11]
[11, 11, 11, 11]
</code></pre>
<p>Note that, for every n in your input list, uniquedict[n] is now a list of all the n's from your input list.</p>
| 1 |
2016-09-10T14:04:22Z
|
[
"python",
"list",
"listview",
"interpolation"
] |
Tornado multiple processes: create multiple MySQL connections
| 39,426,030 |
<p>I'm running a Tornado HTTPS server across multiple processes using the first method described here <a href="http://www.tornadoweb.org/en/stable/guide/running.html" rel="nofollow">http://www.tornadoweb.org/en/stable/guide/running.html</a> (server.start(n))</p>
<p>The server is connected to a local MySQL instance and I would like to have a independent MySQL connection per Tornado process.</p>
<p>However, right now I only have one MySQL connection according to the output of SHOW PROCESSLIST. I guess this happens because I establish the connection before calling server.start(n) and IOLoop.current().start() right?</p>
<p>What I don't really understand is whether the processes created after calling server.start(n) share some data (for instance, global variables within the same module) or are totally independent.</p>
<p>Should I establish the connection after calling server.start(n) ? Or after calling IOLoop.current().start() ? If I do so, will I have one MySQL connection per Tornado process?</p>
<p>Thanks</p>
| 0 |
2016-09-10T12:21:59Z
| 39,432,345 |
<p>Each child process gets a copy of the variables that existed in the parent process when <code>start(n)</code> was called. For things like connections, this will usually cause problems. When using multi-process mode, it's important to do as little as possible before starting the child processes, so don't create the mysql connections until after <code>start(n)</code> (but before <code>IOLoop.start()</code>; <code>IOLoop.start()</code> doesn't return until the server is stopped). </p>
| 1 |
2016-09-11T02:37:39Z
|
[
"python",
"mysql",
"multiprocessing",
"tornado",
"multiprocess"
] |
Python read particular cell value in excel
| 39,426,107 |
<p>I have an exel file named "123.csv" that is the output i get when running a PROM functionality, consisting of two columns "case" and "event". I want to modify this output by grouping events based on case. More specifically i want to write a python script that will group events that belong to the same case to be merged in a new cell, no mate what the length of my initial matrix is.Could anyone please give me some idea?
<a href="http://i.stack.imgur.com/ln2QK.png" rel="nofollow">curent and desiret output</a></p>
<pre><code>import csv
with open('123.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print ', '.join(row).replace(',',' ').replace('"',' ')
</code></pre>
<p>this is a part i wrote, but it only reads the file and removes some punctiation</p>
| 2 |
2016-09-10T12:31:15Z
| 39,426,204 |
<p>It's easy to do with simple csv & defaultdict (python 3)</p>
<p>Your input is like</p>
<pre><code>case,event
101,A
101,X
101,Y
102,B
102,C
103,Z
</code></pre>
<p>code:</p>
<pre><code>import collections
with open("csv.csv") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr) # read title
for r in cr:
d[r[0]].append(r[1]) # fill dict
with open("csv2.csv","w",newline="") as f:
cr = csv.writer(f,delimiter=",")
cr.writerow(header) # title
for k,v in d.items():
cr.writerow([k,",".join(v)])
</code></pre>
<p>output</p>
<pre><code>case,event
103,Z
101,"A,X,Y"
102,"B,C"
</code></pre>
| 0 |
2016-09-10T12:44:17Z
|
[
"python",
"csv"
] |
Python read particular cell value in excel
| 39,426,107 |
<p>I have an exel file named "123.csv" that is the output i get when running a PROM functionality, consisting of two columns "case" and "event". I want to modify this output by grouping events based on case. More specifically i want to write a python script that will group events that belong to the same case to be merged in a new cell, no mate what the length of my initial matrix is.Could anyone please give me some idea?
<a href="http://i.stack.imgur.com/ln2QK.png" rel="nofollow">curent and desiret output</a></p>
<pre><code>import csv
with open('123.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print ', '.join(row).replace(',',' ').replace('"',' ')
</code></pre>
<p>this is a part i wrote, but it only reads the file and removes some punctiation</p>
| 2 |
2016-09-10T12:31:15Z
| 39,426,245 |
<p>You can use groupby from itertools to do this for you. Example of this:</p>
<pre><code>from itertools import groupby
current = [(101, 'A'), (101, 'B'), (101, 'Y'), (102, 'C'), (102, 'D'), (102, 'U')]
desired = []
for key, group in groupby(current, lambda x: x[0]):
lst = [element[1] for element in group]
grouped = (key, lst)
desired.append(grouped)
print(desired)
</code></pre>
<p>Basically you give groupby the array of what you have now and an lambda function that takes the first element of the array (the array need to be sorted). Groupby will use first element to group elements by it.</p>
| 0 |
2016-09-10T12:50:44Z
|
[
"python",
"csv"
] |
Print only vowels in a string
| 39,426,149 |
<p>I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)</p>
<p>For now I've got this ;</p>
<pre><code>sentence = input('Enter your sentence: ' )
if 'a,e,i,o,u' in sentence:
print(???)
else:
print("empty")
</code></pre>
| 2 |
2016-09-10T12:36:41Z
| 39,426,166 |
<p>Something like this?</p>
<pre><code>sentence = input('Enter your sentence: ' )
for letter in sentence:
if letter in 'aeiou':
print(letter)
</code></pre>
| 2 |
2016-09-10T12:39:29Z
|
[
"python",
"string",
"python-3.x",
"printing"
] |
Print only vowels in a string
| 39,426,149 |
<p>I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)</p>
<p>For now I've got this ;</p>
<pre><code>sentence = input('Enter your sentence: ' )
if 'a,e,i,o,u' in sentence:
print(???)
else:
print("empty")
</code></pre>
| 2 |
2016-09-10T12:36:41Z
| 39,426,193 |
<p>Supply provide an a list comprehension to <code>print</code> and unpack it:</p>
<pre><code>>>> s = "Hey there, everything allright?" # received from input
>>> print(*[i for i in s if i in 'aeiou'])
e e e e e i a i
</code></pre>
<p>This makes a list of all vowels and supplies it as positional arguments to the print call by unpacking <code>*</code>.</p>
<p>If you need distinct vowels, just supply a set comprehension:</p>
<pre><code>print(*{i for i in s if i in 'aeiou'}) # prints i e a
</code></pre>
<p>If you need to add the else clause that prints, pre-construct the list and act on it according to if it's empty or not:</p>
<pre><code>r = [i for i in s if i in 'aeiou']
if r:
print(*r)
else:
print("empty")
</code></pre>
| 0 |
2016-09-10T12:42:41Z
|
[
"python",
"string",
"python-3.x",
"printing"
] |
Print only vowels in a string
| 39,426,149 |
<p>I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)</p>
<p>For now I've got this ;</p>
<pre><code>sentence = input('Enter your sentence: ' )
if 'a,e,i,o,u' in sentence:
print(???)
else:
print("empty")
</code></pre>
| 2 |
2016-09-10T12:36:41Z
| 39,426,290 |
<p>The two answers are good if you want to print <em>all</em> the occurrences of the vowels in the sentence -- so "Hello World" would print 'o' twice, etc.</p>
<p>If you only care about <em>distinct</em> vowels, you can instead loop over the vowels. In a sense, you're flipping the code suggested by the other answers:</p>
<pre><code>sentence = input('Enter your sentence: ')
for vowel in 'aeiou':
if vowel in sentence:
print(vowel)
</code></pre>
<p>So, "Hey there, everything alright?" would print</p>
<pre><code>a e i
</code></pre>
<p>As opposed to:</p>
<pre><code>e e e e e i a i
</code></pre>
<p>And the same idea, but following Jim's method of unpacking a list comprehension to <code>print</code>:</p>
<pre><code>print(*[v for v in 'aeiou' if v in sentence])
</code></pre>
| 1 |
2016-09-10T12:56:51Z
|
[
"python",
"string",
"python-3.x",
"printing"
] |
Print only vowels in a string
| 39,426,149 |
<p>I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)</p>
<p>For now I've got this ;</p>
<pre><code>sentence = input('Enter your sentence: ' )
if 'a,e,i,o,u' in sentence:
print(???)
else:
print("empty")
</code></pre>
| 2 |
2016-09-10T12:36:41Z
| 39,426,389 |
<p>You could always use RegEx:</p>
<pre><code>import re
sentence = input("Enter your sentence: ")
vowels = re.findall("[aeiou]",sentence.lower())
if len(vowels) == 0:
for i in vowels:
print(i)
else:
print("Empty")
</code></pre>
| 0 |
2016-09-10T13:10:09Z
|
[
"python",
"string",
"python-3.x",
"printing"
] |
Python easier way to insert new items into XML sub sub elements using ElementTree
| 39,426,162 |
<p>I am editing a config file and would like to add new sub elements into the structure. The problem I am having is that in the config file the sub elements have the same name and I have not found a way to find the index the insert location with a .find command. An example of the config file is here:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ConfigurationFile>
<Configuration ItemName="Parent1">
<Category ItemName="Parent2">
<Category ItemName="Parent3">
<Category ItemName="ChildLevelToAdd">
<Option ItemName="x" ValueType="6">5</Option>
<Option ItemName="z" ValueType="6">0</Option>
<Category ItemName="ChildCategory">
<Option ItemName="a" ValueType="1"></Option>
<Option ItemName="b" ValueType="2"></Option>
<Option ItemName="c" ValueType="3">
</Option>
</Category>
</Category>
</Category>
</Category>
</code></pre>
<p>
</p>
<p>I am trying to add a new "ChildToAdd" category and everything that falls below it. </p>
<p>I have tried the following code to index, but it seems it is only able to locate first child elements:</p>
<pre><code>a = root.find('Configuration') #It is only possible to find sub-elements of the root
b = root.find('Category') #These generate a none type
</code></pre>
<p>The best way I have found to insert the new category element is using:</p>
<pre><code>root[0][0][0].insert(0,ET.Element("Category", ItemName = "NewChild"))
</code></pre>
<p>And then when I want to add options to this newly created category I use: </p>
<pre><code>root[0][0][0][0].insert(0,ET.Element("NewOption", ItemName = "NewVal", ValueType ="NewType"))
</code></pre>
<p>This seems like a very untidy way to do this. I am wondering if there are any cleaner methods to find and specify the insertion point for the new subsubelement (category) and its future sub-elements (options)? </p>
| 1 |
2016-09-10T12:39:12Z
| 39,426,659 |
<p>Use XPath expression in the form of <strong><code>.//element_name</code></strong> to find element anywhere within context node (the root element in this case). For example, the following should return first instance of <code><Category></code> element, anywhere within <code>root</code> :</p>
<pre><code>root.find('.//Category')
</code></pre>
<p>You can also find element by its attribute value using XPath. For example, the following should return <code><Category></code> element where <code>ItemName</code> attribute value equals "Parent3" :</p>
<pre><code>root.find('.//Category[@ItemName="Parent3"]')
</code></pre>
<p>ElementTree supports some other XPath syntax as documented in <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#elementtree-xpath" rel="nofollow">here</a>.</p>
<hr>
<p>I'd also suggest to store your new element in a variable so that you can add child element to it later without having to query the XML again :</p>
<pre><code>c = ET.Element("Category", ItemName = "NewChild")
c.insert(0,ET.Element("NewOption", ItemName = "NewVal", ValueType ="NewType"))
p = root.find('.//Category[@ItemName="Parent3"]')
p.insert(0, c)
</code></pre>
| 1 |
2016-09-10T13:41:59Z
|
[
"python",
"xml-parsing",
"elementtree"
] |
Pandas groupby method
| 39,426,428 |
<p>l have a 41 year dataset and l would like to do some statistical calculations by using a Pandas module. However, l have a lack of Pandas knowledge.
here is an example csv file dataset:</p>
<pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6
1.01.1979 1 1 1979 0.431 2.167 9.375 0.431 2.167 9.375
2.01.1979 2 1 1979 1.216 2.583 9.162 1.216 2.583 9.162
3.01.1979 3 1 1979 4.041 9.373 23.169 4.041 9.373 23.169
4.01.1979 4 1 1979 1.799 3.866 8.286 1.799 3.866 8.286
5.01.1979 5 1 1979 0.003 0.051 0.342 0.003 0.051 0.342
6.01.1979 6 1 1979 2.345 3.777 7.483 2.345 3.777 7.483
7.01.1979 7 1 1979 0.017 0.031 0.173 0.017 0.031 0.173
8.01.1979 8 1 1979 5.061 5.189 43.313 5.061 5.189 43.313
</code></pre>
<p>here is my code:</p>
<pre><code>import numpy as np
import pandas as pd
import csv
filename="output813b.csv"
cols = ["date","year","month","day" ,"pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"]
data1=pd.read_csv(filename,sep=',', header=None,names=cols,usecols=range(1,9))
colmns_needed=["month" ,"pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"]
data2=pd.read_csv(filename,sep=',', header=None,names=colmns_needed)
mm=data2.groupby("month")
print(mm.sum())
print('\n')
</code></pre>
<p>but values under columns of PCP seems stored as string.
here is example output for <code>pcp1</code>:</p>
<pre><code>Month pcp1
1 0.4310.4720000.91800000.01011.63904.65900.5780...
10 00.1500000000.027000.02400.1630.9610000000.017...
11 00.4940000000000.0480.003012.26200000003.612.9...
12 0.1890.0760.47000000000.08800.1080.26107.15000...
13 00.06500.1060.00700000050.6207.1510.0860.1487....
14 0000.64200000000.017025.5910.93400.04500000000...
15 0.742000.0720000000000.32500000000002.9877.512...
16 6.43900000000000.38103.986000000000033.5534.76...
17 0.0890000.2750000.555001.9230.562.9130.1360000...
18 3.28200000000.024000.656002.1750000000008.2434...
19 1.28200000000000000.0070000000007.0383.0450.17...
2 1.2160.1050000000010.4690.2092.9700.0415.6062....
20 00.4960.05100000000000.3550.1582.8530.04600000...
21 00000000000002.69903.5190.13000002.830.5151.09...
22 0000000007.19600000000000001.4421.76500.04500....
23 0000000008.168000.02100000000000.1083.8760.968...
</code></pre>
<p>how can l solve that problem? </p>
| 3 |
2016-09-10T13:14:38Z
| 39,426,661 |
<p>Do not specify <code>header=None</code> in your <code>read_csv</code> calls. You are telling the function that there is no header row in the data, when according to the sample data you posted above, the first row of the file is a header. So it treats that first header row as data, thus mixing values like <code>pcp1</code> and <code>0.431</code>, and causing all the columns to be interpreted as strings. </p>
| 2 |
2016-09-10T13:42:02Z
|
[
"python",
"pandas"
] |
Can dask be used to groupby and recode out of core?
| 39,426,511 |
<p>I have 8GB csv files and 8GB of RAM. Each file has two strings per row in this form:</p>
<pre><code>a,c
c,a
f,g
a,c
c,a
b,f
c,a
</code></pre>
<p>For smaller files I remove duplicates counting how many copies of each row there were in the first two columns and then recode the strings to integers <a href="http://stackoverflow.com/a/39419342/2179021">as follows</a>:</p>
<pre><code>import pandas as pd
from sklearn.preprocessing import LabelEncoder
df = pd.read_csv("file.txt", header=None, prefix="ID_")
# Perform the groupby (before converting letters to digits).
df = df.groupby(['ID_0', 'ID_1']).size().rename('count').reset_index()
# Initialize the LabelEncoder.
le = LabelEncoder()
le.fit(df[['ID_0', 'ID_1']].values.flat)
# Convert to digits.
df[['ID_0', 'ID_1']] = df[['ID_0', 'ID_1']].apply(le.transform)
</code></pre>
<p>This gives:</p>
<pre><code> ID_0 ID_1 count
0 0 1 2
1 1 0 3
2 2 4 1
3 4 3 1
</code></pre>
<p>which is exactly what I need for this toy example.</p>
<p>For the larger file I can't take these steps because of lack of RAM. </p>
<p>I can imagine it is possible to combine unix sort and a bespoke python solution doing multiple passes over the data to process my data set. But someone suggested dask might be suitable. Having read the docs I am still not clear.</p>
<blockquote>
<p>Can dask be used to do this sort of out of core processing or is there some other out of core pandas solution?</p>
</blockquote>
| 1 |
2016-09-10T13:24:25Z
| 39,428,253 |
<p>Assuming that the grouped dataframe fits your memory, the change you would have to make to your code should be pretty minor. Here's my attempt:</p>
<pre><code>import pandas as pd
from dask import dataframe as dd
from sklearn.preprocessing import LabelEncoder
# import the data as dask dataframe, 100mb per partition
# note, that at this point no data is read yet, dask will read the files
# once compute or get is called.
df = dd.read_csv("file.txt", header=None, prefix="ID_", blocksize=100000000)
# Perform the groupby (before converting letters to digits).
# For better understanding, let's split this into two parts:
# (i) define the groupby operation on the dask dataframe and call compute()
# (ii) compute returns a pandas dataframe, which we can then use for further analysis
pandas_df = df.groupby(['ID_0', 'ID_1']).apply(lambda x: len(x), columns=0).compute()
pandas_df = pandas_df.rename('count').reset_index()
# Initialize the LabelEncoder.
le = LabelEncoder()
le.fit(pandas_df[['ID_0', 'ID_1']].values.flat)
# Convert to digits.
pandas_df[['ID_0', 'ID_1']] = pandas_df[['ID_0', 'ID_1']].apply(le.transform)
</code></pre>
<p>One possible solution in pandas would be to read the files in chunks (passing the chunksize argument to read_csv), running the groupby on individual chunks and combining the results.</p>
<hr>
<p>Here's how you can solve the problem in pure python:</p>
<pre><code>counts = {}
with open('data') as fp:
for line in fp:
id1, id2 = line.rstrip().split(',')
counts[(id1, id2)] = 1 + counts.get((id1, id2), 0)
df = pd.DataFrame(data=[(k[0], k[1], v) for k, v in counts.items()],
columns=['ID_0', 'ID_1', 'count'])
# apply label encoding etc.
le = LabelEncoder()
le.fit(df[['ID_0', 'ID_1']].values.flat)
# Convert to digits.
df[['ID_0', 'ID_1']] = df[['ID_0', 'ID_1']].apply(le.transform)
</code></pre>
| 2 |
2016-09-10T16:36:23Z
|
[
"python",
"pandas",
"dask"
] |
Python: Json dumps escape quote
| 39,426,532 |
<p>There is a POST request which works perfectly when I pass the data as below:</p>
<pre><code>url = 'https://www.nnnow.com/api/product/details'
requests.post(url, data="{\"styleId\":\"BMHSUR2HTS\"}", headers=headers)
</code></pre>
<p>But when I use <code>json.dumps()</code> on a dictionary and send the response, I do not get the response (response code 504), using <code>headers={'Content-Type': 'application/json'}</code> . Have also tried json parameter of Post requests.</p>
<pre><code>requests.post(url, data=json.dumps({"styleId":"BMHSUR2HTS"}), headers={'content-type': 'application/json'})
</code></pre>
<p>Now, the data returned by <code>json.dumps({"styleId":"BMHSUR2HTS"})</code> and
<code>"{\"styleId\":\"BMHSUR2HTS\"}"</code> is not the same.</p>
<p><code>json.dumps({"styleId":"BMHSUR2HTS"}) == "{\"styleId\":\"BMHSUR2HTS\"}"</code> gives <code>False</code> even though a print on both shows a similar string.</p>
<p>How can I get the same format as <code>"{\"styleId\":\"BMHSUR2HTS\"}"</code> from a dictionary <code>{"styleId":"BMHSUR2HTS"}</code> ?</p>
| 1 |
2016-09-10T13:26:46Z
| 39,428,488 |
<p>If you print the <code>json.dumps({"styleId":"BMHSUR2HTS"})</code> it'll happen 2 things:
1. your output is a string (just try <code>type(json.dumps({"styleId":"BMHSUR2HTS"}))</code>);
2. if you pay attention the output will add a space between the json name and value: '{"styleId": "BMHSURT2HTS"}'.</p>
<p>Not sure how do you want to handle this, and in your entry code, but there are 2 main options to workaround this issue:
1. Replace the space on json.dumps output: <code>json.dumps({"styleId":"BMHSUR2HTS"}).replace(': ', ':')</code>
2. Convert all to json by using eval(): <code>eval(json.dumps({"styleId":"BMHSUR2HTS"}))</code> and <code>eval(YOUR_JSON_STRING)</code></p>
<p>I hope this helps you.</p>
| 0 |
2016-09-10T17:00:18Z
|
[
"python",
"json"
] |
Iterating over multiIndex dataframe
| 39,426,564 |
<p>I have a data frame as shown below
<img src="http://i.stack.imgur.com/H6Sh0.png" alt="dataframe"></p>
<p>I have a problem in iterating over the rows. for every row fetched I want to return the key value. For example in the second row for <strong>2016-08-31 00:00:01</strong> entry df1 & df3 has compass value 4.0 so I wanted to return the keys which has the same compass value which is df1 & df3 in this case
I Have been iterating rows using </p>
<pre><code>for index,row in df.iterrows():
</code></pre>
| 0 |
2016-09-10T13:30:25Z
| 39,427,383 |
<p><strong>Update</strong></p>
<p>Okay so now I understand your question better this will work for you.
First change the shape of your dataframe with</p>
<pre><code>dfs = df.stack().swaplevel(axis=0)
</code></pre>
<p>This will make your dataframe look like:</p>
<p><a href="http://i.stack.imgur.com/UaOj7.png" rel="nofollow"><img src="http://i.stack.imgur.com/UaOj7.png" alt="enter image description here"></a></p>
<p>Then you can iterate the rows like before and extract the information you want. I'm just using print statements for everything, but you can put this in some more appropriate data structure.</p>
<pre><code>for index, row in dfs.iterrows():
dup_filter = row.duplicated(keep=False)
dfss = row_tuple[dup_filter].index.values
print("Attribute:", index[0])
print("Index:", index[1])
print("Matches:", dfss, "\n")
</code></pre>
<p>which will print out something like</p>
<pre><code>.....
Attribute: compass
Index: 5
Matches: ['df1' 'df3']
Attribute: gyro
Index: 5
Matches: ['df1' 'df3']
Attribute: accel
Index: 6
Matches: ['df1' 'df3']
....
</code></pre>
<p>You could also do it one attribute at a time by </p>
<p><code>dfs_compass = df.stack().swaplevel(axis=0).loc['compass']</code></p>
<p>and iterate through the rows with just the index.</p>
<p><strong>Old</strong></p>
<p>If I understand your question correctly, i.e. you want to return the indexes of rows which have matching values on the second level of your columns, i.e. ('compass', 'accel', 'gyro'). The following will work.</p>
<pre><code>compass_match_indexes = []
for index, row in df.iterrows():
match_filter = row[:, 'compass'].duplicated()
if len(row[:, 'compass'][match_filter] > 0)
compass_match_indexes.append(index)
</code></pre>
<p>You can use select your dataframe with that list like <code>df.loc[compass_match_indexes]</code></p>
<p>--</p>
<p>Another approach, you could get the transform of your DataFrame with df.T and then use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow">duplicated</a> function.</p>
| 1 |
2016-09-10T15:07:43Z
|
[
"python",
"pandas",
"dataframe",
"multi-index"
] |
what kind of table widget module i should use for python 3x
| 39,426,619 |
<p>I was trying to use <code>tkintertable</code> for Python 3.5.2 but I got an error message at the console saying: </p>
<pre><code>File "C:\Users\issba\AppData\Local\Programs\Python\Python35-32\lib\site-packages\tkintertable\__init__.py", line 24, in <module>
from Tables import *
ImportError: No module named 'Tables'
</code></pre>
<p>Then I found out it's out of date using one of the comments <a href="http://stackoverflow.com/questions/30650901/no-module-named-tkinter-when-using-tkintertables">here</a>. So I looked on Google yesterday till I got <code>tktable</code> but I could not find the supported releases, so my question is: <br>
Is it true that <code>tkintertable</code> is no longer available for Python 3x and what is a replacement for this issue? Please try to provide a link for setup. </p>
| 0 |
2016-09-10T13:36:53Z
| 39,427,605 |
<p><a href="https://github.com/dmnfarrell/tkintertable" rel="nofollow">This</a> is the official development site of <code>tkintertable</code>. At the end of the <a href="https://github.com/dmnfarrell/tkintertable#about" rel="nofollow">about section</a> it says: </p>
<blockquote>
<p><b>This library is currently for Python 2 only.</b></p>
</blockquote>
<p>I think it clears the question on whether it is available for Python 3 or not.<br/></p>
<p>And for your second question:<br/></p>
<blockquote>
<p>what is a replacement for this issue?</p>
</blockquote>
<p><a href="http://stackoverflow.com/questions/22456445/how-to-imitate-this-table-using-tkinter">This</a> can be useful.</p>
| 0 |
2016-09-10T15:31:20Z
|
[
"python",
"tkinter"
] |
How can I implement x[i][j] = y[i+j] efficiently in numpy?
| 39,426,690 |
<p>Let <strong>x</strong> be a matrix with a shape of (A,B) and <strong>y</strong> be an array with a size of A+B-1.</p>
<pre><code>for i in range(A):
for j in range(B):
x[i][j] = y[i+j]
</code></pre>
<p>How can I implement equivalent code efficiently using functions in numpy?</p>
| 4 |
2016-09-10T13:45:12Z
| 39,426,755 |
<p><strong>Approach #1</strong> Using <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.hankel.html" rel="nofollow"><code>Scipy's hankel</code></a> -</p>
<pre><code>from scipy.linalg import hankel
x = hankel(y[:A],y[A-1:]
</code></pre>
<p><strong>Approach #2</strong> Using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> -</p>
<pre><code>x = y[np.arange(A)[:,None] + np.arange(B)]
</code></pre>
<p><strong>Approach #3</strong> Using <code>NumPy strides technique</code> -</p>
<pre><code>n = y.strides[0]
x = np.lib.stride_tricks.as_strided(y, shape=(A,B), strides=(n,n))
</code></pre>
<hr>
<p>Runtime test -</p>
<pre><code>In [93]: def original_app(y,A,B):
...: x = np.zeros((A,B))
...: for i in range(A):
...: for j in range(B):
...: x[i][j] = y[i+j]
...: return x
...:
...: def strided_method(y,A,B):
...: n = y.strides[0]
...: return np.lib.stride_tricks.as_strided(y, shape=(A,B), strides=(n,n))
...:
In [94]: # Inputs
...: A,B = 100,100
...: y = np.random.rand(A+B-1)
...:
In [95]: np.allclose(original_app(y,A,B),hankel(y[:A],y[A-1:]))
Out[95]: True
In [96]: np.allclose(original_app(y,A,B),y[np.arange(A)[:,None] + np.arange(B)])
Out[96]: True
In [97]: np.allclose(original_app(y,A,B),strided_method(y,A,B))
Out[97]: True
In [98]: %timeit original_app(y,A,B)
100 loops, best of 3: 5.29 ms per loop
In [99]: %timeit hankel(y[:A],y[A-1:])
10000 loops, best of 3: 114 µs per loop
In [100]: %timeit y[np.arange(A)[:,None] + np.arange(B)]
10000 loops, best of 3: 60.5 µs per loop
In [101]: %timeit strided_method(y,A,B)
10000 loops, best of 3: 22.4 µs per loop
</code></pre>
<p>Additional ways based on <code>strides</code> -</p>
<p>It seems <code>strides</code> technique has been used at few places : <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.image.extract_patches_2d.html" rel="nofollow"><code>extract_patches</code></a> and <a href="http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows" rel="nofollow"><code>view_as_windows</code></a> that are being used in such image-processing based modules. So, with those, we have two more approaches -</p>
<pre><code>from skimage.util.shape import view_as_windows
from sklearn.feature_extraction.image import extract_patches
x = extract_patches(y,(B))
x = view_as_windows(y,(B))
In [151]: np.allclose(original_app(y,A,B),extract_patches(y,(B)))
Out[151]: True
In [152]: np.allclose(original_app(y,A,B),view_as_windows(y,(B)))
Out[152]: True
In [153]: %timeit extract_patches(y,(B))
10000 loops, best of 3: 62.4 µs per loop
In [154]: %timeit view_as_windows(y,(B))
10000 loops, best of 3: 108 µs per loop
</code></pre>
| 7 |
2016-09-10T13:53:26Z
|
[
"python",
"numpy"
] |
Python - How to shorten code
| 39,426,786 |
<p>I've developed a Python program that I need advice on simplifying.</p>
<p>This is part of my code:</p>
<pre><code>import wx
import sys
import socket
def error_handler(c):
if c == 'canceled':
sys.exit('User canceled configuration.')
elif c == 'empty':
sys.exit('Empty value.')
def hostname():
dlg = wx.TextEntryDialog(None,
'What is your default Hostname?',
'Hostname',
socket.gethostname())
if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
if dlg.GetValue() == "":
error_handler('empty')
else:
HOSTNAME = dlg.GetValue()
return HOSTNAME
def random_hostname():
dlg = wx.SingleChoiceDialog(None,
'Do you want to randomize your Hostname',
'Randomize',
['Yes', 'No', 'Disable'],
wx.CHOICEDLG_STYLE)
if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
RANDOM_HOSTNAME = dlg.GetStringSelection()
return RANDOM_HOSTNAME
def nameserver():
dlg = wx.TextEntryDialog(None,
'Nameserver IP\n',
'Nameserver',
'127.0.0.1')
if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
if dlg.GetValue() == "":
error_handler('empty')
else:
NAMESERVER = dlg.GetValue()
return NAMESERVER
def main():
app = wx.App()
print 'HOSTNAME =', hostname()
print 'RANDOM_HOSTNAME =', random_hostname()
print 'NAMESERVER =', nameserver()
app.MainLoop()
if __name__ == '__main__':
main()
</code></pre>
<p>In this code I make function for Hostname, Random hostname and nameserver, but in all 3 function I have to repeat almost same code:</p>
<pre><code>if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
if dlg.GetValue() == "":
error_handler('empty')
else:
HOSTNAME = dlg.GetValue()
return HOSTNAME
</code></pre>
<p>But I want to make more than 20 functions for checking some values.
Is there (and I know that there is) some better trick to shorten every function?</p>
<p>I want something like this:</p>
<pre><code>import wx
import sys
import socket
def error_handler(c):
if c == 'canceled':
sys.exit('User canceled configuration.')
elif c == 'empty':
sys.exit('Empty value.')
else
return dialog value
def hostname():
dlg = wx.TextEntryDialog(None,
'What is your default Hostname?',
'Hostname',
socket.gethostname())
error_handler(dlg)
def random_hostname():
dlg = wx.SingleChoiceDialog(None,
'Do you want to randomize your Hostname',
'Randomize',
['Yes', 'No', 'Disable'],
wx.CHOICEDLG_STYLE)
error_handler(dlg)
def nameserver():
dlg = wx.TextEntryDialog(None,
'Nameserver IP\n',
'Nameserver',
'127.0.0.1')
error_handler(dlg)
def main():
app = wx.App()
print 'HOSTNAME =', hostname()
print 'RANDOM_HOSTNAME =', random_hostname()
print 'NAMESERVER =', nameserver()
app.MainLoop()
if __name__ == '__main__':
main()
</code></pre>
<p>I wish to thank everybody who will help me with this.</p>
| -1 |
2016-09-10T13:57:29Z
| 39,426,832 |
<p>It looks you already know the answer with creating another function, <code>error_handler</code> to do the repeated work! You could wrap your error handler in a <a href="https://docs.python.org/2/tutorial/errors.html#handling-exceptions" rel="nofollow">try/except</a> block that would look something along the lines of this:</p>
<pre><code>def hostname():
try:
dlg = wx.TextEntryDialog(None,
'What is your default Hostname?',
'Hostname',
socket.gethostname())
except:
error_handler(dlg)
</code></pre>
| 0 |
2016-09-10T14:04:35Z
|
[
"python",
"function"
] |
Python - How to shorten code
| 39,426,786 |
<p>I've developed a Python program that I need advice on simplifying.</p>
<p>This is part of my code:</p>
<pre><code>import wx
import sys
import socket
def error_handler(c):
if c == 'canceled':
sys.exit('User canceled configuration.')
elif c == 'empty':
sys.exit('Empty value.')
def hostname():
dlg = wx.TextEntryDialog(None,
'What is your default Hostname?',
'Hostname',
socket.gethostname())
if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
if dlg.GetValue() == "":
error_handler('empty')
else:
HOSTNAME = dlg.GetValue()
return HOSTNAME
def random_hostname():
dlg = wx.SingleChoiceDialog(None,
'Do you want to randomize your Hostname',
'Randomize',
['Yes', 'No', 'Disable'],
wx.CHOICEDLG_STYLE)
if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
RANDOM_HOSTNAME = dlg.GetStringSelection()
return RANDOM_HOSTNAME
def nameserver():
dlg = wx.TextEntryDialog(None,
'Nameserver IP\n',
'Nameserver',
'127.0.0.1')
if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
if dlg.GetValue() == "":
error_handler('empty')
else:
NAMESERVER = dlg.GetValue()
return NAMESERVER
def main():
app = wx.App()
print 'HOSTNAME =', hostname()
print 'RANDOM_HOSTNAME =', random_hostname()
print 'NAMESERVER =', nameserver()
app.MainLoop()
if __name__ == '__main__':
main()
</code></pre>
<p>In this code I make function for Hostname, Random hostname and nameserver, but in all 3 function I have to repeat almost same code:</p>
<pre><code>if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
if dlg.GetValue() == "":
error_handler('empty')
else:
HOSTNAME = dlg.GetValue()
return HOSTNAME
</code></pre>
<p>But I want to make more than 20 functions for checking some values.
Is there (and I know that there is) some better trick to shorten every function?</p>
<p>I want something like this:</p>
<pre><code>import wx
import sys
import socket
def error_handler(c):
if c == 'canceled':
sys.exit('User canceled configuration.')
elif c == 'empty':
sys.exit('Empty value.')
else
return dialog value
def hostname():
dlg = wx.TextEntryDialog(None,
'What is your default Hostname?',
'Hostname',
socket.gethostname())
error_handler(dlg)
def random_hostname():
dlg = wx.SingleChoiceDialog(None,
'Do you want to randomize your Hostname',
'Randomize',
['Yes', 'No', 'Disable'],
wx.CHOICEDLG_STYLE)
error_handler(dlg)
def nameserver():
dlg = wx.TextEntryDialog(None,
'Nameserver IP\n',
'Nameserver',
'127.0.0.1')
error_handler(dlg)
def main():
app = wx.App()
print 'HOSTNAME =', hostname()
print 'RANDOM_HOSTNAME =', random_hostname()
print 'NAMESERVER =', nameserver()
app.MainLoop()
if __name__ == '__main__':
main()
</code></pre>
<p>I wish to thank everybody who will help me with this.</p>
| -1 |
2016-09-10T13:57:29Z
| 39,426,893 |
<pre><code>def funct(dlg, wx, funcCheck):
if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
if dlg.GetValue() == "":
error_handler('empty')
else:
value = funcCheck()
return value
</code></pre>
<p>then you can call it this way</p>
<pre><code>funct(dlg, wx, dlg.GetValue)
</code></pre>
<p>Continue to add conditions to the function depending on what you want</p>
| 0 |
2016-09-10T14:11:25Z
|
[
"python",
"function"
] |
How can I know what is the name of the "key" in the dictionary which contain the paramaters for the HTTP POST request?
| 39,426,855 |
<p>I'm trying to make a Python script which make a HTTP request with a POST argument.
On this site:</p>
<p><a href="https://www.google.com/movies" rel="nofollow">google.com/movies</a></p>
<p>I'm trying to make a script which use the Google search bar and enter the name of a cinema ("Le grand Rex" is the cinema which I'm looking for)</p>
<p>When I right click and display "inspect Element" on the google search bar, it display:</p>
<pre><code><input dir="" id="gbqfq" class="gbqfif" name="q" autocomplete="off" value="" placeholder="Search Movies" type="text">
</code></pre>
<p>I see that the "value" will contain what the user write in the Google search bar. So I add in my dictionary which contain the argument, a key named "value" which contain the cinema I'm looking for ("Le grand rex" in my case) as follow:</p>
<pre><code>#! /usr/bin/env python3
import urllib.parse
import urllib.request
from bs4 import BeautifulSoup
url = "https://www.google.com/movies"
value = {
"name" : "q",
"dir" : "Le Grand Rex"
}
data = urllib.parse.urlencode(value)
data = data.encode('ascii')
the_page = urllib.request.Request(url, data)
new = urllib.request.urlopen(the_page)
#
soup = BeautifulSoup(new, 'html.parser')
h2 = soup.find_all("h2")
for element in h2:
print(element)
</code></pre>
<p>However when I check if I open the right page (more precisely, the page which is supposed to be display when a user type "Le Grand Rex" in the Google movie search bar), but unfortunately it's not the right one. </p>
<p>So:</p>
<p>Is the http reques the adequate way for reach my purpose?</p>
<p>How can I know what is the name of the "key" in the dictionary which contain the paramaters for the HTTP POST request?</p>
| 0 |
2016-09-10T14:08:02Z
| 39,455,926 |
<p><a href="https://www.w3.org/TR/html4/interact/forms.html#submit-format" rel="nofollow">The <code>name</code> attribute contains the key.</a></p>
<pre><code>{'q': 'Le Grand Rex'}
</code></pre>
| 0 |
2016-09-12T17:47:32Z
|
[
"python",
"dictionary",
"beautifulsoup"
] |
How to add horizontal line (`Span`) to the Box plot in Bokeh?
| 39,426,976 |
<p>What I want is to render a <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/charts.html#bar-charts" rel="nofollow">bar chart</a> with a <a href="http://stackoverflow.com/questions/28797330/infinite-horizontal-line-in-bokeh">horizontal line</a>, so I can see which values (represented by bars) exceed certain treshold (horisontal line). My data is represented by Pandas dataframe.</p>
<pre><code>from bokeh.plotting import figure, output_file, show
from bokeh.charts import Bar
from bokeh.models import Span
from bokeh.io import save
from pandas import DataFrame
output_file('tmp_file')
p = figure(plot_width=800, plot_height=600)
rows = [(1,'2004-01-15', 10), (2,'2004-02-21', 15)]
headers = ['id', 'date', 'value']
df = DataFrame.from_records(rows, columns=headers)
bar = Bar(df, 'date', values='value', agg='mean')
treshold = 12
hline = Span(location=treshold, dimension='width', line_color='red', line_width=3)
p.renderers.extend([hline, bar])
save(p)
</code></pre>
<p>The Exeption I get:</p>
<pre><code>File "/usr/lib/python3.4/site-packages/bokeh/core/properties.py", line 1056, in validate
raise ValueError("expected an element of %s, got seq with invalid items %r" % (self, invalid))
ValueError: expected an element of List(Instance(Renderer)), got seq with invalid items [<bokeh.charts.chart.Chart object at 0x7fa0a4534f28>]
</code></pre>
| 0 |
2016-09-10T14:22:00Z
| 39,427,333 |
<p>Ok, I figured it out...</p>
<pre><code>from bokeh.charts import Bar
from bokeh.models import Span
from bokeh.io import save, output_file, show
from pandas import DataFrame
output_file('tmp_file')
rows = [(1,'2004-01-15', 10), (2,'2004-02-21', 15)]
headers = ['id', 'date', 'value']
df = DataFrame.from_records(rows, columns=headers)
bar = Bar(df, 'date', values='value', agg='mean')
treshold = 12
hline = Span(location=treshold, dimension='width', line_color='red', line_width=3)
bar.renderers.extend([hline])
save(bar)
</code></pre>
| 2 |
2016-09-10T15:02:33Z
|
[
"python",
"pandas",
"dataframe",
"data-visualization",
"bokeh"
] |
Difference between generators and functions returning generators
| 39,426,977 |
<p>I was debugging some code with generators and came to this question. Assume I have a generator function</p>
<pre><code>def f(x):
yield x
</code></pre>
<p>and a function returning a generator:</p>
<pre><code>def g(x):
return f(x)
</code></pre>
<p>They surely return the same thing. Can there be any differences when using them interchangeably in Python code? Is there any way to distinguish the two (without <code>inspect</code>)?</p>
| 10 |
2016-09-10T14:22:10Z
| 39,427,083 |
<p>They will act the same. And about way to distinguish the two (without <code>inspect</code>). In python? Only inspect:</p>
<pre><code>import inspect
print inspect.isgeneratorfunction(g) --> False
print inspect.isgeneratorfunction(f) --> True
</code></pre>
<p>Of course you can also check it using <code>dis</code>:</p>
<pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
... yield x
...
>>> def g(x):
... return f(x)
...
>>> import dis
>>> dis.dis(f)
2 0 LOAD_FAST 0 (x)
3 YIELD_VALUE
4 POP_TOP
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
>>> dis.dis(g)
2 0 LOAD_GLOBAL 0 (f)
3 LOAD_FAST 0 (x)
6 CALL_FUNCTION 1
9 RETURN_VALUE
</code></pre>
<p>but <code>inspect</code> is more appropriate.</p>
| 1 |
2016-09-10T14:34:23Z
|
[
"python",
"generator"
] |
Difference between generators and functions returning generators
| 39,426,977 |
<p>I was debugging some code with generators and came to this question. Assume I have a generator function</p>
<pre><code>def f(x):
yield x
</code></pre>
<p>and a function returning a generator:</p>
<pre><code>def g(x):
return f(x)
</code></pre>
<p>They surely return the same thing. Can there be any differences when using them interchangeably in Python code? Is there any way to distinguish the two (without <code>inspect</code>)?</p>
| 10 |
2016-09-10T14:22:10Z
| 39,427,164 |
<p>The best way to check it out is using <a href="https://docs.python.org/2/library/inspect.html#inspect.isgeneratorfunction" rel="nofollow">inspect.isgeneratorfunction</a>, which is quite simple function:</p>
<pre><code>def ismethod(object):
"""Return true if the object is an instance method.
Instance method objects provide these attributes:
__doc__ documentation string
__name__ name with which this method was defined
im_class class object in which this method belongs
im_func function object containing implementation of method
im_self instance to which this method is bound, or None"""
return isinstance(object, types.MethodType)
def isfunction(object):
"""Return true if the object is a user-defined function.
Function objects provide these attributes:
__doc__ documentation string
__name__ name with which this function was defined
func_code code object containing compiled function bytecode
func_defaults tuple of any default values for arguments
func_doc (same as __doc__)
func_globals global namespace in which this function was defined
func_name (same as __name__)"""
return isinstance(object, types.FunctionType)
def isgeneratorfunction(object):
"""Return true if the object is a user-defined generator function.
Generator function objects provides same attributes as functions.
See help(isfunction) for attributes listing."""
return bool((isfunction(object) or ismethod(object)) and
object.func_code.co_flags & CO_GENERATOR)
</code></pre>
<p>Now, if you declared your generator using a syntax like this:</p>
<pre><code>my_generator = (i*i for i in range(1000000))
</code></pre>
<p>In that case, you could check its type quite easily, for instance, <code>__class__</code> will return <code><type 'generator'></code>.</p>
| 1 |
2016-09-10T14:43:10Z
|
[
"python",
"generator"
] |
Difference between generators and functions returning generators
| 39,426,977 |
<p>I was debugging some code with generators and came to this question. Assume I have a generator function</p>
<pre><code>def f(x):
yield x
</code></pre>
<p>and a function returning a generator:</p>
<pre><code>def g(x):
return f(x)
</code></pre>
<p>They surely return the same thing. Can there be any differences when using them interchangeably in Python code? Is there any way to distinguish the two (without <code>inspect</code>)?</p>
| 10 |
2016-09-10T14:22:10Z
| 39,427,547 |
<p>If you want to <strong>identify</strong> what is a generator, the answer is simple. <code>f</code> is a generator because it contains the <code>yield</code> statement. <code>g</code> is not a generator because it does not contain the <code>yield</code> statement. (You can have a look at <a href="https://docs.python.org/2/reference/simple_stmts.html?highlight=yield#the-yield-statement" rel="nofollow">https://docs.python.org/2/reference/simple_stmts.html?highlight=yield#the-yield-statement</a>)</p>
<p>As for what is the difference in <strong>using</strong> them, they are quite the same. You can store a generator in a variable, then use it in a <code>for</code> statement. In that case, <code>g(x)</code> just acts as a "middle man". Have a look at the following examples:</p>
<pre><code>def f(x):
for r in range(x):
yield r
def g(x):
return f(x)
print "using f(x)"
for i in f(3):
print i
print "using g(x)"
for j in g(3):
print j
print "store the iterator f(x) in a variable, then use it in a 'for' statement"
m = f(3)
for k in m:
print k
print "store the iterator f(x) returned by g(x), then use it in a 'for' statement"
n = g(3)
for k in n:
print k
</code></pre>
<p>These are in python2. Just add parentheses in print statements for python3. </p>
| 1 |
2016-09-10T15:24:33Z
|
[
"python",
"generator"
] |
How can I convert this Python mutable function into immutable?
| 39,427,027 |
<p>I have a mutable Fibonacci function that mutates a list in order to return that list as a fib sequence. I want to do the same thing... but the list (or tuple in this case) should not be able to change. The return still has to send the whole list, how can I implement this, without using recursion. </p>
<p>Ex) if x = 6... list should return {1,1,2,3,5,8}</p>
<p>I'm running in python 3.5</p>
<p>Here is my code:</p>
<pre><code>def mutableFib(x):
result = []
for y in range(0,x):
if y < 2:
result.append(1)
else:
last = result[y - 1]
previous = result[y - 2]
result.append(last + previous) //result is being changed
return result
</code></pre>
| -1 |
2016-09-10T14:29:11Z
| 39,427,699 |
<p>You could create a new list for every new element.</p>
<pre><code>def fibonacci(x):
list_of_fibonaccis = []
for y in range(0,x):
if y < 2:
temp_fibonacci = [1] * (y + 1)
else:
last = list_of_fibonaccis[y-1][-1]
previous = list_of_fibonaccis[y-1][-2]
temp_fibonacci = list_of_fibonaccis[y-1] + [last + previous]
list_of_fibonaccis.append(temp_fibonacci)
return list_of_fibonaccis[-1]
</code></pre>
| 0 |
2016-09-10T15:38:20Z
|
[
"python",
"list",
"immutability"
] |
How can I convert this Python mutable function into immutable?
| 39,427,027 |
<p>I have a mutable Fibonacci function that mutates a list in order to return that list as a fib sequence. I want to do the same thing... but the list (or tuple in this case) should not be able to change. The return still has to send the whole list, how can I implement this, without using recursion. </p>
<p>Ex) if x = 6... list should return {1,1,2,3,5,8}</p>
<p>I'm running in python 3.5</p>
<p>Here is my code:</p>
<pre><code>def mutableFib(x):
result = []
for y in range(0,x):
if y < 2:
result.append(1)
else:
last = result[y - 1]
previous = result[y - 2]
result.append(last + previous) //result is being changed
return result
</code></pre>
| -1 |
2016-09-10T14:29:11Z
| 39,428,102 |
<p>If I understand what you mean by "a functional approach that doesn't use recursion," it seems like the input parameter should be a list of the first n Fibonacci numbers and the output should be a list of the first n+1 Fibonacci numbers. If this is correct, then you could use</p>
<pre><code>def fibonacci(fib):
if not fib: return [1]
if len(fib) == 1: return [1,1]
return fib + [fib[-1]+fib[-2]]
</code></pre>
| 0 |
2016-09-10T16:19:08Z
|
[
"python",
"list",
"immutability"
] |
how to click iframe using python selenium
| 39,427,156 |
<p>I want to click an iframe's radio button, but it doesn't work.
my code is this.</p>
<pre><code>import time
from selenium import webdriver
Url='https://www.youtube.com/watch?v=eIStvhR347g'
driver = webdriver.Firefox()
driver.get('https://video-download.online')
driver.find_element_by_id("link").send_keys(Url)
driver.find_element_by_id("submit").click()
time.sleep(5)
#this part is problems... don't working
driver.switch_to_frame(driver.find_element_by_tag_name("iframe"))
driver.find_element_by_css_selector("136-wrapper").click()
driver.find_element_by_link_text("Proceed").click()
</code></pre>
<p>html source is this.</p>
<pre><code><html>
<head>
<meta charset="utf-8"/>
<script>
if (top.location !== location) {
top.location = self.location;
}
if (location.host !== 'video-download.online' && location.host !== 'beta.video-download.online') {
eval("location.href=''+'//'+'video-download.online';");
}
</script>
<meta name="msapplication-tap-highlight" content="no"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
<meta name="author" content="Luca Steeb"/>
<meta name="theme-color" content="#008679"/>
<meta name="description" content="Download from this uploaded.net premium link generator with highspeed. For free."/>
<meta property="og:title" content="Video-Download.online"/>
<meta property="og:description" content="Download videos, mp3s and playlists from 1979 sites - for free."/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="video-download.online"/>
<meta property="fb:page_id" content="1143492155680932"/>
<meta property="og:image" content="//video-download.online/img/logo.jpg"/>
<link rel="shortcut icon" href="/favicon.ico?1"/>
<link rel="icon" sizes="192x192" href="/img/logo_small.jpg"/>
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
<link rel="search" type="application/opensearchdescription+xml" title="Video-Download.online" href="/opensearch.xml"/>
<title>
Online Video Download
</title>
<meta name="robots" content="noindex, nofollow"/>
<link rel="stylesheet" href="/css/bt.css"/>
<link rel="stylesheet" href="/css/style.css"/>
<noscript><iframe height=0 src="//www.googletagmanager.com/ns.html?id=GTM-TWMNRP"style=display:none;visibility:hidden width=0></iframe></noscript><script>!function(e,t,a,n,r){e[n]=e[n]||[],e[n].push({"gtm.start":(new Date).getTime(),event:"gtm.js"});var g=t.getElementsByTagName(a)[0],m=t.createElement(a),s="dataLayer"!=n?"&l="+n:"";m.async=!0,m.src="//www.googletagmanager.com/gtm.js?id="+r+s,g.parentNode.insertBefore(m,g)}(window,document,"script","dataLayer","GTM-TWMNRP")</script>
<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');ga('create','UA-54289597-5','auto');ga('send','pageview');</script>
<script>function send(action) { ga('send', 'event', 'button', 'click', 'download-' + action) }</script>
<script async src="/js/jquery.js"></script>
<script>function _(n,i){i?window[n]?i():setTimeout(function(){_(n,i)},100):window.jQuery?window.jQuery(document).ready(function(){n(window.jQuery)}):setTimeout(function(){_(n)},100)}</script>
</head>
<body>
<header class="navbar navbar-info navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle no-waves" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="nav-brand">
<a class="navbar-brand" href="/">
<img class="logo" src="/img/logo.svg" alt=""/>
<div class="parent">
Video-Download<small>.online</small>
<br/>
<span class="small-text">1979 sites officially supported</span>
<span id="changelog"></span>
</div>
<span class="clear"></span>
</a>
</div>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<div class="social">
<div class="fb-like fb-nav" data-href="https://www.facebook.com/VideoDownload.online"
data-layout="button_count" data-action="like" data-show-faces="false" data-share="true">
</div>
</div>
<div class="social-close" title="Hide all social buttons">&times;</div>
<li class=" ">
<a href="/">
Home
</a>
</li>
<li class=" ">
<a href="/sites">
Sites
</a>
</li>
<li class=" ">
<a href="/contact">
Contact
</a>
</li>
<!--html.navItem('/app', 'Mobile App')-->
</ul>
</div>
</div>
</header>
<noscript class="fixed">
<div class="container">Please enable javascript. Video Download and almost all other sites don't work properly
without it.
</div>
</noscript>
<div id="alert" class="alert alert-fixed alert-dismissible m-t-15 hidden">
<div class="container relative">
<span id="alertText"></span>
<span class="close-alert" onclick="_(function() { $('#alert').remove();$('body').removeClass('alert-showing') })" title="close">Ã</span>
</div>
</div>
<main class="container">
<div>
<h1>Legal</h1>
<div style="width: 50%;" class="center">
</div>
</main>
<script src="/sweetalert/sweetalert.js"></script>
<link rel="stylesheet" href="/sweetalert/sweetalert.css">
<script src="/waves/waves.min.js"></script>
<script src="/js/dropdown.js"></script>
<script src="/js/main.js"></script>
<script src="/js/bootstrap.js"></script>
<script type="text/javascript">/* <![CDATA[ */(function(d,s,a,i,j,r,l,m,t){try{l=d.getElementsByTagName('a');t=d.createElement('textarea');for(i=0;l.length-i;i++){try{a=l[i].href;s=a.indexOf('/cdn-cgi/l/email-protection');m=a.length;if(a&&s>-1&&m>28){j=28+s;s='';if(j<m){r='0x'+a.substr(j,2)|0;for(j+=2;j<m&&a.charAt(j)!='X';j+=2)s+='%'+('0'+('0x'+a.substr(j,2)^r).toString(16)).slice(-2);j++;s=decodeURIComponent(s)+a.substr(j,m-j)}t.innerHTML=s.replace(/</g,'&lt;').replace(/>/g,'&gt;');l[i].href='mailto:'+t.value}}catch(e){}}}catch(e){}})(document);/* ]]> */</script></body>
</html>
</code></pre>
<p>frame source is this.</p>
<pre><code><html>
<head>
<meta charset="utf-8"/>
<meta name="robots" content="noindex, nofollow"/>
<link rel="stylesheet" href="/css/bt.css"/>
<link rel="stylesheet" href="/css/style.css"/>
<script src="/js/jquery.js"></script>
<style>body{margin:0!important;}tr{clear:both;cursor:pointer;}td{padding:0 20px 0 0;white-space:nowrap;}.radio{margin-top:5px;margin-bottom:5px;}.small{padding:0;font-size:85%;}@media (max-width: 319px) {table{font-size:12px;}}@media (max-width: 480px) {td{padding:0 5px 0 0;}.small{font-size:50%;}}</style>
</head>
<body>
<form id="format" method="post">
<input name="id" type="hidden" value="isxklqy5blw9of7"/>
<table>
<tr>
<td class="small">
<div class="">
<div class="radio " id="undefined-wrapper">
<label class="text-capitalize" for="undefined">
<input id="undefined" name="format" type="radio" value="undefined" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>I don't care</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td class="small">
<div class="">
<div class="radio " id="160-wrapper">
<label class="text-capitalize" for="160">
<input id="160" name="format" type="radio" value="160" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>256x144</td>
<td></td>
<td>
30 FPS
</td>
<td>23.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="133-wrapper">
<label class="text-capitalize" for="133">
<input id="133" name="format" type="radio" value="133" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>426x240</td>
<td></td>
<td>
30 FPS
</td>
<td>51.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="134-wrapper">
<label class="text-capitalize" for="134">
<input id="134" name="format" type="radio" value="134" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>640x360</td>
<td></td>
<td>
30 FPS
</td>
<td>65.4 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="135-wrapper">
<label class="text-capitalize" for="135">
<input id="135" name="format" type="radio" value="135" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>854x480</td>
<td></td>
<td>
30 FPS
</td>
<td>138.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="136-wrapper">
<label class="text-capitalize" for="136">
<input id="136" name="format" type="radio" value="136" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1280x720</td>
<td>HD</td>
<td>
30 FPS
</td>
<td>272.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="298-wrapper">
<label class="text-capitalize" for="298">
<input id="298" name="format" type="radio" value="298" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1280x720</td>
<td>HD</td>
<td>
60 FPS
</td>
<td>385.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="137-wrapper">
<label class="text-capitalize" for="137">
<input id="137" name="format" type="radio" value="137" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1920x1080</td>
<td>Full HD</td>
<td>
30 FPS
</td>
<td>535.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="299-wrapper">
<label class="text-capitalize" for="299">
<input id="299" name="format" type="radio" value="299" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1920x1080</td>
<td>Full HD</td>
<td>
60 FPS
</td>
<td>707.0 MB</td>
</tr>
</table>
<button class="btn center" type="submit">Proceed &raquo;</button>
</form>
</body>
<script>
$('tr').click(function() {
$(this).find('input').prop('checked', true);
});
</script>
<script src="/waves/waves.min.js"></script>
<script>
Waves.attach('.btn', ['waves-light']);
Waves.init();
</script>
</code></pre>
<p>I tried these codes, but don't work.</p>
<pre><code>driver.switch_to_frame(driver.find_element_by_xpath('//iframe[contains(@name, "frame")]'))
driver.switch_to_frame(driver.find_element_by_tag_name("iframe"))
driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
driver.switch_to_frame(0)
</code></pre>
<p>these iframe switching codes are any exception is nothing, but result is '[]'.</p>
<pre><code>>>> driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
>>> driver.find_elements_by_xpath("//*[@type='radio']")
[]
>>> driver.find_elements_by_xpath("//*[@type='radio']")[0].click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code></pre>
<p>thanks for your help</p>
| 1 |
2016-09-10T14:42:34Z
| 39,429,238 |
<p>(Assuming provided HTML is correct) actually your both locator is wrong to locate <code>radio button</code> element as well as <code>proceed button</code> element.</p>
<blockquote>
<p>driver.find_element_by_css_selector("136-wrapper").click()</p>
</blockquote>
<p>Using <a href="http://www.w3schools.com/cssref/css_selectors.asp" rel="nofollow"><code>css_selector</code></a> id locator used with <code>#</code>, so correct <a href="http://www.w3schools.com/cssref/sel_id.asp" rel="nofollow"><code>css_selector</code> with id</a> should be <code>#136-wrapper</code></p>
<p>But this locator will be locate to <code><div></code> element while you want <code><input id="136" name="format" type="radio" value="136" onchange="" undefined required /></code> element, so here you can locate <code>radio button</code> and click using <code>find_element_by_id()</code> as :-</p>
<pre><code>driver.find_element_by_id("136").click()
</code></pre>
<blockquote>
<p>driver.find_element_by_link_text("Proceed").click()</p>
</blockquote>
<p><a href="http://selenium-python.readthedocs.io/locating-elements.html#locating-hyperlinks-by-link-text" rel="nofollow"><code>find_element_by_link_text()</code></a> works to locate only <code><a></code> anchor element with text while you want to locate <code><button></code> element, so this locator wouldn't work.</p>
<p>To locate <code>Proceed</code> button you should try using <code>find_element_by_xpath()</code> as :-</p>
<pre><code>driver.find_element_by_xpath(".//button[contains(text(),'Proceed')]").click()
</code></pre>
| 0 |
2016-09-10T18:23:43Z
|
[
"python",
"selenium",
"firefox"
] |
Django models's attributes correctly saved by forms, but returns None type when queried
| 39,427,217 |
<p>I have a model called UserProfile defined like so:</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True, null=True)
location = models.CharField(max_length=200, null=True)
longitude = models.FloatField(null=True)
latitude = models.FloatField(null=True)
credit = models.FloatField(default=0, null=True)
def __unicode__(self):
return self.user.username
</code></pre>
<p>The 'register' page includes the following form:</p>
<p>When it is submitted it goes to:</p>
<pre><code>def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(request.POST)
profile_form = UserProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
print(request.POST)
lat = request.POST.get('lat')
print("lat is: " + lat)
lng = request.POST.get('lng')
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.latitude = lat
profile.longitude = lng
profile.save()
else:
print user_form.errors, profile_form.errors
else:
profile_form = UserProfileForm()
user_form = UserForm()
return render(request, "register.html", {'user_form' : user_form, 'profile_form' : profile_form})
</code></pre>
<p>That all seems to work fine, but when I try to query this data in another view, the location, lat, and lng properties come up as 'None' types.</p>
<pre><code>def link(request):
print("trying to authenticate...")
if request.user.is_authenticated():
user_profile = UserProfile(user=request.user)
else:
return render(request, 'login.html')
if request.method == "POST":
print("request was a post.")
if request.is_ajax():
print("request is ajax.")
print("User profile is: " + str(user_profile))
# returns billy, so we're looking at the right object
print("user location is: " + str(user_profile.location))
user_longitude = user_profile.longitude
user_latitude = user_profile.latitude
distance = request.POST.get('distance')
value = request.POST.get('value')
</code></pre>
<p>As you can see, the data coming up here is different than what is returned by the shell queries:</p>
<pre><code>User profile is billy
user location is: None
user longitude is: None
</code></pre>
<p>I'm very confused as to how location, etc are float types in the shell and register view, but None types in the 'link' view. Any ideas?</p>
| 0 |
2016-09-10T14:50:21Z
| 39,427,577 |
<p>In your <code>link</code> view, you're not querying for the userprofile, you're just instantiating a new (blank) one with the user set to the current user.</p>
<p>You probably meant to do:</p>
<pre><code>user_profile = UserProfile.objects.get(user=request.user)
</code></pre>
<p>but it would be even easier to do:</p>
<pre><code>user_profile = request.user.userprofile
</code></pre>
<p>Another minor point: you don't show the form, but I assume that the UserProfileForm has <code>latitude</code> and <code>longitude</code> fields on it, in which case there is no need to set them manually. If they're not on the form, why not? By getting them directly from request.POST you're bypassing all the validation the form would do, such as checking that they are valid float values.</p>
| 1 |
2016-09-10T15:27:42Z
|
[
"python",
"django",
"views",
"nonetype",
"querying"
] |
Need help assiigning numbers to letters in python
| 39,427,232 |
<p><a href="http://i.stack.imgur.com/SuSs7.png" rel="nofollow">This is a a plan of what i want to do with the code.</a></p>
<p>This is all i have to offer, I'm not sure if it's correct.</p>
<pre><code>input ("What's your name?")
[A,J,S]=1
[B,K,T]=2
[C,L,U]=3
[D,M,V]=4
[E,N,W]=5
[F,O,X]=6
[G,P,Y]=7
[H,Q,Z]=8
[I,R]=9
</code></pre>
<ul>
<li><p>Input a personâs name</p></li>
<li><p>Calculate their lucky name number using the grid in Figure 1 above</p></li>
<li><p>Display the names</p></li>
<li><p>Display the lucky name number</p></li>
</ul>
| -6 |
2016-09-10T14:51:47Z
| 39,427,623 |
<p>Firstly, the input value needs to be assigned to a variable. So instead of doing</p>
<pre><code>input ("What's your name?")
</code></pre>
<p>You should write</p>
<pre><code>input_text = input("What's your name?")
</code></pre>
<p>This will store the user's input to the string variable input_text.</p>
<p>Next, we will need to declare a dictionary to map each letter to its number.</p>
<pre><code>alpha_map = {'A': 1, 'B': 2, 'C': 3} # And so on until 'Z'
</code></pre>
<p>After we have done this, we can iterate through each character of input_text and grab its value from the dictionary.</p>
<pre><code>alpha_values = [] # An empty list
for character in input_text:
alpha_values.append(alpha_map[character]) # Adds each character's value to alpha_values.
</code></pre>
<p>You can use the sum() function to sum up the list of values.</p>
<p>As for adding up the digits, you could convert the resulting number into a string and convert each character to an int before summing up.</p>
<pre><code>total = 0
for character in str(number):
total += int(character)
</code></pre>
<p>Note that you will have to strip the input text of any non-alphabetical characters, and capitalize all letters for this program to run - there are already plenty of online documentations explaining how to do this.</p>
| 2 |
2016-09-10T15:33:10Z
|
[
"python",
"python-3.x"
] |
How Flask-Bootstrap works?
| 39,427,256 |
<p>I'm learning Flask web development, and the tutorial I'm following introduces an extension called <strong>Flask-Bootstrap</strong>. To use this extension, you must initialize it first, like this:</p>
<pre><code>from flask_bootstrap import Bootstrap
# ...
bootstrap = Bootstrap(app)
</code></pre>
<p>Weirdly enough to me, the variable <code>bootstrap</code> is not used in the rest of my module. However, if I comment out this line, a <code>jinja2.exceptions.TemplateNotFound</code> exception will be raised. Also, the templates used start with this line:</p>
<pre><code>{% extends "bootstrap/base.html" %}
</code></pre>
<p>But I don't have a directory named <code>/bootstrap</code> under <code>/templates</code>!</p>
<p>I want to know what's going on:</p>
<ol>
<li>What does the <code>bootstrap = Bootstrap(app)</code> line do?</li>
<li>Where does <code>bootstrap/base.html</code> reside? </li>
</ol>
| -1 |
2016-09-10T14:53:57Z
| 39,427,671 |
<p>As @davidism said in his comment, the <code>bootstrap = Bootstrap(app)</code> line "installs the extension on the app". The mechanism behind such installation is beyond the scope of this answer.</p>
<p>The <code>bootstrap/base.html</code> resides in the Flask-Bootstrap package. For example, on my machine it's absolute path is:</p>
<pre><code>/Users/sunqingyao/Documents/Projects/flasky/venv/lib/python2.7/site-packages/flask_bootstrap/templates/bootstrap/base.html
</code></pre>
<p>Here is its content:</p>
<pre><code>{% block doc -%}
<!DOCTYPE html>
<html{% block html_attribs %}{% endblock html_attribs %}>
{%- block html %}
<head>
{%- block head %}
<title>{% block title %}{{title|default}}{% endblock title %}</title>
{%- block metas %}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{%- endblock metas %}
{%- block styles %}
<!-- Bootstrap -->
<link href="{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet">
{%- endblock styles %}
{%- endblock head %}
</head>
<body{% block body_attribs %}{% endblock body_attribs %}>
{% block body -%}
{% block navbar %}
{%- endblock navbar %}
{% block content -%}
{%- endblock content %}
{% block scripts %}
<script src="{{bootstrap_find_resource('jquery.js', cdn='jquery')}}"></script>
<script src="{{bootstrap_find_resource('js/bootstrap.js', cdn='bootstrap')}}"></script>
{%- endblock scripts %}
{%- endblock body %}
</body>
{%- endblock html %}
</html>
{% endblock doc -%}
</code></pre>
<p><sub>The answer to "how can Jinja2 find <code>base.html</code>" would be added as soon as I find the relevant part in the document.</sub></p>
| 0 |
2016-09-10T15:36:52Z
|
[
"python",
"twitter-bootstrap",
"templates",
"flask",
"flask-bootstrap"
] |
Set wx.Frame size (wxPython - wxWidgets)
| 39,427,319 |
<p>I am new to wxPython and I am finding some issues while seting a given size for both frames and windows (widgets). I have isolated the issue to the simplest case where I try to create a Frame of 250x250 pixels.</p>
<p>Running the code I get a window of an actual size of 295 width by 307 height (taking into consideration the Windows´s top window bar)</p>
<p>I am using Python 2.7 in Windows 10.</p>
<p>What am I missing? </p>
<pre><code>#!/bin/env python
import wx
# App Class
class MyAppTest7(wx.App):
def OnInit(self):
frame = AppFrame(title = u'Hello World', pos=(50, 60), size=(250, 250))
frame.Show()
self.SetTopWindow(frame)
return True
# AppFrame
class AppFrame(wx.Frame):
def __init__(self, title, pos, size):
wx.Frame.__init__(self, parent=None, id=-1, title=title, pos=pos, size=size)
if __name__ == '__main__':
app = MyAppTest7(False)
app.MainLoop()
</code></pre>
<p>An addtional test to further show issue:</p>
<pre><code>#!/bin/env python
import wx
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, title="The Main Frame")
self.SetTopWindow(self.frame)
self.frame.Show(True)
return True
class MyFrame(wx.Frame):
def __init__(self, parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition, size=(400,100), style=wx.DEFAULT_FRAME_STYLE, name="MyFrame"):
super(MyFrame, self).__init__(parent, id, title, pos, size, style, name)
self.panel = wx.Panel(self)
if __name__ == "__main__":
app = MyApp(False)
app.MainLoop()
</code></pre>
<p>And the result:</p>
<p>As you can see displayed window (frame) has 482 pixels (-see Paint's bottom bar-) instead of the expected 400.</p>
<p><a href="http://i.stack.imgur.com/ZtsvE.png" rel="nofollow">Window size measured in pixels</a></p>
| 0 |
2016-09-10T15:01:44Z
| 39,456,255 |
<p>Add this before your call to <code>app.MainLoop()</code>:</p>
<pre><code>import wx.lib.inspection
wx.lib.inspection.InspectionTool().Show()
</code></pre>
<p>That will let you easily see the actual size (and other info) for each widget in the application, like this:</p>
<p><a href="http://i.stack.imgur.com/yXaSn.png" rel="nofollow"><img src="http://i.stack.imgur.com/yXaSn.png" alt="Widget Inspection Tool"></a></p>
| 0 |
2016-09-12T18:09:06Z
|
[
"python",
"python-2.7",
"wxpython",
"wxwidgets"
] |
condensing multiple if statements in python
| 39,427,378 |
<p>I'm trying to write a function to check if an object is found in multiple lists and to remove the object from any list its found in. I want to know if there is a way to make it cleaner or smarter using some form of generic variable where you predefine the format or something along those lines.
my code in its ugly form:</p>
<pre><code>def create_newlist(choice):
if choice in list_a:
list_a.remove(choice)
if choice in list_b:
list_b.remove(choice)
if choice in list_c:
list_c.remove(choice)
if choice in list_d:
list_d.remove(choice)
if choice in list_e:
list_e.remove(choice)
</code></pre>
<p>What I'm hoping for is something like:</p>
<pre><code>if choice in list_x:
list_x.remove(choice)
</code></pre>
<p>I would like it to work for each list, would I need to loop through? any suggestions would be great! I have the workaround but I would love to learn a more elegant way of coding this!</p>
| 6 |
2016-09-10T15:07:25Z
| 39,427,440 |
<p>Make your <code>list_x</code> a list of all your lists</p>
<p>Then do it this way</p>
<pre><code>for each in list_x:
if choice in each:
# if is actually not required
each.remove(choice)
</code></pre>
| 2 |
2016-09-10T15:13:16Z
|
[
"python",
"list",
"loops",
"if-statement"
] |
condensing multiple if statements in python
| 39,427,378 |
<p>I'm trying to write a function to check if an object is found in multiple lists and to remove the object from any list its found in. I want to know if there is a way to make it cleaner or smarter using some form of generic variable where you predefine the format or something along those lines.
my code in its ugly form:</p>
<pre><code>def create_newlist(choice):
if choice in list_a:
list_a.remove(choice)
if choice in list_b:
list_b.remove(choice)
if choice in list_c:
list_c.remove(choice)
if choice in list_d:
list_d.remove(choice)
if choice in list_e:
list_e.remove(choice)
</code></pre>
<p>What I'm hoping for is something like:</p>
<pre><code>if choice in list_x:
list_x.remove(choice)
</code></pre>
<p>I would like it to work for each list, would I need to loop through? any suggestions would be great! I have the workaround but I would love to learn a more elegant way of coding this!</p>
| 6 |
2016-09-10T15:07:25Z
| 39,427,443 |
<p>How about creating a list of lists and looping over that? </p>
<p>Something like: </p>
<pre><code>lists = [list_a, list_b, list_c, list_d, list_e]
for lst in lists:
if choice in lst:
lst.remove(choice)
</code></pre>
| 5 |
2016-09-10T15:13:32Z
|
[
"python",
"list",
"loops",
"if-statement"
] |
condensing multiple if statements in python
| 39,427,378 |
<p>I'm trying to write a function to check if an object is found in multiple lists and to remove the object from any list its found in. I want to know if there is a way to make it cleaner or smarter using some form of generic variable where you predefine the format or something along those lines.
my code in its ugly form:</p>
<pre><code>def create_newlist(choice):
if choice in list_a:
list_a.remove(choice)
if choice in list_b:
list_b.remove(choice)
if choice in list_c:
list_c.remove(choice)
if choice in list_d:
list_d.remove(choice)
if choice in list_e:
list_e.remove(choice)
</code></pre>
<p>What I'm hoping for is something like:</p>
<pre><code>if choice in list_x:
list_x.remove(choice)
</code></pre>
<p>I would like it to work for each list, would I need to loop through? any suggestions would be great! I have the workaround but I would love to learn a more elegant way of coding this!</p>
| 6 |
2016-09-10T15:07:25Z
| 39,429,954 |
<h3>In a one-liner</h3>
<p>If you use <code>some_list.remove(item)</code>, only the first found match of <code>item</code> is removed from the list. Therefore, it depends if the lists possibly include duplicated items, which (all) need to be removed:</p>
<h3>1. If all items in all lists are unique</h3>
<pre><code>list1 = ["a", "b" , "c", "d"]
list2 = ["k", "l", "m", "n"]
list3 = ["c", "b", "a", "e"]
[l.remove("a") for l in [list1, list2, list3] if "a" in l]
print(list3)
> ["c", "b", "e"]
</code></pre>
<p><em>However</em> </p>
<h3>2. If one or more lists possibly includes duplicated items</h3>
<p>In that case <code>itertools</code>' <a href="https://docs.python.org/3/library/itertools.html#itertools.filterfalse" rel="nofollow">filterfalse()</a> will come in handy:</p>
<pre><code>from itertools import filterfalse
def remove_val(val, lists):
return [list(filterfalse(lambda w: w == val, l)) for l in lists]
l1 = ["a", "b" , "c", "d"]
l2 = ["k", "l", "m", "n"]
l3 = ["a", "c", "b", "a", "a", "e"]
newlists = remove_val("a", [l1, l2, l3])
</code></pre>
<p>Then the test:</p>
<pre><code>print(newlists)
> [['b', 'c', 'd'], ['k', 'l', 'm', 'n'], ['c', 'b', 'e']]
</code></pre>
| 3 |
2016-09-10T19:43:11Z
|
[
"python",
"list",
"loops",
"if-statement"
] |
condensing multiple if statements in python
| 39,427,378 |
<p>I'm trying to write a function to check if an object is found in multiple lists and to remove the object from any list its found in. I want to know if there is a way to make it cleaner or smarter using some form of generic variable where you predefine the format or something along those lines.
my code in its ugly form:</p>
<pre><code>def create_newlist(choice):
if choice in list_a:
list_a.remove(choice)
if choice in list_b:
list_b.remove(choice)
if choice in list_c:
list_c.remove(choice)
if choice in list_d:
list_d.remove(choice)
if choice in list_e:
list_e.remove(choice)
</code></pre>
<p>What I'm hoping for is something like:</p>
<pre><code>if choice in list_x:
list_x.remove(choice)
</code></pre>
<p>I would like it to work for each list, would I need to loop through? any suggestions would be great! I have the workaround but I would love to learn a more elegant way of coding this!</p>
| 6 |
2016-09-10T15:07:25Z
| 39,439,237 |
<p>An alternative to the former suggestions, which is a bit clearer, is to define a helper function. So, instead of:</p>
<pre><code>def create_newlist(choice):
if choice in list_a:
list_a.remove(choice)
if choice in list_b:
list_b.remove(choice)
if choice in list_c:
list_c.remove(choice)
if choice in list_d:
list_d.remove(choice)
if choice in list_e:
list_e.remove(choice)
</code></pre>
<p>You'd have:</p>
<pre><code>def create_newlist(_list, choice):
if choice in _list:
_list.remove(choice)
lists = [list_a, list_b, list_c, list_d, list_e]
for _lst in lists:
create_newlist(_lst, choice)
</code></pre>
| 0 |
2016-09-11T18:19:27Z
|
[
"python",
"list",
"loops",
"if-statement"
] |
Matplot Legend uncorrect names
| 39,427,476 |
<p>l have a 41_year_dataset and l would like to plot these data with Matplotlib and when l add legend on graph and legend shows 6 lines correctly except names. how can l fix it?</p>
<p>here is my code:</p>
<pre><code>import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import matplotlib
filename="output813b.csv"
cols = ["date","year","month","day" ,"pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"]
data1=pd.read_csv(filename,sep=',')
colmns_needed=["year","month" ,"pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"]
data2=pd.read_csv(filename,sep=',')
data2.loc[:, 'pcp1':'pcp6'] = data2.loc[:, 'pcp1':'pcp6'].astype('float')
yy=data2.groupby("year")
mm=data2.groupby("month")
ts=yy.sum()
y1=ts.pcp1
y2=ts.pcp2
y3=ts.pcp3
y4=ts.pcp4
y5=ts.pcp5
y6=ts.pcp6
"""print(yy.mean())"""
yr=1978
x=[]
for i in range(len(y1)):
yr+=1
x.append(yr)
plt.plot(x,y1,"ro",x,y2,x,y3,x,y4,x,y5,x,y6)
plt.ylabel('PCP SUM(mm)')
plt.xlabel("Years")
plt.title("SUM OF PCP")
plt.legend()
plt.show()
</code></pre>
<p>example data:</p>
<pre><code>month day pcp1 pcp2 pcp3 pcp4 pcp5 pcp6
year
1979 2382 5738 301.324 388.796 742.131 488.490 320.556 356.847
1980 2384 5767 294.930 423.243 823.397 552.660 376.599 453.105
1981 2382 5738 610.289 767.643 1277.867 859.655 663.417 726.007
1982 2382 5738 142.187 233.438 472.786 247.644 141.886 180.665
1983 2382 5738 322.897 423.026 824.202 541.882 312.711 339.395
1984 2384 5767 247.387 302.478 528.636 402.985 239.666 222.452
1985 2382 5738 277.279 375.935 778.349 417.070 238.995 289.696
1986 2382 5738 225.559 270.099 577.484 361.182 187.847 206.059
1987 2382 5738 377.751 510.545 952.429 664.123 451.063 510.339
1988 2384 5767 290.310 409.777 871.704 539.924 289.630 339.593
</code></pre>
<p>another question is how l can get year column as x axis?. could not do this and l use for loop instead of it.<a href="http://i.stack.imgur.com/mLGCu.png" rel="nofollow"><img src="http://i.stack.imgur.com/mLGCu.png" alt="enter image description here"></a>l</p>
| 0 |
2016-09-10T15:17:31Z
| 39,427,878 |
<p>A simple trick is to call <code>plot</code> once per line, each with its own <code>label</code> argument containing the text that will show up in the legend.</p>
<pre><code>plt.plot(x, y1, "ro", label='pcp1')
plt.plot(x, y2, label='pcp2')
plt.plot(x, y3, label='pcp3')
plt.plot(x, y4, label='pcp4')
plt.plot(x, y5, label='pcp5')
plt.plot(x, y6, label='pcp6')
plt.ylabel('PCP SUM(mm)')
plt.xlabel("Years")
plt.title("SUM OF PCP")
plt.legend()
plt.show()
</code></pre>
<p>Now, when calling <code>legend()</code>, it will display the correct texts as you want.</p>
<p><a href="http://i.stack.imgur.com/mGCiH.png" rel="nofollow"><img src="http://i.stack.imgur.com/mGCiH.png" alt="enter image description here"></a></p>
| 1 |
2016-09-10T15:57:09Z
|
[
"python",
"pandas",
"matplotlib"
] |
Handling missing fields when using Python lamda's
| 39,427,492 |
<p>I have this rethinkDB query which basically returns the documents which "basicConstraints" fields that start with "CA:FA".</p>
<p>However in some of my documents the "basicConstraints" field does not exist. </p>
<pre><code>q = r.db('scanafi').table(active_table) \
.concat_map(lambda doc: doc["certificates"]\
.concat_map(lambda x: x["parsed_certificate"]["X509 extensions"])\
.filter(lambda x: x["basicConstraints"]
.match("^CA:FA"))) \
.run()
</code></pre>
<p>How can I also include all of the documents which contain this missing field in my query?</p>
| 1 |
2016-09-10T15:19:29Z
| 39,427,541 |
<p>It seems that your <code>x</code> doesn't have methods like a regular python dict (I'm not familiar with rethinkdb). You could just use a real function here, with a try/except clause:</p>
<pre><code>def basic_constraints(x):
try:
return x["basicConstraints"]
except: # find out what the actual exception is and put that here
return True
q = r.db('scanafi').table(active_table) \
.concat_map(lambda doc: doc["certificates"]\
.concat_map(lambda x: x["parsed_certificate"]["X509 extensions"])\
.filter(basic_constraints)
.match("^CA:FA"))) \
.run()## Heading ##
</code></pre>
| 0 |
2016-09-10T15:24:20Z
|
[
"python",
"lambda",
"rethinkdb",
"rethinkdb-python"
] |
Handling missing fields when using Python lamda's
| 39,427,492 |
<p>I have this rethinkDB query which basically returns the documents which "basicConstraints" fields that start with "CA:FA".</p>
<p>However in some of my documents the "basicConstraints" field does not exist. </p>
<pre><code>q = r.db('scanafi').table(active_table) \
.concat_map(lambda doc: doc["certificates"]\
.concat_map(lambda x: x["parsed_certificate"]["X509 extensions"])\
.filter(lambda x: x["basicConstraints"]
.match("^CA:FA"))) \
.run()
</code></pre>
<p>How can I also include all of the documents which contain this missing field in my query?</p>
| 1 |
2016-09-10T15:19:29Z
| 39,462,637 |
<p>You can write <code>x.has_fields('basicConstraints').not().or_(x['basicConstraints'].match("^CA:FA"))</code>.</p>
| 0 |
2016-09-13T05:19:51Z
|
[
"python",
"lambda",
"rethinkdb",
"rethinkdb-python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.