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 |
---|---|---|---|---|---|---|---|---|---|
How can I kill omxplayer player on a Raspberry Pi using Python
| 39,515,757 |
<p>I'm doing a DIY project using a Raspberry Pi 3 where I need to play 4 videos using omxplayer. </p>
<p>Each video is played once you press a certain button on the protoboard:</p>
<ul>
<li>Press Button 1 - Play Video 1</li>
<li>Press Button 2 - Play Video 2</li>
<li>Press Button 3 - Play Video 3</li>
<li>Press Button 4 - Play Video 4</li>
</ul>
<p>I was successful playing the 4 videos whenever I press any of the buttons using the following python code:</p>
<pre><code>import RPi.GPIO as GPIO
import time
import os
GPIO.setmode(GPIO.BCM) # Declaramos que los pines seran llamados como numeros
GPIO.setwarnings(False)
GPIO.setup(4, GPIO.IN) # GPIO 7 como entrada
GPIO.setup(17, GPIO.IN) # GPIO 17 como entrada
GPIO.setup(27, GPIO.IN) # GPIO 27 como entrada
GPIO.setup(22, GPIO.IN) # GPIO 22 como entrada
pathVideos = "/home/pi/VideoHD/Belen" # Directorio donde se encuentran los videos en HD
def reproducirVideos(nameVideo):
command = "omxplayer -p -o hdmi %s/%s.mp4" % (pathVideos,nameVideo)
os.system(command)
print "Reproduciendo el Video: %s " % nameVideo
def programaPrincipal():
print("Inicio")
while True:
if (GPIO.input(4)):
print("Iniciando Video: AMANECER")
reproducirVideos("amanecer")
elif (GPIO.input(17)):
print("Iniciando Video: DIA")
reproducirVideos("dia")
elif (GPIO.input(27)):
print("Iniciando Video: ATARDECER")
reproducirVideos("atardecer")
elif (GPIO.input(22)):
print("Iniciando Video: ANOCHECER")
reproducirVideos("anochecer")
else:
pass
print("Fin de programa")
GPIO.cleanup() #Limpiar los GPIO
programaPrincipal() #Llamamos a la funcion blinkLeds para ejecutar el programa
</code></pre>
<p>Here is my issue. </p>
<p>When I press a button e.g Button 1, the whole video 1 starts playing properly on the screen. If I press any button while the video1 is running, nothing happens. What I want to achieve is that whenever I press any button on the protoboard, omxplayer should stop reproducing any video (if the is any playing) and start a new one.</p>
<p>I have read something about kill omxplayer using PIPE like they say in the following link but without success:</p>
<p><a href="http://stackoverflow.com/questions/20871658/how-can-i-kill-omxplayer-by-python-subprocess">How can I kill omxplayer by Python Subprocess</a></p>
<p>Any help will be appreciated</p>
| 0 |
2016-09-15T16:10:50Z
| 39,730,666 |
<p>I modified <strong>reproducirVideos()</strong> function with the following code in order to kill any process of <strong>omxplayer</strong> </p>
<pre><code>def reproducirVideos(nameVideo):
command1 = "sudo killall -s 9 omxplayer.bin"
os.system(command1)
command2 = "omxplayer -p -o hdmi %s/%s.mp4 &" % (pathVideos,nameVideo)
os.system(command2)
print "Reproduciendo el Video: %s " % nameVideo
</code></pre>
<p>I also added <strong>&</strong> at the end of <strong>command2</strong> in order to get the command run on the background</p>
<p>A Little bit "hacky" but worked properly for me :)</p>
| 0 |
2016-09-27T17:14:21Z
|
[
"python",
"raspberry-pi",
"omxplayer"
] |
Print function input into int
| 39,515,788 |
<p>My goal is very simple, which makes it all the more irritating that I'm repeatedly failing:</p>
<p>I wish to turn an input integer into a string made up of all numbers within the input range, so if the input is <code>3</code>, the code would be:
<code>print(*range(1, 3+1), sep="")</code> </p>
<p>which obviously works, however when using an <code>n = input()</code> , no matter where I put the <code>str()</code>, I get the same error: </p>
<pre><code>"Can't convert 'int' object to str implicitly"
</code></pre>
<p>I feel sorry to waste your collective time on such an annoyingly trivial task..</p>
<p>My code:</p>
<pre><code>n= input()
print(*range(1, n+1), sep="")
</code></pre>
<p>I've also tried list comprehensions (my ultimate goal is to have this all on one line): </p>
<pre><code>[print(*range(1,n+1),sep="") | n = input() ]
</code></pre>
<p>I know this is not proper syntax, how on earth am I supposed to word this properly? </p>
<p><a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">This</a> didn't help, ditto <a href="http://stackoverflow.com/questions/19352888/print-function-in-python3">this</a>, ditto <a href="http://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly">this</a>, I give up --> ask S.O.</p>
| 0 |
2016-09-15T16:12:26Z
| 39,516,571 |
<p>I see no reason why you would use <code>str</code> here, you should use <code>int</code>; the value returned from <code>input</code> is of type <code>str</code> and you need to transform it.</p>
<p>A one-liner could look like this:</p>
<pre><code>print(*range(1, int(input()) + 1), sep=' ')
</code></pre>
<p>Where <code>input</code> is wrapped in <code>int</code> to transform the str returned to an <code>int</code> and supply it as an argument to <code>range</code>.</p>
<p>As an addendum, your error here is caused by <code>n + 1</code> in your <code>range</code> call where <code>n</code> is <em>still</em> an <code>str</code>; Python <em>won't</em> implicitly transform the value held by <code>n</code> to an <code>int</code> and perform the operation; it'll complain:</p>
<pre><code>n = '1'
n + 1
TypeErrorTraceback (most recent call last)
<ipython-input-117-a5b1a168a772> in <module>()
----> 1 n + 1
TypeError: Can't convert 'int' object to str implicitly
</code></pre>
<p>That's why you need to be <em>explicit</em> and wrap it in <code>int()</code>. Additionally, take note that the one liner <em>will</em> fail with input that can't be transformed to an <code>int</code>, you need to wrap it in a <code>try-except</code> statement to handle that if needed.</p>
| 3 |
2016-09-15T16:58:37Z
|
[
"python",
"python-3.x"
] |
Print function input into int
| 39,515,788 |
<p>My goal is very simple, which makes it all the more irritating that I'm repeatedly failing:</p>
<p>I wish to turn an input integer into a string made up of all numbers within the input range, so if the input is <code>3</code>, the code would be:
<code>print(*range(1, 3+1), sep="")</code> </p>
<p>which obviously works, however when using an <code>n = input()</code> , no matter where I put the <code>str()</code>, I get the same error: </p>
<pre><code>"Can't convert 'int' object to str implicitly"
</code></pre>
<p>I feel sorry to waste your collective time on such an annoyingly trivial task..</p>
<p>My code:</p>
<pre><code>n= input()
print(*range(1, n+1), sep="")
</code></pre>
<p>I've also tried list comprehensions (my ultimate goal is to have this all on one line): </p>
<pre><code>[print(*range(1,n+1),sep="") | n = input() ]
</code></pre>
<p>I know this is not proper syntax, how on earth am I supposed to word this properly? </p>
<p><a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">This</a> didn't help, ditto <a href="http://stackoverflow.com/questions/19352888/print-function-in-python3">this</a>, ditto <a href="http://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly">this</a>, I give up --> ask S.O.</p>
| 0 |
2016-09-15T16:12:26Z
| 39,516,637 |
<p>In your code, you should just be able to do:</p>
<pre><code>n = int(input())
print(*range(1,n+1),sep="")
</code></pre>
<p>But you would also want to have some error checking to ensure that a number is actually entered into the prompt.</p>
<p>A one-liner that works:</p>
<pre><code>print(*range(1, int(input()) + 1), sep="")
</code></pre>
| 2 |
2016-09-15T17:03:03Z
|
[
"python",
"python-3.x"
] |
Does python threading module speed up the execution time?
| 39,515,821 |
<p>I have a database containing employee information. I have 4000 employees. Each employee has an unique identification number.
I try to fetch employee information for each employee from the database using a python script. For 1 employee, the execution time for fetching info is 1 seconds. For 4000 employees, it makes <code>4000</code> seconds (67 minutes, who would like to wait that long?).
The employee infos should be stored in a dictionary, in the following format:</p>
<pre><code>infos = {"ID1": ["info for employee 1"], "ID2": ["info for employee 2"], ... }
</code></pre>
<p>I'm thinking of doing the following to reduce the execution time:</p>
<ol>
<li>Get employee id numbers</li>
<li>Divide the id numbers into 10 groups</li>
<li>Start 10 threads simultaneously</li>
<li>Make each thread use 1 of 10 employee id groups and fetch those employees' info
from database into separate dictionaries</li>
<li>In the end, combine those 10 dictionaries</li>
</ol>
<p>Is it possible? Would this method reduce the execution time 10 times?</p>
| 0 |
2016-09-15T16:13:42Z
| 39,515,956 |
<p>I think you're confusing <em>threading</em> with <em>concurrency</em>.</p>
<p>Threading is the act of simply using multiple threads of execution at the same time. This doesn't mean multiple actions are done simultaneously though... your processor still has to switch between the threads. This technique is useful when you're expecting to wait a long time for an operation to complete (like reading a large file) and you want other stuff to happen in the meantime (printing a progress bar, for example).</p>
<p>Concurrency is when you create multiple threads, and different threads get assigned to different cores in the processor. This is, of course, dependent on the hardware (you need a multicore processor to accomplish it).</p>
<p>Python's <code>threading</code> module allows for multiple threads to be created, sure; and in an ideal world it would automatically handle concurrency. But the default Python interpreter, CPython, does not allow for native concurrency due to the "Global Interpreter Lock". (See <a href="https://docs.python.org/3/library/threading.html" rel="nofollow">this page</a> just above the section 17.1.3 heading and <a href="http://stackoverflow.com/a/1294402/3377150">this SO post</a> for more information about GIL.) In fact, using <code>threading</code> like you suggest may even make your execution <em>slower</em> (see <a href="https://www.quantstart.com/articles/parallelising-python-with-threading-and-multiprocessing" rel="nofollow">here</a>).</p>
<p>I've not done concurrency in Python, but I would advise you to check out the <a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow"><code>multiprocessing</code></a> module as a possible solution.</p>
| 0 |
2016-09-15T16:22:20Z
|
[
"python",
"database",
"multithreading"
] |
Parsing paragraph out of text file in Python?
| 39,515,844 |
<p>I am trying to parse certain paragraphs out of multiple text file and store them in list. All the text file have some similar format to this:</p>
<pre><code>MODEL NUMBER: A123
MODEL INFORMATION: some info about the model
DESCRIPTION: This will be a description of the Model. It
could be multiple lines but an empty line at the end of each.
CONCLUSION: Sold a lot really profitable.
</code></pre>
<p>Now i can pull out the information where its one line, but am having trouble when i encounter something which is multiple line (like 'Description'). The description length is not known but i know at the end it would have an empty line (which would mean using '\n'). This is what i have so far:</p>
<pre><code>import os
dir = 'Test'
DESCRIPTION = []
for files in os.listdir(dir):
if files.endswith('.txt'):
with open(dir + '/' + files) as File:
reading = File.readlines()
for num, line in enumerate(reading):
if 'DESCRIPTION:' in line:
Start_line = num
if len(line.strip()) == 0:
</code></pre>
<p>I don't know if its the best approach, but what i was trying to do with <code>if len(line.strip()) == 0:</code> is to create a list of blank lines and then find the first greater value than <code>Start_Line</code>. I saw this <a href="http://stackoverflow.com/questions/7281760/in-python-how-do-you-find-the-index-of-the-first-value-greater-than-a-threshold">Bisect</a>.</p>
<p>In the end i would like my data to be if i say <code>print Description</code></p>
<pre><code>['DESCRIPTION: Description from file 1',
'DESCRIPTION: Description from file 2',
'DESCRIPTION: Description from file 3,]
</code></pre>
<p>Thanks.</p>
| 0 |
2016-09-15T16:14:53Z
| 39,516,446 |
<p>Regular expression. Think about it this way: you have a pattern that will allow you to cut any file into pieces you will find palatable: "newline followed by capital letter"</p>
<p>re.split is your friend</p>
<p>Take a string</p>
<pre><code>"THE
BEST things
in life are
free
IS
YET
TO
COME"
</code></pre>
<p>As a string:</p>
<pre><code>p = "THE\nBEST things\nin life are\nfree\nIS\nYET\nTO\nCOME"
c = re.split('\n(?=[A-Z])', p)
</code></pre>
<p>Which produces list c </p>
<p><code>['THE', 'BEST things\nin life are\nfree', 'IS', 'YET', 'TO', 'COME']</code></p>
<p>I think you can take it from there, as this would separate your files into each a list of strings with each string beings its own section, then from there you can find the "DESCRIPTION" element and store it, you see that you separate each section, including its subcontents by that re split. Important to note that the way I've set up the regex it recognies the PATTERN "newline and then Capital Letter" but CUTS after the newline, which is why it is outside the brackets. </p>
| 0 |
2016-09-15T16:51:23Z
|
[
"python",
"list",
"python-2.7",
"file"
] |
Python libraries imported but unused
| 39,515,845 |
<p>The code is actually re-written from an application that worked
Using the latest version of python via Anaconda and Spyder ide
With Spyder
<a href="http://i.stack.imgur.com/MxgeS.jpg" rel="nofollow">code screenshot</a></p>
<pre><code>from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import matplotlib as plt
import os
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
import sklearn.metrics
from sklearn.metrics import classification_report
</code></pre>
<p>Code analysis show pandas library imported but unused.</p>
<p>Please help out a python noobie</p>
<p>thanks for the comments, I'm learning!!</p>
<p>I have run the script both with and without the imports as suggested and the console return the errors as seen in the SS<a href="http://i.stack.imgur.com/A0sIn.jpg" rel="nofollow">console error messages</a></p>
<pre><code>>>> runfile('C:/Users/dbldee/Desktop/TREES/Decisiontree.py', wdir='C:/Users/dbldee/Desktop/TREES')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\dbldee\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\Users\dbldee\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/dbldee/Desktop/TREES/Decisiontree.py", line 42, in <module>
classifier = classifier.fit(pred_train,tar_train)
TypeError: fit() missing 1 required positional argument: 'y'
>>>
</code></pre>
<p>Which suggests that the problem may be with reading of the file??</p>
| -3 |
2016-09-15T16:15:13Z
| 39,515,954 |
<p>Spyder is doing a <a href="https://en.wikipedia.org/wiki/Extended_static_checking" rel="nofollow">static check</a> to help with the correctness of your python program. You probably can run it just fine as it is, but the tool is helping you with python style and conciseness.</p>
<p>Try removing the line </p>
<pre><code>import pandas as pd
</code></pre>
<p>and it should stop complaining. Try breaking and changing the program following the ide's suggestions without fear to break the program, that is what will make you learn.</p>
| 2 |
2016-09-15T16:22:05Z
|
[
"python",
"pandas"
] |
Cryptography: converting C function to python
| 39,515,934 |
<p>I am trying to solve a cryptography problem (<a href="https://callicode.fr/pydefis/Reverse/txt" rel="nofollow">https://callicode.fr/pydefis/Reverse/txt</a>), the alghorithm make use of the following C function (F1).
I don't know C, I tried to convert it to python(F2) without success. Thank you in advance for letting me know what I did wrong.</p>
<p><strong>F1:</strong></p>
<pre><code>void Encrypt(unsigned char key[20], unsigned char *pPlainBuffer, unsigned char *pCipherBuffer, unsigned int nLength)
{
int nKeyPos = 0;
unsigned int n;
unsigned char KeyA = 0;
if ((pPlainBuffer != NULL) && (pCipherBuffer != NULL)) {
for (n = 0; n < 20; n++)
KeyA ^= key[n];
nKeyPos = KeyA % 20;
for (n = 0; n < nLength; n++) {
pCipherBuffer[n] = pPlainBuffer[n]^(key[nKeyPos]*KeyA);
KeyA += pCipherBuffer[n];
nKeyPos = pCipherBuffer[n] % 20;
}
}
}
</code></pre>
<p><strong>F2:</strong></p>
<pre><code>def Encrypt(plainText, key): # plainText is a list of hexadecimals representing ascii
# characters, key is a list of int size 20 each int
# beetween 0 and 255
keyA = 0
for n in range(20):
keyA ^= key[n]
nKeyPos = KeyA % 20
for n in range(len(plainText)):
codedText[n] = plainText[n]^(key[nKeyPos]*KeyA)
keyA += codedText[n]
nKeyPos = codedText[n] % 20
</code></pre>
| -1 |
2016-09-15T16:20:57Z
| 39,516,690 |
<p>Here's a little working example:</p>
<pre><code>def Encrypt(key, pPlainBuffer):
nKeyPos = 0
KeyA = 0
if pPlainBuffer is not None:
pCipherBuffer = []
for n in range(20):
KeyA = KeyA ^ key[n]
nKeyPos = KeyA % 20
for n in range(len(pPlainBuffer)):
pCipherBuffer.append(pPlainBuffer[n] ^ (key[nKeyPos] * KeyA))
KeyA += pCipherBuffer[n]
nKeyPos = pCipherBuffer[n] % 20
return pCipherBuffer
def Decrypt(key, pCipherBuffer):
nKeyPos = 0
KeyA = 0
if pCipherBuffer is not None:
pPlainBuffer = []
for n in range(20):
KeyA ^= key[n]
nKeyPos = KeyA % 20
for n in range(len(pCipherBuffer)):
pPlainBuffer.append(pCipherBuffer[n] ^ (key[nKeyPos] * KeyA))
KeyA += pCipherBuffer[n]
nKeyPos = pCipherBuffer[n] % 20
return pPlainBuffer
if __name__ == "__main__":
import random
key = [random.randint(0, 255) for k in range(20)]
pPlainBuffer = [ord(c) for c in "this is the unencrypted message"]
a = Encrypt(key, pPlainBuffer)
b = Decrypt(key, a)
print("-"*80)
print("Encrypted message")
print("-"*80)
print(":".join("{:02x}".format(c) for c in a))
print("-"*80)
print("Decrypted message")
print("-"*80)
print("".join([chr(c) for c in b]))
# --------------------------------------------------------------------------------
# Encrypted message
# --------------------------------------------------------------------------------
# 1ba:2678:197df9:bec4844:2d163e70c:1d01cf925ab:45512ab14a9b:4724251445d50:550934523b78ca:1f34a7cfbb7db6a1:1bfb485c731bcdb713:161112a22402868312ad:b1696bc757013314e2975:531cf11bdcc471dc32befef:a2627edf4f99a01240ba016f:839c3758163127edc2e955cc63:100437038699e709cce258a3ed1b:6c7fa638eaa735df4ae48a03e32a9:58911d1d6ea1c00863052f0fa160a0d:2c7f52a5aa98fec79d57f011bf256acf0:22559e3d644a5d56f620427531855711f90:81693c9711311b3cfe601f0f44c5ec6c8eb9:6a628fdbfce204d77db6eb221a161b683dee6a:c86f7e57fa208eaff7fbe01b26048cae230f1a8:308b00994e93e28e9e0f004693351a122c7da861d:2bc2e905f06bc052ef96e3dd7d68389e9df11483546:9717a6cd2ce3ac9b8757110bab10b835b11adda93df2:12072f89ef89b60cbd3d4c3735dda19daddbeecfd47b5d:1084c8b9afea8c4ece5432ef4130712f4f9a5a403acac323:27679b285784a6a9f1d42189acfc9433655c776e5ce16d191:1c6f807e0f27d47ad8ee72ba6740cb5dee4d918da413efe2f6d
# --------------------------------------------------------------------------------
# Decrypted message
# --------------------------------------------------------------------------------
# --------------------------------------------------------------------------------
# this is the unencrypted message
</code></pre>
<p>That'd be almost a 1:1 c++ rewrited version but if you wanted a more pythonic one:</p>
<pre><code>def encrypt(key, plain_buffer):
key_pos = 0
key_a = 0
cipher_buffer = []
if plain_buffer is not None:
for k in key:
key_a = key_a ^ k
key_pos = key_a % 20
for n, d in enumerate(plain_buffer):
cipher_buffer.append(d ^ (key[key_pos] * key_a))
key_a += cipher_buffer[n]
key_pos = cipher_buffer[n] % 20
return cipher_buffer
def decrypt(key, cipher_buffer):
key_pos = 0
key_a = 0
plain_buffer = []
if cipher_buffer is not None:
for k in key:
key_a ^= k
key_pos = key_a % 20
for n, d in enumerate(cipher_buffer):
plain_buffer.append(d ^ (key[key_pos] * key_a))
key_a += cipher_buffer[n]
key_pos = cipher_buffer[n] % 20
return plain_buffer
if __name__ == "__main__":
import random
random.seed(1)
key = [random.randint(0, 255) for k in range(20)]
plain_buffer = [ord(c) for c in "this is the unencrypted message"]
a = encrypt(key, plain_buffer)
b = decrypt(key, a)
print("-" * 80)
print("Encrypted message")
print("-" * 80)
print(":".join("{:02x}".format(c) for c in a))
print("-" * 80)
print("Decrypted message")
print("-" * 80)
print("".join([chr(c) for c in b]))
</code></pre>
<p>Although is not using unsigned chars, that's why the encrypted message looks that big.</p>
| 1 |
2016-09-15T17:06:30Z
|
[
"python",
"c",
"cryptography"
] |
Cryptography: converting C function to python
| 39,515,934 |
<p>I am trying to solve a cryptography problem (<a href="https://callicode.fr/pydefis/Reverse/txt" rel="nofollow">https://callicode.fr/pydefis/Reverse/txt</a>), the alghorithm make use of the following C function (F1).
I don't know C, I tried to convert it to python(F2) without success. Thank you in advance for letting me know what I did wrong.</p>
<p><strong>F1:</strong></p>
<pre><code>void Encrypt(unsigned char key[20], unsigned char *pPlainBuffer, unsigned char *pCipherBuffer, unsigned int nLength)
{
int nKeyPos = 0;
unsigned int n;
unsigned char KeyA = 0;
if ((pPlainBuffer != NULL) && (pCipherBuffer != NULL)) {
for (n = 0; n < 20; n++)
KeyA ^= key[n];
nKeyPos = KeyA % 20;
for (n = 0; n < nLength; n++) {
pCipherBuffer[n] = pPlainBuffer[n]^(key[nKeyPos]*KeyA);
KeyA += pCipherBuffer[n];
nKeyPos = pCipherBuffer[n] % 20;
}
}
}
</code></pre>
<p><strong>F2:</strong></p>
<pre><code>def Encrypt(plainText, key): # plainText is a list of hexadecimals representing ascii
# characters, key is a list of int size 20 each int
# beetween 0 and 255
keyA = 0
for n in range(20):
keyA ^= key[n]
nKeyPos = KeyA % 20
for n in range(len(plainText)):
codedText[n] = plainText[n]^(key[nKeyPos]*KeyA)
keyA += codedText[n]
nKeyPos = codedText[n] % 20
</code></pre>
| -1 |
2016-09-15T16:20:57Z
| 39,516,742 |
<p>you have many issues... the most glaring being that python integers are not constrained to a byte width by default so you must explicitly set the width</p>
<p>additionally you must convert the letters to numbers in python as they are fundamentally different things (in C/c++ letters are really just numbers)</p>
<pre><code>def Encrypt(plainText, key): # plainText is a list of hexadecimals representing ascii
# characters, key is a list of int size 20 each int # beetween 0 and 255
keyA = 0
for letter in key:
keyA ^= ord(letter) # conver letter to number
keyA = keyA & 0xFF # fix width to one byte
key = itertools.cycle(key) # repeate forever
codedText = ""
for letter,keyCode in zip(plainText,key):
xorVal = (ord(keyCode) * keyA) & 0xFF # make one byte wide
newLetter = chr((ord(letter) ^ xorVal )&0xFF) # make one byte wide
codedText += newLetter
keyA += ord(newLetter)
keyA = keyA&0xFF # keep it one byte wide
</code></pre>
| 1 |
2016-09-15T17:10:33Z
|
[
"python",
"c",
"cryptography"
] |
Matplotlib Rotating 3d Disk
| 39,515,937 |
<p>I have a line and some points that are on that are on that line in 3D space. I know there is a certain amount of error in the the point, but the error only extends perpendicular to the line. To view this I'd like to have disks with a radius of the error that are centered on the line and orthogonal to the direction of the line. I found this <a href="http://stackoverflow.com/questions/18228966/how-can-matplotlib-2d-patches-be-transformed-to-3d-with-arbitrary-normals">solution</a> but I can't get it to quite work. </p>
<p>If I run the code and state I want the output normal to the 'z' axis I get waht I woudl expect. Disks with a given radius on the line and oriented on z axis. </p>
<pre><code>pathpatch_2d_to_3d(p, z=z,normal='z')
</code></pre>
<p><a href="http://i.stack.imgur.com/9E4OI.png" rel="nofollow"><img src="http://i.stack.imgur.com/9E4OI.png" alt="Image with normal='z'"></a></p>
<p>I would like the disks rotated. In order to find the well vector at that point I'm using a point close by using that vector. This is the vector that I am putting as <code>normal=(vx,vy,vz)</code> but when I do that, the disks are not even on the chart. I'm not certain where I'm going wrong. Does anyone have any advice? </p>
<p>Here is my code.</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
import numpy as np
from scipy.interpolate import interp1d
md,wellz,wellx,welly=np.genfromtxt("./well.csv",delimiter=",",unpack=True)
# Building interpolation function that map a measured depth to its repsective x,y,z coordinates
fz = interp1d(md,wellz)
fx = interp1d(md,wellx)
fy = interp1d(md,welly)
pointDepth = np.array([15790,15554,15215,14911,14274,13927,13625,13284,12983,12640,12345,12004,11704,11361,11061,10717,10418,10080,9771])
def rotation_matrix(d):
"""
Calculates a rotation matrix given a vector d. The direction of d
corresponds to the rotation axis. The length of d corresponds to
the sin of the angle of rotation.
Variant of: http://mail.scipy.org/pipermail/numpy-discussion/2009-March/040806.html
"""
sin_angle = np.linalg.norm(d)
if sin_angle == 0:
return np.identity(3)
d = d/sin_angle
eye = np.eye(3)
ddt = np.outer(d, d)
skew = np.array([[ 0, d[2], -d[1]],
[-d[2], 0, d[0]],
[d[1], -d[0], 0]], dtype=np.float64)
M = ddt + np.sqrt(1 - sin_angle**2) * (eye - ddt) + sin_angle * skew
return M
def pathpatch_2d_to_3d(pathpatch, z = 0, normal = 'z'):
"""
Transforms a 2D Patch to a 3D patch using the given normal vector.
The patch is projected into they XY plane, rotated about the origin
and finally translated by z.
"""
if type(normal) is str: #Translate strings to normal vectors
index = "xyz".index(normal)
normal = np.roll((1,0,0), index)
normal = normal/np.linalg.norm(normal) #Make sure the vector is normalised
path = pathpatch.get_path() #Get the path and the associated transform
trans = pathpatch.get_patch_transform()
path = trans.transform_path(path) #Apply the transform
pathpatch.__class__ = art3d.PathPatch3D #Change the class
pathpatch._code3d = path.codes #Copy the codes
pathpatch._facecolor3d = pathpatch.get_facecolor #Get the face color
verts = path.vertices #Get the vertices in 2D
d = np.cross(normal, (0, 0, 1)) #Obtain the rotation vector
M = rotation_matrix(d) #Get the rotation matrix
pathpatch._segment3d = np.array([np.dot(M, (x, y, 0)) + (0, 0, z) for x, y in verts])
def pathpatch_translate(pathpatch, delta):
"""
Translates the 3D pathpatch by the amount delta.
"""
pathpatch._segment3d += delta
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(wellx,welly,wellz,c='k')
for n,pd in enumerate(pointDepth):
x,y,z = fx(pd),fy(pd),fz(pd)
# figure out a vector from the point
vx,vy,vz = (fx(pd-10)-x),(fy(pd-10)-y),(fz(pd-10)-z)
#Draw Circle
p = Circle((x,y), 100)
ax.add_patch(p)
pathpatch_2d_to_3d(p, z=z,normal=(vx,vy,vz))
pathpatch_translate(p,(0,0,0))
ax.set_xlim3d(np.min(wellx),np.max(wellx))
ax.set_ylim3d(np.min(welly), np.max(welly))
ax.set_zlim3d(np.min(wellz), np.max(wellz))
plt.show()
</code></pre>
| 0 |
2016-09-15T16:21:15Z
| 39,520,369 |
<p>Here is the solution I've come up with. I decided to take the difference between where the point falls on the line and where the first point in <code>p.._segment3d</code>. This gives me how far away my circle is from where I want it to be, then I simply translated the patch that distance minus the radius of the circle so it would be centered.</p>
<p>I've added in some random numbers to serve as some "error" and here is final code and resulting image</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
import numpy as np
from scipy.interpolate import interp1d
md,wellz,wellx,welly=np.genfromtxt("./well.csv",delimiter=",",unpack=True)
# Building interpolation function that map a measured depth to its repsective x,y,z coordinates
fz = interp1d(md,wellz)
fx = interp1d(md,wellx)
fy = interp1d(md,welly)
pointDepth = np.array([15790,15554,15215,14911,14274,13927,13625,13284,12983,12640,12345,12004,11704,11361,11061,10717,10418,10080,9771])
# Some random radii
dist = [random.random()*100 for x in pointDepth]
def rotation_matrix(d):
"""
Calculates a rotation matrix given a vector d. The direction of d
corresponds to the rotation axis. The length of d corresponds to
the sin of the angle of rotation.
Variant of: http://mail.scipy.org/pipermail/numpy-discussion/2009-March/040806.html
"""
sin_angle = np.linalg.norm(d)
if sin_angle == 0:
return np.identity(3)
d = d/sin_angle
eye = np.eye(3)
ddt = np.outer(d, d)
skew = np.array([[ 0, d[2], -d[1]],
[-d[2], 0, d[0]],
[d[1], -d[0], 0]], dtype=np.float64)
M = ddt + np.sqrt(1 - sin_angle**2) * (eye - ddt) + sin_angle * skew
return M
def pathpatch_2d_to_3d(pathpatch, z = 0, normal = 'z'):
"""
Transforms a 2D Patch to a 3D patch using the given normal vector.
The patch is projected into they XY plane, rotated about the origin
and finally translated by z.
"""
if type(normal) is str: #Translate strings to normal vectors
index = "xyz".index(normal)
normal = np.roll((1,0,0), index)
normal = normal/np.linalg.norm(normal) #Make sure the vector is normalised
path = pathpatch.get_path() #Get the path and the associated transform
trans = pathpatch.get_patch_transform()
path = trans.transform_path(path) #Apply the transform
pathpatch.__class__ = art3d.PathPatch3D #Change the class
pathpatch._code3d = path.codes #Copy the codes
pathpatch._facecolor3d = pathpatch.get_facecolor #Get the face color
verts = path.vertices #Get the vertices in 2D
d = np.cross(normal, (0, 0, 1)) #Obtain the rotation vector
M = rotation_matrix(d) #Get the rotation matrix
pathpatch._segment3d = np.array([np.dot(M, (x, y, 0)) + (0, 0, z) for x, y in verts])
def pathpatch_translate(pathpatch, delta):
"""
Translates the 3D pathpatch by the amount delta.
"""
pathpatch._segment3d += delta
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(wellx,welly,wellz,c='k')
for n,pd in enumerate(pointDepth):
x,y,z = fx(pd),fy(pd),fz(pd)
r = dist[n]
# figure out a vector from the point
vx,vy,vz = (fx(pd-10)-x),(fy(pd-10)-y),(fz(pd-10)-z)
#Draw Circle
p = Circle((x,y), r)
ax.add_patch(p)
pathpatch_2d_to_3d(p, z=z,normal=(vx,vy,vz))
difs = (x,y,z)-p._segment3d[0]
pathpatch_translate(p,(difs[0]-r/2,difs[1]-r/2,difs[2]-r/2))
ax.set_xlim3d(np.min(wellx),np.max(wellx))
ax.set_ylim3d(np.min(welly), np.max(welly))
ax.set_zlim3d(np.min(wellz), np.max(wellz))
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/FxJoU.png" rel="nofollow"><img src="http://i.stack.imgur.com/FxJoU.png" alt="enter image description here"></a></p>
| 0 |
2016-09-15T21:06:50Z
|
[
"python",
"matplotlib",
"3d"
] |
What is error code 35, returned by the telegram.org server
| 39,515,953 |
<p>My client often receives the following message container from the telegram server, seemingly at random:</p>
<pre><code>{'MessageContainer': [{'msg': {u'bad_msg_notification': {u'bad_msg_seqno': 4, u'bad_msg_id': 6330589643093583872L, u'error_code': 35}}, 'seqno': 4, 'msg_id': 6330589645303624705L}, {'msg': {u'msgs_ack': {u'msg_ids': [6330589643093583872L]}}, 'seqno': 4, 'msg_id': 6330589645303639041L}]})
</code></pre>
<p>You may notice: <strong>'error code': 35</strong> above, but there is no description of what that error code means. So far I have been ignoring it but that is not a good long term solution IMHO. Any ideas what that error code means?</p>
| 1 |
2016-09-15T16:22:04Z
| 39,516,162 |
<p>As <a href="https://core.telegram.org/mtproto/service_messages_about_messages" rel="nofollow">Telegram API docs</a> says, error with code 35 is "odd msg_seqno expected (relevant message), but even received"</p>
| 1 |
2016-09-15T16:34:53Z
|
[
"python",
"api",
"telegram"
] |
What is error code 35, returned by the telegram.org server
| 39,515,953 |
<p>My client often receives the following message container from the telegram server, seemingly at random:</p>
<pre><code>{'MessageContainer': [{'msg': {u'bad_msg_notification': {u'bad_msg_seqno': 4, u'bad_msg_id': 6330589643093583872L, u'error_code': 35}}, 'seqno': 4, 'msg_id': 6330589645303624705L}, {'msg': {u'msgs_ack': {u'msg_ids': [6330589643093583872L]}}, 'seqno': 4, 'msg_id': 6330589645303639041L}]})
</code></pre>
<p>You may notice: <strong>'error code': 35</strong> above, but there is no description of what that error code means. So far I have been ignoring it but that is not a good long term solution IMHO. Any ideas what that error code means?</p>
| 1 |
2016-09-15T16:22:04Z
| 39,755,683 |
<p>There are a set of errors associated with <strong><em>bad_msg_seqno</em></strong> </p>
<p><strong>From the documentation:</strong> </p>
<blockquote>
<p>Here, error_code can also take on the following values:</p>
<ol start="32">
<li>msg_seqno too low (the server
has already received a message with a lower msg_id but with either a
higher or an equal and odd seqno)</li>
<li>msg_seqno too high (similarly,
there is a message with a higher msg_id but with either a lower or
an equal and odd seqno)</li>
<li>an even msg_seqno expected (irrelevant
message), but odd received</li>
<li>odd msg_seqno expected (relevant
message), but even received</li>
</ol>
</blockquote>
<p><strong>Formal Definition:</strong> <a href="https://core.telegram.org/mtproto/description#message-sequence-number-msg-seqno" rel="nofollow">Message Sequence Number (msg_seqno)</a></p>
<blockquote>
<p>a 32-bit number equal to twice the number of âcontent-relatedâ
messages (those requiring acknowledgment, and in particular those that
are not containers) created by the sender prior to this message and
subsequently incremented by one if the current message is a
content-related message. A container is always generated after its
entire contents; therefore, its sequence number is greater than or
equal to the sequence numbers of the messages contained in it.</p>
</blockquote>
<p><strong>Notes:</strong></p>
<ol>
<li>Every new session starts from seq_no = 1 --> (0 * 2) + 1</li>
<li>Every sequence number you send is calculated as: (number_of_content_messages_ already_sent * 2) + 1 hence the all sequence numbers you send are always odd</li>
<li>A container messages seq_no == the max seq_no of its content messages</li>
<li>The server will always reply you with the correct <code>server_seq_no</code> which should be 1 greater than your <strong><em>correct</em></strong> max seq_no so far.</li>
<li>hence a good check / seq_no correction scheme would be to use the latest received <code>server_seq_no</code> (which should always be even) to confirm what your <code>current-expected</code> seq_no should be, and adjust as required.</li>
</ol>
<p>The above technique has worked for me in avoiding these intermittent error messages completely.</p>
| 1 |
2016-09-28T19:03:22Z
|
[
"python",
"api",
"telegram"
] |
how to sort items in a list alphabetically by the letters in their respective names.
| 39,516,032 |
<p>I am trying to sort values in a list by the letters in their name: I want, for example, ["8a", "8c", "8b", "8d"] to become ["8a", "8b","8c", "8d"]. Does this have something to do with a key?</p>
| 0 |
2016-09-15T16:27:01Z
| 39,516,100 |
<p>You can accomplish this by sorting it by a list.</p>
<pre><code>list = ["8a", "8c", "8b", "8d"]
list.sort()
print(list)
</code></pre>
| 0 |
2016-09-15T16:31:24Z
|
[
"python"
] |
how to sort items in a list alphabetically by the letters in their respective names.
| 39,516,032 |
<p>I am trying to sort values in a list by the letters in their name: I want, for example, ["8a", "8c", "8b", "8d"] to become ["8a", "8b","8c", "8d"]. Does this have something to do with a key?</p>
| 0 |
2016-09-15T16:27:01Z
| 39,516,107 |
<p>That would solve solve your problem:</p>
<pre><code>_list = ["8a", "8c", "8b", "8d"]
_list.sort()
print _list
</code></pre>
<p>Output:</p>
<pre><code>['8a', '8b', '8c', '8d']
</code></pre>
| 0 |
2016-09-15T16:31:36Z
|
[
"python"
] |
how to sort items in a list alphabetically by the letters in their respective names.
| 39,516,032 |
<p>I am trying to sort values in a list by the letters in their name: I want, for example, ["8a", "8c", "8b", "8d"] to become ["8a", "8b","8c", "8d"]. Does this have something to do with a key?</p>
| 0 |
2016-09-15T16:27:01Z
| 39,516,153 |
<p>The answer is easy if the data looks like in your question. If the data is more complex you will have to give the <code>sort</code> method a key which contains only characters from the alphabet.</p>
<pre><code>data = ["34b", "2a5t", "2a5s", "abcd"]
data.sort(key=lambda x: ''.join(c for c in x if c.isalpha()))
print(data)
</code></pre>
<p>This will give you <code>['abcd', '2a5s', '2a5t', '34b']</code>.</p>
<p>If you want to see how the constructed key looks like you can check it like this:</p>
<pre><code>for value in data:
print(value, ''.join(c for c in value if c.isalpha()))
34b b
2a5t at
2a5s as
abcd abcd
</code></pre>
| 3 |
2016-09-15T16:34:20Z
|
[
"python"
] |
how to sort items in a list alphabetically by the letters in their respective names.
| 39,516,032 |
<p>I am trying to sort values in a list by the letters in their name: I want, for example, ["8a", "8c", "8b", "8d"] to become ["8a", "8b","8c", "8d"]. Does this have something to do with a key?</p>
| 0 |
2016-09-15T16:27:01Z
| 39,516,165 |
<p>The .sort() method for lists has been mentioned; there's a sorting function that takes the list as an argument, and returns a sorted list without modifying the list in place:</p>
<pre><code>>>> mylist = ["8a", "8c", "8b", "8d"]
>>> sorted(list)
['8a', '8b', '8c', '8d']
>>> mylist
['8a', '8c', '8b', '8d']
</code></pre>
| 0 |
2016-09-15T16:35:20Z
|
[
"python"
] |
how to sort items in a list alphabetically by the letters in their respective names.
| 39,516,032 |
<p>I am trying to sort values in a list by the letters in their name: I want, for example, ["8a", "8c", "8b", "8d"] to become ["8a", "8b","8c", "8d"]. Does this have something to do with a key?</p>
| 0 |
2016-09-15T16:27:01Z
| 39,516,195 |
<p>Assuming your format is always number followed by letter, you need to give the sort method a specific key to sort by: in this case you want to sort by the last character. A lot of the other answers are just sorting your list alphabetically using the number followed by letter whereas I get the feeling you only want to sort by the letter. This is one possible way:</p>
<pre><code> s = ['9d', '12a', '1e']
sorted_s = sorted(s, key=lambda x:x[-1]) # sorts by the last character of every entry
</code></pre>
<p>This will return:</p>
<pre><code>['12a', '9d', '1e']
</code></pre>
| 1 |
2016-09-15T16:36:37Z
|
[
"python"
] |
how to sort items in a list alphabetically by the letters in their respective names.
| 39,516,032 |
<p>I am trying to sort values in a list by the letters in their name: I want, for example, ["8a", "8c", "8b", "8d"] to become ["8a", "8b","8c", "8d"]. Does this have something to do with a key?</p>
| 0 |
2016-09-15T16:27:01Z
| 39,516,406 |
<blockquote>
<p>trying to sort values in a list by the letters in their name</p>
</blockquote>
<p>The example you mentioned is very simple. Based on your requirement, below is the code using <code>re.findall()</code> and <code>sorted()</code> to sort based on letters in any order within string:</p>
<pre><code>>>> import re
>>> s = ['a9d', '1a2ba', '1e2s', '1b3tr']
>>> sorted(s, key=lambda x: re.findall("[a-zA-Z]+", x))
['1a2ba', 'a9d', '1b3tr', '1e2s'] # Sorted based on: aba, ad, btr, es
</code></pre>
| 0 |
2016-09-15T16:48:31Z
|
[
"python"
] |
How do I can get list of Google YouTube API methods?
| 39,516,051 |
<p>I need to get list of YouTube API (v3) methods, because I want to implement a simple client library, which will not contain URL to every method, and just call them with their name.
I'll use Python for this.</p>
| 0 |
2016-09-15T16:28:14Z
| 39,532,811 |
<p>As @sous2817 said, you can see all the methods that the YouTube API supports in this <a href="https://developers.google.com/youtube/v3/docs/" rel="nofollow">documentation</a>. </p>
<blockquote>
<p>This reference guide explains how to use the API to perform all of these operations. The guide is organized by resource type. A resource represents a type of item that comprises part of the YouTube experience, such as a video, a playlist, or a subscription. For each resource type, the guide lists one or more data representations, and resources are represented as JSON objects. The guide also lists one or more supported methods (<code>LIST</code>, <code>POST</code>, <code>DELETE</code>, etc.) for each resource type and explains how to use those methods in your application.</p>
</blockquote>
<p>Here are <a href="https://developers.google.com/youtube/v3/code_samples/python" rel="nofollow">Python Code Samples</a> which use the <a href="https://developers.google.com/api-client-library/python/" rel="nofollow">Google APIs Client Library for Python</a>:</p>
<blockquote>
<p><strong>Call the API's captions.list method to list the existing caption tracks.</strong></p>
</blockquote>
<pre><code>def list_captions(youtube, video_id):
results = youtube.captions().list(
part="snippet",
videoId=video_id
).execute()
for item in results["items"]:
id = item["id"]
name = item["snippet"]["name"]
language = item["snippet"]["language"]
print "Caption track '%s(%s)' in '%s' language." % (name, id, language)
return results["items"]
</code></pre>
<blockquote>
<p><strong>Call the API's captions.download method to download an existing caption track.</strong></p>
</blockquote>
<pre><code>def download_caption(youtube, caption_id, tfmt):
subtitle = youtube.captions().download(
id=caption_id,
tfmt=tfmt
).execute()
print "First line of caption track: %s" % (subtitle)
</code></pre>
<p><a href="https://developers.google.com/youtube/v3/code_samples/python#create_and_manage_youtube_video_caption_tracks" rel="nofollow">More sample codes</a>.</p>
| 1 |
2016-09-16T13:32:38Z
|
[
"python",
"python-2.7",
"youtube",
"youtube-api",
"youtube-data-api"
] |
python pandas: date/time function to compute time period
| 39,516,055 |
<p>I have the following working code, trying to filter in the data within 14 days of the reference date. However, I had to hard code the date:</p>
<pre><code>reference_ts = "2016-09-15 00:00:00"
df1 = df[df.my_ts >= "2016-09-01 00:00:00"]
</code></pre>
<p>I am wondering is there any function that I can use to compute a certain time period from a reference time point? Something like the pseudo code below:</p>
<pre><code>df1 = df[df.my_ts >= date_sub(reference_ts,14)]
</code></pre>
<p>Thanks!</p>
| -1 |
2016-09-15T16:28:29Z
| 39,516,192 |
<p>Yes, there is.</p>
<p>You can just check <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">timedelta</a></p>
<p>It is gonna solve your problem.</p>
| 0 |
2016-09-15T16:36:23Z
|
[
"python",
"datetime",
"pandas"
] |
python pandas: date/time function to compute time period
| 39,516,055 |
<p>I have the following working code, trying to filter in the data within 14 days of the reference date. However, I had to hard code the date:</p>
<pre><code>reference_ts = "2016-09-15 00:00:00"
df1 = df[df.my_ts >= "2016-09-01 00:00:00"]
</code></pre>
<p>I am wondering is there any function that I can use to compute a certain time period from a reference time point? Something like the pseudo code below:</p>
<pre><code>df1 = df[df.my_ts >= date_sub(reference_ts,14)]
</code></pre>
<p>Thanks!</p>
| -1 |
2016-09-15T16:28:29Z
| 39,516,418 |
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html" rel="nofollow">pd.Timedelta()</a>:</p>
<pre><code>reference_ts = pd.to_datetime("2016-09-15 00:00:00")
df1 = df[df.my_ts >= reference_ts - pd.Timedelta(days=14)]
</code></pre>
| 1 |
2016-09-15T16:49:31Z
|
[
"python",
"datetime",
"pandas"
] |
Looping not happening correctly in Python
| 39,516,173 |
<p>This is my python code that works on some data (a list) that looks like:</p>
<pre><code>1 Check _ VERB VB _ 0 ROOT _ _
2 out _ PRT RP _ 1 prt _ _
3 this _ DET DT _ 4 det _ _
4 video _ NOUN NN _ 1 dobj _ _
5 about _ ADP IN _ 4 prep _ _
6 Northwest _ NOUN NNP _ 7 nn _ _
7 Arkansas _ NOUN NNP _ 5 pobj _ _
8 - _ . , _ 7 punct _ _
9 https _ X ADD _ 7 appos _ _
10 : _ . : _ 4 punct _ _
11 hello _ NUM CD _ 12 num _ _
12 # _ NOUN NN _ 4 dep _ _
13 TEAMWALMART _ NOUN NNP _ 12 appos _ _
1 Check _ VERB VB _ 0 ROOT _ _
2 out _ PRT RP _ 1 prt _ _
3 this _ DET DT _ 6 det _ _
4 # _ NOUN NN _ 5 dep _ _
5 AMAZING _ VERB VBG _ 6 amod _ _
6 vide _ NOUN NN _ 1 dobj _ _
7 o _ NOUN NNP _ 6 partmod _ _
8 about _ ADP IN _ 7 prep _ _
9 Walmart _ NOUN NNP _ 8 pobj _ _
10 # _ . $ _ 9 dep _ _
11 MORETHANEXPECTED _ VERB VBN _ 9 dep _ _
</code></pre>
<p>The python code contains two parts:
1. read the lines and create the original text by collecting all the second tokens in the lines above.
2. create word tags that look like: <code>{'pos_tag': 'NNP', 'position': '13', 'dep_rel': 'appos', 'parent': '12', 'word': 'TEAMWALMART'}</code> for each word.</p>
<p>Python code:</p>
<pre><code>for line in data:
if line:
tweet.append(line)
if not line:
original_tweet = get_original_tweet(tweet)
word_tags = get_word_tags(tweet)
new_json_object['text'] = original_tweet
new_json_object['tags'] = word_tags
new_json_object_list.append(new_json_object.copy())
del tweet[:]
print new_json_object_list
def get_original_tweet(tweet_lines):
tweet_words = []
for line in tweet_lines:
tweet_words.append(line.split()[1])
original_tweet = ' '.join(tweet_words)
return original_tweet
def get_word_tags(tweet_lines):
word_tags = {}
word_tags_list = []
for line in tweet_lines:
words = line.split()
word_tags['word'] = words[1]
word_tags['position'] = words[0]
word_tags['pos_tag'] = words[4]
word_tags['dep_rel'] = words[7]
word_tags['parent'] = words[6]
word_tags_list.append(word_tags.copy())
word_tags.clear()
return word_tags_list
</code></pre>
<p>This code works fine but does that only on the first set of lines i.e. till line 13 in the data. It is ignoring the second tweet. I don't know what I am missing. The code seems correct to me. Can someone help me debug this please?</p>
| 0 |
2016-09-15T16:35:42Z
| 39,516,943 |
<p>I don't have enough rep to comment, so I'll write a super short answer.</p>
<p>I think you just need a blank line at the end of your data list.</p>
| 0 |
2016-09-15T17:23:05Z
|
[
"python",
"python-2.7",
"loops",
"debugging",
"for-loop"
] |
How to call a redis command and send output to a file?
| 39,516,196 |
<p>I want to run a redis command using a python script like:</p>
<pre><code>redis-cli hget "User-123"
</code></pre>
<p>And I want the output to be written to a file.</p>
<p>I cannot actually install the redis client because this script has to have no dependancies. </p>
<p>I have python 2.6.6</p>
| 0 |
2016-09-15T16:36:38Z
| 39,518,913 |
<p>Use <a href="https://github.com/andymccurdy/redis-py" rel="nofollow">redis-py</a>, it works with 2.6. Then use python's builtin <a href="https://docs.python.org/2.6/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">file i/o</a> functions to write to a file.</p>
| 0 |
2016-09-15T19:29:17Z
|
[
"python",
"redis"
] |
Python: Get Gmail server with smtplib never ends
| 39,516,200 |
<p>I simply tried:</p>
<pre><code>>>> import smtplib
>>> server = smtplib.SMTP('smtp.gmail.com:587')
</code></pre>
<p>in my Python interpreter but the second statement never ends.</p>
<p>Can someone help? </p>
| 0 |
2016-09-15T16:36:59Z
| 39,516,410 |
<p>You might find that you need a login and password as a prerequisite to a successful login-in.<br>
Try something like this:</p>
<pre><code>import smtplib
ServerConnect = False
try:
smtp_server = smtplib.SMTP('smtp.gmail.com','587')
smtp_server.login('your_login', 'password')
ServerConnect = True
except SMTPHeloError as e:
print "Server did not reply"
except SMTPAuthenticationError as e:
print "Incorrect username/password combination"
except SMTPException as e:
print "Authentication failed"
</code></pre>
<p>If you get "connection unexpected closed" try changing the server line to:</p>
<pre><code>smtp_server = smtplib.SMTP_SSL('smtp.gmail.com','465')
</code></pre>
<p>Be aware: Google may block sign-in attempts from some apps or devices that do not use modern security standards. Since these apps and devices are easier to break into, blocking them helps keep your account safe. See:<a href="https://support.google.com/accounts/answer/6010255?hl=en" rel="nofollow">https://support.google.com/accounts/answer/6010255?hl=en</a></p>
<p>Gmail settings:</p>
<pre><code>SMTP Server (Outgoing Messages) smtp.gmail.com SSL 465
smtp.gmail.com StartTLS 587
IMAP Server (Incoming Messages) imap.gmail.com SSL 993
Please make sure, that IMAP access is enabled in the account settings.
Login to your account and enable IMAP.
You also need to enable "less secure apps" (third party apps) in the Gmail settings:
https://support.google.com/accounts/answer/6010255?hl=en
See also: How to enable IMAP/POP3/SMTP for Gmail account
</code></pre>
<p>If all else fails trying to <code>ping gmail.com</code> from the command line. </p>
| 0 |
2016-09-15T16:49:07Z
|
[
"python",
"smtplib"
] |
Theano - SGD with 1 hidden layer
| 39,516,254 |
<p>I was using <a href="https://github.com/Newmu/Theano-Tutorials/blob/master/2_logistic_regression.py" rel="nofollow">Newmu tutorial</a> for logistic regression from his github. Wanted to add one hidden layer to his model, so I divided weights variable into two arrays h_w and o_w.
The problem is - when I'm trying to make an update its impossible to operate on the list (w = [h_w, o_w])</p>
<pre><code> "File "C:/Users/Dis/PycharmProjects/untitled/MNISTnet.py",
line 32, in <module>
**update = [[w, w - gradient * 0.05]] TypeError: can't multiply sequence by non-int of type 'float'**"
</code></pre>
<p>I'm beginner in theano and numpy and theano documentation couldn't help me. I've found stack() function, but when combining <code>w = T.stack([h_w, o_w], axis=1)</code> theano gives me error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Dis\PycharmProjects\untitled\MNISTnet.py", line 35, in <module>
gradient = T.grad(cost=cost, wrt=w)
File "C:\Program Files\Anaconda2\lib\site-packages\theano-0.9.0.dev1-py2.7.egg\theano\gradient.py", line 533, in grad
handle_disconnected(elem)
File "C:\Program Files\Anaconda2\lib\site-packages\theano-0.9.0.dev1-py2.7.egg\theano\gradient.py", line 520, in handle_disconnected
raise DisconnectedInputError(message)
theano.gradient.DisconnectedInputError:
Backtrace when that variable is created:
File "C:\Users\Dis\PycharmProjects\untitled\MNISTnet.py", line 30, in <module>
w = T.stack([h_w, o_w], axis=1)
</code></pre>
<p>So, my question: how can I convert that list <code>[<TensorType(float64, matrix)>, <TensorType(float64, matrix)>]</code> to variable <code><TensorType(float64, matrix)></code>?</p>
<p>My full code below:</p>
<pre><code>import theano
from theano import tensor as T
import numpy as np
from load import mnist
def floatX(X):
return np.asarray(X, dtype=theano.config.floatX)
def init_weights(shape):
return theano.shared(floatX(np.random.randn(*shape) * 0.01))
def model(X, o_w, h_w):
hid = T.nnet.sigmoid(T.dot(X, h_w))
out = T.nnet.softmax(T.dot(hid, o_w))
return out
trX, teX, trY, teY = mnist(onehot=True)
X = T.fmatrix()
Y = T.fmatrix()
h_w = init_weights((784, 625))
o_w = init_weights((625, 10))
py_x = model(X, o_w, h_w)
y_pred = T.argmax(py_x, axis=1)
w = [o_w, h_w]
cost = T.mean(T.nnet.categorical_crossentropy(py_x, Y))
gradient = T.grad(cost=cost, wrt=w)
print type(gradient)
update = [[w, w - gradient * 0.05]]
</code></pre>
| 0 |
2016-09-15T16:39:47Z
| 39,516,894 |
<p><code>T.grad(..)</code> returns <a href="http://deeplearning.net/software/theano/tutorial/gradients.html" rel="nofollow">gradient</a> w.r.t to each parameter, so you cannot do <code>[w, w - gradient * 0.05]</code>, you have to specify which gradient[*] parameter you are referring to. Also it's not a good idea to use stack for multiple parameters, simple list is good enough, check this <a href="http://deeplearning.net/tutorial/logreg.html" rel="nofollow">tutorial</a>.
This should work:</p>
<pre><code>import theano
from theano import tensor as T
import numpy as np
from load import mnist
def floatX(X):
return np.asarray(X, dtype=theano.config.floatX)
def init_weights(shape):
return theano.shared(floatX(np.random.randn(*shape) * 0.01))
def model(X, o_w, h_w):
hid = T.nnet.sigmoid(T.dot(X, h_w))
out = T.nnet.softmax(T.dot(hid, o_w))
return out
trX, teX, trY, teY = mnist(onehot=True)
X = T.fmatrix()
Y = T.fmatrix()
h_w = init_weights((784, 625))
o_w = init_weights((625, 10))
py_x = model(X, o_w, h_w)
y_pred = T.argmax(py_x, axis=1)
w = [o_w, h_w]
cost = T.mean(T.nnet.categorical_crossentropy(py_x, Y))
gradient = T.grad(cost=cost, wrt=w)
print type(gradient)
update = [[o_w, o_w - gradient[0] * 0.05],
[h_w, h_w - gradient[1] * 0.05]]
</code></pre>
<p>I suggest going through Theano <a href="http://deeplearning.net/software/theano/tutorial/index.html" rel="nofollow">tutorials</a> to get started.</p>
| 1 |
2016-09-15T17:20:08Z
|
[
"python",
"numpy",
"theano"
] |
Loop through object functions
| 39,516,322 |
<p><code>dir(object)</code> returns a list of object attributes and functions. How can I iterate over all callable functions and get the output of the functions? (ASSUMING NO FUNCTION ARGS)</p>
<pre><code>for a in dir(obj) if not a.startswith('__') and callable(getattr(obj,a)):
response = obj.a()
</code></pre>
<p>This does not work as python is treating a as the attribute name. Is there any way to do this?</p>
| -2 |
2016-09-15T16:44:09Z
| 39,516,344 |
<p>you need to use getattr to actually get the callable and then call it ...</p>
<p>do this</p>
<pre><code>fn = getattr(obj,a)
fn()
</code></pre>
<p>not this</p>
<pre><code>obj.a()
</code></pre>
<p>of coarse you are not checking if the callable has any required arguments or anything like that ... im not sure what you are actually trying to accomplish... but im skeptical that this is the right technique</p>
<p>additionally you need one more <code>)</code> on this line <code>callable(getattr(obj,a):</code></p>
| 1 |
2016-09-15T16:45:16Z
|
[
"python",
"python-2.7"
] |
How move a multipolygon with geopandas in python2
| 39,516,553 |
<p>I'm novice in GIS world in python (geopandas, shapely, etc). I need "move" a Multipolygon upwards, but I don't know how to do that.</p>
<h3>The Problem</h3>
<pre><code>import pandas as pd
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import seaborn as sns
import pysal as ps
from pysal.contrib.viz import mapping as maps
import geopandas as gpd
fs = 5
nums = ("renta", 1)
f, ax = plt.subplots(1, figsize=(fs,fs))
spain.plot(column="XBAR", ax=ax, linewidth=0.05, cmap="OrRd", scheme="unique_values")
ax.set_axis_off()
plt.title("RENTA MEDIA", fontsize=20)
plt.tight_layout()
plt.savefig("../imgs/map_%s_%s.svg" % nums, bbox_iches="tight", dpi=2800)
plt.show()
</code></pre>
<p>output:</p>
<p><img src="http://i.imgur.com/N66XItd.png" alt=""></p>
<p>As you can see, Islands "Canarias" are away from rest of Spain, I want a smaller figure, and it's takes account that color is important, it's represent income mean for each counties.</p>
<p>If it's helps:</p>
<pre><code>canarias = spain[spain.ca == "CANARIAS"]["geometry"]
print canarias
print canarias.type
13 (POLYGON ((-17.92791748046875 27.8495826721191...
Name: geometry, dtype: object
13 MultiPolygon
dtype: object
</code></pre>
<p>Note: Are counties missing, that's why I don't have data for this counties.</p>
<p>My first attempt was try to change coords of polygon for example, I try to find how to do some like this: canarias.coords + (-3,-4) but I didn't find how to access to coords of multipolygon to do that.</p>
<p>I appreciate any help. </p>
<p>PS: Sorry for my English :-/</p>
| 1 |
2016-09-15T16:57:44Z
| 39,671,488 |
<p>I think you are looking for <code>shapely.affinity.translate</code>. From the docs:</p>
<pre><code>Signature: shapely.affinity.translate(geom, xoff=0.0, yoff=0.0, zoff=0.0)
Docstring:
Returns a translated geometry shifted by offsets along each dimension.
The general 3D affine transformation matrix for translation is:
/ 1 0 0 xoff \
| 0 1 0 yoff |
| 0 0 1 zoff |
\ 0 0 0 1 /
</code></pre>
<p>For your specific example, you can use:</p>
<pre><code>canarias = spain[spain.ca == "CANARIAS"].geometry
canarias_shift = canarias.apply(lambda x: shapely.affinity.translate(x, xoff=-3, yoff=-4))
</code></pre>
| 2 |
2016-09-24T01:01:25Z
|
[
"python",
"python-2.7",
"shapely",
"geopandas"
] |
Blocking button click signals in PyQt
| 39,516,651 |
<p>I have a program that uses pyqt's .animateClick() feature to show the user a sequence of different button clicks that the user has to copy in that specific order. The problem is I don't want the animateClick() to send a signal, I only want the button click signals from the user. Here is some of my code to demonstrate what I mean, and how I tried to solve that problem (that doesn't work). I simplified my code quite a bit so its easier to read, let me know if you have any questions.</p>
<pre><code>from PyQt4 import QtCore,QtGui
global flag
global ai_states
ai_states = []
user_states = []
class Program(object):
# Set up the push buttons
#Code Here.
# Connect push buttons to function get_state()
self.pushButton.clicked.connect(self.get_state)
self.pushButton_2.clicked.connect(self.get_state)
self.pushButton_3.clicked.connect(self.get_state)
self.pushButton_4.clicked.connect(self.get_state)
# Code that starts the start() function
def start(self):
flag = 0
ai_states[:] = []
i = -1
# Code here that generates ai_states, numbers 1-4, in any order, based on button numbers.
for k in ai_states:
i = i + 1
# Code here that animates button clicks determined by ai_states
# Changes the flag to 1 once the loop ends
if i == len(ai_states):
flag = 1
def get_state(self):
if flag == 1:
user_states.append(str(self.centralWidget.sender().text()))
else:
pass
if len(user_states) == len(ai_states):
# Checks to make sure the user inputted the same clicks as the ai_states
</code></pre>
<p>Even though the flag does come out to be 1 after the start() function, it is still appending the animatedClick() signals. What am I doing wrong? I'm new to GUI programming, so I'm probably going about this in a very bad way. Any help would be appreciated.</p>
| 0 |
2016-09-15T17:04:09Z
| 39,521,373 |
<p>Never use global variables unless you really have to. If you need shared access to variables, use instance attributes:</p>
<pre><code>from PyQt4 import QtCore,QtGui
class Program(object):
def __init__(self):
self.ai_states = []
self.user_states = []
self.flag = 1
# Set up the push buttons
# Code Here
# Connect push buttons to function get_state()
self.pushButton.clicked.connect(self.get_state)
self.pushButton_2.clicked.connect(self.get_state)
self.pushButton_3.clicked.connect(self.get_state)
self.pushButton_4.clicked.connect(self.get_state)
# Code that starts the start() function
def start(self):
self.flag = 0
del self.ai_states[:]
i = -1
# Code here that generates ai_states, numbers 1-4, in any order, based on button numbers.
for k in self.ai_states:
i = i + 1
# Code here that animates button clicks determined by ai_states
# Changes the flag to 1 once the loop ends
self.flag = 1
def get_state(self):
if self.flag == 1:
self.user_states.append(str(self.centralWidget.sender().text()))
if len(self.user_states) == len(self.ai_states):
# Checks to make sure the user inputted the same clicks as the ai_states
</code></pre>
| 1 |
2016-09-15T22:40:24Z
|
[
"python",
"user-interface",
"pyqt",
"signals"
] |
extend a pandas datetimeindex by 1 period
| 39,516,671 |
<p>consider the <code>DateTimeIndex</code> <code>dates</code></p>
<pre><code>dates = pd.date_range('2016-01-29', periods=4, freq='BM')
dates
DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29'],
dtype='datetime64[ns]', freq='BM')
</code></pre>
<p>I want to extend the index by one period at the frequency attached to the object.</p>
<hr>
<p>I expect</p>
<pre><code>pd.date_range('2016-01-29', periods=5, freq='BM')
DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29',
'2016-05-31'],
dtype='datetime64[ns]', freq='BM')
</code></pre>
<hr>
<p>I've tried</p>
<pre><code>dates.append(dates[[-1]] + pd.offsets.BusinessMonthEnd())
</code></pre>
<p>However</p>
<ul>
<li>Not generalized to use frequency of <code>dates</code></li>
<li>I get a performance warning
<blockquote>
<p>PerformanceWarning: Non-vectorized DateOffset being applied to Series or DatetimeIndex</p>
</blockquote></li>
</ul>
| 1 |
2016-09-15T17:05:16Z
| 39,516,881 |
<p>try this:</p>
<pre><code>In [207]: dates = dates.append(pd.DatetimeIndex(pd.Series(dates[-1] + pd.offsets.BusinessMonthEnd())))
In [208]: dates
Out[208]: DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29', '2016-05-31'], dtype='datetime64[ns]', freq=None)
</code></pre>
<p>or using <code>list</code> (<code>[...]</code>) instead of <code>pd.Series()</code>:</p>
<pre><code>In [211]: dates.append(pd.DatetimeIndex([dates[-1] + pd.offsets.BusinessMonthEnd()]))
Out[211]: DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29', '2016-05-31'], dtype='datetime64[ns]', freq=None)
</code></pre>
| 1 |
2016-09-15T17:19:30Z
|
[
"python",
"pandas",
"datetimeindex"
] |
extend a pandas datetimeindex by 1 period
| 39,516,671 |
<p>consider the <code>DateTimeIndex</code> <code>dates</code></p>
<pre><code>dates = pd.date_range('2016-01-29', periods=4, freq='BM')
dates
DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29'],
dtype='datetime64[ns]', freq='BM')
</code></pre>
<p>I want to extend the index by one period at the frequency attached to the object.</p>
<hr>
<p>I expect</p>
<pre><code>pd.date_range('2016-01-29', periods=5, freq='BM')
DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29',
'2016-05-31'],
dtype='datetime64[ns]', freq='BM')
</code></pre>
<hr>
<p>I've tried</p>
<pre><code>dates.append(dates[[-1]] + pd.offsets.BusinessMonthEnd())
</code></pre>
<p>However</p>
<ul>
<li>Not generalized to use frequency of <code>dates</code></li>
<li>I get a performance warning
<blockquote>
<p>PerformanceWarning: Non-vectorized DateOffset being applied to Series or DatetimeIndex</p>
</blockquote></li>
</ul>
| 1 |
2016-09-15T17:05:16Z
| 39,517,022 |
<p>The timestamps in your <code>DatetimeIndex</code> already know that they are describing business month ends, so you can simply add 1:</p>
<pre><code>import pandas as pd
dates = pd.date_range('2016-01-29', periods=4, freq='BM')
print(repr(dates[-1]))
# => Timestamp('2016-04-29 00:00:00', offset='BM')
print(repr(dates[-1] + 1))
# => Timestamp('2016-05-31 00:00:00', offset='BM')
</code></pre>
<p>You can add the latter to your index using <code>.union</code>:</p>
<pre><code>dates = dates.union([dates[-1] + 1])
print(dates)
# => DatetimeIndex(['2016-01-29', '2016-02-29', '2016-03-31', '2016-04-29',
# '2016-05-31'],
# dtype='datetime64[ns]', freq='BM')
</code></pre>
<p>Compared to <code>.append</code>, this retains knowledge of the offset.</p>
| 4 |
2016-09-15T17:28:32Z
|
[
"python",
"pandas",
"datetimeindex"
] |
"OpenSSL: EC_KEY_generate_key FAIL ... error:00000000:lib(0):func(0):reason(0)" on pyelliptic.ECC()
| 39,516,710 |
<p>I'm getting the above error while using <code>pyelliptic</code> (versions given below).</p>
<p>The python code which triggers it: </p>
<pre><code>print("Salt: %s" % salt)
server_key = pyelliptic.ECC(curve="prime256v1") # ----->> Line2
print("Server_key: %s" % server_key) # ----->> Line3
server_key_id = base64.urlsafe_b64encode(server_key.get_pubkey()[1:])
</code></pre>
<p>The <code>"Salt: ..."</code> message is displayed okay, the error is in the <code>pyelliptic.ECC()</code> call.</p>
<p>Traceback:</p>
<pre><code>File "/usr/local/lib/python2.7/dist-packages/pyelliptic/ecc.py", line 89, in __init__
self.privkey, self.pubkey_x, self.pubkey_y = self._generate()
File "/usr/local/lib/python2.7/dist-packages/pyelliptic/ecc.py", line 231, in _generate
raise Exception("[OpenSSL] EC_KEY_generate_key FAIL ... " + OpenSSL.get_error())
</code></pre>
<p>The error(s) I get are (the 2nd one may or may not be relevant):</p>
<ol>
<li><code>Exception('[OpenSSL] EC_KEY_generate_key FAIL ... error:00000000:lib(0):func(0):reason(0)',)</code>
(Ref. File Link: <a href="https://github.com/yann2192/pyelliptic/blob/master/pyelliptic/ecc.py#L214" rel="nofollow" title="pyelliptic/ecc.py File">https://github.com/yann2192/pyelliptic/blob/master/pyelliptic/ecc.py#L214</a> )</li>
<li><code>extern "Python": function Cryptography_rand_bytes() called, but @ffi.def_extern() was not called in the current subinterpreter. Returning 0.</code></li>
</ol>
<p>Requirements.txt (partial):</p>
<pre><code>setuptools==27.1.2
cryptography==1.5
pyelliptic==1.5.7
pyOpenSSL==16.1.0
</code></pre>
<p><a href="https://github.com/yann2192/pyelliptic/issues/39" rel="nofollow">https://github.com/yann2192/pyelliptic/issues/39</a> says that <code>pyelliptic</code> <code>v1.5.7</code> has some issues with old versions (Not sure if this is applicable here).</p>
<p><strong>Other Details:</strong></p>
<p>Python Version: 2.7.</p>
<p>Getting this error only on Google Compute Engine VM Instance. </p>
<p>Working Fine on Local Development Server.
Working Fine from python shell too Google Compute Engine VM.</p>
<p><sub>(The question is a follow-up of <a href="http://stackoverflow.com/questions/39413987/entrypoint-object-has-no-attribute-resolve-when-using-google-compute-engine/39499600#39413987">'EntryPoint' object has no attribute 'resolve' when using Google Compute Engine</a>, the discussion there might be of use)</sub></p>
| 0 |
2016-09-15T17:08:07Z
| 39,614,611 |
<p>Just added the following:<code>WSGIApplicationGroup %{GLOBAL}</code></p>
<p>in <code>/etc/apache2/sites-available/default-ssl.conf</code> file and all these errors got resolved. </p>
| 0 |
2016-09-21T10:56:48Z
|
[
"python",
"django",
"google-compute-engine"
] |
Scrapping row of info underneath a table header when the html tags for the row are not nested under the header tag
| 39,516,833 |
<p>I'm trying to scrape a <a href="https://wd.kyepsb.net/EPSB.WebApps/KECI/view_data.aspx?id=37161" rel="nofollow">table</a> but I've run into a bit of a snag. I want to make sure that the data underneath each header (ex. <code>Cert Issued (30)</code>) is grouped with the corresponding header. </p>
<p>The problem arises when I'm trying to work with the html below.</p>
<pre><code><tr>
<td>
<table class="EPSBResultGrid" cellspacing="0" rules="cols" border="1" style="border-color:DarkGray;border-collapse:collapse;">
<tbody><tr class="EPSBResultGridHeader">
<th scope="col">Cred</th><th scope="col">Description</th><th scope="col">Effective</th><th scope="col">Expiration</th><th scope="col">Restricted To</th>
</tr><tr class="EPSBResultGridHeader">
<td colspan="9" style="border-width:1px;border-style:solid;font-weight:bold;">Do Not Print (00)</td>
</tr><tr class="EPSBResultGridItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_CRED_CODE">RANK1</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_CRED_DESC">Rank I</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EFF_DATE_txtDateYYYY">2000<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateYYYY" value="2000"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridHeader">
<td colspan="9" style="border-width:1px;border-style:solid;font-weight:bold;">Cert Issued (30)</td>
</tr><tr class="EPSBResultGridAlternatingItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_CRED_CODE">G20</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_CRED_DESC">Middle School Teaching Field: Social Studies</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EFF_DATE_txtDateYYYY">1995<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateYYYY" value="1995"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_CRED_CODE">G71</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_CRED_DESC">Middle School Teaching Field: Mathematics</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EFF_DATE_txtDateYYYY">1995<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateYYYY" value="1995"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridAlternatingItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_CRED_CODE">PCS</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_CRED_DESC">Provisional Certificate For Guidance Counselor, Secondary Grades 5-12</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EFF_DATE_txtDateMM">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateMM" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EFF_DATE_txtDateYYYY">2016<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateYYYY" value="2016"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_CRED_CODE">PMBF</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_CRED_DESC">Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EFF_DATE_txtDateYYYY">2015<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateYYYY" value="2015"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ORG_NAME"></span></td>
</tr>
</tbody></table><br><span><span>Note: Suspended and revoked credentials are shown with red text with a strike through line.</span></span>
</td>
</tr>
</code></pre>
<p>The the info (<code>class="EPSBResultGridItem"</code> & <code>class="EPSBResultGridAlternatingItem"</code>) below the headers (<code>class="EPSBResultHeader"</code>) are not nested underneath them and as a result I've been having trouble finding a way to make sure that the information under each header is grouped with the correct header. </p>
<p>This is my code:</p>
<pre><code>count = 0
header = tree.xpath(
'.//table/tr[@class="EPSBResultGridHeader"]')
difference = 10 - len(header)
for i in range(0, difference):
header.append('')
for license_row in header:
count = count + 1
try:
header_data = license_row.xpath(".//text()")
header_data = clean(header_data)
nested_data = license_row.xpath(".//following-sibling::tr//text()")
nested_data = clean(nested_data)
print count, header_data
print count, nested_data
except AttributeError:
header_data = ''
# Append licensure data
if count == 1:
lheader1.append(header_data)
lheader_info1(nested_data)
if count == 2:
lheader2.append(header_data)
lheader_info2(nested_data)
if count == 3:
lheader3.append(header_data)
lheader_info3(nested_data)
if count == 4:
lheader4.append(header_data)
lheader_info4(nested_data)
if count == 5:
lheader5.append(header_data)
lheader_info5(nested_data)
</code></pre>
<p>My end goal is to have an output like this:</p>
<pre><code>>>>print lheader_info2
['RANK1', 'Rank I', '07-01-2018', '06-30-2021']
>>>print lheader_info3
['G20', 'Middle School Teaching Field: Social Studies----', 'G30', 'Middle School Teaching Field: English And Communications----', 'ILE2', 'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II', '07-01-2017', '06-30-2021', 'ILM2', 'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II', '07-01-2017', '06-30-2021', 'ILV2', 'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II', '07-01-2018', '06-30-2021', 'PMBF', 'Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)', '07-01-2016', '06-30-2021']
</code></pre>
<p>I'm using <code>lxml</code> but I've also used <code>BeautifulSoup</code> if that seems like a better way to do it. </p>
| 2 |
2016-09-15T17:17:09Z
| 39,516,972 |
<p>I would locate every subheader and iterate over the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-next-siblings-and-find-next-sibling" rel="nofollow">next <code>tr</code> siblings</a> breaking the loop once another header is met, or reached the end of the table:</p>
<pre><code>from collections import defaultdict
from pprint import pprint
import requests
from bs4 import BeautifulSoup
url = "https://wd.kyepsb.net/EPSB.WebApps/KECI/view_data.aspx?id=37161"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
data = defaultdict(list)
table = soup.find("table", class_="EPSBResultGrid")
for header in table.select("tr.EPSBResultGridHeader")[1:]:
header_name = header.get_text(strip=True)
for row in header.find_next_siblings("tr"):
if "EPSBResultGridHeader" in row.get("class", []):
break
data[header_name].append(row.td.get_text(strip=True))
pprint(dict(data))
</code></pre>
<p>Prints:</p>
<pre><code>{'Cert Issued (30)': ['G20', 'G30', 'ILE2', 'ILM2', 'ILV2', 'PMBF'],
'Do Not Print (00)': ['RANK1'],
'History (97)': ['ILE2', 'ILM2', 'ILV2', 'RANK1']}
</code></pre>
<p>The <code>[1:]</code> slice here is to skip the initial top-level table header.</p>
| 2 |
2016-09-15T17:24:44Z
|
[
"python",
"python-2.7",
"beautifulsoup",
"lxml"
] |
Scrapping row of info underneath a table header when the html tags for the row are not nested under the header tag
| 39,516,833 |
<p>I'm trying to scrape a <a href="https://wd.kyepsb.net/EPSB.WebApps/KECI/view_data.aspx?id=37161" rel="nofollow">table</a> but I've run into a bit of a snag. I want to make sure that the data underneath each header (ex. <code>Cert Issued (30)</code>) is grouped with the corresponding header. </p>
<p>The problem arises when I'm trying to work with the html below.</p>
<pre><code><tr>
<td>
<table class="EPSBResultGrid" cellspacing="0" rules="cols" border="1" style="border-color:DarkGray;border-collapse:collapse;">
<tbody><tr class="EPSBResultGridHeader">
<th scope="col">Cred</th><th scope="col">Description</th><th scope="col">Effective</th><th scope="col">Expiration</th><th scope="col">Restricted To</th>
</tr><tr class="EPSBResultGridHeader">
<td colspan="9" style="border-width:1px;border-style:solid;font-weight:bold;">Do Not Print (00)</td>
</tr><tr class="EPSBResultGridItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_CRED_CODE">RANK1</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_CRED_DESC">Rank I</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EFF_DATE_txtDateYYYY">2000<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateYYYY" value="2000"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridHeader">
<td colspan="9" style="border-width:1px;border-style:solid;font-weight:bold;">Cert Issued (30)</td>
</tr><tr class="EPSBResultGridAlternatingItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_CRED_CODE">G20</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_CRED_DESC">Middle School Teaching Field: Social Studies</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EFF_DATE_txtDateYYYY">1995<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateYYYY" value="1995"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_CRED_CODE">G71</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_CRED_DESC">Middle School Teaching Field: Mathematics</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EFF_DATE_txtDateYYYY">1995<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateYYYY" value="1995"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridAlternatingItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_CRED_CODE">PCS</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_CRED_DESC">Provisional Certificate For Guidance Counselor, Secondary Grades 5-12</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EFF_DATE_txtDateMM">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateMM" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EFF_DATE_txtDateYYYY">2016<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateYYYY" value="2016"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_CRED_CODE">PMBF</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_CRED_DESC">Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EFF_DATE_txtDateYYYY">2015<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateYYYY" value="2015"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ORG_NAME"></span></td>
</tr>
</tbody></table><br><span><span>Note: Suspended and revoked credentials are shown with red text with a strike through line.</span></span>
</td>
</tr>
</code></pre>
<p>The the info (<code>class="EPSBResultGridItem"</code> & <code>class="EPSBResultGridAlternatingItem"</code>) below the headers (<code>class="EPSBResultHeader"</code>) are not nested underneath them and as a result I've been having trouble finding a way to make sure that the information under each header is grouped with the correct header. </p>
<p>This is my code:</p>
<pre><code>count = 0
header = tree.xpath(
'.//table/tr[@class="EPSBResultGridHeader"]')
difference = 10 - len(header)
for i in range(0, difference):
header.append('')
for license_row in header:
count = count + 1
try:
header_data = license_row.xpath(".//text()")
header_data = clean(header_data)
nested_data = license_row.xpath(".//following-sibling::tr//text()")
nested_data = clean(nested_data)
print count, header_data
print count, nested_data
except AttributeError:
header_data = ''
# Append licensure data
if count == 1:
lheader1.append(header_data)
lheader_info1(nested_data)
if count == 2:
lheader2.append(header_data)
lheader_info2(nested_data)
if count == 3:
lheader3.append(header_data)
lheader_info3(nested_data)
if count == 4:
lheader4.append(header_data)
lheader_info4(nested_data)
if count == 5:
lheader5.append(header_data)
lheader_info5(nested_data)
</code></pre>
<p>My end goal is to have an output like this:</p>
<pre><code>>>>print lheader_info2
['RANK1', 'Rank I', '07-01-2018', '06-30-2021']
>>>print lheader_info3
['G20', 'Middle School Teaching Field: Social Studies----', 'G30', 'Middle School Teaching Field: English And Communications----', 'ILE2', 'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II', '07-01-2017', '06-30-2021', 'ILM2', 'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II', '07-01-2017', '06-30-2021', 'ILV2', 'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II', '07-01-2018', '06-30-2021', 'PMBF', 'Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)', '07-01-2016', '06-30-2021']
</code></pre>
<p>I'm using <code>lxml</code> but I've also used <code>BeautifulSoup</code> if that seems like a better way to do it. </p>
| 2 |
2016-09-15T17:17:09Z
| 39,518,565 |
<p>using <em>lxml</em></p>
<pre><code>def pair():
tree = html.fromstring(requests.get(url).content)
# get table and iterate over the trs
iter_trs = tree.cssselect("table.EPSBResultGrid")[0].iter("tr")
# skip the initial tr
next(iter_trs)
# first EPSBResultGridHeader
start = next(iter_trs).xpath("td//text()")[0]
nodes, tmp = {}, []
# iterate over the rest of the nodes
for node in iter_trs:
# if we find another EPSBResultGridHeader, yield what we have and start again.
if node.get("class") == "EPSBResultGridHeader":
nodes[start] = tmp
start, tmp = node.xpath("td//text()")[0], []
else:
tmp.append([td.xpath("normalize-space(.)").replace(ur"\xa0", "") for td in node.xpath("./td")])
return nodes
</code></pre>
<p>Which would give you:</p>
<pre><code>{'Cert Issued (30)': [[u'G20',
u'Middle School Teaching Field: Social Studies',
u'--',
u'--',
u''],
[u'G30',
u'Middle School Teaching Field: English And Communications',
u'--',
u'--',
u''],
[u'ILE2',
u'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II',
u'07-01-2017',
u'06-30-2021',
u''],
[u'ILM2',
u'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II',
u'07-01-2017',
u'06-30-2021',
u''],
[u'ILV2',
u'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II',
u'07-01-2018',
u'06-30-2021',
u''],
[u'PMBF',
u'Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)',
u'07-01-2016',
u'06-30-2021',
u'']],
'Do Not Print (00)': [[u'RANK1',
u'Rank I',
u'07-01-2018',
u'06-30-2021',
u'']],
'History (97)': [[u'ILE2',
u'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II',
u'07-01-2012',
u'06-30-2017',
u''],
[u'ILM2',
u'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II',
u'07-01-2012',
u'06-30-2017',
u''],
[u'ILV2',
u'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II',
u'07-01-2013',
u'06-30-2018',
u''],
[u'RANK1', u'Rank I', u'12-15-1995', u'06-30-2018', u'']]}
</code></pre>
<p>If you want flat lists use extend <code>tmp.extend(td.xpath("normalize-space(.)").replace(u"\xa0", "") for td in node.xpath("./td")):</code></p>
<pre><code>{'Cert Issued (30)': [u'G20',
u'Middle School Teaching Field: Social Studies',
u'--',
u'--',
u'',
u'G30',
u'Middle School Teaching Field: English And Communications',
u'--',
u'--',
u'',
u'ILE2',
u'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II',
u'07-01-2017',
u'06-30-2021',
u'',
u'ILM2',
u'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II',
u'07-01-2017',
u'06-30-2021',
u'',
u'ILV2',
u'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II',
u'07-01-2018',
u'06-30-2021',
u'',
u'PMBF',
u'Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)',
u'07-01-2016',
u'06-30-2021',
u''],
'Do Not Print (00)': [u'RANK1', u'Rank I', u'07-01-2018', u'06-30-2021', u''],
'History (97)': [u'ILE2',
u'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II',
u'07-01-2012',
u'06-30-2017',
u'',
u'ILM2',
u'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II',
u'07-01-2012',
u'06-30-2017',
u'',
u'ILV2',
u'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II',
u'07-01-2013',
u'06-30-2018',
u'',
u'RANK1',
u'Rank I',
u'12-15-1995',
u'06-30-2018',
u'']}
</code></pre>
| 2 |
2016-09-15T19:04:55Z
|
[
"python",
"python-2.7",
"beautifulsoup",
"lxml"
] |
Return result from Python to Vba
| 39,516,875 |
<p>I'm using a VBA code that calls a python script. I can send a parameter to my python script and reading it using <code>sys.argv[1]</code>.</p>
<p>In the python code I have a function that takes the given argument and return a value.</p>
<p>Please how can I get the return value in VBA? </p>
| -1 |
2016-09-15T17:19:08Z
| 39,517,658 |
<p>Consider using VBA Shell's <code>StdOut</code> to capture a stream of the output lines. Be sure to have the Python script print to screen the value:</p>
<p><strong>Python</strong></p>
<pre><code>...
print(outputval)
</code></pre>
<p><strong>VBA</strong> <em>(<code>s</code> below would be string output)</em></p>
<pre class="lang-vb prettyprint-override"><code>Public Sub PythonOutput()
Dim oShell As Object, oCmd As String
Dim oExec As Object, oOutput As Object
Dim arg As Variant
Dim s As String, sLine As String
Set oShell = CreateObject("WScript.Shell")
arg = "somevalue"
oCmd = "python ""C:\Path\To\Python\Script.py""" & " " & arg
Set oExec = oShell.Exec(oCmd)
Set oOutput = oExec.StdOut
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbNewLine
Wend
Debug.Print s
Set oOutput = Nothing: Set oExec = Nothing
Set oShell = Nothing
End Sub
</code></pre>
<p><strong>Credit</strong></p>
<p>Script borrowed from <a href="http://stackoverflow.com/users/243392/bburns-km">@bburns.km</a>, non-accepted answer, from this <a href="http://stackoverflow.com/a/32600510/1422451">SO post</a></p>
| 0 |
2016-09-15T18:08:39Z
|
[
"python",
"vba"
] |
column width in QTableWidget and PyQt4
| 39,516,891 |
<p>I have a QTableWidget and I want to make sure that all the columns are stretched, i.e occupy all of the form. The solution that I found is provided <a href="http://stackoverflow.com/a/23215842/1636521">here</a> but it seems to be for <code>Qt5</code> and <code>C++</code>. I'm working with <code>PyQt4</code> and <code>Python</code>. Is there a way to do this in <code>PyQt4</code>?</p>
| 0 |
2016-09-15T17:20:04Z
| 39,524,213 |
<p>the function for PyQt that is similar to that and which also apply to QHeaderView is :</p>
<pre><code>setResizeMode (self, ResizeMode mode)
</code></pre>
<p>with possible values for resize mode </p>
<pre><code>enum ResizeMode { Interactive, Fixed, Stretch, ResizeToContents, Custom }
</code></pre>
<p>more information :</p>
<p><a href="http://pyqt.sourceforge.net/Docs/PyQt4/qheaderview.html" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt4/qheaderview.html</a></p>
| 0 |
2016-09-16T05:25:22Z
|
[
"python",
"python-2.7",
"qt",
"qt4",
"pyqt4"
] |
How can i easily handle numberseries formated with brackets?
| 39,516,950 |
<p>I have a long list of numberseries formated like this:</p>
<pre><code>["4450[0-9]", "6148[0-9][0-9]"]
</code></pre>
<p>I want to make a list from one of those series with single numbers:</p>
<pre><code>[44500,44501,..., 44509]
</code></pre>
<p>i need to do this for many series within the original list and i'm wondering what the best way is for doing that?</p>
| 1 |
2016-09-15T17:23:19Z
| 39,517,249 |
<pre><code>def invertRE(x):
if not x:
yield []
else:
idx = 1 if not x.startswith("[") else x.index("]") + 1
for rest in invertRE(x[idx:]):
if x.startswith("["):
v1,v2 = map(int,x[1:idx-1].split("-"))
for i in range(v1,v2+1):
yield [str(i),]+rest
else:
yield [x[0],] + rest
print(map("".join,invertRE("123[4-7][7-8]")))
</code></pre>
<p>Im pretty sure this will work ... but really you should try something on your own before comming here ...</p>
| 1 |
2016-09-15T17:43:18Z
|
[
"python",
"numbers",
"series",
"number-sequence"
] |
How can i easily handle numberseries formated with brackets?
| 39,516,950 |
<p>I have a long list of numberseries formated like this:</p>
<pre><code>["4450[0-9]", "6148[0-9][0-9]"]
</code></pre>
<p>I want to make a list from one of those series with single numbers:</p>
<pre><code>[44500,44501,..., 44509]
</code></pre>
<p>i need to do this for many series within the original list and i'm wondering what the best way is for doing that?</p>
| 1 |
2016-09-15T17:23:19Z
| 39,517,251 |
<p>Probably not the best solution, but you can approach it recursively looking for the <code>[x-y]</code> ranges and <a href="https://wiki.python.org/moin/Generators" rel="nofollow">generating</a> values (using <code>yield</code> and <a href="https://docs.python.org/3/whatsnew/3.3.html#pep-380" rel="nofollow"><code>yield from</code></a> in this case, hence for Python 3.3+):</p>
<pre><code>import re
pattern = re.compile(r"\[(\d+)-(\d+)\]")
def get_range(s):
matches = pattern.search(s)
if not matches:
yield int(s)
else:
start, end = matches.groups()
for i in range(int(start), int(end) + 1):
repl = pattern.sub(str(i), s, 1)
yield from get_range(repl)
for item in get_range("6148[0-9][0-9]"):
print(item)
</code></pre>
<p>Prints:</p>
<pre><code>614800
614801
...
614898
614899
</code></pre>
| 2 |
2016-09-15T17:43:28Z
|
[
"python",
"numbers",
"series",
"number-sequence"
] |
How can i easily handle numberseries formated with brackets?
| 39,516,950 |
<p>I have a long list of numberseries formated like this:</p>
<pre><code>["4450[0-9]", "6148[0-9][0-9]"]
</code></pre>
<p>I want to make a list from one of those series with single numbers:</p>
<pre><code>[44500,44501,..., 44509]
</code></pre>
<p>i need to do this for many series within the original list and i'm wondering what the best way is for doing that?</p>
| 1 |
2016-09-15T17:23:19Z
| 39,530,391 |
<p>Found this module which seems to do what i want.</p>
<p><a href="https://pypi.python.org/pypi/braceexpand/0.1.1" rel="nofollow">https://pypi.python.org/pypi/braceexpand/0.1.1</a></p>
<pre><code>>>> from braceexpand import braceexpand
>>> s = "1[0-2]"
>>> ss = "1[0-2][0-9]"
>>> list(braceexpand(s.replace("[", "{").replace("-","..").replace("]","}")))
['10', '11', '12']
>>> list(braceexpand(ss.replace("[", "{").replace("-","..").replace("]","}")))
['100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129']
</code></pre>
<p>alecxe's answer is still the "best" answer and not a shortcut tho</p>
| 0 |
2016-09-16T11:29:04Z
|
[
"python",
"numbers",
"series",
"number-sequence"
] |
No newline character at end of file even after writing it
| 39,516,995 |
<pre><code># Create strings for preparation of file writing
s = ";"
seq = (risd41Email, risd41Pass, rimsd41Email, rimsd41Pass);
textString = s.join(seq);
# Create file, write contents, move to usertxtfiles dir
with open(filename, "w") as text_file:
text_file.write(str(textString))
text_file.write('\n')
os.rename(fileMigPath, fileDestPath)
</code></pre>
<p>I have the above code that clearly writes a newline to the file I am editing. When I try to use the file another script does not execute the line because there is no newline character at the end of the file. If I copy the file and then open it in vi and then save it, vi adds a newline character and the line of the file executes properly. If I run diff between the file that wasn't saved in vi versus the one that was I get the message that the difference is no newline at end of file. I am using Python 2.7.12 on Ubuntu server Xenial. </p>
| 2 |
2016-09-15T17:26:23Z
| 39,517,344 |
<p>Try that:</p>
<pre><code> text_file.write('\n\n')
</code></pre>
<p>This should work!</p>
| 1 |
2016-09-15T17:49:31Z
|
[
"python"
] |
'expected string or buffer' when using re.match with pandas
| 39,517,013 |
<p>I am trying to clean some data from a csv file. I need to make sure that whatever is in the 'Duration' category matches a certain format. This is how I went about that:</p>
<pre><code>import re
import pandas as pd
data_path = './ufos.csv'
ufos = pd.read_csv(data_path)
valid_duration = re.compile('^[0-9]+ (seconds|minutes|hours|days)$')
ufos_clean = ufos[valid_duration.match(ufos.Duration)]
ufos_clean.head()
</code></pre>
<p>This gives me the following error:</p>
<pre><code>TypeErrorTraceback (most recent call last)
<ipython-input-4-5ebeaec39a83> in <module>()
6
7 valid_duration = re.compile('^[0-9]+ (seconds|minutes|hours|days)$')
----> 8 ufos_clean = ufos[valid_duration.match(ufos.Duration)]
9
10 ufos_clean.head()
TypeError: expected string or buffer
</code></pre>
<p>I used a similar method to clean data before without the regular expressions. What am I doing wrong?</p>
<p>Edit:</p>
<p>MaxU got me the closest, but what ended up working was:</p>
<pre><code>valid_duration_RE = '^[0-9]+ (seconds|minutes|hours|days)$'
ufos_clean = ufos
ufos_clean = ufos_clean[ufos.Duration.str.contains(valid_duration_RE)]
</code></pre>
<p>There's probably a lot of redundancy in there, I'm pretty new to python, but it worked.</p>
| 1 |
2016-09-15T17:27:41Z
| 39,517,176 |
<p>I guess you want it the other way round (not tested):</p>
<pre><code>import re
import pandas as pd
data_path = './ufos.csv'
ufos = pd.read_csv(data_path)
def cleanit(val):
# your regex solution here
pass
ufos['ufos_clean'] = ufos['Duration'].apply(cleanit)
</code></pre>
<p>After all, <code>ufos</code> is a <code>DataFrame</code>.</p>
| 0 |
2016-09-15T17:38:06Z
|
[
"python",
"regex",
"pandas",
"dataframe"
] |
'expected string or buffer' when using re.match with pandas
| 39,517,013 |
<p>I am trying to clean some data from a csv file. I need to make sure that whatever is in the 'Duration' category matches a certain format. This is how I went about that:</p>
<pre><code>import re
import pandas as pd
data_path = './ufos.csv'
ufos = pd.read_csv(data_path)
valid_duration = re.compile('^[0-9]+ (seconds|minutes|hours|days)$')
ufos_clean = ufos[valid_duration.match(ufos.Duration)]
ufos_clean.head()
</code></pre>
<p>This gives me the following error:</p>
<pre><code>TypeErrorTraceback (most recent call last)
<ipython-input-4-5ebeaec39a83> in <module>()
6
7 valid_duration = re.compile('^[0-9]+ (seconds|minutes|hours|days)$')
----> 8 ufos_clean = ufos[valid_duration.match(ufos.Duration)]
9
10 ufos_clean.head()
TypeError: expected string or buffer
</code></pre>
<p>I used a similar method to clean data before without the regular expressions. What am I doing wrong?</p>
<p>Edit:</p>
<p>MaxU got me the closest, but what ended up working was:</p>
<pre><code>valid_duration_RE = '^[0-9]+ (seconds|minutes|hours|days)$'
ufos_clean = ufos
ufos_clean = ufos_clean[ufos.Duration.str.contains(valid_duration_RE)]
</code></pre>
<p>There's probably a lot of redundancy in there, I'm pretty new to python, but it worked.</p>
| 1 |
2016-09-15T17:27:41Z
| 39,518,084 |
<p>You can use vectorized <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.match.html" rel="nofollow">.str.match()</a> method:</p>
<pre><code>valid_duration_RE = '^[0-9]+ (seconds|minutes|hours|days)$'
ufos_clean = ufos[ufos.Duration.str.contains(valid_duration_RE)]
</code></pre>
| 1 |
2016-09-15T18:33:09Z
|
[
"python",
"regex",
"pandas",
"dataframe"
] |
Finding closest value in a dictionary
| 39,517,040 |
<p>I have a dictionary, <code>T</code>, with keys in the form <code>k,i</code> with an associated value that is a real number (float). Let's suppose I choose a particular key <code>a,b</code> from the dictionary <code>T</code> with corresponding value <code>V1</code>âwhat's the most efficient way to find the closest value to <code>V1</code> for a key that has the form <code>a+1,i</code>, where <code>i</code> is an integer that ranges from 0 to n? (<code>k</code>,<code>a</code>, and <code>b</code> are also integers.) To add one condition on the values of items in <code>T</code>, as <code>i</code> increases in the key, the value associated to <code>T[a+1,i]</code> is strictly increasing (i.e. <code>T[a+1,i+1] > T[a+1,i]</code>).</p>
<p>I was planning to simply run a while loop that starts from <code>i = 0</code> and compares the value<code>T[a+1,i]</code> to <code>V1</code>. To be more clear, the loop would simply stop at the point at which <code>np.abs(T[a+1,i] - V1) < np.abs(T[a+1,i+1] - V1)</code>, as I would know the item associated to <code>T[a+1,i]</code> is the closest to <code>T[a,b] = V1</code>. But given the strictly increasing condition I have imposed, is there a more efficient method than running a while loop that iterates over the dictionary elements? <code>i</code> will go from 0 to n where n could be an integer in the millions. Also, this process would be repeated frequently so efficiency is key. </p>
| 1 |
2016-09-15T17:29:35Z
| 39,517,206 |
<p>Since the values for a given <code>a</code> are strictly increasing with successive <code>i</code> values, you can do a binary search for the value that is closest to your target.</p>
<p>While it's certainly possible to write your own binary search code on your dictionary, I suspect you'd have an easier time with a different data structure. If you used nested lists (with <code>a</code> as the index to the outer list, and <code>i</code> as the index to an inner list), you could use the <code>bisect</code> module to search the inner list efficiently.</p>
| 0 |
2016-09-15T17:40:03Z
|
[
"python",
"python-2.7",
"loops",
"dictionary",
"iteration"
] |
Finding closest value in a dictionary
| 39,517,040 |
<p>I have a dictionary, <code>T</code>, with keys in the form <code>k,i</code> with an associated value that is a real number (float). Let's suppose I choose a particular key <code>a,b</code> from the dictionary <code>T</code> with corresponding value <code>V1</code>âwhat's the most efficient way to find the closest value to <code>V1</code> for a key that has the form <code>a+1,i</code>, where <code>i</code> is an integer that ranges from 0 to n? (<code>k</code>,<code>a</code>, and <code>b</code> are also integers.) To add one condition on the values of items in <code>T</code>, as <code>i</code> increases in the key, the value associated to <code>T[a+1,i]</code> is strictly increasing (i.e. <code>T[a+1,i+1] > T[a+1,i]</code>).</p>
<p>I was planning to simply run a while loop that starts from <code>i = 0</code> and compares the value<code>T[a+1,i]</code> to <code>V1</code>. To be more clear, the loop would simply stop at the point at which <code>np.abs(T[a+1,i] - V1) < np.abs(T[a+1,i+1] - V1)</code>, as I would know the item associated to <code>T[a+1,i]</code> is the closest to <code>T[a,b] = V1</code>. But given the strictly increasing condition I have imposed, is there a more efficient method than running a while loop that iterates over the dictionary elements? <code>i</code> will go from 0 to n where n could be an integer in the millions. Also, this process would be repeated frequently so efficiency is key. </p>
| 1 |
2016-09-15T17:29:35Z
| 39,517,400 |
<pre><code>import numpy as np
target_value = 0.9
dict = {(1, 2): 0, (4, 3): 1}
k = list(dict.keys())
v = np.array(list(dict.values()))
dist = abs(v - target_value)
arg = np.argmin(dist)
answer = k[arg]
print(answer)
</code></pre>
| 0 |
2016-09-15T17:52:47Z
|
[
"python",
"python-2.7",
"loops",
"dictionary",
"iteration"
] |
Finding closest value in a dictionary
| 39,517,040 |
<p>I have a dictionary, <code>T</code>, with keys in the form <code>k,i</code> with an associated value that is a real number (float). Let's suppose I choose a particular key <code>a,b</code> from the dictionary <code>T</code> with corresponding value <code>V1</code>âwhat's the most efficient way to find the closest value to <code>V1</code> for a key that has the form <code>a+1,i</code>, where <code>i</code> is an integer that ranges from 0 to n? (<code>k</code>,<code>a</code>, and <code>b</code> are also integers.) To add one condition on the values of items in <code>T</code>, as <code>i</code> increases in the key, the value associated to <code>T[a+1,i]</code> is strictly increasing (i.e. <code>T[a+1,i+1] > T[a+1,i]</code>).</p>
<p>I was planning to simply run a while loop that starts from <code>i = 0</code> and compares the value<code>T[a+1,i]</code> to <code>V1</code>. To be more clear, the loop would simply stop at the point at which <code>np.abs(T[a+1,i] - V1) < np.abs(T[a+1,i+1] - V1)</code>, as I would know the item associated to <code>T[a+1,i]</code> is the closest to <code>T[a,b] = V1</code>. But given the strictly increasing condition I have imposed, is there a more efficient method than running a while loop that iterates over the dictionary elements? <code>i</code> will go from 0 to n where n could be an integer in the millions. Also, this process would be repeated frequently so efficiency is key. </p>
| 1 |
2016-09-15T17:29:35Z
| 39,519,502 |
<p>I propose to use bisect module.</p>
<pre><code>import bisect
import numpy as np
t = np.array([[1.1, 2.0, 3.7],
[3.5, 5.6, 7.8],
[2.5, 3.4, 10.0]])
def find_closest(t, a, i):
"""
>>> find_closest(t, 0, 2)
(1, 0)
"""
v = t[a, i]
b_index = bisect.bisect_right(t[a + 1], v)
try:
if t[a + 1][b_index] - v > t[a + 1][b_index - 1] - v:
b_index -= 1
except IndexError:
pass
return a + 1, b_index
</code></pre>
| 0 |
2016-09-15T20:06:51Z
|
[
"python",
"python-2.7",
"loops",
"dictionary",
"iteration"
] |
Is it possible to use references in JSON?
| 39,517,184 |
<p>I have this JSON:</p>
<pre><code>{
"app_name": "my_app",
"version": {
"1.0": {
"path": "/my_app/1.0"
},
"2.0": {
"path": "/my_app/2.0"
}
}
}
</code></pre>
<p>Is it somehow possible to reference the keywords <code>app_name</code> and the key of <code>version</code> so that I don't have to repeat "my_app" and the version numbering?</p>
<p>I was thinking something along the lines of... (code totally made up):</p>
<pre><code>{
"@app_name": "my_app",
"version": {
"1.0": {
"path": "/{{$app_name}}/{{key[-1]]}}"
},
"2.0": {
"path": "/{{$app_name}}/{{key[-1]}}"
}
}
}
</code></pre>
<p>Or is this something that could instead be handled better using YAML?</p>
<p>In the end, I intend to read this data into a Python dictionary.</p>
| 0 |
2016-09-15T17:38:46Z
| 39,517,222 |
<p>No, JSON does not have references. (The functionality you request here, with substring expansion, would open itself to memory attacks against the parser; by not supporting this functionality, JSON avoids vulnerability to such attacks).</p>
<p>If you want such functionality, you need to implement it yourself.</p>
| 1 |
2016-09-15T17:41:22Z
|
[
"python",
"json",
"yaml"
] |
Is it possible to use references in JSON?
| 39,517,184 |
<p>I have this JSON:</p>
<pre><code>{
"app_name": "my_app",
"version": {
"1.0": {
"path": "/my_app/1.0"
},
"2.0": {
"path": "/my_app/2.0"
}
}
}
</code></pre>
<p>Is it somehow possible to reference the keywords <code>app_name</code> and the key of <code>version</code> so that I don't have to repeat "my_app" and the version numbering?</p>
<p>I was thinking something along the lines of... (code totally made up):</p>
<pre><code>{
"@app_name": "my_app",
"version": {
"1.0": {
"path": "/{{$app_name}}/{{key[-1]]}}"
},
"2.0": {
"path": "/{{$app_name}}/{{key[-1]}}"
}
}
}
</code></pre>
<p>Or is this something that could instead be handled better using YAML?</p>
<p>In the end, I intend to read this data into a Python dictionary.</p>
| 0 |
2016-09-15T17:38:46Z
| 39,517,226 |
<p>Not in pure JSON, but you could performs string substitution after you parse the JSON.</p>
| 0 |
2016-09-15T17:41:55Z
|
[
"python",
"json",
"yaml"
] |
How can I use references in YAML?
| 39,517,356 |
<p>I have this YAML:</p>
<pre><code>app_name: my_app
version:
1.0:
path: /my_app/1.0
2.0:
path: /my_app/2.0
</code></pre>
<p>Is it possible to somehow avoid typing out "my_app" and its version and instead read that from the YAML itself by using some sort of referencing?</p>
<p>I had something like this in mind:</p>
<pre><code>app_name: my_app
version:
1.0:
path: /@app_name/$key[-1]
2.0:
path: /@app_name/$key[-1]
</code></pre>
<p>In the end, I intend to read this into a Python dictionary.</p>
| 0 |
2016-09-15T17:50:13Z
| 39,517,579 |
<p>There is no mechanism in YAML that does substitution on substrings of scalars, the best you have are anchors and aliases, and they refer to whole scalars or collections (mappings, sequences).</p>
<p>If you want to do such thing you will have to do the substitution after parsing in the YAML, interpreting the various values and rebuilding the data structure. </p>
<p>There are several examples (including here on [so]) of substitution where some part of the YAML is used as dictionary to replace other parts. When you do that you can parse the YAML input once, substitute on the source, and reparse the output of that substitution.
Because you use relative references, that will not work for you and you would need to do the substitution in the parsed tree.
The alternative is modifying the parser to strip the <code>@</code> from inputs and do this on the fly.</p>
<p>In both cases it would be a bad idea to use the same token (<code>@</code>) for marking a key to "store" its value (<code>@app_name</code>), as well as marking a key to store the key itself (<code>@1.0</code>), and for using the associated value (which you do in two completely different ways <code>@app_name</code> and <code>@key[-1]</code>).</p>
| 1 |
2016-09-15T18:04:14Z
|
[
"python",
"yaml"
] |
Writing a program that finds perfect numbers - error
| 39,517,496 |
<p>I'm working on a program that finds perfect numbers (i.e., 6, because its factors, 1, 2, and 3, add up to itself). My code is</p>
<pre><code>k=2
mprim = []
mprimk = []
pnum = []
def isprime(n):
"""Returns True if n is prime."""
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True
def mprime(k):
while k < 50:
check = (2**k)-1
if isprime(check) == True:
mprim.append(check)
mprimk.append(k)
print check
k+=1
else:
k+=1
mprime(k)
def isperf(lst):
for i in lst:
prm = (((2**i)-1)(2**i))/(2)
pnum.append(prm)
isperf(mprimk)
print pnum
</code></pre>
<p>The first part, that checks if a number is prime, and produces <em>mercenne primes</em>, is working alright. Its the second part I'm having trouble with. I have read that if <code>2^k - 1</code> is prime, then <code>((2^k - 1)(2^k))/2</code> is a <em>perfect number</em>, so I am using that formula. </p>
<p>The error it gives is </p>
<pre><code>Traceback (most recent call last):
File "python", line 47, in <module>
File "python", line 44, in isperf
TypeError: 'int' object is not callable
</code></pre>
<p>Line 47 is <code>isperf(mprimk)</code> and line 44 is <code>prm = (((2**i)-1)(2**i))/(2)</code>. Any assistance would be appreciated. </p>
<p>Thanks!</p>
| 0 |
2016-09-15T17:58:36Z
| 39,520,221 |
<p>The error clearly states that you are trying to call an int type, which isn't callable. </p>
<p>In practice it means you trying to do something like <code>123()</code></p>
<p>And code responsible for it is <code>((2**i)-1)(2**i)</code> because you forgot <code>*</code> and it should be <code>(((2**i)-1)*(2**i))/(2)</code></p>
| 1 |
2016-09-15T20:56:19Z
|
[
"python",
"math",
"compiler-errors",
"listiterator"
] |
Download file from Blob URL with Python
| 39,517,522 |
<p>I wish to have my Python script download the <em>Master data (Download, XLSX)</em> Excel file from this <a href="http://www.xetra.com/xetra-en/instruments/etf-exchange-traded-funds/list-of-tradable-etfs" rel="nofollow">Frankfurt stock exchange webpage</a>.</p>
<p>When to retrieve it with <code>urrlib</code> and <code>wget</code>, it turns out that the URL leads to a <em>Blob</em> and the file downloaded is only 289 bytes and unreadable.</p>
<blockquote>
<p><a href="http://www.xetra.com/blob/1193366/b2f210876702b8e08e40b8ecb769a02e/data/All-tradable-ETFs-ETCs-and-ETNs.xlsx" rel="nofollow">http://www.xetra.com/blob/1193366/b2f210876702b8e08e40b8ecb769a02e/data/All-tradable-ETFs-ETCs-and-ETNs.xlsx</a></p>
</blockquote>
<p>I'm entirely unfamiliar with Blobs and have these questions:</p>
<ul>
<li><p>Can the file "behind the Blob" be successfully retrieved using Python?</p></li>
<li><p>If so, is it necessary to uncover the "true" URL behind the Blob â if there is such a thing â and how? My concern here is that the link above won't be static but actually change often.</p></li>
</ul>
| 0 |
2016-09-15T18:00:21Z
| 39,517,774 |
<p>That 289 byte long thing might be a HTML code for <code>403 forbidden</code> page. This happen because the server is smart and rejects if your code does not specify a user agent.</p>
<h1>Python 3</h1>
<pre><code># python3
import urllib.request as request
url = 'http://www.xetra.com/blob/1193366/b2f210876702b8e08e40b8ecb769a02e/data/All-tradable-ETFs-ETCs-and-ETNs.xlsx'
# fake user agent of Safari
fake_useragent = 'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25'
r = request.Request(url, headers={'User-Agent': fake_useragent})
f = request.urlopen(r)
# print or write
print(f.read())
</code></pre>
<h1>Python 2</h1>
<pre><code># python2
import urllib2
url = 'http://www.xetra.com/blob/1193366/b2f210876702b8e08e40b8ecb769a02e/data/All-tradable-ETFs-ETCs-and-ETNs.xlsx'
# fake user agent of safari
fake_useragent = 'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25'
r = urllib2.Request(url, headers={'User-Agent': fake_useragent})
f = urllib2.urlopen(r)
print(f.read())
</code></pre>
| 1 |
2016-09-15T18:15:12Z
|
[
"python",
"download",
"blob",
"urllib"
] |
Download file from Blob URL with Python
| 39,517,522 |
<p>I wish to have my Python script download the <em>Master data (Download, XLSX)</em> Excel file from this <a href="http://www.xetra.com/xetra-en/instruments/etf-exchange-traded-funds/list-of-tradable-etfs" rel="nofollow">Frankfurt stock exchange webpage</a>.</p>
<p>When to retrieve it with <code>urrlib</code> and <code>wget</code>, it turns out that the URL leads to a <em>Blob</em> and the file downloaded is only 289 bytes and unreadable.</p>
<blockquote>
<p><a href="http://www.xetra.com/blob/1193366/b2f210876702b8e08e40b8ecb769a02e/data/All-tradable-ETFs-ETCs-and-ETNs.xlsx" rel="nofollow">http://www.xetra.com/blob/1193366/b2f210876702b8e08e40b8ecb769a02e/data/All-tradable-ETFs-ETCs-and-ETNs.xlsx</a></p>
</blockquote>
<p>I'm entirely unfamiliar with Blobs and have these questions:</p>
<ul>
<li><p>Can the file "behind the Blob" be successfully retrieved using Python?</p></li>
<li><p>If so, is it necessary to uncover the "true" URL behind the Blob â if there is such a thing â and how? My concern here is that the link above won't be static but actually change often.</p></li>
</ul>
| 0 |
2016-09-15T18:00:21Z
| 39,518,081 |
<pre><code>from bs4 import BeautifulSoup
import requests
import re
url='http://www.xetra.com/xetra-en/instruments/etf-exchange-traded-funds/list-of-tradable-etfs'
html=requests.get(url)
page=BeautifulSoup(html.content)
reg=re.compile('Master data')
find=page.find('span',text=reg) #find the file url
file_url='http://www.xetra.com'+find.parent['href']
file=requests.get(file_url)
with open(r'C:\\Users\user\Downloads\file.xlsx','wb') as ff:
ff.write(file.content)
</code></pre>
<p>recommend requests and BeautifulSoup,both good lib</p>
| 1 |
2016-09-15T18:33:01Z
|
[
"python",
"download",
"blob",
"urllib"
] |
Spark coalesce vs collect, which one is faster?
| 39,517,541 |
<p>I am using <code>pyspark</code> to process 50Gb data using AWS EMR with ~15 m4.large cores. </p>
<p>Each row of the data contains some information at a specific time on a day. I am using the following <code>for</code> loop to extract and aggregate information for every hour. Finally I <code>union</code> the data, as I want my result to save in <strong>one</strong> csv file.</p>
<pre><code># daily_df is a empty pyspark DataFrame
for hour in range(24):
hourly_df = df.filter(hourFilter("Time")).groupby("Animal").agg(mean("weights"), sum("is_male"))
daily_df = daily_df.union(hourly_df)
</code></pre>
<p>As of my knowledge, I have to perform the following to force the <code>pyspark.sql.Dataframe</code> object to save to 1 csv files (approx 1Mb) instead of 100+ files:</p>
<pre><code>daily_df.coalesce(1).write.csv("some_local.csv")
</code></pre>
<p>It seems it took about 70min to finish this progress, and I am wondering if I can make it faster by using <code>collect()</code> method like?</p>
<pre><code>daily_df_pandas = daily_df.collect()
daily_df_pandas.to_csv("some_local.csv")
</code></pre>
| 2 |
2016-09-15T18:01:34Z
| 39,517,877 |
<p>Both <code>coalesce(1)</code> and <code>collect</code> are pretty bad in general but with expected output size around 1MB it doesn't really matter. It simply shouldn't be a bottleneck here.</p>
<p>One simple improvement is to drop <code>loop</code> -> <code>filter</code> -> <code>union</code> and perform a single aggregation:</p>
<pre><code>df.groupby(hour("Time"), col("Animal")).agg(mean("weights"), sum("is_male"))
</code></pre>
<p>If that's not enough then most likely the issue here is configuration (the good place to start could be adjusting <code>spark.sql.shuffle.partitions</code> if you don't do that already).</p>
| 1 |
2016-09-15T18:21:27Z
|
[
"python",
"apache-spark",
"pyspark"
] |
Spark coalesce vs collect, which one is faster?
| 39,517,541 |
<p>I am using <code>pyspark</code> to process 50Gb data using AWS EMR with ~15 m4.large cores. </p>
<p>Each row of the data contains some information at a specific time on a day. I am using the following <code>for</code> loop to extract and aggregate information for every hour. Finally I <code>union</code> the data, as I want my result to save in <strong>one</strong> csv file.</p>
<pre><code># daily_df is a empty pyspark DataFrame
for hour in range(24):
hourly_df = df.filter(hourFilter("Time")).groupby("Animal").agg(mean("weights"), sum("is_male"))
daily_df = daily_df.union(hourly_df)
</code></pre>
<p>As of my knowledge, I have to perform the following to force the <code>pyspark.sql.Dataframe</code> object to save to 1 csv files (approx 1Mb) instead of 100+ files:</p>
<pre><code>daily_df.coalesce(1).write.csv("some_local.csv")
</code></pre>
<p>It seems it took about 70min to finish this progress, and I am wondering if I can make it faster by using <code>collect()</code> method like?</p>
<pre><code>daily_df_pandas = daily_df.collect()
daily_df_pandas.to_csv("some_local.csv")
</code></pre>
| 2 |
2016-09-15T18:01:34Z
| 39,518,016 |
<p>To save as single file these are options</p>
<p>Option 1 :
<code>coalesce</code>(1) (no shuffle data over network) or <code>repartition</code>(1) or <code>collect</code> may work for small data-sets, but large data-sets it may not perform, as expected.since all data will be moved to one partition on one node </p>
<p>option 1 would be fine if a single executor has more RAM for use than the driver.</p>
<p>Option 2 :
Other option would be <code>FileUtil.copyMerge()</code> - to merge the outputs into a single file. </p>
<p>Option 3 :
after getting part files you can use hdfs <code>getMerge</code> command </p>
<p>Now you have to decide based on your requirements... which one is safer/faster</p>
<p>also, can have look at <a href="http://stackoverflow.com/questions/36723908/dataframe-save-after-join-is-creating-numerous-part-files">Dataframe save after join is creating numerous part files</a></p>
| 1 |
2016-09-15T18:29:13Z
|
[
"python",
"apache-spark",
"pyspark"
] |
Adding Grouped Dataframes
| 39,517,555 |
<p>I have two dataframes. I like the to add add the values in the columns together if the grouping is the same. Doing this with a simple addition works great as long as both group values are in each table. If they are not, it returns <code>nan</code>. I am assuming because you can't add <code>nan</code> and an <code>int</code>, but not sure how to work around this.</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data=[['A', 4],
['A', 1],
['B', 1],
['B', 5]],
columns=['Person', 'Days'])
df1 = pd.DataFrame(data=[['A', 5],
['A', 0],
['C', 3],
['C', 5]],
columns=['Person', 'Days'])
df['Days'] = df['Days'] <= 3
df1['Days'] = df1['Days'] <= 3
df = df.groupby('Person').agg(['count'])
df1 = df1.groupby('Person').agg(['count'])
print df + df1
</code></pre>
<p>Actual Output:</p>
<pre><code> Days
count
Person
A 4
B NaN
C NaN
</code></pre>
<p>Desired Output:</p>
<pre><code> Days
count
Person
A 4
B 2
C 2
</code></pre>
| 2 |
2016-09-15T18:02:22Z
| 39,517,619 |
<p><strong>UPDATE:</strong></p>
<pre><code>In [40]: funcs = ['count','sum']
In [41]: df.groupby('Person').agg(funcs).add(df1.groupby('Person').agg(funcs), fill_value=0)
Out[41]:
Days
count sum
Person
A 4.0 2
B 2.0 1
C 2.0 1
</code></pre>
<p><strong>Old answer:</strong></p>
<pre><code>In [14]: df.groupby('Person').size().to_frame('count').add(
....: df1.groupby('Person').size().to_frame('count'), fill_value=0)
Out[14]:
count
Person
A 4.0
B 2.0
C 2.0
</code></pre>
<p>PS I worked with original DFs - i didn't execute this code :</p>
<pre><code>df = df.groupby('Person').agg(['count'])
df1 = df1.groupby('Person').agg(['count'])
</code></pre>
| 2 |
2016-09-15T18:06:37Z
|
[
"python",
"python-2.7",
"pandas"
] |
conversion of np.array(dtype='str') in an np.array(dtype='datetime')
| 39,517,660 |
<p>I have a very simple python question. I need to transform the string values within an np.array into datetime values. The string values contain the following format: ('%Y%m%d'). Does any one know how to this?
Here my test data:</p>
<pre><code>date_str = np.array([['20121002', '20121002', '20121002'],
['20121003', '20121003', '20121003'],
['20121004', '20121004', '20121004']])
</code></pre>
<p>I try to convert this array with the pandas library.
Here is my code:</p>
<pre><code>import pandas as pd
pd.to_datetime(date_str, format="%d%m%Y")
</code></pre>
<p>Please help me there should be a very simple way to convert this and note that I'm a python beginner.</p>
| -1 |
2016-09-15T18:08:45Z
| 39,517,742 |
<p>You can create a DataFrame, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> to it <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>pd.to_datetime</code></a>:</p>
<pre><code>In [68]: pd.DataFrame(date_str).apply(pd.to_datetime)
Out[68]:
0 1 2
0 2012-10-02 2012-10-02 2012-10-02
1 2012-10-03 2012-10-03 2012-10-03
2 2012-10-04 2012-10-04 2012-10-04
</code></pre>
<p>In order to verify the type of the result, here's the type of the first column, for example:</p>
<pre><code>In [73]: pd.DataFrame(date_str).apply(pd.to_datetime).iloc[:, 0].dtype
Out[73]: dtype('<M8[ns]')
</code></pre>
| 0 |
2016-09-15T18:13:49Z
|
[
"python",
"datetime",
"pandas",
"numpy"
] |
conversion of np.array(dtype='str') in an np.array(dtype='datetime')
| 39,517,660 |
<p>I have a very simple python question. I need to transform the string values within an np.array into datetime values. The string values contain the following format: ('%Y%m%d'). Does any one know how to this?
Here my test data:</p>
<pre><code>date_str = np.array([['20121002', '20121002', '20121002'],
['20121003', '20121003', '20121003'],
['20121004', '20121004', '20121004']])
</code></pre>
<p>I try to convert this array with the pandas library.
Here is my code:</p>
<pre><code>import pandas as pd
pd.to_datetime(date_str, format="%d%m%Y")
</code></pre>
<p>Please help me there should be a very simple way to convert this and note that I'm a python beginner.</p>
| -1 |
2016-09-15T18:08:45Z
| 39,517,795 |
<p>Convert each element of the array to a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="nofollow">pandas series</a>, and perform the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">to_datetime()</a> operation.</p>
<pre><code>In [81]: [pd.to_datetime(pd.Series(x), format="%Y%m%d") for x in date_str]
Out[81]:
[0 2012-10-02
1 2012-10-02
2 2012-10-02
dtype: datetime64[ns], 0 2012-10-03
1 2012-10-03
2 2012-10-03
dtype: datetime64[ns], 0 2012-10-04
1 2012-10-04
2 2012-10-04
dtype: datetime64[ns]]
</code></pre>
| 0 |
2016-09-15T18:16:32Z
|
[
"python",
"datetime",
"pandas",
"numpy"
] |
Setting the SendAs via python gmail api returns "Custom display name disallowed"
| 39,517,707 |
<p>I can't find any results when searching Google for this response. </p>
<p>I'm using the current Google Python API Client to make requests against the Gmail API. I can successfully insert a label, I can successfully retrieve a user's SendAs settings, but I cannot update, patch, or create a SendAS without receiving this error.</p>
<p>Here's a brief snippit of my code:
<code>
sendAsResource = {"sendAsEmail": "existingalias@test.com",
"isDefault": True,
"replyToAddress": "existingalias@test.com",
"displayName": "Test Sendas",
"isPrimary": False,
"treatAsAlias": False
}
self.service.users().settings().sendAs().create(userId = "me", body=sendAsResource).execute()
</code></p>
<p>The response I get is:</p>
<p><code><HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/settings/sendAs?alt=json returned "Custom display name disallowed"></code></p>
<p>I've tried <code>userId="me"</code> as well as the user i'm authenticated with, both result in this error. I am using a service account with domain wide delegation. Since adding a label works fine, I'm confused why this doesn't.</p>
<p>All pip modules are up to date as of this morning (google-api-python-client==1.5.3)</p>
<p>Edit: After hours of testing I decided to try on another user and this worked fine. There is something unique about my initial test account.</p>
| 0 |
2016-09-15T18:11:41Z
| 39,777,352 |
<p>This was a bug in the Gmail API. It is fixed now.</p>
| 0 |
2016-09-29T18:18:39Z
|
[
"python",
"gmail-api",
"google-api-python-client"
] |
slow script trying to find unique values in list
| 39,517,737 |
<p>I've got a problem in Python:
I want to find how many UNIQUE <code>a**b</code> values exist if:<br>
<code>2 ⤠a ⤠100</code>and <code>2 ⤠b ⤠100</code>?</p>
<p>I wrote the following script, but it's too slow on my laptop (and doesnt even produce the results):</p>
<pre><code>List=[]
a = 2
b = 2
c = pow(a, b)
while b != 101:
while a != 101:
if List.count(c) == 0:
List.append(c)
a += 1
b += 1
print len(List)
</code></pre>
<p>Is it good? Why is it slow?</p>
| 1 |
2016-09-15T18:13:36Z
| 39,517,964 |
<p>The reason your script is slow and doesn't return a value is that you have created an infinite loop. You need to dedent the <code>a += 1</code> line by one level, otherwise, after the first time through the inner <code>while</code> loop <code>a</code> will not get incremented again.</p>
<p>There are some additional issues with the script that have been pointed out in the comments, but this is what is responsible for the issues your are experiencing.</p>
| 0 |
2016-09-15T18:26:12Z
|
[
"python"
] |
slow script trying to find unique values in list
| 39,517,737 |
<p>I've got a problem in Python:
I want to find how many UNIQUE <code>a**b</code> values exist if:<br>
<code>2 ⤠a ⤠100</code>and <code>2 ⤠b ⤠100</code>?</p>
<p>I wrote the following script, but it's too slow on my laptop (and doesnt even produce the results):</p>
<pre><code>List=[]
a = 2
b = 2
c = pow(a, b)
while b != 101:
while a != 101:
if List.count(c) == 0:
List.append(c)
a += 1
b += 1
print len(List)
</code></pre>
<p>Is it good? Why is it slow?</p>
| 1 |
2016-09-15T18:13:36Z
| 39,517,989 |
<p>This code doesn't work; it's an infinite loop because of the way you don't increment <code>a</code> on every iteration of the loop. After you fix that, you still won't get the right answer because you never reset <code>a</code> to 2 when <code>b</code> reaches <code>101</code>. </p>
<p>Then, <code>List</code> will ever contain only <code>4</code> because you set <code>c</code> outside the loop to <code>2 ** 2</code> and never change it inside the loop. And when you fix <em>that</em> it'll still be slower than it really needs to be because you are reading the entire list each time through to get the count, and as it gets longer, that takes more and more time. </p>
<p>You generally should use <code>in</code> rather than <code>count</code> if you just need to know if an item is in a list, since it will stop as soon as it finds the the item, but in this specific instance you should be using a <code>set</code> anyway, since you are looking for unique values. You can just <code>add</code> to the set without checking to see whether the item is already in it.</p>
<p>Finally, using <code>for</code> loops is more readable than using <code>while</code> loops.</p>
<pre><code>result = set()
for a in xrange(2, 101):
for b in xrange(2, 101):
result.add(a ** b)
print len(result)
</code></pre>
<p>This takes less than a second on my machine.</p>
| 3 |
2016-09-15T18:27:57Z
|
[
"python"
] |
slow script trying to find unique values in list
| 39,517,737 |
<p>I've got a problem in Python:
I want to find how many UNIQUE <code>a**b</code> values exist if:<br>
<code>2 ⤠a ⤠100</code>and <code>2 ⤠b ⤠100</code>?</p>
<p>I wrote the following script, but it's too slow on my laptop (and doesnt even produce the results):</p>
<pre><code>List=[]
a = 2
b = 2
c = pow(a, b)
while b != 101:
while a != 101:
if List.count(c) == 0:
List.append(c)
a += 1
b += 1
print len(List)
</code></pre>
<p>Is it good? Why is it slow?</p>
| 1 |
2016-09-15T18:13:36Z
| 39,518,018 |
<p>Your code is not good, since it does not produce correct results. As the comment by @grael pointed out, you do not recalculate the value of <code>c</code> inside the loop, so you are counting only one value over and over again. There are also other problems, as other people have noted.</p>
<p>Your code is not fast for several reasons.</p>
<ol>
<li><p>You are using a brute-force method. The answer can be found more simply by using number theory and combinatorics. Look at the prime factorization of each number between 2 and 100 and consider the prime factorization of each power of that number. You never need to calculate the complete number--the prime factorization is enough. I'll leave the details to you but this would be much faster.</p></li>
<li><p>You are rolling your own loop, but it is faster to use python's. Loop <code>a</code> and <code>b</code> with:</p>
<pre><code>for a in range(2,101):
for b in range(2,101):
c = pow(a, b)
# other code here
</code></pre></li>
</ol>
<p>This code uses the built-in capabilities of the language and should be faster. This also avoids your errors since it is simpler.</p>
<ol start="3">
<li>You use a <em>very</em> slow method to see if a number has already been calculated. Your <code>if List.count(c) == 0</code> must check every previous number to see if the current number has been seen. This will become very slow when you have already seen thousands of numbers. It is much faster to keep the already-seen numbers in a set rather than a list. Checking if a number is in a set is <em>much faster</em> than using <code>count()</code> on a list.</li>
</ol>
<p>Try combining all these suggestions. As another answer shows, just using the last two probably suffice.</p>
| 0 |
2016-09-15T18:29:14Z
|
[
"python"
] |
Why is exit() or exec needed after telnetlib read_all()
| 39,517,861 |
<p>A lot of resources, including the example in the official documentation at <a href="https://docs.python.org/2/library/telnetlib.html" rel="nofollow">telnetlib</a> suggest that at the end before you do a read_all(), you need to write exit after the command as: </p>
<pre><code>tn.write("ls\n")
tn.write("exit\n")
</code></pre>
<p>Can someone please help me understand why is this needed ?</p>
<p>If I try doing it without the exit, the telnet connection hangs (or at least looks like it is hung) as the output of the command executed does not show on the terminal. </p>
<p>Also, another way of making it work, as I found in some resources was to use 'exec' to fire up the command and then you don't need the exit thing anymore. </p>
<p>Please help me understand this as well. </p>
| 0 |
2016-09-15T18:20:34Z
| 39,518,037 |
<p>read_all() reads all the output until EOF. In other words, it waits until remote server closes connection and returns you all the data it has sent. If you have not previously notified the server with an "exit" command that you have no more commands for it, it will wait for them. And a deadlock occurs: you are holding open connection because you are waiting for server to tell you that it has sent everything it intended to say, and server waits for new orders from you and is ready to add more data to it's output.</p>
| 0 |
2016-09-15T18:30:20Z
|
[
"python",
"exec",
"telnet",
"exit",
"telnetlib"
] |
How do I input I change the letters in a string to numbers for a frequency count?
| 39,517,867 |
<p>In preparation for an upcoming national cipher challenge, I was hoping to create a piece of code that would take the coded message as a string and record the frequency of each letter in order to try and figure out what the letter is most likely to be when decoded (I'm sorry if that's not very clear!). This is how I planned to do this:</p>
<hr>
<p>1) Copy + paste the code into a python program</p>
<p>2) The program would convert the letters to numbers</p>
<p>3) for x in range(0,len(<em>name of variable the string is assigned to</em>):
if string[x] in "1":</p>
<p>increase count for '1' by one</p>
<p>x = x + 1</p>
<p>else:</p>
<p>x = x + 1</p>
<p>Then change it to </p>
<p>if string[x] in "2"</p>
<p>and so on until 26 when the program would print the frequency of each number. Any help whatsoever with this code would be appreciated. Even just some pseudocode would massively help.</p>
<p>Thank you!</p>
<p>Matt.</p>
<p>(PS, I'm completely new to this site!)</p>
| -2 |
2016-09-15T18:20:59Z
| 39,517,976 |
<p>You can try <code>Counter</code> for counting frequency:</p>
<pre><code>from collections import Counter
s = 'abahvhavsvgs'
print(Counter(s))
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>Counter({'v': 3, 'a': 3, 'h': 2, 's': 2, 'b': 1, 'g': 1})
</code></pre>
<p>For iterating over Counter (i.e. accessing particular element) you can use <code>most_common()</code> like:</p>
<pre><code>c =Counter(s)
print(c.most_common())
</code></pre>
<p>Output: (list of tuples)</p>
<pre><code>[('v', 3), ('a', 3), ('s', 2), ('h', 2), ('g', 1), ('b', 1)]
</code></pre>
<blockquote>
<p><strong>Note:</strong> If you want to see occurrence of particular letter let's say <code>'a'</code>, you can directly access it like <code>print(c['a'])</code> it gives output
as <code>3</code> and if letter is not present in the string like <code>'z'</code> if you
execute <code>print(c['z'])</code> it gives output as <code>0</code></p>
</blockquote>
<p>See also the <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow">documentation of <code>Counter.most_common()</code></a>.So you can <em>iterate</em> over like if you do <code>print(c.most_common()[0])</code> it will give output <code>('v', 3)</code> as character with number of times it is occurred in the string.</p>
<p>For details about <code>collections</code> and <code>counter</code> see this <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">Counter Explained</a>.</p>
<p><strong>Another Solution</strong>(using <code>defaultdict</code> ):</p>
<pre><code>from collections import defaultdict
s = 'abahvhavsvgs'
d_int = defaultdict(int) # to make default value to 0
for i in s:
d_int[i] +=1
print(d_int)
</code></pre>
<p>Output:</p>
<pre><code>defaultdict(<class 'int'>, {'v': 3, 'h': 2, 's': 2, 'b': 1, 'g': 1, 'a': 3})
</code></pre>
<p>You can convert it into dictionary by <code>print(dict(d_int))</code> gives you output as <code>{'g': 1, 's': 2, 'v': 3, 'h': 2, 'a': 3, 'b': 1}</code> . Instead of using normal dictionary where every time you have to check if key is present in the dictionary (like in case of @Patrick Haugh solution) you can use <code>defaultdict</code>. For details about defaultdict you can this article <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict Document</a>. (<strong>Note:</strong> But then you have to do additional logic to sort by value or to find which letter occurs most times or least times!). </p>
<p>Hope this helps.</p>
| 2 |
2016-09-15T18:26:45Z
|
[
"python",
"string"
] |
How do I input I change the letters in a string to numbers for a frequency count?
| 39,517,867 |
<p>In preparation for an upcoming national cipher challenge, I was hoping to create a piece of code that would take the coded message as a string and record the frequency of each letter in order to try and figure out what the letter is most likely to be when decoded (I'm sorry if that's not very clear!). This is how I planned to do this:</p>
<hr>
<p>1) Copy + paste the code into a python program</p>
<p>2) The program would convert the letters to numbers</p>
<p>3) for x in range(0,len(<em>name of variable the string is assigned to</em>):
if string[x] in "1":</p>
<p>increase count for '1' by one</p>
<p>x = x + 1</p>
<p>else:</p>
<p>x = x + 1</p>
<p>Then change it to </p>
<p>if string[x] in "2"</p>
<p>and so on until 26 when the program would print the frequency of each number. Any help whatsoever with this code would be appreciated. Even just some pseudocode would massively help.</p>
<p>Thank you!</p>
<p>Matt.</p>
<p>(PS, I'm completely new to this site!)</p>
| -2 |
2016-09-15T18:20:59Z
| 39,519,053 |
<p>Your post leads me to believe that you're an absolute beginner, so I think that it would be valuable for you to implement this on your own, so that you understand what's going on. </p>
<p>First: reading the cipher.</p>
<p>Instead of editing your code every time, you can read the contents of a file. Copy the cipher into a new txt file. I'll name mine "cipher.txt"</p>
<p>Then:</p>
<pre><code>f = open('cipher.txt', 'r')
</code></pre>
<p>creates a file object named <code>f</code> that I can use to get the contents of a file. I will put all the text in the file onto one line, by removing the newline characters.</p>
<pre><code>contents = r.read().replace('\n', '')
</code></pre>
<p>So <code>contents</code> is a string that holds all the text in our cipher. One of the nice things about strings in python is that they are iterable, so we can say</p>
<pre><code>for char in contents:
</code></pre>
<p>to look at all the characters individually, in order.</p>
<p>But hold up! Where are we going to store our results? Let's assume that there could be any kind of character in our file, even one we may not expect. The other solution returned a list of tuples, but I like to use dictionaries for this kind of thing.</p>
<p>So let's make a dictionary</p>
<pre><code>char_dict = {}
</code></pre>
<p>and start counting!</p>
<pre><code>for char in contents:
if char not in char_dict:
char_dict[char] = 1
else:
char_dict[char] += 1
</code></pre>
<p>Dictionaries are just pairs of things. So if a char is not in our dictionary, we pair it with one. If it is in our dictionary, we increase the number we pair it with by one.</p>
<p>Then we can do things with the dictionary. To access 'a' in the dictionary you would just say</p>
<pre><code>char_dict['a']
</code></pre>
<p>The other posters answer may be easier to write, but I hope this helped you understand a little bit of what's happening "under the hood", so to speak.</p>
| 1 |
2016-09-15T19:38:10Z
|
[
"python",
"string"
] |
pip install nose==1.3.7 installs version 0.10.4
| 39,517,887 |
<p>I'm trying to force pip to install nose v1.3.7. Using the following command:</p>
<pre><code>pip install --proxy **** --no-cache -I nose==1.3.7
</code></pre>
<p>but, I get the following output:</p>
<p><a href="http://i.stack.imgur.com/nTJAQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/nTJAQ.png" alt="enter image description here"></a></p>
<p>Why is pip installing 0.10.4 instead, after I specifically asked for 1.3.7?</p>
<p>I should note that I'm doing is within a python virtualenv.</p>
<p>Other details: Centos 6.8, python 2.6, pip 8.1.2</p>
| 1 |
2016-09-15T18:21:47Z
| 39,518,129 |
<p>Forcing an uninstall of nose and reinstalling it seems to have worked. Still uncertain why the -I flag didn't do as it's intended to do.</p>
| 0 |
2016-09-15T18:35:42Z
|
[
"python",
"pip",
"nose"
] |
Error in program-censor(codecademy)-Practice makes perfect
| 39,517,934 |
<p>I tried executing this code but in the output the last <em>word-hack</em> is not turning into <em>asterisk</em> and is not even shown. </p>
<p>Enter code here:</p>
<pre><code>def censor(text,word):
w=""
text1=""
for i in text:
if i==" ":
if w==word:
text1=text1+"*"*len(word)
else:
text1=text1+w
text1=text1+" "
w=""
else:
w=w+i
return text1
print censor("this hack is wack hack", "hack")
</code></pre>
| 1 |
2016-09-15T18:24:39Z
| 39,518,049 |
<p>The error is happening in the fourth line of the function. If you add an extra space to the end of "text" in your example, you get it it print what you want. Without digging too much into why the problem is happening, the following will work.</p>
<pre><code>def censor(text,word):
text = text + " "
w=""
text1=""
for i in text:
if i==" ":
if w==word:
text1=text1+"*"*len(word)
else:
text1=text1+w
text1=text1+" "
w=""
else:
w=w+i
return text1
print(censor("this hack is wack hack ", "hack"))
</code></pre>
| 0 |
2016-09-15T18:31:11Z
|
[
"python"
] |
Function that returns a list of the count of positive numbers and sum of negative numbers
| 39,518,074 |
<p>I have a problem when I ran my code against the unit test. Any advice would be appreciated. Please find the code below:</p>
<pre><code>def manipulate_data(data):
count = 0
sum1 = 0
new_list = []
for x in data:
if x > 0:
count += 1
if x < 0:
sum1 += x
new_list.append(count)
new_list.append(sum1)
return new_list
</code></pre>
<p>The unit test is below:</p>
<pre><code>import unittest
class ManipulateDataTestCases(unittest.TestCase):
def test_only_lists_allowed(self):
result = manipulate_data({})
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
def test_it_returns_correct_output_with_positives(self):
result = manipulate_data([1, 2, 3, 4])
self.assertEqual(result, [4, 0], msg='Invalid output')
def test_returns_correct_ouptut_with_negatives(self):
result = manipulate_data([1, -9, 2, 3, 4, -5]);
self.assertEqual(result, [4, -14], msg='Invalid output')
</code></pre>
<p>The error I get is:</p>
<pre class="lang-none prettyprint-override"><code>`Total Specs: 3 Total Failures: 1
1 . test_only_lists_allowed
Failure in line 11, in test_only_lists_allowed
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
AssertionError: Invalid argument`
</code></pre>
| 0 |
2016-09-15T18:32:41Z
| 39,518,140 |
<p>The results are correct. In <code>test_only_lists_allowed()</code> you are comparing the list returned by the function to the string <code>'Only lists allowed'</code>.</p>
<p>That test will fail.</p>
| 0 |
2016-09-15T18:36:37Z
|
[
"python"
] |
Function that returns a list of the count of positive numbers and sum of negative numbers
| 39,518,074 |
<p>I have a problem when I ran my code against the unit test. Any advice would be appreciated. Please find the code below:</p>
<pre><code>def manipulate_data(data):
count = 0
sum1 = 0
new_list = []
for x in data:
if x > 0:
count += 1
if x < 0:
sum1 += x
new_list.append(count)
new_list.append(sum1)
return new_list
</code></pre>
<p>The unit test is below:</p>
<pre><code>import unittest
class ManipulateDataTestCases(unittest.TestCase):
def test_only_lists_allowed(self):
result = manipulate_data({})
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
def test_it_returns_correct_output_with_positives(self):
result = manipulate_data([1, 2, 3, 4])
self.assertEqual(result, [4, 0], msg='Invalid output')
def test_returns_correct_ouptut_with_negatives(self):
result = manipulate_data([1, -9, 2, 3, 4, -5]);
self.assertEqual(result, [4, -14], msg='Invalid output')
</code></pre>
<p>The error I get is:</p>
<pre class="lang-none prettyprint-override"><code>`Total Specs: 3 Total Failures: 1
1 . test_only_lists_allowed
Failure in line 11, in test_only_lists_allowed
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
AssertionError: Invalid argument`
</code></pre>
| 0 |
2016-09-15T18:32:41Z
| 39,518,583 |
<p>For the case of {}, the result of manipulate_data is [0,0]
try this:</p>
<pre><code>def manipulate_data(data):
if not isinstance(data, list):
return 'Only lists allowed'
count = 0
sum1 = 0
new_list = []
for x in data:
if x > 0:
count += 1
if x < 0:
sum1 += x
new_list.append(count)
new_list.append(sum1)
return new_list
import unittest
class ManipulateDataTestCases(unittest.TestCase):
def test_only_lists_allowed(self):
result = manipulate_data({})
# print('result: ', result)
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
if __name__ == '__main__':
unittest.main()
</code></pre>
| 0 |
2016-09-15T19:05:59Z
|
[
"python"
] |
Function that returns a list of the count of positive numbers and sum of negative numbers
| 39,518,074 |
<p>I have a problem when I ran my code against the unit test. Any advice would be appreciated. Please find the code below:</p>
<pre><code>def manipulate_data(data):
count = 0
sum1 = 0
new_list = []
for x in data:
if x > 0:
count += 1
if x < 0:
sum1 += x
new_list.append(count)
new_list.append(sum1)
return new_list
</code></pre>
<p>The unit test is below:</p>
<pre><code>import unittest
class ManipulateDataTestCases(unittest.TestCase):
def test_only_lists_allowed(self):
result = manipulate_data({})
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
def test_it_returns_correct_output_with_positives(self):
result = manipulate_data([1, 2, 3, 4])
self.assertEqual(result, [4, 0], msg='Invalid output')
def test_returns_correct_ouptut_with_negatives(self):
result = manipulate_data([1, -9, 2, 3, 4, -5]);
self.assertEqual(result, [4, -14], msg='Invalid output')
</code></pre>
<p>The error I get is:</p>
<pre class="lang-none prettyprint-override"><code>`Total Specs: 3 Total Failures: 1
1 . test_only_lists_allowed
Failure in line 11, in test_only_lists_allowed
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
AssertionError: Invalid argument`
</code></pre>
| 0 |
2016-09-15T18:32:41Z
| 39,518,587 |
<p>Did you write your unit test? The person who did thinks that you should only be checking lists. The way to do this in python is:</p>
<pre><code>>>>l = []
>>>isinstance(l, list)
True
>>>d = {}
>>>isinstance(d, dict)
True
>>>isinstance(d, list)
False
</code></pre>
<p>The way it's written, your program will attempt to iterate over all iterables, including <code>dict</code>. If you want to keep this behavior, keep in mind that it will iterate over keys, not values, of a <code>dict</code>.</p>
| 0 |
2016-09-15T19:06:17Z
|
[
"python"
] |
Function that returns a list of the count of positive numbers and sum of negative numbers
| 39,518,074 |
<p>I have a problem when I ran my code against the unit test. Any advice would be appreciated. Please find the code below:</p>
<pre><code>def manipulate_data(data):
count = 0
sum1 = 0
new_list = []
for x in data:
if x > 0:
count += 1
if x < 0:
sum1 += x
new_list.append(count)
new_list.append(sum1)
return new_list
</code></pre>
<p>The unit test is below:</p>
<pre><code>import unittest
class ManipulateDataTestCases(unittest.TestCase):
def test_only_lists_allowed(self):
result = manipulate_data({})
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
def test_it_returns_correct_output_with_positives(self):
result = manipulate_data([1, 2, 3, 4])
self.assertEqual(result, [4, 0], msg='Invalid output')
def test_returns_correct_ouptut_with_negatives(self):
result = manipulate_data([1, -9, 2, 3, 4, -5]);
self.assertEqual(result, [4, -14], msg='Invalid output')
</code></pre>
<p>The error I get is:</p>
<pre class="lang-none prettyprint-override"><code>`Total Specs: 3 Total Failures: 1
1 . test_only_lists_allowed
Failure in line 11, in test_only_lists_allowed
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
AssertionError: Invalid argument`
</code></pre>
| 0 |
2016-09-15T18:32:41Z
| 39,542,036 |
<p>def manipulate_data(data):
if not isinstance(data, list):
return 'Only lists allowed'</p>
<pre><code>count = 0
sum1 = 0
new_list = []
for x in data:
if x > 0:
count += 1
if x < 0:
sum1 += x
new_list.append(count)
new_list.append(sum1)
return new_list
</code></pre>
| 1 |
2016-09-17T01:27:51Z
|
[
"python"
] |
how to add coordinate array as rows in panda dataframe
| 39,518,141 |
<p>I have a text file that looks like this </p>
<pre><code>,A,B
0,"[[-81.03443909 29.22855949]
[-81.09729767 29.27094078]
[-80.9937973 29.19698906]
[-81.03072357 29.27445984]
[-81.00499725 29.22187805]]","[[-81.42427063 28.30874634]
[-81.42427063 28.30874634]
[-81.42427063 28.30874634]
[-81.36068726 28.29172897]
[-81.42297363 28.30497551]
[-81.48571777 28.24975777]
[-81.35914612 28.29036331]]"
</code></pre>
<p>This is what the <code>data</code> I'm using looks like, after it's put into a Pandas DataFrame</p>
<pre><code>[[-78.70117188 33.80754852]
[-78.9934082 33.61843491]
[-80.81887817 28.60919952]
...,
[-76.62332916 35.54064941]
[-79.04235077 33.81600952]
[-79.03309631 33.55596161]]
</code></pre>
<p>And I would like it to look like this</p>
<pre><code> lat long
cluster point
0 a 0.445900 -1.286198
b -0.574496 -0.407154
c 0.872979 0.068084
d 0.297255 -2.157051
</code></pre>
<p>Before I create the .txt file the data is in a <code>nd.array</code> and I'm using pandas to create the text file. So maybe there's a way I can skip the txt file and use pandas to split or format the array into a neat dataframe. I've been at this for a while and I can't figure out how. </p>
<p>This is how I generate my data. I'm keeping things clear by only copying 2 columns but in the future I would like to pass an unique point identifier</p>
<pre><code># Generate sample data
col_1 ="RL15_LONGITUDE"
col_2 ="RL15_LATITUDE"
data = pd.read_csv("input_data.csv")
coords = data.as_matrix(columns=[col_1, col_2])
data = data[[col_1,col_2]].dropna()
data = data.as_matrix().astype('float16',copy=False)
</code></pre>
<p>This is the output of <code>print clusters</code></p>
<pre><code>[array([[-81.03443909, 29.22855949],
[-81.09729767, 29.27094078],
[-81.42297363, 28.30497551],
[-81.48571777, 28.24975777],
[-81.35914612, 28.29036331]], dtype=float32), array([[-81.49134064, 27.58896065],
[-81.5194931 , 27.63422012],
[-81.5096283 , 27.55581093],
[-82.05444336, 26.93555069]], dtype=float32), array([[-82.18956757, 26.52433586],
[-82.18956757, 26.52433586],
[-82.18956757, 26.52433586],
[-82.19439697, 26.53297997]], dtype=float32)]
</code></pre>
<p>This is how I'm creating my dataframe and writing a <code>.txt</code> file</p>
<pre><code>clusters = pd.DataFrame({'A':[clusters]})
clusters.to_csv('output.txt')
</code></pre>
| 2 |
2016-09-15T18:36:49Z
| 39,519,844 |
<p>Here is a starting point:</p>
<pre><code>In [72]: (pd.concat([pd.DataFrame(c, columns=['lat','lon']).assign(cluster=i)
....: for i,c in enumerate(clusters)])
....: .reset_index()
....: .rename(columns={'index':'point'})
....: )
Out[72]:
point lat lon cluster
0 0 -81.034439 29.228559 0
1 1 -81.097298 29.270941 0
2 2 -81.422974 28.304976 0
3 3 -81.485718 28.249758 0
4 4 -81.359146 28.290363 0
5 0 -81.491341 27.588961 1
6 1 -81.519493 27.634220 1
7 2 -81.509628 27.555811 1
8 3 -82.054443 26.935551 1
9 0 -82.189568 26.524336 2
10 1 -82.189568 26.524336 2
11 2 -82.189568 26.524336 2
12 3 -82.194397 26.532980 2
</code></pre>
<p>Or with a multi-index:</p>
<pre><code>In [73]: (pd.concat([pd.DataFrame(c, columns=['lat','lon']).assign(cluster=i)
....: for i,c in enumerate(clusters)])
....: .reset_index()
....: .rename(columns={'index':'point'})
....: .set_index(['cluster','point'])
....: )
Out[73]:
lat lon
cluster point
0 0 -81.034439 29.228559
1 -81.097298 29.270941
2 -81.422974 28.304976
3 -81.485718 28.249758
4 -81.359146 28.290363
1 0 -81.491341 27.588961
1 -81.519493 27.634220
2 -81.509628 27.555811
3 -82.054443 26.935551
2 0 -82.189568 26.524336
1 -82.189568 26.524336
2 -82.189568 26.524336
3 -82.194397 26.532980
</code></pre>
| 1 |
2016-09-15T20:30:26Z
|
[
"python",
"pandas",
"numpy",
"dataframe"
] |
Can't assign to function call, yet code seems correct
| 39,518,205 |
<p>I was making a VERY simple calculator, because I was bored, but for some reason it errors out with 'Can't assign to function call'.
This is the code:</p>
<pre><code>type=input("Please select a method.\n\n1.) Addition\n2.) Subtraction\n3.) Multiplication\n4.) Division\n\n")
if type == "1":
int(number1)=input("First number?")
int(number2)=input("Second number?")
answer=number1+number2
print ("The answer is " +answer +".")
if type == "2":
int(number1)=input("First number?")
int(number2)=input("Second number?")
answer=number1-number2
print ("The answer is " +answer +".")
if type == "3":
int(number1)=input("First number?")
int(number2)=input("Second number?")
answer=number1*number2
print ("The answer is " +answer +".")
if type == "4":
int(number1)=input("First number?")
int(number2)=input("Second number?")
answer=number1/number2
print ("The answer is " +answer +".")
else:
print("Pick a number from 1-4")
</code></pre>
<p>I feel like this is very obvious and I'm just being an idiot.</p>
| 0 |
2016-09-15T18:41:13Z
| 39,518,246 |
<p>You are casting your variables to <code>int</code> at the wrong time. You need to cast the input given to you as an integer, rather than cast the variable to an integer before a string value is given to you.</p>
<p>All instances similar to <code>int(number1)=input("First number?")</code> need to be changed to <code>number1 = int(input("First number?"))</code>.</p>
<p>This is called <a href="https://docs.python.org/2/reference/expressions.html" rel="nofollow">precedence</a>.</p>
| 0 |
2016-09-15T18:43:35Z
|
[
"python",
"python-3.x"
] |
Can't assign to function call, yet code seems correct
| 39,518,205 |
<p>I was making a VERY simple calculator, because I was bored, but for some reason it errors out with 'Can't assign to function call'.
This is the code:</p>
<pre><code>type=input("Please select a method.\n\n1.) Addition\n2.) Subtraction\n3.) Multiplication\n4.) Division\n\n")
if type == "1":
int(number1)=input("First number?")
int(number2)=input("Second number?")
answer=number1+number2
print ("The answer is " +answer +".")
if type == "2":
int(number1)=input("First number?")
int(number2)=input("Second number?")
answer=number1-number2
print ("The answer is " +answer +".")
if type == "3":
int(number1)=input("First number?")
int(number2)=input("Second number?")
answer=number1*number2
print ("The answer is " +answer +".")
if type == "4":
int(number1)=input("First number?")
int(number2)=input("Second number?")
answer=number1/number2
print ("The answer is " +answer +".")
else:
print("Pick a number from 1-4")
</code></pre>
<p>I feel like this is very obvious and I'm just being an idiot.</p>
| 0 |
2016-09-15T18:41:13Z
| 39,518,247 |
<p>You need to convert the input string to int, not the variable it is getting assigned to:</p>
<pre><code>if type == "1":
number1=int(input("First number?"))
number2=int(input("Second number?"))
answer=number1+number2
</code></pre>
| 2 |
2016-09-15T18:43:38Z
|
[
"python",
"python-3.x"
] |
Syntax Error: no ascii character input operation
| 39,518,206 |
<p>I've got quite a problem with python right now. I try around to just calculate a few integers in an array. So it should not be too complicated. I worked on it over a 2 days now, but can't get it to work.</p>
<pre><code>def calculate( str ):
global x
if (len(x)==9):
a = []
for i in x_str:
a.append(i)
print(a)
b = 0
for j in range(1,9):
if (type(a[j])==int):
b = b + (a[j] * j)
else:
print('Your x is not a number!')
print(b)
else:
print('Your x is too long or too short.')
isdn = input('Enter your x with 9 numbers')
calculate( x )
# Operation
x =â¯input('How is your x?')
try:
x =â¯str( x )
calculate( x )
except:
print('Not a String!')
</code></pre>
<p>I just want to input an integer with 9 numbers and change that to an array. And do a simple calculation then with it.</p>
<p>I tried to do it without that damn try and except first, but that does not work either. Somehow Python won't except that x is a string when I enter it with input. What can I do, to get this calculation to work? It keeps telling me:</p>
<pre><code>SyntaxError: Non-ASCII character '\xe2' in file
</code></pre>
<p>I am really desperate right now, since I cannot get it to work.... Somehow Python is mixing strings and integers up and I cannot understand why. I know other languages, but never had that much trouble to get a simple calculation to work.
Does anyone can point me out my mistake? Or what I can do?</p>
| 1 |
2016-09-15T18:41:14Z
| 39,518,442 |
<p>I changed:</p>
<ul>
<li><code>a.append(i)</code> to <code>a.append(int(i))</code></li>
<li>removed <code>global x</code></li>
<li><code>for i in x_str:</code> to <code>for i in x:</code></li>
<li>changed your <code>isdn</code> variable to <code>x</code></li>
</ul>
<hr>
<pre><code>def calculate( x ):
if (len(x)==9):
a = []
for i in x:
a.append(int(i))
</code></pre>
<hr>
<pre><code>else:
print('Your x is too long or too short.')
x = input('Enter your x with 9 numbers')
calculate( x )
</code></pre>
<p>You also had bad (invisible) characters before the <code>x = input</code> and the <code>x = str ( x )</code>. I cleaned them up in the code below if you want to copy/paste.</p>
<pre><code>x = input('How is your x?')
try:
x = str( x )
calculate( x )
except:
print('Not a String!')
</code></pre>
| 1 |
2016-09-15T18:56:39Z
|
[
"python",
"python-3.x",
"syntax"
] |
I can connect to an AWS region but am not authorized to get the spot prices
| 39,518,236 |
<p>I am trying to get AWS spot price history and I have been getting help from this tutorial: <a href="https://medium.com/cloud-uprising/the-data-science-of-aws-spot-pricing-8bed655caed2#.nk3k2m1z0" rel="nofollow">https://medium.com/cloud-uprising/the-data-science-of-aws-spot-pricing-8bed655caed2#.nk3k2m1z0</a></p>
<p>I am able to connect to the given region as I get back the connection object.</p>
<p>But I get an error when I reach the following line:</p>
<pre><code>prices = ec2.get_spot_price_history(start_time=start, end_time=end, instance_type=instance)
</code></pre>
<p>This is the error I get:</p>
<pre><code>will process from 2016-05-26T00:00:00 to 2016-05-26T11:59:59
EC2Connection:ec2.us-east-1.amazonaws.com
Traceback (most recent call last):
File "test.py", line 30, in <module>
prices = conn.get_spot_price_history(start_time=start, end_time=end, instance_type=instance_types[0])
File "/usr/lib/python2.7/dist-packages/boto/ec2/connection.py", line 1420, in get_spot_price_history
[('item', SpotPriceHistory)], verb='POST')
File "/usr/lib/python2.7/dist-packages/boto/connection.py", line 1186, in get_list
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 401 Unauthorized
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>AuthFailure</Code><Message>AWS was not able to validate the provided access credentials</Message></Error></Errors><RequestID>70a8b7bd-28e2-4526-83df-d0cb86e1f491</RequestID></Response>
</code></pre>
<p>Can anyone tell my how is it possible that i can connect but am not authorized?</p>
| 1 |
2016-09-15T18:43:02Z
| 39,519,110 |
<p>The AWS credentials that you are using do not have permission to execute the <code>ec2:DescribeSpotPriceHistory</code> command.</p>
<p>To resolve this:</p>
<ol>
<li>Go to the IAM Management Console</li>
<li>Find the IAM user or role that you're using during your connection</li>
<li>Give yourself permission to execute <code>ec2:DescribeSpotPriceHistory</code></li>
</ol>
<p>Don't be lazy by giving yourself admin access. Do it right and just give yourself the right permissions.</p>
| -1 |
2016-09-15T19:41:14Z
|
[
"python",
"amazon-web-services",
"amazon-ec2",
"boto",
"unauthorized"
] |
I can connect to an AWS region but am not authorized to get the spot prices
| 39,518,236 |
<p>I am trying to get AWS spot price history and I have been getting help from this tutorial: <a href="https://medium.com/cloud-uprising/the-data-science-of-aws-spot-pricing-8bed655caed2#.nk3k2m1z0" rel="nofollow">https://medium.com/cloud-uprising/the-data-science-of-aws-spot-pricing-8bed655caed2#.nk3k2m1z0</a></p>
<p>I am able to connect to the given region as I get back the connection object.</p>
<p>But I get an error when I reach the following line:</p>
<pre><code>prices = ec2.get_spot_price_history(start_time=start, end_time=end, instance_type=instance)
</code></pre>
<p>This is the error I get:</p>
<pre><code>will process from 2016-05-26T00:00:00 to 2016-05-26T11:59:59
EC2Connection:ec2.us-east-1.amazonaws.com
Traceback (most recent call last):
File "test.py", line 30, in <module>
prices = conn.get_spot_price_history(start_time=start, end_time=end, instance_type=instance_types[0])
File "/usr/lib/python2.7/dist-packages/boto/ec2/connection.py", line 1420, in get_spot_price_history
[('item', SpotPriceHistory)], verb='POST')
File "/usr/lib/python2.7/dist-packages/boto/connection.py", line 1186, in get_list
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 401 Unauthorized
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>AuthFailure</Code><Message>AWS was not able to validate the provided access credentials</Message></Error></Errors><RequestID>70a8b7bd-28e2-4526-83df-d0cb86e1f491</RequestID></Response>
</code></pre>
<p>Can anyone tell my how is it possible that i can connect but am not authorized?</p>
| 1 |
2016-09-15T18:43:02Z
| 39,519,332 |
<p>I figured out the problem. It turns out my pc time was 7 minutes slower. and I read somewhere that AWS in addition to your credentials also uses your CPU time.</p>
<p>Basically I manually changed the time, and now it works:)</p>
| 0 |
2016-09-15T19:54:22Z
|
[
"python",
"amazon-web-services",
"amazon-ec2",
"boto",
"unauthorized"
] |
GtkFileChooserButon reset to initial state before file selection
| 39,518,302 |
<p>How to reset a <code>GtkFileChooserButton</code> for its initial state, ie before file selection?</p>
<p>code:</p>
<pre><code>#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
def file_changed(filechooserbutton):
print("File selected: %s" % filechooserbutton.get_filename())
window = Gtk.Window()
window.set_title("FileChooserButton")
window.set_default_size(150, -1)
window.connect("destroy", Gtk.main_quit)
filechooserbutton = Gtk.FileChooserButton(title="FileChooserButton")
filechooserbutton.connect("file-set", file_changed)
window.add(filechooserbutton)
window.show_all()
Gtk.main()
</code></pre>
<p>Before file selection:</p>
<p><a href="http://i.stack.imgur.com/V6Dib.png" rel="nofollow"><img src="http://i.stack.imgur.com/V6Dib.png" alt="enter image description here"></a></p>
<p>After file selection:</p>
<p><a href="http://i.stack.imgur.com/i8VOE.png" rel="nofollow"><img src="http://i.stack.imgur.com/i8VOE.png" alt="enter image description here"></a></p>
| 1 |
2016-09-15T18:46:47Z
| 39,526,252 |
<p>GtkFileChooserButton implements GtkFileChooser, so you can use the <a href="https://developer.gnome.org/gtk3/stable/GtkFileChooser.html#gtk-file-chooser-unselect-all" rel="nofollow">unselect_all</a> function.</p>
| 1 |
2016-09-16T07:45:25Z
|
[
"python",
"gtk"
] |
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB LESPACE, but settings are not configured
| 39,518,350 |
<p>Iâm using Django 1.9.1 with Python 3.5.2 and I'm having a problem running a Python script that uses Django models.</p>
<pre><code>C:\Users\admin\trailers>python load_from_api.py
Traceback (most recent call last):
File "load_from_api.py", line 6, in <module>
from movies.models import Movie
File "C:\Users\admin\trailers\movies\models.py", line 5, in <module>
class Genre(models.Model):
File "C:\Users\admin\trailers\movies\models.py", line 6, in Genre
id = models.CharField(max_length=10, primary_key=True)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 1072, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 55, in __getattr__
self._setup(name)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 41, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.
</code></pre>
<p>here's the script:</p>
<pre><code>#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "trailers.settings"
import django
django.setup()
import tmdbsimple as tmdb
from movies.models import Movie
#some code...
</code></pre>
<p>I can't really figure out what's wrong. Any help is appreciated!</p>
| 1 |
2016-09-15T18:49:53Z
| 39,525,966 |
<p>I would recommend using <a href="https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/" rel="nofollow">Django Custom Management Commands</a> - they are really simple to use, they use your settings, your environment, you can pass parameters and also you can write help strings so you can use <code>--help</code> </p>
<p>Then you just call it with <code>./manage.py my_custom_command</code></p>
<p>Or if you just want to run your script add this to the your script</p>
<pre><code>project_path = '/home/to/your/trailers/project/src'
if project_path not in sys.path:
sys.path.append(project_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.common")
import django
django.setup()
</code></pre>
| 0 |
2016-09-16T07:26:54Z
|
[
"python",
"django"
] |
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB LESPACE, but settings are not configured
| 39,518,350 |
<p>Iâm using Django 1.9.1 with Python 3.5.2 and I'm having a problem running a Python script that uses Django models.</p>
<pre><code>C:\Users\admin\trailers>python load_from_api.py
Traceback (most recent call last):
File "load_from_api.py", line 6, in <module>
from movies.models import Movie
File "C:\Users\admin\trailers\movies\models.py", line 5, in <module>
class Genre(models.Model):
File "C:\Users\admin\trailers\movies\models.py", line 6, in Genre
id = models.CharField(max_length=10, primary_key=True)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 1072, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 55, in __getattr__
self._setup(name)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 41, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.
</code></pre>
<p>here's the script:</p>
<pre><code>#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "trailers.settings"
import django
django.setup()
import tmdbsimple as tmdb
from movies.models import Movie
#some code...
</code></pre>
<p>I can't really figure out what's wrong. Any help is appreciated!</p>
| 1 |
2016-09-15T18:49:53Z
| 39,538,836 |
<p>I figured out how to run it without changing the script and that's by using</p>
<p><code>python manag.py shell</code></p>
<p>and then </p>
<p><code>exec(open('filename').read())</code></p>
<p>that seemed to work just fine.</p>
| 0 |
2016-09-16T19:27:11Z
|
[
"python",
"django"
] |
Receiving getaddrinfo [Errno -2] when trying to use Beaglebone Black to send email
| 39,518,411 |
<p>I'm trying to use a Beaglebone Black (BBB) to send email notifications, but I'm getting caught up on this getaddrinfo error that reads as follows; </p>
<blockquote>
<p>socket.gaierror: [Errno -2] Name or service not known</p>
</blockquote>
<p>I've been working on this for a while and can't find why this isn't working. </p>
<p>The nano file I"m trying to run:</p>
<pre><code>import smtplib
#import time
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
#time.sleep(1000)
print("SMTP object created...")
smtpObj.ehlo()
#time.sleep(1000)
print("EHLO...")
smtpObj.starttls()
#time.sleep(1000)
print("Starting TLS...")
smtpObj.login('EXAMPLEACCOUNT@gmail.com', 'EXAMPLEPASSWORD')
#time.sleep(1000)
print("Logged into EXAMPLEACCOUNT@gmail.com...")
smtpObj.sendmail('EXAMPLEACCOUNT@gmail.com', 'EXAMPLERECIPIENT', '''Subject:test subject \ntest body
Auto Alert System.''')
{}
#time.sleep(1000)
print("Sending email...")
smtpObj.quit()
#time.sleep(1000)
print("Destorying object.")
</code></pre>
<p>The output of invoking the test_email2.py function is as follows:</p>
<pre><code>root@beaglebone:~/Desktop/email_project# python test_email2.py
Traceback (most recent call last):
File "test_email2.py", line 4, in <module>
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
File "/usr/lib/python2.7/smtplib.py", line 249, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib/python2.7/socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
</code></pre>
<p>The format I've been following is based on that provided by <a href="https://automatetheboringstuff.com/chapter16/" rel="nofollow">https://automatetheboringstuff.com/chapter16/</a></p>
| 3 |
2016-09-15T18:54:40Z
| 39,518,649 |
<p><code>socket.gaierror</code> means that (underlying in libc) <code>getaddrinfo</code> function failed to get IP addresses for domain names you provided. It explains why it failed: <code>[Errno -2] Name or service not known</code>, so it doesn't know about a domain with such a name, <code>smtp.gmail.com</code>. This domain name obviously exists, so you should look into DNS system settings in your BBB system (and it's actually more of a SuperUser community question).</p>
<p>What DNS servers are used in configuration? If you're using a local caching DNS server at loopback, is it up and running? Is it configured properly to allow recursive requests? This particular problem most likely has nothing to do with Python or your code; it's your BBB system cannot resolve at least some, if not all, domain names.</p>
| 1 |
2016-09-15T19:10:37Z
|
[
"python",
"email",
"smtp",
"beagleboneblack",
"errno"
] |
I can't load multiple times a file with inside of it an empty list
| 39,518,431 |
<p>I need to load more than one time a file with inside of it and empty list.
At first I tried:</p>
<pre><code>import pickle
file_example = open("file.cpk","wb")
empty_list = []
pickle.dump(empty_list,file_example)
file_example.close()
def file_open():
file_open.file = open("file.pck","rb")
file_open.empty_list = pickle.load(file_open.file)
file_open.empty_list = pickle.load(file_open.file)
file_open()
file_open()
</code></pre>
<p>but it said "Ran out of input". I found that I have to use .seek to load more than one time the same file, so I did this:</p>
<pre><code>import pickle
file_example = open("file.cpk","wb")
empty_list = []
pickle.dump(empty_list,file_example)
file_example.close()
def file_open():
file_open.file = open("file.pck","rb")
file_open.empty_list = pickle.load(file_open.file)
file_open.empty_list.seek(0)
file_open.empty_list = pickle.load(file_open.file)
file_open()
</code></pre>
<p>And now says "'list' object has no attribute 'seek'". How can I load more than one time that file?</p>
| 1 |
2016-09-15T18:55:54Z
| 39,518,516 |
<p>You need to call seek on the file object:</p>
<pre><code>import pickle
file_example = open("file.pck","wb")
empty_list = []
pickle.dump(empty_list,file_example)
file_example.close()
def file_open():
file_open.file = open("file.pck","rb")
file_open.empty_list = pickle.load(file_open.file)
file_open.file.seek(0)
file_open.empty_list = pickle.load(file_open.file)
file_open()
</code></pre>
| 1 |
2016-09-15T19:01:03Z
|
[
"python"
] |
python default configuration reuse of variables
| 39,518,488 |
<pre><code>class DefaultConfig(object):
class S3(object):
DATA_ROOT = 's3://%(bucket_name)s/NAS'
DATA_LOCATION = '{}/%(instrument_id)s/%(run_id)s'.format(DefaultConfig.S3.DATA_ROOT)
</code></pre>
<p>The code above gives me the following error. </p>
<pre><code> File "./s3Utils.py", line 5, in <module>
from InfraConfig import InfraConfig as IC
File "/opt/src/datasource/src/main/python/util/InfraConfig.py", line 4, in <module>
class DefaultConfig(object):
File "/opt/src/datasource/src/main/python/util/InfraConfig.py", line 6, in DefaultConfig
class S3(object):
File "/opt/src/datasource/src/main/python/util/InfraConfig.py", line 14, in S3
DATA_LOCATION = '{}/%(instrument_id)s/%(run_id)s'.format(DefaultConfig.S3.DATA_ROOT)
NameError: name 'DefaultConfig' is not defined
</code></pre>
<p>Why is it unable to find DefaultConfig.S3.DATA_ROOT
Also, this is my attempt at writing structured configuration with reuse of values of DefaultConfig. Is there a way to do this without writing a yml file?</p>
| 1 |
2016-09-15T18:59:07Z
| 39,518,524 |
<p>You should use it without any prefixes:</p>
<pre><code>class DefaultConfig(object):
class S3(object):
DATA_ROOT = 's3://%(bucket_name)s/NAS'
DATA_LOCATION = '{}/%(instrument_id)s/%(run_id)s'.format(DATA_ROOT)
print DefaultConfig.S3.DATA_LOCATION
</code></pre>
<p>returns:</p>
<pre><code>> s3://%(bucket_name)s/NAS/%(instrument_id)s/%(run_id)s
</code></pre>
| 1 |
2016-09-15T19:01:38Z
|
[
"python"
] |
python default configuration reuse of variables
| 39,518,488 |
<pre><code>class DefaultConfig(object):
class S3(object):
DATA_ROOT = 's3://%(bucket_name)s/NAS'
DATA_LOCATION = '{}/%(instrument_id)s/%(run_id)s'.format(DefaultConfig.S3.DATA_ROOT)
</code></pre>
<p>The code above gives me the following error. </p>
<pre><code> File "./s3Utils.py", line 5, in <module>
from InfraConfig import InfraConfig as IC
File "/opt/src/datasource/src/main/python/util/InfraConfig.py", line 4, in <module>
class DefaultConfig(object):
File "/opt/src/datasource/src/main/python/util/InfraConfig.py", line 6, in DefaultConfig
class S3(object):
File "/opt/src/datasource/src/main/python/util/InfraConfig.py", line 14, in S3
DATA_LOCATION = '{}/%(instrument_id)s/%(run_id)s'.format(DefaultConfig.S3.DATA_ROOT)
NameError: name 'DefaultConfig' is not defined
</code></pre>
<p>Why is it unable to find DefaultConfig.S3.DATA_ROOT
Also, this is my attempt at writing structured configuration with reuse of values of DefaultConfig. Is there a way to do this without writing a yml file?</p>
| 1 |
2016-09-15T18:59:07Z
| 39,518,552 |
<p>It is unable to find the <code>DefaultConfing</code> because <code>DefaultConfig</code> is not defined at the moment <code>S3</code> is created.</p>
<p>Remember that class are objects. Because there are objects, that means they need to be instantiate. Python instantiate a class at the end of its definition, and therefore register it in the globals. Because the class definition is not finished, you can't use the <code>DefaultConfig</code> name.</p>
| 2 |
2016-09-15T19:03:38Z
|
[
"python"
] |
django getattr and issues with updating
| 39,518,520 |
<p>In django I built a simple method that gets called and is passed a uniqueid, field specifier, and a value. It then does a simple addition to update the value in the field. I've coded it a number of ways and have come to the conclusion that getattr does not work when trying to save, update, or refresh the database.
One variation of my code:</p>
<pre><code>def updatetable(uid, fieldtitle, value):
workingobj = bog_db.objects.get(name=uid)
objectcall = getattr(workingobj,fieldtitle)
objectcall = F(fieldtitle) + value
workingobj.refresh_from_db()
return
</code></pre>
<p>I tried hand jamming some code to see if I could figure out the problem.
btw: value = 37</p>
<pre><code>In [36]: call = getattr(workingobj,fieldname)
In [37]: call
Out[37]: 37
In [38]: call += value
In [39]: call
Out[39]: 74
In [40]: workingobj.save()
#refreshed database, checked table, values in db not updated
In [41]: workingobj.total_number_posts += value
In [42]: workingobj.total_number_posts
Out[42]: 74
In [43]: workingobj.save()
#refreshed database, values in db were updated
</code></pre>
<p>It would appear to me that Django does not want you using getattr for doing db calls and updates and instead wants you to EXPLICITLY call object.field.</p>
<p>Is this true? Does getattr make a copy of the attributes? I want to better understand why it is behaving this way. </p>
<p>Thanks</p>
| 1 |
2016-09-15T19:01:22Z
| 39,518,610 |
<p>I'm not sure what you're expecting here, but this is nothing to do with Django wanting anything, and nothing to do with <code>setattr</code>.</p>
<p>Integers are immutable. However you get the value of fieldname and store it in <code>call</code>, you cannot modify it. Doing <code>call += value</code> creates a new value and stores it in <code>call</code>; that now has no relationship with the original value of fieldname. </p>
<p>Note that you would get <em>exactly</em> the same result if you originally did <code>call = workingobj.fieldname</code>.</p>
| 0 |
2016-09-15T19:07:49Z
|
[
"python",
"django",
"django-models",
"getattr"
] |
Pandas series.rename gives TypeError: 'str' object is not callable error
| 39,518,534 |
<p>I can't figure out why this happens. I know this could happen if I have the function name "shadowed" somehow. But how could I in this scenario? </p>
<p>If I open iPython in my terminal and then type:</p>
<pre><code>import pandas as pd
a = pd.Series([1,2,3,4])
a.rename("test")
</code></pre>
<p>I get TypeError: 'str' object is not callable. What could be the causes of this?</p>
<p>Longer error msg:</p>
<pre><code> /usr/local/lib/python2.7/site-packages/pandas/core/series.pyc in rename(self, index, **kwargs)
2262 @Appender(generic._shared_docs['rename'] % _shared_doc_kwargs)
2263 def rename(self, index=None, **kwargs):
-> 2264 return super(Series, self).rename(index=index, **kwargs)
2265
2266 @Appender(generic._shared_docs['reindex'] % _shared_doc_kwargs)
/usr/local/lib/python2.7/site-packages/pandas/core/generic.pyc in rename(self, *args, **kwargs)
604
605 baxis = self._get_block_manager_axis(axis)
--> 606 result._data = result._data.rename_axis(f, axis=baxis, copy=copy)
607 result._clear_item_cache()
608
/usr/local/lib/python2.7/site-packages/pandas/core/internals.pyc in rename_axis(self, mapper, axis, copy)
2586 """
2587 obj = self.copy(deep=copy)
-> 2588 obj.set_axis(axis, _transform_index(self.axes[axis], mapper))
2589 return obj
2590
/usr/local/lib/python2.7/site-packages/pandas/core/internals.pyc in _transform_index(index, func)
4389 return MultiIndex.from_tuples(items, names=index.names)
4390 else:
-> 4391 items = [func(x) for x in index]
4392 return Index(items, name=index.name)
4393
</code></pre>
<p>Reference for test example <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rename.html" rel="nofollow">here</a>.</p>
| 2 |
2016-09-15T19:02:06Z
| 39,518,872 |
<p>Great, thanks to Nickil Maveli who pointed out I need 0.18.1, now it works. My mistake thinking <code>brew upgrade</code> would have sorted out me having the latest version.</p>
| 0 |
2016-09-15T19:26:26Z
|
[
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Creating active users via Google Directory API
| 39,518,568 |
<p>I am the admin for my Google domain and I am trying to automate provisioning of new users. I first attempted to do so using a command line tool called GAM.</p>
<p><a href="https://github.com/jay0lee/GAM" rel="nofollow">https://github.com/jay0lee/GAM</a></p>
<p>While this tool works, at least half of the users I create are flagged for unusual activity and are created as suspended. I have tried setting the flags in a variety of combinations but am getting the same result.</p>
<p>I also tried to use the Directory API directly by writing a python program but all new users are still being created as suspended users. Here is my program. Can anyone shed some light on this? Thank you.</p>
<pre><code>from __future__ import print_function
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/admin.directory.user'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Directory API Python Quickstart'
def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'admin-directory_v1-python-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def create_user():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('admin', 'directory_v1', http=http)
userinfo = {'primaryEmail': 'jane@mydomain.com',
'name': { 'givenName': 'Jane', 'familyName': 'Smith' },
'password': '34gjklre304iojlo24j2kl3kdlj',}
service.users().insert(body=userinfo).execute()
if __name__ == '__main__':
create_user()
main()
</code></pre>
| 1 |
2016-09-15T19:05:06Z
| 39,529,622 |
<p>Take note of the following statement from Directory API about <a href="https://developers.google.com/admin-sdk/directory/v1/guides/manage-users" rel="nofollow">Creating accounts</a>:</p>
<blockquote>
<p>If the Google account has purchased mail licenses, the new user
account is automatically assigned a mailbox. This assignment may take
a few minutes to be completed and activated.</p>
</blockquote>
<p>So it may take sometime. Also note from the user <a href="https://developers.google.com/admin-sdk/directory/v1/reference/users" rel="nofollow">resources</a> that:</p>
<blockquote>
<p>A new account is automatically suspended by Google until the initial
administrator login which activates the account. After the account is
activated, the account is no longer suspended.</p>
</blockquote>
<p>So after creating the new account, try logging it in to officially activate it.</p>
| 0 |
2016-09-16T10:47:42Z
|
[
"python",
"google-admin-sdk",
"google-directory-api"
] |
Creating active users via Google Directory API
| 39,518,568 |
<p>I am the admin for my Google domain and I am trying to automate provisioning of new users. I first attempted to do so using a command line tool called GAM.</p>
<p><a href="https://github.com/jay0lee/GAM" rel="nofollow">https://github.com/jay0lee/GAM</a></p>
<p>While this tool works, at least half of the users I create are flagged for unusual activity and are created as suspended. I have tried setting the flags in a variety of combinations but am getting the same result.</p>
<p>I also tried to use the Directory API directly by writing a python program but all new users are still being created as suspended users. Here is my program. Can anyone shed some light on this? Thank you.</p>
<pre><code>from __future__ import print_function
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/admin.directory.user'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Directory API Python Quickstart'
def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'admin-directory_v1-python-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def create_user():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('admin', 'directory_v1', http=http)
userinfo = {'primaryEmail': 'jane@mydomain.com',
'name': { 'givenName': 'Jane', 'familyName': 'Smith' },
'password': '34gjklre304iojlo24j2kl3kdlj',}
service.users().insert(body=userinfo).execute()
if __name__ == '__main__':
create_user()
main()
</code></pre>
| 1 |
2016-09-15T19:05:06Z
| 39,623,164 |
<p>This issue ended up being attributed to testing on a free trial domain. Using a trial domain, both GAM and the python program above created some suspended users and some active users. However, when I tried both methods on my paid full version google domain I was able to consistently create all active users.</p>
| 0 |
2016-09-21T17:39:59Z
|
[
"python",
"google-admin-sdk",
"google-directory-api"
] |
http POST message body not received
| 39,518,577 |
<p>Im currently creating a python socket http server, and I'm working on my GET and POST requests. I got my GET implementation working fine, but the body element of the POST requests won't show up.
Code snippet:</p>
<pre><code>self.host = ''
self.port = 8080
self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.listener.bind((self.host, self.port))
self.listener.listen(1)
while True:
client_connection, client_address = self.listener.accept()
request = client_connection.recv(2048)
print request
</code></pre>
<p>This code yields the http header after processing the post request from the webpage:</p>
<pre><code>POST /test.txt HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded
Origin: http://localhost:8080
Content-Length: 21
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17
Referer: http://localhost:8080/
Accept-Language: nb-no
Accept-Encoding: gzip, deflate
</code></pre>
<p>But there is no body, so the question is why am i not receiving the http body when i know it is sent?</p>
<p>Thanks!</p>
| 1 |
2016-09-15T19:05:31Z
| 39,519,337 |
<pre><code>while True:
client_connection, client_address = self.listener.accept()
request = client_connection.recv(2048)
print request
</code></pre>
<p><code>recv</code> does not read exactly 2048 bytes but it reads up to 2048 bytes. If some data arrive <code>recv</code> will return with the data even if more data might follow. My guess is that in your case the client is first sending the HTTP header and then the body. If NAGLE algorithms is off at the client side (common) it is likely that your first <code>recv</code> will only get the header and that you would need another <code>recv</code> for the body. This would explain what happens in your case: you get the header but not the body since you don't do another <code>recv</code>.</p>
<p>But even that would be a too simple implementation which will go wrong sooner or later. To make it correctly you should implement the HTTP protocol correctly: first read the HTTP header which might need multiple <code>recv</code> if the header is large. Then you should parse the header, figure out the size of the body (<code>Content-length</code> header) and read the remaining bytes.</p>
| 0 |
2016-09-15T19:54:34Z
|
[
"python",
"sockets",
"http",
"http-1.1"
] |
Select single item in MYSQLdb - Python
| 39,518,620 |
<p>I've been learning Python recently and have learned how to connect to the database and retrieve data from a database using MYSQLdb. However, all the examples show how to get multiple rows of data. I want to know how to retrieve only one row of data. </p>
<p>This is my current method. </p>
<pre><code>cur.execute("SELECT number, name FROM myTable WHERE id='" + id + "'")
results = cur.fetchall()
number = 0
name = ""
for result in results:
number = result['number']
name = result['name']
</code></pre>
<p>It seems redundant to do <code>for result in results:</code> since I know there is only going to be one result. </p>
<p>How can I just get one row of data without using the <code>for</code> loop?</p>
| 1 |
2016-09-15T19:09:06Z
| 39,518,647 |
<p><code>.fetchone()</code> to the rescue:</p>
<pre><code>result = cur.fetchone()
</code></pre>
| 2 |
2016-09-15T19:10:31Z
|
[
"python",
"mysql-python"
] |
Select single item in MYSQLdb - Python
| 39,518,620 |
<p>I've been learning Python recently and have learned how to connect to the database and retrieve data from a database using MYSQLdb. However, all the examples show how to get multiple rows of data. I want to know how to retrieve only one row of data. </p>
<p>This is my current method. </p>
<pre><code>cur.execute("SELECT number, name FROM myTable WHERE id='" + id + "'")
results = cur.fetchall()
number = 0
name = ""
for result in results:
number = result['number']
name = result['name']
</code></pre>
<p>It seems redundant to do <code>for result in results:</code> since I know there is only going to be one result. </p>
<p>How can I just get one row of data without using the <code>for</code> loop?</p>
| 1 |
2016-09-15T19:09:06Z
| 39,518,657 |
<p>use <code>.pop()</code></p>
<pre><code>if results:
result = results.pop()
number = result['number']
name = result['name']
</code></pre>
| 1 |
2016-09-15T19:10:51Z
|
[
"python",
"mysql-python"
] |
Append or Add to string of specific index
| 39,518,734 |
<p>I have a list of class objects 'x'. I am trying to create a new list by appending certain attribute values of the objects but I would like to append more that one attribute per index. For example, what I currently get:</p>
<pre><code>x = blah.values()
newList = []
for i in range(len(x)):
if x[i].status == 'ACT':
newList.append(str(x[i].full_name)),
newList.append(str(x[i].team))
else:
pass
print newList
</code></pre>
<p>The above code provides me with something like:</p>
<pre><code>['Victor Cruz', 'NYG', 'Marcus Cromartie', 'SF',....]
</code></pre>
<p>What I am trying to get:</p>
<pre><code>['Victor Cruz NYG', 'Marcus Cromartie SF',....]
</code></pre>
<p>How can I append more than one attribute per index? Hope this make sense, I can try to further elaborate if needed, thanks!</p>
| 2 |
2016-09-15T19:17:00Z
| 39,518,754 |
<p>You can use <code>.format()</code> in order to format your string. Notice the space between <code>{} {}</code></p>
<pre><code>for i in range(len(x)):
if x[i].status == 'ACT':
newList.append("{} {}".format(x[i].full_name,x[i].team) )
</code></pre>
<p>Another way is using <code>"%s" % string</code> notation</p>
<pre><code>newList.append("%s %s" % (str(x[i].full_name),str(x[i].team)))
</code></pre>
<p>Another example of <code>.format</code> using.</p>
<pre><code>"{} is {}".format('My answer', 'good')
>>> "My answer is good"
</code></pre>
| 2 |
2016-09-15T19:18:31Z
|
[
"python",
"python-2.7"
] |
Append or Add to string of specific index
| 39,518,734 |
<p>I have a list of class objects 'x'. I am trying to create a new list by appending certain attribute values of the objects but I would like to append more that one attribute per index. For example, what I currently get:</p>
<pre><code>x = blah.values()
newList = []
for i in range(len(x)):
if x[i].status == 'ACT':
newList.append(str(x[i].full_name)),
newList.append(str(x[i].team))
else:
pass
print newList
</code></pre>
<p>The above code provides me with something like:</p>
<pre><code>['Victor Cruz', 'NYG', 'Marcus Cromartie', 'SF',....]
</code></pre>
<p>What I am trying to get:</p>
<pre><code>['Victor Cruz NYG', 'Marcus Cromartie SF',....]
</code></pre>
<p>How can I append more than one attribute per index? Hope this make sense, I can try to further elaborate if needed, thanks!</p>
| 2 |
2016-09-15T19:17:00Z
| 39,518,758 |
<p>You could put the items into one string using <code>.format()</code> and <code>append</code> the string once:</p>
<pre><code>for i in range(len(x)):
if x[i].status == 'ACT':
newList.append('{} {}'.format(x[i].full_name, x[i].team))
</code></pre>
<hr>
<p>On a lighter note, using a <em>list comprehension</em> is a great alternative for creating your list:</p>
<pre><code>newList = ['{} {}'.format(o.full_name, o.team) for o in blah.values() if o.status == 'ACT']
</code></pre>
<p>You'll notice that <code>range</code> and <code>len</code> are no longer used in the comprehension, and there is no longer need for <em>indexing</em>.</p>
| 2 |
2016-09-15T19:19:02Z
|
[
"python",
"python-2.7"
] |
Looping SQL query in python
| 39,518,814 |
<p>I am writing a python script which queries the database for a URL string. Below is my snippet.</p>
<pre><code>db.execute('select sitevideobaseurl,videositestring '
'from site, video '
'where siteID =1 and site.SiteID=video.VideoSiteID limit 1')
result = db.fetchall()
filename = '/home/Site_info'
output = open(filename, "w")
for row in result:
videosite= row[0:2]
link = videosite[0].format(videosite[1])
full_link = link.replace("http://","https://")
print full_link
output.write("%s\n"%str(full_link))
output.close()
</code></pre>
<p>The query basically gives a URL link.It gives me baseURL from a table and the video site string from another table.</p>
<pre><code>output: https://www.youtube.com/watch?v=uqcSJR_7fOc
</code></pre>
<p>SiteID is the primary key which is int and not in sequence. </p>
<p>I wish to loop this sql query to pick a new siteId for every execution so that i have unique site URL everytime and write all the results to a file. </p>
<pre><code>desired output: https://www.youtube.com/watch?v=uqcSJR_7fOc
https://www.dailymotion.com/video/hdfchsldf0f
</code></pre>
<p>There are about 1178 records.</p>
<p>Thanks for your time and help in advance. </p>
| 2 |
2016-09-15T19:22:20Z
| 39,519,812 |
<p>I'm not sure if I completely understand what you're trying to do. I think your goal is to get a list of all links to videos. You get a link to a video by joining the <code>sitevideobaseurl</code> from <code>site</code> and <code>videositestring</code> from <code>video</code>.</p>
<p>From my experience it's much easier to let the database do the heavy lifting, it's build for that. It should be more efficient to join the tables, return all the results and then looping trough them instead of making subsequent queries to the database for each row.</p>
<p>The code should look something like this: (Be careful, I didn't test this)</p>
<pre><code>query = """
select s.sitevideobaseurl,
v.videositestring
from video as v
join site as s
on s.siteID = v.VideoSiteID
"""
db.execute(query)
result = db.fetchall()
filename = '/home/Site_info'
output = open(filename, "w")
for row in result:
link = "%s%s" % (row[0],row[1])
full_link = link.replace("http://","https://")
print full_link
output.write("%s\n" % str(full_link))
output.close()
</code></pre>
<p>If you have other reasons for wanting to fetch these ony by one an idea might be to fetch a list of all <code>SiteID</code>s and store them in a list. Afterwards you start a loop for each item in that list and insert the id into the query via a parameterized query.</p>
| 1 |
2016-09-15T20:28:17Z
|
[
"python",
"mysql",
"loops"
] |
for loop in a switch-dictionary for interactive menu
| 39,518,850 |
<p>I have a problem in a SWITCH /CASE Disctionary I am trying to implement. I got an example from <a href="http://www.pydanny.com/why-doesnt-python-have-switch-case.html" rel="nofollow">here</a> </p>
<p>I simply create an interactive menu in which you can choose more than 1 option at the same time in the order you choose them.</p>
<pre><code>ip = ["10.10.10.1","10.10.10.2"]
def display_menu():
os.system('clear')
main_title = "***** MENU *****"
print main_title.center(50,' ')
print("\n\n\t1. Ping Check\n\t2. CPU Load.")
#Allows you to choose more than one option
def pick_the_order():
display_menu()
order = map(int,raw_input("Choose (separated by spaces if more than one): ").split())
return order
</code></pre>
<p>Once it chooses the options it calls the proper functions:</p>
<pre><code>def echo_pick(ips1):
print "ECHO call", ips1
def snmp_pick(ips1):
print "SNMP Call", ips1
def numbers_to_functions_to_strings(argument):
global ip
for ips, option in zip(ip, argument):
print "Ip:",ips
print "option:", option
switcher = {
1: echo_pick(ips),
2: snmp_pick(ips)
}
switcher.get(option, "That is not a valid option")
print numbers_to_functions_to_strings(pick_the_order())
</code></pre>
<p>The problem I am facing is that, when running the program it runs the for for each of the options, no matter if your option is 1 or 2. The output is something like this (when choosing option 1 and 2):</p>
<pre><code>Ip: 10.10.10.1
option: 1
ECHO call 10.10.10.1
SNMP Call 10.10.10.1
Ip: 10.10.10.2
option: 2
ECHO call 10.10.10.2
SNMP Call 10.10.10.2
None
</code></pre>
<p>And the output I am looking for is this (when choosing option 1 and 2):</p>
<pre><code>Ip: 10.10.10.1
option: 1
ECHO call 10.10.10.1
ECHO call 10.10.10.2
Ip: 10.10.10.2
option: 2
SNMP Call 10.10.10.1
SNMP Call 10.10.10.2
None
</code></pre>
<p>What is making the FOR going through all the options? Even when I choose only 1 option, say ECHO call, it should only call <code>echo_pick(ips1)</code>, but it still calls <code>snmp_pick(ips)</code></p>
<p>Can anybody can help me on what part of my logic is not working properly? It seems that is is bypassing the values in option and just runs them anyway.</p>
| 1 |
2016-09-15T19:24:53Z
| 39,518,974 |
<p>You actually make the function call, and not use the reference to those functions.</p>
<p>If you define your dictionary as following:</p>
<pre><code>switcher = {
1: func1(ips)
2: func2(ips)
}
</code></pre>
<p>You already made the call to <code>func1</code> and <code>func2</code>. The solution here is just to make a reference to those functions, get the right one and execute it:</p>
<pre><code>def numbers_to_functions_to_strings(argument):
# global ip: no need to make it global since you do not modify them.
switcher = {
1: echo_pick, # <-- reference to the function
2: snmp_pick
}
for option in arguments:
if option not in swticher:
print("Invalid option:", option)
continue
func_to_call = switcher[option] # <-- pick the right function
for ips in ip: # NOTE: you should reverse ips and ip. Naming convention :)
func_to_call(ips) # <-- call the function
</code></pre>
<p>Note that I didn't zip the arguments. Maybe it is because I didn't understand the problem but I think that you misuse the <code>zip</code> function here.</p>
| 0 |
2016-09-15T19:32:45Z
|
[
"python",
"for-loop",
"switch-statement"
] |
AttributeError: 'module' object has no attribute 'get_frontal_face_detector'
| 39,518,871 |
<p>I was trying to use python's dlib library to detect the facial landmarks. I was using the example given on <a href="http://dlib.net/face_landmark_detection.py.html" rel="nofollow">face detector</a>. I have installed all the dependencies before installing dlib.</p>
<p>First I installed cmake and libboost using "sudo apt-get install libboost-python-dev cmake" as given on the link above. I then installed dlib using "pip install dlib".</p>
<p>My code:</p>
<pre><code>import sys
import os
import dlib
import glob
from skimage import io
predictor_path = 'shape_predictor_68_face_landmarks.dat'
faces_folder_path = './happy'
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
win = dlib.image_window()
for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")):
print("Processing file: {}".format(f))
img = io.imread(f)
win.clear_overlay()
win.set_image(img)
# Ask the detector to find the bounding boxes of each face. The 1 in the
# second argument indicates that we should upsample the image 1 time. This
# will make everything bigger and allow us to detect more faces.
dets = detector(img, 1)
print("Number of faces detected: {}".format(len(dets)))
for k, d in enumerate(dets):
print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
k, d.left(), d.top(), d.right(), d.bottom()))
# Get the landmarks/parts for the face in box d.
shape = predictor(img, d)
print("Part 0: {}, Part 1: {} ...".format(shape.part(0),
shape.part(1)))
# Draw the face landmarks on the screen.
win.add_overlay(shape)
win.add_overlay(dets)
dlib.hit_enter_to_continue()
</code></pre>
<p>But when I run the program, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "dlib.py", line 2, in <module>
import dlib
File "/home/shivam/musicplayer/dlib.py", line 6, in <module>
detector = dlib.get_frontal_face_detector() #Face detector
AttributeError: 'module' object has no attribute 'get_frontal_face_detector'
</code></pre>
<p>Here is the directory structure of my project:
<a href="http://i.stack.imgur.com/oYGuE.png" rel="nofollow"><img src="http://i.stack.imgur.com/oYGuE.png" alt="enter image description here"></a></p>
| 1 |
2016-09-15T19:26:20Z
| 39,518,947 |
<p>Rename your file from <code>dlib.py</code> to something else, say <code>dlib_project.py</code>. </p>
<p>Your file, named so, is shadowing the <code>dlib</code> library that has all of the functionality you need, as it is imported instead of the library, being first in the hierarchy.</p>
| 2 |
2016-09-15T19:31:23Z
|
[
"python",
"opencv",
"dlib"
] |
Comparing list comprehensions and explicit loops (3 array generators faster than 1 for loop)
| 39,518,899 |
<p>I did homework and I accidentally found a strange inconsistency in the speed of the algorithm.
Here is 2 versions of code of same function bur with 1 difference: in first version i use 3 times array generator to filter some array and in second version i use 1 for loop with 3 if statements to do same filter work.</p>
<p>So, here is code of 1st version:</p>
<pre><code>def kth_order_statistic(array, k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = [x for x in array if x < pivot]
m = [x for x in array if x == pivot]
r = [x for x in array if x > pivot]
if k <= len(l):
return kth_order_statistic(l, k)
elif k > len(l) + len(m):
return kth_order_statistic(r, k - len(l) - len(m))
else:
return m[0]
</code></pre>
<p>And here code of 2nd version:</p>
<pre><code>def kth_order_statistic2(array, k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = []
m = []
r = []
for x in array:
if x < pivot:
l.append(x)
elif x > pivot:
r.append(x)
else:
m.append(x)
if k <= len(l):
return kth_order_statistic2(l, k)
elif k > len(l) + len(m):
return kth_order_statistic2(r, k - len(l) - len(m))
else:
return m[0]
</code></pre>
<p>IPython output for 1st version:</p>
<pre><code>In [4]: %%timeit
...: A = range(100000)
...: shuffle(A)
...: k = randint(1, len(A)-1)
...: order_statisctic(A, k)
...:
10 loops, best of 3: 120 ms per loop
</code></pre>
<p>And for 2nd version:</p>
<pre><code>In [5]: %%timeit
...: A = range(100000)
...: shuffle(A)
...: k = randint(1, len(A)-1)
...: kth_order_statistic2(A, k)
...:
10 loops, best of 3: 169 ms per loop
</code></pre>
<p>So why first version is faster than second? I also made third version wich using filter() function instead of array generator and it was slower than second version (it got 218 ms per loop)</p>
| 3 |
2016-09-15T19:28:06Z
| 39,518,977 |
<p>Using simple <code>for</code> is faster than <code>list comprehesion</code>. It is almost 2 times faster. Check below results:</p>
<p>Using <code>list comprehension</code>: <em>58 usec</em> </p>
<pre><code>moin@moin-pc:~$ python -m timeit "[i for i in range(1000)]"
10000 loops, best of 3: 58 usec per loop
</code></pre>
<p>Using <code>for</code> loop: <em>37.1 usec</em></p>
<pre><code>moin@moin-pc:~$ python -m timeit "for i in range(1000): i"
10000 loops, best of 3: 37.1 usec per loop
</code></pre>
<p><strong>But in your case, <code>for</code> is taking more time than list comprehension not because YOUR for loop is slow. But because of <code>.append()</code> you are using within the code.</strong></p>
<p>With <code>append()</code> in <code>for</code> loop`: <em>114 usec</em></p>
<pre><code>moin@moin-pc:~$ python -m timeit "my_list = []" "for i in range(1000): my_list.append(i)"
10000 loops, best of 3: 114 usec per loop
</code></pre>
<p>Which clearly shows that it is <strong><code>.append()</code> which is taking twice the time taken by <code>for</code> loop</strong>.</p>
<p>However, on <code>storing the "list.append" in different variable</code>: <em>69.3 usec</em></p>
<pre><code>moin@moin-pc:~$ python -m timeit "my_list = []; append = my_list.append" "for i in range(1000): append(i)"
10000 loops, best of 3: 69.3 usec per loop
</code></pre>
<p>There is a huge improvement in the performance as compared to the last case in above comparisons, and result is quite comparable to that of <code>list comprehension</code>. That means, instead of calling <code>my_list.append()</code> each time, the performance can be improved by storing the reference of function in another variable i.e <code>append_func = my_list.append</code> and making a call using that variable <code>append_func(i)</code>.</p>
<p>Which also proves, <strong>it is faster to call class's function stored in the variable as compared to directly making the function call using object of the class</strong>.</p>
<p><em>Thank You <a href="http://stackoverflow.com/users/1672429/stefan-pochmann">Stefan</a> for bringing the last case in notice.</em></p>
| 6 |
2016-09-15T19:32:59Z
|
[
"python",
"arrays",
"python-2.7",
"time"
] |
Comparing list comprehensions and explicit loops (3 array generators faster than 1 for loop)
| 39,518,899 |
<p>I did homework and I accidentally found a strange inconsistency in the speed of the algorithm.
Here is 2 versions of code of same function bur with 1 difference: in first version i use 3 times array generator to filter some array and in second version i use 1 for loop with 3 if statements to do same filter work.</p>
<p>So, here is code of 1st version:</p>
<pre><code>def kth_order_statistic(array, k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = [x for x in array if x < pivot]
m = [x for x in array if x == pivot]
r = [x for x in array if x > pivot]
if k <= len(l):
return kth_order_statistic(l, k)
elif k > len(l) + len(m):
return kth_order_statistic(r, k - len(l) - len(m))
else:
return m[0]
</code></pre>
<p>And here code of 2nd version:</p>
<pre><code>def kth_order_statistic2(array, k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = []
m = []
r = []
for x in array:
if x < pivot:
l.append(x)
elif x > pivot:
r.append(x)
else:
m.append(x)
if k <= len(l):
return kth_order_statistic2(l, k)
elif k > len(l) + len(m):
return kth_order_statistic2(r, k - len(l) - len(m))
else:
return m[0]
</code></pre>
<p>IPython output for 1st version:</p>
<pre><code>In [4]: %%timeit
...: A = range(100000)
...: shuffle(A)
...: k = randint(1, len(A)-1)
...: order_statisctic(A, k)
...:
10 loops, best of 3: 120 ms per loop
</code></pre>
<p>And for 2nd version:</p>
<pre><code>In [5]: %%timeit
...: A = range(100000)
...: shuffle(A)
...: k = randint(1, len(A)-1)
...: kth_order_statistic2(A, k)
...:
10 loops, best of 3: 169 ms per loop
</code></pre>
<p>So why first version is faster than second? I also made third version wich using filter() function instead of array generator and it was slower than second version (it got 218 ms per loop)</p>
| 3 |
2016-09-15T19:28:06Z
| 39,519,199 |
<p>The algorithmic structure differs and the conditional structure is to be incriminated. the test to append into r and m can be discarded by the previous test. A more strict comparison regarding a for loop with <code>append</code>, and list comprehension would be against the non-optimal following </p>
<pre><code>for x in array:
if x < pivot:
l.append(x)
for x in array:
if x== pivot:
m.append(x)
for x in array:
if x > pivot:
r.append(x)
</code></pre>
| 2 |
2016-09-15T19:46:24Z
|
[
"python",
"arrays",
"python-2.7",
"time"
] |
Comparing list comprehensions and explicit loops (3 array generators faster than 1 for loop)
| 39,518,899 |
<p>I did homework and I accidentally found a strange inconsistency in the speed of the algorithm.
Here is 2 versions of code of same function bur with 1 difference: in first version i use 3 times array generator to filter some array and in second version i use 1 for loop with 3 if statements to do same filter work.</p>
<p>So, here is code of 1st version:</p>
<pre><code>def kth_order_statistic(array, k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = [x for x in array if x < pivot]
m = [x for x in array if x == pivot]
r = [x for x in array if x > pivot]
if k <= len(l):
return kth_order_statistic(l, k)
elif k > len(l) + len(m):
return kth_order_statistic(r, k - len(l) - len(m))
else:
return m[0]
</code></pre>
<p>And here code of 2nd version:</p>
<pre><code>def kth_order_statistic2(array, k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = []
m = []
r = []
for x in array:
if x < pivot:
l.append(x)
elif x > pivot:
r.append(x)
else:
m.append(x)
if k <= len(l):
return kth_order_statistic2(l, k)
elif k > len(l) + len(m):
return kth_order_statistic2(r, k - len(l) - len(m))
else:
return m[0]
</code></pre>
<p>IPython output for 1st version:</p>
<pre><code>In [4]: %%timeit
...: A = range(100000)
...: shuffle(A)
...: k = randint(1, len(A)-1)
...: order_statisctic(A, k)
...:
10 loops, best of 3: 120 ms per loop
</code></pre>
<p>And for 2nd version:</p>
<pre><code>In [5]: %%timeit
...: A = range(100000)
...: shuffle(A)
...: k = randint(1, len(A)-1)
...: kth_order_statistic2(A, k)
...:
10 loops, best of 3: 169 ms per loop
</code></pre>
<p>So why first version is faster than second? I also made third version wich using filter() function instead of array generator and it was slower than second version (it got 218 ms per loop)</p>
| 3 |
2016-09-15T19:28:06Z
| 39,519,661 |
<p>Let's define the functions we will need to answer the question and timeit them:</p>
<p><a href="http://i.stack.imgur.com/M8Chj.png" rel="nofollow"><img src="http://i.stack.imgur.com/M8Chj.png" alt="enter image description here"></a></p>
<p>we can see that the for loops without the append command is as fast as the list comprehension. In fact, if we have a look at the bytecode we can see that in the case of the list comprehension python is able to use a built-in bytecode command called LIST_APPEND instead of:</p>
<ul>
<li>Load the list: 40 LOAD_FAST</li>
<li>Load the attribute: 43 LOAD_ATTRIBUTE</li>
<li>Call the loaded function: 49 CALL_FUNCTION</li>
<li>Unload the list(?): 52 POP_TOP</li>
</ul>
<p>As you can see from the picture below the previous bytecode are missing with list comprehension and with the "loop_fast" function. Comparing the timeit of the three function is clear that those are responsible for the different timing of the three methods.</p>
<p><a href="http://i.stack.imgur.com/1ec67.png" rel="nofollow"><img src="http://i.stack.imgur.com/1ec67.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/luk5b.png" rel="nofollow"><img src="http://i.stack.imgur.com/luk5b.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/YpFaj.png" rel="nofollow"><img src="http://i.stack.imgur.com/YpFaj.png" alt="enter image description here"></a></p>
| 4 |
2016-09-15T20:17:32Z
|
[
"python",
"arrays",
"python-2.7",
"time"
] |
Comparing list comprehensions and explicit loops (3 array generators faster than 1 for loop)
| 39,518,899 |
<p>I did homework and I accidentally found a strange inconsistency in the speed of the algorithm.
Here is 2 versions of code of same function bur with 1 difference: in first version i use 3 times array generator to filter some array and in second version i use 1 for loop with 3 if statements to do same filter work.</p>
<p>So, here is code of 1st version:</p>
<pre><code>def kth_order_statistic(array, k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = [x for x in array if x < pivot]
m = [x for x in array if x == pivot]
r = [x for x in array if x > pivot]
if k <= len(l):
return kth_order_statistic(l, k)
elif k > len(l) + len(m):
return kth_order_statistic(r, k - len(l) - len(m))
else:
return m[0]
</code></pre>
<p>And here code of 2nd version:</p>
<pre><code>def kth_order_statistic2(array, k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = []
m = []
r = []
for x in array:
if x < pivot:
l.append(x)
elif x > pivot:
r.append(x)
else:
m.append(x)
if k <= len(l):
return kth_order_statistic2(l, k)
elif k > len(l) + len(m):
return kth_order_statistic2(r, k - len(l) - len(m))
else:
return m[0]
</code></pre>
<p>IPython output for 1st version:</p>
<pre><code>In [4]: %%timeit
...: A = range(100000)
...: shuffle(A)
...: k = randint(1, len(A)-1)
...: order_statisctic(A, k)
...:
10 loops, best of 3: 120 ms per loop
</code></pre>
<p>And for 2nd version:</p>
<pre><code>In [5]: %%timeit
...: A = range(100000)
...: shuffle(A)
...: k = randint(1, len(A)-1)
...: kth_order_statistic2(A, k)
...:
10 loops, best of 3: 169 ms per loop
</code></pre>
<p>So why first version is faster than second? I also made third version wich using filter() function instead of array generator and it was slower than second version (it got 218 ms per loop)</p>
| 3 |
2016-09-15T19:28:06Z
| 39,520,286 |
<p>Let's dissipate that doubt :
The <strong>second version</strong> is slightly faster : <strong>list comprehension are faster</strong>, yet two arrays looping and as much conditionals are discarded in one iteration. </p>
<pre><code>def kth_order_statistic1(array,k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = [x for x in array if x < pivot]
m = [x for x in array if x == pivot]
r = [x for x in array if x > pivot]
if k <= len(l):
return kth_order_statistic1(l, k)
elif k > len(l) + len(m):
return kth_order_statistic1(r, k - len(l) - len(m))
else:
return m[0]
def kth_order_statistic2(array,k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = []
m = []
r = []
for x in array:
if x < pivot:
l.append(x)
elif x > pivot:
r.append(x)
else:
m.append(x)
if k <= len(l):
return kth_order_statistic2(l, k)
elif k > len(l) + len(m):
return kth_order_statistic2(r, k - len(l) - len(m))
else:
return m[0]
def kth_order_statistic3(array,k):
pivot = (array[0] + array[len(array) - 1]) // 2
l = []
m = []
r = []
for x in array:
if x < pivot: l.append(x)
for x in array:
if x== pivot: m.append(x)
for x in array:
if x > pivot: r.append(x)
if k <= len(l):
return kth_order_statistic3(l, k)
elif k > len(l) + len(m):
return kth_order_statistic3(r, k - len(l) - len(m))
else:
return m[0]
import time
import random
if __name__ == '__main__':
A = range(100000)
random.shuffle(A)
k = random.randint(1, len(A)-1)
start_time = time.time()
for x in range(1000) :
kth_order_statistic1(A,k)
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
for x in range(1000) :
kth_order_statistic2(A,k)
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
for x in range(1000) :
kth_order_statistic3(A,k)
print("--- %s seconds ---" % (time.time() - start_time))
</code></pre>
<p><br></p>
<pre><code>python :
--- 25.8894710541 seconds ---
--- 24.073086977 seconds ---
--- 32.9823839664 seconds ---
ipython
--- 25.7450709343 seconds ---
--- 22.7140650749 seconds ---
--- 35.2958850861 seconds ---
</code></pre>
<p>The timing may vary according to the random draw, but the differences between the three are pretty much the same.</p>
| 2 |
2016-09-15T20:59:53Z
|
[
"python",
"arrays",
"python-2.7",
"time"
] |
How to print info when 2 things are correct and to use the input fuction when the those two things are incorrect
| 39,518,960 |
<p>I am doing a controlled assessment. I have this code : </p>
<pre><code># user Qualifications
print("\nQualification Level")
print("\n""\"AP\" = Apprentice",
"\n\"FQ\" = Fully-Qualified")
user_qual = input("Enter you Qualification Level: ")
</code></pre>
<p>When the <code>user_qual</code> is equal to <code>AP</code> or <code>FQ</code> I want to print "correct". But when the <code>user_qual</code> is not equal to either <code>AP</code> or <code>FQ</code>, I want to print an error message and re-ask the <code>user_qual</code> input question. However, I tried many different ways but couldn't do it.</p>
<p>Please just give a simple solution and nothing complicated. I am just a beginner and learning the basics.</p>
| 0 |
2016-09-15T19:31:56Z
| 39,519,099 |
<p>You can try defining the qualification levels within a variable. In this simple case a <a href="http://openbookproject.net/thinkcs/python/english3e/tuples.html" rel="nofollow">tuple</a> suffices, but if there were to be more qualification levels, a <a href="http://openbookproject.net/thinkcs/python/english3e/dictionaries.html" rel="nofollow">dictionary</a> would make more sense.</p>
<pre><code>qualification_levels = ('AP', 'FQ')
print("\n""\"AP\" = Apprentice",
"\n\"FQ\" = Fully-Qualified")
user_qual = input("Enter you Qualification Level: ")
if user_qual in qualification_levels:
print('correct!')
else:
print('ERROR!!!')
</code></pre>
| 0 |
2016-09-15T19:40:31Z
|
[
"python",
"python-3.x"
] |
How to print info when 2 things are correct and to use the input fuction when the those two things are incorrect
| 39,518,960 |
<p>I am doing a controlled assessment. I have this code : </p>
<pre><code># user Qualifications
print("\nQualification Level")
print("\n""\"AP\" = Apprentice",
"\n\"FQ\" = Fully-Qualified")
user_qual = input("Enter you Qualification Level: ")
</code></pre>
<p>When the <code>user_qual</code> is equal to <code>AP</code> or <code>FQ</code> I want to print "correct". But when the <code>user_qual</code> is not equal to either <code>AP</code> or <code>FQ</code>, I want to print an error message and re-ask the <code>user_qual</code> input question. However, I tried many different ways but couldn't do it.</p>
<p>Please just give a simple solution and nothing complicated. I am just a beginner and learning the basics.</p>
| 0 |
2016-09-15T19:31:56Z
| 39,519,154 |
<p>You need to turn your code into a function so it can be called again, if the criteria are not met:</p>
<pre><code>def prompt():
# user Qualifications
print('\nQualification Level')
print('\n"AP" = Apprentice\n"FQ" = Fully-Qualified')
user_qual = input('Enter you Qualification Level: ')
if user_qual not in ('AP','FQ'):
prompt() # Criteria not met, so ask again
print('Correct!') # Criteria met, don't ask again
# Call the function the first time
prompt()
</code></pre>
<p>As @IanAuld mentions in the comments, if you want to allow users to provide the answer (ie. AP) in a case insensitive manner (so users can type 'ap' instead), you would want to convert the case before evaluating it, like so:</p>
<pre><code>if user_qual.upper() not in ('AP','FQ'):
...rest of code...
</code></pre>
| 0 |
2016-09-15T19:43:18Z
|
[
"python",
"python-3.x"
] |
When trying to install lxml in python, get error ftp error 200 type set to I
| 39,518,975 |
<p>These are the specific error message i got when trying to install lxml in python. I have installed C++ 9.0. Can anyone tell how to fix it? Thanks a lot.</p>
<p>C:\Python27\Scripts></p>
<pre><code>pip install lxml
Collecting lxml
Using cached lxml-3.6.4.tar.gz
Complete output from command python setup.py egg_info:
Building lxml version 3.6.4.
Retrieving "ftp://ftp.zlatkovic.com/pub/libxml/libxslt- 1.1.26.win32.zip" to
"libs\libxslt-1.1.26.win32.zip"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "c:\users\apple\appdata\local\temp\pip-build-difyii\lxml\setup.py", line 233, in <module>
**setup_extra_options()
File "c:\users\apple\appdata\local\temp\pip-build-difyii\lxml\setup.py", line 144, in setup_extra_options
STATIC_CFLAGS, STATIC_BINARIES)
File "setupinfo.py", line 55, in ext_modules
OPTION_DOWNLOAD_DIR, static_include_dirs, static_library_dirs)
File "buildlibxml.py", line 95, in get_prebuilt_libxml2xslt
libs = download_and_extract_zlatkovic_binaries(download_dir)
File "buildlibxml.py", line 55, in download_and_extract_zlatkovic_binaries
urlretrieve(srcfile, destfile)
File "c:\python27\lib\urllib.py", line 98, in urlretrieve
return opener.retrieve(url, filename, reporthook, data)
File "c:\python27\lib\urllib.py", line 245, in retrieve
fp = self.open(url, data)
File "c:\python27\lib\urllib.py", line 213, in open
return getattr(self, name)(url)
File "c:\python27\lib\urllib.py", line 558, in open_ftp
(fp, retrlen) = self.ftpcache[key].retrfile(file, type)
File "c:\python27\lib\urllib.py", line 906, in retrfile
conn, retrlen = self.ftp.ntransfercmd(cmd)
File "c:\python27\lib\ftplib.py", line 334, in ntransfercmd
host, port = self.makepasv()
File "c:\python27\lib\ftplib.py", line 312, in makepasv
host, port = parse227(self.sendcmd('PASV'))
File "c:\python27\lib\ftplib.py", line 830, in parse227
raise error_reply, resp
IOError: [Errno ftp error] 200 Type set to I
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\users\apple\appdata\local\temp\pip-build-difyii\lxml\
</code></pre>
| 0 |
2016-09-15T19:32:54Z
| 39,900,926 |
<p>Add </p>
<p>urlcleanup() </p>
<p>before </p>
<p>File "buildlibxml.py", line 55, in download_and_extract_zlatkovic_binaries</p>
<pre><code> urlretrieve(srcfile, destfile)
</code></pre>
<p><a href="http://stackoverflow.com/a/39900735/6932850">See Here</a></p>
| 0 |
2016-10-06T16:12:43Z
|
[
"python",
"ftp",
"lxml"
] |
From django rest framework 3 pre_save, pre_delete is not available than how to manipulate and insert requested user name in any field?
| 39,519,019 |
<p>I am using django rest framework. I want to insert request user name in the author field of posts. But I cannot manipulate the data before saving as the pre_save method is depreciated from drf 3 <a href="http://www.django-rest-framework.org/api-guide/generic-views/" rel="nofollow">drf generic view</a>. </p>
<pre><code>class SpoterMixin(object):
def create(self, request, *args, **kwargs):
data = request.data
data['author'] = request.user.id
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
data = request.data
data['author'] = request.user.id # here I am manipulating and inserting the requested user
serializer = self.get_serializer(instance,data=data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
class SpotViewSet(UserRequestMixin,viewsets.ModelViewSet):
queryset = PostModel.objects.all()
serializer_class = SpotSerializer
</code></pre>
<p>Is there a more efficient way of doing this as if I trying to implement all the views likes this that would increase a lot of boilerplate code.</p>
<p>So is there any alternative for the pre_save method.</p>
| 0 |
2016-09-15T19:35:40Z
| 39,519,097 |
<p>You can use <code>perfom_create</code> and <code>perform_update</code> in your views </p>
<blockquote>
<p>The pre_save and post_save hooks no longer exist, but are replaced
with perform_create(self, serializer) and perform_update(self,
serializer).</p>
<p>These methods should save the object instance by calling
serializer.save(), adding in any additional arguments as required.
They may also perform any custom pre-save or post-save behavior.</p>
</blockquote>
<p>Example</p>
<pre><code>def perform_create(self, serializer):
# Include the owner attribute directly, rather than from request data.
instance = serializer.save(owner=self.request.user)
# Perform a custom post-save action.
send_email(instance.to_email, instance.message)
</code></pre>
| 0 |
2016-09-15T19:40:21Z
|
[
"python",
"django",
"rest",
"python-3.x",
"django-rest-framework"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.