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 |
|---|---|---|---|---|---|---|---|---|---|
Parse text position vector to floats | 39,939,185 | <p>I have a .txt file that contains lines in this format:</p>
<pre><code>{"Position":[81.2305,4.05698,9.14912]}
</code></pre>
<p>Because I have lots of other lines that start with an open bracket and a name enclosed in quotes followed by a semi-colon, I have split the line into two like this:</p>
<pre><code>[ '{"Pos... | 0 | 2016-10-09T01:53:52Z | 39,939,247 | <p>Your data looks like JSON, so you can use the built-in JSON module:</p>
<pre><code>import json
pos = [] # list of (x,y,z)
with open('t.txt') as infile:
for line in infile:
# skip blank lines (add other cases as needed)
if not line.strip():
continue
item = json.loads(line)
... | 3 | 2016-10-09T02:06:01Z | [
"python",
"regex",
"python-3.x"
] |
Parse text position vector to floats | 39,939,185 | <p>I have a .txt file that contains lines in this format:</p>
<pre><code>{"Position":[81.2305,4.05698,9.14912]}
</code></pre>
<p>Because I have lots of other lines that start with an open bracket and a name enclosed in quotes followed by a semi-colon, I have split the line into two like this:</p>
<pre><code>[ '{"Pos... | 0 | 2016-10-09T01:53:52Z | 39,939,611 | <pre><code>import re
re.sub(r':',':#',s).split('#')
</code></pre>
| 0 | 2016-10-09T03:08:05Z | [
"python",
"regex",
"python-3.x"
] |
How do I put a string in a list at every nth index? | 39,939,197 | <p>I'm working on a function that gets the suit and value as a string in a list from another function:</p>
<pre><code>def getCard(n):
deckListSuit = []
grabSuit = getSuit(n)
n = (n-1) % 13 + 1
if n == 1:
deckListSuit.append("Ace")
return deckListSuit + grabSuit
if 2 <= n <= 10... | 0 | 2016-10-09T01:56:46Z | 39,939,275 | <p>You can do it in your <code>for</code> loop</p>
<pre><code>for n in myList:
hand += [" of ".join(getCard(n))]
return hand
</code></pre>
<p>You can also do it in <code>getCard</code> and return <code>'3 of Spades'</code></p>
<hr>
<p>BTW: you could keep it as tuples on list </p>
<pre><code>hand = [ ("3", "Sp... | 2 | 2016-10-09T02:11:36Z | [
"python",
"list",
"python-3.x",
"join"
] |
How do I put a string in a list at every nth index? | 39,939,197 | <p>I'm working on a function that gets the suit and value as a string in a list from another function:</p>
<pre><code>def getCard(n):
deckListSuit = []
grabSuit = getSuit(n)
n = (n-1) % 13 + 1
if n == 1:
deckListSuit.append("Ace")
return deckListSuit + grabSuit
if 2 <= n <= 10... | 0 | 2016-10-09T01:56:46Z | 39,939,361 | <p>If you use a list of tuple you can do with format and list comprehension</p>
<pre><code>test_hand = [("3","space"),("4","old")]
return ["{} of {}".format(i,z) for i,z in (test_hand)]
</code></pre>
<p>output:</p>
<pre><code> ['3 of space', '4 of old']
</code></pre>
| 0 | 2016-10-09T02:25:29Z | [
"python",
"list",
"python-3.x",
"join"
] |
TypeError: YN_prompt() missing 1 required positional argument: 'self' | 39,939,253 | <p>I'm new to python and I'm kind of stuck. When I run my program, I get this </p>
<pre><code>"Traceback (most recent call last):
File "C:/Users/Dell/Documents/Code/junk.py", line 1, in <module>
class E:
File "C:/Users/Dell/Documents/Code/junk.py", line 27, in E
YN_prompt()
TypeError: YN_prompt() mis... | 0 | 2016-10-09T02:07:20Z | 39,939,334 | <p>You need to instantiate a class instance first. For example: </p>
<pre><code>Example_class = E()
</code></pre>
<p>and then you can call your function like this</p>
<pre><code> Example_class.YN_prompt()
</code></pre>
<p>Check this older post for more infos <a href="http://stackoverflow.com/questions/17534345/type... | -1 | 2016-10-09T02:20:35Z | [
"python"
] |
TypeError: YN_prompt() missing 1 required positional argument: 'self' | 39,939,253 | <p>I'm new to python and I'm kind of stuck. When I run my program, I get this </p>
<pre><code>"Traceback (most recent call last):
File "C:/Users/Dell/Documents/Code/junk.py", line 1, in <module>
class E:
File "C:/Users/Dell/Documents/Code/junk.py", line 27, in E
YN_prompt()
TypeError: YN_prompt() mis... | 0 | 2016-10-09T02:07:20Z | 39,939,514 | <p>Looks like you wanted to keep your while loop inside your class :</p>
<pre><code>class E:
import random
import time
thing = 1
cookie = random.randrange(4)
def YN_prompt(self):
ugly = 1
while ugly == 1:
yn = input("\n Go again? y/n \n")
if yn == ("y"):
... | 0 | 2016-10-09T02:51:11Z | [
"python"
] |
Get right timezone information when using datetime.datetime.now()? | 39,939,286 | <p>I'm trying to get the date in datetime.datetime.now() format but for MT time in Python 2.7.</p>
<p>If you suggest using a library please explain how to install it. Thanks.</p>
| 0 | 2016-10-09T02:13:54Z | 39,939,464 | <pre><code>from pytz import timezone
from datetime import datetime
datetime.now(timezone('US/Mountain'))
</code></pre>
<p>That's what you probably need. As for installing the library, just <code>pip install pytz</code></p>
| 2 | 2016-10-09T02:41:35Z | [
"python",
"python-2.7"
] |
Script runs strangely in interpreter. What is the effect of the -i flag? | 39,939,517 | <p>I recently made a program which prints a word diagonally. Whenever I go to the console/python interpreter and type </p>
<p><code>python3 "xxx.py"</code>, it will just continue onto the next line and won't do anything.</p>
<p>However, if I do: <code>python3 -i "xxx.py"</code> it enters python and lets me enter inpu... | 0 | 2016-10-09T02:51:30Z | 39,941,758 | <p>The flag <code>-i</code> tells python to process the script, and then enter interactive mode. Without the <code>-i</code> python will just process the script and then exit.</p>
<p>A script might define functions, classes etc, but not call them. If you want the script to do something, you must have at least one line... | 2 | 2016-10-09T08:57:40Z | [
"python"
] |
Securing android application made by kivy | 39,939,523 | <p>I've made an app using the Kivy cross-platform tool and I built the <code>apk</code> file using <code>python-for-android</code>. I want to store a secret-key locally in the application but since the <code>apk</code> file can be disassembled, How can I make sure my secret-key is safe?</p>
| 0 | 2016-10-09T02:52:18Z | 40,034,392 | <p>After dissembling my <code>apk</code> file, I figured out that <code>python-for-android</code> stores all of its stuff including the python installation and the project itself in a binary file named <code>private.mp3</code> so the source is not fully open and I might be good to go.</p>
| 0 | 2016-10-14T03:17:53Z | [
"android",
"python",
"security",
"kivy"
] |
ImportError: No module named yaml | 39,939,541 | <p>I am very new to PyDev and Python, though I have used Eclipse but I did't do much with it. So I am having some trouble with importing yaml in my Flask project. </p>
<p>I install yaml and I can import it from the terminal. But I can't import it when I try to run the project in the eclipse</p>
<pre><code>import yaml... | -2 | 2016-10-09T02:55:16Z | 40,055,486 | <p>Run this from both eclipse and the commandline: </p>
<pre><code>import sys; print(sys.executable)
</code></pre>
<p>Do you get the same result for both?</p>
<p>using this statements help me to understand I was using different interpreters which are located in my system. thank you @shuttle87</p>
| 0 | 2016-10-15T05:49:15Z | [
"python",
"eclipse",
"flask",
"yaml",
"pydev"
] |
Python generator doesn't iterate | 39,939,547 | <p>I am trying to do a tree traversal but the problem is the yield returns a generator object but I am not able to iterate the generator object. I am very new to python, so any help will be appreciated.</p>
<pre><code>def inorder_keys(self):
try:
if self.flag:
self.head = self.root
... | 0 | 2016-10-09T02:57:00Z | 39,940,156 | <p>So, your data structure seems awfully weird to me, but here is the general pattern that you want to use:</p>
<pre><code>def inorder_keys(self):
if self.head.left is not None:
yield from self.head.left.inorder_keys()
yield self.head_key
if self.head.right is not None:
yield from self.head... | 0 | 2016-10-09T04:55:19Z | [
"python",
"python-3.x"
] |
How to get last OPTION from SELECT list using XPath - Scrapy | 39,939,553 | <p>I am using this selector but it is giving error</p>
<p><code>//*[@id="quantity"]/option/[last()-1]</code></p>
<p>How do I select last OPTION?</p>
<p>I am using Scrapy Framework.</p>
| 0 | 2016-10-09T02:58:21Z | 39,939,583 | <p>You have an extra <code>/</code> before the <code>[</code> making the XPath expression <em>invalid</em>. Remove it:</p>
<pre><code>//*[@id="quantity"]/option[last()-1]
</code></pre>
<p>Note that you can also solve it using Python/Scrapy:</p>
<pre><code>response.xpath('//*[@id="quantity"]/option')[-1].extract()
</... | 2 | 2016-10-09T03:03:40Z | [
"python",
"scrapy"
] |
find a substring in a string python | 39,939,564 | <p>This might be a beginner question but I can't seem to find the answer anywhere</p>
<p>How do I search and return a substring from another string in which the charachers are in a different order ?</p>
<p>When I check with the code below it seems to give the right answer but I'm trying to print it rather getting Tru... | -3 | 2016-10-09T03:00:12Z | 39,939,586 | <p>You're <code>print()</code>ing the <code>else</code> case. I think you meant to return that string. (at least according to your assertion code)</p>
| 0 | 2016-10-09T03:04:02Z | [
"python",
"string",
"substring"
] |
find a substring in a string python | 39,939,564 | <p>This might be a beginner question but I can't seem to find the answer anywhere</p>
<p>How do I search and return a substring from another string in which the charachers are in a different order ?</p>
<p>When I check with the code below it seems to give the right answer but I'm trying to print it rather getting Tru... | -3 | 2016-10-09T03:00:12Z | 39,939,669 | <p>You used <code>str.find()</code> wrong.</p>
<pre><code>"It determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given."
</code></pre>
<p>It will consider the order, which is not what you want. Change your <code>fix_machine</code> to:</p>
<pre><code>... | 0 | 2016-10-09T03:20:20Z | [
"python",
"string",
"substring"
] |
Pandas DataFrame (TypeError: Empty 'DataFrame': no numeric data to plot) | 39,939,589 | <p>I'm trying to learn how to use pandas and im trying to display a plot showing the total births by sex & year.</p>
<p>[1] [<a href="http://i.stack.imgur.com/R7Vz7.png]" rel="nofollow">http://i.stack.imgur.com/R7Vz7.png]</a> (Cant figure out why there's another column called sex</p>
<p>but this image above the d... | 0 | 2016-10-09T03:04:21Z | 39,939,746 | <p>This is happening because during the pivot the dataFrame becomes multi-indexed. There are no columns with values to plot against eachother. You can use <code>df.reset_index()</code> to set the multiple indexes as columns, and then plot their values.</p>
| 0 | 2016-10-09T03:32:08Z | [
"python",
"csv",
"plot",
"dataframe"
] |
Save Different Channels of Ycbcr as seperate images | Python | 39,939,595 | <p>I need to apply some transformations to the individual channels of the Ycbcr color space.</p>
<p>I have an tiff format image as the source and I need to convert it to ycbcr color space. I have not been able to successfully save the different channels as separate images. I have been only able to extract the luminesc... | 0 | 2016-10-09T03:05:06Z | 39,940,287 | <p>Here is my code:</p>
<pre><code>import numpy
import Image as im
image = im.open('1.tiff')
ycbcr = image.convert('YCbCr')
# output of ycbcr.getbands() put in order
Y = 0
Cb = 1
Cr = 2
YCbCr=list(ycbcr.getdata()) # flat list of tuples
# reshape
imYCbCr = numpy.reshape(YCbCr, (image.size[1], image.size[0], 3))
# Con... | 0 | 2016-10-09T05:18:43Z | [
"python",
"python-imaging-library",
"color-space"
] |
Save Different Channels of Ycbcr as seperate images | Python | 39,939,595 | <p>I need to apply some transformations to the individual channels of the Ycbcr color space.</p>
<p>I have an tiff format image as the source and I need to convert it to ycbcr color space. I have not been able to successfully save the different channels as separate images. I have been only able to extract the luminesc... | 0 | 2016-10-09T03:05:06Z | 39,940,615 | <p>Simply use the <a href="http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#PIL.Image.Image.split" rel="nofollow"><code>.split()</code></a> method to split the image into different channels (called <em>bands</em> in PIL). No need to use numpy.</p>
<pre><code>(y, cb, cr) = ycbcr.split()
# y, cb and cr are all... | 0 | 2016-10-09T06:17:29Z | [
"python",
"python-imaging-library",
"color-space"
] |
How to split this string to dict with python? | 39,939,610 | <p><strong>String</strong> </p>
<pre><code>string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"'
</code></pre>
<p><strong>Expected Result</strong> </p>
<pre><code>dict1 = {'{ABCD-1234-3E3F}' : 'MEANING1', '{ABCD-1B34-3X5F}' : 'MEANING2', '{XLMN-2345-KFDE}' : 'WHITE'}
</code... | 0 | 2016-10-09T03:07:59Z | 39,939,655 | <pre><code>string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"'
elements = string1.replace('"','').split(',')
dict(zip(elements[::2],elements[1::2]))
</code></pre>
<p>You can first split the original string and extract elements from it. Now you can pair element in odd and even p... | 1 | 2016-10-09T03:15:56Z | [
"python",
"split"
] |
How to split this string to dict with python? | 39,939,610 | <p><strong>String</strong> </p>
<pre><code>string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"'
</code></pre>
<p><strong>Expected Result</strong> </p>
<pre><code>dict1 = {'{ABCD-1234-3E3F}' : 'MEANING1', '{ABCD-1B34-3X5F}' : 'MEANING2', '{XLMN-2345-KFDE}' : 'WHITE'}
</code... | 0 | 2016-10-09T03:07:59Z | 39,939,666 | <p>If you are looking for a one-liner, this will work:</p>
<pre><code>>>> dict(tuple(x.split(',')) for x in string1[1:-1].split('","'))
{'{ABCD-1B34-3X5F}': 'MEANING2', '{XLMN-2345-KFDE}': 'WHITE', '{ABCD-1234-3E3F}': 'MEANING1'}
</code></pre>
| 5 | 2016-10-09T03:19:11Z | [
"python",
"split"
] |
How to split this string to dict with python? | 39,939,610 | <p><strong>String</strong> </p>
<pre><code>string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"'
</code></pre>
<p><strong>Expected Result</strong> </p>
<pre><code>dict1 = {'{ABCD-1234-3E3F}' : 'MEANING1', '{ABCD-1B34-3X5F}' : 'MEANING2', '{XLMN-2345-KFDE}' : 'WHITE'}
</code... | 0 | 2016-10-09T03:07:59Z | 39,940,011 | <p>And here another one-liner alternative:</p>
<pre><code>>>> string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"'
>>> dict((nm, v) for nm,v in [pair.split(',') for pair in eval(string1)])
>>> {'{ABCD-1234-3E3F}': 'MEANING1', '{ABCD-1B34-3X5F}': 'MEANI... | 0 | 2016-10-09T04:25:31Z | [
"python",
"split"
] |
Filter one array according to data in another array | 39,939,627 | <p>I have two arrays of random numbers, <code>X</code> and <code>Y</code>. X represents x-coordinates and <code>Y</code> represents y-coordinates. I want to filter <code>X</code> such that I only keep indices <code>i</code> of <code>X</code> where:</p>
<pre><code>X[i]^2 + Y[i]^2 < 1
</code></pre>
<p>I know how to ... | 0 | 2016-10-09T03:12:17Z | 39,939,675 | <p>This will do:</p>
<pre><code>X_filtered = X[X**2 + Y**2 < 1]
</code></pre>
<p><code>X**2 + Y**2 < 1</code> returns a boolean array and accessing <code>X</code> on this array returns <code>X</code> only at the indices equal to <code>True</code>.</p>
| 0 | 2016-10-09T03:21:49Z | [
"python",
"arrays",
"numpy"
] |
Filter one array according to data in another array | 39,939,627 | <p>I have two arrays of random numbers, <code>X</code> and <code>Y</code>. X represents x-coordinates and <code>Y</code> represents y-coordinates. I want to filter <code>X</code> such that I only keep indices <code>i</code> of <code>X</code> where:</p>
<pre><code>X[i]^2 + Y[i]^2 < 1
</code></pre>
<p>I know how to ... | 0 | 2016-10-09T03:12:17Z | 39,939,692 | <pre><code>for ind,(a,b) in enumerate(zip(x,y)) :
if (a**2 + b**2) < 1 :
print ind
</code></pre>
| -1 | 2016-10-09T03:24:58Z | [
"python",
"arrays",
"numpy"
] |
Filter one array according to data in another array | 39,939,627 | <p>I have two arrays of random numbers, <code>X</code> and <code>Y</code>. X represents x-coordinates and <code>Y</code> represents y-coordinates. I want to filter <code>X</code> such that I only keep indices <code>i</code> of <code>X</code> where:</p>
<pre><code>X[i]^2 + Y[i]^2 < 1
</code></pre>
<p>I know how to ... | 0 | 2016-10-09T03:12:17Z | 39,939,750 | <p><code>X = [X[i] for i in range(len(X)) if X[i]**2 + Y[i]**2 < 1]</code></p>
<p>this will filter X so that X only contains those that match your filtering criteria. </p>
<p>Note that this does use looping via comprehension, so I am not quite sure how this is to be done without looping. </p>
| -1 | 2016-10-09T03:33:12Z | [
"python",
"arrays",
"numpy"
] |
Filter one array according to data in another array | 39,939,627 | <p>I have two arrays of random numbers, <code>X</code> and <code>Y</code>. X represents x-coordinates and <code>Y</code> represents y-coordinates. I want to filter <code>X</code> such that I only keep indices <code>i</code> of <code>X</code> where:</p>
<pre><code>X[i]^2 + Y[i]^2 < 1
</code></pre>
<p>I know how to ... | 0 | 2016-10-09T03:12:17Z | 39,939,761 | <p>So I think these arrays are too large to loop? If you only want to <strong>keep</strong> the indices for later, try <a href="https://wiki.python.org/moin/Generators" rel="nofollow">Generators</a>:</p>
<pre><code>def X_indices_filterd(X, Y):
for i in enumerate(X):
if (X[i] ** 2 + Y[i] ** 2 < 1) yield ... | -1 | 2016-10-09T03:35:13Z | [
"python",
"arrays",
"numpy"
] |
Writing a Pandas Dataframe to MySQL | 39,939,716 | <p>I'm trying to write a Python Pandas Dataframe to a MySQL database. I realize that it's possible to use sqlalchemy <a href="http://stackoverflow.com/questions/37627520/insert-pandas-dataframe-to-mysql-using-sqlalchemy">for this</a>, but I'm wondering if there is another way that may be easier, preferably already buil... | 1 | 2016-10-09T03:27:52Z | 39,947,371 | <p>The other option to <strong>sqlalchemy</strong> can be used <strong>to_sql</strong> but in future released will be deprecated but now in version <strong>pandas 0.18.1 documentation</strong> is still active. </p>
<p>According to pandas documentation <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pand... | 0 | 2016-10-09T19:00:07Z | [
"python",
"mysql",
"dataframe"
] |
Sum data points from individual pandas dataframes in a summary dataframe based on custom (and possibly overlapping) bins | 39,939,723 | <p>I have many dataframes with individual counts (e.g. <code>df_boston</code> below). Each row defines a data point that is uniquely identified by its <code>marker</code> and its <code>point</code>. I have a summary dataframe (<code>df_inventory_master</code>) that has custom bins (the <code>point</code>s above map to ... | 0 | 2016-10-09T03:29:34Z | 39,943,965 | <p>Here is how I approached it, basically a *sql style left join * using the pandas merge operation, then apply() across the row axis, with a lambda to decide if the individual records are in the band or not, finally groupby and sum: </p>
<pre><code>df_merged = df_inventory_master.merge(df_boston, on=['Marker'],how... | 1 | 2016-10-09T13:06:57Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
WAV files being saved in wrong order | 39,939,724 | <p>I have a program that loops over a for loop, and saves sine waves as wav files to create a range of tones for a keyboard. The loop goes from -int to +int, and saves these WAV files in each iteration. The only problem is that when it gets to around x = 2, the file order is messed up. I don't know why this happens or ... | 1 | 2016-10-09T03:30:00Z | 39,979,197 | <p>There is not enough code to replicate, However, here is an example using enumerate that will put the subsequent xrange elements in order. Perhaps this will aid in keeping your wavefiles in sequence. </p>
<pre><code>for i, x in enumerate(xrange(-43, 47, 1)):
file_name = "file{0}-{1}.wav".format(i, x)
pri... | 0 | 2016-10-11T14:09:17Z | [
"python",
"for-loop",
"audio",
"wav"
] |
Why aren't all the base classes constructors being called? | 39,939,737 | <p>In Python 2.7.10</p>
<pre><code>class OneMixin(object):
def __init__(self):
# super(OneMixin, self).__init__()
print "one mixin"
class TwoMixin(object):
def __init__(self):
# super(TwoMixin, self).__init__()
print "two mixin"
class Account(OneMixin, TwoMixin):
def __ini... | 1 | 2016-10-09T03:31:24Z | 39,939,819 | <p>This is because <code>super</code> is used to delegate the calls to either parent or sibling class of a type. <a href="https://docs.python.org/2.7/library/functions.html#super" rel="nofollow">Python documentation</a> has following description of the second use case:</p>
<blockquote>
<p>The second use case is to s... | 1 | 2016-10-09T03:46:21Z | [
"python",
"python-2.7"
] |
Why aren't all the base classes constructors being called? | 39,939,737 | <p>In Python 2.7.10</p>
<pre><code>class OneMixin(object):
def __init__(self):
# super(OneMixin, self).__init__()
print "one mixin"
class TwoMixin(object):
def __init__(self):
# super(TwoMixin, self).__init__()
print "two mixin"
class Account(OneMixin, TwoMixin):
def __ini... | 1 | 2016-10-09T03:31:24Z | 39,939,825 | <p>The reason is that you're overriding the <code>__init__</code> method of the parent class. The method resolution order will be the same, regardless of what is in your <code>__init__</code> method.</p>
<p>The way <code>super</code> works is that it will pass it down to the next class down the line in the method res... | 1 | 2016-10-09T03:47:51Z | [
"python",
"python-2.7"
] |
How do you print a function that returns a request in Python? | 39,939,741 | <p>I have a function that gets the profile data of an user:</p>
<p><strong>API.py</strong></p>
<pre><code>def getProfileData(self):
data = json.dumps({
'_uuid' : self.uuid,
'_uid' : self.username_id,
'_csrftoken' : self.token
})
return self.SendRequest('accounts/current_user/?... | 4 | 2016-10-09T03:31:45Z | 39,940,117 | <p>If all you want to do is print the response that you get back, you can do that in <code>SendRequest</code>, but I suspect tha tyour real problem is that you are self-serializing your post data when <code>requests</code> does that for you. In any case, since your question is about printing:</p>
<pre><code> if re... | 1 | 2016-10-09T04:46:35Z | [
"python"
] |
How to get a numpy ndarray of integers from a file with header? | 39,939,773 | <p>I have a plain text file (.txt) with the following content.</p>
<pre><code>Matrix Header.
6 11
0 1 1 1 1 1 1 1 1 1 1
1 0 1 1 1 1 0 1 1 1 1
1 1 1 1 0 0 1 1 1 1 1
0 0 0 0 1 1 1 0 0 0 0
1 1 1 0 0 1 1 1 1 1 1
1 0 0 1 1 1 1 0 1 1 0
6 rows, 11 columns
</code></pre>
<p>I need obtain a numpy ndarray of integers a... | 2 | 2016-10-09T03:37:29Z | 39,939,861 | <p>A simple solution is to explicitly ignore the lines you don't need:</p>
<pre><code>with open(path) as infile:
lines = infile.readlines()
np.loadtxt(lines[2:-2])
del lines # if you want to immediately release the memory
</code></pre>
<p>This directly gives you what you want, assuming the header and footer are a... | 1 | 2016-10-09T03:53:47Z | [
"python",
"numpy",
"multidimensional-array"
] |
How to get a numpy ndarray of integers from a file with header? | 39,939,773 | <p>I have a plain text file (.txt) with the following content.</p>
<pre><code>Matrix Header.
6 11
0 1 1 1 1 1 1 1 1 1 1
1 0 1 1 1 1 0 1 1 1 1
1 1 1 1 0 0 1 1 1 1 1
0 0 0 0 1 1 1 0 0 0 0
1 1 1 0 0 1 1 1 1 1 1
1 0 0 1 1 1 1 0 1 1 0
6 rows, 11 columns
</code></pre>
<p>I need obtain a numpy ndarray of integers a... | 2 | 2016-10-09T03:37:29Z | 39,940,289 | <p>To avoid the error that might occur because of the text at the end, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow"><code>numpy.genfromtxt</code></a> with the <code>max_rows</code> argument. For example,</p>
<pre><code>In [26]: with open(filename, 'rb'... | 1 | 2016-10-09T05:19:37Z | [
"python",
"numpy",
"multidimensional-array"
] |
How do I create an animated gif in Python using Wand? | 39,939,780 | <p>The instructions are simple enough in the <a href="http://docs.wand-py.org/en/0.4.1/guide/sequence.html" rel="nofollow">Wand docs</a> for <em>reading</em> a sequenced image (e.g. animated gif, icon file, etc.):</p>
<pre><code>>>> from wand.image import Image
>>> with Image(filename='sequence-anima... | 3 | 2016-10-09T03:38:37Z | 40,088,327 | <p>The best examples are located in the unit-tests shipped with the code. <a href="https://github.com/dahlia/wand/blob/master/tests/sequence_test.py" rel="nofollow"><code>wand/tests/sequence_test.py</code></a> for example.</p>
<p>For creating an animated gif with wand, remember to load the image into the sequence, and... | 2 | 2016-10-17T13:55:56Z | [
"python",
"imagemagick",
"animated-gif",
"wand"
] |
Sorting parallel lists in python - first item descending, second item ascending | 39,939,813 | <p>I have two lists - one for a team name and the second for points </p>
<p>I wanted to sort them based on the points without losing track of the corresponding team. I found something on SO that works great for doing this - and it sorts teams by points in descending order (most to least).</p>
<p>There doesn't appear ... | 1 | 2016-10-09T03:45:02Z | 39,939,850 | <p>You have two options here. You could use <code>cmp</code> or <code>key</code> as a parameter to <code>sorted</code>.</p>
<p>With a <code>cmp</code> you're defining a function which takes two arguments, the two values being compared. If the first argument is smaller than the second, return a negative number. If it i... | 1 | 2016-10-09T03:52:57Z | [
"python",
"list",
"python-2.7",
"sorting"
] |
Sorting parallel lists in python - first item descending, second item ascending | 39,939,813 | <p>I have two lists - one for a team name and the second for points </p>
<p>I wanted to sort them based on the points without losing track of the corresponding team. I found something on SO that works great for doing this - and it sorts teams by points in descending order (most to least).</p>
<p>There doesn't appear ... | 1 | 2016-10-09T03:45:02Z | 39,939,940 | <p>You can specify how <code>sorted</code> will sort by passing in the <code>key</code> kwarg. One handy way to use <code>key</code> is with <code>itemgetter</code> from the <code>operator</code> module.</p>
<p>For example, if you have a list of tuples (such as by zipping two lists) and you want to sort by the second ... | 1 | 2016-10-09T04:06:17Z | [
"python",
"list",
"python-2.7",
"sorting"
] |
Issue with my word score function | 39,939,909 | <p>So here is my code:</p>
<pre><code>def word_score(string1, string2):
'''Returns the word score for two strings'''
if len(string1) == 0 or len(string2) == 0:
return 0
else:
if string1[0] in string2:
return 1 + word_score(string1[1:], string2... | 0 | 2016-10-09T04:00:46Z | 39,939,986 | <p>You can convert the str in a list, then in a set for eliminate duplicates and check the intersection len.</p>
<pre><code>def word_score(string1, string2):
'''Returns the word score for two strings'''
string1=list(string1)
string2=list(string2)
string1=set(string1)
string2=set(string2)
if len... | 0 | 2016-10-09T04:18:12Z | [
"python",
"recursion"
] |
Issue with my word score function | 39,939,909 | <p>So here is my code:</p>
<pre><code>def word_score(string1, string2):
'''Returns the word score for two strings'''
if len(string1) == 0 or len(string2) == 0:
return 0
else:
if string1[0] in string2:
return 1 + word_score(string1[1:], string2... | 0 | 2016-10-09T04:00:46Z | 39,939,989 | <p>You can try to "erase" the letters from the second word, when a "positive match" occurs.
This way, your duplicate issues will disappear. </p>
| 0 | 2016-10-09T04:18:53Z | [
"python",
"recursion"
] |
Issue with my word score function | 39,939,909 | <p>So here is my code:</p>
<pre><code>def word_score(string1, string2):
'''Returns the word score for two strings'''
if len(string1) == 0 or len(string2) == 0:
return 0
else:
if string1[0] in string2:
return 1 + word_score(string1[1:], string2... | 0 | 2016-10-09T04:00:46Z | 39,940,044 | <p>Assuming that you can't use <code>set</code>, <code>dict</code> or <code>Counter</code> one way would be to iterate the characters in <code>string1</code> one by one and use <a href="https://docs.python.org/3.5/library/stdtypes.html#str.find" rel="nofollow"><code>str.find</code></a> to check if it can be found from ... | 1 | 2016-10-09T04:32:58Z | [
"python",
"recursion"
] |
What is the best way to fetch huge data from mysql with sqlalchemy? | 39,939,970 | <p>I want to process over 10 millions data stored in MySQL. So I wrote this to slice the sql to several parts then concatenate the data for latter process. It works well if <code>count < 2 millions</code>. However when the <code>count</code> rise, the time sqlalchemy consumes goes much longer.</p>
<pre><code>def fe... | 1 | 2016-10-09T04:14:43Z | 39,947,245 | <p>This is because you're using <code>LIMIT</code>/<code>OFFSET</code>, so when you specify offset 3000000, for example, the database has to skip over 3000000 records.</p>
<p>The correct way to do this is to <code>ORDER BY</code> some indexed column, like the primary key <code>id</code> column, for example, then do a ... | 1 | 2016-10-09T18:47:11Z | [
"python",
"sqlalchemy"
] |
Issues clicking an element using selenium | 39,939,995 | <p>Im using this code to explore tripadvisor (Portuguese comments)</p>
<pre><code>from selenium import webdriver
from bs4 import BeautifulSoup
driver=webdriver.Firefox()
driver.get("https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-TAP-Portugal#review_425811350")
driver.set_window_size(1920, 10... | 1 | 2016-10-09T04:20:01Z | 39,940,106 | <p>What worked for me was to use an Explicit Wait and the <code>element_to_be_clickable</code> Expected Condition and get to the inner <code>span</code> element:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver... | 3 | 2016-10-09T04:44:30Z | [
"python",
"selenium",
"selenium-webdriver",
"web-scraping"
] |
Python Regex for ignoring a sentence with two consecutive upper case letters | 39,940,000 | <p>I have a simple problem at hand to ignore the sentences that contain two or more consecutive capital letters and many more grammar rules .</p>
<p><strong>Issue:</strong> By the definition the regex should not match the string <code>'This is something with two CAPS.'</code> , but it does match.</p>
<p><strong>Code:... | 1 | 2016-10-09T04:21:03Z | 39,940,080 | <p>Itâs probably easier to write your regex in the negative (find all sentences that are bad sentences) than it is in the positive. </p>
<pre><code>checker = re.compile(r'([A-Z][A-Z]|[ ][ ]|^[a-z])')
check2 = re.compile(r'^[A-Z][a-z].* .*\.$')
return not checker.findall(sentence) and check2.findall(sentence)
</code... | 0 | 2016-10-09T04:39:01Z | [
"python",
"regex",
"python-3.x"
] |
Python Regex for ignoring a sentence with two consecutive upper case letters | 39,940,000 | <p>I have a simple problem at hand to ignore the sentences that contain two or more consecutive capital letters and many more grammar rules .</p>
<p><strong>Issue:</strong> By the definition the regex should not match the string <code>'This is something with two CAPS.'</code> , but it does match.</p>
<p><strong>Code:... | 1 | 2016-10-09T04:21:03Z | 39,940,122 | <p>Your negative lookahead is only applying to the beginning of the string being tested. </p>
<p>2nd Capturing Group <code>(^(?![A-Z][A-Z]+))</code></p>
<p><code>^</code> asserts position at start of the string</p>
<p>Negative Lookahead <code>(?![A-Z][A-Z]+)</code></p>
<p><code>"This will NOT fail."</code></p>
<p>... | 0 | 2016-10-09T04:47:06Z | [
"python",
"regex",
"python-3.x"
] |
How to save crawl page link into item using scrapy? | 39,940,017 | <p>This is my spider page:</p>
<pre><code>rules = (
Rule(LinkExtractor(allow=r'torrents-details\.php\?id=\d*'), callback='parse_item', follow=True),
)
def parse_item(self, response):
item = MovieNotifyItem()
item['title'] = response.xpath('//h5[@class="col s12 light center teal darken-... | 1 | 2016-10-09T04:26:26Z | 39,940,118 | <p>If I understand correctly, you are looking for the <code>response.url</code>:</p>
<pre><code>def parse_item(self, response):
item = MovieNotifyItem()
item['url'] = response.url # "url" field should be defined for "MovieNotifyItem" Item class
# ...
yield item
</code></pre>
| 0 | 2016-10-09T04:46:38Z | [
"python",
"python-3.x",
"scrapy"
] |
apply gaussian filtering on numpy array with nan value and then plot the image | 39,940,065 | <p>I have a numpy 2d array (image) with values >=0.0 but there are some indices with value 'nan'. When I try to plot this figure it looks like the below image. The 0 in the image array becomes black and nan becomes white.</p>
<p><a href="http://i.stack.imgur.com/S5JHF.png" rel="nofollow"><img src="http://i.stack.imgur... | 0 | 2016-10-09T04:36:36Z | 39,942,576 | <p>When doing a gaussian filter of an image, any pixel close to a <code>nan</code> pixel will also turn into a <code>nan</code>, since its new value is the weighted sum over all neighboring pixels covered by the convolution kernel.</p>
<p>Therefore, smoothing this particular image using, for example, <code>scipy.ndima... | 0 | 2016-10-09T10:31:19Z | [
"python",
"matplotlib"
] |
How to pass argument implicitly in Python Class function | 39,940,089 | <p>I was writing a python class and related functions. Suppose following is a class having a function that adds up all values of a numeric list and returns the sum</p>
<pre><code> alist = [2,3,7,4,7]
MyClasss(object):
def __init__(self):
print("Roses are red")
def add_list(self,thelist):
j = ... | 0 | 2016-10-09T04:41:31Z | 39,940,172 | <p>You can add it to <code>__init__</code> on construction</p>
<pre><code>class MyClasss(object):
def __init__(self, theList):
self.theList = theList
def add_list(self):
return sum(self.theList)
>>> a = MyClasss([2,3,7,4,7])
>>> print("sum is ", a.add_list())
23
>>> ... | 2 | 2016-10-09T04:57:44Z | [
"python",
"function",
"class"
] |
Django Form request.POST.get() always returns empty | 39,940,182 | <p>Sorry if this is a noob question. I'm creating a login form for a Django app, but I'm having trouble getting it to work. request.POST.get() doesn't return anything, so the authentication always fails. Am I missing something obvious?</p>
<p>login.html:</p>
<pre><code>{% extends "base.html" %}
{% block content%}
&... | 0 | 2016-10-09T04:58:34Z | 39,940,202 | <p>Check out the names in the form input fields they are case sensitive. in Django do this</p>
<pre><code> usern = request.POST.get('Username', '')
passw = request.POST.get('Password', '')
</code></pre>
<p>or in html form make them lowercase the input name field</p>
| 1 | 2016-10-09T05:03:18Z | [
"python",
"django"
] |
How do I view errors my Flask App is returning? | 39,940,204 | <p>I've started to make an app using Python 3 with the Flask framework. I mostly followed this <a href="https://pythonprogramming.net/creating-first-flask-web-app/" rel="nofollow">tutorial</a>. I'm currently using a free-tier AWS Ubuntu-16.04 server to host the app on while trying to develop it.</p>
<p>How am I meant ... | 0 | 2016-10-09T05:03:38Z | 39,940,222 | <p>You should enable debugging for your app.</p>
<pre><code>app = Flask(__name__)
app.debug = True
</code></pre>
<p>That will output the traceback on the error pages, instead of just a generic 'Server error' page. </p>
| 1 | 2016-10-09T05:06:53Z | [
"python",
"python-3.x",
"flask"
] |
Python Regex match 2nd or 3rd word in line | 39,940,205 | <p>I'm trying to separate lines into 3 sections using regex, with a typical line fitting into this kind of pattern: <code>-30.345 150.930 112.356</code></p>
<p>I'm extracting the first section of data fine using <code>lat = float(re.match('[^\s]+', line).group(0))</code>, but have been unable to correctly target the 2... | 1 | 2016-10-09T05:03:54Z | 39,940,254 | <p>If you cannot do <code>split</code> then you can just match the numbers with optional <code>-</code> or <code>+</code> at the start:</p>
<pre><code>>>> s = '-30.345 foo 150.930 abc 112.356 another .123'
>>> re.findall(r'([+-]?\d*\.?\d+)', s)
['-30.345', '150.930', '112.356', '.123']
</code></pre>
... | 1 | 2016-10-09T05:12:51Z | [
"python",
"regex"
] |
How do I remove commas and quotations from my list output | 39,940,447 | <p>Having a hard time stripping these quotation marks and commas from my list, </p>
<p><code>**SHOWN BELOW IN THE SECOND PART OF MY CODE OUTPUT**</code>I need all of the (' ',) to be stripped from the output and I keep trying the <code>rstrip()</code> on my <code>team variable</code>but it is giving me this ERROR.</p>... | -2 | 2016-10-09T05:47:16Z | 39,940,472 | <p>Remove the parenthesis and <code>strip</code></p>
<pre><code>print(team.strip(), count)
</code></pre>
| 1 | 2016-10-09T05:51:32Z | [
"python",
"list",
"output",
"strip"
] |
How do I remove commas and quotations from my list output | 39,940,447 | <p>Having a hard time stripping these quotation marks and commas from my list, </p>
<p><code>**SHOWN BELOW IN THE SECOND PART OF MY CODE OUTPUT**</code>I need all of the (' ',) to be stripped from the output and I keep trying the <code>rstrip()</code> on my <code>team variable</code>but it is giving me this ERROR.</p>... | -2 | 2016-10-09T05:47:16Z | 39,940,474 | <p>remove <code>strip()</code> from the count</p>
<pre><code>print(team.strip(), count)
</code></pre>
| 1 | 2016-10-09T05:51:52Z | [
"python",
"list",
"output",
"strip"
] |
How do I remove commas and quotations from my list output | 39,940,447 | <p>Having a hard time stripping these quotation marks and commas from my list, </p>
<p><code>**SHOWN BELOW IN THE SECOND PART OF MY CODE OUTPUT**</code>I need all of the (' ',) to be stripped from the output and I keep trying the <code>rstrip()</code> on my <code>team variable</code>but it is giving me this ERROR.</p>... | -2 | 2016-10-09T05:47:16Z | 39,940,480 | <p>Wrapping the items with <code>( )</code> makes it a tuple; you should remove the extra parenthesis in your call to <code>print</code>. And you don't need <a href="https://docs.python.org/2/library/string.html#string.strip" rel="nofollow"><code>strip</code></a> for <code>int</code> type. You also don't to <code>stri... | 4 | 2016-10-09T05:52:25Z | [
"python",
"list",
"output",
"strip"
] |
How do I remove commas and quotations from my list output | 39,940,447 | <p>Having a hard time stripping these quotation marks and commas from my list, </p>
<p><code>**SHOWN BELOW IN THE SECOND PART OF MY CODE OUTPUT**</code>I need all of the (' ',) to be stripped from the output and I keep trying the <code>rstrip()</code> on my <code>team variable</code>but it is giving me this ERROR.</p>... | -2 | 2016-10-09T05:47:16Z | 39,940,507 | <p>it is not part of your element . <code>print()</code> adds this when it display list, tuple, dict. And you see it because you used too many <code>()</code> and created tuple.</p>
<p>You have </p>
<pre><code>print( (team.strip(), count.strip()) )
</code></pre>
<p>where <code>(team.strip(), count.strip())</code>... | 2 | 2016-10-09T05:56:54Z | [
"python",
"list",
"output",
"strip"
] |
How do you create a gtk window in python and also have code running in the background? | 39,940,463 | <p>I am trying to create a GUI window with a web address inside (a video stream in this case) while also having some additional code running in the background that communicate with the GPIO ports on a Raspberry Pi. I can get the window to work but the background code only starts when the window is closed. Or if I rever... | 0 | 2016-10-09T05:50:04Z | 39,940,602 | <p><code>gtk.main()</code> runs till you close window (it is call "main loop" or "event loop" and it does everything in GUI program - get key/mouse event, send it to widgets, redraw widgets, run functions when ypu press button, etc.). </p>
<p>You have to use <code>Threading</code> to run (long-running) code at the sam... | 1 | 2016-10-09T06:14:41Z | [
"python",
"raspberry-pi",
"gtk"
] |
stuck in implementing search in django | 39,940,520 | <p>I want to implement search in django. I don't use any search technique like solar etc. I am using simple filter query of django.
Now the problem is this:
I have a model <strong><code>Product</code></strong>
with five field <code>name</code>, <code>cost</code>, <code>brand</code>, <code>expiry_date</code>, <code>wei... | 1 | 2016-10-09T05:59:42Z | 39,940,558 | <p>if you want when the name is None, you have to search all names in Product Model
try this logic</p>
<pre><code>if name == None:
result = Product.objects.all()
else:
result = Product.objects.filter(name = name)
</code></pre>
| 0 | 2016-10-09T06:06:15Z | [
"python",
"django"
] |
stuck in implementing search in django | 39,940,520 | <p>I want to implement search in django. I don't use any search technique like solar etc. I am using simple filter query of django.
Now the problem is this:
I have a model <strong><code>Product</code></strong>
with five field <code>name</code>, <code>cost</code>, <code>brand</code>, <code>expiry_date</code>, <code>wei... | 1 | 2016-10-09T05:59:42Z | 39,940,590 | <p>You didn't show your search query. However, I think using <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#contains" rel="nofollow"><code>contains</code></a> (or <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#icontains" rel="nofollow"><code>icontains</code></a> for case in... | 2 | 2016-10-09T06:13:32Z | [
"python",
"django"
] |
stuck in implementing search in django | 39,940,520 | <p>I want to implement search in django. I don't use any search technique like solar etc. I am using simple filter query of django.
Now the problem is this:
I have a model <strong><code>Product</code></strong>
with five field <code>name</code>, <code>cost</code>, <code>brand</code>, <code>expiry_date</code>, <code>wei... | 1 | 2016-10-09T05:59:42Z | 39,940,926 | <p>Try this:</p>
<pre><code>result = Product.objects.all()
name = request.GET.get('name', None)
if name:
result = result.objects.filter(name__icontains=name)
</code></pre>
| 0 | 2016-10-09T07:03:27Z | [
"python",
"django"
] |
install storm on windows 10 | 39,940,644 | <p>I'm new here and I've tried a lot of my own effort before calling you, guys.</p>
<p>I'm trying to install apache storm on windows 10.
I have installed ZooKeeper successfully, and set the Java_Home and Storm_Home.
Python is C:/Python27.
What I don't understand is those instructions:</p>
<p>PATH Add:</p>
<pre><code... | 1 | 2016-10-09T06:21:58Z | 39,940,839 | <pre><code>Download this storm setup from below link:
https://dl.dropboxusercontent.com/s/iglqz73chkul1tu/storm-0.9.1-incubating-SNAPSHOT-12182013.zip
Extract that file to the location of your choice. i choose 'C:\'
**Configure Environment Variables**:
On Windows Storm requires the STORM_HOME and JAVA_HOME environme... | 0 | 2016-10-09T06:49:19Z | [
"java",
"python",
"apache"
] |
BFMatcher match in OpenCV throwing error | 39,940,766 | <p>I am using SURF descriptors for image matching. I am planning to match a given image to a database of images.</p>
<pre><code>import cv2
import numpy as np
surf = cv2.xfeatures2d.SURF_create(400)
img1 = cv2.imread('box.png',0)
img2 = cv2.imread('box_in_scene.png',0)
kp1,des1 = surf.detectAndCompute(img1,None)
kp2,... | 1 | 2016-10-09T06:38:34Z | 39,946,169 | <p><strong>To search between descriptors of two images</strong> use:</p>
<pre><code>img1 = cv2.imread('box.png',0)
img2 = cv2.imread('box_in_scene.png',0)
kp1,des1 = surf.detectAndCompute(img1,None)
kp2,des2 = surf.detectAndCompute(img2,None)
bf = cv2.BFMatcher(cv2.NORM_L1,crossCheck=False)
matches = bf.match(des1,... | 1 | 2016-10-09T17:02:52Z | [
"python",
"opencv",
"surf",
"orb"
] |
How do I use a webscraper in python if I have a minimal OS? | 39,940,786 | <p>I am trying to make my raspberry pi interact with my wifi router using python. Since my router doesn't have an API, I need to use a webscraper or something similar in python to enter password, go to links, etc... I have tried using selenium and Beautifulsoup, but those both require web browsers that I cant get on ra... | 1 | 2016-10-09T06:41:24Z | 39,940,850 | <p>Most routers use basic authentication. You can supply the username and password in the request URL by the following scheme: <code>https://USERNAME:PASSWORD@webaddress.com</code></p>
<p>You don't need Selenium to make HTTP requests. Selenium is for browser automation. BeautifulSoup is for parsing HTML and has nothin... | 0 | 2016-10-09T06:50:38Z | [
"python",
"web-scraping",
"raspberry-pi",
"raspbian"
] |
Counting seed values from first sequence in second sequence | 39,940,809 | <p>If a function is given a sequence <code>seeds</code> of seed values, it needs to count for every single seed value the number of times they show up in the 2nd sequence <code>xs</code>. Then it should return the counts as a list of integers, in the same order of the seed values. If <code>seeds</code> includes duplica... | 0 | 2016-10-09T06:45:02Z | 39,940,876 | <blockquote>
<p>I can't figure out how exactly I would count the number of seed values in the second sequence and not just check if the values exist.</p>
</blockquote>
<p>Python sequences have a handy <code>.count</code> method.</p>
<pre><code>>>> [1,1,1,2,3,4,5].count(1)
3
>>> "ababababcdefg".cou... | 2 | 2016-10-09T06:56:07Z | [
"python",
"sequence",
"counting",
"seed"
] |
Counting seed values from first sequence in second sequence | 39,940,809 | <p>If a function is given a sequence <code>seeds</code> of seed values, it needs to count for every single seed value the number of times they show up in the 2nd sequence <code>xs</code>. Then it should return the counts as a list of integers, in the same order of the seed values. If <code>seeds</code> includes duplica... | 0 | 2016-10-09T06:45:02Z | 39,940,911 | <p>Check out <code>collections.Counter()</code></p>
<pre><code>import collections
def count_each(seeds,xs):
c = collections.Counter(xs)
return [c[seed] for seed in seeds]
</code></pre>
| 2 | 2016-10-09T07:01:53Z | [
"python",
"sequence",
"counting",
"seed"
] |
Counting seed values from first sequence in second sequence | 39,940,809 | <p>If a function is given a sequence <code>seeds</code> of seed values, it needs to count for every single seed value the number of times they show up in the 2nd sequence <code>xs</code>. Then it should return the counts as a list of integers, in the same order of the seed values. If <code>seeds</code> includes duplica... | 0 | 2016-10-09T06:45:02Z | 39,941,178 | <pre><code>def count_letter(seeds,xs):
for c in seeds:
count=0
for d in xs:
if c==d:
count=count+1
print (c,"Occured ",count,"times")
count_letter([10,20],[10,20,30,10])
count_letter('aeiou','encyclopedia')
</code></pre>
| 0 | 2016-10-09T07:39:07Z | [
"python",
"sequence",
"counting",
"seed"
] |
How to select a single JSON object out of several and navigate its hierarchy in python | 39,940,873 | <p>I have a webpage that contains several javascript elements. I only want to access one, named <code>SOURCE.pdp.propertyJSON</code>, and access the attributes in a PYTHONIC manner.</p>
<p>An edited (for the sake of readability) version of the HTML sourcecode is below; following is my python code.</p>
<p>Any pointers... | 0 | 2016-10-09T06:55:11Z | 39,943,498 | <p>You can load the data as a dict using json.loads:</p>
<pre><code>from bs4 import BeautifulSoup as bsoup
import re
from json import loads
source = """<script type="text/javascript"> SOURCE = SOURCE || {};
SOURCE.pdp = SOURCE.pdp || {};
SOURCE.pdp.propertyJSON = { "neighborhood": "Westwood", "neighbo... | 0 | 2016-10-09T12:14:36Z | [
"javascript",
"python",
"json",
"beautifulsoup"
] |
Plotting over groups of values in Python | 39,940,958 | <p>I have a dataframe that looks like this. </p>
<pre><code> country age new_user
298408 UK 32 1
193010 US 37 0
164494 UK 17 0
28149 US 34 0
297080 China 29 1
</code></pre>
<p>I want to plot the count of new_users for the... | 0 | 2016-10-09T07:07:41Z | 39,947,623 | <pre><code>import seaborn as sns
from pandas import DataFrame
from matplotlib.pyplot import show, legend
d = {"country": ['UK','US','US','UK','PRC'],
"age": [32, 37, 17, 34, 29],
"new_user": [1, 0, 0, 0,1]}
df = DataFrame(d)
bins = range(0, 100, 10)
ax = sns.distplot(df.age[df.new_user==1],
... | 0 | 2016-10-09T19:25:12Z | [
"python",
"matplotlib",
"plot",
"seaborn",
"python-ggplot"
] |
Create sparse matrix for two columns in a Pandas Dataframe | 39,941,060 | <p>I am trying to create a sparse matrix out of a Pandas Dataset (>10Gb)</p>
<p>Assume I have a dataset of the type</p>
<p>Table: Class</p>
<pre><code> student |teacher
---------------------
0 | abc | a
1 | def | g
</code></pre>
<p>And I have a list of students </p>
<pre><code>students = [ "abc", "d... | 1 | 2016-10-09T07:22:52Z | 39,942,704 | <p>You can convert the columns to category type and then use the <code>codes</code> to create the <code>coo_matrix</code> object:</p>
<pre><code>import numpy as np
import string
import random
import pandas as pd
from scipy import sparse
lowercase = list(string.ascii_lowercase)
students = np.random.choice(lowercase, ... | 1 | 2016-10-09T10:44:17Z | [
"python",
"pandas",
"matrix",
"scipy",
"sparse-matrix"
] |
pycharm can't complete remote interpreter setup for Docker | 39,941,116 | <p>I'm new to Docker. I'm using Docker & docker-compose, going through a flask tutorial. The base docker image is python 2.7 slim.
It's running on Linux. docker 1.11.2
The application is working fine.
I want to get pycharm pro connecting to the remote interpreter, something I have never done before. </p>
<p>I fo... | 0 | 2016-10-09T07:30:37Z | 39,960,909 | <p><strong>I - docker-compose up</strong></p>
<p>I think PyCharm will run <code>docker-compose up</code>, have you try to run this command first in your terminal (from where your <code>docker-compose.yml</code> is) ?</p>
<p>Maybe if some errors occur, you will get more info in your terminal.</p>
<p><strong>II - pych... | 0 | 2016-10-10T14:43:34Z | [
"python",
"docker",
"pycharm"
] |
pycharm can't complete remote interpreter setup for Docker | 39,941,116 | <p>I'm new to Docker. I'm using Docker & docker-compose, going through a flask tutorial. The base docker image is python 2.7 slim.
It's running on Linux. docker 1.11.2
The application is working fine.
I want to get pycharm pro connecting to the remote interpreter, something I have never done before. </p>
<p>I fo... | 0 | 2016-10-09T07:30:37Z | 39,971,120 | <p>I'm not using docker-machine
The problem was that TCP access to the docker API is not established by default under ubuntu 16.04. </p>
<p>There are suggestions to enable TCP/IP access.</p>
<p>However, JetBrains gave me the simplest solution:</p>
<blockquote>
<p>If you are using Linux it is most likely that Docke... | 0 | 2016-10-11T05:44:41Z | [
"python",
"docker",
"pycharm"
] |
Don't show zero values on 2D heat map | 39,941,128 | <p>I want to plot a 2D map of a sillicon wafer dies. Hence only the center portion have values and corners have the value 0. I'm using matplotlib's plt.imshow to obtain a simple map as follows:</p>
<pre><code>data = np.array([[ 0. , 0. , 1. , 1. , 0. , 0. ],
[ 0. , 1. , 1. , 1. , 1. , 0. ],
[ 1... | 4 | 2016-10-09T07:31:56Z | 39,941,795 | <p>There are two ways to get rid of the dark blue corners:</p>
<p>You can flag the data with zero values:</p>
<pre><code>data[data == 0] = np.nan
plt.imshow(data, interpolation = 'none', vmin = 0)
</code></pre>
<p>Or you can create a masked array for <code>imshow</code>:</p>
<pre><code>data_masked = np.ma.masked_wh... | 3 | 2016-10-09T09:01:10Z | [
"python",
"matplotlib"
] |
Issue while running "lektor server" command on windows | 39,941,130 | <p>Python version : 2.7</p>
<p>Showing the following error on lektor server command</p>
<pre><code>Traceback (most recent call last):
File "/Users/item4/Projects/lektor/lektor/devserver.py", line 49, in build
builder.prune()
File "/Users/item4/Projects/lektor/lektor/builder.py", line 1062, in prune
for af... | 1 | 2016-10-09T07:32:09Z | 39,941,457 | <p>Finally I got the answer. It may helpful</p>
<p>I have edited /Users/item4/Projects/lektor/lektor/builder.py and added a single line</p>
<pre><code>con.text_factory = lambda x: unicode(x, 'utf-8', 'ignore')
</code></pre>
<p>after the following line</p>
<pre><code>con = sqlite3.connect(self.buildstate_database_fi... | 1 | 2016-10-09T08:14:58Z | [
"python",
"lektor"
] |
fast Python IPv6 compaction | 39,941,174 | <p>I'm trying to write some code that can quickly return a properly compacted IPv6 address. I've tried...</p>
<pre><code>socket.inet_pton(socket.AF_INET6,socket.inet_PTON(socket.AF_INET6,address))
ipaddress.IPv6Address(address)
IPy.IP(address)
</code></pre>
<p>...listed from faster to slower in their speed of handlin... | 2 | 2016-10-09T07:38:30Z | 39,943,161 | <p>Just use <code>socket</code> functions. The first line of code in your question is almost 10 times faster than your string manipulations:</p>
<pre><code>from socket import inet_ntop, inet_pton, AF_INET6
def compact1(addr, inet_ntop=inet_ntop, inet_pton=inet_pton, AF_INET6=AF_INET6):
return inet_ntop(AF_INET6, i... | 0 | 2016-10-09T11:39:12Z | [
"python",
"python-3.x"
] |
How is the .pop() method able to redefine a variable by only being the value of another? | 39,941,196 | <p>So in python if you create your <code>list</code>, then a new variable, <code>reject_list</code> and assign it the <code>.pop()</code> method, it changes the value in the previous <code>list</code> variable. </p>
<pre><code>list = ['item', 'thing', 'piece']
reject_list = list.pop()
print(list)
['item', 'thing']
</... | -1 | 2016-10-09T07:41:33Z | 39,941,252 | <p>Your explanation of what you're seeing is not correct. The change in the value of <code>list</code> has nothing to do with you assigning the result of <code>list.pop()</code> to <code>reject_list</code>.</p>
<p>Python is an object-based language which means the basic element of data in it are <em>objects</em>, whic... | 1 | 2016-10-09T07:48:22Z | [
"python",
"methods"
] |
How is the .pop() method able to redefine a variable by only being the value of another? | 39,941,196 | <p>So in python if you create your <code>list</code>, then a new variable, <code>reject_list</code> and assign it the <code>.pop()</code> method, it changes the value in the previous <code>list</code> variable. </p>
<pre><code>list = ['item', 'thing', 'piece']
reject_list = list.pop()
print(list)
['item', 'thing']
</... | -1 | 2016-10-09T07:41:33Z | 39,941,606 | <p>The answer is that the <code>list.pop()</code> method specifically modifies the object; <strong>removes</strong> and returns an item from the list. <code>str.title()</code> returns a <em>version</em> of the string in title case, but does not modify the string itself.</p>
<p>It's also noteworthy that strings are imm... | 0 | 2016-10-09T08:35:56Z | [
"python",
"methods"
] |
Why my subprocess generated by pool.apply_async() always run as MainProcess? | 39,941,272 | <p>My env is Python2.7.I am very fuzzed,I run my apply_async(test_func),and I let the test_func print the current process_name.As like:</p>
<pre><code>q = Queue(maxsize=20) #multiprocessing.Queue
def test_func(queue):
print 'Process'
print multiprocessing.current_process()
if __name__ == '__main__':
pool... | 0 | 2016-10-09T07:49:51Z | 39,941,754 | <p>Occasionally,I know that I should use <code>apply_async(test_func, (i,))</code>,and this is a mistake for me.</p>
<p>But what very odd is that,when I usse <code>apply_async(test_func, (q,))</code>,it will not work.the <code>q</code> is multiprocessing.Queue().If I remove it or substitute for any other except Queue ... | 0 | 2016-10-09T08:57:24Z | [
"python"
] |
Why my subprocess generated by pool.apply_async() always run as MainProcess? | 39,941,272 | <p>My env is Python2.7.I am very fuzzed,I run my apply_async(test_func),and I let the test_func print the current process_name.As like:</p>
<pre><code>q = Queue(maxsize=20) #multiprocessing.Queue
def test_func(queue):
print 'Process'
print multiprocessing.current_process()
if __name__ == '__main__':
pool... | 0 | 2016-10-09T07:49:51Z | 39,941,771 | <p>First, your <code>test_func</code> function has no <code>return</code> statement, so it returns <code>None</code>:</p>
<pre><code>def test_func(queue):
print 'Process'
print multiprocessing.current_process()
</code></pre>
<p>Inserting this into an interactive Python:</p>
<pre><code>>>> import mul... | 1 | 2016-10-09T08:59:07Z | [
"python"
] |
pycairo: justify text-align | 39,941,286 | <p>I use python bindings to Cairo to render text.</p>
<p>My question is: Is it possible to render a string using something like <code>text-align: justify</code>? Suppose I have fixed width and I want to print a paragraph.</p>
| 1 | 2016-10-09T07:51:47Z | 39,942,325 | <p>Solved [using pangocairo]:</p>
<pre><code>import pygtk
import cairo
import pango
import pangocairo
...
layout = pangocairo_context.create_layout()
...
layout.set_width(...)
layout.set_wrap(pango.WRAP_WORD)
layout.set_justify(True)
layout.set_text(text)
</code></pre>
| 1 | 2016-10-09T10:05:46Z | [
"python",
"text",
"alignment",
"cairo",
"justify"
] |
Create DataFrame from multiple Series | 39,941,321 | <p>I have 2 <code>Series</code>, given by:</p>
<pre><code>import pandas as pd
r = pd.Series()
for i in range(0, 10):
r = r.set_value(i,i*3)
r.name = 'rrr'
s = pd.Series()
for i in range(0, 10):
s = s.set_value(i,i*5)
s.name = 'sss'
</code></pre>
<p>How to I create a <code>DataFrame</code> from them?</p>
| 0 | 2016-10-09T07:55:08Z | 39,941,338 | <p>You can use pd.concat:</p>
<pre><code>pd.concat([r, s], axis=1)
Out:
rrr sss
0 0 0
1 3 5
2 6 10
3 9 15
4 12 20
5 15 25
6 18 30
7 21 35
8 24 40
9 27 45
</code></pre>
<p>Or the DataFrame constructor:</p>
<pre><code>pd.DataFrame({'r': r, 's': s})
Out:
r s
0 ... | 0 | 2016-10-09T07:57:48Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
python: loop a list of list and assign value inside the loop | 39,941,393 | <p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p>
<pre><code>alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = 1
print(alist)
alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = item.append(10)
print(alist)
</code></pre>
| 5 | 2016-10-09T08:04:49Z | 39,941,425 | <p>Referencing <a href="https://docs.python.org/3/reference/compound_stmts.html#the-for-statement" rel="nofollow">the document</a>: </p>
<blockquote>
<p>The for-loop makes assignments to the variables(s) in the target list.
This overwrites all previous assignments to those variables including
those made in the s... | 1 | 2016-10-09T08:11:30Z | [
"python"
] |
python: loop a list of list and assign value inside the loop | 39,941,393 | <p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p>
<pre><code>alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = 1
print(alist)
alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = item.append(10)
print(alist)
</code></pre>
| 5 | 2016-10-09T08:04:49Z | 39,941,443 | <p>Are you forgetting that <code>list.append()</code> does not return the list itself but actually modifies the list in place?</p>
<p><code>item = 1</code> does as expected. For the rest of the for-loop, item is now <code>1</code>, and not the list it originally was. It won't reassign what <code>item</code> is, that's... | 2 | 2016-10-09T08:13:29Z | [
"python"
] |
python: loop a list of list and assign value inside the loop | 39,941,393 | <p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p>
<pre><code>alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = 1
print(alist)
alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = item.append(10)
print(alist)
</code></pre>
| 5 | 2016-10-09T08:04:49Z | 39,941,451 | <p>When you write</p>
<pre><code>for item in alist:
</code></pre>
<p>You are actually creating a copy of each item in <code>liast</code> in the <code>item</code> variable, and you are <em>not</em> getting a reference to <code>item</code>.</p>
<p>However, <code>append</code> changes the list in-place and doesn't retu... | 0 | 2016-10-09T08:14:22Z | [
"python"
] |
python: loop a list of list and assign value inside the loop | 39,941,393 | <p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p>
<pre><code>alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = 1
print(alist)
alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = item.append(10)
print(alist)
</code></pre>
| 5 | 2016-10-09T08:04:49Z | 39,941,454 | <p>The <code>=</code> operator does not make any change in the second code, using <code>.append</code> causes changes in <code>alist</code>. Use following line as the third line in the second code. You will see the same result:</p>
<pre><code>item.append(10)
</code></pre>
<p>In the first code <code>item</code> point ... | 2 | 2016-10-09T08:14:37Z | [
"python"
] |
python: loop a list of list and assign value inside the loop | 39,941,393 | <p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p>
<pre><code>alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = 1
print(alist)
alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = item.append(10)
print(alist)
</code></pre>
| 5 | 2016-10-09T08:04:49Z | 39,941,472 | <p>In the first example <code>item</code> is bound to each element in list <code>alist</code>, and then <code>item</code> is <em>rebound</em> to the integer <code>1</code>. This does not change the element of the list - it merely <em>rebinds</em> the name <code>item</code> to the <code>int</code> object <code>1</code>.... | 4 | 2016-10-09T08:16:19Z | [
"python"
] |
python: loop a list of list and assign value inside the loop | 39,941,393 | <p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p>
<pre><code>alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = 1
print(alist)
alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = item.append(10)
print(alist)
</code></pre>
| 5 | 2016-10-09T08:04:49Z | 39,941,492 | <p>It's pointer variable in python.</p>
<p>The first example:</p>
<pre><code>for item in alist:
item = 1
</code></pre>
<p>each item is pointing to each _item in alist but suddenly you change the item value, not the of the value of the _item in alist, as a result nothing change to alist</p>
<p>The second example:... | 2 | 2016-10-09T08:20:06Z | [
"python"
] |
python: loop a list of list and assign value inside the loop | 39,941,393 | <p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p>
<pre><code>alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = 1
print(alist)
alist = [[1,2], [3,4], [5,6]]
for item in alist:
item = item.append(10)
print(alist)
</code></pre>
| 5 | 2016-10-09T08:04:49Z | 39,942,033 | <p>This is a somewhat unintuitive behavor of variables. It happens because, in Python, variables are always references to values.</p>
<h1>Boxes and tags</h1>
<p>In some languages, we tend to think about variables as "boxes" where we put values; in Python, however, they are references, and behave more like tags or "ni... | 5 | 2016-10-09T09:28:59Z | [
"python"
] |
ImageView or VideoView, which should I display my streaming "video" in android? | 39,941,465 | <p>I have an android App (native) which streaming video from other camera. </p>
<p>I created a simple server with <code>python</code>, <code>flask</code>, and <code>opencv</code> (to process the video)</p>
<pre><code>from mockCamera import VideoCamera;
import time
import argparse
from flask import Flask, render_temp... | 0 | 2016-10-09T08:15:50Z | 39,955,287 | <p>You would usually use a VideoView to show a video, setting it up with the URL to the video on your server.</p>
<p>For example:</p>
<pre class="lang-js prettyprint-override"><code> //Create the video player and set the video path
videoPlayerView = (VideoView) rootView.findViewById(R.id.video_area);
... | 0 | 2016-10-10T09:32:30Z | [
"android",
"python",
"opencv",
"video",
"streaming"
] |
Python: Cross Connecting a loop within a loop | 39,941,515 | <p>Just for practice, I am trying to write a function in python which contains a loop within a loop. However I get an <code>IndexError: list index out of range</code></p>
<p>Here's the function</p>
<pre><code>def merge(A,B):
c = []
k = 0
i = 0
j = 0
while i < len(A):
while j < len(B)... | 0 | 2016-10-09T08:22:57Z | 39,941,574 | <p>You are incrementing i or j in the if statement in the middle - with your sample data, if i is already <code>len(A)-1</code>, i.e. 2 and is incremented when j < <code>len(B)-1</code>, because the <code>while j < len(B)</code> will continue to execute, and on the next time round the loop of course <code>i</code... | 3 | 2016-10-09T08:32:15Z | [
"python",
"python-2.7",
"python-3.x"
] |
Django and requirements | 39,941,604 | <p>Im a bit stuck. I can't get this configuration to work and I don't know why. The code I site below is from <a href="https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04" rel="nofollow">https://www.digitalocean.com/community/tutorials/how-to-serv... | 0 | 2016-10-09T08:35:39Z | 39,941,911 | <p>in your /etc/apache2/apache2.conf file add </p>
<pre><code><Directory /home/dimitris/mysite>
AllowOverride All
Require all granted
</Directory>
</code></pre>
<p>your site.conf file in the example i load mysite with virtualenv</p>
<pre><code>WSGIDaemonProcess myp user=dimitris group=dimitris t... | 0 | 2016-10-09T09:13:50Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
Django and requirements | 39,941,604 | <p>Im a bit stuck. I can't get this configuration to work and I don't know why. The code I site below is from <a href="https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04" rel="nofollow">https://www.digitalocean.com/community/tutorials/how-to-serv... | 0 | 2016-10-09T08:35:39Z | 39,942,763 | <p>Either you create your project at /home/user or change the apache conf file by appending an extra /myproject wherever you are specifying the path as below:</p>
<pre><code>Alias /static /home/user/myproject/myproject/static
<Directory /home/user/myproject/myproject/static>
Require all granted
</Director... | 0 | 2016-10-09T10:52:53Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
Python classes and objects, How to display contents of a list | 39,941,609 | <p>So below is my coding and whenever I click on the button "Show average mark" it gives me an error </p>
<pre><code>"Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Mohammed\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.fun... | -2 | 2016-10-09T08:36:12Z | 39,941,637 | <p>In your <code>__init__</code> method, you need to change <code>studentList = []</code> to <code>self.studentList = []</code></p>
| 1 | 2016-10-09T08:40:38Z | [
"python",
"list"
] |
Python classes and objects, How to display contents of a list | 39,941,609 | <p>So below is my coding and whenever I click on the button "Show average mark" it gives me an error </p>
<pre><code>"Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Mohammed\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.fun... | -2 | 2016-10-09T08:36:12Z | 39,941,646 | <p>When you do:</p>
<pre><code>self.studentList.append([self.n, self.num, self.hw])
</code></pre>
<p>studentList must be defined/assigned value before.</p>
<p>In your code, what you did is:</p>
<pre><code>def __init__(self, master):
self.master = master
master.title("student markList")
studentList = ... | 1 | 2016-10-09T08:41:22Z | [
"python",
"list"
] |
Expanding function based on array length | 39,941,644 | <p>I have the following code, which I would like to make responsive to the initial array that is passed to it (letters). Currently it can handle letters <= 3, however I would like to make it expandable to n.</p>
<p>In this example, if the array only contains two entries ["a", " b"], it would trigger the second if s... | 0 | 2016-10-09T08:41:13Z | 39,942,027 | <p>Maybe try something like this?</p>
<pre><code>import itertools
import numpy as np
#variable length
letters = ["a", "b", "c", "d", "e", "f", "g"]
n = len(letters) # Max limit for each element, ie. limit of 2 from [a, b], for k = 2 is ['a00 b00', 'a00 b10', 'a10 b00', 'a10 b10']
k = 3 # Number of elements we want t... | 1 | 2016-10-09T09:28:00Z | [
"python",
"arrays",
"itertools"
] |
Expanding function based on array length | 39,941,644 | <p>I have the following code, which I would like to make responsive to the initial array that is passed to it (letters). Currently it can handle letters <= 3, however I would like to make it expandable to n.</p>
<p>In this example, if the array only contains two entries ["a", " b"], it would trigger the second if s... | 0 | 2016-10-09T08:41:13Z | 39,943,143 | <p>Here's the smallest change you could make - replace your <code>if</code> statement with:</p>
<pre><code>variable_s[x] = ''.join(
letter+str(format(p_i/(increment)**(-1.0),'.2f')).replace("0.", "")
for letter, p_i in zip(letters, p)
)
</code></pre>
<p>Other notes:</p>
<ul>
<li><code>p[1]/(increment)**(-1.0... | 1 | 2016-10-09T11:37:17Z | [
"python",
"arrays",
"itertools"
] |
Numpy Sum Performance | 39,941,716 | <p>I made a plot of the time required for numpy.sum() to sum elements of an array. Here is my plot:</p>
<p><a href="http://i.stack.imgur.com/MSSpd.png" rel="nofollow"><img src="http://i.stack.imgur.com/MSSpd.png" alt="Numpy sum performance"></a></p>
<p>The x axis denotes the number of entries that have been summed.
... | -1 | 2016-10-09T08:51:07Z | 39,942,707 | <p>When you measure performance of some code, it is advisable to run it multiple times and take the average to avoid skewed results.</p>
<p>By default, timeit module execute the code for 1 million times. I am not seeing the issue you mentioned even if I run it only for 100 times. Here is an equivalent version of your ... | -1 | 2016-10-09T10:44:36Z | [
"python",
"performance",
"numpy",
"sum"
] |
TypeError for definied variable in python | 39,942,031 | <p>I'm trying to make a music player that allows a song to be put into the shell and is then played however, I'm having an issue with a type error in <code>class Notes():</code> and I can't figure out why.</p>
<pre><code>import winsound
import time
length = 125
class Notes():
def processNote(note):
if(no... | 1 | 2016-10-09T09:28:27Z | 39,942,086 | <p>And if I can say something, instead of</p>
<pre><code>class Notes():
def processNote(note):
if(note == 'C'):return Notes.processNote(262)
if(note == 'D'):return Notes.processNote(294)
if(note == 'D5'):return Notes.processNote(587)
(thousands IFs)
</code></pre>
<p>You could use t... | 1 | 2016-10-09T09:36:14Z | [
"python",
"music",
"typeerror"
] |
TypeError for definied variable in python | 39,942,031 | <p>I'm trying to make a music player that allows a song to be put into the shell and is then played however, I'm having an issue with a type error in <code>class Notes():</code> and I can't figure out why.</p>
<pre><code>import winsound
import time
length = 125
class Notes():
def processNote(note):
if(no... | 1 | 2016-10-09T09:28:27Z | 39,942,097 | <p>Currently, the function <code>processNote()</code> returns <code>None</code> for any valid input, because you are calling it twice instead of just returning the value. It may be helpful to look at how your code will be processed to understand why this happens:</p>
<p>Imagine <code>processNote()</code> is called wit... | 0 | 2016-10-09T09:37:36Z | [
"python",
"music",
"typeerror"
] |
python: adding data as string in mysql gives weird error | 39,942,061 | <p>I'm having a weird problem with a piece of python code.</p>
<p>The idea how it should work:
1. a barcode is entered (now hardcode for the moment);
2. barcode is looked up in local mysqldb, if not found, the barcode is looked up via api from datakick, if it's not found there either, step 3
3. i want to add the barco... | 0 | 2016-10-09T09:32:08Z | 39,942,218 | <pre><code>sql = "select * from Voorraad where Id=%s" % barcode
</code></pre>
<p>Your problem is that you are missing quotes for your ID. Change that line above to this:</p>
<pre><code>sql = "select * from Voorraad where Id='%s'" % barcode
</code></pre>
| 0 | 2016-10-09T09:52:26Z | [
"python",
"mysql"
] |
python: adding data as string in mysql gives weird error | 39,942,061 | <p>I'm having a weird problem with a piece of python code.</p>
<p>The idea how it should work:
1. a barcode is entered (now hardcode for the moment);
2. barcode is looked up in local mysqldb, if not found, the barcode is looked up via api from datakick, if it's not found there either, step 3
3. i want to add the barco... | 0 | 2016-10-09T09:32:08Z | 39,942,224 | <p>I believe that you miss the single quotation mark for all your string placeholders. That would explain why it works with numbers but not with strings.</p>
<p>I didn't tested it, but in my opinion your SQL statement should look like:</p>
<pre><code>sql = "insert into Voorraad (Id, NaamProduct,HoeveelHeidProduct) va... | 0 | 2016-10-09T09:53:17Z | [
"python",
"mysql"
] |
Strange merging - list of words | 39,942,069 | <p>I have a list of lists of words like this:</p>
<pre><code>texts=[['word1', 'word2', 'word3']['word4', 'word5', 'word6']]
</code></pre>
<p>My desired output would be:</p>
<pre><code>texts=[['word1 word2 word3']['word4 word5 word6']
</code></pre>
<p>This is what I tried:</p>
<p>for item in texts:</p>
<pre><code>... | 0 | 2016-10-09T09:33:16Z | 39,942,081 | <p>Just pass the sub lists to <code>join</code>:</p>
<pre><code>In [62]: [[' '.join(sub_list)] for sub_list in texts]
Out[62]: [['word1 word2 word3'], ['word4 word5 word6']]
</code></pre>
| 2 | 2016-10-09T09:34:58Z | [
"python",
"list"
] |
Np.concatenate ValueError: all the input arrays must have same number of dimensions | 39,942,117 | <p>I am trying to concatenate but ended up with the mentioned error. Am also new to python. </p>
<pre><code>def cving(x1, x2, x3, x4, x5, y1, y2, y3, y4, y5, ind1, ind2, ind3, ind4, ind5, num):
if num == 0:
xwhole = np.concatenate((x2, x3, x4, x5), axis=0)
yhol = np.concatenate((y2, y3, y4, y5), axis=0)
r... | 0 | 2016-10-09T09:39:47Z | 39,942,604 | <p>The error message says it all: <code>x1</code> is 2D while <code>x4</code> is 1D. Concatenating these makes no sense. You need to make sure all concatenated arrays are of same dimension, e.g. by adding a dimension to all 1D arrays</p>
<pre><code>x4 = x4[:, np.newaxis]
</code></pre>
| 2 | 2016-10-09T10:34:05Z | [
"python",
"np"
] |
How can I make an organized file into dictionary in python3? | 39,942,189 | <p>I'm trying to make the file:</p>
<pre><code>c;f
b;d
a;c
c;e
d;g
a;b
e;d
f;g
f;d
</code></pre>
<p>Into a dict like</p>
<pre><code>{'e': {'d'}, 'a': {'b', 'c'}, 'd': {'g'}, 'b': {'d'}, 'c': {'f', 'e'}, 'f': {'g', 'd'}}.
</code></pre>
<p>The code I'm using now is like below</p>
<pre><code>def read_file(file : open... | 3 | 2016-10-09T09:48:54Z | 39,942,230 | <p>Dictionaries overwrite the previous key, Use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict here</a> </p>
<pre><code>>>> import collections
>>> answer = collections.defaultdict(set)
>>> for line in f:
... k, v = line... | 3 | 2016-10-09T09:53:36Z | [
"python",
"string",
"python-3.x",
"dictionary",
"set"
] |
Problems resampling pandas time series with time gap between indices | 39,942,269 | <p>I want to resample the pandas series </p>
<pre><code>import pandas as pd
index_1 = pd.date_range('1/1/2000', periods=4, freq='T')
index_2 = pd.date_range('1/2/2000', periods=3, freq='T')
series = pd.Series(range(4), index=index_1)
series=series.append(pd.Series(range(3), index=index_2))
print series
>>>200... | 0 | 2016-10-09T09:59:00Z | 39,942,544 | <p><code>resample()</code> is not the right function for your purpose.</p>
<p>try this:</p>
<pre><code>series[series.index.minute % 2 == 0]
</code></pre>
| 1 | 2016-10-09T10:27:56Z | [
"python",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.