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 |
|---|---|---|---|---|---|---|---|---|---|
python to split a long string into different rows | 39,710,389 | <p><code>123|china|jack|342|usa|Nick|324345|spin|Amy</code></p>
<p>I want the end result like this(I know I need a new line for every 3 element):</p>
<pre><code>123,china,jack
342,usa,Nick
324345,spin,Amy
</code></pre>
<p>Thank you</p>
| -1 | 2016-09-26T19:00:48Z | 39,710,547 | <p>Try that:</p>
<pre><code>x = '123|china|jack|342|usa|Nick|324345|spin|Amy'
l = x.split('|')
new_l = [l[i:i+3] for i in range(0,len(l),3)]
</code></pre>
<p>This will give you:</p>
<pre><code>>>> for i in new_l:
... print ','.join(i)
...
123,china,jack
342,usa,Nick
324345,spin,Amy
</code></pre>
<bloc... | 2 | 2016-09-26T19:09:53Z | [
"python"
] |
python to split a long string into different rows | 39,710,389 | <p><code>123|china|jack|342|usa|Nick|324345|spin|Amy</code></p>
<p>I want the end result like this(I know I need a new line for every 3 element):</p>
<pre><code>123,china,jack
342,usa,Nick
324345,spin,Amy
</code></pre>
<p>Thank you</p>
| -1 | 2016-09-26T19:00:48Z | 39,711,099 | <p>It could be done with one <code>print</code> statement</p>
<pre><code>>>> d = '123|china|jack|342|usa|Nick|324345|spin|Amy'
>>> l = d.split('|')
>>> print(*list(map(lambda v: ','.join(v),[l[x: x+3] for x in range(0, len(l), 3)])), sep='\n')
123,china,jack
342,usa,Nick
324345,spin,Amy
</co... | 1 | 2016-09-26T19:42:38Z | [
"python"
] |
How can I install a tweepy package via pip? | 39,710,454 | <p>Can't get pip to work; trying to install Tweepy per this <a href="http://mark-kay.net/2013/12/18/collecting-tweets-using-python/" rel="nofollow">article</a>.</p>
<p>This <a href="http://stackoverflow.com/questions/39060397/how-can-i-install-twilio-package-via-pip/39710119#39710119">thread</a> managed to solve it fo... | 0 | 2016-09-26T19:03:58Z | 39,710,762 | <p>Are you using pip install command inside of the python prompt?
If yes then you need to type it directly into command prompt.Open command prompt and type.</p>
<pre><code>pip install tweepy
</code></pre>
| 0 | 2016-09-26T19:23:32Z | [
"python",
"pip",
"package-managers"
] |
Python: Why does return not actually return anything that I can see | 39,710,576 | <p>I have the following code:</p>
<pre><code>def is_prime(n):
limit = (n**0.5) + 1
q = 2
p = 1
while p != 0 and q < limit:
p = n % q
q = q + 1
if p == 0 and n != 2:
return 'false'
else:
return 'true'
</code></pre>
<p>But when I send in an inte... | -1 | 2016-09-26T19:11:55Z | 39,710,691 | <p>If you want to print something to the console you have to use a print statement. The return keyword means that you can use this value in a piece of code that calls this function. So to print something:</p>
<pre><code>print (x)
</code></pre>
<p>For more information about the print statement see: <a href="https://en... | 1 | 2016-09-26T19:18:33Z | [
"python",
"python-2.7"
] |
Python: Why does return not actually return anything that I can see | 39,710,576 | <p>I have the following code:</p>
<pre><code>def is_prime(n):
limit = (n**0.5) + 1
q = 2
p = 1
while p != 0 and q < limit:
p = n % q
q = q + 1
if p == 0 and n != 2:
return 'false'
else:
return 'true'
</code></pre>
<p>But when I send in an inte... | -1 | 2016-09-26T19:11:55Z | 39,710,877 | <p>Nothing is wrong, but you have to print out the return of your function.
Like this:</p>
<pre><code>def Test():
if True:
return "Hi"
print(Test())
</code></pre>
<p>In this case python will show "Hi" in your console.</p>
| 1 | 2016-09-26T19:30:22Z | [
"python",
"python-2.7"
] |
Confusion about Python Functions and Lists | 39,710,632 | <p>I am trying to create a function to remove an item from the passed list either by a specified index, or item passed. </p>
<p>If the user wishes to remove an item from the list using an index, the third argument passed will be <code>âindexâ</code>, if the user wishes to remove the first item found in the list us... | -1 | 2016-09-26T19:15:31Z | 39,710,833 | <p>You really need to work on your questionsmithing skills. It's very difficult to understand what you are trying to accomplish. After making about half a dozen assumptions, I think this is what you are trying to do:</p>
<pre><code>def listRemover(mylist,index_or_name,mytype):
if mytype == "index":
del myl... | 1 | 2016-09-26T19:27:43Z | [
"python"
] |
Confusion about Python Functions and Lists | 39,710,632 | <p>I am trying to create a function to remove an item from the passed list either by a specified index, or item passed. </p>
<p>If the user wishes to remove an item from the list using an index, the third argument passed will be <code>âindexâ</code>, if the user wishes to remove the first item found in the list us... | -1 | 2016-09-26T19:15:31Z | 39,710,952 | <blockquote>
<p>It appears that I need to create a function to do this, and then pass in my list, the index/item, etc.) but I am very lost on this part.</p>
</blockquote>
<p><a href="https://www.google.com/webhp#q=define+function+python" rel="nofollow">Google it!</a> (query = "define function python")</p>
<p>Show y... | 1 | 2016-09-26T19:34:09Z | [
"python"
] |
Confusion about Python Functions and Lists | 39,710,632 | <p>I am trying to create a function to remove an item from the passed list either by a specified index, or item passed. </p>
<p>If the user wishes to remove an item from the list using an index, the third argument passed will be <code>âindexâ</code>, if the user wishes to remove the first item found in the list us... | -1 | 2016-09-26T19:15:31Z | 39,711,509 | <p>The question (I think) is: "<em>If the user wishes to remove an item from the list using an index, the third argument passed will be âindexâ, if the user wishes to remove the first item found in the list using the item passed, the second argument will be â{item}â</em>"</p>
<p>The purpose of this exercise ... | 1 | 2016-09-26T20:07:16Z | [
"python"
] |
Pycharm does not find module with one interpreter but does with another, why? | 39,710,675 | <p>I am trying to install a package called "quantecon" through PyCharm. If I have Python 3.5 as an interpreter then I can find the package in the settings menu. But I need to run Anaconda, it has a bunch of other packages I need like scipy, numpy, etc. Once I install Anaconda and use it as the interpreter (it runs on P... | 1 | 2016-09-26T19:17:49Z | 39,711,203 | <p>Inside PyCharm, in Ubuntu, go to <code>File -> Settings -> Project -> Project Interpreter</code> and change the interpreter. If Anaconda is not there, click on the gear, add local and then go to <code>/home/user/anaconda2/bin/python</code></p>
| 0 | 2016-09-26T19:49:17Z | [
"python",
"module",
"pycharm",
"package-managers"
] |
Pycharm does not find module with one interpreter but does with another, why? | 39,710,675 | <p>I am trying to install a package called "quantecon" through PyCharm. If I have Python 3.5 as an interpreter then I can find the package in the settings menu. But I need to run Anaconda, it has a bunch of other packages I need like scipy, numpy, etc. Once I install Anaconda and use it as the interpreter (it runs on P... | 1 | 2016-09-26T19:17:49Z | 39,711,232 | <p>Did you change the interpreter in PyCharm?</p>
<p>If not, go to File -> Settings -> Project -> Project Interpreter and change the interpreter to the one in Anaconda. It should find the package, unless it's installed in a weird location.</p>
<p>If you don't have the Anaconda interpreter in the list of available int... | 0 | 2016-09-26T19:51:10Z | [
"python",
"module",
"pycharm",
"package-managers"
] |
Pycharm does not find module with one interpreter but does with another, why? | 39,710,675 | <p>I am trying to install a package called "quantecon" through PyCharm. If I have Python 3.5 as an interpreter then I can find the package in the settings menu. But I need to run Anaconda, it has a bunch of other packages I need like scipy, numpy, etc. Once I install Anaconda and use it as the interpreter (it runs on P... | 1 | 2016-09-26T19:17:49Z | 39,711,364 | <p>I think you want to install quantecon to your anaconda:</p>
<p><a href="https://anaconda.org/pypi/quantecon" rel="nofollow">https://anaconda.org/pypi/quantecon</a></p>
<p>(make sure you use anaconda's version of pip, not system pip)</p>
<p>You could also try to create a new Conda environment that has quantecon in... | 0 | 2016-09-26T19:59:01Z | [
"python",
"module",
"pycharm",
"package-managers"
] |
Infer the length of a sequence using the CIGAR | 39,710,796 | <p>To give you a bit of context: I am trying to convert a sam file to bam</p>
<pre><code>samtools view -bT reference.fasta sequences.sam > sequences.bam
</code></pre>
<p>which exits with the following error</p>
<pre><code>[E::sam_parse1] CIGAR and query sequence are of different length
[W::sam_read1] parse error ... | 4 | 2016-09-26T19:25:17Z | 39,812,985 | <p>I suspect the reason there isn't a tool to fix this problem is because there is no general solution, aside from performing the alignment again using software that does not exhibit this problem. In your example, the query sequence aligns perfectly to the reference and so in that case the CIGAR string is not very inte... | 0 | 2016-10-02T01:18:55Z | [
"python",
"module",
"bioinformatics",
"samtools"
] |
pd.read_html() imports a list rather than a dataframe | 39,710,903 | <p>I used <code>pd.read_html()</code> to import a table from a webpage but instead of structuring the data as a dataframe Python imported it as a list. How can I import the data as a dataframe? Thank you!</p>
<p>The code is the following:</p>
<pre><code>import pandas as pd
import html5lib
url = 'http://www.fdic.g... | 0 | 2016-09-26T19:31:44Z | 39,710,987 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html" rel="nofollow"><code>.read_html()</code></a> produces a <em>list of dataframes</em> (there could be multiple tables in an HTML source), get the desired one by index. In your case, there is a single dataframe:</p>
<pre><code>dfs = ... | 1 | 2016-09-26T19:36:10Z | [
"python",
"html",
"pandas"
] |
Python Iterating through Directories and Renaming | 39,710,929 | <p>I am trying to iterate through a list of subdirectories and then opening the files within that subdirectory and renaming the files to lowercase. Here is my code:</p>
<pre><code>for root, subdirs, pics in os.walk(rootdir):
for pic in pics:
if pic.endswith('.jpg'):
picpath = os.path.join(pic)
#p... | 0 | 2016-09-26T19:33:00Z | 39,711,017 | <pre><code>picpath = os.path.join(root, pic)
# ^^^^^
</code></pre>
<p>looks like it should do the job. Per <a href="https://docs.python.org/2/library/os.html#os.walk" rel="nofollow">the docs</a>,</p>
<blockquote>
<p>Note that the names in the lists contain no path components. To get a full pat... | 1 | 2016-09-26T19:38:09Z | [
"python",
"iteration",
"rename"
] |
Python Iterating through Directories and Renaming | 39,710,929 | <p>I am trying to iterate through a list of subdirectories and then opening the files within that subdirectory and renaming the files to lowercase. Here is my code:</p>
<pre><code>for root, subdirs, pics in os.walk(rootdir):
for pic in pics:
if pic.endswith('.jpg'):
picpath = os.path.join(pic)
#p... | 0 | 2016-09-26T19:33:00Z | 39,711,224 | <p>you have to append the directory name to your path or <code>os.rename</code> is unable to find the proper directory where to apply the rename.</p>
<p>That said, your conversion to lowercase complicates the task. lowercase must only be applied to the basename (that would work on Windows filesystem because case doesn... | 1 | 2016-09-26T19:50:17Z | [
"python",
"iteration",
"rename"
] |
POST related Fields Django rest Framework | 39,710,972 | <p>new at django. What I am trying to do is POSTING a model which has a OneToOneField property. How do you POST that?</p>
<p><strong>Models.py</strong></p>
<pre><code>Article(models.Model):
name=models.CharField(max_length=50)
description=models.TextField(max_length=200)
Characteristic(models.Model):
arti... | 0 | 2016-09-26T19:35:15Z | 39,731,574 | <p>Finally I was able to solve it. It is only about dictionaries.</p>
<p><strong>Method POST</strong></p>
<pre><code>def post(self,request,format=None):
serializer=CharacteristicsSerializer(data=request.data)
if serializer.is_valid():
tmp=self.get_article(pk=int(self.request.data['article']))
... | 0 | 2016-09-27T18:10:36Z | [
"python",
"django",
"django-rest-framework"
] |
How to add lines to contour plot in python `matplotlib`? | 39,710,994 | <p>I have the following function to illustrate some contour lines :</p>
<pre><code>"""
Illustrate simple contour plotting, contours on an image with
a colorbar for the contours, and labelled contours.
See also contour_image.py.
"""
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab... | 0 | 2016-09-26T19:36:44Z | 39,711,759 | <p><code>plt.plot</code> draws a two-dimensional line from a sequence of x- and y-coordinates. There's no z-coordinate associated with each point, so there's no need to pass in a third array argument. At the moment <code>plt.plot</code> is interpreting those arrays as coordinates for two separate lines, and is doing th... | 1 | 2016-09-26T20:23:50Z | [
"python",
"matplotlib",
"plot"
] |
NaiveBayes Classification in NLTK using python | 39,711,057 | <p>I have the following datasets...
<a href="http://i.stack.imgur.com/9l9nJ.png" rel="nofollow">dataset</a></p>
<p>I have load the data using this</p>
<pre><code>import numpy as np
import pandas as pd
input_file = "C:/Users/User/Documents/R/exp.csv"
df = pd.read_csv(input_file, header = 0)
</code></pre>
<p>Now, I a... | -2 | 2016-09-26T19:40:20Z | 39,712,929 | <p>You can find information on NLTK and it's workings with their <a href="http://www.nltk.org/book/" rel="nofollow">online tutorial</a>.</p>
<p>Specifically, you should look into features and classifiers, both of which can be found in <a href="http://www.nltk.org/book/ch06.html" rel="nofollow">Chapter 6</a>.</p>
<p>F... | 0 | 2016-09-26T21:45:57Z | [
"python",
"nltk",
"naivebayes"
] |
Python: random choice executing all function calls listed | 39,711,221 | <p>I'm stuck on a probably simple issue:
when using choice with functions, it seems like all of them gets executed while only one should.
Example:</p>
<pre><code>from ordereddict import OrderedDict
from random import choice
def PrintStrings():
Text = choice(["Gutentag!", "Ni hao!", "Hola!"])
print "Chosen Tex... | 1 | 2016-09-26T19:50:13Z | 39,711,325 | <p>Putting aside some strange data structures choices, you are calling a function in <code>function</code>. Remove the parenthesis' to just pass the function as an <em>object</em>.</p>
<p><code>PrintStrings()</code> -> <code>PrintStrings</code></p>
<p>Here's a possible solution to get the required output:</p>
<pre><... | 1 | 2016-09-26T19:56:51Z | [
"python",
"random",
"choice"
] |
Python: random choice executing all function calls listed | 39,711,221 | <p>I'm stuck on a probably simple issue:
when using choice with functions, it seems like all of them gets executed while only one should.
Example:</p>
<pre><code>from ordereddict import OrderedDict
from random import choice
def PrintStrings():
Text = choice(["Gutentag!", "Ni hao!", "Hola!"])
print "Chosen Tex... | 1 | 2016-09-26T19:50:13Z | 39,712,031 | <p>An object will give you a means to run code only on serialization, not on instantiation:</p>
<pre><code>class PrintStrings(object):
def __init__(self):
self.text = None
def __str__(self):
if self.text is None:
text = choice(["Gutentag!", "Ni hao!", "Hola!"])
print "Ch... | 0 | 2016-09-26T20:42:45Z | [
"python",
"random",
"choice"
] |
TypeError for bar plot with custom date range | 39,711,229 | <p>I'm attempting to display a dataframe as a bar graph with a custom date range for <code>xlim</code>. I'm able to output a graph if I select <code>kind='line'</code> but I get the following error message when attempting <code>kind='bar'</code>: </p>
<pre><code>TypeError: ufunc 'isfinite' not supported for the input ... | 2 | 2016-09-26T19:50:51Z | 39,712,085 | <p>What about an alternative approach - filtering your data <strong>before</strong> plotting?</p>
<pre><code>In [10]: df.set_index('Date').ix['2010-01-01' : '2010-01-10']
Out[10]:
Quantity
Date
2010-01-01 1
2010-01-02 0
2010-01-03 0
2010-01-04 2
2010-01-05 3
2010-01-... | 2 | 2016-09-26T20:46:35Z | [
"python",
"pandas",
"matplotlib",
"plot",
"dataframe"
] |
How does a descriptor with __set__ but without __get__ work? | 39,711,281 | <p>I read somewhere about the fact you can have a descriptor with <code>__set__</code> and without <code>__get__</code>.</p>
<p>How does it work? </p>
<p>Does it count as a data descriptor? Is it a non-data descriptor?</p>
<p>Here is a code example:</p>
<pre><code>class Desc:
def __init__(self, name):
s... | 3 | 2016-09-26T19:54:31Z | 39,711,282 | <p>The descriptor you've given in the example is a data descriptor.</p>
<p>Upon setting the attribute, as any other data descriptor, it takes the highest priority and is called like so:</p>
<pre><code>type(myinst).__dict__["attr"].__set__(myinst, 1234)
</code></pre>
<p>This in turn, adds <code>attr</code> to the ins... | 5 | 2016-09-26T19:54:31Z | [
"python",
"python-descriptors"
] |
Python - Reading a UTF-8 encoded string byte-by-byte | 39,711,335 | <p>I have a device that returns a UTF-8 encoded string. I can only read from it byte-by-byte and the read is terminated by a byte of value 0x00.</p>
<p>I'm making a Python 2.7 function for others to access my device and return string.</p>
<p>In a previous design when the device just returned ASCII, I used this in a l... | 3 | 2016-09-26T19:57:24Z | 39,711,380 | <p>The correct solution would be to read until you hit the terminating byte, then convert to UTF-8 at that time (so you have all characters):</p>
<pre><code>mybytes = bytearray()
while True:
x = read_next_byte()
if x == 0:
break
mybytes.append(x)
my_string = mybytes.decode('utf-8')
</code></pre>
<... | 3 | 2016-09-26T19:59:45Z | [
"python",
"python-2.7",
"unicode",
"encoding",
"utf-8"
] |
How to use base classes in Django | 39,711,366 | <p>I'm trying to alter an app I've created so that it is reusable. It's based around a single model which sites using the app will subclass. As it stands, my non-reusable version has the following kind of structure:</p>
<pre><code># models.py
class Document(models.Model):
contents = models.TextField()
date =... | 1 | 2016-09-26T19:59:06Z | 39,711,935 | <p>You can't query your abstract classes directly like that since they won't have managers, only the inherited classes. If you really must do inheritance, you can use a concrete base model and inherit from that at the cost of a join on every query.</p>
<p>Think long and hard about whether this is truly necessary, or i... | 0 | 2016-09-26T20:36:57Z | [
"python",
"django",
"django-models"
] |
How to use base classes in Django | 39,711,366 | <p>I'm trying to alter an app I've created so that it is reusable. It's based around a single model which sites using the app will subclass. As it stands, my non-reusable version has the following kind of structure:</p>
<pre><code># models.py
class Document(models.Model):
contents = models.TextField()
date =... | 1 | 2016-09-26T19:59:06Z | 39,772,562 | <p>I ended up going with a solution mentioned in my edit, namely creating a <code>get_document_model()</code> method inspired by <a href="https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/#get_user_model" rel="nofollow"><code>get_user_model()</code></a>. This gives me exactly the desired behavior. </p>... | 0 | 2016-09-29T14:04:41Z | [
"python",
"django",
"django-models"
] |
python add array of hours to datetime | 39,711,370 | <p>import timedelta as td
I have a date time and I want to add an array of hours to it. </p>
<p>i.e. </p>
<pre><code>Date[0]
datetime.datetime(2011, 1, 1, 0, 0)
Date[0] + td(hours=9)
datetime.datetime(2011, 1, 1, 9, 0)
hrs = [1,2,3,4]
Date[0] + td(hours=hrs)
</code></pre>
<p>But obviously it is not supported.</p>
... | 1 | 2016-09-26T19:59:22Z | 39,711,427 | <p>Use a nested <em>list comprehension</em> and <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.replace" rel="nofollow"><code>.replace()</code> method</a>. Sample for a list with 2 datetimes:</p>
<pre><code>In [1]: from datetime import datetime
In [2]: l = [datetime(2011, 1, 1, 0, 0), datet... | 2 | 2016-09-26T20:02:55Z | [
"python",
"datetime"
] |
Getting percentages after binning pandas dataframe | 39,711,422 | <p>Based on the following mock DF:</p>
<pre><code>df = pd.DataFrame({'State': {0: "AZ", 1: "AZ", 2:"AZ", 3: "AZ", 4: "AK", 5: "AK", 6 : "AK", 7: "AK"},
'# of Boxes': {0: 1, 1: 2, 2:2, 3: 1, 4: 2, 5: 2, 6 : 1, 7: 2},
'Price': {0: 2, 1: 4, 2:15, 3: 25, 4: 17, 5: 13, 6 : 3, 7: 3}},
... | 3 | 2016-09-26T20:02:07Z | 39,711,931 | <p>Here is a solution using <code>pivot_table()</code> method:</p>
<pre><code>In [57]: pvt = (df.assign(bins=pd.cut(df.Price, [0,15,30]))
....: .pivot_table(index=['State','# of Boxes'],
....: columns='bins', aggfunc='size', fill_value=0)
....: )
In [58]: pvt
Out[58]:
bin... | 2 | 2016-09-26T20:36:32Z | [
"python",
"pandas",
"dataframe"
] |
Getting percentages after binning pandas dataframe | 39,711,422 | <p>Based on the following mock DF:</p>
<pre><code>df = pd.DataFrame({'State': {0: "AZ", 1: "AZ", 2:"AZ", 3: "AZ", 4: "AK", 5: "AK", 6 : "AK", 7: "AK"},
'# of Boxes': {0: 1, 1: 2, 2:2, 3: 1, 4: 2, 5: 2, 6 : 1, 7: 2},
'Price': {0: 2, 1: 4, 2:15, 3: 25, 4: 17, 5: 13, 6 : 3, 7: 3}},
... | 3 | 2016-09-26T20:02:07Z | 39,711,997 | <p>I think you can use <code>groupby</code> by columns with binned <code>Series</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>cut</code></a>, aggregated by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.... | 3 | 2016-09-26T20:40:43Z | [
"python",
"pandas",
"dataframe"
] |
Matplotlib: Points do not show in SVG | 39,711,461 | <p>I have a scatter plot that I'd like to output as SVG (Python 3.5). However, when used with <code>agg</code> as backend, some points are simply missing. See the data and the PNG and SVG output. Is this some kind of misconfiguration or a bug?</p>
<p>Code:</p>
<pre><code>import matplotlig
matplotlib.use('agg')
import... | 1 | 2016-09-26T20:04:30Z | 39,712,842 | <p>The problem seems to be related to the <code>None</code> values. Though there is simply no point included if no matching point exists, it seems to influence the rendering of the SVG. Removing both entries if at one or the other point is <code>None</code> fixes the issue.</p>
<pre><code>data = np.array([x, y])
data ... | 0 | 2016-09-26T21:39:05Z | [
"python",
"svg",
"matplotlib"
] |
Cannot find django.views.generic . Where is generic. Looked in all folders for the file | 39,711,473 | <p>I know this is a strange question but I am lost on what to do. i cloned pinry... It is working and up . I am trying to find django.views.generic. I have searched the directory in my text editor, I have looked in django.views. But I cannot see generic (only a folder with the name "generic"). I cant understand where t... | 1 | 2016-09-26T20:05:25Z | 39,711,943 | <p>Try running this from a Python interpreter: </p>
<pre><code>>>> import django.views.generic
>>> django.views.generic.__file__
</code></pre>
<p>This will show you the location of the <code>gerneric</code> as a string path. In my case the output is:</p>
<pre><code>'/.../python3.5/site-packages/dja... | 3 | 2016-09-26T20:37:33Z | [
"python",
"django",
"generics"
] |
Do you and should you rename a custom User model in Django 1.9? | 39,711,484 | <p>I am creating a new User model for my Django project. I have been many people calling their custom user model, XXXUser and custom user manager, XXXUserManager. </p>
<p>I was wondering if there is a reason for this. Can you just create a custom user and still call it User? Does this create conflicts in the code?<... | 1 | 2016-09-26T20:06:00Z | 39,711,543 | <p>If you want custom user models then take a look at subclassing either <code>AbstractUser</code> or <code>AbstractBaseUser</code> detailed in the documentation here <a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-django-s-default-user" rel="nofollow">https://docs.djangoproject.com/e... | 0 | 2016-09-26T20:09:31Z | [
"python",
"django",
"django-admin",
"django-1.9"
] |
Do you and should you rename a custom User model in Django 1.9? | 39,711,484 | <p>I am creating a new User model for my Django project. I have been many people calling their custom user model, XXXUser and custom user manager, XXXUserManager. </p>
<p>I was wondering if there is a reason for this. Can you just create a custom user and still call it User? Does this create conflicts in the code?<... | 1 | 2016-09-26T20:06:00Z | 39,711,775 | <p>Basically you can. But for readability purposes it's better to do it <code>XxxUser</code>, if you see <code>XxxUser</code> you are instantly understand that this is custom one. And you need to keep in mind that you should replace some code that is common for base usage.</p>
<p>Such as(should be replaces)</p>
<pre>... | 0 | 2016-09-26T20:24:55Z | [
"python",
"django",
"django-admin",
"django-1.9"
] |
Firefox blank webbrowser with selenium | 39,711,674 | <p>When I call a firefox webbrowser with python firefox webdriver, the firefox is opening with a blank page (nothing in the navigation barre), wait and close.</p>
<p>The python consol give me this error :</p>
<p>Traceback (most recent call last):
File "firefox_selenium2.py", line 4, in
driver = webdriver.Firef... | 3 | 2016-09-26T20:17:24Z | 39,712,057 | <p>According to this post
<a href="https://github.com/SeleniumHQ/selenium/issues/2739#issuecomment-249479530" rel="nofollow">https://github.com/SeleniumHQ/selenium/issues/2739#issuecomment-249479530</a>
the is that you need to use something called Gecko Driver, found here <a href="https://github.com/mozilla/geckodriver... | 0 | 2016-09-26T20:44:34Z | [
"python",
"python-3.x",
"selenium",
"firefox"
] |
Writing to different columns in Excel from python | 39,711,698 | <p>I'm using Python Selenium webdriver to scrape a web table by iterating over the rows in the table, and CSV module to write to excel.</p>
<pre><code>When printing in python my scraped web table shows
['PS208\n43:51\nOUTBOUND\nFDEX\n708135']
['PS207\n01:24\nINBOUND\nUPSS\n889058']
['PS206\n12:34\nOTHER\nFDEG\n506796'... | 1 | 2016-09-26T20:19:32Z | 39,712,275 | <pre><code>import csv
output = ['PS208\n43:51\nOUTBOUND\nFDEX\n708135']
output = output[0].split('\n')
with open(output_file, 'ab') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(output)
</code></pre>
<p>Each row can be written into coulmns like this. Adding a loop for each block of data and splittin... | 0 | 2016-09-26T20:58:11Z | [
"python",
"csv",
"selenium",
"webdriver"
] |
Find all-zero columns in pandas sparse matrix | 39,711,838 | <p>For example I have a coo_matrix A :</p>
<pre><code>import scipy.sparse as sp
A = sp.coo_matrix([3,0,3,0],
[0,0,2,0],
[2,5,1,0],
[0,0,0,0])
</code></pre>
<p>How can I get result [0,0,0,1], which indicates that first 3 columns contain non-zero values, only the 4t... | 2 | 2016-09-26T20:29:06Z | 39,711,946 | <p><strong>Approach #1</strong> We could do something like this -</p>
<pre><code># Get the columns indices of the input sparse matrix
C = sp.find(A)[1]
# Use np.in1d to create a mask of non-zero columns.
# So, we invert it and convert to int dtype for desired output.
out = (~np.in1d(np.arange(A.shape[1]),C)).astype(... | 1 | 2016-09-26T20:37:43Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] |
Find all-zero columns in pandas sparse matrix | 39,711,838 | <p>For example I have a coo_matrix A :</p>
<pre><code>import scipy.sparse as sp
A = sp.coo_matrix([3,0,3,0],
[0,0,2,0],
[2,5,1,0],
[0,0,0,0])
</code></pre>
<p>How can I get result [0,0,0,1], which indicates that first 3 columns contain non-zero values, only the 4t... | 2 | 2016-09-26T20:29:06Z | 39,712,076 | <p>The actual logical operation can be performed like this:</p>
<pre><code>b = (A!=0).sum(axis=0)==0
# matrix([[False, False, False, True]], dtype=bool)
</code></pre>
<p>Now, to ensure that I'm answering your question exactly, I'd better tell you how you <em>could</em> convert from booleans to integers (although rea... | 1 | 2016-09-26T20:45:35Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] |
Find all-zero columns in pandas sparse matrix | 39,711,838 | <p>For example I have a coo_matrix A :</p>
<pre><code>import scipy.sparse as sp
A = sp.coo_matrix([3,0,3,0],
[0,0,2,0],
[2,5,1,0],
[0,0,0,0])
</code></pre>
<p>How can I get result [0,0,0,1], which indicates that first 3 columns contain non-zero values, only the 4t... | 2 | 2016-09-26T20:29:06Z | 39,713,115 | <p>Recent</p>
<p><a href="http://stackoverflow.com/questions/39683931/scipy-sparse-coo-matrix-how-to-fast-find-all-zeros-column-fill-with-1-and-norma">scipy.sparse.coo_matrix how to fast find all zeros column, fill with 1 and normalize</a></p>
<p>similar, except it wants to fill those columns with 1s and normalize th... | 1 | 2016-09-26T22:02:40Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] |
Find all-zero columns in pandas sparse matrix | 39,711,838 | <p>For example I have a coo_matrix A :</p>
<pre><code>import scipy.sparse as sp
A = sp.coo_matrix([3,0,3,0],
[0,0,2,0],
[2,5,1,0],
[0,0,0,0])
</code></pre>
<p>How can I get result [0,0,0,1], which indicates that first 3 columns contain non-zero values, only the 4t... | 2 | 2016-09-26T20:29:06Z | 39,715,773 | <p>Convert to an array or dense matrix, sum the absolute value along the first axis, test the result against zero, convert to int</p>
<pre><code>>>> import numpy as np
>>> (np.sum(np.absolute(a.toarray()), 0) == 0) * 1
array([0, 0, 0, 1])
>>> (np.sum(np.absolute(a.todense()), 0) == 0) * 1
ma... | 0 | 2016-09-27T04:04:03Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] |
Python - DNS lookup from SQL database | 39,711,864 | <p>I was hoping you could point me in the right direction about a little problem I'm having.</p>
<p>I want to create a basic web app that performs DNS queries to validate whether a specific set of DNS records are active or not. The DNS records are all A records and are hosted on an SQL-based CMDB. </p>
<p>I'm a fan o... | 1 | 2016-09-26T20:31:27Z | 39,712,126 | <p>There are a few tools, which one is the best depends on your needs.</p>
<p><strong>1]</strong> A great python tool that does what you ask and a lot more is <strong>scapy</strong>.
For example:</p>
<pre><code>>>> packet = DNSQR()
>>> packet.show()
###[ DNS Question Record ]###
qname= '.'
qtyp... | 0 | 2016-09-26T20:49:03Z | [
"python",
"sql-server",
"dns"
] |
Reading audio data from an ALSA buffer to a numpy array | 39,711,867 | <p>I'm trying to pull data from an ALSA buffer in order to generate count noise from a mic. However, when I try to convert the data to an array I get an incorrect result.</p>
<p>Below is part of my code:</p>
<pre><code>#!/usr/bin/env python
from __future__ import print_function
import alsaaudio
import numpy
card =... | 1 | 2016-09-26T20:31:38Z | 39,712,320 | <p><code>hexdump -d</code> displays the contents as <em>unsigned</em> 16bit integers, whereas you are converting it to a <em>signed</em> int16 numpy array.</p>
<p>Try converting to a dtype of <code>'u2'</code> (or equivalently, <code>np.uint16</code>) and you'll see that the output matches that of <code>hexdump</code>... | 0 | 2016-09-26T21:01:32Z | [
"python",
"arrays",
"numpy",
"alsa"
] |
Python 2.7 smtplib how to send attachment with Error 13 permission denied? | 39,711,974 | <p>hope you are well. I'm using python 2.7 with PyCharm on a Windows 7 and new at it.
I'm trying to send email with attachment but get error :<br>
IOError: [Errno 13] Permission denied: 'C:\Users\Myname\Desktop' This is my code: </p>
<pre><code>import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.... | 0 | 2016-09-26T20:39:08Z | 39,712,004 | <p>You are trying to open a <em>directory</em> as a file, you need to pass the actual file you want to open:</p>
<pre><code>attachment = open(r"C:\Users\MyName\Desktop\the_file")
</code></pre>
| 1 | 2016-09-26T20:40:57Z | [
"python",
"python-2.7",
"mime-types",
"mime",
"smtplib"
] |
How can I filter for string values in a mixed datatype object in Python Pandas Dataframe | 39,711,977 | <p>I have a column in a Pandas Dataframe like:(whose value_counts are shown below)</p>
<pre><code>1 246804
2 135272
5 8983
8 3459
4 3177
6 1278
9 522
D ... | 3 | 2016-09-26T20:39:29Z | 39,712,236 | <p>I think you should be able to filter your <code>value_counts</code> series using <code>.ix[]</code> or <code>.loc[]</code> indexers, filtering (indexing) by strings</p>
<p>Demo:</p>
<pre><code>In [27]: df
Out[27]:
Count
Admission_Source_Code
1 246804
2 ... | 2 | 2016-09-26T20:55:54Z | [
"python",
"pandas",
"dataframe"
] |
How can I filter for string values in a mixed datatype object in Python Pandas Dataframe | 39,711,977 | <p>I have a column in a Pandas Dataframe like:(whose value_counts are shown below)</p>
<pre><code>1 246804
2 135272
5 8983
8 3459
4 3177
6 1278
9 522
D ... | 3 | 2016-09-26T20:39:29Z | 39,731,770 | <p>I did some tests using your example and filters works well, for example:</p>
<pre><code>df = pandas.read_csv('Yourfile.csv')
df['Admission_Source_Code'].value_counts()
1 246804
2 135272
5 8983
8 3459
4 31... | 0 | 2016-09-27T18:22:53Z | [
"python",
"pandas",
"dataframe"
] |
Plot an R function curve in rpy2 | 39,712,048 | <p>I am trying to get the plot a simple curve in rpy2. </p>
<p><code>curve((x))</code> in R behaves as expected, but I cannot implement this in rpy2. </p>
<p>When I issue the following commands in sequence:</p>
<pre><code>import rpy2.robjects as ro
R = ro.r
R.curve(R.x)
</code></pre>
<p>I get the error that <code>... | 0 | 2016-09-26T20:43:46Z | 39,737,102 | <p>Simply pass in an actual function, call, or expression like <code>sin</code> as <code>x</code> is not assigned in Python. Below uses the example from the R documentation for <a href="http://stat.ethz.ch/R-manual/R-devel/library/graphics/html/curve.html" rel="nofollow">curve</a>: <code>curve(sin, -2*pi, 2*pi)</code>.... | 1 | 2016-09-28T02:31:05Z | [
"python",
"curve",
"rpy2"
] |
convert tripple pointer array to numpy array or list python | 39,712,181 | <p>I'm speeding up my program by integrating c code into my python program. I'm using <code>ctypes</code> to execute functions in c from python. </p>
<p>c program: </p>
<pre><code> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_ITERATIONS 1000
sta... | 0 | 2016-09-26T20:53:00Z | 39,863,021 | <p>I'm not sure about this triple-pointer business, but getting arrays from C to numpy works like this:</p>
<p>Assuming you have already received a ctypes <code>POINTER</code> to your image buffer, and you know the <code>height</code>, <code>width</code> and data type...</p>
<p>You can make a <code>ctypes</code> arra... | 0 | 2016-10-04T22:58:24Z | [
"python",
"c",
"arrays",
"python-3.x",
"ctypes"
] |
In Python (without Pickle), Can Arbitrary JSON strings be Constructed Dynamically? | 39,712,225 | <p>In Python (2.7), is there a way to dynamically generate arbitrary JSON strings without using Pickle? </p>
<p>(To be clear, this inquiry dwells on constructing the JSON payload...long before invoking json.dumps().)</p>
<p>WHY?</p>
<p>Imagine you are undertaking a project that will involve interacting with several ... | -1 | 2016-09-26T20:55:22Z | 39,712,675 | <p><strong>Default JSON encoder</strong> is capable of creating a JSON from some basic types (e.g. int, str, list, dict), but it can't handle custom objects.</p>
<p>For example:</p>
<pre><code>json.dumps([1, 2, 3]) # this works: '[1, 2, 3]'
class A(object):
def __init__(self):
self.value1 = 1
se... | 1 | 2016-09-26T21:25:57Z | [
"python",
"json",
"python-2.7",
"pickle"
] |
How can i call URL's from text file one by one | 39,712,304 | <p>I want to parse on one website with some URL's and i created a text file has all links that i want to parse. How can i call this URL's from the text file one by one on python program. </p>
<pre><code>from bs4 import BeautifulSoup
import requests
soup = BeautifulSoup(requests.get("https://www.example.com").content,... | -2 | 2016-09-26T21:00:30Z | 39,712,397 | <p>Use a context manager :</p>
<pre><code>with open("/file/path") as f:
urls = [u.strip('\n') for u in f.readlines()]
</code></pre>
<p>You obtain your list with all urls in your file and can then call them as you like.</p>
| 0 | 2016-09-26T21:06:54Z | [
"python",
"parsing",
"web-scraping",
"beautifulsoup"
] |
Is there a way with pygame to get keyboard input when the window is minimized? | 39,712,307 | <p>Title says it all. Is there a way with pygame to get keyboard input when the window is minimized? </p>
<p>Thanks.</p>
| 0 | 2016-09-26T21:00:43Z | 39,712,596 | <p>Yes, although you have to have it focused.</p>
<pre><code>import pygame
pygame.init()
pygame.display.iconify()
while 1:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
print(event.key)
</code></pre>
<p>Otherwise it seems to not be possible according to <a href="http://st... | 0 | 2016-09-26T21:20:00Z | [
"python",
"pygame"
] |
Python Jinja2 macro whitespace issues | 39,712,338 | <p>This is kind of extension to my other question <a href="http://stackoverflow.com/questions/39626767/python-jinja2-call-to-macro-results-in-undesirable-newline">Python Jinja2 call to macro results in (undesirable) newline</a>. </p>
<p>My python program is</p>
<pre><code>import jinja2
template_env = jinja2.Environme... | 1 | 2016-09-26T21:02:35Z | 39,720,257 | <p>Complete edit of answer. I see what you're going for now, and I have a working solution (I added in one <code>if</code> statement to your template). Here is what I used, with all other lines of your code unchanged:</p>
<pre><code>template_str = '''{% macro print_car_review(car) %}
{% if car.get('review') %}
... | 0 | 2016-09-27T08:52:55Z | [
"python",
"macros",
"whitespace",
"jinja2"
] |
Why is my django form validating when I am not calling is_valid | 39,712,398 | <p>I have a form which actions towards my home view, it contains two buttons, save and cancel. When run on the local dev server (manage.py runserver) this works fine. When I pushed this to production, the cancel button returns form validation errors, despite not calling the is_valid method.</p>
<p>Here is the view:</p... | 0 | 2016-09-26T21:06:56Z | 39,724,255 | <p>It looks like (slightly hard to tell as the formatting/indentation is off slightly) when your form is submitting the cancel value, it's submitting <code>Cancel</code>, and you're checking for <code>cancel</code>, so that logic is never executed. </p>
| 0 | 2016-09-27T12:08:07Z | [
"python",
"django",
"python-2.7",
"django-1.9"
] |
sum of 'float64' column type in pandas return float instead of numpy.float64 | 39,712,435 | <p>I have a dataframe in pandas. I am taking sum of a column of a dataframe as:</p>
<pre><code>x = data['col1'].sum(axis=0)
print(type(x))
</code></pre>
<p>I have checked that <code>col1</code> column in <code>data</code> dataframe is of type <code>float64</code>. But the type of <code>x</code> is <code><class 'fl... | 4 | 2016-09-26T21:09:26Z | 39,720,343 | <p>This seems to be from the way that pandas is handling nans. When I set <code>skipna=False</code> in the <code>sum</code> method I get the <code>numpy</code> datatype</p>
<pre><code>import pandas as pd
import numpy as np
type(pd.DataFrame({'col1':[.1,.2,.3,.4]}).col1.sum(skipna=True))
#float
type(pd.DataFrame({'co... | 3 | 2016-09-27T08:57:17Z | [
"python",
"pandas",
"numpy"
] |
Django: Which way is better way to find(search) a equal data object? | 39,712,490 | <p>I am implementing searching functions in <code>Django</code>, which of these would be better?</p>
<pre><code>def same_cart_item_in_cart(cart, new_cart_item):
already_exist_cart_item = cart.cartitem_set.filter(
Q(variation__product=new_cart_item.variation.product),
Q(variation=new_cart_item.varia... | 0 | 2016-09-26T21:13:31Z | 39,712,791 | <p>As i said in the comment <1> option is better.</p>
<p>And it you are trying to save new instance and check it before saving, Django made it for you. You can add <a href="https://docs.djangoproject.com/en/1.10/ref/models/options/#unique-together" rel="nofollow"><code>unique_together</code></a> to your <code>Model... | 0 | 2016-09-26T21:34:41Z | [
"python",
"django"
] |
calculate the total value dict | 39,712,512 | <p>I have a problem, how to calculate the total dict of the same keys ? I have a dict:</p>
<pre><code>{'learning': {'DOC1': 0.14054651081081646,
'DOC2': 0,
'DOC3': 0.4684883693693881},
'life': {'DOC1': 0.14054651081081646,
'DOC2': 0.20078072972973776,
'DOC... | 0 | 2016-09-26T21:14:44Z | 39,712,576 | <p>Pretty simple:</p>
<pre><code>for k in d['learning']:
print(d['learning'][k] + d['life'][k])
</code></pre>
<p>... with <code>d</code> being your <code>dict</code> and no error checking whatsoever (does the key exist, is it really a number, etc.).
<hr>
As whole code snippet with a comprehension:</p>
<pre><code... | 1 | 2016-09-26T21:18:32Z | [
"python",
"dictionary",
"tf-idf"
] |
calculate the total value dict | 39,712,512 | <p>I have a problem, how to calculate the total dict of the same keys ? I have a dict:</p>
<pre><code>{'learning': {'DOC1': 0.14054651081081646,
'DOC2': 0,
'DOC3': 0.4684883693693881},
'life': {'DOC1': 0.14054651081081646,
'DOC2': 0.20078072972973776,
'DOC... | 0 | 2016-09-26T21:14:44Z | 39,712,755 | <p>You can use a dictionary comprehension to add all the numbers nested in a dictionary <code>d</code> just like so:</p>
<pre><code>totals = {k: sum(v.get(k, 0) for v in d.values()) for k in d.values()[0]} # dict of totals
</code></pre>
| 0 | 2016-09-26T21:31:49Z | [
"python",
"dictionary",
"tf-idf"
] |
Create groups/classes based on conditions within columns | 39,712,602 | <p>I need help transforming my data so I can read through transaction data.</p>
<p><strong>Business Case</strong></p>
<p>I'm trying to group together some related transactions to create some groups or classes of events. This data set represents workers going out on various leaves of absence events. I want to create o... | 7 | 2016-09-26T21:20:28Z | 39,791,114 | <p>This is a bit clunky but it yields the right output at least for your small example:</p>
<pre><code>import pandas as pd
data = {'Employee ID': ["100", "100", "100","100","200","200","200","300"],
'Effective Date': ["2016-01-01","2015-06-05","2014-07-01","2013-01-01","2016-01-01","2015-01-01","2013-01-01","... | 3 | 2016-09-30T12:04:16Z | [
"python",
"pandas"
] |
Create groups/classes based on conditions within columns | 39,712,602 | <p>I need help transforming my data so I can read through transaction data.</p>
<p><strong>Business Case</strong></p>
<p>I'm trying to group together some related transactions to create some groups or classes of events. This data set represents workers going out on various leaves of absence events. I want to create o... | 7 | 2016-09-26T21:20:28Z | 39,903,229 | <p>You can do this without having to loop or iterate through your dataframe. Per <a href="http://stackoverflow.com/a/10964938/5066140">Wes McKinney</a> you can use <code>.apply()</code> with a groupBy object and define a function to apply to the groupby object. If you use this with <code>.shift()</code> (<a href="htt... | 2 | 2016-10-06T18:29:09Z | [
"python",
"pandas"
] |
InvalidStateError with asyncio futures and RuntimeError with aiohttp when using Futures with callback | 39,712,656 | <p>I'm new to <code>asyncio</code> and <code>aiohttp</code>. I am currently getting this error and not sure why I am getting <code>InvalidStateError</code> for my <code>asyncio</code> future and <code>RuntimeError</code> for my session:</p>
<pre><code>Traceback (most recent call last):
File "/Library/Frameworks/Pyth... | 1 | 2016-09-26T21:24:55Z | 39,727,049 | <p><code>add_done_callback</code> accepts a <em>callback</em>, not a <em>coroutine</em>.
Moreover it's a part of very low level API which should be avoided by a casual developer.</p>
<p>But your main mistake is calling <code>session.post()</code> outside of <code>ClientSession</code> async context manager, the stacktr... | 2 | 2016-09-27T14:14:30Z | [
"python",
"python-3.5",
"python-asyncio",
"aiohttp"
] |
pyspark: difference between using (,) and [,] for pair representation for reducedByKey | 39,712,696 | <p>I am applying a map and then reduceByKey transformations on an RDD using pyspark. I tried both of the following syntax, and both of them seem to work:</p>
<p>case 1:</p>
<pre><code>my_rdd_out = my_rdd.map(lambda r: [r['my_id'], [[r['my_value']]]])\
.reduceByKey(lambda a, b: a+b)\
... | 0 | 2016-09-26T21:27:33Z | 39,712,807 | <p>The difference between a <code>tuple</code> and a <code>list</code> in python is that <code>tuple</code> object are immutable so they are hashable. <code>list</code> objects are not hashable since they can be modified using their reference.</p>
<p>In your case you can use any of them (or the <code>reduceByKey</code... | 1 | 2016-09-26T21:35:43Z | [
"python",
"lambda",
"row",
"pyspark"
] |
Open automatically python file as Administrator | 39,712,751 | <p>I want to use the third party module called "ping", <a href="https://pypi.python.org/pypi/python-ping/2011.10.17.376a019" rel="nofollow">found here</a></p>
<p>But it requires to open the file as "Administrator" in Windows.</p>
<p>I want it so every time the computer is started, to open this file as Administrator.
... | -1 | 2016-09-26T21:31:32Z | 39,713,305 | <p>So there's this program called </p>
<blockquote>
<p>Task Scheduler you can find it just by pressing start and searching
"Task Scheduler"</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/mOi8Z.png" rel="nofollow"><img src="http://i.stack.imgur.com/mOi8Z.png" alt="Looks like this."></a></p>
<blockquote>
... | 0 | 2016-09-26T22:19:32Z | [
"python"
] |
Keeping the user's input intact when outputing to terminal at the same time | 39,712,754 | <p>To simplify, let's say I'm trying to write a command line two-way chat in Python. I would like the user to input his message with <code>input()</code> at the command prompt, but a listening thread could print a message at any moment. By default, this would "break" the user's input. Visually something like this:</p>
... | 1 | 2016-09-26T21:31:44Z | 39,712,946 | <p>There are two ways of doing this.</p>
<p>One is to use <code>ncurses</code>. There are python bindings for this. With <code>ncurses</code>, the terminal screen is under your complete control, and you can print characters at any point.</p>
<p>Without <code>ncurses</code>, you can't write above the current line. Wha... | 1 | 2016-09-26T21:47:35Z | [
"python",
"multithreading",
"python-3.x",
"output"
] |
How to set size for scatter plot | 39,712,767 | <p>I have three lines setting a plot. I expect the size of the pic.png to be 640x640 pixels. But I got 800x800 picture. </p>
<pre><code>plt.figure(figsize=(8, 8), dpi=80)
plt.scatter(X[:],Y[:])
plt.savefig('pic.png')
</code></pre>
<p>BTW I have no problem setting size with object-oriented interface but I need to use ... | 0 | 2016-09-26T21:32:46Z | 39,713,009 | <p>The following code produces a 576x576 PNG image in my machine:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.random.rand(10)
plt.figure(figsize=(8, 8), dpi=80)
plt.scatter(x, y)
plt.savefig('pic.png')
</code></pre>
<p>Shifting <code>dpi=80</code> to the <code>plt.save... | 0 | 2016-09-26T21:54:05Z | [
"python",
"matplotlib"
] |
How to set size for scatter plot | 39,712,767 | <p>I have three lines setting a plot. I expect the size of the pic.png to be 640x640 pixels. But I got 800x800 picture. </p>
<pre><code>plt.figure(figsize=(8, 8), dpi=80)
plt.scatter(X[:],Y[:])
plt.savefig('pic.png')
</code></pre>
<p>BTW I have no problem setting size with object-oriented interface but I need to use ... | 0 | 2016-09-26T21:32:46Z | 39,713,472 | <p>While Alberto's answer gives you the correct work around, looking at the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig" rel="nofollow">documentation for <code>plt.savefig</code></a> gives you a better idea as to why this behavior happens.</p>
<blockquote>
<p>dpi: [ None | scalar > 0... | 2 | 2016-09-26T22:37:57Z | [
"python",
"matplotlib"
] |
Search and replace placeholder text in PDF with Python | 39,712,828 | <p>I need to generate a customized PDF copy of a template document.
The easiest way - I thought - was to create a source PDF that has some placeholder text where customization needs to happen , ie <code><first_name></code> and <code><last_name></code>, and then replace these with the correct values.</p>
<p... | 1 | 2016-09-26T21:37:29Z | 39,713,796 | <p>There is no direct way to do this that will work reliably. PDFs are not like HTML: they specify the positioning of text character-by-character. They may not even include the whole font used to render the text, just the characters needed to render the specific text in the document. No library I've found will do nice ... | 3 | 2016-09-26T23:18:43Z | [
"python",
"pdf"
] |
getaddrinfow fails if running process from Python | 39,712,983 | <p>I try to run 3rd party process (nsqd.exe) from my python script but when I do nsqd fails to bind socket. I've no idea why.</p>
<p>The script I'm using:</p>
<pre><code>import subprocess
import sys
proc = subprocess.Popen(['nsqd.exe', '-tcp-address="127.0.0.1:{}"'.format(sys.argv[1]),
'-http-address="127.0.0.1:... | 0 | 2016-09-26T21:52:07Z | 39,713,824 | <p>Remove the double quotes in your <code>Popen</code> so it becomes:</p>
<pre><code>proc = subprocess.Popen(['nsqd.exe',
'-tcp-address=127.0.0.1:{}'.format(sys.argv[1]),
'-http-address=127.0.0.1:{}'.format(sys.argv[2])
])
</code></pre>
<p>Bef... | 2 | 2016-09-26T23:22:07Z | [
"python",
"windows",
"tcp",
"subprocess",
"nsq"
] |
Speech to Text Watson interrupt by silence | 39,713,014 | <p>We are using the API Sessionless and python, we have put the 'continue:True' parameter like this:</p>
<p>def make_completed_audio_request(url, API_name=None, language=None, time=None):</p>
<pre><code>username, password, endpoint, lan=select_voice_api(name=API_name, language=language)
audio = get_complete_audio(url... | 0 | 2016-09-26T21:54:47Z | 39,748,499 | <p>I am using watson_developer_cloud API. Its easy to use and what is more important - it works. Here is the code sample:</p>
<pre><code>import json
from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1
speech_to_text = SpeechToTextV1(
username="yourusername",
password="yourpas... | 0 | 2016-09-28T13:08:31Z | [
"python",
"speech-to-text",
"watson"
] |
python 27 - Creating and running instances of another script in parallel | 39,713,080 | <p>I'm attempting to build a multiprocessing script that retrieves dicts of attributes from a MySQL table and then runs instances of my main script in <strong>parallel</strong>, using each dict retrieved from the MySQL table as an argument to each instance of the main script. The main script has a method called queen_b... | 0 | 2016-09-26T22:00:05Z | 39,713,378 | <p>You could store your dictionaries in a list and then try something like that:</p>
<pre><code>from multiprocessing import Pool as ThreadPool
# ...
def parallel_function(list_of_dictionaries,threads=20):
thread_pool = ThreadPool(threads)
results = thread_pool.map(SC.queen_bee() ,list_of_dictionaries)
th... | 0 | 2016-09-26T22:28:22Z | [
"python",
"parallel-processing",
"multiprocessing"
] |
python 27 - Creating and running instances of another script in parallel | 39,713,080 | <p>I'm attempting to build a multiprocessing script that retrieves dicts of attributes from a MySQL table and then runs instances of my main script in <strong>parallel</strong>, using each dict retrieved from the MySQL table as an argument to each instance of the main script. The main script has a method called queen_b... | 0 | 2016-09-26T22:00:05Z | 39,731,021 | <p>I think I have it licked. The answer appears to have been to use Pool's map function to call a worker function that's <strong>inside</strong> the same multiprocessing script. The worker function then instantiates the main script that calls its own worker function ('queen_bee' in this case).</p>
<p>Using my code exa... | 0 | 2016-09-27T17:35:30Z | [
"python",
"parallel-processing",
"multiprocessing"
] |
How can I sort datetime columns by row value in a Pandas dataframe? | 39,713,137 | <p>I'm new to Python and Pandas, and I've pulled in a database table that contains 15+ different datetime columns. My task is to sort these columns generally by earliest to latest value in the rows. However, the data is not clean; sometimes, where Column A's date would come before Column B's date in Row 0, A would come... | 2 | 2016-09-26T22:05:19Z | 39,713,482 | <p>If you don't mind taking a bit of a shortcut and using the median of each date column, this should work:</p>
<pre><code>def order_date_columns(df, date_columns_to_sort):
x = [(col, df[col].astype(np.int64).median()) for col in date_columns_to_sort]
return [x[0] for x in sorted(x, key=lambda x: x[1])]
</code... | 2 | 2016-09-26T22:39:10Z | [
"python",
"python-2.7",
"sorting",
"datetime",
"pandas"
] |
How can I sort datetime columns by row value in a Pandas dataframe? | 39,713,137 | <p>I'm new to Python and Pandas, and I've pulled in a database table that contains 15+ different datetime columns. My task is to sort these columns generally by earliest to latest value in the rows. However, the data is not clean; sometimes, where Column A's date would come before Column B's date in Row 0, A would come... | 2 | 2016-09-26T22:05:19Z | 39,729,862 | <p>Since you're using Python 2.7, you can use the <code>cmp</code> keyword argument to <code>sorted</code>. To get the column names in the order that you're looking for, I would do something like:</p>
<pre><code># Returns -1 if first_column[i] > second_column[i] more often.
# Returns 1 if vice versa.
# Returns 0 if... | 1 | 2016-09-27T16:29:05Z | [
"python",
"python-2.7",
"sorting",
"datetime",
"pandas"
] |
To remove a particular element from the xml-string using lxml Python 3.5 | 39,713,146 | <p>I have the below xml as an input to a function of python. I want to find a particular element which has Null value((firstChild.nodeValue)) and totally delete that from the xml and return the string. I have a contingency of using only the lxml module. Can I get help with this. </p>
<pre><code><country name="Liec... | -1 | 2016-09-26T22:06:21Z | 39,713,463 | <p>You can use a union to look for all nodes in a single xpath, then presuming you want to remove nodes with no text you can just call <code>tree.remove(node)</code>:</p>
<pre><code>x = """<country name="Liechtenstein">
<rank></rank>
<a></a>
<b></b>
<year>... | 0 | 2016-09-26T22:36:49Z | [
"python",
"xml",
"lxml",
"python-3.5"
] |
To remove a particular element from the xml-string using lxml Python 3.5 | 39,713,146 | <p>I have the below xml as an input to a function of python. I want to find a particular element which has Null value((firstChild.nodeValue)) and totally delete that from the xml and return the string. I have a contingency of using only the lxml module. Can I get help with this. </p>
<pre><code><country name="Liec... | -1 | 2016-09-26T22:06:21Z | 39,715,599 | <p>The below code worked :)</p>
<pre><code>def remove_empty_elements(self,xml_input):
tree = etree.fromstring(xml_input)
for found in tree.xpath("//*[text()=' ']"):
print("deleted " + str(found))
found.getparent().remove(found)
print(etree.tostring(tree).decode("utf-8"))
</code></pre>
| -1 | 2016-09-27T03:42:07Z | [
"python",
"xml",
"lxml",
"python-3.5"
] |
linear interpolation -- make grid | 39,713,164 | <p>I want to interpolate between different models. To make things easier, my data is shown below:</p>
<p><a href="http://i.stack.imgur.com/8Obef.png" rel="nofollow"><img src="http://i.stack.imgur.com/8Obef.png" alt="enter image description here"></a></p>
<p>I have 10 different simulations (which I will call <code>z</... | 1 | 2016-09-26T22:07:58Z | 39,722,817 | <p>It seems that in your problem the curves y(x) are well behaving, so you could probably just interpolate y(x) for the given values of z first and then interpolate between the obtained y-values afterwards.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import ... | 0 | 2016-09-27T10:55:07Z | [
"python",
"interpolation",
"linear-interpolation"
] |
linear interpolation -- make grid | 39,713,164 | <p>I want to interpolate between different models. To make things easier, my data is shown below:</p>
<p><a href="http://i.stack.imgur.com/8Obef.png" rel="nofollow"><img src="http://i.stack.imgur.com/8Obef.png" alt="enter image description here"></a></p>
<p>I have 10 different simulations (which I will call <code>z</... | 1 | 2016-09-26T22:07:58Z | 39,882,149 | <p>What you're doing seems a bit weird to me, at least you seem to use a single set of <code>y</code> values to do the interpolation. What I suggest is not performing two interpolations one after the other, but considering your <code>y(z,x)</code> function as the result of a pure 2d interpolation problem.</p>
<p>So as... | 0 | 2016-10-05T19:27:39Z | [
"python",
"interpolation",
"linear-interpolation"
] |
Python 3 - How to randomize what text displays | 39,713,257 | <p>I am a beginner at python and I am trying to figure out how I can randomly display text. For example, 60% chance of "Hello", 40% chance of saying "Goodbye", etc. Right now, for fun, I am trying to create sort of a bottle flip game. If you don't know what it is, its basically when you flip a half empty water bottle a... | -2 | 2016-09-26T22:15:23Z | 39,713,302 | <p>You have the right idea, basically, but you can greatly simplify your code.</p>
<pre><code>if number < 5:
print ("You have landed the bottle!")
elif number < 10:
print ("The bottle did not land, better luck next time.")
else:
print ("The bottle landed on the cap!")
</code></pre>
<p>You can change... | 0 | 2016-09-26T22:19:13Z | [
"python",
"python-3.x",
"random"
] |
Python 3 - How to randomize what text displays | 39,713,257 | <p>I am a beginner at python and I am trying to figure out how I can randomly display text. For example, 60% chance of "Hello", 40% chance of saying "Goodbye", etc. Right now, for fun, I am trying to create sort of a bottle flip game. If you don't know what it is, its basically when you flip a half empty water bottle a... | -2 | 2016-09-26T22:15:23Z | 39,713,375 | <p>You could also use a list of the possible solutions.</p>
<pre><code>import random
possibilities=['landed'] * 3 + ['missed'] * 6 + ['landed on cap']
print(random.choice(possibilities))
</code></pre>
| 0 | 2016-09-26T22:27:46Z | [
"python",
"python-3.x",
"random"
] |
Possible to have same key pair more than once in a dictonary | 39,713,338 | <p>I'm creating a blackjack game with a deck of cards like so:<br>
<code>cards = {'ace':[1,11],'2':2,'3':3}...</code> and so on. </p>
<p>I want to have <code>3</code> decks of cards, so is it possible to have more than one ace, etc.? If so, how? I still want each card to have the keypair of its value, but I don't car... | 0 | 2016-09-26T22:23:25Z | 39,713,537 | <p>You could use two separate data structures: One to define <em>unchanging</em> information such as card names and values (as you have already done), and another to keep track of <em>changing</em> information, such as how many of each card remains in the deck.</p>
| 1 | 2016-09-26T22:46:00Z | [
"python",
"python-3.x",
"dictionary"
] |
Possible to have same key pair more than once in a dictonary | 39,713,338 | <p>I'm creating a blackjack game with a deck of cards like so:<br>
<code>cards = {'ace':[1,11],'2':2,'3':3}...</code> and so on. </p>
<p>I want to have <code>3</code> decks of cards, so is it possible to have more than one ace, etc.? If so, how? I still want each card to have the keypair of its value, but I don't car... | 0 | 2016-09-26T22:23:25Z | 39,713,565 | <p>Using a dictionary type in Python will not allow you to have duplicate keys (<a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">see documentation</a>). So it would not be possible to have more than one 'ace' key in any given dictionary.</p>
<p>You didn't give much context a... | 0 | 2016-09-26T22:49:48Z | [
"python",
"python-3.x",
"dictionary"
] |
Difficulty with document batch import, pymongo | 39,713,374 | <p>I'm having a much more difficult time than I thought I would importing multiple documents from Mongo into RAM in batch. I am writing an application to communicate with a MongoDB via <code>pymongo</code> that currently has 2GBs, but in the near future could grow to over 1TB. Because of this, batch reading a limited n... | 0 | 2016-09-26T22:27:43Z | 39,713,962 | <ul>
<li>Python version is irrelevant here, nothing to do with your output.</li>
<li>Batch_size defines only how many documents mongoDB returns in a single
trip to DB (under some limitations: <a href="http://api.mongodb.com/python/current/api/pymongo/cursor.html" rel="nofollow">see here
here</a> ) </li>
<li>collection.... | 1 | 2016-09-26T23:41:27Z | [
"python",
"mongodb",
"python-3.x",
"pymongo"
] |
Convert range to timestamp in Pandas | 39,713,381 | <p>I have a column in a pandas data frame that goes from 0 to 172800000 in steps of 10. I would like to convert into datetime stamp with a specified date, beginning at midnight of that day. </p>
<p>So, suppose, </p>
<pre><code>time = np.arange(0,172800000, 10)
</code></pre>
<p>I would like to convert this in the fol... | 2 | 2016-09-26T22:28:56Z | 39,713,580 | <p>Try:</p>
<pre><code>test['TIME'] = pd.to_datetime('2016-09-20') + pd.to_timedelta(time, 'ms')
</code></pre>
| 3 | 2016-09-26T22:52:00Z | [
"python",
"pandas"
] |
Convert range to timestamp in Pandas | 39,713,381 | <p>I have a column in a pandas data frame that goes from 0 to 172800000 in steps of 10. I would like to convert into datetime stamp with a specified date, beginning at midnight of that day. </p>
<p>So, suppose, </p>
<pre><code>time = np.arange(0,172800000, 10)
</code></pre>
<p>I would like to convert this in the fol... | 2 | 2016-09-26T22:28:56Z | 39,713,581 | <p>This is the raison d'Ètre for <code>pandas.date_range()</code>:</p>
<pre><code>import pandas as pd
test = pd.DataFrame({'TIME': pd.date_range(start='2016-09-20',
freq='10ms', periods=20)})
print(test)
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-overr... | 3 | 2016-09-26T22:52:08Z | [
"python",
"pandas"
] |
Extracting quotations/citations with nltk (not regex) | 39,713,487 | <p>The input list of sentences:</p>
<pre><code>sentences = [
"""Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!""",
"""Alice replied in a very melancholy voice. She continued, 'I'll try again.'"""
]
</code></pre>
<p>The desired output:</p>
<pre><code>How Doth the Little Bus... | 1 | 2016-09-26T22:39:34Z | 39,730,272 | <p>Well, under the hood, <code>SExprTokenizer</code> is a regex-based approach as well, as can be seen from the source code you linked to.<br>
What also can be seen from the source is that the authors apparently didn't consider that the opening and closing "paren" are represented with the same character.
The depth of t... | 1 | 2016-09-27T16:51:53Z | [
"python",
"nltk",
"tokenize"
] |
Read/Write TCP options field | 39,713,540 | <p>I want to read and write custom data to TCP options field using Scapy. I know how to use TCP options field in Scapy in "normal" way as dictionary, but is it possible to write to it byte per byte?</p>
| 0 | 2016-09-26T22:46:17Z | 40,023,525 | <p>You can not directly write the TCP options field byte per byte, however you can either:</p>
<ul>
<li>write your entire TCP segment byte per byte: <code>TCP("\x01...\x0n")</code></li>
<li>add an option to Scapy's code manually in scapy/layers/inet.py <code>TCPOptions</code> structure</li>
</ul>
<p>These are workaro... | 1 | 2016-10-13T14:15:39Z | [
"python",
"tcp",
"scapy"
] |
Issues with iteration in a recursive function | 39,713,568 | <p>The code below is used to find the shortest path based on the constraints (of maxTotalDist and maxDistOutdoors) given. I have got it <em>mostly</em> working, but the problem I am having is that even though I am able to find a path (on some given problems). I'm not able to <em>confirm</em> that I've found it. </p>
<... | 0 | 2016-09-26T22:50:05Z | 39,800,307 | <p>All of the recursive calls will see the same value as <code>visited[0]</code>. It will always be the first child of the original <code>start</code> value. Since you're appending all other values to the end of the list, nothing will ever replace that child as the first value in <code>visited</code>.</p>
<p>I think y... | 0 | 2016-09-30T21:25:10Z | [
"python",
"recursion",
"iteration",
"graph-theory"
] |
Neo4j Transferring All Data from Postgres | 39,713,636 | <p>I'm attempting to transfer all data over to Neo4j, and am wondering if it would be alright to name all properties on nodes the same as in Postgres exactly. E.g id will be id, name will be name, and so on. Are there any conflicts with doing something like this?</p>
| 0 | 2016-09-26T22:59:21Z | 39,718,452 | <p>No, especially if you use the one of the clients to do the migration as they will automatically escape anything that needs to be escaped, but there's nothing I've come across.</p>
| 0 | 2016-09-27T07:19:02Z | [
"python",
"neo4j",
"neo4jclient",
"neo4jrestclient"
] |
Assigning indicators based on observation quantile | 39,713,678 | <p>I am working with a pandas DataFrame. I would like to assign a column indicator variable to 1 when a particular condition is met. I compute quantiles for particular groups. If the value is outside the quantile, I want to assign the column indicator variable to 1. For example, the following code prints the quantiles ... | 2 | 2016-09-26T23:03:59Z | 39,713,787 | <p>you want to use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow"><code>transform</code></a> after your <code>groupby</code> to get an equivalently sized array. <code>gt</code> is greater than. <code>mul</code> is multiply. I multiply by <code>1</code> to get the boo... | 3 | 2016-09-26T23:17:22Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Using xargs for parallel Python scripts | 39,713,719 | <p>I currently have a bash script, script.sh, with two nested loops. The first enumerates possible values for a, and the second enumerates possible values for b, like</p>
<pre><code>#!/bin/sh
for a in {1..10}
do
for b in {1..10}
do
nohup python script.py $a $b &
done
done
</code></pre>
<p>So t... | 1 | 2016-09-26T23:08:42Z | 39,713,884 | <p>This would actually look more like:</p>
<pre><code>#!/bin/bash
for a in {1..10}; do
for b in {1..10}; do
printf '%s\0' "$a" "$b"
done
done | xargs -0 -x -n 2 -P 5 python script.py
</code></pre>
<p>Note that there's no <code>nohup</code>, nor any <code>&</code> -- to track the number of concurrent invoc... | 4 | 2016-09-26T23:31:19Z | [
"python",
"bash",
"parallel-processing",
"xargs"
] |
Using xargs for parallel Python scripts | 39,713,719 | <p>I currently have a bash script, script.sh, with two nested loops. The first enumerates possible values for a, and the second enumerates possible values for b, like</p>
<pre><code>#!/bin/sh
for a in {1..10}
do
for b in {1..10}
do
nohup python script.py $a $b &
done
done
</code></pre>
<p>So t... | 1 | 2016-09-26T23:08:42Z | 39,713,996 | <p>If you use bash, then the following should work:</p>
<pre><code>#!/bin/bash
for a in {1..10}
do
for b in {1..10}
do
if [ `jobs | wc -l` -lt 6 ]; then # less than 6 background jobs
nohup python script.py $a $b &
else
wait -n # wait for any background job to term... | 1 | 2016-09-26T23:45:07Z | [
"python",
"bash",
"parallel-processing",
"xargs"
] |
Using xargs for parallel Python scripts | 39,713,719 | <p>I currently have a bash script, script.sh, with two nested loops. The first enumerates possible values for a, and the second enumerates possible values for b, like</p>
<pre><code>#!/bin/sh
for a in {1..10}
do
for b in {1..10}
do
nohup python script.py $a $b &
done
done
</code></pre>
<p>So t... | 1 | 2016-09-26T23:08:42Z | 39,717,822 | <p>GNU Parallel is made for exactly these kinds of jobs:</p>
<pre><code>parallel python script.py ::: {1..10} ::: {1..10}
</code></pre>
<p>If you need $a and $b placed differently you can use {1} and {2} to refer to the two input sources:</p>
<pre><code>parallel python script.py --option-a {1} --option-b {2} ::: {1.... | 1 | 2016-09-27T06:47:07Z | [
"python",
"bash",
"parallel-processing",
"xargs"
] |
How I can get current date in xml in odoo? | 39,713,720 | <p>I am adding group by filter of past due in accounting tab in odoo. And want to get context <strong>due_date < current date</strong>, but i am not getting current date anywhere, I don't know how i can get it, anybody can tell me that how to get current date in odoo? </p>
<p><strong>here is my group by filter</str... | 1 | 2016-09-26T23:08:47Z | 39,713,941 | <pre><code><xpath expr="//filter[@string='Due Month']" position="after
<filter string="Past Due" name="past_due_filter" domain="[('date_due','&lt;',current_date)]" />
</xpath>
</code></pre>
| 2 | 2016-09-26T23:38:55Z | [
"python",
"xml",
"openerp",
"odoo-8"
] |
How I can get current date in xml in odoo? | 39,713,720 | <p>I am adding group by filter of past due in accounting tab in odoo. And want to get context <strong>due_date < current date</strong>, but i am not getting current date anywhere, I don't know how i can get it, anybody can tell me that how to get current date in odoo? </p>
<p><strong>here is my group by filter</str... | 1 | 2016-09-26T23:08:47Z | 39,717,919 | <p>you can use "context_today" or <code>time</code> module, examples:</p>
<pre><code><filter name="today" string="Today" domain="[('date','=',time.strftime('%%Y-%%m-%%d'))]"/>
<filter name="last_24h" string="Last 24h" domain="[('start_date','&gt;', (context_today() - datetime.timedelta(days=1)).strftime(... | 2 | 2016-09-27T06:53:02Z | [
"python",
"xml",
"openerp",
"odoo-8"
] |
Python - decode or regex? | 39,713,773 | <p>I have this <code>dict</code> being scraped from the web, but it comes with this <code>unicode</code> issue:</p>
<pre><code>{'track': [u'\u201cAnxiety\u201d',
u'\u201cLockjaw\u201d [ft. Kodak Black]',
u'\u201cMelanin Drop\u201d',
u'\u201cDreams\u201d',
u'\u201cIntern\u201... | 2 | 2016-09-26T23:15:06Z | 39,713,902 | <p>Those are quotes (â and â). If you just want to get rid of them at the beginning or end of the string, it is easiest to <code>strip</code> them.</p>
<pre><code>>>> u'\u201cAnxiety\u201d'.strip(u'\u201c\u201d')
u'Anxiety'
</code></pre>
<p>If you want to get rid of them anywhere in the string, <code>rep... | 4 | 2016-09-26T23:32:42Z | [
"python",
"regex",
"unicode"
] |
Python - decode or regex? | 39,713,773 | <p>I have this <code>dict</code> being scraped from the web, but it comes with this <code>unicode</code> issue:</p>
<pre><code>{'track': [u'\u201cAnxiety\u201d',
u'\u201cLockjaw\u201d [ft. Kodak Black]',
u'\u201cMelanin Drop\u201d',
u'\u201cDreams\u201d',
u'\u201cIntern\u201... | 2 | 2016-09-26T23:15:06Z | 39,713,915 | <pre><code>dict['track'] = list(map(lambda x: x.replace('\u201c','').replace('\u201d',''), dict['track']))
</code></pre>
| 0 | 2016-09-26T23:34:32Z | [
"python",
"regex",
"unicode"
] |
Need some clarification on Kruskals and Union-Find | 39,713,798 | <p>Please help me fill any gaps in my knowledge(teaching myself):</p>
<p>So far I understand that given a graph of N vertices, and edges we want to form a MST that will have N-1 Edges</p>
<ol>
<li><p>We order the edges by their weight</p></li>
<li><p>We create a set of subsets where each vertice is given its own subs... | 0 | 2016-09-26T23:18:50Z | 39,714,030 | <blockquote>
<p>wouldn't finding the subset in subsets be taking too long to be O(nlog(n))</p>
</blockquote>
<p>Yes</p>
<blockquote>
<p>Is there a better approach or am i doing this correctly?</p>
</blockquote>
<p>The better approach is using <a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Dis... | 0 | 2016-09-26T23:50:07Z | [
"python",
"graph",
"kruskals-algorithm"
] |
Need some clarification on Kruskals and Union-Find | 39,713,798 | <p>Please help me fill any gaps in my knowledge(teaching myself):</p>
<p>So far I understand that given a graph of N vertices, and edges we want to form a MST that will have N-1 Edges</p>
<ol>
<li><p>We order the edges by their weight</p></li>
<li><p>We create a set of subsets where each vertice is given its own subs... | 0 | 2016-09-26T23:18:50Z | 39,714,032 | <p>Actually the running time of the algorithm is O(E log(V)).</p>
<p>The key to its performance lies on your point 4, more specifically, the implementation of determining for a light edge e = (a, b) if 'a' and 'b' belongs to the same set and, if not, performing the union of their respective sets.</p>
<p>For more clar... | 0 | 2016-09-26T23:50:24Z | [
"python",
"graph",
"kruskals-algorithm"
] |
Python class init function | 39,713,891 | <p>When I init a class in python, is it only called once? For example, if I write an if statement in the init area. </p>
<pre><code>class hi():
def __init__():
# bla bla bla
</code></pre>
<p>Does it only loop over once?</p>
| 0 | 2016-09-26T23:31:50Z | 39,713,966 | <p><code>__init__</code> is the constructor of the class. It is called once for every instance of the class you create.</p>
<pre><code>class A(object):
def __init__(self):
print('__init__ called')
a1 = A() # prints: __init__ called
a2 = A() # prints: __init__ called
</code></pre>
<p>BTW, this is not so... | 1 | 2016-09-26T23:41:59Z | [
"python",
"class"
] |
Problems with pd.read_csv | 39,713,900 | <p>I have Anaconda 3 on Windows 10. I am using pd.read_csv() to load csv files but I get error messages. To begin with I tried <code>df = pd.read_csv('C:\direct_marketing.csv')</code> which worked and the file was imported.</p>
<p>Then I tried <code>df = pd.read_csv('C:\tutorial.csv')</code> and I received the follow... | 0 | 2016-09-26T23:32:33Z | 39,713,944 | <p>Try escaping the backslashes:</p>
<pre><code>df = pd.read_csv('C:\\Users\\test.csv')
</code></pre>
| 2 | 2016-09-26T23:39:24Z | [
"python",
"csv"
] |
Problems with pd.read_csv | 39,713,900 | <p>I have Anaconda 3 on Windows 10. I am using pd.read_csv() to load csv files but I get error messages. To begin with I tried <code>df = pd.read_csv('C:\direct_marketing.csv')</code> which worked and the file was imported.</p>
<p>Then I tried <code>df = pd.read_csv('C:\tutorial.csv')</code> and I received the follow... | 0 | 2016-09-26T23:32:33Z | 39,713,956 | <p>try use two back-slash '\' instead of '\'. It might have take it as a escape sign.. ?</p>
| 1 | 2016-09-26T23:40:27Z | [
"python",
"csv"
] |
Convert int to list in python | 39,713,904 | <p>Take a list, say for example this one:</p>
<pre><code>a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
</code></pre>
<p>and write a program that prints out all the elements of the list as the list [1,1,2,3,5] that are less than 5.
Currently it prints as </p>
<pre><code>1
1
2
3
5
</code></pre>
<p>My code </p>
<pre><co... | 0 | 2016-09-26T23:32:51Z | 39,713,932 | <p>If you want all to print out all the element that great and <strong>equal to</strong> 5 then you are doing it right. But if you want to print out less then 5 you want:</p>
<pre><code>for i in a:
if i < 5:
count += 1
print(i)
</code></pre>
| 0 | 2016-09-26T23:37:58Z | [
"python"
] |
Convert int to list in python | 39,713,904 | <p>Take a list, say for example this one:</p>
<pre><code>a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
</code></pre>
<p>and write a program that prints out all the elements of the list as the list [1,1,2,3,5] that are less than 5.
Currently it prints as </p>
<pre><code>1
1
2
3
5
</code></pre>
<p>My code </p>
<pre><co... | 0 | 2016-09-26T23:32:51Z | 39,713,976 | <p>To have it print out as a list, keep it as a list. You can use list comprehension to accomplish this:</p>
<pre><code>>>> a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> [i for i in a if i<=5]
[1, 1, 2, 3, 5]
</code></pre>
<p>If we use <code>print</code>, it still looks the same:</p>
<pre><cod... | 1 | 2016-09-26T23:43:28Z | [
"python"
] |
Convert int to list in python | 39,713,904 | <p>Take a list, say for example this one:</p>
<pre><code>a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
</code></pre>
<p>and write a program that prints out all the elements of the list as the list [1,1,2,3,5] that are less than 5.
Currently it prints as </p>
<pre><code>1
1
2
3
5
</code></pre>
<p>My code </p>
<pre><co... | 0 | 2016-09-26T23:32:51Z | 39,714,031 | <p>You should have the if condition be more strict if you want only element smaller than 5. It should be <code>if i<5:</code> instead of <code>i<=5</code>.</p>
<p>If you want to store the elements in a new list, see the example below.</p>
<pre><code>a = [1,1,2,3,5,8,13,21,34,55,89]
new_list=[]
for i in a:
i... | 0 | 2016-09-26T23:50:08Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.