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 |
---|---|---|---|---|---|---|---|---|---|
Fixing return format for my function | 39,945,808 | <p>The code for my function works correctly, but it is not returning the function in the format I would like. The function counts seed values in a 2nd sequence and then is supposed to return the seed counts as a list of integers. It is returning the seed counts but on separate lines rather then in a list. Here is my code and what its returning in command prompt.</p>
<pre><code> def count_each(seeds,xs):
for c in seeds:
count=0
for d in xs:
if c==d:
count=count+1
print ([count])
</code></pre>
<p>count_each([10,20],[10,20,30,10])</p>
<p>count_each([4,8],[1,2,4,4,4,8,8,10])</p>
<p>In command prompt, I would like this function to print [2,1] for count_each([10,20],[10,20,30,10]) and [3,2] for count_each([4,8],[1,2,4,4,4,8,8,10]) but instead it is printing each seed value on its own line like so </p>
<p><a href="http://i.stack.imgur.com/vXAd3.png" rel="nofollow">http://i.stack.imgur.com/vXAd3.png</a></p>
<p>In the picture above it prints [2], [1], [3], and [2] on separate lines when it should instead print just two lines of [2,1] and [3,2] for the two sequences. How can I have the function return the seed values for each sequence as a list instead of having the values on separate lines.</p>
<p>Edit: I need to accomplish this without importing from other modules and with the simplest code possible.</p>
| 1 | 2016-10-09T16:23:02Z | 39,946,076 | <p>You are almost done, but if you want to print the output in a list you must first create list.Here try this:</p>
<pre><code>def count_each(seeds,xs):
output = []
for c in seeds:
count=0
for d in xs:
if c==d:
count=count+1
output.append(count)
print (output)
</code></pre>
| 2 | 2016-10-09T16:51:34Z | [
"python",
"list",
"format",
"sequence"
] |
No Output from checkboxes in Python | 39,945,848 | <p>I'm a newbie to Python and this forum. So I'll try to explain my issue the best I can.<br>
I'm trying to get the results of check boxes to appear along with their corresponding data from fields in an SQLite database. I get in my code if I simply have "print selectedbooks" I get the checkbox results but in order to get the corresponding data from the other fields fields I have the following code. I'm not sure what I'm doing wrong. My code is below. Everything inside the "for" loop will not print</p>
<pre><code>import sys, cgi, cgitb, sqlite3
# Create instance of FieldStorage
form = cgi.FieldStorage()
conn = sqlite3.connect('battleofthebooks.db')
c = conn.cursor()
value = form.getlist('selectedbook')
selectedbook = "<br/><br />".join(sorted(value))
print "Content-Type: text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Battle of the Books</title>"
print "</head>"
print "<body>"
print "<h3>You have chosen the following books:</h3>"
print selectedbook
TITLE = ""
for row in c.execute("SELECT * FROM BOBBOOKLIST where TITLE=(?)", (TITLE, )):
print selectedbook
print row[2]
print "<br />"
print row[3]
print "<br />"
print "Books in Stock: ", row[4]
print "<br />"
</code></pre>
| 0 | 2016-10-09T16:26:46Z | 39,948,579 | <p>Ahh the faithful c.execute operation. Ok. Give the print of </p>
<pre><code>print c.execute("SELECT * FROM BOBBOOKLIST where TITLE=(?)", (TITLE, ))
</code></pre>
<p>then you would be knowing the answer. When c.execute is triggered, the data is new and the cursor is no longer valid to the old one.
You could always store the value of c.execute to a variable, then iterate the variable in the for loop.</p>
| 0 | 2016-10-09T21:11:13Z | [
"python",
"forms",
"variables",
"for-loop",
"cgi"
] |
Caesar Cipher Program | 39,946,000 | <pre><code>def caesar_cipher(message):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
newmessage = ""
for letter in message:
if letter in alphabet:
positionnumber = alphabet.index(letter) + 13
position = positionnumber % 26
newmessage += alphabet[position]
else:
newmessage += letter
print(newmessage)
</code></pre>
<p>How can I get this to change capitals as well?</p>
| -1 | 2016-10-09T16:44:50Z | 39,946,690 | <pre><code>def caesar_cipher(message):
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
newmessage = ""
for letter in message:
if letter in alphabet:
positionnumber = alphabet.index(letter) + 13
position = positionnumber % 26
newmessage += alphabet[position]
elif letter.isupper():
positionnumber = alphabet.index(letter.lower()) + 13
position = positionnumber % 26
newmessage += alphabet[position].upper()
print(newmessage)
</code></pre>
<p>Use <code>isupper()</code> to identify capital letters</p>
| 0 | 2016-10-09T17:52:40Z | [
"python"
] |
Caesar Cipher Program | 39,946,000 | <pre><code>def caesar_cipher(message):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
newmessage = ""
for letter in message:
if letter in alphabet:
positionnumber = alphabet.index(letter) + 13
position = positionnumber % 26
newmessage += alphabet[position]
else:
newmessage += letter
print(newmessage)
</code></pre>
<p>How can I get this to change capitals as well?</p>
| -1 | 2016-10-09T16:44:50Z | 39,946,718 | <p>This can be done very efficiently using the <code>ord</code> function. It gives you the ASCII value of a character. Regardless of how you define the alphabet, you simply do separate ciphers for uppercase and lowercase.</p>
<pre><code>def rot13(char):
"""
Calculate the ROT13 substitute for `char`
:param char: The character to substitute
:type char: str
:returns: The substitute
:rtype: str
"""
if ord('a') <= ord(char) <= ord('z'): # lowercase
return chr((ord(char) - ord('a') + 13) % 26 + ord('a'))
elif ord('A') <= ord(char) <= ord('Z'): # uppercase
return chr((ord(char) - ord('A') + 13) % 26 + ord('A'))
raise ValueError('Not an ASCII letter: %r' % char)
def caesar_cipher(message):
return ''.join(rot13(char) for char in message)
</code></pre>
| 0 | 2016-10-09T17:55:19Z | [
"python"
] |
how can we define (1,2,3,4,5,6,7,8,9) so *args take 1,2,3,7,8 | 39,946,043 | <p>Suppose we have a function with variable length parameter but i want some specific values to taken by variable length parameter ??</p>
<p>example :</p>
<pre><code>def hello(a,*args,b=10):
pass
hello(1,2,3,4,5,6,7,8,9)
</code></pre>
<blockquote>
<p>how can we define (1,2,3,4,5,6,7,8,9) so *args take 1,2,3,7,8 ?? other values can be taken by a or b or you can add more parameters to take remaining values i just want that *args should take only 1,2,3,7,8 remaining taken by other parameters.</p>
</blockquote>
| -2 | 2016-10-09T16:49:01Z | 39,946,128 | <p>If you want <code>*args</code> to be the 1st, 2nd, 3rd, 7th and 8th argument, you should make the function just take <code>*args</code> and then make the other args into a seperate variable.</p>
<pre><code>def hello(*args, b=10):
other_args = args[3:6] + args[8:] # Takes the fourth, fifth, sixth and ninth and onward
args = args[:3] + args[6:8] # Takes first, second, third, seventh and eighth args
hello(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, b=11)
# -> args == (1, 2, 3, 7, 8)
# other_args == (4, 5, 9, 10)
# b == 11
</code></pre>
| 0 | 2016-10-09T16:58:31Z | [
"python",
"python-2.7",
"python-3.x"
] |
Chained Conditions that require order to not produce order | 39,946,049 | <p>Whenever I <strong>chain conditions</strong> in Python (or any other language tbh) I stumble upon asking myself this, kicking me out of the productive "Zone".
When I chain conditions I can, by ordering them correctly, check conditions that without checking for the other conditions first, may produce an Error.</p>
<p>As an example lets assume the following snippet:</p>
<pre class="lang-py prettyprint-override"><code>if "attr" in some_dictionary and some_value in some_dictionary["attr"]:
print("whooohooo")
</code></pre>
<p>If the first condition wasnt in the first place or even absent, the second condition my produce an <code>KeyError</code></p>
<p>I do this pretty often to simply save space in the code, but I always wondered, if this is good style, if it comes with a risk or if its simply "pythonic".</p>
| 0 | 2016-10-09T16:49:25Z | 39,946,106 | <p>A more Pythonic way is to "ask for forgivness rather than permission". In other words, use a try-except block:</p>
<pre><code>try:
if some_value in some_dictionary["attr"]:
print("Woohoo")
except KeyError:
pass
</code></pre>
| 2 | 2016-10-09T16:55:03Z | [
"python",
"condition",
"keyerror"
] |
Chained Conditions that require order to not produce order | 39,946,049 | <p>Whenever I <strong>chain conditions</strong> in Python (or any other language tbh) I stumble upon asking myself this, kicking me out of the productive "Zone".
When I chain conditions I can, by ordering them correctly, check conditions that without checking for the other conditions first, may produce an Error.</p>
<p>As an example lets assume the following snippet:</p>
<pre class="lang-py prettyprint-override"><code>if "attr" in some_dictionary and some_value in some_dictionary["attr"]:
print("whooohooo")
</code></pre>
<p>If the first condition wasnt in the first place or even absent, the second condition my produce an <code>KeyError</code></p>
<p>I do this pretty often to simply save space in the code, but I always wondered, if this is good style, if it comes with a risk or if its simply "pythonic".</p>
| 0 | 2016-10-09T16:49:25Z | 39,946,630 | <p>Python is a late binding language, which is reflected in these kind of checks. The behavior is called <a href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not" rel="nofollow">short-circuiting</a>. One thing I often do is:</p>
<pre><code>def do(condition_check=None):
if condition_check is not None and condition_check():
# do stuff
</code></pre>
<p>Now, many people will argue that <code>try: except:</code> is more appropriate. This really depends on the use case!</p>
<ul>
<li><code>if</code> expressions are faster when the check is likely to fail, so use them when you know what is happening.</li>
<li><code>try</code> expressions are faster when the check is likely to succeed, so use them to safeguard against exceptional circumstances.</li>
<li><code>if</code> is explicit, so you know precisely what you are checking. Use it if you know what is happening, i.e. strongly typed situations.</li>
<li><code>try</code> is implicit, so you only have to care about the outcome of a call. Use it when you don't care about the details, i.e. in weakly typed situations.</li>
<li><code>if</code> works in a well-defined scope - namely right where you are performing the check. Use it for nested relations, where you want to check the top-most one.</li>
<li><code>try</code> works on the entire contained call stack - an exception may be thrown several function calls deeper. Use it for flat or well-defined calls.</li>
</ul>
<p>Basically, <code>if</code> is a precision tool, while <code>try</code> is a hammer - sometimes you need precision, and sometimes you just have nails.</p>
| 1 | 2016-10-09T17:47:29Z | [
"python",
"condition",
"keyerror"
] |
How to coroutine IPython <-> a callback() | 39,946,052 | <p>In an IPython terminal, I want a function deep in <code>main()</code>
to go back to IPython, where I can print, set ... as usual, then keep running <code>main()</code>:</p>
<pre><code>IPython
run main.py
...
def callback( *args ):
...
try:
back_to_ipython() # <-- how to do this ?
In[]: print, set *args ...
...
except KeyboardInterrupt: # or IPython magic
pass
return # from callback(), keep running main()
</code></pre>
<p>This must run in python2.</p>
<p>(The name <code>callback</code> could be <code>anything</code>, but my use case is scipy.optimize -> callback.
Perhaps some clever scipy person has done this ?)</p>
<p><hr>
Added Tuesday 11 Oct: thanks for <code>embed</code>,
but it seems to run into a bug, or my misunderstanding:</p>
<pre><code># http://stackoverflow.com/questions/39946052/how-to-coroutine-ipython-a-callback
import sys
from IPython import __version__
from IPython import embed # $site/IPython/terminal/embed.py
from IPython.terminal.ipapp import load_default_config
print "versions: IPython %s python %s" % (
__version__, sys.version.split()[0] )
def pdict( header, adict ):
print header
for k, v in sorted( adict.items() ):
print "%s\t: %s" % (k, v)
config = load_default_config()
pdict( "load_default_config:", config )
aglobal = [3]
#...............................................................................
def callback( adict ):
# pdict( "callback:", adict )
t = adict["t"]
x = 3
embed( header="callback: t %d" % t )
# interact: print t x ...
# ^D / EOF
return
def aloop( *args ):
for t in range( 3 ):
callback( locals() )
aloop( 1, 2, 3 ) # works in "run this.py"
# but typing "aloop()" in an IPython terminal ->
# embed.py:218: UserWarning: Failed to get module unknown module
# global_ns.get('__name__', 'unknown module')
</code></pre>
| 0 | 2016-10-09T16:49:35Z | 39,946,229 | <p>You could insert a breakpoint, which would give similar outcome:</p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p><a href="https://docs.python.org/3.6/library/pdb.html" rel="nofollow">https://docs.python.org/3.6/library/pdb.html</a></p>
<p>Alternative here (<code>embed()</code> function within iPython):
<a href="http://stackoverflow.com/questions/16867347/step-by-step-debugging-with-ipython">Step-by-step debugging with IPython</a></p>
| 0 | 2016-10-09T17:07:26Z | [
"python",
"scipy",
"ipython",
"coroutine"
] |
How to coroutine IPython <-> a callback() | 39,946,052 | <p>In an IPython terminal, I want a function deep in <code>main()</code>
to go back to IPython, where I can print, set ... as usual, then keep running <code>main()</code>:</p>
<pre><code>IPython
run main.py
...
def callback( *args ):
...
try:
back_to_ipython() # <-- how to do this ?
In[]: print, set *args ...
...
except KeyboardInterrupt: # or IPython magic
pass
return # from callback(), keep running main()
</code></pre>
<p>This must run in python2.</p>
<p>(The name <code>callback</code> could be <code>anything</code>, but my use case is scipy.optimize -> callback.
Perhaps some clever scipy person has done this ?)</p>
<p><hr>
Added Tuesday 11 Oct: thanks for <code>embed</code>,
but it seems to run into a bug, or my misunderstanding:</p>
<pre><code># http://stackoverflow.com/questions/39946052/how-to-coroutine-ipython-a-callback
import sys
from IPython import __version__
from IPython import embed # $site/IPython/terminal/embed.py
from IPython.terminal.ipapp import load_default_config
print "versions: IPython %s python %s" % (
__version__, sys.version.split()[0] )
def pdict( header, adict ):
print header
for k, v in sorted( adict.items() ):
print "%s\t: %s" % (k, v)
config = load_default_config()
pdict( "load_default_config:", config )
aglobal = [3]
#...............................................................................
def callback( adict ):
# pdict( "callback:", adict )
t = adict["t"]
x = 3
embed( header="callback: t %d" % t )
# interact: print t x ...
# ^D / EOF
return
def aloop( *args ):
for t in range( 3 ):
callback( locals() )
aloop( 1, 2, 3 ) # works in "run this.py"
# but typing "aloop()" in an IPython terminal ->
# embed.py:218: UserWarning: Failed to get module unknown module
# global_ns.get('__name__', 'unknown module')
</code></pre>
| 0 | 2016-10-09T16:49:35Z | 39,947,930 | <p>Adapting the answer in <a href="http://stackoverflow.com/a/24827245/901925">http://stackoverflow.com/a/24827245/901925</a>, I added an Ipython <code>embed</code> (<a href="https://ipython.org/ipython-doc/3/api/generated/IPython.terminal.embed.html" rel="nofollow">https://ipython.org/ipython-doc/3/api/generated/IPython.terminal.embed.html</a>)</p>
<pre><code>import numpy as np
from scipy.optimize import minimize, rosen
import time
import warnings
from IPython import embed
class TookTooLong(Warning):
pass
class MinimizeStopper(object):
def __init__(self, max_sec=60):
self.max_sec = max_sec
self.start = time.time()
def __call__(self, xk=None):
elapsed = time.time() - self.start
if elapsed > self.max_sec:
embed(header='FirstTime')
warnings.warn("Terminating optimization: time limit reached",
TookTooLong)
else:
# you might want to report other stuff here
print("Elapsed: %.3f sec" % elapsed)
# example usage
x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
res = minimize(rosen, x0, method='Nelder-Mead', callback=MinimizeStopper(1E-3))
</code></pre>
<p>with a run like:</p>
<pre><code>1251:~/mypy$ python3 stack39946052.py
Elapsed: 0.001 sec
Python 3.5.2 (default, Jul 5 2016, 12:43:10)
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
FirstTime
In [1]: xk
Out[1]: array([ 1.339, 0.721, 0.824, 1.71 , 1.236])
In [2]: elapsed
Out[2]: 0.0010917186737060547
In [3]: self.max_sec
Out[3]: 0.001
In [4]: self.max_sec=1000
In [5]:
Do you really want to exit ([y]/n)? y
stack39946052.py:20: TookTooLong: Terminating optimization: time limit reached
TookTooLong)
....
</code></pre>
| 0 | 2016-10-09T19:57:34Z | [
"python",
"scipy",
"ipython",
"coroutine"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.</p>
<p>I tried the following code but they don't work:</p>
<pre><code> >>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
<p>Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.</p>
<p>I also tried using a <code>map()</code> function but I just got the same results:</p>
<pre><code>>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
| 4 | 2016-10-09T16:53:05Z | 39,946,300 | <p>Totally silly of course, but for fun:</p>
<pre><code>s = '34 3 542 11'
n = ""; total = 0
for c in s:
if c == " ":
total = total + int(n)
n = ""
else:
n = n + c
# add the last number
total = total + int(n)
print(total)
> 590
</code></pre>
<p>This assumes all characters (apart from whitespaces) are figures.</p>
| 5 | 2016-10-09T17:13:39Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.</p>
<p>I tried the following code but they don't work:</p>
<pre><code> >>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
<p>Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.</p>
<p>I also tried using a <code>map()</code> function but I just got the same results:</p>
<pre><code>>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
| 4 | 2016-10-09T16:53:05Z | 39,946,311 | <p>You've definitely put some effort in here, but one part of your approach definitely won't work as-is: you're iterating over the <em>characters</em> in the string, but you keep trying to treat each character as its own number. I've written a (very commented) method that accomplishes what you want without using any lists or list methods:</p>
<pre><code>def sum_numbers(s):
"""
Convert a string of numbers into a sum of those numbers.
:param s: A string of numbers, e.g. '1 -2 3.3 4e10'.
:return: The floating-point sum of the numbers in the string.
"""
def convert_s_to_val(s):
"""
Convert a string into a number. Will handle anything that
Python could convert to a float.
:param s: A number as a string, e.g. '123' or '8.3e-18'.
:return: The float value of the string.
"""
if s:
return float(s)
else:
return 0
# These will serve as placeholders.
sum = 0
current = ''
# Iterate over the string character by character.
for c in s:
# If the character is a space, we convert the current `current`
# into its numeric representation.
if c.isspace():
sum += convert_s_to_val(current)
current = ''
# For anything else, we accumulate into `current`.
else:
current = current + c
# Add `current`'s last value to the sum and return.
sum += convert_s_to_val(current)
return sum
</code></pre>
<hr>
<p>Personally, I would use this one-liner, but it uses <code>str.split()</code>:</p>
<pre><code>def sum_numbers(s):
return sum(map(float, s.split()))
</code></pre>
| 2 | 2016-10-09T17:14:56Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.</p>
<p>I tried the following code but they don't work:</p>
<pre><code> >>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
<p>Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.</p>
<p>I also tried using a <code>map()</code> function but I just got the same results:</p>
<pre><code>>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
| 4 | 2016-10-09T16:53:05Z | 39,946,356 | <p>Try this:</p>
<pre><code>def sum_numbers(s):
sum = 0
#This string will represent each number
number_str = ''
for i in s:
if i == ' ':
#if it is a whitespace it means
#that we have a number so we incease the sum
sum += int(number_str)
number_str = ''
continue
number_str += i
else:
#add the last number
sum += int(number_str)
return sum
</code></pre>
| 0 | 2016-10-09T17:18:55Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.</p>
<p>I tried the following code but they don't work:</p>
<pre><code> >>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
<p>Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.</p>
<p>I also tried using a <code>map()</code> function but I just got the same results:</p>
<pre><code>>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
| 4 | 2016-10-09T16:53:05Z | 39,946,415 | <p>No lists were used (nor harmed) in the production of this answer:</p>
<pre><code>def sum_string(string):
total = 0
if len(string):
j = string.find(" ") % len(string) + 1
total += int(string[:j]) + sum_string(string[j:])
return total
</code></pre>
<p>If the string is noisier than the OP indicates, then this should be more robust:</p>
<pre><code>import re
def sum_string(string):
pattern = re.compile(r"[-+]?\d+")
total = 0
match = pattern.search(string)
while match:
total += int(match.group())
match = pattern.search(string, match.end())
return total
</code></pre>
<p><strong>EXAMPLES</strong></p>
<pre><code>>>> sum_string('34 3 542 11')
590
>>> sum_string(' 34 4 ')
38
>>> sum_string('lksdjfa34adslkfja4adklfja')
38
>>> # and I threw in signs for fun
...
>>> sum_string('34 -2 45 -8 13')
82
>>>
</code></pre>
| 1 | 2016-10-09T17:25:24Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.</p>
<p>I tried the following code but they don't work:</p>
<pre><code> >>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
<p>Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.</p>
<p>I also tried using a <code>map()</code> function but I just got the same results:</p>
<pre><code>>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
| 4 | 2016-10-09T16:53:05Z | 39,946,519 | <p>You could write a generator:</p>
<pre><code>def nums(s):
idx=0
while idx<len(s):
ns=''
while idx<len(s) and s[idx].isdigit():
ns+=s[idx]
idx+=1
yield int(ns)
while idx<len(s) and not s[idx].isdigit():
idx+=1
>>> list(nums('34 3 542 11'))
[34, 3, 542, 11]
</code></pre>
<p>Then just sum that:</p>
<pre><code>>>> sum(nums('34 3 542 11'))
590
</code></pre>
<p>or, you could use <code>re.finditer</code> with a regular expression and a generator construction:</p>
<pre><code>>>> sum(int(m.group(1)) for m in re.finditer(r'(\d+)', '34 3 542 11'))
590
</code></pre>
<p>No lists used...</p>
| 0 | 2016-10-09T17:36:33Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.</p>
<p>I tried the following code but they don't work:</p>
<pre><code> >>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
<p>Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.</p>
<p>I also tried using a <code>map()</code> function but I just got the same results:</p>
<pre><code>>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
| 4 | 2016-10-09T16:53:05Z | 39,946,554 | <pre><code>def sum_numbers(s):
total=0
gt=0 #grand total
l=len(s)
for i in range(l):
if(s[i]!=' '):#find each number
total = int(s[i])+total*10
if(s[i]==' ' or i==l-1):#adding to the grand total and also add the last number
gt+=total
total=0
return gt
print(sum_numbers('1 2 3'))
</code></pre>
<p>Here each substring is converted to number and added to grant total</p>
| 0 | 2016-10-09T17:39:26Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.</p>
<p>I tried the following code but they don't work:</p>
<pre><code> >>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
<p>Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.</p>
<p>I also tried using a <code>map()</code> function but I just got the same results:</p>
<pre><code>>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
| 4 | 2016-10-09T16:53:05Z | 39,996,547 | <p>If you want to be able to handle floats and negative numbers:</p>
<pre><code>def sum_numbers(s):
sm = i = 0
while i < len(s):
t = ""
while i < len(s) and not s[i].isspace():
t += s[i]
i += 1
if t:
sm += float(t)
else:
i += 1
return sm
</code></pre>
<p>Which will work for all cases:</p>
<pre><code>In [9]: sum_numbers('34 3 542 11')
Out[9]: 590.0
In [10]: sum_numbers('1.93 -1 23.12 11')
Out[10]: 35.05
In [11]: sum_numbers('')
Out[11]: 0
In [12]: sum_numbers('123456')
Out[12]: 123456.0
</code></pre>
<p>Or a variation taking slices:</p>
<pre><code>def sum_numbers(s):
prev = sm = i = 0
while i < len(s):
while i < len(s) and not s[i].isspace():
i += 1
if i > prev:
sm += float(s[prev:i])
prev = i
i += 1
return sm
</code></pre>
<p>You could also use <em>itertools.groupby</em> which uses no lists, using a set of allowed chars to group by:</p>
<pre><code>from itertools import groupby
def sum_numbers(s):
allowed = set("0123456789-.")
return sum(float("".join(v)) for k,v in groupby(s, key=allowed.__contains__) if k)
</code></pre>
<p>which gives you the same output:</p>
<pre><code>In [14]: sum_numbers('34 3 542 11')
Out[14]: 590.0
In [15]: sum_numbers('1.93 -1 23.12 11')
Out[15]: 35.05
In [16]: sum_numbers('')
Out[16]: 0
In [17]: sum_numbers('123456')
Out[17]: 123456.0
</code></pre>
<p>Which if you only have to consider positive ints could just use <em>str.isdigit</em> as the key:</p>
<pre><code>def sum_numbers(s):
return sum(int("".join(v)) for k,v in groupby(s, key=str.isdigit) if k)
</code></pre>
| 1 | 2016-10-12T10:39:59Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.</p>
<p>I tried the following code but they don't work:</p>
<pre><code> >>> def sum_numbers(s):
for i in range(len(s)):
int(i)
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
<p>Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.</p>
<p>I also tried using a <code>map()</code> function but I just got the same results:</p>
<pre><code>>>> def sum_numbers(s):
for i in range(len(s)):
map(int, s[i])
total = s[i] + s[i]
return total
>>> sum_numbers('1 2 3')
'11'
</code></pre>
| 4 | 2016-10-09T16:53:05Z | 40,029,760 | <p>If we omit the fact <a href="https://docs.python.org/3/library/functions.html#eval" rel="nofollow"><code>eval</code></a> is <a href="http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice">evil</a>, we can solve that problem with it.</p>
<pre><code>def sum_numbers(s):
s = s.replace(' ', '+')
return eval(s)
</code></pre>
<p>Yes, that simple. But i won't put that thing in production.</p>
<p>And sure we need to test that:</p>
<pre><code>from hypothesis import given
import hypothesis.strategies as st
@given(list_num=st.lists(st.integers(), min_size=1))
def test_that_thing(list_num):
assert sum_numbers(' '.join(str(i) for i in list_num)) == sum(list_num)
test_that_thing()
</code></pre>
<p>And it would raise nothing.</p>
| 0 | 2016-10-13T19:51:49Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
Setting up Environment Variable for GCP | 39,946,130 | <p>I read <a href="https://developers.google.com/identity/protocols/application-default-credentials" rel="nofollow">this</a> article but I still don't understand how I have to set up the environment variable with the <code>.json</code> file with the credentials. Do I have to enter something in the Terminal or write something in my Python code?</p>
<p>Also, is the path relative to the user directory? Thanks</p>
| 0 | 2016-10-09T16:58:50Z | 39,967,090 | <p>You can do either: the key part is that the environmental variable must be present for the SDK to pick up in the code that you're running. You could set it programmatically in Python (<a href="http://stackoverflow.com/questions/5971312/how-to-set-environment-variables-in-python">example</a>) or in your terminal (<a href="http://stackoverflow.com/questions/234742/setting-environment-variables-in-linux-using-bash">example</a>), depending on what you want to do. You just need the process that's executing your code to have the variable set in <em>its</em> environment.</p>
<p>Use an absolute path.</p>
| 0 | 2016-10-10T21:33:31Z | [
"python",
"environment-variables",
"google-cloud-platform"
] |
Using python-docx to batch print the name of the last user to modify | 39,946,249 | <p>I'm trying to use Python to print the names of the last users to modify a bunch of documents (docx). In reality, this script should return a bunch of different names. I'm having to mix a bunch of different modules, but either I'm doing something wrong, or docx doesn't like the batch work. Has anybody got more experience with this that might be able to find the issue?</p>
<pre><code>from docx import Document
import docx, glob, os
for filename in glob.glob('/Users/owner/Desktop/Rename/*.docx'):
fullfilename=os.path.abspath(filename)
document = Document('fullfilename')
core_properties = document.core_properties
print(core_properties.last_modified_by)
</code></pre>
<p>For reference, I've merged two scripts for this, and docx seemed to work well when it was one file at a time, is there something going wrong with my loop?:</p>
<pre><code>from docx import Document
import docx
document = Document('mine.docx')
core_properties = document.core_properties
print(core_properties.last_modified_by)
</code></pre>
<p>I'm using Python 3.4 and docx 0.8.6</p>
| 0 | 2016-10-09T17:09:03Z | 39,947,778 | <p>The main problem seems to be a lack of indenting. Python uses indentation (instead of curly braces) to determine what the block of your loop should be. So in this case it's only running through once. What you need is this:</p>
<pre><code>import glob, os
from docx import Document
for filename in glob.glob('/Users/owner/Desktop/Rename/*.docx'):
fullfilename = os.path.abspath(filename)
document = Document('fullfilename')
core_properties = document.core_properties
print(core_properties.last_modified_by)
</code></pre>
<p>Note there is no need to import <code>docx</code>, since you don't use it (directly). In general, the <code>Document</code> object is all that needs importing in python-docx projects.</p>
| 0 | 2016-10-09T19:40:47Z | [
"python",
"ms-office",
"batch-processing",
"python-docx"
] |
tkinter won't quit when I press quit button, it just changes location | 39,946,260 | <p>This is the code and when I run it the quit button doesn't work:</p>
<pre class="lang-py prettyprint-override"><code>def quit2():
menu.destroy()
def menu1():
menu=Tk()
global menu
play=Button(menu, text='play', command =main)
play.pack()
quit1=Button(menu, text='quit', command=quit2)
quit1.pack()
menu.mainloop()
while True:
menu1()
</code></pre>
| -2 | 2016-10-09T17:10:14Z | 39,946,355 | <p>You use <code>while True</code> so after you close window <code>while True</code> opens new window.</p>
<p>Use last line <code>menu1()</code> without <code>while True</code></p>
<p><strong>EDIT:</strong></p>
<pre><code>from tkinter import *
def quit2():
menu.destroy()
def menu1():
global menu
menu = Tk()
play = Button(menu, text='play', command=main)
play.pack()
quit1 = Button(menu, text='quit', command=quit2)
quit1.pack()
menu.mainloop()
#without `while True`
menu1()
</code></pre>
| 1 | 2016-10-09T17:18:51Z | [
"python",
"tkinter"
] |
Problems while calling NLTK with Python 3.5.2_2? | 39,946,273 | <p>When I try to import nltk in python 3.5.2_2 I get the following message:</p>
<pre><code>>>> import nltk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/nltk/__init__.py", line 117, in <module>
from nltk.align import *
File "/usr/local/lib/python3.5/site-packages/nltk/align/__init__.py", line 15, in <module>
from nltk.align.ibm1 import IBMModel1
File "/usr/local/lib/python3.5/site-packages/nltk/align/ibm1.py", line 18, in <module>
from nltk.corpus import comtrans
File "/usr/local/lib/python3.5/site-packages/nltk/corpus/__init__.py", line 64, in <module>
from nltk.tokenize import RegexpTokenizer
File "/usr/local/lib/python3.5/site-packages/nltk/tokenize/__init__.py", line 65, in <module>
from nltk.tokenize.regexp import (RegexpTokenizer, WhitespaceTokenizer,
File "/usr/local/lib/python3.5/site-packages/nltk/tokenize/regexp.py", line 201, in <module>
blankline_tokenize = BlanklineTokenizer().tokenize
File "/usr/local/lib/python3.5/site-packages/nltk/tokenize/regexp.py", line 172, in __init__
RegexpTokenizer.__init__(self, r'\s*\n\s*\n\s*', gaps=True)
File "/usr/local/lib/python3.5/site-packages/nltk/tokenize/regexp.py", line 119, in __init__
self._regexp = compile_regexp_to_noncapturing(pattern, flags)
File "/usr/local/lib/python3.5/site-packages/nltk/internals.py", line 54, in compile_regexp_to_noncapturing
return sre_compile.compile(convert_regexp_to_noncapturing_parsed(sre_parse.parse(pattern)), flags=flags)
File "/usr/local/lib/python3.5/site-packages/nltk/internals.py", line 50, in convert_regexp_to_noncapturing_parsed
parsed_pattern.pattern.groups = 1
AttributeError: can't set attribute
</code></pre>
<p>I tried to reinstall it with pip3 and I am still having the same issue... Any idea of how to correctly install NLTK in OSX?, and how to solve this issue?.</p>
| 0 | 2016-10-09T17:11:01Z | 39,946,966 | <p>This might work</p>
<ol>
<li>Go to <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></li>
<li>Download nltk-3.2.1-py2.py3-none-any.whl </li>
<li>Change folder in command line to where you downloaded that whl file</li>
<li>Now write <code>C:/windows/python35/scripts/pip install nltk-3.2.1-py2.py3-none-any.whl</code></li>
</ol>
<p>And of course change those paths if they dont match</p>
| 0 | 2016-10-09T18:19:10Z | [
"python",
"python-3.x",
"nltk",
"python-3.5"
] |
Problems while calling NLTK with Python 3.5.2_2? | 39,946,273 | <p>When I try to import nltk in python 3.5.2_2 I get the following message:</p>
<pre><code>>>> import nltk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/nltk/__init__.py", line 117, in <module>
from nltk.align import *
File "/usr/local/lib/python3.5/site-packages/nltk/align/__init__.py", line 15, in <module>
from nltk.align.ibm1 import IBMModel1
File "/usr/local/lib/python3.5/site-packages/nltk/align/ibm1.py", line 18, in <module>
from nltk.corpus import comtrans
File "/usr/local/lib/python3.5/site-packages/nltk/corpus/__init__.py", line 64, in <module>
from nltk.tokenize import RegexpTokenizer
File "/usr/local/lib/python3.5/site-packages/nltk/tokenize/__init__.py", line 65, in <module>
from nltk.tokenize.regexp import (RegexpTokenizer, WhitespaceTokenizer,
File "/usr/local/lib/python3.5/site-packages/nltk/tokenize/regexp.py", line 201, in <module>
blankline_tokenize = BlanklineTokenizer().tokenize
File "/usr/local/lib/python3.5/site-packages/nltk/tokenize/regexp.py", line 172, in __init__
RegexpTokenizer.__init__(self, r'\s*\n\s*\n\s*', gaps=True)
File "/usr/local/lib/python3.5/site-packages/nltk/tokenize/regexp.py", line 119, in __init__
self._regexp = compile_regexp_to_noncapturing(pattern, flags)
File "/usr/local/lib/python3.5/site-packages/nltk/internals.py", line 54, in compile_regexp_to_noncapturing
return sre_compile.compile(convert_regexp_to_noncapturing_parsed(sre_parse.parse(pattern)), flags=flags)
File "/usr/local/lib/python3.5/site-packages/nltk/internals.py", line 50, in convert_regexp_to_noncapturing_parsed
parsed_pattern.pattern.groups = 1
AttributeError: can't set attribute
</code></pre>
<p>I tried to reinstall it with pip3 and I am still having the same issue... Any idea of how to correctly install NLTK in OSX?, and how to solve this issue?.</p>
| 0 | 2016-10-09T17:11:01Z | 39,959,599 | <p>I solved this issue by upgrading with pip3 nltk and sklearn:</p>
<pre><code>user@MacBook-Pro-de-User:~$ pip3 install nltk --upgrade
Collecting nltk
Downloading nltk-3.2.1.tar.gz (1.1MB)
100% |ââââââââââââââââââââââââââââââââ| 1.1MB 675kB/s
Building wheels for collected packages: nltk
Running setup.py bdist_wheel for nltk ... done
Stored in directory: /Users/user/Library/Caches/pip/wheels/55/0b/ce/960dcdaec7c9af5b1f81d471a90c8dae88374386efe6e54a50
Successfully built nltk
Installing collected packages: nltk
Found existing installation: nltk 3.0.0
Uninstalling nltk-3.0.0:
Successfully uninstalled nltk-3.0.0
Successfully installed nltk-3.2.1
user@MacBook-Pro-de-User:~$ python3
Python 3.5.2 (default, Sep 28 2016, 18:08:09)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import nltk
/usr/local/lib/python3.5/site-packages/sklearn/utils/fixes.py:55: DeprecationWarning: inspect.getargspec() is deprecated, use inspect.signature() instead
if 'order' in inspect.getargspec(np.copy)[0]:
>>>
user@MacBook-Pro-de-User:~$ clear
user@MacBook-Pro-de-User:~$ pip3 install sklearn --upgrade
Requirement already up-to-date: sklearn in /usr/local/lib/python3.5/site-packages
Collecting scikit-learn (from sklearn)
Downloading scikit_learn-0.18-cp35-cp35m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (6.8MB)
100% |ââââââââââââââââââââââââââââââââ| 6.8MB 202kB/s
Installing collected packages: scikit-learn
Found existing installation: scikit-learn 0.15.2
Uninstalling scikit-learn-0.15.2:
Successfully uninstalled scikit-learn-0.15.2
Successfully installed scikit-learn-0.18
user@MacBook-Pro-de-User:~$ clear
user@MacBook-Pro-de-User:~$ python3
Python 3.5.2 (default, Sep 28 2016, 18:08:09)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import nltk
>>>
</code></pre>
| 0 | 2016-10-10T13:36:04Z | [
"python",
"python-3.x",
"nltk",
"python-3.5"
] |
Does the Order of Conditions affect Performance? | 39,946,279 | <p>Does it matter how I order the conditions in Python in respect to the speed of the script? In SQL e.g. it does not as the "Interpreter" assumes which condition ordering would be the fastest. </p>
<p>In Python, as far as I know, the order of conditions will be taken as given by the interpreter. So as an example, if I chain or-conditions, is it better to order the conditions by assumed time they will consume because maybe the interpreter stops even looking for the other conditions when the first one doesn't apply anyway?</p>
| 0 | 2016-10-09T17:11:34Z | 39,946,334 | <p>Yes, the order of conditions matters. They are evaluated left-to-right unless you change that by using parentheses, for example.</p>
<p>And yes, conditions are only evaluated if the outcome of the expression isn't already clear. For example, in</p>
<pre><code>if 1==0 and foo**10000 > 2:
</code></pre>
<p>Python will return <code>False</code> immediately and not even attempt to calculate <code>foo**10000</code>.</p>
| 5 | 2016-10-09T17:16:49Z | [
"python",
"performance",
"condition"
] |
Does the Order of Conditions affect Performance? | 39,946,279 | <p>Does it matter how I order the conditions in Python in respect to the speed of the script? In SQL e.g. it does not as the "Interpreter" assumes which condition ordering would be the fastest. </p>
<p>In Python, as far as I know, the order of conditions will be taken as given by the interpreter. So as an example, if I chain or-conditions, is it better to order the conditions by assumed time they will consume because maybe the interpreter stops even looking for the other conditions when the first one doesn't apply anyway?</p>
| 0 | 2016-10-09T17:11:34Z | 39,946,341 | <p>Python will not reorder your conditions like in SQL, but it will <a href="https://en.wikipedia.org/wiki/Short-circuit_evaluation" rel="nofollow">short circuit</a>. What this means is that it will stop evaluating as soon as possible. So if you have <code>if True == True or long_function_call():</code>, <code>long_function_call()</code> will never be evaluated. This works similarly for <code>and</code> with something like <code>if True == False and long_function_call():</code>. It would be in your best interest to consider this when writing conditional statements and can result in changes in performance.</p>
| 2 | 2016-10-09T17:17:28Z | [
"python",
"performance",
"condition"
] |
Does the Order of Conditions affect Performance? | 39,946,279 | <p>Does it matter how I order the conditions in Python in respect to the speed of the script? In SQL e.g. it does not as the "Interpreter" assumes which condition ordering would be the fastest. </p>
<p>In Python, as far as I know, the order of conditions will be taken as given by the interpreter. So as an example, if I chain or-conditions, is it better to order the conditions by assumed time they will consume because maybe the interpreter stops even looking for the other conditions when the first one doesn't apply anyway?</p>
| 0 | 2016-10-09T17:11:34Z | 39,946,498 | <p>Boolean operators in Python are <a href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not" rel="nofollow">short-circuiting</a> - as soon as the result of an expression is clear, evaluation stops. This plays an important role in Python's late-binding.</p>
<p>For example, this is a common check:</p>
<pre><code>def do(condition_check=None):
if condition_check is not None and condition_check():
# do stuff
</code></pre>
<p>Python is in general very conservative about premature optimizations. If there is any chance that something might break, Python will not try it.</p>
<p>If you want to check Interpreter optimizations, try the <code>dis</code> module. It shows the instructions actually being run by the Python core. For example, Python will resolve constant expressions (<code>10**10</code> => <code>10000000000</code>) and back out of an <code>and</code> early (<code>JUMP_IF_FALSE_OR_POP</code>).</p>
<pre><code>dis.dis('1==0 and 10**10 > 2')
1 0 LOAD_CONST 0 (1)
3 LOAD_CONST 1 (0)
6 COMPARE_OP 2 (==)
9 JUMP_IF_FALSE_OR_POP 21
12 LOAD_CONST 4 (10000000000)
15 LOAD_CONST 3 (2)
18 COMPARE_OP 4 (>)
>> 21 RETURN_VALUE
</code></pre>
<p>Note that not even pypy does any further optimization on this code!</p>
| 1 | 2016-10-09T17:34:19Z | [
"python",
"performance",
"condition"
] |
Apply transform of your own function in Pandas dataframe | 39,946,287 | <p>I have pandas dataframe on which I need to some data manipulation, the following code provide me the average of column "Variable" group by "Key":</p>
<pre><code>df.groupby('key').Variable.transform("mean")
</code></pre>
<p>The advantage of using "transform" is that it return back the result with the same index which is pretty useful.</p>
<p>Now, I want to have my customize function and use it within "transform" instead of "mean" more over my function need two or more column something like:</p>
<pre><code>lambda (Variable, Variable1, Variable2): (Variable + Variable1)/Variable2
</code></pre>
<p>(actual function of mine is more complicated than this example) and each row of my dataframe has Variable,Variable1 and Variable2. </p>
<p>I am wondering if I can define and use such a customized function within "transform" to be able to rerun the result back with same index?</p>
<p>Thanks,
Amir </p>
| 0 | 2016-10-09T17:12:36Z | 39,946,424 | <p>Don't call transform against <code>Variable</code>, call it on the grouper and then call your variables against the dataframe the function receives as argument:</p>
<pre><code>df.groupby('key').transform(lambda x: (x.Variable + x.Variable1)/x.Variable2)
</code></pre>
| 0 | 2016-10-09T17:26:43Z | [
"python",
"pandas",
"dataframe",
"aggregation"
] |
PyQt: Progress bar and label disappear | 39,946,413 | <p>I am new to Python and PyQt. When I start my program, after a few seconds, the progress bar and label disappear. The progress bar starts appearing and disappearing (the label is gone) when the mouse hovers over the progress bar, showing up once more before disappearing. But if I comment the line where I set up the progress bar value, the label does not disappear.</p>
<p>Here is the code:</p>
<pre><code>from PyQt4 import QtCore, QtGui, Qt
from PyQt4.Qt import QDialog, QApplication
import sys
import sensors
from sensors import *
import threading
class tmp():
def main(self):
global test
global name
sensors.init()
try:
for chip in sensors.iter_detected_chips():
#print (chip)
#print('Adapter:', chip.adapter_name)
for feature in chip:
if feature.label == 'Physical id 0':
test = feature.get_value()
name = feature.label
#print ('%s (%r): %.1f' % (feature.name, feature.label, feature.get_value()))
threading.Timer(5.0, self.main).start()
return test
print
finally:
sensors.cleanup()
zz = tmp()
zz.main()
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setGeometry(50, 50, 250, 150)
self.setWindowTitle("Title here")
#lay = QtGui.QVBoxLayout()
#lay.addWidget(self.prgB)
#lay.addWidget(self.lbl)
#self.setLayout(lay)
self.home()
def home(self):
self.prgB = QtGui.QProgressBar(self)
self.prgB.setGeometry(20, 20, 210, 20)
self.lbl = QtGui.QLabel(self)
self.lbl.setGeometry(20, 40, 210, 20)
lay = QtGui.QVBoxLayout()
lay.addWidget(self.prgB)
lay.addWidget(self.lbl)
self.setLayout(lay)
self.update()
def update(self):
textas = ('%s : %.1f' % (name, test))
self.lbl.setText(str(textas))
self.prgB.setValue(test)
threading.Timer(5.0, self.update).start()
QtGui.QApplication.processEvents()
self.show()
def run():
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
app = QtGui.QApplication(sys.argv)
GUI = MainWindow()
sys.exit(app.exec_())
run()
</code></pre>
<p>What I am trying to do is just get the temp value (pysensors) and pass it to the label text and progress bar value. It is working, just as I said, but after a few seconds the label is gone and the progress bar disappears.
I know (or I guess) there is something wrong with the update function. I just can't find out whats wrong.</p>
| 0 | 2016-10-09T17:25:09Z | 39,948,819 | <p>First of all you don't need the separate class tmp(). Delete it and just move the main() function in MainWindow class. After doing this name,test variables should not be global any more. Define them in your <strong>init</strong> (for example self.test = 0, self.name='something') and refer to them in the rest of the code as self.test and self.name.</p>
<p>Now the most important mistake in your code is that you are trying to update GUI components from a different thread. GUI components should be handled only by the main thread using the signal/slot mechanism that pyqt provides.</p>
<p>The steps for doing this in your case are</p>
<ol>
<li>Define a new signal in MainWindow class</li>
<li>Connect this signal to the update() function</li>
<li>Emit this signal from main() function</li>
</ol>
<p>In the end your code should look like this</p>
<pre><code>class MainWindow(QtGui.QWidget):
signalUpdateBar = QtCore.pyqtSignal()
def __init__(self):
...
self.test = 0
self.name = "0"
...
def home(self):
...
self.signalUpdateBar.connect(self.update)
self.main()
self.show()
def main():
try:
...
self.test = feature.get_value()
self.name = feature.label
threading.Timer(5.0, self.main).start()
self.signalUpdateBar.emit()
finally:
...
</code></pre>
<p>Moreover in your update() function </p>
<pre><code> self.prgB.setValue(self.test)
</code></pre>
<p>should be the last statement. Anything below that is not necessary.</p>
| 1 | 2016-10-09T21:38:27Z | [
"python",
"multithreading",
"python-2.7",
"pyqt"
] |
Selecting checkboxes using selenium web driver with python | 39,946,419 | <p>I am trying to perform a test on Amazon.com categories checkboxes using selenium web driver with python code, and I tried several ways but I am not sure how to select the checkbox of the Book category for example without having its id or name. I used some plugins to get the right xpath like XPath Helper for chrome and path checker on Firefox... </p>
<p>Here is my code and my tries are commented. </p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
sleep(4)
self.browser.close()
self.browser = None
def test_07_ListOfTodayDeals(self):
self.browser.get("http://www.amazon.com")
deals = self.browser.find_element_by_link_text("Today's Deals")
deals.click()
books = self.browser.find_element_by_id("widgetFilters")
books.find_element_by_xpath("/x:div[1]/x:div/x:span[8]/x:div/x:label/x:span").click()
#for i in range(20):
#try:
#self.browser.find_element_by_xpath(".//*[contains(text(), 'Books')]").click()
#break
#except NoSuchElementException as e:
#print('retry')
#time.sleep(1)
#else:
#print('Test Failed')
browser.close()
#sign_in_button = self.browser.find_element(By_XPATH,'(//input[@name=''])[8]')
#sign_in_button.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()
#sleep(5)
#self.assertTrue("No results found." not in self.browser.page_source)
if __name__ == "__main__":
unittest.main(verbosity=2)
</code></pre>
<p>HTML</p>
<pre><code><span class="a-declarative" data-action="gbfilter-checkbox" data-gbfilter-checkbox="{&quot;attribute&quot;:&quot;whitelist_categories&quot;,&quot;value&quot;:&quot;283155&quot;,&quot;rangeEnd&quot;:&quot;&quot;,&quot;rangeStart&quot;:&quot;&quot;,&quot;filterType&quot;:&quot;checkboxes&quot;}">
<div class="a-checkbox checkbox checked a-spacing-micro"><label><input name="" value="" checked="" type="checkbox"><i class="a-icon a-icon-checkbox"></i><span class="a-label a-checkbox-label">
Books
</span></label></div>
</span>
</code></pre>
| 1 | 2016-10-09T17:25:44Z | 39,950,187 | <p>You should try using <code>xpath</code> as below :-</p>
<pre><code>self.browser.find_element_by_xpath(".//div[normalize-space(.)='Books']/input[@type='checkbox']").click()
</code></pre>
<p>Or</p>
<pre><code>self.browser.find_element_by_xpath(".//div[contains(@class,'checkbox') and contains(., 'Books')]/input[@type='checkbox']").click()
</code></pre>
| 0 | 2016-10-10T01:23:02Z | [
"python",
"selenium",
"xpath",
"checkbox"
] |
Selecting checkboxes using selenium web driver with python | 39,946,419 | <p>I am trying to perform a test on Amazon.com categories checkboxes using selenium web driver with python code, and I tried several ways but I am not sure how to select the checkbox of the Book category for example without having its id or name. I used some plugins to get the right xpath like XPath Helper for chrome and path checker on Firefox... </p>
<p>Here is my code and my tries are commented. </p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
sleep(4)
self.browser.close()
self.browser = None
def test_07_ListOfTodayDeals(self):
self.browser.get("http://www.amazon.com")
deals = self.browser.find_element_by_link_text("Today's Deals")
deals.click()
books = self.browser.find_element_by_id("widgetFilters")
books.find_element_by_xpath("/x:div[1]/x:div/x:span[8]/x:div/x:label/x:span").click()
#for i in range(20):
#try:
#self.browser.find_element_by_xpath(".//*[contains(text(), 'Books')]").click()
#break
#except NoSuchElementException as e:
#print('retry')
#time.sleep(1)
#else:
#print('Test Failed')
browser.close()
#sign_in_button = self.browser.find_element(By_XPATH,'(//input[@name=''])[8]')
#sign_in_button.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()
#sleep(5)
#self.assertTrue("No results found." not in self.browser.page_source)
if __name__ == "__main__":
unittest.main(verbosity=2)
</code></pre>
<p>HTML</p>
<pre><code><span class="a-declarative" data-action="gbfilter-checkbox" data-gbfilter-checkbox="{&quot;attribute&quot;:&quot;whitelist_categories&quot;,&quot;value&quot;:&quot;283155&quot;,&quot;rangeEnd&quot;:&quot;&quot;,&quot;rangeStart&quot;:&quot;&quot;,&quot;filterType&quot;:&quot;checkboxes&quot;}">
<div class="a-checkbox checkbox checked a-spacing-micro"><label><input name="" value="" checked="" type="checkbox"><i class="a-icon a-icon-checkbox"></i><span class="a-label a-checkbox-label">
Books
</span></label></div>
</span>
</code></pre>
| 1 | 2016-10-09T17:25:44Z | 39,968,894 | <p>I have solved my problem with a very simple line of code using the right xpath:</p>
<pre><code>self.browser.find_element_by_xpath("(//input[@name=''])[8]").click()
</code></pre>
<p>and it perfectly worked!</p>
| 0 | 2016-10-11T00:52:19Z | [
"python",
"selenium",
"xpath",
"checkbox"
] |
Selecting checkboxes using selenium web driver with python | 39,946,419 | <p>I am trying to perform a test on Amazon.com categories checkboxes using selenium web driver with python code, and I tried several ways but I am not sure how to select the checkbox of the Book category for example without having its id or name. I used some plugins to get the right xpath like XPath Helper for chrome and path checker on Firefox... </p>
<p>Here is my code and my tries are commented. </p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
sleep(4)
self.browser.close()
self.browser = None
def test_07_ListOfTodayDeals(self):
self.browser.get("http://www.amazon.com")
deals = self.browser.find_element_by_link_text("Today's Deals")
deals.click()
books = self.browser.find_element_by_id("widgetFilters")
books.find_element_by_xpath("/x:div[1]/x:div/x:span[8]/x:div/x:label/x:span").click()
#for i in range(20):
#try:
#self.browser.find_element_by_xpath(".//*[contains(text(), 'Books')]").click()
#break
#except NoSuchElementException as e:
#print('retry')
#time.sleep(1)
#else:
#print('Test Failed')
browser.close()
#sign_in_button = self.browser.find_element(By_XPATH,'(//input[@name=''])[8]')
#sign_in_button.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()
#sleep(5)
#self.assertTrue("No results found." not in self.browser.page_source)
if __name__ == "__main__":
unittest.main(verbosity=2)
</code></pre>
<p>HTML</p>
<pre><code><span class="a-declarative" data-action="gbfilter-checkbox" data-gbfilter-checkbox="{&quot;attribute&quot;:&quot;whitelist_categories&quot;,&quot;value&quot;:&quot;283155&quot;,&quot;rangeEnd&quot;:&quot;&quot;,&quot;rangeStart&quot;:&quot;&quot;,&quot;filterType&quot;:&quot;checkboxes&quot;}">
<div class="a-checkbox checkbox checked a-spacing-micro"><label><input name="" value="" checked="" type="checkbox"><i class="a-icon a-icon-checkbox"></i><span class="a-label a-checkbox-label">
Books
</span></label></div>
</span>
</code></pre>
| 1 | 2016-10-09T17:25:44Z | 39,970,729 | <p>I have modified your code and now it's working</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
sleep(4)
self.browser.close()
self.browser = None
def test_07_ListOfTodayDeals(self):
self.browser.get("http://www.amazon.com")
deals = self.browser.find_element_by_link_text("Today's Deals")
deals.click()
sleep(5)
self.browser.find_element_by_xpath("//span[@class='a-label a-checkbox-label' and contains(text(),'Books')]/preceding-sibling::input[1]").click()
self.browser.close()
if __name__ == "__main__":
unittest.main(verbosity=2)
</code></pre>
| 0 | 2016-10-11T04:57:13Z | [
"python",
"selenium",
"xpath",
"checkbox"
] |
cmake osx deployment target is '10.11' but CMAKE_OSX_SYSROOT error | 39,946,504 | <p>I'm getting this cmake error while installing a python file related to openAI gym. The error log which is bugging me is the below lines..</p>
<pre><code>CMake Error at /usr/local/Cellar/cmake/3.5.2/share/cmake/Modules/Platform/Darwin.cmake:76 (message):
CMAKE_OSX_DEPLOYMENT_TARGET is '10.11' but CMAKE_OSX_SYSROOT:
""
is not set to a MacOSX SDK with a recognized version. Either set
CMAKE_OSX_SYSROOT to a valid SDK or set CMAKE_OSX_DEPLOYMENT_TARGET to
empty.
</code></pre>
<p>Can anyone please guide me how to overcome this error ? I have also attached the full error log if it helps.
<a href="https://www.dropbox.com/s/qxyxaleu38xgwi0/errorLogOpenAI.txt?dl=0" rel="nofollow">https://www.dropbox.com/s/qxyxaleu38xgwi0/errorLogOpenAI.txt?dl=0</a></p>
<p>I have tried set CMAKE_OSX_DEPLOYMENT_TARGET empty command and re-executed installation, but it still threw same error.</p>
<p>Complete error log : <a href="https://www.dropbox.com/s/f0dftar6ovbrreu/pachi_2_pdf.pdf?dl=0" rel="nofollow">https://www.dropbox.com/s/f0dftar6ovbrreu/pachi_2_pdf.pdf?dl=0</a></p>
| 1 | 2016-10-09T17:34:54Z | 40,004,078 | <p>Expanding on comment. As error text suggests:</p>
<pre><code>is not set to a MacOSX SDK with a recognized version. Either set
CMAKE_OSX_SYSROOT to a valid SDK or set CMAKE_OSX_DEPLOYMENT_TARGET to
empty.
</code></pre>
<p>You can unset CMAKE_OSX_DEPLOYMENT_TARGET to let cmake chose defaults. You can add following in your cmake file:</p>
<pre><code>unset(CMAKE_OSX_DEPLOYMENT_TARGET)
</code></pre>
| 1 | 2016-10-12T16:48:13Z | [
"python",
"osx",
"cmake"
] |
compare two lists (python) | 39,946,508 | <p>I need to compare two lists in a program to see if there are matching strings. One of them is a txt document that I already imported. Thats what I did</p>
<pre><code> def compareLists(self, listA, listB):
sameWords = list()
for a in xrange(0,len(listA)):
for b in xrange(0,len(listB)):
if listA[a] == listB[b]:
sameWords.append(listA[a])
pass
pass
pass
return sameWords
</code></pre>
<p>But if I run the program it doesnt show any matches although I know that there has to be one. I think its somewhere inside the if block.</p>
| 1 | 2016-10-09T17:35:21Z | 39,946,617 | <p>I am assuming the indentation is correct in your code. Continuing with your strategy, this code should work.</p>
<pre><code>def compareLists(self, listA, listB):
sameWords = list()
for a in xrange(0,len(listA)):
for b in xrange(0,len(listB)):
if listA[a] == listB[b]:
sameWords.append(listA[a])
return sameWords
</code></pre>
<p>Alternatively, as @Efferalgan suggested, simply do the set intersection.</p>
<pre><code>def compareLists(self, listA, listB):
return list(set(listA) & set(listB))
</code></pre>
<p><strong>Note:</strong> The set intersection will remove duplicate matching words from your result.</p>
<p>As you said, you are reading in the lines from a text file, and it looks like the newlines are still in there.</p>
<pre><code>my_text_list = [s for s in open("my_text.txt").read().rsplit()]
</code></pre>
| 1 | 2016-10-09T17:45:48Z | [
"python",
"list"
] |
Regular Expression to replace dot with space before parentheses | 39,946,538 | <p>I am working on some customer comments that some of them did not follow grammatical rules. For Example <code>(Such as s and b.)</code> in the following text that provides more explanation for previous sentence is surrounded by two dots. </p>
<pre><code> text = "I was initially scared of ANY drug after my experience. But about a year later I tried. (Such as s and b.). I had a very bad reaction to this."
</code></pre>
<p>First, I want to find <code>. (Such as s and b.).</code> and then replace the dot before <code>(Such as s and b.)</code> to space. This is my code, but it does not work. </p>
<pre><code>text = re.sub (r'(\.)(\s+?\(.+\)\s*\.)', r' \2 ', text )
</code></pre>
<p>Output should be: </p>
<pre><code> "I was initially scared of ANY drug after my experience. But about a year later I tried (Such as s and b.). I had a very bad reaction to this."
</code></pre>
<p>I am using python.</p>
| 2 | 2016-10-09T17:38:00Z | 39,946,590 | <p>The sample provided does not make much sense because the only change is that the ` character is moved one position to the left.</p>
<p>However, this might do the trick (to keep the dot inside the paranthesis):</p>
<pre><code>text = re.sub(r'\.\s*\)\s*\.', '.)', text)
</code></pre>
<p>Or this to have it outside:</p>
<pre><code>text = re.sub(r'\.\s*\)\s*\.', ').', text)
</code></pre>
<p><strong>Edit:</strong> Or maybe you're looking for this to replace the dot before the opening paranthesis?</p>
<pre><code>text = re.sub(r'\.(?=\s*\(.*?\)\.)', ').', text)
</code></pre>
| 1 | 2016-10-09T17:43:01Z | [
"python",
"regex"
] |
Regular Expression to replace dot with space before parentheses | 39,946,538 | <p>I am working on some customer comments that some of them did not follow grammatical rules. For Example <code>(Such as s and b.)</code> in the following text that provides more explanation for previous sentence is surrounded by two dots. </p>
<pre><code> text = "I was initially scared of ANY drug after my experience. But about a year later I tried. (Such as s and b.). I had a very bad reaction to this."
</code></pre>
<p>First, I want to find <code>. (Such as s and b.).</code> and then replace the dot before <code>(Such as s and b.)</code> to space. This is my code, but it does not work. </p>
<pre><code>text = re.sub (r'(\.)(\s+?\(.+\)\s*\.)', r' \2 ', text )
</code></pre>
<p>Output should be: </p>
<pre><code> "I was initially scared of ANY drug after my experience. But about a year later I tried (Such as s and b.). I had a very bad reaction to this."
</code></pre>
<p>I am using python.</p>
| 2 | 2016-10-09T17:38:00Z | 39,946,657 | <p>I would suggest this to remove a dot before parentheses when there is another one following them:</p>
<pre><code>text = re.sub(r'\.(\s*?\([^)]*\)\s*\.)', r'\1', text)
</code></pre>
<p>See it run on <a href="https://repl.it/DrvM/3" rel="nofollow">repl.it</a></p>
| 1 | 2016-10-09T17:49:41Z | [
"python",
"regex"
] |
How to eval() a string in a dictionary Python2.7 | 39,946,562 | <p>I have a dictionary:</p>
<pre><code>key = {'K_z':'K_w'}
</code></pre>
<p>I want to get K_w as a value name instead of a string, I heard that the eval() function can convert strings to value names.</p>
<p>But when I type:</p>
<pre><code>print(eval(key['K_z']))
</code></pre>
<p>I get 'K_z' instead of having the K_w value.</p>
<p>Can you help me ?</p>
<p>If it helps, I'm using it for pygame to let the player change the key bindings, specially with AZERTY and QWERTY differences...</p>
| -2 | 2016-10-09T17:40:22Z | 39,946,706 | <pre><code>import pygame
key = {'K_z':'K_w',}
print (getattr(pygame,key['K_z']))
</code></pre>
<p>Using this <a href="http://claude.segeral.pagesperso-orange.fr/qwerazer/" rel="nofollow">azerty and qwerty </a> you can easily create the key dictionary by copying and editing the html table into excel and then some scripts </p>
| -1 | 2016-10-09T17:54:05Z | [
"python",
"dictionary",
"pygame",
"eval"
] |
How to eval() a string in a dictionary Python2.7 | 39,946,562 | <p>I have a dictionary:</p>
<pre><code>key = {'K_z':'K_w'}
</code></pre>
<p>I want to get K_w as a value name instead of a string, I heard that the eval() function can convert strings to value names.</p>
<p>But when I type:</p>
<pre><code>print(eval(key['K_z']))
</code></pre>
<p>I get 'K_z' instead of having the K_w value.</p>
<p>Can you help me ?</p>
<p>If it helps, I'm using it for pygame to let the player change the key bindings, specially with AZERTY and QWERTY differences...</p>
| -2 | 2016-10-09T17:40:22Z | 39,988,649 | <p>Is this what you are looking for?</p>
<pre><code>key = {'K_z':'K_w'}
print(key['K_z'])
</code></pre>
<p>K_w</p>
<p>I don't think that <code>eval()</code> will help as it evaluates arguments. In pygame you could use <code>if key[pygame.K_w] or key[pygame.K_z]</code> do something.</p>
| 0 | 2016-10-12T00:14:43Z | [
"python",
"dictionary",
"pygame",
"eval"
] |
How to Convert to Seconds from Data Time using Tableau or Excel | 39,946,614 | <p>I have a data CSV file where the Time Duration is expressed with a "regular" datetime syntax such as <code>12/30/99 00:00:55 AM</code>.</p>
<p>Since this value represents the time duration (and not the date and time) I need to translate it to a number that would represent the the duration in minutes such as <code>55</code> minutes.</p>
<p>I wonder if it could be possible to use Tableau's Calculated Field or Excel Expression to extract the timing <code>00:00:55</code> part and convert it to a number representing a time duration in minutes?</p>
<p>Here is how I would do this using Python:
1. First I would split the incoming value to isolate the 00:00:55 duration portion from <code>12/30/99 00:00:55 AM</code>:</p>
<pre><code>`value = '12/30/99 00:00:55 AM'`
`duration = value.split()[1]`
</code></pre>
<ol start="2">
<li>Then I would separate hours, minutes and seconds:</li>
</ol>
<p><code>hours, minutes, sec = duration.split(':')</code></p>
<ol start="3">
<li>Finally I would sum each after converting each to seconds:</li>
</ol>
<p><code>seconds = (int(hours)*60*60 + int(minutes)*60 + int(sec))</code></p>
| 1 | 2016-10-09T17:45:43Z | 39,947,332 | <p>This would be a very crude way of doing it and would rely on the format being the same.</p>
<pre><code>=(MID(E3,10,2)Ã60Ã60)+(MID(E3,13,2)Ã60)+(MID(E3,16,2))
</code></pre>
<p>MID - (Cell Reference, Start Position, No. of Characters to Extract)</p>
<p>This assumes the value is in E3, this should be changed to what ever cell you have the original value of "12/30/99 00:00:55 AM" in.</p>
| 0 | 2016-10-09T18:55:57Z | [
"python",
"excel",
"tableau"
] |
How to Convert to Seconds from Data Time using Tableau or Excel | 39,946,614 | <p>I have a data CSV file where the Time Duration is expressed with a "regular" datetime syntax such as <code>12/30/99 00:00:55 AM</code>.</p>
<p>Since this value represents the time duration (and not the date and time) I need to translate it to a number that would represent the the duration in minutes such as <code>55</code> minutes.</p>
<p>I wonder if it could be possible to use Tableau's Calculated Field or Excel Expression to extract the timing <code>00:00:55</code> part and convert it to a number representing a time duration in minutes?</p>
<p>Here is how I would do this using Python:
1. First I would split the incoming value to isolate the 00:00:55 duration portion from <code>12/30/99 00:00:55 AM</code>:</p>
<pre><code>`value = '12/30/99 00:00:55 AM'`
`duration = value.split()[1]`
</code></pre>
<ol start="2">
<li>Then I would separate hours, minutes and seconds:</li>
</ol>
<p><code>hours, minutes, sec = duration.split(':')</code></p>
<ol start="3">
<li>Finally I would sum each after converting each to seconds:</li>
</ol>
<p><code>seconds = (int(hours)*60*60 + int(minutes)*60 + int(sec))</code></p>
| 1 | 2016-10-09T17:45:43Z | 39,947,340 | <p>If you wanted to do it just in an Excel formula to get to seconds would be similar to Python:-</p>
<pre><code>=HOUR(A1)*3600+MINUTE(A1)*60+SECOND(A1)
</code></pre>
<p>assuming the value can be read from the CSV file into an Excel datetime value in cell A1.</p>
<p>Another way of doing it (using the fact that time values in Excel are fractions of a day) is</p>
<pre><code>=MOD(A1,1)*24*3600
</code></pre>
| 1 | 2016-10-09T18:56:38Z | [
"python",
"excel",
"tableau"
] |
How to Convert to Seconds from Data Time using Tableau or Excel | 39,946,614 | <p>I have a data CSV file where the Time Duration is expressed with a "regular" datetime syntax such as <code>12/30/99 00:00:55 AM</code>.</p>
<p>Since this value represents the time duration (and not the date and time) I need to translate it to a number that would represent the the duration in minutes such as <code>55</code> minutes.</p>
<p>I wonder if it could be possible to use Tableau's Calculated Field or Excel Expression to extract the timing <code>00:00:55</code> part and convert it to a number representing a time duration in minutes?</p>
<p>Here is how I would do this using Python:
1. First I would split the incoming value to isolate the 00:00:55 duration portion from <code>12/30/99 00:00:55 AM</code>:</p>
<pre><code>`value = '12/30/99 00:00:55 AM'`
`duration = value.split()[1]`
</code></pre>
<ol start="2">
<li>Then I would separate hours, minutes and seconds:</li>
</ol>
<p><code>hours, minutes, sec = duration.split(':')</code></p>
<ol start="3">
<li>Finally I would sum each after converting each to seconds:</li>
</ol>
<p><code>seconds = (int(hours)*60*60 + int(minutes)*60 + int(sec))</code></p>
| 1 | 2016-10-09T17:45:43Z | 39,947,671 | <p>After linking CSV file Tableau goes ahead and auto assigns the data type to each column based on its own assumptions. The original CSV's <strong>Duration</strong> column field value was actually <code>00:00:00:55</code>. But since Tableau considered it as datetime type it converted in on a fly to <code>12/30/99 00:00:55 AM</code> appending <code>12/30/99</code> at the beginning and <code>AM</code> at the end.
I right-clicked the <strong>Duration</strong> Dimension (this is how Tableau calls columns) and changed its date type to <code>String</code>. To convert this value to minutes I had to create a custom Calculated Field with following expression:</p>
<pre><code>INT(SPLIT(STR([Duration]), ':', 1))*60*60*60 + INT(SPLIT(STR([Duration]), ':', 2))*60*60 + INT(SPLIT(STR([Duration]), ':', 3))*60 + INT(SPLIT(STR([Duration]), ':', 4))/60
</code></pre>
| 0 | 2016-10-09T19:29:23Z | [
"python",
"excel",
"tableau"
] |
ReactorNotRestartable error in while loop with scrapy | 39,946,632 | <p>I get <code>twisted.internet.error.ReactorNotRestartable</code> error when I execute following code:</p>
<pre><code>from time import sleep
from scrapy import signals
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from scrapy.xlib.pydispatch import dispatcher
result = None
def set_result(item):
result = item
while True:
process = CrawlerProcess(get_project_settings())
dispatcher.connect(set_result, signals.item_scraped)
process.crawl('my_spider')
process.start()
if result:
break
sleep(3)
</code></pre>
<p>For the first time it works, then I get error. I create <code>process</code> variable each time, so what's the problem?</p>
| 0 | 2016-10-09T17:47:46Z | 39,955,395 | <p>By default, <a href="https://doc.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerProcess" rel="nofollow"><code>CrawlerProcess</code></a>'s <a href="https://doc.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerProcess.start" rel="nofollow"><code>.start()</code></a> will stop the Twisted reactor it creates when all crawlers have finished.</p>
<p>You should call <code>process.start(stop_after_crawl=False)</code> if you create <code>process</code> in each iteration.</p>
<p>Another option is to handle the Twisted reactor yourself and use <a href="https://doc.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerRunner" rel="nofollow"><code>CrawlerRunner</code></a>. <a href="https://doc.scrapy.org/en/latest/topics/practices.html#running-multiple-spiders-in-the-same-process" rel="nofollow">The docs have an example</a> on doing that.</p>
| 0 | 2016-10-10T09:38:34Z | [
"python",
"python-2.7",
"scrapy",
"twisted"
] |
Removing punctuation/symbols from a list with Python except periods, commas | 39,946,660 | <p>In Python, I need to remove almost all punctuation from a list but save periods and commas. Should I create a function to do this or a variable? Basically I want to delete all symbols except letters (I've already converted uppercase letters to lowercase) and periods and commas (and maybe apostrophes). </p>
<pre><code>#Clean tokens up (remove symbols except ',' and '.')
def depunctuate()
clean_tokens = []
for i in lc_tokens:
if (i not in [a-z.,])
...
</code></pre>
| 1 | 2016-10-09T17:49:52Z | 39,946,713 | <p>You can build a set of unwanted punctuation from <a href="https://docs.python.org/2/library/string.html#string.punctuation" rel="nofollow"><code>string.punctuation</code></a> - which provides a string containing punctuation, and then use a <em>list comprehension</em> to filter out the letters contained in the set:</p>
<pre><code>import string
to_delete = set(string.punctuation) - {'.', ','} # remove comma and fullstop
clean_tokens = [x for x in lc_tokens if x not in to_delete]
</code></pre>
| 0 | 2016-10-09T17:54:53Z | [
"python",
"normalization"
] |
Removing punctuation/symbols from a list with Python except periods, commas | 39,946,660 | <p>In Python, I need to remove almost all punctuation from a list but save periods and commas. Should I create a function to do this or a variable? Basically I want to delete all symbols except letters (I've already converted uppercase letters to lowercase) and periods and commas (and maybe apostrophes). </p>
<pre><code>#Clean tokens up (remove symbols except ',' and '.')
def depunctuate()
clean_tokens = []
for i in lc_tokens:
if (i not in [a-z.,])
...
</code></pre>
| 1 | 2016-10-09T17:49:52Z | 39,946,762 | <pre><code>import string
# Create a set of all allowed characters.
# {...} is the syntax for a set literal in Python.
allowed = {",", "."}.union(string.ascii_lowercase)
# This is our starting string.
lc_tokens = 'hello, "world!"'
# Now we use list comprehension to only allow letters in our allowed set.
# The result of list comprehension is a list, so we use "".join(...) to
# turn it back into a string.
filtered = "".join([letter for letter in lc_tokens if letter in allowed])
# Our final result has everything but lowercase letters, commas, and
# periods removed.
assert filtered == "hello,world"
</code></pre>
| 0 | 2016-10-09T17:59:43Z | [
"python",
"normalization"
] |
Descriptor protocol implementation of property() | 39,946,666 | <p>The Python <a href="https://docs.python.org/3.5/howto/descriptor.html#properties" rel="nofollow">descriptor How-To</a> describes how one could implement the <code>property()</code> in terms of descriptors. I do not understand the reason of the first if-block in the <code>__get__</code> method. Under what circumstances will <code>obj</code> be <code>None</code>? What is supposed to happen then? Why do the <code>__get__</code> and <code>__del__</code> methods not check for that?</p>
<p>Code is a bit lengthy, but it's probably better to give the full code rather than just a snippet. Questionable line is marked.</p>
<pre><code>class Property(object):
"Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
def __get__(self, obj, objtype=None):
# =====>>> What's the reason of this if block? <<<=====
if obj is None:
return self
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError("can't delete attribute")
self.fdel(obj)
def getter(self, fget):
return type(self)(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)
</code></pre>
| 2 | 2016-10-09T17:50:38Z | 39,947,061 | <p>From the <a href="https://docs.python.org/3.5/howto/descriptor.html#invoking-descriptors" rel="nofollow">descriptor documentation</a>:</p>
<blockquote>
<p>The details of invocation depend on whether <code>obj</code> is an object or a class.</p>
</blockquote>
<p>Basically, instances call descriptors as <code>type(b).__dict__['x'].__get__(b, type(b))</code>, while classes call descriptors as <code>B.__dict__['x'].__get__(None, B)</code>. If <code>obj is None</code> means the getter was called from the class, not an instance.</p>
<p>This machinery is used for example to implement <a href="https://docs.python.org/3.5/howto/descriptor.html#static-methods-and-class-methods" rel="nofollow">classmethods</a>.</p>
<p>The <code>__set__</code> and <code>__delete__</code> do not check for <code>obj is None</code> because they can never be called like this. Only <code>__get__</code> is invoked when called from the class. Doing <code>cls.prop = 2</code> or <code>del cls.prop</code> will directly overwrite or delete the property object, without invoking <code>__set__</code> or <code>__delete__</code>.</p>
| 1 | 2016-10-09T18:29:09Z | [
"python"
] |
Descriptor protocol implementation of property() | 39,946,666 | <p>The Python <a href="https://docs.python.org/3.5/howto/descriptor.html#properties" rel="nofollow">descriptor How-To</a> describes how one could implement the <code>property()</code> in terms of descriptors. I do not understand the reason of the first if-block in the <code>__get__</code> method. Under what circumstances will <code>obj</code> be <code>None</code>? What is supposed to happen then? Why do the <code>__get__</code> and <code>__del__</code> methods not check for that?</p>
<p>Code is a bit lengthy, but it's probably better to give the full code rather than just a snippet. Questionable line is marked.</p>
<pre><code>class Property(object):
"Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
def __get__(self, obj, objtype=None):
# =====>>> What's the reason of this if block? <<<=====
if obj is None:
return self
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError("can't delete attribute")
self.fdel(obj)
def getter(self, fget):
return type(self)(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)
</code></pre>
| 2 | 2016-10-09T17:50:38Z | 39,947,066 | <p>You can see what the effect is by making another version that leaves that test out. I made a class Property that uses the code you posted, and another BadProperty that leaves out that <code>if</code> block. Then I made this class:</p>
<pre><code>class Foo(object):
@Property
def good(self):
print("In good getter")
return "good"
@good.setter
def good(self, val):
print("In good setter")
@BadProperty
def bad(self):
print("In bad getter")
return "bad"
@bad.setter
def bad(self, val):
print("In bad setter")
</code></pre>
<p>The similarities and differences can be seen in this example:</p>
<pre><code>>>> x = Foo()
# same
>>> x.good
In good getter
'good'
>>> x.bad
In bad getter
'bad'
>>> x.good = 2
In good setter
>>> x.bad = 2
In bad setter
# different!
>>> Foo.good
<__main__.Property object at 0x0000000002B71470>
>>> Foo.bad
In bad getter
'bad'
</code></pre>
<p>The effect of the <code>if</code> block is to return the raw property object itself if it is accessed via the class. Without this check, the getter is called even when accessing the descriptor via the class.</p>
<p>The <code>__set__</code> and <code>__del__</code> methods do not need such a check, since the descriptor protocol is not invoke at all when setting/deleting attributes on a class (only on an instance). This is not totally obvious from the documentation, but can be seen in the difference between the description of <code>__get__</code> vs. those of <code>__set__</code>/<code>__del__</code> in <a href="https://docs.python.org/3/reference/datamodel.html#object.__get__" rel="nofollow">the docs</a>, where <code>__get__</code> can get the attribute of "the owner class or an instance" but <code>__set__</code>/<code>__del__</code> only set/delete the attribute on an instance.</p>
| 2 | 2016-10-09T18:29:25Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not palindrome')
</code></pre>
<p>I am not getting the correct answer for this palindrome program.</p>
| 0 | 2016-10-09T17:56:44Z | 39,946,764 | <p>The classic solution:</p>
<pre><code>def palindrome(n):
start = 0
end = len(n) - 1
while (start < end):
if (n[start] != n[end]):
return False
start = start + 1
end = end - 1
return True
</code></pre>
| 0 | 2016-10-09T17:59:58Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not palindrome')
</code></pre>
<p>I am not getting the correct answer for this palindrome program.</p>
| 0 | 2016-10-09T17:56:44Z | 39,946,801 | <p>Use raw_input:</p>
<pre><code>n = str(raw_input('Enter the string:'))
</code></pre>
| 1 | 2016-10-09T18:02:48Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not palindrome')
</code></pre>
<p>I am not getting the correct answer for this palindrome program.</p>
| 0 | 2016-10-09T17:56:44Z | 39,946,846 | <pre><code>def palindrome(my_string):
reverse_string = my_string[::-1]
if list(my_string)==list(reverse_string):
return True
else:
return False
my_string = input("ENTER THE STRING ")
if(palindrome(my_string)):
print("Palindrome")
else:
print("Not Palindrome")
</code></pre>
| 2 | 2016-10-09T18:07:16Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not palindrome')
</code></pre>
<p>I am not getting the correct answer for this palindrome program.</p>
| 0 | 2016-10-09T17:56:44Z | 39,946,914 | <pre><code>while index < int(len(n) / 2):
if n[index] != n[len(n) - index - 1]:
return False
index+=1
return True
</code></pre>
| 0 | 2016-10-09T18:13:51Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not palindrome')
</code></pre>
<p>I am not getting the correct answer for this palindrome program.</p>
| 0 | 2016-10-09T17:56:44Z | 39,947,109 | <p>Your check is broken. Look at <code>return True</code>:</p>
<pre><code>def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1 # only increment on match !!!
return True # return True on *first* match !!!
break # unnecessary, return exits the loop
return False # never reached, but would only trigger if there are no matches
</code></pre>
<p>Basically, you go through your string and on the first <em>match</em> you report True. So if first and last letter are the same, <code>True</code> is returned. Only if <em>no</em> pair of characters matches, you return <code>False</code>. This is the opposite of what want to check. It should be this instead:</p>
<pre><code>def palindrome(n):
index = 0
check = True
while index < len(n)/2:
if n[index] != n[-1-index]:
return False # one didn't match, cannot be a palindrome
index+=1
return True # all did match, is a palindrome
</code></pre>
| 0 | 2016-10-09T18:33:39Z | [
"python"
] |
What is the Python equivalent to C# LINQ Sum() | 39,946,748 | <p>In C# I can get the sum of some values like so:</p>
<pre><code>new List<Tuple<string, int>>().Sum(x => x.Item2);
</code></pre>
<p>How can I achieve the same result in Python? Assuming I have a list of tuples</p>
| 1 | 2016-10-09T17:58:22Z | 39,946,784 | <p>The equivalent is a <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">comprehension</a> inside a <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum()</code></a>.</p>
<pre><code>sum(x[1] for x in tuples)
</code></pre>
<p>For example, we can define some sample random data.</p>
<pre><code>from random import randint
r = lambda: randint(0, 100)
data = [(r(), r(), r()) for x in range(100)]
sum(x[1] for x in data)
</code></pre>
| 5 | 2016-10-09T18:01:48Z | [
"c#",
"python"
] |
Falcon parsing json error | 39,946,770 | <p>I'm trying out Falcon for a small api project. Unfortunate i'm stuck on the json parsing stuff and code from the documentation examples does not work.</p>
<p>I have tried so many things i've found on Stack and Google but no changes.
I've tried the following codes that results in the errors below</p>
<pre><code>import json
import falcon
class JSON_Middleware(object):
def process_request(self, req, resp):
raw_json = json.loads(req.stream.read().decode('UTF-8'))
"""Exception: AttributeError: 'str' object has no attribute 'read'"""
raw_json = json.loads(req.stream.read(), 'UTF-8')
"""Exception: TypeError: the JSON object must be str, not 'bytes'"""
raw_json = json.loads(req.stream, 'UTF-8')
"""TypeError: the JSON object must be str, not 'Body'"""
</code></pre>
<p>I'm on the way of giving up, but if somebody can tell me why this is happening and how to parse JSON in Falcon i would be extremely thankful.</p>
<p>Thanks</p>
<p>Environment:
OSX Sierra
Python 3.5.2
Falcon and other is the latest version from Pip</p>
| 0 | 2016-10-09T18:00:16Z | 39,954,948 | <p>your code should work if other pieces of code are in place . a quick test(filename app.py):</p>
<pre><code>import falcon
import json
class JSON_Middleware(object):
def process_request(self, req, resp):
raw_json = json.loads(req.stream.read())
print raw_json
class Test:
def on_post(self,req,resp):
pass
app = application = falcon.API(middleware=JSON_Middleware())
t = Test()
app.add_route('/test',t)
</code></pre>
<p>run with: <code>gunicorn app</code><br>
<code>$ curl -XPOST 'localhost:8000' -d '{"Hello":"wold"}'</code></p>
| 0 | 2016-10-10T09:14:11Z | [
"python",
"python-3.x",
"falconframework"
] |
finding pattern within csv file | 39,946,798 | <p>I have a CSV Excel file example:</p>
<pre><code>Receipt Name Address Date Time Items
25007 A ABC pte ltd 4/7/2016 10:40 Cheese, Cookie, Pie
.
.
25008 B CCC pte ltd 4/7/2016 12:40 Cheese, Cookie
</code></pre>
<p>What is a simple way to compare the 'Items' column and find out the most common pattern of the items people buy together and display the top combinations?
In this case the similar pattern is Cheese, Cookie.</p>
| 2 | 2016-10-09T18:02:38Z | 39,946,925 | <p>Presuming you have comma separated values, you can use a <em>frozenset</em> of the pairings and use a <em>Counter</em> dict to get the counts:</p>
<pre><code>from collections import Counter
import csv
with open("test.csv") as f:
next(f)
counts = Counter(frozenset(tuple(row[-1].split(",")))
for row in csv.reader(f))
print(counts.most_common())
</code></pre>
<p>If you want all combinations or pairs as per your updated input:</p>
<pre><code>from collections import Counter
from itertools import combinations
def combs(s):
return combinations(s.split(","), 2)
import csv
with open("test.csv") as f:
next(f)
counts = Counter(frozenset(t)
for row in csv.reader(f)
for t in combs(row[-1]))
# counts -> Counter({frozenset(['Cheese', 'Cookie']): 2, frozenset(['Cheese', 'Pie']): 1, frozenset(['Cookie', 'Pie']): 1})
print(counts.most_common())
</code></pre>
<p>The order of the pairings is irrelevant as <code>frozenset([1,2])</code> and <code>frozenset([2,1])</code> would be considered the same.</p>
<p>If you want to consider all combinations from <code>2-n</code>:</p>
<pre><code>def combs(s):
indiv_items = s.split(",")
return chain.from_iterable(combinations(indiv_items, i) for i in range(2, len(indiv_items) + 1))
import csv
with open("test.csv") as f:
next(f)
counts = Counter(frozenset(t)
for row in csv.reader(f)
for t in combs(row[-1]))
print(counts)
print(counts.most_common())
</code></pre>
<p>Which for:</p>
<pre><code>Receipt,Name,Address,Date,Time,Items
25007,A,ABC,pte,ltd,4/7/2016,10:40,"Cheese,Cookie,Pie"
25008,B,CCC,pte,ltd,4/7/2016,12:40,"Cheese,Cookie"
25009,B,CCC,pte,ltd,4/7/2016,12:40,"Cookie,Cheese,pizza"
25010,B,CCC,pte,ltd,4/7/2016,12:40,"Pie,Cheese,pizza"
</code></pre>
<p>would give you:</p>
<pre><code>Counter({frozenset(['Cheese', 'Cookie']): 3, frozenset(['Cheese', 'pizza']): 2, frozenset(['Cheese', 'Pie']): 2, frozenset(['Cookie', 'Pie']): 1, frozenset(['Cheese', 'Cookie', 'Pie']): 1, frozenset(['Cookie', 'pizza']): 1, frozenset(['Pie', 'pizza']): 1, frozenset(['Cheese', 'Cookie', 'pizza']): 1, frozenset(['Cheese', 'Pie', 'pizza']): 1})
[(frozenset(['Cheese', 'Cookie']), 3), (frozenset(['Cheese', 'pizza']), 2), (frozenset(['Cheese', 'Pie']), 2), (frozenset(['Cookie', 'Pie']), 1), (frozenset(['Cheese', 'Cookie', 'Pie']), 1), (frozenset(['Cookie', 'pizza']), 1), (frozenset(['Pie', 'pizza']), 1), (frozenset(['Cheese', 'Cookie', 'pizza']), 1), (frozenset(['Cheese', 'Pie', 'pizza']), 1)]
</code></pre>
| 0 | 2016-10-09T18:15:05Z | [
"python",
"regex",
"csv"
] |
finding pattern within csv file | 39,946,798 | <p>I have a CSV Excel file example:</p>
<pre><code>Receipt Name Address Date Time Items
25007 A ABC pte ltd 4/7/2016 10:40 Cheese, Cookie, Pie
.
.
25008 B CCC pte ltd 4/7/2016 12:40 Cheese, Cookie
</code></pre>
<p>What is a simple way to compare the 'Items' column and find out the most common pattern of the items people buy together and display the top combinations?
In this case the similar pattern is Cheese, Cookie.</p>
| 2 | 2016-10-09T18:02:38Z | 39,947,519 | <p>Suppose after processing the CSV file you find the list of items from the CSV file to be:</p>
<pre><code>>>> items=['Cheese,Cookie,Pie', 'Cheese,Cookie,Pie', 'Cake,Cookie,Cheese',
... 'Cheese,Mousetrap,Pie', 'Cheese,Jam','Cheese','Cookie,Cheese,Mousetrap']
</code></pre>
<p>First determine all possible pairs:</p>
<pre><code>>>> from itertools import combinations
>>> all_pairs={frozenset(t) for e in items for t in combinations(e.split(','),2)}
</code></pre>
<p>Then you can do:</p>
<pre><code>from collections import Counter
pair_counts=Counter()
for s in items:
for pair in {frozenset(t) for t in combinations(s.split(','), 2)}:
pair_counts.update({tuple(pair):1})
>>> pair_counts
Counter({('Cheese', 'Cookie'): 4, ('Cheese', 'Pie'): 3, ('Cookie', 'Pie'): 2, ('Cheese', 'Mousetrap'): 2, ('Cookie', 'Mousetrap'): 1, ('Cheese', 'Jam'): 1, ('Mousetrap', 'Pie'): 1, ('Cake', 'Cheese'): 1, ('Cake', 'Cookie'): 1})
</code></pre>
<p>Which can be extended to a more general case:</p>
<pre><code>max_n=max(len(e.split(',')) for e in items)
for n in range(max_n, 1, -1):
all_groups={frozenset(t) for e in items for t in combinations(e.split(','),n)}
group_counts=Counter()
for s in items:
for group in {frozenset(t) for t in combinations(s.split(','), n)}:
group_counts.update({tuple(group):1})
print 'group length: {}, most_common: {}'.format(n, group_counts.most_common())
</code></pre>
<p>Prints:</p>
<pre><code>group length: 3, most_common: [(('Cheese', 'Cookie', 'Pie'), 2), (('Cheese', 'Mousetrap', 'Pie'), 1), (('Cheese', 'Cookie', 'Mousetrap'), 1), (('Cake', 'Cheese', 'Cookie'), 1)]
group length: 2, most_common: [(('Cheese', 'Cookie'), 4), (('Cheese', 'Pie'), 3), (('Cookie', 'Pie'), 2), (('Cheese', 'Mousetrap'), 2), (('Cookie', 'Mousetrap'), 1), (('Cheese', 'Jam'), 1), (('Mousetrap', 'Pie'), 1), (('Cake', 'Cheese'), 1), (('Cake', 'Cookie'), 1)]
</code></pre>
| 2 | 2016-10-09T19:15:46Z | [
"python",
"regex",
"csv"
] |
All lowest common ancestor with NetworkX | 39,946,894 | <p>I want to get all LCA nodes from node"a" and node"o".</p>
<p>In this DiGraph, node"l" and node"m" are LCA nodes.</p>
<p>The following is the code.</p>
<pre><code>import networkx as nx
def calc_length(Graph, node1, node2, elem):
length1 = nx.shortest_path_length(Graph, node1, elem)
length2 = nx.shortest_path_length(Graph, node1, elem)
length_sum = length1 + length2
return length_sum
G = nx.DiGraph() #Directed graph
G.add_nodes_from(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p"])
edges = [("a","b"),("b","c"),("b","d"),("a","e"),("a","h"),("e","f"),("e","g"),("e","i"),("h","l"),("h","m"),("g","j"),("o","p"),("o","n"),("n","m"),("n","l"),("n","k"),("p","j"),]
G.add_edges_from([(e[0], e[1]) for e in edges])
preds_1 = nx.bfs_predecessors(G, "a")
preds_2 = nx.bfs_predecessors(G, "o")
common_preds = set([n for n in preds_1]).intersection(set([n for n in preds_2]))
common_preds = list(common_preds)
dic ={}
for elem in common_preds:
length_sum = calc_length(G, "a", "o", elem)
dic[elem] = length_sum
min_num = min(dic.values())
for k, v in sorted(dic.items(), key=lambda x:x[1]):
if v != min_num:
break
else:
print k, v
</code></pre>
<p>I want faster execution speed.</p>
<p>Please let me know if you have a better method to solve the problem than the one previously mentioned.</p>
<p>I would be grateful for your help.</p>
| 1 | 2016-10-09T18:11:32Z | 39,967,777 | <p>There are several issues here, some of which I have pointed out in the comments. Part of the problem is that the nomenclature is confusing: the lowest common ancestor (<a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" rel="nofollow">as defined on wikipedia</a> and presumably in computer science in general) really should be named lowest common descendant in order to conform with the nomenclature used by networkx (and any sane network scientist that I know of). Your breadth-first-search should hence really follow the descendants, not the predecessors. The following implements such an LCA search:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import networkx as nx
def find_lowest_common_ancestor(graph, a, b):
"""
Find the lowest common ancestor in the directed, acyclic graph of node a and b.
The LCA is defined as on
@reference:
https://en.wikipedia.org/wiki/Lowest_common_ancestor
Notes:
------
This definition is the opposite of the term as it is used e.g. in biology!
Arguments:
----------
graph: networkx.DiGraph instance
directed, acyclic, graph
a, b:
node IDs
Returns:
--------
lca: [node 1, ..., node n]
list of lowest common ancestor nodes (can be more than one)
"""
assert nx.is_directed_acyclic_graph(graph), "Graph has to be acyclic and directed."
# get ancestors of both (intersection)
common_ancestors = list(nx.descendants(graph, a) & nx.descendants(graph, b))
# get sum of path lengths
sum_of_path_lengths = np.zeros((len(common_ancestors)))
for ii, c in enumerate(common_ancestors):
sum_of_path_lengths[ii] = nx.shortest_path_length(graph, a, c) \
+ nx.shortest_path_length(graph, b, c)
# print common_ancestors
# print sum_of_path_lengths
# return minima
minima, = np.where(sum_of_path_lengths == np.min(sum_of_path_lengths))
return [common_ancestors[ii] for ii in minima]
def test():
nodes = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p"]
edges = [("a","b"),
("b","c"),
("b","d"),
("a","e"),
("a","h"),
("e","f"),
("e","g"),
("e","i"),
("h","l"),
("h","m"),
("g","j"),
("o","p"),
("o","n"),
("n","m"),
("n","l"),
("n","k"),
("p","j"),]
G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
# plot
pos = nx.spring_layout(G)
nx.draw(G, pos)
nx.draw_networkx_labels(G, pos, labels=dict([(c, c) for c in 'abcdefghijklmnop']))
plt.show()
a,b = 'a','o'
lca = find_lowest_common_ancestor(G, a, b)
print "Lowest common ancestor(s) for {} and {}: {}".format(a, b, lca)
return
if __name__ == "__main__":
test()
</code></pre>
| 0 | 2016-10-10T22:35:06Z | [
"python",
"algorithm",
"networkx",
"lowest-common-ancestor"
] |
Kivy does not find fonts in Cygwin | 39,947,005 | <p>I use <code>Kivy</code> in <code>Cygwin.</code></p>
<p>Per <strong>Vasilkov, Mark. <em>Kivy Blueprints</em>. Birmingham:Packt Publishing, 2015. pp. 17</strong>, I wanted to use the <code>Roboto</code> fonts in the following code:</p>
<pre><code># File: main.py
from kivy.app import App
from kivy.core.text import LabelBase
LabelBase.register(name='Roboto',
fn_regular='Roboto-Thin.ttf',
fn_bold='Roboto-Medium.ttf')
class ClockApp(App):
pass
if __name__ == '__main__':
ClockApp().run()
</code></pre>
<p>However, even though <code>Cygwin</code> is aware that the <code>Roboto</code> fonts are installed in <code>/usr/share/fonts/,</code> viz.:</p>
<pre><code>$ fc-list | grep -i robot
/usr/share/fonts/roboto/Roboto-Regular.ttf: Roboto:style=Regular
/usr/share/fonts/roboto/Roboto-LightItalic.ttf: Roboto,Roboto Light:style=Light Italic,Italic
/usr/share/fonts/roboto/Roboto-Bold.ttf: Roboto:style=Bold
/usr/share/fonts/roboto/Roboto-MediumItalic.ttf: Roboto,Roboto Medium:style=Medium Italic,Italic
/usr/share/fonts/roboto/Roboto-ThinItalic.ttf: Roboto,Roboto Thin:style=Thin Italic,Italic
/usr/share/fonts/roboto/RobotoCondensed-Italic.ttf: Roboto Condensed:style=Italic
/usr/share/fonts/roboto/Roboto-Italic.ttf: Roboto:style=Italic
/usr/share/fonts/roboto/Roboto-Black.ttf: Roboto,Roboto Black:style=Black,Regular
/usr/share/fonts/roboto/RobotoCondensed-LightItalic.ttf: Roboto Condensed,Roboto Condensed Light:style=Light Italic,Italic
/usr/share/fonts/roboto/Roboto-Light.ttf: Roboto,Roboto Light:style=Light,Regular
/usr/share/fonts/roboto/RobotoCondensed-Regular.ttf: Roboto Condensed:style=Regular
/usr/share/fonts/roboto/Roboto-BoldItalic.ttf: Roboto:style=Bold Italic
/usr/share/fonts/roboto/RobotoCondensed-BoldItalic.ttf: Roboto Condensed:style=Bold Italic
/usr/share/fonts/roboto/RobotoCondensed-Light.ttf: Roboto Condensed,Roboto Condensed Light:style=Light,Regular
/usr/share/fonts/roboto/RobotoCondensed-Bold.ttf: Roboto Condensed:style=Bold
/usr/share/fonts/roboto/Roboto-Medium.ttf: Roboto,Roboto Medium:style=Medium,Regular
/usr/share/fonts/roboto/Roboto-Thin.ttf: Roboto,Roboto Thin:style=Thin,Regular
/usr/share/fonts/roboto/Roboto-BlackItalic.ttf: Roboto,Roboto Black:style=Black Italic,Italic
</code></pre>
<p>when I run the above Python code, I get:</p>
<pre><code>$ python main.py
[INFO ] [Logger ] Record log in /home/Administrator/.kivy/logs/kivy_16-10-09_18.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.10 (default, Jun 1 2015, 18:17:45)
[GCC 4.9.2]
[INFO ] [Factory ] 179 symbols loaded
[INFO ] [Image ] Providers: img_tex, img_dds, img_gif, img_pygame, img_pil (img_ffpyplayer ignored)
[INFO ] [Text ] Provider: pygame
Traceback (most recent call last):
File "main.py", line 9, in <module>
fn_bold='Roboto-Medium.ttf')
File "/usr/lib/python2.7/site-packages/kivy/core/text/__init__.py", line 223, in register
raise IOError('File {0}s not found'.format(font_type))
IOError: File Roboto-Thin.ttfs not found
</code></pre>
<h2>What should I do to let <code>Kivy</code> use the <code>Roboto</code> fonts?</h2>
| 0 | 2016-10-09T18:23:37Z | 39,964,402 | <p>You have to provide the path of your fonts in your <code>LabelBase.register()</code>. Do you have those font files in your directory?</p>
| 0 | 2016-10-10T18:19:49Z | [
"python",
"fonts",
"cygwin",
"kivy",
"x11"
] |
Sort a csv with python from standard input | 39,947,024 | <p>This is my python script for sorting by column a csv file read from stdin:</p>
<pre><code>with sys.stdin as csvfile:
reader = csv.reader(csvfile, delimiter=',')
sortedlist = sorted(reader, key=operator.itemgetter(2))
for row in sortedlist:
print(','.join(row)),
print('\n'),
</code></pre>
<p>I run the command in order to sort by 3rd column(zero indexed is 2):</p>
<pre><code>./sorter1.py < test.csv > test_sorted.csv
</code></pre>
<p>and the sorted file test_sorted.csv is:</p>
<pre><code>31,53,101,122
88,95,103,59
66,58,104,50
93,46,105,52
88,88,118,107
**115,57,31,34**
110,87,36,63
32,108,36,107
75,35,57,35
99,46,57,28
41,35,67,59
108,99,98,35
36,66,98,60
</code></pre>
<p>It is like sorted two files and merged it. Is it a matter of buffer size of the reader or a matter of sorted method? </p>
<p><strong>This sorts alphabetically not numerically</strong></p>
| 0 | 2016-10-09T18:26:03Z | 39,947,307 | <blockquote>
<p>This sorts alphabetically not numerically</p>
</blockquote>
<p>You'll have to <em>cast</em> the sort column values to integer in order to sort numerically. I have replaced the sort function with a <code>lambda</code> that includes the conversion to <code>int</code>:</p>
<pre><code>sortedlist = sorted(reader, key=lambda x: int(x[2]))
</code></pre>
| 1 | 2016-10-09T18:53:34Z | [
"python",
"sorting",
"csv"
] |
How to continue the object in django get_next/previous_by_date_created and published? | 39,947,041 | <p>Anyone can help me how to continue the object in Django by <code>get_next/previous_by_date_created</code> and published only?</p>
<pre><code>>>> obj_4 = Post.objects.get(pk=4)
>>> obj_4.publish
True
>>> obj_4.get_previous_by_date_created()
<Post: Title Post 3>
>>> obj_4.get_previous_by_date_created().publish
False
>>> obj_4.get_previous_by_date_created().pk
3
>>> obj_2 = Post.objects.get(pk=2)
<Post: Title Post 2>
>>> obj_2.publish
True
>>> obj_4.get_next_by_date_created()
<Post: Title Post 5>
>>> obj_4.get_next_by_date_created().publish
True
>>>
</code></pre>
<p>I need to continue the object by published only. For example:</p>
<pre><code>>>> obj_4 = Post.objects.get(pk=4)
>>> obj_4.get_previous_by_date_created_and_published()
<Post: Title Post 2>
</code></pre>
<p>Other conditions, if we have such as bellow:</p>
<pre><code>pk : [1, 2, 3, 4, 5, 6, 7, 8 ]
publish : [True, False, False, False, True, True, False, True]
</code></pre>
<p>And then, if i starting from <code>pk=5</code>, the output should be <code>pk=1</code>.</p>
<pre><code>>>> obj_5 = Post.objects.get(pk=5)
>>> obj_5.get_previous_by_date_created_and_published().pk
1
>>>
>>> obj_5.get_previous_by_date_created_and_published().publish
True
>>>
</code></pre>
<p>Thanks so much before...</p>
<p><strong>UPDATE SOLVED:</strong></p>
<p><strong>1.</strong> <code>views.py</code></p>
<pre><code>class DetailPostView(generic.DetailView):
model = Post
template_name = 'detail.html'
def get_previous_by_created_and_published(self):
prev = Post.objects.filter(
created__lte=self.get_object().created,
publish=True
).order_by('-created').first()
return prev
def get_next_by_created_and_published(self):
next = Post.objects.filter(
created__gte=self.get_object().created,
publish=True
).order_by('-created').first()
return next
def get_context_data(self, **kwargs):
context_data = super(DetailPostView, self).get_context_data(**kwargs)
context_data[
'get_previous_by_created_and_published'
] = self.get_previous_by_created_and_published()
context_data[
'get_next_by_created_and_published'
] = self.get_next_by_created_and_published()
return context_data
</code></pre>
<p><strong>2.</strong> <code>templates/detail.html</code></p>
<pre><code><ul class="pager">
<li class="previous">
{% if get_previous_by_created_and_published %}
<a href="{% url 'detail_post_page' slug=get_previous_by_created_and_published.slug %}">&larr; Previous</a>
{% endif %}
</li>
<li class="next">
{% if get_next_by_created_and_published %}
<a href="{% url 'detail_post_page' slug=get_next_by_created_and_published.slug %}">Next &rarr;</a>
{% endif %}
</li>
</ul>
</code></pre>
| 0 | 2016-10-09T18:27:58Z | 39,947,399 | <p>An implementation which will work is:</p>
<pre><code>def get_previous_by_created_and_published(self):
prev = Post.objects.filter(created__lte=self.created,
published=True
).order_by('-created').first()
return prev
</code></pre>
<p>Though I'm assuming here that if there are multiple published posts created before this then you'll only want the most recent, as the name of your method suggests.</p>
<p><code>get_next_by_created_and_published</code> will work in a similar manner, though with <code>__gte</code> and the ordering flipped.</p>
| 1 | 2016-10-09T19:02:41Z | [
"python",
"django",
"django-templates"
] |
Tensorflow: method to save and restore TensorFlowEstimator() | 39,947,044 | <p>How to save and load this object (<code>regressor</code>)? </p>
<pre><code>from tensorflow.contrib import learn
regressor = learn.TensorFlowEstimator()
</code></pre>
<p>I could not use tensorflow's default Saver() to save it.</p>
<p>How to do incremental learning with this model? I am confused about <code>continue_training</code> parameter in its constructor. It says you can call fit again and again with new data. And at the same time it provides <code>partial_fit()</code>. Please help me understand ? </p>
| 1 | 2016-10-09T18:28:04Z | 39,947,135 | <p>According to this <a href="https://github.com/tensorflow/skflow#saving--restoring-models" rel="nofollow">TF tutorial</a>, the following should work: </p>
<p>for saving:</p>
<pre><code>regressor.save('/tmp/tf_examples/my_model_1/')
</code></pre>
<p>for restoring:</p>
<pre><code>new_regressor = TensorFlowEstimator.restore('/tmp/tf_examples/my_model_2')
</code></pre>
<hr>
<p>For incremental training: Please refer the following details. They've given pretty much good explanation.</p>
<p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/api_docs/python/functions_and_classes/shard4/tf.contrib.learn.TensorFlowEstimator.md#tfcontriblearntensorflowestimator__init__model_fn-n_classes-batch_size32-steps200-optimizeradagrad-learning_rate01-clip_gradients50-class_weightnone-continue_trainingfalse-confignone-verbose1-tensorflowestimatorinit" rel="nofollow">continue_training</a> - set this to <code>True</code>, the model initialized once and it will be continually trained on every call of fit.</p>
<p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/api_docs/python/functions_and_classes/shard4/tf.contrib.learn.TensorFlowEstimator.md#tfcontriblearntensorflowestimatorpartial_fitx-y-tensorflowestimatorpartial_fit" rel="nofollow">partial_fit</a> - Incremental fit on a batch of samples</p>
| 1 | 2016-10-09T18:36:12Z | [
"python",
"python-3.x",
"machine-learning",
"tensorflow",
"lstm"
] |
One line python code to return all sublists of list containing specific substring in a particluar column | 39,947,119 | <p>I want to return all the sublists of lists which contains specific substring in a particular column:</p>
<p>For eg:</p>
<pre><code>List=[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2003ac"],["2006ab","2005ac"]]
</code></pre>
<p>Search Criteria : Return all sublists which contains substring 2005 at the 2nd index .</p>
<p>Output : </p>
<pre><code>[["2006ab","2005ac"],["2006ab","2005ac"],["2006ab","2005ac"]]
</code></pre>
<p>I tried using : </p>
<pre><code> matching = [s for s in List if "2005" in s[1]]
</code></pre>
<p>but it returns:</p>
<pre><code>[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2005ac"]]
</code></pre>
| 0 | 2016-10-09T18:34:44Z | 39,947,151 | <p>Your list comprehension approach is good and gives the correct result. Are you sure your code is the same from which you pasted the output because it works for me:</p>
<pre><code>>>> List=[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2003ac"],["2006ab","2005ac"]]
>>> [sublist for sublist in List if '2005' in sublist[1]]
[['2006ab', '2005ac'], ['2006ab', '2005ac'], ['2006ab', '2005ac']]
</code></pre>
<p>which is same as what you desire.</p>
<p>If you are looking for an alternative, you may use <code>filter()</code></p>
<pre><code>>>> filter(lambda x: '2005' in x[1], List)
[['2006ab', '2005ac'], ['2006ab', '2005ac'], ['2006ab', '2005ac']]
</code></pre>
| 1 | 2016-10-09T18:37:44Z | [
"python",
"python-2.7",
"python-3.x",
"filter",
"nested-lists"
] |
Python: How to create nested dictionaries out of lists with specific values | 39,947,137 | <p>I apologize in advance for the long post, but I've made sure it's easy to follow and very clear. </p>
<p>My question is this:</p>
<blockquote>
<p>How can I create a nested dictionary out of lists, with specified duplicate keys? </p>
</blockquote>
<p>Here's an example of what I'd like to make, using data for a fictional news article: </p>
<pre><code>{'http://www.SomeNewsWebsite.com/Article12345':
{'Title': 'Trump Does Another Ridiculous Thing',
'Source': 'Some News Website',
'Thumbnail': 'SomeNewsWebsite.com/image12345'}}
</code></pre>
<p>Reading a similar <a href="http://stackoverflow.com/questions/36154563/how-to-create-nested-dictionaries-with-duplicate-keys-in-python">post</a>, I have seen people do similar things but have struggled to port those ideas into my own work. </p>
<p>That's the end of my question. Below, I've posted my code and example lists generated by said code, which is what I'd be using to make this nested dictionary. It's also available on my <a href="https://github.com/JaidenDeChon/headliner.py" rel="nofollow">Github</a>. </p>
<p>So far, I can use the following code to fetch the data, cut out the important bits, and then make two lists-- one for URLs, one for Titles. Then it uses Zip to combine them into a tidy dictionary. </p>
<pre><code>url = "http://www.reuters.com"
source = "Reuters"
thumbnail = "http://logok.org/wp-content/uploads/2014/04/Reuters-logo.png"
def soup():
""" Fetches HTML from site and turns it into a bs4 object. """
get_html = requests.get(url)
html = get_html.text
make_soup = BeautifulSoup(html, 'html.parser')
return make_soup
# Tell bs4 where to find the important information (headlines, URLs)
important_data = (soup().select(".story-content > .story-title > a"))
# Turn that important data into a string so it may be parsed using RegEx
stringed_data = ' || '.join(str(v) for v in important_data)
def get_headline():
""" Uses Regular Expressions to find headlines. Returns a list. """
headline = re.findall(r'(?<=">)(.*?)(?=</a>)', stringed_data)
return headline
def get_link():
""" Uses Regular Expressions to find links. Returns a list. """
link = re.findall(r'(?<=<a href=")(.*?)(?=")', stringed_data)
return link
def build_dict():
""" Combine everything into a tidy dictionary. """
full_urls = [i if i.startswith('http') else url + i for i in get_link()]
reuters_dictionary = dict(zip(get_headline(), full_urls))
return full_urls
get_link()
get_headline()
soup()
build_dict()
</code></pre>
<p>When run, this code will create 2 lists, then a dictionary. Example data is shown below:</p>
<pre><code>List of titles:(29 items long)
['Trump strikes defiant tone ahead of debate', 'Matthew swamps North Carolina, still dangerous as it heads out to sea', "Tesla's Musk says will not have to raise funds in fourth-quarter", 'Suspect arrested in fatal shooting of two California police officers', 'Russia says U.S. actions threaten its national security', 'Western-backed coalition under pressure over Yemen raid', "Fed's Fischer says job gains solid, expects growth to pick up", "Thai king's condition unstable after hemodialysis treatment: palace", 'Pope names new group of cardinals, adding to potential successors', 'Palestinian kills two people in Jerusalem, then shot dead: police', "Commentary: House of Lies â the uncanny allure of 'Girl on the Train'", 'Earnings season begins as White House race heats up', 'Russia expects OPEC to ask non members to consider joining output curb', 'Banks ponder the meaning of life as Deutsche agonizes', 'IMF says still engaged with Greece, no decision yet on bailout role', 'Pound slump exacerbates Brexit impact for German exporters: DIHK', 'Iranian, Iraqi oil ministers will not attend Istanbul talks: sources', 'Ukraine military postpones withdrawal from town, cites rebel shelling', 'German police make new raid in hunt for refugee planning bomb attack', "South African President Zuma's rape accuser dies: family", 'Xi says China must speed up plans for domestic network technology', 'UberEats to expand to Berlin in 2017: Tagesspiegel', 'Beijing, Shanghai propose curbs on who can drive for ride-hailing services', 'Pressure on Trump likely to be intense at second debate with Clinton', "Sanders supporters seethe over Clinton's leaked remarks to Wall St.", 'Evangelical leaders stick with Trump, focus on defeating Clinton', 'Citi sells its Argentinian consumer business to Banco Santander', "Itaú to pay $220 million for Citigroup's Brazil assets", 'LafargeHolcim agrees sale of Chilean business Cemento Polpaico']
List of URLs: (29 items long)
['/article/us-usa-election-idUSKCN1290JZ', '/article/us-storm-matthew-idUSKCN129063', '/article/us-tesla-equity-solarcity-idUSKCN1290QW', '/article/us-california-police-shooting-idUSKCN1280YH', '/article/us-russia-usa-idUSKCN1290DP', '/article/us-yemen-security-coalition-pressure-idUSKCN1290JM', '/article/us-usa-fed-fischer-idUSKCN1290JB', '/article/us-thailand-king-idUSKCN1290R8', '/article/us-pope-cardinals-idUSKCN1290C9', '/article/us-israel-palestinians-violence-idUSKCN129070', '/article/us-society-entertainment-film-idUSKCN127229', '/article/us-usa-stocks-weekahead-idUSKCN1272HS', '/article/us-oil-opec-russia-idUSKCN1290KD', '/article/us-imf-g20-banks-idUSKCN1290DX', '/article/us-imf-g20-greece-idUSKCN1290R6', '/article/us-britain-eu-germany-idUSKCN1290TZ', '/article/us-oil-opec-istanbul-idUSKCN1290N2', '/article/us-ukraine-crisis-withdrawal-idUSKCN1290UL', '/article/us-germany-bomb-idUSKCN1290D2', '/article/us-safrica-zuma-idUSKCN1290SX', '/article/us-china-internet-security-idUSKCN1290LA', '/article/us-uber-germany-eats-idUSKCN1290OB', '/article/us-china-regulations-ride-hailing-idUSKCN1280EL', '/article/us-usa-election-debate-idUSKCN1290AS', '/article/us-usa-election-clinton-idUSKCN1280Z9', '/article/us-usa-election-trump-evangelicals-idUSKCN1280WE', '/article/us-citi-argentina-m-a-banco-santander-ri-idUSKCN1290SD', '/article/us-citibank-brasil-m-a-itau-unibco-hldg-idUSKCN1280HM', '/article/us-lafargeholcim-divestment-chile-idUSKCN1280BU']
Dictionary of titles and URLs: (29 items long)
{'Banks ponder the meaning of life as Deutsche agonizes': 'http://www.reuters.com/article/us-imf-g20-banks-idUSKCN1290DX', 'German police make new raid in hunt for refugee planning bomb attack': 'http://www.reuters.com/article/us-germany-bomb-idUSKCN1290D2', 'Suspect arrested in fatal shooting of two California police officers': 'http://www.reuters.com/article/us-california-police-shooting-idUSKCN1280YH', 'Evangelical leaders stick with Trump, focus on defeating Clinton': 'http://www.reuters.com/article/us-usa-election-trump-evangelicals-idUSKCN1280WE', 'Xi says China must speed up plans for domestic network technology': 'http://www.reuters.com/article/us-china-internet-security-idUSKCN1290LA', "Australia's Rinehart and China's Shanghai CRED agree on deal for Kidman cattle empire": 'http://www.reuters.com/article/us-australia-china-landsale-dakang-p-f-idUSKCN12908O', 'LafargeHolcim agrees sale of Chilean business Cemento Polpaico': 'http://www.reuters.com/article/us-lafargeholcim-divestment-chile-idUSKCN1280BU', 'Citi sells Argentinian consumer unit a day after Brazil sale': 'http://www.reuters.com/article/us-citi-argentina-m-a-banco-santander-ri-idUSKCN1290SD', 'Beijing, Shanghai propose curbs on who can drive for ride-hailing services': 'http://www.reuters.com/article/us-china-regulations-ride-hailing-idUSKCN1280EL', 'Pope names new group of cardinals, adding to potential successors': 'http://www.reuters.com/article/us-pope-cardinals-idUSKCN1290C9', "Commentary: House of Lies â the uncanny allure of 'Girl on the Train'": 'http://www.reuters.com/article/us-society-entertainment-film-idUSKCN127229', 'Iranian, Iraqi oil ministers will not attend Istanbul talks: sources': 'http://www.reuters.com/article/us-oil-opec-istanbul-idUSKCN1290N2', "South African President Zuma's rape accuser dies: family": 'http://www.reuters.com/article/us-safrica-zuma-idUSKCN1290SX', 'Palestinian kills two people in Jerusalem, then shot dead: police': 'http://www.reuters.com/article/us-israel-palestinians-violence-idUSKCN129070', 'Matthew swamps North Carolina, still dangerous as it heads out to sea': 'http://www.reuters.com/article/us-storm-matthew-idUSKCN129063', 'Western-backed coalition under pressure over Yemen raid': 'http://www.reuters.com/article/us-yemen-security-coalition-pressure-idUSKCN1290JM', 'Trump strikes defiant tone ahead of debate': 'http://www.reuters.com/article/us-usa-election-idUSKCN1290JZ', 'Russia says U.S. actions threaten its national security': 'http://www.reuters.com/article/us-russia-usa-idUSKCN1290DP', 'Pressure on Trump likely to be intense at second debate with Clinton': 'http://www.reuters.com/article/us-usa-election-debate-idUSKCN1290AS', "Sanders supporters seethe over Clinton's leaked remarks to Wall St.": 'http://www.reuters.com/article/us-usa-election-clinton-idUSKCN1280Z9', "Tesla's Musk says will not have to raise funds in fourth-quarter": 'http://www.reuters.com/article/us-tesla-equity-solarcity-idUSKCN1290QW', "Fed's Fischer says job gains solid, expects growth to pick up": 'http://www.reuters.com/article/us-usa-fed-fischer-idUSKCN1290JB', 'Ukraine military postpones withdrawal from town, cites rebel shelling': 'http://www.reuters.com/article/us-ukraine-crisis-withdrawal-idUSKCN1290UL', "Thai king's condition unstable after hemodialysis treatment: palace": 'http://www.reuters.com/article/us-thailand-king-idUSKCN1290R8', 'Earnings season begins as White House race heats up': 'http://www.reuters.com/article/us-usa-stocks-weekahead-idUSKCN1272HS', 'IMF says still engaged with Greece, no decision yet on bailout role': 'http://www.reuters.com/article/us-imf-g20-greece-idUSKCN1290R6', 'Pound slump exacerbates Brexit impact for German exporters: DIHK': 'http://www.reuters.com/article/us-britain-eu-germany-idUSKCN1290TZ', 'Russia expects OPEC to ask non members to consider joining output curb': 'http://www.reuters.com/article/us-oil-opec-russia-idUSKCN1290KD', 'UberEats to expand to Berlin in 2017: Tagesspiegel': 'http://www.reuters.com/article/us-uber-germany-eats-idUSKCN1290OB'}
</code></pre>
<p>For clarity, I'd like to use this data to create a dictionary for each pairing of title and URL, like the following:</p>
<pre><code>{'http://www.reuters.com/article/us-imf-g20-banks-idUSKCN1290DX':
{'Title': 'Banks ponder the meaning of life as Deutsche agonizes',
'Source': 'Reuters',
'Thumbnail': 'http://logok.org/wp-content/uploads/2014/04/Reuters-logo.png'}}
</code></pre>
<p>Thanks a ton for taking the time to read, and thank you in advance for your help. </p>
| 0 | 2016-10-09T18:36:14Z | 39,947,916 | <p>Consider a dictionary comprehension:</p>
<pre><code>newsdict = {v: {'Title': k,
'Source': 'Reuters',
'Thumbnail': 'http://logok.org/wp-content/uploads/2014/04/Reuters-logo.png'}
for k, v in reuters_dictionary.items()}
</code></pre>
| 2 | 2016-10-09T19:56:34Z | [
"python",
"python-3.x",
"list-comprehension",
"dict-comprehension"
] |
Python: How to create nested dictionaries out of lists with specific values | 39,947,137 | <p>I apologize in advance for the long post, but I've made sure it's easy to follow and very clear. </p>
<p>My question is this:</p>
<blockquote>
<p>How can I create a nested dictionary out of lists, with specified duplicate keys? </p>
</blockquote>
<p>Here's an example of what I'd like to make, using data for a fictional news article: </p>
<pre><code>{'http://www.SomeNewsWebsite.com/Article12345':
{'Title': 'Trump Does Another Ridiculous Thing',
'Source': 'Some News Website',
'Thumbnail': 'SomeNewsWebsite.com/image12345'}}
</code></pre>
<p>Reading a similar <a href="http://stackoverflow.com/questions/36154563/how-to-create-nested-dictionaries-with-duplicate-keys-in-python">post</a>, I have seen people do similar things but have struggled to port those ideas into my own work. </p>
<p>That's the end of my question. Below, I've posted my code and example lists generated by said code, which is what I'd be using to make this nested dictionary. It's also available on my <a href="https://github.com/JaidenDeChon/headliner.py" rel="nofollow">Github</a>. </p>
<p>So far, I can use the following code to fetch the data, cut out the important bits, and then make two lists-- one for URLs, one for Titles. Then it uses Zip to combine them into a tidy dictionary. </p>
<pre><code>url = "http://www.reuters.com"
source = "Reuters"
thumbnail = "http://logok.org/wp-content/uploads/2014/04/Reuters-logo.png"
def soup():
""" Fetches HTML from site and turns it into a bs4 object. """
get_html = requests.get(url)
html = get_html.text
make_soup = BeautifulSoup(html, 'html.parser')
return make_soup
# Tell bs4 where to find the important information (headlines, URLs)
important_data = (soup().select(".story-content > .story-title > a"))
# Turn that important data into a string so it may be parsed using RegEx
stringed_data = ' || '.join(str(v) for v in important_data)
def get_headline():
""" Uses Regular Expressions to find headlines. Returns a list. """
headline = re.findall(r'(?<=">)(.*?)(?=</a>)', stringed_data)
return headline
def get_link():
""" Uses Regular Expressions to find links. Returns a list. """
link = re.findall(r'(?<=<a href=")(.*?)(?=")', stringed_data)
return link
def build_dict():
""" Combine everything into a tidy dictionary. """
full_urls = [i if i.startswith('http') else url + i for i in get_link()]
reuters_dictionary = dict(zip(get_headline(), full_urls))
return full_urls
get_link()
get_headline()
soup()
build_dict()
</code></pre>
<p>When run, this code will create 2 lists, then a dictionary. Example data is shown below:</p>
<pre><code>List of titles:(29 items long)
['Trump strikes defiant tone ahead of debate', 'Matthew swamps North Carolina, still dangerous as it heads out to sea', "Tesla's Musk says will not have to raise funds in fourth-quarter", 'Suspect arrested in fatal shooting of two California police officers', 'Russia says U.S. actions threaten its national security', 'Western-backed coalition under pressure over Yemen raid', "Fed's Fischer says job gains solid, expects growth to pick up", "Thai king's condition unstable after hemodialysis treatment: palace", 'Pope names new group of cardinals, adding to potential successors', 'Palestinian kills two people in Jerusalem, then shot dead: police', "Commentary: House of Lies â the uncanny allure of 'Girl on the Train'", 'Earnings season begins as White House race heats up', 'Russia expects OPEC to ask non members to consider joining output curb', 'Banks ponder the meaning of life as Deutsche agonizes', 'IMF says still engaged with Greece, no decision yet on bailout role', 'Pound slump exacerbates Brexit impact for German exporters: DIHK', 'Iranian, Iraqi oil ministers will not attend Istanbul talks: sources', 'Ukraine military postpones withdrawal from town, cites rebel shelling', 'German police make new raid in hunt for refugee planning bomb attack', "South African President Zuma's rape accuser dies: family", 'Xi says China must speed up plans for domestic network technology', 'UberEats to expand to Berlin in 2017: Tagesspiegel', 'Beijing, Shanghai propose curbs on who can drive for ride-hailing services', 'Pressure on Trump likely to be intense at second debate with Clinton', "Sanders supporters seethe over Clinton's leaked remarks to Wall St.", 'Evangelical leaders stick with Trump, focus on defeating Clinton', 'Citi sells its Argentinian consumer business to Banco Santander', "Itaú to pay $220 million for Citigroup's Brazil assets", 'LafargeHolcim agrees sale of Chilean business Cemento Polpaico']
List of URLs: (29 items long)
['/article/us-usa-election-idUSKCN1290JZ', '/article/us-storm-matthew-idUSKCN129063', '/article/us-tesla-equity-solarcity-idUSKCN1290QW', '/article/us-california-police-shooting-idUSKCN1280YH', '/article/us-russia-usa-idUSKCN1290DP', '/article/us-yemen-security-coalition-pressure-idUSKCN1290JM', '/article/us-usa-fed-fischer-idUSKCN1290JB', '/article/us-thailand-king-idUSKCN1290R8', '/article/us-pope-cardinals-idUSKCN1290C9', '/article/us-israel-palestinians-violence-idUSKCN129070', '/article/us-society-entertainment-film-idUSKCN127229', '/article/us-usa-stocks-weekahead-idUSKCN1272HS', '/article/us-oil-opec-russia-idUSKCN1290KD', '/article/us-imf-g20-banks-idUSKCN1290DX', '/article/us-imf-g20-greece-idUSKCN1290R6', '/article/us-britain-eu-germany-idUSKCN1290TZ', '/article/us-oil-opec-istanbul-idUSKCN1290N2', '/article/us-ukraine-crisis-withdrawal-idUSKCN1290UL', '/article/us-germany-bomb-idUSKCN1290D2', '/article/us-safrica-zuma-idUSKCN1290SX', '/article/us-china-internet-security-idUSKCN1290LA', '/article/us-uber-germany-eats-idUSKCN1290OB', '/article/us-china-regulations-ride-hailing-idUSKCN1280EL', '/article/us-usa-election-debate-idUSKCN1290AS', '/article/us-usa-election-clinton-idUSKCN1280Z9', '/article/us-usa-election-trump-evangelicals-idUSKCN1280WE', '/article/us-citi-argentina-m-a-banco-santander-ri-idUSKCN1290SD', '/article/us-citibank-brasil-m-a-itau-unibco-hldg-idUSKCN1280HM', '/article/us-lafargeholcim-divestment-chile-idUSKCN1280BU']
Dictionary of titles and URLs: (29 items long)
{'Banks ponder the meaning of life as Deutsche agonizes': 'http://www.reuters.com/article/us-imf-g20-banks-idUSKCN1290DX', 'German police make new raid in hunt for refugee planning bomb attack': 'http://www.reuters.com/article/us-germany-bomb-idUSKCN1290D2', 'Suspect arrested in fatal shooting of two California police officers': 'http://www.reuters.com/article/us-california-police-shooting-idUSKCN1280YH', 'Evangelical leaders stick with Trump, focus on defeating Clinton': 'http://www.reuters.com/article/us-usa-election-trump-evangelicals-idUSKCN1280WE', 'Xi says China must speed up plans for domestic network technology': 'http://www.reuters.com/article/us-china-internet-security-idUSKCN1290LA', "Australia's Rinehart and China's Shanghai CRED agree on deal for Kidman cattle empire": 'http://www.reuters.com/article/us-australia-china-landsale-dakang-p-f-idUSKCN12908O', 'LafargeHolcim agrees sale of Chilean business Cemento Polpaico': 'http://www.reuters.com/article/us-lafargeholcim-divestment-chile-idUSKCN1280BU', 'Citi sells Argentinian consumer unit a day after Brazil sale': 'http://www.reuters.com/article/us-citi-argentina-m-a-banco-santander-ri-idUSKCN1290SD', 'Beijing, Shanghai propose curbs on who can drive for ride-hailing services': 'http://www.reuters.com/article/us-china-regulations-ride-hailing-idUSKCN1280EL', 'Pope names new group of cardinals, adding to potential successors': 'http://www.reuters.com/article/us-pope-cardinals-idUSKCN1290C9', "Commentary: House of Lies â the uncanny allure of 'Girl on the Train'": 'http://www.reuters.com/article/us-society-entertainment-film-idUSKCN127229', 'Iranian, Iraqi oil ministers will not attend Istanbul talks: sources': 'http://www.reuters.com/article/us-oil-opec-istanbul-idUSKCN1290N2', "South African President Zuma's rape accuser dies: family": 'http://www.reuters.com/article/us-safrica-zuma-idUSKCN1290SX', 'Palestinian kills two people in Jerusalem, then shot dead: police': 'http://www.reuters.com/article/us-israel-palestinians-violence-idUSKCN129070', 'Matthew swamps North Carolina, still dangerous as it heads out to sea': 'http://www.reuters.com/article/us-storm-matthew-idUSKCN129063', 'Western-backed coalition under pressure over Yemen raid': 'http://www.reuters.com/article/us-yemen-security-coalition-pressure-idUSKCN1290JM', 'Trump strikes defiant tone ahead of debate': 'http://www.reuters.com/article/us-usa-election-idUSKCN1290JZ', 'Russia says U.S. actions threaten its national security': 'http://www.reuters.com/article/us-russia-usa-idUSKCN1290DP', 'Pressure on Trump likely to be intense at second debate with Clinton': 'http://www.reuters.com/article/us-usa-election-debate-idUSKCN1290AS', "Sanders supporters seethe over Clinton's leaked remarks to Wall St.": 'http://www.reuters.com/article/us-usa-election-clinton-idUSKCN1280Z9', "Tesla's Musk says will not have to raise funds in fourth-quarter": 'http://www.reuters.com/article/us-tesla-equity-solarcity-idUSKCN1290QW', "Fed's Fischer says job gains solid, expects growth to pick up": 'http://www.reuters.com/article/us-usa-fed-fischer-idUSKCN1290JB', 'Ukraine military postpones withdrawal from town, cites rebel shelling': 'http://www.reuters.com/article/us-ukraine-crisis-withdrawal-idUSKCN1290UL', "Thai king's condition unstable after hemodialysis treatment: palace": 'http://www.reuters.com/article/us-thailand-king-idUSKCN1290R8', 'Earnings season begins as White House race heats up': 'http://www.reuters.com/article/us-usa-stocks-weekahead-idUSKCN1272HS', 'IMF says still engaged with Greece, no decision yet on bailout role': 'http://www.reuters.com/article/us-imf-g20-greece-idUSKCN1290R6', 'Pound slump exacerbates Brexit impact for German exporters: DIHK': 'http://www.reuters.com/article/us-britain-eu-germany-idUSKCN1290TZ', 'Russia expects OPEC to ask non members to consider joining output curb': 'http://www.reuters.com/article/us-oil-opec-russia-idUSKCN1290KD', 'UberEats to expand to Berlin in 2017: Tagesspiegel': 'http://www.reuters.com/article/us-uber-germany-eats-idUSKCN1290OB'}
</code></pre>
<p>For clarity, I'd like to use this data to create a dictionary for each pairing of title and URL, like the following:</p>
<pre><code>{'http://www.reuters.com/article/us-imf-g20-banks-idUSKCN1290DX':
{'Title': 'Banks ponder the meaning of life as Deutsche agonizes',
'Source': 'Reuters',
'Thumbnail': 'http://logok.org/wp-content/uploads/2014/04/Reuters-logo.png'}}
</code></pre>
<p>Thanks a ton for taking the time to read, and thank you in advance for your help. </p>
| 0 | 2016-10-09T18:36:14Z | 39,947,955 | <p>This should give you the result you want:</p>
<pre><code>def build_dict():
""" Combine everything into a tidy dictionary. """
full_urls = [i if i.startswith('http') else url + i for i in get_link()]
reuters_dictionary = {}
for (headline, url) in zip(get_headline(), full_urls):
reuters_dictionary[url] = {
'Title': headline,
'Source': source,
'Thumbnail' : thumbnail
}
return full_urls # <- I think you want to do "return reuters_dictionary" here(?)
</code></pre>
<p>However, there is nothing about duplicate keys here. Why do you feel a need for duplicate keys?</p>
<p>Also you should probably refactor to remove those global variables.</p>
<p>At last if you are already using BeatifulSoup, why do you then fall back to regular expressions afterwards? I think using BeautifulSoup everywhere should be more robust.</p>
| 0 | 2016-10-09T20:00:50Z | [
"python",
"python-3.x",
"list-comprehension",
"dict-comprehension"
] |
Python processing how to link with Meteor | 39,947,179 | <p>I have a python script that do some processing over a database of files, the script produce some plots and other relevant numbers as consequence of the analysis. I'm building a Meteor App and what i want , is show the results from my python script inside a Meteor template.</p>
<p>what i wnat is that the entire app works like this :</p>
<p>1) upload file to the database ( done )
2) a button to start the processing of the file by the python script
3) show the results inside the meteor app</p>
<p>so far i have follow <a href="https://forums.meteor.com/t/meteor-python/2563/6" rel="nofollow">this</a> and i'm able to run the script from a meteor button, but how can i use the data generated by the script ( including some plots and relevant numbers) to populate the meteor template? </p>
<p>Thanks for your answer StackOverflow :) </p>
| 0 | 2016-10-09T18:41:24Z | 39,947,569 | <p>In the Meteor Method use the following code :</p>
<pre><code>'methodName':function(){
new Fiber(function(){
console.log('test python file');
var file_path = process.env.PWD + "/path_to_file/hello.py";
exec("python " + file_path, function (error, stdout, stderr) {
if (error) console.log('error'+error);
if (stdout) console.log('stdout'+stdout);
if (stderr) console.log('stderr'+stderr);
});
}).run();
}
</code></pre>
<p>Here <code>stdout</code> contains the output of the python code. You cannot directly use the plots generated from the python as it will be difficult to integrate, however, you can send the data to the meteor and use meteor to generate the plots on the client side using libraries like d3js or plot.ly.</p>
<p>The output data can be a matrix or JSON or can be even a file, which the meteor subsequently reads and does the operation.</p>
<p>EDIT 1: Example to use it in template</p>
<pre><code>'methodName':function(){
new Fiber(function(){
console.log('test python file');
var file_path = process.env.PWD + "/path_to_file/hello.py";
exec("python " + file_path, function (error, stdout, stderr) {
if (error) console.log('error'+error);
else if (stdout) return stdout;
else if (stderr) console.log('stderr'+stderr);
});
}).run();
}
</code></pre>
<p>//In Helper</p>
<pre><code>'helper1': function(){
return Meteor.call('methodName');
}
</code></pre>
<p>//In Html</p>
<pre><code>{{heplper1}}
</code></pre>
| 1 | 2016-10-09T19:19:39Z | [
"javascript",
"python",
"meteor"
] |
Find all combinations of a list | 39,947,298 | <p>The function scoreList(Rack) takes in a list of letters. You are also given a global variable Dictionary: ["a", "am", "at", "apple", "bat", "bar", "babble", "can", "foo", "spam", "spammy", "zzyzva"].</p>
<p>Using a list of letters find all possible words that can be made with the letters that are in the Dictionary. For each word that can be made also find the score of that word using scrabbleScore.</p>
<p>scrabbleScore =</p>
<pre><code> [ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1],
["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8],
["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3],
["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4],
["w", 4], ["x", 8], ["y", 4], ["z", 10] ]
</code></pre>
<p>I can use expressions made up of list comprehensions(map, filter, reduce, etc.), if statements, and for loops but only if they are in the context of a list comprehension.</p>
<p>Example:</p>
<pre><code>>>> scoreList(["a", "s", "m", "t", "p"])
[['a', 1], ['am', 4], ['at', 2], ['spam', 8]]
>>> scoreList(["a", "s", "m", "o", "f", "o"])
[['a', 1], ['am', 4], ['foo', 6]]
</code></pre>
<p>The order in which they are presented does not matter. It also must remain a list and not a dic. Would love some help with this problem or if you could give me a better understanding of how to use map or filter in this problem.</p>
<p>My Code so far:</p>
<pre><code>def scoreList(Rack):
result = [d for d in Dictionary if all(l in Rack for l in d)]
return result
</code></pre>
<p>My Output:</p>
<pre><code> >>> scoreList(["a", "s", "m", "t", "p"])
['a', 'am', 'at', 'spam']
</code></pre>
<p>As you can see I have found out how to output the words but not the score. I also haven't figured out how to implement the use of map, filter, or any other list comprehensions.</p>
| -2 | 2016-10-09T18:52:52Z | 39,947,397 | <p>Apparently you're asking the same question repeatedly (according to a comment on your question). So I'm going to answer this as thoroughly as possible</p>
<p>You seem to have a scrabble dictionary in a list called <code>Dictionary</code>. I'm going to move forward from that point:</p>
<pre><code>import itertools
def scoreList(rack):
points = dict([ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1],
["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8],
["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3],
["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4],
["w", 4], ["x", 8], ["y", 4], ["z", 10] ])
validWords = set(Dictionary)
answer = []
for l in range(1, len(rack)):
for word in itertools.permutations(rack, l):
if not word in validWords: continue
answer.append(word, sum(points[char] for char in word))
return answer
</code></pre>
| 0 | 2016-10-09T19:02:29Z | [
"python",
"list"
] |
Incremental training using TensorFlowEstimator | 39,947,322 | <p>I am using tensorflow for my machine learning model. </p>
<pre><code>from tensorflow.contrib import learn
regressor = learn.TensorFlowEstimator()
</code></pre>
<p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/api_docs/python/functions_and_classes/shard4/tf.contrib.learn.TensorFlowEstimator.md" rel="nofollow">reference</a></p>
<p>How to do incremental learning with model? I am confused about continue_training parameter in its constructor. It says you can call fit again and again with new data. And at the same time it provides partial_fit(). Please help me understand ?</p>
| 0 | 2016-10-09T18:55:24Z | 39,947,532 | <p>You can just use fit() with continue_training; partial_fit will eventually get deprecated.</p>
| 2 | 2016-10-09T19:16:42Z | [
"python",
"python-3.x",
"machine-learning",
"tensorflow"
] |
Big files containing several columns, export all the columns by naming them with the file name and a value | 39,947,344 | <p>Thank you in advance for your answer !
I have lot of files wich contain columns.
I want to export all the columns separately in multiple files.
Moreover, I want to use the first value of each column to be the index of the file name.</p>
<p>For example. If I have the file "test_.dat" which contains 3 columns :</p>
<h2>12 54 159</h2>
<h2>2 9 87</h2>
<h2>5 99 201</h2>
<p>...
...</p>
<h2>91 1 777</h2>
<p>I want three files: "test_12.dat", "test_54.dat" & "test_159.dat".
Where "test_12.dat" is :</p>
<hr>
<h2>2</h2>
<h2>5</h2>
<h2>...</h2>
<h2>...</h2>
<h2>91</h2>
<p>I know that I need to consider two loops (one for the initial files) and another one for the reading/export of the columns.
I know only how tu use append, but this is a very time consuming approach.
I would deeply appreciate your support.
Here is my try:</p>
<p>Find all ".dat" from a folder :</p>
<pre><code>for fname in glob.glob(âtest_*.datâ):
temp=numpy.loadtxt(fname,skiprows=2)
data.append(temp)
namefiles=glob.glob('test*.dat')
</code></pre>
<p>Append all the columns together (Very long step):</p>
<pre><code>for i in range (len(nomfichier)):
for k in range (1,nbrechi+1):
for j in range (points):
ikj.append(data[i][j][k])
</code></pre>
<p>Define two variables to split the variables (points is the number of rows) </p>
<pre><code>seq2=[ikj[i:i+points] for i in range(0, len(ikj), points)]
chunks = [ikj[points*i:points*(i+1)] for i in range(len(ikj)/points + 1)]
</code></pre>
<p>Export the columns in the specific files:</p>
<pre><code>for j in range(len(nomfichier)):
for i in range(len(seq2)/len(namefiles)):
z=z+1
savetxt(namefiles[j][:-4] + « _number_ » + str(flattened[i]) + ".dat", zip(firstcolumn,seq2[z]))
print(namefiles[j][:-4] + « _number_ » + str(flattened[i]))
zz.append(z)
</code></pre>
| 0 | 2016-10-09T18:57:02Z | 39,947,607 | <p>An easy way is to read the large file with <code>pandas</code>, it is designed for big data handling.</p>
<p>To read the data use the following:</p>
<pre><code>import pandas as pd
df = pd.read_csv('test.bat', sep='\s', engine='python', header=None)
</code></pre>
<p>to save the columns as individual files you can use the following code:</p>
<pre><code>for ci in df.columns.values:
data = df[ci]
data.to_csv('test_{}.bat'.format(data[0]))
</code></pre>
<p>You can change the <code>sep</code> depending on what is used in your bat file. The defualt for pandas is a comma but in this case, like in your example data ,I used space. Hope it helps!</p>
| 1 | 2016-10-09T19:23:36Z | [
"python"
] |
Big files containing several columns, export all the columns by naming them with the file name and a value | 39,947,344 | <p>Thank you in advance for your answer !
I have lot of files wich contain columns.
I want to export all the columns separately in multiple files.
Moreover, I want to use the first value of each column to be the index of the file name.</p>
<p>For example. If I have the file "test_.dat" which contains 3 columns :</p>
<h2>12 54 159</h2>
<h2>2 9 87</h2>
<h2>5 99 201</h2>
<p>...
...</p>
<h2>91 1 777</h2>
<p>I want three files: "test_12.dat", "test_54.dat" & "test_159.dat".
Where "test_12.dat" is :</p>
<hr>
<h2>2</h2>
<h2>5</h2>
<h2>...</h2>
<h2>...</h2>
<h2>91</h2>
<p>I know that I need to consider two loops (one for the initial files) and another one for the reading/export of the columns.
I know only how tu use append, but this is a very time consuming approach.
I would deeply appreciate your support.
Here is my try:</p>
<p>Find all ".dat" from a folder :</p>
<pre><code>for fname in glob.glob(âtest_*.datâ):
temp=numpy.loadtxt(fname,skiprows=2)
data.append(temp)
namefiles=glob.glob('test*.dat')
</code></pre>
<p>Append all the columns together (Very long step):</p>
<pre><code>for i in range (len(nomfichier)):
for k in range (1,nbrechi+1):
for j in range (points):
ikj.append(data[i][j][k])
</code></pre>
<p>Define two variables to split the variables (points is the number of rows) </p>
<pre><code>seq2=[ikj[i:i+points] for i in range(0, len(ikj), points)]
chunks = [ikj[points*i:points*(i+1)] for i in range(len(ikj)/points + 1)]
</code></pre>
<p>Export the columns in the specific files:</p>
<pre><code>for j in range(len(nomfichier)):
for i in range(len(seq2)/len(namefiles)):
z=z+1
savetxt(namefiles[j][:-4] + « _number_ » + str(flattened[i]) + ".dat", zip(firstcolumn,seq2[z]))
print(namefiles[j][:-4] + « _number_ » + str(flattened[i]))
zz.append(z)
</code></pre>
| 0 | 2016-10-09T18:57:02Z | 39,948,146 | <pre><code>fps_out = []
with open('test_.dat', 'r') as fp_in:
for line in fp_in:
if not fps_out:
for data in line.split():
fps_out.append(open('test_%s.dat' % data, 'w'))
else:
for pos, data in enumerate(line.split()):
fps_out[pos].write(data + '\n')
for fp in fps_out:
fp.close()
</code></pre>
| 0 | 2016-10-09T20:19:51Z | [
"python"
] |
Subset Sum : Why is DFS + pruning faster than 2 for loop? | 39,947,395 | <p>This issue is leetcode 416 Partition Equal Subset Sum.</p>
<pre><code>#2 for loop, which got TLE
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
allsum = sum(nums)
if allsum % 2 == 1:
return False
subsets = {() : 0}
temp = dict(subsets)
for each in nums:
for subset in subsets:
new = temp[subset] + each
if new * 2 == allsum:
return True
elif new * 2 < allsum:
temp[tuple(list(subset) + [each])] = new
else:
del temp[subset]
subsets = dict(temp)
return False
DFS + pruning:
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
if sum(nums) % 2 != 0:
return False
else:
target = sum(nums) / 2
return self.path(nums, len(nums), target)
def path(self, nums, length, target):#DFS + pruning
if target == 0:
return True
elif target < 0 or (target > 0 and length == 0):
return False
if self.path(nums, length - 1, target - nums[length - 1]):
return True
return self.path(nums, length - 1, target)
</code></pre>
<p>Why is 2 for loop slower than DFS? They both have pruning, and I think the time complexity of DFS, which is a np problem, should be worse than 2 for loop, isn't it?</p>
| 1 | 2016-10-09T19:02:16Z | 39,947,827 | <p>Just because you are using two loops it doesn't mean that your algorithm is in <em>O(n<sup>2</sup>)</em> or polynomial. The complexity of the algorithm depends on how many times each loop executes.
In this part of code:</p>
<pre><code> for each in nums:
for subset in subsets:
....
</code></pre>
<p>The first loop will run <em>n</em> times because the size of <code>nums</code> is <em>n</em> and it doesn't change. However size of <code>subsets</code> is getting 2 times larger after each iteration. So the body of your second <code>for</code> loop will executes <code>1 + 2 + 4 + 8 + 16 + 32 + ... + 2^n = 2^(n+1)</code> times.</p>
<p>So your algorithm is in <em>O(2<sup>n</sup>)</em> without even considering the costly operations (copying <code>list</code>s and <code>dict</code>s) you perform in the body of the second loop.</p>
<p>Your second method (Which is not technically a DFS) is equivalent to your first method in the case complexity. They both are <em>O(n<sup>2</sup>)</em>. But in the second method you do less extra work in comparison to your first method (copying <code>list</code>s and <code>dict</code>s, etc). So your first method will might run faster but it doesn't matter in the long run. Both of this methods won't be efficient enough for a bigger size of input.</p>
<p>Note that this is a very famous problem called <a href="https://en.wikipedia.org/wiki/Subset_sum_problem" rel="nofollow">Subset-sum</a> which is NP-Complete. It can be solved using <a href="http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/" rel="nofollow">Dynamic Programming</a> in <a href="https://en.wikipedia.org/wiki/Pseudo-polynomial_time" rel="nofollow">Pseudo-polynomial time</a>.</p>
| 0 | 2016-10-09T19:45:48Z | [
"python",
"algorithm",
"loops",
"recursion",
"time-complexity"
] |
Django multiple one to many join | 39,947,477 | <p>I have one to many relationship in many places in my Django app.
For example I have user, home and key:</p>
<pre><code>class User(Model):
id_user = models.AutoField(primary_key=True)
class Home(Model):
id_home = models.AutoField(primary_key=True)
id_user = models.ForeignKey('user.User', models.DO_NOTHING, db_column='id_user_home')
class Key(Model):
id_key = models.AutoField(primary=True)
id_home = models.ForeignKey('home.Home', models.DO_NOTHING, db_column='id_home_key')
</code></pre>
<p>From session I have <code>user = User(1)</code> and I want to get all keys for homes of this user.</p>
| 0 | 2016-10-09T19:11:52Z | 39,947,854 | <p>What you are looking for is <code>Key.objects.filter(id_home__id_user=user)</code>. This creates 2 joins such that <code>Key x Home x User</code> and filters on <code>id_user</code>.</p>
<p>You can inspect generated sql with:</p>
<p><code>print(Key.objects.filter(id_home__id_user=user).query)
</code></p>
| 3 | 2016-10-09T19:50:03Z | [
"python",
"django",
"join"
] |
Dimension Error while feeding data in an AlexNet implemented using TensofFlow | 39,947,484 | <p>I am trying to feed my own data using TensorFlow in an AlexNet. I'm using (227 x 227) rgb images while training and the <code>BATCH_SIZE</code> is 50. The following is a part of the code. I'm always getting an error in the line <code>train_accuracy = accuracy.eval( ... )</code></p>
<pre><code>x = tf.placeholder(tf.float32, shape=[None, 227, 227, 3])
x_image = tf.reshape(x, [1, 227, 227, 3])
y_ = tf.placeholder(tf.float32, shape=[None, 5])
train_image_batch, train_label_batch = tf.train.batch([train_image, train_label], batch_size=BATCH_SIZE)
test_image_batch, test_label_batch = tf.train.batch([test_image, test_label], batch_size=BATCH_SIZE)
print train_label_batch.get_shape()
print y_.get_shape()
print "input pipeline ready"
cross_entropy = tf.reduce_mean(-tf.reduce_sum(train_y * tf.log(y_conv), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(train_y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
# initialize the queue threads to start to shovel data
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for i in range(2):
train_batch_image = sess.run(train_image_batch)
train_batch_label = sess.run(train_label_batch)
#if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={x: train_batch_image, y_: train_batch_label, keep_prob: 1.0})
print("step %d, training accuracy %g"%(i, train_accuracy))
train_step.run(feed_dict={x: train_batch_image, y_: train_batch_label, keep_prob: 0.5})
test_batch_image = sess.run(train_image_batch)
test_batch_label = sess.run(train_label_batch)
print("test accuracy %g"%accuracy.eval(feed_dict={x: test_batch_image, y_: test_batch_label, keep_prob: 1.0}))
coord.request_stop()
coord.join(threads)
sess.close()
</code></pre>
<p>The current Error is:</p>
<blockquote>
<p>Traceback (most recent call last):
File "tf_alexnet.py", line 294, in
train_accuracy = accuracy.eval(feed_dict={x: train_batch_image, y_: train_batch_label, keep_prob: 1.0})
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 556, in eval
return _eval_using_default_session(self, feed_dict, self.graph, session)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3649, in _eval_using_default_session
return session.run(tensors, feed_dict)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 382, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 655, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 723, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 743, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: Input to reshape is a tensor with 7729350 values, but the requested shape has 154587
[[Node: Reshape = Reshape[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_0, Reshape/shape)]]
Caused by op u'Reshape', defined at:
File "tf_alexnet.py", line 79, in
x_image = tf.reshape(x, [1, 227, 227, 3])
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1750, in reshape
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 703, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2310, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1232, in <strong>init</strong>
self._traceback = _extract_stack()</p>
</blockquote>
| 0 | 2016-10-09T19:12:46Z | 39,950,787 | <p>The problem is you set batch_size to 50, but trying to reshape x to the form as if you had batch size equal to one. To fix that problem, change 1 in the shape to -1, it would preserve total size of the input.</p>
| 0 | 2016-10-10T03:09:47Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow",
"conv-neural-network"
] |
How to display ndarray images inline during loop in IPython? | 39,947,551 | <p>The following code</p>
<pre><code>%matplotlib inline
for i in range(0, 5):
index = np.random.choice(len(dataset))
print('index:', index)
image = dataset[index, :, :]
print('image shape:', np.shape(image))
plt.imshow(image)
</code></pre>
<p>display five printouts and one single image at the end in <code>jupyter notebook</code>.</p>
<p>Is it possible, to display images on each loop iteration?</p>
<p>I was able to do this with image files with </p>
<pre><code>for fullname in fullnames:
print('fullname:', fullname)
display(Image(filename=fullname))
</code></pre>
<p>Is it possible to do the same with ndarrays?</p>
<p><strong>UPDATE</strong></p>
<p>Writing</p>
<pre><code>for i in range(0, 5):
...
plt.figure()
plt.imshow(image)
</code></pre>
<p>made it better, but not perfect. Images displayed in multiple, but all are AFTER the text.</p>
<p>Should be interleaved.</p>
| 0 | 2016-10-09T19:18:08Z | 39,953,765 | <p>Try:</p>
<pre><code>for i in range(0, 5):
...
plt.figure()
plt.imshow(image)
plt.show()
</code></pre>
<p>With out show the figures are only rendered and displayed after the cell finishes being executed (i.e. exits the <code>for</code> loop). With <code>plt.show()</code> you force rendering after every iteration.</p>
| 1 | 2016-10-10T08:02:21Z | [
"python",
"matplotlib",
"jupyter-notebook"
] |
Fastest way to compute vector in Python | 39,947,565 | <p>I have the following (using Python's pandas):</p>
<p>y: n by 1 dataframe</p>
<p>x: n by k dataframe</p>
<p>theta: k by 1 dataframe</p>
<p>Each of the elements in the above dataframes contains a real number.</p>
<p>I need a dataframe w, where w = y'x (' denotes transpose), but w only contains the observations for which y multiplied element-wise by (x * theta) is less than 1. In other words, the dimension of w is at most n by k, and there will be fewer rows if there are some observations that do not meet the criteria.</p>
<p>What's the fastest way (in terms of time) to get w?</p>
| 1 | 2016-10-09T19:19:15Z | 39,948,799 | <p>Use <code>.values</code> to access underlying numpy arrays</p>
<pre><code>Y = y.values
X = x.values
Th = theta.values
W = Y.T.dot(X)
mask = Y * X.dot(Th) < 1
w = pd.DataFrame(W[mask], y.index[mask])
</code></pre>
| 3 | 2016-10-09T21:36:32Z | [
"python",
"pandas"
] |
Depth-First Search runtime measuring | 39,947,594 | <p>I'm currently studying the Depth-First Search algorithm and although i've confirmed that it does run in O(N+M) it still doesn't show up very well when i measure runtime, since in a graph with 2000 to 16000 nodes, and a constant 50000 edges. The runtime remains almost constant (close to 0,5 seconds), as if the nodes aren't doing much on it. Is there a way to get a more significant change in the runtime without adding too many more nodes?</p>
<p>I'm using an implementation in Python and using the command "time" to measure the runtime.</p>
| 0 | 2016-10-09T19:22:35Z | 39,947,670 | <p>The problem may be that Python has relatively high overhead (reading and analyzing the program). Check out this question: <a href="http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script">How can you profile a Python script?</a>.</p>
<p>More specifically, </p>
<pre><code>python -m cProfile myscript.py
</code></pre>
<p>should show you the total time (<code>tottime</code>) spent on the function that actually does the DFS.</p>
| 1 | 2016-10-09T19:29:17Z | [
"python",
"algorithm",
"time-complexity"
] |
Explain the use of __setattr__ | 39,947,633 | <p>Can you please explain the use of the <code>__setattr__</code> method in the below code :</p>
<pre><code>class Human(object):
def __setattr__(self,name,value):
if name == 'gender':
if value in ('male', 'female'):
self.gender = value
else :
raise AttributeError('Gender can only be Male or Female')
h = Human()
h.name = 'Mary'
h.gender = 'female'
print h.gender
</code></pre>
| -4 | 2016-10-09T19:25:53Z | 39,947,690 | <p>In your code, <code>__setattr__()</code> function is making a validation that while assigning the value of <code>self.gender</code>, it's value should be only between <code>male</code> and <code>female</code>. In case of any other value, it will raise <code>AttributeError</code> exception.</p>
<p><em>Note:</em> In your <code>__setattr__()</code> function, there is no call to <code>super</code> of <code>__setattr__</code>, and hence this function is not actually updating the properties of class. You should add below line in your <code>__setattr__()</code> in order to make it work:</p>
<pre><code>super(Human, self).__setattr__(name, value)
</code></pre>
<hr>
<p><strong>Overview about <a href="https://docs.python.org/2/reference/datamodel.html#object.__setattr__" rel="nofollow"><code>.__setattr__(self, name, value)</code></a></strong>:</p>
<p>Whenever you assign any value to the property of the class, <code>__setattr__(self, name, value)</code> function is called where <code>name</code> is the property of <code>class</code> and <code>value</code> is the new value to be assigned. Below is the sample code to demonstrate that:</p>
<pre><code>>>> class MyClass(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
... def __setattr__(self, name, value):
... print 'In Set Attr for: ', name, ', ', value
... super(MyClass, self).__setattr__(name, value)
...
...
>>> my_object = MyClass(1, 2)
In Set Attr for: x, 1
In Set Attr for: y, 2
>>> my_object.x = 10 # <-- Called while assigning value x
In Set Attr for: x, 10
</code></pre>
| 0 | 2016-10-09T19:31:47Z | [
"python"
] |
Renaming model breakes migration history | 39,947,634 | <p>I have two models in two different apps:</p>
<pre><code># app1 models.py
class App1Model(models.Model):
pass
# app2 models.py
from app1.models import App1Model
class App2Model(App1Model):
pass
</code></pre>
<p>And I want to rename App1Model and then recreate App2Model to have explicit <code>OneToOneField</code> instead of magic <code>app1model_ptr</code>. So I create migration which deletes App2Model completely (I don't care about data because whatever reason), it runs successfully. Then I create migration in first app which renames App1Model and it runs perfect too, I check this table with new name and all it's relationships (and to it too), it's fine.</p>
<p>And then weird thing happens: when I run <code>makemigrations</code> or <code>migrate</code> on app2 I get an error </p>
<pre><code>django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'app2.App2Model'>]
</code></pre>
<p>It fails while creating current project state on very first migration of app2 (0001_initial.py in app2 migrations) where this model was created first time by inheriting from App1Model with its old name.
Is there some way of fixing this? In current state <code>App2Model</code> already deleted, <code>App1Model</code> renamed and I can't do anything with migrations on app2 because of this issue.</p>
<p>P.S. I use Django 1.10.2</p>
| 0 | 2016-10-09T19:25:59Z | 39,948,244 | <p>Just found solution:</p>
<p>Need to add last migration of <code>app2</code> where I deleted <code>App2Model</code> as dependency to migration of <code>app1</code> where I renamed <code>App1Model</code> so project state will be built in correct order. Actually error message itself has something related to it but I failed to catch the point: </p>
<blockquote>
<p>This can happen if you are inheriting models from an app with
migrations (e.g. contrib.auth) in an app with no migrations; see
<a href="https://docs.djangoproject.com/en/1.10/topics/migrations/#dependencies" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/migrations/#dependencies</a>
for more</p>
</blockquote>
<p>I put it here for future me and for those who will suffer from similar thing.</p>
| 2 | 2016-10-09T20:31:47Z | [
"python",
"django",
"database-migration"
] |
PYTHON - How do I remove a function after it's been executed? | 39,947,645 | <p>I'm a bit new to Python programming and I'm trying to create a text-adventure game. I assume I'm using ver 2.7.3?</p>
<p>2.7.3 (default, Jun 22 2015, 19:33:41)
[GCC 4.6.3]</p>
<p>I want to make an inventory system that has a max size. I'm currently using a list for my inventory.</p>
<p>I also want to make some functions a one-time thing; where you can only select one item without choosing another.</p>
<p>Or maybe remove a function <em>after</em> it's been executed?</p>
<p>I assume these have to do with classes, but I'm not really advanced on that whole thing. Here is a sample of my code/game. I would like the player to only select one weaponKind.</p>
<p>Since I have a lot of <code>while True</code> loops, it's safe to say that the player can go back and choose another <code>weaponKind</code>.</p>
<pre><code>inventory = ['pen','apple']
import time
while True:
a2 = raw_input("You begin to download it. The progress bar seems very small, so you decide you'd better do something as time passes. What will you do?" + '\n' + "==> Decide strife specibus" + '\n' + "==> Examine items in (on?) shelf." + '\n' + "==> Doodle on arm" + '\n' + "==> Check inventory" + '\n'+ "==> End game.").upper()
if a2 == 'DOODLE ON ARM':
print("You're a natural tattoo artist. Those stick figured dinosaurs rock.")
if a2 == 'END':
quit()
if a2 == 'CHECK INVENTORY':
print(inventory)
continue
if a2 == 'STRFE':
strife = raw_input("You assume you have to fight monsters in this game. You've heard this is a real-life thing, no VR junk and whatnot. Where will you scour for a weapon? " + '\n' + "==> Scour in the kitchen." + '\n' + "==> Scour in your room. " + '\n' + "==> Scour in the yard.").upper()
if strife == 'KITCHEN':
while True:
a2 = raw_input("You begin to download it. The progress bar seems very small, so you decide you'd better do something as time passes. What will you do?" + '\n' + "==> Decide strife specibus" + '\n' + "==> Examine items in (on?) shelf." + '\n' + "==> Doodle on arm" + '\n' + "==> Check inventory" + '\n'+ "==> End game.").upper()
if a2 == 'DOODLE ON ARM':
print("You're a natural tattoo artist. Those stick figured dinosaurs rock.")
if a2 == 'END':
quit()
if a2 == 'CHECK INVENTORY':
print(inventory)
continue
if a2 == 'STRFE':
strife = raw_input("You assume you have to fight monsters in this game. You've heard this is a real-life thing, no VR junk and whatnot. Where will you scour for a weapon? " + '\n' + "==> Scour in the kitchen." + '\n' + "==> Scour in your room. " + '\n' + "==> Scour in the yard." + '\n').upper()
if strife == 'KITCHEN':
while True:
kitchen = raw_input("You lazily go downstairs to the kitchen. There's a plate of *shudder* Betty Crocker cookies on the island. There's the cupboard full of kitchen supplies where your weapon will be. There's also the fridge. The window suggests it's a bit before noon. What will you do?" + '\n' + "==> Eat cookies" + '\n' + "==> Examine cupboard" + '\n' + "==> Open fridge." + '\n' + "==> Exit Kitchen" + '\n').upper()
if kitchen == 'EAT COOKIES':
print("You hesitate for a moment before grabbing a cookie. Curse that Crocker Corp and its manipulating ways!")
def cookie(food):
cookie = food(name = 'BC cookie')
inventory.append('BC cookie')
print(inventory)
time.sleep(3)
if kitchen == 'EXAMINE CUPBOARD':
while True:
specibi = raw_input("There's a mixer, cheese grater, and knife." + '\n' + "> Choose mixer." '\n' + "> Choose knife." + '\n' + "> Choose grater." + '\n').upper()
if specibi == 'MIXER':
def mixerKind(strife):
mixerkind = strife(name = "BETTY CRACKER")
inventory.append("BETTY CRACKER")
print(inventory)
time.sleep(3)
if specibi == 'KNIFE':
def knifeKind(strife):
knifeKind = strife(name = "BETTY CRACKER")
inventory.append("Kitchen Knife")
print(inventory)
time.sleep(3)
break
if kitchen == 'EXIT':
break
if strife == 'ROOM':
pers = raw_input("You find an item related to your interest in archery which is a ")
if pers == pers:
def originalKind(strife):
ogkind = strife(name = pers)
inventory.append(str(pers))
print(inventory)
</code></pre>
| -1 | 2016-10-09T19:27:02Z | 39,948,449 | <p>Here's some code to get your game started, that includes a nice class-based solution to your problem, and cleans up your code so that you don't have a bunch of random logic everywhere that will be illegible to you next week. I'm sure there will be a gazillion things in here that you don't understand. Google them all, and change arbitrary lines of code and run it to see what happens. Enjoy!</p>
<pre><code># This is how I would solve your problem.
# A room may have various activities that can be performed....
# the different types of activity will have different classes
# an activity will include any logic involved in performing the activity
# e.g. an "ItemChoiceActivity" will have a list of possible items,
# the logic of "only one can be chosen" is inherent to the class
class Activity(object):
pass
class ItemChoiceActivity(Activity):
'''Implements an activity in which the hero chooses one item from a list'''
def __init__(self, description, items):
# pass in a list of Item objects
self.items = ChoiceList(items)
self.description = description
def run(self, hero):
'''Running an activity gives the hero something to do,
then does something to that hero'''
print self.items
i = int(raw_input("Choose an item:"))
hero.pickup_item(self.items[i])
print hero, " has gained a ", self.items[i]
def __str__(self):
return self.description
__repr__=__str__
# Rooms are a linked grid, sort of like a linked list
class Room(object):
'''Implements a Room. A Room has a textual description, and links to other rooms in the dungeon
'''
def __init__(self, description):
self.description = description #e.g "You enter an empty room... There is a skeleton on the floor.... It stinks in here"
self.other_room_descriptions = ChoiceList([])
self.other_rooms = []
self.activities = ChoiceList([])
def add_link(self, other_room, link_description):
''' Add a link to another room in the dungeon.
other_room := the other room to link to
link_description := "north", "south", "secret passage behind the dumpster", etc.
'''
# you can iterate through these to describe the directions the hero can go
self.other_rooms.append(other_room)
self.other_room_descriptions.append(link_description)
def add_activity(self, activity):
self.activities.append(activity)
def perform_activity(self, i, hero):
self.activities[i].run(hero)
self.activities.pop(i)
def __str__(self):
return self.description
__repr__=__str__
class Item(object):
def __init__(self, description):
self.description = description #e.g "staff of healing +2"
def __str__(self):
return self.description
__repr__ = __str__
class ChoiceList(list):
'''Just a list of Items, or whatever, but has a nice string repr to display to user'''
def __str__(self):
this = ""
for i in range(len(self)):
this += str(i) + ": " + str(self[i]) + "\n"
return this
__repr__ = __str__
class Hero(object):
def __init__(self, description):
MAX_INVENTORY_SIZE = 10
self.description = description
self.inventory = ChoiceList([None]*MAX_INVENTORY_SIZE) #Have a static size list to do the standard 'inventory slots' type thing
def pickup_item(self, item):
'''Return true if pickup successful, false if no slots available
this allows the game to handle the situation that the hero
cannot hold the item... should be handled in the activity'''
for i in range(len(self.inventory)):
if self.inventory[i] is None:
self.inventory[i] = item
return True
return False
def drop_item(self, i):
'''Drop item at index i... using indices, because that's probably how they will be represented to the user... e.g. user calls "list items" and they get a list 1:staff, 2:wand, etc., then they pick an item by it's index.
Returns the item dropped'''
item = self.inventory[i]
self.inventory[i] = None
return item
def __str__(self):
return self.description
__repr__=__str__
class Game(object):
def __init__(self, current_room, hero):
self.current_room = current_room
self.hero = hero
self.options = ChoiceList(["Activity", "Move"])
def main_loop(self):
print self.current_room.description
print self.options
what_to_do = int(raw_input("What to do?"))
if what_to_do == self.options.index("Activity"):
print self.current_room.activities
activity = int(raw_input("Choose an activity:"))
self.current_room.perform_activity(activity, hero)
elif what_to_do == self.options.index("Move"):
print self.current_room.other_room_descriptions
room = int(raw_input("Choose a room:"))
self.current_room = self.current_room.other_rooms[room]
if __name__ == "__main__":
room1 = Room("A really swell room. Just great, really.")
room1.add_activity(ItemChoiceActivity("Choose your first weapon", [Item('staff'), Item('pickle')]))
room2 = Room("A dead end")
room1.add_link(room2, "a door to the north")
room2.add_link(room1, "a door to the south")
hero = Hero("some redneck guy")
game = Game(room1, hero)
while True:
game.main_loop()
</code></pre>
| 2 | 2016-10-09T20:57:20Z | [
"python",
"python-2.7",
"adventure"
] |
Webscraper in Python - How do I extract exact text I need? | 39,947,699 | <p>Good day</p>
<p>I am trying to write my first webscraper. I have managed to write the following:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
s = requests.Session()
r = s.get("http://www.sharenet.co.za/v3/quickshare.php?scode=BTI")
r = s.post("http://www.sharenet.co.za/v3/quickshare.php?scode=BTI")
soup = BeautifulSoup(r.text, "html.parser")
print(soup.find_all("td", class_="dataCell"))
</code></pre>
<p>I am trying to extract a share price. When Inspect the element this is the HTML code:</p>
<pre><code><td class="dataCell" align="right">85221</td>
</code></pre>
<p><a href="http://i.stack.imgur.com/Vi8e1.png" rel="nofollow">Image of share price table</a></p>
<p>Basically, my issue is that can search for all the tags but can't extract the exact tag I want.</p>
<p>Thanks in advance for any help.</p>
| 0 | 2016-10-09T19:32:27Z | 39,947,719 | <p>Tags have a <code>get_text()</code> method. <code>find_all</code> returns a list of tags.</p>
<pre><code>for cell_tag in soup.find_all("td"):
print(cell_tag.get_text())
</code></pre>
| 4 | 2016-10-09T19:34:25Z | [
"python",
"beautifulsoup"
] |
Most efficient way to find the number of possible unique fixed length permutations? | 39,947,858 | <p>I've got this dictionary:</p>
<pre><code>num_dict = {
(2, 3): [(2, 2), (4, 4), (4, 5)],
(2, 2): [(2, 3), (4, 4), (4, 5)],
(4, 5): [(4, 4)],
(1, 0): [(1, 1), (2, 2), (2, 3), (4, 4), (4, 5)],
(4, 4): [(4, 5)],
(1, 1): [(1, 0), (2, 2), (2, 3), (4, 4), (4, 5)],
}
</code></pre>
<p>I need to find the max number of 3 long combinations of the first values of each of these tuples, where only the values of each key can proceed said key.</p>
<p>My current code for finding all unique (3 long) combinations is this:</p>
<pre><code>ans_set = set()
for x in num_dict:
for y in num_dict[x]:
for z in num_dict[y]:
ans_set.add((x[0], y[0], z[0]))
return len(ans_set)
</code></pre>
<p><em>This returns</em> <code>10</code> and <code>ans_set</code> ends up being:</p>
<pre><code>{
(2, 2, 2), (1, 2, 2), (1, 4, 4),
(2, 2, 4), (1, 1, 2), (4, 4, 4),
(1, 2, 4), (1, 1, 4), (1, 1, 1),
(2, 4, 4)
}
</code></pre>
<p><em>But I don't actually care about what the sets are, just the number of them</em></p>
<p>This method is not particularly efficient as it actually generates every possible combination and puts it in a set.</p>
<p>I don't need to know each unique combination, I just need to know how many there are.</p>
<p>I have a feeling this can be done, maybe using the lengths of the value lists? but I am having trouble wrapping my head around it.</p>
<p>Clarifying questions about what I need are welcome as I realize I might not have explained it in the most clear fashion.</p>
<h1>Final Edit</h1>
<p>I've found the best way to find the number of triples by reevaluating what i needed it to do. This method doesn't actually find the triples, it just counts them.</p>
<pre><code>def foo(l):
llen = len(l)
total = 0
cache = {}
for i in range(llen):
cache[i] = 0
for x in range(llen):
for y in range(x + 1, llen):
if l[y] % l[x] == 0:
cache[y] += 1
total += cache[x]
return total
</code></pre>
<p>And here's a version of the function that explains the thought process as it goes (not good for huge lists though because of spam prints):</p>
<pre><code>def bar(l):
list_length = len(l)
total_triples = 0
cache = {}
for i in range(list_length):
cache[i] = 0
for x in range(list_length):
print("\n\nfor index[{}]: {}".format(x, l[x]))
for y in range(x + 1, list_length):
print("\n\ttry index[{}]: {}".format(y, l[y]))
if l[y] % l[x] == 0:
print("\n\t\t{} can be evenly diveded by {}".format(l[y], l[x]))
cache[y] += 1
total_triples += cache[x]
print("\t\tcache[{0}] is now {1}".format(y, cache[y]))
print("\t\tcount is now {}".format(total_triples))
print("\t\t(+{} from cache[{}])".format(cache[x], x))
else:
print("\n\t\tfalse")
print("\ntotal number of triples:", total_triples)
</code></pre>
| 0 | 2016-10-09T19:50:27Z | 39,947,997 | <p>If i get you right:</p>
<pre><code>from itertools import combinations
num_dict = {
(2, 3): [(2, 2), (4, 4), (4, 5)],
(2, 2): [(2, 3), (4, 4), (4, 5)],
(4, 5): [(4, 4)],
(1, 0): [(1, 1), (2, 2), (2, 3), (4, 4), (4, 5)],
(4, 4): [(4, 5)],
(1, 1): [(1, 0), (2, 2), (2, 3), (4, 4), (4, 5)]
}
set(combinations([k[0] for k in num_dict.keys()], 3))
</code></pre>
<p>Output:</p>
<pre><code>{(1, 4, 1),
(2, 1, 1),
(2, 1, 4),
(2, 2, 1),
(2, 2, 4),
(2, 4, 1),
(2, 4, 4),
(4, 1, 1),
(4, 1, 4),
(4, 4, 1)}
</code></pre>
<p>And <code>len()</code> is <code>10</code></p>
<p>So basically what you're would do, make all combinations with <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations</code></a>, from first elements of dict keys with a length 3 and then get <code>set</code> to eliminate repeating elements.</p>
<p><strong>UPDATE</strong></p>
<p>Since you updated the question with desired output data</p>
<p>You can do the following</p>
<pre><code>from itertools import combinations_with_replacement
list(combinations_with_replacement(set([k[0] for k in num_dict.keys()]), 3))
</code></pre>
<p>Output:</p>
<pre><code>[(1, 1, 1),
(1, 1, 2),
(1, 1, 4),
(1, 2, 2),
(1, 2, 4),
(1, 4, 4),
(2, 2, 2),
(2, 2, 4),
(2, 4, 4),
(4, 4, 4)]
</code></pre>
<p><strong>UPD2</strong></p>
<p>So about time consumption i've ran it</p>
<pre><code>num_dict = {
(2, 3): [(2, 2), (4, 4), (4, 5)],
(2, 2): [(2, 3), (4, 4), (4, 5)],
(4, 5): [(4, 4)],
(1, 0): [(1, 1), (2, 2), (2, 3), (4, 4), (4, 5)],
(4, 4): [(4, 5)],
(1, 1): [(1, 0), (2, 2), (2, 3), (4, 4), (4, 5)]
}
def a(num_dict):
ans_set = set()
for x in num_dict:
for y in num_dict[x]:
for z in num_dict[y]:
ans_set.add((x[0], y[0], z[0]))
return len(ans_set)
def b(num_dict):
from itertools import combinations_with_replacement
return len(list(combinations_with_replacement(set([k[0] for k in num_dict.keys()]), 3)))
%timeit a(num_dict)
%timeit b(num_dict)
</code></pre>
<p>And the the results are:</p>
<pre><code>The slowest run took 4.90 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 12.1 µs per loop
The slowest run took 5.37 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.77 µs per loop
</code></pre>
<p>So solution that i've presented here is 2x times faster.</p>
| 1 | 2016-10-09T20:05:24Z | [
"python",
"algorithm"
] |
OpenCV: Save frame matrix to text file (Python) | 39,947,903 | <p>I have got a USB connected webcam and want to save captured frame to text file. Frame is numpy array and i need to get only red color values. So, here's my code: </p>
<pre><code>vc = cv2.VideoCapture(1)
if vc.isOpened():
rval, frame = vc.read()
frame = imutils.resize(frame, width=640, height=480)
print(frame[...,...,2])
savetxt('../test.txt', frame[...,...,2])
</code></pre>
<p><strong>print</strong> gets me this:</p>
<p>[[127 125 125 ..., 114 118 101]</p>
<p>[123 126 125 ..., 111 112 100]</p>
<p>[129 124 122 ..., 116 116 100]</p>
<p>..., </p>
<p>[121 120 121 ..., 97 104 88]</p>
<p>[118 121 121 ..., 96 103 90]</p>
<p>[116 122 120 ..., 97 105 90]]</p>
<p>But even if I could print the whole array, it does not fit terminal window.
So i'd like to save it to file but <strong>savetxt</strong> func is not working as I want. Here's the beginning of test.txt:
1.270000000000000000e+02 1.250000000000000000e+02 1.250000000000000000e+02 </p>
<p>and so on.</p>
<p>I'm using OpenCv 3.1 and Python 2.7.12 </p>
<p>Any help? </p>
| 1 | 2016-10-09T19:55:39Z | 39,947,957 | <p><code>savetxt</code> default format is <code>'%.18e'</code> which explains the format you're getting.</p>
<pre><code>numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ')[source]¶
</code></pre>
<p>Change the format specifier with <code>fmt</code> parameter to print integers instead of floats:</p>
<pre><code>savetxt('../test.txt', frame[...,...,2],fmt="%d")
</code></pre>
| 1 | 2016-10-09T20:00:51Z | [
"python",
"osx",
"opencv",
"numpy"
] |
TypeError remains: Str object is not callable | 39,947,940 | <p>I'm trying to make a python program that converts a 24-hour notation to a 12-hour notation, but the linux shell keeps saying: 'Str' object is not callable.
I'm looking for hours now but can't find the solution?
Do you people see it?</p>
<p>def time(time, hours, minutes):</p>
<pre><code> """ Changes time from 24-hour notation to 12-hour notation and adds postfix"""
if int(hours) > 12:
x = ("{0:<20}, is the same time as{1:>20}{2:>20}".format(time, hours -12 + ":" + minutes, "PM"))
return x
if int(hours) < 12 and int(minutes) != 00 :
x = ("{0:<20}, is the same time as{1:>20}{2:>20}".format(time, time, "AM"))
return x
if int(hours) == 00 and int(minutes) == 00:
x = ("{0:<20}, is the same time as{1:>20}{2:>20}".format(time, hours +12 + ":" + minutes, "AM"))
return x
if int(hours) == 12 and int(minutes) == 00:
x = ("{0:<20}, is the same time as{1:>20}{2:>20}".format(time, time , "PM"))
return x
</code></pre>
<p>def main():</p>
<pre><code> print("{0:^30}".format("24h times converted to 12h times"))
for time in sys.stdin:
hours, minutes = time.split(':')
y = time(time,hours, minutes)
print (y)
</code></pre>
<p>if <strong>name</strong> == "<strong>main</strong>":
main()</p>
| -6 | 2016-10-09T19:59:03Z | 39,947,972 | <p>In the main loop you are using same name for the Function and the String i.e "time".
This is causing ambiguity. Give them a different name and it will work fine.
Use Like this.</p>
<pre><code>for timeString in sys.stdin:
hours, minutes = timeString.split(':')
y = time(timeString,hours, minutes)
print (y)
</code></pre>
<p>Hope this helps.</p>
| 0 | 2016-10-09T20:02:08Z | [
"python",
"string",
"object",
"typeerror"
] |
Block tag inside url_for() in Jinja2 | 39,947,941 | <p>I'm using Jinja2 to render my frontend (and python is on the backend). Each page will have a different image on its top, like this:</p>
<pre><code><header>
<img src="static/img/pic1.png">
</header>
</code></pre>
<p>I used <em>url_for()</em> to get the correct path of my static folder:</p>
<pre><code><header>
<img src="{{ url_for('static', filename='img/pic1.png') }}">
</header>
</code></pre>
<p>So far, so good. But I would like to put a block inside the filename parameter, so I can reuse the code and only overwrite the name of the image. This is what I'm trying:</p>
<pre><code><header>
<img src="{{ url_for('static', filename='{% block img %}img/pic1.png{% endblock %}') }}">
</header>
</code></pre>
<p>But it doesn't work, this is the final code that is rendered by Jinja2:</p>
<pre><code><header>
<img src="/static/%7B%25%20block%20img%20%25%7Dimg/pic1.png%7B%25%20endblock%20%25%7D">
</header>
</code></pre>
<p>As you can see, Jinja2 doesn't recognize the <em>block</em> tag as an expression and treats it as a string. If it worked, I would be able to set the picture of each page only using this code:</p>
<pre><code>{% extends "base.html" %}
{% block img %}img/pic2.png{% endblock %}
...
</code></pre>
<p>Could someone help, please? By the way, <a href="http://stackoverflow.com/questions/32024551/reference-template-variable-within-jinja-expression">this</a> post didn't help me.</p>
| 0 | 2016-10-09T19:59:05Z | 39,948,209 | <p>What you need is a <strong>macro</strong> to define a kind of function in your template. See this topic in
<a href="http://jinja.pocoo.org/docs/dev/templates/" rel="nofollow">http://jinja.pocoo.org/docs/dev/templates/</a></p>
<pre><code>{% macro header_img(name) -%}
<img src="{{ url_for('static', filename=name) }}">
{%- endmacro %}
</code></pre>
<p>You can put this macro in an util template and <a href="http://jinja.pocoo.org/docs/dev/templates/#import" rel="nofollow">import</a> it in each page.</p>
<p>Use the syntax:</p>
<pre><code><header>{{ header_img("your_image.jpg") }}</header>
</code></pre>
| 2 | 2016-10-09T20:27:45Z | [
"python",
"frontend",
"jinja2"
] |
"Int" object not iterable for a leap year program | 39,947,965 | <p>I am making a program to calculate if the given input is a leap year or not. I am using Python 2.7 on Windows 10 with Anaconda Shell.
It's a silly program and I dont understand why I am getting this error. There are a couple of solutions to this particular program online but I want to make my version work. Please help!</p>
<p>I am getting the error message "TypeError: 'int' object is not iterable"
I tried googling stuff and looking through some previous answers here but I am confused!</p>
<pre><code>def sort_year(user_input):
for i,j in range(0,9):
if user_input == [ij00]:
leap_yr1(user_input)
else:
leap_yr2(user_input)
def leap_yr1(user_input):
if user_input % 400 == 0:
print("The given year is a leap year")
else:
print("The given year is not a leap year")
def leap_yr2(user_input):
if user_input % 4 == 0:
print("The given year is a leap year")
else:
print("The given year is not a leap year")
print("Which year do you want to check?: ")
user_input = int(raw_input())
sort_year(user_input)
</code></pre>
| -3 | 2016-10-09T20:01:20Z | 39,948,149 | <p>I think you try to write</p>
<pre><code>for i in range(0,9):
for j in range(0,9):
</code></pre>
<p>But I think you try to check two last digits in <code>user_input</code> so you don't need <code>for</code>. </p>
<p>If <code>number</code> has <code>00</code> at the end then <code>number % 100 == 0</code> (here <code>%</code> means function <code>modulo</code>)</p>
<pre><code>def sort_year(user_input):
if user_input % 100 == 0:
leap_yr1(user_input)
else:
leap_yr2(user_input)
</code></pre>
| 3 | 2016-10-09T20:20:26Z | [
"python",
"python-2.7",
"int",
"iterable"
] |
counting back generations of a number | 39,947,975 | <p>I am trying to reverse engineer a set of numbers given to me (f,m) I need to go through and find how many generations it takes starting from 1,1 using the algorithm below for each generation:</p>
<pre><code>x = 1
y = 1
new_generation = y+x
x OR y = new_generation
</code></pre>
<p>IE, I do not know if X, or Y is changed, the other variable is left the same... A list of possible outputs would look like this for the ending values of 4 and 7:</p>
<pre><code>f = 4
m = 7
[1, 1]
[2, 1, 1, 2]
[3, 1, 2, 3, 3, 2, 1, 3]
[4, 1, 3, 4, 5, 3, 2, 5, 5, 2, 3, 5, 4, 3, 1, 4]
[5, 1, 4, 5, **7, 4**, 3, 7, 7, 5, 2, 7, 7, 2, 5, 7, 7, 3, **4, 7**, 5, 4, 1, 5]
</code></pre>
<p>Where every two sets of numbers (2,1) and (1,2) are a possible output. Note the ** denote the answer (in this case the order doesn't matter so long as both m and f have their value in the list).</p>
<p>Clearly there is exponential growth here, so I can't (or it less efficient) to make a list and then find the answer; instead I am using the following code to reverse this process...</p>
<pre><code>def answer(m,f):
#the variables will be sent to me as a string, so here I convert them...
m = (int(m))
f = (int(f))
global counter
#While I have not reduced my given numbers to my starting numbers....
while m != 1 or f != 1:
counter +=1
#If M is greater, I know the last generation added F to M, so remove it
if m > f:
m = m-f
#If F is greater, I know the last generation added M to M, so remove it
elif f > m:
f = f-m
else:
#They can never be the same (one must always be bigger, so if they are the same and NOT 1, it can't be done in any generation)
return "impossible"
return str(counter)
print(answer("23333","30000000000"))
</code></pre>
<p>This returns the correct answer (for instance, 4,7 returns "4" which is correct) but it takes to long when I pass larger numbers (I must be able to handle 10^50, insane amount, I know!).
<hr>
My thought was I should be able to apply some mathematical equation to the number to reduce it and them multiple the generations, but I'm having trouble finding a way to do this that also holds the integrity of the answer (for instance, if I divide the bigger by the smaller, on small numbers (7, 300000) I get a very close (but wrong) answer, however on closer numbers such as (23333, 300000) the answer is no where even close, which makes sense due to the differences in the generation path). Note I have also tried this in a recursive function (to find generations) and using the a non-reversed method (building the list and checking the answer; which was significantly slower for obvious reasons)</p>
<p><hr>
Here are some test cases with their answers:</p>
<blockquote>
<pre><code>f = "1"
m = "2"
Output: "1"
f = "4"
m = "7"
Output: "4"
f = "4"
m = "2"
Output: "impossible"
</code></pre>
</blockquote>
<p>Any help is much appreciated! P.S. I am running Python 2.7.6</p>
<p>[EDIT]
<hr>
The below code is working as desired.</p>
<pre><code>from fractions import gcd
def answer(m,f):
#Convert strings to ints...
m = (int(m))
f = (int(f))
#If they share a common denominator (GCD) return impossible
if gcd(m,f) != 1:
return "impossible"
counter = 0
#While there is still a remainder...
while m != 0 and f != 0:
if m > f:
counter += m // f
#M now equals the remainder.
m %= f
elif f > m:
counter += f // m
f %= m
return str(counter - 1)
</code></pre>
| 3 | 2016-10-09T20:02:15Z | 39,948,580 | <p>Try a form of recursion:</p>
<p>(Python 2.7.6)</p>
<pre><code>def back():
global f,m,i
if f<m:
s=m//f
i+=s
m-=s*f
elif m<f:
s=f//m
i+=s
f-=s*m
else:
return False
return True
while True:
f=int(raw_input('f = '))
m=int(raw_input('m = '))
i=0
while True:
if f==m==1:
print 'Output:',str(i)
break
else:
if not back():
print 'Output: impossible'
break
print
</code></pre>
<p>(Python 3.5.2)</p>
<pre><code>def back():
global f,m,i
if f<m:
s=m//f
i+=s
m-=s*f
elif m<f:
s=f//m
i+=s
f-=s*m
else:
return False
return True
while True:
f=int(input('f = '))
m=int(input('m = '))
i=0
while True:
if f==m==1:
print('Output:',str(i))
break
else:
if not back():
print('Output: impossible')
break
print()
</code></pre>
<p>Note: I am a Python 3.5 coder so I have tried to backdate my code, please let me know if there is something wrong with it.</p>
<p>The input format is also different: instead of <code>f = "some_int"</code> it is now <code>f = some_int</code>, and the output is formatted similarly.</p>
| 0 | 2016-10-09T21:11:24Z | [
"python",
"loops",
"recursion",
"mathematical-optimization"
] |
counting back generations of a number | 39,947,975 | <p>I am trying to reverse engineer a set of numbers given to me (f,m) I need to go through and find how many generations it takes starting from 1,1 using the algorithm below for each generation:</p>
<pre><code>x = 1
y = 1
new_generation = y+x
x OR y = new_generation
</code></pre>
<p>IE, I do not know if X, or Y is changed, the other variable is left the same... A list of possible outputs would look like this for the ending values of 4 and 7:</p>
<pre><code>f = 4
m = 7
[1, 1]
[2, 1, 1, 2]
[3, 1, 2, 3, 3, 2, 1, 3]
[4, 1, 3, 4, 5, 3, 2, 5, 5, 2, 3, 5, 4, 3, 1, 4]
[5, 1, 4, 5, **7, 4**, 3, 7, 7, 5, 2, 7, 7, 2, 5, 7, 7, 3, **4, 7**, 5, 4, 1, 5]
</code></pre>
<p>Where every two sets of numbers (2,1) and (1,2) are a possible output. Note the ** denote the answer (in this case the order doesn't matter so long as both m and f have their value in the list).</p>
<p>Clearly there is exponential growth here, so I can't (or it less efficient) to make a list and then find the answer; instead I am using the following code to reverse this process...</p>
<pre><code>def answer(m,f):
#the variables will be sent to me as a string, so here I convert them...
m = (int(m))
f = (int(f))
global counter
#While I have not reduced my given numbers to my starting numbers....
while m != 1 or f != 1:
counter +=1
#If M is greater, I know the last generation added F to M, so remove it
if m > f:
m = m-f
#If F is greater, I know the last generation added M to M, so remove it
elif f > m:
f = f-m
else:
#They can never be the same (one must always be bigger, so if they are the same and NOT 1, it can't be done in any generation)
return "impossible"
return str(counter)
print(answer("23333","30000000000"))
</code></pre>
<p>This returns the correct answer (for instance, 4,7 returns "4" which is correct) but it takes to long when I pass larger numbers (I must be able to handle 10^50, insane amount, I know!).
<hr>
My thought was I should be able to apply some mathematical equation to the number to reduce it and them multiple the generations, but I'm having trouble finding a way to do this that also holds the integrity of the answer (for instance, if I divide the bigger by the smaller, on small numbers (7, 300000) I get a very close (but wrong) answer, however on closer numbers such as (23333, 300000) the answer is no where even close, which makes sense due to the differences in the generation path). Note I have also tried this in a recursive function (to find generations) and using the a non-reversed method (building the list and checking the answer; which was significantly slower for obvious reasons)</p>
<p><hr>
Here are some test cases with their answers:</p>
<blockquote>
<pre><code>f = "1"
m = "2"
Output: "1"
f = "4"
m = "7"
Output: "4"
f = "4"
m = "2"
Output: "impossible"
</code></pre>
</blockquote>
<p>Any help is much appreciated! P.S. I am running Python 2.7.6</p>
<p>[EDIT]
<hr>
The below code is working as desired.</p>
<pre><code>from fractions import gcd
def answer(m,f):
#Convert strings to ints...
m = (int(m))
f = (int(f))
#If they share a common denominator (GCD) return impossible
if gcd(m,f) != 1:
return "impossible"
counter = 0
#While there is still a remainder...
while m != 0 and f != 0:
if m > f:
counter += m // f
#M now equals the remainder.
m %= f
elif f > m:
counter += f // m
f %= m
return str(counter - 1)
</code></pre>
| 3 | 2016-10-09T20:02:15Z | 39,948,598 | <p>This is not a Python question, nor is it really a programming question. This is a problem designed to make you <em>think</em>. As such, if you just get the answer from somebody else, you will gain no knowledge or hindsight from the exercise.</p>
<p>Just add a <code>print(m, f)</code> in your <code>while</code> loop and watch how the numbers evolve for small inputs. For example, try with something like <code>(3, 100)</code>: don't you see any way you could speed things up, rather than repeatedly removing 3 from the bigger number?</p>
| 2 | 2016-10-09T21:13:37Z | [
"python",
"loops",
"recursion",
"mathematical-optimization"
] |
counting back generations of a number | 39,947,975 | <p>I am trying to reverse engineer a set of numbers given to me (f,m) I need to go through and find how many generations it takes starting from 1,1 using the algorithm below for each generation:</p>
<pre><code>x = 1
y = 1
new_generation = y+x
x OR y = new_generation
</code></pre>
<p>IE, I do not know if X, or Y is changed, the other variable is left the same... A list of possible outputs would look like this for the ending values of 4 and 7:</p>
<pre><code>f = 4
m = 7
[1, 1]
[2, 1, 1, 2]
[3, 1, 2, 3, 3, 2, 1, 3]
[4, 1, 3, 4, 5, 3, 2, 5, 5, 2, 3, 5, 4, 3, 1, 4]
[5, 1, 4, 5, **7, 4**, 3, 7, 7, 5, 2, 7, 7, 2, 5, 7, 7, 3, **4, 7**, 5, 4, 1, 5]
</code></pre>
<p>Where every two sets of numbers (2,1) and (1,2) are a possible output. Note the ** denote the answer (in this case the order doesn't matter so long as both m and f have their value in the list).</p>
<p>Clearly there is exponential growth here, so I can't (or it less efficient) to make a list and then find the answer; instead I am using the following code to reverse this process...</p>
<pre><code>def answer(m,f):
#the variables will be sent to me as a string, so here I convert them...
m = (int(m))
f = (int(f))
global counter
#While I have not reduced my given numbers to my starting numbers....
while m != 1 or f != 1:
counter +=1
#If M is greater, I know the last generation added F to M, so remove it
if m > f:
m = m-f
#If F is greater, I know the last generation added M to M, so remove it
elif f > m:
f = f-m
else:
#They can never be the same (one must always be bigger, so if they are the same and NOT 1, it can't be done in any generation)
return "impossible"
return str(counter)
print(answer("23333","30000000000"))
</code></pre>
<p>This returns the correct answer (for instance, 4,7 returns "4" which is correct) but it takes to long when I pass larger numbers (I must be able to handle 10^50, insane amount, I know!).
<hr>
My thought was I should be able to apply some mathematical equation to the number to reduce it and them multiple the generations, but I'm having trouble finding a way to do this that also holds the integrity of the answer (for instance, if I divide the bigger by the smaller, on small numbers (7, 300000) I get a very close (but wrong) answer, however on closer numbers such as (23333, 300000) the answer is no where even close, which makes sense due to the differences in the generation path). Note I have also tried this in a recursive function (to find generations) and using the a non-reversed method (building the list and checking the answer; which was significantly slower for obvious reasons)</p>
<p><hr>
Here are some test cases with their answers:</p>
<blockquote>
<pre><code>f = "1"
m = "2"
Output: "1"
f = "4"
m = "7"
Output: "4"
f = "4"
m = "2"
Output: "impossible"
</code></pre>
</blockquote>
<p>Any help is much appreciated! P.S. I am running Python 2.7.6</p>
<p>[EDIT]
<hr>
The below code is working as desired.</p>
<pre><code>from fractions import gcd
def answer(m,f):
#Convert strings to ints...
m = (int(m))
f = (int(f))
#If they share a common denominator (GCD) return impossible
if gcd(m,f) != 1:
return "impossible"
counter = 0
#While there is still a remainder...
while m != 0 and f != 0:
if m > f:
counter += m // f
#M now equals the remainder.
m %= f
elif f > m:
counter += f // m
f %= m
return str(counter - 1)
</code></pre>
| 3 | 2016-10-09T20:02:15Z | 39,948,688 | <p>You are on the right track with the top-down approach you posted. You can speed it up by a huge factor if you use integer division instead of repeated subtraction.</p>
<pre><code>def answer(m, f):
m = int(m)
f = int(f)
counter = 0
while m != 0 and f != 0:
if f > m:
m, f = f, m
print(m, f, counter, sep="\t")
if f != 1 and m % f == 0:
return "impossible"
counter += m // f
m %= f
return str(counter - 1)
</code></pre>
<p>Using the above, <code>answer(23333, 30000000000)</code> yields</p>
<pre><code>30000000000 23333 0
23333 15244 1285732
15244 8089 1285733
8089 7155 1285734
7155 934 1285735
934 617 1285742
617 317 1285743
317 300 1285744
300 17 1285745
17 11 1285762
11 6 1285763
6 5 1285764
5 1 1285765
1285769
</code></pre>
<p>and <code>answer(4, 7)</code> yields</p>
<pre><code>7 4 0
4 3 1
3 1 2
4
</code></pre>
| 1 | 2016-10-09T21:23:30Z | [
"python",
"loops",
"recursion",
"mathematical-optimization"
] |
CPLEX finds optimal LP solution but returns no basis error | 39,948,095 | <p>I am solving a series of LP problems using the CPLEX Python API.
Since many of the problems are essentially the same, save a hand full of parameters. I want to use a warm start with the solution of the previous problem for most of them, by calling the function <code>cpx.start.set_start(col_status, row_status, col_primal, row_primal, col_dual, row_dual)</code> where <code>cpx = cplex.Cplex()</code>. </p>
<p>This function is documented <a href="https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.6.3/ilog.odms.cplex.help/refpythoncplex/html/cplex._internal._subinterfaces.InitialInterface-class.html" rel="nofollow">here</a>. Two of the arguments, <code>col_status</code> and <code>row_status</code>, are obtained by calling <code>cpx.solution.basis.get_col_basis()</code> and <code>cpx.solution.basis.get_row_basis()</code>. </p>
<p>However, despite <code>cpx.solution.status[cpx.solution.get_status()]</code> returning <code>optimal</code> and being able to obtain both <code>cpx.solution.get_values()</code> and <code>cpx.solution.get_dual_values()</code> ...</p>
<p>Calling <code>cpx.solution.basis.get_basis()</code> returns <code>CPLEX Error 1262: No basis exists.</code></p>
<p>Now, according to <a href="https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014643478#77777777-0000-0000-0000-000014676127" rel="nofollow">this post</a> one can call the warm start function with empty lists for the column and row basis statuses, as follows.</p>
<pre><code>lastsolution = cpx.solution.get_values()
cpx.start.set_start(col_status=[], row_status=[],
col_primal=lastsolution, row_primal=[],
col_dual=[], row_dual=[])
</code></pre>
<p>However, this actually results in making a few more CPLEX iterations. Why more is unclear, but the overall goal is to have significantly less, obviously.</p>
<p>Version Info
Python 2.7.12
CPLEX 12.6.3</p>
| 0 | 2016-10-09T20:14:09Z | 39,965,160 | <p>I'm not sure why you're getting the <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/refcallablelibrary/macros/CPXERR_NO_BASIS.html" rel="nofollow">CPXERR_NO_BASIS</a>. See my comment.</p>
<p>You may have better luck if you provide the values for <code>row_primal</code>, <code>col_dual</code>, and <code>row_dual</code> too. For example:</p>
<pre><code>cpx2.start.set_start(col_status=[],
row_status=[],
col_primal=cpx.solution.get_values(),
row_primal=cpx.solution.get_linear_slacks(),
col_dual=cpx.solution.get_reduced_costs(),
row_dual=cpx.solution.get_dual_values())
</code></pre>
<p>I was able to reproduce the behavior you describe using the <code>afiro.mps</code> model that comes with the CPLEX examples (number of deterministic ticks actually increased when specifying <code>col_primal</code> alone). However, when doing the above, it did help (number of det ticks improved and iterations went to 0).</p>
<p>Finally, I don't believe that there is any guarantee that using <code>set_start</code> will always help (it may even be a bad idea in some cases). I don't have a reference for this.</p>
| 0 | 2016-10-10T19:10:15Z | [
"python",
"cplex"
] |
Detect the input number of signs in python and use it in a loop for encryption | 39,948,119 | <p>I am writing a very easy encryption program. I just shift the ASCII order number of a sign with a key. My code looks as following:</p>
<pre><code>#Type in sign or text and key
clear_text = input("Text? ")
key = int(input("Key? "))
# saves ASCII order number of the sign
ord_number = ord(clear_text)
#shift ASCII odernumber with the key -> encryption
shift_ord_number = ord_number + key
key_ord_number = chr(shift_ord_number)
print(key_ord_number)
</code></pre>
<p>I want to advance this code by being able to type in a whole sentence. For this I somehow must detect how many signs the user has typed in. How would that be possible? And what loops would you recommend?</p>
| 0 | 2016-10-09T20:16:57Z | 39,948,152 | <p>You want to use a string for your sentence, from which you can extract individual characters to do your encryption on. In fact, <code>clear_text</code> is already a string, but (presumably) since you only entered a single character, it is only 1 character long.</p>
<p>To get the length of a string, you can use <code>len(clear_text)</code>. You can also iterate over the characters of a string using </p>
<pre><code>for char in clear_text:
ord_number = ord(char)
shift_ord_number = ord_number + key
key_ord_number = chr(shift_ord_number)
print(key_ord_number)
</code></pre>
| 1 | 2016-10-09T20:20:46Z | [
"python"
] |
Detect the input number of signs in python and use it in a loop for encryption | 39,948,119 | <p>I am writing a very easy encryption program. I just shift the ASCII order number of a sign with a key. My code looks as following:</p>
<pre><code>#Type in sign or text and key
clear_text = input("Text? ")
key = int(input("Key? "))
# saves ASCII order number of the sign
ord_number = ord(clear_text)
#shift ASCII odernumber with the key -> encryption
shift_ord_number = ord_number + key
key_ord_number = chr(shift_ord_number)
print(key_ord_number)
</code></pre>
<p>I want to advance this code by being able to type in a whole sentence. For this I somehow must detect how many signs the user has typed in. How would that be possible? And what loops would you recommend?</p>
| 0 | 2016-10-09T20:16:57Z | 39,948,305 | <p>Iterate over the string with the <code>for</code> loop and use your encryption logic with in the loop. </p>
<p>Making minimal changes to your original code, below is the sample code to achieve it:</p>
<pre><code>clear_text = input("Text? ")
key = int(input("Key? "))
new_list = []
for c in clear_text:
# saves ASCII order number of the sign
ord_number = ord(c)
#shift ASCII odernumber with the key -> encryption
shift_ord_number = ord_number + key
key_ord_number = chr(shift_ord_number)
new_list.append(key_ord_number)
new_string = ''.join(new_list)
</code></pre>
<p>where <code>new_string</code> is the encrypted string.</p>
<p>Instead of <code>for</code> loop, you may also do <em>list comprehension</em> as:</p>
<pre><code>new_string = ''.join(chr(ord(c) + key) for c in clear_text)
</code></pre>
<p><em>Sample Example:</em></p>
<pre><code>>>> clear_text = 'This is the sample code'
>>> key = 3
>>> ''.join(chr(ord(c) + key) for c in clear_text)
'Wklv#lv#wkh#vdpsoh#frgh' # <- value of "my_string"
</code></pre>
| 1 | 2016-10-09T20:38:42Z | [
"python"
] |
sklearn FeatureHasher parallelized | 39,948,138 | <p>sklearn's <code>Featurehasher</code> feature extractor has several advantages compared to its <code>DictVectorizer</code> counter-part, thanks to using the hashing trick.</p>
<p>One advantage which seems harder to tap is its ability to run in parallel.</p>
<p>My question is, how can I easily make <code>FeatureHasher</code> run in parallel?</p>
| 1 | 2016-10-09T20:18:56Z | 39,951,415 | <p>You could implement a parallel version of <code>FeatureHasher.transform</code> using <code>joblib</code> (the library favoured by scikit-learn for parallel processing):</p>
<pre><code>from sklearn.externals.joblib import Parallel, delayed
import numpy as np
import scipy.sparse as sp
def transform_parallel(self, X, n_jobs):
transform_splits = Parallel(n_jobs=n_jobs, backend="threading")(
delayed(self.transform)(X_split)
for X_split in np.array_split(X, n_jobs))
return sp.vstack(transform_splits)
FeatureHasher.transform_parallel = transform_parallel
f = FeatureHasher()
f.transform_parallel(np.array([{'a':3,'b':2}]*10), n_jobs=5)
<10x1048576 sparse matrix of type '<class 'numpy.float64'>'
with 20 stored elements in Compressed Sparse Row format>
</code></pre>
| 1 | 2016-10-10T04:43:59Z | [
"python",
"machine-learning",
"scikit-learn",
"feature-extraction"
] |
How to use sendAudio in Telegram bot (Python) | 39,948,163 | <p>I have a Telegram bot, it replies with text and images, but I have a problem with sending an MP3 file in the reply. Can anyone please help?</p>
<p>This part of code defines the reply:</p>
<pre><code> def reply(msg=None, img=None, aud=None):
if msg:
resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
'chat_id': str(chat_id),
'text': msg.encode('utf-8'),
'disable_web_page_preview': 'false',
# 'reply_to_message_id': str(message_id),
'reply_markup': json_keyboard,
})).read()
elif img:
resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
('chat_id', str(chat_id)),
('reply_to_message_id', str(message_id)),
], [
('photo', 'image.jpg', img),
])
elif aud:
resp = multipart.post_multipart(BASE_URL + 'sendAudio', [
('chat_id', str(chat_id)),
('reply_to_message_id', str(message_id)),
], [
('audio', 'aud.mp3', aud),
])
else:
logging.error('no msg or img specified')
resp = None
</code></pre>
<p>And this one defines the type of message it should return:</p>
<pre><code> elif 'Two' in text:
img = Image.open('statimg/firstf.jpg')
output = StringIO.StringIO()
img.save(output, 'JPEG')
reply(img=output.getvalue())
elif 'Three' in text:
aud = open('statimg/firsta.mp3')
output = StringIO.StringIO()
aud.save(output, 'MP3')
reply(aud=output.getvalue())
elif 'One' in text:
# json_keyboard = json.dumps({keym: [bline3]})
bline1 = [b1]
bline2 = [b2]
json_keyboard = json.dumps({keym: [bline1, bline2]})
if func6.state == 0:
reply('Hello text1')
func6()
elif func6.state == 1:
func6()
reply('Hello text2')
</code></pre>
<p>For "One" and "Two" in text ot works perfectly (returns text for "One" and image for "Two"), but for "Three" it doesn't return an mp3 file.</p>
<p>What could be the problem? Thanks a lot in advance!</p>
| 1 | 2016-10-09T20:22:19Z | 39,950,861 | <p>I think the issue is with <code>output = StringIO.StringIO()</code></p>
<p>you should use
<code>io.BytesIO()</code></p>
<p>Here is a working code I am using: </p>
<pre><code>def sendTelegramAudio(self, file_url, text):
url = "https://api.telegram.org/botxxx:yyyy/sendAudio";
remote_file = requests.get(file_url)
file1 = io.BytesIO(remote_file.content)
file1.name = 'audio.mp3'
files = {'audio': file1}
data = {'chat_id' : "@your_channel", 'caption':text}
r= requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
</code></pre>
| 0 | 2016-10-10T03:21:45Z | [
"python",
"json",
"mp3",
"telegram",
"telegram-bot"
] |
How to get values from my python file to my form using Flask? | 39,948,223 | <p>I'm trying to extract "address" from my python file "get interfaces.py" display it into my form using flask, but my code is not working, and may be I'm doing it wrong. I'm new in Flask </p>
<p>Here's my python file get_interfaces.py</p>
<pre><code>with open('/etc/network/interfaces', 'r+') as f:
for line in f:
found_address = line.find('address')
if found_address != -1:
address = line[found_address+len('address:'):]
print 'Address: ', address
found_network = line.find('network')
if found_network != -1:
network = line[found_network+len('network:'):]
print 'Network: ', network
found_netmask = line.find('netmask')
if found_netmask != -1:
netmask = line[found_netmask+len('netmask:'):]
print 'Netmask: ', netmask
found_broadcast = line.find('broadcast')
if found_broadcast != -1:
broadcast = line[found_broadcast+len('broadcast:'):]
print 'Broadcast: ', broadcast
</code></pre>
<p>Where the variable "address" is what I want.</p>
<p>My flask: </p>
<pre><code>from flask import render_template, request, redirect, url_for, Response
from app import app, lm
from flask.ext.login import login_required, login_user, logout_user, UserMixin
from Mensajeria.ConfiguracionInterfaces import ConfiguracionInterfaces
import zmq
import struct
import subprocess
import os
import threading, time, json
import cProfile, pstats, StringIO
@app.route('//')
def ibisaserver_cliente():
pr = cProfile.Profile()
pr.enable()
Ci = ConfiguracionInterfaces()
pr.disable()
s = StringIO.StringIO()
sortby = 'calls'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
logging.debug(s.getvalue())
return render_template('test.html',
title='test',
Ci=Ci)
</code></pre>
<p>Here's my configuracioninterfaces.py :</p>
<pre><code>import ConfigParser
import os
class ConfiguracionInterfaces(object):
def __init__(self):
self.config = ConfigParser.RawConfigParser()
#Ruta para archivo en PC:
self.rutaExterna = os.path.join(os.getcwd(), "app/Mensajeria/get_interfaces.py")
self.config.read(['get_interfaces.py', self.rutaExterna])
#Ruta para archivo en MOXA:
#self.config.read('/home/moxa/properties.cfg')
def obtenerAddress(self):
endPoint = self.config.get('address', 'address')
return address
def modificarAddress(self, address):
self.config.set('address', 'address', address)
#with open('/home/moxa/properties.cfg', 'wb')as archivo:
with open(self.rutaExterna, 'wb') as archivo:
self.config.write(archivo)
</code></pre>
<p>My HTML:</p>
<pre><code><form method="post" name="prueba">
<div class="form-group">
<label class="col-sm-3 col-sm-3 control-label">prueba:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="address" value="{{ Ci.obtenerAddress() }}" disabled>
</div>
</div>
</form>
</code></pre>
| -3 | 2016-10-09T20:29:01Z | 39,948,311 | <p>In <code>get_interfaces.py</code> create function (ie. <code>get_info()</code>)<br>
with your code and with <code>return address</code> at the end.</p>
<p>In flask file run</p>
<pre><code>import get_interfaces
address = get_interfaces.get_info()
</code></pre>
<hr>
<p>BTW: if your code can return more than one address then create list with this addresses and use <code>return list_with_addresses</code></p>
<p>And in flask file you will have</p>
<pre><code>all_addresses = get_interfaces.get_info()
first_address = all_addresses[0]
second_address = all_addresses[1]
</code></pre>
| 0 | 2016-10-09T20:39:16Z | [
"python",
"html",
"django",
"python-2.7",
"flask"
] |
How to get values from my python file to my form using Flask? | 39,948,223 | <p>I'm trying to extract "address" from my python file "get interfaces.py" display it into my form using flask, but my code is not working, and may be I'm doing it wrong. I'm new in Flask </p>
<p>Here's my python file get_interfaces.py</p>
<pre><code>with open('/etc/network/interfaces', 'r+') as f:
for line in f:
found_address = line.find('address')
if found_address != -1:
address = line[found_address+len('address:'):]
print 'Address: ', address
found_network = line.find('network')
if found_network != -1:
network = line[found_network+len('network:'):]
print 'Network: ', network
found_netmask = line.find('netmask')
if found_netmask != -1:
netmask = line[found_netmask+len('netmask:'):]
print 'Netmask: ', netmask
found_broadcast = line.find('broadcast')
if found_broadcast != -1:
broadcast = line[found_broadcast+len('broadcast:'):]
print 'Broadcast: ', broadcast
</code></pre>
<p>Where the variable "address" is what I want.</p>
<p>My flask: </p>
<pre><code>from flask import render_template, request, redirect, url_for, Response
from app import app, lm
from flask.ext.login import login_required, login_user, logout_user, UserMixin
from Mensajeria.ConfiguracionInterfaces import ConfiguracionInterfaces
import zmq
import struct
import subprocess
import os
import threading, time, json
import cProfile, pstats, StringIO
@app.route('//')
def ibisaserver_cliente():
pr = cProfile.Profile()
pr.enable()
Ci = ConfiguracionInterfaces()
pr.disable()
s = StringIO.StringIO()
sortby = 'calls'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
logging.debug(s.getvalue())
return render_template('test.html',
title='test',
Ci=Ci)
</code></pre>
<p>Here's my configuracioninterfaces.py :</p>
<pre><code>import ConfigParser
import os
class ConfiguracionInterfaces(object):
def __init__(self):
self.config = ConfigParser.RawConfigParser()
#Ruta para archivo en PC:
self.rutaExterna = os.path.join(os.getcwd(), "app/Mensajeria/get_interfaces.py")
self.config.read(['get_interfaces.py', self.rutaExterna])
#Ruta para archivo en MOXA:
#self.config.read('/home/moxa/properties.cfg')
def obtenerAddress(self):
endPoint = self.config.get('address', 'address')
return address
def modificarAddress(self, address):
self.config.set('address', 'address', address)
#with open('/home/moxa/properties.cfg', 'wb')as archivo:
with open(self.rutaExterna, 'wb') as archivo:
self.config.write(archivo)
</code></pre>
<p>My HTML:</p>
<pre><code><form method="post" name="prueba">
<div class="form-group">
<label class="col-sm-3 col-sm-3 control-label">prueba:</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="address" value="{{ Ci.obtenerAddress() }}" disabled>
</div>
</div>
</form>
</code></pre>
| -3 | 2016-10-09T20:29:01Z | 39,948,454 | <p>First, I dont see the need for you to write a separate python file to manipulate address from a textfile. You can do the same as a method inside the flask code itself without any decorators.</p>
<pre><code>def getIPAddress():
...
...
return address
</code></pre>
<p>once done, you can call the method getIPAddress with a return variable stored as explained above by Furas and use the same throughout the decorator.</p>
<p>Second, in your jinja, you are instantiating the class itself in jinja2 <code>"{{ Ci.obtenerAddress()"</code> which is overkill and doesnt follow jinja2 syntax. You could pass the address when you are rendering the value to the template "Ci=Ci"</p>
| 0 | 2016-10-09T20:57:27Z | [
"python",
"html",
"django",
"python-2.7",
"flask"
] |
apache mod_wsgi error with django in virtualenv | 39,948,367 | <p>I can't seem to find a good answer to this. Who needs to own the virtualenv when running it as a WSGIDaemon? I assume on my OS (Ubuntu 16) www-data, but I want to be sure. Trying some new things to get this thing working based off of the answer from this post...</p>
<p><a href="http://stackoverflow.com/questions/38284814/django-apache-configuration-with-wsgidaemonprocess-not-working">django apache configuration with WSGIDaemonProcess not working</a></p>
<p>Does the django project, the virtualenv folder, or both need to be owned by the apache group? What ownerships need to be in place to serve a django project without specifying a port? Why do I get the following? </p>
<p>The root problem:</p>
<pre><code> Call to 'site.addsitedir()' failed for '(null)'
</code></pre>
<p>When I start apache, I get this error. I've followed several different guides, including:
<a href="http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html" rel="nofollow">http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html</a>
and
<a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/" rel="nofollow">https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/</a>
but have had zero success.</p>
<p>My virtual environment path is <code>/usr/local/virtualenvs/servicesite</code></p>
<p>My django project path is <code>/home/addohm/projects/rtservice/servicesite</code>
<em>this is where manage.py resides</em>,
which leaves <code>/home/addohm/projects/rtservice/servicesite/servicesite</code> as the location of my wsgi.py.</p>
<p><strong>wsgi.py:</strong></p>
<pre><code>SERVICESITE = ['/usr/local/virtualenvs/servicesite/lib/python3.5/site-packages']
import os
import sys
import site
prev_sys_path = list(sys.path)
for directory in SERVICESITE
site.addsitedir(directory)
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
""" **Doesn't seem to work, throwing error in apache logs**
site.addsitedir('/usr/local/virtualenvs/servicesite/lib/python3.5/site-packages')
"""
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "servicesite.settings")
application = get_wsgi_application()
DJANGO_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
sys.path.append(DJANGO_PATH)
</code></pre>
<p><strong>apache2.conf</strong></p>
<p>[...]</p>
<pre><code>WSGIDaemonProcess servicesite python-path=/home/addohm/projects/rtservice/servicesite:/usr/local/virtualenvs/servicesite/lib/python3.5/site-packages
WSGIProcessGroup servicesite
WSGIScriptAlias / /home/addohm/projects/rtservice/servicesite/servicesite/wsgi.py
Alias /static/ /home/addohm/projects/rtservice/servicesite/static/
<Directory /home/addohm/projects/rtservice/servicesite/static/>
Require all granted
</Directory>
<Directory /home/addohm/projects/rtservice/servicesite/servicesite>
<Files wsgy.py>
Require all granted
</Files>
</Directory>
</code></pre>
<p>[...]</p>
| 0 | 2016-10-09T20:47:04Z | 39,949,355 | <p>You should not have need to change anything in the original <code>wsgi.py</code> generated by Django for you. It is generally sufficient to have:</p>
<pre><code>import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "servicesite.settings")
application = get_wsgi_application()
</code></pre>
<p>Your Apache configuration should then preferably be:</p>
<pre><code>WSGIDaemonProcess service site python-home=/usr/local/virtualenvs/servicesite \
python-path=/home/addohm/projects/rtservice/servicesite
WSGIProcessGroup servicesite
WSGIScriptAlias / /home/addohm/projects/rtservice/servicesite/servicesite/wsgi.py
Alias /static/ /home/addohm/projects/rtservice/servicesite/static/
<Directory /home/addohm/projects/rtservice/servicesite/static/>
Require all granted
</Directory>
<Directory /home/addohm/projects/rtservice/servicesite/servicesite>
<Files wsgy.py>
Require all granted
</Files>
</Directory>
</code></pre>
<p>That is, use <code>python-home</code> for the location of the directory specified by <code>sys.prefix</code> for the virtual environment. Avoid using <code>python-path</code> and referring to the <code>site-packages</code> directory. Using <code>python-home</code> has been preferred way for a very long time and using it ensures that things fail in a more obvious way when you don't do things the correct way.</p>
<p>A few very important things.</p>
<p>The first is that mod_wsgi must be compiled for the specific Python major/minor version you want to use.</p>
<p>Second, the Python virtual environment must be created from the same Python installation as mod_wsgi was compiled for. You can't have mod_wsgi compiled against a system Python installation, but have your virtual environment based off a separate Python installation for same major/minor version in <code>/usr/local</code>.</p>
<p>Third, the user that Apache runs your code as must have read access to any directories/files for the main Python installation, the virtual environment and your application code. When you stick stuff under a home directory, it will not generally have access as the home directory prohibits others from reading anything in the home directory.</p>
<p>Fourth, if the mod_wsgi daemon process group is set to run as a different user than the Apache user, the Apache user still must at least have ability to read the <code>wsgi.py</code> file and all the directories down to that point.</p>
<p>Further reading on virtual environments which is more up to date:</p>
<ul>
<li><a href="http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html" rel="nofollow">http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html</a></li>
</ul>
| 1 | 2016-10-09T22:56:49Z | [
"python",
"django",
"apache",
"ubuntu",
"mod-wsgi"
] |
python nested if statements not working | 39,948,410 | <p>I'm trying to make a game using pygame, and I've set up a couple of functions that I've tested and they work fine. However, in the code below, when I add a print statement to show if my code works, it prints on the first one but not the second. Any help?</p>
<pre><code>for square in row:
tile_x = row.index(square)
# print statement works here
if self.x_pos - tile_x >= -4 and self.x_pos - tile_x <= 4:
tile_x = 4 - (self.x_pos - tile_x)
tile_y = 4 - (self.y_pos - tile_y)
if square == 'G':
display('Grass',tile_x,tile_y)
# print statement doesn't work here
elif square == 'T':
display('Tree',tile_x,tile_y)
elif square == 'B':
display('Bush',tile_x,tile_y)
elif square == 'R':
display('Rock',tile_x,tile_y)
elif square == 'S':
display('Stone',tile_x,tile_y)
# display function has been tested, and it works fine
</code></pre>
| -3 | 2016-10-09T20:51:46Z | 39,948,483 | <p>I would first have a dict vs all those if statements:</p>
<pre><code>di={'G':'Grass',
'T':'Tree',
'B':'Bush',
'R':'Rock',
'S':'Stone'}
</code></pre>
<p>Then you can do <code>display(di[square],tile_x,tile_y)</code></p>
| -1 | 2016-10-09T21:00:14Z | [
"python",
"if-statement"
] |
python nested if statements not working | 39,948,410 | <p>I'm trying to make a game using pygame, and I've set up a couple of functions that I've tested and they work fine. However, in the code below, when I add a print statement to show if my code works, it prints on the first one but not the second. Any help?</p>
<pre><code>for square in row:
tile_x = row.index(square)
# print statement works here
if self.x_pos - tile_x >= -4 and self.x_pos - tile_x <= 4:
tile_x = 4 - (self.x_pos - tile_x)
tile_y = 4 - (self.y_pos - tile_y)
if square == 'G':
display('Grass',tile_x,tile_y)
# print statement doesn't work here
elif square == 'T':
display('Tree',tile_x,tile_y)
elif square == 'B':
display('Bush',tile_x,tile_y)
elif square == 'R':
display('Rock',tile_x,tile_y)
elif square == 'S':
display('Stone',tile_x,tile_y)
# display function has been tested, and it works fine
</code></pre>
| -3 | 2016-10-09T20:51:46Z | 39,948,628 | <p>I have just thought of something</p>
<p>I am using <code>row.index(square)</code>, which is finding the <strong>first</strong> 'g' square and using the tile_x of <strong>that</strong> first square. This means it thinks the square I'm looking for is not in the correct range to show on the map, so the first if statement returns False and it doesn't show up or print out.</p>
| 1 | 2016-10-09T21:18:17Z | [
"python",
"if-statement"
] |
Getting BlockingIOError (WinError 10035) when accepting a socket | 39,948,411 | <p>I've gotten a chance to work again with Python, but this time I decided to take Python 3.5 to my journey.</p>
<p>I had to port a working non-blocking socket server using <a href="http://www.tornadoweb.org/en/stable/" rel="nofollow">Tornado</a>, from Python 2.7 to 3.5. Used same source code, but this time it doesn't work as needed.</p>
<p>I keep getting <code>[WinError 10035] A non-blocking socket operation could not be completed immediately on send</code> whenever I accept a socket connection using <code>socket.accept()</code> and I still can't figure out why.</p>
<p>Tried to use example <a href="https://gist.github.com/robcowie/974695" rel="nofollow">code that I've found a few years ago on GitHub Gist</a> and still keep getting an error. Is there any changes in socket library or is it just a bug?</p>
| 0 | 2016-10-09T20:52:16Z | 39,950,119 | <p>This error is harmless and expected. The problem is that the gist you linked to doesn't know about windows-specific error codes (on line 24 it checks for EWOULDBLOCK and EAGAIN, but it should also use WSAEWOULDBLOCK).</p>
<p>Since that gist was written, Tornado has gained some new utilities to make this easier. If you're using <code>IOStreams</code>, you can use <code>tornado.tcpserver.TCPServer</code> to accept your connections, or if you want to continue using plain sockets you can use the lower-level <code>tornado.netutil.add_accept_handler</code>. </p>
| 1 | 2016-10-10T01:12:53Z | [
"python",
"sockets",
"tornado",
"nio"
] |
PyLdaVis : TypeError: cannot sort an Index object in-place, use sort_values instead | 39,948,442 | <p>I am trying to visualize LDA topics in Python using PyLDAVis but I can't seem to get it right. My model has a vocab size of 150K words and about 16 Million tokens were taken to train it.</p>
<p>I am doing it outside of an iPython notebook and this is the code that I wrote to do it.</p>
<pre><code>model_filename = "150k_LdaModel_topics_"+ topics +"_passes_"+passes +".model"
dictionary = gensim.corpora.Dictionary.load('LDADictSpecialRemoved150k.dict')
corpus = gensim.corpora.MmCorpus('LDACorpusSpecialRemoved150k.mm')
ldamodel = gensim.models.ldamodel.LdaModel.load(model_filename)
import pyLDAvis.gensim
vis = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary)
pyLDAvis.save_html(vis, "topic_viz_"+topics+"_passes_"+passes+".html")
</code></pre>
<p>I get the following error after 2-3 hours of running code on a high speed server with >30GBs of RAM. Can someone help where I am going wrong?</p>
<pre><code>Traceback (most recent call last):
File "create_vis.py", line 36, in <module>
vis = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary)
File "/local/lib/python2.7/site-packages/pyLDAvis/gensim.py", line 110, in prepare
return vis_prepare(**opts)
File "/local/lib/python2.7/site-packages/pyLDAvis/_prepare.py", line 398, in prepare
token_table = _token_table(topic_info, term_topic_freq, vocab, term_frequency)
File "/local/lib/python2.7/site-packages/pyLDAvis/_prepare.py", line 267, in _token_table
term_ix.sort()
File "/local/lib/python2.7/site-packages/pandas/indexes/base.py", line 1703, in sort
raise TypeError("cannot sort an Index object in-place, use "
TypeError: cannot sort an Index object in-place, use sort_values instead
</code></pre>
| 0 | 2016-10-09T20:56:26Z | 39,998,684 | <p>There was a problem with the LDAVis Code and upon reporting the issue, it has been resolved.</p>
| 0 | 2016-10-12T12:30:24Z | [
"python",
"visualization",
"lda",
"gensim",
"topic-modeling"
] |
How to connect a client to a server through an HTTP proxy in Python? | 39,948,448 | <p>I'm really new to coding using sockets.</p>
<p>I like the socket library, I get to understand a big part of what's happening in my program, so i you don't mind i would like to stick with it.</p>
<p>So as the title says, I have a socket based client and server and I would like to exchange content through an HTTP proxy(I'm using a Squid proxy). This little piece of code is supposed to bypass the proxy in my campus to simulate a chat over the campus network. This is totally legal since I asked the IT guys that work there.</p>
<p>Here's the deal, I am able to send a POST request through the proxy to my server which receives it and sends it back to client 1, but when I try to send more requests to the proxy none of them gets to the server so I think to my self the connection died but here's the thing, when I send messages from client 2 which is connected directly to the server, the server AND client 1 receive them.</p>
<pre><code>import socket
from _thread import *
def sender(server,h):
b=input("<<--Send--")
b=h
server.send(b.encode())
PROXY_IP="127.0.0.1"
PROXY_PORT=3128
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.settimeout(0.05)
server.connect((PROXY_IP,PROXY_PORT))
header="""POST http://127.0.0.1:3001 HTTP/1.1\r\n
Host: 127.0.0.1:3001\r\n
Proxy-Connection: keep-alive\r\n
Content-Length: 5 \r\n\r\n
hello\r\n"""
server.send(header.encode())
while 1:
try:
start_new_thread(sender,(server,header))
a=server.recv(1024)
print("-->>{}".format(a.decode()))
except KeyboardInterrupt:
break
except:
pass
server.close()
</code></pre>
<p>I already tried the CONNECT method which works perfectly, but it's not allowed in my campus network proxy.
What am I doing wrong ?
Is there something I should know about how to re-send content through a proxy ?
Thank you for your time and please bear with me..</p>
<p>Here's what I get on the client that sends a request to the proxy:</p>
<pre><code>~#Sent : POST http://127.0.0.1:3001 HTTP/1.1
Host: 127.0.0.1:3001
Proxy-Connection: keep-alive
Content-Length: 5
hello
#Received : HTTP/1.1 200 OK
Server: squid/3.5.19
Mime-Version: 1.0
Date: Mon, 10 Oct 2016 00:46:39 GMT
X-Transformed-From: HTTP/0.9
X-Cache: MISS from kali
X-Cache-Lookup: MISS from kali:3128
Transfer-Encoding: chunked
Via: 1.1 kali (squid/3.5.19)
Connection: keep-alive
#Received : B2
POST / HTTP/1.1
Content-Length: 5
Host: 127.0.0.1:3001
Via: 1.1 kali (squid/3.5.19)
X-Forwarded-For: 127.0.0.1
Cache-Control: max-age=259200
Connection: keep-alive
hello
#Sent : POST http://127.0.0.1:3001 HTTP/1.1
Host: 127.0.0.1:3001
Proxy-Connection: keep-alive
Content-Length: 5
hello
</code></pre>
<p>Nothing is received after this..</p>
| 0 | 2016-10-09T20:57:10Z | 39,951,627 | <pre><code>POST http://127.0.0.1:3001 HTTP/1.1\r\n
Host: 127.0.0.1:3001\r\n
Proxy-Connection: keep-alive\r\n
Content-Length: 5 \r\n\r\n
hello\r\n
</code></pre>
<p>The body of your HTTP response consists of 7 bytes not 5 as you've stated in your <code>Content-length</code>. The <code>\r\n</code> after the 5 byte still belong to the response body. Giving the wrong size might mixup request handling, i.e. the proxy is expecting a new request but is actually getting <code>\r\n</code>, i.e. the 2 bytes after your 5 bytes <code>Content-length</code>.</p>
<p>Apart from that both path and <code>Host</code> header must include the name of the target from the perspective of the proxy. Using 127.0.0.1. like in your example would mean that you try to access a server at the same host of the proxy, i.e. localhost from the view of the proxy. This is probably not what you've intended.</p>
<pre><code>...
X-Transformed-From: HTTP/0.9
</code></pre>
<p>This header in the response of the proxy indicates that your server does not properly speak HTTP/1.x. Instead of sending HTTP header and body it just sends the payload back without any HTTP header, like done in the HTTP 0.9 protocol which was obsoleted 20 years ago. With HTTP 0.9 the response will always end only at the end of the TCP connection. This means that you cannot have multiple requests within the same TCP connection.</p>
<blockquote>
<p>I'm really new to coding using sockets.</p>
</blockquote>
<p>The problem is not caused by the wrong use of sockets but due the wrong implementation of the application protocol, i.e. the data send over the socket. If you really need to implement HTTP please study the standards, i.e. <a href="https://tools.ietf.org/html/rfc7230" rel="nofollow">RFC 7230</a> and following. If you don't want to do this use existing and tested HTTP libraries instead of writing your own.</p>
| 0 | 2016-10-10T05:12:16Z | [
"python",
"sockets",
"proxy",
"server",
"client"
] |
python how to use subprocess pipe with linux shell | 39,948,459 | <p>I have a python script search for logs, it continuously output the logs found and I want to use linux pipe to filter the desired output. example like that:</p>
<p>$python logsearch.py | grep timeout</p>
<p>The problem is the sort and wc are blocked until the logsearch.py finishes, while the logsearch.py will continuous output the result.</p>
<p>sample logsearch.py:</p>
<pre><code>p = subprocess.Popen("ping google.com", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for line in p.stdout:
print(line)
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>figured out, just change the stdout in subprocess to sys.stdout, python will handle the pipe for you.</p>
<pre><code>p = subprocess.Popen("ping -c 5 google.com", shell=True, stdout=**sys.stdout**)
</code></pre>
<p>Thanks for all of you help!</p>
| 0 | 2016-10-09T20:57:52Z | 39,948,807 | <p>And why use grep? Why don't do all the stuff in Python?</p>
<pre><code>from subprocess import Popen, PIPE
p = Popen(['ping', 'google.com'], shell=False, stdin=PIPE, stdout=PIPE)
for line in p.stdout:
if 'timeout' in line.split():
# Process the error
print("Timeout error!!")
else:
print(line)
</code></pre>
<p><strong>UPDATE:</strong><br>
I change the Popen line as recommended @triplee. Pros and cons in <a href="http://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess">Actual meaning of 'shell=True' in subprocess</a> </p>
| 0 | 2016-10-09T21:37:18Z | [
"python",
"linux",
"shell",
"pipe",
"subprocess"
] |
How can I convert Python boolean object to C int (or C++ boolean) (Python C API) | 39,948,485 | <p>I have a variable <code>PyObject</code> that I know is a Python bool. It either is <code>True</code> or <code>False</code> (eg. <code>Py_True</code> or <code>Py_False</code>). Now I would like to convert it to C++ somehow.</p>
<p>Doing this with strings isn't so hard, there is a helper function for that - <code>PyBytes_AsString</code> that converts python string into C string. Now I need something like that for boolean (or int as there is no <code>bool</code> in C).</p>
<p>Or if there isn't conversion, maybe some function that can compare with true or false? Something like <code>int PyBool_IsTrue(PyObject*)</code>?</p>
<p>Here is some example code for easier understanding of what I need:</p>
<pre><code>#include <Python.h>
int main()
{
/* here I create Python boolean with value of True */
PyObject *b = Py_RETURN_TRUE;
/* now that I have it I would like to turn in into C type so that I can determine if it's True or False */
/* something like */
if (PyBool_IsTrue(b))
{ /* it's true! */ }
else
{ /* it's false */ }
return 0;
}
</code></pre>
<p>This obviously wouldn't work as there is no such function like <code>PyBool_IsTrue</code> :( how can I do that?</p>
<p>Snippet of Python header (boolobject.h):</p>
<pre><code>/* Boolean object interface */
#ifndef Py_BOOLOBJECT_H
#define Py_BOOLOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif
PyAPI_DATA(PyTypeObject) PyBool_Type;
#define PyBool_Check(x) (Py_TYPE(x) == &PyBool_Type)
/* Py_False and Py_True are the only two bools in existence.
Don't forget to apply Py_INCREF() when returning either!!! */
/* Don't use these directly */
PyAPI_DATA(struct _longobject) _Py_FalseStruct, _Py_TrueStruct;
/* Use these macros */
#define Py_False ((PyObject *) &_Py_FalseStruct)
#define Py_True ((PyObject *) &_Py_TrueStruct)
/* Macros for returning Py_True or Py_False, respectively */
#define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True
#define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False
/* Function to return a bool from a C long */
PyAPI_FUNC(PyObject *) PyBool_FromLong(long);
#ifdef __cplusplus
}
#endif
#endif /* !Py_BOOLOBJECT_H */
</code></pre>
| 2 | 2016-10-09T21:00:18Z | 39,949,255 | <p>The answer is in Python headers but may not be obvious.</p>
<p>Python headers declare 2 somewhat static objects here, with couple of macros:</p>
<pre><code>/* Don't use these directly */
PyAPI_DATA(struct _longobject) _Py_FalseStruct, _Py_TrueStruct;
/* Use these macros */
#define Py_False ((PyObject *) &_Py_FalseStruct)
#define Py_True ((PyObject *) &_Py_TrueStruct)
/* Macros for returning Py_True or Py_False, respectively */
#define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True
#define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False
</code></pre>
<p>It seems that both <code>True</code> and <code>False</code> are in fact Python objects and all values in Python that are <code>True</code> or <code>False</code> are in fact references to these two global <code>Py_True</code> and <code>Py_False</code> objects. When such object is returned using <code>Py_RETURN_TRUE</code>, the reference count is incremented.</p>
<p>This means that every C pointer that points to PyObject of value <code>Py_True</code> in fact points to same memory address. Therefore checking if <code>PyObject</code> is true or false is as simple as:</p>
<pre><code>/* here I create Python boolean with value of True */
PyObject *b = Py_RETURN_TRUE;
/* now we compare the address of pointer with address of Py_True */
if (b == Py_True)
{ /* it's true! */ }
else
{ /* it's false */ }
</code></pre>
<p>It's generally good idea to use <code>int PyBool_Check(PyObject*)</code> to verify if object in question is Python boolean.</p>
| 0 | 2016-10-09T22:40:08Z | [
"python",
"c"
] |
Find range of arguments that return the same result for a linear function | 39,948,543 | <p>Consider the <code>y = round(300000/x**2)</code>. I would like to find the ranges of <code>x</code> that return the same <code>y</code> for <code>100 < x < 40000</code>.</p>
<p>How would I do that with python/numpy?</p>
| 2 | 2016-10-09T21:07:20Z | 39,948,612 | <p>All values between <code>100</code> and <code>40000</code> return <code>0</code> for <code>y = round(300/x**2)</code>.</p>
<p>I assume you meant the following</p>
<pre><code>def y(x):
return round((300/x)**2)
</code></pre>
<p>In which case you can use <a href="https://docs.python.org/3.6/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a></p>
<pre><code>from itertools import groupby
keys, groups = groupby(range(100, 40000), y)
</code></pre>
<p>Now <code>groups</code> will contain grouped integers that result in the same output from the function <code>y</code>.</p>
| 2 | 2016-10-09T21:15:09Z | [
"python",
"numpy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.