title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
python & pandas - Drop rows where column values are index values in another DataFrame | 39,391,816 | <p>The Original DataFrame(<code>df1</code>) looks like:</p>
<pre><code> NoUsager Sens NoAdresse Fait Weekday NoDemande Periods
0 000001 + 000079 1 Dim 42191000972 Soir
1 001875 + 005018 1 Dim 42191001052 Matin
2 001651 + 005018 1 Dim 42191001051 Matin
3 001486 + ... | 1 | 2016-09-08T13:07:32Z | 39,392,483 | <pre><code>cols = ['NoDemande','NoUsager']
mask = df1[cols].isin(df2.reset_index()[cols].to_dict('list'))
df1[~mask.all(1)]
</code></pre>
<p><a href="http://i.stack.imgur.com/wfDHx.png" rel="nofollow"><img src="http://i.stack.imgur.com/wfDHx.png" alt="enter image description here"></a></p>
<hr>
<p>There were three t... | 2 | 2016-09-08T13:36:58Z | [
"python",
"pandas",
"dataframe"
] |
script to embed in android device? | 39,391,847 | <p><strong>Scenario:</strong> I want to embed a script/executable (whatever) into a Android device to control the camera app, take photos open and close the camera app. I have root access to the device.
<strong>Question:</strong> Is it possible to do by using python/adb? how can I do that?</p>
| -1 | 2016-09-08T13:08:32Z | 39,391,932 | <p>If you have root access then you can do that easily as you have full access to your device. Using background services and sometimes broadcast receivers you can achieve the scenario explained in the question.</p>
| 0 | 2016-09-08T13:13:06Z | [
"java",
"android",
"python",
"adb"
] |
Python pdb computes value 774 but program assigns 836 | 39,391,997 | <p>I'm sure I am missing something here, but I find this very weird.</p>
<p>In <code>pdb</code> I get to the following step...</p>
<pre><code> Importing data...
> /usr/local/lib/python2.7/dist-packages/tensorflow/tensorflow/scroll/marching_cube.py(111)read_data()
-> n_cubes = int((n_slices - n_input_z) * int(ma... | 1 | 2016-09-08T13:15:35Z | 39,393,840 | <p>Try setting the breakpoint at the start of the function being run as a thread, or within its <code>while true:</code> loop if it has one, by adding this:</p>
<pre><code>import pdb
pdb.set_trace()
</code></pre>
<p>Then run the script normally (<em>not</em> through <code>pdb</code>) and execution will break into the... | 0 | 2016-09-08T14:39:15Z | [
"python",
"pdb"
] |
finding the maximum value between text and numbers for each timestep | 39,392,004 | <p>I have the intention to find the maximum values for each rows under the TS in the input data for a very big data. This is the input data:</p>
<pre><code>SCALAR
ND 3
ST 0
TS 10.00
0.0000
0.0000
0.0000
SCALAR
ND 3
ST 0
TS 3600.47
255.1744
255.0201
257.0000
SCALAR
ND 3
ST 0
TS 7200.42
255.... | 0 | 2016-09-08T13:15:48Z | 39,392,358 | <p>Your attempt fails in several different places; you assigned to <code>lines1</code> but ignored that, you try to use the <code>lines</code> list each and every iteration to produce a <code>max()</code> value, you never filtered out the non-numeric lines so trying to call <code>float()</code> on those would fail, and... | 2 | 2016-09-08T13:31:12Z | [
"python",
"list",
"python-3.x",
"max"
] |
Django Rest framework Viewset Permissions "create" without "list" | 39,392,007 | <p>I have the following viewset:</p>
<pre><code>class ActivityViewSet(viewsets.ModelViewSet):
queryset = Activity.objects.all()
serializer_class = ActivitySerializer
def get_permissions(self):
if self.action in ['update','partial_update','destroy','list']:
self.permission_classes = [pe... | 0 | 2016-09-08T13:15:51Z | 39,392,875 | <p>Maybe you can try this:</p>
<pre><code>class NotCreateAndIsAdminUser(permissions.IsAdminUser):
def has_permission(self, request, view):
return (view.action in ['update','partial_update','destroy','list']
and super(NotCreateAndIsAdminUser, self).has_permission(request, view))
class Cr... | 1 | 2016-09-08T13:55:14Z | [
"python",
"django",
"permissions",
"django-rest-framework"
] |
pandas.value_counts for NA | 39,392,021 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>pandas.value_counts</code></a>
works for numeric arrays with <code>None</code>:</p>
<pre><code>> s = pd.Series([1,2,1,None])
> vc = s.value_counts(dropna=False)
> vc
1.0 2
2.0 1
NaN ... | 1 | 2016-09-08T13:16:31Z | 39,392,175 | <p>I was also surprised to see that <code>cv[np.nan]</code> does not work, but this does: <code>vc.loc[np.nan]</code></p>
| 1 | 2016-09-08T13:23:17Z | [
"python",
"pandas",
"types"
] |
Derived Result from Butter Filter and FFT doesn't change over time | 39,392,173 | <p>I am very new in Signal Processing, have met a situation that I am not sure if it is correct or not. Please correct me then I will update more details.</p>
<p>My data is <a href="https://app.box.com/s/8ijccq76z65itv9jluid3nadfzp160qr" rel="nofollow">here</a> </p>
<p>I acquired an accelerometer signal taken from m... | 1 | 2016-09-08T13:23:15Z | 39,407,217 | <p>I give the problem a quick try, and below is my snippet</p>
<pre><code>data = _accel['v'].tolist()
Fs = 99
# remove the DC part, to help the plotting later
data = data - np.mean(data)
# Perform FFT for real data, on the whole 6000 samples,
# using 4096 discrete frequencies, which is dense enough to capture
# ... | 0 | 2016-09-09T08:33:01Z | [
"python",
"signals",
"fft",
"sensor"
] |
Derived Result from Butter Filter and FFT doesn't change over time | 39,392,173 | <p>I am very new in Signal Processing, have met a situation that I am not sure if it is correct or not. Please correct me then I will update more details.</p>
<p>My data is <a href="https://app.box.com/s/8ijccq76z65itv9jluid3nadfzp160qr" rel="nofollow">here</a> </p>
<p>I acquired an accelerometer signal taken from m... | 1 | 2016-09-08T13:23:15Z | 39,425,743 | <p>The problem is that every time a new chunk of data is processed in your loop, the filtering is initialized with a default state (which correspond to the state of the filter if all previous samples were zeros). As a result, the filter barely has time to settle after the initial transient (caused by the step from thos... | 0 | 2016-09-10T11:48:58Z | [
"python",
"signals",
"fft",
"sensor"
] |
Pelican site language | 39,392,297 | <p>I am setting up a new Pelican blog and stumbled upon a bit of a problem. I am German, the blog is going to be in german so I want the generated text (dates, 'Page 1/5'...) to be in german. (In my post date I include the weekday)</p>
<p>In <code>pelicanconf.py</code> I tried<br>
<code>DEFAULT_LANG = u'ger'</code> an... | 0 | 2016-09-08T13:28:55Z | 39,392,393 | <p>Did you try <a href="http://docs.getpelican.com/en/3.6.3/settings.html?highlight=locale" rel="nofollow">LOCALE</a>?</p>
<pre><code>LOCALE = ('de_DE', 'de')
</code></pre>
<p>See <a href="http://docs.getpelican.com/en/3.6.3/settings.html#date-format-and-locale" rel="nofollow">Date format and locale</a> for more info... | 1 | 2016-09-08T13:32:45Z | [
"python",
"blogs",
"pelican"
] |
Reshaping OpenCV Image (numpy) Dimensions | 39,392,340 | <p>I need to convert an image in a numpy array loaded via cv2 into the correct format for the deep learning library mxnet for its convolutional layers.</p>
<p>My current images are shaped as follows: (256, 256, 3), or (height, width, channels).</p>
<p>From what I've been told, this actually needs to be (3, 256, 256),... | 1 | 2016-09-08T13:30:41Z | 39,392,523 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html" rel="nofollow"><code>numpy.rollaxis</code></a> as follow:
If your <code>image</code> as shape <code>(height, width, channels)</code></p>
<pre><code>import numpy as np
new_shaped_image = np.rollaxis(image, axis=2, start=0)... | 2 | 2016-09-08T13:39:11Z | [
"python",
"opencv",
"numpy",
"mxnet"
] |
How do I make a custom model Field call to_python when the field is accessed immediately after initialization (not loaded from DB) in Django >=1.10? | 39,392,343 | <p>After upgrading from Django <code>1.9</code> to <code>1.10</code>, I've experienced a change in behaviour with a field provided by the django-geolocation package.</p>
<p>This is the change that was made for <code>1.10</code> compatibility that broke the behaviour: <a href="https://github.com/philippbosch/django-geo... | 12 | 2016-09-08T13:30:49Z | 39,471,064 | <p>After lots of digging it turns out that in <code>1.8</code> the behaviour of custom fields was changed in such a way that <code>to_python</code> is no longer called on assignment to a field.</p>
<p><a href="https://docs.djangoproject.com/en/1.10/releases/1.8/#subfieldbase">https://docs.djangoproject.com/en/1.10/rel... | 6 | 2016-09-13T13:14:46Z | [
"python",
"django",
"django-models",
"django-geoposition"
] |
How to pass "-v" argument for python in pyCharm IDE | 39,392,385 | <p>I want to run a python program in verbose mode in pycharm IDE. I specified "-v" in Interpreter option under Run/Debug Configurations window. But it shows the following error:</p>
<blockquote>
<p>/usr/bin/python2.7
/home/user1/Downloads/pycharm-community-2016.1.4/helpers/pydev/pydev_run_in_console.py
35261 342... | 1 | 2016-09-08T13:32:31Z | 39,395,547 | <p>It should work if you run it like this:</p>
<pre><code>/usr/bin/python2.7 -v /home/user1/my_codings/gitStuffs/Cura_Debian_Release/usr/share/cura/cura.py
</code></pre>
<p>If you need debugger (or to add other files) then <code>-v</code> should go first:</p>
<pre><code>/usr/bin/python2.7 -v /home/user1/Downloads/py... | 0 | 2016-09-08T16:01:01Z | [
"python",
"pycharm"
] |
Why is file.close() slowing my code | 39,392,437 | <p>I am writing a program which generates a specified number of sentences, which are each written to a file. I have been trying to optimize the code for cases with 10 million sentences or more. </p>
<p>I recently specified the buffer parameter in my open calls to 512MB in order to improve write performance however, m... | 0 | 2016-09-08T13:34:47Z | 39,392,792 | <p>Writing to disk is slow, so many programs store up writes into large chunks which they write all-at-once. This is called buffering, and Python does it automatically when you open a file. When you write to the file, you're actually writing to a "buffer" in memory. When it fills up, Python will automatically write it ... | 1 | 2016-09-08T13:51:56Z | [
"python",
"performance",
"io"
] |
Why is file.close() slowing my code | 39,392,437 | <p>I am writing a program which generates a specified number of sentences, which are each written to a file. I have been trying to optimize the code for cases with 10 million sentences or more. </p>
<p>I recently specified the buffer parameter in my open calls to 512MB in order to improve write performance however, m... | 0 | 2016-09-08T13:34:47Z | 39,393,552 | <p>You explicitly elected to use a huge buffer (that 536870912 is the number of bytes buffered before flushing the buffer, about half a GB of memory). <code>close</code> includes an implicit <code>flush</code> of whatever is left in the buffer, and assuming you're writing a lot, that's going to mean it involves writing... | 1 | 2016-09-08T14:25:56Z | [
"python",
"performance",
"io"
] |
How to mute all sounds in chrome webdriver with selenium | 39,392,479 | <p>I want to write a script in which I use selenium package like this:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.youtube.com/watch?v=hdw1uKiTI5c")
</code></pre>
<p>now after getting the desired URL I want to mute the chrome sounds.
how could I do this?
somethin... | 6 | 2016-09-08T13:36:40Z | 39,392,601 | <p>Not sure if you can, generally for any page, do it after you have opened the page, but you can mute all the sound for the entire duration of the browser session by setting the <a href="http://peter.sh/experiments/chromium-command-line-switches/#mute-audio" rel="nofollow"><code>--mute-audio</code></a> switcher:</p>
... | 7 | 2016-09-08T13:43:39Z | [
"python",
"selenium"
] |
Copying and Modifying a Dataframe Pandas | 39,392,639 | <p>I have 3 Dataframes df1,df,df3 all copying an original Dataframe df0.</p>
<pre><code>df1=df0
df2=df0
df3=df0
df1=dfo.iloc[1:,1:].div(dfo.iloc[1:,1:].sum(axis=1),axis=0)
df2=dfo.iloc[1:,1:].div(dfo.iloc[1:,1:].sum(axis=1),axis=0)*ACCOUNT_CASH
df3=df2//df0
print(df1)
print(df2)
print(df3)
</code></pre>
<p>Somehow ... | 2 | 2016-09-08T13:45:27Z | 39,392,826 | <p>Your lines </p>
<pre><code>df1=df0
df2=df0
df3=df0
</code></pre>
<p>simply create three new bindings, where three new names refer to <em>the same object</em> as that bound to by <code>df0</code>. </p>
<p>To actually create copies, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame... | 2 | 2016-09-08T13:52:59Z | [
"python",
"variables",
"pointers",
"pandas",
"memory"
] |
How can I document click commands using Sphinx? | 39,392,753 | <p>(Note: this is being asked to share knowledge, not to look for help)</p>
<p><a href="http://click.pocoo.org/5/" rel="nofollow"><code>click</code></a> is a popular Python library for developing CLI applications with. <a href="http://www.sphinx-doc.org/en/stable/" rel="nofollow"><code>sphinx</code></a> is a popular l... | 1 | 2016-09-08T13:50:17Z | 39,392,754 | <p><strong>Decorating command containers</strong></p>
<p>One possible solution to this problem that I've recently discovered and seems to work would be to start off defining a decorator that can be applied to classes. The idea is that the programmer would define commands as private members of a class, and the decorato... | 1 | 2016-09-08T13:50:17Z | [
"python",
"documentation",
"command-line-interface",
"python-sphinx",
"python-click"
] |
Best event for QtableWidget to add subrecords in pyqt | 39,392,901 | <p>I have a relational database with 2 related tables.
Also <code>psycopg2</code> adapter were used to retrieve data.There are two <code>QtableWidget</code> to display data from two related tables in ui.
What is the appropriate event (from <code>QtableWidget</code> events) to detect new record is selected or filled int... | 1 | 2016-09-08T13:56:55Z | 39,396,641 | <p>You probably want to connect to the <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qtablewidget.html#itemSelectionChanged" rel="nofollow">itemSelectionChanged</a> signal.</p>
<pre><code>def __init__(...)
...
self.table1.itemSelectionChanged.connect(self.update_table2)
def update_table2(self):
items = ... | 0 | 2016-09-08T17:05:36Z | [
"python",
"pyqt",
"relational-database",
"psycopg2",
"qtablewidget"
] |
Redeployable conda environments | 39,392,910 | <p>I want to create a conda environment on my laptop that I can deploy to my cluster. For this I want two things:</p>
<ol>
<li>To be able to create a conda environment for a different architecture</li>
<li>To be able to zip up the environment, move it to some other place in some other file system, unzip it, and run <... | 3 | 2016-09-08T13:57:10Z | 39,393,176 | <p>At present, conda does not have a direct way to create environments for arbitrary architectures. I'm also not sure exactly how feasible it is. For the vast majority of packages, it's just a metadata thing, and is totally workable. For binary packages, though, we (sometimes) have to replace the prefix that is embe... | 2 | 2016-09-08T14:09:21Z | [
"python",
"conda"
] |
Django: ManyToMany URL in Template | 39,393,011 | <p>I can't add URL my <code>category title</code> in homepage. There is my code and error. What i can add instead of <code>{{ c.get_absolute_url }}</code>. What i am missing here?</p>
<p>models.py </p>
<pre><code>class Category(models.Model):
title = models.CharField(max_length=120, unique=True)
slug = mo... | 1 | 2016-09-08T14:02:09Z | 39,393,371 | <p>In your models you call <code>category_url</code> but in your urls you have <code>category_detail</code>, replace the <code>get_absolute_url</code> function for this:</p>
<pre><code>def get_absolute_url(self):
return reverse("category_detail", kwargs={"slug": self.slug})
</code></pre>
| 1 | 2016-09-08T14:18:06Z | [
"python",
"django",
"django-templates",
"django-urls"
] |
python: find keys in a dictionary whose values are lists of strings by searching list with a regex return an iterator over the keys | 39,393,029 | <p>I have a dictionary whose items a lists of strings. I want an iterator over the keys that gives me just those keys that have in their items a string which matches a regex.</p>
<pre><code>my_dict = { "uk" : ["prince albert", "princes diana", "elton john", "john lennon"],
"us" : ["albert einstein", "prince", "john... | 0 | 2016-09-08T14:02:59Z | 39,393,886 | <p>This should do the trick:</p>
<pre><code>text = 'prince'
keys = set([key for key in my_dict for item in my_dict[key] if text in item])
</code></pre>
<p>or as a function:</p>
<pre><code>def trick(text, values):
keys = set([key for key in values for item in my_dict[key] if text in item])
return keys
</code>... | 0 | 2016-09-08T14:41:10Z | [
"python",
"regex",
"dictionary",
"iterator"
] |
python: find keys in a dictionary whose values are lists of strings by searching list with a regex return an iterator over the keys | 39,393,029 | <p>I have a dictionary whose items a lists of strings. I want an iterator over the keys that gives me just those keys that have in their items a string which matches a regex.</p>
<pre><code>my_dict = { "uk" : ["prince albert", "princes diana", "elton john", "john lennon"],
"us" : ["albert einstein", "prince", "john... | 0 | 2016-09-08T14:02:59Z | 39,394,157 | <p>Here is generator:</p>
<pre><code>def iterkeysregex(regexp, dict):
cr = re.compile(regexp)
# index keys
match_keys = [k for k, v in dict.items() if cr.search("".join(v))]
# generating
for k in match_keys:
yield k
</code></pre>
<p>Usage</p>
<pre><code>for x in iterkeysregex('to', my_dict):
print(x,... | 0 | 2016-09-08T14:54:43Z | [
"python",
"regex",
"dictionary",
"iterator"
] |
python: find keys in a dictionary whose values are lists of strings by searching list with a regex return an iterator over the keys | 39,393,029 | <p>I have a dictionary whose items a lists of strings. I want an iterator over the keys that gives me just those keys that have in their items a string which matches a regex.</p>
<pre><code>my_dict = { "uk" : ["prince albert", "princes diana", "elton john", "john lennon"],
"us" : ["albert einstein", "prince", "john... | 0 | 2016-09-08T14:02:59Z | 39,398,588 | <p>The version I ended up using looks essentially like this:</p>
<pre><code>def iterkeysregex(my_dict, my_regex):
regex = re.compile(my_regex)
for k, v in my_dict.iteritems():
for s in v:
if re.search(regex, s):
yield k
</code></pre>
<p>Thanks to all who helped.</p>
| 0 | 2016-09-08T19:14:40Z | [
"python",
"regex",
"dictionary",
"iterator"
] |
Trying to compile Python fails because of files' timestamps | 39,393,063 | <p>I want to compile Python; I cloned the repository from Github:</p>
<pre><code>git clone --depth=1 --branch=2.7 https://github.com/python/cpython.git
</code></pre>
<p>Configure works but building fails because Python is not found:</p>
<pre><code>$ cd cpython
$ ./configure
...
$ make
/bin/mkdir -p Include
./Parser/... | 1 | 2016-09-08T14:04:39Z | 39,423,382 | <p>Apparently it's known issue. Use <code>make touch</code> after checkout, then <code>make</code> should work.</p>
<p>See <a href="https://github.com/python/cpython/blob/b72e279bfa0eece094f652b9fc329200d5964ffa/Makefile.pre.in#L1504" rel="nofollow">https://github.com/python/cpython/blob/b72e279bfa0eece094f652b9fc3292... | 0 | 2016-09-10T06:45:11Z | [
"python",
"git",
"makefile",
"compilation"
] |
Update large sqlite database in chunks | 39,393,095 | <p>I have a sqlite database (appr. 11 GB) that has multiple tables including the tables <code>distance</code> and <code>vertices</code>. The table <code>distance</code> is pretty large (120 mio rows), <code>vertices</code> is smaller (15 000 rows). I want to use sqlite3 in python to update one column of <code>distance<... | 1 | 2016-09-08T14:06:07Z | 39,399,561 | <p>It should be possible to update chunks with statements like this:</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE distance SET ... WHERE rowid BETWEEN 100000 AND 200000;
</code></pre>
<p>You don't need to use multiple transactions; the only thing that actually must be kept in memory is the list of rows... | 1 | 2016-09-08T20:22:00Z | [
"python",
"memory",
"sqlite3",
"sql-update"
] |
How to fetch JSON data from API, format / encode / write to a file? | 39,393,200 | <p>I need to fetch some data from a weather API, extract certain info and send it to std. output (in my case this is the console/terminal; I am playing around with python API scripting and do not yet have a web site/app do show fetched data).</p>
<p><strong>Example Python code from the API provider (simple to understa... | 2 | 2016-09-08T14:10:27Z | 39,393,717 | <p>Seems that it was quite a simple solution. In my original code, I was saving a "non-parsed" variable to a file:</p>
<pre><code>import urllib2
import json
API_KEY='key'
f = urllib2.urlopen('http://api.wunderground.com/api/'
+ API_KEY + '/geolookup/conditions/q/IA/Cedar_Rapids.json')
# Saving the below variable i... | 1 | 2016-09-08T14:33:51Z | [
"python",
"json"
] |
Python append value to a list returned from a function via for loop | 39,393,223 | <p>I have a function:</p>
<pre><code>def function(x,y):
do something
print a,b
return a,b
</code></pre>
<p>Now I use a for loop like:</p>
<pre><code>for i in range(10,100,10):
function(i,30)
</code></pre>
<p>which prints the values <code>a,b</code> for the given input values via the for loop.
It al... | 0 | 2016-09-08T14:11:38Z | 39,393,350 | <p>you can use list comprehension first, get list_a, list_b via zip.</p>
<pre><code>def function(x,y):
return x,y
result = [function(i,30) for i in range(10,100,10)]
list_a, list_b = zip(*result)
</code></pre>
| 3 | 2016-09-08T14:17:18Z | [
"python",
"list",
"function",
"for-loop",
"append"
] |
Python append value to a list returned from a function via for loop | 39,393,223 | <p>I have a function:</p>
<pre><code>def function(x,y):
do something
print a,b
return a,b
</code></pre>
<p>Now I use a for loop like:</p>
<pre><code>for i in range(10,100,10):
function(i,30)
</code></pre>
<p>which prints the values <code>a,b</code> for the given input values via the for loop.
It al... | 0 | 2016-09-08T14:11:38Z | 39,393,352 | <p>You mean something like that:</p>
<pre><code>list_a = []
list_b = []
for i in range(10,100,10):
a, b = function(i,30)
list_a.append(a)
list_b.append(b)
</code></pre>
| 0 | 2016-09-08T14:17:24Z | [
"python",
"list",
"function",
"for-loop",
"append"
] |
Python append value to a list returned from a function via for loop | 39,393,223 | <p>I have a function:</p>
<pre><code>def function(x,y):
do something
print a,b
return a,b
</code></pre>
<p>Now I use a for loop like:</p>
<pre><code>for i in range(10,100,10):
function(i,30)
</code></pre>
<p>which prints the values <code>a,b</code> for the given input values via the for loop.
It al... | 0 | 2016-09-08T14:11:38Z | 39,393,363 | <p>you may need to try map() function, which is more friendly~~</p>
<p><a href="http://stackoverflow.com/questions/10973766/understanding-the-map-function">Understanding the map function</a></p>
<p>which should be the same as in python 3:
def map(func, iterable):
for i in iterable:
yield func(i) </p>
<p... | -2 | 2016-09-08T14:17:48Z | [
"python",
"list",
"function",
"for-loop",
"append"
] |
Python append value to a list returned from a function via for loop | 39,393,223 | <p>I have a function:</p>
<pre><code>def function(x,y):
do something
print a,b
return a,b
</code></pre>
<p>Now I use a for loop like:</p>
<pre><code>for i in range(10,100,10):
function(i,30)
</code></pre>
<p>which prints the values <code>a,b</code> for the given input values via the for loop.
It al... | 0 | 2016-09-08T14:11:38Z | 39,393,479 | <p>Something like this should work:</p>
<pre><code># Define a simple test function
def function_test(x,y):
return x,y
# Initialize two empty lists
list_a = []
list_b = []
# Loop over a range
for i in range(10,100,10):
a = function_test(i,30) # The output of the function is a tuple, which we put in "a"
... | 0 | 2016-09-08T14:22:54Z | [
"python",
"list",
"function",
"for-loop",
"append"
] |
Aggregate Pandas DataFrame based on condition that uses multiple columns? | 39,393,294 | <pre><code>import pandas as pd
data = {
"K": ["A", "A", "B", "B", "B"],
"LABEL": ["X123", "X123", "X21", "L31", "L31"],
"VALUE": [1, 3, 1, 2, 5.0]
}
df = pd.DataFrame.from_dict(data)
output = """
K LABEL VALUE
0 A X12 1.0
1 A X12 3.0
2 B X21 1.0
3 B L31 2.0
4 B L31 5.0
"... | 1 | 2016-09-08T14:14:40Z | 39,394,331 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow"><code>DFGroupby.agg</code></a> like you have done before followed by writing a generic function which computes the necessary requirements with the help of <a href="http://pandas.... | 2 | 2016-09-08T15:02:16Z | [
"python",
"pandas",
"dataframe"
] |
Aggregate Pandas DataFrame based on condition that uses multiple columns? | 39,393,294 | <pre><code>import pandas as pd
data = {
"K": ["A", "A", "B", "B", "B"],
"LABEL": ["X123", "X123", "X21", "L31", "L31"],
"VALUE": [1, 3, 1, 2, 5.0]
}
df = pd.DataFrame.from_dict(data)
output = """
K LABEL VALUE
0 A X12 1.0
1 A X12 3.0
2 B X21 1.0
3 B L31 2.0
4 B L31 5.0
"... | 1 | 2016-09-08T14:14:40Z | 39,395,189 | <p>you can try data frame chain:</p>
<pre><code>result = (df.groupby(['K', 'LABEL'])
.apply(lambda frame: frame.VALUE.sum()
if frame.LABEL.iloc[0].startswith("X") else len(frame))
.to_frame()
.rename({'0': 'FINAL_VALUE'})
)
</code></pre>
| 0 | 2016-09-08T15:42:16Z | [
"python",
"pandas",
"dataframe"
] |
Python pydoc for python packages | 39,393,305 | <p>I'm trying to document a python package in <strong>init.py</strong> and it's unclear to me how pydoc parses a """triple bracketed""" comment to display to the user via:</p>
<pre><code>>>> help(package)
</code></pre>
<p>or </p>
<pre><code>$ pydoc package
</code></pre>
<p>How is the comment parsed to pr... | 1 | 2016-09-08T14:15:12Z | 39,394,759 | <p>Let's consider this dummy package:</p>
<pre><code>./whatever
âââ __init__.py
âââ nothing
â  âââ __init__.py
âââ something.py
</code></pre>
<p>in <code>./whatever/__init__.py</code> we have:</p>
<pre><code>"""
This is whatever help info.
This is whatever description
EXAMPLES:
...... | 2 | 2016-09-08T15:20:37Z | [
"python",
"pydoc"
] |
Python pydoc for python packages | 39,393,305 | <p>I'm trying to document a python package in <strong>init.py</strong> and it's unclear to me how pydoc parses a """triple bracketed""" comment to display to the user via:</p>
<pre><code>>>> help(package)
</code></pre>
<p>or </p>
<pre><code>$ pydoc package
</code></pre>
<p>How is the comment parsed to pr... | 1 | 2016-09-08T14:15:12Z | 39,394,854 | <p>Looks like the first line contains a short description (should not exceed one line, as described in <a href="https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings" rel="nofollow">PEP 257</a>), that will be put after the name; followed by a blank line and then a paragraph, what will be used to provide conte... | 1 | 2016-09-08T15:25:19Z | [
"python",
"pydoc"
] |
Python-Dictionary parsing and update better | 39,393,389 | <p>I have an input dictionary which looks like this:</p>
<pre><code>{"payment":
{"payment_id": "AAHPW34190", "clm_list":
{"dtl":
[{"clm_id": "1A2345"},
{"clm_id": "9999"}
]},
"payment_amt": "20"}}
</code></pre>
<p>I need the output to look like this:</p>
<... | 2 | 2016-09-08T14:18:37Z | 39,395,724 | <p>I reformat the output of your input dict. suppose that the following dict is an element of a list, in which there are millions of dict.</p>
<pre><code>{"payment": {"payment_id": "AAHPW34190",
"clm_list": {"dtl": [{"clm_id": "1A2345"}, {"clm_id":"9999"}]},
"payment_amt": "20"}
}
</code></p... | 0 | 2016-09-08T16:09:45Z | [
"python",
"dictionary"
] |
How to add one config file for my WLST python script | 39,393,554 | <p>I have one script to check the server status. But instead of hard coding the server details like (username,password,url) I would like to give those configuration details in seperate config file. Could some one help me to create one seperate config file to give these server details. Please let me know how to create a... | 0 | 2016-09-08T14:25:57Z | 39,398,946 | <p>First, it is a best practice to encrypt user and password instead of storing them in clear text, even in a separate config file. For this purpose use the </p>
<blockquote>
<p>storeUserConfig()</p>
</blockquote>
<p>method to encrypt and store connection's credentials. Next, use the generated file when connecting ... | 0 | 2016-09-08T19:38:24Z | [
"python",
"parsing",
"weblogic",
"config",
"wlst"
] |
What do these lines of code do? | 39,393,652 | <p>I am working with <code>numpy</code>. I encountered this line of code. </p>
<pre><code>a = (1.,80.,5.)
</code></pre>
<p>What does this mean? At some other line, I found</p>
<pre><code>aList = np.arange(a[0], a[1]+a[2], a[2])
</code></pre>
<p><strong>Note:</strong> <code>np</code> is namespace assigned from <code... | -2 | 2016-09-08T14:30:39Z | 39,393,731 | <p>For the first code segment you are creating a tuple with 3 numbers 1, 80 and 5 in this. </p>
<pre><code>a=(1.,80.,5.)
1.0, 80.0, 5.0)
</code></pre>
<p>In the second code segment you are arranging a list with evenly spaced values from 1 to 81 (because you are adding a<a href="http://docs.scipy.org/doc/numpy/referen... | 3 | 2016-09-08T14:34:32Z | [
"python",
"numpy"
] |
What do these lines of code do? | 39,393,652 | <p>I am working with <code>numpy</code>. I encountered this line of code. </p>
<pre><code>a = (1.,80.,5.)
</code></pre>
<p>What does this mean? At some other line, I found</p>
<pre><code>aList = np.arange(a[0], a[1]+a[2], a[2])
</code></pre>
<p><strong>Note:</strong> <code>np</code> is namespace assigned from <code... | -2 | 2016-09-08T14:30:39Z | 39,393,757 | <p>First line is just a tuple.</p>
<p>Second line is using the <code>np.arange</code> method which returns venly spaced values within a given interval:</p>
<p><code>np.arange(start, stop, step)</code></p>
<p>The parameters you have are using the tuple, <code>a</code>.
Where <code>a[0] = 1</code> and <code>a[1] = 80<... | 1 | 2016-09-08T14:35:28Z | [
"python",
"numpy"
] |
What do these lines of code do? | 39,393,652 | <p>I am working with <code>numpy</code>. I encountered this line of code. </p>
<pre><code>a = (1.,80.,5.)
</code></pre>
<p>What does this mean? At some other line, I found</p>
<pre><code>aList = np.arange(a[0], a[1]+a[2], a[2])
</code></pre>
<p><strong>Note:</strong> <code>np</code> is namespace assigned from <code... | -2 | 2016-09-08T14:30:39Z | 39,393,771 | <p><code>a</code> is a <em>tuple</em> of floats. A tuple is a kind of structure that is kinda like a <em>list</em>, but is <em>immutable</em> (i.e. you cannot modify any of its components once it has been created). But, like a list it can be indexed. </p>
<p>In theory, some tuples have special names, for example a tup... | 2 | 2016-09-08T14:36:00Z | [
"python",
"numpy"
] |
What do these lines of code do? | 39,393,652 | <p>I am working with <code>numpy</code>. I encountered this line of code. </p>
<pre><code>a = (1.,80.,5.)
</code></pre>
<p>What does this mean? At some other line, I found</p>
<pre><code>aList = np.arange(a[0], a[1]+a[2], a[2])
</code></pre>
<p><strong>Note:</strong> <code>np</code> is namespace assigned from <code... | -2 | 2016-09-08T14:30:39Z | 39,393,779 | <pre><code>a = (1.,80.,5.)
</code></pre>
<p>Creates a tuple of 3 floats (1.0, 80.0 and 5.0).</p>
<pre><code>aList = np.arange(a[0], a[1]+a[2], a[2])
</code></pre>
<p>Created this list:</p>
<pre><code>[ 1. 6. 11. 16. 21. 26. 31. 36. 41. 46. 51. 56. 61. 66. 71. 76. 81.]
</code></pre>
<p>Which, accor... | 1 | 2016-09-08T14:36:16Z | [
"python",
"numpy"
] |
What do these lines of code do? | 39,393,652 | <p>I am working with <code>numpy</code>. I encountered this line of code. </p>
<pre><code>a = (1.,80.,5.)
</code></pre>
<p>What does this mean? At some other line, I found</p>
<pre><code>aList = np.arange(a[0], a[1]+a[2], a[2])
</code></pre>
<p><strong>Note:</strong> <code>np</code> is namespace assigned from <code... | -2 | 2016-09-08T14:30:39Z | 39,393,979 | <p>For the first one, it is a tuple of 3 items:</p>
<pre><code>>>> a = (1.,80.,5.)
>>> a
(1.0, 80.0, 5.0)
</code></pre>
<p>For the second one, it generates a list (start: 1.0, end: 80.0 + 5.0, step: 5.0):</p>
<pre><code>>>> a_list = numpy.arange(a[0], a[1]+a[2], a[2])
>>> a_list
a... | 1 | 2016-09-08T14:46:25Z | [
"python",
"numpy"
] |
Django 1.10 - Use django.shortcuts.render to generate a webpage with variables which includes a javascript as parameter | 39,393,785 | <p>I'm new to Django, trying to migrate a website that I have built to a Django application.
I have generated an HTML template on which I want to present dynamic content based on the URL that was requested.
The HTML template looks like this:</p>
<pre><code>{% load staticfiles%}
<!DOCTYPE html>
<html lang="e... | 0 | 2016-09-08T14:36:26Z | 39,393,862 | <p>You should put that script in a separate file and then pass the file name to the template instead. </p>
<p>Put your script in a js file, say <code>my_script.js</code>:</p>
<pre><code>window.lpTag=window.lpTag||{};if(typeof window.lpTag._tagCount==='undefined') ...
</code></pre>
<p>Then in your view:</p>
<pre><co... | 1 | 2016-09-08T14:40:26Z | [
"javascript",
"python",
"html",
"django"
] |
My variable is defined but python is saying it isn't? | 39,393,789 | <p>I keep getting an error telling me that the name <code>hourly_pay</code> is not defined, but I have it defined inside the <code>main</code> function. </p>
<p>I'm a beginner as I've just started class but to me it looks like it should be working:</p>
<pre><code>commission_pay_amount = .05
income_taxes = .25
Pay_per... | -2 | 2016-09-08T14:36:41Z | 39,393,902 | <p><code>hourly_paying</code> is defined in <code>main()</code> and it stays in main's scope. You need to pass it to <code>display_results</code> and modify <code>display_results</code> to accept all the values that you need. For example:</p>
<pre><code>commission_pay_amount = .05
income_taxes = .25
Pay_per_hour = 7.5... | 0 | 2016-09-08T14:42:05Z | [
"python",
"variables",
"scope",
"nameerror"
] |
My variable is defined but python is saying it isn't? | 39,393,789 | <p>I keep getting an error telling me that the name <code>hourly_pay</code> is not defined, but I have it defined inside the <code>main</code> function. </p>
<p>I'm a beginner as I've just started class but to me it looks like it should be working:</p>
<pre><code>commission_pay_amount = .05
income_taxes = .25
Pay_per... | -2 | 2016-09-08T14:36:41Z | 39,393,919 | <p>In python (in contrast to JavaScript), variables are locally scoped by default. This means that the variables are only accessible inside the function they are defined in. This behaviour can be overridden, but usually <a href="https://stackoverflow.com/questions/19158339/why-are-global-variables-evil">you do not want... | 3 | 2016-09-08T14:42:54Z | [
"python",
"variables",
"scope",
"nameerror"
] |
Python pandas slice dataframe by multiple index ranges | 39,393,856 | <p>What is the pythonic way to slice a dataframe by more index ranges (eg. by <code>10:12</code> and <code>25:28</code>)?
I want this in a more elegant way:</p>
<pre><code>df = pd.DataFrame({'a':range(10,100)})
df.iloc[[i for i in range(10,12)] + [i for i in range(25,28)]]
</code></pre>
<p>Result:</p>
<pre><code> ... | 3 | 2016-09-08T14:40:05Z | 39,393,929 | <p>You can use numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow">r_</a> "slicing trick":</p>
<pre><code>df = pd.DataFrame({'a':range(10,100)})
df.iloc[pd.np.r_[10:12, 25:28]]
</code></pre>
<p>Gives:</p>
<pre><code> a
10 20
11 21
25 35
26 36
27 37
</code></pre... | 8 | 2016-09-08T14:43:19Z | [
"python",
"pandas",
"indexing",
"slice"
] |
Get a constrained list of unique elements from a list of lists | 39,393,882 | <p>I have to solve this optimization problem using Python. I have a list of lists, each one containing elements. For instance:</p>
<pre><code>l = [
['elem1'],
['elem2'],
['elem3','elem4'],
['elem4','elem5']
]
</code></pre>
<p>What I need to obtain is a list <code>r</code> such that: </... | 0 | 2016-09-08T14:41:05Z | 39,394,340 | <p>Here's an approach that uses recursive backtracking to make selections and backtracks if they don't work. The function returns a failure in the form of a string if no list can meet the constraints.</p>
<pre><code>l = [
['elem1', 'elem5'],
['elem2'],
['elem3','elem4'],
['elem1','elem2']
... | 0 | 2016-09-08T15:02:27Z | [
"python",
"list",
"data-structures"
] |
Python service - writing filename with timestamp | 39,393,899 | <p>I wrote a Python script that will run indefinitely. It monitors a directory using <code>PyInotify</code> and uses the <code>Multiprocessing</code> module to run any new files created in those directories through an external script. That all works great. </p>
<p>The problem I am having is writing the output to a fil... | 0 | 2016-09-08T14:41:50Z | 39,394,942 | <p>I adjusted your code to change the file name each minute, which speeds up debugging quite a bit and yet still tests the hypothesis.</p>
<pre><code>import datetime
import gzip, time
from os.path import expanduser
while True:
now = datetime.datetime.now()
filename = expanduser("~")+"/%s-%s-%s-%s-%s.gz" % (now... | 2 | 2016-09-08T15:29:03Z | [
"python",
"multiprocess",
"pyinotify"
] |
Flask('application') versus Flask(__name__) | 39,393,926 | <p>In the official <a href="http://flask.pocoo.org/docs/0.11/quickstart/#a-minimal-application" rel="nofollow">Quickstart</a>, it's recommended to use <code>__name__</code> when using a single <strong>module</strong>:</p>
<blockquote>
<ol start="2">
<li>... If you are using a single module (as in this example), yo... | 2 | 2016-09-08T14:43:11Z | 39,393,990 | <p><code>__name__</code> is just a convenient way to get the import name of the place the app is defined. Flask uses the import name to know where to look up resources, templates, static files, instance folder, etc. When using a package, if you define your app in <code>__init__.py</code> then the <code>__name__</code... | 2 | 2016-09-08T14:47:06Z | [
"python",
"flask",
"import",
"module",
"package"
] |
Using two different data frames to compute new variable | 39,393,986 | <p>I have two dataframes of the same dimensions that look like:</p>
<pre><code> df1
ID flag
0 1
1 0
2 1
df2
ID flag
0 0
1 1
2 0
</code></pre>
<p>In both dataframes I want to create a new variable that denotes an additive flag. So the new variable will look like this:</p>
<p... | 1 | 2016-09-08T14:46:49Z | 39,394,146 | <p>You can use <code>np.logical_or</code> to achieve this, if we set <code>df1</code> to be all 0's except for the last row so we don't just get a column of <code>1</code>'s, we can cast the result of <code>np.logical_or</code> using <code>astype(int)</code> to convert the boolean array to <code>1</code> and <code>0</c... | 2 | 2016-09-08T14:54:08Z | [
"python",
"pandas"
] |
Input data type for sklearn SVD fit_transform function | 39,393,994 | <p>I have already processed document data in CSV file, which I read in pandas DataFrame:</p>
<pre><code>+----------+------+------------+
| document | term | count |
+----------+------+------------+
| 1 | 126 | 1 |
| 1 | 80 | 1 |
| 1 | 1221 | 2 |
| 2 | 2332... | 0 | 2016-09-08T14:47:25Z | 39,394,239 | <p>You can convert this CSV to libsvm format:</p>
<pre><code><label> <index1>:<value1> <index2>:<value2> ...
.
.
.
</code></pre>
<p>So, your example data will look like:</p>
<pre><code>0 80:1 126:1 1221:2
0 2332:1
</code></pre>
<p>Then read this file using <code>sklearn.datasets.load_s... | 1 | 2016-09-08T14:57:59Z | [
"python",
"scikit-learn",
"nlp",
"svd",
"dimensionality-reduction"
] |
WSGI: Django App is not getting the required site-packages | 39,394,259 | <p>Unfortuanetely I am stuck with my Website returning a 500 error.</p>
<p>The apache log is not really specific, and so I do not really know what to do. Before some apt-get upgrades everything worked fine.</p>
<p>I do think this might be a permission error. How do I have to set the permissions working with WSGI?</p>... | 0 | 2016-09-08T14:59:04Z | 39,400,170 | <p>Use:</p>
<pre><code>WSGIDaemonProcess aegee-stuttgart.org python-home=/home/sysadmin/.virtualenvs/django python-path=/home/sysadmin/public_html/aegee-stuttgart.org
</code></pre>
<p>not what you had. It is possible to use <code>python-path</code> to refer to a virtual environment, but you were using the wrong direc... | 1 | 2016-09-08T21:03:41Z | [
"python",
"django",
"mod-wsgi"
] |
UnicodeDecodeError: 'ascii' codec can't decode byte with reading CSV | 39,394,263 | <p>Trying to read from a CSV file and write the data into an XML file. I am encountering:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0x8a in position 87: ordinal not in range(128)
</code></pre>
<p>My question is, what is the best way to ignore this kind of error and continue processing the dat... | 1 | 2016-09-08T14:59:06Z | 39,395,031 | <p>You can try opening csv with codecs:</p>
<pre><code>import codecs
codecs.open(file_name, 'r', 'utf8')
</code></pre>
<p>Given that each line will contain '\n' string you will need to apply <strong>line.rstrip()</strong> when looping trough lines.</p>
<p>Note: Please don't try to convert values to str as you will e... | 0 | 2016-09-08T15:33:36Z | [
"python",
"xml",
"python-2.7",
"csv",
"ascii"
] |
change opacity/alpha/transparency in png image | 39,394,317 | <p>I have a png image with transparency on it and I would like to change its opacity keeping the transparency of the pixel just add a percentage or something.
I tried using <code>putalpha</code> but it just destroys the transparency in the image.</p>
<p>What I want is something like the <code>opacity</code> property i... | 0 | 2016-09-08T15:01:29Z | 39,420,226 | <p>found a way to do it.</p>
<pre><code>image=Image.open("star_blue.png")
opacity=0.5
bands=list(self.image.split())
if len(bands)==4:
bands[3]=bands[3].point(lambda x:x*opacity)
new_image=Image.merge(image.mode,bands)
</code></pre>
<p>found the code <a href="http://stackoverflow.com/questions/13662184/python... | 0 | 2016-09-09T21:53:56Z | [
"python",
"pillow"
] |
Comparing the contents of very large files efficiently | 39,394,328 | <p>I need to compare two files of differing formats quickly and I'm not sure how to do it. I would very much appreciate it if someone could point me in the right direction.</p>
<p>I am working on CentOS 6 and I am most comfortable with Python (both Python 2 and Python 3 are available).</p>
<hr>
<h2>The problem</h2>
... | 0 | 2016-09-08T15:02:13Z | 39,395,013 | <p>If you can find a way to take advantage of hash tables your task will change from O(N^2) to O(N). The implementation will depend on exactly how large your files are and whether or not you have duplicate job IDs in file 2. I'll assume you don't have any duplicates. If you can fit file 2 in memory, just load the thing... | 1 | 2016-09-08T15:33:01Z | [
"python",
"performance",
"file",
"io"
] |
Comparing the contents of very large files efficiently | 39,394,328 | <p>I need to compare two files of differing formats quickly and I'm not sure how to do it. I would very much appreciate it if someone could point me in the right direction.</p>
<p>I am working on CentOS 6 and I am most comfortable with Python (both Python 2 and Python 3 are available).</p>
<hr>
<h2>The problem</h2>
... | 0 | 2016-09-08T15:02:13Z | 39,395,104 | <p>The most efficient way I can think of is to use some standard UNIX tools which every modern Linux system should have. I know that this is not a python solution, but you determination to use python seems to build mostly on what you already know about that language and not any external constraints. Given how simple th... | 1 | 2016-09-08T15:37:53Z | [
"python",
"performance",
"file",
"io"
] |
Comparing the contents of very large files efficiently | 39,394,328 | <p>I need to compare two files of differing formats quickly and I'm not sure how to do it. I would very much appreciate it if someone could point me in the right direction.</p>
<p>I am working on CentOS 6 and I am most comfortable with Python (both Python 2 and Python 3 are available).</p>
<hr>
<h2>The problem</h2>
... | 0 | 2016-09-08T15:02:13Z | 39,395,819 | <p>This is simple utility to convert File 2 format to File 1 like format (i hope i understand question right, python 2 used)
save code to file <code>util1.py</code> for example </p>
<pre><code>import time
import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
print 'Err need filename'
sy... | 1 | 2016-09-08T16:14:31Z | [
"python",
"performance",
"file",
"io"
] |
Comparing the contents of very large files efficiently | 39,394,328 | <p>I need to compare two files of differing formats quickly and I'm not sure how to do it. I would very much appreciate it if someone could point me in the right direction.</p>
<p>I am working on CentOS 6 and I am most comfortable with Python (both Python 2 and Python 3 are available).</p>
<hr>
<h2>The problem</h2>
... | 0 | 2016-09-08T15:02:13Z | 39,396,201 | <p>I was trying to develop something where you'd split one of the files into smaller files (say 100,000 records each) and keep a pickled dictionary of each file that contains all <code>Job_id</code> as a key and its line as a value. In a sense, an index for each database and you could use a hash lookup on each subfile ... | 1 | 2016-09-08T16:37:29Z | [
"python",
"performance",
"file",
"io"
] |
Comparing the contents of very large files efficiently | 39,394,328 | <p>I need to compare two files of differing formats quickly and I'm not sure how to do it. I would very much appreciate it if someone could point me in the right direction.</p>
<p>I am working on CentOS 6 and I am most comfortable with Python (both Python 2 and Python 3 are available).</p>
<hr>
<h2>The problem</h2>
... | 0 | 2016-09-08T15:02:13Z | 39,397,188 | <p>Parse each file and convert the data to <code>datetime.timedelta</code> objects. Make a dictionary with the job number as the keys and timedelta object as the value(s):</p>
<pre><code>import operator, datetime, collections
def parse1(fp = 'job-file1.txt'):
with open(fp) as f:
next(f)
for line i... | 1 | 2016-09-08T17:43:51Z | [
"python",
"performance",
"file",
"io"
] |
Python regex replacing \u2022 | 39,394,437 | <p>This is my string:</p>
<pre><code>raw_list = u'Software Engineer with a huge passion for new and innovative products. Experienced gained from working in both big and fast-growing start-ups. Specialties \u2022 Languages and Frameworks: JavaScript (Nodejs, React), Android, Ruby on Rails 4, iOS (Swift) \u2022 Databas... | 0 | 2016-09-08T15:07:02Z | 39,394,518 | <p>Unless you use a <em>Unicode</em> string literal, the <code>\uhhhh</code> escape sequence has no meaning. Not to Python, and not to the <code>re</code> module. Add the <code>u</code> prefix:</p>
<pre><code>re.sub(ur'\u2022', ' ', raw_list)
</code></pre>
<p>Note the <code>ur</code> there; that's a raw unicode strin... | 1 | 2016-09-08T15:10:12Z | [
"python",
"regex"
] |
Python regex replacing \u2022 | 39,394,437 | <p>This is my string:</p>
<pre><code>raw_list = u'Software Engineer with a huge passion for new and innovative products. Experienced gained from working in both big and fast-growing start-ups. Specialties \u2022 Languages and Frameworks: JavaScript (Nodejs, React), Android, Ruby on Rails 4, iOS (Swift) \u2022 Databas... | 0 | 2016-09-08T15:07:02Z | 39,394,527 | <p>You're using a raw string, with the <code>r</code>. That tells Python to interpret the string literally, instead of actually taking escaped characters (such as \n).</p>
<pre><code>>>> r'\u2022'
'\\u2022'
</code></pre>
<p>You can see it's actually a double backslash. Instead you want to use >>> <code>u'\u2... | 4 | 2016-09-08T15:10:36Z | [
"python",
"regex"
] |
Python regex replacing \u2022 | 39,394,437 | <p>This is my string:</p>
<pre><code>raw_list = u'Software Engineer with a huge passion for new and innovative products. Experienced gained from working in both big and fast-growing start-ups. Specialties \u2022 Languages and Frameworks: JavaScript (Nodejs, React), Android, Ruby on Rails 4, iOS (Swift) \u2022 Databas... | 0 | 2016-09-08T15:07:02Z | 39,394,688 | <p>This is my approach, changing regex pattern, you might try</p>
<pre><code>re.sub(r'[^\x00-\x7F]+','',raw_list)
</code></pre>
<blockquote>
<p>Out[1]: u'Software Engineer with a huge passion for new and
innovative products. Experienced gained from working in both big and
fast-growing start-ups. Specialties L... | 1 | 2016-09-08T15:17:31Z | [
"python",
"regex"
] |
Output something other than '0 pruned nodes' | 39,394,632 | <p>Every time I've used <code>xgboost</code> (not only with python), the training messages always include "0 pruned nodes" on each line. For example:</p>
<pre><code>import pandas as pd
from sklearn import datasets
import xgboost as xgb
iris = datasets.load_iris()
dtrain = xgb.DMatrix(iris.data, label = iris.target)
p... | 1 | 2016-09-08T15:14:57Z | 39,396,350 | <p>You will have pruned nodes using <strong>regularization</strong>! Use the <code>gamma</code>parameter!</p>
<p>The objective functions contains two parts: training loss and regularization.
The regularisation in XGBoost is controlled by three parameters: <code>alpha</code>, <code>lambda</code> and <code>gamma</code> ... | 0 | 2016-09-08T16:46:21Z | [
"python",
"xgboost"
] |
Python Bokeh - blending | 39,394,634 | <p>I am trying to create a bar chart from a dataframe <code>df</code> in Python Bokeh library. The data I have simply looks like:</p>
<pre><code>value datetime
5 01-01-2015
7 02-01-2015
6 03-01-2015
... ... (for 3 years)
</code></pre>
<p>I would like to have a bar chart that shows 3 bars per month: </p>
<u... | 1 | 2016-09-08T15:15:01Z | 39,445,860 | <p>That blend example put me on the right track.</p>
<pre><code>import pandas as pd
from pandas import Series
from dateutil.parser import parse
from bokeh.plotting import figure
from bokeh.layouts import row
from bokeh.charts import Bar, output_file, show
from bokeh.charts.attributes import cat, color
from bokeh.chart... | 2 | 2016-09-12T08:06:44Z | [
"python",
"bar-chart",
"bokeh"
] |
Auto-perform actions when updating a mutable in Python | 39,394,724 | <p>I know how to use property setters to perform actions every time an attribute of a class is modified to avoid having to code in every action every time the variable is changed.</p>
<p>I wanted to know if it was possible to do the same for mutables, like lists and dictionaries ?</p>
<p>What I want to achieve is the... | 1 | 2016-09-08T15:18:55Z | 39,395,042 | <p>You'd have to use a custom class; you could subclass <code>dict</code> or <a href="https://docs.python.org/3/library/collections.html#userdict-objects" rel="nofollow"><code>collections.UserDict()</code></a>, and override the appropriate <a href="https://docs.python.org/3/reference/datamodel.html#emulating-container... | 1 | 2016-09-08T15:34:22Z | [
"python",
"list",
"dictionary",
"getter-setter"
] |
Django : How do i save foreign key object in django rest api class base view | 39,394,816 | <p>I 'm having Two models</p>
<p><strong>User & Location</strong></p>
<p>User having foreign key of Location. So at the time of <strong>Post</strong> request how do i save the location object in serializer. I'm using classbase view.</p>
<p>Following is my code</p>
<pre><code>class UserList(ListCreateAPIView):
... | 2 | 2016-09-08T15:23:25Z | 39,396,619 | <p>Use this code :</p>
<pre><code> def create(self, request, args, *kwargs):
location_id = self.request.data.get("user_location_id")
location = Location.objects.get(pk=location_id)
serializer = self.get_serializer(data=request.data, partial=True)
serializer.is_valid(r... | 2 | 2016-09-08T17:03:56Z | [
"python",
"django",
"django-rest-framework"
] |
How to get specific values from RDD in SPARK with PySpark | 39,394,826 | <p>The following is my RDD, there are 5 fields</p>
<pre><code>[('sachin', 200, 10,4,True), ('Raju', 400, 40,4,True), ('Mike', 100, 50,4,False) ]
</code></pre>
<p>Here I need to fetch 1st ,3rd and 5th Fields only , How to do in PySpark . Expected results as bellow . I tried reduceByKey in several ways, couldn't achiev... | -1 | 2016-09-08T15:24:02Z | 39,406,855 | <p>With a simple map?</p>
<pre><code>rdd.map(lambda x: (x[0], x[2], x[4]))
</code></pre>
| 0 | 2016-09-09T08:12:20Z | [
"python",
"apache-spark",
"pyspark"
] |
Python's self vs instance | 39,394,849 | <p>What is the difference between the self and instance keywords in Python 3?</p>
<p>I see code like,</p>
<pre><code>def update(self, instance, validated_data):
"""
Update and return an existing `Snippet` instance, given the validated data.
"""
instance.title = validated_data.get('title', instance.tit... | 0 | 2016-09-08T15:25:08Z | 39,394,944 | <p>The snippet is a bit short but <code>instance</code> is not a keyword (neither <code>self</code>, that is just convention).</p>
<p>It is an argument to another instance of another (maybe same) class.</p>
| 1 | 2016-09-08T15:29:11Z | [
"python",
"django"
] |
Python's self vs instance | 39,394,849 | <p>What is the difference between the self and instance keywords in Python 3?</p>
<p>I see code like,</p>
<pre><code>def update(self, instance, validated_data):
"""
Update and return an existing `Snippet` instance, given the validated data.
"""
instance.title = validated_data.get('title', instance.tit... | 0 | 2016-09-08T15:25:08Z | 39,394,992 | <p>The question is rather generic, but let me see if I can shed some light on it for you:</p>
<p><code>self</code> refers to the class(by convention, not a keyword) of which <code>update</code> is a part. The class has variables and methods and you can refer to these with the <code>self</code> keyword(not a reserved k... | 1 | 2016-09-08T15:31:40Z | [
"python",
"django"
] |
Python's self vs instance | 39,394,849 | <p>What is the difference between the self and instance keywords in Python 3?</p>
<p>I see code like,</p>
<pre><code>def update(self, instance, validated_data):
"""
Update and return an existing `Snippet` instance, given the validated data.
"""
instance.title = validated_data.get('title', instance.tit... | 0 | 2016-09-08T15:25:08Z | 39,395,179 | <p>Neither <code>self</code> nor <code>instance</code> are keywords in Python. The identifier <code>self</code> is used by convention as the first parameter of instance methods in a class. The object instance on which a method is called is automatically passed in as the first parameter.</p>
<p>In the above snippet, <c... | 1 | 2016-09-08T15:42:02Z | [
"python",
"django"
] |
selection rows with special conditions | 39,394,901 | <p>I have this dataframe : </p>
<pre><code>TIMESTAMP equipmeent1 equipement2 class_energy
2016-05-10 04:30:00 107 0 high
2016-05-10 04:40:00 100 90 medium
2016-05-10 04:50:00 106 0 low
2016-05-10 05:00:00 107 0 high
</code></pre>
<p>I try to select rows with special condition : </p>
<pre><code>x.loc... | 1 | 2016-09-08T15:27:14Z | 39,394,958 | <p>You need to and the conditions using <code>&</code> and use parentheses:</p>
<pre><code>x.loc[(x['class_energy'] == 'high') & (x['TIMESTAMP'] > '2016-05-10 04:30:00') & (x['TIMESTAMP'] < '2016-05-10 05:00:00') ]
</code></pre>
<p>It's unclear what you're intending by randomly including <code>04:10... | 2 | 2016-09-08T15:29:34Z | [
"python",
"pandas"
] |
Sqlalchemy mysql parameterized query | 39,394,936 | <p>I am trying to pass table name as variable into a sql query and execute it with a sqlalchemy cursor:</p>
<pre><code>from sqlalchemy.sql import text
cur = DB_ENGINE.connect()
p = cur.execute(text('select * from :table'), {'table':'person'}).fetchall()
print p
</code></pre>
<p>and I got this error message:</p>
<pr... | 0 | 2016-09-08T15:28:52Z | 39,394,980 | <p>Placeholders can only represent VALUES. You cannot use them for sql keywords/identifiers.</p>
<p>If you need to dynamically change an identifier, then you'll have to build the query string yourself, e.g.</p>
<pre><code>sql = "SELECT foo FROM " + var_with_table_name + "WHERE somefield = ?"
</code></pre>
<p>which t... | 0 | 2016-09-08T15:31:07Z | [
"python",
"mysql",
"sqlalchemy"
] |
Change value of all rows in a column of pandas data frame | 39,394,975 | <p>I have a data frame <code>df</code> like:</p>
<pre><code> measure model threshold
285 0.241715 a 0.0001
275 0.241480 a 0.0001
546 0.289773 b 0.0005
556 0.241715 b 0.0005
817 0.357532 a 0.001
827 0.269750 b 0.001
1088 0.489164 a 0.0025
</... | 1 | 2016-09-08T15:30:42Z | 39,395,122 | <p>You get the warning because you probably either made a reference to the original df:</p>
<p><code>df1 = df</code></p>
<p>and then tried your code but your intention was to take a copy so you should use <code>copy()</code> to explicitly take a copy:</p>
<p><code>df_copy = df.copy()</code></p>
<p>this will get rid... | 1 | 2016-09-08T15:38:52Z | [
"python",
"pandas",
"dataframe",
"slice"
] |
Hyphen at beginning of regex causes it to stop matching (python 2.7) - but at the end it's fine? | 39,395,217 | <p>I'm writing a simple script to dump the tracks, artists, and times of a bandcamp album (<a href="https://nihonkizuna.bandcamp.com/album/nihon-kizuna" rel="nofollow">https://nihonkizuna.bandcamp.com/album/nihon-kizuna</a>), but I'm having trouble with the regex. For context, the track titles are in the format "Artist... | 0 | 2016-09-08T15:43:35Z | 39,395,292 | <p>Why don't use a regular <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a>:</p>
<pre><code>artists, newtracks = zip(*[item.split(" - ") for item in tracks])
</code></pre>
<p>The <code>zip(*[...])</code> here would <em>unzip</em> the list of 2-item tuples... | 1 | 2016-09-08T15:47:23Z | [
"python",
"regex",
"python-2.7"
] |
Hyphen at beginning of regex causes it to stop matching (python 2.7) - but at the end it's fine? | 39,395,217 | <p>I'm writing a simple script to dump the tracks, artists, and times of a bandcamp album (<a href="https://nihonkizuna.bandcamp.com/album/nihon-kizuna" rel="nofollow">https://nihonkizuna.bandcamp.com/album/nihon-kizuna</a>), but I'm having trouble with the regex. For context, the track titles are in the format "Artist... | 0 | 2016-09-08T15:43:35Z | 39,395,347 | <p>As the documentation to <a href="https://docs.python.org/2/library/re.html#re.match" rel="nofollow"><code>re.match</code></a> states:</p>
<blockquote>
<p>If zero or more characters <strong>at the beginning</strong> of string match the regular expression pattern, (...).</p>
</blockquote>
<p>Use <a href="https://d... | 2 | 2016-09-08T15:49:35Z | [
"python",
"regex",
"python-2.7"
] |
Indent Expected? | 39,395,226 | <p>I'm sort of new to python and working on a small text adventure it's been going well until now I'm currently implementing a sword system where if you have a certain size sword you can slay certain size monsters. I'm trying to code another monster encounter and I have coded the sword stuff but I'm trying to finish i... | -4 | 2016-09-08T15:43:57Z | 39,395,307 | <p>There is in fact multiples things you need to know about indentation in Python:</p>
<h2><strong>Python really care about indention.</strong></h2>
<p>In a lot of other language the indention is not necessary but improve the readability. In Python indentation replaces the keyword <code>begin / end</code> or <code>{ ... | 3 | 2016-09-08T15:47:53Z | [
"python",
"indentation"
] |
Using mplot3D to plot DataFrame | 39,395,252 | <p>I have a dataframe like this:</p>
<pre><code> f1 model cost_threshold sigmoid_slope
366 0.140625 open 0.0001 0.0001
445 0.356055 open 0.0001 0.0010
265 0.204674 open 0.0001 0.0100
562 0.230088 open 0.0001 0.0500
737 0.210923 ... | 0 | 2016-09-08T15:45:20Z | 39,396,298 | <p>This is how to get X, Y and Z respectively:</p>
<pre><code>Z = df.pivot_table('f1', 'cost_threshold', 'sigmoid_slope', fill_value=0).as_matrix()
Y = df.groupby("cost_threshold").sigmoid_slope.apply(pd.Series.reset_index, drop=True).unstack().values
Z = df.groupby("sigmoid_slope").cost_threshold.apply(pd.Series.re... | 0 | 2016-09-08T16:42:53Z | [
"python",
"pandas",
"matplotlib",
"dataframe",
"mplot3d"
] |
Create a Django Database | 39,395,253 | <p>This code works on other people's local computer - we aren't running it in production yet. But mine isn't working. A coworker indicated that I need to create a database. Prior to using mysql, I was using sqlite, which didn't require this. </p>
<p>When I run python manage.py runserver this is what I get:</p>
<pre><... | 0 | 2016-09-08T15:45:21Z | 39,395,446 | <p>Presumably you have tested the username and password by going into the mysql shell. So you can just do the same thing again, and from there do <code>CREATE DATABASE testdb</code>.</p>
| 0 | 2016-09-08T15:54:40Z | [
"python",
"mysql",
"django",
"django-settings"
] |
Python Client for Google Maps Services's Places couldn't pass Page_Token | 39,395,524 | <p>I'm trying out Python Client for Google Maps Services to pull a list of places using Places API.</p>
<p>Here is the GitHub page: <a href="https://github.com/googlemaps/google-maps-services-python" rel="nofollow">https://github.com/googlemaps/google-maps-services-python</a>
Here is the documentation page: <a href="h... | -1 | 2016-09-08T15:59:09Z | 39,402,865 | <p>Alright, after hours of trial and error. I noticed I need to add a time.sleep(2) to make it work. I'm not sure why but it works. </p>
<p>It failed with time.sleep(1), time.sleep(2) and above will solve the problem.</p>
<p>Hopefully someone can shed some light to the reason behind.</p>
<p>Here is my code that work... | 0 | 2016-09-09T02:21:32Z | [
"python",
"google-maps"
] |
peewee - Define models seprately from Database() initialization | 39,395,528 | <p>I need to use some ORM engine, like <strong>peewee</strong>, for handling SQLite database within my python application. However, most of such libraries offer syntax like this to define <code>models.py</code>:</p>
<pre><code>import peewee
db = peewee.Database('hello.sqlite')
class Person(peewee.Model):
name = ... | 0 | 2016-09-08T15:59:32Z | 39,463,851 | <p>may be youa re lookin at proxy feature :
<a href="http://peewee.readthedocs.io/en/latest/peewee/api.html?highlight=proxy#Proxy" rel="nofollow">proxy - peewee</a></p>
<pre><code>database_proxy = Proxy() # Create a proxy for our db.
class BaseModel(Model):
class Meta:
database = database_proxy # Use pr... | 0 | 2016-09-13T06:52:09Z | [
"python",
"sqlite",
"python-3.x",
"orm",
"peewee"
] |
Post to nested fields with Django Rest Framework serializers | 39,395,529 | <p>I have setup my serializer to return nested content successfully.</p>
<p>However, I have not been able to post data within the nested fields.</p>
<p>I don't get an error when posting the data- but it only posts to the non-nested fields.</p>
<p>I would like for it to take the "name" field OR primary key (of model ... | 1 | 2016-09-08T15:59:38Z | 39,396,777 | <p>Your json should be.</p>
<pre><code>{
"title": "TEST_title",
"tag": [ {"name": "test1" },
{"name": "test2"}
],
"info": []
}
</code></pre>
<hr>
<pre><code>class TagSerializer(serializers.ModelSerializer):
taglevel = filters.CharFilter(taglevel="taglevel")
class Meta:
model = Tag
... | 1 | 2016-09-08T17:15:11Z | [
"python",
"django",
"django-rest-framework"
] |
Python won't print expression | 39,395,530 | <p>So, I'm kind of new to programming and have been trying Python. I'm doing a really simple program that converts usd to euroes. </p>
<p>This is the text of the problem that I'm trying to solve</p>
<blockquote>
<p>You are going to travel to France. You will need to convert dollars to euros (the
currency of the E... | 0 | 2016-09-08T15:59:42Z | 39,395,785 | <p>Check your logic more.</p>
<p><code>cr1 = int(input("What is the convertion rate of the first one? "))</code></p>
<p>Your conversion rate is in int. As in Integer which means it can't have a floating point (a decimal "CR1: 0.78" from your example). Your cr1 will become 0 if you cast it into an int. Also change you... | 1 | 2016-09-08T16:12:42Z | [
"python",
"printing"
] |
How to configure pymssql with SSL support on Ubuntu 16.04 LTS? | 39,395,548 | <p>What are the steps required to configure pymssql with SSL support on Ubuntu 16.04 LTS so I can connect to a SQL Server instance that requires an encrypted connection (e.g., Azure)?</p>
| 1 | 2016-09-08T16:01:03Z | 39,395,549 | <p>The following worked for me on a clean install of Xubuntu 16.04 LTS x64:</p>
<p>The first challenge is that the FreeTDS we get from the Ubuntu repositories does not support SSL "out of the box", so we need to build our own. Start by installing python-pip (which also installs build-essentials, g++, and a bunch of ot... | 0 | 2016-09-08T16:01:03Z | [
"python",
"ubuntu-16.04",
"pymssql"
] |
Can't login to a specific ASP.NET website using python requests | 39,395,550 | <p>So I've been trying for the last 6 hours to make this work, but I couldn't and endless searches didn't help, So I guess I'm either doing something very fundamental wrong, or it's just a trivial bug which happens to match my logic so I need extra eyes to help me fix it.<br>
The website url is <a href="https://www.wes... | 1 | 2016-09-08T16:01:04Z | 39,398,599 | <p>You are doing way too much work and in doing so not passing valid data,you extract value attribute directly i.e <code>.select_one('#__VIEWSTATEGENERATOR')["value"]</code> and the same for all the rest, the cookies will be set in the Session object after your initial get so the logic boils down to:</p>
<pre><code>wi... | 0 | 2016-09-08T19:15:25Z | [
"python",
"asp.net",
"python-requests",
"login-script"
] |
NameError in Python | 39,395,567 | <p>I am getting a <code>NameError: name 'eyes' not found</code> while trying to run an OpenCV project in Python on <code>cmd</code>. I am using Python 2.7 and OpenCV 2.4.13, which I think is not a problem.</p>
<pre><code>import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_defa... | 1 | 2016-09-08T16:02:03Z | 39,395,666 | <p>Problem of indentation, just like <a href="http://stackoverflow.com/a/39368777/4228275">this one</a>:</p>
<p><code>eyes</code> is out of scope when you go out of the <code>faces</code> loop.</p>
<pre><code>while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_casca... | 0 | 2016-09-08T16:06:41Z | [
"python",
"opencv"
] |
Python, interpolation, | 39,395,576 | <p>This issue realy drives me crazy.
I have got ascii file with ~1 000 000 rows in it.
There are 3 columns
X - coordinate, Z- depths- V -speed. For instance:</p>
<pre><code> X Z V
45000 -11657.8 5985.61
45000 -11578.22 5974.688
45000 -11... | 0 | 2016-09-08T16:02:31Z | 39,396,629 | <p>In order to interpolate, you need some example of inputs and outputs that will be the base of the interpolation. In your case, <code>Z_list</code> is the input and <code>V_list</code>, the output.</p>
<p>Next, you can use the <code>interp</code> function from <a href="http://www.numpy.org/" rel="nofollow">numpy</a>... | 1 | 2016-09-08T17:04:55Z | [
"python",
"numpy",
"interpolation"
] |
matplotlib - change figsize but keep fontsize constant | 39,395,616 | <p>I want to display several figures with different sizes, making sure that the text has always the same size when the figures are printed. How can I achieve that?</p>
<p>As an example. Let's say I have two figures:</p>
<pre><code>import matplotlib.pylab as plt
import matplotlib as mpl
mpl.rc('font', size=10)
fig1 ... | 0 | 2016-09-08T16:04:31Z | 39,395,976 | <p>In this case, the font size would be the same (i.e. also 10 points). </p>
<p>However, in Jupyter Notebook the figures may be displayed at a different size if they are too wide, see below: </p>
<p><a href="http://i.stack.imgur.com/zBGLp.png" rel="nofollow"><img src="http://i.stack.imgur.com/zBGLp.png" alt="Jupyter ... | 1 | 2016-09-08T16:22:50Z | [
"python",
"matplotlib",
"figure"
] |
How to call super of enclosing class in a mixin in Python? | 39,395,618 | <p>I have the following code, in Django:</p>
<pre><code>class Parent(models.Model):
def save(self):
# Do Stuff A
class Mixin(object):
def save(self):
# Do Stuff B
class A(Parent, Mixin):
def save(self):
super(A, self).save()
# Do stuff C
</code></pre>
<p>Now, I want to us... | 1 | 2016-09-08T16:04:41Z | 39,395,973 | <p>The bast practice for calling the implementation from the superclass is to use <code>super</code>:</p>
<pre><code>class Mixin(object):
def save(self):
super(Mixin, self).save()
# Do Stuff B here or before super call, as you wish
</code></pre>
<p>What is important is that you call <code>super</c... | 2 | 2016-09-08T16:22:29Z | [
"python"
] |
How to call super of enclosing class in a mixin in Python? | 39,395,618 | <p>I have the following code, in Django:</p>
<pre><code>class Parent(models.Model):
def save(self):
# Do Stuff A
class Mixin(object):
def save(self):
# Do Stuff B
class A(Parent, Mixin):
def save(self):
super(A, self).save()
# Do stuff C
</code></pre>
<p>Now, I want to us... | 1 | 2016-09-08T16:04:41Z | 39,396,086 | <p>How about calling super in your mixin class?</p>
<pre><code>class Parent(object):
def test(self):
print("parent")
class MyMixin(object):
def test(self):
super(MyMixin, self).test()
print("mixin")
class MyClass(MyMixin, Parent):
def test(self):
super(MyClass, self).tes... | 1 | 2016-09-08T16:29:22Z | [
"python"
] |
Testing class methods with pytest | 39,395,731 | <p>In the documentation of pytest various examples for test cases are listed. Most of them show the test of functions. But Iâm missing an example of how to test classes and class methods. Letâs say we have the following class in the module <code>cool.py</code> we like to test:</p>
<pre><code>class SuperCool(object... | 3 | 2016-09-08T16:10:10Z | 39,395,874 | <p>All you need to do to test a class method is instantiate that class, and call the method on that instance:</p>
<pre><code>def test_action(self):
sc = SuperCool()
assert sc.action(1) == 1
</code></pre>
| 2 | 2016-09-08T16:17:39Z | [
"python",
"py.test"
] |
Testing class methods with pytest | 39,395,731 | <p>In the documentation of pytest various examples for test cases are listed. Most of them show the test of functions. But Iâm missing an example of how to test classes and class methods. Letâs say we have the following class in the module <code>cool.py</code> we like to test:</p>
<pre><code>class SuperCool(object... | 3 | 2016-09-08T16:10:10Z | 39,395,889 | <p>Well, one way is to just create your object within the test method and interact with it from there: </p>
<pre><code>def test_action(self, x):
o = SuperCool()
assert o.action(2) == 4
</code></pre>
<p>You can apparently use something like the classic <code>setup</code> and <code>teardown</code> style unittes... | 1 | 2016-09-08T16:18:26Z | [
"python",
"py.test"
] |
How to generalize a function call which may be async, tornado coroutine, or normal? | 39,395,732 | <p>I have an application which has a library in multiple configurations:</p>
<ul>
<li>Python2.7 native</li>
<li>Python2.7 tornado</li>
<li>Python3.5 asyncio</li>
</ul>
<p>Currently, I have code that is nearly identical against all three, but there are minor differences in how each function call are invoked. This mean... | 0 | 2016-09-08T16:10:16Z | 39,396,509 | <p>Use <code>@gen.coroutine</code> and <code>yield</code>: This will work in all Python versions. A function decorated with <code>gen.coroutine</code> is a little slower than a native coroutine, but can be used in all the same scenarios.</p>
<p>For the synchronous case, use <code>run_sync</code>:</p>
<pre><code>resul... | -1 | 2016-09-08T16:56:30Z | [
"python",
"python-2.7",
"tornado",
"python-3.5",
"python-asyncio"
] |
How to generalize a function call which may be async, tornado coroutine, or normal? | 39,395,732 | <p>I have an application which has a library in multiple configurations:</p>
<ul>
<li>Python2.7 native</li>
<li>Python2.7 tornado</li>
<li>Python3.5 asyncio</li>
</ul>
<p>Currently, I have code that is nearly identical against all three, but there are minor differences in how each function call are invoked. This mean... | 0 | 2016-09-08T16:10:16Z | 39,410,323 | <p>You can't do all of this in one function - how is <code>client.foo()</code> supposed to know whether it's being called from a "normal" synchronous application, or whether its caller is going to use <code>yield</code> or <code>await</code>. However, as long as you're willing to have Tornado as a dependency, you can a... | 1 | 2016-09-09T11:15:31Z | [
"python",
"python-2.7",
"tornado",
"python-3.5",
"python-asyncio"
] |
404 HEAD issue when creating AWS Elasticsearch index | 39,395,745 | <p>I am trying to create my first index using python and I keep getting a 404 index not found exception. Here is the current code:</p>
<pre><code>es = Elasticsearch([{'host': 'host_url', 'port': 443, 'use_ssl': True, 'timeout': 300}])
if es.indices.exists('test_logs'):
es.indices.delete(index = 'test_logs')
req... | 0 | 2016-09-08T16:10:53Z | 39,492,905 | <p>Changed my connection to: </p>
<pre><code>es = Elasticsearch(
hosts = host,
connection_class = RequestsHttpConnection,
port = 443,
use_ssl = True,
verify_certs = False)
</code></pre>
<p>Works fine now. Do not know why the previous one failed.</p>
| 0 | 2016-09-14T14:24:07Z | [
"python",
"amazon-web-services",
"elasticsearch",
"aws-elasticsearchservice"
] |
Flask doesn't see JSON data sent by Node | 39,395,798 | <p>I am trying to send JSON data to Flask using Node, but I can't read the data in Flask. I tried printing <code>request.data</code> in Flask but it didn't output anything. I also tried printing <code>request.json</code>, but it returned a 400 response. Why doesn't Flask see the JSON data sent by Node?</p>
<pre><co... | 3 | 2016-09-08T16:13:33Z | 39,412,159 | <p>The Python Server is fine, and run correctly, the problem lies in the handcrafted http request, which for some reason is malformed.</p>
<p>Using the <a href="https://github.com/request/request" rel="nofollow"><code>request</code></a> module works:</p>
<pre><code>var request = require('request');
request({
met... | 0 | 2016-09-09T12:57:22Z | [
"javascript",
"python",
"json",
"node.js",
"flask"
] |
Python: how to check a variable is a meaningful numerical type | 39,395,921 | <p>In python, how can I check a variable is a numerical type and has a meaningful value? </p>
<p>Here I mean by 'numerical type' those like <code>int</code>, <code>float</code>, and <code>complex</code> with all different bit length, and by 'meaningful value' that it is not <code>nan</code> or any other special values... | 0 | 2016-09-08T16:20:03Z | 39,396,031 | <pre><code>>>> from math import isnan
>>> isnan(float('nan'))
True
>>> isnan(1j.real)
False
>>> isnan(1j.imag)
False
</code></pre>
<p>Integers can never be NaNs.</p>
| 1 | 2016-09-08T16:25:32Z | [
"python",
"numpy",
"math"
] |
Python: how to check a variable is a meaningful numerical type | 39,395,921 | <p>In python, how can I check a variable is a numerical type and has a meaningful value? </p>
<p>Here I mean by 'numerical type' those like <code>int</code>, <code>float</code>, and <code>complex</code> with all different bit length, and by 'meaningful value' that it is not <code>nan</code> or any other special values... | 0 | 2016-09-08T16:20:03Z | 39,396,169 | <p>Python 2.x and 3.x</p>
<pre><code>import math
import numbers
def is_numerical(x):
return isinstance(x, numbers.Number) and not isinstance(x, bool) and not math.isnan(abs(n)) and math.isfinite(abs(n))
</code></pre>
<p>Reason for the distinction is because Python 3 merged the <code>long</code> and <code>int</co... | 1 | 2016-09-08T16:35:00Z | [
"python",
"numpy",
"math"
] |
Python: how to check a variable is a meaningful numerical type | 39,395,921 | <p>In python, how can I check a variable is a numerical type and has a meaningful value? </p>
<p>Here I mean by 'numerical type' those like <code>int</code>, <code>float</code>, and <code>complex</code> with all different bit length, and by 'meaningful value' that it is not <code>nan</code> or any other special values... | 0 | 2016-09-08T16:20:03Z | 39,397,026 | <p>I am answering to my own question. This is based on <a href="http://stackoverflow.com/a/39396169/883431">Seth Michael Larson's answer</a>
and <a href="http://stackoverflow.com/a/12588878/883431">DaveTheScientist's answer for another question</a>. Considering that I need to be careful for <code>float('inf')</code> an... | -1 | 2016-09-08T17:32:28Z | [
"python",
"numpy",
"math"
] |
Python: how to check a variable is a meaningful numerical type | 39,395,921 | <p>In python, how can I check a variable is a numerical type and has a meaningful value? </p>
<p>Here I mean by 'numerical type' those like <code>int</code>, <code>float</code>, and <code>complex</code> with all different bit length, and by 'meaningful value' that it is not <code>nan</code> or any other special values... | 0 | 2016-09-08T16:20:03Z | 39,397,415 | <p>It depends how thorough you want to be. Besides the builtin types (<code>complex</code>, <code>float</code>, and <code>int</code>) there are also other types that are considered numbers in python. For instance: <a href="https://docs.python.org/3/library/fractions.html" rel="nofollow"><code>fractions.Fraction</code><... | 1 | 2016-09-08T17:59:42Z | [
"python",
"numpy",
"math"
] |
Django-tables2: ValueError at /interactive_table/ Expected table or queryset, not str | 39,396,222 | <p>I was following along with the tutorial for Django-tables2 tutorial (which can be found here: <a href="https://django-tables2.readthedocs.io/en/latest/pages/tutorial.html" rel="nofollow">https://django-tables2.readthedocs.io/en/latest/pages/tutorial.html</a>). I've fixed all the errors up until now, but I've hit one... | 0 | 2016-09-08T16:38:43Z | 39,396,275 | <p>change <code>obj</code> to <code>people</code> in render function.</p>
<p>Try to understand how templates and template variables work with django. </p>
<p>Documentations might be a good place to <a href="https://docs.djangoproject.com/en/1.10/topics/templates/" rel="nofollow">look</a></p>
| 2 | 2016-09-08T16:41:58Z | [
"python",
"django",
"django-tables2"
] |
Django-tables2: ValueError at /interactive_table/ Expected table or queryset, not str | 39,396,222 | <p>I was following along with the tutorial for Django-tables2 tutorial (which can be found here: <a href="https://django-tables2.readthedocs.io/en/latest/pages/tutorial.html" rel="nofollow">https://django-tables2.readthedocs.io/en/latest/pages/tutorial.html</a>). I've fixed all the errors up until now, but I've hit one... | 0 | 2016-09-08T16:38:43Z | 39,396,286 | <p>Change your template response to return <code>people</code> instead of <code>obj</code></p>
<pre><code>return render(request, 'template.html', {'people': models.people.objects.all()})
</code></pre>
| 1 | 2016-09-08T16:42:16Z | [
"python",
"django",
"django-tables2"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.