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 |
|---|---|---|---|---|---|---|---|---|---|
php exec function doesn't work correct | 38,523,675 | <p>I'm using Python beside Laravel on my PC , I Have Installed Python .
when I try to run a python code which is in a file via command line ( Windows ) , there is no problem , but when I attempt to run that file via :<br></p>
<pre><code>exec("python ".__DIR__.'\new.py');
</code></pre>
<p>from my routes.php document ,... | 0 | 2016-07-22T10:05:42Z | 38,523,845 | <p>It look like the <code>__DIR__</code> constant doesn't add the final slash.
Try using something like this:</p>
<pre><code>exec("python ".__DIR__.DIRECTORY_SEPARATOR."new.py");
</code></pre>
<p>(Sorry for my english!)</p>
| 0 | 2016-07-22T10:13:53Z | [
"php",
"python",
"laravel",
"laravel-5",
"exec"
] |
Trying to get ironpython to create a text file that I can store info in | 38,523,771 | <p>I'm writing a gui for ironpython and I'm trying create a text file that the user can name in a textbox. The textfile is being used to give me a python script from a vector file. Any suggestions</p>
| 0 | 2016-07-22T10:10:03Z | 38,528,335 | <p>With the following I was able to create a file with IronPython</p>
<pre><code>ScriptEngine m_engine = Python.CreateEngine();
ScriptScope m_scope = m_engine.CreateScope();
String code = @"file = open('myfile.txt', 'w+')";
ScriptSource source = m_engine.CreateScriptSourceFromString(code, SourceCodeKind.SingleStatemen... | 0 | 2016-07-22T13:57:55Z | [
"c#",
"python",
"visual-studio-2013",
"ironpython"
] |
Trying to get ironpython to create a text file that I can store info in | 38,523,771 | <p>I'm writing a gui for ironpython and I'm trying create a text file that the user can name in a textbox. The textfile is being used to give me a python script from a vector file. Any suggestions</p>
| 0 | 2016-07-22T10:10:03Z | 38,566,514 | <p>I am putting up the code that worked for me when I was writing in python. Hope it helps.</p>
<pre><code>def on_save_as(self, sender, e):
dlg = SaveFileDialog()
dlg.Filter = "Text File (*.txt)|*.txt"
dlg.Title = "SaveFile"
if dlg.ShowDialog():
self.save_file(dlg.FileName)
def save_file(self... | 0 | 2016-07-25T11:26:31Z | [
"c#",
"python",
"visual-studio-2013",
"ironpython"
] |
Variable shift in Pandas | 38,523,920 | <p>having two columns A and B in a dataframe: </p>
<pre><code> A B
0 1 6
1 2 7
2 1 8
3 2 9
4 1 10
</code></pre>
<p>I would like to create a column C. C must have values of B shifted by value of A:</p>
<pre><code> A B C
0 1 6 NaN
1 2 7 NaN
2 1 8 7
3 2 9 7
4 1 10 9
</code><... | 2 | 2016-07-22T10:17:50Z | 38,524,134 | <p>This is tricky due to index alignment, you can define a user func and <code>apply</code> row-wise on your df, here the function will perform a shift on the B column and return the index value (using <code>.name</code> attribute to return the index) of the shifted column:</p>
<pre><code>In [134]:
def func(x):
... | 0 | 2016-07-22T10:27:45Z | [
"python",
"pandas",
"shift"
] |
Change Cython's naming rules for .so files | 38,523,941 | <p>I'm using Cython to generate a shared object out of Python module. The compilation output is written to <code>build/lib.linux-x86_64-3.5/<Package>/<module>.cpython-35m-x86_64-linux-gnu.so</code>. Is there any option to change the naming rule? I want the file to be named <code><module>.so</code> wit... | 1 | 2016-07-22T10:18:51Z | 38,525,461 | <p>Seems like <code>setuptools</code> provides no option to change or get rid of the suffix completely. The magic happens in <code>distutils/command/build_ext.py</code>: </p>
<pre><code>def get_ext_filename(self, ext_name):
from distutils.sysconfig import get_config_var
ext_path = ext_name.split('.')
ext_s... | 1 | 2016-07-22T11:35:47Z | [
"python",
"cython"
] |
Python Pandas, create empty DataFrame specifying column dtypes | 38,523,965 | <p>There is one thing that I find myself having to do quite often, and it surprises me how difficult it is to achieve this in Pandas. Suppose I need to create an empty <code>DataFrame</code> with specified index type and name, and column types and names. (I might want to fill it later, in a loop for example.) The easie... | 1 | 2016-07-22T10:19:52Z | 38,524,255 | <p>Unfortunately the <code>DateFrame</code> ctor accepts a single <code>dtype</code> descriptor, however you can cheat a little by using <code>read_csv</code>:</p>
<pre><code>In [143]:
import pandas as pd
import io
cols=["id", "name", "score", "height", "weight"]
df = pd.read_csv(io.StringIO(""), names=cols, dtype=dic... | 2 | 2016-07-22T10:33:41Z | [
"python",
"pandas",
"dataframe"
] |
Python Pandas, create empty DataFrame specifying column dtypes | 38,523,965 | <p>There is one thing that I find myself having to do quite often, and it surprises me how difficult it is to achieve this in Pandas. Suppose I need to create an empty <code>DataFrame</code> with specified index type and name, and column types and names. (I might want to fill it later, in a loop for example.) The easie... | 1 | 2016-07-22T10:19:52Z | 39,509,517 | <p>You can set the dtype of a DataFrame's column also by replacing it:</p>
<pre><code>df['column_name'] = df['column_name'].astype(float)
</code></pre>
| 0 | 2016-09-15T11:05:44Z | [
"python",
"pandas",
"dataframe"
] |
Python Pandas, create empty DataFrame specifying column dtypes | 38,523,965 | <p>There is one thing that I find myself having to do quite often, and it surprises me how difficult it is to achieve this in Pandas. Suppose I need to create an empty <code>DataFrame</code> with specified index type and name, and column types and names. (I might want to fill it later, in a loop for example.) The easie... | 1 | 2016-07-22T10:19:52Z | 39,510,423 | <p>You simplify things a little by using a list comprehension</p>
<pre><code>def create_empty_dataframe():
index = pandas.Index([], name="id", dtype=int)
# specify column name and data type
columns = [('name', str),
('score', int),
('height', float),
('weight',... | 0 | 2016-09-15T11:55:53Z | [
"python",
"pandas",
"dataframe"
] |
switching rows and columns in dataframe | 38,524,060 | <p>I have a dataframe that looks like the following:</p>
<pre><code>import pandas as pd
datelisttemp = pd.date_range('1/1/2014', periods=3, freq='D')
s = list(datelisttemp)*3
s.sort()
df = pd.DataFrame({'day':s,'stats':['mean','var','std','mean','var','std','mean','var','std'], 's1':[21 ,25 ,27 ,42 ,4 ,74 ,63 ,67, 6],... | 3 | 2016-07-22T10:24:11Z | 38,524,543 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>. Last <code>reset_index</code>, rename... | 2 | 2016-07-22T10:47:51Z | [
"python",
"pandas",
"dataframe"
] |
Parse User name for extracting user location Twitter | 38,524,071 | <p>I am trying to scrape user location with respect to user names from twitter. </p>
<p>Input: The user list has more than 50K User names </p>
<pre><code>AkkiPritam,6.77E+17,12/15/2015,#chennaifloods
AkkiPritam,6.77E+17,12/15/2015,#bhoomikatrust
AkkiPritam,6.77E+17,12/15/2015,#akshaykumar
gischethans,6.77E+17,12/15/2... | -3 | 2016-07-22T10:24:48Z | 38,525,522 | <p>You are using 'data' to define your DataFrame and 'df' for what I think should be the columns of the DataFrame</p>
<pre><code>data = pd.read_csv('user_keyword.csv')
df = ['user_name', 'user_id', 'date', 'keyword']
</code></pre>
<p>I assume that the user_keyword.csv file has no header, try adding:</p>
<pre><code>d... | 1 | 2016-07-22T11:39:02Z | [
"python",
"pandas",
"twitter",
"geolocation",
"latitude-longitude"
] |
Scrapy Change Items Order | 38,524,090 | <p>I'm scraping some data and exporting it to a json file, but i cant seem to set the order of the items. After doing some reading i found scrapy Items are wrappers of python dict and will return the item fields in an unpredicted order. </p>
<p>i have tried adding: </p>
<pre><code> def keys(self):
return ['ite... | 0 | 2016-07-22T10:25:34Z | 38,551,719 | <p>In JSON, an object is defined thus:</p>
<pre><code>An object is an unordered set of name/value pairs.
</code></pre>
<p>See <a href="http://json.org" rel="nofollow">http://json.org</a>.</p>
<p>Most implementations of JSON make no effort to preserve the order of an object's name/value pairs, since it is (by definit... | 0 | 2016-07-24T11:55:06Z | [
"python",
"python-2.7",
"scrapy",
"scrapy-spider"
] |
python script for creating maproxy OGC WMS service using Mapnik and PostGIS | 38,524,212 | <p>Would that be possible to create programatically a new OGC WMS (1.1/1/3) service using:</p>
<ol>
<li>Python</li>
<li>MapProxy</li>
<li>Mapnik</li>
<li>PostGIS/Postgres</li>
</ol>
<p>any script/gist or sample would be more then appreciated.</p>
<p>Cheers, M</p>
| 0 | 2016-07-22T10:32:20Z | 39,139,392 | <p>In general everything is about configuration files. I create automatically new WMS endpoints for my Mapserver/Mapproxy setup with a python script, which also process my images.</p>
<p>MapServer config-pattern:</p>
<pre><code>MAP
NAME "WMS Server"
#IMAGECOLOR 255 255 255
IMAGETYPE custom
TRANSPARENT OFF
C... | 0 | 2016-08-25T07:41:09Z | [
"python",
"postgis",
"mapnik"
] |
python script for creating maproxy OGC WMS service using Mapnik and PostGIS | 38,524,212 | <p>Would that be possible to create programatically a new OGC WMS (1.1/1/3) service using:</p>
<ol>
<li>Python</li>
<li>MapProxy</li>
<li>Mapnik</li>
<li>PostGIS/Postgres</li>
</ol>
<p>any script/gist or sample would be more then appreciated.</p>
<p>Cheers, M</p>
| 0 | 2016-07-22T10:32:20Z | 39,417,434 | <p>If we are looking for publish data in postgres to WMS, enable tilecache, and use more advanced rendering engine like mapnik, then I would say there could be one component missing is the GIS server.</p>
<p>So if I am guessing your requirement correctly as I mentioned earlier then here is what the system design could... | 0 | 2016-09-09T18:10:04Z | [
"python",
"postgis",
"mapnik"
] |
What file does the python symlink point to | 38,524,275 | <p>I bought my mac about a year ago and somehow changed my python symlink so that when I run <code>python some_file.py</code>, python 3.4 is used to run the file instead of python 2.7. I now need to change it back, but I can't figure out what I did to change it in the first place! When I run:</p>
<pre><code>import os
... | 0 | 2016-07-22T10:34:39Z | 38,524,389 | <p>You probably installed that specific Python version using the official Python installer for OS X; see the <a href="https://docs.python.org/2/using/mac.html" rel="nofollow"><em>Using Python on a Macintosh</em> documentation</a>. The installer creates the <code>/usr/local/bin</code> symlink for you.</p>
<p>If you als... | 1 | 2016-07-22T10:40:44Z | [
"python",
"python-2.7",
"python-3.x"
] |
Declaring decorator inside a class | 38,524,332 | <p>I'm trying to use custom wrappers/decorators in Python, and I'd like to declare one <strong>inside</strong> a class, so that I could for instance print a snapshot of the attributes. I've tried things from <a href="http://stackoverflow.com/q/11740626/5018771">this question</a> with no success.</p>
<hr>
<p>Here is w... | 2 | 2016-07-22T10:37:23Z | 38,524,579 | <p>You will need to handle <code>self</code> explicitly.</p>
<pre><code>class TestWrapper():
def __init__(self, a, b):
self.a = a
self.b = b
self.c = 0
def enter_exit_info(func):
def wrapper(self, *arg, **kw):
print '-- entering', func.__name__
print '--... | 7 | 2016-07-22T10:49:36Z | [
"python",
"python-2.7",
"wrapper",
"decorator",
"python-decorators"
] |
Declaring decorator inside a class | 38,524,332 | <p>I'm trying to use custom wrappers/decorators in Python, and I'd like to declare one <strong>inside</strong> a class, so that I could for instance print a snapshot of the attributes. I've tried things from <a href="http://stackoverflow.com/q/11740626/5018771">this question</a> with no success.</p>
<hr>
<p>Here is w... | 2 | 2016-07-22T10:37:23Z | 38,524,581 | <p>Instead of defining the decorator inside the class you can just intercept the <code>self</code> parameter:</p>
<pre><code>def enter_exit_info(func):
def wrapper(self, *arg, **kw):
print '-- entering', func.__name__
print '-- ', self.__dict__
res = func(self, *arg, **kw)
print '--... | 0 | 2016-07-22T10:49:46Z | [
"python",
"python-2.7",
"wrapper",
"decorator",
"python-decorators"
] |
Declaring decorator inside a class | 38,524,332 | <p>I'm trying to use custom wrappers/decorators in Python, and I'd like to declare one <strong>inside</strong> a class, so that I could for instance print a snapshot of the attributes. I've tried things from <a href="http://stackoverflow.com/q/11740626/5018771">this question</a> with no success.</p>
<hr>
<p>Here is w... | 2 | 2016-07-22T10:37:23Z | 38,524,704 | <p>TL;DR : what you want is</p>
<pre><code>def enter_exit_info(func):
def wrapper(self, *arg, **kw):
print '-- entering', func.__name__
print '-- ', self.__dict__
res = func(*arg, **kw)
print '-- exiting', func.__name__
print '-- ', self.__dict__
return res
retur... | 2 | 2016-07-22T10:55:49Z | [
"python",
"python-2.7",
"wrapper",
"decorator",
"python-decorators"
] |
Declaring decorator inside a class | 38,524,332 | <p>I'm trying to use custom wrappers/decorators in Python, and I'd like to declare one <strong>inside</strong> a class, so that I could for instance print a snapshot of the attributes. I've tried things from <a href="http://stackoverflow.com/q/11740626/5018771">this question</a> with no success.</p>
<hr>
<p>Here is w... | 2 | 2016-07-22T10:37:23Z | 38,525,351 | <p>Hi do you want the output should be in dictionary format?
If you don't want the output in dictionary format u can try this....</p>
<p>def enter_exit_info(func):
def wrapper(*arg, **kw):
print '-- entering', func.<strong>name</strong><br>
res = func(*arg, **kw)
print '-- e... | -1 | 2016-07-22T11:29:55Z | [
"python",
"python-2.7",
"wrapper",
"decorator",
"python-decorators"
] |
Python Pandas v0.18+: is there a way to resample a dataframe without filling NAs? | 38,524,400 | <p>I wonder if there is a way to up resample a <code>DataFrame</code> without having to decide how NAs should be filled immediately.</p>
<p>I tried the following but got the Future Warning:</p>
<blockquote>
<p>FutureWarning: .resample() is now a deferred operation use .resample(...).mean() instead of .resample(...)... | 3 | 2016-07-22T10:41:23Z | 38,524,422 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.asfreq.html" rel="nofollow"><code>Resampler.asfreq</code></a>:</p>
<pre><code>print (df.resample('B').asfreq())
A
2015-01-30 0.0
2015-02-02 NaN
2015-02-03 NaN
2015-02-04 NaN
2015-02-05 NaN
2... | 1 | 2016-07-22T10:42:31Z | [
"python",
"pandas",
"dataframe",
null,
"resampling"
] |
Extracting tables from website | 38,524,459 | <p>I am trying to get the table from Morningstar into pandas</p>
<p>Website link - <a href="http://financials.morningstar.com/cash-flow/cf.html?t=3IINFOTECH&region=ind&culture=en-US" rel="nofollow">http://financials.morningstar.com/cash-flow/cf.html?t=3IINFOTECH&region=ind&culture=en-US</a></p>
<p>Sin... | -1 | 2016-07-22T10:44:00Z | 38,532,560 | <p>You can get the data using just <em>requests</em> and <em>Beautifulsoup</em>, the html is retrieved with an ajax call:</p>
<pre><code>from bs4 import BeautifulSoup
from json import loads
import requests
from time import time
params = {'columnYear': '5', 'region': 'ind', 'rounding': '3', 'period': '12',
... | 0 | 2016-07-22T17:50:01Z | [
"python",
"pandas",
"beautifulsoup"
] |
Session cookies and http headers | 38,524,532 | <p>I'm did a login system to experiment a login script in python, the login system has a form token which i extract from the page with regex (so i can post it along with username/password after), that's what i'm trying to avoid. So i did this example code to show you, and maybe you can anser me. Is there anyway besides... | 0 | 2016-07-22T10:47:25Z | 38,525,008 | <p>You can't retrieve session variables defined in PHP this way:</p>
<blockquote>
<p>A session is a way to store information (in variables) to be used
across multiple pages.</p>
<p>Unlike a cookie, the information is not stored on the users computer.</p>
</blockquote>
<p><em>Source: <a href="http://www.w3sch... | 1 | 2016-07-22T11:11:53Z | [
"python",
"http",
"session",
"request"
] |
Set default value of field depends on other field in odoo | 38,524,745 | <p>I am setting up default value of <code>analytics_id</code> in <code>account.move.line</code> by below code</p>
<pre class="lang-py prettyprint-override"><code>class account_move_line(models.Model):
_inherit = 'account.move.line'
_name = "account.move.line"
def _get_default_account(self, cr, uid, contex... | 0 | 2016-07-22T10:58:08Z | 38,538,520 | <p>Try to use this type of code</p>
<pre class="lang-py prettyprint-override"><code>res = self.pool.get('account.analytic.plan.instance').search(cr, uid, [('code','=','LAL')], context=context)
if res:
br_analytic_plan=self.pool.get('account.analytic.plan.instance').browse(cr,uid,res[0],context=context)
if --... | 0 | 2016-07-23T05:32:46Z | [
"python",
"openerp",
"odoo-8",
"openerp-8",
"odoo-9"
] |
In tensorflow, how to iterate over a sequence of inputs stored in a tensor? | 38,524,776 | <p>I am trying RNN on a variable length multivariate sequence classification problem.</p>
<p>I have defined following function to get the output of the sequence (i.e. the output of RNN cell after the final input from sequence is fed)</p>
<pre><code>def get_sequence_output(x_sequence, initial_hidden_state):
previo... | 0 | 2016-07-22T10:59:52Z | 38,531,914 | <p>You can convert a tensor into a list using the unpack function which converts the first dimension into a list. There is also a split function which does something similar. I use unpack in an RNN model I am working on.</p>
<pre><code>y = tf.unpack(tf.transpose(y, (1, 0, 2)))
</code></pre>
<p>In this case y starts... | 1 | 2016-07-22T17:06:42Z | [
"python",
"tensorflow",
"recurrent-neural-network",
"gated-recurrent-unit"
] |
How to assign dataframe to dynamic variable to python? | 38,524,821 | <p>As a part of code,I need to assign a dataframe to a dynamic variable created during the process.</p>
<p>I did research on assigning value as below:</p>
<pre><code>I = 1
x = 'varName'+str(I)
exec("%s = %d" % (x,2))
varName1
</code></pre>
<p>But how to do it for dataframe?</p>
<p>Thanks</p>
| 0 | 2016-07-22T11:01:52Z | 38,524,988 | <p>"dynamic variables" are an antipattern. What you want is either a <code>dict</code>: </p>
<pre><code>vars = {}
key = "something_%s" % another_string
vars[key] = something()
</code></pre>
<p>or (more probably since you seem to be using some numeric index):</p>
<pre><code>vars = []
for whatever in (some_sequence):
... | 0 | 2016-07-22T11:11:04Z | [
"python",
"pandas"
] |
How to convolve array of arrays with a mask in Python? | 38,524,847 | <p>Given a t1xt2xn array and a m1xm2 mask, how to obtain the t1xt2xn array where the n-dim arrays are convolved with the mask?</p>
<p>The function scipy.signal.convolve is not able to handle this because it only accept inputs with same number of dimensions.</p>
<p>Example with the "same" logic:</p>
<pre><code>in1 =
... | 1 | 2016-07-22T11:03:36Z | 38,527,060 | <p>I'm very sorry but I haven't strong math background, so my answer could be wrong. Anyway, if you need to use mask for selecting you should convert it to bool type. For example:</p>
<pre><code>in1 = np.array([[[0,1,2], [3,4,5], [6,7,8]],
[[9,10,11], [12,13,14], [15,16,17]],
[[1... | 0 | 2016-07-22T12:56:34Z | [
"python",
"mask",
"convolution"
] |
Anaconda 3 for Linux Has No ensurepip? | 38,524,856 | <p>This is my environment:</p>
<ul>
<li><p>CentOS 64-bit 7.2.1511</p></li>
<li><p>Anaconda 3 4.1.1 64-bit (Python 3.5.2)</p></li>
</ul>
<p>I want to create venv virtual environment by <code>pyvenv</code>. Unfortunately, I got this error message:</p>
<p><code>$ pyvenv test
Error: Command '['/root/test/bin/python', '-... | 2 | 2016-07-22T11:04:30Z | 39,114,277 | <p>Yes, Anaconda3/2 for Linux and Mac OS do not have <code>ensurepip</code> installed. </p>
<p>According to <a href="https://github.com/ContinuumIO/anaconda-issues/issues/952" rel="nofollow">this issue record</a>, it is NOT a bug, this is done <em>intentionally</em> when the Python in Anaconda being compiled without t... | 2 | 2016-08-24T04:09:57Z | [
"python",
"anaconda",
"python-venv"
] |
pip install mysql-connector==2.1.3 fails | 38,524,946 | <pre><code>(ENV)$ pip install mysql-connector==2.1.3
Collecting mysql-connector==2.1.3
Using cached mysql-connector-2.1.3.zip
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector
usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: -c --help [cmd1 cmd... | 0 | 2016-07-22T11:09:12Z | 38,525,912 | <p>Your setuptools version might be outdated.
try upgrading pip:</p>
<pre><code>pip install --upgrade setuptools
</code></pre>
<p>You can find information about this error in this thread:</p>
<p><a href="http://stackoverflow.com/questions/14296531/what-does-error-option-single-version-externally-managed-not-recogniz... | 0 | 2016-07-22T12:00:28Z | [
"python",
"mysql",
"pip"
] |
Python: Recursive Structs | 38,524,949 | <p>I have problem with <a href="https://thrift.apache.org/" rel="nofollow">thrift</a> code generator or python.</p>
<p>Code sample (generated by thrift):</p>
<pre><code>class SomeClass:
spec = (
(1, (SomeClass, SomeClass.spec)),
)
</code></pre>
<p>Error message:</p>
<pre><code>NameError: name 'S... | 0 | 2016-07-22T11:09:18Z | 38,525,700 | <p>Try to replace the code with the following code snippet, Note: it is using lists instead of tuples since tuples are immutable.</p>
<pre><code>class SomeClass:
spec = None
@classmethod
def init(cls):
cls.spec = []
cls.spec.append( [ 1 , (cls, cls.spec) ] )
SomeClass.init()
print( SomeCl... | 1 | 2016-07-22T11:48:20Z | [
"python",
"recursion",
"structure",
"thrift"
] |
Python: Recursive Structs | 38,524,949 | <p>I have problem with <a href="https://thrift.apache.org/" rel="nofollow">thrift</a> code generator or python.</p>
<p>Code sample (generated by thrift):</p>
<pre><code>class SomeClass:
spec = (
(1, (SomeClass, SomeClass.spec)),
)
</code></pre>
<p>Error message:</p>
<pre><code>NameError: name 'S... | 0 | 2016-07-22T11:09:18Z | 38,527,916 | <p>Seems, thats python's genered code contains useless field </p>
<pre><code>SomeClass.spec
</code></pre>
<p>So i just delete it.</p>
<p>I compared this with java generated code.</p>
<p><strong>If someone will use my solution dont forget to change generated methods, thats check, when your spec!=None</strong> </p>
| 0 | 2016-07-22T13:37:56Z | [
"python",
"recursion",
"structure",
"thrift"
] |
Max tablename length with registerTempTable in Python | 38,524,981 | <p>I am a absolute novice in python and this is a very basic question to which I could not find an answer while searching.</p>
<p>I am using <strong>registerTempTable</strong> function to register a dataframe as table, I wanted to check what is the max length there can be for the tablename? To test I used up to 70 cha... | 0 | 2016-07-22T11:10:48Z | 38,537,603 | <p>If you are working with a HiveContext, then the max length of a table name should be the max length allowed by Hive/Metastore (last time I checked, were 128 characters), probably the same thing happen with SqlContext.</p>
| 0 | 2016-07-23T02:36:45Z | [
"python",
"pyspark"
] |
Generate list of dictionaries without adjacent dictionary key/values equal | 38,525,024 | <p>I have a sorted list based on the value for key <code>name</code> as below:</p>
<pre><code>s = [{'name': 'Bart', 'age': 12}, {'name': 'Bart', 'age': 19}, {'name': 'Bart', 'age': 1},{'name': 'Homer', 'age': 30}, {'name': 'Homer', 'age': 12},{'name': 'Simpson', 'age': 19}]
</code></pre>
<p>I want to arrange the elem... | 0 | 2016-07-22T11:12:28Z | 38,525,492 | <p>I wrote this according to your requirements, though it is not as condensed:</p>
<pre><code>s = [{'name': 'Bart', 'age': 12}, {'name': 'Bart', 'age': 19}, {'name': 'Bart', 'age': 1},
{'name': 'Homer', 'age': 30}, {'name': 'Homer', 'age': 12},{'name': 'Simpson', 'age': 19}]
res=[]
for m,n in zip(s, reversed(s))... | 1 | 2016-07-22T11:37:10Z | [
"python",
"lambda"
] |
Python Data Scraping | 38,525,038 | <p>Data Scraping in Pyhton.
Code is working fine but it is showing the error which I mentioned below.
What could be the reason?</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
from xlwt import workbook
wb = Workbook()
sheet1 = wb.add_sheet('Sheet1')
soup = BeautifulSoup(urllib2.urlopen("http://en.wiki... | -1 | 2016-07-22T11:13:09Z | 38,525,097 | <pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
</code></pre>
<p>Add this to top of your file</p>
| 0 | 2016-07-22T11:16:38Z | [
"python",
"excel"
] |
Python Data Scraping | 38,525,038 | <p>Data Scraping in Pyhton.
Code is working fine but it is showing the error which I mentioned below.
What could be the reason?</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
from xlwt import workbook
wb = Workbook()
sheet1 = wb.add_sheet('Sheet1')
soup = BeautifulSoup(urllib2.urlopen("http://en.wiki... | -1 | 2016-07-22T11:13:09Z | 38,525,127 | <p>for row in soup('table', {'class': 'wikitable sortable jquery-tablesorterâ})[0].tbody('tr'):</p>
<p>You used a wrong character as single quote delimiter sign after jquery-tablesorter</p>
| 0 | 2016-07-22T11:18:31Z | [
"python",
"excel"
] |
Finding the maximum element with a recursive function | 38,525,085 | <p>I wrote a function that tries to find out what has the maximum value in a list:</p>
<pre><code>def maxElement(L):
length=len(L)
if L[length-1]>L[length-2]:
del L[length-2]
print L
elif L[length-1]<L[length-2]:
del L[length-1]
return L
print maxElement([1,2,95754754745,... | 2 | 2016-07-22T11:16:08Z | 38,525,222 | <p>You are not calling your function again, which makes recursion impossible. Furthermore you have no base case which would stop recursion, which in this case would be:</p>
<pre><code>if length == 1:
return L
</code></pre>
<p>Here is the fixed code:</p>
<pre><code>def maxElement(L):
length=len(L)
if length... | 6 | 2016-07-22T11:24:13Z | [
"python",
"list",
"function"
] |
Finding the maximum element with a recursive function | 38,525,085 | <p>I wrote a function that tries to find out what has the maximum value in a list:</p>
<pre><code>def maxElement(L):
length=len(L)
if L[length-1]>L[length-2]:
del L[length-2]
print L
elif L[length-1]<L[length-2]:
del L[length-1]
return L
print maxElement([1,2,95754754745,... | 2 | 2016-07-22T11:16:08Z | 38,525,233 | <p>It did exactly what you asked it to do. </p>
<p>Your function is not recursive as you forgot calling it again towards the end.</p>
<p>Something like this is what you are looking for:</p>
<pre><code>def maxElement(L):
length=len(L)
if L[length-1]>L[length-2]:
del L[length-2]
print L
... | 6 | 2016-07-22T11:24:38Z | [
"python",
"list",
"function"
] |
Finding the maximum element with a recursive function | 38,525,085 | <p>I wrote a function that tries to find out what has the maximum value in a list:</p>
<pre><code>def maxElement(L):
length=len(L)
if L[length-1]>L[length-2]:
del L[length-2]
print L
elif L[length-1]<L[length-2]:
del L[length-1]
return L
print maxElement([1,2,95754754745,... | 2 | 2016-07-22T11:16:08Z | 38,525,409 | <p>Why are you not simply using max()?</p>
<blockquote>
<p>max([1,2,95754754745,3,1,8,444,2,42425])</p>
<p>95754754745L</p>
</blockquote>
| 2 | 2016-07-22T11:33:31Z | [
"python",
"list",
"function"
] |
How to run background processes on Bluemix? | 38,525,257 | <p>I'm trying to get a really simple python program to run as a background process on IBM Bluemix as a CloudFoundry app.</p>
<p>I've put it in a <a href="https://github.com/Zapaan/bluemix-bg-proc-test" rel="nofollow">Github repo</a>.
There's a one-line req file because I find it easier than a setup.py and the python b... | 0 | 2016-07-22T11:25:41Z | 38,527,239 | <p>Short answer to the question : a separate app with the <code>no-route</code> argument set to <code>true</code></p>
<p>Ok, so I've apparently got it to work fully.</p>
<p>I'm not sure what I've done but the problem might have come from the fact that I was asking for a 32M instance and the minimum seems to be 64M so... | 0 | 2016-07-22T13:06:15Z | [
"python",
"ibm-bluemix",
"cloudfoundry"
] |
create_or_get with data from user input | 38,525,530 | <p>Trying to implement a user registration form on a website I can't make user input to be added as a new user to the database. I'm using Flask with Peewee, and have:</p>
<pre><code>nUser ={
'email': request.form['e_mail'],
'uname': request.form['username'],
'pword': request.form['password'], ... | 0 | 2016-07-22T11:39:29Z | 38,525,732 | <p>The official documentation that you link to show that <code>create_or_get</code> takes keyword arguments only. To pass a dict, you need to use the <code>**</code> syntax:</p>
<pre><code>User.create_or_get(**nuser)
</code></pre>
| 1 | 2016-07-22T11:49:38Z | [
"python",
"flask",
"peewee",
"flask-peewee"
] |
How to import java class, to Robot Framework like library | 38,525,558 | <p>I can't understand how to import .jar file, in Robot Framework.</p>
<p>Here is the code:</p>
<pre><code>*** Settings ***
Library MyLibrary
*** Test Cases ***
My Test
Do Nothing
Hello world
</code></pre>
<p>and Java:</p>
<pre><code>public class MyLibrary {
public void hello(String name) {
... | 0 | 2016-07-22T11:41:01Z | 38,535,672 | <p>You have to use jython (jybot). There are other settings like JYTHONPATH.</p>
| 0 | 2016-07-22T21:43:23Z | [
"java",
"python",
"robotframework"
] |
generate a qr code in pyramid view, return it without writing to disk | 38,525,722 | <p>I have a pyramid view that needs to generate a qr code and return it as an image to the user. I want to avoid storing the image, I want to just generate it, send it and forget about it.</p>
<p>The first thing I tried was something like this:</p>
<pre><code>oRet = StringIO.StringIO()
oQR = pyqrcode.create('yo mamm... | 0 | 2016-07-22T11:49:13Z | 38,529,362 | <p>we have a winner:</p>
<pre><code>oRet = StringIO.StringIO()
oQR = pyqrcode.create('yo mamma')
oQR.png(oRet, scale=8)
oResp = Response(body = oRet.getvalue(), content_type="image/png",content_disposition='attachment; filename="yummy.png"')
return oResp
</code></pre>
<p>The trick was to use <code>oRet.getvalue()<... | 0 | 2016-07-22T14:46:53Z | [
"python",
"response",
"qr-code",
"pyramid"
] |
Variable scope in Python higher-order functions | 38,525,774 | <p>I am looking at some learning material here: <a href="http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators" rel="nofollow">http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators</a></p>
<p>Particularly the <code>Me... | 0 | 2016-07-22T11:52:11Z | 38,526,343 | <p>the cache object and g(x) object both have the same scope as they are both objects in the memoize function. This means that g(x) will have access to cache because they are both objects scoped in the memoize function.</p>
| 0 | 2016-07-22T12:23:28Z | [
"python",
"higher-order-functions"
] |
Variable scope in Python higher-order functions | 38,525,774 | <p>I am looking at some learning material here: <a href="http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators" rel="nofollow">http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators</a></p>
<p>Particularly the <code>Me... | 0 | 2016-07-22T11:52:11Z | 38,526,815 | <p>the <code>def memoize():</code> line introduces a new scope. the <code>g</code> function code 'sees' the scope of its enclosing function. Sure do look into this question's answers: <a href="http://stackoverflow.com/q/291978/6610">Short Description of Python Scoping Rules</a>.</p>
<p>So no: that's not an error! I... | 1 | 2016-07-22T12:44:41Z | [
"python",
"higher-order-functions"
] |
Return response during multi if in python | 38,525,779 | <p>I'm doing a <a href="http://flask.pocoo.org/docs/0.11/testing/" rel="nofollow">unit testing</a>, I'm checking fields in two databases collections so during it I have to do a multi if conditions like this:</p>
<pre><code>for doc1,doc2 in itertools.izip(docs1, docs2):
if ... :
if ... :
respon... | -3 | 2016-07-22T11:52:34Z | 38,526,694 | <p>In this case you should consider using a default value and only checking for the error case:</p>
<pre><code>response = "OK" # default value
for doc1,doc2 in itertools.izip(docs1, docs2):
if ... :
if ... :
response = "Error"
else... :
if ... :
response = "Error"
... | 0 | 2016-07-22T12:39:43Z | [
"python",
"unit-testing",
"flask"
] |
Return response during multi if in python | 38,525,779 | <p>I'm doing a <a href="http://flask.pocoo.org/docs/0.11/testing/" rel="nofollow">unit testing</a>, I'm checking fields in two databases collections so during it I have to do a multi if conditions like this:</p>
<pre><code>for doc1,doc2 in itertools.izip(docs1, docs2):
if ... :
if ... :
respon... | -3 | 2016-07-22T11:52:34Z | 38,527,076 | <p>It seems to me that you're not really unit-testing. The structure in your function and unit test are exactly the same. So if your code change the test will have to change too. I don't think that testing the "=" operator is worth your time. </p>
<p>I could be wrong but I think you should have a function taking doc1 ... | 0 | 2016-07-22T12:57:27Z | [
"python",
"unit-testing",
"flask"
] |
PyQt QWidget destructor error `AttributeError: 'NoneType' object has no attribute 'path'` | 38,525,796 | <p>I use a custom widget inheriting from <code>QWidget</code>. This widget may use an online resource: a picture I download from the internet and store in a local file before displaying it in a <code>QLabel</code> instance.</p>
<p>When the user closes the window I want the local file to be deleted so I changed the des... | 0 | 2016-07-22T11:53:39Z | 38,531,458 | <p>Looking at the github code, the problem seems to be that when the widget is closed, the Qt application terminate and sys.exit() is called, so probably the module is garbage collected before<code>__del__</code> call.</p>
<p>there:</p>
<pre><code>if __name__ == '__main__':
app = QApplication( sys.argv)
url =... | 2 | 2016-07-22T16:36:22Z | [
"python",
"python-3.x",
"debugging",
"pyqt"
] |
Use the same browser session for multiple tests with Selenium Pytest | 38,525,925 | <p>I want to be able to use the same browser session for multiple tests within the same test file.</p>
<p>I have a class set up for the login:</p>
<pre><code>class Loginpage ():
url="http://appsv01:8084/#/"
def __init__(self, workbook):
self.workbook=workbook
def login(self,value_Name,worksheet):
#Open a... | 0 | 2016-07-22T12:01:14Z | 38,526,945 | <p>You could pass the driver object to the function calls:</p>
<pre><code> #open the browser
driver = webdriver.Chrome('C:/temp/chromedriver.exe')
driver.get("http://appsv01:8084")
driver.maximize_window()
#perform the first test
def test_one(driver):
#do something with driver here, e.g.
driver.find_element_... | 0 | 2016-07-22T12:50:56Z | [
"python",
"selenium"
] |
Accessing user home directory from django | 38,525,997 | <p>I'm creating a Django app who can access to the user home directory. For this purpose I want to create a directory using something like <code>os.mkdir('/home/user/new_directory')</code> or a <em>subprocess</em> command.</p>
<p>Because Django is started by an apache server, python act as the apache user and can't ac... | 3 | 2016-07-22T12:04:54Z | 38,527,243 | <p>You can set the home directories via <code>MEDIA_URL</code> /or symlink itself.
I think of a combined aproach of symlink and os.system calls.</p>
<p><a href="http://unix.stackexchange.com/questions/68368/what-is-symlinking-and-how-can-learn-i-how-to-to-do-this">what-is-symlinking-and-how-can-learn-i-how-to-to-do-th... | 0 | 2016-07-22T13:06:30Z | [
"python",
"django",
"unix",
"authentication",
"subprocess"
] |
How to post to Google+? | 38,526,066 | <p>I want to make some application (Google App Engine) which will be fetching some data from other websites and post them in one of my "collections" in Google+.</p>
<p>For now I have this code:
main.py</p>
<pre><code># -*- coding: utf-8 -*-
import webapp2
import httplib2
from googleapiclient.discovery import build
f... | 3 | 2016-07-22T12:08:47Z | 38,526,485 | <p>You have to add the scope
`<a href="https://www.googleapis.com/auth/plus.stream.write" rel="nofollow">https://www.googleapis.com/auth/plus.stream.write</a>
<a href="https://www.googleapis.com/auth/plus.me" rel="nofollow">https://www.googleapis.com/auth/plus.me</a>
for writing the post to google+ account.By authori... | 0 | 2016-07-22T12:30:30Z | [
"python",
"google-app-engine",
"google-api",
"google-plus",
"google-plus-domains"
] |
How to post to Google+? | 38,526,066 | <p>I want to make some application (Google App Engine) which will be fetching some data from other websites and post them in one of my "collections" in Google+.</p>
<p>For now I have this code:
main.py</p>
<pre><code># -*- coding: utf-8 -*-
import webapp2
import httplib2
from googleapiclient.discovery import build
f... | 3 | 2016-07-22T12:08:47Z | 39,765,266 | <p>Yes, you need to have a Work Account. Unfortunately the Google Plus Pages API is not open to the public. You can send a request to sign up <a href="https://developers.google.com/+/api/pages-signup" rel="nofollow">here</a>. </p>
<p>That's why you get the <strong>HTTP 403 Forbidden</strong> error, which means that se... | 3 | 2016-09-29T08:32:16Z | [
"python",
"google-app-engine",
"google-api",
"google-plus",
"google-plus-domains"
] |
how to shift single value of a pandas dataframe column | 38,526,122 | <p>Using pandas <code>first_valid_index()</code> to get index of first non-null value of a column, how can I shifta single value of column rather than the whole column. i.e.</p>
<pre><code>data = {'year': [2010, 2011, 2012, 2013, 2014, 2015, 2016,2017, 2018, 2019],
'columnA': [10, 21, 20, 10, 39, 30, 31,45, 23... | 3 | 2016-07-22T12:11:21Z | 38,526,268 | <p>is that what you want?</p>
<pre><code>In [63]: idx = df.columnB.first_valid_index()
In [64]: df.ix[idx, 'columnB'] += df.total.shift().ix[idx]
In [65]: df
Out[65]:
columnA columnB total
year
2010 10 NaN 100
2011 21 NaN 200
2012 20 NaN 300
2013 10 310.0 ... | 2 | 2016-07-22T12:19:37Z | [
"python",
"pandas",
"dataframe"
] |
how to shift single value of a pandas dataframe column | 38,526,122 | <p>Using pandas <code>first_valid_index()</code> to get index of first non-null value of a column, how can I shifta single value of column rather than the whole column. i.e.</p>
<pre><code>data = {'year': [2010, 2011, 2012, 2013, 2014, 2015, 2016,2017, 2018, 2019],
'columnA': [10, 21, 20, 10, 39, 30, 31,45, 23... | 3 | 2016-07-22T12:11:21Z | 38,526,494 | <p>You can filter all column names, where is least one <code>NaN</code> value and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.union.html" rel="nofollow"><code>union</code></a> with column <code>total</code>:</p>
<pre><code>for col in df.columns:
if col not in pd.Index(['tot... | 1 | 2016-07-22T12:31:12Z | [
"python",
"pandas",
"dataframe"
] |
How to draw a coordinate system on top of an image using tkinter? | 38,526,285 | <p>I want to show an image and draw a coordinate system(x-axe, y-axe) on top of it.
I can show the image</p>
<pre><code>img = ImageTk.PhotoImage(Image.open(path).resize((400,400),Image.ANTIALIAS))
panel = tk.Label(root,image = img, width = 400, height = 400s)
panel.pack(size= "bottom", fill = "both", expand = "yes")
p... | 1 | 2016-07-22T12:20:42Z | 38,527,334 | <p>You have to place the image on the canvas and then put the axis lines on top of it:</p>
<pre><code>import Tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
img_path = 'water-drop-splash.png'
img = ImageTk.PhotoImage(Image.open(img_path).resize((400,400), Image.ANTIALIAS))
canvas = tk.Canvas(root, heigh... | 3 | 2016-07-22T13:10:29Z | [
"python",
"canvas",
"tkinter"
] |
How to find frequency of a square wave using FFT | 38,526,289 | <p>In the FFT (second) plot, I am expecting a bigger peak at frequency = 1.0, compared to other frequencies, since it is a 1 Hz Square Wave signal sampled at 5Hz. </p>
<p><em>I am a beginner at this, possibly missing something silly here</em>
Here's what I have done:</p>
<pre><code>import numpy as np
from matplotlib ... | 2 | 2016-07-22T12:20:54Z | 38,527,464 | <p>It seems you missed the fact that Fourier transform produces functions (or sequences of numbers in case of DFT/FFT) in complex space:</p>
<pre><code>>>> np.fft.fft(s1t5)
[ 5. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j
5.-15.38841769j 0. +0.j 0. +0.j 0. +0.... | 3 | 2016-07-22T13:16:11Z | [
"python",
"numpy",
"scipy",
"fft"
] |
How to measure runtime in web.py? | 38,526,308 | <p>I created a python webserver with web.py.
This webserver works fine. But I will get the infromation how long the webserver needs to get the result from the database and send it back to the client.</p>
<p>Can I realize that with the modul timeit?
Does someone has an idea?</p>
| 0 | 2016-07-22T12:21:34Z | 38,526,659 | <p>You can use <a href="http://webpy.org/docs/0.3/api#web.http" rel="nofollow"><code>web.profiler</code></a> middleware to display some profiling information within each response.</p>
<pre><code>application = web.application(urls, globals(), web.profiler)
</code></pre>
<p>If that information isn't enough, you could u... | 0 | 2016-07-22T12:38:30Z | [
"python",
"web.py",
"web-frameworks"
] |
Image in label not appearing in secondary window (tkinter) | 38,526,809 | <p>I am trying to display an image inside of a label in a second Tkinter window.
In my main window (window), the images are displayed perfectly, but when I write the same code to appear inside of the second window (root), the code executes, but you cannot see the image, only blank space.</p>
<p>Any help would be great... | 1 | 2016-07-22T12:44:28Z | 38,527,181 | <p>You wrongly kept the reference to the image. This means you need to change this line:</p>
<pre><code>root.main_photo = main_photo
</code></pre>
<p>To:</p>
<pre><code>main_photo.image = finance_news_image2
</code></pre>
| 1 | 2016-07-22T13:03:09Z | [
"python",
"python-3.x",
"tkinter"
] |
Understanding Numeric Datatype in SqlAlchemy | 38,526,826 | <p>I have a class</p>
<pre><code>class vw_invoice_header(db.Model):
__tablename__ = "vw_invoice_header"
tax_amount = db.column(db.Numeric)
total_price = db.column(db.Numeric)
invc_number = db.Column(db.String(40))
term_code = db.Column(db.String(20))
order_date = db.Column(db.Date)
airway_... | 0 | 2016-07-22T12:45:11Z | 38,527,030 | <p>Your first two fields should be <code>db.Column</code> not <code>db.column</code> (note the capitalization). <code>db.column</code> creates a <code>sqlalchemy.sql.elements.ColumnClause</code> object whereas <code>db.Column</code> creates a <code>sqlalchemy.sql.schema.Column</code> object like you want.</p>
<pre><co... | 1 | 2016-07-22T12:55:25Z | [
"python",
"sqlalchemy"
] |
embed ipython notebook in sphinx document | 38,526,888 | <p>I am writing the API document for my own project.
And I found that this cool <a href="http://yt-project.org/doc/quickstart/data_objects_and_time_series.html" rel="nofollow">documentation</a> (yt project) uses ipython notebook directly to give example. When I looked into their documentation repo on bitbucket, one re... | 1 | 2016-07-22T12:48:22Z | 38,530,400 | <p><code>nbsphinx</code> is a Sphinx extension that provides a source parser for <code>*.ipynb</code> files. </p>
<p>To Install nbsphinx:</p>
<pre><code>pip install nbsphinx --user
</code></pre>
<p>Edit your <code>conf.py</code> and add <code>'nbsphinx'</code> to extensions.</p>
<p>Edit your <code>index.rst</code> ... | 1 | 2016-07-22T15:35:45Z | [
"python",
"ipython-notebook",
"python-sphinx"
] |
Cannot extract URL of plotly charts (to be embedded into html reports) | 38,526,899 | <p>I am trying to print the URL for a plotly chart.</p>
<p>The command:</p>
<pre><code>plot_url = py.iplot(fig, filename= 'chart name',auto_open=False)
print plot_url
</code></pre>
<p>returns:</p>
<pre><code>plotly.tools.PlotlyDisplay object>
</code></pre>
<p>rather than:</p>
<pre><code>https://plot.ly/23/~and... | 0 | 2016-07-22T12:48:39Z | 38,662,339 | <p>I think I've found the answer.
The issue was that I was using <code>py.iplot</code> instead of <code>py.plot</code>.</p>
<p>Changing the code to:</p>
<pre><code>plot_url = py.plot(fig, filename= 'chart name',auto_open=False)
print plot_url
</code></pre>
<p>outputs the correct url.</p>
| 0 | 2016-07-29T15:22:43Z | [
"python",
"embed",
"plotly"
] |
How to execute if else unix command from python and get ret value | 38,526,908 | <p>Following is the code which I am trying to execute using python</p>
<pre><code>from subprocess import Popen, PIPE
cmd = 'if (-e "../a.txt") then \n ln -s ../a.txt . \n else \n echo "file is not present " \n endif'
ret_val = subprocess.call(cmd,shell="True")
</code></pre>
<p>When executed gives following error... | 0 | 2016-07-22T12:49:08Z | 38,526,969 | <p>In sh scripts, <code>if</code> is terminated with <code>fi</code>, not <code>endif</code>.</p>
<p><a href="http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html" rel="nofollow">http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html</a></p>
<hr>
<p>Or just write the darn code in Python:</p>
<pre><c... | 6 | 2016-07-22T12:52:22Z | [
"python",
"unix"
] |
Missing values at the beginning - matplotlib | 38,527,053 | <p>Trying to add missing values (None) or in <code>numpy</code> <code>np.nan</code> to my matplot graph. Normally it is possible to have missing values in this way:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure(1)
x = range(10)
y = [1, 2, None, 0, 1, 2, 3, 3, 5, 10]
ax = fig.add_subplot(111)
ax.pl... | 2 | 2016-07-22T12:56:16Z | 38,527,184 | <p>Matplotlib automatically choses the parameters for x- and y- axes. In this case it is only showing the dots that can be visualized. If either x- or y is "None", nothing can be visualized. If you yet want to see the "empty" part of the graph, just adjust the axis range yourself. </p>
<p>How to do so, has been answer... | 3 | 2016-07-22T13:03:19Z | [
"python",
"matplotlib"
] |
Missing values at the beginning - matplotlib | 38,527,053 | <p>Trying to add missing values (None) or in <code>numpy</code> <code>np.nan</code> to my matplot graph. Normally it is possible to have missing values in this way:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure(1)
x = range(10)
y = [1, 2, None, 0, 1, 2, 3, 3, 5, 10]
ax = fig.add_subplot(111)
ax.pl... | 2 | 2016-07-22T12:56:16Z | 38,527,189 | <p>The reason why the empty values don't seem to have an effect on the second plot is because of the automatic determination of the x and y limits of the axes object. In the first case, you have "real" data that spans the whole x / y range you care about and the axes is automatically scaled to fit this data. In the sec... | 4 | 2016-07-22T13:03:33Z | [
"python",
"matplotlib"
] |
Run a tensorflow with a list of fetches does not work | 38,527,096 | <p>I'm playing around with Tensorflow and implemented a k means clustering algorithm. Everything works well, but if I want to run the session with a couple of fetches in a <code>list</code> I always get the error, that a <code>list</code> can not be converted to a <code>Tensor</code> or <code>Operation</code>.</p>
<p>... | 0 | 2016-07-22T12:58:43Z | 38,531,878 | <p><code>tf.dynamic_partition</code> returns a <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/array_ops.html#dynamic_partition" rel="nofollow">list of Tensors</a>, so <code>clusters</code> is itself a list. </p>
<pre><code>clusters = tf.dynamic_partition(tf_data, mins, k)
</code></pre>
<p>When you ... | 2 | 2016-07-22T17:04:09Z | [
"python",
"tensorflow"
] |
different roles in Django: show different content in web page | 38,527,159 | <p>I'm using Django to develop an webapp, I created different roles of users, for example <code>CunstomerUser, GoodUser, Admin</code>...etc.</p>
<p>Now I want to show them different things when they login. For example, when they open a popup, the <code>CustomerUser</code> will see a textarea field for commenting and f... | 0 | 2016-07-22T13:01:56Z | 38,527,306 | <p>I might be wrong but you could still use django template syntax in javascript, because django template is evaluated before the page is loaded, so it still works by hiding/showing the portion that's relevant to the specific user:</p>
<pre><code><script>
{% if request.user.is_superuser %}
var userType = 'su... | 2 | 2016-07-22T13:09:08Z | [
"javascript",
"python",
"django"
] |
Running Python script via systemd fails to load module | 38,527,235 | <p>I have a Python script that uses <code>zmq</code> and I've installed this library via <code>pip install zmq</code> and I can run the program fine if called manually via the command line. However as soon as I attempt to have a <code>systemd</code> unit call the script, running <code>systemctl status myservice.service... | 1 | 2016-07-22T13:06:04Z | 38,528,565 | <p>The most likely explanation is that you have some environment variables set (e.g. an extension of your PYTHONPATH?) which is not set when the script is being run by systemd.</p>
<p>You could try using the Environment parameter (see [0]) so set PYTHONPATH (and whatever else might influence this) to whatever it is in... | 2 | 2016-07-22T14:08:28Z | [
"python",
"linux",
"service",
"systemd"
] |
Running Python script via systemd fails to load module | 38,527,235 | <p>I have a Python script that uses <code>zmq</code> and I've installed this library via <code>pip install zmq</code> and I can run the program fine if called manually via the command line. However as soon as I attempt to have a <code>systemd</code> unit call the script, running <code>systemctl status myservice.service... | 1 | 2016-07-22T13:06:04Z | 38,529,122 | <p><code>systemd</code> runs as root. The modules installed via <code>pip</code> are installed for a user rather than for the system and so installing the modules without root privileges made the modules unaccessible for root.</p>
<p>To solve this I ran <code>sudo -H pip install zmq</code> and <code>sudo -H pip3 insta... | 1 | 2016-07-22T14:35:10Z | [
"python",
"linux",
"service",
"systemd"
] |
ldap3 library: modify attribute with multiple values | 38,527,246 | <p>Trying to modify an ldap attribute that has multiple values, can't seem to figure out the syntax.</p>
<p>I'm using the <a href="https://github.com/cannatag/ldap3" rel="nofollow">ldap3</a> library with python3.</p>
<p>The <a href="http://ldap3.readthedocs.io/modify.html" rel="nofollow">documentation</a> gives an ex... | 0 | 2016-07-22T13:06:36Z | 38,531,371 | <p>You need to ensure you are passing in the DN of the ldapobject you wish to modify. </p>
<pre><code>c.modify(FULL_DN_OF_OBJECT, {'memberuid': [(MODIFY_REPLACE, ['clark.kent', 'the.hulk','bat.man'])]})
</code></pre>
<p>Then you should be able just to pass in newmemberlist instead of ['clark.kent', 'the.hulk','bat.m... | 1 | 2016-07-22T16:30:53Z | [
"python",
"python-3.x",
"ldap"
] |
ldap3 library: modify attribute with multiple values | 38,527,246 | <p>Trying to modify an ldap attribute that has multiple values, can't seem to figure out the syntax.</p>
<p>I'm using the <a href="https://github.com/cannatag/ldap3" rel="nofollow">ldap3</a> library with python3.</p>
<p>The <a href="http://ldap3.readthedocs.io/modify.html" rel="nofollow">documentation</a> gives an ex... | 0 | 2016-07-22T13:06:36Z | 38,616,209 | <p>I believe MODIFY_REPLACE command would not accept multiple values, as it would not understand which values would be replaced with new ones. Instead you should try doing MODIFY_DELETE old values first and MODIFY_ADD new values afterwards.</p>
| 0 | 2016-07-27T14:42:39Z | [
"python",
"python-3.x",
"ldap"
] |
Python Pandas: Create new rows in dataFrame based on two columns | 38,527,268 | <p>I have the following dataframe 'df' based on which I'd like to create a new df 'new_df'. I have some troubles getting the new df.</p>
<pre><code> Cust-id Sex Country Orders Products
0 'Cu1' 'F' 'FR' 'ord1 + ord2' 'A+G'
1 'Cu2' 'M' 'US' 'ord3' 'C'
2 'Cu3' 'M' '... | 1 | 2016-07-22T13:07:29Z | 38,527,415 | <p>You can use:</p>
<pre><code>#remove ', split by +, create Series
s1 = df.Products.str.strip("'")
.str.split('+', expand=True)
.stack()
.reset_index(drop=True, level=1)
#remove ', split by +, create Series, strip spaces
s2 = df.Orders.str.strip("'... | 0 | 2016-07-22T13:14:03Z | [
"python",
"pandas"
] |
Python Pandas: Create new rows in dataFrame based on two columns | 38,527,268 | <p>I have the following dataframe 'df' based on which I'd like to create a new df 'new_df'. I have some troubles getting the new df.</p>
<pre><code> Cust-id Sex Country Orders Products
0 'Cu1' 'F' 'FR' 'ord1 + ord2' 'A+G'
1 'Cu2' 'M' 'US' 'ord3' 'C'
2 'Cu3' 'M' '... | 1 | 2016-07-22T13:07:29Z | 38,527,525 | <p>Write the df to a csv using following code will correct the error </p>
<pre><code> df.dropna().to_csv('train1.csv')
</code></pre>
<p>try this</p>
| -1 | 2016-07-22T13:19:14Z | [
"python",
"pandas"
] |
Using urllib instead of wget for session authentication | 38,527,372 | <p>So currently i have a line of python code which uses wget and os.system to download a file from a website. However when i try to convert this wget to a more elegant library such as urllib or requests, the cookies fail to authenticate and instead downloads the login html page instead of the file.</p>
<p>Here is what... | 1 | 2016-07-22T13:12:09Z | 38,662,646 | <p>You should use <code>=</code> instead <code>:</code> in your query:</p>
<pre><code>s.post(loginUrl, data="name={}&password={}".format(username,password))
</code></pre>
<p>Also, you could (and should, following the <code>requests</code> best practice) proceed a dict to <code>data</code> argument:</p>
<pre><cod... | 1 | 2016-07-29T15:38:47Z | [
"python"
] |
Python: automatically call a parent function after child instantiation | 38,527,374 | <p>Python 2.7</p>
<p>I would like to automotically call a function of a parent object after I instantiate its child</p>
<pre><code>class Mother:
def __init__(self):
pass
def call_me_maybe(self):
print 'hello son'
class Child(Mother):
def __init__(self):
print 'hi mom'
# desi... | 1 | 2016-07-22T13:12:14Z | 38,527,403 | <p>Use <code>super()</code>?</p>
<pre><code>class Child(Mother):
def __init__(self):
print 'hi mom'
super(Child, self).call_me_maybe()
</code></pre>
| 1 | 2016-07-22T13:13:34Z | [
"python",
"oop",
"inheritance",
"python-object"
] |
Python: automatically call a parent function after child instantiation | 38,527,374 | <p>Python 2.7</p>
<p>I would like to automotically call a function of a parent object after I instantiate its child</p>
<pre><code>class Mother:
def __init__(self):
pass
def call_me_maybe(self):
print 'hello son'
class Child(Mother):
def __init__(self):
print 'hi mom'
# desi... | 1 | 2016-07-22T13:12:14Z | 38,527,451 | <p>You could use <a href="http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods"><code>super</code></a> but you should set your <em>superclass</em> to inherit from <code>object</code>:</p>
<pre><code>class Mother(object):
# ^
def __init__(self):
pass
def c... | 3 | 2016-07-22T13:15:58Z | [
"python",
"oop",
"inheritance",
"python-object"
] |
Python: automatically call a parent function after child instantiation | 38,527,374 | <p>Python 2.7</p>
<p>I would like to automotically call a function of a parent object after I instantiate its child</p>
<pre><code>class Mother:
def __init__(self):
pass
def call_me_maybe(self):
print 'hello son'
class Child(Mother):
def __init__(self):
print 'hi mom'
# desi... | 1 | 2016-07-22T13:12:14Z | 38,527,571 | <p>Since the child class inherits the parents methods, you can simply call the method in the <code>__init__()</code> statement.</p>
<pre><code>class Mother(object):
def __init__(self):
pass
def call_me_maybe(self):
print('hello son')
class Child(Mother):
def __init__(self):
pri... | 1 | 2016-07-22T13:21:44Z | [
"python",
"oop",
"inheritance",
"python-object"
] |
Fill NA-values with Mean across column and row values | 38,527,444 | <p>I have next dataframe</p>
<pre><code> A B C D E F
0 158 158 158 177 1 10
1 158 158 158 177 2 20
2 177 177 177 177 3 30
3 1 3 5 7 NaN 10
4 177 177 177 177 6 50
</code></pre>
<p>Now I try to get a new one dataframe where <strong>E3</strong> = AVG[AVG(E)=3, AV... | 1 | 2016-07-22T13:15:42Z | 38,531,038 | <p>I couldn't find a one-liner however if you can keep three data frames in memory</p>
<ul>
<li>one with row averages </li>
<li>another with column averages </li>
<li>third with the average of the above two</li>
</ul>
<p>then <code>fillna</code> will replace <code>NaN</code> values based on the exact location in the ... | 1 | 2016-07-22T16:09:49Z | [
"python",
"python-2.7",
"pandas"
] |
Jenkins with Windows slave with Python - Setting environment variables while building and using them when running a python script | 38,527,505 | <p>I'm currently using a Jenkins build to run a bash command that activates a Python script. The build is parametrised, and i need to be able to set environment variables containing those parameters on the Windows slave to be used by the Python script.</p>
<p>So, my question is: How do i set temporary env. variables f... | 0 | 2016-07-22T13:18:17Z | 38,527,694 | <p>What I usually do is going on the build output, on the left you will find "Build environment Variables" or something similar and check if you can see them there, but the solution cited on the other SO post works usually for me as well</p>
| 0 | 2016-07-22T13:27:38Z | [
"python",
"jenkins",
"jenkins-plugins"
] |
AWS IOT with DynamoDB logging service issue | 38,527,573 | <p>We have implemented a simple DynamoDB database that is updated by a remote IoT device that does not have a user (i.e. root) constantly logged in to the device. We have experience issues in logging data as the database is not updated if a user (i.e. root) is not logged into the device (we log in via a ssh session). W... | 1 | 2016-07-22T13:21:46Z | 38,537,832 | <p>No, it does not. I have done similar setup and it is working fine. Are you sure that your IoT device does not go into some kind of sleep mode after a while ?</p>
| 0 | 2016-07-23T03:24:41Z | [
"python",
"amazon-web-services",
"amazon-dynamodb",
"iot"
] |
Appended object to a set is `NoneType` python 2.7 | 38,527,667 | <p>I have a huge array of labels which I make unique via:</p>
<pre><code>unique_train_labels = set(train_property_labels)
</code></pre>
<p>Which prints out as <code>set([u'A', u'B', u'C'])</code>. I want to create a new set of unique labels with a new label called "no_region", and am using:</p>
<pre><code>unique_tra... | 1 | 2016-07-22T13:26:22Z | 38,527,744 | <p>The set <code>add</code> method mutates the set <em>inplace</em> and returns a <code>None</code>. </p>
<p>You should do:</p>
<pre><code>unique_train_labels_threshold = unique_train_labels.copy()
unique_train_labels_threshold.add('no_region')
</code></pre>
<p>Using <code>copy</code> ensures mutations on the new se... | 4 | 2016-07-22T13:30:07Z | [
"python",
"python-2.7",
"numpy",
"random",
"set"
] |
Appended object to a set is `NoneType` python 2.7 | 38,527,667 | <p>I have a huge array of labels which I make unique via:</p>
<pre><code>unique_train_labels = set(train_property_labels)
</code></pre>
<p>Which prints out as <code>set([u'A', u'B', u'C'])</code>. I want to create a new set of unique labels with a new label called "no_region", and am using:</p>
<pre><code>unique_tra... | 1 | 2016-07-22T13:26:22Z | 38,527,881 | <p>I can't find in the documentation anywhere were it says that <code>add</code> generates a new set.<br>
You need to copy the original, then add to the new copy.</p>
<pre><code>import copy
unique_train_labels_threshold = copy.deepcopy(unique_train_labels)
unique_train_labels_threshold.add('no_region')
</code></pre>
| 0 | 2016-07-22T13:36:04Z | [
"python",
"python-2.7",
"numpy",
"random",
"set"
] |
Appended object to a set is `NoneType` python 2.7 | 38,527,667 | <p>I have a huge array of labels which I make unique via:</p>
<pre><code>unique_train_labels = set(train_property_labels)
</code></pre>
<p>Which prints out as <code>set([u'A', u'B', u'C'])</code>. I want to create a new set of unique labels with a new label called "no_region", and am using:</p>
<pre><code>unique_tra... | 1 | 2016-07-22T13:26:22Z | 38,528,506 | <p>As mentioned in Moses' answer, the <code>set.add</code> method mutates the original set, it does not create a new set. In Python it's conventional for methods that perform in-place mutation to return <code>None</code>; the methods of all built-in mutable types do that, and the convention is generally observed by 3rd... | 3 | 2016-07-22T14:05:49Z | [
"python",
"python-2.7",
"numpy",
"random",
"set"
] |
Tensorflow: How to convert NaNs to a number? | 38,527,722 | <p>I'm trying to calculate the entropy of the weights while training my graph and to use it for regularization. This of course involves <code>w*tf.log(w)</code>, and as my weights are changing some of them are bound to get into a region which results in NaNs being returned.</p>
<p>Ideally I would include a line in my ... | 1 | 2016-07-22T13:28:54Z | 38,527,873 | <p>I think you need to use tf.select.</p>
<pre><code>w = tf.select(tf.is_nan(w), tf.ones_like(w) * NUMBER, w); #if w is nan use 1 * NUMBER else use element in w
</code></pre>
| 3 | 2016-07-22T13:35:55Z | [
"python",
"tensorflow",
null
] |
Tensorflow: How to convert NaNs to a number? | 38,527,722 | <p>I'm trying to calculate the entropy of the weights while training my graph and to use it for regularization. This of course involves <code>w*tf.log(w)</code>, and as my weights are changing some of them are bound to get into a region which results in NaNs being returned.</p>
<p>Ideally I would include a line in my ... | 1 | 2016-07-22T13:28:54Z | 38,527,913 | <p>You cannot convert nan to a number (such as you cannot convert infinite to a number).</p>
<p>The nan resulkts most probably from the <code>w*tf.log(w)</code> once w is (or contains) zero(s). You might add 1e-6 first so that no division by zero occurs.</p>
| -1 | 2016-07-22T13:37:38Z | [
"python",
"tensorflow",
null
] |
How can I hide columns in Openpyxl? | 38,527,725 | <p>I'm hiding a bunch of columns in an Excel sheet. I'm getting this error: <code>AttributeError: can't set attribute</code> from this line <code>worksheet.column_dimensions['B'].visible = False</code></p>
<p>Sorry if this is a super simple question. I just updated to a new version of Openpyxl/Pandas so i'm now having... | 0 | 2016-07-22T13:29:01Z | 38,527,841 | <p>You should set the <code>hidden</code> attribute to <code>True</code>:</p>
<pre><code> worksheet.column_dimensions['A'].hidden= True
</code></pre>
<p>In order to hide more than one column:</p>
<pre><code>for col in ['A', 'B', 'C']:
worksheet.column_dimensions[col].hidden= True
</code></pre>
| 3 | 2016-07-22T13:34:27Z | [
"python",
"openpyxl"
] |
How can I hide columns in Openpyxl? | 38,527,725 | <p>I'm hiding a bunch of columns in an Excel sheet. I'm getting this error: <code>AttributeError: can't set attribute</code> from this line <code>worksheet.column_dimensions['B'].visible = False</code></p>
<p>Sorry if this is a super simple question. I just updated to a new version of Openpyxl/Pandas so i'm now having... | 0 | 2016-07-22T13:29:01Z | 38,528,918 | <p>Columns can be grouped:</p>
<pre><code>ws.column_dimensions.group(start='B', end='CU', hidden=True)
</code></pre>
| 0 | 2016-07-22T14:25:33Z | [
"python",
"openpyxl"
] |
Python Array slicing. [:,:] | 38,527,922 | <p>I have this code that I am looking over and commenting (I made some improvements to it but I have not really looked in-depth at the math and creation part)</p>
<p>Declaration :</p>
<pre><code>percentile = ((nextImage - BaselineMin) / (BaselineMax - BaselineMin)) * 100
</code></pre>
<p>Where nextImage, BaselineMin... | 0 | 2016-07-22T13:38:11Z | 38,528,223 | <p>That line of code sets every element in "percentile" that has a value of 0 to -999.</p>
<p>Here is a simple 2 by 2 example:</p>
<pre><code>>>> import numpy as np
>>> arr = np.array([[1,2],[0,4]])
>>> arr
array([[1, 2],
[0, 4]])
>>> arr[:,:][arr[:,:] == 0] = -999
>>&... | 1 | 2016-07-22T13:52:29Z | [
"python",
"arrays",
"python-2.7",
"numpy"
] |
Python Array slicing. [:,:] | 38,527,922 | <p>I have this code that I am looking over and commenting (I made some improvements to it but I have not really looked in-depth at the math and creation part)</p>
<p>Declaration :</p>
<pre><code>percentile = ((nextImage - BaselineMin) / (BaselineMax - BaselineMin)) * 100
</code></pre>
<p>Where nextImage, BaselineMin... | 0 | 2016-07-22T13:38:11Z | 38,528,245 | <p>As I understand it, the line of code in question reads like this:</p>
<p>"Set anything in <code>percentile</code> that is 0 to -999".</p>
<p>The first part <code>percentile[:,:]</code> just refers to every element in <code>percentile</code>. I'm fairly sure you wouldn't need the array slicing here, just replacing ... | 2 | 2016-07-22T13:53:35Z | [
"python",
"arrays",
"python-2.7",
"numpy"
] |
Python Array slicing. [:,:] | 38,527,922 | <p>I have this code that I am looking over and commenting (I made some improvements to it but I have not really looked in-depth at the math and creation part)</p>
<p>Declaration :</p>
<pre><code>percentile = ((nextImage - BaselineMin) / (BaselineMax - BaselineMin)) * 100
</code></pre>
<p>Where nextImage, BaselineMin... | 0 | 2016-07-22T13:38:11Z | 38,528,438 | <h1>Cutting the operation</h1>
<h2>first part</h2>
<p><code>percentile[:, :] == 0</code> or just <code>percentile == 0</code> will give a boolean numpy array of 720x600, True where the value==0 otherwise False.</p>
<h2>second part</h2>
<p><code>percentile[percentile == 0]</code> gives the values that meet the condi... | 1 | 2016-07-22T14:03:19Z | [
"python",
"arrays",
"python-2.7",
"numpy"
] |
How do I test a method that requires a file's presence? | 38,528,004 | <p>For the first time, I'm using Python to create a library, and I'm trying to take the opportunity in this project to learn unit testing. I've written a first method and I want to write some unit tests for it. (Yes, I know that TDD requires I write the test first, I'll get there, really.)</p>
<p>The method is fairly ... | 9 | 2016-07-22T13:41:25Z | 38,531,496 | <p>There are so many different way to approach this. I like to think what would be valuable to test, off the top of my head, I can think of a couple things:</p>
<ul>
<li>validation logic (<code>if self.file == None</code>)</li>
<li>pruning logic </li>
<li>that all file types claimed to be supported are actually suppo... | 2 | 2016-07-22T16:38:38Z | [
"python",
"unit-testing"
] |
How do I test a method that requires a file's presence? | 38,528,004 | <p>For the first time, I'm using Python to create a library, and I'm trying to take the opportunity in this project to learn unit testing. I've written a first method and I want to write some unit tests for it. (Yes, I know that TDD requires I write the test first, I'll get there, really.)</p>
<p>The method is fairly ... | 9 | 2016-07-22T13:41:25Z | 38,533,332 | <p>Suggest refactoring the pruning logic to a separate method that does not depend on file or ZipFile. This:</p>
<pre><code>def file_count(self):
...
with ZipFile(self.file) as zip:
members = zip.namelist()
# Remove folder members if there are any.
pruned = [item for item in members if ... | 0 | 2016-07-22T18:41:52Z | [
"python",
"unit-testing"
] |
How do I test a method that requires a file's presence? | 38,528,004 | <p>For the first time, I'm using Python to create a library, and I'm trying to take the opportunity in this project to learn unit testing. I've written a first method and I want to write some unit tests for it. (Yes, I know that TDD requires I write the test first, I'll get there, really.)</p>
<p>The method is fairly ... | 9 | 2016-07-22T13:41:25Z | 38,557,629 | <p><a href="http://stackoverflow.com/users/5763213/oasiscircle">Oasiscircle</a> and <a href="http://stackoverflow.com/users/594589/dm03514">dm03514</a> were very helpful on this and lead me to the right answer eventually, especially with dm's answer to a <a href="http://stackoverflow.com/questions/38556197/how-do-i-moc... | 0 | 2016-07-24T22:52:17Z | [
"python",
"unit-testing"
] |
SWIG typemap from C char* to python string | 38,528,102 | <p>I am trying to use a C library in Python using SWIG. This C library passes function results through arguments everywhere. Using the online SWIG manual, I have succeeded in getting an integer function result passed to Python, but I am having a hard time figuring out how to do this for a character string. </p>
<p>Thi... | 0 | 2016-07-22T13:45:54Z | 38,539,335 | <p>Have a look at the SWIG manual <a href="http://www.swig.org/Doc3.0/SWIGDocumentation.html#Library_nn12" rel="nofollow">9.3.4 String handling: cstring.i</a>. This provides several typemaps for use with <code>char *</code> arguments.</p>
<p>Probably (assuming you are indeed using <code>strcpy(outstr, "aaa")</code> as... | 1 | 2016-07-23T07:30:44Z | [
"python",
"c",
"swig",
"typemaps"
] |
SWIG typemap from C char* to python string | 38,528,102 | <p>I am trying to use a C library in Python using SWIG. This C library passes function results through arguments everywhere. Using the online SWIG manual, I have succeeded in getting an integer function result passed to Python, but I am having a hard time figuring out how to do this for a character string. </p>
<p>Thi... | 0 | 2016-07-22T13:45:54Z | 38,561,366 | <p>This is how I got it to work, by modifying the example in section 34.9.3 of the <a href="http://swig.org/Doc2.0/Python.html#Python_nn53" rel="nofollow">SWIG 2.0 manual</a>:</p>
<pre><code>%typemap(in, numinputs=0) char *outstr (char temp) {
$1 = &temp;
}
%typemap(argout) char *outstr {
PyObject *o, *o2,... | 0 | 2016-07-25T06:52:33Z | [
"python",
"c",
"swig",
"typemaps"
] |
Write html tags to text file in python | 38,528,179 | <p>I've used pdfminer to convert complex (tables, figures) and very long pdfs to html. I want to parse the results further (e.g. extract tables, paragraphs etc) and then use sentence tokenizer from nltk to do further analysis. For this purposes I want to save the html to text file to figure out how to do the parsing. U... | 0 | 2016-07-22T13:49:38Z | 38,528,423 | <p>First, unless there's a trivial error, </p>
<p>the .txt write happens after the return function: txt file write is never executed!</p>
<p>Then, to suppress output to the console, just do that before running your routine:</p>
<pre><code> import sys,os
oldstdout = sys.stdout # save to be able to restore it later
... | 0 | 2016-07-22T14:02:37Z | [
"python",
"io",
"pdftotext",
"pdfminer",
"pdf-to-html"
] |
How to use super() with arguments in Python 2.7? | 38,528,215 | <p>I am asking this question because every single other page on SO I've Googled on the subject seems to devolve into overly simple cases or random discussions on details beyond the scope.</p>
<pre><code>class Base:
def __init__(self, arg1, arg2, arg3, arg4):
self.arg1 = arg1
self.arg2 = arg2
... | 0 | 2016-07-22T13:52:02Z | 38,528,264 | <p>Your base class must inherit from <code>object</code> (new style class) and the call to <code>super</code> should be <code>super(Child, self)</code>.</p>
<p>You should also not pass <code>arg5</code> to <code>Base</code>'s <code>__init__</code>.</p>
<pre><code>class Base(object):
def __init__(self, arg1, arg2,... | 5 | 2016-07-22T13:54:26Z | [
"python",
"python-2.7",
"class",
"arguments",
"super"
] |
How to get previous date from a date without saturday,sunday and holiday? | 38,528,332 | <p>Need to get previous date from given without sat, sun and holidays(table).</p>
<p>Leave scenerio.</p>
<pre><code>f_date=self.get_query_argument("from_date")
date_1 = datetime.strptime(f_date,"%Y-%m-%d")
bef_date = date_1 - timedelta(days=1)
if bef_date.weekday()==5:
prev_date = bef_date - timedelta(days=1)
elif... | 1 | 2016-07-22T13:57:51Z | 38,528,474 | <p>try using "in" on your table</p>
<pre><code>foo = [1,2,3,4,5]
2 in foo
</code></pre>
<p>returns "True"</p>
<p>for dates</p>
<pre><code>d1 = (datetime.datetime.now()-datetime.timedelta(1)).date()
d2 = (datetime.datetime.now()-datetime.timedelta(2)).date()
d3 = (datetime.datetime.now()-datetime.timedelta(3)).date(... | 0 | 2016-07-22T14:04:35Z | [
"python"
] |
How can I create a tuple consisting of class objects? | 38,528,367 | <p>This question is for Python version 2.7. For example, if I have the following class:</p>
<pre><code>class Example:
def __init__(self, a, b):
self.a = a
self.b = b
object = Example("x", "y")
t = tuple(object)
</code></pre>
<p>After executing the code above I get <code>TypeError: iteration over n... | 2 | 2016-07-22T13:59:25Z | 38,528,392 | <p>You don't have to call <code>tuple</code> on the object to do this:</p>
<pre><code>obj = Example("x", "y")
t = (obj,) # one item tuple
</code></pre>
<p>Be careful to not use the name <code>object</code> to not shadow the builtin <code>object</code> class.</p>
<p>To create a tuple with more than one item:</p>
<pr... | 2 | 2016-07-22T14:01:13Z | [
"python",
"python-2.7",
"tuples"
] |
How can I create a tuple consisting of class objects? | 38,528,367 | <p>This question is for Python version 2.7. For example, if I have the following class:</p>
<pre><code>class Example:
def __init__(self, a, b):
self.a = a
self.b = b
object = Example("x", "y")
t = tuple(object)
</code></pre>
<p>After executing the code above I get <code>TypeError: iteration over n... | 2 | 2016-07-22T13:59:25Z | 38,528,579 | <p>Your problem doesn't really have to do with the type of the tuple's elements, but rather with single-item tuples. From the <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>A special problem is the construction of tuples con... | 1 | 2016-07-22T14:09:12Z | [
"python",
"python-2.7",
"tuples"
] |
Send parameters to a user-defined function? | 38,528,371 | <p>We define a user-defined function as follows.</p>
<pre><code>def testfun(x):
return( x[0]*a+x[1]*b)
</code></pre>
<p>Call the function:</p>
<pre><code>sol = optimize.root(testfun, [0, 0], method = 'lm')
</code></pre>
<p>How can we pass <code>a</code> and <code>b</code> when calling the function ?</p>
| -2 | 2016-07-22T13:59:35Z | 38,528,406 | <p>For this problem specifically, <code>optimize.root</code> has an <code>args</code> input which accepts a tuple of values to pass as additional inputs to your objective function:</p>
<pre><code>def testfun(x, a, b):
return ([x[0] * a + x[1] * b])
# Specify values for a and b
a = 1
b = 2
sol = optimize.root(tes... | 4 | 2016-07-22T14:01:42Z | [
"python",
"python-3.x",
"scipy"
] |
How to efficiently replace element in plot with ipywidgets? | 38,528,426 | <p>How can I efficiently display similar plots with ipywidgets using Jupyter Notebook?</p>
<p>I wish to plot interactively a heavy plot (heavy in the sense that it has lots of data points and takes some time to plot it) and modify a single element of it using interact from ipywidgets without replotting all the complic... | 0 | 2016-07-22T14:02:46Z | 38,529,367 | <p>This is an rough example of an interactive way to change a rectangle width (I'm assuming you are in an IPython or Jupyter notebook):</p>
<pre><code>import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import ipywidgets
from IPython.display import display
%matplotlib nbagg
f = pl... | 1 | 2016-07-22T14:47:13Z | [
"python",
"matplotlib",
"jupyter",
"jupyter-notebook",
"ipywidgets"
] |
print elements in list as concatenated string | 38,528,453 | <p>I have a simple dictionary: </p>
<pre><code>convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
</code></pre>
<p>and list</p>
<pre><code>letters = ('a', 'b', 'c', 'd')
</code></pre>
<p>I want to iterate over each element in the list, and use it as a lookup in my dictionary, and print the value <strong>as a concatenat... | 2 | 2016-07-22T14:03:58Z | 38,528,490 | <p>Use <a href="https://docs.python.org/2.7/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> with a generator expression.
Note that you have to explicitly convert to <code>str</code> when using this method:</p>
<pre><code>convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
letters = ('a', 'b', 'c', 'd')... | 4 | 2016-07-22T14:05:08Z | [
"python",
"python-2.7",
"printing"
] |
print elements in list as concatenated string | 38,528,453 | <p>I have a simple dictionary: </p>
<pre><code>convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
</code></pre>
<p>and list</p>
<pre><code>letters = ('a', 'b', 'c', 'd')
</code></pre>
<p>I want to iterate over each element in the list, and use it as a lookup in my dictionary, and print the value <strong>as a concatenat... | 2 | 2016-07-22T14:03:58Z | 38,528,991 | <p>If all you want is to <code>print</code> only and you don't need the end result, then you can use the <code>arg</code> of <a href="https://docs.python.org/2/library/functions.html#print" rel="nofollow"><code>print</code></a> method:</p>
<pre><code>>>> from __future__ import print_function
>>> for ... | 1 | 2016-07-22T14:28:59Z | [
"python",
"python-2.7",
"printing"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.