title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to define a temporary variable in python? | 39,386,837 | <p>Does python have a "temporary" or "very local" variable facility? I am looking for a one-liner and I want to keep my variable space tidy.</p>
<p>I would like to do something like this:</p>
<pre><code>...a, b, and c populated as lists earlier in code...
using ix=getindex(): print(a[ix],b[ix],c[ix])
...now ix is no... | 1 | 2016-09-08T09:05:47Z | 39,387,003 | <p>Technically not an answer, but: Don't worry about temporary variables too much, they are only valid within their local scope (most likely function in your case) and garbage collector gets rid of them as soon as that function is finished. One liners in python are mostly used for dict and list comprehensions. </p>
<p... | 0 | 2016-09-08T09:14:28Z | [
"python"
] |
How to define a temporary variable in python? | 39,386,837 | <p>Does python have a "temporary" or "very local" variable facility? I am looking for a one-liner and I want to keep my variable space tidy.</p>
<p>I would like to do something like this:</p>
<pre><code>...a, b, and c populated as lists earlier in code...
using ix=getindex(): print(a[ix],b[ix],c[ix])
...now ix is no... | 1 | 2016-09-08T09:05:47Z | 39,387,060 | <blockquote>
<p>Does python have a "temporary" or "very local" variable facility? </p>
</blockquote>
<p>yes, it's called a block, e.g. a function:</p>
<pre><code>def foo(*args):
bar = 'some value' # only visible within foo
print bar # works
foo()
> some value
print bar # does not work, bar is not in the ... | 0 | 2016-09-08T09:17:56Z | [
"python"
] |
When will a blocking socket timeout? | 39,386,917 | <p>In the <a href="https://docs.python.org/2/library/socket.html#socket-objects" rel="nofollow">documentation</a> of the <code>socket</code> module it is written that:</p>
<blockquote>
<p>Sockets are always created in blocking mode. In blocking mode,
operations block until complete or the system returns an error (... | 1 | 2016-09-08T09:09:59Z | 39,388,193 | <p>If you not set, Operating System control the connect timeout. TCP/IP in blocking mode have three different timeout:</p>
<ul>
<li>Connect.</li>
<li>Read.</li>
<li>Write.</li>
</ul>
<p>For connect timeout and how TCP/IP connect work, you should checkout <strong>tcp_syn_retries</strong> sustem configuration value on ... | 1 | 2016-09-08T10:11:53Z | [
"python",
"sockets",
"connection-timeout"
] |
Python, how to get the http header | 39,386,933 | <p>I was making a script to "automate my life" :) but came across an issue that I'm not able to solve.</p>
<p>This python script goes scrapes a page and gets the links of the "products" I need, the problem is that once I've the link to the page of the product to download the pdf of this "product" you have to press a b... | 0 | 2016-09-08T09:10:53Z | 39,387,014 | <p>It doesn't solve the problem of "getting the header", but I would suggest using <a href="http://www.seleniumhq.org/" rel="nofollow">Selenium</a>. It's a web browser automation tool and you can set your script to click on the button.</p>
<p>Here's the Selenium reference for Python: <a href="http://selenium-python.re... | 0 | 2016-09-08T09:15:18Z | [
"python",
"http",
"download",
"header",
"automation"
] |
Python, how to get the http header | 39,386,933 | <p>I was making a script to "automate my life" :) but came across an issue that I'm not able to solve.</p>
<p>This python script goes scrapes a page and gets the links of the "products" I need, the problem is that once I've the link to the page of the product to download the pdf of this "product" you have to press a b... | 0 | 2016-09-08T09:10:53Z | 39,387,441 | <p>You can use Beautiful Soup for that. <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">Beautiful Soup</a> is a Python library for pulling data out of HTML and XML files.</p>
| 0 | 2016-09-08T09:35:12Z | [
"python",
"http",
"download",
"header",
"automation"
] |
Read a file in python starting with a particular string | 39,386,957 | <p>I have a file in the following path:</p>
<pre><code>/home/[user]/foo_01-01-2016.txt
</code></pre>
<p>I need to read it using the wild card (*) character:</p>
<pre><code>import pandas as pd
df = pd.read_csv("/home/[user]/foo_*.txt")
</code></pre>
<p>But its giving a file not found error.</p>
| 3 | 2016-09-08T09:12:24Z | 39,387,055 | <p>You can use <a href="https://docs.python.org/3.5/library/glob.html" rel="nofollow"><code>glob</code></a>, but output is list, so select first item by <code>[0]</code>:</p>
<pre><code>import pandas as pd
import glob
path =r'/home/[user]'
filename = glob.glob(path + "/foo_*.txt")
print (filename[0])
df = pd.read_cs... | 1 | 2016-09-08T09:17:44Z | [
"python",
"file",
"pandas",
"dataframe",
"wildcard"
] |
IDE pour Python 2.7 ou Python 3 | 39,386,962 | <p>I started it not long ago on <strong>Python</strong> ^^
I'm looking for an <strong>IDE that could directly install the libraries and Packages</strong> that I need without having to install the packages and get them by myself, because I observed some incompatibilities between packages on Windows and on Linux so <stro... | -4 | 2016-09-08T09:12:41Z | 39,387,850 | <p>Je doute fort que tu trouves une telle chose. </p>
<p>Python possède une riche panoplie de modules. Ãnormément on été implémenter aux préalable certains sont standard d'autre ne le sont pas et sont maintenu par divers groupes ou personnes. </p>
<p>Hypothétiquement, installer tout les modules que Python p... | 0 | 2016-09-08T09:54:23Z | [
"python",
"python-2.7",
"python-3.x",
"ide",
"developer-tools"
] |
multiclass classification in xgboost (python) | 39,386,966 | <p>I can't figure out how to pass number of classes or eval metric to xgb.XGBClassifier with the objective function 'multi:softmax'.</p>
<p>I looked at many documentations but the only talk about the sklearn wrapper which accepts n_class/num_class.</p>
<p>My current setup looks like</p>
<pre><code>kf = cross_validat... | 1 | 2016-09-08T09:12:48Z | 39,387,627 | <p>You don't need to set <code>num_class</code> in the scikit-learn API for XGBoost classification. It is done automatically when <code>fit</code> is called. Look at <a href="https://github.com/dmlc/xgboost/blob/master/python-package/xgboost/sklearn.py" rel="nofollow">xgboost/sklearn.py</a> at the beginning of the <cod... | 1 | 2016-09-08T09:44:08Z | [
"python",
"scikit-learn",
"xgboost"
] |
Python odeint clearly returning wrong solution | 39,387,033 | <p>Using python 2.7.8.<br>
The differential equation I'm working with is x'=2-3*x. Not that difficult. The correct solution is a decaying exponential with a y-intercept of 2/3. Exercise has three initial conditions. Also have to have a slope field with solution on the same plot. I have the slope field, but the solution... | 1 | 2016-09-08T09:16:49Z | 39,391,462 | <p>You want your ODE function to return 1 output, namely</p>
<pre><code>def my_ode_func(x,t):
return 2.0 - 3.0*x
</code></pre>
<p>Then <code>odeint</code> gives the expected exponential decay from the initial condition to <code>x=2/3</code>.</p>
<pre><code>import numpy as np
from scipy.integrate import odeint
t ... | 1 | 2016-09-08T12:51:27Z | [
"python",
"ode"
] |
Same python function giving different output | 39,387,127 | <p>I am making a scraping script in python. I first collect the links of the movie from where I have to scrap the songs list.
Here is the <strong>movie.txt</strong> list containing movies link</p>
<blockquote>
<p><a href="https://www.lyricsbogie.com/category/movies/a-flat-2010" rel="nofollow">https://www.lyricsbogi... | 0 | 2016-09-08T09:21:26Z | 39,387,730 | <p>To understand what is happening, you can print the representation of the url read from the file in the <code>for</code> loop:</p>
<pre><code>for url in file:
print(repr(url))
...
</code></pre>
<p>Printing this representation (and not just the string) makes it easier to see special characters. In this case,... | 1 | 2016-09-08T09:48:18Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Same python function giving different output | 39,387,127 | <p>I am making a scraping script in python. I first collect the links of the movie from where I have to scrap the songs list.
Here is the <strong>movie.txt</strong> list containing movies link</p>
<blockquote>
<p><a href="https://www.lyricsbogie.com/category/movies/a-flat-2010" rel="nofollow">https://www.lyricsbogi... | 0 | 2016-09-08T09:21:26Z | 39,387,733 | <p>I have a doubt that your file is not read as a single line, to be sure, can you test this code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup as bs
def get_songs_links_for_movies(url):
print("##Getting songs from %s" % url)
source_code = requests.get(url)
plain_text = source_code.text
... | -1 | 2016-09-08T09:48:28Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Replace special character in string | 39,387,268 | <p>I'm having a issue with a problem where I want to replace a special character in a text-file that I have created with a string that I defined.</p>
<pre><code>"""
This is a guess the number game.
"""
import datetime, random
from random import randint
fileOpen = open('text.txt','r')
savedData = fileOpen.read()
fileO... | 0 | 2016-09-08T09:27:52Z | 39,387,322 | <p><a href="https://docs.python.org/3/library/stdtypes.html#str.replace" rel="nofollow"><code>str.replace</code></a> doesn't alter the string in place, no string operations do because <em>strings are immutable</em>. It returns a copy of the replaced string which you need to assign to another name:</p>
<pre><code>repla... | 2 | 2016-09-08T09:30:04Z | [
"python",
"string",
"python-3.x"
] |
Get path to file within a package? | 39,387,328 | <p>I have a Python package which is organized like this:</p>
<pre><code>package
|- subpackage
| |- code.py
| |- window.ui
| ...
</code></pre>
<p>In <code>code.py</code> I want to access the file <code>window.ui</code> via</p>
<pre><code>PyQt4.uic.loadUi('window.ui', self)
</code></pre>
<p>This works well, if I ju... | 0 | 2016-09-08T09:30:23Z | 39,387,818 | <p>Use absolute path of the file instead of relative path.</p>
<pre><code>abspath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "window.ui")
PyQt4.uic.loadUi(abspath, self)
</code></pre>
| 2 | 2016-09-08T09:52:24Z | [
"python",
"import",
"module"
] |
Sum digits of numbers in a list | 39,387,399 | <p>Trying to write a function that takes a list like:</p>
<pre><code>x = [1, 13, 14, 9, 8]
</code></pre>
<p>for example and sums the digits like:</p>
<pre><code>1 + (1+3) + (1+4) + 9 + 8 = 27
</code></pre>
<p>What I have attempted thus far:</p>
<pre><code>def sum_d(x):
if not x:
return 0
els... | -4 | 2016-09-08T09:33:44Z | 39,387,574 | <p>How about this beauty:</p>
<pre><code>the_sum = sum(int(char) for n in x for char in str(n))
print(the_sum) # prints -> 27
</code></pre>
<p>What is happening here is that i am going through all elements of the list one by one (<code>for n in x</code>), i convert them to strings to be able to iterate through ea... | 6 | 2016-09-08T09:41:57Z | [
"python",
"list",
"python-3.x"
] |
Sum digits of numbers in a list | 39,387,399 | <p>Trying to write a function that takes a list like:</p>
<pre><code>x = [1, 13, 14, 9, 8]
</code></pre>
<p>for example and sums the digits like:</p>
<pre><code>1 + (1+3) + (1+4) + 9 + 8 = 27
</code></pre>
<p>What I have attempted thus far:</p>
<pre><code>def sum_d(x):
if not x:
return 0
els... | -4 | 2016-09-08T09:33:44Z | 39,387,576 | <pre><code>x = [1,13,14,9,8]
number = 0
for element in x:
my_string = str(element)
for i in range(len(my_string)):
number += int(my_string[i])
print(number)
</code></pre>
<p>This will do it, there might be a way to slice ints that doesn't involve converting them to strings though.</p>
| 0 | 2016-09-08T09:41:58Z | [
"python",
"list",
"python-3.x"
] |
Sum digits of numbers in a list | 39,387,399 | <p>Trying to write a function that takes a list like:</p>
<pre><code>x = [1, 13, 14, 9, 8]
</code></pre>
<p>for example and sums the digits like:</p>
<pre><code>1 + (1+3) + (1+4) + 9 + 8 = 27
</code></pre>
<p>What I have attempted thus far:</p>
<pre><code>def sum_d(x):
if not x:
return 0
els... | -4 | 2016-09-08T09:33:44Z | 39,387,628 | <p>A slight modification, and your original code will work :</p>
<pre><code>def sum_d(x):
x = str(x)
if len(x) == 1:
return int(x)
else:
return int(x[0]) + sum_d(int(x[1:]))
</code></pre>
<p>also possible in single line :</p>
<pre><code>sum(int(y) for y in (chain(*[str(x) for x in [1, 13,... | 1 | 2016-09-08T09:44:09Z | [
"python",
"list",
"python-3.x"
] |
Sum digits of numbers in a list | 39,387,399 | <p>Trying to write a function that takes a list like:</p>
<pre><code>x = [1, 13, 14, 9, 8]
</code></pre>
<p>for example and sums the digits like:</p>
<pre><code>1 + (1+3) + (1+4) + 9 + 8 = 27
</code></pre>
<p>What I have attempted thus far:</p>
<pre><code>def sum_d(x):
if not x:
return 0
els... | -4 | 2016-09-08T09:33:44Z | 39,387,676 | <pre><code>def sumx(x):
for i in range(0,len(x)):
if(x[i]>10):
sum=0
while(x[i]>0):
sum+=x[i]%10
x[i]=x[i]/10
x[i]=sum
print(x)
>>> sumx(x)
[5, 4, 5, 9, 8]
</code></pre>
| 0 | 2016-09-08T09:46:02Z | [
"python",
"list",
"python-3.x"
] |
ElementTree XML parsing from UTF-8 source file | 39,387,403 | <p>I have this XML file with utf-8 encoding.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item>
<Cikkszam>00008</Cikkszam>
<EAN/>
<Megjegyzes>BISK</Megjegyzes>
<Leiras1>Bisk Ontario, Dakota szappantartóhoz</Leiras1>
<Leiras2>mÅ... | 0 | 2016-09-08T09:33:53Z | 39,387,675 | <p><code>'proba.xml'.encode('utf8')</code> encodes the string <code>'proba.xml'</code> as UTF-8. It does nothing to the file of the same name.</p>
<p>When the file really is encoded as UTF-8 then your code will work:</p>
<pre><code>from xml.etree.ElementTree import ElementTree
doc = ElementTree().parse('proba.xml')
... | 0 | 2016-09-08T09:46:02Z | [
"python",
"xml",
"parsing",
"utf-8"
] |
group list elements based on another list | 39,387,435 | <p>I have two list: <code>inp</code> and <code>base</code>. i want to add each item in <code>inp</code> to a list in <code>out</code> based on position in <code>base</code> variable.
this code works fine:</p>
<pre><code>from pprint import pprint as print
num = 3
out = [[] for i in range(num)]
inp = [[1,1],[2,1],[3,2]... | 1 | 2016-09-08T09:35:00Z | 39,387,728 | <p>Assuming <code>base</code>and <code>inp</code> as NumPy arrays, we could do something like this -</p>
<pre><code># Get sorted indices for base
sidx = base.argsort()
# Get where the sorted version of base changes groups
split_idx = np.flatnonzero(np.diff(base[sidx])>0)+1
# OR np.unique(base[sidx],return_index=Tr... | 0 | 2016-09-08T09:48:11Z | [
"python",
"arrays",
"numpy"
] |
Error while running TensorBox ReInspect implementation on TensorFlow | 39,387,558 | <p>I am trying to train TensorBox ReInspect implementation (<a href="https://github.com/Russell91/TensorBox/" rel="nofollow">https://github.com/Russell91/TensorBox/</a>) on my machine with one GPU (NVidia GeForce GTX 750 Ti).
When I run the <code>train.py</code> script:</p>
<pre><code>python train.py --hypes hypes/ove... | 1 | 2016-09-08T09:41:13Z | 39,424,451 | <p>It appeared that the problem was because of state_is_true flag. Refer this thread for the solution:
<a href="https://github.com/Russell91/TensorBox/issues/59#issuecomment-245566316" rel="nofollow">https://github.com/Russell91/TensorBox/issues/59#issuecomment-245566316</a></p>
| 0 | 2016-09-10T09:04:55Z | [
"python",
"tensorflow"
] |
Celery cannot find a worker | 39,387,670 | <p>I'm using celery with such configuration</p>
<pre><code>default_exchange = Exchange('default', type='direct')
latest_exchange = Exchange('latest', type='direct')
shared_celery_config = {
'BROKER_URL': 'redis://localhost:6379/0',
'CELERY_RESULT_BACKEND': 'redis://localhost:6379/0',
'CELERY_DEFAULT_EXCHA... | 0 | 2016-09-08T09:45:58Z | 39,390,292 | <p>The issue was resolved. I have an web application which uses gevent and in <code>tasks</code> module I have import from another module that has <code>monkey.patch_all()</code>. Somehow it prevents billiard and therefore a worker to start pool and that leads to this consequences.
Anyway, <strong>do not use gevent at... | 0 | 2016-09-08T11:57:16Z | [
"python",
"python-2.7",
"celery",
"python-2.x",
"celeryd"
] |
not displaying old value when editing cell in a QTableWidget | 39,387,842 | <p>I have a basic QTableWidget, created with this python code:</p>
<pre><code>from silx.gui import qt
app = qt.QApplication([])
qtw = qt.QTableWidget()
qtw.show()
qtw.setColumnCount(8)
qtw.setRowCount(7)
app.exec_()
</code></pre>
<p>The <code>from silx.gui import qt</code> line is just a wrapper that finds out the in... | 1 | 2016-09-08T09:53:57Z | 39,388,920 | <p>You could try connecting the signal emited by QTableWidget <code>cellClicked(int row, int column)</code> with a slot created for clearing the entry. <br><a href="http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html#connecting-disconnecting-and-emitting-signals" rel="nofollow">http://pyqt.sourceforge.n... | 0 | 2016-09-08T10:46:36Z | [
"python",
"qt",
"pyqt",
"qtablewidget"
] |
not displaying old value when editing cell in a QTableWidget | 39,387,842 | <p>I have a basic QTableWidget, created with this python code:</p>
<pre><code>from silx.gui import qt
app = qt.QApplication([])
qtw = qt.QTableWidget()
qtw.show()
qtw.setColumnCount(8)
qtw.setRowCount(7)
app.exec_()
</code></pre>
<p>The <code>from silx.gui import qt</code> line is just a wrapper that finds out the in... | 1 | 2016-09-08T09:53:57Z | 39,396,773 | <p>Generally, edit behavior is controlled via <code>QItemDelegates</code>. Typically, this is done to provide more advanced editing, or to filter input data or perform some side effects (like update a database) when edits are made. But you can also use it to just clear the editor presented to the user when editing.</... | 0 | 2016-09-08T17:15:04Z | [
"python",
"qt",
"pyqt",
"qtablewidget"
] |
CSV Files in Python (Sliding Window) | 39,387,857 | <p>I am a beginner to Python, I need a help with manipulating csv files in Python.
I am trying to do sliding window mechanism for each row in dataset.</p>
<p>for an example if the dataset is this</p>
<pre><code>timestamp | temperature | windspeed
965068200 9.61883 60.262
965069100 9.47203 60.1664
965070000 ... | 2 | 2016-09-08T09:54:43Z | 39,388,379 | <p><strong>This answer assumes you are using Python 3.x - for Python 2.x some changes are required (some obvious places are commented)</strong></p>
<p>For the data format in the question, this could be a starting point in Python:</p>
<pre><code>import collections
def slide(infile,outfile,window_size):
queue=coll... | 1 | 2016-09-08T10:19:38Z | [
"java",
"python",
"csv",
"dataset",
"pycharm"
] |
pandas divide row value by aggregated sum with a condition set by other cell | 39,387,954 | <p>Hi Hoping to get some help, I have two columns Dataframe <code>df</code> as; </p>
<pre><code>Source ID
1 2
2 3
1 2
1 2
1 3
3 1
</code></pre>
<p>My intention is to group the Source and divide the ID cell by total based on the grouped Source and attach this to the orginial dataframe so ... | 1 | 2016-09-08T09:59:21Z | 39,388,025 | <p>try this:</p>
<pre><code>In [79]: df.assign(ID_new=df.ID/df.groupby('Source').ID.transform('sum'))
Out[79]:
Source ID ID_new
0 1 2 0.222222
1 2 3 1.000000
2 1 2 0.222222
3 1 2 0.222222
4 1 3 0.333333
5 3 1 1.000000
</code></pre>
<p>if you need it as a ne... | 1 | 2016-09-08T10:02:50Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
How do I get Django to log why an sql transaction failed? | 39,387,983 | <p>I am trying to debug a Pootle (pootle is build on django) installation which fails with a django transaction error whenever I try to add a template to an existing language. Using the python debugger I can see that it fails when pootle tries to save a model as well as all the queries that have been made in that sessi... | 0 | 2016-09-08T10:01:02Z | 39,447,127 | <p>Install django debug toolbar, you can easily check all of the queries that have been executed</p>
| 1 | 2016-09-12T09:24:35Z | [
"python",
"mysql",
"django",
"pootle"
] |
Writing elements to one2many from another model? | 39,387,996 | <p>How can we pass data's to one2many field where my data's are from another model.
I have written like these but error is showing.</p>
<p>I am accessing these function through button.</p>
<pre><code>@api.multi
def action_order(self):
rec= self.env['purchase.order'].create({
'partner_id' : self.vendo... | 0 | 2016-09-08T10:01:47Z | 39,389,986 | <p>The value for <code>order_line</code> has to be a list of triplets. For creating new entries you need triplets in form <code>(0, 0, value_dictionary)</code></p>
<p>So change your code to:</p>
<pre class="lang-py prettyprint-override"><code>'order_line' : [(0, 0, {
'brand_id' : self.product_brand_id,
'produ... | 0 | 2016-09-08T11:41:42Z | [
"python",
"openerp"
] |
Writing elements to one2many from another model? | 39,387,996 | <p>How can we pass data's to one2many field where my data's are from another model.
I have written like these but error is showing.</p>
<p>I am accessing these function through button.</p>
<pre><code>@api.multi
def action_order(self):
rec= self.env['purchase.order'].create({
'partner_id' : self.vendo... | 0 | 2016-09-08T10:01:47Z | 39,397,230 | <p>It looks like the the item '<strong>self.product_measure.id</strong>' for '<strong>product_uom</strong>' is creating the problem. It seems it is an 'Integer' field and you are trying to access 'id' out of it.</p>
| 0 | 2016-09-08T17:46:57Z | [
"python",
"openerp"
] |
COnvert number to letter | 39,388,041 | <p>i had install module <strong>num2words</strong>
this is my code :</p>
<pre><code>from num2words import num2words
</code></pre>
<p>class HrHolidays(models.Model):
_inherit = 'hr.holidays'</p>
<pre><code>interim = fields.Many2one(
'hr.employee',
string="Interim")
partner_id = fields.Many2one('res.partne... | 0 | 2016-09-08T10:03:39Z | 39,638,043 | <p>verify the definition of the function</p>
<pre><code>def calculatenumber(self,cr, uid, ids,number_of_days_temp, context=None):
number_text = num2words(number_of_days_temp,lang='fr')
return {'value': {'number_text': number_text}}
</code></pre>
<p>or you can use the new api</p>
<pre><code>@api.onchange('num... | 0 | 2016-09-22T11:41:29Z | [
"python",
"odoo-8"
] |
How to change a string into a formatted string? | 39,388,072 | <p>I want to change a source string: </p>
<pre><code>str1 = 'abc-ccd_2013'
</code></pre>
<p>into the following target string:</p>
<pre><code>str2 = 'abc\-ccd\_2013'.
</code></pre>
<p>All <code>'-'</code> should be replaced with <code>'\-'</code> and all <code>'_'</code> should be replaced into <code>'\_'</code>.</p... | 1 | 2016-09-08T10:05:32Z | 39,388,352 | <p>Your code does work and can be combined to a single expression:</p>
<pre><code>>>> print("abc-ccd_2013".replace("-","\-").replace("_","\_"))
abc\-ccd\_2013
</code></pre>
<p>Note the difference of <code>print</code> vs <code>repr</code>:</p>
<pre><code>>>> "abc-ccd_2013".replace("-","\-").replace... | 2 | 2016-09-08T10:18:23Z | [
"python",
"console"
] |
How to change a string into a formatted string? | 39,388,072 | <p>I want to change a source string: </p>
<pre><code>str1 = 'abc-ccd_2013'
</code></pre>
<p>into the following target string:</p>
<pre><code>str2 = 'abc\-ccd\_2013'.
</code></pre>
<p>All <code>'-'</code> should be replaced with <code>'\-'</code> and all <code>'_'</code> should be replaced into <code>'\_'</code>.</p... | 1 | 2016-09-08T10:05:32Z | 39,388,365 | <p>This works. When printing raw string, '\' is replaced with '\\' so it does not interpret it as escape character used for e.g. endline character '\n', tab character '\t' and so on.
Try command
<code>print str2</code> or <code>print a1</code>
and it will be fine.</p>
<p>Update: Even stackoverflow replaces '\\' with '... | 1 | 2016-09-08T10:18:55Z | [
"python",
"console"
] |
How to change a string into a formatted string? | 39,388,072 | <p>I want to change a source string: </p>
<pre><code>str1 = 'abc-ccd_2013'
</code></pre>
<p>into the following target string:</p>
<pre><code>str2 = 'abc\-ccd\_2013'.
</code></pre>
<p>All <code>'-'</code> should be replaced with <code>'\-'</code> and all <code>'_'</code> should be replaced into <code>'\_'</code>.</p... | 1 | 2016-09-08T10:05:32Z | 39,388,788 | <p>You could also do the following : </p>
<pre><code>str1 = 'abc-ccd_2013'
repl = ('-', '\-'), ('_', '\_')
print reduce(lambda a1, a2: a1.replace(*a2), repl, str1)
</code></pre>
<p>You will have to use the print function to get your desired result.</p>
| 0 | 2016-09-08T10:39:48Z | [
"python",
"console"
] |
IntegrityError : (1048, "Column 'user_dob' cannot be null") | 39,388,335 | <p>I have modified my serializers fields by as follow,</p>
<pre><code>class UserSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(source='user_id')
name = serializers.CharField(source='get_name')
email = serializers.EmailField(source='user_email')
dob = serializers.DateField(source... | 3 | 2016-09-08T10:17:36Z | 39,396,681 | <p>Since you are using a serializer that maps your "user_dob" field with "dob" you should pass parameter according to name provided in serialzers.</p>
| 2 | 2016-09-08T17:08:37Z | [
"python",
"django",
"django-rest-framework"
] |
How to prevent all writes to disk from within python | 39,388,531 | <p>When doing automated tests, I like to make sure my script does not write any data to the disk. I am doing tests on the script as a whole, not unit tests of individual functions.</p>
<p><strong>Is there a way to intercept all Disk-IO that a python script performs from within this script?</strong></p>
<p>Obviously, ... | 0 | 2016-09-08T10:27:12Z | 39,388,594 | <p>If mocking <code>open</code> is enough, you can stick the mock into the <a href="https://docs.python.org/3/library/builtins.html" rel="nofollow"><code>builtins</code> module</a>; this is the module that is consulted for all built-in functions:</p>
<pre><code>with mock.patch('builtins.open', mock_open()):
# ...
... | 1 | 2016-09-08T10:30:43Z | [
"python"
] |
IndexError: list index out of range python | 39,388,551 | <p>The follwoing code takes a log file and re-writes it in csv format: </p>
<pre><code>file = open("C:\\Scripts\\logs\\SteelUsage2.bsu")
DataFile = open("C:\\Scripts\\MFGData90.csv","a+")
for line in file.readlines():
#print line
line=line.strip()
numbers=line.split()
#print numbers
#print numbe... | 0 | 2016-09-08T10:28:19Z | 39,388,649 | <p>after <code>numbers=line.split()</code> add a line with this test:
<code>if len(numbers) < 11: continue</code></p>
| 0 | 2016-09-08T10:33:06Z | [
"python"
] |
IndexError: list index out of range python | 39,388,551 | <p>The follwoing code takes a log file and re-writes it in csv format: </p>
<pre><code>file = open("C:\\Scripts\\logs\\SteelUsage2.bsu")
DataFile = open("C:\\Scripts\\MFGData90.csv","a+")
for line in file.readlines():
#print line
line=line.strip()
numbers=line.split()
#print numbers
#print numbe... | 0 | 2016-09-08T10:28:19Z | 39,388,723 | <p>So what do you want do to with the line with <code>NAME</code></p>
<p>In fact when your script read it, you have :</p>
<pre><code>>>> line = "NAME"
>>> line = line.strip()
>>> numbers = line.split()
>>> numbers
['NAME']
</code></pre>
<p>And therefore <code>numbers[1]</code> wil... | 0 | 2016-09-08T10:36:57Z | [
"python"
] |
IndexError: list index out of range python | 39,388,551 | <p>The follwoing code takes a log file and re-writes it in csv format: </p>
<pre><code>file = open("C:\\Scripts\\logs\\SteelUsage2.bsu")
DataFile = open("C:\\Scripts\\MFGData90.csv","a+")
for line in file.readlines():
#print line
line=line.strip()
numbers=line.split()
#print numbers
#print numbe... | 0 | 2016-09-08T10:28:19Z | 39,388,791 | <pre><code>file = open("tst")
DataFile = open("tst_csv.csv","a+")
desired_size = 6
for line in file.readlines():
#print line
line=line.strip()
numbers=line.split()
if not len(numbers) >= desired_size:
continue
#print numbers[0]
#alpha = numbers [0]
#print alpha
StartHour= n... | -1 | 2016-09-08T10:40:01Z | [
"python"
] |
IndexError: list index out of range python | 39,388,551 | <p>The follwoing code takes a log file and re-writes it in csv format: </p>
<pre><code>file = open("C:\\Scripts\\logs\\SteelUsage2.bsu")
DataFile = open("C:\\Scripts\\MFGData90.csv","a+")
for line in file.readlines():
#print line
line=line.strip()
numbers=line.split()
#print numbers
#print numbe... | 0 | 2016-09-08T10:28:19Z | 39,388,915 | <p>You take line after line of your log and split is in separate parts. (11 in your case).</p>
<p>So if you want to access a part of the line which doesn't exist, you get an error.
Try checking every line if it has all parts and access then.</p>
<p>I wouldn't suggest using continue, because its considered as bad pra... | -1 | 2016-09-08T10:46:28Z | [
"python"
] |
Several static directories for tornado | 39,388,641 | <p>We are building uServices based on tornado. There are some routes which are common for all uServices, for the time being <code>health</code> and <code>docs</code>. The docs route is built using <code>Swagger</code>. That means, the swagger route, and associated assets, are part of our common library (but not the doc... | 0 | 2016-09-08T10:32:41Z | 39,391,070 | <p>It's not possible to do this with the <code>static_path</code> setting, but as long as you don't require the <code>static_url()</code> function, you can create multiple <code>StaticFileHandler</code> entries in your URLSpec list:</p>
<pre><code>Application([
('/static1/(.*)', tornado.web.StaticFileHandler, dict... | 1 | 2016-09-08T12:34:41Z | [
"python",
"tornado",
"assets"
] |
Pandas groupwise percentage | 39,388,820 | <p>How can I calculate a group-wise percentage in pandas?</p>
<p>similar to
<a href="http://stackoverflow.com/questions/23627782/pandas-groupby-size-and-percentages">Pandas: .groupby().size() and percentages</a> or <a href="http://stackoverflow.com/questions/29299078/pandas-very-simple-percent-of-total-size-from-grou... | -1 | 2016-09-08T10:41:51Z | 39,389,016 | <p>IIUC you can use:</p>
<pre><code>mydf = pd.DataFrame({'Field':[1,1,3,3,3],
'ClassLabel':[4,4,4,4,4],
'A':[7,8,9,5,7]})
print (mydf)
A ClassLabel Field
0 7 4 1
1 8 4 1
2 9 4 3
3 5 4 3
4 7 4 3
... | 3 | 2016-09-08T10:51:10Z | [
"python",
"pandas",
"group-by",
"percentage"
] |
Error in model prediction using hmmlearn | 39,388,890 | <p>Hi I have a dataframe test, I am trying to predict using a Gaussian HMM with hmmlearn.</p>
<p>When I do this:</p>
<pre><code>y = model.predict(test)
y
</code></pre>
<p>I get the hmm working fine producing and array of states</p>
<p>however if i do this:</p>
<pre><code>for i in range(0,len(test)):
y = model... | 0 | 2016-09-08T10:45:11Z | 39,405,552 | <p>HMM models sequences of observations. If you feed a single observation into <code>predict</code> (which does <a href="https://en.wikipedia.org/wiki/Viterbi_algorithm" rel="nofollow">Viterbi decoding</a> by default) you essentially reduce the prediction to the <code>argmax</code> over</p>
<pre><code>(model.startprob... | 1 | 2016-09-09T06:57:37Z | [
"python",
"pandas",
"numpy",
"hmmlearn"
] |
Python: Concatenating scipy sparse matrix | 39,388,902 | <p>I am trying to Concatenate 2 sparse matrix by the help of hstack function. xtrain_cat is the output of DictVectorizer(encodes categorical values) and xtrain_num is a pandas cvs file.</p>
<pre><code> xtrain_num = sparse.csr_matrix(xtrain_num)
print type(xtrain_num)
print xtrain_cat.shape
print xtrain_... | 1 | 2016-09-08T10:45:47Z | 39,389,831 | <p>You should try:</p>
<pre><code>x_train_data = hstack((xtrain_cat,xtrain_num))
</code></pre>
<p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.hstack.html" rel="nofollow">It takes a sequence</a>:</p>
<blockquote>
<p><strong>blocks</strong> sequence of sparse matrices with compatible sh... | 3 | 2016-09-08T11:33:06Z | [
"python",
"scipy",
"sparse-matrix"
] |
rpy2 can not import R package with rJava--mac | 39,388,994 | <p>I want to use rpy2 import R package 'iqspr' which I have aleady installed and test on my Rstudio, this package works fine. </p>
<p>Here are the errors I am getting.</p>
<pre><code>from rpy2.robjects.packages import importr
java=importr('rJava')
iqspr=importr('iqspr')
</code></pre>
<p>errors </p>
<pre><code>/Lib... | 0 | 2016-09-08T10:49:51Z | 39,430,503 | <p>Issues involving RStudio and rJava were reported in the past (for example <a href="http://stackoverflow.com/questions/30738974/rjava-load-error-in-rstudio-r-after-upgrading-to-osx-yosemite">rJava load error in RStudio/R after "upgrading" to OSX Yosemite</a>), and it is quite possible that the cause is simi... | 0 | 2016-09-10T20:57:18Z | [
"python",
"rpy2",
"rjava"
] |
Django Rest Framework : Fields are not getting create or update after making custom methods inside models | 39,389,134 | <pre><code>class UserInfo(models.Model):
user_id = models.AutoField(primary_key=True)
user_firstname = models.CharField(max_length=20, verbose_name = "First Name")
user_lastname = models.CharField(max_length=20, verbose_name = "Last Name")
user_email = models.EmailField(max_length=50, verbose_name =... | 3 | 2016-09-08T10:56:54Z | 39,396,877 | <p>Pass the parameters for creating object according to name defined in serializer that will work as you have desired make sure you pass values for all the parameters that can not be null. Now incase you want user to pass the parameter name instead of user_firstname & user_lastname you will need to get the value f... | 2 | 2016-09-08T17:21:57Z | [
"python",
"django",
"django-rest-framework"
] |
Python post to remote host | 39,389,265 | <p>Hi I want to write robot to register in toefl test , I send request to remote web site as:</p>
<pre><code>from django.http import HttpResponse
import requests
from bs4 import BeautifulSoup
from django.middleware import csrf
def index(request):
session = requests.Session()
page = session.get('https://toe... | 1 | 2016-09-08T11:04:27Z | 39,416,200 | <p>you should make sure that you enter cookies correctly like:</p>
<pre><code>def index(request):
response = HttpResponse()
if 'JSESSIONID' in request.COOKIES:
print('1')
else:
session = requests.Session()
page = session.get('https://toefl-registration.ets.org/TOEFLWeb/extISERLogonPrompt.do')
cookie =... | 0 | 2016-09-09T16:42:11Z | [
"python",
"django"
] |
Trend curve through data jumps back and forth when it should be smooth | 39,389,442 | <p>I want to plot a trend curve of my data points.
I did that with this code with an exponential model: </p>
<pre><code>with open(file,'r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
next(plots)
x=[]
y=[]
for row in plots:
x.append(float(row[1]))
y.append(float(row[3]))
plt.plot(x, y, 'ro',label="... | 1 | 2016-09-08T11:13:31Z | 39,390,711 | <p>One way, you can put <code>x.sort()</code> in before plotting:</p>
<pre><code>x.sort()
ypredict=func(x, *popt)
</code></pre>
<p>Another way would be to use something like this (better for a plot in my opinion),</p>
<pre><code># 1000 evenly spaced points over the range of x values
x_plot = np.linspace(x.min(), x.m... | 0 | 2016-09-08T12:18:23Z | [
"python",
"curve",
"points",
"trend"
] |
Javascript generators in Scala.js | 39,389,447 | <p>Currently I use Transcrypt to generate Javascript code from Python code. In this way I'm able to implement generators in Python like:</p>
<pre><code>def color():
colors = ["red", "blue", "yellow"]
i = -1
while True:
i += 1
if i >= colors.length:
i = 0
reset = yield... | 0 | 2016-09-08T11:13:51Z | 39,390,565 | <p>I believe the general concept you are looking for is Continuations. It's a fairly large and complex topic unto itself -- they used to be talked about more, but have largely been supplanted by the easier-to-use async library. But the <a href="https://index.scala-lang.org/scala/scala-continuations" rel="nofollow">scal... | 0 | 2016-09-08T12:11:24Z | [
"javascript",
"python",
"scala",
"scala.js",
"transcrypt"
] |
Install SWIGged Python library into dist-packages/myfoo.py, not dist-packages/myfoo/myfoo.py | 39,389,556 | <p>I have a directory structure like</p>
<pre><code> setup.py
myfoo/
myfoo.i
myfoo.cpp
myfoo.hpp
</code></pre>
<p>with <code>setup.py</code>,</p>
<pre><code>from distutils.core import setup, Extension
setup(
name='myfoo',
ext_modules=[
Extension(
'_myfoo',
[... | 0 | 2016-09-08T11:19:36Z | 39,393,365 | <p>Removing</p>
<pre><code>packages=['myfoo'],
</code></pre>
<p>and adding</p>
<pre><code>py_modules = ['myfoo'],
package_dir = {'' : 'myfoo'}
</code></pre>
<p>to <code>setup.py</code> does the trick.</p>
| 0 | 2016-09-08T14:17:50Z | [
"python",
"c++",
"swig",
"distutils"
] |
How to work "if np.array([False]):" | 39,389,581 | <p>The output of the following code is <strong>NOTHING</strong>.</p>
<pre><code>if np.array([False]):
print("hello")
</code></pre>
<p>Although I tried to search for it, I don't know how it works. Can Python overload <code>if</code>? </p>
<p>The following is a case of a pure array.</p>
<pre><code>if [False]:
pri... | 1 | 2016-09-08T11:20:56Z | 39,389,687 | <p><code>if [False]:</code> will always be <code>True</code> because <code>[Flase]</code> is a list with one item (i.e., non-empty), so the <code>if</code> block will be entered and you will see the output of your <code>print</code> call. </p>
<p><code>np.array([False])</code></p>
<p>returns a <code>numpy.ndarray</co... | 1 | 2016-09-08T11:26:35Z | [
"python",
"numpy"
] |
How to work "if np.array([False]):" | 39,389,581 | <p>The output of the following code is <strong>NOTHING</strong>.</p>
<pre><code>if np.array([False]):
print("hello")
</code></pre>
<p>Although I tried to search for it, I don't know how it works. Can Python overload <code>if</code>? </p>
<p>The following is a case of a pure array.</p>
<pre><code>if [False]:
pri... | 1 | 2016-09-08T11:20:56Z | 39,389,795 | <p>It seems np.array([]) returns False and so do for <code>0</code> and <code>False</code></p>
<pre><code>>>> bool(np.array([]))
False
>>> bool(np.array([0]))
False
>>> bool(np.array([False]))
False
</code></pre>
<p>Here the list returns true if it has any item..</p>
<pre><code>>>>... | 2 | 2016-09-08T11:31:21Z | [
"python",
"numpy"
] |
How to work "if np.array([False]):" | 39,389,581 | <p>The output of the following code is <strong>NOTHING</strong>.</p>
<pre><code>if np.array([False]):
print("hello")
</code></pre>
<p>Although I tried to search for it, I don't know how it works. Can Python overload <code>if</code>? </p>
<p>The following is a case of a pure array.</p>
<pre><code>if [False]:
pri... | 1 | 2016-09-08T11:20:56Z | 39,390,315 | <p>One thing i noticed is <code>if np.array([False])</code> or <code>bool(np.array([False])</code> returns the bool of the only item in the array. And you are not supposed to have more than one item in numpy array if you are doing <code>if</code> or <code>bool</code>. </p>
<p>If there are more than one elements, have ... | 2 | 2016-09-08T11:58:10Z | [
"python",
"numpy"
] |
Raise MemoryError when I am fitting a sequence to sequnce LSTM using Keras+Theano | 39,389,585 | <p>I was trying to implement a sequence to sequence language model. During training process, the model takes in a sequence of 50d word vectors generated by GloVe, and output 1-to-V(V is the size of vocabulary) vector meaning the next word which thus can be regarded as the distribution of next word corresponding to the ... | 2 | 2016-09-08T11:21:00Z | 39,440,233 | <p>What happened is that your computing device (probably a GPU) ran out of memory. I suspect it is a NVIDIA card (due to lack of alternatives), so check the output of <code>nvidia-smi</code> to see if you run into memory issues.</p>
<p>Depending on the backend (Theano or TensorFlow) you may experience different behavi... | 0 | 2016-09-11T20:15:09Z | [
"python",
"keras",
"lstm",
"language-model"
] |
Error when importing numpy (SyntaxError) | 39,389,684 | <p>I suddenly obtained such error when importing numpy:</p>
<p><a href="http://i.stack.imgur.com/G3Z8f.png" rel="nofollow">Print screen with error</a></p>
<p>It shows up when I type </p>
<pre><code>import numpy as np
</code></pre>
<p>or just</p>
<pre><code>import numpy
</code></pre>
<p>It also happens in python c... | 1 | 2016-09-08T11:26:18Z | 39,389,804 | <p>Check that you use a Python 2 edition of numpy.</p>
| 0 | 2016-09-08T11:31:41Z | [
"python",
"numpy",
"syntax-error"
] |
SQLAlchemy: How to cast string value to date in multiple insert statement? | 39,389,719 | <p>I have a list of dict objects</p>
<pre><code>data = [
{'id': 1, 'dt':'2002-01-02' },
{'id': 2, 'dt':'2014-01-15' },
{'id': 3, 'dt':'2005-10-20' }
]
</code></pre>
<p>and a table in sqlite created using sqlalchemy as follows</p>
<pre><code>engine = create_engine(config.SQLALCHEMY_DATABASE_URI)
metadata = MetaData()... | 0 | 2016-09-08T11:27:54Z | 39,389,898 | <p>You need to convert your <code>dt</code> strings to date objects, for instance:</p>
<pre><code>import datetime
for item in data:
item['dt'] = datetime.datetime.strptime(item['dt'], "%Y-%m-%d").date()
</code></pre>
<p>If you don't need the ORM part of SQLAlchemy (no class/table mapping). The easiest way is to t... | 1 | 2016-09-08T11:36:24Z | [
"python",
"sqlite",
"sqlalchemy"
] |
How to substitute two numpy subarrays with a single one | 39,389,741 | <p>is there a simple solution to substitute two numpy subarrays with a single one while the entires are a results of functions being called on the entries of the two former arrays. E.g:</p>
<pre><code>[1, a, b][1, c, d] -> [1, f_add, f_sub]
</code></pre>
<p>with </p>
<pre><code>f_add(a, b, c, d):
return a + ... | 0 | 2016-09-08T11:29:13Z | 39,390,984 | <p>You can use a generator expression to get this result (assuming there are three subelements for each element of the array):</p>
<pre><code>ar = ([[1, 0, 50], [2, 0, 50], [1, 3.0, 1.0]],
[[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]])
ar = tuple([[[x[0][0], sum(x[0][1:]) + sum(x[-1][1:]), x[0][-1]-x[-1][-1]], x[1]] f... | 0 | 2016-09-08T12:30:00Z | [
"python",
"arrays",
"numpy"
] |
How to substitute two numpy subarrays with a single one | 39,389,741 | <p>is there a simple solution to substitute two numpy subarrays with a single one while the entires are a results of functions being called on the entries of the two former arrays. E.g:</p>
<pre><code>[1, a, b][1, c, d] -> [1, f_add, f_sub]
</code></pre>
<p>with </p>
<pre><code>f_add(a, b, c, d):
return a + ... | 0 | 2016-09-08T11:29:13Z | 39,392,277 | <p>It sounds like things could get quite complicated if you have lots of functions working on the array. I would consider breaking each row into a class to manage the function calls a bit more succinctly. For example you could contain all of the relevant functions within the class:</p>
<pre class="lang-python prettypr... | 0 | 2016-09-08T13:28:03Z | [
"python",
"arrays",
"numpy"
] |
How to substitute two numpy subarrays with a single one | 39,389,741 | <p>is there a simple solution to substitute two numpy subarrays with a single one while the entires are a results of functions being called on the entries of the two former arrays. E.g:</p>
<pre><code>[1, a, b][1, c, d] -> [1, f_add, f_sub]
</code></pre>
<p>with </p>
<pre><code>f_add(a, b, c, d):
return a + ... | 0 | 2016-09-08T11:29:13Z | 39,399,573 | <p>Here's a function to perform the first (inner most) step, assuming the 2 inputs are lists:</p>
<pre><code>def merge(a,b):
res = [a[0]] # test b[0] is same?
abcd = a[1:]+b[1:] # list join
# use np.concatenate here is a,b are arrays
res.append(f_add(*abcd))
res.append(f_sum(a[2],b[2]))
re... | 0 | 2016-09-08T20:22:45Z | [
"python",
"arrays",
"numpy"
] |
turn a pivot table from pandas into a flat tabular format with a single header row | 39,389,766 | <p>What's the easiest way to turn my pandas dataframe into a dataframe which has one header row and the two columns</p>
<p>from this:</p>
<pre><code> date today
index
1 2016-07-01 2016-09-08
2 2016-07-01 2016-09-08
3 2016-07-01 2016-09-08
4 2016-07-01 2016-09-08
</code></pre>
<p>into thi... | 1 | 2016-09-08T11:29:56Z | 39,389,815 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p>
<pre><code>print (df.columns)
Index(['date', 'today'], dtype='object')
print (df.index)
Int64Index([1, 2, 3, 4], dtype='int64', name='index')
df.reset_index(inplac... | 0 | 2016-09-08T11:32:06Z | [
"python",
"pandas",
"dataframe"
] |
How to write conditional code that's compatible with both plain Python values and NumPy arrays? | 39,389,819 | <p>For writing âpiecewise functionsâ in Python, I'd normally use <code>if</code> (in either the control-flow or ternary-operator form).</p>
<pre><code>def spam(x):
return x+1 if x>=0 else 1/(1-x)
</code></pre>
<p>Now, with NumPy, the mantra is to avoid working on single values in favour of vectorisation, f... | 7 | 2016-09-08T11:32:16Z | 39,390,839 | <p>I would use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html" rel="nofollow">numpy.asarray</a> (which is a no-op if the argument is already an numpy array) if I want to handle both numbers and numpy arrays</p>
<pre><code>def eggs(x):
x = np.asfarray(x)
m = x>=0
x[m] = x... | 2 | 2016-09-08T12:23:30Z | [
"python",
"arrays",
"numpy",
"vectorization"
] |
How to write conditional code that's compatible with both plain Python values and NumPy arrays? | 39,389,819 | <p>For writing âpiecewise functionsâ in Python, I'd normally use <code>if</code> (in either the control-flow or ternary-operator form).</p>
<pre><code>def spam(x):
return x+1 if x>=0 else 1/(1-x)
</code></pre>
<p>Now, with NumPy, the mantra is to avoid working on single values in favour of vectorisation, f... | 7 | 2016-09-08T11:32:16Z | 39,391,848 | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a>. You'll get an array as the output even for plain number input, though.</p>
<pre><code>def eggs(x):
y = np.asarray(x)
return np.where(y>=0, y+1, 1/(1-y))
</code></pre>
<p>This work... | 4 | 2016-09-08T13:08:48Z | [
"python",
"arrays",
"numpy",
"vectorization"
] |
How to cope u prefix utf-8 string( need to decode but fail by `u` )? | 39,389,971 | <p>I am using python build a web base file manager with python 3 compatibility.</p>
<p>Every file header is:</p>
<pre><code># -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
</code></pre>
<p>Then I found something wrong due to Unicode.</p>
<p>My system is Chinese, I have a folder nam... | 0 | 2016-09-08T11:40:53Z | 39,390,378 | <p><code>unicode</code> strings can be <em>encoded</em> to byte <code>str</code>.<br>
<code>str</code> can be <em>decoded</em> to <code>unicode</code> strings.</p>
<p>When you have a <code>u''</code> string literal, <em>or</em> when you <code>import unicode_literals</code>, all your string literals will be <code>unico... | 0 | 2016-09-08T12:03:00Z | [
"python",
"python-2.7",
"unicode"
] |
How to cope u prefix utf-8 string( need to decode but fail by `u` )? | 39,389,971 | <p>I am using python build a web base file manager with python 3 compatibility.</p>
<p>Every file header is:</p>
<pre><code># -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
</code></pre>
<p>Then I found something wrong due to Unicode.</p>
<p>My system is Chinese, I have a folder nam... | 0 | 2016-09-08T11:40:53Z | 39,402,273 | <blockquote>
<p>What I want is convert</p>
<p>u'E:\filemanager\data\c - \xe5\x89\xaf\xe6\x9c\xac' to</p>
<p>either u'E:\filemanager\data\c - \u526f\u672c' or 'E:\filemanager\data\c - \xe5\x89\xaf\xe6\x9c\xac'</p>
<p>\xe5\x89\xaf\xe6\x9c\xac can not be decode due to the u prefix, , that is the key probl... | 1 | 2016-09-09T00:55:34Z | [
"python",
"python-2.7",
"unicode"
] |
Create DataFrame from Loop with Bloomberg function | 39,390,060 | <p>I have a list of company ticker's:</p>
<pre><code>df = {'Ticker': ['AVON LN EQUITY', 'GFS LN EQUITY'], 'Value': [1., 2.]}
df = pd.DataFrame(df)
</code></pre>
<p>I am using the BLPAPI wrapper, <a href="https://github.com/alex314159/blpapiwrapper" rel="nofollow">https://github.com/alex314159/blpapiwrapper</a></p>
<... | 0 | 2016-09-08T11:45:00Z | 39,391,598 | <p>Was simpler than I thought</p>
<pre><code>for d in df['Ticker']:
x[d] = bloom_func(d)
</code></pre>
| 0 | 2016-09-08T12:57:22Z | [
"python",
"pandas",
"bloomberg"
] |
Can't pass a list as class attribute | 39,390,157 | <p>I have created an iterator. I'm trying to iterate through recipe ingredients, to check if a vegan person can it it, or not.</p>
<pre><code>class Vegan:
NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter']
def __init__(self, *args):
self.ingredient_list = (args)
self.index = -1
d... | 1 | 2016-09-08T11:50:28Z | 39,390,508 | <p>Here's a possible solution to your problem:</p>
<pre><code>class Vegan:
NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter']
def __init__(self, *args):
self.ingredient_list = (args)
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.i... | 0 | 2016-09-08T12:08:37Z | [
"python",
"oop"
] |
Can't pass a list as class attribute | 39,390,157 | <p>I have created an iterator. I'm trying to iterate through recipe ingredients, to check if a vegan person can it it, or not.</p>
<pre><code>class Vegan:
NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter']
def __init__(self, *args):
self.ingredient_list = (args)
self.index = -1
d... | 1 | 2016-09-08T11:50:28Z | 39,390,515 | <p>Your issue is because you are indexing the ingredient not the tuple, <code>ingredient[self.index]</code> should be <code>self.ingredient_list[self.index]</code>. </p>
<p>You could simplify your code to behave like yours but work by making <em>args</em> <em>iterable</em> so you can pass the strings as you were with... | 3 | 2016-09-08T12:08:53Z | [
"python",
"oop"
] |
Can't pass a list as class attribute | 39,390,157 | <p>I have created an iterator. I'm trying to iterate through recipe ingredients, to check if a vegan person can it it, or not.</p>
<pre><code>class Vegan:
NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter']
def __init__(self, *args):
self.ingredient_list = (args)
self.index = -1
d... | 1 | 2016-09-08T11:50:28Z | 39,390,832 | <p>I think the problem with your class is that you're looping through the elements in your <code>__next__()</code> method. Here is a solution using your code:</p>
<pre><code>class Vegan:
NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter']
def __init__(self, *args):
self.ingredient_list = args
... | 0 | 2016-09-08T12:23:13Z | [
"python",
"oop"
] |
pandas.factorize on an entire data frame | 39,390,160 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow"><code>pandas.factorize</code></a> encodes input values as an enumerated type or categorical variable. </p>
<p>But how can I easily and efficiently convert many columns of a data frame? What about the reverse mapping... | 1 | 2016-09-08T11:50:52Z | 39,390,208 | <p>You can use <code>apply</code> if you need to <code>factorize</code> each column separately:</p>
<pre><code>df = pd.DataFrame({'A':['type1','type2','type2'],
'B':['type1','type2','type3'],
'C':['type1','type3','type3']})
print (df)
A B C
0 type1 type1 type1... | 2 | 2016-09-08T11:53:16Z | [
"python",
"pandas",
"dataframe",
"machine-learning"
] |
kivy: KeyError: (3385,) in widget.py | 39,390,227 | <p>When trying to exectue following code (edited version from the <a href="https://github.com/kivy/kivy-designer" rel="nofollow">kivy-designer</a>, stands under the MIT license):</p>
<pre><code>def __init__(self, **kwargs):
self._buttons = {}
super(PlaygroundSizeView, self).__init__(**kwargs)
for title, ... | 0 | 2016-09-08T11:54:38Z | 39,390,409 | <p>That line #1 has a typo in add_widget.
Are you sure that add_widget returns the parent widget?
I suggest you make a ScrollView first, then add the grid, then add the item to accordion.</p>
| 0 | 2016-09-08T12:04:15Z | [
"python",
"kivy",
"destructor",
"keyerror"
] |
removing dict entries by key using startswith | 39,390,368 | <p>I have a dict containing several entries beginning with '_'.
I want to get rid of all this entries using:</p>
<pre><code>for key in item:
if key.startswith('_')
del item[key]
</code></pre>
<p>But i get a syntax error on <em>if key.startswith('_')</em></p>
<p>Is this method not allowed on key for dict... | 0 | 2016-09-08T12:02:17Z | 39,390,432 | <p>Your if statement is syntactically wrong. You need a : at the end of it like this</p>
<pre><code>for key in item:
if key.startswith('_'):
del item[key]
</code></pre>
| 0 | 2016-09-08T12:05:24Z | [
"python"
] |
removing dict entries by key using startswith | 39,390,368 | <p>I have a dict containing several entries beginning with '_'.
I want to get rid of all this entries using:</p>
<pre><code>for key in item:
if key.startswith('_')
del item[key]
</code></pre>
<p>But i get a syntax error on <em>if key.startswith('_')</em></p>
<p>Is this method not allowed on key for dict... | 0 | 2016-09-08T12:02:17Z | 39,390,491 | <p>You miss the <code>:</code> at the end of the if.</p>
<pre><code>for key in item:
if key.startswith('_'): # <----------
del item[key]
</code></pre>
| 1 | 2016-09-08T12:07:46Z | [
"python"
] |
Python: How can I enable use of kwargs when calling from command line? (perhaps with argparse) | 39,390,418 | <p>suppose I have the module myscript.py; This module is production code, and is called often as <code>%dir%>python myscript.py foo bar</code>. </p>
<p>I want to extend it to take keyword arguments. I know that I can take these arguments using the script below, but unfortunately one would have to call it using </p>... | 0 | 2016-09-08T12:04:48Z | 39,390,779 | <p>First, you won't be passing an arbitrary Python expression as an argument. It's brittle and unsafe.</p>
<p>To set up the argument parser, you define the arguments you want, then parse them to produce a <code>Namespace</code> object that contains the information specified by the command line call.</p>
<pre><code>im... | 0 | 2016-09-08T12:20:44Z | [
"python",
"python-2.7",
"command-line",
"argparse",
"kwargs"
] |
Python: How can I enable use of kwargs when calling from command line? (perhaps with argparse) | 39,390,418 | <p>suppose I have the module myscript.py; This module is production code, and is called often as <code>%dir%>python myscript.py foo bar</code>. </p>
<p>I want to extend it to take keyword arguments. I know that I can take these arguments using the script below, but unfortunately one would have to call it using </p>... | 0 | 2016-09-08T12:04:48Z | 39,391,133 | <p>If you want to pass in keyword arguments as you would in the main function, <code>key=value</code>, you can do it like so:</p>
<pre><code>import sys
def main(foo, bar, *args):
print "Called my script with"
print "foo = %s" % foo
print "bar = %s" % bar
for arg in args:
k = arg.split("=")[0... | 0 | 2016-09-08T12:36:58Z | [
"python",
"python-2.7",
"command-line",
"argparse",
"kwargs"
] |
Python: How can I enable use of kwargs when calling from command line? (perhaps with argparse) | 39,390,418 | <p>suppose I have the module myscript.py; This module is production code, and is called often as <code>%dir%>python myscript.py foo bar</code>. </p>
<p>I want to extend it to take keyword arguments. I know that I can take these arguments using the script below, but unfortunately one would have to call it using </p>... | 0 | 2016-09-08T12:04:48Z | 39,391,238 | <p>@Moon beat me to it with a similar solution, but I'd suggest doing the parsing beforehand and passing in actual <code>kwargs</code>:</p>
<pre><code>import sys
def main(foo, bar, **kwargs):
print('Called myscript with:')
print('foo = {}'.format(foo))
print('bar = {}'.format(bar))
for k, v in kwargs.... | 0 | 2016-09-08T12:41:12Z | [
"python",
"python-2.7",
"command-line",
"argparse",
"kwargs"
] |
How to get the line number of a match with scrapy | 39,390,585 | <p>Using the following example:</p>
<pre><code>$ scrapy shell http://doc.scrapy.org/en/latest/_static/selectors-sample1.html
</code></pre>
<p>where <em>selectors-sample1-html</em> is:</p>
<pre><code><html>
<head>
<base href='http://example.com/' />
<title>Example website</title>
&... | 0 | 2016-09-08T12:12:39Z | 39,395,927 | <p>I don't know of a way to get source line for text nodes, but for element nodes, you can hack into the underlying lxml object of the selector (with <code>.root</code>), and access <code>.sourceline</code> attribute:</p>
<pre><code>$ scrapy shell http://doc.scrapy.org/en/latest/_static/selectors-sample1.html
2016-09-... | 0 | 2016-09-08T16:20:11Z | [
"python",
"scrapy"
] |
Are there any workarounds for pandas casting INT to Float when NaN is present? | 39,390,610 | <p>Trying to get my column to be formatted as INT as the 1.0 2.0 3.0 is causing issues with how I am using the data. The first thing I tried was <code>df['Severity'] = pd.to_numeric(df['Severity'], errors='coerce')</code>. While this looked like it worked initially, it reverted back to appearing as float when I wrote... | 2 | 2016-09-08T12:13:49Z | 39,391,360 | <p>It's up to you how to handle missing values there is no correct way as it's up to you. You can either drop them using <code>dropna</code> or replace/fill them using <code>replace/fillna</code>, note that there is no way to represent <code>NaN</code> using integers: <a href="https://en.wikipedia.org/wiki/NaN#Integer_... | 1 | 2016-09-08T12:46:53Z | [
"python",
"pandas",
"int"
] |
Mapping a dataframe based on the columns from other dataframe | 39,390,612 | <p>I have two data frames one looks like this,</p>
<pre><code>df1.head()
#CHR Start End Name
chr1 141474 173862 SAP
chr1 745489 753092 ARB
chr1 762988 794826 SAS
chr1 1634175 1669127 ETH
chr1 2281853 2284259 BRB
</code></pre>
<p>And second datafarme looks as follows,</p>
<pre><code>df2.head... | 1 | 2016-09-08T12:13:55Z | 39,391,207 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>df = pd.merge(df1, df... | 1 | 2016-09-08T12:40:00Z | [
"python",
"pandas",
"numpy",
"indexing",
"merge"
] |
Melding several columns by unique value | 39,390,616 | <p>I have a dataset with a lot of columns. The data is structured like this:</p>
<pre><code>id Artist 1 Artist 2 Artist 3
1 Red hot
2 Wiz Red hot
3 Red hot Wiz Bronson
4 Bronson Bruce Red hot
5 Wiz Bronson
6 Red Hot
</code></pre>
<p>And I need it to ... | 0 | 2016-09-08T12:14:19Z | 39,390,849 | <p>I think you can use:</p>
<pre><code>#if column `id` is not index, first set it to index
df.set_index('id', inplace=True)
#create multiindex from columns
df.columns = df.columns.str.split(expand=True)
print (df)
Artist
1 2 3
id
1 Red hot ... | 0 | 2016-09-08T12:23:49Z | [
"python",
"excel",
"pandas"
] |
Where should I locate my Python file if I want to use virtualenv? | 39,390,639 | <p>I have a virtual environment and I do not know where should I save my Python file ? it only works when I run it in <code>/home/jojo/Enviroment/venv1</code> can I save it in other place ? Especially when I want to use PyCharm thank you </p>
| 0 | 2016-09-08T12:15:40Z | 39,391,137 | <p>virtualenv and your code base <strong>can</strong> very well be in different locations. I prefer things this way. Here are sample commands that I use. </p>
<p><strong>Step 1</strong>: Activate the virtualenv.</p>
<pre><code>[mayank@demo /dev]$ source /usr/local/pyenv3.4/bin/activate
(pyenv3.4)[mayank@demo dev]$
... | 1 | 2016-09-08T12:37:02Z | [
"python",
"pycharm",
"virtualenv"
] |
Getting contents of an lxml.objectify comment | 39,390,653 | <p>I have an XML file that I'm reading using python's <code>lxml.objectify</code> library.</p>
<p>I'm not finding a way of getting the contents of an XML comment:</p>
<pre><code><data>
<!--Contents 1-->
<some_empty_tag/>
<!--Contents 2-->
</data>
</code></pre>
<p>I'm able to retri... | 0 | 2016-09-08T12:16:08Z | 39,391,003 | <p>You just need to convert the child back to string to extract the comments, like this:</p>
<pre><code>In [1]: from lxml import etree, objectify
In [2]: tree = objectify.fromstring("""<data>
...: <!--Contents 1-->
...: <some_empty_tag/>
...: <!--Contents 2-->
...: </data&... | 0 | 2016-09-08T12:31:10Z | [
"python",
"lxml.objectify"
] |
Reading math function issue | 39,390,899 | <p>Here is my code</p>
<pre><code>import math
try:
valor = float(input("Give a real number "))
print("Your value given is: ", value)
except ValueError:
print("You gave a value not interpretable as a real onel!!")
</code></pre>
<p>And when my input is <code>sqrt(2)</code>, I got this error, anyone knows... | 0 | 2016-09-08T12:25:46Z | 39,391,510 | <p>As you can see from the <a href="https://docs.python.org/2/library/functions.html#input" rel="nofollow">doc</a>, <code>input</code> is equivalent to <code>eval(raw_input(prompt))</code>, but you can still make it work:</p>
<pre><code>>>> import math
>>> input()
math.sqrt(2)
1.4142135623730951
>... | 0 | 2016-09-08T12:53:18Z | [
"python",
"math",
"input",
"nameerror"
] |
Getting GET in django view | 39,390,919 | <p>I have this URL pattern to get to my view: </p>
<pre><code>url(r'^api/cabinet/(?P<cabinetid>[0-9]+)/bin/$', views.api_cabinetbin),
</code></pre>
<p>and pointing my browser to <code>http://domain/api/cabinet/10/bin/</code> gives me the info on cabinet 10.</p>
<p>I would like to put some extra info to the URL... | 1 | 2016-09-08T12:27:06Z | 39,391,614 | <p>Turns out, <code>format</code> has some magical properties in Django REST framework.</p>
<p>Using another variable did work.</p>
| 2 | 2016-09-08T12:57:59Z | [
"python",
"django",
"django-rest-framework"
] |
Convert Model.Objects.all() to JSON in python using django | 39,390,927 | <p>I have a list of objects of the same model type. I want to iterate over this list and create a JSON to send back. I tried some things like 2-dim arrays, google,... but can't find something like this? Though I think it can't be difficult. </p>
<p>my code now is:</p>
<pre><code>def get_cashflows(request):
r... | 0 | 2016-09-08T12:27:23Z | 39,391,091 | <p>As @Ivan mentions the DRF does this out of the box if you want an API layer, but if you just want a basic view to return some json without the overhead of configuring a new package then it should be a fairly simple operation with django's serializers:</p>
<pre><code>from django.core import serializers
def get_cash... | 0 | 2016-09-08T12:35:14Z | [
"python",
"json",
"django"
] |
Finding craters [descending/ ascending ints] in a python list of ints | 39,391,007 | <p>I have a list of ints in python, and I would like the output to be a list of different "craters" in the sequence. I define a crater as a sequence of numbers that begins with descending ints that gradually grow bigger, until they reach a number that is equal to the first int of the crater or greater than the first in... | 2 | 2016-09-08T12:31:17Z | 39,392,144 | <p>Here is what I came with:</p>
<pre><code>def find_crater(my_list):
previous = None
current_crater = []
crater_list = []
for elem in my_list:
#For the first element
if not previous:
previous = elem
continue
if len(current_crater) == 0:
if ... | 0 | 2016-09-08T13:22:11Z | [
"python",
"list",
"int"
] |
Finding craters [descending/ ascending ints] in a python list of ints | 39,391,007 | <p>I have a list of ints in python, and I would like the output to be a list of different "craters" in the sequence. I define a crater as a sequence of numbers that begins with descending ints that gradually grow bigger, until they reach a number that is equal to the first int of the crater or greater than the first in... | 2 | 2016-09-08T12:31:17Z | 39,392,602 | <p>Try this:</p>
<p>We just slice the list finding <code>start_index:end_index</code> making three cases</p>
<ul>
<li>When element is equal</li>
<li>When element is greater </li>
<li>Boundary case when last element even if smaller may need to be sliced</li>
</ul>
<hr>
<pre><code>def find_crater(l):
result =... | 0 | 2016-09-08T13:43:43Z | [
"python",
"list",
"int"
] |
Finding craters [descending/ ascending ints] in a python list of ints | 39,391,007 | <p>I have a list of ints in python, and I would like the output to be a list of different "craters" in the sequence. I define a crater as a sequence of numbers that begins with descending ints that gradually grow bigger, until they reach a number that is equal to the first int of the crater or greater than the first in... | 2 | 2016-09-08T12:31:17Z | 39,392,656 | <p>Presuming your expected output is wrong which it seems to be, all you want to do is go until you find an element >= to the start of the chain and catch chains that only contain a single element:</p>
<pre><code>def craters(lst):
it = iter(lst)
# get start of first chain
first = next(it)
tmp = [first]... | 0 | 2016-09-08T13:46:08Z | [
"python",
"list",
"int"
] |
Exception handling in Django of queryset | 39,391,068 | <p>I'm trying to catch an exception if a user does not exist and redirect if that's the case. </p>
<p>When I run this I get an error saying:</p>
<blockquote>
<p>'NoneType' object is not iterable</p>
</blockquote>
<pre><code>try:
return {'sub_user': User.objects.get(username=username)}
except User.DoesNotExist:... | -1 | 2016-09-08T12:34:38Z | 39,391,185 | <p>The problem is not in how you catch the exception.</p>
<p>You need to return the result of the call to <code>redirect</code>.</p>
| 2 | 2016-09-08T12:39:09Z | [
"python",
"django",
"python-3.x"
] |
Extracting hand writing text out in shape with OpenCV | 39,391,080 | <p>I am very new to OpenCV Python and I really need some help here.</p>
<p>So what I am trying to do here is to extract out these words in the image below.</p>
<p><a href="http://i.stack.imgur.com/XsSOP.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/XsSOP.jpg" alt="hand drawn image"></a></p>
<p>The words and... | 0 | 2016-09-08T12:35:00Z | 39,394,512 | <p>You can use the fact that the connected component of the letters are much smaller than the large strokes of the rest of the diagram.</p>
<p>I used opencv3 connected components in the code but you can do the same things using findContours.</p>
<p>The code:</p>
<pre><code>import cv2
import numpy as np
# Params
max... | 2 | 2016-09-08T15:09:46Z | [
"python",
"opencv"
] |
How to use opencv functions in C++ file and bind it with Python? | 39,391,136 | <p>I want to pass an image from python script to c++ code for opencv computations. To bind the two I have followed <a href="https://github.com/Algomorph/pyboostcvconverter" rel="nofollow">this</a>. The binding is working fine But when I use any opencv in-built functions it gives me error. </p>
<p>Traceback (most recen... | 0 | 2016-09-08T12:37:02Z | 39,407,557 | <p>It could be that you have to edit the CMakeLists.txt in line 27 <code>find_package(OpenCV COMPONENTS core REQUIRED)</code> and add more components like <code>find_package(OpenCV COMPONENTS core imgproc highgui REQUIRED)</code></p>
| 0 | 2016-09-09T08:51:53Z | [
"python",
"c++",
"opencv",
"binding"
] |
python XML find and replace | 39,391,157 | <p>After fighting a day with python / etree without considerable success:</p>
<p>I have a xml file (items.xml)</p>
<pre><code><symbols>
<symbol>
<layer class="SvgMarker">
<prop k="size" v="6.89"/>
</layer>
</symbol>
<symbol>
<... | 0 | 2016-09-08T12:38:02Z | 39,391,909 | <p>You need to take care of hierarchy in xml tags and their type conversion to perform multiplication. I tested below code with your xml, it works fine.</p>
<pre><code>import xml.etree.ElementTree as ET
tree = ET.parse('homemade.xml') #Step 1
root = tree.getroot()
for symbol in tree.findall('symbol'):
... | 0 | 2016-09-08T13:12:05Z | [
"python",
"xml"
] |
python XML find and replace | 39,391,157 | <p>After fighting a day with python / etree without considerable success:</p>
<p>I have a xml file (items.xml)</p>
<pre><code><symbols>
<symbol>
<layer class="SvgMarker">
<prop k="size" v="6.89"/>
</layer>
</symbol>
<symbol>
<... | 0 | 2016-09-08T12:38:02Z | 39,392,330 | <p>This would help you</p>
<pre><code>import xml.etree.ElementTree as ET
tree = ET.parse('test.xml') # Path to input file
root = tree.getroot()
for prop in root.iter('.//*[@class="SvgMarker"]/prop'):
prop.set('v', str(float(prop.get('v')) * 1.5))
tree.write('out.xml', encoding="UTF-8")
</code></pre>
<p>Ref: <a ... | 0 | 2016-09-08T13:30:25Z | [
"python",
"xml"
] |
using x.reshape on a 1D array in sklearn | 39,391,275 | <p>I tried to use sklearn to use a simple decision tree classifier, and it complained that using a 1D array is now depricated and must use X.reshape(1,-1). So I did but it has turned my labels list to a list of lists with only one element so number of labels and samples do not match now. Another words my list of labels... | 0 | 2016-09-08T12:42:40Z | 39,392,612 | <p>You are reshaping the wrong thing. Reshape the data your are predicting on, not your labels.</p>
<pre><code>>>> clf.predict(np.array([150,0]).reshape(1,-1))
array([1])
</code></pre>
<p>Your labels have to align with your training data (features) ,so the length of both arrays should be the same. If labels ... | 1 | 2016-09-08T13:44:28Z | [
"python",
"scikit-learn"
] |
How to change number of iterations in maxent classifier for POS Tagging in NLTK? | 39,391,280 | <p>I am trying to perform POS tagging using <code>ClassifierBasedPOSTagger</code> with <code>classifier_builder=MaxentClassifier.train</code>. Here is the piece of code:</p>
<pre><code>from nltk.tag.sequential import ClassifierBasedPOSTagger
from nltk.classify import MaxentClassifier
from nltk.corpus import brown
bro... | 0 | 2016-09-08T12:42:45Z | 39,392,005 | <p>You can set parameter value of <code>max_iter</code> to desired number.</p>
<p><strong>Code:</strong></p>
<pre><code>from nltk.tag.sequential import ClassifierBasedPOSTagger
from nltk.classify import MaxentClassifier
from nltk.corpus import brown
brown_tagged_sents = brown.tagged_sents(categories='news')
# Change... | 1 | 2016-09-08T13:15:48Z | [
"python",
"nlp",
"classification",
"nltk"
] |
Detect automatic item selection in a Listbox using Tkinter | 39,391,439 | <p>I mean, for Buttons you can write something like this: </p>
<pre><code>def addItem():
pass
addbtn = Button(mainFrame, text = "Add Item", command = addItem)
</code></pre>
<p>How can I do the same thing for a Listbox? Like this one for example:</p>
<pre><code>def on_selection():
pass
list = Listbox(mainFra... | -1 | 2016-09-08T12:50:27Z | 39,403,827 | <pre><code>import tkinter as tk
root = tk.Tk()
def on_selection(event):
print(dir(event))
def some_nonevent():
print(str(2 + 2))
listbox = tk.Listbox(root, selectmode=tk.SINGLE, activestyle='none')
for name in ['john', 'tim', 'sam', 'jill', 'sandra']:
listbox.insert(tk.END, name)
listbox.bind('<<Listbo... | 0 | 2016-09-09T04:22:05Z | [
"python",
"events",
"tkinter",
"listbox"
] |
defining max and min yaxis values after using ax.set_yscale('log') in matplotlib python | 39,391,589 | <p>I generated the following chart:</p>
<p><a href="http://i.stack.imgur.com/R8wui.png" rel="nofollow"><img src="http://i.stack.imgur.com/R8wui.png" alt="Regular Chart"></a></p>
<p>Then wanted to adjust the vertical axis of the first subplot to show in logscale,
so did <code>ax.set_yscale('log')</code>.</p>
<p>This... | 1 | 2016-09-08T12:57:05Z | 39,391,963 | <p>The same as you do on any other scale, use <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_ylim" rel="nofollow"><code>ax.set_ylim()</code></a></p>
<p>If you want to set it to the range 8,20 as you have above, then pass those two limits to <code>set_ylim</code>:</p>
<pre><code>ax.set_ylim(... | 1 | 2016-09-08T13:14:16Z | [
"python",
"matplotlib"
] |
Gaps in border around text | 39,391,592 | <p>I would like to add a border around some texts in a matplotlib plot, which I can do using <code>patheffects.withStroke</code>. However, for some letters and number there is a small gap to the top right of the symbol.</p>
<p>Is there a way to not have this gap?</p>
<p>Minimal working example:</p>
<pre><code>import... | 2 | 2016-09-08T12:57:14Z | 39,393,019 | <p>The documentation does not mention it (or I did not found it) but, searching in the code, we can see that the <code>patheffects.withStroke</code> method accepts a lot of keyword arguments.</p>
<p>You can have the list of those keyword arguments by executing this in interactive session:</p>
<pre><code>>>> ... | 2 | 2016-09-08T14:02:25Z | [
"python",
"matplotlib"
] |
ValueError: import data via chunks into pandas.csv_reader() | 39,391,597 | <p>I have a large <code>gzip</code> file which I would like to import into a pandas dataframe. Unfortunately, the file has an uneven number of columns. The data has roughly this format: </p>
<pre><code>.... Col_20: 25 Col_21: 23432 Col22: 639142
.... Col_20: 25 Col_22: 25134 Col23: 243344
.... Col_21: 75 ... | 1 | 2016-09-08T12:57:21Z | 39,391,888 | <p>You could also try this:</p>
<pre><code>for chunk in pd.read_csv(filename, sep='\t', chunksize=10**5, engine='python', error_bad_lines=False):
print(chunk)
</code></pre>
<p><code>error_bad_lines</code> would skip bad lines thought. I will see if a better alternative can be found</p>
<p>EDIT: In order to maintain ... | 1 | 2016-09-08T13:11:00Z | [
"python",
"pandas",
"chunking"
] |
Django 'instancemethod' object has no attribute '__getitem__' | 39,391,611 | <p>Html</p>
<pre><code> <ul class="dropdown-menu" role="menu">
<li>java <input type="checkbox" name="categories[]" value="Java"></li>
<li class="divider"></li>
<li>c <input type="checkbox" name="categories[]" value="C"></li>
<li class="... | 2 | 2016-09-08T12:57:53Z | 39,391,709 | <p>Change </p>
<pre><code>list_categories = request.POST.getlist['categories']
</code></pre>
<p>for</p>
<pre><code>list_categories = request.POST.getlist('categories')
</code></pre>
<p><code>getlist</code> is a method, so the syntax requires parenthesis.</p>
| 2 | 2016-09-08T13:02:40Z | [
"python",
"django"
] |
doc2vec How to cluster DocvecsArray | 39,391,753 | <p>I've patched the following code from examples I've found over the web:</p>
<pre><code># gensim modules
from gensim import utils
from gensim.models.doc2vec import LabeledSentence
from gensim.models import Doc2Vec
from sklearn.cluster import KMeans
# random
from random import shuffle
# classifier
class LabeledLine... | 1 | 2016-09-08T13:04:24Z | 39,392,564 | <p>So it looks like you're almost there.</p>
<p>You are outputting a set of vectors. For the sklearn package, you have to put those into a numpy array - using the numpy.toarray() function would probably be best. <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_iris.html" rel="nofollow">The do... | 0 | 2016-09-08T13:41:40Z | [
"python",
"machine-learning",
"k-means",
"word2vec",
"doc2vec"
] |
jinja2: including script, replacing {{variable}} and json encoding the result | 39,391,789 | <p>I'm attempting to build a json document using Jinja2 and the document has a nested script. The script contains <code>{{<variables>}}</code> that I need to replace along with non-json characters. Therefore, the script needs to be json-escaped afterwards using <code>json.dumps()</code>.</p>
<p><code>str = '{
... | 0 | 2016-09-08T13:06:01Z | 39,412,150 | <p>Solved this in a way that feels a little hackish, so I'd love some feedback. When instantiating my class, I defined a global function called <code>include_script</code>:</p>
<pre><code>loader = jinja2.FileSystemLoader(templates_folder)
env = inja2.Environment(loader=self.loader)
env.globals['include_script'] = ren... | 0 | 2016-09-09T12:57:01Z | [
"python",
"json",
"jinja2"
] |
jinja2: including script, replacing {{variable}} and json encoding the result | 39,391,789 | <p>I'm attempting to build a json document using Jinja2 and the document has a nested script. The script contains <code>{{<variables>}}</code> that I need to replace along with non-json characters. Therefore, the script needs to be json-escaped afterwards using <code>json.dumps()</code>.</p>
<p><code>str = '{
... | 0 | 2016-09-08T13:06:01Z | 39,418,644 | <p>Given the (incomplete) example it seems you are searching the <code>filter</code> tag.</p>
<p>First the script in a form that's actually runnable and defines a <code>json</code> filter in terms of <code>json.dumps()</code>:</p>
<pre><code>import json
import jinja2
loader = jinja2.FileSystemLoader('templates')
env... | 0 | 2016-09-09T19:37:04Z | [
"python",
"json",
"jinja2"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.