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 |
|---|---|---|---|---|---|---|---|---|---|
Understanding Inheritance in python | 40,080,783 | <p>I am learning OOP in python.</p>
<p>I am struggling why this is not working as I intended?</p>
<pre><code>class Patent(object):
"""An object to hold patent information in Specific format"""
def __init__(self, CC, PN, KC=""):
self.cc = CC
self.pn = PN
self.kc = KC
class USPatent(Pat... | 2 | 2016-10-17T07:34:11Z | 40,080,883 | <p>You are passing in an empty string:</p>
<pre><code>Patent.__init__(self, CC, PN, KC="")
</code></pre>
<p>That calls the <code>Patent.__init__()</code> method setting <code>KC</code> to <code>""</code>, always.</p>
<p>Pass in whatever value of <code>KC</code> you received instead:</p>
<pre><code>class USPatent(Pa... | 4 | 2016-10-17T07:39:52Z | [
"python",
"inheritance"
] |
Understanding Inheritance in python | 40,080,783 | <p>I am learning OOP in python.</p>
<p>I am struggling why this is not working as I intended?</p>
<pre><code>class Patent(object):
"""An object to hold patent information in Specific format"""
def __init__(self, CC, PN, KC=""):
self.cc = CC
self.pn = PN
self.kc = KC
class USPatent(Pat... | 2 | 2016-10-17T07:34:11Z | 40,080,893 | <p>The line</p>
<pre><code>Patent.__init__(self, CC, PN, KC="")
</code></pre>
<p>Should be</p>
<pre><code>Patent.__init__(self, CC, PN, KC)
</code></pre>
<p>The former sets the argument with the name "KC" to the value <code>""</code> (the empty string) using the keyword-style argument syntax. What you want is pass ... | 1 | 2016-10-17T07:40:31Z | [
"python",
"inheritance"
] |
Establishing a socket connection between computers? | 40,080,811 | <p>I was learning about networking and I have some trouble understanding what went wrong.</p>
<p>I created a Client and a Server script:</p>
<p>Server:</p>
<pre><code>import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()... | 0 | 2016-10-17T07:35:53Z | 40,080,962 | <p>The problem was that I wasn't referring to the server IP when running from another computer, I fixed it by passing the server IP, in the client script, like this host = "10.x.x.x"</p>
<p>Sorry for creating a useless question! </p>
| 0 | 2016-10-17T07:45:04Z | [
"python",
"sockets",
"networking",
"communication"
] |
Separate system of coordinates for x and y | 40,080,850 | <p>I am using matplotlib for plotting in my project. I have a time series on my chart and I would like to add a text annotation. However I would like it to be floating like this: x dimension of the text would be bound to data (e.g. certain date on x-axis like 2015-05-04) and y dimension bound to Axes coordinates system... | 0 | 2016-10-17T07:37:58Z | 40,080,939 | <p>It seems like I found the solution: one should use blended transformation:
<a href="http://matplotlib.org/users/transforms_tutorial.html#blended-transformations" rel="nofollow">http://matplotlib.org/users/transforms_tutorial.html#blended-transformations</a></p>
| 0 | 2016-10-17T07:43:41Z | [
"python",
"matplotlib",
"text",
"transformation",
"axes"
] |
Logging with hug and waitress | 40,080,937 | <p>I want to add logging to my Python <a href="http://www.hug.rest" rel="nofollow">hug</a> REST app. I couldn't find any wayto do it when serving the app through the <code>hug</code> command (via <code>hug -f app.py</code>), therefore I try to combine hug with <a href="https://github.com/Pylons/waitress/" rel="nofollow... | 1 | 2016-10-17T07:43:40Z | 40,081,533 | <p>You have to configure logging for the <code>logging</code> module. Take a look at the <a href="https://docs.python.org/2/library/logging.config.html" rel="nofollow">documentation for <code>logging.config</code></a> (in particular <code>dictConfig</code> and <code>fileConfig</code>). As a start, to test whether it wo... | 1 | 2016-10-17T08:19:04Z | [
"python",
"logging",
"wsgi",
"waitress",
"hug"
] |
How could I clean up this pattern drawing code? | 40,081,081 | <p>so I am trying to draw a simple pattern, kind of two parted. The way it is supposed to look is:</p>
<pre><code>**........*
*.*.......*
*..*......*
*...*.....*
.........*
........*
.......*
......*
</code></pre>
<p>As of now, I have the bottom part finished but it isn't very clean at all, it is very bulky and ther... | 0 | 2016-10-17T07:52:38Z | 40,081,472 | <pre><code>'.'*6
</code></pre>
<p>means
<code>......</code> (dot six times) so instead of </p>
<pre><code>for c in range(0,9):
print('.', end='')
</code></pre>
<p>just do</p>
<pre><code>print('.'*9,end='')
</code></pre>
| 0 | 2016-10-17T08:14:52Z | [
"python",
"loops",
"while-loop",
"range"
] |
Pandas: convert unicode elem in column to list | 40,081,109 | <p>I have dataframe</p>
<pre><code>category dictionary
Classified [u'\u043e', u'\u0441', u'\u043a', u'\u043f\u043e', u'\u0443', u'avito', u'\u043e\u0431', u'\u043d\u0438', u'\u043e\u0431\u044a\u044f\u0432\u043b\u0435\u043d\u0438\u044f', u'%8f-', u'\u0434\u043e', u'\u0435\u0449\u0435', u'\u043f\u0440\u0438', u'000'... | 0 | 2016-10-17T07:53:38Z | 40,081,967 | <p>Try this:</p>
<pre><code>rlst = []
for lst in lsts:
ls0 = lst.strip('[] ').split(',')
rlst.append([unicode(l.lstrip(' u\'').rstrip('\'')) for l in ls0])
</code></pre>
<p><code>rlst</code> is your result as a list of lists of unicode strings.</p>
| 0 | 2016-10-17T08:45:22Z | [
"python",
"pandas",
"unicode"
] |
Testing List of Lists to remove unwanted lists based on a constraint | 40,081,231 | <p>I have a list of lists. The lists are made up of people from certain areas, if the lists have too many people from a certain area I would like to remove the list from the set of lists. The lists are lengths of 9</p>
<pre><code>list=[[["Aarat","California"],
["Aaron","California"],
["Abba","California"],
["Abaddon",... | 1 | 2016-10-17T08:00:58Z | 40,081,552 | <p>Say you start with something like:</p>
<pre><code>list=[[["Aarat","California"],
["Aaron","California"],
["Abba","California"],
["Abaddon","California"],
["Abner","Nevada"],
["Abram","Nevada"],
["Abraham","Nevada"],
["Absalom","Nevada"],
["Adullam","Utah"]],[["Abital","California"],
... | 1 | 2016-10-17T08:20:20Z | [
"python",
"algorithm",
"list"
] |
How to create 2 gram shingles? | 40,081,237 | <p>I have this code which i got from some tutorial-:</p>
<pre><code>list1 = [['hello','there','you','too'],['hello','there','you','too','there'],['there','you','hello']]
def get_shingle(size,f):
#shingles = set()
for i in range (0,len(f)-2+1):
yield f[i:i+2]
#shingles1 = set(get_shingle(list1[0],2))
... | 2 | 2016-10-17T08:01:13Z | 40,081,519 | <p>Because the <code>yield</code> command returns a generator. The conversion of a generator to a set is triggering the unhashable type error.</p>
<p>You can make your code work by a simple alteration.</p>
<pre><code>shingles1 = get_shingle(2,list1[0])
lst = [x for x in shingles1]
</code></pre>
<p>This will give you... | 1 | 2016-10-17T08:17:42Z | [
"python"
] |
How to create 2 gram shingles? | 40,081,237 | <p>I have this code which i got from some tutorial-:</p>
<pre><code>list1 = [['hello','there','you','too'],['hello','there','you','too','there'],['there','you','hello']]
def get_shingle(size,f):
#shingles = set()
for i in range (0,len(f)-2+1):
yield f[i:i+2]
#shingles1 = set(get_shingle(list1[0],2))
... | 2 | 2016-10-17T08:01:13Z | 40,081,589 | <p>The issue lies in the fact that your get_shingle() function yields <code>lists</code>.
Lists are not hashable, which is needed to build a set. You can easily solve this by yielding a tuple (which is hashable), instead of a list.</p>
<p>Transform the following line in your code:</p>
<pre><code>yield tuple(f[i:i+2])... | 1 | 2016-10-17T08:22:41Z | [
"python"
] |
How to create 2 gram shingles? | 40,081,237 | <p>I have this code which i got from some tutorial-:</p>
<pre><code>list1 = [['hello','there','you','too'],['hello','there','you','too','there'],['there','you','hello']]
def get_shingle(size,f):
#shingles = set()
for i in range (0,len(f)-2+1):
yield f[i:i+2]
#shingles1 = set(get_shingle(list1[0],2))
... | 2 | 2016-10-17T08:01:13Z | 40,081,924 | <p>Yield command generates a generator and set(iterator) expects an iterator which is immutable </p>
<p>So something like this will work</p>
<pre><code>shingles1 = set(get_shingle(2,list1[0]))
set(tuple(x) for x in shingles1)
</code></pre>
| 1 | 2016-10-17T08:42:43Z | [
"python"
] |
Matplotlib odd subplots | 40,081,489 | <p>I have to plot a figure with 11 subpots as you can see below. But as it is an odd number, i dont know how to deal the subplot (4,3,12) to remove it... and place the 2 last plots on the center
Moreover i would like to increse the subplot size as the space is too important. The code is below.</p>
<p><a href="https://... | 1 | 2016-10-17T08:16:13Z | 40,081,771 | <p>One way of achieving what you require is to use matplotlibs <a href="http://matplotlib.org/users/gridspec.html" rel="nofollow">subplot2grid</a> feature. Using this you can set the total size of the grid (4,3 in your case) and choose to only plot data in certain subplots in this grid. Below is a simplified example:</... | 1 | 2016-10-17T08:33:52Z | [
"python",
"matplotlib",
"subplot"
] |
Python AppEngine MapReduce | 40,081,642 | <p>i have created a pretty simple MapReduce pipeline, but i am having a cryptic:</p>
<p><code>PipelineSetupError: Error starting production.cron.pipelines.ItemsInfoPipeline(*(), **{})#a741186284ed4fb8a4cd06e38921beff:</code></p>
<p>when i try to start it. This is the pipeline code:</p>
<pre><code>class ItemsInfoPipe... | 0 | 2016-10-17T08:25:32Z | 40,093,196 | <p>This was driving me nuts today. When I run in pycharm I don't get this errors - on command line I did:</p>
<pre><code>python /usr/local/google_appengine/dev_appserver.py app.yaml --port 8000 --host localhost --admin_port=8080 --port=8000
</code></pre>
<p>instead of:</p>
<pre><code>dev_appserver.py app.yaml --port... | 0 | 2016-10-17T18:24:45Z | [
"python",
"google-app-engine",
"mapreduce",
"google-app-engine-python"
] |
Getting low test accuracy using Tensorflow batch_norm function | 40,081,697 | <p>I am using the official Batch Normalization (BN) function (<a href="https://github.com/tensorflow/tensorflow/blob/b826b79718e3e93148c3545e7aa3f90891744cc0/tensorflow/contrib/layers/python/layers/layers.py#L100" rel="nofollow">tf.contrib.layers.batch_norm()</a>) of Tensorflow on the MNIST data. I use the following co... | 1 | 2016-10-17T08:28:39Z | 40,083,061 | <p>You get ~99% accuracy when you test you model with <code>is_training=True</code> only because of the batch size of 100.
If you change the batch size to 1 your accuracy will decrease.</p>
<p>This is due to the fact that you're computing the exponential moving average and variance for the input batch and than you're ... | 1 | 2016-10-17T09:42:34Z | [
"python",
"tensorflow"
] |
Delete first n digits from a column | 40,081,709 | <p>I have a pandas dataframe(roughly 7000 rows) that looks as follows:</p>
<pre><code>Col1 Col2
12345 1234
678910 6789
</code></pre>
<p>I would like to delete the first 4 digits from col1, so as to end up with:</p>
<pre><code>Col1 Col2
5 1234
10 6789
</code></pre>
<p>Or just separate the first col... | 0 | 2016-10-17T08:29:28Z | 40,081,768 | <p>Separating first column into two new ones:</p>
<pre><code>In [5]: df[['New1','New2']] = (df['Col1'].astype(str)
.str.extract(r'(\d{4})(\d+)', expand=True)
.astype(int))
In [6]: df
Out[6]:
Col1 Col2 New1 New2
0 12345 1234 1... | 3 | 2016-10-17T08:33:29Z | [
"python",
"database",
"pandas",
"dataframe"
] |
I can't iterate over line_styles (Matplotlib) | 40,081,848 | <p>Plot generates different colors for each lines but I also need to generate different line_styles for the graph. After searching for some information, I found itertools module. Yet I can't generate plot with the error: <strong>There is no Line2D property "shape_list".</strong></p>
<pre><code>import itertools
from gl... | 0 | 2016-10-17T08:38:25Z | 40,082,148 | <p>I think that <code>g = itertools.cycle(shape_list)</code> should go outside the loop</p>
<p>Also see <a href="http://matplotlib.org/api/markers_api.html#module-matplotlib.markers" rel="nofollow">here</a> for valid markers
What you probably want is
<code>
plt.plot(WL, T, label=fname[0:3], marker = g.__next__())</cod... | 1 | 2016-10-17T08:55:20Z | [
"python",
"matplotlib"
] |
I can't iterate over line_styles (Matplotlib) | 40,081,848 | <p>Plot generates different colors for each lines but I also need to generate different line_styles for the graph. After searching for some information, I found itertools module. Yet I can't generate plot with the error: <strong>There is no Line2D property "shape_list".</strong></p>
<pre><code>import itertools
from gl... | 0 | 2016-10-17T08:38:25Z | 40,082,194 | <p>The markers you can use with <code>plot</code> are defined <a href="http://matplotlib.org/api/markers_api.html" rel="nofollow">in the documentation</a> </p>
<p>to change the marker style, use the <code>marker=</code> argument to the call to <code>plot()</code></p>
<p>eg:</p>
<pre><code>plt.plot(WL, T, label=fname... | 1 | 2016-10-17T08:57:34Z | [
"python",
"matplotlib"
] |
How can I show a flyout in GTK 3? | 40,081,856 | <p>I started creating GTK3 apps in Python a few days ago.<br>
I was wondering how to create a flyout menu like the one gedit shows when Open button is clicked.</p>
<p>Thank you!</p>
<p><a href="https://i.stack.imgur.com/NMjzF.png" rel="nofollow"><img src="https://i.stack.imgur.com/NMjzF.png" alt="Flyout in gedit"></a... | 1 | 2016-10-17T08:38:42Z | 40,100,121 | <p>You're looking for a <a href="http://lazka.github.io/pgi-docs/index.html#Gtk-3.0/classes/MenuButton.html#Gtk.MenuButton" rel="nofollow"><code>Gtk.MenuButton</code></a> with the <code>use_popover</code> property set to <code>True</code>.</p>
| 0 | 2016-10-18T05:22:08Z | [
"python",
"gtk3"
] |
how to disable window7 minimize ability | 40,081,882 | <p>I want to disable all windows minimized ability in win7.I have used <strong>SetWindowLong</strong> in Python win32gui.</p>
<pre><code>from win32gui import *
def disablemin(hwnd,HWMD):
SetWindowLong(hwnd,win32con.GWL_STYLE,GetWindowLong(hwnd,win32con.GWL_STYLE) & ~win32con.WS_MINIMIZEBOX)
EnumWindows(disab... | 0 | 2016-10-17T08:40:04Z | 40,087,113 | <p>There are a few problems with your idea.</p>
<ol>
<li>You're trying to alter the behavior of other windows, windows that aren't yours. This is always a bad idea.</li>
<li>You try to alter the window styles once. This isn't necessarily sufficient; they can be restored by the victim process.</li>
<li>Even if the wind... | 0 | 2016-10-17T13:01:15Z | [
"python",
"c++",
"pywin32"
] |
Saving image in python | 40,081,960 | <p>I'm new to python. What I want to do is to read in an image, convert it to gray value and save it.</p>
<p>This is what I have so far:</p>
<pre><code># construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args ... | 0 | 2016-10-17T08:44:46Z | 40,081,991 | <p>I don't know what you mean about "lots of different modules". You're presumably using Pillow; you opened the image via <code>Image.open</code> and assigned the converted image to <code>im_grey</code>, so now you have an instance of Image which has <a href="http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#P... | 0 | 2016-10-17T08:46:38Z | [
"python",
"image",
"save"
] |
Saving image in python | 40,081,960 | <p>I'm new to python. What I want to do is to read in an image, convert it to gray value and save it.</p>
<p>This is what I have so far:</p>
<pre><code># construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args ... | 0 | 2016-10-17T08:44:46Z | 40,082,036 | <p><strong>Method 1: save method</strong></p>
<pre><code>im_grey.save('greyscale.png')
</code></pre>
<p>Use Image_object.save() method</p>
<p><strong>Method 2: imsave method</strong></p>
<pre><code>import matplotlib.image as mpimg
mpimg.imsave("greyscale.png", im_grey)
</code></pre>
| 1 | 2016-10-17T08:49:17Z | [
"python",
"image",
"save"
] |
How to clean a string using python regular expression | 40,082,056 | <p>I have the following string which have to clean</p>
<pre><code>#import re
addr="abcd&^fhj"
problemchars = re.compile(r'[=\+/&<>;\'"\?%#$@\,\. \t\r\n]')
re.search(problemchars,addr)
</code></pre>
| -1 | 2016-10-17T08:50:12Z | 40,082,109 | <p>In that case use <code>re.sub</code> searching <code>\W</code> (non-alphanum) and replacing by nothing.</p>
<pre><code>import re
addr="abcd&^fhj"
print(re.sub("\W","",addr))
</code></pre>
<p>(<code>"\W+"</code> works too, but not sure it would be more performant) </p>
| 1 | 2016-10-17T08:53:46Z | [
"python",
"regex"
] |
How to clean a string using python regular expression | 40,082,056 | <p>I have the following string which have to clean</p>
<pre><code>#import re
addr="abcd&^fhj"
problemchars = re.compile(r'[=\+/&<>;\'"\?%#$@\,\. \t\r\n]')
re.search(problemchars,addr)
</code></pre>
| -1 | 2016-10-17T08:50:12Z | 40,082,282 | <p>you could use the filter function as well if you don't want to go with regex</p>
<pre><code>line = "abcd&^fhj"
line = filter(str.isalpha, line)
print line # Change for python3
</code></pre>
<p>Output : </p>
<pre><code>abcdfhj
</code></pre>
<p>Edit: For python 3 you could change the print statement like this... | 0 | 2016-10-17T09:02:45Z | [
"python",
"regex"
] |
How to faster compute the count frequency of words in a large words list with python and be a dictionary | 40,082,114 | <p>There is a very long words list, the length of list is about 360000. I want to get the each word frequency, and to be a dictionary. </p>
<p>For example:</p>
<pre><code>{'I': 50, 'good': 30,.......}
</code></pre>
<p>Since the word list is large, I found it take a lot of time to compute it. Do you have faster meth... | 0 | 2016-10-17T08:54:02Z | 40,082,491 | <p>You are doing several things wrong here:</p>
<ul>
<li><p>You are building a huge list first, then turn that list object into a dictionary. There is no need to use the <code>[..]</code> list comprehension; just dropping the <code>[</code> and <code>]</code> would turn it into a much more memory-efficient generator e... | 9 | 2016-10-17T09:13:08Z | [
"python",
"performance",
"list",
"python-3.x",
"dictionary"
] |
python create .pgm file | 40,082,165 | <p>Well first I have to mention that I read the material on this page including :
<a href="http://stackoverflow.com/questions/12374937/create-binary-pbm-pgm-ppm">Create binary PBM/PGM/PPM</a></p>
<p>I also read the page explaining the .pgm file format<a href="http://netpbm.sourceforge.net/doc/pgm.html" rel="nofollow">... | 0 | 2016-10-17T08:56:12Z | 40,083,491 | <p>First your code has missing open <code>'</code> for <code>\n'</code> in statement <code>pgmHeader = 'P5' + ...</code>. Second no <code>fout = open(filename, 'wb')</code>. The main problem is that you use <code>ASCII</code> format to encode the pixel data, you should use <code>binary</code> format to encode them (be... | 0 | 2016-10-17T10:02:34Z | [
"python",
"image",
"format",
"pgm"
] |
IndexError: list index out of range when composing dict from 2 column csv | 40,082,321 | <p>My script that crunches numbers stored in csv gets the numbers into a dict from the csv like this:</p>
<pre><code>fide_rating_file = fide_csv_rating_file.read()
fide_rating_file = fide_rating_file.split("\n")
fide_rating_file2 = [f for f in fide_rating_file if len(f) > 0]
fide_rating_file3 = [f.split(",") for f ... | 1 | 2016-10-17T09:04:55Z | 40,082,395 | <p>You only get a sublist containing at least two items iff, there is a comma on every line</p>
<pre><code>fide_rating_file3 = [f.split(",") for f in fide_rating_file2]
# ^^^^^^^^^^^^
</code></pre>
<p>You may test for the presence of commas before splitting or clean out lines without commas in the ... | 0 | 2016-10-17T09:08:21Z | [
"python"
] |
IndexError: list index out of range when composing dict from 2 column csv | 40,082,321 | <p>My script that crunches numbers stored in csv gets the numbers into a dict from the csv like this:</p>
<pre><code>fide_rating_file = fide_csv_rating_file.read()
fide_rating_file = fide_rating_file.split("\n")
fide_rating_file2 = [f for f in fide_rating_file if len(f) > 0]
fide_rating_file3 = [f.split(",") for f ... | 1 | 2016-10-17T09:04:55Z | 40,085,105 | <p>Per everyones advice I used the standard library csv module</p>
<pre><code>dict(csv.reader(fide_csv_rating_file))
</code></pre>
<p>Following error traceback pointed me to the incorrect lines, just removed them with regex find and replace and then succesfully created the dict.</p>
<p>Thanks guys.</p>
| 0 | 2016-10-17T11:23:05Z | [
"python"
] |
Weird namespace behaviour | 40,082,617 | <p>When trying to run the following code:</p>
<pre><code>i = 0
def truc():
print (i)
if (False): i = 0
truc()
</code></pre>
<p>it yields an UnboundLocalError, but</p>
<pre><code>i = 0
def truc():
print (i)
#if (False): i = 0
truc()
</code></pre>
<p>doesn't.</p>
<p>Is that a wanted behaviour ?</p>
... | 0 | 2016-10-17T09:20:06Z | 40,082,728 | <pre><code>i = 0
def truc():
global i
print (i)
if (False): i = 0
truc()
</code></pre>
<p>To refer the outer scope variable of the function, <code>i</code> should be declared as global.</p>
| -1 | 2016-10-17T09:24:57Z | [
"python"
] |
Weird namespace behaviour | 40,082,617 | <p>When trying to run the following code:</p>
<pre><code>i = 0
def truc():
print (i)
if (False): i = 0
truc()
</code></pre>
<p>it yields an UnboundLocalError, but</p>
<pre><code>i = 0
def truc():
print (i)
#if (False): i = 0
truc()
</code></pre>
<p>doesn't.</p>
<p>Is that a wanted behaviour ?</p>
... | 0 | 2016-10-17T09:20:06Z | 40,082,747 | <p>just add</p>
<pre><code>global i
</code></pre>
<p>at the beginning of the method <code>truc()</code> to declare that <code>i</code> is global variable</p>
<pre><code>def truc():
global i
if (False):
i = 0
</code></pre>
<p>Take a look at this <a href="https://docs.python.org/3/faq/programming.html... | 0 | 2016-10-17T09:25:48Z | [
"python"
] |
Weird namespace behaviour | 40,082,617 | <p>When trying to run the following code:</p>
<pre><code>i = 0
def truc():
print (i)
if (False): i = 0
truc()
</code></pre>
<p>it yields an UnboundLocalError, but</p>
<pre><code>i = 0
def truc():
print (i)
#if (False): i = 0
truc()
</code></pre>
<p>doesn't.</p>
<p>Is that a wanted behaviour ?</p>
... | 0 | 2016-10-17T09:20:06Z | 40,083,039 | <p>You'll have to add <code>global i</code> to the function.</p>
<pre><code>i = 0
def truc():
global i
if (False):
i = 0
</code></pre>
<p>Other ways to handle this problem is:</p>
<p>Making <code>i</code> capitalized you'll be able to access it without the <code>global</code> however <code>i</... | -1 | 2016-10-17T09:40:57Z | [
"python"
] |
PDB BioPython- extracting the coordinates | 40,082,685 | <p>I am new to Python, is there any function in BioPython to calculate the vector of an atom given a PDB file, passing the coordinates as its input?</p>
<p>[OR]</p>
<p>Is there a BioPython function to extract the coordinates separately from a PDB file?</p>
| 0 | 2016-10-17T09:23:18Z | 40,095,551 | <p>There's such method for atoms and surpringsingly it's called <a href="http://biopython.org/DIST/docs/api/Bio.PDB.Atom.Atom-class.html#get_vector" rel="nofollow">get_vector()</a>.</p>
<pre><code>from Bio.PDB import PDBParser
p = PDBParser()
s = p.get_structure("4K5Y", "4K5Y.pdb")
for chains in... | 0 | 2016-10-17T20:59:17Z | [
"python",
"biopython"
] |
Installing python software in virtual environment gives 'Permission denied' error | 40,082,688 | <p>I am trying to install a piece of python software on our server(<a href="http://integronfinder.readthedocs.io/en/v1.5/" rel="nofollow">http://integronfinder.readthedocs.io/en/v1.5/</a>). However, I am not the server administrator and cannot run the command under <code>sudo</code>, as I get a 'permission denied' erro... | 0 | 2016-10-17T09:23:26Z | 40,082,894 | <p>It isn't that much you can do than to try to get sudo permission in some way or another.</p>
| 0 | 2016-10-17T09:33:06Z | [
"python",
"install",
"virtualenv",
"permission-denied"
] |
Complex pivoting in pandas | 40,082,726 | <p>I have a dataframe like:</p>
<pre><code> In [4]: df
Out[4]:
A B C D E F G
0 apple orange 10 20 cat rat 10
1 apple orange 10 20 cat rat 20
2 grapes banana 22 34 dog frog 34
3 grapes banana 22 34 dog frog 40
4 grapes banana 22 34 dog ... | 1 | 2016-10-17T09:24:54Z | 40,082,961 | <p>Here's one way</p>
<pre><code>In [237]: dff = (df.groupby(['A','B','C','D','E','F'])['G'].unique()
.....: .apply(pd.Series, 1).fillna(0))
In [238]: dff.columns = ['G_%s' % (x+1) for x in dff.columns]
In [239]: dff
Out[239]:
G_1 G_2 G_3
A B C D E ... | 2 | 2016-10-17T09:36:32Z | [
"python",
"pandas",
"numpy"
] |
Python - Write to csv from a particular column number | 40,082,743 | <p>I have a csv file Temp.csv that I am copying over to another csv file Final.csv using the following piece of code.</p>
<pre><code>dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'Final.csv')
tempfile = os.path.join(dirname, 'Temp.csv')
with open(csvfilename, 'wb') as output_... | 1 | 2016-10-17T09:25:39Z | 40,082,868 | <p>You can try :</p>
<pre><code>with open(tempfile, 'r') as data_file:
for line in data_file:
line = line.replace('\n', '')
row = line.split(",")
csvfilename.writerow([row[0]+","+row[3]])
</code></pre>
| 0 | 2016-10-17T09:31:42Z | [
"python",
"csv"
] |
Python - Write to csv from a particular column number | 40,082,743 | <p>I have a csv file Temp.csv that I am copying over to another csv file Final.csv using the following piece of code.</p>
<pre><code>dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'Final.csv')
tempfile = os.path.join(dirname, 'Temp.csv')
with open(csvfilename, 'wb') as output_... | 1 | 2016-10-17T09:25:39Z | 40,083,024 | <p><strong>EDIT</strong> Answering comment. You just need to prepend 3 empty strings to your <code>row</code></p>
<pre><code>dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'Final.csv')
tempfile = os.path.join(dirname, 'Temp.csv')
with open(csvfilename, 'wb') as output_file:
... | 1 | 2016-10-17T09:39:58Z | [
"python",
"csv"
] |
slicing series of panels | 40,082,844 | <p>I have a simple dataframe:</p>
<pre><code>>>> df = pd.DataFrame(np.random.randint(0,5,(20, 2)), columns=['col1','col2'])
>>> df['ind1'] = list('AAAAAABBBBCCCCCCCCCC')
>>> df.set_index(['ind1'], inplace=True)
>>> df
col1 col2
ind1
A 0 4
A 1 ... | 3 | 2016-10-17T09:30:24Z | 40,090,424 | <p>Your problem is that <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.window.Rolling.corr.html" rel="nofollow"><code>.corr()</code></a> is being called without specifying the <code>other</code> argument. Even though your dataframe only has two columns, Pandas doesn't know which correlation... | 2 | 2016-10-17T15:35:29Z | [
"python",
"pandas",
"slice"
] |
Error when using sympy's solver on polynomials with complex coefficients (4th deg) | 40,082,924 | <p>Trying to solve a 4th degree polynomial equation with sympy, I arrived at some difficulties. My code and the equation i'm trying to solve:</p>
<pre><code>import sympy as sym
from sympy import I
sym.init_printing()
k = sym.Symbol('k')
t, sigma ,k0, L , V = sym.symbols('t, sigma, k0, L,V')
x4 = ( -t**2 + 2*I * t / ... | 1 | 2016-10-17T09:34:39Z | 40,142,028 | <p>Looks like you can work around the issue by using <code>solve(expr2, k, rational=False)</code>. </p>
| 2 | 2016-10-19T21:45:10Z | [
"python",
"sympy",
"solver"
] |
MySQL python: Cursor returns the variable name | 40,082,968 | <p>I saw before if someone ask the same but i didn't see a similar question. </p>
<pre><code>def get_session(Var = '', Key=''):
conn = connection()
cursor = conn.cursor()
print "Var: "+Var
cursor.execute("Select %(var)s FROM users WHERE sessions = %(key)s",{'var':Var,'key':Key})
if(cursor.rowcount ... | 0 | 2016-10-17T09:36:49Z | 40,083,105 | <p>You can try:</p>
<pre><code>cursor.execute("Select %s FROM users WHERE sessions = '%s'" %("Name","asdf123"))
</code></pre>
<p>So query becomes : </p>
<pre><code>Select Name FROM users WHERE sessions = 'asdf123'
</code></pre>
<p>You can use variables as well
Eg:</p>
<pre><code>name_of_col = "Name"
session_name =... | 0 | 2016-10-17T09:45:00Z | [
"python",
"mysql",
"string",
"cursor"
] |
MySQL python: Cursor returns the variable name | 40,082,968 | <p>I saw before if someone ask the same but i didn't see a similar question. </p>
<pre><code>def get_session(Var = '', Key=''):
conn = connection()
cursor = conn.cursor()
print "Var: "+Var
cursor.execute("Select %(var)s FROM users WHERE sessions = %(key)s",{'var':Var,'key':Key})
if(cursor.rowcount ... | 0 | 2016-10-17T09:36:49Z | 40,083,190 | <p>The problem was the quotes that sql put in automatically</p>
<pre><code>def get_session(Var = '', Key=''):
conn = connection()
cursor = conn.cursor()
sql = "Select "+ Var+" FROM users WHERE sessions = %(key)s"
print "Var: "+Var
cursor.execute(sql,{'key':Key})
print str(cursor.rowcount)
i... | 0 | 2016-10-17T09:48:20Z | [
"python",
"mysql",
"string",
"cursor"
] |
Nesting a string inside a list n times ie list of a list of a list | 40,083,007 | <pre><code>def nest(x, n):
a = []
for i in range(n):
a.append([x])
return a
print nest("hello", 5)
</code></pre>
<p>This gives an output</p>
<pre><code>[['hello'], ['hello'], ['hello'], ['hello'], ['hello']]
</code></pre>
<p>The desired output is </p>
<pre><code>[[[[["hello"]]]]]
</code></pre>
| 4 | 2016-10-17T09:39:05Z | 40,083,051 | <p>instead of appending you sould wrap <code>x</code> and call recursively the method till call number is lesser than <code>n</code></p>
<pre><code>def nest(x, n):
if n <= 0:
return x
else:
return [nest(x, n-1)]
</code></pre>
| 2 | 2016-10-17T09:41:54Z | [
"python",
"list",
"python-2.7",
"nested"
] |
Nesting a string inside a list n times ie list of a list of a list | 40,083,007 | <pre><code>def nest(x, n):
a = []
for i in range(n):
a.append([x])
return a
print nest("hello", 5)
</code></pre>
<p>This gives an output</p>
<pre><code>[['hello'], ['hello'], ['hello'], ['hello'], ['hello']]
</code></pre>
<p>The desired output is </p>
<pre><code>[[[[["hello"]]]]]
</code></pre>
| 4 | 2016-10-17T09:39:05Z | 40,083,055 | <p>Every turn through the loop you are adding to the list. You want to be further nesting the list, not adding more stuff onto it. You could do it something like this:</p>
<pre><code>def nest(x, n):
for _ in range(n):
x = [x]
return x
</code></pre>
<p>Each turn through the loop, <code>x</code> has ano... | 5 | 2016-10-17T09:42:23Z | [
"python",
"list",
"python-2.7",
"nested"
] |
Nesting a string inside a list n times ie list of a list of a list | 40,083,007 | <pre><code>def nest(x, n):
a = []
for i in range(n):
a.append([x])
return a
print nest("hello", 5)
</code></pre>
<p>This gives an output</p>
<pre><code>[['hello'], ['hello'], ['hello'], ['hello'], ['hello']]
</code></pre>
<p>The desired output is </p>
<pre><code>[[[[["hello"]]]]]
</code></pre>
| 4 | 2016-10-17T09:39:05Z | 40,083,670 | <p>Here is a pythonic recursion approach:</p>
<pre><code>In [8]: def nest(x, n):
...: return nest([x], n-1) if n else x
</code></pre>
<p>DEMO:</p>
<pre><code>In [9]: nest(3, 4)
Out[9]: [[[[3]]]]
In [11]: nest("Stackoverflow", 7)
Out[11]: [[[[[[['Stackoverflow']]]]]]]
</code></pre>
| 1 | 2016-10-17T10:11:54Z | [
"python",
"list",
"python-2.7",
"nested"
] |
Adding a table after a Python matplotlib basemap | 40,083,108 | <p>I am creating a map using matplotlib basemap and I want to add a table underneath it (say 4 colums, 4 rows) with text in the cells (the text and table is not linked in any way to the basemap). I have not been able to do so with subplots. This is saved as a 1 page pdf. Any suggestions?</p>
<pre><code>from mpl_toolki... | 0 | 2016-10-17T09:45:08Z | 40,117,650 | <p>Create two subplots and add a table to the second axe object? See the documentation for <code>Axes.table()</code></p>
<p><a href="http://matplotlib.org/api/axes_api.html?highlight=table#matplotlib.axes.Axes.table" rel="nofollow">http://matplotlib.org/api/axes_api.html?highlight=table#matplotlib.axes.Axes.table</a><... | 0 | 2016-10-18T20:38:19Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] |
Consecutive elements in a Sparse matrix row | 40,083,118 | <p>I am working on a sparse matrix stored in COO format. What would be the fastest way to get the number of consecutive elements per each row.</p>
<p>For example consider the following matrix:</p>
<pre><code>a = [[0,1,2,0],[1,0,0,2],[0,0,0,0],[1,0,1,0]]
</code></pre>
<p>Its COO representation would be </p>
<pre><co... | 0 | 2016-10-17T09:45:26Z | 40,091,662 | <p>Convert it to a dense array, and apply your logic row by row.</p>
<ul>
<li>you want the number of groups per row</li>
<li>zeros count when defining groups</li>
<li>row iteration is faster with arrays</li>
</ul>
<p>In <code>coo</code> format your matrix looks like:</p>
<pre><code>In [623]: M=sparse.coo_matrix(a)
I... | 1 | 2016-10-17T16:47:07Z | [
"python",
"python-2.7",
"matrix",
"scipy",
"sparse-matrix"
] |
Where is the image being uploaded? | 40,083,181 | <p>I have created a custom User model in django:</p>
<pre><code>class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), max_length=254, unique=True)
first_name = models.CharField(_('first name'), max_length=30)
image = models.ImageField(_('profile image'), upload... | -1 | 2016-10-17T09:48:00Z | 40,083,377 | <p>You're correct that user uploaded files should be stored in MEDIA_ROOT.</p>
<p>You can check this location by firing up the Django shell and checking on setting:</p>
<pre><code>$ python manage.py shell
>>> from django.conf import settings
>>> settings.MEDIA_ROOT
<< snip: the media root loca... | 0 | 2016-10-17T09:56:32Z | [
"python",
"django",
"image",
"django-rest-framework"
] |
Where is the image being uploaded? | 40,083,181 | <p>I have created a custom User model in django:</p>
<pre><code>class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), max_length=254, unique=True)
first_name = models.CharField(_('first name'), max_length=30)
image = models.ImageField(_('profile image'), upload... | -1 | 2016-10-17T09:48:00Z | 40,084,118 | <p>If what you want is just to know your folder's location, you can run the following command (In linux-based systems):</p>
<pre><code>sudo find / -name userimages
</code></pre>
| 1 | 2016-10-17T10:34:03Z | [
"python",
"django",
"image",
"django-rest-framework"
] |
Replace comma with dot Pandas | 40,083,266 | <p>Given the following array, I want to replace commas with dots:</p>
<pre><code>array(['0,140711', '0,140711', '0,0999', '0,0999', '0,001', '0,001',
'0,140711', '0,140711', '0,140711', '0,140711', '0,140711',
'0,140711', 0L, 0L, 0L, 0L, '0,140711', '0,140711', '0,140711',
'0,140711', '0,140711', ... | 1 | 2016-10-17T09:51:27Z | 40,083,822 | <p>You need to assign the result of your operate back as the operation isn't inplace, besides you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.s... | 1 | 2016-10-17T10:19:55Z | [
"python",
"pandas"
] |
python. How to redirect Maya history? | 40,083,308 | <p>All Maya script logs and errors printed in history tab. This is output from all commands and python scripts.</p>
<p>For better debugging scripts I want all the logs were sent somewhere on the server. How to intercept and send the output to your script. Then I will do all that is necessary, and the output is either ... | 0 | 2016-10-17T09:53:13Z | 40,083,783 | <p>its sounds like that you need a real-time error tracker like <a href="https://sentry.io/welcome/" rel="nofollow">Sentry</a>
, in Sentry are logging modules that are maked exactly for this reason, communicate Server/Client <a href="https://docs.sentry.io/clients/python/integrations/logging/" rel="nofollow">logging</a... | 3 | 2016-10-17T10:17:55Z | [
"python",
"debugging",
"logging",
"output",
"maya"
] |
python. How to redirect Maya history? | 40,083,308 | <p>All Maya script logs and errors printed in history tab. This is output from all commands and python scripts.</p>
<p>For better debugging scripts I want all the logs were sent somewhere on the server. How to intercept and send the output to your script. Then I will do all that is necessary, and the output is either ... | 0 | 2016-10-17T09:53:13Z | 40,092,916 | <p>You can also redirect Script Editor history using Maya's <code>scriptEditorInfo</code> command found <a href="http://help.autodesk.com/cloudhelp/2017/ENU/Maya-Tech-Docs/CommandsPython/scriptEditorInfo.html" rel="nofollow">here</a>:</p>
<p>An example usage of this would be something like:</p>
<pre><code>import maya... | 2 | 2016-10-17T18:06:17Z | [
"python",
"debugging",
"logging",
"output",
"maya"
] |
How exactly is SELECT blah, blah FROM table stored in a python file | 40,083,401 | <pre><code>query_string = 'SELECT item_id, item_name, description, item_price FROM valve_list'
</code></pre>
<p>* valve_list is a database table.</p>
<p>The code above is in a python file, how exactly does it stores the data? is it a list containing a list for each item in my database table? like this?</p>
<pre><cod... | -2 | 2016-10-17T09:57:46Z | 40,083,601 | <p>At the moment "query_string" is just a var. You typically need to pass the string to an object which has a connection to a database and executes on the database, typically a cursor. The cursor fetches a result set which can be iterated over to produce the database output.</p>
| 0 | 2016-10-17T10:09:02Z | [
"python",
"mysql",
"sqlite",
"sqlite3"
] |
Accessing to a dict on a json in python | 40,083,438 | <p>I am trying to assign a value of a dict copied in JSON to a variable in my code.
This is the dictionary copied on the .json:</p>
<pre><code>"Monetarios": [{"MIFID_NO_CURR_RISK":"B1"},{"MIFID_CURR_RISK":"B2"}],
"Monetario Dinamico": [{"MIFID_NO_CURR_RISK":"B1"},{"MIFID_CURR_RISK":"B2"}],
"Renta... | -1 | 2016-10-17T09:59:56Z | 40,083,473 | <pre><code>carga_dict['Renta Fija Corto Plazo'][0]['MIFID_NO_CURR_RISK']
</code></pre>
<p><code>carga_dict['Renta Fija Corto Plazo']</code> is a list of dictionary. so you have to first select the list element and find the appropriate key.</p>
| 0 | 2016-10-17T10:01:21Z | [
"python",
"json",
"dictionary"
] |
Mocking an object retaining its functionality in Python | 40,083,528 | <p>I'm testing the behavior of an object. In the sample code below, I check if the method <code>bar2</code> is called.</p>
<p>The debug print shows that yes, <code>bar2</code> is called. Unfortunately, the <code>mock</code>-library doesn't track this call.</p>
<p>What should I do to make <code>mock</code> to notice s... | 0 | 2016-10-17T10:04:47Z | 40,083,608 | <p>You don't. You mocked out <code>Foo()</code>, so the implementation is gone; the whole point of mocking is to replace the class. </p>
<p>If you are testing <code>Foo</code> itself, don't mock the class. You can mock individual methods instead:</p>
<pre><code>with mock.patch('__main__.Foo.bar2') as bar2_mock:
f... | 4 | 2016-10-17T10:09:29Z | [
"python",
"mocking"
] |
why python not crash in this case? | 40,083,647 | <p>For the example in this page:
<a href="https://wiki.python.org/moin/CrashingPython#Exhausting_Resources" rel="nofollow">https://wiki.python.org/moin/CrashingPython#Exhausting_Resources</a>
Why the case can't be reproduced in my python 2.7
Why it can make python crash?</p>
<pre><code>$ python
Python 2.4.2 (#2, Sep ... | -7 | 2016-10-17T10:10:55Z | 40,083,776 | <p>This was simply a bug, see <a href="http://bugs.python.org/issue532646" rel="nofollow">issue #532646</a>.</p>
<p>All software has bugs, and the Python project is no exception. It can't be reproduced in 2.7 because the bug was found and fixed.</p>
<p>Specifically, the page you found documents various such crashing ... | 0 | 2016-10-17T10:17:41Z | [
"python"
] |
I want to crawl data from 1 to 10 pages automatically from website.How can i do it? | 40,083,648 | <pre><code>import requests
from bs4 import BeautifulSoup
My_Url = "http://questions.consumercomplaints.in/page/2"
Data = requests.get(My_Url)
Soup = BeautifulSoup(Data.content)
head_id = Soup.find_all({"div":"href"})
len(head_id)
for i in head_id:
print i.text
</code></pre>
<p>From above code i scrapped (reviews/... | -1 | 2016-10-17T10:10:58Z | 40,083,706 | <p>Why not surround your function in a ranged for loop?</p>
<pre><code>import requests
from bs4 import BeautifulSoup
for i in range(3,11):
My_Url = "http://questions.consumercomplaints.in/page/" + str(i)
Data = requests.get(My_Url)
Soup = BeautifulSoup(Data.content)
head_id = Soup.find_all({"div":"href... | 0 | 2016-10-17T10:13:39Z | [
"python",
"python-2.7",
"web-scraping",
"web-crawler",
"ipython"
] |
Alternative to deepcopy a lit of BitVectors in python | 40,083,846 | <p>In my project, I am using <code>deepcopy()</code> function to create a deep copy a list of <code>BitVector</code>s. Unfortunately, its taking a lot of time. </p>
<pre><code>a = [<BitVector obj at 0x000...>, <BitVector obj at 0x000...>, <BitVector obj at 0x000...> ...]
</code></pre>
<p>On changing... | 0 | 2016-10-17T10:21:11Z | 40,086,450 | <p>The <code>BitVector</code> implementation is pure python and copying could be optimised substantially. Further, the provided implementation of <code>BitVector.deep_copy</code> is substantially slower than <code>copy.deepcopy</code>. Here is a an implementation of a deep copy that is ~10 times faster on my machine.</... | 1 | 2016-10-17T12:30:47Z | [
"python",
"python-3.x",
"deep-copy"
] |
tornado.locks.Lock release | 40,083,970 | <p>The tornado example gives the following example for locks:</p>
<pre><code>>>> from tornado import gen, locks
>>> lock = locks.Lock()
>>>
>>> @gen.coroutine
... def f():
... with (yield lock.acquire()):
... # Do something holding the lock.
... pass
...
... # No... | 0 | 2016-10-17T10:27:45Z | 40,085,656 | <p>Right, the <code>with</code> statement ensures the Lock is released, no need to call <code>release</code> yourself.</p>
<p><code>release</code> is naturally non-blocking -- your coroutine can complete a call to <code>release</code> without waiting for any other coroutines -- therefore <code>release</code> does not ... | 1 | 2016-10-17T11:50:22Z | [
"python",
"tornado"
] |
Remove duplicates from a list of list based on a subset of each list | 40,084,023 | <p>I wrote a function to remove "duplicates" from a list of list.</p>
<p>The elements of my list are: </p>
<pre><code>[ip, email, phone number].
</code></pre>
<p>I would like to remove the sublists that got the same EMAIL and PHONE NUMBER, I don't really care about the IP address.</p>
<p>The solution that I current... | 1 | 2016-10-17T10:29:59Z | 40,084,082 | <p>Your approach does a full scan for each and every element in the list, making it take O(N**2) (quadratic) time. The <code>list.pop(index)</code> is also expensive as everything following <code>index</code> is moved up, making your solution approach O(N**3) cubic time.</p>
<p>Use a set and add <code>(email, phonenum... | 4 | 2016-10-17T10:32:37Z | [
"python",
"performance",
"list",
"python-3.x"
] |
Remove duplicates from a list of list based on a subset of each list | 40,084,023 | <p>I wrote a function to remove "duplicates" from a list of list.</p>
<p>The elements of my list are: </p>
<pre><code>[ip, email, phone number].
</code></pre>
<p>I would like to remove the sublists that got the same EMAIL and PHONE NUMBER, I don't really care about the IP address.</p>
<p>The solution that I current... | 1 | 2016-10-17T10:29:59Z | 40,084,874 | <p>Another solution might be to use groupby.</p>
<pre><code>from itertools import groupby
from operator import itemgetter
deduped = []
data.sort(key=itemgetter(1,2))
for k, v in groupby(data, key=itemgetter(1,2):
deduped.append(list(v)[0])
</code></pre>
<p>or using a list comprehension:</p>
<pre><code>deduped ... | 0 | 2016-10-17T11:09:23Z | [
"python",
"performance",
"list",
"python-3.x"
] |
Remove duplicates from a list of list based on a subset of each list | 40,084,023 | <p>I wrote a function to remove "duplicates" from a list of list.</p>
<p>The elements of my list are: </p>
<pre><code>[ip, email, phone number].
</code></pre>
<p>I would like to remove the sublists that got the same EMAIL and PHONE NUMBER, I don't really care about the IP address.</p>
<p>The solution that I current... | 1 | 2016-10-17T10:29:59Z | 40,085,224 | <p>Another approach could be to use a <code>Counter</code></p>
<pre><code>from collections import Counter
data = [(1, "a@b.com", 1234), (1, "a@b.com", 1234), (2, "a@b.com", 1234)]
counts = Counter([i[:2] for i in data])
print [i for i in data if counts[i[:2]] == 1] # Get unique
</code></pre>
| 0 | 2016-10-17T11:28:55Z | [
"python",
"performance",
"list",
"python-3.x"
] |
Background color of disabled Spinner | 40,084,041 | <p>I'm trying to set the background color of the Spinner, if disabled.</p>
<p>Here is what I tried in my kv-file:</p>
<pre><code><MySpinner@Spinner>:
background_normal: ''
background_disabled_normal: ''
disabled_color: (0, 0, 0, 1)
color: (0, 0, 0, 1)
background_disabled_color: (1,1,1,1)
... | 1 | 2016-10-17T10:30:44Z | 40,089,959 | <p>It inherits from <code>Button</code>, therefore if it's not in the <code>spinner.py</code> file, it'll be in <a href="https://github.com/kivy/kivy/blob/master/kivy/uix/button.py#L90" rel="nofollow"><code>button.py</code></a></p>
<p>You can see that <code>Button</code> uses images for the background and with <code>b... | 1 | 2016-10-17T15:11:58Z | [
"python",
"kivy"
] |
Iterating over an image in python | 40,084,246 | <p>I would like to iterate over an image in python.
This is my code so far:</p>
<pre><code>def imageIteration(greyValueImage):
for (x,y), pixel in np.ndenumerate(greyValueImage):
vals = greyValueImage[x, y]
print(vals)
</code></pre>
<p>The problem here ist that I get the following exception:</p>
... | 0 | 2016-10-17T10:39:26Z | 40,084,317 | <p>You can't unpack like that. Just do</p>
<pre><code>def imageIteration(greyValueImage):
for index, pixel in np.ndenumerate(greyValueImage):
x, y, _ = index
vals = greyValueImage[x, y]
print(vals)
</code></pre>
<p>Because <code>ndenumerate</code> returns 2 values list of 2, and number.
<a... | 1 | 2016-10-17T10:43:20Z | [
"python",
"image",
"loops",
"for-loop",
"iteration"
] |
Iterating over an image in python | 40,084,246 | <p>I would like to iterate over an image in python.
This is my code so far:</p>
<pre><code>def imageIteration(greyValueImage):
for (x,y), pixel in np.ndenumerate(greyValueImage):
vals = greyValueImage[x, y]
print(vals)
</code></pre>
<p>The problem here ist that I get the following exception:</p>
... | 0 | 2016-10-17T10:39:26Z | 40,084,406 | <p>What is the value of greyValueImage?</p>
<p>There should be nothing wrong with your code, you can of course unpack the values of a tuple in a for loop.</p>
| 0 | 2016-10-17T10:48:03Z | [
"python",
"image",
"loops",
"for-loop",
"iteration"
] |
Iterating over an image in python | 40,084,246 | <p>I would like to iterate over an image in python.
This is my code so far:</p>
<pre><code>def imageIteration(greyValueImage):
for (x,y), pixel in np.ndenumerate(greyValueImage):
vals = greyValueImage[x, y]
print(vals)
</code></pre>
<p>The problem here ist that I get the following exception:</p>
... | 0 | 2016-10-17T10:39:26Z | 40,085,250 | <p>You can of course just use a for loop to iterate over each pixel. An example is shown below:</p>
<pre><code># assuming greyValueImage is a numpy array
rows, cols = greyValueImage.shape() # get the shape of the array
for x in range (cols):
for y in range (rows):
vals = greyValueImage[x,y]
print ... | 0 | 2016-10-17T11:30:44Z | [
"python",
"image",
"loops",
"for-loop",
"iteration"
] |
python: importing libpci raises SyntaxError | 40,084,353 | <p>I just installed libpci on my machine: </p>
<pre><code>$ pip2.7 install libpci
</code></pre>
<p>And tried to run this: </p>
<pre><code>#!/usr/local/bin/python2.7
import libpci
print('hello libpci')
</code></pre>
<p>but this raises the following syntax error:</p>
<pre><code>Traceback (most recent call last):
... | 1 | 2016-10-17T10:45:23Z | 40,084,421 | <p>The <a href="https://pypi.python.org/pypi/libpci" rel="nofollow"><code>libpci</code> project</a> requires Python 3.4 or newer. From the project tags:</p>
<blockquote>
<pre><code>Categories
[...]
Programming Language :: Python :: 3
Programming Language :: Python :: 3.4
</code></pre>
</blockquote>
<p>The syntax erro... | 3 | 2016-10-17T10:48:34Z | [
"python",
"python-2.7"
] |
Strange behavior of urllib.request in two different cases while webscrapping | 40,084,385 | <p>I am trying to download bhavcopy of NSE EoD data for last 15 years using web scrapping through urllib.request.</p>
<p>I am seeing that urllib.request is behaving strangely, it is working in one case but in another case it is throwing me error 403 Access Denies ..</p>
<p>I used the HTTP Headers for masking but in o... | 0 | 2016-10-17T10:47:07Z | 40,092,289 | <p>Pass a <em>user-agent</em> , <code>'Accept': '*/*'</code> and the <em>referer</em> headers:</p>
<pre><code>url = "https://www.nseindia.com/content/historical/EQUITIES/2001/JAN/cm01JAN2001bhav.csv.zip"
r = request.Request(url, headers={'User-Agent': 'mybot', 'Accept': '*/*',
"Refere... | 0 | 2016-10-17T17:26:21Z | [
"python",
"url",
"web-scraping",
"urllib",
"http-status-code-403"
] |
pyexcel export error "No content, file name. Nothing is given" | 40,084,424 | <p>I'm using <code>django-pyexcel</code> to export data from the website, but when I go to the export URL I get the error:</p>
<blockquote>
<p>Exception Type: IOError</p>
<p>Exception Value: No content, file name. Nothing is given</p>
</blockquote>
<p>The code to export the data was copied from the <a href="ht... | 0 | 2016-10-17T10:48:39Z | 40,084,501 | <p>The problem turned out to be the file format used, <code>xls</code> in this case.</p>
<p>I had only installed the <code>xlsx</code> (<code>pyexcel-xlsx</code>) processor so it did not know how to handle the <code>xls</code> file format.</p>
<p>The exception message could have been a bit better as I spent ages tryi... | 0 | 2016-10-17T10:51:31Z | [
"python",
"django",
"pyexcel",
"django-excel"
] |
Reuse lexer object in antlr4 python target | 40,084,581 | <p>I have a simple antlr4 lexer, the following script works,</p>
<pre><code> lexer = MyLexer(InputStream(argv[1]))
stream = CommonTokenStream(lexer)
parser = MyParser(stream)
tree = parser.query()
v = MyVisitor()
v.visit(tree)
</code></pre>
<p>But I'm wondering if I can reuse the <code>MyLe... | 0 | 2016-10-17T10:55:53Z | 40,101,520 | <p>It's possible by setting an input stream in the lexer (could even be the same as before) via <code>lexer.setInputStream()</code>. Then also re-set the lexer in the parser (can also be the same) via <code>parser.setTokenSource()</code>. Finally call <code>stream.reset()</code> and <code>parser.reset()</code> if you r... | 0 | 2016-10-18T06:56:37Z | [
"python",
"antlr",
"antlr4"
] |
AttributeError: module 'ctypes.wintypes' has no attribute 'create_unicode_buffer' | 40,084,734 | <p>This is a part of my code:</p>
<pre><code>import os
def _get_appdata_path():
import ctypes
from ctypes import wintypes, windll
CSIDL_APPDATA = 26
_SHGetFolderPath = windll.shell32.SHGetFolderPathW
_SHGetFolderPath.argtypes = [wintypes.HWND,
ctypes.c_int,
... | 0 | 2016-10-17T11:03:20Z | 40,085,812 | <p>Use ctypes.create_unicode_buffer, which works in both PY2 and PY3. It was only accidentally in wintypes in PY2 due to its use of <code>from ctypes import *</code>. :D</p>
| 2 | 2016-10-17T11:58:40Z | [
"python",
"compiler-errors",
"ctypes",
"python-3.5"
] |
Download csv file from https tableau server with python using request and basic authentication | 40,084,814 | <p>I have a tableau 10.0 server. I have a view at <code>https://example.com/views/SomeReport/Totals</code>. In a browser, if I navigate to <code>https://example.com/views/SomeReport/Totals.csv</code> I am prompted to login and then the view is downloaded as a csv file. </p>
<p>Im trying to download this same file usi... | 0 | 2016-10-17T11:07:29Z | 40,085,848 | <p>I'm gonna go out on a limb here and say that Tableau is not doing HTTP basic authentication, but rather have their own method. So when you try to access the thing through requests, it rejects it because it doesn't know how to auth like that.</p>
<p>When you access it as a human, it knows to redirect you to their lo... | 1 | 2016-10-17T12:00:18Z | [
"python",
"python-requests",
"basic-authentication",
"tableau-server"
] |
Python RegEx in-text slash escape | 40,084,822 | <p>I apologize for the incoherent title, but it's hard to come up with one in this situation.</p>
<p>I have a bunch of texts and (almost) always they start either like this:</p>
<pre><code>Word (Foo) - Main Text
</code></pre>
<p>or this:</p>
<pre><code>Word (Foo/Bar) - Main Text
</code></pre>
<p>I want to remove e... | 0 | 2016-10-17T11:07:36Z | 40,084,955 | <p>Do:</p>
<pre><code>^[^-]*-\s*(.*)
</code></pre>
<p>Now only captured group is your desired portion.</p>
<ul>
<li><p><code>^[^-]*</code> matches substring upto first <code>-</code></p></li>
<li><p><code>-</code> matches a literal <code>-</code>, <code>\s*</code> matches zero or more whitespace</p></li>
<li><p>The ... | 2 | 2016-10-17T11:14:10Z | [
"python",
"regex"
] |
(Python) Using modulo to get the remainder from changing secs, to hrs and minutes | 40,084,887 | <p>I'm currently new to learning python and stumbled upon this problem: </p>
<blockquote>
<p>Exercise 2-7 Get the Time
Write an algorithm that reads the amount of time in seconds and then displays the equivalent
hours, minutes and remaining seconds.
⢠One hour corresponds to 60 minutes.
⢠One minute corr... | 0 | 2016-10-17T11:10:19Z | 40,085,098 | <p>This is just "out of my head", because I got no testing system I could use right now.</p>
<pre><code>def amount_time(t):
print("Number of Seconds:", t % 60)
print("Number of Minutes:", (t // 60) % 60)
print("Number of Hours:", (t // 3600))
</code></pre>
<p>What "t % 60" does: </p>
<ol>
<li>take t, div... | 0 | 2016-10-17T11:22:41Z | [
"python",
"modulo"
] |
(Python) Using modulo to get the remainder from changing secs, to hrs and minutes | 40,084,887 | <p>I'm currently new to learning python and stumbled upon this problem: </p>
<blockquote>
<p>Exercise 2-7 Get the Time
Write an algorithm that reads the amount of time in seconds and then displays the equivalent
hours, minutes and remaining seconds.
⢠One hour corresponds to 60 minutes.
⢠One minute corr... | 0 | 2016-10-17T11:10:19Z | 40,085,115 | <p>Your calculation of minuts doesnt work correct, you use Modulo with the hours.
You could do the same with minutes as you did wirh seconds instead:</p>
<pre><code>m = (t - h * 3600) // 60
s = int (t - h*3600 - m*60)
ms = int ((t - h*3600 - m*60 - s) * 1000) # milliseconds
</code></pre>
<p>and to build the resul... | 0 | 2016-10-17T11:23:22Z | [
"python",
"modulo"
] |
How do I properly plot data extracted from a scope as .csv file | 40,084,895 | <p>I just extracted a .csv file from a scope, which shows how a signal changes in the time duration of 6 seconds. Problem is that I can't come up with a proper way of plotting this signal, without things getting mushed together.</p>
<p>Mushed together like this:</p>
<p><a href="https://i.stack.imgur.com/XYYa9.png" re... | 2 | 2016-10-17T11:10:48Z | 40,085,620 | <p>I don't know if this was intended, but the output of your signal simply oscillates between 0 and 1. I tried</p>
<pre><code>import numpy as np
a = np.genfromtxt('test.csv', delimiter=',') #Using numpy to directly read csv file into numpy array. Also, I renamed the csv file to test.csv
a=a[1:] #To remove the he... | 0 | 2016-10-17T11:48:22Z | [
"python",
"matlab",
"csv",
"plot",
"gnuplot"
] |
How do I properly plot data extracted from a scope as .csv file | 40,084,895 | <p>I just extracted a .csv file from a scope, which shows how a signal changes in the time duration of 6 seconds. Problem is that I can't come up with a proper way of plotting this signal, without things getting mushed together.</p>
<p>Mushed together like this:</p>
<p><a href="https://i.stack.imgur.com/XYYa9.png" re... | 2 | 2016-10-17T11:10:48Z | 40,086,324 | <p>As a rudimentary analysis, you could do the following using a <code>deque</code> to process a sliding window of values:</p>
<pre><code>from collections import deque
import csv
import matplotlib
import matplotlib.pyplot as plt
maxlen = 20
window = deque(maxlen=maxlen)
with open('12a6-data_extracted_2.csv') as f_i... | 2 | 2016-10-17T12:24:25Z | [
"python",
"matlab",
"csv",
"plot",
"gnuplot"
] |
How do I properly plot data extracted from a scope as .csv file | 40,084,895 | <p>I just extracted a .csv file from a scope, which shows how a signal changes in the time duration of 6 seconds. Problem is that I can't come up with a proper way of plotting this signal, without things getting mushed together.</p>
<p>Mushed together like this:</p>
<p><a href="https://i.stack.imgur.com/XYYa9.png" re... | 2 | 2016-10-17T11:10:48Z | 40,088,759 | <h2>Zoomable plot with Gnuplot</h2>
<p>Your problem is that you are plotting this with linear interpolation, with Gnuplot you plot digital data with the <code>with steps</code> style. If you use the <code>wxt</code> terminal (some other terminals also work) you get a zoomable plot, e.g.:</p>
<pre class="lang-gnuplot ... | 2 | 2016-10-17T14:14:39Z | [
"python",
"matlab",
"csv",
"plot",
"gnuplot"
] |
Taking subarrays from numpy array with given stride | 40,084,931 | <p>Lets say I have a Python Numpy array array a.</p>
<pre><code>numpy.array([1,2,3,4,5,6,7,8,9,10,11].)
</code></pre>
<p>I want to create a matrix of sub sequences from this array of length 5 with stride 3. The results matrix hence will look as follows:</p>
<pre><code>numpy.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,1... | 4 | 2016-10-17T11:12:49Z | 40,085,052 | <p><strong>Approach #1 :</strong> Using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p>
<pre><code>nrows = ((a.size-L)//S)+1
out = a[S*np.arange(nrows)[:,None] + np.arange(L)]
</code></pre>
<p><strong>Approach #2 :</strong> Using more effici... | 5 | 2016-10-17T11:20:00Z | [
"python",
"numpy",
"vectorization"
] |
How can you write a dict lookup to a csv from mysql with python | 40,085,056 | <p>I write this csv from a mysql db tabel in this way:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>with open('outfile','w') as f:
writer = csv.writer(f)
fo... | 1 | 2016-10-17T11:20:19Z | 40,086,082 | <p>Since each row is a list. You can modify it in-place, or create a new list with the value you want to replace with.
for example:</p>
<pre><code>row[0] = value
</code></pre>
<p>In your code you can do like this.</p>
<pre><code>with open('outfile','w') as f:
writer = csv.writer(f)
for row in cursor.fetchall():
... | 0 | 2016-10-17T12:12:22Z | [
"python",
"mysql"
] |
Why won't my Python script run using Docker? | 40,085,168 | <p>I need to use Tensorflow on my Windows machine. I have installed Docker, and following these two tutorials (<a href="https://runnable.com/docker/python/dockerize-your-python-application" rel="nofollow">https://runnable.com/docker/python/dockerize-your-python-application</a> and <a href="https://civisanalytics.com/bl... | -1 | 2016-10-17T11:26:26Z | 40,087,989 | <p>If you want to see inline output, try adding the <code>--tty</code> and <code>--interactive</code> (or <code>-ti</code> for short) options. This will give you the stdout from your container on the console, as well as interact via stdin with your script.</p>
<p>The other way to run is with <code>--detach</code>, wh... | 1 | 2016-10-17T13:40:02Z | [
"python",
"windows",
"docker",
"tensorflow"
] |
Why won't my Python script run using Docker? | 40,085,168 | <p>I need to use Tensorflow on my Windows machine. I have installed Docker, and following these two tutorials (<a href="https://runnable.com/docker/python/dockerize-your-python-application" rel="nofollow">https://runnable.com/docker/python/dockerize-your-python-application</a> and <a href="https://civisanalytics.com/bl... | -1 | 2016-10-17T11:26:26Z | 40,104,804 | <p>I fixed it! The problem was simply the './' in the CMD line in the Dockerfile. Removing this and building it again solved the problem.</p>
| 0 | 2016-10-18T09:42:39Z | [
"python",
"windows",
"docker",
"tensorflow"
] |
How to smooth lines in a figure in python? | 40,085,300 | <p>So with the code below I can plot a figure with 3 lines, but they are angular. Is it possible to smooth the lines? </p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
# Dataframe consist of 3 columns
df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
df['name'] = ['A', 'B', 'C',... | 0 | 2016-10-17T11:33:00Z | 40,115,645 | <p>You should apply interpolation on your data and it shouldn't be "linear". Here I applied the "cubic" interpolation using scipy's <code>interp1d</code>. Also, note that for using cubic interpolation your data should have at least 4 points. So I added another year 2031 and another value too all weights (I got the new ... | 0 | 2016-10-18T18:37:23Z | [
"python",
"pandas",
"matplotlib",
"plot",
"lines"
] |
Extract each object after edge detection using sobel filter | 40,085,314 | <p>Sobel Edge detection:<br>
<img src="https://i.stack.imgur.com/bbgpD.png" alt="Sobel Edge detection"></p>
<p>Original Image:<br>
<img src="https://i.stack.imgur.com/L8yvq.jpg" alt="Original Image"></p>
<p>I have used sobel edge detection technique to identify the boundaries of each object in the given image. How ca... | 0 | 2016-10-17T11:33:26Z | 40,087,750 | <p>What you are after is called image segmentation. Your case looks particularly difficult because of low contrast between the furniture elements, and because of texture and shadows.</p>
<p>You will also realize that you need to define what you call an "object" and you will realize that it is about impossible to isola... | 1 | 2016-10-17T13:30:10Z | [
"python",
"opencv",
"image-processing",
"image-segmentation",
"skimage"
] |
Extract each object after edge detection using sobel filter | 40,085,314 | <p>Sobel Edge detection:<br>
<img src="https://i.stack.imgur.com/bbgpD.png" alt="Sobel Edge detection"></p>
<p>Original Image:<br>
<img src="https://i.stack.imgur.com/L8yvq.jpg" alt="Original Image"></p>
<p>I have used sobel edge detection technique to identify the boundaries of each object in the given image. How ca... | 0 | 2016-10-17T11:33:26Z | 40,087,908 | <h1>What</h1>
<p>You want to use <code>cv2.findContours()</code> with <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours" rel="nofollow">hierarchy enabled</a>. Try retr_ccomp.</p>
<h1>Why</h1>
<p>That will try to find the regions... | 0 | 2016-10-17T13:36:55Z | [
"python",
"opencv",
"image-processing",
"image-segmentation",
"skimage"
] |
Size of list and string | 40,085,333 | <p>I am trying to fetch the size of list in bytes and also size of string in bytes.</p>
<p>If we see the output below for the code, size of list is shown as <code>52 bytes</code>, where as when I join the list and check the size, output is <code>35 bytes</code>. At last I tried to get size of string <code>"Iamtestings... | 0 | 2016-10-17T11:34:38Z | 40,085,512 | <ol>
<li><p>A list (any list) data structure requires additional maintenance overhead to keep elements inside it. This overhead is reflected in the difference of the results of <code>getsizeof</code>.</p></li>
<li><p>Python strings are a <a href="https://docs.python.org/2.7/library/stdtypes.html#typesseq" rel="nofollow... | 2 | 2016-10-17T11:43:10Z | [
"python",
"python-2.7"
] |
Aggregating a dataframe to give the sum of values | 40,085,339 | <p>I tried to group data based on multiple fields but the groupby is not coming in a perfect dataframe</p>
<pre><code>Comgroup Cd Geo IMT Best Remit Name Q1 Q2 Q3 Q4 Total
IT Product AP ANZ AVNET 0 0 0 823.09 823.09
IT Product AG ANZ TOSHIBA 0 0 5065.4 237060.72 242126.12
IT Product EMEA AN... | 1 | 2016-10-17T11:34:50Z | 40,087,968 | <p>Need to do total_spendfinal.reset_index(inplace=True) </p>
| 0 | 2016-10-17T13:39:22Z | [
"python",
"pandas",
"dataframe"
] |
Which scipy function should I use to interpolate from a rectangular grid to regularly spaced rectangular grid in 2D? | 40,085,367 | <p>I pretty new to python, and I'm looking for the most efficient pythonic way to interpolate from a grid to another one.
The original grid is a structured grid (the terms regular or rectangular grid are also used), and the spacing is not uniform.
The new grid is a regularly spaced grid. Both grids are 2D. For now it's... | 0 | 2016-10-17T11:36:40Z | 40,087,542 | <h1>RectBivariateSpline</h1>
<p>Imagine your grid as a canyon, where the high values are peaks and the low values are valleys. The bivariate spline is going to try to fit a thin sheet over that canyon to interpolate. This will still work on irregularly space input, as long as the x and y array you supply are also irre... | 0 | 2016-10-17T13:21:24Z | [
"python",
"numpy",
"scipy",
"grid"
] |
Find pd.DataFrame cell that has the value of None | 40,085,390 | <p>I have a <code>pd.DataFrame</code> that looks like this:</p>
<pre><code>index A B
0 apple bear
0 axis None
0 ant None
0 avocado None
</code></pre>
<p>and my goal is to simple drop those row if they have <code>None</code> in the B column.</p>
<p>I tried <code>df[df['B'] != ... | 0 | 2016-10-17T11:37:42Z | 40,085,459 | <p>You could try this:</p>
<pre><code>df.dropna(subset=["B"])
</code></pre>
| 0 | 2016-10-17T11:40:27Z | [
"python",
"pandas",
"dataframe"
] |
Accessing dictionary keys&values via list of keys and values | 40,085,536 | <p>This is going to be a very embarrassing first post from me - just coming back to coding in Python after learning basics ~6 months ago and not using it since then.</p>
<p>I am coding a Blackjack game in object oriented approach, and defined a Deck object as shown below:</p>
<pre><code>class Deck(object):
suits ... | 1 | 2016-10-17T11:44:06Z | 40,085,612 | <p>You can use <code>getattr</code> function do get attribute from object</p>
<pre><code>def initialize_deck(self):
for suit in self.suits:
suit_dict = getattr(self, suit)
for rank in self.ranks:
suit_dict[rank] = 1
</code></pre>
<p>Or you can do it using <code>setattr</code></p>
<pre... | 1 | 2016-10-17T11:48:07Z | [
"python",
"dictionary",
"iteration"
] |
How to use Python main() function in GAE (Google App Engine)? | 40,085,542 | <p>I'd like to use a <code>main()</code> function in my GAE code <br>(note: the code below is just a minimal demonstration for a much larger program, hence the need for a <code>main()</code>).</p>
<p>If I use the following code, it performs as expected:</p>
<pre><code>import webapp2
class GetHandler(webapp2.RequestH... | 0 | 2016-10-17T11:44:21Z | 40,087,671 | <p>GAE apps are not designed to be standalone apps, a <code>main()</code> function doesn't make a lot of sense for them.</p>
<p>Basically GAE apps are really just collections of handler code and rules/configurations designed to extend and customize the behaviour of the generic GAE infra/sandbox code so that it behaves... | 1 | 2016-10-17T13:26:25Z | [
"python",
"python-2.7",
"google-app-engine",
"main",
"wsgi"
] |
How to use Python main() function in GAE (Google App Engine)? | 40,085,542 | <p>I'd like to use a <code>main()</code> function in my GAE code <br>(note: the code below is just a minimal demonstration for a much larger program, hence the need for a <code>main()</code>).</p>
<p>If I use the following code, it performs as expected:</p>
<pre><code>import webapp2
class GetHandler(webapp2.RequestH... | 0 | 2016-10-17T11:44:21Z | 40,114,504 | <p>Seems that the solution was quite simple (it kept eluding me because it hid in plain sight): <code>__name__</code> is <strong>main</strong> and not <strong>__main__</strong>!</p>
<p>In short, the following code utilises a <code>main()</code> as expected:</p>
<pre><code># with main()
import webapp2
class GetHandle... | 0 | 2016-10-18T17:28:24Z | [
"python",
"python-2.7",
"google-app-engine",
"main",
"wsgi"
] |
python 2.7 unicode greek characters using matplotlib | 40,085,589 | <p>I have this coode to plot a figure:</p>
<pre><code>plt.plot(x,y, color = "blue", label = u'\u03C9')
</code></pre>
<p>
The unicode don't work in plot label, but it works when I try</p>
<pre><code>print(u'\u03C9')
</code></pre>
<p>Thank's in advance.</p>
| 0 | 2016-10-17T11:47:04Z | 40,085,718 | <p>Run <code>plt.legend()</code> to show the labels.</p>
<p>You can see a working version here: <a href="https://gist.github.com/davidbrai/742de3cb7def6da8f125e4572e691ee4" rel="nofollow">https://gist.github.com/davidbrai/742de3cb7def6da8f125e4572e691ee4</a></p>
| 0 | 2016-10-17T11:53:19Z | [
"python",
"matplotlib",
"unicode",
"label"
] |
Appending multiple elements with etree, how to write each element on new line? | 40,085,606 | <p>I am adding some elements to some nodes in a a graphml file using Python and etree. I have two lists of strings with some data which I want to write to my .graphml file. I have managed to do this but when using the .append() function it writes the two new elements on the same line. Is there a good way to get a line ... | 0 | 2016-10-17T11:47:48Z | 40,092,623 | <p>You should be able to get the wanted output by providing a suitable value for the <a href="https://docs.python.org/2.7/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tail" rel="nofollow"><code>tail</code></a> property on the new elements. The <code>tail</code> is text that comes after an element's ... | 0 | 2016-10-17T17:47:18Z | [
"python",
"xml",
"elementtree",
"graphml"
] |
Using regex to match words and numbers with whitespaces | 40,085,728 | <p>I am trying to create a regex pattern that would match the following:</p>
<pre><code>Updated x word word
</code></pre>
<p><code>x</code> = being a number, e.g. 2</p>
<p>I have tried the following:</p>
<pre><code>(Updated\s\d\s\w\s\w)
</code></pre>
<p>For example, I would like: <code>Updated 2 mins ago</code>, t... | 1 | 2016-10-17T11:54:02Z | 40,085,767 | <p>You need to use <a href="http://www.regular-expressions.info/repeat.html" rel="nofollow">quantifiers</a> to show that the digit and word groups can consist of more than one character:</p>
<pre><code>(Updated\s\d+\s\w+\s\w+)
</code></pre>
<p>This works: <a href="http://regexr.com/3ef08" rel="nofollow">http://regexr... | 1 | 2016-10-17T11:56:09Z | [
"python",
"regex",
"python-2.7"
] |
Using regex to match words and numbers with whitespaces | 40,085,728 | <p>I am trying to create a regex pattern that would match the following:</p>
<pre><code>Updated x word word
</code></pre>
<p><code>x</code> = being a number, e.g. 2</p>
<p>I have tried the following:</p>
<pre><code>(Updated\s\d\s\w\s\w)
</code></pre>
<p>For example, I would like: <code>Updated 2 mins ago</code>, t... | 1 | 2016-10-17T11:54:02Z | 40,085,771 | <p>Try this :</p>
<pre><code>(Updated\s\d+\s\w+\s\w+)
</code></pre>
<p>The <code>+</code> means "one or more characters of this type", which is probably what you need here.</p>
<p>See it here : <a href="http://regexr.com/3ef0b" rel="nofollow">http://regexr.com/3ef0b</a></p>
| 1 | 2016-10-17T11:56:21Z | [
"python",
"regex",
"python-2.7"
] |
Median of each columns in python | 40,085,735 | <p>I am trying to find median of each column of my list in python. Here is my code snippet-</p>
<pre><code>X_train1=np.array(X_train1).astype(np.float)
median1= X_train1.median(axis=0)
</code></pre>
<p>But I am getting the following error-</p>
<pre><code>AttributeError: 'numpy.ndarray' object has no attribute 'media... | 0 | 2016-10-17T11:54:13Z | 40,085,787 | <p>You should use np.median. e.g.:</p>
<pre><code>np.median(X_train1,axis=0)
</code></pre>
| 3 | 2016-10-17T11:57:02Z | [
"python",
"numpy"
] |
Importing dictionaries into python script? | 40,085,759 | <p>So i am creating a very basic text based game, however i want the answers the program gives to be relatively correct in response to different inputs. Instead of having to tell the program to write a specific thing for each different answer, i want to be able to import a dictionary of types into the script and have k... | 1 | 2016-10-17T11:55:35Z | 40,085,932 | <p>This is almost correct, except you want to tweak your import statement a bit:</p>
<p><code>from mydiction import NegConns, PosConns
</code></p>
<p>and change your equality tests to array-membership tests, like so:</p>
<p><code>if question in NegConns:</code> or,
<code>if question in PosConns:
</code></p>
<p>Also... | 1 | 2016-10-17T12:04:22Z | [
"python",
"python-2.7"
] |
Importing dictionaries into python script? | 40,085,759 | <p>So i am creating a very basic text based game, however i want the answers the program gives to be relatively correct in response to different inputs. Instead of having to tell the program to write a specific thing for each different answer, i want to be able to import a dictionary of types into the script and have k... | 1 | 2016-10-17T11:55:35Z | 40,086,122 | <p>I think that's OK, but you could create a list with the Negative and Positive answers and check it during the if statement. See how it works:</p>
<pre><code> negativeAnswers = ['No','Nope','I don't think so']
positiveAnswers = ['Yeah', 'Yes', 'Of Course']
question1 = raw_input('How are you?')
if question.l... | 0 | 2016-10-17T12:14:20Z | [
"python",
"python-2.7"
] |
Importing dictionaries into python script? | 40,085,759 | <p>So i am creating a very basic text based game, however i want the answers the program gives to be relatively correct in response to different inputs. Instead of having to tell the program to write a specific thing for each different answer, i want to be able to import a dictionary of types into the script and have k... | 1 | 2016-10-17T11:55:35Z | 40,086,803 | <p>Let's say your directory structure is as:</p>
<pre><code>--\my_project # Your directory containing the files
-| mydiction.py
-| testmod.py
</code></pre>
<p>Add a <code>__init__.py</code> in <em>my_project</em> directory to make it as python <a href="https://docs.python.org/2/tutorial/modules.html" rel="... | 0 | 2016-10-17T12:47:57Z | [
"python",
"python-2.7"
] |
Python : Data extraction from xml file | 40,085,783 | <p>Given the following file of <code>xml</code> which stores the values of vehicles trip info. How can I generate a cumulative traveled distance over each time step as a .text file. There is no specific order in the xml, it's all random. </p>
<pre><code><tripinfos>
<tripinfo id="1" depart="1.00" ar... | 0 | 2016-10-17T11:56:54Z | 40,086,713 | <p>I'm sure there's a better solution that uses an xml library, but here's an easy one</p>
<pre><code>import numpy as np
a = open('file.xml')
lines = a.readlines()
my_arr = np.zeros((len(lines)-2,2))
for i in range(len(lines[1:-1])):
contents=lines[i+1].split('\"')
my_arr[i,0]=(eval(contents[5]))
my_arr[... | 0 | 2016-10-17T12:43:40Z | [
"python",
"xml",
"python-2.7"
] |
Python : Data extraction from xml file | 40,085,783 | <p>Given the following file of <code>xml</code> which stores the values of vehicles trip info. How can I generate a cumulative traveled distance over each time step as a .text file. There is no specific order in the xml, it's all random. </p>
<pre><code><tripinfos>
<tripinfo id="1" depart="1.00" ar... | 0 | 2016-10-17T11:56:54Z | 40,089,430 | <p>I ended up using a dict to store each arrival time, and since I know the max arrival time, I can initalize the key with a range.</p>
<pre><code>import xml.etree.ElementTree as ET
filepath = r'tripinfo.xml'
tree = ET.parse(filepath)
root = tree.getroot()
mydict = {k:[] for k in range(7202)}
for trip in root.iter('... | 0 | 2016-10-17T14:45:32Z | [
"python",
"xml",
"python-2.7"
] |
Python : Data extraction from xml file | 40,085,783 | <p>Given the following file of <code>xml</code> which stores the values of vehicles trip info. How can I generate a cumulative traveled distance over each time step as a .text file. There is no specific order in the xml, it's all random. </p>
<pre><code><tripinfos>
<tripinfo id="1" depart="1.00" ar... | 0 | 2016-10-17T11:56:54Z | 40,091,042 | <p>Here I offer a partial solution to your problem.</p>
<pre><code># import some packages
from numpy import array
import xml.etree.ElementTree as et
# init some lists
ids=[]
depart=[]
arrival=[]
duration=[]
distance=[]
# prep the xml document
xmltxt = """
<root>
<tripinfo id="1" depart="1.00" ar... | 0 | 2016-10-17T16:09:11Z | [
"python",
"xml",
"python-2.7"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.