title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to get the max/min value in Pandas DataFrame when nan value in it | 38,508,294 | <p>Since one column of my pandas dataframe has <code>nan</code> value, so when I want to get the max value of that column, it just return error. </p>
<pre><code>>>> df.iloc[:, 1].max()
'error:512'
</code></pre>
<p>How can I skip that <code>nan</code> value and get the max value of that column?</p>
| 2 | 2016-07-21T15:26:32Z | 38,515,089 | <p>When the df contains <code>NaN</code> values it reports <code>NaN</code> values, Using
<code>np.nanmax(df.values)</code> gave the desired answer.</p>
| 0 | 2016-07-21T22:02:54Z | [
"python",
"pandas"
] |
Put Header with Python - docx | 38,508,320 | <p>I am using Python-docx to create and write a Word document.</p>
<p>How i can put a text in document header using python-docx?</p>
<p><a href="http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png" rel="nofollow">http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png</a></p>
<p>Thanks</p... | 0 | 2016-07-21T15:27:40Z | 38,508,977 | <p>You can use header.text like</p>
<pre><code>header = section.header
header.text = 'foobar'
</code></pre>
<p>see <a href="http://python-docx.readthedocs.io/en/latest/dev/analysis/features/header.html?highlight=header" rel="nofollow">http://python-docx.readthedocs.io/en/latest/dev/analysis/features/header.html?highl... | 1 | 2016-07-21T15:58:58Z | [
"python",
"python-2.7",
"python-docx"
] |
Put Header with Python - docx | 38,508,320 | <p>I am using Python-docx to create and write a Word document.</p>
<p>How i can put a text in document header using python-docx?</p>
<p><a href="http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png" rel="nofollow">http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png</a></p>
<p>Thanks</p... | 0 | 2016-07-21T15:27:40Z | 38,515,968 | <p>Unfortunately this feature is not implemented yet. The page @SamRogers linked to is part of the enhancement proposal (aka. "analysis page"). The implementation is in progress however, by @eupharis, so might be available in a month or so. The ongoing pull request is here if you want to follow it. <a href="https://git... | 1 | 2016-07-21T23:31:37Z | [
"python",
"python-2.7",
"python-docx"
] |
Equalivent of Qt.setGeometry() in tkinter | 38,508,348 | <p>What is the equal function of PyQt <code>setGeometry()</code> in tkinter? Or Is there any function works like that? I searched a bit but couldn't find, all of examples looks like tkinter works on a specific widget and we just can set width-height.</p>
<p><a href="http://zetcode.com/gui/pyqt4/firstprograms/" rel="no... | 0 | 2016-07-21T15:28:36Z | 38,509,359 | <p>The nearest thing tkinter has is probably the <a href="http://effbot.org/tkinterbook/place.htm" rel="nofollow">place</a> geometry manager. With it you can set the x,y coordinates (either absolute or relative) and the width and height attributes (also absolute or relative).</p>
<p>For example, to place a label at 10... | 1 | 2016-07-21T16:16:05Z | [
"python",
"tkinter",
"pyqt4",
"python-3.4",
"pyqt5"
] |
Equalivent of Qt.setGeometry() in tkinter | 38,508,348 | <p>What is the equal function of PyQt <code>setGeometry()</code> in tkinter? Or Is there any function works like that? I searched a bit but couldn't find, all of examples looks like tkinter works on a specific widget and we just can set width-height.</p>
<p><a href="http://zetcode.com/gui/pyqt4/firstprograms/" rel="no... | 0 | 2016-07-21T15:28:36Z | 38,509,811 | <p>You can also do something similar to @BryanOakley's answer by the <code>grid</code> geometry manager:<br></p>
<pre><code>from tkinter import *
root = Tk()
label = Label(root, bg='cyan')
label.grid(ipadx=100, ipady=50, padx=50, pady=50)
</code></pre>
<p><b>UPDATE:</b> Please feedback why you think this answer is n... | 0 | 2016-07-21T16:39:00Z | [
"python",
"tkinter",
"pyqt4",
"python-3.4",
"pyqt5"
] |
Getting last change time in Python on Windows | 38,508,351 | <p>I have two scripts, one in Python, one in Powershell, that get and compare the last modification of a file. The one in Powershell uses:</p>
<pre><code>$t = $f.LastWriteTime.ToFileTimeUtc()
</code></pre>
<p>This time is primary for me and I need to get the same information in Python. I am using <code>os.stat</code>... | 3 | 2016-07-21T15:28:47Z | 38,524,858 | <p>So, for the benefit of anyone with this problem. Actually, it turns out that the question I mentioned, <a href="http://stackoverflow.com/questions/27534448/how-do-i-get-change-file-time-in-windows">How do I get *change* file time in Windows?</a>, is a bit misleading, as it mentions an obscure driver access only func... | 0 | 2016-07-22T11:04:35Z | [
"python",
"windows",
"ctypes"
] |
get specific index when using izip over list | 38,508,355 | <p>I want to iterate over a list and find the latest "consecutive value".</p>
<p>What does that mean, well:</p>
<p>If I have a list <code>priceValue = [423, 399, 390, 400, 430, 420, 423]</code>, my latest consecutive value will be the 2 last indexes: 420 to 423, index number: 5 and 6.</p>
<p>I want to iterate and ge... | 1 | 2016-07-21T15:29:04Z | 38,508,443 | <p>Use <a href="https://docs.python.org/2/library/functions#enumerate" rel="nofollow"><code>enumerate</code></a> which yields index with original items:</p>
<pre><code>>>> for i, x in enumerate(['a', 'b', 'c']):
... print i, x # i: index, x: item
...
0 a
1 b
2 c
</code></pre>
<hr>
<pre><code>>>&g... | 0 | 2016-07-21T15:33:13Z | [
"python",
"loops"
] |
get specific index when using izip over list | 38,508,355 | <p>I want to iterate over a list and find the latest "consecutive value".</p>
<p>What does that mean, well:</p>
<p>If I have a list <code>priceValue = [423, 399, 390, 400, 430, 420, 423]</code>, my latest consecutive value will be the 2 last indexes: 420 to 423, index number: 5 and 6.</p>
<p>I want to iterate and ge... | 1 | 2016-07-21T15:29:04Z | 38,508,543 | <pre><code>[(i, i+1) for i in range(len(priceValue)-1) if priceValue[i]<priceValue[i+1]]
</code></pre>
<p>Output :</p>
<pre><code>[(2, 3), (3, 4), (5, 6)]
</code></pre>
<p>Or more quite :</p>
<pre><code>res=[({i:priceValue[i], i+1:priceValue[i+1]}) for i in range(len(priceValue)-1) if priceValue[i]<priceValue... | 0 | 2016-07-21T15:38:08Z | [
"python",
"loops"
] |
get specific index when using izip over list | 38,508,355 | <p>I want to iterate over a list and find the latest "consecutive value".</p>
<p>What does that mean, well:</p>
<p>If I have a list <code>priceValue = [423, 399, 390, 400, 430, 420, 423]</code>, my latest consecutive value will be the 2 last indexes: 420 to 423, index number: 5 and 6.</p>
<p>I want to iterate and ge... | 1 | 2016-07-21T15:29:04Z | 38,508,547 | <p>If you dont mind avoiding for loops, you can also find the last consecutive value by calculating differences:</p>
<pre><code>import numpy as np
x = [423, 399, 390, 400, 430, 420, 423]
d = np.diff(x)
</code></pre>
<p>The index you want is the last positive index:</p>
<pre><code>np.where(d > 0)[0][-1]
>>&g... | 0 | 2016-07-21T15:38:15Z | [
"python",
"loops"
] |
Web-Scraping Max Retries Rejected | 38,508,357 | <p>I have issues scraping certain websites, while others work. For example, this works:</p>
<pre><code>page = requests.get('https://wsj.com/', proxies=proxydict)
</code></pre>
<p>But this doesn't:</p>
<pre><code>page = requests.get('https://www.privateequityinternational.com/', proxies=proxydict)
</code></pre>
<p>I... | 1 | 2016-07-21T15:29:14Z | 38,535,044 | <p>The issue is the page is served over <em>http</em> in your browser not <em>https</em>, you get a warning from google when you try to access the page using https:</p>
<pre><code>In [1]: import requests
...: page = requests.get('http://www.wsj.com')
...:
In [2]: page
Out[2]: <Response [200]>
</code></pr... | 1 | 2016-07-22T20:52:10Z | [
"python",
"web-scraping",
"http-headers",
"python-requests",
"screen-scraping"
] |
Encode two ipv4 addresses in 64 bits | 38,508,422 | <p>If I have pairs of IP addresses like:</p>
<pre><code>IP1="168.2.65.33"
IP2="192.4.2.55"
</code></pre>
<p>I would like to encode each pair as a 64 bit value so that the first 32 bits is the first IP address and the second is the second IP address. I would then like to be able to save the 64 bit value to a file in s... | 1 | 2016-07-21T15:32:24Z | 38,508,493 | <p>Don't worry about encoding them in 64 bits. An IPv4 address is 32 bits (4 bytes). If you write two of them to a file, it will be 8 bytes in size.</p>
<p>Use <a href="https://docs.python.org/2/library/socket.html#socket.inet_aton" rel="nofollow"><code>socket.inet_aton</code></a> to convert a human-readable IP addres... | 5 | 2016-07-21T15:35:23Z | [
"python"
] |
Encode two ipv4 addresses in 64 bits | 38,508,422 | <p>If I have pairs of IP addresses like:</p>
<pre><code>IP1="168.2.65.33"
IP2="192.4.2.55"
</code></pre>
<p>I would like to encode each pair as a 64 bit value so that the first 32 bits is the first IP address and the second is the second IP address. I would then like to be able to save the 64 bit value to a file in s... | 1 | 2016-07-21T15:32:24Z | 38,508,524 | <p>Yes, it's possible, like this:</p>
<pre><code>import struct
import os
IP1="168.2.65.233"
IP2="192.4.2.55"
s = struct.pack('>8B', *map(int, IP1.split('.') + IP2.split('.')))
with open('f', 'wb') as f:
f.write(s)
print(os.stat('f').st_size) #: 8.
</code></pre>
<p>This works in Python 2 and 3.</p>
<p>Based on ... | 1 | 2016-07-21T15:36:54Z | [
"python"
] |
Encode two ipv4 addresses in 64 bits | 38,508,422 | <p>If I have pairs of IP addresses like:</p>
<pre><code>IP1="168.2.65.33"
IP2="192.4.2.55"
</code></pre>
<p>I would like to encode each pair as a 64 bit value so that the first 32 bits is the first IP address and the second is the second IP address. I would then like to be able to save the 64 bit value to a file in s... | 1 | 2016-07-21T15:32:24Z | 38,508,747 | <p>In Python3 there is an <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow"><code>ipaddress</code></a> module for working with IPs. Pack them into 32 bits each and add them together:</p>
<pre><code>from ipaddress import ip_address
original1 = ip_address('192.168.0.1')
original2 = ip_address('8... | 1 | 2016-07-21T15:47:33Z | [
"python"
] |
removing iterated string from string array | 38,508,447 | <p>I am writing a small script that lists the currently connected hard disks on my machine. I only need the disk identifier(disk0), not the partition ID(disk0s1, disk0s2, etc.)
How can I iterate through an array that contains diskID and partitionID and remove the partitionID entries? Here's what I'm trying so far:</p>
... | 0 | 2016-07-21T15:33:28Z | 38,508,702 | <p>try beginning with</p>
<pre><code>allDrives = os.listdir("/dev/")
disks = [drive for drive in allDrives if ('disk' in drive)]
</code></pre>
<p>then, given disks id's are only 5-chars length</p>
<pre><code>short_disks = [disk[:6] for disk in disks]
unique_short_disks = list(set(short_disks))
</code></pre>
| 0 | 2016-07-21T15:45:03Z | [
"python",
"arrays",
"string",
"loops",
"system"
] |
Extract rows from python array in python | 38,508,457 | <p>I have a numpy array <code>X</code> with shape <code>(768, 8)</code>.</p>
<p>The last value for each row can either be <code>0</code> or <code>1</code>, I only want rows with value <code>1</code>, and call this <code>T</code>.</p>
<p>I did:</p>
<pre><code>T = [x for x in X if x[7]==1]
</code></pre>
<p>This is co... | 0 | 2016-07-21T15:33:48Z | 38,508,539 | <p>By calling </p>
<pre><code>T = [x for x in X if x[8]==1]
</code></pre>
<p>you are making <code>T</code> as a list. To convert it any list to a numpy array, just use:</p>
<pre><code>T = numpy.array([x for x in X if x[8]==1])
</code></pre>
<p>Here is what happens:</p>
<pre><code>In [1]: import numpy as np
In [2... | 0 | 2016-07-21T15:37:58Z | [
"python",
"numpy"
] |
Extract rows from python array in python | 38,508,457 | <p>I have a numpy array <code>X</code> with shape <code>(768, 8)</code>.</p>
<p>The last value for each row can either be <code>0</code> or <code>1</code>, I only want rows with value <code>1</code>, and call this <code>T</code>.</p>
<p>I did:</p>
<pre><code>T = [x for x in X if x[7]==1]
</code></pre>
<p>This is co... | 0 | 2016-07-21T15:33:48Z | 38,509,788 | <p>NumPy's boolean indexing gets the job done in a fully vectorized manner. This approach is generally more efficient (and arguably more elegant) than using list comprehensions and type conversions.</p>
<pre><code>T = X[X[:, -1] == 1]
</code></pre>
<p>Demo:</p>
<pre><code>In [232]: first_columns = np.random.randint(... | 2 | 2016-07-21T16:37:33Z | [
"python",
"numpy"
] |
Appending Vowel Location Python | 38,508,554 | <p>I am trying to figure out why I am getting an empty list when this code is ran. The goal is to take a string, find the index of any vowels and append that index to a list. With an index starting at one instead of zero. Any tips where the error might be occurring would be great! If there is a general oversight you no... | 1 | 2016-07-21T15:38:28Z | 38,508,585 | <p><code>if letter == vowels:</code> should be <code>if letter in vowels:</code></p>
<p>vowels is a list and a string can never be equal to a list and you should also move the return out of the loop as that will stop the function in it's track the first time it loops through</p>
| 1 | 2016-07-21T15:40:05Z | [
"python",
"indices",
"enumerate"
] |
Appending Vowel Location Python | 38,508,554 | <p>I am trying to figure out why I am getting an empty list when this code is ran. The goal is to take a string, find the index of any vowels and append that index to a list. With an index starting at one instead of zero. Any tips where the error might be occurring would be great! If there is a general oversight you no... | 1 | 2016-07-21T15:38:28Z | 38,508,616 | <p>Method <code>lower</code> does not modify the string <em>in-place</em> (strings are <em>immutable</em>), so you should instead do:</p>
<pre><code>word = word.lower()
</code></pre>
<p>Then to check for the membership of a character in the list of <code>vowels</code>, you should use the <code>in</code> operator and ... | 1 | 2016-07-21T15:41:15Z | [
"python",
"indices",
"enumerate"
] |
Appending Vowel Location Python | 38,508,554 | <p>I am trying to figure out why I am getting an empty list when this code is ran. The goal is to take a string, find the index of any vowels and append that index to a list. With an index starting at one instead of zero. Any tips where the error might be occurring would be great! If there is a general oversight you no... | 1 | 2016-07-21T15:38:28Z | 38,509,188 | <p><strong>It work great</strong></p>
<pre><code>def vowel_indices(word):
vowels = ["a", "e", "i", "o", "u"]
word.lower()
indexes = [index for c,index in zip(word,range(len(word))) if c in vowels]
print(indexes)
</code></pre>
| 1 | 2016-07-21T16:08:19Z | [
"python",
"indices",
"enumerate"
] |
How to avoid gaps with matplotlib.fill_between and where | 38,508,556 | <p>I want to fill the area between two curves but only when the lower curve is >0.
I'm using <code>fill_between()</code> in <code>matplotlib</code> with a <code>where</code> condition (to test which curve is greater) and <code>numpy.maximum()</code> (to test whether the lower curve is >0). But there are gaps in the fil... | 2 | 2016-07-21T15:38:31Z | 38,509,267 | <p>By interpolating values using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html" rel="nofollow"><code>numpy.interp</code></a>:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10)
a = np.array([101, 102, 71, 56, 49, 15, 29, 31, 45, 41])
b = np.array([5... | 3 | 2016-07-21T16:12:23Z | [
"python",
"numpy",
"matplotlib"
] |
while loop until input is has fulfilled two statements | 38,508,564 | <pre><code>def ask_input(prompt, error):
while True:
value = input(prompt)
try:
int(value) > 1
break
except ValueError:
print(error)
else:
return value
</code></pre>
<p>So I want to make simple function that returns value if its int... | 0 | 2016-07-21T15:38:53Z | 38,508,592 | <p>Use <code>if</code> statement:</p>
<pre><code>while True:
value = input(prompt)
try:
if int(value) > 1:
return int(value) # return the value if condition met
except ValueError as error:
print(error)
</code></pre>
| 1 | 2016-07-21T15:40:23Z | [
"python",
"loops",
"while-loop"
] |
while loop until input is has fulfilled two statements | 38,508,564 | <pre><code>def ask_input(prompt, error):
while True:
value = input(prompt)
try:
int(value) > 1
break
except ValueError:
print(error)
else:
return value
</code></pre>
<p>So I want to make simple function that returns value if its int... | 0 | 2016-07-21T15:38:53Z | 38,508,849 | <p>Use a <strong>try/except</strong> to accept only integers. Then test the input for the greater than 1 condition using an <code>if</code> condition, return the value if it satisfies the condition. It's better to use <code>raw_input()</code> in this case as you want an integer literal as input, where as <code>input()<... | 1 | 2016-07-21T15:52:31Z | [
"python",
"loops",
"while-loop"
] |
while loop until input is has fulfilled two statements | 38,508,564 | <pre><code>def ask_input(prompt, error):
while True:
value = input(prompt)
try:
int(value) > 1
break
except ValueError:
print(error)
else:
return value
</code></pre>
<p>So I want to make simple function that returns value if its int... | 0 | 2016-07-21T15:38:53Z | 38,509,087 | <p>Your code prompts the user for anything that can be converted to an integer, whether or not it is > 1, then return None. This is not what you intended.</p>
<p>There are 2 different problems here:</p>
<pre><code>int(value) > 1
</code></pre>
<p>If the input value is not parsable as an integer, then this will rai... | 0 | 2016-07-21T16:03:42Z | [
"python",
"loops",
"while-loop"
] |
Pyspark (spark 1.6.x) ImportError: cannot import name Py4JJavaError | 38,508,603 | <p>I am using Apache-Spark (pyspark) and everything works fine. Now, I am trying to load a data that may or may not exist. So, I am trying to catch the Py4JJavaError and am trying to import it as follows:</p>
<pre><code>from py4j.java_gateway import Py4JJavaError
ImportError: cannot import name Py4JJavaError
</code></... | 0 | 2016-07-21T15:40:42Z | 38,509,119 | <p>Try <code>from py4j.protocol import Py4JJavaError</code>.</p>
| 2 | 2016-07-21T16:05:01Z | [
"python",
"apache-spark",
"pyspark"
] |
Python download images with alernating variables | 38,508,715 | <p>I was trying to download images with url's that change but got an error.</p>
<pre><code>url_image="http://www.joblo.com/timthumb.php?src=/posters/images/full/"+str(title_2)+"-poster1.jpg&h=333&w=225"
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
headers = {'User-Agent': user_agent}
req = urllib.r... | 0 | 2016-07-21T15:45:37Z | 38,510,385 | <p>My advice is to use urlib2. In addition, I've written a nice function (I think) that will also allow gzip encoding (reduce bandwidth) if the server supports it. I use this for downloading social media files, but should work for anything.</p>
<p>I would try to debug your code, but since it's just a snippet (and th... | 0 | 2016-07-21T17:09:42Z | [
"python",
"image",
"download",
"urllib",
"python-3.5"
] |
Parsing complex Xml Python 3.4 | 38,508,775 | <p>I have the following xml :</p>
<pre><code><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Suite>
<TestCase>
<TestCaseID>001</TestCaseID>
<TestCaseDescription>Hello</TestCaseDescription>
<TestSetup>
<Action>
<ActionCommand>gfdg</... | 0 | 2016-07-21T15:48:30Z | 38,547,968 | <p>Simply add another loop to iterate through the <code><ValidationStep></code> node and its children. Also, you do not need the two other lists as you can update a dictionary during the parsing loop:</p>
<pre><code>import xml.etree.ElementTree as et
dom = et.parse('Input.xml')
root = dom.getroot()
test_case =... | 0 | 2016-07-24T01:37:54Z | [
"python",
"xml"
] |
How to turn a system of sympy equations into matrix form | 38,508,780 | <p>How do I turn a system of sympy equations into a matrix form?</p>
<p>For example, how do I turn a system like this:</p>
<pre><code>equation_one = 4*a*x + 3*b*y
equation_two = 2*b*x + 1*a*y
</code></pre>
<p>Into a system like this:</p>
<pre><code>matrix_form = ([equation_one, equation_two], [x, y])
</code></pre>
... | 2 | 2016-07-21T15:48:54Z | 38,509,562 | <p>After some searching, I found </p>
<pre><code>sympy.linear_eq_to_matrix(equations, *symbols)
</code></pre>
<p>This has solved my problem. </p>
| 3 | 2016-07-21T16:26:10Z | [
"python",
"sympy"
] |
beautifulsoup with get_text - handle spaces | 38,508,850 | <p>I using BS4 (python3) for extracting text from html file. My file looks like this:</p>
<pre><code><BODY>
<P>Hello World!</P>
</BODY>
</HTML>
</code></pre>
<p>When i calling <code>get_text()</code> method, the output is "Hello World!". Because it's HTML, I was expected ... | 1 | 2016-07-21T15:52:36Z | 38,508,894 | <p>The problem is, neither <code>get_text(strip=True)</code> nor joining the <code>.stripped_strings</code> would work here because there is a single <code>NavigableString</code> in the <code>p</code> element in the second case and it's value is <code>Hello\n World!</code>. The newline is inside the text node in other ... | 0 | 2016-07-21T15:55:00Z | [
"python",
"python-3.x",
"beautifulsoup"
] |
Existing code on github, principal functions never called | 38,508,956 | <p>I am trying to work on an addon developed by Microsoft Azure for his old Cloud Service. The aim is to render Blender scenes using the Azure environment.</p>
<p>Here it is : <a href="https://github.com/Azure/azure-batch-apps-blender" rel="nofollow">https://github.com/Azure/azure-batch-apps-blender</a></p>
<p>As Mic... | 0 | 2016-07-21T15:58:08Z | 38,511,603 | <p>Thanks for your interest in the Blender plugin!
The "missing code" that you mention here is actually part of the old Batch Apps C# SDK, which exposed an interface, allowing us to override select functions with Blender specific functionality.
While I'm afraid I can't find any old documentation for it, this project sh... | 1 | 2016-07-21T18:17:35Z | [
"c#",
"python",
"azure",
"blender",
"azure-batch"
] |
How to query AWS to get ELB names and attached instances to that using python boto modules? | 38,509,004 | <p>I am trying retrieve the ELB names and the attached instances ids using python boto modules. </p>
<pre><code>{
import boto
conn = boto.connect_elb()
conn.get_all_load_balancers()
}
</code></pre>
<p>Gives only load-balancer names now how can i retrieve the Instance-ids attached to the load-balancer ? <... | 0 | 2016-07-21T15:59:58Z | 38,509,222 | <p><code>conn.get_all_load_balancers()</code> - returns a list of elbs objects. Each elb object has a parameter <code>instances</code> that will show you attached instances. And from there you can get their Id's.<br>
If you want to find elb by name, then you need to filter first loop. </p>
<p>So something like this sh... | 2 | 2016-07-21T16:10:01Z | [
"python",
"amazon-web-services",
"boto"
] |
Sliding window iterator using rolling in pandas | 38,509,107 | <p>If it's single row, I can get the iterator as following</p>
<pre><code>import pandas as pd
import numpy as np
a = np.zeros((100,40))
X = pd.DataFrame(a)
for index, row in X.iterrows():
print index
print row
</code></pre>
<p>Now I want each iterator will return a subset X[0:9, :], X[5:14, :], X[10:19, :] ... | 2 | 2016-07-21T16:04:28Z | 38,509,466 | <p>That's not how rolling works. It "provides rolling transformations" (from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow">the docs</a>).</p>
<p>You can loop and use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-i... | 1 | 2016-07-21T16:21:12Z | [
"python",
"pandas"
] |
Sliding window iterator using rolling in pandas | 38,509,107 | <p>If it's single row, I can get the iterator as following</p>
<pre><code>import pandas as pd
import numpy as np
a = np.zeros((100,40))
X = pd.DataFrame(a)
for index, row in X.iterrows():
print index
print row
</code></pre>
<p>Now I want each iterator will return a subset X[0:9, :], X[5:14, :], X[10:19, :] ... | 2 | 2016-07-21T16:04:28Z | 38,510,101 | <p>I'll experiment with the following dataframe.</p>
<h3>Setup</h3>
<pre><code>import pandas as pd
import numpy as np
from string import uppercase
def generic_portfolio_df(start, end, freq, num_port, num_sec, seed=314):
np.random.seed(seed)
portfolios = pd.Index(['Portfolio {}'.format(i) for i in uppercase[:... | 4 | 2016-07-21T16:53:11Z | [
"python",
"pandas"
] |
when will the python __call__ would be called? | 38,509,124 | <p>I tried to understand the following code. </p>
<pre><code>class Chain(object):
def __init__(self, path=''):
self._path = path
def __getattr__(self, path):
return Chain('%s/%s' % (self._path, path))
def __str__(self):
return self._path
__repr__ = __str__
def __call__(... | 1 | 2016-07-21T16:05:09Z | 38,509,247 | <p><code>abc</code> is considered an attribute rather than a method call. Therefore it should be handled by <code>__getattr__</code> instead of <code>__call__</code>.</p>
| 0 | 2016-07-21T16:11:30Z | [
"python"
] |
when will the python __call__ would be called? | 38,509,124 | <p>I tried to understand the following code. </p>
<pre><code>class Chain(object):
def __init__(self, path=''):
self._path = path
def __getattr__(self, path):
return Chain('%s/%s' % (self._path, path))
def __str__(self):
return self._path
__repr__ = __str__
def __call__(... | 1 | 2016-07-21T16:05:09Z | 38,509,332 | <p><code>__getattr__</code> is used for attribute lookup on a class instance. <code>__call__</code> is used when a class instance is used as a function.</p>
<pre><code>Chain() # creates a class instance
Chain().abc # calls __getattr__ which returns new instance
Chain().abc... | 2 | 2016-07-21T16:15:14Z | [
"python"
] |
Calculator in Python can't print out the result I want | 38,509,137 | <p>I wanted to create this calculator in Python and I had some problems when it printed out. The problem was that everytime that I ran the program it printed out Check for errors. When I removed it, it started to print me out numbers put together. For example 1 + 2 = 12 or 2 + 5= 25, etc.This thing happened only when I... | 0 | 2016-07-21T16:05:54Z | 38,509,225 | <p>I think you want to be using <code>==</code> instead of <code>is</code> to compare string literals with a variable. I'd expect your usage to always return false.</p>
| 0 | 2016-07-21T16:10:14Z | [
"python"
] |
Calculator in Python can't print out the result I want | 38,509,137 | <p>I wanted to create this calculator in Python and I had some problems when it printed out. The problem was that everytime that I ran the program it printed out Check for errors. When I removed it, it started to print me out numbers put together. For example 1 + 2 = 12 or 2 + 5= 25, etc.This thing happened only when I... | 0 | 2016-07-21T16:05:54Z | 38,509,324 | <p>@Fjoni Yzeiri: Hi folk, </p>
<p>This is a common issue when starting with Python, as you don't declare the variable type of the input, it will save it as a <code>String</code>, so if you concatenate (<code>+</code> in Python) it will concatenate the two Inputs.</p>
<p>To solve this you have to explicitly cast this... | 0 | 2016-07-21T16:15:03Z | [
"python"
] |
Calculator in Python can't print out the result I want | 38,509,137 | <p>I wanted to create this calculator in Python and I had some problems when it printed out. The problem was that everytime that I ran the program it printed out Check for errors. When I removed it, it started to print me out numbers put together. For example 1 + 2 = 12 or 2 + 5= 25, etc.This thing happened only when I... | 0 | 2016-07-21T16:05:54Z | 38,509,354 | <p>The problem is solved now. Someone posted the answer but he deleted it I think and I couldn't upvote it. I needed to change </p>
<pre><code>num1 = input()
</code></pre>
<p>to </p>
<pre><code>num1 = int(input())
</code></pre>
| 0 | 2016-07-21T16:15:57Z | [
"python"
] |
How to create user specific file with unique name in the reducer phase of Hadoop Map Reduce Framework(In Python)) | 38,509,221 | <p>I have written one code for the reducer which will read the output from the mapper. And then It will create a new file with the key name And all the values corresponding to same key will be stored into one file.</p>
<p><strong>My code is:</strong></p>
<pre><code>!/usr/bin/env python
import sys
last_key = No... | 0 | 2016-07-21T16:10:01Z | 38,513,216 | <p>There are no straightforward solution to achieve this.You may follow below approaches to achieve this using Mapreduce:</p>
<p>Approach 1: Using partitioner</p>
<ol>
<li>Find out unique number of files.e.g. count unique number of '%this_key%' in file.</li>
<li>Set number of reducer to previous step result in mapred... | 0 | 2016-07-21T19:52:22Z | [
"python",
"python-2.7",
"hadoop",
"hdfs",
"hadoop-streaming"
] |
Need to remove items from both a list and a dictionary of tuple value pairs at same time | 38,509,239 | <p>This is very related to a <a href="http://stackoverflow.com/questions/38506857/deleting-previous-token-in-a-sentence-if-same-as-current-token-python">previous question</a> but I realised that my objective is much more complicated:</p>
<p>I have a sentence: <code>"Forbes Asia 200 Best Under 500 Billion 2011"</code><... | 0 | 2016-07-21T16:11:05Z | 38,512,276 | <p>Not a very elegant, but working solution:</p>
<pre><code>oldTokens = [u'Forbes', u'Asia', u'200', u'Best', u'Under', u'500', u'Billion', u'2011']
numberTokenIDs = {(7,): 2011.0, (2,): 200.0, (5,6): 500000000000.00}
locationTokenIDs = {(0, 1): u'Forbes Asia'}
newTokens = []
newnumberTokenIDs = {}
newlocationToken... | 1 | 2016-07-21T18:55:32Z | [
"python",
"dictionary",
"tuples"
] |
How to get Python WebJob working on Azure | 38,509,344 | <p>I am struggling to deploy a Python WorkerRole on Microsoft Azure. Has anybody successfully gotten a Python process working on Microsoft Azure?</p>
<p>Microsoft seems to be telling people that their documentation related to Python on Azure is out of date, see <a href="https://azure.microsoft.com/en-us/documentation... | -2 | 2016-07-21T16:15:37Z | 38,560,924 | <p>@andrewkittredge, I don't think you need to install Python environment manually before deploying a WorkerRole or a WebJob, because the Python runtime has been installed on Azure, just need to be specified or set up in the related configuration.</p>
<p>According to the <a href="https://azure.microsoft.com/en-us/docu... | 0 | 2016-07-25T06:22:14Z | [
"python",
"azure",
"azure-sdk-python"
] |
Python Logging in Bottle not working in route | 38,509,377 | <p>I am trying to use the Python logging library to log messages in my Bottle app. The logging works as expected outside the route, but my app is not logging anything in a route. Any idea what's wrong?</p>
<pre><code>import logging
#logging
logger = logging.getLogger('myApp')
logger.setLevel(logging.INFO)
fh = loggin... | 0 | 2016-07-21T16:17:12Z | 39,001,814 | <p>Your example works for me.
You are probably getting an error before getting to the line</p>
<pre><code>logger.info("testing logging inside route. word: %s" % (userWord))
</code></pre>
<p>Notice that you should see on your console the following line if your POST went well</p>
<blockquote>
<p>127.0.0.1 - - [17/Au... | 0 | 2016-08-17T16:25:14Z | [
"python",
"logging",
"routing",
"bottle"
] |
Accessing non-subscriptable properties | 38,509,475 | <p>Scripting the Blender, I successfully did <code>bpy.ops.render.render(some_args)</code> but <code>bpy.ops.render['render']</code> fails with BPyOpsSubMod object is not subscriptable. This puzzles me since I expected that, likewise in Javascript, any Python object is a dictionary and I can access object methods eithe... | 0 | 2016-07-21T16:21:31Z | 38,509,636 | <p>It's not true that every object <em>is</em> a dictionary. Every object <em>has</em> a dictionary, accessible through the name <a href="https://docs.python.org/3/library/stdtypes.html#object.__dict__" rel="nofollow"><code>.__dict__</code></a>.</p>
<p>You can use either</p>
<pre><code>bpy.ops.render.__dict__['render... | -1 | 2016-07-21T16:30:02Z | [
"python",
"python-3.x",
"reference",
"attributes",
"members"
] |
multi-threadings and multi-processes pools in multiprocessing | 38,509,514 | <p>As for multi-threadings and multi-processes pools in <code>multiprocessing</code></p>
<pre><code> pool = Pool()
result = pool.map(func, arg)
pool.close()
pool.join()
</code></pre>
<p>Why <code>close</code> and <code>join</code> are necessary to make the code <strong>safe</strong>? What bad consequences can it m... | 0 | 2016-07-21T16:23:26Z | 38,510,437 | <p>@Lee Hi Folk,</p>
<p>Basically, these instructions will set some closure concepts into the current executions, it will say "I won't put more data into the queue(<code>close</code>) and I'll wait the end of the sub-processes before go on(<code>join</code>)".</p>
<p>From docs:</p>
<blockquote>
<p>close()</p>
... | 1 | 2016-07-21T17:12:32Z | [
"python",
"multithreading",
"multiprocessing"
] |
Numpy: Checking if a value is NaT | 38,509,538 | <pre><code>nat = np.datetime64('NaT')
nat == nat
>> FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
np.isnan(nat)
>> TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''sa... | 2 | 2016-07-21T16:25:01Z | 38,531,233 | <p>When you make a comparison at the first time, you always have a warning. But meanwhile returned result of comparison is correct:</p>
<pre><code>import numpy as np
nat = np.datetime64('NaT')
def nat_check(nat):
return nat == np.datetime64('NaT')
nat_check(nat)
Out[4]: FutureWarning: In the future, 'NAT... | 1 | 2016-07-22T16:22:26Z | [
"python",
"numpy"
] |
Numpy: Checking if a value is NaT | 38,509,538 | <pre><code>nat = np.datetime64('NaT')
nat == nat
>> FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
np.isnan(nat)
>> TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''sa... | 2 | 2016-07-21T16:25:01Z | 40,130,488 | <p>Another way would be to catch the exeption:</p>
<pre><code>def is_nat(npdatetime):
try:
npdatetime.strftime('%x')
return False
except:
return True
</code></pre>
| 0 | 2016-10-19T11:43:17Z | [
"python",
"numpy"
] |
Problems with newline parameter in numpy savetxt function | 38,509,654 | <p>Having the structured array like this :</p>
<p><code>[ (b'H', 0.9425, 0.1412, 7.1414) ... (b'N', 1.0037, 4.0524, 6.8000)]</code></p>
<p>I want to make a <code>.txt file</code> using <code>numpy.savetxt</code> where each element of the array is written in separate line:</p>
<pre><code>H 0.9425 0.1412 7.1414
... | 0 | 2016-07-21T16:30:48Z | 38,518,321 | <p>I wonder if there's a problem with <code>\n</code> on your system; maybe Python is using one value, while your file viewer is expecting another (there are dos, linux, and mac standards).</p>
<p>I have no problem with this data and format in an Ipython session on a linux machine.</p>
<pre><code>In [88]: d=[ (b'H', ... | 0 | 2016-07-22T04:44:29Z | [
"python",
"numpy"
] |
Execute another python script, then shut down current script | 38,509,674 | <p>I have a python script <code>script_a.py</code> that uses <code>subprocess.call()</code> that executes another script <code>script_b.py</code> as it's last instruction before ending. I need <code>script_b.py</code> to wait until <code>script_a.py</code> closes before proceeding with its own instructions. For this I ... | 2 | 2016-07-21T16:31:43Z | 38,510,262 | <p>Your script_a.py would be:</p>
<pre><code>import subprocess
#do whatever stuff you want here
p = subprocess.Popen(["python","b.py"])
p.wait()
p.terminate()
#continue doing stuff
</code></pre>
| 1 | 2016-07-21T17:02:49Z | [
"python",
"subprocess",
"sys"
] |
Execute another python script, then shut down current script | 38,509,674 | <p>I have a python script <code>script_a.py</code> that uses <code>subprocess.call()</code> that executes another script <code>script_b.py</code> as it's last instruction before ending. I need <code>script_b.py</code> to wait until <code>script_a.py</code> closes before proceeding with its own instructions. For this I ... | 2 | 2016-07-21T16:31:43Z | 38,511,400 | <p>you could make some totally hacky crap</p>
<p><strong>script_b.py</strong></p>
<pre><code>while not os.path.exists("a.done"):pass
time.sleep(0.2) # a little longer just to be really sure ...
os.remove("a.done")
... # rest of script b
</code></pre>
<p><strong>script_a.py</strong></p>
<pre><code>import atexit
atex... | 1 | 2016-07-21T18:07:47Z | [
"python",
"subprocess",
"sys"
] |
Populate dictionary from list in loop | 38,509,704 | <p>I have the following code that works fine and I was wondering how to implement the same logic using list comprehension.</p>
<pre><code>def get_features(document, feature_space):
features = {}
for w in feature_space:
features[w] = (w in document)
return features
</code></pre>
<p>Also am I going ... | 3 | 2016-07-21T16:33:00Z | 38,509,750 | <p>Like this, with a <em>dict comprehension</em>:</p>
<pre><code>def get_features(document, feature_space):
return {w: (w in document) for w in feature_space}
</code></pre>
<p>The <code>features[key] = value</code> expression becomes the <code>key: value</code> part at the start, and the rest of the <code>for</co... | 3 | 2016-07-21T16:35:11Z | [
"python",
"python-3.x",
"dictionary-comprehension"
] |
Setting Flask dictionary value via Jinja | 38,509,765 | <p>If I was to use the following in my Jinja template:</p>
<pre><code>{% set data['enabled'] = True %}
</code></pre>
<p>I receive the error <code>TemplateSyntaxError: expected token '=', got '['</code>. Setting one word variables is fine, but as the error states, setting dictionary values through Jinja brings an erro... | 0 | 2016-07-21T16:35:46Z | 38,509,972 | <p>Jinja2 tries to limit assignments in its code, to remove the logic from the view (check out an <a href="http://martinfowler.com/eaaDev/uiArchs.html" rel="nofollow">MVC explanation</a>).</p>
<p>If you still want to do an assignment you will have to use <a href="https://docs.python.org/3/library/stdtypes.html#dict.up... | 2 | 2016-07-21T16:46:36Z | [
"python",
"flask",
"jinja2"
] |
Get the current and next value in a Jinja for loop | 38,509,802 | <p>Is there a way to iterate over a list in Jinja2 that can access the nth and (n+1) th element in a single iteration?</p>
<pre><code>{% for x in my_list %}
<!-- print the current and the (current+1) -->
{{x}}, {{x+1}} <-- this is wrong but hopefully highlights the problem
{% endfor %}
</code></pre>
<p>Als... | 0 | 2016-07-21T16:38:32Z | 38,514,019 | <p>Jinja has a <a href="http://jinja.pocoo.org/docs/dev/templates/#for" rel="nofollow"><code>loop.index</code></a> variable that you can use to access the next value in your list:</p>
<pre><code>@app.route('/')
def index():
return render_template_string("""
<body>
{% for x in my_list %}
... | 0 | 2016-07-21T20:42:07Z | [
"python",
"flask",
"jinja2"
] |
Define custom error messages on invalid attribute call | 38,509,807 | <p>How do I define custom error messages for specific invalid attribute calls in python? </p>
<p>I wrote a class thats attribute assignment is dependent on the input on instance creation and like to return a more descriptive error message if an unassigned attribute is called:</p>
<pre><code>class test:
def __init... | 0 | 2016-07-21T16:38:51Z | 38,510,732 | <p>Override <strong>getattr</strong> in your class.</p>
<pre><code>class test(object):
def __init__(self, input):
if input == 'foo':
self.type = 'foo'
self.a = 'foo'
if input == 'bar':
self.type = 'bar'
self.b = 'bar'
def __getattr__(self, attr... | 1 | 2016-07-21T17:30:31Z | [
"python",
"class",
"error-handling",
"attributes"
] |
"Almost Equal" in Jasmine | 38,509,815 | <p><strong>The Story:</strong></p>
<p>In Python built-in <code>unittest</code> framework, there is an "approximate equality" assertion implemented via <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual"><code>assertAlmostEqual()</code></a> method:</p>
<pre><code>x = 0.1234567... | 9 | 2016-07-21T16:39:13Z | 38,556,097 | <p>For a single float, use <a href="https://github.com/jasmine/jasmine/blob/master/src/core/matchers/toBeCloseTo.js"><code>toBeCloseTo</code></a>:</p>
<pre><code>expect(x).toBeCloseTo(y, 7)
</code></pre>
<p>For a float array, it seems the best you could do is loop over it and call <code>toBeCloseTo</code> for each pa... | 5 | 2016-07-24T19:49:45Z | [
"javascript",
"python",
"unit-testing",
"testing",
"jasmine"
] |
"Almost Equal" in Jasmine | 38,509,815 | <p><strong>The Story:</strong></p>
<p>In Python built-in <code>unittest</code> framework, there is an "approximate equality" assertion implemented via <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual"><code>assertAlmostEqual()</code></a> method:</p>
<pre><code>x = 0.1234567... | 9 | 2016-07-21T16:39:13Z | 38,575,094 | <p>You can add a custom equality tester for the float type. It will be called on a single float and on each float present in an array:</p>
<pre class="lang-js prettyprint-override"><code>beforeEach(function () {
jasmine.addCustomEqualityTester(function floatEquality(a, b) {
if (a === +a && b === +b &am... | 4 | 2016-07-25T18:34:30Z | [
"javascript",
"python",
"unit-testing",
"testing",
"jasmine"
] |
How to use certain elements in a list to compare elements in other lists and output a certain element if duplicates are found in Python? | 38,509,829 | <p>I am new here (and new to programming).
I have tried to locate the relevant questions with no luck.</p>
<p>Basically, I got some lists shown below:</p>
<pre><code>[0, 'a', 1, 3, 3.3, 220, 22.27]
[0, 'b', 1, 13, 3.3, 220, 23.19]
[0, 'c', 1, 23, 3.3, 220, 24.11]
[1, 'a', 1, 3, 3.5, 200, 20.02]
[1, 'b', 1, 43, 3.3, 2... | 0 | 2016-07-21T16:39:41Z | 38,510,139 | <p>@wagaman: Hi Pal, Here a little snippet to do this job:</p>
<pre><code>universe = []
universe.append([0, 'a', 1, 3, 3.3, 220, 22.27])
universe.append([0, 'b', 1, 13, 3.3, 220, 23.19])
universe.append([0, 'c', 1, 23, 3.3, 220, 24.11])
universe.append([1, 'a', 1, 3, 3.5, 200, 20.02])
universe.append([1, 'b', 1, 43, 3... | 0 | 2016-07-21T16:55:30Z | [
"python",
"list",
"compare"
] |
How to use certain elements in a list to compare elements in other lists and output a certain element if duplicates are found in Python? | 38,509,829 | <p>I am new here (and new to programming).
I have tried to locate the relevant questions with no luck.</p>
<p>Basically, I got some lists shown below:</p>
<pre><code>[0, 'a', 1, 3, 3.3, 220, 22.27]
[0, 'b', 1, 13, 3.3, 220, 23.19]
[0, 'c', 1, 23, 3.3, 220, 24.11]
[1, 'a', 1, 3, 3.5, 200, 20.02]
[1, 'b', 1, 43, 3.3, 2... | 0 | 2016-07-21T16:39:41Z | 38,516,669 | <p>Let us first define the input data:</p>
<pre><code>some_lists = [[0, 'a', 1, 3, 3.3, 220, 22.27],
[0, 'b', 1, 13, 3.3, 220, 23.19],
[0, 'c', 1, 23, 3.3, 220, 24.11],
[1, 'a', 1, 3, 3.5, 200, 20.02],
[1, 'b', 1, 43, 3.3, 220, 25.94],
[2, 'a', 1, 3... | 0 | 2016-07-22T01:05:32Z | [
"python",
"list",
"compare"
] |
Error loading a image file into ndarray with scipy.ndimage.imread | 38,509,870 | <p>Im trying to load a image file into a ndarray with something like this:</p>
<pre><code>image_data = ndimage.imread(image_file).astype(float)
</code></pre>
<p>but i get this error:</p>
<pre><code>/home/milos/anaconda3/envs/tensorflow/lib/python3.5/site-packages/scipy/ndimage/io.py in imread(fname, flatten, mode)
... | 0 | 2016-07-21T16:41:44Z | 38,510,552 | <p>Managed to do it in the end by bypassing scipy : </p>
<pre><code>from PIL import Image
img = Image.open(image_file)
image_data = np.array(img).astype(float)
</code></pre>
<p>would still like to know what the problem is with scipy, so please post if you know it</p>
<p>Edit :</p>
<p>Found a better solution:</p>
<... | 2 | 2016-07-21T17:20:00Z | [
"python",
"scipy"
] |
Error loading a image file into ndarray with scipy.ndimage.imread | 38,509,870 | <p>Im trying to load a image file into a ndarray with something like this:</p>
<pre><code>image_data = ndimage.imread(image_file).astype(float)
</code></pre>
<p>but i get this error:</p>
<pre><code>/home/milos/anaconda3/envs/tensorflow/lib/python3.5/site-packages/scipy/ndimage/io.py in imread(fname, flatten, mode)
... | 0 | 2016-07-21T16:41:44Z | 39,311,336 | <p>I'm using Python 2.7.x and encountering the same problem. I'm not sure what's going on with scipy.ndimage.imread() in this context either. Uninstalling Pillow (PIL) does not resolve the problem. So, I did the same as what Milos proposed and it worked:</p>
<pre><code>import PIL
import numpy as np
image_file = './my_... | 0 | 2016-09-03T21:07:31Z | [
"python",
"scipy"
] |
Lost accent characters php | 38,509,878 | <p>good afternoon , I have a script in python to run it from PHP. The script makes a query to a database and returns a JSON object :</p>
<p><code>[{"ESC_DEF": 0, "ESC_EJE": 2017, "ESC_FEC_PRE": null, "ESC_USU_BAJA": null, "ESC_NOM": "prueba fran 3", "ESC_SIT": "ABIERTO", "ESC_USU_ALTA": "hep68", "RONDA_ID": 1, "ESC_OR... | 0 | 2016-07-21T16:42:03Z | 38,510,338 | <p>"\xc3\xb3" is "ó". In removing the slashes with stripslashes($str) you're also losing the unicode escapes and therefore only getting the weird chars instead of the small latin o you're looking for. Not well versed in php but try running without that function.</p>
| 0 | 2016-07-21T17:07:06Z | [
"php",
"python",
"json",
"utf-8"
] |
How do I load balance phantomjs using docker-compose and haproxy? | 38,510,040 | <p>I have an application that uses selenium webdriver to interface with PhantomJS. To scale things up, I want to run multiple instances of PhantomJS and load balance them with haproxy. This is for a local application, so I'm not concerned with deployment to a production environment or anything like that.</p>
<p>Here... | 1 | 2016-07-21T16:50:06Z | 38,514,405 | <p>You should be able to add cookies within haproxy config itself..</p>
<pre><code>cookie SERVERID insert indirect nocache
server httpd1 10.0.0.19:9443 cookie httpd1 check
server httpd2 10.0.0.18:9443 cookie httpd2 check
</code></pre>
<p>Then sessions will be stick through haproxy itself.</p>
| 0 | 2016-07-21T21:09:43Z | [
"python",
"selenium",
"phantomjs",
"docker-compose",
"haproxy"
] |
Read in data and set it to the index of a DataFrame with Pandas | 38,510,059 | <p>I want to iterate through the rows of a DataFrame and assign values to a new DataFrame. I've accomplished that task indirectly like this:</p>
<pre><code>#first I read the data from df1 and assign it to df2 if something happens
counter = 0 #line1
for index,row in df1.iterrows(): #line2
... | 2 | 2016-07-21T16:50:50Z | 38,510,181 | <p>No need to iterate, you can do: </p>
<pre><code>df2.index = df1['df1_col']
</code></pre>
<p>If you really want to iterate, save it to a list and set the index.</p>
| 0 | 2016-07-21T16:58:07Z | [
"python",
"pandas",
"dataframe"
] |
Read in data and set it to the index of a DataFrame with Pandas | 38,510,059 | <p>I want to iterate through the rows of a DataFrame and assign values to a new DataFrame. I've accomplished that task indirectly like this:</p>
<pre><code>#first I read the data from df1 and assign it to df2 if something happens
counter = 0 #line1
for index,row in df1.iterrows(): #line2
... | 2 | 2016-07-21T16:50:50Z | 38,510,551 | <p>There are a bunch of ways to do this. According to your code, all you've done is created an empty <code>df2</code> dataframe with an index of values from <code>df1.df1_col</code>. You could do this directly like this:</p>
<pre><code>df2 = pd.DataFrame([], df1.df1_col)
# ^ ^
# ... | 4 | 2016-07-21T17:19:58Z | [
"python",
"pandas",
"dataframe"
] |
Python continue Not Working Properly | 38,510,108 | <p>I am writing a method using Python and I believe that the <code>continue</code> statement is not working properly. Can some explain to me what is wrong there?</p>
<p>The method code is below:</p>
<pre><code>def xlToLinkedDt(lst1, lst2, name1, name2):
logging.info(">> New iteration")
dates1, t... | 0 | 2016-07-21T16:53:44Z | 38,510,174 | <blockquote>
<p>The code is not supposed to log both messages.</p>
</blockquote>
<p>Yes, it is.</p>
<p>After your code executes <em>continue</em>, the loop moves back to the beginning of the block inside the for-loop, in the next iteration. If the condition in your <code>if</code>-block is not met at the next iter... | 2 | 2016-07-21T16:57:37Z | [
"python",
"for-loop",
"continue"
] |
Python continue Not Working Properly | 38,510,108 | <p>I am writing a method using Python and I believe that the <code>continue</code> statement is not working properly. Can some explain to me what is wrong there?</p>
<p>The method code is below:</p>
<pre><code>def xlToLinkedDt(lst1, lst2, name1, name2):
logging.info(">> New iteration")
dates1, t... | 0 | 2016-07-21T16:53:44Z | 38,510,231 | <p>You used <code>continue</code>, I guess you meant <code>break</code>.</p>
<p><code>continue</code> will skip to the next iteration of your <code>for</code> loop.
<code>break</code> will leave the <code>for</code> loop.</p>
<p>Try that :</p>
<pre><code>def test():
print("Function start")
for i in range(10... | 0 | 2016-07-21T17:00:33Z | [
"python",
"for-loop",
"continue"
] |
Difference between a list & a stack in python? | 38,510,140 | <p>What is the difference between a list & a stack in python? </p>
<p>I have read its explanation in the python documentation but there both the things seems to be same?</p>
<pre><code>>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>&... | -2 | 2016-07-21T16:55:34Z | 38,510,166 | <p>A stack is a <em>data structure concept</em>. The documentation uses a Python <code>list</code> object to implement one. That's why that section of the tutorial is named <em>Using Lists as Stacks</em>.</p>
<p>Stacks are just things you add stuff to, and when you take stuff away from a stack again, you do so in reve... | 7 | 2016-07-21T16:56:57Z | [
"python",
"list",
"stack"
] |
Difference between a list & a stack in python? | 38,510,140 | <p>What is the difference between a list & a stack in python? </p>
<p>I have read its explanation in the python documentation but there both the things seems to be same?</p>
<pre><code>>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>&... | -2 | 2016-07-21T16:55:34Z | 38,510,167 | <p>A "stack" is a specific application of <code>list</code>, with operations limited to appending (pushing) to and popping (pulling) from the end.</p>
| 1 | 2016-07-21T16:57:05Z | [
"python",
"list",
"stack"
] |
Difference between a list & a stack in python? | 38,510,140 | <p>What is the difference between a list & a stack in python? </p>
<p>I have read its explanation in the python documentation but there both the things seems to be same?</p>
<pre><code>>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>&... | -2 | 2016-07-21T16:55:34Z | 38,510,206 | <p>In python lists can also be used as stacks. Think of a list like a combination between your normal lists and a stack.
This is also described <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">here</a> </p>
<blockquote>
<p>The list methods make it very easy to use a list as a stack, wh... | 0 | 2016-07-21T16:59:05Z | [
"python",
"list",
"stack"
] |
Difference between a list & a stack in python? | 38,510,140 | <p>What is the difference between a list & a stack in python? </p>
<p>I have read its explanation in the python documentation but there both the things seems to be same?</p>
<pre><code>>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>&... | -2 | 2016-07-21T16:55:34Z | 38,525,709 | <p>Stack works in the concept of Last in First out.
We can perform push and pop operations in the stack
But compare to stack list is easy to do all operations like add,insert,delete,concat etc...
Stack is the application of stack and it's like data structures we use it more.</p>
| 0 | 2016-07-22T11:48:38Z | [
"python",
"list",
"stack"
] |
sudo/suid non-root nesting fails | 38,510,197 | <p>I have a python script (which must be called as root), which calls a bash script (which must be called as non-root), which sometimes needs to call sudo. This does not work - the "leaf" sudo calls give the message "$user is not in the sudoers file. This incident will be reported." How can I make this work?</p>
<p... | 0 | 2016-07-21T16:58:53Z | 38,510,429 | <p>I'd suggest using <code>sudo</code> to drop privileges rather than doing so yourself -- that's a bit more thorough where possible, modifying effective as opposed to only real uid and gid. (To modify the full set yourself, you might try changing <code>setuid()</code> to <code>setreuid()</code>, and likewise <code>set... | 1 | 2016-07-21T17:11:58Z | [
"python",
"linux",
"bash",
"python-3.x",
"sudo"
] |
Python: TypeError: 'list' object is not callable on global variable | 38,510,214 | <p>I am currently in the process of programming a text-based adventure in Python as a learning exercise. I want "help" to be a global command, stored as values in a list, that can be called at (essentially) any time. As the player enters a new room, or the help options change, I reset the <code>help_commands</code> lis... | -1 | 2016-07-21T16:59:43Z | 38,510,242 | <p>You are mixing the name of a list with that of a function:</p>
<pre><code>help = ["Exit [direction], Open [object], Talk to [Person], Use [Item]"]
</code></pre>
<p>And then:</p>
<pre><code>def help():
sub_help = '|'.join(help_commands)
print "The following commands are avalible: " + sub_help
</code></pre>... | 5 | 2016-07-21T17:01:11Z | [
"python",
"python-2.7"
] |
selenium not showing pop up when script is running | 38,510,246 | <p>I am using python-selenium bindings to automate webpage. I am using following line of code to press <code>ENTER</code> button and invoke a pop up:</p>
<pre><code>driver.find_element_by_xpath("xpath_of_element").send_keys(u'\ue007')
</code></pre>
<p>The Test Case is pass but it donot invoke the pop-up when the scri... | 0 | 2016-07-21T17:01:35Z | 38,522,945 | <p>You should try using <code>click()</code> instead of <code>send_keys()</code> as below :-</p>
<pre><code>driver.find_element_by_xpath("xpath_of_element").click()
</code></pre>
<p><strong>Edited</strong> :- if in your case pop-up occurred by keyboard events try as below :-</p>
<pre><code>from selenium.webdriver.co... | 0 | 2016-07-22T09:30:11Z | [
"python",
"selenium",
"selenium-webdriver"
] |
the usage or API of tf.app.flags | 38,510,339 | <p>When reading the <a href="https://github.com/tensorflow/tensorflow/blob/e008ecf12607f691952a9bfe8971f406b30bc56e/tensorflow/models/image/cifar10/cifar10_train.py#L129" rel="nofollow">cifar10 example</a>, I can see the following code segment, which is said to follow the google commandline standard. But in specific, ... | -1 | 2016-07-21T17:07:07Z | 38,513,531 | <p>My experience with TensorFlow is that looking at the source code is often more useful than Ctrl+F in the API doc. I keep PyCharm open with the TensorFlow project, and can easily search for either example of how to do something (e.g., custom reader).</p>
<p>In this particular case, you want to look at what's going o... | 0 | 2016-07-21T20:13:53Z | [
"python",
"tensorflow",
"conv-neural-network"
] |
Passing a Python list of strings to Applescript? | 38,510,374 | <p>I have a Python script that evaluates certain directories on my hard-drive for criteria matching files. It returns a list of strings, containing the file names.<br>
In Applescript, I call the Python script with <code>do shell script "path-to-script.py"</code>.<br>
If I print the list inside the Python script and run... | 0 | 2016-07-21T17:09:09Z | 38,510,527 | <p>The most straightforward way to do this is to have the Python script print the list items on separate lines:</p>
<pre><code>print("\n".join(list_of_files))
</code></pre>
<p>And in AppleScript, break those lines up into a list:</p>
<pre><code>set AppleScript's text item delimiters to return
set list_of_files to te... | 1 | 2016-07-21T17:18:13Z | [
"python",
"list",
"applescript"
] |
Passing a Python list of strings to Applescript? | 38,510,374 | <p>I have a Python script that evaluates certain directories on my hard-drive for criteria matching files. It returns a list of strings, containing the file names.<br>
In Applescript, I call the Python script with <code>do shell script "path-to-script.py"</code>.<br>
If I print the list inside the Python script and run... | 0 | 2016-07-21T17:09:09Z | 38,785,155 | <p>It would be good practice to save Applescript's text item delimiters to a variable first and restore them after you have done what you want. Also enclose it all in a try block to avoid leaving the text delimiters in an unexpected state for any other scripts that may be run. i.e.</p>
<pre><code>try
set oldDelim... | 0 | 2016-08-05T08:54:17Z | [
"python",
"list",
"applescript"
] |
why is my Python program slowing down my computer | 38,510,688 | <p>I have a small program in python that collect probe requests and send ssids and macs to a server. But it slows down my computer after few minutes. I have tried to add dict so that I will make a POST only when it is necessary.
But the problem still the same: after few minutes, my computer is slowing down. I have tri... | 0 | 2016-07-21T17:27:39Z | 38,512,460 | <p>Your program is using too much memory. This is because you aren't clearing your macSsid dictionary. If you delete the entries after you use them (using <code>del</code>), your program will use less memory and thus stop slowing down your computer.</p>
| 0 | 2016-07-21T19:05:19Z | [
"python",
"performance"
] |
why is my Python program slowing down my computer | 38,510,688 | <p>I have a small program in python that collect probe requests and send ssids and macs to a server. But it slows down my computer after few minutes. I have tried to add dict so that I will make a POST only when it is necessary.
But the problem still the same: after few minutes, my computer is slowing down. I have tri... | 0 | 2016-07-21T17:27:39Z | 38,514,595 | <p>I believe it is caused by this line:</p>
<pre><code> if pkt.info not in macSsid[pkt.addr2]:
</code></pre>
<p>As the list referenced by macSsid[pkt.addr2] gets larger, the cost of doing an iterative search on a python list becomes very high. This is a list, not a dictionary, so there is no index, and python has... | 0 | 2016-07-21T21:23:12Z | [
"python",
"performance"
] |
lxml - Default name spaces | 38,510,693 | <p>I am trying to parse an xml file using <code>lxml</code>.</p>
<pre><code>my_tree = etree.parse(file)
my_root = my_tree.getroot()
for child in my_root:
print(child.tag)
# {some default namespace}Prop
# {some default namespace}Prop
# {some default namespace}Stuff
# ...
</code></pre>
<p>Ideally, I just want to ... | 1 | 2016-07-21T17:27:53Z | 38,511,267 | <p>I just use a helper class. <code>context</code> is the document, <code>my</code> is the namespace, and <code>key</code> is the tag name.</p>
<pre><code>found = self.context.find('.//{%s}%s' % (self.my, key))
</code></pre>
| 1 | 2016-07-21T17:59:35Z | [
"python",
"xml",
"lxml"
] |
lxml - Default name spaces | 38,510,693 | <p>I am trying to parse an xml file using <code>lxml</code>.</p>
<pre><code>my_tree = etree.parse(file)
my_root = my_tree.getroot()
for child in my_root:
print(child.tag)
# {some default namespace}Prop
# {some default namespace}Prop
# {some default namespace}Stuff
# ...
</code></pre>
<p>Ideally, I just want to ... | 1 | 2016-07-21T17:27:53Z | 38,512,138 | <p>Hackish or not, you have to specify a prefix. <strong>XPath 1.0</strong>, which is what lxml supports, does not have a concept of default namespace (it works differently in <strong>XPath 2.0</strong>, but that does not apply here).</p>
<p>The other option is to not bother with prefixes at all. Use the fully qualifi... | 1 | 2016-07-21T18:47:22Z | [
"python",
"xml",
"lxml"
] |
lxml - Default name spaces | 38,510,693 | <p>I am trying to parse an xml file using <code>lxml</code>.</p>
<pre><code>my_tree = etree.parse(file)
my_root = my_tree.getroot()
for child in my_root:
print(child.tag)
# {some default namespace}Prop
# {some default namespace}Prop
# {some default namespace}Stuff
# ...
</code></pre>
<p>Ideally, I just want to ... | 1 | 2016-07-21T17:27:53Z | 39,132,809 | <p>you can "automatically" redefine your default namespace with something like:</p>
<pre><code>{k if k is not None else 'default':v for k,v in my_root.nsmap.items()}
</code></pre>
<p>which gets a namespace dictionary with the key None replaced by "default" and leaves all other keys untouched:</p>
<pre><code>{'defaul... | 1 | 2016-08-24T20:50:13Z | [
"python",
"xml",
"lxml"
] |
How to add album art to mp3 file using python 3? | 38,510,694 | <p>I was wondering what module to use for setting an image as the album art for a particular mp3 file. Mutagen seemed to be a popular choice, but it doesn't seem to work on python 3 and I can't find any documentation.</p>
| 0 | 2016-07-21T17:27:58Z | 39,316,853 | <p>Here's a modified version of the code I use. You will want to change the <code>example.mp3</code> and <code>cover.jpg</code> (and perhaps the mime type too):</p>
<pre><code>import eyed3
audiofile = eyed3.load('example.mp3')
if (audiofile.tag == None):
audiofile.initTag()
audiofile.tag.images.set(3, open('cove... | 1 | 2016-09-04T12:21:42Z | [
"python",
"audio",
"python-3.4",
"eyed3"
] |
Error using tensorflow: needs protobuf 3.0.0 but finds 2.6.1 - pip3 shows 3.0.0b2 installed | 38,510,795 | <p>running my newest python code (which uses keras/tensorflow), I get this error:</p>
<pre><code>[libprotobuf FATAL google/protobuf/stubs/common.cc:61] This program requires version 3.0.0 of the Protocol Buffer runtime library, but the installed version is 2.6.1. Please update your library. If you compiled the progr... | 0 | 2016-07-21T17:33:59Z | 38,678,009 | <p>I'm using Ubuntu 16.04, with tensorflow 0.90 installed from source, with cuda 8.0RC & cudann5. I had this exact same error with some keras code which utilised the tensorflow backend.</p>
<p>It's not 100% clear where the problem lies, but it doesn't appear when running any tensorflow code directly, nor with skfl... | 1 | 2016-07-30T20:03:42Z | [
"python",
"version",
"tensorflow",
"protocol-buffers"
] |
Dictionary to list with lists inside and print to csv | 38,510,815 | <p>I have a dictionary I wish to turn into a list containing lists so that I can write into a csv, but what ever I do, it doesn't work.</p>
<p>I used sorted(dllist.items()) to sort them as </p>
<pre><code>[(key1, value1), (key2, value2), ... ,(keyN, valueN)]
</code></pre>
<p>This is what I have,</p>
<pre><code>dict... | 0 | 2016-07-21T17:35:25Z | 38,510,903 | <p>Given the output from <code>sorted</code>, this does it:</p>
<pre><code>>>> my_dict = [('aaa', [5787, 40, 1161, 1222]), ('aab', [6103, 69, 810, 907]), ('aac', [3081, 41, 559, 638]), ('aae', [1011000, 191, 411, 430])]
>>> my_list = [tuple([i[0]] + i[1]) for i in my_dict]
>>>
>>> ... | 0 | 2016-07-21T17:40:22Z | [
"python",
"csv",
"dictionary"
] |
Dictionary to list with lists inside and print to csv | 38,510,815 | <p>I have a dictionary I wish to turn into a list containing lists so that I can write into a csv, but what ever I do, it doesn't work.</p>
<p>I used sorted(dllist.items()) to sort them as </p>
<pre><code>[(key1, value1), (key2, value2), ... ,(keyN, valueN)]
</code></pre>
<p>This is what I have,</p>
<pre><code>dict... | 0 | 2016-07-21T17:35:25Z | 38,510,910 | <p>You can add tuples (which appends them to each other) and you can convert lists into tuples. So, the following works for me:</p>
<pre><code>>>> x = [('a', [1,2,3]), ('b', [4,5,6])]
>>> x
[('a', [1, 2, 3]), ('b', [4, 5, 6])]
>>> y = [(i,) + tuple(j) for i, j in x]
>>> y
[('a', 1, ... | 0 | 2016-07-21T17:40:45Z | [
"python",
"csv",
"dictionary"
] |
Dictionary to list with lists inside and print to csv | 38,510,815 | <p>I have a dictionary I wish to turn into a list containing lists so that I can write into a csv, but what ever I do, it doesn't work.</p>
<p>I used sorted(dllist.items()) to sort them as </p>
<pre><code>[(key1, value1), (key2, value2), ... ,(keyN, valueN)]
</code></pre>
<p>This is what I have,</p>
<pre><code>dict... | 0 | 2016-07-21T17:35:25Z | 38,510,991 | <p>Given my assumption about what your dictionary looks like, this should do the conversion you want and write the output to a CSV file:</p>
<pre><code>import csv
d = { 'aaa': [5787, 40, 1161, 1222], 'aab': [6103, 69, 810, 907] }
rows = [[k] + v for k, v in sorted(d.items())]
with open("out.csv", "w") as out:
wr... | 0 | 2016-07-21T17:45:00Z | [
"python",
"csv",
"dictionary"
] |
to redirect to URL which accepts POST requests only in django | 38,510,832 | <p>I am currently working on a project based on django framework which requires apis to be built that accept POST requests only except one or two which can recieve GET requests. One of those apis, say /x/, is invoked on the submission of form with method type as POST. The view attached to this api /x/ modifies the req... | 0 | 2016-07-21T17:36:19Z | 38,511,160 | <p>"I have tried both redirect and HttpResponseRedirect methods but both of them call the url or view functions as a GET"</p>
<p>This is because redirecting POST data is considered bad design choice and is not supported by Django in any obvious way. Check out this answer to similar question:</p>
<p><a href="http://st... | 1 | 2016-07-21T17:53:58Z | [
"python",
"django",
"redirect",
"http-post"
] |
Pandas cumsum on groupby not behaving as expected | 38,510,860 | <p>I have a dataframe like this:</p>
<pre><code>df = pd.DataFrame({'prob':np.random.uniform(0,1,size), 'target':np.random.randint(0,2, size=size),
'pred':np.random.randint(0,2, size=size)})
</code></pre>
<p>That I want to compute <code>cumsum</code> of a <code>groupby</code> of a <code>qcut</code>:</p>... | 0 | 2016-07-21T17:37:33Z | 38,511,161 | <p>You want to calculate the percentage for each group and <strong>then</strong> take the cumsum. </p>
<p>In your original code <code>df.groupby('box').target.cumsum()</code> will take the <code>cumsum</code> of each group - so you will have one element for each of the elements in the grouped DataFrame. Then the divis... | 4 | 2016-07-21T17:54:01Z | [
"python",
"pandas"
] |
Python vs Java Loop | 38,510,897 | <p>I am working through some problems on HackerRank, and I thought I would try implementing the same solution in Python that I had already solved correctly in Java. Although my code almost exactly mirrors my previous Python solution, I am getting an out of bounds exception in the <code>if input_str[i-1] == input_str[i]... | 1 | 2016-07-21T17:40:09Z | 38,510,962 | <p>In the Java loop, <code>s.length()</code> is recalculated every iteration. In Python, <code>len(input_str)</code> is only calculated once and does not reflect the correct length after you've modified <code>input_str</code> in the <code>if</code> block.</p>
<p>Similarly, assigning <code>i = 0</code> does not work th... | 5 | 2016-07-21T17:43:42Z | [
"java",
"python",
"string",
"for-loop"
] |
Python vs Java Loop | 38,510,897 | <p>I am working through some problems on HackerRank, and I thought I would try implementing the same solution in Python that I had already solved correctly in Java. Although my code almost exactly mirrors my previous Python solution, I am getting an out of bounds exception in the <code>if input_str[i-1] == input_str[i]... | 1 | 2016-07-21T17:40:09Z | 38,513,156 | <p>I believe you are wasting a lot of time and system resources by doing it that way. A better solution would be to change the algorithm into one that only iterates <code>input_str</code> only once. In which case, you get <code>O(n)</code> execution time. My edited code looks thus:</p>
<pre><code>input_str = input()
i... | 1 | 2016-07-21T19:49:08Z | [
"java",
"python",
"string",
"for-loop"
] |
Python vs Java Loop | 38,510,897 | <p>I am working through some problems on HackerRank, and I thought I would try implementing the same solution in Python that I had already solved correctly in Java. Although my code almost exactly mirrors my previous Python solution, I am getting an out of bounds exception in the <code>if input_str[i-1] == input_str[i]... | 1 | 2016-07-21T17:40:09Z | 38,513,636 | <p>I would build on funaquarius24 and not even use indexes:</p>
<pre><code>input_str = raw_input()
result = input_str[0]
for c in input_str[1:]:
if c != result[-1]:
result += c
print(result)
</code></pre>
| 0 | 2016-07-21T20:20:16Z | [
"java",
"python",
"string",
"for-loop"
] |
Is `if x:` completely equivalent to `if bool(x) is True:`? | 38,510,964 | <p>For a small testing framework we are writing I'm trying to provide some utility functions.</p>
<p>One of them is supposed to be equivalent to <code>if x:</code> but if that is <strong>completely</strong> equivallent to <code>if bool(x) is True:</code> then I could only provide one function to check <code>if x is Tr... | 5 | 2016-07-21T17:44:01Z | 38,510,993 | <p><code>if x:</code> is <em>completely</em> equivalent to testing for the boolean truth value, yes.</p>
<p>From the <a href="https://docs.python.org/2/reference/compound_stmts.html#the-if-statement" rel="nofollow"><code>if</code> statement documentation</a>:</p>
<blockquote>
<p>It selects exactly one of the suites... | 6 | 2016-07-21T17:45:03Z | [
"python"
] |
Is `if x:` completely equivalent to `if bool(x) is True:`? | 38,510,964 | <p>For a small testing framework we are writing I'm trying to provide some utility functions.</p>
<p>One of them is supposed to be equivalent to <code>if x:</code> but if that is <strong>completely</strong> equivallent to <code>if bool(x) is True:</code> then I could only provide one function to check <code>if x is Tr... | 5 | 2016-07-21T17:44:01Z | 38,510,997 | <p>Yes. These are equivalent. The rules used by <code>if</code> are the same as those used by <code>bool</code>. <code>not</code> simply inverts these values without changing the logic for determining truthiness or falseness.</p>
| 2 | 2016-07-21T17:45:24Z | [
"python"
] |
Is `if x:` completely equivalent to `if bool(x) is True:`? | 38,510,964 | <p>For a small testing framework we are writing I'm trying to provide some utility functions.</p>
<p>One of them is supposed to be equivalent to <code>if x:</code> but if that is <strong>completely</strong> equivallent to <code>if bool(x) is True:</code> then I could only provide one function to check <code>if x is Tr... | 5 | 2016-07-21T17:44:01Z | 38,512,053 | <p>additionally to the answer of @Martijn, if what you are building are some class, you can define what behavior you want it to have in a truth testing case like <code>ìf x</code> by defining <code>__bool__</code> function. </p>
<pre><code>>>> class A:
pass
>>> a=A()
>>> if a:
... | 1 | 2016-07-21T18:42:43Z | [
"python"
] |
Read CSV file and filter results | 38,510,966 | <p>Im writing a script where one of its functions is to read a CSV file that contain URLs on one of its rows. Unfortunately the system that create those CSVs doesn't put double-quotes on values inside the URL column so when the URL contain commas it breaks all my csv parsing. </p>
<p>This is the code I'm using: </p>
... | 0 | 2016-07-21T17:44:09Z | 38,511,672 | <p>Have you considered using Pandas to read your data in?</p>
<p>Another possible solution would be to use regular expressions to pre-process the data...</p>
<pre><code>#make a list of everything you want to change
old = re.findall(regex, f.read())
#append quotes and create a new list
new = []
for url in old:
u... | 0 | 2016-07-21T18:21:56Z | [
"python",
"csv",
"parsing"
] |
Read CSV file and filter results | 38,510,966 | <p>Im writing a script where one of its functions is to read a CSV file that contain URLs on one of its rows. Unfortunately the system that create those CSVs doesn't put double-quotes on values inside the URL column so when the URL contain commas it breaks all my csv parsing. </p>
<p>This is the code I'm using: </p>
... | 0 | 2016-07-21T17:44:09Z | 38,532,633 | <p>You will have to do it a little more manually. Try this</p>
<pre><code>def process(lines, delimiter=','):
header = None
url_index_from_start = None
url_index_from_end = None
for line in lines:
if not header:
header = [l.strip() for l in line.split(delimiter)]
url_inde... | 1 | 2016-07-22T17:54:37Z | [
"python",
"csv",
"parsing"
] |
Is there an alternative for sys.exit() in python? | 38,511,096 | <pre><code>try:
x="blaabla"
y="nnlfa"
if x!=y:
sys.exit()
else:
print("Error!")
except Exception:
print(Exception)
</code></pre>
<p>I'm not asking about why it is throwing an error. I know that it raises <code>exceptions.SystemExit</code>. I was wondering if there was another way to exit?... | -3 | 2016-07-21T17:50:38Z | 38,511,414 | <p><code>os._exit()</code> will do a low level process exit without <code>SystemExit</code> or normal python exit processing.</p>
| 1 | 2016-07-21T18:08:15Z | [
"python",
"python-3.x",
"try-except"
] |
Is there an alternative for sys.exit() in python? | 38,511,096 | <pre><code>try:
x="blaabla"
y="nnlfa"
if x!=y:
sys.exit()
else:
print("Error!")
except Exception:
print(Exception)
</code></pre>
<p>I'm not asking about why it is throwing an error. I know that it raises <code>exceptions.SystemExit</code>. I was wondering if there was another way to exit?... | -3 | 2016-07-21T17:50:38Z | 38,512,740 | <p>Some questions like that should really be accompanied by the real intention behind the code. The reason is that some problems should be solved completely differently. In the body of the script, the <code>return</code> can be used to quit the script. From another point of view, you can just remember the situation in ... | 0 | 2016-07-21T19:24:09Z | [
"python",
"python-3.x",
"try-except"
] |
ACK & TCP Window on Ubuntu | 38,511,136 | <p>Good evening,</p>
<p>I am working on a project which is using eventlet <a href="http://eventlet.net/" rel="nofollow">http://eventlet.net/</a> ontop of wsgi in Python to create a websocket server. So far everything is working well. We did some deep level packet analysis today however and noticed something odd. We ar... | 0 | 2016-07-21T17:52:44Z | 38,514,795 | <blockquote>
<p>Is there some sort of time limit at which a ACK is sent regardless of the received buffer size?</p>
</blockquote>
<p>ACK is being sent to give a feedback from receiver, if sender will not receive ACK during some time (estimated RTT) it guesses that packet is lost and will retransmit this packet again... | 1 | 2016-07-21T21:37:57Z | [
"python",
"sockets",
"ubuntu",
"networking",
"tcp"
] |
Parsing Multiple .json files | 38,511,163 | <p>I am trying to parse multiple files dealing with "Mike's Pies" as you can see in the code below. I have written it to where I get the desired output, now I would like to parse all the files named "Mike's Pies"</p>
<pre><code> import json
import sys
import glob
with open("Mike's Pies.20130201.json") as json_data:... | 0 | 2016-07-21T17:54:10Z | 38,511,280 | <p>It sounds like you have code which works on <code>"Mike's Pies.20130201.json"</code>, and you want to run that code on <em>every</em> file that starts with "Mike's Pies" and ends with "json", regardless of the timestamp-like bit in the middle. Am I right? You can get all matching filenames with <code>glob</code> and... | 1 | 2016-07-21T18:00:21Z | [
"python"
] |
While debugging, how to print all variables (which is in list format) who are trainable in Tensorflow? | 38,511,166 | <p>While debugging, how to print all variables (which is in list format) who are trainable in Tensorflow?</p>
<p>For instance,</p>
<pre><code> tvars = tf.trainable_variables()
</code></pre>
<p>I want to check all the variables in tvars (which is list type).</p>
<p>I've already tried the below code which returns ... | 0 | 2016-07-21T17:54:19Z | 38,580,555 | <p>Since <code>tf.trainable_variables()</code> returns a list of <code>tf.Variable</code> objects, you should be able to pass its result straight to <code>Session.run()</code>:</p>
<pre><code>tvars = tf.trainable_variables()
tvars_vals = sess.run(tvars)
for var, val in zip(tvars, tvars_vals):
print(var.name, val)... | 1 | 2016-07-26T03:28:56Z | [
"python",
"tensorflow"
] |
How to declare variables to be used in multiple modules in python | 38,511,192 | <p>This question has probably been asked before, but the other posts I found on Stack Overflow mainly dealt with changing global variables and importing functions etc. Perhaps my wording wasn't right when I did a quick search.</p>
<p>I am starting to code in Python, and I was wondering what the most efficient and prop... | 0 | 2016-07-21T17:55:45Z | 38,511,405 | <p>Importing the whole module will act as a sort of namespace, and it seems to me to be the simplest way to do it. So you have "mystuff.py":</p>
<pre><code>a = 1
b = 2
def MyFunc():
....
</code></pre>
<p>Then in your other modules:</p>
<pre><code>import mystuff
print mystuff.a
print mystuff.b
mystuff.MyFunc(... | 1 | 2016-07-21T18:08:05Z | [
"python",
"class",
"import",
"global-variables",
"constants"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.