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 |
|---|---|---|---|---|---|---|---|---|---|
Removing "\n"s when printing sentences from text file in python?
| 39,339,621
|
<p>I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:</p>
<pre><code>file = open('11.txt','r+')
alice = file.read()
print(alice[:500])
</code></pre>
<p>Output is:</p>
<pre><code>ALICE'S ADVENTURES IN WONDERLAND
Lewis Carroll
THE MILLENNIUM FULCRUM EDITION 3.0
CHAPTER I. Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'
So she was considering in her own mind (as well as she could, for the
hot d
</code></pre>
<p>Now, when I split it into sentences (The assignment was specifically to do this by "splitting at the periods," so it's a very simplified split), I get this:</p>
<pre><code>>>> print(sentences[:5])
["ALICE'S ADVENTURES IN WONDERLAND\n\nLewis Carroll\n\nTHE MILLENNIUM FULCRUM EDITION 3", '0\n\n\n\n\nCHAPTER I', " Down the Rabbit-Hole\n\nAlice was beginning to get very tired of sitting by her sister on the\nbank, and of having nothing to do: once or twice she had peeped into the\nbook her sister was reading, but it had no pictures or conversations in\nit, 'and what is the use of a book,' thought Alice 'without pictures or\nconversations?'\n\nSo she was considering in her own mind (as well as she could, for the\nhot day made her feel very sleepy and stupid), whether the pleasure\nof making a daisy-chain would be worth the trouble of getting up and\npicking the daisies, when suddenly a White Rabbit with pink eyes ran\nclose by her", "\n\nThere was nothing so VERY remarkable in that; nor did Alice think it so\nVERY much out of the way to hear the Rabbit say to itself, 'Oh dear!\nOh dear! I shall be late!' (when she thought it over afterwards, it\noccurred to her that she ought to have wondered at this, but at the time\nit all seemed quite natural); but when the Rabbit actually TOOK A WATCH\nOUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,\nAlice started to her feet, for it flashed across her mind that she had\nnever before seen a rabbit with either a waistcoat-pocket, or a watch\nto take out of it, and burning with curiosity, she ran across the field\nafter it, and fortunately was just in time to see it pop down a large\nrabbit-hole under the hedge", '\n\nIn another moment down went Alice after it, never once considering how\nin the world she was to get out again']
</code></pre>
<p>Where do the extra "\n" characters come from and how can I remove them?</p>
| -1
|
2016-09-06T02:01:53Z
| 39,339,757
|
<p>If you want to replace all the newlines with one space, do this:</p>
<pre><code>import re
new_sentences = [re.sub(r'\n+', ' ', s) for s in sentences]
</code></pre>
| 3
|
2016-09-06T02:26:17Z
|
[
"python",
"split",
"format",
"sentence"
] |
Removing "\n"s when printing sentences from text file in python?
| 39,339,621
|
<p>I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:</p>
<pre><code>file = open('11.txt','r+')
alice = file.read()
print(alice[:500])
</code></pre>
<p>Output is:</p>
<pre><code>ALICE'S ADVENTURES IN WONDERLAND
Lewis Carroll
THE MILLENNIUM FULCRUM EDITION 3.0
CHAPTER I. Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'
So she was considering in her own mind (as well as she could, for the
hot d
</code></pre>
<p>Now, when I split it into sentences (The assignment was specifically to do this by "splitting at the periods," so it's a very simplified split), I get this:</p>
<pre><code>>>> print(sentences[:5])
["ALICE'S ADVENTURES IN WONDERLAND\n\nLewis Carroll\n\nTHE MILLENNIUM FULCRUM EDITION 3", '0\n\n\n\n\nCHAPTER I', " Down the Rabbit-Hole\n\nAlice was beginning to get very tired of sitting by her sister on the\nbank, and of having nothing to do: once or twice she had peeped into the\nbook her sister was reading, but it had no pictures or conversations in\nit, 'and what is the use of a book,' thought Alice 'without pictures or\nconversations?'\n\nSo she was considering in her own mind (as well as she could, for the\nhot day made her feel very sleepy and stupid), whether the pleasure\nof making a daisy-chain would be worth the trouble of getting up and\npicking the daisies, when suddenly a White Rabbit with pink eyes ran\nclose by her", "\n\nThere was nothing so VERY remarkable in that; nor did Alice think it so\nVERY much out of the way to hear the Rabbit say to itself, 'Oh dear!\nOh dear! I shall be late!' (when she thought it over afterwards, it\noccurred to her that she ought to have wondered at this, but at the time\nit all seemed quite natural); but when the Rabbit actually TOOK A WATCH\nOUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,\nAlice started to her feet, for it flashed across her mind that she had\nnever before seen a rabbit with either a waistcoat-pocket, or a watch\nto take out of it, and burning with curiosity, she ran across the field\nafter it, and fortunately was just in time to see it pop down a large\nrabbit-hole under the hedge", '\n\nIn another moment down went Alice after it, never once considering how\nin the world she was to get out again']
</code></pre>
<p>Where do the extra "\n" characters come from and how can I remove them?</p>
| -1
|
2016-09-06T02:01:53Z
| 39,339,761
|
<p>The text uses newlines to delimit sentences as well as fullstops. You have an issue where just replacing the new line characters with an empty string will result in having words without spaces between them. Before you split <code>alice</code> by <code>'.'</code>, I would use something along the lines of @elethan's solution to replace all of the multiple new lines in <code>alice</code> with a <code>'.'</code> Then you could do <code>alice.split('.')</code> and all of the sentences separated with multiple new lines would be split appropriately along with the sentences separated with <code>.</code> initially.</p>
<p>Then your only issue is the decimal point in the version number.</p>
| 0
|
2016-09-06T02:27:00Z
|
[
"python",
"split",
"format",
"sentence"
] |
Removing "\n"s when printing sentences from text file in python?
| 39,339,621
|
<p>I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:</p>
<pre><code>file = open('11.txt','r+')
alice = file.read()
print(alice[:500])
</code></pre>
<p>Output is:</p>
<pre><code>ALICE'S ADVENTURES IN WONDERLAND
Lewis Carroll
THE MILLENNIUM FULCRUM EDITION 3.0
CHAPTER I. Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'
So she was considering in her own mind (as well as she could, for the
hot d
</code></pre>
<p>Now, when I split it into sentences (The assignment was specifically to do this by "splitting at the periods," so it's a very simplified split), I get this:</p>
<pre><code>>>> print(sentences[:5])
["ALICE'S ADVENTURES IN WONDERLAND\n\nLewis Carroll\n\nTHE MILLENNIUM FULCRUM EDITION 3", '0\n\n\n\n\nCHAPTER I', " Down the Rabbit-Hole\n\nAlice was beginning to get very tired of sitting by her sister on the\nbank, and of having nothing to do: once or twice she had peeped into the\nbook her sister was reading, but it had no pictures or conversations in\nit, 'and what is the use of a book,' thought Alice 'without pictures or\nconversations?'\n\nSo she was considering in her own mind (as well as she could, for the\nhot day made her feel very sleepy and stupid), whether the pleasure\nof making a daisy-chain would be worth the trouble of getting up and\npicking the daisies, when suddenly a White Rabbit with pink eyes ran\nclose by her", "\n\nThere was nothing so VERY remarkable in that; nor did Alice think it so\nVERY much out of the way to hear the Rabbit say to itself, 'Oh dear!\nOh dear! I shall be late!' (when she thought it over afterwards, it\noccurred to her that she ought to have wondered at this, but at the time\nit all seemed quite natural); but when the Rabbit actually TOOK A WATCH\nOUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,\nAlice started to her feet, for it flashed across her mind that she had\nnever before seen a rabbit with either a waistcoat-pocket, or a watch\nto take out of it, and burning with curiosity, she ran across the field\nafter it, and fortunately was just in time to see it pop down a large\nrabbit-hole under the hedge", '\n\nIn another moment down went Alice after it, never once considering how\nin the world she was to get out again']
</code></pre>
<p>Where do the extra "\n" characters come from and how can I remove them?</p>
| -1
|
2016-09-06T02:01:53Z
| 39,340,553
|
<pre><code>file = open('11.txt','r+')
file.read().split('\n')
</code></pre>
| 0
|
2016-09-06T04:14:22Z
|
[
"python",
"split",
"format",
"sentence"
] |
creating numpy array with first and last elements different and all other elements the same
| 39,339,646
|
<p>I want to create the following type of array</p>
<pre><code>N = 5 # size of the array
eta = 2
a00 = 1 # first element of array
a0N = 3 # last element of array
# all entries should be 'eta' except the first and the last one
diag = [a00, eta, eta, eta, a0N]
</code></pre>
<p>I know how to create array that has eta as all its entries as follows.</p>
<pre><code>diag = np.zeros(N) + eta
</code></pre>
<p>Will I be able to create what I want using
<code>np.zeros(N)</code> or will I have to use a more low level constructor such as <code>numpy.ndarray</code>? . </p>
| 1
|
2016-09-06T02:07:26Z
| 39,339,760
|
<p>I'm not aware of a built in method for this kind of array. This is a pretty standard way of doing it.</p>
<pre><code>N = 5 # size of the array
eta = 2
a00 = 1 # first element of array
a0N = 3 # last element of array
# make a vector of 'etas', then change the first and last element
diag = np.ones(N,)*eta
diag[0] = a00
diag[-1] = a0N
</code></pre>
<p>Another workaround would be to make a list of the elements in your desired array. Then you can cast it as an array with np.array, as shown:</p>
<pre><code>list_diag = [a00] + [eta for i in range(N-2)] + [a0N]
diag = np.array(list_diag)
</code></pre>
<p>Note: the latter solution might look cute, but will be much slower as N gets larger. </p>
| 3
|
2016-09-06T02:26:33Z
|
[
"python",
"numpy",
"scipy"
] |
Why doesn't the bear(boolean) remain in its position?
| 39,339,647
|
<p>I wanted to add more functionality to exercise 35 of Zed Shaw's LPTHW. The script runs without crashing and allows the player to revisit previous rooms, as I desired. However, in the bear_room the only way the player can get through is to scream at the bear, switching the bear_moved boolean to True.</p>
<p>If the player does this and then goes backward into the start room, it was my intent that the bear_moved boolean remained in the True position, meaning that the bear would still be moved away from the door upon re-entry. </p>
<p>That isn't happening when I run the script; Upon entering the bear_room for the first time I scream at the bear, causing it to move away from the door. I then back out of the room, returning to the start room. When I go back into the bear_room the bear has mysteriously plopped its fat self in front of the door again.</p>
<p>I placed the bear_moved boolean outside of the function just for this purpose--this was the only thing I could come up with to give that extra functionality to the program. </p>
<p>To recap, why doesn't the bear stay moved when I exit the bear_room and re-enter? How can I achieve the functionality I'm aiming for?</p>
<pre><code>from sys import exit
bear_moved = False
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if next.isdigit():
if int(next) > 101:
dead("You greedy bastard!")
elif int(next) < 101:
print "Nice, you're not greedy! You win!"
exit(0)
else:
pass
elif 'back' in next or 'backtrack' in next:
bear_room(bear_moved)
else:
print "Type a number!"
gold_room()
def bear_room(bear_moved):
if bear_moved == False:
print "There's a bear in here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
elif bear_moved == True:
print "The bear has moved away from the door."
else:
pass
next = raw_input("> ")
if 'honey' in next:
dead("The looks at you and then slaps your face off.")
elif 'taunt' in next or 'tease' in next or 'scream' in next or 'yell' in next and bear_moved == False:
bear_moved = True
bear_room(bear_moved)
elif 'taunt' in next or 'tease' in next or 'scream' in next or 'yell' in next and bear_moved == True:
dead("The bear flies into a rage and chews your leg off.")
elif 'open' in next and bear_moved == True:
gold_room()
elif 'open' in next and bear_moved == False:
dead("The bear, still standing in the way, lunges up and rips your throat out.")
elif 'back' in next or 'backtrack' in next:
start()
else:
print "I got no idea what this means."
bear_room(bear_moved)
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input("> ").lower()
if 'flee' in next:
start()
elif 'head' in next:
dead("Well that was tasy!")
else:
cthuhlu_room()
def dead(why):
print why, "Game Over!"
exit(0)
def start():
print "You're in a dark room."
print "You have no idea who you are or how you got here."
print "Your head is throbbing..."
print "There are two doors, one to your left, and one to your right."
print "Which door do you take?"
next = raw_input("> ").lower()
if 'left' in next:
bear_room(bear_moved)
elif 'right' in next:
cthulhu_room()
else:
start()
start()
</code></pre>
| 0
|
2016-09-06T02:07:39Z
| 39,353,929
|
<p>Here's the top of your <strong>bear_room</strong> function, with the global functionality fixed. You still have to appropriately alter the calls to the routine.</p>
<p>You are still learning about Boolean values; note the changes I made in your tests. You don't have to test <strong>bear_moved == True</strong>; the variable itself <em>is</em> a True/False value. Comparing it against <strong>True</strong> does nothing. Comparing it against <strong>False</strong> is simply the <strong>not</strong> operation. I deleted your <strong>else: pass</strong> because the only way to reach that spot is if bear_moved is <strong>NaN</strong> (not a number), a value you shouldn't see in this program. Logically, you couldn't get to that clause at all.</p>
<p>Of course, there are still improvements to make in your program: fix the spelling and grammar errors, make the logic flow a little more cleanly (did you do any sort of flow chart for this?), and nest if statements to save work and reading time.</p>
<pre><code>def bear_room():
global bear_moved
if not bear_moved:
print "There's a bear in here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
else:
print "The bear has moved away from the door."
</code></pre>
| 2
|
2016-09-06T16:38:02Z
|
[
"python",
"recursion",
"boolean",
"global",
"functionality"
] |
Why doesn't the bear(boolean) remain in its position?
| 39,339,647
|
<p>I wanted to add more functionality to exercise 35 of Zed Shaw's LPTHW. The script runs without crashing and allows the player to revisit previous rooms, as I desired. However, in the bear_room the only way the player can get through is to scream at the bear, switching the bear_moved boolean to True.</p>
<p>If the player does this and then goes backward into the start room, it was my intent that the bear_moved boolean remained in the True position, meaning that the bear would still be moved away from the door upon re-entry. </p>
<p>That isn't happening when I run the script; Upon entering the bear_room for the first time I scream at the bear, causing it to move away from the door. I then back out of the room, returning to the start room. When I go back into the bear_room the bear has mysteriously plopped its fat self in front of the door again.</p>
<p>I placed the bear_moved boolean outside of the function just for this purpose--this was the only thing I could come up with to give that extra functionality to the program. </p>
<p>To recap, why doesn't the bear stay moved when I exit the bear_room and re-enter? How can I achieve the functionality I'm aiming for?</p>
<pre><code>from sys import exit
bear_moved = False
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if next.isdigit():
if int(next) > 101:
dead("You greedy bastard!")
elif int(next) < 101:
print "Nice, you're not greedy! You win!"
exit(0)
else:
pass
elif 'back' in next or 'backtrack' in next:
bear_room(bear_moved)
else:
print "Type a number!"
gold_room()
def bear_room(bear_moved):
if bear_moved == False:
print "There's a bear in here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
elif bear_moved == True:
print "The bear has moved away from the door."
else:
pass
next = raw_input("> ")
if 'honey' in next:
dead("The looks at you and then slaps your face off.")
elif 'taunt' in next or 'tease' in next or 'scream' in next or 'yell' in next and bear_moved == False:
bear_moved = True
bear_room(bear_moved)
elif 'taunt' in next or 'tease' in next or 'scream' in next or 'yell' in next and bear_moved == True:
dead("The bear flies into a rage and chews your leg off.")
elif 'open' in next and bear_moved == True:
gold_room()
elif 'open' in next and bear_moved == False:
dead("The bear, still standing in the way, lunges up and rips your throat out.")
elif 'back' in next or 'backtrack' in next:
start()
else:
print "I got no idea what this means."
bear_room(bear_moved)
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input("> ").lower()
if 'flee' in next:
start()
elif 'head' in next:
dead("Well that was tasy!")
else:
cthuhlu_room()
def dead(why):
print why, "Game Over!"
exit(0)
def start():
print "You're in a dark room."
print "You have no idea who you are or how you got here."
print "Your head is throbbing..."
print "There are two doors, one to your left, and one to your right."
print "Which door do you take?"
next = raw_input("> ").lower()
if 'left' in next:
bear_room(bear_moved)
elif 'right' in next:
cthulhu_room()
else:
start()
start()
</code></pre>
| 0
|
2016-09-06T02:07:39Z
| 39,355,176
|
<p>I researched even more about Python's global and local variables. I now realize that I was changing a local variable within the function, not the global bear_moved. Which is exactly why the bear had plopped its fat self back in front of the door upon re-entry.</p>
<p>After stripping the parameter from the bear_room() function and making the bear_moved reference inside of it global, the function worked just as I had originally wanted it to. I also replaced the bear_moved == (boolean) expressions with simply bear_moved or not bear_moved.</p>
<pre><code>from sys import exit
bear_moved = False
# Exercise 35 of Zed Shaw's LPTHW
# Player can now revisit previous rooms
# The bear_room function uses simple recursion
# instead of the while loop of the original script
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if next.isdigit():
if int(next) > 101:
dead("You greedy bastard!")
elif int(next) < 101:
print "Nice, you're not greedy! You win!"
exit(0)
else:
pass
elif 'back' in next or 'backtrack' in next:
bear_room()
else:
print "Type a number!"
gold_room()
def bear_room():
"""Globalizing bear_moved variable
and stripping parameter as advised."""
global bear_moved
if not bear_moved:
print "There's a bear in here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
elif bear_moved:
print "The bear has moved away from the door."
next = raw_input("> ")
if 'honey' in next:
dead("The looks at you and then slaps your face off.")
elif 'taunt' in next and not bear_moved:
bear_moved = True
bear_room()
elif 'taunt' in next and bear_moved:
dead("The bear flies into a rage and chews your leg off.")
elif 'open' in next and bear_moved:
gold_room()
elif 'open' in next and not bear_moved:
dead("The bear, still standing in the way, lunges up and rips your throat out.")
elif 'back' in next or 'backtrack' in next:
start()
else:
print "I got no idea what this means."
bear_room()
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input("> ").lower()
if 'flee' in next or 'run' in next:
start()
elif 'head' in next:
dead("Well that was tasy!")
else:
cthulhu_room()
def dead(why):
print why, "Game Over!"
exit(0)
def start():
print "You're in a dark room."
print "You have no idea who you are or how you got here."
print "Your head is throbbing..."
print "There are two doors, one to your left, and one to your right."
print "Which door do you take?"
next = raw_input("> ").lower()
if 'left' in next:
bear_room()
elif 'right' in next:
cthulhu_room()
else:
start()
start()
</code></pre>
| 0
|
2016-09-06T18:01:07Z
|
[
"python",
"recursion",
"boolean",
"global",
"functionality"
] |
Display Python 2D list without commas, brackets, etc
| 39,339,703
|
<p>I want to display a 2D list without brackets, commas, or any stuffs. I printed the content of the list using the following code: </p>
<pre><code>print(ncA_string[a][0],ncA_string[a][1],ncA_string[a][2],ncA_string[a][3])
</code></pre>
<p>Unfortunately, however, it is showing the commas, and brackets.
<a href="http://i.stack.imgur.com/bVV1s.png" rel="nofollow">Here's the picture of the output</a></p>
<p>I wanna display it like this: <code>((((((ab)c)d)e)</code></p>
<p>I'm new to using python and I've tried using the join map but i couldn't understand it yet. </p>
<p>Can anyone teach me how to?? </p>
<p>Thank you so much :))</p>
| -4
|
2016-09-06T02:17:19Z
| 39,340,011
|
<p>You need to flatten <code>ncA_string[a]</code> first. Try to use <code>flatten</code> function from this answer <a href="http://stackoverflow.com/a/12472461/1112457">http://stackoverflow.com/a/12472461/1112457</a> . Then you can unpack the flattened list as arguments to the <code>print</code> function:</p>
<pre><code>print(*flatten(ncA_string[a]))
</code></pre>
<p>or if you want to print it without spaces:</p>
<pre><code>print(''.join(flatten(ncA_string[a])))
</code></pre>
| 0
|
2016-09-06T03:02:15Z
|
[
"python",
"list"
] |
How do I run Pygame on Pycharm
| 39,339,709
|
<p>I am trying to run pygame on the PyCharm IDE, I have installed the latest version of pygame for python 3.5 and have added it to the project interpreter. I installed pygame from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame</a> and copied it too <code>python35-32/Scripts/</code>. The test program below runs fine in the python shell but I want to run it from PyCharm.</p>
<p>I have been trying to solve this for the past hour and I've hit a wall.
When I run this simple test program to see if pygame is working: </p>
<pre><code>import pygame
pygame.init()
pygame.display.set_mode((800, 800))
</code></pre>
<p>I get this error:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/jerem/PycharmProjects/Games/hello_pygame.py", line 1, in <module>
import pygame
File "C:\Users\jerem\AppData\Roaming\Python\Python35\site-packages\pygame\__init__.py", line 141, in <module>
from pygame.base import *
ImportError: No module named 'pygame.base'
</code></pre>
<p>Any help would be greatly appreiciated!
Thanks again,
JC</p>
| 0
|
2016-09-06T02:18:27Z
| 39,339,783
|
<p>Follow the instructions provided here. I think its related to the problem you are having on pygame and PyCharm on windows.
<a href="http://stackoverflow.com/questions/35609592/how-do-i-download-pygame-for-python-3-5-1">How do I download Pygame for Python 3.5.1?</a></p>
| 0
|
2016-09-06T02:29:36Z
|
[
"python",
"python-3.x",
"pygame",
"pycharm",
"failed-installation"
] |
How does this for, in generator work in Python 2.7.x
| 39,339,711
|
<p>I'm aware of the <code>for x in list</code> loop in Python, but I stumbled on a type of generator whose documentation I couldn't find. I found out that the example below only works if the lists inside the list <code>a</code> are of length 2, or it gives an unpacking error, so I suspect some kind of 2-tuple or dict-related unpacker may be at play. Can somebody explain to me how this generator syntax works?</p>
<pre><code>$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [[1,2],[3,4],[5,6]]
>>> (b for c, b in a)
<generator object <genexpr> at 0x1071abaa0>
>>> [x for x in (b for c, b in a)]
[2, 4, 6]
</code></pre>
<p>I ran into it in a project that used this generator in a call to <code>min</code>. Originally I thought it was multiple args being passed in, but the syntax made no sense, and testing it individually revealed a generator.</p>
<p><a href="https://github.com/bigbighd604/Python/blob/master/graph/Ford-Fulkerson.py#L59" rel="nofollow">https://github.com/bigbighd604/Python/blob/master/graph/Ford-Fulkerson.py#L59</a></p>
| 1
|
2016-09-06T02:18:30Z
| 39,339,744
|
<p>Don't be fooled by the comma in <code>c, b</code>. In Python, commas -- not parentheses -- are what defines a tuple. Your code is equivalent to <code>[x for x in (b for (c, b) in a)]</code>, which iterates through the elements of <code>a</code>, assigning <code>c</code> to the first element of each two-element list in <code>a</code> and <code>b</code> to the second, and then assigning <code>b</code> to <code>x</code>. If <code>a</code> had an element that was not a two-element iterable, you would get a <code>ValueError</code>.</p>
| 4
|
2016-09-06T02:23:44Z
|
[
"python",
"python-2.7"
] |
How does this for, in generator work in Python 2.7.x
| 39,339,711
|
<p>I'm aware of the <code>for x in list</code> loop in Python, but I stumbled on a type of generator whose documentation I couldn't find. I found out that the example below only works if the lists inside the list <code>a</code> are of length 2, or it gives an unpacking error, so I suspect some kind of 2-tuple or dict-related unpacker may be at play. Can somebody explain to me how this generator syntax works?</p>
<pre><code>$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [[1,2],[3,4],[5,6]]
>>> (b for c, b in a)
<generator object <genexpr> at 0x1071abaa0>
>>> [x for x in (b for c, b in a)]
[2, 4, 6]
</code></pre>
<p>I ran into it in a project that used this generator in a call to <code>min</code>. Originally I thought it was multiple args being passed in, but the syntax made no sense, and testing it individually revealed a generator.</p>
<p><a href="https://github.com/bigbighd604/Python/blob/master/graph/Ford-Fulkerson.py#L59" rel="nofollow">https://github.com/bigbighd604/Python/blob/master/graph/Ford-Fulkerson.py#L59</a></p>
| 1
|
2016-09-06T02:18:30Z
| 39,339,770
|
<p>Starting from the inside, we are creating a generator expression from list a:</p>
<pre><code>a = [[1,2],[3,4],[5,6]]
</code></pre>
<p>So, Let us look at that one alone:</p>
<pre><code>(b for c, b in a)
</code></pre>
<p>So, if you look back at list <code>a</code>, we have a list of lists, where each sub-list is just two items. So, what is happening here with your generator expression, is that <code>c, b</code> are representing each of the unpacked values in your sub-list as a tuple. However, if you look at the expression, we are only taking <code>b</code>, which is why the result will end up being: </p>
<pre><code>2, 4, 6
</code></pre>
<p>Then moving outward, we are then just creating a list-comprehension from that generator expression:</p>
<pre><code>[x for x in (b for c, b in a)]
</code></pre>
<p>Ending in a list:</p>
<pre><code>[2, 4, 6]
</code></pre>
<p>Actually, if you are looking to get a list out of that expression, you can just do:</p>
<pre><code>list(b for c, b in a)
</code></pre>
| 1
|
2016-09-06T02:28:12Z
|
[
"python",
"python-2.7"
] |
Backslash escaping is not working in Python
| 39,339,743
|
<p>I want Python interpreter to show me <code>\'</code> as a calculated value. I tried typing <code>"\\'"</code> and it returned me the same thing. If I try <code>"\'"</code> then the backslash is not shown anymore after I hit return. How do I get it to show the backslash like this after I hit return- <code>\'</code> ?</p>
<h3>Additional question</h3>
<p>This is exact question I am not understanding:
Expression --> </p>
<blockquote>
<p>'C' + <code></code> + 'D'</p>
</blockquote>
<p>Calculated Value --></p>
<blockquote>
<p>'C\'D'</p>
</blockquote>
<p>Find the missing literal </p>
| 1
|
2016-09-06T02:23:33Z
| 39,339,769
|
<p><code>print("\'")</code></p>
<p>repr of a string will never put out a single backslash. repr smartly picks quotes to avoid backslashes. You can get a \' to come out if you do something like '\'"'</p>
| 0
|
2016-09-06T02:28:07Z
|
[
"python"
] |
Backslash escaping is not working in Python
| 39,339,743
|
<p>I want Python interpreter to show me <code>\'</code> as a calculated value. I tried typing <code>"\\'"</code> and it returned me the same thing. If I try <code>"\'"</code> then the backslash is not shown anymore after I hit return. How do I get it to show the backslash like this after I hit return- <code>\'</code> ?</p>
<h3>Additional question</h3>
<p>This is exact question I am not understanding:
Expression --> </p>
<blockquote>
<p>'C' + <code></code> + 'D'</p>
</blockquote>
<p>Calculated Value --></p>
<blockquote>
<p>'C\'D'</p>
</blockquote>
<p>Find the missing literal </p>
| 1
|
2016-09-06T02:23:33Z
| 39,339,772
|
<p>Here are two ways to get <code>\'</code>:</p>
<pre><code>>>> print("\\'")
\'
>>> print(r"\'")
\'
</code></pre>
<h3>Discussion</h3>
<pre><code>>>> print("\'")
'
</code></pre>
<p>The above prints out a single <code>'</code> because an escaped <code>'</code> is just a <code>'</code>.</p>
<pre><code>>>> print(r"\'")
\'
</code></pre>
<p>The above prints the backslash because <code>r</code> prevents interpretation of escapes.</p>
<pre><code>>>> print("\\'")
\'
</code></pre>
<p>The above prints <code>\'</code> because an escaped backslash is a backslash.</p>
<h3>Other forms of strings</h3>
<p>Using unicode-strings (under python2):</p>
<pre><code>>>> print(u"\\'")
\'
>>> print(ur"\'")
\'
</code></pre>
<p>Using byte-codes (also python 2):</p>
<pre><code>>>> print(b"\\'")
\'
>>> print(br"\'")
\'
</code></pre>
<h3>Answer for additional question</h3>
<p>Using the principles described above, the answer for the additional question is:</p>
<pre><code>>>> print('C' + "\\'" 'D')
C\'D
>>> print('C' + r"\'" 'D')
C\'D
</code></pre>
| 7
|
2016-09-06T02:28:26Z
|
[
"python"
] |
Celery Worker - Consume from Queue matching a regex
| 39,339,804
|
<p><strong>Background</strong></p>
<p>Celery worker can be started against a set of queues using -Q flag. E.g. </p>
<blockquote>
<p>-Q dev.Q1,dev.Q2,dev.Q3</p>
</blockquote>
<p>So far I have seen examples where all the queue names are explicitly listed as comma separated values. It is troublesome if I have a very long list.</p>
<p><strong>Question</strong></p>
<p>Is there a way I can specify queue names as a regex & celery worker will start consuming from all queues satisfying that regex.</p>
<p>E.g.</p>
<blockquote>
<p>-Q dev.*</p>
</blockquote>
<p>This should consume from all queuess starting with dev i.e. dev.Q1, dev.Q2, dev.Q3. <em>But what I have seen is - it creates a queue dev.</em>.*</p>
<p>Also how can I tune the regex so that it doesn't pick ERROR queues e.g. dev.Q1.ERROR, dev.Q2.ERROR.</p>
| 0
|
2016-09-06T02:32:35Z
| 39,340,088
|
<p>Something along these lines would work: (\b(dev.)(\w+)).
Then refer to the second group for the stuff after "dev.".</p>
<p>You'll need to set it up to capturing repeated instances if you want to get multiple.</p>
| 0
|
2016-09-06T03:11:30Z
|
[
"python",
"celery",
"django-celery"
] |
How to get rows with the max value by using Python?
| 39,339,907
|
<p>I have R code to use data table to merger the rows with same FirstName and LastName but selecting the max value for specified columns(e.g. Score1, Score2, Score3). The input/output is as follows:</p>
<p><Strong>Input:</Strong></p>
<pre>
FirstName LastName Score1 Score2 Score3
fn1 ln1 41 88 50
fn1 ln1 72 66 77
fn1 ln1 69 72 90
fn2 ln2 80 81 73
fn2 ln2 59 91 66
fn3 ln3 75 80 66
</pre>
<p><Strong>Output:</Strong></p>
<pre>
FirstName LastName Score1 Score2 Score3
fn1 ln1 72 88 90
fn2 ln2 80 91 73
fn3 ln3 75 80 66
</pre>
<p>Now I want to migrate the R program to Spark. How can I do this by using Python?</p>
| 3
|
2016-09-06T02:47:04Z
| 39,340,129
|
<p>Here is the way to do it with in-built packages of python:</p>
<pre><code>import csv
from collections import OrderedDict
newdata = OrderedDict()
with open('test.csv', 'rb') as testr:
testreader = csv.reader(testr)
for row in testreader:
name = row[0]+ '-' + row[1]
if name in newdata:
newdata[name] = [max(existdata, readdata) for existdata, readdata in zip(newdata[name], row[2:])]
else:
newdata[name] = row[2:]
with open('newdata.csv', 'wb') as testw:
testwriter = csv.writer(testw)
for name, data in newdata.iteritems():
testwriter.writerow(name.split('-') + data)
</code></pre>
<p>Best way is to do it is with Pandas, will post in a while.</p>
<h1>EDIT:</h1>
<p>Here is the pandas code:</p>
<pre><code>import pandas
readfile = pandas.read_csv('test.csv') # assuming your CSV is same directory as program
print readfile
</code></pre>
<p><a href="http://i.stack.imgur.com/cGDIK.png" rel="nofollow"><img src="http://i.stack.imgur.com/cGDIK.png" alt="actual data"></a></p>
<pre><code>max_readfile = readfile.groupby(['FirstName', 'LastName']).max()
print max_readfile
</code></pre>
<p>output:</p>
<p><a href="http://i.stack.imgur.com/ledll.png" rel="nofollow"><img src="http://i.stack.imgur.com/ledll.png" alt="pandas output"></a></p>
<p>** @user2241910 quickly posted the pandas solution :)</p>
| 1
|
2016-09-06T03:16:22Z
|
[
"python",
"apache-spark"
] |
How to get rows with the max value by using Python?
| 39,339,907
|
<p>I have R code to use data table to merger the rows with same FirstName and LastName but selecting the max value for specified columns(e.g. Score1, Score2, Score3). The input/output is as follows:</p>
<p><Strong>Input:</Strong></p>
<pre>
FirstName LastName Score1 Score2 Score3
fn1 ln1 41 88 50
fn1 ln1 72 66 77
fn1 ln1 69 72 90
fn2 ln2 80 81 73
fn2 ln2 59 91 66
fn3 ln3 75 80 66
</pre>
<p><Strong>Output:</Strong></p>
<pre>
FirstName LastName Score1 Score2 Score3
fn1 ln1 72 88 90
fn2 ln2 80 91 73
fn3 ln3 75 80 66
</pre>
<p>Now I want to migrate the R program to Spark. How can I do this by using Python?</p>
| 3
|
2016-09-06T02:47:04Z
| 39,340,143
|
<p>As suggested by durbachit, you'll want to use pandas.</p>
<pre><code>import pandas as pd
df = pd.read_csv(**your file here**)
max_df = df.groupby(by=['FirstName','LastName']).max()
</code></pre>
<p>And max_df will be your desired output. <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby" rel="nofollow">Docs for pandas groupby.</a></p>
| 2
|
2016-09-06T03:17:48Z
|
[
"python",
"apache-spark"
] |
How to get rows with the max value by using Python?
| 39,339,907
|
<p>I have R code to use data table to merger the rows with same FirstName and LastName but selecting the max value for specified columns(e.g. Score1, Score2, Score3). The input/output is as follows:</p>
<p><Strong>Input:</Strong></p>
<pre>
FirstName LastName Score1 Score2 Score3
fn1 ln1 41 88 50
fn1 ln1 72 66 77
fn1 ln1 69 72 90
fn2 ln2 80 81 73
fn2 ln2 59 91 66
fn3 ln3 75 80 66
</pre>
<p><Strong>Output:</Strong></p>
<pre>
FirstName LastName Score1 Score2 Score3
fn1 ln1 72 88 90
fn2 ln2 80 91 73
fn3 ln3 75 80 66
</pre>
<p>Now I want to migrate the R program to Spark. How can I do this by using Python?</p>
| 3
|
2016-09-06T02:47:04Z
| 39,340,205
|
<pre><code>import pandas
rows = pandas.read_csv('rows.csv', delim_whitespace=True)
rows.groupby(['FirstName', 'LastName']).max()
</code></pre>
| 0
|
2016-09-06T03:27:26Z
|
[
"python",
"apache-spark"
] |
Pandas - dropping rows with missing data not working using .isnull(), notnull(), dropna()
| 39,339,935
|
<p>This is really weird. I have tried several ways of dropping rows with missing data from a pandas dataframe, but none of them seem to work.
This is the code (I just uncomment one of the methods used - but these are the three that I used in different modifications - this is the latest):</p>
<pre><code>import pandas as pd
Test = pd.DataFrame({'A':[1,2,3,4,5],'B':[1,2,'NaN',4,5],'C':[1,2,3,'NaT',5]})
print(Test)
#Test = Test.ix[Test.C.notnull()]
#Test = Test.dropna()
Test = Test[~Test[Test.columns.values].isnull()]
print "And now"
print(Test)
</code></pre>
<p>But in all cases, all I get is this:</p>
<pre><code> A B C
0 1 1 1
1 2 2 2
2 3 NaN 3
3 4 4 NaT
4 5 5 5
And now
A B C
0 1 1 1
1 2 2 2
2 3 NaN 3
3 4 4 NaT
4 5 5 5
</code></pre>
<p>Is there any mistake that I am making? or what is the problem? Ideally, I would like to get this:</p>
<pre><code> A B C
0 1 1 1
1 2 2 2
4 5 5 5
</code></pre>
| 2
|
2016-09-06T02:50:00Z
| 39,340,010
|
<p>Your example DF has <code>NaN</code> and <code>NaT</code> as strings which <code>.dropna</code>, <code>.notnull</code> and co. won't consider falsey, so given your example you can use...</p>
<pre><code>df[~df.isin(['NaN', 'NaT']).any(axis=1)]
</code></pre>
<p>Which gives you:</p>
<pre><code> A B C
0 1 1 1
1 2 2 2
4 5 5 5
</code></pre>
<p>If you had a DF such as (note of the use of <code>np.nan</code> and <code>np.datetime64('NaT')</code> instead of strings:</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3,4,5],'B':[1,2,np.nan,4,5],'C':[1,2,3,np.datetime64('NaT'),5]})
</code></pre>
<p>Then running <code>df.dropna()</code> which give you:</p>
<pre><code> A B C
0 1 1.0 1
1 2 2.0 2
4 5 5.0 5
</code></pre>
<p>Note that column <code>B</code> is now a <code>float</code> instead of an integer as that's required to store <code>NaN</code> values.</p>
| 2
|
2016-09-06T03:02:02Z
|
[
"python",
"pandas"
] |
Pandas - dropping rows with missing data not working using .isnull(), notnull(), dropna()
| 39,339,935
|
<p>This is really weird. I have tried several ways of dropping rows with missing data from a pandas dataframe, but none of them seem to work.
This is the code (I just uncomment one of the methods used - but these are the three that I used in different modifications - this is the latest):</p>
<pre><code>import pandas as pd
Test = pd.DataFrame({'A':[1,2,3,4,5],'B':[1,2,'NaN',4,5],'C':[1,2,3,'NaT',5]})
print(Test)
#Test = Test.ix[Test.C.notnull()]
#Test = Test.dropna()
Test = Test[~Test[Test.columns.values].isnull()]
print "And now"
print(Test)
</code></pre>
<p>But in all cases, all I get is this:</p>
<pre><code> A B C
0 1 1 1
1 2 2 2
2 3 NaN 3
3 4 4 NaT
4 5 5 5
And now
A B C
0 1 1 1
1 2 2 2
2 3 NaN 3
3 4 4 NaT
4 5 5 5
</code></pre>
<p>Is there any mistake that I am making? or what is the problem? Ideally, I would like to get this:</p>
<pre><code> A B C
0 1 1 1
1 2 2 2
4 5 5 5
</code></pre>
| 2
|
2016-09-06T02:50:00Z
| 39,340,141
|
<p>Try this on orig data: </p>
<pre><code>Test.replace(["NaN", 'NaT'], np.nan, inplace = True)
Test = Test.dropna()
Test
</code></pre>
<p>Or Modify data and do this </p>
<pre><code>import pandas as pd
Test = pd.DataFrame({'A':[1,2,3,4,5],'B':[1,2,np.nan,4,5],'C':[1,2,3,pd.NaT,5]})
print(Test)
Test = Test.dropna()
print(Test)
A B C
0 1 1.0 1
1 2 2.0 2
4 5 5.0 5
</code></pre>
| 1
|
2016-09-06T03:17:34Z
|
[
"python",
"pandas"
] |
Regex - Match string with or without suffix, but without including it in match group
| 39,339,957
|
<p>I'm currently trying to make a text message command server (basically, I send a text to google voice, that gets forwarded to my email, I use a python IMAP library to access the message, and I parse it), and I have an interesting problem. Sometimes, when a text comes through, the string </p>
<pre><code>--
Sent using SMS-to-email. Reply to this email to text the sender back and save on SMS fees.
https://www.google.com/voice/
</code></pre>
<p>is appended to the text message, which causes errors when parsing the command. Right now, to detect commands, I use the following regex (which is multiline and case-sensitive due to certain commands such as a timed send command that may use multiple lines):</p>
<pre><code>^/(randomfact) *(\S*)\s*$
</code></pre>
<p>But since the string telling me it was sent through SMS to email comes through once in a while, a match doesn't get detected. Using the <code>print</code> function of python, the message is shown as follows:</p>
<pre><code>/randomfact\r\n\r\n--\r\nSent using SMS-to-email. Reply to this email to text the sender back and \r\nsave on SMS fees.\r\nhttps://www.google.com/voice/
</code></pre>
<p>Right now, to combat that issue, I have tried doing this:</p>
<pre><code>^/(randomfact)\s*(\d*)(?=\n\n--\nSent using SMS-to-email\. Reply to this email to text the sender back and save on SMS fees\.\nhttps://www\.google\.com/voice/)
</code></pre>
<p>But it only works if the string IS appended to the command. If it isn't, then the regex fails. My question is: Is there any way to exclude that string from any regex matches, whether it exists in the string or not?</p>
| 0
|
2016-09-06T02:53:51Z
| 39,340,116
|
<p>If I understand your problem correctly, you are filtering out the optional signature of the message. In python you should be able to set the single line regex flag (i.e. <code>re.S</code>), and use the following regex to capture the desired content.</p>
<pre><code>regex = re.compile(r'(.+)(?=--)|(.+)', r.S)
</code></pre>
| 0
|
2016-09-06T03:14:52Z
|
[
"python",
"regex"
] |
Regex - Match string with or without suffix, but without including it in match group
| 39,339,957
|
<p>I'm currently trying to make a text message command server (basically, I send a text to google voice, that gets forwarded to my email, I use a python IMAP library to access the message, and I parse it), and I have an interesting problem. Sometimes, when a text comes through, the string </p>
<pre><code>--
Sent using SMS-to-email. Reply to this email to text the sender back and save on SMS fees.
https://www.google.com/voice/
</code></pre>
<p>is appended to the text message, which causes errors when parsing the command. Right now, to detect commands, I use the following regex (which is multiline and case-sensitive due to certain commands such as a timed send command that may use multiple lines):</p>
<pre><code>^/(randomfact) *(\S*)\s*$
</code></pre>
<p>But since the string telling me it was sent through SMS to email comes through once in a while, a match doesn't get detected. Using the <code>print</code> function of python, the message is shown as follows:</p>
<pre><code>/randomfact\r\n\r\n--\r\nSent using SMS-to-email. Reply to this email to text the sender back and \r\nsave on SMS fees.\r\nhttps://www.google.com/voice/
</code></pre>
<p>Right now, to combat that issue, I have tried doing this:</p>
<pre><code>^/(randomfact)\s*(\d*)(?=\n\n--\nSent using SMS-to-email\. Reply to this email to text the sender back and save on SMS fees\.\nhttps://www\.google\.com/voice/)
</code></pre>
<p>But it only works if the string IS appended to the command. If it isn't, then the regex fails. My question is: Is there any way to exclude that string from any regex matches, whether it exists in the string or not?</p>
| 0
|
2016-09-06T02:53:51Z
| 39,340,314
|
<pre><code>def remove_footer(incoming_str):
footer = '''
--
Sent using SMS-to-email. Reply to this email to text the sender back and save on SMS fees.
https://www.google.com/voice/'''
if incoming_str[-len(footer):] == footer:
return incoming_str[:-len(footer)]
else:
return incoming_str
</code></pre>
<blockquote>
<p>Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.</p>
</blockquote>
| 0
|
2016-09-06T03:43:21Z
|
[
"python",
"regex"
] |
Django customize model fields to show on template
| 39,339,962
|
<p>I'm in a weird situation. I have following model. On a template i render only name and author. The thing is there is <strong>edit display</strong> button, when click on edit display. It should show all the fields name to choose. When i choose fields and save table's element should be updated as chosen fields.</p>
<p>models.py</p>
<pre><code>class Finding(models.Model):
name = models.CharField()
isbn = models.CharField()
author = models.ForeignKey()
created = models.DateTimeField()
shop = models.ManyToManyField()
</code></pre>
<p>template(findings.html)</p>
<pre><code><table>
<tr>
<td>{{name}}</td>
<td>{{author}}</td>
</tr>
</table>
</code></pre>
<p>I was thinking about using a session. But this should be dynamic and permanent. Every user may change showing fields according to their preference. How can i achieve this.</p>
| 0
|
2016-09-06T02:54:20Z
| 39,343,786
|
<p>You can create a checkedbox form and handle the values in the view to return appropriate html content, for example (form):</p>
<pre><code>class CheckBox(forms.Form):
name = forms.BooleanField(required=False)
</code></pre>
<p>View:</p>
<pre><code>def your_view(request):
form = MyForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
if request.POST["name"]:
name = 1
if request.POST["author"]:
author = 1
return render(request, 'app/findings.html', {'name':name, 'author':author})
</code></pre>
<p>Then in your template, you can use django template if statement to check which has been selected, for example:</p>
<pre><code>{% if name == 1 %}
<td>{{name}}</td>
{% endif %}
{% if author == 1 %}
<td>{{author}}</td>
{% endif %}
</code></pre>
<p>I hope this gives you some direction.</p>
| 0
|
2016-09-06T08:09:20Z
|
[
"python",
"django"
] |
Screenshot from a user's mouse input with python
| 39,340,002
|
<p>So i want to implement a global and partial screenshot tool (like snipping tool in Windows) with python. I want user to input the area that he wants to screenshot with mouse. I can use pyscreenshot module but how can i manipulate the input on :</p>
<pre><code>im=ImageGrab.grab(bbox=(10,10,510,510)) # X1,Y1,X2,Y2
</code></pre>
<p>in the example given?</p>
<p>p.s. <a href="https://github.com/ponty/pyscreenshot" rel="nofollow">https://github.com/ponty/pyscreenshot</a> module's repository</p>
| 0
|
2016-09-06T03:00:07Z
| 39,340,066
|
<p>You could do something like</p>
<pre><code>cursor = X.NONE
self.window.grab_pointer(1,X.PointerMotionMask|X.ButtonReleaseMask|X.ButtonPressMask,X.GrabModeAsync, X.GrabModeAsync, X.NONE, cursor, X.CurrentTime)
</code></pre>
<p>See a complete example <a href="https://gist.github.com/initbrain/6628609" rel="nofollow">here</a> </p>
| 0
|
2016-09-06T03:08:48Z
|
[
"python",
"screenshot"
] |
How to match a sentence exactly, rather than substring match
| 39,340,046
|
<p>So I created a simple reddit bot using PRAW:</p>
<pre><code>import praw
import time
from praw.helpers import comment_stream
r = praw.Reddit("han_solo_response")
r.login()
target_text = "I love you"
response_text = "I know"
processed = []
while True:
for c in comment_stream(r, 'all'):
if target_text in c.body and c.id not in processed:
#if find comment not in cache
c.reply(response_text)
processed.append(c.id) #then push the response
time.sleep(20)
</code></pre>
<p>It generates the han solo response " i know" every time someone anywhere on reddit posts " i love you" per the famous star wars movie exchange. It is working now but it is catching anything containing "i love you" eg i had to delete one comment where the guy was saying " i love your car".</p>
<p>How can I limit its trigger to precisely "I love you", not "your" or any other word containing "you", or for that matter, make it so that the response is only triggered by the standalone phrase, not when it appears within the context of a sentence.</p>
| 0
|
2016-09-06T03:06:05Z
| 39,340,078
|
<p>This line:</p>
<p><code>if target_text in c.body and c.id not in processed:</code></p>
<p>should be:</p>
<p><code>if target_text == c.body and c.id not in processed:</code></p>
<p>If you want to make it case-insensitive:</p>
<p><code>target_text = "i love you"</code></p>
<p>and</p>
<p><code>if target_text == c.body.lower() and c.id not in processed:</code></p>
| 0
|
2016-09-06T03:10:21Z
|
[
"python",
"bots",
"reddit"
] |
UnicodeDecodeError while dumping dictionary to file using json dump
| 39,340,074
|
<p>I have a dictionary, created from reading the windows registry where keys of dictionary are registry keys and corresponding values are the values of the same key in dictionary.
Now, I am trying to dump to a file using <code>json.dump()</code>. But, this gives me two different errors on two different systems. I am unaware about the content of dictionary, but it has unicode values in it. I am opening the file in 'ab' mode to dump data on to same.</p>
<pre><code>with open(file_path, 'ab') as fp:
json.dump(reg_dict, fp)
</code></pre>
<p>The below errors are observed :-</p>
<pre><code>UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3: invalid start byte
</code></pre>
<p>And </p>
<pre><code>UnicodeDecodeError: 'utf8' codec can't decode byte 0xf1 in position 21: invalid continuation byte
</code></pre>
<p>Attaching the image for both the errors. I am not sure how can I resolve this, neither why this is coming. Any help will be appreciated.</p>
<p><a href="http://i.stack.imgur.com/s9cYL.png" rel="nofollow"><img src="http://i.stack.imgur.com/s9cYL.png" alt="Error in System 1"></a></p>
<p><a href="http://i.stack.imgur.com/S4UXd.png" rel="nofollow"><img src="http://i.stack.imgur.com/S4UXd.png" alt="Error in System 2"></a></p>
| -2
|
2016-09-06T03:10:04Z
| 39,340,725
|
<p>I suppose that encoding of data read from the registry not changed. So it is UTF-16. Specifically, UTF-16LE on one system and UTF-16BE on another. This explains the different errors. If my assumption is correct, this may help you:</p>
<pre><code>import collections
import io
import json
def decode_dict(data):
if isinstance(data, str):
return data.decode('utf-16')
elif isinstance(data, unicode):
return data
elif isinstance(data, collections.Mapping):
return dict(map(decode_dict, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(decode_dict, data))
else:
return data
with io.open(file_path, 'w', encoding='utf-8') as fh:
fh.write(json.dumps(decode_dict(reg_dict), ensure_ascii=False))
</code></pre>
| 1
|
2016-09-06T04:35:25Z
|
[
"python",
"json",
"python-2.7",
"dictionary"
] |
Plotting (and saving) specific cells from multiple dataframe in Pandas
| 39,340,103
|
<p>For example, if I have 3 dataframes like this:</p>
<pre><code>In [1]: df1 = pd.DataFrame({'A': ['32', '36', '40', '33'],
...: 'B': ['32', '34', '39', '35'],
...: 'C': ['34', '32', '35', '36'],
...: 'D': ['35', '39', '42', '40']},
...: index=[0, 1, 2, 3])
...:
In [2]: df2 = pd.DataFrame({'A': ['33', '36', '37', '40'],
...: 'B': ['42', '43', '46', '39'],
...: 'C': ['34', '36', '38', '40'],
...: 'D': ['32', '35', '34', '37']},
...: index=[0, 1, 2, 3])
...:
In [3]: df3 = pd.DataFrame({'A': ['38', '39', '40', '41'],
...: 'B': ['38', '37', '41', '40'],
...: 'C': ['36', '39', '42', '41'],
...: 'D': ['34', '39', '37', '39']},
...: index=[0, 1, 2, 3])
</code></pre>
<p>How if I want to plot specific cells from those 3 dataframe? For example, I want to plot the cell in the first row and first column from those dataframe, to see the trend.
To access it one by one using iloc is seem so lame, especially with more dataframes (actually I have 33 dataframes imported from csv, with 600 columns and 400 rows each)
Is there any way doing it easier than iloc?</p>
| 2
|
2016-09-06T03:13:30Z
| 39,340,421
|
<p>You can do this either by doing a little bit of scripting or by making one big dataframe combining all the smaller dataframes</p>
<p>Scripting:</p>
<ol>
<li>Put all your df in a list <code>df_list = [df1, df2, df3]</code></li>
<li><p>Parse through the list, collect all the values in a list and then plot it. </p>
<pre><code>def plot_xy_cell(x, y, df_list):
vals = [i.iloc(x, y) for i in df_list]
##plot the vals
</code></pre></li>
</ol>
<p>Big Dataframe:</p>
<ol>
<li>Create an extra index in each dataframe.</li>
<li>Combine all the dfs into one.</li>
<li>Use groupby clause to plot required columns</li>
</ol>
| 0
|
2016-09-06T03:57:21Z
|
[
"python",
"pandas",
"dataframe"
] |
Plotting (and saving) specific cells from multiple dataframe in Pandas
| 39,340,103
|
<p>For example, if I have 3 dataframes like this:</p>
<pre><code>In [1]: df1 = pd.DataFrame({'A': ['32', '36', '40', '33'],
...: 'B': ['32', '34', '39', '35'],
...: 'C': ['34', '32', '35', '36'],
...: 'D': ['35', '39', '42', '40']},
...: index=[0, 1, 2, 3])
...:
In [2]: df2 = pd.DataFrame({'A': ['33', '36', '37', '40'],
...: 'B': ['42', '43', '46', '39'],
...: 'C': ['34', '36', '38', '40'],
...: 'D': ['32', '35', '34', '37']},
...: index=[0, 1, 2, 3])
...:
In [3]: df3 = pd.DataFrame({'A': ['38', '39', '40', '41'],
...: 'B': ['38', '37', '41', '40'],
...: 'C': ['36', '39', '42', '41'],
...: 'D': ['34', '39', '37', '39']},
...: index=[0, 1, 2, 3])
</code></pre>
<p>How if I want to plot specific cells from those 3 dataframe? For example, I want to plot the cell in the first row and first column from those dataframe, to see the trend.
To access it one by one using iloc is seem so lame, especially with more dataframes (actually I have 33 dataframes imported from csv, with 600 columns and 400 rows each)
Is there any way doing it easier than iloc?</p>
| 2
|
2016-09-06T03:13:30Z
| 39,340,653
|
<p><strong><em>Option 1</em></strong></p>
<p>The most general solution to your question would be to wrap your dataframes into a <code>pandas.Panel</code></p>
<pre><code>pnl = pd.Panel({'df1': df1, 'df2': df2, 'df3': df3})[['df1', 'df2', 'df3']]
</code></pre>
<p>Then you could access the desired series</p>
<pre><code>pnl.iloc[:, 0, 0]
df1 32
df2 33
df3 38
Name: A, dtype: object
</code></pre>
<hr>
<p><strong><em>Option 2</em></strong></p>
<p>you could also drop the dataframes into another dataframe</p>
<pre><code>df = pd.concat([d.stack() for d in [df1, df2, df3]],
axis=1, keys=['df1', 'df2', 'df3'])
</code></pre>
<p>Then access the specific data with</p>
<pre><code>df.iloc[0, :]
df1 32
df2 33
df3 38
Name: (0, A), dtype: object
</code></pre>
<p>Or</p>
<pre><code>df.to_panel().iloc[:, 0, 0]
df1 32
df2 33
df3 38
Name: A, dtype: object
</code></pre>
<hr>
<p><strong><em>Option 3</em></strong></p>
<p>You can just grab the 3 items and wrap it in a <code>panda.Series</code></p>
<pre><code>pd.Series([d.iloc[0, 0] for d in [df1, df2, df3]])
0 32
1 33
2 38
dtype: object
</code></pre>
| 2
|
2016-09-06T04:26:21Z
|
[
"python",
"pandas",
"dataframe"
] |
How to set the python searching directory of data file in another sub-folder in pycharm?
| 39,340,127
|
<p>Here my project has folder alignment as follows:</p>
<pre><code> myProject:
---------
main.py
-------------
folder1:
test.py
--------------
folder2:
lib.py
__init__.py
---------------
folder_for_data:
data_file1
data_file2
</code></pre>
<p>So how to specify the searching path if I want to open the <code>data_file1</code> in the <code>test.py</code> scripts ? Actually, I can successfully open the data file in <code>main.py</code> by directly specifying the path as <code>folder2/folder_for_data/data_file1</code>. However, as I do the same thing in <code>test.py</code>, PyCharm tells me there is no such file or directory. I already add <code>myProject</code> to Content Root in pycharm, but why I can't open the file as I specified above. </p>
<p>By the way, I can import modules in lib.py with <code>from folder2.lib import module</code>. I guess if there are any tricks required to specify searching root path for data files? </p>
| 0
|
2016-09-06T03:15:56Z
| 39,347,898
|
<p>For the most part, this question is independent of PyCharm. It's mostly about how to import modules and load data files in Python using relative paths.</p>
<p>Importing modules is different than opening data files, for quite a number of reasons. It is affected by: the working directory that you run Python from, the PYTHONPATH, use of Python 2 vs. Python 3.4+, whether you have setup your work as a Python package, and whether you have an <strong>init</strong>.py in place.</p>
<p>For the data file, my suggestion: use Python's facilities to find the directory of the running script, then use the path modules to make a directory relative to that.</p>
| 0
|
2016-09-06T11:24:11Z
|
[
"python",
"pycharm"
] |
How to access the key values in python dictionary with variables?
| 39,340,225
|
<p>I have a dict whose keys are numbers. It looks like this:</p>
<pre><code>{'1': 3, '2': 7, '3', 14}
</code></pre>
<p>I need to access the value of each key with a variable, but get stuck because of the quotation marks of keys. How can I do that?</p>
| 0
|
2016-09-06T03:29:33Z
| 39,340,264
|
<p>You can cast your number to a string,</p>
<pre><code>my_dict = {'1': 3, '2': 7, '3': 14}
number = 2
print(my_dict[str(number)])
</code></pre>
| 1
|
2016-09-06T03:36:11Z
|
[
"python",
"dictionary"
] |
How to access the key values in python dictionary with variables?
| 39,340,225
|
<p>I have a dict whose keys are numbers. It looks like this:</p>
<pre><code>{'1': 3, '2': 7, '3', 14}
</code></pre>
<p>I need to access the value of each key with a variable, but get stuck because of the quotation marks of keys. How can I do that?</p>
| 0
|
2016-09-06T03:29:33Z
| 39,340,514
|
<p>If values is all what you want to access and the sequence doesn't matter then you can simply loop through the dict to access the values.</p>
<pre><code>my_dict = {'1': 3, '2': 7, '3': 14}
for k in my_dict:
print my_dict[k]
</code></pre>
| 0
|
2016-09-06T04:09:52Z
|
[
"python",
"dictionary"
] |
Don't understand why ValueError: No JSON object could be decoded occurs
| 39,340,295
|
<p>I'm getting this following error</p>
<pre class="lang-none prettyprint-override"><code>ValueError: No JSON object could be decoded
</code></pre>
<p>My json data is valid, i changing the JSON file encoding to utf-8, but still didn't work, this is my code :</p>
<pre><code>f = open(os.path.dirname(os.path.abspath(__file__))+"/test.json", 'w+')
data = json.load(f)
pprint(data)
</code></pre>
<p>And this is my test.json data:</p>
<pre><code>{"X":19235, "Y":19220, "Z":22685}
</code></pre>
| 0
|
2016-09-06T03:40:11Z
| 39,345,699
|
<p>First of all, let's confirm your json data is valid emulating the content of your file like this:</p>
<pre><code>import json
from StringIO import StringIO
f = StringIO("""
{"X":19235, "Y":19220, "Z":22685}
""")
try:
data = f.read()
json.loads(data)
except:
print("BREAKPOINT")
print("DONE")
</code></pre>
<p>The script is printing only <code>DONE</code>, that means the content of your file is a valid JSON, so if we take a look to your script:</p>
<pre><code>f = open(os.path.dirname(os.path.abspath(__file__))+"/test.json", 'w+')
data = json.load(f)
pprint(data)
</code></pre>
<p>The main problem of your code is you're using <code>w+</code> write mode, which is truncating the file (you should use reading mode) so the file object is not valid anymore. Try this:</p>
<pre><code>f = open(os.path.dirname(os.path.abspath(__file__))+"/test.json", 'rb')
data = json.load(f)
pprint(data)
</code></pre>
<p>or this:</p>
<pre><code>f = open(os.path.dirname(os.path.abspath(__file__))+"/test.json", 'rb')
data = json.loads(f.read())
pprint(data)
</code></pre>
| 1
|
2016-09-06T09:40:35Z
|
[
"python",
"json",
"object"
] |
Scrapy Json Rule SgmlLink Extractor
| 39,340,339
|
<p>I just want to know on how can I make rule when the website sends me a json response instead of html? On the start url first response, it gives me an html response, but when I navigated through pages, it gives me json response. Here my rule:</p>
<pre><code> Rule(SgmlLinkExtractor(restrict_xpaths=('//div[@class="GridTimeline-items"]'), tags=('div'),
attrs=('data-min-position'), allow=(r''), process_value=my_process_value_friends),
callback='parse_friends', follow=True),
</code></pre>
<p>My question is, how can I apply xpath on json response? </p>
<p>Thank you ,</p>
| 0
|
2016-09-06T03:46:22Z
| 39,342,048
|
<p>You can't parse json with xpath or css selectors. You can however turn the json to python dictionary:</p>
<pre><code>import json
def parse(self, response):
data = json.loads(response.body)
# then just parse it, e.g.
item = dict()
item['name'] = data['name']
# ...
</code></pre>
<p>Or you can conver json to xml and then parse it with scrapy selectors. There a lot of packages that do that but I'll highlight <a href="https://github.com/quandyfactory/dicttoxml" rel="nofollow"><code>dicttoxml</code></a> in my example:</p>
<pre><code>import json
from dicttoxml import dicttoxml
from scrapy import Selector
def parse(self, response):
data = json.loads(response.body)
data_xml = dicttoxml(data)
sel = Selector(root=data_xml)
# then parse it
item = dict()
item['name'] = sel.xpath("//name/text()")
# ...
</code></pre>
| 0
|
2016-09-06T06:34:25Z
|
[
"python",
"json",
"scrapy",
"web-crawler",
"sgml"
] |
anti crawler - Python
| 39,340,360
|
<p>I know to write Python crawler with beautiful soup module. Now I want to detect if someone crawls my website. How to do that. Can someone point me to pesudo code or sourcecode. Basically I am looking to write anti-crawler in python. </p>
| -3
|
2016-09-06T03:48:58Z
| 39,341,503
|
<p>It's hard, but can do things to filter crawlers.</p>
<p><strong>Auth</strong></p>
<p>Show pages only to authorized users. </p>
<p><strong>Strong Captcha</strong></p>
<p>If your captcha system strong enough, can anti a part of crawlers.</p>
<p><strong>User Agent</strong></p>
<p>Requests from crawler may not set user agent, so you can block those requests have no user agent(or not right user agent).</p>
<p><strong>Request Frequency</strong></p>
<p>Some crawler requests your website more faster than human, block their IP.</p>
<p><strong>JS load</strong></p>
<p>Using javascript to load your html, normal crawl only get the base html before javascript loading completed.</p>
<p><strong>Temporary URL</strong></p>
<p>Your can encode your url with timestamp(or something else) and public the url to user for visiting, making some crawlers cannot find entrance.</p>
<p><strong>Or Any other</strong></p>
<p>....</p>
| 0
|
2016-09-06T05:53:13Z
|
[
"python",
"python-2.7",
"python-3.x",
"web-crawler",
"google-crawlers"
] |
anti crawler - Python
| 39,340,360
|
<p>I know to write Python crawler with beautiful soup module. Now I want to detect if someone crawls my website. How to do that. Can someone point me to pesudo code or sourcecode. Basically I am looking to write anti-crawler in python. </p>
| -3
|
2016-09-06T03:48:58Z
| 39,343,850
|
<p>What about assuming that not all crawlers are nasty? Most do respect the <a href="http://www.robotstxt.org/" rel="nofollow">robots directives</a>. Of course you can implement all sorts of heuristics to block robots but the first thing you do would be to have </p>
<pre><code>User-agent: *
Disallow: /
</code></pre>
<p>in a robots.txt at the root of your site.</p>
<p>Then if you really want to make things hard for the ones who do not follow robots.txt then use Javascript for all the links : not 100% guaranteed to block robots but it will make their lives a lot more difficult.</p>
| 0
|
2016-09-06T08:12:08Z
|
[
"python",
"python-2.7",
"python-3.x",
"web-crawler",
"google-crawlers"
] |
Django - Built project broken
| 39,340,444
|
<p>So basically, I have a DJANGO project that can be executed and work well. And I don't know why (maybe I upgrade my django or sth) that this is no longer working.</p>
<p>First I try "python3 manage.py runserver" I get this from console:</p>
<p><a href="http://i.stack.imgur.com/oLfwV.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/oLfwV.jpg" alt="enter image description here"></a></p>
<p>So I try to collect the static file with "python3 manage.py collectstatic"</p>
<p><a href="http://i.stack.imgur.com/ATT34.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/ATT34.jpg" alt="enter image description here"></a></p>
<p>And I do have "ckeditor" in my static folder</p>
<p><a href="http://i.stack.imgur.com/ColZz.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/ColZz.jpg" alt="enter image description here"></a></p>
<p>And I'm sure that my project is work because it still online somewhere.
And notice 1 thing that in the project that my "manage.py" is not turning red. like this
<a href="http://i.stack.imgur.com/VqWOs.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/VqWOs.jpg" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/nfnum.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/nfnum.jpg" alt="enter image description here"></a></p>
<p>I know its just UI behavior but it seems that the project is broken. Anyone has idea bout it?</p>
| -2
|
2016-09-06T04:00:15Z
| 39,340,846
|
<p>It seems to me that you've got a python dependency problem. You've probably added django ckeditor in your INSTALLED_APPS settings, but it's not installed in your (virtual) env.</p>
<p>So have you installed django ckeditor using pip ? It's not related to the static folders or anything, they're not compile time errors. They are 404s.</p>
| 0
|
2016-09-06T04:49:12Z
|
[
"python",
"django"
] |
Why can't PyBrain Learn Binary
| 39,340,464
|
<p>I am attempting to get a network (PyBrain) to learn binary. This my code and it keeps return values around 8, but it should be return 9 when I activate with this target.</p>
<pre><code>from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure import *
from pybrain.datasets import *
from pybrain.supervised.trainers import BackpropTrainer
from matplotlib.pyplot import *
trains = 3000
hiddenLayers = 4
dim = 4
target = (1, 0, 0, 1)
ds = SupervisedDataSet(dim, 1)
ds.addSample((0, 0, 0, 0), (0,))
ds.addSample((0, 0, 0, 1), (1,))
ds.addSample((0, 0, 1, 0), (2,))
ds.addSample((0, 0, 1, 1), (3,))
ds.addSample((0, 1, 0, 0), (4,))
ds.addSample((0, 1, 0, 1), (5,))
ds.addSample((0, 1, 1, 0), (6,))
ds.addSample((0, 1, 1, 1), (7,))
ds.addSample((1, 0, 0, 0), (8,))
net = buildNetwork(dim, hiddenLayers, 1, bias=True, hiddenclass=SigmoidLayer)
trainer = BackpropTrainer(net, ds)
tests = []
for i in range(trains):
trainer.train()
tests.append(net.activate(target))
plot(range(len(tests)), tests)
print net.activate(target)
show()
</code></pre>
<p>I have tried adjusting the number hidden Layers, the hiddenclass from TanhLayer to SigmoidLayer and varied the number of trains, but it always converges around 500 times (training the network to the dataset). Should I be using a different trainer than back propagation and if so why?</p>
| 2
|
2016-09-06T04:02:51Z
| 39,340,882
|
<p>I would suggest you make the target something in the middle instead of on the fringe.</p>
<p>I tried expanding the training data upwards with 10 and 11, then it produced better results on predicting 9, even with 9 left out of the training data. Also you get a pretty good result if you try to predict 4, even if you do not have 4 in the training data.</p>
<p>From my experience I would not expect a neural net to readily guess numbers that are beyond the borders of the test data.</p>
| 1
|
2016-09-06T04:53:28Z
|
[
"python",
"neural-network",
"artificial-intelligence",
"pybrain"
] |
Why can't PyBrain Learn Binary
| 39,340,464
|
<p>I am attempting to get a network (PyBrain) to learn binary. This my code and it keeps return values around 8, but it should be return 9 when I activate with this target.</p>
<pre><code>from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure import *
from pybrain.datasets import *
from pybrain.supervised.trainers import BackpropTrainer
from matplotlib.pyplot import *
trains = 3000
hiddenLayers = 4
dim = 4
target = (1, 0, 0, 1)
ds = SupervisedDataSet(dim, 1)
ds.addSample((0, 0, 0, 0), (0,))
ds.addSample((0, 0, 0, 1), (1,))
ds.addSample((0, 0, 1, 0), (2,))
ds.addSample((0, 0, 1, 1), (3,))
ds.addSample((0, 1, 0, 0), (4,))
ds.addSample((0, 1, 0, 1), (5,))
ds.addSample((0, 1, 1, 0), (6,))
ds.addSample((0, 1, 1, 1), (7,))
ds.addSample((1, 0, 0, 0), (8,))
net = buildNetwork(dim, hiddenLayers, 1, bias=True, hiddenclass=SigmoidLayer)
trainer = BackpropTrainer(net, ds)
tests = []
for i in range(trains):
trainer.train()
tests.append(net.activate(target))
plot(range(len(tests)), tests)
print net.activate(target)
show()
</code></pre>
<p>I have tried adjusting the number hidden Layers, the hiddenclass from TanhLayer to SigmoidLayer and varied the number of trains, but it always converges around 500 times (training the network to the dataset). Should I be using a different trainer than back propagation and if so why?</p>
| 2
|
2016-09-06T04:02:51Z
| 39,341,487
|
<p>You've built a network with 4 input nodes, 4 hidden nodes, and 1 output node, and 2 biases.</p>
<p><a href="http://i.stack.imgur.com/CsqV5.png" rel="nofollow"><img src="http://i.stack.imgur.com/CsqV5.png" alt="enter image description here"></a></p>
<p>Considering each letter as the activation for that node, we can say each hidden node computes its activation as sigmoid(w<sub>0</sub>*1 + w<sub>1</sub>*A + w<sub>2</sub>*B + w<sub>3</sub>*C + w<sub>4</sub>*D), and the output node computes its activation as (w<sub>0</sub>*1 + w<sub>1</sub>*E + w<sub>2</sub>*F + w<sub>3</sub>*G + w<sub>4</sub>*H) (with no sigmoid). The number of lines in the diagram is the number of the weight parameters in the model that are tweaked during learning.</p>
<p>With so many parameters but only 9 samples to train on, there are many locally optimal, not-quite-right solutions that the network can converge to. </p>
<p>One way to fix this is to increase your number of training samples. You could generalize past 1s and 0s and offer samples such as ((0, 0, 1.0, 0.5), (2.5,)) and ((0, 1.2, 0.0, 1.0), (5.8,)).</p>
<p>Another option is to simplify your model. All you need for a perfect solution is 4 inputs hooked directly to the output with no biases or sigmoids. That model would only have 4 weights which training would set to 1, 2, 4, and 8. The final computation would be 1*A + 2*B + 4*C + 8*D.</p>
| 2
|
2016-09-06T05:51:20Z
|
[
"python",
"neural-network",
"artificial-intelligence",
"pybrain"
] |
Filling HTML password field using Python (Requests)
| 39,340,490
|
<p>I have been trying to login to a website (<a href="https://osu.ppy.sh/" rel="nofollow">https://osu.ppy.sh/</a>) using the Requests library in Python (<a href="http://docs.python-requests.org/" rel="nofollow">http://docs.python-requests.org/</a>). The following code seems to fill in the "username" field but not the "password" field:</p>
<pre><code>payload = {
'username': 'some_username',
'password': 'some_password'
}
with requests.Session() as s:
p = s.post('https://osu.ppy.sh/forum/ucp.php?mode=login', data=payload)
print(p.text)
</code></pre>
<p>The output from running the code above contains the following:</p>
<pre><code><td valign="top"><b class="gensmall">Username:</b></td>
<td><input class="post" type="text" name="username" size="25" maxlength="40" value="some_username" tabindex="1"/>
</td>
</tr>
<tr>
<td valign="top"><b class="gensmall">Password:</b></td>
<td>
<input class="post" type="password" name="password" size="25" maxlength="100" tabindex="2"/>
</td>
</code></pre>
<p>Notice how the username text field shows</p>
<pre><code>value="some_username"
</code></pre>
<p>while the password field does not have a value set.</p>
<p>Shouldn't my code set the values of both the username and password fields?</p>
<p>If so, why isn't it setting the value of the password field as well? Is it because the password field is </p>
<pre><code>type="password"
</code></pre>
<p>and Requests.post() can only set the values of text fields?</p>
<p>Is it because the "username" text field has and empty</p>
<pre><code>value=""
</code></pre>
<p>beforehand but the password field doesn't?</p>
<p>It is filling in the password field and I'm just not seeing it?</p>
<p>Any help is appreciated.</p>
| 0
|
2016-09-06T04:06:27Z
| 39,341,170
|
<p>First, it's not because the type of password, the most likely point is that your payload is not completed.</p>
<p>I checked the form data to login <a href="https://osu.ppy.sh" rel="nofollow">https://osu.ppy.sh</a>, it likes this:</p>
<p><a href="http://i.stack.imgur.com/bkzlF.png" rel="nofollow"><img src="http://i.stack.imgur.com/bkzlF.png" alt="enter image description here"></a></p>
<p>You can find that the Form Data contains a few of different fields: redirect, sid, username, password, login. </p>
<p>To login success, you should figure out these fields if they are required, and fill the right values in your payload.</p>
| -2
|
2016-09-06T05:23:19Z
|
[
"python",
"python-3.x",
"python-requests"
] |
Shut down Flask SocketIO Server
| 39,340,650
|
<p>For circumstances outside of my control, I need to use the Flask server to serve basic html files, the Flask SocketIO wrapper to provide a web socket interface between any clients and the server. The <code>async_mode</code> has to be <code>threading</code> instead of <code>gevent</code> or <code>eventlet</code>, I understand that it is less efficient to use threading, but I can't use the other two frameworks.</p>
<p>In my unit tests, I need to shut down and restart the web socket server. When I attempt to shut down the server, I get the <code>RunTimeError</code> 'Cannot stop unknown web server.' This is because the function <code>werkzeug.server.shutdown</code> is not found in the Flask Request Environment <code>flask.request.environ</code> object.</p>
<p>Here is how the server is started.</p>
<pre><code>SERVER = flask.Flask(__name__)
WEBSOCKET = flask_socketio.SocketIO(SERVER, async_mode='threading')
WEBSOCKET.run(SERVER, host='127.0.0.1', port=7777)
</code></pre>
<p>Here is the short version of how I'm attempting to shut down the server.</p>
<pre><code>client = WEBSOCKET.test_client(SERVER)
@WEBSOCKET.on('kill')
def killed():
WEBSOCKET.stop()
try:
client.emit('kill')
except:
pass
</code></pre>
<p>The stop method must be called from within a flask request context, hence the weird kill event callback. Inside the stop method, the <code>flask.request.environ</code> has the value</p>
<pre><code>'CONTENT_LENGTH' (40503696) = {str} '0'
'CONTENT_TYPE' (60436576) = {str} ''
'HTTP_HOST' (61595248) = {str} 'localhost'
'PATH_INFO' (60437104) = {str} '/socket.io'
'QUERY_STRING' (60327808) = {str} ''
'REQUEST_METHOD' (40503648) = {str} 'GET'
'SCRIPT_NAME' (60437296) = {str} ''
'SERVER_NAME' (61595296) = {str} 'localhost'
'SERVER_PORT' (61595392) = {str} '80'
'SERVER_PROTOCOL' (65284592) = {str} 'HTTP/1.1'
'flask.app' (65336784) = {Flask} <Flask 'server'>
'werkzeug.request' (60361056) = {Request} <Request 'http://localhost/socket.io' [GET]>
'wsgi.errors' (65338896) = {file} <open file '<stderr>', mode 'w' at 0x0000000001C92150>
'wsgi.input' (65338848) = {StringO} <cStringIO.StringO object at 0x00000000039902D0>
'wsgi.multiprocess' (65369288) = {bool} False
'wsgi.multithread' (65369232) = {bool} False
'wsgi.run_once' (65338944) = {bool} False
'wsgi.url_scheme' (65338800) = {str} 'http'
'wsgi.version' (65338752) = {tuple} <type 'tuple'>: (1, 0)
</code></pre>
<p>My question is, how do I set up the Flask server to have the <code>werkzeug.server.shutdown</code>method available inside the flask request contexts?</p>
<p>Also this is using Python 2.7</p>
| 0
|
2016-09-06T04:26:03Z
| 39,342,270
|
<p>I have good news for you, the testing environment does not use a real server, in that context the client and the server run inside the same process, so the communication between them does not go through the network as it does when you run things for real. Really in this situation there is no server, so there's nothing to stop.</p>
<p>It seems you are starting a real server, though. For unit tests, that server is not used, all you need are your unit tests which import the application and then use a test client to issue socket.io events. I think all you need to do is just not start the server, the unit tests should run just fine without it if all you use is the test client as you show above.</p>
| 1
|
2016-09-06T06:48:37Z
|
[
"python",
"python-2.7",
"flask",
"werkzeug",
"flask-socketio"
] |
Error while concatenating lists in python
| 39,340,749
|
<p>I am working on an assignment for one of my classes at school where I need to concatenate two lists together. I am using the code:</p>
<pre><code>flowers = ["rose", "bougainvillea", "yukka", "marigold", "daylily", "lily of the valley"]
thorny = flowers[0:3]
poisonous = flowers[-1]
dangerous = flowers[0:3] + flowers[-1]
</code></pre>
<p>I keep getting the error message: </p>
<pre><code>dangerous = list(set(flowers[0:3] + flowers[-1]))
TypeError: can only concatenate list (not "str") to list
</code></pre>
<p>I was wondering why this doesn't work. Thanks!</p>
| 0
|
2016-09-06T04:38:45Z
| 39,340,759
|
<p><code>flowers[0:3]</code> returns a list while <code>flowers[-1]</code> returns a string, so you are adding a string to a list. You can use <code>flowers[-1:]</code> to return a list instead.</p>
| 6
|
2016-09-06T04:40:28Z
|
[
"python"
] |
Error while concatenating lists in python
| 39,340,749
|
<p>I am working on an assignment for one of my classes at school where I need to concatenate two lists together. I am using the code:</p>
<pre><code>flowers = ["rose", "bougainvillea", "yukka", "marigold", "daylily", "lily of the valley"]
thorny = flowers[0:3]
poisonous = flowers[-1]
dangerous = flowers[0:3] + flowers[-1]
</code></pre>
<p>I keep getting the error message: </p>
<pre><code>dangerous = list(set(flowers[0:3] + flowers[-1]))
TypeError: can only concatenate list (not "str") to list
</code></pre>
<p>I was wondering why this doesn't work. Thanks!</p>
| 0
|
2016-09-06T04:38:45Z
| 39,340,881
|
<p>Put square brackets around <em>flowers[-1]</em> to return the item as a list. E.g. </p>
<pre><code>flowers = ["rose", "bougainvillea", "yukka", "marigold", "daylily", "lily of the valley"]
thorny = flowers[0:3]
poisonous = [(flowers[-1])]
dangerous = thorny + poisonous
</code></pre>
| -1
|
2016-09-06T04:53:26Z
|
[
"python"
] |
xbee.remote_at not working
| 39,340,773
|
<p>I am using python-xbee to work with XBee modules (Python 2.7). I have an XBee (coordinator) directly connected to my laptop through a serial port and another separate one (endpoint). I can easily communicate with them both using the <code>at</code> command, but I can't communicate with them using <code>remote_at</code>.</p>
<p>When I run</p>
<pre><code>import serial
from xbee.zigbee import ZigBee
import time
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
def print_xbee_data(data):
print(data)
serial_port = serial.Serial(PORT, BAUD_RATE)
# For some reason escaped=True does not work
xbee = ZigBee(serial_port, escaped=True, callback=print_xbee_data)
xbee.send('at', frame='a', command='nd', parameter=None)
# Delay: to wait to keep the thread running to receive the response(s)
time.sleep(5)
</code></pre>
<p>The output is:</p>
<pre><code>{'status': '\x00', 'frame_id': '\x01', 'parameter': {'status': '\x00', 'source_addr': 'a\xd4', 'parent_address': '\x00\x00', 'profile_id': '\xc1\x05', 'source_addr_long': '\x00\x13\xa2\x00@0\xbd@', 'device_type': '\x02', 'node_identifier': ' ', 'manufacturer': '\x10\x1e'}, 'command': 'ND', 'id': 'at_response'}
</code></pre>
<p>But when I run (I am using both escaped and not-escaped address formats just to be sure)</p>
<pre><code>xbee.remote_at(dest_addr=b'a\xd4', command='MY')
xbee.remote_at(dest_addr=b'\x61\xd4', command='MY')
xbee.send('remote_at',
frame_id='A',
dest_addr_long='\x00\x13\xa2\x00@0\xbd@',
dest_addr='a\xd4',
options='\x02',
command='D0',
parameter='\x02')
xbee.send('remote_at',
frame_id='A',
dest_addr_long='\x00\x13\xa2\x00\x40\x30\xbd\x40',
dest_addr='\x61\xd4',
options='\x02',
command='D0',
parameter='\x02')
time.sleep(5)
</code></pre>
<p>I get no output.</p>
<ul>
<li>Why doesn't <code>escaped=True</code> work?</li>
<li>Why don't I get any output?</li>
<li>How can I go about fixing the problem?</li>
</ul>
<p>Thanks a lot.</p>
| 0
|
2016-09-06T04:41:43Z
| 39,354,245
|
<ol>
<li><code>escaped=True</code> is only if you have <code>ATAP</code> set to 2 (escaped API mode) instead of 1 (API mode).</li>
<li>Are you sure your modules are joined to each other, and you're not seeing an <code>ATND</code> response from your local device? Make sure you're using the address of the remote module.</li>
</ol>
| 0
|
2016-09-06T16:58:53Z
|
[
"python",
"serial-port",
"xbee",
"zigbee"
] |
xbee.remote_at not working
| 39,340,773
|
<p>I am using python-xbee to work with XBee modules (Python 2.7). I have an XBee (coordinator) directly connected to my laptop through a serial port and another separate one (endpoint). I can easily communicate with them both using the <code>at</code> command, but I can't communicate with them using <code>remote_at</code>.</p>
<p>When I run</p>
<pre><code>import serial
from xbee.zigbee import ZigBee
import time
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
def print_xbee_data(data):
print(data)
serial_port = serial.Serial(PORT, BAUD_RATE)
# For some reason escaped=True does not work
xbee = ZigBee(serial_port, escaped=True, callback=print_xbee_data)
xbee.send('at', frame='a', command='nd', parameter=None)
# Delay: to wait to keep the thread running to receive the response(s)
time.sleep(5)
</code></pre>
<p>The output is:</p>
<pre><code>{'status': '\x00', 'frame_id': '\x01', 'parameter': {'status': '\x00', 'source_addr': 'a\xd4', 'parent_address': '\x00\x00', 'profile_id': '\xc1\x05', 'source_addr_long': '\x00\x13\xa2\x00@0\xbd@', 'device_type': '\x02', 'node_identifier': ' ', 'manufacturer': '\x10\x1e'}, 'command': 'ND', 'id': 'at_response'}
</code></pre>
<p>But when I run (I am using both escaped and not-escaped address formats just to be sure)</p>
<pre><code>xbee.remote_at(dest_addr=b'a\xd4', command='MY')
xbee.remote_at(dest_addr=b'\x61\xd4', command='MY')
xbee.send('remote_at',
frame_id='A',
dest_addr_long='\x00\x13\xa2\x00@0\xbd@',
dest_addr='a\xd4',
options='\x02',
command='D0',
parameter='\x02')
xbee.send('remote_at',
frame_id='A',
dest_addr_long='\x00\x13\xa2\x00\x40\x30\xbd\x40',
dest_addr='\x61\xd4',
options='\x02',
command='D0',
parameter='\x02')
time.sleep(5)
</code></pre>
<p>I get no output.</p>
<ul>
<li>Why doesn't <code>escaped=True</code> work?</li>
<li>Why don't I get any output?</li>
<li>How can I go about fixing the problem?</li>
</ul>
<p>Thanks a lot.</p>
| 0
|
2016-09-06T04:41:43Z
| 39,380,421
|
<p>remote_at requires a non-zero frame_id to return a response. Run:</p>
<pre><code>xbee.remote_at(dest_addr='\x61\xd4', command='MY', frame_id='A')
</code></pre>
<p>and the output is:</p>
<pre><code>{'status': '\x00', 'source_addr': '\x00\x00', 'source_addr_long': '\x00\x13\xa2\x00@\n\x05\xab', 'frame_id': 'A', 'command': 'MY', 'parameter': '\x00\x00', 'id': 'remote_at_response'}
</code></pre>
<p>Although the status is OK (<code>'status': '\x00'</code>) the above command is not doing what we want. Here <code>'source_addr_long': '\x00\x13\xa2\x00@\n\x05\xab'</code> is the address of local XBee (coordinator). In order for the command to do what we want it to (send <code>MY</code> command to the remote device) we MUST specify the 64-bit address (long). Therefore the correct command is:</p>
<pre><code>xbee.remote_at(dest_address_long='\x00\x13\xa2\x00@0\xbd@', dest_addr='a\xd4', command='MY', frame_id='A')
</code></pre>
<p>Replacing <code>dest_addr='a\xd4'</code> with <code>dest_addr='\xff\xfe</code> works, too.</p>
| 0
|
2016-09-07T23:26:23Z
|
[
"python",
"serial-port",
"xbee",
"zigbee"
] |
More pythonic way to nest functions
| 39,340,832
|
<p>Here is the code that I have:</p>
<pre><code>def reallyquit():
from easygui import boolbox
if __debug__: print ("realy quit?")
answer = boolbox("Are you sure you want to Quit?")
if answer == 1:
sys.exit()
return
columns = ['adr1','adr2','spam','spam', 'spam']
Street = choicebox("Street Address?", title, columns)
while Street == None:
reallyquit()
Street = choicebox("Street Address?", title, columns)
</code></pre>
<p>Is there a more pythonic way to recursively ask a question if a user closes a box inadvertently? Mainly looking for tips on the last 4 lines, but feel free to critique the rest.</p>
| 2
|
2016-09-06T04:47:51Z
| 39,340,889
|
<pre class="lang-py prettyprint-override"><code>import sys
from easygui import boolbox, choicebox
def reallyquit():
"Ask if the user wants to quit. If so, exit."
if __debug__:
print("really quit?")
answer = boolbox("Are you sure you want to Quit?")
if answer == 1:
sys.exit()
columns = ['adr1', 'adr2', 'spam', 'spam']
street = None
# ask for address until given or user decides to quit
while street is None:
street = choicebox("Street Address?", title, columns)
if street is None:
reallyquit()
</code></pre>
<p>In the main logic: Usually you would not test if a value is equal to <code>None</code>, since it is a singleton (only one in the system, and all occurrences of <code>None</code> are to the same logical <code>None</code>). Thus <code>is None</code> is a better test. I've also used a little more Pythonic code formatting (spaces after commas in a list, lowercase variable names), and a test order that doesn't duplicate the user interaction call.</p>
<p>An alternative form suggested by <a href="http://stackoverflow.com/users/102441/eric">Eric</a> would be something like:</p>
<pre><code>while True:
street = choicebox("Street Address?", title, columns)
if street is not None:
break
reallyquit()
</code></pre>
<p>This has the virtue of not repeating the <code>street is None</code> test, but is a bit longer. Your preference for which option seems clearer and more logical may vary. </p>
<p>For the preparations: Imports are taken out of functions, and <code>choicebox</code> is imported where it was previously missing. The function is given
a defining comment string. The one statement per line standard is enforced. And the unnecessary <code>return</code> removed.</p>
<p>This is still a fairly coarse program, but it's now "more Pythonic."</p>
<p>Not to be overwhelming, but the standard for Pythonic code appearance is <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>. There are tools such as <a href="https://pypi.python.org/pypi/pep8" rel="nofollow">pep8</a> you can install to check compliance. The deeper or "semantic" part of Pythonic code is sketched out in <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">PEP 20</a>, also known as "The Zen of Python." There is, sadly, no tool to judge compliance with those deeper principles. Experience is required.</p>
| 2
|
2016-09-06T04:54:21Z
|
[
"python",
"python-2.7",
"easygui"
] |
More pythonic way to nest functions
| 39,340,832
|
<p>Here is the code that I have:</p>
<pre><code>def reallyquit():
from easygui import boolbox
if __debug__: print ("realy quit?")
answer = boolbox("Are you sure you want to Quit?")
if answer == 1:
sys.exit()
return
columns = ['adr1','adr2','spam','spam', 'spam']
Street = choicebox("Street Address?", title, columns)
while Street == None:
reallyquit()
Street = choicebox("Street Address?", title, columns)
</code></pre>
<p>Is there a more pythonic way to recursively ask a question if a user closes a box inadvertently? Mainly looking for tips on the last 4 lines, but feel free to critique the rest.</p>
| 2
|
2016-09-06T04:47:51Z
| 39,341,149
|
<p>I think this is more idiomatic than using a sentinel variable:</p>
<pre><code>while True:
street = choicebox("Street Address?", title, columns)
if street is None:
reallyquit()
else:
break
</code></pre>
<p>Also, consider using the <a href="https://docs.python.org/3/library/logging.html" rel="nofollow"><code>logging</code></a> module for your debug printing, so instead of <code>if __debug__: print(whatever)</code> you just have <code>logging.debug(whatever)</code> and set the logging level.</p>
| 0
|
2016-09-06T05:19:43Z
|
[
"python",
"python-2.7",
"easygui"
] |
Converting output of dependency parsing to tree
| 39,340,907
|
<p>I am using <code>Stanford dependency parser</code> and the I get the following output of the sentence</p>
<blockquote>
<p>I shot an elephant in my sleep</p>
</blockquote>
<pre><code>python dep_parsing.py
[((u'shot', u'VBD'), u'nsubj', (u'I', u'PRP')), ((u'shot', u'VBD'), u'dobj', (u'elephant', u'NN')), ((u'elephant', u'NN'), u'det', (u'an', u'DT')), ((u'shot', u'VBD'), u'nmod', (u'sleep', u'NN')), ((u'sleep', u'NN'), u'case', (u'in', u'IN')), ((u'sleep', u'NN'), u'nmod:poss', (u'my', u'PRP$'))]
</code></pre>
<p><strong>I want to convert this into a graph with nodes being each token and edges being the relation between them.</strong></p>
<p>I need the graph structure for further processing hence it would help if modification to it are easy and also must be easily representable.</p>
<p>Here is my code till now.</p>
<pre><code>from nltk.parse.stanford import StanfordDependencyParser
stanford_parser_dir = 'stanford-parser/'
eng_model_path = stanford_parser_dir + "stanford-parser-models/edu/stanford/nlp/models/lexparser/englishRNN.ser.gz"
my_path_to_models_jar = stanford_parser_dir + "stanford-parser-3.5.2-models.jar"
my_path_to_jar = stanford_parser_dir + "stanford-parser.jar"
dependency_parser = StanfordDependencyParser(path_to_jar=my_path_to_jar, path_to_models_jar=my_path_to_models_jar)
result = dependency_parser.raw_parse('I shot an elephant in my sleep')
dep = result.next()
a = list(dep.triples())
print a
</code></pre>
<p>How can I make such a graph structure?</p>
| 0
|
2016-09-06T04:56:09Z
| 39,342,032
|
<p>You can traverse over <code>dep.triples()</code> and get your desired output.</p>
<p><strong>Code:</strong></p>
<pre><code>for triple in dep.triples():
print triple[1],"(",triple[0][0],", ",triple[2][0],")"
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>nsubj ( shot , I )
dobj ( shot , elephant )
det ( elephant , an )
nmod ( shot , sleep )
case ( sleep , in )
nmod:poss ( sleep , my )
</code></pre>
<p>For more information you can check : <a href="http://www.nltk.org/_modules/nltk/parse/dependencygraph.html" rel="nofollow">NLTK Dependencygraph</a> methods <code>triples()</code>, <code>to_dot()</code> and <code>dep.tree().draw()</code></p>
<p>Edit - </p>
<p>The output of <code>dep.to_dot()</code> is</p>
<pre><code>digraph G{
edge [dir=forward]
node [shape=plaintext]
0 [label="0 (None)"]
0 -> 2 [label="root"]
1 [label="1 (I)"]
2 [label="2 (shot)"]
2 -> 4 [label="dobj"]
2 -> 7 [label="nmod"]
2 -> 1 [label="nsubj"]
3 [label="3 (an)"]
4 [label="4 (elephant)"]
4 -> 3 [label="det"]
5 [label="5 (in)"]
6 [label="6 (my)"]
7 [label="7 (sleep)"]
7 -> 5 [label="case"]
7 -> 6 [label="nmod:poss"]
}
</code></pre>
| 2
|
2016-09-06T06:33:38Z
|
[
"python",
"data-structures",
"nlp",
"dependency-parsing"
] |
Connection Refused on Concurrent connection to openerp with xmlrpc (via python)
| 39,340,950
|
<p>I've tried to build a stress test sistem which provide multiple concurent user login. The scheme is 1 thread for 1 user login. But i cant login with multiple user at the same time (concurent).</p>
<p>At the other side, i've tried to login with multiple user in sequential scheme (with thread.lock and thread.release over login method), and it works.</p>
<p>Can i login with multiple user at the same time on python thread scheme like this?</p>
<p>This is my code
(<strong>Updated:</strong>
i've update my code, and now i tried to read via xml_rpc with multithread.
Open Connection/Login is OK, but the i always get the <strong>Failed Return on Reading Method</strong>..
):</p>
<p>This threading class:</p>
<pre><code>class theUser (threading.Thread):
def __init__(self, threadID, row, dbhost, xml_port, dbuser, dbpassword, dbname):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = str(row[0])
self.pswd = str(row[1])
self.msg = ''
self.xml_port = xml_port
self.params={'dbhost' : dbhost,
'dbuser' : dbuser,
'dbpassword': dbpassword,
'dbname' : dbname,
'user' : str(row[0]),
'password' : str(row[1])
}
def run(self):
try:
self.sock_common = xmlrpclib.ServerProxy ('http://%s:%s/xmlrpc/common' % (dbhost, xml_port))
self.uid = self.sock_common.login(self.params['dbname'], self.name, self.pswd)
self._read_data()
except:
return
def _read_data(self):
self.ids = [1,2,3,10]
self.sock_common.execute(self.params['dbname'], self.uid, self.params['password'], 'res.partner', 'read', self.ids, ['name'])
</code></pre>
<p>This is the main code:</p>
<pre><code>for row in reader:
print idx, xml_port, row
if idx == 0:
header = row
else:
# Create new User threads
thread_ = theUser(idx, row, dbhost, xml_port, dbuser, dbpassword, dbname)
# Start new User Threads
thread_.start()
# Add threads to thread list
threads.append(thread_)
idx += 1
</code></pre>
<p>Please help me..</p>
| 1
|
2016-09-06T05:00:03Z
| 39,344,711
|
<p>You forgot <code>xml_port</code> when you create <code>theUser</code>, it should be: </p>
<pre><code>thread_ = theUser(idx, row, dbhost, xml_port, dbuser, dbpassword, dbname)
</code></pre>
<p>And <code>self.sock_common</code> won't be set if an exception is raised.You can move it to <code>run()</code> function.</p>
<p>To read <code>res.partner</code>: </p>
<pre><code>def _read_data(self):
self.ids = [1,2,3,10]
models = xmlrpclib.ServerProxy('http://%s:%s/xmlrpc/object' % (dbhost, xml_port))
res = models.execute(self.params['dbname'], self.uid, self.params['password'], 'res.partner', 'read', self.ids, ['name'])
print res
</code></pre>
<p>You can check if a given user is permited to read using: </p>
<pre><code>models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
models.execute_kw(db, uid, password,
'res.partner', 'check_access_rights',
['read'], {'raise_exception': False})
</code></pre>
<p>If the user can read, it should return <code>true</code>.</p>
<blockquote>
<p>This script is from <a href="https://www.odoo.com/documentation/8.0/api_integration.html" rel="nofollow">Odoo Web Service API</a></p>
</blockquote>
| 1
|
2016-09-06T08:54:44Z
|
[
"python",
"multithreading",
"openerp",
"python-multithreading",
"stress-testing"
] |
Converting stanford dependencies in numbered format
| 39,340,965
|
<p>I am using <code>Stanford dependency parser</code> and the I get the following output of the sentence</p>
<blockquote>
<p>I shot an elephant in my sleep</p>
</blockquote>
<pre><code>>>>python dep_parsing.py
[((u'shot', u'VBD'), u'nsubj', (u'I', u'PRP')), ((u'shot', u'VBD'), u'dobj', (u'elephant', u'NN')), ((u'elephant', u'NN'), u'det', (u'an', u'DT')), ((u'shot', u'VBD'), u'nmod', (u'sleep', u'NN')), ((u'sleep', u'NN'), u'case', (u'in', u'IN')), ((u'sleep', u'NN'), u'nmod:poss', (u'my', u'PRP$'))]
</code></pre>
<p><strong>However, I want the numbered tokens as output just as <a href="http://nlp.stanford.edu:8080/parser/" rel="nofollow">it is here</a></strong></p>
<pre><code>nsubj(shot-2, I-1)
root(ROOT-0, shot-2)
det(elephant-4, an-3)
dobj(shot-2, elephant-4)
case(sleep-7, in-5)
nmod:poss(sleep-7, my-6)
nmod(shot-2, sleep-7)
</code></pre>
<p>Here is my code till now.</p>
<pre><code> from nltk.parse.stanford import StanfordDependencyParser
stanford_parser_dir = 'stanford-parser/'
eng_model_path = stanford_parser_dir + "stanford-parser-models/edu/stanford/nlp/models/lexparser/englishRNN.ser.gz"
my_path_to_models_jar = stanford_parser_dir + "stanford-parser-3.5.2-models.jar"
my_path_to_jar = stanford_parser_dir + "stanford-parser.jar"
dependency_parser = StanfordDependencyParser(path_to_jar=my_path_to_jar, path_to_models_jar=my_path_to_models_jar)
result = dependency_parser.raw_parse('I shot an elephant in my sleep')
dep = result.next()
a = list(dep.triples())
print a
</code></pre>
<p>How can I have such an output?</p>
| 0
|
2016-09-06T05:01:40Z
| 39,417,631
|
<p>Write a recursive function that traverses your tree. As a first pass, just try assigning the numbers to the words.</p>
| 0
|
2016-09-09T18:23:52Z
|
[
"python",
"nlp",
"nltk",
"stanford-nlp",
"dependency-parsing"
] |
assert vs == for testing code in Python?
| 39,341,060
|
<p>What is the need for importing unittest and running assertTrue (for example) while testing a python function instead of writing a usual python function with == True check for testing? What is the new thing about unittesting, as even the test cases have to be written by user, which can be checked by == instead of assert family of functions in unittest? My question basically is: assert in unittest vs the equality check operation == in Python.</p>
| 1
|
2016-09-06T05:10:33Z
| 39,341,480
|
<p>I would say that the most interesting thing is the "easy-to-test" that the unittest package (as well as others, for example pytest) provides. When using unittest you can just run a command and check if your refactoring or your last feature broke something on the rest of the program. I would read something about <a href="https://en.wikipedia.org/wiki/Test-driven_development" rel="nofollow">test-driven development</a> to understand better what is the importance of unittesting. </p>
| 1
|
2016-09-06T05:50:55Z
|
[
"python",
"python-2.7",
"unit-testing",
"testing",
"tdd"
] |
How to get the specific number of lines in a file using python programming?
| 39,341,092
|
<p>This is my code for getting 20 lines every time but f1.tell() gives last position of the file. So i cannot get 20 lines for the next time.
Can anyone help me to do this? please</p>
<pre><code>f1=open("sample.txt","r")
last_pos=0
while true:
f1.seek(last_pos)
for line,i in enumerate(f1.readlines()):
if line == 20:
last_pos=f1.tell()
break
else:
print i
sample.txt file contains below data
1
2
3
4
.
.
.
.
40
I want Output like
1
2
3
4
.
.
.
20
20
21
22
23
24
25
.
.
.
.
39
39
40
</code></pre>
| 0
|
2016-09-06T05:13:30Z
| 39,341,185
|
<p>Using <code>readlines</code> reads all the file: you reach the end, hence what you are experiencing.</p>
<p>Using a loop with <code>readline</code> works, though, and gives you the position of the end of the 20th line (well, rather the start of the 21st)</p>
<p>Code (I removed the infinite loop BTW):</p>
<pre><code>f1=open("sample.txt","r")
last_pos=0
line=0
while True:
l=f1.readline()
if l=="":
break
line+=1
if line == 20:
last_pos=f1.tell()
print(last_pos)
break
f1.close()
</code></pre>
<p>You could iterate with <code>for i,l in enumerate(f1):</code> but iterators & ftell are not compatible (you get: <code>OSError: telling position disabled by next() call</code>).</p>
<p>Then, to seek to a given position, just <code>f1.seek(last_pos)</code></p>
<p>EDIT: if you need to print the line twice eveny 20 lines, you actually don't even need <code>seek</code>, just print the last line when you count 20 lines.</p>
<p>BUT if you really want to do that this way, here's the way:</p>
<pre><code>f1=open("sample.txt","r")
line=0
rew=False
while True:
start_line_pos=f1.tell()
l=f1.readline()
if l=="":
break
print(l.strip())
line+=1
if rew:
rew = False # avoid re-printing the 20th line again and again
elif line % 20 == 0:
f1.seek(start_line_pos)
rew = True
line-=1 # pre-correct line counter
f1.close()
</code></pre>
<p>You notice a bit of logic to avoid getting stuck on line 20. It works fine: when reaching line 20, 40, ... it seeks back to the previously stored file position and reads 1 line again. The <code>rew</code> flag prevents to do that more than once.</p>
| 1
|
2016-09-06T05:25:16Z
|
[
"python",
"file"
] |
How to get the specific number of lines in a file using python programming?
| 39,341,092
|
<p>This is my code for getting 20 lines every time but f1.tell() gives last position of the file. So i cannot get 20 lines for the next time.
Can anyone help me to do this? please</p>
<pre><code>f1=open("sample.txt","r")
last_pos=0
while true:
f1.seek(last_pos)
for line,i in enumerate(f1.readlines()):
if line == 20:
last_pos=f1.tell()
break
else:
print i
sample.txt file contains below data
1
2
3
4
.
.
.
.
40
I want Output like
1
2
3
4
.
.
.
20
20
21
22
23
24
25
.
.
.
.
39
39
40
</code></pre>
| 0
|
2016-09-06T05:13:30Z
| 39,341,497
|
<p>Jean-François Fabre already explained that <code>readline</code> could read the whole file.</p>
<p>But anyway you should never mix line level input (<code>readline</code>) and byte level input (<code>tell</code>, <code>seek</code> or <code>read</code>). As the low level OS system calls can only read a byte count, <code>readline</code> actually reads a <em>buffer</em> and searches for a newline in it. But the file pointer given by <code>tell</code> is positionned at the end of the buffer and <strong>not</strong> at the end of the line.</p>
<p>There is no way to set the file pointer at the end of a line except by processing the file one char at a time and manually detecting the end of line.</p>
| 0
|
2016-09-06T05:52:49Z
|
[
"python",
"file"
] |
Getting TypeError when I am trying to run server using Django?
| 39,341,093
|
<p>I found questions which were close to the question asked by me, but the solutions I found there were not useful to me. Using django version 1.10.1</p>
<p>Output to </p>
<blockquote>
<p>python manage.py runserver</p>
</blockquote>
<pre><code>Performing system checks...
Unhandled exception in thread started by <function wrapper at 0xb6838064>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/sidgupta234/Desktop/Hack/guide/guide/urls.py", line 21, in <module>
url(r'^$', "hacko.views.home", name='home'),
File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 85, in url
raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().
</code></pre>
<p>urls.py file </p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', "hacko.views.home", name='home'),
url(r'^index/$', "hacko.views.index", name='index'),
]
</code></pre>
<p>views.py file</p>
<pre><code>from django.shortcuts import render
import requests
from django.http import HttpResponse
import unicodedata
# Create your views here.
def home(request):
return render(request,"sample.html");
def index(request):
print "i was called"
if(request.GET.get('q', '')):
theUrl="http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&titles="+request.GET.get('q', '')
r = requests.get(theUrl, auth=('user', 'pass'));
print r.text
return HttpResponse(r.text, content_type='hacko/json')
elif(request.GET.get('p', '')):
theUrl="https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles="+request.GET.get('p', '')
r = requests.get(theUrl, auth=('user', 'pass'));
print r.text
return HttpResponse(r.text, content_type='hacko/json')
else:
key="f7ee811c-3f3d-47b4-ad77-b31fe1831b2f"
r="http://www.dictionaryapi.com/api/v1/references/thesaurus/xml/"+request.GET.get('r', '')+"?key="+key
r=requests.get(r);
r=r.text
r=unicodedata.normalize('NFKD', r).encode('ascii','ignore')
return HttpResponse(r,content_type="text/plain")
</code></pre>
| 0
|
2016-09-06T05:13:38Z
| 39,341,186
|
<p>In 1.10, you can no longer pass import paths to url(), you need to pass the actual view function:</p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
from hacko import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
url(r'^index/$', views.index, name='index'),
]
</code></pre>
| 0
|
2016-09-06T05:25:17Z
|
[
"python",
"django"
] |
Getting TypeError when I am trying to run server using Django?
| 39,341,093
|
<p>I found questions which were close to the question asked by me, but the solutions I found there were not useful to me. Using django version 1.10.1</p>
<p>Output to </p>
<blockquote>
<p>python manage.py runserver</p>
</blockquote>
<pre><code>Performing system checks...
Unhandled exception in thread started by <function wrapper at 0xb6838064>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/sidgupta234/Desktop/Hack/guide/guide/urls.py", line 21, in <module>
url(r'^$', "hacko.views.home", name='home'),
File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 85, in url
raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().
</code></pre>
<p>urls.py file </p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', "hacko.views.home", name='home'),
url(r'^index/$', "hacko.views.index", name='index'),
]
</code></pre>
<p>views.py file</p>
<pre><code>from django.shortcuts import render
import requests
from django.http import HttpResponse
import unicodedata
# Create your views here.
def home(request):
return render(request,"sample.html");
def index(request):
print "i was called"
if(request.GET.get('q', '')):
theUrl="http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&titles="+request.GET.get('q', '')
r = requests.get(theUrl, auth=('user', 'pass'));
print r.text
return HttpResponse(r.text, content_type='hacko/json')
elif(request.GET.get('p', '')):
theUrl="https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles="+request.GET.get('p', '')
r = requests.get(theUrl, auth=('user', 'pass'));
print r.text
return HttpResponse(r.text, content_type='hacko/json')
else:
key="f7ee811c-3f3d-47b4-ad77-b31fe1831b2f"
r="http://www.dictionaryapi.com/api/v1/references/thesaurus/xml/"+request.GET.get('r', '')+"?key="+key
r=requests.get(r);
r=r.text
r=unicodedata.normalize('NFKD', r).encode('ascii','ignore')
return HttpResponse(r,content_type="text/plain")
</code></pre>
| 0
|
2016-09-06T05:13:38Z
| 39,341,189
|
<p>Update your <strong>urls.py file</strong> like below</p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
from hacko import views #importing views from app
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
url(r'^index/$', views.index, name='index'),
]
</code></pre>
<p>for your <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial03/#writing-more-views" rel="nofollow">reference</a>. And also follow the correct article or tutorial that match with your <code>django version</code>. Its always good to follow Django official site. </p>
| 3
|
2016-09-06T05:25:36Z
|
[
"python",
"django"
] |
Numpy reshape issues
| 39,341,156
|
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing, cross_validation, svm
df = pd.read_csv('table.csv')
print (df.head())
df = df[['Price', 'Asset']]
x = np.array(df.Price)
y = np.array(df.Asset)
x_train, x_test, y_train, y_test = cross_validation.train_test_split(
x, y, test_size=0.2)
x_train = np.pad(x, [(0,0)], mode='constant')
x_train.reshape((23,1))
y_train = np.pad(y, [(0,0)], mode ='constant')
y_train.reshape((23,1))
np.reshape(-1, 1)
</code></pre>
<p>Error:</p>
<pre><code>runfile('C:/Users/HP/Documents/linear.py', wdir='C:/Users/HP/Documents')
Price Asset
0 87.585859 191
1 87.839996 232
2 87.309998 245
3 88.629997 445
4 88.379997 393
C:\Users\HP\Anaconda3\lib\site-packages\sklearn\utils\validation.py:386:
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)
Traceback (most recent call last):
File "<ipython-input-124-030ffa933525>", line 1, in <module>
runfile('C:/Users/HP/Documents/linear.py', wdir='C:/Users/HP/Documents')
File "C:\Users\HP\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\Users\HP\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/HP/Documents/linear.py", line 38, in <module>
clf.fit(x_train, y_train)
File "C:\Users\HP\Anaconda3\lib\site-packages\sklearn\linear_model\base.py", line 427, in fit
y_numeric=True, multi_output=True)
File "C:\Users\HP\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 520, in check_X_y
check_consistent_length(X, y)
File "C:\Users\HP\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 176, in check_consistent_length
"%s" % str(uniques))
ValueError: Found arrays with inconsistent numbers of samples: [ 1 23]
</code></pre>
<p>My DataFrame size: 23, 2. </p>
<p>I padded my x_train and y_train to [23,1] because i got this initial error <strong>ValueError</strong>: Found arrays with inconsistent numbers of samples: [1 18].
My error message after padding: <strong>ValueError</strong>: Found arrays with inconsistent numbers of samples: [ 1 23]. </p>
<p>Then i tried to reshape it and still got the error message: <strong>ValueError</strong>: Found arrays with inconsistent numbers of samples: [ 1 23]. </p>
<p>How do i fix this?</p>
| 1
|
2016-09-06T05:21:46Z
| 39,345,490
|
<p>If you only want to reshape an array from size <code>(x, 1)</code> to <code>(1, x)</code> you can use the <code>np.transpose</code> or <code>numpy.ndarray.T</code> function:</p>
<pre><code>x_train = x_train.T
y_train = np.transpose(y_train)
</code></pre>
<p>Both achieve the same result. </p>
<p>Edit: <em>This only works for one-dimensional arrays. Use reshape for higher dimensional arrays.</em></p>
<p>If you do not give us the full traceback which shows in which line the error occurs, we can't help you in more detail.</p>
| 0
|
2016-09-06T09:31:10Z
|
[
"python",
"numpy"
] |
Running 2 Gunicorn Apps and Nginx with Supervisord
| 39,341,226
|
<p>This problem has admittedly stumped me for months. I've just procrastinated fixing other bugs and putting this aside until now where it HAS to be fixed --</p>
<p>I am trying to run 2 separate gunicorn apps and start nginx within the same supervisord.conf file. When I start supervisor, I am able to successfully run the handlecalls app but when I go to the website that commentbox is responsible for loading, I get an internal service error (500).</p>
<p>When I run the handlecalls and commentbox apps separately with the commands following the command field, the apps run fine. Why is the commentbox program giving me a 500 error when I try to run both with supervisord?</p>
<h1>my supervisord script:</h1>
<pre><code>[program:nginx]
directory = /var/www/vmail
command = service nginx start -g "daemon off;"
autostart = True
[program:commentbox]
directory = /var/www/vmail
command = gunicorn app:app -bind 0.0.0.0:8000
autostart = True
[program:handlecalls]
directory = /var/www/vmail
command = gunicorn handle_calls:app --bind 0.0.0.0:8000
autostart = True
[supervisord]
directory = /var/www/vmail
logfile = /var/www/vmail/supervisorerrs.log
loglevel = trace
</code></pre>
| 1
|
2016-09-06T05:28:46Z
| 39,341,380
|
<p>This has nothing to do with supervisord. Supervisord is just a way for you to start/stop/restart your server. This has more to do with your server's configuration.</p>
<p>The basic: To serve two gunicorn apps with nginx, you have to run them on two different ports, then config nginx to proxy_pass the request to their respective ports. The reson is: once a process is running on a port, that port cannot be used by another process.</p>
<p>So change the configuration in your supervisord script to:</p>
<pre><code>[program:commentbox]
directory = /var/www/vmail
command = gunicorn app:app -bind 0.0.0.0:8000
autostart = True
[program:handlecalls]
directory = /var/www/vmail
command = gunicorn handle_calls:app --bind 0.0.0.0:8001
autostart = True
</code></pre>
<p>Then in your nginx server's configuration for <code>handlecalls</code></p>
<pre><code>proxy_pass 127.0.0.1:8081
</code></pre>
<p><strong>Update: Here is the basics of deploying a web application</strong></p>
<ol>
<li>As mentioned above, one port can only be listened by a process.</li>
<li>You can use nginx as a http server, listening to port <code>80</code> (or <code>443</code> for https), then passing the request to other applications listening to other ports (for example, <code>commentbox</code> on port <code>8000</code> and handlecalls on port <code>8001</code>)</li>
<li><p>You can add rules to nginx as how to serve your application by adding certain server configuration files in <code>/etc/nginx/sites-available/</code> (by default. It is different in some cases). The rules should specify a way for nginx to know which application it should send the request to, for example:</p>
<ul>
<li>To reuse the same http port (<code>80</code>), each application should be assigned to a different domain. i.e: <code>commentbox.yourdomain.com</code> for <code>commentbox</code> and <code>handlecalls.yourdomain.com</code> for <code>handlecalls</code></li>
<li>A way to serve two different apps on the same domain, is for them to serve on different ports. For example: <code>yourdomain.com</code> would serve <code>commentbox</code> and <code>yourdomain.com:8080</code> would serve <code>handlecalls</code></li>
<li>A way to serve two different apps on the same domain and the same ports, is for them to serve on two different endpoints. For example <code>yourdomain.com/commentbox</code> would serve <code>commentbox</code> and <code>yourdomain.com/handlecalls</code> would serve <code>handlecalls</code></li>
</ul></li>
<li><p>After adding configuration files to <code>/etc/nginx/sites-available/</code>, you must symlink those files to <code>/etc/nginx/sites-enabled/</code>, well, to tell nginx that you want to enable them. You can add the files directly to <code>/etc/nginx/sites-enabled/</code>, but I don't recommend it, since it doesn't give you a convenient way to enable/disable your application.</p></li>
</ol>
<p><strong>Update: Here is how to config nginx to serve gunicorn applications using two different subdomains:</strong></p>
<ol>
<li>Add two subdomains <code>commentbox.yourdomain.com</code> and <code>handlecalls.yourdomain.com</code>, and point them both to your server's IP.</li>
<li><p>Create a a configuration file for <code>commentbox</code> at <code>/etc/nginx/sites-available/commentbox</code> with the following content (edit as fit):</p>
<pre><code>server {
listen 80;
server_name commentbox.yourdomain.com;
root /path/to/your/application/static/folder;
location / {
try_files $uri @app;
}
location @app {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
proxy_pass http://127.0.0.1:8000;
}
}
</code></pre></li>
<li><p>Create a configuration file for <code>handlecalls</code> at <code>/etc/nginx/sites-available/handlecalls</code> with the following content (edit as fit):</p>
<pre><code>server {
listen 80;
server_name handlecalls.yourdomain.com;
root /path/to/your/application/static/folder;
location / {
try_files $uri @app;
}
location @app {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
proxy_pass http://127.0.0.1:8001;
}
}
</code></pre></li>
<li><p>Create symlinks to enable those servers:</p>
<pre><code>sudo ln -s /etc/nginx/sites-available/commentbox /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/handlecalls /etc/nginx/sites-enabled/
</code></pre></li>
<li><p>Restart nginx to take effect</p>
<pre><code>sudo service nginx restart
</code></pre></li>
</ol>
| 2
|
2016-09-06T05:41:54Z
|
[
"python",
"nginx",
"gunicorn",
"supervisord",
"supervisor"
] |
How to use sqlalchemy core for pagination in Flask?
| 39,341,583
|
<p>I am using flask framework with <strong>SQLAlchemy core</strong> only. My result set returned from the 'select' statement contains few thousands of records. I would like to use pagination to avoid memory error. How can I get a JSON output using cursor for api GET method, for any page dynamically? I have tried the accepted solution here <a href="http://stackoverflow.com/questions/4840731/how-to-use-cursor-for-pagination">How to use cursor() for pagination?</a>, but could not quite get it right. Please guide. Using PostgreSQL 9.4
Options I have tried:</p>
<p>1.</p>
<pre><code>@app.route('/test/api/v1.0/docs_page/<int:page>', methods=['POST'])
def search_docs_page(page):
if 'id' in session:
doc_list = []
no_of_pgs = 0
doc_list = common_search_code()
# doc_list is a resultset after querying the table for a set of query condition
header_dict = dict(request.headers)
for i in header_dict.items():
if i == 'Max-Per-Page':
max_per_pg = int(header_dict[i])
no_of_pgs = len(doc_list) / max_per_pg
print 'number of doc: ' + str(len(doc_list))
print 'number of pages: ' + str(no_of_pgs)
print 'max per page:' + str(max_per_pg)
print 'page number: '+ str(page)
page = int(request.args.get(page, type=int, default=1))
pagination = Pagination(page=page,
total=len(doc_list),
search=True, record_name='documents')
return jsonify({'pagination': list(pagination.__dict__),
'doc_list': doc_list}), 200
return jsonify({'message': "Unauthorized"}), 401
</code></pre>
<p>I want to control the number of records to be printed in each page by passing the parameter in the request header as in this curl:</p>
<p>curl -b cookies.txt -X POST <a href="http://localhost:8081/test/api/v1.0/docs_page/1" rel="nofollow">http://localhost:8081/test/api/v1.0/docs_page/1</a> -H 'max_per_page:4' -H 'Content-type:application/json'</p>
<pre><code>@app.route('/test/api/v1.0/docs_page2', methods=['POST'])
def search_docs_page2():
if 'id' in session:
docs = []
no_of_pgs = 0
doc_list = common_search_code()
header_dict = dict(request.headers)
for i in header_dict.items():
if i == 'Max-Per-Page':
max_per_pg = int(header_dict[i])
no_of_pgs = len(doc_list) / max_per_pg
print 'number of doc: ' + str(len(doc_list))
print 'number of pages: ' + str(no_of_pgs)
print 'max per page:' + str(max_per_pg)
page = int(request.form.get('page', type=int, default=1))
cursor = request.form.get('cursor')
if cursor:
print 'hey'
doc_list.with_cursor(cursor)
docs = doc_list.fetchmany(4)
for r in docs:
print r, 'rrrr'
return jsonify({'docs': docs}), 200
return jsonify({'message': "Unauthorized"}), 401
curl:curl -b cookies.txt -X POST http://localhost:8081/test/api/v1.0/docs_page2 -H 'max_per_page:4' -H 'Content-type:application/json' -F 'cursor=1'
</code></pre>
| 0
|
2016-09-06T05:59:38Z
| 39,362,995
|
<p>Currently, I have made changes to the above code to work this way:</p>
<pre><code>@app.route('/test/api/v1.0/docs_page2', methods=['POST'])
def search_docs_page2():
if 'id' in session:
docs = []
no_of_pgs = 0
header_dict = dict(request.headers)
for k in header_dict:
print header_dict[k], 'key', k
if 'Max-Per-Page' in header_dict.keys():
max_per_pg = int(header_dict['Max-Per-Page'])
page_no = int(request.headers.get('page_no', type=int, default=1))
offset1 = (page_no - 1) * max_per_pg
query1 = common_search_code()
s = query1.limit(max_per_pg).offset(offset1)
rs = conn.execute(s)
for r in rs:
docs.append(dict(r))
# no_of_pgs = float(len(doc_list) / float(max_per_pg))
no_of_pgs = float(len(docs) / float(max_per_pg))
no_of_pgs = int(math.ceil(no_of_pgs))
print 'number of doc: ' + str(len(docs))
print 'number of pages: ' + str(no_of_pgs)
print 'max per page:' + str(max_per_pg)
# docs.append(doc_list[offset:(offset + max_per_pg)])
return jsonify({'docs': docs,
'no_of_pages': str(no_of_pgs)}), 200
return jsonify({'message': "Max. per page not specified"}), 400
return jsonify({'message': "Unauthorized"}), 401
</code></pre>
<p>Curl for the same:</p>
<pre><code>curl -b cookies.txt -X POST http://localhost:8081/test/api/v1.0/docs_page2 -H 'max_per_page:4' -H 'Content-type:application/json' -H 'page_no:2'
</code></pre>
| 0
|
2016-09-07T06:50:04Z
|
[
"python",
"pagination",
"sqlalchemy"
] |
Numpy memmap better IO and memory usage
| 39,341,636
|
<p>Currently I am working with a NumPy memmap array with 2,000,000 * 33 * 33 *4 (N * W * H * C) data. My program reads <strong><em>random (N) indices</em></strong> from this array.</p>
<p>I have 8GB of RAM, 2TB HDD. The HDD read IO is only around 20M/s, RAM usage stays at 2.5GB. It seems that there is a HDD bottleneck because I am retrieving random indices that are obviously not in the memmap cache. Therefore, I would like the memmap cache to use RAM as much as possible.</p>
<p>Is there a way for me to tell memmap to maximize IO and RAM usage?</p>
| 0
|
2016-09-06T06:04:08Z
| 39,344,643
|
<p>(Checking my python 2.7 source)
As far as I can tell NumPy memmap uses mmap.
mmap does define:</p>
<pre><code># Variables with simple values
...
ALLOCATIONGRANULARITY = 65536
PAGESIZE = 4096
</code></pre>
<p>However i am not sure it would be wise (or even possible) to change those.
Furthermore, this may not solve your problem and would definitely not give you the most efficient solution, because there is caching and page reading at OS level and at hardware level (because for hardware it takes more or less the same time to read a single value or the whole page).</p>
<p>A much better solution would probably be to sort your requests. (I suppose here that N is large, otherwise just sort them once):
Gather a bunch of them (say one or ten millions?) and before doing the request, sort them. Then ask the ordered queries. Then after getting the answers put them back in their original order...</p>
| 1
|
2016-09-06T08:51:20Z
|
[
"python",
"numpy",
"mmap",
"memory-mapped-files"
] |
Centering line scatterplot in plotly
| 39,341,673
|
<p>I am creating a line scatter plot using plotly python API. There are old and new data plotted in y-axis with the date in the x-axis.I would like to center the graph such that one part of the graph is old data and another half of the graph is new data. How can this be done in plotly?In the attached image, the blue one represents old and orange represents new data. How old and new can be centered such that one part of the graph is old data and another half of the graph is new data?
<a href="http://i.stack.imgur.com/5Qm16.png" rel="nofollow">Plotly_Line_Scatterplot</a></p>
| -1
|
2016-09-06T06:07:35Z
| 39,341,950
|
<p>Building on the manual axes example from the <a href="https://plot.ly/python/axes/" rel="nofollow">Plotly documentation</a>:</p>
<pre><code>import plotly.plotly as py
import plotly.graph_objs as go
xold=[5, 6, 7, 8]
yold=[3, 2, 1, 0]
xnew=[10, 11, 12, 13, 14, 15, 16, 17, 18]
ynew=[0, 1, 2, 3, 4, 5, 6, 7, 8]
oldData = go.Scatter(xold, yold)
newData = go.Scatter(xnew, ynew)
data = [oldData, newData]
lenOld = max(xold) - min(xold)
lenNew = max(xnew) - min(xnew)
lenX = 2*max(lenOld,lenNew)
layout = go.Layout(
xaxis=dict(
range=[min(xnew)-lenX/2, min(xnew)+lenX/2]
)
)
fig = go.Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename='axes-range-manual')
</code></pre>
<p>For simplicity I have used integers as x-values rather than using dates but the same principle will apply. </p>
<p>Please note, I don't have <code>plotly</code> installed at present so I haven't tested this code. </p>
| 0
|
2016-09-06T06:28:05Z
|
[
"python",
"graph",
"center",
"scatter-plot",
"plotly"
] |
account.invoice add custom computed & filtered field
| 39,341,727
|
<p>I'm sorry for my English</p>
<p>I am writing a custom Odoo module and my goal is add a custom computed field in account.invoice with the sum of every tax value stored in tax_line_ids amount field (excluding negative withholdings); this is my code:</p>
<pre><code># -*- coding: utf-8 -*-
from openerp import models, fields, api
class account_invoice(models.Model):
_inherit = 'account.invoice'
x_sum_stored_taxes_exclude_withholding = fields.Float('Total Taxes', compute='_compute_total_taxes', digits=(12,2), store=True)
@api.one
@api.depends('tax_line_ids.amount')
def _compute_total_taxes(self):
for record in self:
record.x_sum_stored_taxes_exclude_withholding = sum(line.amount for line in record.x_sum_stored_taxes_exclude_withholding)
</code></pre>
<p>But the result in the new field "x_sum_stored_taxes_exclude_withholding" is filled only with zero's. I really tried many ways and I can not find the right one!</p>
<p>Help!!
:'(</p>
| 1
|
2016-09-06T06:11:12Z
| 39,344,119
|
<pre class="lang-py prettyprint-override"><code>record.x_sum_stored_taxes_exclude_withholding =\
sum(line.amount for line in record.x_sum_stored_taxes_exclude_withholding)
</code></pre>
<p>You should use `tax_line_ids ?</p>
<pre class="lang-py prettyprint-override"><code>record.x_sum_stored_taxes_exclude_withholding =\
sum([line.amount for line in record.tax_line_ids])
</code></pre>
<p>And ofcourse you need only positive values:</p>
<pre class="lang-py prettyprint-override"><code>record.x_sum_stored_taxes_exclude_withholding =\
sum([line.amount for line in record.tax_line_ids if line.amount >= 0.0])
</code></pre>
| 0
|
2016-09-06T08:27:08Z
|
[
"python",
"openerp",
"odoo-8",
"odoo-9"
] |
two charset in one website,how to parse
| 39,341,801
|
<p>i was study python scraping knowledge recently,and i want to scrap a website</p>
<p><a href="http://news.sina.com.cn/" rel="nofollow">a website with two charset,utf-8 and gb2312</a></p>
<p>i get the warning from beautifulsoup: </p>
<blockquote>
<p>Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER.</p>
</blockquote>
<p>i google the problem and i think it may be the decode problem,my code can scrap other website smoothly.</p>
<p>so ,what should i do?</p>
<p>this is my code:</p>
<pre><code>from urllib.request import urlopen
from bs4 import BeautifulSoup
code_type = 'utf-8'
html = urlopen("http://news.sina.com.cn/")
print(html)
bsObj = BeautifulSoup(html, "html.parser",from_encoding=code_type)
imglist = bsObj.findAll("img")
print(imglist)
</code></pre>
| 0
|
2016-09-06T06:16:30Z
| 39,341,858
|
<p>Detect the page coding before parsing it.</p>
<p>Reference to chardet repo
<a href="https://github.com/chardet/chardet" rel="nofollow">https://github.com/chardet/chardet</a>.</p>
<p>You should't set the code_type as utf-8 for all pages, detect the right encoding of page and modify it to the right one.</p>
<p>Encoding detecting might be failed sometime. In that case, you should prepare a dict to store known websites' encoding and use the dict while parsing special pages.</p>
| 0
|
2016-09-06T06:20:58Z
|
[
"python",
"web-scraping",
"beautifulsoup"
] |
Python to detect latex mathematics using regular expressions or other methods
| 39,341,886
|
<p>I want to detect if a long text string (input from "somewhere") contains mathematical expressions <a href="https://en.wikibooks.org/wiki/LaTeX/Mathematics" rel="nofollow">encoded in LaTeX</a>. This means searching for substrings (denoted <code>...</code> in what follows) enclosed inside either of:</p>
<ol>
<li><code>$...$</code></li>
<li><code>\[...\]</code></li>
<li><code>\(...\)</code></li>
<li><code>\begin{displaymath} ... \end{displaymath}</code></li>
</ol>
<p>There are some variations of item 3 with other keywords than <code>displaymath</code>, and there may be a whitespace inside the brace, etc., but I suppose I can figure out the rest once I get (1), (2), (3) working.</p>
<p>For (1), I suppose I can do the following:</p>
<pre><code>import re
if re.search(r"$(\w+)$", str):
(do something)`
</code></pre>
<p>But I am having problems with the others, especially when it has the <code>\</code>. Help would be appreciated.</p>
<p>The python version should be 2.7.12 but ideally code that works for both versions 2.x and 3.x will be preferred.</p>
| 0
|
2016-09-06T06:23:04Z
| 39,342,081
|
<p>You need to escape <code>\</code>,<code>[</code>,<code>]</code>,<code>{</code>,<code>}</code>,<code>(</code>,<code>)</code> as they have special meaning in regular expression. </p>
<p>So, you need to add an extra <code>\</code> before them, when you want to match them literally. </p>
<p>For your second pattern, use:</p>
<pre><code>\\\[(.+?)\\\]
</code></pre>
<p>For third pattern, use:</p>
<pre><code>\\\((.+?)\\\)
</code></pre>
<p>For fourth pattern,</p>
<pre><code>\\begin\{displaymath\}(.+?)\\end\{displaymath\}
</code></pre>
<p>You can see the demo for the fourth pattern <a href="https://regex101.com/r/xG8mA8/1" rel="nofollow">here</a>.</p>
| 0
|
2016-09-06T06:37:07Z
|
[
"python",
"string-matching"
] |
Django Rest Framework: Filter/Validate Related Fields
| 39,341,994
|
<p>I have two models: Foo which carries an owner field and Bar which has a relation to Foo:</p>
<pre><code>class Foo(models.Model):
owner = models.ForeignKey('auth.User')
name = models.CharField(max_length=20, null=True)
class Bar(models.Model):
foo = models.OneToOneField(Foo, related_name='bar')
[...]
</code></pre>
<p>I use HyperlinkedModelSerializer for representation:</p>
<pre><code>class BarSerializer(serializers.HyperlinkedModelSerializer):
foo = serializers.HyperlinkedRelatedField(view_name='foo-detail', queryset=Foo.objects.all())
[...]
class Meta:
model = Bar
fields = ('foo', [...])
class FooSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.SlugRelatedField(read_only=True, slug_field='username')
bar = serializers.HyperlinkedRelatedField(view_name='bar-detail', read_only=True)
class Meta:
model = Foo
fields = ('name', 'bar', 'owner')
</code></pre>
<p>My views look like this:</p>
<pre><code>class FooViewSet(viewsets.ModelViewSet):
queryset = Foo.objects.all()
serializer_class = FooSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwner,)
def get_queryset(self):
user = self.request.user
if not user.is_authenticated():
return Foo.objects.none()
if user.username == "admin":
return Foo.objects.all()
return Foo.objects.filter(owner=user)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class BarViewSet(viewsets.ModelViewSet):
queryset = Bar.objects.all()
serializer_class = BarSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwner,)
def get_queryset(self):
user = self.request.user
if not user.is_authenticated():
return Bar.objects.none()
if user.username == "admin":
return Bar.objects.all()
return Bar.objects.filter(foo__owner=user)
</code></pre>
<p>I don't whant User A to be able to see User B's stuff and vice versa. That works pretty well so far with one exception:</p>
<p>User A created an instance of Foo but doesn't instantly create an instance of Bar linking to Foo. Now User B can guess the URL to User A's Foo instance and specify that when creating his instance of Bar. </p>
<p>At this point, User A gets an instance of Bar which he didn't create.</p>
<p>I'm new to Django and rest_framework, so I have no idea how to solve this. Can somebody get me on the right track? My first idea was to use the foo field in BarSerializer to filter Foos using the queryset. But I didn't figure out how to get access to the auth.User object from there.</p>
| 2
|
2016-09-06T06:31:04Z
| 39,343,567
|
<p>You can access the request inside a Serializer if you <a href="http://www.django-rest-framework.org/api-guide/serializers/#including-extra-context" rel="nofollow">include it in its context</a>.
Then you can do <a href="http://www.django-rest-framework.org/api-guide/serializers/#field-level-validation" rel="nofollow">field level validation</a> inside the Bar serializer:</p>
<pre><code>def validate_foo(self, val):
user = self.context['request'].user
try:
foo = Foo.objects.get(pk=val)
except Foo.DoesNotExist:
raise serializers.ValidationError("Some Error")
if foo.user is not user:
raise serializers.ValidationError("Some Error")
return value
</code></pre>
| 0
|
2016-09-06T07:57:42Z
|
[
"python",
"django",
"django-rest-framework"
] |
Dynamically created tasks/dags are not working in apache airflow
| 39,342,255
|
<p>I'm created a DAG with scheduling @daily interval and separate task id for every workflow. But Its is not running as excepted. Is it possible to do like this? Is there any other ways to create dynamic tasks for a particular dag? And to pause a particular task instance using command line?</p>
<pre><code>from __future__ import print_function
from builtins import range
from airflow.operators import PythonOperator,DummyOperator,BranchPythonOperator,SqlSensor
from airflow.models import DAG
from datetime import datetime, timedelta
import time
from pprint import pprint
seven_days_ago = datetime.combine(
datetime.today() - timedelta(7), datetime.min.time())
args = {
'owner': 'varakumar',
'start_date': seven_days_ago,
}
dag = DAG(
dag_id='dynamic_task_creation', default_args=args,
schedule_interval="@daily")
def get_decision():
return "right"
start = DummyOperator(
task_id='start',
dag=dag)
td=datetime.today()
x=str(datetime(td.year,td.month,td.day,td.hour,td.minute,td.second)).replace (" ", "_").replace (":", "-")
pause_task_id = ("pause-%s" % x)
pause = DummyOperator(
task_id=pause_task_id,
dag=dag)
pause.set_upstream(start)
decision = BranchPythonOperator(
task_id='decision',
python_callable=lambda: get_decision(),
dag=dag)
decision.set_upstream(pause)
left = DummyOperator(
task_id='left',
dag=dag)
left.set_upstream(decision)
right = DummyOperator(
task_id='right',
dag=dag)
right.set_upstream(decision)
</code></pre>
<p>Thank you in advance</p>
| 0
|
2016-09-06T06:47:34Z
| 39,400,952
|
<p>The first problem I see is that you're using a dynamic <code>start_date</code>. I've seen some weird behavior when doing that, and I think it's based on the way that airflow maintains its list of past dagruns. Try to specify a fixed <code>start_date</code> and see if that resolves anything.</p>
<p>In either case, the airflow docs <a href="https://airflow.incubator.apache.org/code.html#airflow.models.BaseOperator" rel="nofollow">advise against dynamic start dates</a> (scroll down a bit and read the description for <code>start_date</code>).</p>
<p>EDIT: Also check <a href="https://airflow.incubator.apache.org/faq.html#what-s-the-deal-with-start-date" rel="nofollow">this</a> out for more info on that.</p>
| 0
|
2016-09-08T22:12:23Z
|
[
"python",
"airflow"
] |
Python while loop does not work properly
| 39,342,318
|
<p>I am using a <code>while</code> loop inside a <code>if</code> / <code>else</code> condition. For some reason under one condition the while loop does not work. The condition is shown in my code below. Under these conditions I would assume that the <code>else</code> condition should be utilized and the <code>weight</code> and the <code>max_speed</code> should be decreased until both <code>while</code> conditions are not valid anymore. What am I doing wrong?</p>
<pre><code>weight = 0
max_speed = 15
if weight == 0 and max_speed <= 10:
while weight == 0 and max_speed <= 10:
weight=weight+1
print(weight)
print(max_speed)
else:
while weight != 0 and max_speed > 10:
weight = weight-1
max_speed=max_speed-1
print(weight)
print(max_speed)
</code></pre>
| 0
|
2016-09-06T06:50:53Z
| 39,342,484
|
<p>I think you are confused between <code>or</code> and <code>and</code>.</p>
<p><code>and</code> means that the expression will be <code>True</code> if both condition satisfies. Where <code>or</code> means any condition satisfies.</p>
<p>Now based on your code:</p>
<pre><code>weight = 0
max_speed = 15
if weight == 0 and max_speed <= 10:
# Goes to else block since max_speed = 15 which is >10
else:
# This while won't be executed since weight = 0
while weight != 0 and max_speed > 10:
</code></pre>
| 1
|
2016-09-06T06:58:11Z
|
[
"python",
"if-statement",
"while-loop"
] |
Python while loop does not work properly
| 39,342,318
|
<p>I am using a <code>while</code> loop inside a <code>if</code> / <code>else</code> condition. For some reason under one condition the while loop does not work. The condition is shown in my code below. Under these conditions I would assume that the <code>else</code> condition should be utilized and the <code>weight</code> and the <code>max_speed</code> should be decreased until both <code>while</code> conditions are not valid anymore. What am I doing wrong?</p>
<pre><code>weight = 0
max_speed = 15
if weight == 0 and max_speed <= 10:
while weight == 0 and max_speed <= 10:
weight=weight+1
print(weight)
print(max_speed)
else:
while weight != 0 and max_speed > 10:
weight = weight-1
max_speed=max_speed-1
print(weight)
print(max_speed)
</code></pre>
| 0
|
2016-09-06T06:50:53Z
| 39,342,546
|
<p>Assuming that you need your <code>weight=0</code> and <code>max_speed=10</code>; You can do this -> </p>
<pre><code>weight = 0
max_speed = 15
while weight !=0 or max_speed > 10:
if weight>0:
weight = weight-1
else:
weight = weight+1
if max_speed>10:
max_speed=max_speed-1
print("{} {}".format(weight, max_speed))
</code></pre>
<p>Your output looks like -></p>
<pre><code>1 14
0 13
1 12
0 11
1 10
0 10
</code></pre>
| 2
|
2016-09-06T07:01:34Z
|
[
"python",
"if-statement",
"while-loop"
] |
My python threads seem to freeze raspberry pi
| 39,342,335
|
<p>I wrote this python code to run continuously on my raspberry pi with Raspian by:
' nohup python code.py & '</p>
<p>It works like intended for a while (anything from 5 mins to 60), then seems to freeze my pi (I have not connected a monitor yet, but it kills the remote connection and the green on-LED stops),
There should not start more then maybe 6 threads at once as they finish, but it might still overload.</p>
<p>My question is, am I doing something wrong or could I optimize it for performance?</p>
<p>And it writes a HUGE amount of text to the "nohup-document", can this cause problems?</p>
<pre><code>#This downloads the link using "youtube-dl"
def Download(link):
command = "youtube-dl " + link
call(command.split(), shell=False)
#This check if the link exist in document, else writes it to the document and start downloading it
def CheckAndDL2(DLlink):
if not DLlink in open('usedlinks.txt').read():
f = open('usedlinks.txt', 'a')
f.write(DLlink + "\n")
f.close()
try:
thread.start_new_thread(Download, (DLlink,))
except:
print("unable to start thread1")
while 1:
#getLinks will update links[] with new urls
getLinks(myurl)
CheckAndDL2(links[1])
time.sleep(10)
CheckAndDL2(links[2])
time.sleep(10)
CheckAndDL2(links[3])
print('Loop done')
links = []
time.sleep(120)
</code></pre>
| 0
|
2016-09-06T06:51:37Z
| 39,354,528
|
<p>Stupid me! I was using a <strong>powersupply</strong> with a current output at 0.45mA. I changed to 1A and no problems since!</p>
| 1
|
2016-09-06T17:17:27Z
|
[
"python",
"multithreading",
"raspberry-pi",
"nohup",
"youtube-dl"
] |
Simple 'chat' UDP client and server using Python, can't use `str` as `send()` payload
| 39,342,336
|
<p>Iam trying to do a simple 'chat' using UDP in python. I have done both client and server code that is, </p>
<h1>client</h1>
<pre><code>import socket
fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM )
udp_ip = '127.0.0.1'
udp_port = 8014
while(True):
message = input("Client :")
fd.sendto(message, (udp_ip, udp_port))
reply = fd.recvfrom(1000)
print("Server:%s"%(reply))
</code></pre>
<h1>server</h1>
<pre><code>import socket
udp_ip = '127.0.0.1'
udp_port = 8014
fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
fd.bind((udp_ip,udp_port))
while True:
r = fd.recvfrom(1000)
print("client : %s"%(r[0]))
reply = input('server : ')
client_address = r[1]
fd.sendto(reply, client_address)
</code></pre>
<p>In the client side iam getting </p>
<pre><code>python client.py
Client :'haii'
</code></pre>
<p>In the server side iam getting, </p>
<pre><code> python server.py
client : 'haii'
server : 'hai there'
Traceback (most recent call last):
File "server.py", line 12, in <module>
fd.sendto(reply, client_address)
Type Error: a bytes-like object is required, not 'str'
</code></pre>
<p>How to solve this problem? Is anything wrong there?</p>
<p>~ </p>
| 1
|
2016-09-06T06:51:41Z
| 39,342,485
|
<blockquote>
<p>How to solve this problem? Is anything wrong there?</p>
</blockquote>
<p>well:</p>
<blockquote>
<pre><code>fd.sendto(reply, client_address)
Type Error: a bytes-like object is required, not 'str'
</code></pre>
</blockquote>
<p>As the error says, you can't directly send a string (Python3 strings are a bit more than just a container of bytes); you must convert it to a <code>bytearray</code> first:</p>
<pre><code> fd.sendto(bytearray(reply,"utf-8"), client_address)
</code></pre>
<p>Notice that you need to specify the encoding; that makes a lot of sense, if you think about how differently characters that aren't usual in English are represented on a byte level. Upside of this conversion is that you can, with unicode, send pretty much anything that is text in any language:</p>
<pre><code>fd.sendto(bytearray("सà¥à¤à¤¦à¤° à¤à¤¾à¤·à¤¾","utf-8"), client_address)
</code></pre>
<p>On the other end, you will receive a byte thing, too, and that must be converted to a string first; again, the encoding makes a difference, and you must use the same encoding as to send:</p>
<pre><code>r = fd.recvfrom(1000)
received_msg = str(r, "utf-8")
</code></pre>
<p>Your <code>print("%s" % r )</code> implicitly calls <code>str</code> with default encoding, but that is very likely not a good idea in a network thing. Using utf-8 is pretty much a very good approach to encode strings as bytes. </p>
<p>To give a minimal amount of background: A string should really behave like a string â i.e., a piece of text composed of letters/glyphs/symbols, a representation of <em>text</em>, not some piece of binary memory. Hence, when sending a piece of memory over to someone else, you need to make sure that your text is understood based on a common representation, in this case, UTF8, on both ends.</p>
| 1
|
2016-09-06T06:58:14Z
|
[
"python",
"udp"
] |
Pandas select columns using slicing and integer index
| 39,342,351
|
<p>I am trying to select columns 2 and 4: (column 4 till the end):</p>
<pre><code>df3.iloc[:, [2, 4:]]
</code></pre>
<blockquote>
<p>File "", line 1<br>
df3.iloc[:, [2, 4:]]<br>
___________^<br>
SyntaxError: invalid syntax </p>
</blockquote>
<p>I get an error message obviously. There are many columns after col 4 so writing something like this does not feel right: [2, 4, 5, 6, 7, ...]</p>
<p>Is there any other quick way of doing this?</p>
| 1
|
2016-09-06T06:52:14Z
| 39,342,508
|
<p>You can use <code>range</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html" rel="nofollow"><code>shape</code></a>:</p>
<pre><code>df3 = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (df3)
A B C D E F
0 1 4 7 1 5 7
1 2 5 8 3 3 4
2 3 6 9 5 6 3
cols = ([2] + list(range(4,df3.shape[1])))
print (cols)
[2, 4, 5]
print (df3.iloc[:,cols])
C E F
0 7 5 7
1 8 3 4
2 9 6 3
</code></pre>
<p>Another solution with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow"><code>numpy.r_</code></a>:</p>
<pre><code>cols1 = np.r_[2, np.arange(4,df3.shape[1])]
print (cols1)
[2 4 5]
print (df3.iloc[:,cols1])
C E F
0 7 5 7
1 8 3 4
2 9 6 3
</code></pre>
| 2
|
2016-09-06T06:59:23Z
|
[
"python",
"pandas",
"indexing",
"dataframe",
"slice"
] |
Python: Which will take less memory and execution is fast?
| 39,342,382
|
<p>I have a ResponseMessageService() class, Which have several methods.
I need only one method.</p>
<p>Then Which is better?</p>
<p>call that method directly? by</p>
<pre><code> ResponseMessageService().WrongRegMsg(data="Your Reg ID is wrong!")
</code></pre>
<p>or take a object </p>
<pre><code> response_message_service = ResponseMessageService()
</code></pre>
<p>Then call </p>
<pre><code> response_message_service.WrongRegMsg(data="Your Reg ID is wrong!")
</code></pre>
<p>Which will took less memory and execution is first?</p>
| 1
|
2016-09-06T06:53:31Z
| 39,342,715
|
<p>Regarding your question, </p>
<pre><code>ResponseMessageService().WrongRegMsg(data="Your Reg ID is wrong!")
</code></pre>
<p>would likely to take less memory.</p>
<p>Assigning the instance to a variable makes it retained in the memory, at least until the variable's name is unbound, for example, by using <code>del response_message_service</code></p>
| 1
|
2016-09-06T07:13:07Z
|
[
"python"
] |
How to integrate odoo with elastix
| 39,342,483
|
<p>I am trying to integrate <strong>Odoo</strong> with <strong>Elastix</strong> . so i downloads all the module from <a href="https://github.com/OCA/connector-telephonyt" rel="nofollow">https://github.com/OCA/connector-telephony</a> . and install asterisk_click2dial, base_phone, crm_phone module , but i don't understand how this is configure , like AMI login and password, asterisk server name or if you installed this , you may be better know all the fields of telephony menu . i both the OS installed in virtual box also , if you have any idea please share with me .</p>
| 0
|
2016-09-06T06:58:05Z
| 39,368,540
|
<p>AMI Manager login/password for elastix can be added in /etc/asterisk/manager_custom.conf</p>
<p>Most likly you should read more about AMI interface.</p>
<p>You question is too broad. First of all can recommend read entry-level book for asterisk (for example Asterisk The Future of Telephony), after that study doc for AMI(useless without asterisk understanding)</p>
<p><a href="https://wiki.asterisk.org/wiki/pages/viewpage.action?pageId=4817239" rel="nofollow">https://wiki.asterisk.org/wiki/pages/viewpage.action?pageId=4817239</a></p>
| 0
|
2016-09-07T11:21:54Z
|
[
"python",
"openerp",
"asterisk",
"elastix"
] |
Why am I getting the error: OperationalError at /table/ no such table: table_book
| 39,342,532
|
<p>Whenever I run the program, I get the following error:</p>
<pre><code>OperationalError at /table/
no such table: table_book
</code></pre>
<p>It says that there's an error on line 7 in my template file.</p>
<p>Here is my template.html:</p>
<pre><code><table>
<tr>
<th>author</th>
<th>title</th>
<th>publication year</th>
</tr>
{% for b in obj %}
<tr>
<td>{{ b.author }}</td>
<td>{{ b.title }}</td>
<td>{{ b.publication_year }}</td>
</tr>
{% endfor %}
</table>
</code></pre>
<p>Here is my views.py:</p>
<pre><code>from django.shortcuts import render
def display(request):
return render(request, 'template.tmpl', {'obj': models.Book.objects.all()})
</code></pre>
<p>Here is my models.py:</p>
<pre><code>from django.db import models
class Book(models.Model):
author = models.CharField(max_length = 20)
title = models.CharField(max_length = 40)
publication_year = models.IntegerField()
</code></pre>
<p>Here is my urls.py:</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
# /table/
url(r'^$', views.display, name='display'),
]
</code></pre>
<p>Can somebody please tell me what is wrong?</p>
| -1
|
2016-09-06T07:00:22Z
| 39,342,594
|
<p>The database table table_book is missing. Did you run makemigrations and migrate ?</p>
| 0
|
2016-09-06T07:04:37Z
|
[
"python",
"django"
] |
(Python) Issue with linux command unrar, cannot for the life of me figure out why
| 39,342,552
|
<p>So recently i made a thread here about needing help with a script that should automatically extract <code>.rar</code> files and <code>.zip</code> files for me, without user interaction. With the various help of people i have made this:</p>
<pre><code>import os
import re
from subprocess import check_call
from os.path import join
rx = '(.*zip$)|(.*rar$)|(.*r00$)'
path = "/mnt/externa/Torrents/completed/test"
for root, dirs, files in os.walk(path):
if not any(f.endswith(".mkv") for f in files):
found_r = False
for file in files:
pth = join(root, file)
try:
if file.endswith(".zip"):
print("Unzipping ",file, "...")
check_call(["unzip", pth, "-d", root])
found_zip = True
elif not found_r and file.endswith((".rar",".r00")):
check_call(["unrar","e","-o-", pth, root])
found_r = True
break
except ValueError:
print ("OOps! That did not work")
</code></pre>
<p>The first time i run this script on .rar files it works amazing, it extracts files to the right directory and everything but if i run it again it prints an error:</p>
<pre><code>Extracting from /mnt/externa/Torrents/completed/test/A.Film/Subs/A.Film.subs.rar
No files to extract
Traceback (most recent call last):
File "unrarscript.py", line 20, in <module>
check_call(["unrar","e","-o-", pth, root])
File "/usr/lib/python2.7/subprocess.py", line 541, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['unrar', 'e', '-o-', '/mnt/externa/Torrents/completed/test/A.Film/Subs/A.Film.subs.rar', '/mnt/externa/Torrents/completed/test/A.Film/Subs']' returned non-zero exit status 10
</code></pre>
<p>So i tried with a Try/except but i don't think i did it right, can anyone help on the finishing touches for this script?</p>
| 0
|
2016-09-06T07:01:58Z
| 40,065,661
|
<p>The <code>check_call</code> raises the <code>CalledProcessError</code> exception when unrar returns an error code different from zero.</p>
<p>Your error message show this:</p>
<blockquote>
<p>returned non-zero exit status 10</p>
</blockquote>
<p><code>Rar.txt</code> contains the following list of error codes: (can be found in WinRAR installation folder)</p>
<pre><code> Code Description
0 Successful operation.
1 Non fatal error(s) occurred.
2 A fatal error occurred.
3 Invalid checksum. Data is damaged.
4 Attempt to modify an archive locked by 'k' command.
5 Write error.
6 File open error.
7 Wrong command line option.
8 Not enough memory.
9 File create error
10 No files matching the specified mask and options were found.
11 Wrong password.
255 User stopped the process.
</code></pre>
<p>I see you use <code>-o-</code> to "Skip existing files." when trying to overwrite a file. If the packed file already exists, error code 10 will be returned. If you immediately rerun your script, it is normal that this error is thrown.</p>
<pre><code>C:\>unrar e -o- testfile.rar
UNRAR 5.30 freeware Copyright (c) 1993-2015 Alexander Roshal
Extracting from testfile.rar
No files to extract
C:\>echo %errorlevel%
10
</code></pre>
<p>You can probably do something like this to handle it:</p>
<pre><code>except CalledProcessError as cpe:
if cpe.returncode == 10:
print("File not overwritten")
else:
print("Some other error")
</code></pre>
<p>I see you try to extract vobsubs. There is also a small chance the .sub rar inside the vobubs rar has the same file name.</p>
| 0
|
2016-10-16T00:37:09Z
|
[
"python",
"linux",
"unrar"
] |
Know if child class has implemented a parent method
| 39,342,657
|
<p>I have a base class class X, and a child class Y which could reimplement or not a method from the base class X.</p>
<p>I pass the name of the child class as a variable to functions. </p>
<p>Inside those functions I need to test if that class passed has implemented or not some methods from it's base class.</p>
<p>(I can't use hasattr(childClassName.methodName) since it always returns True)</p>
| 0
|
2016-09-06T07:09:23Z
| 39,342,800
|
<p>use to compare:</p>
<pre><code> getattr(className, 'methodName') is getattr(className, 'method')
</code></pre>
<p>if <code>false</code>, the method was overridden</p>
| 1
|
2016-09-06T07:16:55Z
|
[
"python",
"python-2.7",
"python-2.x"
] |
Access properties defined with in parentheses
| 39,342,740
|
<p>I'm using antlr4 with python2 target,</p>
<pre><code>additive_expression returns [value] @init{$value = 0;}
: multiplicative_expression ((PLUS_OPERATOR | MINUS_OPERATOR) multiplicative_expression)*
</code></pre>
<p>Since the <code>((PLUS_OPERATOR | MINUS_OPERATOR) multiplicative_expression)</code> expression appears zero or multiple times, </p>
<p>I will need to access each of it separately then calculate the final value.</p>
<p>Any ideas? I've tried the following, non of them works</p>
<ol>
<li>use <code>re = (...)</code> and antlr says I can't define it for non-sets</li>
<li>use <code>op = (PLUS_OPERATOR | MINUS_OPERATOR)</code> etc. but it always point to the last appearance of the expression</li>
</ol>
| 1
|
2016-09-06T07:14:18Z
| 39,346,883
|
<p>Try something like this:</p>
<pre><code>additive_expression returns [value]
@init{$value = 0;}
: e1=multiplicative_expression {$value = $e1.value;}
( PLUS_OPERATOR e2=multiplicative_expression {$value += $e2.value;}
| MINUS_OPERATOR e2=multiplicative_expression {$value -= $e2.value;}
)*
;
</code></pre>
<p>Or better, use a visitor instead of embedding target code inside your grammar<sup>1</sup>.</p>
<p><sup>1</sup> <a href="http://stackoverflow.com/questions/23092081/antlr4-visitor-pattern-on-simple-arithmetic-example">ANTLR4 visitor pattern on simple arithmetic example</a></p>
| 1
|
2016-09-06T10:34:17Z
|
[
"python",
"antlr",
"antlr4"
] |
How to format the slider value to datetime pattern in the matplotlib figure?
| 39,342,833
|
<p><a href="http://i.stack.imgur.com/TJgcf.png" rel="nofollow">The figure picture!</a>
Just like the picture, how can i format the number to datetime pattern. For example format 1472860800.0 to 2016-09-03.It can't use the datetime module to format directly. The key point is that it should be formatted in the matplotlib firgure. It is a slider value, and i have read the matplotlib docs ,but i haven't found the sloution.Thanks!</p>
| 0
|
2016-09-06T07:18:32Z
| 39,342,916
|
<p>Use <a href="https://docs.python.org/2/library/datetime.html#module-datetime" rel="nofollow">datetime</a> module</p>
<pre><code>>>> from datetime import datetime
>>> datetime.fromtimestamp(1472860800).strftime("%Y-%m-%d")
'2016-09-03'
</code></pre>
| 0
|
2016-09-06T07:23:02Z
|
[
"python",
"matplotlib"
] |
Running Jupyter kernel and notebook server on different machines
| 39,342,838
|
<p>I'm trying to run an iPython/ Jupyter kernel and the notebook server on two different Windows machines on a LAN.</p>
<p>From most of the links that I found on the internet, they offer advice on how we can access a remote kernel + server setup from a web browser, but no information on how to separate the kernel and the notebook server themselves.</p>
<p>Ideally, I'd like the code to remain on one machine, and the execution to happen on the other.</p>
<p>Is there a way that I could do this?</p>
| 0
|
2016-09-06T07:18:38Z
| 39,394,467
|
<p>This can be done, though it is a bit fiddly, and I do not believe that anyone has done it before on Windows. Jupyter applications use a class called a <a href="http://jupyter-client.readthedocs.io/en/latest/api/manager.html#jupyter_client.KernelManager" rel="nofollow">KernelManager</a> to start/stop kernels. KernelManager provides an API that is responsible for launching kernel processes, and collecting the network information necessary to connect to them. There are two implementations of remote kernels that I know of:</p>
<ul>
<li><a href="https://github.com/danielballan/remotekernel" rel="nofollow">remotekernel</a></li>
<li><a href="https://github.com/korniichuk/rk" rel="nofollow">rk</a></li>
</ul>
<p>Both of these use ssh to launch the remote kernels, and assume unix systems. I don't know how to launch processes remotely on Windows, but presumably you could follow the example of these two projects to do the same thing in a way that works on Windows.</p>
| 0
|
2016-09-08T15:08:01Z
|
[
"python",
"ipython",
"jupyter",
"jupyter-notebook"
] |
Running Jupyter kernel and notebook server on different machines
| 39,342,838
|
<p>I'm trying to run an iPython/ Jupyter kernel and the notebook server on two different Windows machines on a LAN.</p>
<p>From most of the links that I found on the internet, they offer advice on how we can access a remote kernel + server setup from a web browser, but no information on how to separate the kernel and the notebook server themselves.</p>
<p>Ideally, I'd like the code to remain on one machine, and the execution to happen on the other.</p>
<p>Is there a way that I could do this?</p>
| 0
|
2016-09-06T07:18:38Z
| 39,739,526
|
<p>I ended up using this <a href="https://github.com/jupyter/kernel_gateway_demos/tree/master/nb2kg" rel="nofollow">demo</a> which pretty much did this job for me. </p>
| 0
|
2016-09-28T06:26:50Z
|
[
"python",
"ipython",
"jupyter",
"jupyter-notebook"
] |
Python Battleship Game, Recursive Malfunction
| 39,342,852
|
<p>apologies in advance for the data dump. I'm recreating the Battleship game with Python. I'm having trouble with the <code>def battleship</code> function where the computer and user try to guess each other's coordinates. The computer has a <code>e/x</code>probability of guessing the user's coordinates correctly, where e is the number of ships left, and x is the number of unknown coordinates. The problem is, in the case that the user misses, how can I access local variable <code>x</code>, which is assigned a value when the user scores a hit? Since this is a recursive function, <code>x</code> is not defined if the user misses. I would still like the computer to guess the player's battleship location when the user misses. However, the error message I get reads: <code>local variable 'x' referenced before assignment</code></p>
<p>Thanks for your patience. Seems like there should be a simple solution out there. </p>
<pre><code>import random
import sys
globalValue=0 #for length of hitlist
loopcondition=True
compdestruction=0 #keep track of number of destroyed ships
userdestruction=0
destroyedships=[];
hitlist=[]; #a global variable
#to end the program
you=[];
youhitship=[];
class Battleship(object):
""" Ship object container. A game where the user tries to destroy the enemy's ships User tries to guess computer's position x and y """
def __init__(self, size, numberships,position_x,position_y):
self.position_x=position_x
self.position_y=position_y
self.numberships=numberships
self.size = size
def plotships(self,numberships):
"""input is integer coordinates for ships and output is an array of arrays with battleship locations CREATES THE HITLIST DONT REPEAT"""
while len(hitlist)<numberships:
r=Battleship.randomness(self)
if r not in hitlist:
hitlist.append(r)
originalhitlist=len(hitlist)
global globalValue
globalValue+=originalhitlist
def destroy(self):
""" Destroys the ship's point supplied if it contains it """
compChoose=Battleship.randomness(self) #computer's attak pair
print('computer choice is '+str(compChoose))
ship=[self.position_x,self.position_y]
print('Your Turn...')
if ship in hitlist:
print('Direct hit Captain')
global userdestruction
hitlist.remove(ship)
userdestruction+=1
CompWreck=GameBoard(self.size)
CompWreck.update(ship,self.size, destroyedships) #empty (at first) lists with coordinates of up-to-date list of destroyed ships
else:
print('Drat! missed!')
print('\nComps Turn')
if compChoose in you:
print('Kabloom. Your ships sunk.')
global compdestruction
you.remove(compChoose)
compdestruction+=1
YourWreck=GameBoard(self.size) #create an instance of GameBoard
YourWreck.update(ship,self.size,youhitship)
else:
print('Yay! The computer missed!\n')
def randomness(self):
"""random coordinates for computer firing and computer ship location"""
rand_x=random.choice(range(self.size))
rand_y=random.choice(range(self.size))
randcoord=[rand_x,rand_y]
return randcoord
class GameBoard(object):
""" The container for the ships """
def __init__(self, size):
"""Initialize clean GameBoard depending on size, etc """
self.size=size
self.destroyed = 'x' # representation for destroyed area
self.clear = '-' # representation for clear water
def printBoard(self,destroytheseships):
""" Print the current gameboard state"""
global compdestruction
global userdestruction
global globalValue
global loopcondition
graf='' #printed board
x=-1 #so the first row is 0, within the range of hitlist coordinates defined in Battleship.plotships(self)
for row in range(self.size): #for every row inside the first set of brackets
x+=1 #x,y pairs mark the possible ship locations
graf+='\n'
y=-1 #so the first column is 0
for column in range(self.size):
y+=1
if [x,y] in destroytheseships:
graf+=self.destroyed
else:
graf+=self.clear
print(graf)
if userdestruction == globalValue:
print('You Win!')
sys.exit('Game Over')
if compdestruction>=originalyou:
print('You Lose' )
sys.exit('Game Over')
def update(self,ship,size,witchlist):#It matter whether it's computer or user's turn. WITCHLIST defines which list you're choosing from
""" Updates the gameboard according to updated ship """
witchlist.append(ship)
newboard=GameBoard(size) #create a new instance with the same sized board
newboard.printBoard(witchlist)
#Game Interface do it once
size=int(input('Gameboard size'))
numberships=int(input('Waiting for Number of enemy ships'))
b=Battleship(size,numberships,0,0)
b.plotships(numberships) #create a hitlist and returns the original length of hitlist array
for i in range(numberships): #create list of your ships
you_x=int(input('Please enter a X coordinate for your ship'))
you_y=int(input('Please enter a Y coordinate for your ship'))
if ((you_x not in range(0,size)) or (you_y not in range(0,size))):
print('please chooose a different pair of coordinates within board boundaries\n')
continue
your_xy=[you_x,you_y]
you.append(your_xy)
originalyou=len(you)
while loopcondition==True: #take another turn as long as all the ships are not destroyed
ex=int(input('Waiting for attack X coordinate'))
why=int(input('Waiting for attack Y coordinate'))
if ((ex not in range(0,size)) or (why not in range(0,size))):
print('please chooose a different pair of coordinates within board boundaries\n')
continue
b=Battleship(size,numberships,ex,why)
b.destroy()
</code></pre>
| 1
|
2016-09-06T07:19:29Z
| 39,343,920
|
<p>Your <code>if</code> statement means that <code>x</code> isn't calculated on a miss. You will have to add some more logic inside the else statement to work out what <code>x</code> should be. A starting point would be to duplicate the block of code that draws a graph but just keep the lines that modify the value of <code>x</code> (also initialize <code>x</code> as <code>0</code>).</p>
| 1
|
2016-09-06T08:15:33Z
|
[
"python",
"recursion"
] |
wxpython and multiple plt plots in multiple panels
| 39,342,869
|
<p>I built a wxpython gui and am trying to plot two different pie charts in two different panels. However it seems that i can only do one at a time (the other one crashes). Hoping someone might know how to handle this. I also want to do the same with bar charts. My code:</p>
<pre><code>self.V_Panel_Pie1 = FigurePanel(self.V_Panel7)
self.V_Panel_Pie2 = FigurePanel(self.V_Panel8)
sizer_vpanel = wx.BoxSizer(wx.VERTICAL)
sizer_vpanel.Add(self.V_Panel_Pie1,1)
self.V_Panel7.SetSizer(sizer_vpanel)
sizer_vpanel = wx.BoxSizer(wx.VERTICAL)
sizer_vpanel.Add(self.V_Panel_Pie2,1)
self.V_Panel8.SetSizer(sizer_vpanel)
self.V_Panel_Pie1.draw(a_vals, b_vals)
self.V_Panel_Pie2.draw(a_vals2, b_vals2)
class FigurePanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.parent = parent
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.figure, ax = plt.subplots(figsize=(2,2))
self.canvas = FigureCanvas(self, -1, self.figure)
s1 = wx.BoxSizer(wx.VERTICAL)
s1.Add(self.canvas, 0, wx.GROW)
self.sizer.Add(s1, 5, wx.GROW)
self.SetSizer(self.sizer)
self.Layout()
self.Fit()
def draw(self, a, b):
self.figure.clear()
labels = 'a', 'b'
sizes = [a,b]
colors = ['yellowgreen', 'lightskyblue']
explode = (0, 0.1)
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90)
self.canvas.draw()here
</code></pre>
| 0
|
2016-09-06T07:20:26Z
| 39,343,436
|
<p>Look at this <a href="http://stackoverflow.com/questions/10737459/embedding-a-matplotlib-figure-inside-a-wxpython-panel">minimal wxPython/matplotlib example</a>. The Key to success is to take fully use of the matplotlib-objectoriented interface instead of the pyplot interface. Avoid all call invoking pyplot.</p>
<p>Instead of:</p>
<pre><code>self.figure, _ = plt.subplot()
</code></pre>
<p>use:</p>
<pre><code># from matplotlib.figure import Figure
self.figure = Figure()
self.axes = self.figure.add_subplot(211)
self.axes2 = self.figure.add_subplot(212)
# to draw the pies
self.axes.pie(...)
self.axes2.pie(...)
</code></pre>
<p>It is not necessary to call <code>canvas.draw</code> explicitly in this case.</p>
| 1
|
2016-09-06T07:51:05Z
|
[
"python",
"matplotlib",
"wxpython",
"pie-chart"
] |
Using property in canvas results in TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
| 39,342,884
|
<p>I am trying to implement my own ProgressBar* widget.</p>
<pre><code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
kv = """
<MyProgressBar@Widget>:
max: 1
value: 0
limited_value: min(self.value, self.max)
# Filled ratio should never be 0 or 1
# otherwise it would cause size_hints equal to 0,
# that is, None-type value, resulting in ignoring size_hint
filled_ratio: max(.00001, min(.9999, float(self.value) / self.max))
empty_ratio: 1-self.filled_ratio
filled_color: 0,1,0,1
empty_color: .6,.6,.6,.4
size_hint_y: .5
pos_hint: {'center_x': .5, 'center_y': .5}
canvas.before:
Color:
rgba: root.filled_color
Rectangle:
size: root.width * root.filled_ratio, root.height
pos: root.pos
Color:
rgba: root.empty_color
Rectangle:
size: root.width * root.empty_ratio, root.height
pos: root.x + root.width*root.filled_ratio, root.y
<MainWidget>:
MyProgressBar
"""
Builder.load_string(kv)
class MainWidget(BoxLayout):
pass
class MySimpleApp(App):
def build(self):
main = MainWidget(orientation='vertical')
return main
if __name__ == '__main__':
MySimpleApp().run()
</code></pre>
<p>When I run the code I get the following error: </p>
<pre><code> BuilderException: Parser: File "<inline>", line 20:
...
18: rgba: root.filled_color
19: Rectangle:
>> 20: size: root.width * root.filled_ratio, root.height
21: pos: root.pos
22: Color:
...
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
</code></pre>
<p>Replacing <code>root.filled_ratio</code> and <code>root.empty_ratio</code> in <code>canvas</code> with any float makes the error disappear. So, <code>canvas</code> sees <code>root.filled_ratio</code> as <code>None</code> for some reason, while it should be a float. </p>
<p>The error also disappears if instead of: </p>
<pre><code>filled_ratio: max(.00001, min(.9999, float(self.value) / self.max))
empty_ratio: 1-self.filled_ratio
</code></pre>
<p>.. I use:</p>
<pre><code>filled_ratio: .4
empty_ratio: .6
</code></pre>
<p>What am I doing wrong?</p>
<p><sub>*there is already a <a href="https://kivy.org/docs/api-kivy.uix.progressbar.html?highlight=progressbar#" rel="nofollow">ProgressBar</a> in Kivy).</sub> </p>
| 1
|
2016-09-06T07:21:28Z
| 39,344,107
|
<p>Simply defining the properties in python before using them in kv-language fixes the issue: </p>
<pre><code>class MyProgressBar(Widget):
filled_ratio = NumericProperty(0)
empty_ratio = NumericProperty(0)
</code></pre>
<p><sub>(Note: I don't consider this a complete answer since it doesn't explain <em>why</em> this happens. Feel free to create an answer that addresses fully the issue)</sub></p>
| 0
|
2016-09-06T08:26:38Z
|
[
"python",
"kivy",
"kivy-language"
] |
My numpy is latest but tensroflow says it's old one
| 39,342,920
|
<pre><code>$pip list
numpy(1.11.1)
</code></pre>
<p>My numpy is latest and I am sure it could be used in python environment.</p>
<pre><code>>>> import numpy
>>> print numpy.__version__
1.11.1
</code></pre>
<p>however I use tensorflow </p>
<pre><code>$ tensorboard --logdir=/tmp/basic_rnn/logdir
</code></pre>
<p>it shows this error</p>
<pre><code>RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9
</code></pre>
<p>What causes this problem??</p>
| 0
|
2016-09-06T07:23:07Z
| 39,343,558
|
<p>I suspect that the <code>tensorboard</code> command is linked against the wrong Python environment. Make sure that <code>tensorflow</code> uses the same Python interpreter/virtual environment as you checked your numpy installation with. Also check your <code>PATH</code> and <code>PYTHONPATH</code> and take a look at <code>sys.path</code> and <code>sys.prefix</code> to see if there are some paths mixed up.</p>
| 1
|
2016-09-06T07:57:22Z
|
[
"python",
"tensorflow"
] |
python import * or a list from other level
| 39,342,990
|
<p>I'm trying to import a few classes from a module in another level. I can type all the classes, but I' trying to do it dynamically</p>
<p>if I do:</p>
<pre><code>from ..previous_level.module import *
raise: SyntaxError: import * only allowed at module level
</code></pre>
<p>the same from myapp folder:</p>
<pre><code>from myapp.previous_level.module import *
raise: SyntaxError: import * only allowed at module level
</code></pre>
<p>So I thought:</p>
<pre><code>my_classes = ['Class_Foo', 'Class_Bar']
for i in my_classes:
from ..previous_level.module import i
raise: ImportError: cannot import name 'i'
</code></pre>
<p>and also:</p>
<pre><code>my_classes = ['Class_Foo', 'Class_Bar']
for i in my_classes:
__import__('myapp').previous_level.module.y
raise: AttributeError: module 'myapp.previous_level.module' has no attribute 'y'
</code></pre>
<p>I've tried <code>string format</code> , <code>getattr()</code> , <code>__getattr__</code> but no success.</p>
<p>It's impossible to do import this way, or I'm doing something wrong?</p>
| 1
|
2016-09-06T07:26:41Z
| 39,343,518
|
<p>The error <code>SyntaxError: import * only allowed at module level</code> happens if you try to import <code>*</code> from within a function. This is not visible from the question, but it seems that the original code was simething like:</p>
<pre><code>def func():
from ..previous_level.module import * # SyntaxError
</code></pre>
<p>On the other hand, importing at the beginning of a module would be valid:</p>
<pre><code>from ..previous_level.module import * # OK
</code></pre>
<p>That said, I would still suggest using absolute imports without <code>*</code>:</p>
<pre><code>from myapp.previous_level.module import ClassA, ClassB, ClassC
x = ClassA()
# or:
import myapp.previous_level.module
x = myapp.previous_level.module.ClassA()
</code></pre>
<p>BTW, this is completely wrong:</p>
<pre><code>for i in my_classes:
from ..previous_level.module import i
</code></pre>
| 0
|
2016-09-06T07:55:42Z
|
[
"python",
"python-3.x"
] |
Python Append String inside list just as an element without double quotes
| 39,343,312
|
<p>Editing my question so it is little clear:</p>
<p>Problem here is I want to put content of list1 inside List2. I was doing it wrong way as suggested in comments.</p>
<p>I get a list1
value4 = [{'PARAMS': ['ProcessingDate=2016-08-29', 'ReRun=Y']}]</p>
<p>The elements of the PARAMS should be suffixed with '-param' string, so I created a new list with elements of value4[0]['PARAMS'] Then removed the square brackets of this list which ended up as string
FINALPARAMS
<code>'-param', 'ProcessingDate=2016-08-29', '-param', 'ReRun=Y'</code></p>
<p>Then I was trying to insert these values inside another list as elements.</p>
<p><code>myNewlist = ['C:\This\Path', 'value2', 'value3', FINALPARAMS, 'value5']</code></p>
<p>This gives output with doublequotes around the FINALPARAMS values</p>
<p><code>['C:\\This\\Path', 'value2', 'value3', "'-param', 'ProcessingDate=2016-08-29', '-param', 'ReRun=Y'", value5]</code></p>
<p>I want to get rid of the double quotes inside this new list</p>
<p>-*********************************************************************-</p>
<p>Original Question:</p>
<p>This might be a easy solution for Python expert, but i am tired of finding solution. I have done most of the string manipulation I could do, like converting to string and trying out replace etc:</p>
<p>I have my list like below, I need to put the data of <code>value4</code> properly inside `mylist without double quotes.</p>
<p>using python 3.5</p>
<p>I get my <code>value4</code> like below</p>
<pre><code> value4 = [{'PARAMS': ['ProcessingDate=2016-08-29', 'ReRun=Y']}]
</code></pre>
<p>I convert it to list like below, I need <code>-param</code> as suffix for my each element in <code>PARAMS</code></p>
<pre><code>paramlist = value4[0]['PARAMS']
newparamlist = []
for x in paramlist:
newparamlist.append('-param')
newparamlist.append(x)
FINALPARAMS = (str(newparamlist)[1:-1]) #Taking out the squareBrackets
</code></pre>
<p><code>print FINALPARAMS</code> gives the desired result. i.e.</p>
<p><code>'-param', 'ProcessingDate=2016-08-29', '-param', 'ReRun=Y'</code></p>
<p>i use the <code>FINALPARAMS</code> in below list which prints value like this, i want to get rid of the double quotes and treat the string which i got from <code>FINALPARAMS</code> as normal list item inside the <code>myNewlist</code></p>
<p><code>myNewlist = ['C:\This\Path', 'value2', 'value3', FINALPARAMS, 'value5']</code></p>
<p><code>myNewlist</code> results as follows Observe the DoubleQuote I want to get rid of it so the values are treated as list items</p>
<p><code>['C:\\This\\Path', 'value2', 'value3', "'-param', 'ProcessingDate=2016-08-29', '-param', 'ReRun=Y'", value5]</code></p>
<p>I lost 4 hours finding the solution, which looked simple for me initially.
I tried converting this <code>newList</code> to string and replaced the doubleQuotes but my subprocess.checkoutput looks for proper list item</p>
<p>I tried converting the list to string and do <code>replace('"','')</code> this turned out that it has put 4 backslashes to the windows path which is my first element in the list. and my command gave a error System cannot find the path specified</p>
<p>Here my code is present if someone wants to access and change it.
<a href="http://www.tutorialspoint.com/execute_python3_online.php?PID=0Bw_CjBb95KQMd1VkSW1tQnowS00" rel="nofollow">http://www.tutorialspoint.com/execute_python3_online.php?PID=0Bw_CjBb95KQMd1VkSW1tQnowS00</a></p>
| -1
|
2016-09-06T07:44:15Z
| 39,343,466
|
<p>I believe you are confusing putting a <strong>list inside a list</strong> and <strong>concatenating two lists</strong>:</p>
<pre><code>[1, 2, paramlist, 5] # [1, 2, [3, 4], 5]
</code></pre>
<p>is not the same as</p>
<pre><code>[1, 2] + paramlist + [5] # [1, 2, 3, 4, 5]
</code></pre>
<p>Instead of using the correct operation you are trying to cast the list to a string to manually remove the square brackets. Needless to say this is the wrong way of doing it.</p>
<p>So i think you are looking for</p>
<pre><code>value4 = [{'PARAMS': ['ProcessingDate=2016-08-29', 'ReRun=Y']}]
paramlist = value4[0]['PARAMS']
paramlist = [elem for x in paramlist for elem in ('-param', x)]
myNewlist = ['Value1', 'value2', 'value3'] + paramlist + ['value5']
print (myNewlist)
</code></pre>
<p>which yields</p>
<pre><code>['Value1', 'value2', 'value3', '-param', 'ProcessingDate=2016-08-29', '-param', 'ReRun=Y', 'value5']
</code></pre>
| 5
|
2016-09-06T07:52:54Z
|
[
"python",
"string",
"list",
"python-3.x"
] |
Python module not importing
| 39,343,337
|
<p>I am attempting to install a <code>c++ / python</code> based library that offers musical onset detection. Typically, I run <code>sudo pip install foo</code> and <code>cmd+tab</code> over to PyCharm and type <code>import ...</code> and I get auto-completion as I noticed the package resides in <code>Library/Python/2.7/site-packages</code>. However, after completing the installation process for this library, no such auto-complete is there. </p>
<p>The complete list of instructions entail using cmake as well as running a setup script for python. I am unsure about the underlying architectural details (whether its a C++ lib with a python binding, or something..) and whether that plays into my problem. Here, the installation process is:</p>
<p><a href="http://i.stack.imgur.com/j1rFP.png" rel="nofollow"><img src="http://i.stack.imgur.com/j1rFP.png" alt=""></a></p>
<p>It seems that all the <code>cmake / c++</code> building went of with few warnings and no errors, so that is fine.. and so did the python setups.. I do notice a new python package in the 2.7/site-packages dir in the egg format. Yet import mod.. sees nothing. Just compilation errors. </p>
<p>Is there anything I could have done wrong in the installation process or in the importing that would solve this problem? Any help in advance is greatly appreciated. Let me know if more details are needed to diagnosis the problem.</p>
| 0
|
2016-09-06T07:45:43Z
| 39,343,494
|
<p>EDIT: Don't have the rep to comment, yet - therefore I had to write an answer.</p>
<p>Just a wild guess, but do you use a virtual environment? If so, did you <code>pip install</code> the package globally or into your virtualenv? You might also check if pycharm is using the exact version of python where your package resides.</p>
| 0
|
2016-09-06T07:54:16Z
|
[
"python",
"module",
"cmake",
"packages"
] |
Python Selenium: Unable to click button
| 39,343,408
|
<p>I'm new to python and want to write a web scraper which involves mouse clicking an "OK" button on a pop-up window. </p>
<p>Everything else went well but I'm not able to click the final button which leads to the data downloading. </p>
<p>The javascript is as follows:</p>
<p><a href="http://i.stack.imgur.com/SYSWp.png" rel="nofollow"><img src="http://i.stack.imgur.com/SYSWp.png" alt="enter image description here"></a></p>
<p>I tried finding element by id but the following error message appeared:</p>
<p><a href="http://i.stack.imgur.com/SJY2n.png" rel="nofollow"><img src="http://i.stack.imgur.com/SJY2n.png" alt="enter image description here"></a></p>
| 0
|
2016-09-06T07:49:48Z
| 39,343,468
|
<p>try this:</p>
<pre><code>browser.find_element_by_id('ctl00_ContentContainer1_ctl00_ButtonsContent_ExportOptionsBottomButtons_OkLabel').click()
</code></pre>
<p>Changed this:</p>
<pre><code>find_elements_by_id
</code></pre>
<p>to this:</p>
<pre><code>find_element_by_id
</code></pre>
| 1
|
2016-09-06T07:53:06Z
|
[
"javascript",
"python",
"selenium"
] |
Python Selenium: Unable to click button
| 39,343,408
|
<p>I'm new to python and want to write a web scraper which involves mouse clicking an "OK" button on a pop-up window. </p>
<p>Everything else went well but I'm not able to click the final button which leads to the data downloading. </p>
<p>The javascript is as follows:</p>
<p><a href="http://i.stack.imgur.com/SYSWp.png" rel="nofollow"><img src="http://i.stack.imgur.com/SYSWp.png" alt="enter image description here"></a></p>
<p>I tried finding element by id but the following error message appeared:</p>
<p><a href="http://i.stack.imgur.com/SJY2n.png" rel="nofollow"><img src="http://i.stack.imgur.com/SJY2n.png" alt="enter image description here"></a></p>
| 0
|
2016-09-06T07:49:48Z
| 39,343,491
|
<p><code>find_elements_by_id</code> returns a list of elements. Either iterate over the list that <code>find_elements_by_id</code> returns or use <code>find_element_by_id</code> (notice the missing 's') which will return only a single element (if any).</p>
| 1
|
2016-09-06T07:53:57Z
|
[
"javascript",
"python",
"selenium"
] |
How to create documentdb account using python in azure?
| 39,343,755
|
<p>Is any one know how to create document db account programatically for azure? I am aware about creating a database into present document db account.</p>
| 1
|
2016-09-06T08:07:31Z
| 39,355,242
|
<p>You can create DocumentDB accounts programmatically using Azure Resource Manager templates or the Azure Command-Line Interface (CLI). See <a href="https://azure.microsoft.com/en-us/documentation/articles/documentdb-automation-resource-manager-cli/" rel="nofollow" title="DocumentDB Automation">DocumentDB Automation</a> for details</p>
| 0
|
2016-09-06T18:05:49Z
|
[
"python",
"azure"
] |
How to create documentdb account using python in azure?
| 39,343,755
|
<p>Is any one know how to create document db account programatically for azure? I am aware about creating a database into present document db account.</p>
| 1
|
2016-09-06T08:07:31Z
| 39,468,460
|
<p>@Amol Shinde, Trying to use Azure SDK for Python to create documentdb account.</p>
<p>As reference, here is my sample code.</p>
<pre><code>from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
subscription_id = 'xxxx-xxxx-xxx-xxx-xxx'
client_id = 'xxxx-xxxx-xxx-xxx-xxx'
client_secret = 'XXXXXXXXXXXXXXXXXXXXx'
tenant_id = 'xxxx-xxxx-xxx-xxx-xxx'
credentials = ServicePrincipalCredentials(client_id = client_id, secret = client_secret, tenant = tenant_id)
client = ResourceManagementClient(credentials, subscription_id)
documentdb_params = {
'location': 'westus',
'properties': {
'name': 'myDocumentDb',
'databaseAccountOfferType': 'Standard'
}
}
client.resources.create_or_update('<your-resource-group>',
'Microsoft.DocumentDB',
'',
'databaseAccounts',
'myDocumentDb',
'2015-06-01',
documentdb_params)
</code></pre>
<p>And you can refer to the Azure SDK <a href="http://azure-sdk-for-python.readthedocs.io/en/latest/resourcemanagement.html" rel="nofollow">document</a>.</p>
<p>Hope it helps.</p>
| 0
|
2016-09-13T11:04:12Z
|
[
"python",
"azure"
] |
Python multi-threading performance issue related to start()
| 39,343,894
|
<p>I had some performance issues with a multi-threading code to parallelize multiple telnet probes.</p>
<h2>Slow</h2>
<p>My first implementation was is really slow, same a if the tasks were run sequencially:</p>
<pre><code>for printer in printers:
â¦
thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
threads.append(thread)
for thread in threads:
thread.start()
thread.join()
</code></pre>
<h2>Blastlingly Fast</h2>
<pre><code>for printer in printers:
â¦
thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
threads.append(thread)
thread.start() # <----- moved this
for thread in threads:
thread.join()
</code></pre>
<h2>Question</h2>
<p>I don't get why moving the <code>start()</code> method change the performance so much.</p>
| 2
|
2016-09-06T08:14:27Z
| 39,344,036
|
<p>In your first implementation you are actually running the code sequentially because by <strong>calling <a href="https://docs.python.org/3/library/threading.html#threading.Thread.join" rel="nofollow"><code>join()</code></a> immediately after <a href="https://docs.python.org/3/library/threading.html#threading.Thread.start" rel="nofollow"><code>start()</code></a> the main thread is blocked</strong> until the started thread is finished.</p>
| 4
|
2016-09-06T08:21:49Z
|
[
"python",
"performance",
"python-3.x",
"telnet",
"python-multithreading"
] |
Python multi-threading performance issue related to start()
| 39,343,894
|
<p>I had some performance issues with a multi-threading code to parallelize multiple telnet probes.</p>
<h2>Slow</h2>
<p>My first implementation was is really slow, same a if the tasks were run sequencially:</p>
<pre><code>for printer in printers:
â¦
thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
threads.append(thread)
for thread in threads:
thread.start()
thread.join()
</code></pre>
<h2>Blastlingly Fast</h2>
<pre><code>for printer in printers:
â¦
thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
threads.append(thread)
thread.start() # <----- moved this
for thread in threads:
thread.join()
</code></pre>
<h2>Question</h2>
<p>I don't get why moving the <code>start()</code> method change the performance so much.</p>
| 2
|
2016-09-06T08:14:27Z
| 39,344,049
|
<p>In your slow solution you are basically not using multithreading at all. Id's running a thread, waiting to finish it and then running another - there is no difference in running everything in one thread and this solution - you are running them in series.</p>
<p>The second one on the other hand starts all threads and then joins them. This solution limits the execution time to the longest execution time of one single thread - you are running them in parallel.</p>
| 0
|
2016-09-06T08:22:31Z
|
[
"python",
"performance",
"python-3.x",
"telnet",
"python-multithreading"
] |
Python multi-threading performance issue related to start()
| 39,343,894
|
<p>I had some performance issues with a multi-threading code to parallelize multiple telnet probes.</p>
<h2>Slow</h2>
<p>My first implementation was is really slow, same a if the tasks were run sequencially:</p>
<pre><code>for printer in printers:
â¦
thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
threads.append(thread)
for thread in threads:
thread.start()
thread.join()
</code></pre>
<h2>Blastlingly Fast</h2>
<pre><code>for printer in printers:
â¦
thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
threads.append(thread)
thread.start() # <----- moved this
for thread in threads:
thread.join()
</code></pre>
<h2>Question</h2>
<p>I don't get why moving the <code>start()</code> method change the performance so much.</p>
| 2
|
2016-09-06T08:14:27Z
| 39,344,065
|
<p>thread.join() is blocking every thread as soon as they are created in your first implementation.</p>
| 0
|
2016-09-06T08:23:20Z
|
[
"python",
"performance",
"python-3.x",
"telnet",
"python-multithreading"
] |
Python multi-threading performance issue related to start()
| 39,343,894
|
<p>I had some performance issues with a multi-threading code to parallelize multiple telnet probes.</p>
<h2>Slow</h2>
<p>My first implementation was is really slow, same a if the tasks were run sequencially:</p>
<pre><code>for printer in printers:
â¦
thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
threads.append(thread)
for thread in threads:
thread.start()
thread.join()
</code></pre>
<h2>Blastlingly Fast</h2>
<pre><code>for printer in printers:
â¦
thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
threads.append(thread)
thread.start() # <----- moved this
for thread in threads:
thread.join()
</code></pre>
<h2>Question</h2>
<p>I don't get why moving the <code>start()</code> method change the performance so much.</p>
| 2
|
2016-09-06T08:14:27Z
| 39,344,160
|
<p>According to <a href="https://docs.python.org/3/library/threading.html#threading.Thread.join" rel="nofollow">threading.Thread.join()</a> documentation:</p>
<blockquote>
<p>Wait until the thread terminates.
This blocks the calling thread until the thread whose join() method is called terminates -- either normally or through an unhandled exception or until the optional timeout occurs".</p>
</blockquote>
<p>In your <em>slow</em> example you start the thread and wait till it is complete, then you iterate to the next thread. </p>
<h2>Example</h2>
<pre><code>from threading import Thread
from time import sleep
def foo(a, b):
while True:
print(a + ' ' + b)
sleep(1)
ths = []
for i in range(3):
th = Thread(target=foo, args=('hi', str(i)))
ths.append(th)
for th in ths:
th.start()
th.join()
</code></pre>
<h3>Produces</h3>
<pre><code>hi 0
hi 0
hi 0
hi 0
</code></pre>
| 1
|
2016-09-06T08:28:57Z
|
[
"python",
"performance",
"python-3.x",
"telnet",
"python-multithreading"
] |
How to simulate the process of login using scrapy, when the information might be tranferred by ajax?
| 39,343,916
|
<p>I'm doing some crawling jobs on <a href="http://www.asianmetal.cn/" rel="nofollow">http://www.asianmetal.cn/</a>.
But I fail to login using a simple FormRequest like this:</p>
<pre><code>def start_requests(self):
url = 'http://www.asianmetal.cn/login/ajaxLogin.am'
fake_header = httputils.random_headers()
formdata = {
'txtUser_LoginName': '***',
'txtUser_Pwd': '***',
'tfc': '1',
}
yield scrapy.FormRequest(url=url, formdata=formdata,
headers=fake_header, callback=self.parse)
</code></pre>
<p>However it doesn't work. So I did screenshots to find out what happened.</p>
<p><img src="http://i.stack.imgur.com/U7giI.jpg" alt="Formdata"></p>
<p>So how should I simulate the login process?</p>
| 0
|
2016-09-06T08:15:31Z
| 39,347,246
|
<p>You are probably missing some headers. I've tried gibberish log in and these are the headers that were sent:</p>
<p><a href="http://i.stack.imgur.com/tdrkB.png" rel="nofollow"><img src="http://i.stack.imgur.com/tdrkB.png" alt="enter image description here"></a></p>
<p>The only important here is probably <code>X-Requested-With</code>. Some websites also check <code>Referer</code> but that's really rare.</p>
<p>To fix this simply update your fake header with approriate values:</p>
<pre><code>fake_header = {}
fake_header['X-Request-With'] = 'XMLHttpRequest'
fake_header['Referer'] = response.url
</code></pre>
| 0
|
2016-09-06T10:52:33Z
|
[
"python",
"ajax",
"scrapy"
] |
Modify a python code to solve a sequence of linear programs where a lower bound of a variable is being incremented by 1
| 39,343,950
|
<p>Using Gurobi and Python I could optimally solve a linear problem for a given situation. However, when I am given a range in which a lower bound for one of the variable can increase in an increment of 1, I could not figure how to write the right syntax (for loop, while, or other), I think I am missing alot so to speak. Secondly, If I were to plot the optimal objective value sequentially obtained versus each increment of the lower bound of subject variable, how can I go about it? Honestly, I could not exactly imagine how would I retain for every solve its optimal value with its relevant lower bound individually to be shown in a single plot at the end. </p>
| -1
|
2016-09-06T08:17:22Z
| 39,714,245
|
<p>First, define a class that acts as a wrapper for a Gurobi model. It should take a lower bound as an argument which you'll use when defining your variable.</p>
<pre><code>class GurobiModel:
def __init__(self, lowerBound):
# create an empty Gurobi model object
self.model = Model()
# add your variable using the argument as the lower bound
self.variable1 = self.model.addVar(lb=lowerBound,vtype=GRB.INTEGER, name='variable1')
# add more variables, constraints, and objective function
...
def solve(self):
"""Solves the model and returns the optimal objective value (or None if model is infeasible)."""
self.model.optimize()
if model.status == GRB.Status.OPTIMAL:
# if model is optimal, return objective value
return self.model.objVal
else:
print('Model is infeasible')
return None
</code></pre>
<p>Now you can create a main function that creates a new GurobiModel object (with a specified lower bound for your variable of interest) and solves it to optimality:</p>
<pre><code>def main():
N = 50 # number of iterations
result_set = [] # this stores tuples containing the lower bound and the objective function
for i in range(N):
model = GurobiModel(lowerBound = i)
objVal = model.solve()
result_set.append((i, objVal))
</code></pre>
<p>Hopefully this is enough to get you started. There's lots that could be done differently, but this will be fine for smaller models (for example, if your model is quite large, you wouldn't want to rebuild it in entirety every iteration; it would make more sense to extract the variable using the getVarByName() method and change the lower bound).</p>
| 0
|
2016-09-27T00:18:23Z
|
[
"python",
"gurobi"
] |
Python: Cast SwigPythonObject to Python Object
| 39,344,039
|
<p>I'm using some closed Python module: I can call methods via API, but I cannot access the implementation. I know this module is basically wraps some C++ code. </p>
<p>So one of the methods return value type is a <code>SwigPythonObject</code>. How can I work with this object later, suppose I don't have any other aids from the module distributor nor documentation? </p>
<p>I want somehow to convert him to "regular" python object and observe him in the debugger for internal members structure.</p>
<p>Currently what I see in the debugger is something like: </p>
<pre><code>{SwigPythonObject} _<hexa number>_p_unsigned_char
</code></pre>
| 0
|
2016-09-06T08:22:12Z
| 39,357,579
|
<p>It's a little unclear the semantics of what you're asking, but basically it seems as though you've got a pointer to an <code>unsigned char</code> from SWIG that you'd like to work with. Guessing slightly there are probably 3 cases you're likely to encounter this in:</p>
<ol>
<li>The pointer really is a pointer to a single unsigned byte</li>
<li>The pointer is a pointer to a null-terminated string. (Why isn't it just wrapped as a string though?)</li>
<li>The pointer points to a fixed length unsigned byte array. (You'll need to know/guess the length somehow)</li>
</ol>
<p>In this particular instance because there's no packing or alignment to worry about for all three cases we can actually write something for all of the above cases that uses ctypes to read the memory that SWIG references directly into Python and side steps the SWIG proxy. (Note that if the type we were looking at was anything more complex than just a pointer to a single built in type or array of them we'd not be able to do much here)</p>
<p>First up some code, in C - test.h to exercise what we're working on:</p>
<pre class="lang-c prettyprint-override"><code>inline unsigned char *test_str() {
static unsigned char data[] = "HELLO WORLD";
return data;
}
inline unsigned char *test_byte() {
static unsigned char val = 66;
return &val;
}
</code></pre>
<p>Next up is a minimal SWIG module that wraps this:</p>
<pre class="lang-c prettyprint-override"><code>%module test
%{
#include "test.h"
%}
%include "test.h"
</code></pre>
<p>We can check this out in ipython and see that it is wrapped (similarly) to
what you observed:</p>
<pre class="lang-none prettyprint-override"><code>In [1]: import test
In [2]: test.test_byte()
Out[2]: <Swig Object of type 'unsigned char *' at 0x7fc2851cbde0>
In [3]: test.test_str()
Out[3]: <Swig Object of type 'unsigned char *' at 0x7fc2851cbe70>
In [4]: hex(int(test.test_str()))
Out[4]: '0x7f905b0e72cd'
</code></pre>
<p>The thing we use in each case is the fact that calling <code>int(x)</code> where x is our unknown SWIG unsigned char pointer gives us the value of the address the pointer is pointing at as an integer. Combining that with ctype's <code>from_address</code> static method we can construct ctypes instances to access the memory SWIG knows about directly. (NB: address returned by calling <code>int()</code> doesn't match the address in the string representation show because the former is the real address of the data pointed at, but the latter is the address of the SWIG <em>proxy</em> object)</p>
<p>Probably the simplest to wrap is the fixed length case - we can create a ctypes type by using the <code>*</code> operator on <code>c_ubyte</code> of the right size and then call <code>from_address</code>.</p>
<p>For the null-terminated string case we've got two choices really: either use the libc strlen function to figure out the string length and then construct a ctypes type that matches, or alternatively just loop char by char from Python until we hit a null. I chose the latter in my example below as it's simpler. I probably over-complicated it by using a generator and <code>itertools.count()</code> to track the position though.</p>
<p>Finally for the pointer to single byte case I basically reused the existing ctypes type I had to create a 1 byte array and read the value out of that. There's probably a way to construct a type from an address using <code>ctypes.POINTER(ctypes.c_ubyte)</code> and then <code>.contents</code>, but I couldn't quickly see it, so using the 1 byte array trick made it trivial for me.</p>
<p>All this combined to give me the following Python code:</p>
<pre><code>import ctypes
import test
import itertools
# Case 2
def swig_to_str(s):
base = int(s)
ty = ctypes.c_ubyte*1
def impl():
for x in itertools.count():
v=ty.from_address(base+x)[0]
if not v: return
yield chr(v)
return ''.join(impl())
# Case 1
def swig_to_byte(b):
ty=ctypes.c_ubyte*1
v=ty.from_address(int(b))
return v[0]
# Case 3
def swig_to_fixed_len(s, l):
ty=ctypes.c_ubyte*l
return ''.join(chr(x) for x in ty.from_address(int(s)))
t=test.test_str()
print(t)
print(swig_to_str(t))
print(swig_to_fixed_len(t,5))
u=test.test_byte()
print(u)
print(swig_to_byte(u))
</code></pre>
<p>This ran as hoped with Python 2.7 (should take minimal effort to make it correct for 3):</p>
<pre class="lang-none prettyprint-override"><code>swig3.0 -python -Wall test.i
gcc -std=gnu99 -Wall test_wrap.c -o _test.so -shared -I/usr/include/python2.7/ -fPIC
python run.py
<Swig Object of type 'unsigned char *' at 0x7f4a57581cf0>
HELLO WORLD
HELLO
<Swig Object of type 'unsigned char *' at 0x7f4a57581de0>
66
</code></pre>
| 1
|
2016-09-06T20:47:08Z
|
[
"python",
"swig"
] |
Date range issue in pandas python
| 39,344,040
|
<p>I tried this: </p>
<pre><code>pd.date_range(2000, periods = 365, freq = 'D',format = '%d-%m-%Y')
</code></pre>
<p>why I am getting this result:</p>
<pre><code>DatetimeIndex(['1970-01-01 00:00:00.000002', '1970-01-02 00:00:00.000002',
'1970-01-03 00:00:00.000002', '1970-01-04 00:00:00.000002',
'1970-01-05 00:00:00.000002', '1970-01-06 00:00:00.000002',
'1970-01-07 00:00:00.000002', '1970-01-08 00:00:00.000002',
</code></pre>
<p>Any help?</p>
| 2
|
2016-09-06T08:22:17Z
| 39,344,087
|
<p>Try this</p>
<pre><code>pd.date_range('1/1/2000', periods = 365, freq = 'D',format = '%d-%m-%Y')
</code></pre>
| 1
|
2016-09-06T08:25:05Z
|
[
"python",
"date",
"pandas",
"date-range",
"datetimeindex"
] |
Date range issue in pandas python
| 39,344,040
|
<p>I tried this: </p>
<pre><code>pd.date_range(2000, periods = 365, freq = 'D',format = '%d-%m-%Y')
</code></pre>
<p>why I am getting this result:</p>
<pre><code>DatetimeIndex(['1970-01-01 00:00:00.000002', '1970-01-02 00:00:00.000002',
'1970-01-03 00:00:00.000002', '1970-01-04 00:00:00.000002',
'1970-01-05 00:00:00.000002', '1970-01-06 00:00:00.000002',
'1970-01-07 00:00:00.000002', '1970-01-08 00:00:00.000002',
</code></pre>
<p>Any help?</p>
| 2
|
2016-09-06T08:22:17Z
| 39,344,091
|
<p>You need add <code>''</code> to <code>2000</code> only:</p>
<pre><code>print (pd.date_range('2000', periods = 365, freq = 'D'))
DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04',
'2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08',
'2000-01-09', '2000-01-10',
...
'2000-12-21', '2000-12-22', '2000-12-23', '2000-12-24',
'2000-12-25', '2000-12-26', '2000-12-27', '2000-12-28',
'2000-12-29', '2000-12-30'],
dtype='datetime64[ns]', length=365, freq='D')
</code></pre>
<p>If use <code>int</code>, cast it to <code>str</code>:</p>
<pre><code>print (pd.date_range(str(2000), periods = 365, freq = 'D'))
</code></pre>
| 2
|
2016-09-06T08:25:37Z
|
[
"python",
"date",
"pandas",
"date-range",
"datetimeindex"
] |
How to change variable value in other module?
| 39,344,105
|
<p>I have the following modules:</p>
<p><strong>test.py</strong></p>
<pre><code>import test1
var1 = 'Test1'
var2 = 'Test2'
print var1
print var2
test1.modify_vars(var1, var2)
print var1
print var2
</code></pre>
<p>and the module </p>
<p><strong>test1.py</strong></p>
<pre><code>def modify_vars(var1, var2):
var1 += '_changed'
var2 += '_changed'
</code></pre>
<p>I am expecting to get the following output:</p>
<pre><code>Test1
Test2
Test1_changed
Test2_changed
</code></pre>
<p>I will get:</p>
<pre><code>Test1
Test2
Test1
Test2
</code></pre>
<p>It is mandatory to avoid importing test module in test1 module.</p>
<p>How to achieve this without returning values from the method ? (sort of reference passing)</p>
| 0
|
2016-09-06T08:26:35Z
| 39,344,141
|
<p>Strings are immutable. You cannot do what you want. Using <code>+=</code> with a string will always return a new string, which will have nothing to do with whatever <code>var1</code> and <code>var2</code> are assigned to.</p>
<p>The only way to achieve something close to what you want (and, to be honest, you should probably change your requirements) is to use a list rather than separate variables, and modify its contents:</p>
<pre><code>var = ['Test1', 'Test2']
...
def modify_var(var):
var[0] += '_changed'
var[1] += '_changed'
</code></pre>
| 3
|
2016-09-06T08:27:58Z
|
[
"python"
] |
How to change variable value in other module?
| 39,344,105
|
<p>I have the following modules:</p>
<p><strong>test.py</strong></p>
<pre><code>import test1
var1 = 'Test1'
var2 = 'Test2'
print var1
print var2
test1.modify_vars(var1, var2)
print var1
print var2
</code></pre>
<p>and the module </p>
<p><strong>test1.py</strong></p>
<pre><code>def modify_vars(var1, var2):
var1 += '_changed'
var2 += '_changed'
</code></pre>
<p>I am expecting to get the following output:</p>
<pre><code>Test1
Test2
Test1_changed
Test2_changed
</code></pre>
<p>I will get:</p>
<pre><code>Test1
Test2
Test1
Test2
</code></pre>
<p>It is mandatory to avoid importing test module in test1 module.</p>
<p>How to achieve this without returning values from the method ? (sort of reference passing)</p>
| 0
|
2016-09-06T08:26:35Z
| 39,344,727
|
<p>Your function misses a return value</p>
<pre><code>var1 = 'Test1'
var2 = 'Test2'
def modify_var(var1, var2):
var1 += '_changed'
var2 += '_changed'
return (var1,var2)
(var1,var2) = modify_var(var1,var2)
print var1,var2
</code></pre>
<p>Does work. </p>
<p>I believe this requires minimal change to your code.</p>
<p>Tested with python 2.7</p>
| -1
|
2016-09-06T08:55:27Z
|
[
"python"
] |
Grouped boxplot with seaborn
| 39,344,167
|
<p>I have following data in python panda DataFrame. I would like to have grouped box plot similar to one in <a href="https://stanford.edu/~mwaskom/software/seaborn/examples/grouped_boxplot.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/examples/grouped_boxplot.html</a></p>
<p>For each id, I would like to have two box plots plotted side by side. How do i achieve this. I tried plotting it with the seaborn package but without any success. </p>
<pre><code>id predicted real
1 [10, 10, 10] [16, 18, 20]
2 [12, 12, 15] [15, 17, 19, 21, 23]
3 [20, 5, 4, 4] [29, 32]
4 [25, 25, 25, 24, 21] [21, 24, 25, 26, 28, 29, 30, 33]
5 [20, 20, 20, 21] [21, 22, 24, 26, 28, 30, 31, 32]
6 [8, 3, 3, 14] [25, 27]
7 [1, 4, 4, 4, 5, 6, 10] [69, 71, 72]
8 [11, 11, 11, 11] [19, 21, 22, 23, 24]
9 [7, 6, 9, 9] [19, 26, 27, 28]
10 [30, 30, 30, 30, 30] [38, 39]
</code></pre>
| 1
|
2016-09-06T08:29:10Z
| 39,344,866
|
<p>Notice the table structure in the example you are looking at</p>
<pre><code>import seaborn as sns
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", hue="sex", data=tips, palette="PRGn")
sns.despine(offset=10, trim=True)
</code></pre>
<p><a href="http://i.stack.imgur.com/Y1DJO.png" rel="nofollow"><img src="http://i.stack.imgur.com/Y1DJO.png" alt="enter image description here"></a></p>
<pre><code>tips.head()
</code></pre>
<p><a href="http://i.stack.imgur.com/DtcGp.png" rel="nofollow"><img src="http://i.stack.imgur.com/DtcGp.png" alt="enter image description here"></a></p>
<hr>
<p>Our goal is to set your table up like this</p>
<h3>Setup</h3>
<pre><code>from StringIO import StringIO
import pandas as pd
text = """id predicted real
1 [10, 10, 10] [16, 18, 20]
2 [12, 12, 15] [15, 17, 19, 21, 23]
3 [20, 5, 4, 4] [29, 32]
4 [25, 25, 25, 24, 21] [21, 24, 25, 26, 28, 29, 30, 33]
5 [20, 20, 20, 21] [21, 22, 24, 26, 28, 30, 31, 32]
6 [8, 3, 3, 14] [25, 27]
7 [1, 4, 4, 4, 5, 6, 10] [69, 71, 72]
8 [11, 11, 11, 11] [19, 21, 22, 23, 24]
9 [7, 6, 9, 9] [19, 26, 27, 28]
10 [30, 30, 30, 30, 30] [38, 39]"""
df = pd.read_csv(StringIO(text), sep='\s{2,}', engine='python', index_col=0)
df = df.stack().str.strip('[]') \
.str.split(', ').unstack()
df
</code></pre>
<p><a href="http://i.stack.imgur.com/Zz4ev.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zz4ev.png" alt="enter image description here"></a></p>
<hr>
<h3>Get your table in the correct format</h3>
<pre><code>df1 = df.stack().apply(pd.Series).stack().astype(int) \
.rename_axis(['id', 'reality', None]) \
.rename('value').reset_index(['id', 'reality']) \
.reset_index(drop=True)
df1.head()
</code></pre>
<p><a href="http://i.stack.imgur.com/ed8Lr.png" rel="nofollow"><img src="http://i.stack.imgur.com/ed8Lr.png" alt="enter image description here"></a></p>
<pre><code>sns.boxplot(x='id', y='value', hue='reality', data=df1, palette='PRGn')
sns.despine(offset=10, trim=True)
</code></pre>
<p><a href="http://i.stack.imgur.com/cJbQW.png" rel="nofollow"><img src="http://i.stack.imgur.com/cJbQW.png" alt="enter image description here"></a></p>
| 2
|
2016-09-06T09:02:23Z
|
[
"python",
"pandas",
"seaborn"
] |
Is raising exceptions safe within 'before' callback of a transitions.Machine model?
| 39,344,177
|
<p>I am using the <a href="https://github.com/tyarkoni/transitions" rel="nofollow">transitions</a> FSM library. Imagine having an application FSM using the following code:</p>
<pre><code>from transitions import Machine
import os
class Application(object):
states = ["idle", "data_loaded"]
def __init__(self):
self.data = None
machine = Machine(model=self, states=Application.states, initial="idle")
machine.add_transition("filename_dropped",
source="idle",
dest="data_loaded",
before="load_data",
conditions="is_valid_filename")
self.machine = machine
def drop_filename(self, filename):
try:
self.filename_dropped(filename)
except IOError as exc:
print "Oops: %s" % str(exc)
def load_data(self, filename):
with open(filename) as file:
self.data = file.read()
def is_valid_filename(self, filename):
return os.path.isfile(filename)
</code></pre>
<p>It can throw an <code>IOError</code> within load_data. My question is whether it is safe to raise exceptions (either implicitly like in this example or explicitly) from within <code>before</code> callbacks? In case of an <code>IOError</code> the transition is not taking place, the state of this example remains <code>idle</code> and any <code>after</code> callbacks are not being invoked. However, I wonder whether the internal state of the machine instance might get corrupted.</p>
<p>Additional question: Are there any better ways to signal errors with concrete information to the application? In this very example I could use the condition to load the file, but this seems ugly and I would need some additional attribute to keep track of the error etc.</p>
<p>Thanks for any help or advice.</p>
| 0
|
2016-09-06T08:29:37Z
| 39,369,707
|
<blockquote>
<p>However, I wonder whether the internal state of the machine instance might get corrupted.</p>
</blockquote>
<p>It is fine to work with raising Exceptions in callback functions unless you plan to use the <code>queued</code> feature of transitions.</p>
<p>Transitions are executed in the following order:</p>
<p><code>prepare -> conditions -> before -> on_exit -> set_state -> on_enter -> after</code></p>
<p>If anything before <code>set_state</code> raises an Exception or a function in <code>conditions</code> does not return <code>True</code>, the transition is halted.</p>
<p>Your model might be in an undefined state though. If you rely on some 'clean up' or 'tear down' in <code>State.on_enter</code> or <code>after</code>:</p>
<pre><code>from transitions import Machine
class Model:
def __init__(self):
self.busy = False
def before(self):
self.busy = True
raise Exception('oops')
def after(self):
# if state transition is done, reset busy
self.busy = False
model = Model()
m = Machine(model, states=['A','B'], initial='A',
transitions=[{'trigger':'go', 'source':'A', 'dest':'B',
'before':'before', 'after':'after'}])
try:
model.go()
except Exception as e:
print "Exception: %s" % e # Exception: oops
print "State: %s" % model.state # State: A
print "Model busy: %r" % model.busy # Model busy: True
</code></pre>
<blockquote>
<p>Are there any better ways to signal errors with concrete information to the application?</p>
</blockquote>
<p>It depends on what you want to achieve. Raising Errors/Exceptions usually halts the execution of a current task. In my oppinion this is pretty much THE way to propagate issues. If you want to handle the error and represent the error as a state, I would not consider using <code>conditions</code> ugly. Valid transitions with the same <code>trigger</code> are evaluated in the order they were added. With this in mind and the use of <code>unless</code> which is negated notation for <code>conditions</code>, your code could look like this: </p>
<pre><code>from transitions import Machine
import os
class Application(object):
states = ["idle", "data_loaded", "filename_invalid", "data_invalid"]
transitions = [
{'trigger': 'filename_dropped', 'source': 'idle',
'dest': 'filename_invalid', 'unless': 'is_valid_filename'},
{'trigger':'filename_dropped', 'source': 'idle',
'dest':'data_invalid', 'unless': 'is_valid_data'},
{'trigger':'filename_dropped', 'source': 'idle',
'dest':'data_loaded'}
]
def __init__(self):
self.data = None
machine = Machine(model=self, states=Application.states,
transitions=Application.transitions, initial="idle")
self.machine = machine
def drop_filename(self, filename):
self.filename_dropped(filename)
if self.is_data_loaded():
print "Data loaded"
# renamed load_data
def is_valid_data(self, filename):
try:
with open(filename) as file:
self.data = file.read()
except IOError as exc:
print "File loading error: %s" % str(exc)
return False
return True
def is_valid_filename(self, filename):
return os.path.isfile(filename)
app = Application()
app.drop_filename('test.txt')
# >>> Data loaded
print app.state
# >>> data_loaded
app.to_idle()
app.drop_filename('missing.txt')
print app.state
# >>> filename_invalid
app.to_idle()
app.drop_filename('secret.txt')
# >>> File loading error: [Errno 13] Permission denied: 'secret.txt'
print app.state
# >>> data_invalid
</code></pre>
<p>This will create this state machine:</p>
<p><a href="http://i.stack.imgur.com/IKfQL.png" rel="nofollow"><img src="http://i.stack.imgur.com/IKfQL.png" alt="enter image description here"></a></p>
| 1
|
2016-09-07T12:15:02Z
|
[
"python",
"transitions",
"fsm"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.