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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Connecting to Cloud SQL through deployed App Engine app (Different regions) | 38,369,925 | <p>I currently have a deployed App Engine application (authorized through Cloud SQL) and in the same project as my Cloud SQL instance. I am using Python & Flask and follow the original Google code to connect to Cloud SQL.</p>
<pre><code>if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
try:... | 2 | 2016-07-14T09:03:42Z | 38,381,429 | <p>Per <a href="https://cloud.google.com/sql/docs/app-engine-connect" rel="nofollow">https://cloud.google.com/sql/docs/app-engine-connect</a>, the GAE app needs to be in the same region as the Cloud SQL instance.</p>
| 1 | 2016-07-14T18:18:10Z | [
"python",
"google-app-engine",
"flask",
"google-cloud-sql"
] |
Python class decorator, cannot use constructor | 38,370,105 | <p>So I have the following decorator code
</p>
<pre><code>class Factory:
def __init__(self, cls):
self.cls = cls
def __instancecheck__(self, inst):
return isinstance(inst, self.cls)
def Produce(self):
return self.cls()
</code></pre>
<p>
And the following class code
</p>
<pre><... | -1 | 2016-07-14T09:11:46Z | 38,370,192 | <p>The exception is telling you all you need to know, just add a <code>__call__</code> method:</p>
<pre><code>class Factory:
# ...
def __call__(self, *args, **kwargs):
return self.cls(*args, **kwargs)
</code></pre>
| 2 | 2016-07-14T09:15:08Z | [
"python",
"abstraction"
] |
Python class decorator, cannot use constructor | 38,370,105 | <p>So I have the following decorator code
</p>
<pre><code>class Factory:
def __init__(self, cls):
self.cls = cls
def __instancecheck__(self, inst):
return isinstance(inst, self.cls)
def Produce(self):
return self.cls()
</code></pre>
<p>
And the following class code
</p>
<pre><... | -1 | 2016-07-14T09:11:46Z | 38,370,220 | <p>If all you want to do is to add a <code>Produce</code> function to the class, you can rewrite your decorator like this:</p>
<pre><code>def Factory(cls):
def Produce():
return cls()
cls.Produce= Produce # add the function to the class
return cls
</code></pre>
| -1 | 2016-07-14T09:16:21Z | [
"python",
"abstraction"
] |
Manipulate configuration files with ConfigParser lib on python | 38,370,323 | <p>I have a conf file with several configurations, i need to parse the information automatically in order to create a interface for easy use.</p>
<p>i give an example of one of my sections in configuration:</p>
<pre><code>[OutOfHoursAlert]
comment_max_hour = Max Hour
max_hour = 20
comment_min_hour = Min Hour
min_hour... | 0 | 2016-07-14T09:21:09Z | 38,371,712 | <p>You can use <code>new_value = input(comment+": ")</code> to get a new value from the user.</p>
<p>If you want to build an advanced console program that allows to actually edit variables, move the cursor etc., you might want to take a look at the <code>curses</code> module of the python standard library.</p>
| 0 | 2016-07-14T10:24:57Z | [
"python",
"python-2.7",
"configparser"
] |
How do we set the success category for logistic regression in python? | 38,370,402 | <p>I was learning logistic regression in python by comparing it with SAS.</p>
<p><strong>Dataset:</strong> <a href="http://www.ats.ucla.edu/stat/data/binary.csv" rel="nofollow">http://www.ats.ucla.edu/stat/data/binary.csv</a></p>
<p>here admit is the response variable and has categories 0 and 1.</p>
<p>SAS by defaul... | 0 | 2016-07-14T09:24:14Z | 38,372,799 | <p>The only robust way is to create a new 0-1 dummy variable with 1 representing the desired level.</p>
<p>for example:</p>
<pre><code>not_admit = (ADMIT == 0).astype(int)
</code></pre>
<p>"robust" here refers to current ambiguities in the interaction between pandas, patsy and statsmodels which might change a catego... | 1 | 2016-07-14T11:18:57Z | [
"python",
"sas",
"logistic-regression",
"statsmodels"
] |
I don't show the image in Tkinter | 38,370,560 | <p>The image doesn't show in Tkinter. The same code work in a new window, but in my class it does not. What could be the problem ?</p>
<pre><code>import Tkinter
root = Tkinter.Tk
class InterfaceApp(root):
def __init__(self,parent):
root.__init__(self,parent)
self.parent = parent
self.ini... | 0 | 2016-07-14T09:30:50Z | 38,370,985 | <p>You must keep a reference to <code>tr.gif</code> . This means you need to add this line:</p>
<pre><code>imLabel.image = im
</code></pre>
<p>After these 2 lines:</p>
<pre><code>im = Tkinter.PhotoImage(file="tr.gif")
imLabel = Tkinter.Label(frPic, image=im)
</code></pre>
<p>Other notes:</p>
<ul>
<li>Run import Tk... | 1 | 2016-07-14T09:51:20Z | [
"python",
"image",
"python-2.7",
"tkinter"
] |
Multiprocessing a list of RDDs | 38,370,684 | <p>I am trying to <strong>multiprocess</strong> a <em>list</em> of RDDs as follows </p>
<pre><code>from pyspark.context import SparkContext
from multiprocessing import Pool
def square(rdd_list):
def _square(i):
return i*i
return rdd_list.map(_square)
sc = SparkContext('local', 'Data_Split')
data = ... | 3 | 2016-07-14T09:36:24Z | 38,371,333 | <p>It's because when you use multi-process, the RDD has to be serialized/pickled before sending to the other processes. Spark performs a check whenever an attempt to serialized an RDD is made, and throw that error.</p>
| 2 | 2016-07-14T10:08:22Z | [
"python",
"apache-spark",
"pyspark",
"list-comprehension"
] |
Installing Tensorflow from source when it is already installed using pip | 38,370,763 | <p>My machine already have Tensorflow 8.0 installed using pip.
I installed Tensorflow 9.0 from source to support cudnn 5. The thing is when I "import tensorflow" in python it still uses the pip installation.</p>
<p>Can I tell python to import my new installation and ignore the pip installation?</p>
<p>I want to keep ... | 0 | 2016-07-14T09:41:01Z | 38,382,220 | <p>You can try one of these (solution 2 is the one I prefer)</p>
<p>1) Install only for your user:</p>
<pre><code>sudo pip install --user /tmp/tensorflow_pkg/tensorflow-0.9.0-py2-none-any.whl
</code></pre>
<p>2) Create a virtual environment to isolate it from your system install:</p>
<p><a href="https://www.tensorf... | 1 | 2016-07-14T18:59:56Z | [
"python",
"installation",
"tensorflow"
] |
Parsing config.ini in python | 38,370,771 | <p>File</p>
<blockquote>
<p>config.ini</p>
</blockquote>
<p>file
;SQL Server 2012 Configuration File
[OPTIONS]</p>
<pre><code>; Specifies a Setup work flow, like INSTALL, UNINSTALL, or UPGRADE. This is a required parameter.
ACTION="Install"
; Detailed help for command line argument ENU has not been defi... | 0 | 2016-07-14T09:41:29Z | 38,370,957 | <p>If it is a real INI file then you can use Python's standard library module called <a href="https://docs.python.org/3/library/configparser.html" rel="nofollow" title="configparser">configparser</a>.</p>
<p>Otherwise, read the file into memory and split it into a dictionary or a list.</p>
<p>And then you can add wha... | 2 | 2016-07-14T09:50:10Z | [
"python",
"parsing",
"config"
] |
Naming Convention for Overloaded Parameters in Python | 38,370,925 | <p>I was recently coding up a method in Python (numpy) that can perform its operation on either on a single element, or element-wise on an array.</p>
<p>For example:</p>
<pre><code>def addOne(self, i):
bigArray[i] += 1
</code></pre>
<p>Here <code>i</code> can either be a single index, or an array of them, which ... | 0 | 2016-07-14T09:48:44Z | 38,371,056 | <p>There are several things you could do. The first thing is naming your variable accordingly:</p>
<pre><code>def addOne(self, i_or_is):
if not isinstance(i_or_is, list):
i_or_is = [i_or_is]
...
</code></pre>
<p>But in this case, the better solution would probably be to take <code>*args</code>:</p>
<... | 1 | 2016-07-14T09:54:22Z | [
"python",
"parameters",
"method-overloading"
] |
Django translation without request object | 38,370,949 | <p>I'm translating my Django app, in which I have a push notification module. From that module, I send a text field to user's mobile devices. Since the trigger of those notifications is not a proper HTTP request (with its "request" object), the default Django way of translating strings doesn't work. </p>
<p>I have a f... | 0 | 2016-07-14T09:49:49Z | 38,371,172 | <p>You are looking for <a href="https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.translation.override" rel="nofollow"><code>translation.override</code></a> context manager:</p>
<pre><code>language = user.get_language()
with translation.override(language):
# Translate your message here.
</code></pre>
| 2 | 2016-07-14T09:59:33Z | [
"python",
"django",
"notifications",
"internationalization",
"translation"
] |
Everytime Celery is restarted all the scheduled tasks are acknowledged | 38,371,006 | <p>Everytime Celery is restarted all the scheduled tasks are acknowledged again.</p>
<p>And this is leading to a huge time lag to start processing new tasks.</p>
<p>How can we solve this?</p>
| -1 | 2016-07-14T09:52:22Z | 38,414,032 | <p>You can simply purge all the tasks before starting Celery again:</p>
<pre><code>$ celery purge
WARNING: This will remove all tasks from queue: celery.
There is no undo for this operation!
(to skip this prompt use the -f option)
Are you sure you want to delete all tasks (yes/NO)?
</code></pre>
| 0 | 2016-07-16T17:59:50Z | [
"python",
"django",
"server",
"celery"
] |
Everytime Celery is restarted all the scheduled tasks are acknowledged | 38,371,006 | <p>Everytime Celery is restarted all the scheduled tasks are acknowledged again.</p>
<p>And this is leading to a huge time lag to start processing new tasks.</p>
<p>How can we solve this?</p>
| -1 | 2016-07-14T09:52:22Z | 38,414,740 | <p>If you <strong>don't want to purge</strong> the tasks which were in the QUEUE waiting to be executed i.e., you also want them to execute, then obviously those <strong>old tasks</strong> will be executed <strong>before the new tasks</strong> as the new tasks came in the QUEUE after the old ones AND because it is a QU... | 0 | 2016-07-16T19:20:02Z | [
"python",
"django",
"server",
"celery"
] |
Python Pandas Calculating timedelta between event occurrences | 38,371,126 | <p>I have a Pandas (0.14.1) data frame that has a <code>datetime</code> and also an <code>event</code> column as below:</p>
<pre><code>import pandas as pd
from datetime import datetime
from datetime import timedelta
def perdelta(start, end, delta):
curr = start
while curr < end:
yield curr;
curr +... | 0 | 2016-07-14T09:57:46Z | 38,375,456 | <p>This is my unexciting solution. I suspect there should be a faster Panads solution though. The existence of both vertical and horizontal dependency is what makes it harder to treat with <code>apply()</code> or <code>groupby()</code>, etc.</p>
<pre><code>last_trade_time = df.iloc[0]['datetime']
t=[np.nan] * len(df)
... | 0 | 2016-07-14T13:22:05Z | [
"python",
"pandas",
"timedelta"
] |
Python Pandas Calculating timedelta between event occurrences | 38,371,126 | <p>I have a Pandas (0.14.1) data frame that has a <code>datetime</code> and also an <code>event</code> column as below:</p>
<pre><code>import pandas as pd
from datetime import datetime
from datetime import timedelta
def perdelta(start, end, delta):
curr = start
while curr < end:
yield curr;
curr +... | 0 | 2016-07-14T09:57:46Z | 38,427,557 | <p>Vectorizing should be straightforward here: </p>
<ul>
<li>add another column which would hold last event times</li>
<li>set event times in this column if <code>event</code> is not NaN, else NaN</li>
<li>fill NaN values with method <code>ffill</code></li>
<li>subtract from <code>datetime</code> column.</li>
</ul>
<... | 1 | 2016-07-18T01:42:25Z | [
"python",
"pandas",
"timedelta"
] |
Django CMS custom plugin load data from cms_title | 38,371,180 | <p>I want to create a custom plugin for Django CMS. As the <a href="http://docs.django-cms.org/en/release-3.3.x/how_to/custom_plugins.html" rel="nofollow">guide</a> was showing, I created some examples. But now the goal is to create a plugin that will get the data from (mysql) database. It will load all titles that bel... | 0 | 2016-07-14T09:59:47Z | 38,374,728 | <p>Well, after few hours of struggling with this case, I finally succeeded to resolve my problem. </p>
<p>First of all, to answer the part of the question with CMS model and parameter title (in db: cms_title). Creating a new model with the FK to CMS title is the right way.
In <strong>models.py</strong>:</p>
<pre><cod... | 0 | 2016-07-14T12:50:42Z | [
"python",
"django",
"django-cms"
] |
Python/Pandas - Replacing an element in one dataframe with a value from another dataframe | 38,371,181 | <p>I have an issue with replacing an element in one pandas DataFrame by a value from another pandas DataFrame. Apologies for the long post. I have tried to give many inbetween examples to clarify my problem. I use Python 2.7.11 (Anaconda 4.0.0, 64bit).</p>
<p><strong>Data</strong></p>
<p>I have a pandas DataFrame con... | 2 | 2016-07-14T09:59:51Z | 38,374,044 | <p><strong>Short solution</strong></p>
<p>In essence, you want to throw away all item interactions for a given user, but only for items which are <em>not</em> ranked.</p>
<p>To make the proposed solutions more readable, assume <code>df = initial_user_item_matrix</code>.</p>
<p>Simple row selection with boolean condi... | 3 | 2016-07-14T12:21:06Z | [
"python",
"python-2.7",
"numpy",
"pandas",
"dataframe"
] |
How to pass a user-defined argument to a scrapy Spider when running it from a script | 38,371,212 | <p>Similar to <a href="http://stackoverflow.com/questions/15611605/how-to-pass-a-user-defined-argument-in-scrapy-spider">How to pass a user defined argument in scrapy spider</a>, I'm trying to run a spider in which a parameter (the <code>start_url</code>) is user defined. However, instead of running scrapy from the com... | 0 | 2016-07-14T10:01:27Z | 38,372,168 | <pre><code>scrapy crawl FundaMaxPagesSpider -a url='http://stackoverflow.com/'
</code></pre>
<p>Is equivalent to: </p>
<pre><code>process.crawl(FundaMaxPagesSpider, url='http://stackoverflow.com/')
</code></pre>
<p>Now you just treat the arguments as decribed in the answer you mentioned</p>
<pre><code>def __init__(... | 2 | 2016-07-14T10:46:46Z | [
"python",
"scrapy"
] |
How can I get urlopen to work with a list of urls from a file? | 38,371,242 | <p>I'm trying to get a list of urls from a file to work with urlopen so I can iterate through them and work with each url.</p>
<p>I was able to do what I wanted perfectly with one url directly passed as an argument, but I want to be able to do the same with a list retrieved from a file. It can go into the hundreds so ... | 1 | 2016-07-14T09:39:59Z | 38,371,508 | <p>Your problem is caused by a wrong format (encoding) of your URL.</p>
<p>To correct your problem you should convert your URL to utf-8 before parsing it with openurl like so.</p>
<pre><code>string_row = str(row)
after_encode = string_row.encode('utf-8')
page_source = urlopen(after_encode)
</code></pre>
<p>You could... | 0 | 2016-07-14T10:15:13Z | [
"python"
] |
How can I get urlopen to work with a list of urls from a file? | 38,371,242 | <p>I'm trying to get a list of urls from a file to work with urlopen so I can iterate through them and work with each url.</p>
<p>I was able to do what I wanted perfectly with one url directly passed as an argument, but I want to be able to do the same with a list retrieved from a file. It can go into the hundreds so ... | 1 | 2016-07-14T09:39:59Z | 38,572,965 | <p>Thank you all for helping.</p>
<p>I figured it out myself a few hours after posting this, and completely forgot about here. My apologies.</p>
<p>For the benefit of anyone, here is my final working code:</p>
<pre><code>import re
import csv
import urllib2
from bs4 import BeautifulSoup
with open('links.csv','r') as... | 0 | 2016-07-25T16:25:36Z | [
"python"
] |
Dictionary values are overwritng instead of adding into the dictionary | 38,371,351 | <p>The data structure I need to achieve is:</p>
<pre><code>{
'179': {
'name': [ < object > , < object > , < object > ],
'lastname': [ < object > , object > , < object > ]
}
}
</code></pre>
<p>And I have the following code to achieve it:</p>
<pre><code>if g_id ... | 1 | 2016-07-14T10:09:16Z | 38,371,399 | <p>In the <code>else</code> block, you should <em>update</em> the dictionary not <em>reassign</em>: </p>
<pre><code>email_data[g_id] = {'name': names}
email_data[g_id].update({'lastname': lastnames})
</code></pre>
<p>Or simply <em>assign</em> all the keys/values at once:</p>
<pre><code>email_data[g_id] = {'na... | 1 | 2016-07-14T10:11:04Z | [
"python",
"dictionary"
] |
Dictionary values are overwritng instead of adding into the dictionary | 38,371,351 | <p>The data structure I need to achieve is:</p>
<pre><code>{
'179': {
'name': [ < object > , < object > , < object > ],
'lastname': [ < object > , object > , < object > ]
}
}
</code></pre>
<p>And I have the following code to achieve it:</p>
<pre><code>if g_id ... | 1 | 2016-07-14T10:09:16Z | 38,371,491 | <p>You should change:</p>
<pre><code> else:
email_data[g_id] = {'name': names}
email_data[g_id] = {'lastname': lastnames}
</code></pre>
<p>To:</p>
<pre><code> else:
email_data[g_id] = {'name': names, 'lastname': lastnames}
</code></pre>
<p>Otherwise you are overwriting <code>email_... | 2 | 2016-07-14T10:14:36Z | [
"python",
"dictionary"
] |
Add column by previous columns values in Pandas | 38,371,418 | <p>Here is table: </p>
<pre><code>6 30 98 298 588 1598
36 2.0 NaN NaN NaN NaN NaN
50 1.0 NaN NaN NaN NaN NaN
</code></pre>
<p>Here is my dirty way to add new 'total' column: </p>
<pre><code>df_cz['total'] = df_cz[6] *6 + df_cz[30] *30 + df_cz[98] *98 + ...
</code></pre>
<p>Is there a better way to calculate '... | 1 | 2016-07-14T10:11:47Z | 38,372,762 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow"><code>mul</code></a> with columns names converted <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.to_series.html" rel="nofollow"><code>to_series</code></a> with <a href="ht... | 1 | 2016-07-14T11:17:13Z | [
"python",
"pandas",
"dataframe",
"sum",
"multiplication"
] |
How to split key, value from text file using pandas? | 38,371,440 | <p>I'm having input text file like this :</p>
<p><strong>Input.txt-</strong></p>
<pre><code>1=88|2=1438|3=KKK|4=7.7|5=00|7=66|8=a
1=13|2=1388|3=DDD|4=157.73|6=00|7=08|8=b|9=k
</code></pre>
<p>I want to split this key and value pairs and showing in the format like this :</p>
<p><strong>Output.txt-</strong></p>
<pre... | 1 | 2016-07-14T10:12:48Z | 38,379,806 | <p>you can do it using <code>.str.extract()</code> function in conjunction with a generated RegEx:</p>
<pre><code>pat = r'(?:1=)?(?P<a1>[^\|]*)?'
# you may want to adjust the right bound of the range interval
for i in range(2, 12):
pat += r'(?:\|{0}=)?(?P<a{0}>[^\|]*)?'.format(i)
new = df.val.str.ext... | 0 | 2016-07-14T16:43:12Z | [
"python",
"pandas",
"dataframe",
"key",
"value"
] |
how to plot real time in python without keeping previous plots? | 38,371,626 | <p>I have used Theano to do a simple linear regression. Now I want to show the dataset and the line which its slope is optimizing each time.
I have made a dynamic real time plot but the problem is that it keeps the previous plots. I want to keep the oroginal dataset and plot the new line each time. Here is my code:</p... | 0 | 2016-07-14T10:20:20Z | 38,371,887 | <p>Maybe I am not understanding your question (I wanted to write a comment, but I can't...)
Why don't you delete the previous graph every time you create a new one?
Or give a name to the file in which the graph is created, so every time you create a new one it will delete the file with the same name. Maybe you will fi... | 0 | 2016-07-14T10:33:00Z | [
"python",
"matplotlib",
"plot",
"draw",
"theano"
] |
how to plot real time in python without keeping previous plots? | 38,371,626 | <p>I have used Theano to do a simple linear regression. Now I want to show the dataset and the line which its slope is optimizing each time.
I have made a dynamic real time plot but the problem is that it keeps the previous plots. I want to keep the oroginal dataset and plot the new line each time. Here is my code:</p... | 0 | 2016-07-14T10:20:20Z | 38,374,735 | <p>Using plot_handle.set_ydata (and vectorizing a bit)</p>
<pre><code>import theano
from theano import tensor as T
import numpy as np
import matplotlib.pyplot as plt
trX = np.linspace(-1, 1, 10)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33
# PLOT THE ORIGINAL DATASET
plt.figure()
plt.ion()
plt.scatter(trX,trY)... | 0 | 2016-07-14T12:50:55Z | [
"python",
"matplotlib",
"plot",
"draw",
"theano"
] |
ffmpeg compilation Error | 38,371,651 | <p>I have been trying to compile ffmpeg on my raspberry-pi, but it gives me a lot of warnings like (codec is deprecated) especially while run sudo make.</p>
<pre><code> pi@raspberrypi:/usr/src/ffmpeg $ sudo make && sudo make install
....... lots of successful execution here ......
CC libavfilter/avf_showf... | 2 | 2016-07-14T10:21:18Z | 38,371,862 | <p>First of all, <strong>don't compile as root</strong>.</p>
<p>You should run <code>make</code> as your normal user, without <code>sudo</code>.</p>
<p>Only run <code>sudo make install</code> if you're installing in a root-owned location (e.g <code>/usr</code> or <code>/usr/local</code>).</p>
<hr>
<p>As for your qu... | 1 | 2016-07-14T10:31:39Z | [
"python",
"ffmpeg",
"raspberry-pi2"
] |
PyCURL is processing body before headers | 38,371,766 | <p>Inspired by accepted answer to <a href="http://stackoverflow.com/questions/21797753/efficiently-reading-lines-from-compressed-chunked-http-stream-as-they-arrive">this question</a> I'm trying to wrap PyCurl with <code>requests</code>-like interface. Everythig would be fine, but after following <a href="http://pycurl.... | 0 | 2016-07-14T10:27:13Z | 38,374,060 | <p>I've found the solution. The problem was that <code>_split_lines_from_chunks(self, chunks)</code> was trigerred before anything came with the response, so headers were also not there yet.</p>
<p>Here's the code that works. The charset is detected when first line of body is available, so I already have all the heade... | 0 | 2016-07-14T12:21:47Z | [
"python",
"python-3.x",
"pycurl",
"response-headers"
] |
Attribute of a Django Model: Check for Usages on Production Systems | 38,371,772 | <h1>Background</h1>
<p>Imagine I have a model like this:</p>
<pre><code>class Foo(models.Model):
...
name=models.CharField(max_length=1024)
</code></pre>
<p>I want to:</p>
<ol>
<li>deprecate <code>name</code> and update all Python code which uses it.</li>
<li>remove the attribute</li>
</ol>
<p>My guess: gr... | 1 | 2016-07-14T10:27:25Z | 38,372,434 | <p>I think doing this at Python/Django level would be very painful and almost impossible to make sure all cases are covered.</p>
<p>Best is probably to keep both fields for some time and use SQL triggers to:</p>
<ol>
<li>Keep them synced</li>
<li>Raise a warning when the deprecated field is accessed</li>
</ol>
| 2 | 2016-07-14T10:59:51Z | [
"python",
"django",
"deprecation-warning"
] |
Attribute of a Django Model: Check for Usages on Production Systems | 38,371,772 | <h1>Background</h1>
<p>Imagine I have a model like this:</p>
<pre><code>class Foo(models.Model):
...
name=models.CharField(max_length=1024)
</code></pre>
<p>I want to:</p>
<ol>
<li>deprecate <code>name</code> and update all Python code which uses it.</li>
<li>remove the attribute</li>
</ol>
<p>My guess: gr... | 1 | 2016-07-14T10:27:25Z | 38,375,931 | <h2>Unit Testing</h2>
<p>This is when unit tests pay you back 10 fold for the effort you put into them. If you have high code coverage, just go ahead and delete the field. Then run the unit tests. It will quickly show you which lines of code you have to change.</p>
<h2>Using Properties.</h2>
<p>Not so good as using ... | 2 | 2016-07-14T13:44:16Z | [
"python",
"django",
"deprecation-warning"
] |
Upgrading pandas on linux | 38,372,009 | <p>So, Currently I have <code>Python 2.7.6</code> in my linux system and pandas version <code>'0.13.1'</code> so I was using dt accesor in my code which wasnt working.After some google I came to know it requires higher version of pandas. I tried a couple of things. It is giving me warning <code>#warning "Using deprecat... | 0 | 2016-07-14T10:38:25Z | 38,374,463 | <p>Looking at the <a href="https://pastee.org/3dxcw" rel="nofollow">log</a>, the two interesting lines are</p>
<blockquote>
<p>copying build/lib.linux-x86_64-2.7/pandas/_period.so -> /usr/local/lib/python2.7/dist-packages/pandas</p>
<p>error: could not delete '/usr/local/lib/python2.7/dist-packages/pandas/_peri... | 2 | 2016-07-14T12:39:13Z | [
"python",
"linux",
"pandas"
] |
Split nested array values from Pandas Dataframe cell over multiple rows | 38,372,016 | <p>I have a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">Pandas DataFrame</a> of the following form</p>
<p><a href="http://i.stack.imgur.com/xZyo5.png" rel="nofollow"><img src="http://i.stack.imgur.com/xZyo5.png" alt="enter image description here"></a></p>
<p>Th... | 0 | 2016-07-14T10:38:50Z | 38,404,143 | <p>You can run <code>.apply(pd.Series)</code> for each of your columns, then <code>stack</code> and concatenate the results.</p>
<p>For a series</p>
<pre><code>s = pd.Series([[0, 1], [2, 3, 4]], index=[2011, 2012])
s
Out[103]:
2011 [0, 1]
2012 [2, 3, 4]
dtype: object
</code></pre>
<p>it works as follows</... | 1 | 2016-07-15T19:54:34Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
AttributeError: 'Logger' object has no attribute 'FileHandler' | 38,372,102 | <p>I am trying to add FileHandler to logger object in my script:</p>
<pre><code>FOO_LOGGER = logging.getLogger(LOGGER_NAME)
# create the logging file handler
fh = FOO_LOGGER.FileHandler('foo.log')
</code></pre>
<p>and I am getting this error:</p>
<blockquote>
<p>AttributeError: 'Logger' object has no attribute 'F... | -1 | 2016-07-14T10:43:39Z | 38,372,179 | <p>It has no object like that. </p>
<p>Try:</p>
<pre><code>import logging
logger = logging.getLogger('simple_example')
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
logger.addHandler(fh)
</code></pre>
<p>More can be found here: <a href="https://docs.python.org/2/howto/l... | 1 | 2016-07-14T10:47:57Z | [
"python",
"python-2.7"
] |
Redirect to success page after return attachment response | 38,372,144 | <p>I want to redirect to success page after django serve download file by response.
What I have to do?</p>
<p>File is generated by django every time that user request so It doesn't have real file in directory.</p>
<p>"content" variable is just string in .ical format.</p>
<pre class="lang-py prettyprint-override"><c... | 0 | 2016-07-14T10:45:45Z | 38,374,695 | <p>You should do it by redirecting on the client side!</p>
<p>JS Code</p>
<pre><code>document.getElementById('link-with-redirect').addEventListener('click', function() {
setTimeout(function() {
// Should be triggered after download started
document.location.href='{% url "redirect_destination" %}';
});
},... | 0 | 2016-07-14T12:49:12Z | [
"python",
"django"
] |
How to add k-means predicted clusters in a column to a dataframe in Python | 38,372,188 | <p>Have a question about kmeans clustering in python.</p>
<p>So I did the analysis that way:</p>
<pre><code>from sklearn.cluster import KMeans
km = KMeans(n_clusters=12, random_state=1)
new = data._get_numeric_data().dropna(axis=1)
kmeans.fit(new)
predict=km.predict(new)
</code></pre>
<p>How can I add the column wi... | 1 | 2016-07-14T10:48:16Z | 38,372,724 | <p>Assuming the column length is as the same as each column in you dataframe <code>df</code>, all you need to do is this:</p>
<pre><code>df['NEW_COLUMN'] = Series(predict, index=df.index)
</code></pre>
| 1 | 2016-07-14T11:15:34Z | [
"python",
"pandas",
"scikit-learn",
"cluster-analysis",
"k-means"
] |
Python Numpy Apply Rotation Matrix to each line in array | 38,372,194 | <p>I have a rotation matrix, and am using <code>.dot</code> to apply it to new values.
How can I apply it to each row in a numpy array?</p>
<p>Numpy array looks like:</p>
<pre><code> [-0.239746 -0.290771 -0.867432]
[-0.259033 -0.320312 -0.911133]
[-0.188721 -0.356445 -0.889648]
[-0.186279 -0.359619 -0.895996]
</co... | 1 | 2016-07-14T10:48:33Z | 38,372,534 | <p>Multiplying the a matrix with your rotation matrix rotates all columns individually. Just transpose forth, multiply and transpose back to rotate all rows:</p>
<pre><code>a = np.array([
[-0.239746,-0.290771,-0.867432],
[-0.259033,-0.320312,-0.911133],
[-0.188721,-0.356445,-0.889648],
[-0.186279,-0.359619,-0.8959... | 2 | 2016-07-14T11:04:53Z | [
"python",
"arrays",
"numpy",
"matrix",
"rotational-matrices"
] |
Python Numpy Apply Rotation Matrix to each line in array | 38,372,194 | <p>I have a rotation matrix, and am using <code>.dot</code> to apply it to new values.
How can I apply it to each row in a numpy array?</p>
<p>Numpy array looks like:</p>
<pre><code> [-0.239746 -0.290771 -0.867432]
[-0.259033 -0.320312 -0.911133]
[-0.188721 -0.356445 -0.889648]
[-0.186279 -0.359619 -0.895996]
</co... | 1 | 2016-07-14T10:48:33Z | 38,372,811 | <p>Let's assume you have a 3x3 rotation matrix R, and you want to matrix multiply vectors with size 3 as rows ra from array A, to result in rotated vectors rb with size 3 in array B:</p>
<pre><code>import numpy as np
# Define numpy array.
A = np.array([[-0.239746, -0.290771, -0.867432],
[-0.259033, -0.3... | 0 | 2016-07-14T11:19:33Z | [
"python",
"arrays",
"numpy",
"matrix",
"rotational-matrices"
] |
Python Numpy Apply Rotation Matrix to each line in array | 38,372,194 | <p>I have a rotation matrix, and am using <code>.dot</code> to apply it to new values.
How can I apply it to each row in a numpy array?</p>
<p>Numpy array looks like:</p>
<pre><code> [-0.239746 -0.290771 -0.867432]
[-0.259033 -0.320312 -0.911133]
[-0.188721 -0.356445 -0.889648]
[-0.186279 -0.359619 -0.895996]
</co... | 1 | 2016-07-14T10:48:33Z | 38,373,788 | <pre><code>a.dot(rot)
</code></pre>
<p>should do what you want.</p>
| 0 | 2016-07-14T12:06:37Z | [
"python",
"arrays",
"numpy",
"matrix",
"rotational-matrices"
] |
Django FileField move file following upload | 38,372,256 | <p>There are several questions around this topic but not one that I've found that suits what I'm trying to do. I want to be able to upload a file to a model and save that file in a nice location using the model instance attributes like pk. I know that this stuff gets set after <code>model.save()</code> so I need to wri... | 0 | 2016-07-14T10:51:37Z | 38,378,213 | <p>I figured it out after a lot of searching and finding <a href="https://code.djangoproject.com/ticket/15590#comment:10" rel="nofollow">this</a> old documentation ticket that has a good explanation.</p>
<pre><code>class UploadModel(models.Model):
image = models.ImageField(upload_to='uploads')
def save(self, ... | 0 | 2016-07-14T15:23:43Z | [
"python",
"django",
"django-models"
] |
Using keyboard input to store values of a counter | 38,372,438 | <p>I have a while loop that navigates to a webpage that I manually inspect. What I need to be able to do is press the enter key and have the counter stored.
Ideally everything would work like this:</p>
<pre><code>from selenium import webdriver as wd
import time
url = [www.example.com,www.google.com]
ff = wd.Firefox()... | -1 | 2016-07-14T11:00:21Z | 38,372,600 | <p>Simple way is to get input from the user and check if it's empty:</p>
<pre><code>while i<len(url):
ff.get(url[i])
time.sleep(5)
x = input()
if x=="":
stored_url_number.extend(i)
i +=1
</code></pre>
<p>You can skip the checking if you don't care what the input is:</p>
<pre><code>whi... | 1 | 2016-07-14T11:08:54Z | [
"python",
"python-2.7"
] |
How to parse a list in python using re | 38,372,560 | <p>I am trying to parse a list to get the individual images returned by the bash script (stored in the list errors in py script). How can I do this with "re" ?</p>
<p><strong>bash script</strong></p>
<pre><code>#!/bin/bash
value(){
for entry in *
do
if expr "$(file -b $entry)" : 'JPEG ' >/dev/null;
then
echo ... | 0 | 2016-07-14T11:06:43Z | 38,373,245 | <p>I make a few assumptions (based on the example input you give):</p>
<ul>
<li>file names only contain digits and underscores (so I can use <code>\w</code> in regex)</li>
<li>words in a file name are always concatenated by underscores (no spaces)</li>
<li>every file is a jpeg file</li>
</ul>
<p>The code:</p>
<pre><... | 0 | 2016-07-14T11:41:30Z | [
"python",
"regex",
"bash"
] |
Python: Get 2 filenames from command line using OptionParser | 38,372,627 | <p>I want to use a program like this: </p>
<pre><code>python myprg.py -f1 t1.txt -f2 t.csv
</code></pre>
<p>where f1, f2 are filenames.<br>
I have the following code: </p>
<pre><code>from optparse import OptionParser
def main():
optparser = OptionParser()
optparser.add_option('-f1', '--inputFile1',
... | 1 | 2016-07-14T11:10:16Z | 38,372,830 | <p>According to <a href="https://docs.python.org/2/library/optparse.html" rel="nofollow">documentation</a>, optparse does not support multiple letters with single hyphen (-).</p>
<blockquote>
<p>Some option syntaxes that the world has seen include:</p>
<ul>
<li>a hyphen followed by a few letters, e.g. -pf (th... | 3 | 2016-07-14T11:20:24Z | [
"python",
"command-line"
] |
Adding field which is not in model | 38,372,755 | <p>I have just started using Odoo and i am creating my own module, so i added a new field to Products for example: </p>
<pre><code>class ProductTemplate(models.Model):
_inherit = 'product.template'
netto_price = fields.Float()
</code></pre>
<p>now i will have few extra field which change based on netto_price... | 0 | 2016-07-14T11:16:48Z | 38,372,915 | <pre><code>from openerp import api
class ProductTemplate(models.Model):
_inherit = 'product.template'
netto_price = fields.Float()
calculated_price = fields.Float('Calculated price') # or whatever type you want it to be
@api.onchange('netto_price')
def netto_change(self):
return {value: ... | 1 | 2016-07-14T11:24:51Z | [
"python",
"xml",
"odoo-8"
] |
python qt float precision from boost-python submodule | 38,372,786 | <p>I have made a cpp submodule with boost-python for my PyQt program that among others extracts some data from a zip data file.</p>
<p>It works fine when testing it in python:</p>
<pre><code>import BPcmods
BPzip = BPcmods.BPzip()
BPzip.open("diagnostics/p25-dev.zip")
l=BPzip.getPfilenames()
t=BPzip.getTempArray([l[1]... | 0 | 2016-07-14T11:18:21Z | 38,390,716 | <p>Well it was related to using std::stod to convert my strings of data from my datafile to doubles. I don't know why, but changing to:</p>
<pre><code>boost::algorithm::trim(s);
double val = boost::lexical_cast<double>(s);
</code></pre>
<p>made it work as it was supposed to, also in pyqt.</p>
| 0 | 2016-07-15T07:51:41Z | [
"python",
"c++",
"boost",
"pyqt4",
"precision"
] |
Pandas: print pivot_table to dataframe | 38,372,903 | <p>I have data</p>
<pre><code>id year val
123 2014 1
123 2015 0
123 2016 1
456 2014 0
456 2015 0
456 2016 1
789 2014 1
789 2015 0
789 2015 0
</code></pre>
<p>And I want to print pivot_table and get</p>
<pre><code>date 2014 2015 2016
ID
123 1 0 1
456 ... | 1 | 2016-07-14T11:24:22Z | 38,372,978 | <p>You can use:</p>
<pre><code>group = output.pivot_table(index='id', values='val', columns='year', fill_value=0)
print (group)
year 2014 2015 2016
id
123 1 0 1
456 0 0 1
789 1 0 0
</code></pre>
<p>EDIT:</p>
<p>You get these values with real data, becasue... | 1 | 2016-07-14T11:28:02Z | [
"python",
"pandas"
] |
Installing Django app from GitHub | 38,372,908 | <ol>
<li>create virtualenv</li>
<li>create project (chat)</li>
<li>follow instructions at
<a href="https://github.com/qubird/django-chatrooms" rel="nofollow">https://github.com/qubird/django-chatrooms</a>, after which there is a <code>src</code> folder in the root of the virtualenv</li>
<li>navigate to <code>virtualen... | 0 | 2016-07-14T11:24:39Z | 38,375,601 | <p>Just follow these:</p>
<ol>
<li>cd in to the directory where you want your project to store you source code eg. home/.</li>
<li>Then run <code>django-admin startproject chat</code></li>
<li>This will create a chat directory in your current directory</li>
<li>Now cd to the chat directory.</li>
<li>run <code>virtuale... | 0 | 2016-07-14T13:29:03Z | [
"python",
"django",
"github"
] |
Installing Django app from GitHub | 38,372,908 | <ol>
<li>create virtualenv</li>
<li>create project (chat)</li>
<li>follow instructions at
<a href="https://github.com/qubird/django-chatrooms" rel="nofollow">https://github.com/qubird/django-chatrooms</a>, after which there is a <code>src</code> folder in the root of the virtualenv</li>
<li>navigate to <code>virtualen... | 0 | 2016-07-14T11:24:39Z | 38,396,231 | <p>The method below installs directly to the prjoect level directory with no nedd to manually move file , .ie, not installed to src/chatrooms/charooms</p>
<p>1 create virtualenv (optional)</p>
<p>2 create project </p>
<p>3 cd to project</p>
<p>4 run git init</p>
<p>5 run command git clone "{protocol:url}"</p>
<p>... | 0 | 2016-07-15T12:33:21Z | [
"python",
"django",
"github"
] |
Inheriting hr.holidays class and overriding create method in Odoo v9 | 38,373,032 | <p>I have created a custom applications (module) on <code>Odoo v9</code>, that inherits <code>hr.holidays(leaves module)</code> in models of my module, and overrides <code>create()</code> method and also <code>_check_state_access_right()</code> method as I want to modify <code>_check_state_access_right()</code> in my m... | 0 | 2016-07-14T11:30:22Z | 38,391,570 | <p>get rid of <code>_name = 'hr.holidays'</code>, if you just want to override or add properties to a model using <code>_inhereit='hr.holidays'</code> is fine</p>
<p>to properly override the new method in your class the methods name have to be the same, so in your <code>HrHolidaysCustom</code> class change your method... | 0 | 2016-07-15T08:36:59Z | [
"python",
"oop",
"inheritance",
"openerp"
] |
Why XML parsing is so difficult? | 38,373,108 | <p>I am trying to parse this simple document received from EPO-OPS.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/3.0/style/exchange.xsl"?>
<ops:world-patent-data xmlns="http://www.epo.org/exchange" xmlns:ops="http://ops.epo.org" xmlns:xlink="http://www.w3.... | -1 | 2016-07-14T11:33:39Z | 38,373,181 | <p>It is much much easier with BeautifulSoup. Try this:</p>
<pre><code>from bs4 import BeautifulSoup
xml = """<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/3.0/style/exchange.xsl"?>
<ops:world-patent-data xmlns="http://www.epo.org/exchange" xmlns:ops="http://ops.epo.org"... | 2 | 2016-07-14T11:37:56Z | [
"python",
"xml",
"python-3.x"
] |
Why XML parsing is so difficult? | 38,373,108 | <p>I am trying to parse this simple document received from EPO-OPS.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/3.0/style/exchange.xsl"?>
<ops:world-patent-data xmlns="http://www.epo.org/exchange" xmlns:ops="http://ops.epo.org" xmlns:xlink="http://www.w3.... | -1 | 2016-07-14T11:33:39Z | 38,373,235 | <p>You can use XPath expressions with ElementTree. Note that because you have a global XML namespace defined with <code>xmlns</code>, you need to specify that URL:</p>
<pre><code>tree = ElementTree.parse(â¦)
namespaces = { 'ns': 'http://www.epo.org/exchange' }
paragraphs = tree.findall('.//ns:abstract/ns:p', namespa... | 2 | 2016-07-14T11:40:45Z | [
"python",
"xml",
"python-3.x"
] |
Python loop through long list for matching strings and concatenate | 38,373,127 | <p>I am trying to loop through a list in order to find filenames that match except for the final character and concatenate the matches into one string.</p>
<p>The difficulty I have is that there are varying amounts of matches per filename, so there could be a single file with no matches, a file with two matches, three... | 0 | 2016-07-14T11:34:40Z | 38,374,263 | <p>If I understand you correctly you want a group all filenames that match (except the last character and '.jpg') into a string that's all the filenames concatenated? Here's an example how to do that:</p>
<pre><code>from collections import Counter
# The list you provided
reader = ['34113751IHF.jpg', '34113751IHR.jpg'... | 2 | 2016-07-14T12:31:05Z | [
"python",
"string",
"list",
"concatenation",
"match"
] |
Using python language to acces a cmd window | 38,373,150 | <p>It is possible to make a python script which opens a cmd window and enters 5 commands one by one, and after waits for an external trigger to continue entering another 2 commands in the same window.</p>
<p>It is posibble? I hope You understand what I ask.
PS: maybe you can share with me a sample code or something.<... | -3 | 2016-07-14T11:36:02Z | 38,373,476 | <p>What i have done in the past is use Python to write a <code>.bat</code> file and run it. And this does produce the result you describe. You can do this like that:</p>
<pre><code>import subprocess
with open(r'my_bat_file.bat','w') as fout:
fout.write('command no1')
fout.write('command no2')
...
fout... | 3 | 2016-07-14T11:51:47Z | [
"python"
] |
Unable to fill a custom choicefield form on Django | 38,373,173 | <p>I'm new on DJango and I'm trying to fill a choicefield form with custom data but I'm getting an error that I don't understand well.</p>
<p>On my <code>views.py</code> I have:</p>
<pre><code>def simpleDeploy(request):
networkList = getDetailsNetworkPartitions(request)
policiesList = getDetailsApplicationPol... | 0 | 2016-07-14T11:37:23Z | 38,375,759 | <p>It looks like you have used a different key, and the positional arguments are missing. The arguments you are sending are being considered as <code>kwargs</code>.</p>
<p>In the form's <code>__init__</code> you are expecting the following arguments</p>
<pre><code>def __init__(self, networkList, policiesList, *args, ... | 2 | 2016-07-14T13:36:40Z | [
"python",
"django",
"forms",
"choicefield"
] |
getting pygame keyboard events as integers | 38,373,184 | <p>I am making a math game and I want the user to be able to enter the answer. Do I have to do something like this for each number.</p>
<pre><code>for event in pygame.event.get():
blahblahblah
quit event
if event.key == K_1:
str(answer + 1)
</code></pre>
<p>Is there a way to get keyboard events an... | -1 | 2016-07-14T11:38:00Z | 38,373,248 | <p>K_1 is already an integer (49). They are just constants of integers representing a specific key. So in your case, if you want to create an integer '1' when the player presses K_1 and '2' when the player presses K_2, all you have to do is:</p>
<pre><code>answer = event.key - 48
</code></pre>
| 2 | 2016-07-14T11:41:39Z | [
"python",
"pygame",
"keyboard-events"
] |
order values in alphabetical order in pandas dataframe | 38,373,272 | <p>I have a column in a pandas dataframe called feature. I want to order the values of "feature" in an alphabetical order. For example, in the below table, how can I get all the values under age in the order age, color, gender?</p>
<pre><code>ID Feature
1001 color,age,gender
1002 age,gender,color
1003 age,co... | 4 | 2016-07-14T11:42:37Z | 38,373,445 | <p>Here is one way, but, honestly, i don't like it:</p>
<pre><code>In [24]: df.Feature = df.Feature.str.split(',', expand=True).apply(lambda x: pd.Series(np.sort(x)).str.cat(sep=','), axis=1)
In [25]: df
Out[25]:
ID Feature
0 1001 age,color,gender
1 1002 age,color,gender
2 1003 age,color,gender
3... | 3 | 2016-07-14T11:50:42Z | [
"python",
"pandas",
"dataframe"
] |
Removing proper English words from tweets in R | 38,373,276 | <p>I'm working on twitter data using R and am trying to remove all proper English words from the tweet. The idea is to look at the colloquial abbreviations, typos and slang used by a particular demographic whose tweets I have recorded.</p>
<p>Example: </p>
<pre><code> tweet <- c("Trying to find the solution fru... | 3 | 2016-07-14T11:42:54Z | 38,375,127 | <p>Another hunspell based solution using a rather new & interesting <a href="https://github.com/ropensci/hunspell" rel="nofollow">package</a>: </p>
<pre><code># install.packages("hunspell") # uncomment & run if needed
library(hunspell)
tweet <- c("Trying to find the solution frustrated af")
( tokens <- s... | 1 | 2016-07-14T13:08:15Z | [
"python",
"twitter",
"text-mining"
] |
How to plot a circle-cross in python? +oplus | 38,373,285 | <p>I am using Python programming language.
I want to plot a circle-cross shape in a figure.
But i can't find the way to make it.
I attach an example image (png) what i want (the circle-cross shape).
Just in case that attaching is failed, let me describe the shape i want.
Here 'circle-cross' means that a plus mark is in... | -3 | 2016-07-14T11:43:18Z | 38,428,338 | <p>Let's assume we want to plot an oplus that the radius is 1.5 at (2, 3) in xy-axis. My solution is the following lines.</p>
<h1>import a module we need.</h1>
<p><code>import matplotlib.pyplot as plt</code></p>
<h1>popping up an empty figure.</h1>
<p><code>fig=plt.figure()</code>
<code>ax1=fig.add_subplot(1, 1, 1)... | 0 | 2016-07-18T03:52:41Z | [
"python",
"matplotlib"
] |
Trouble trying to scrape paginated links using Scrapy | 38,373,320 | <p>I'm trying to learn Scrapy by fetching title of entries on a property website with pagination. I'm not able fetch the entries from the 'Next' pages defined in the <code>rules</code> list. </p>
<p>Code: </p>
<pre><code>from scrapy import Spider
from scrapy.selector import Selector
from scrapy.linkextractors import... | 0 | 2016-07-14T11:44:51Z | 38,373,906 | <p>There are few things that are wrong with your spider.</p>
<ol>
<li><p>Your <code>allowed_domains</code> is broken, if you inspect your spider you probably get a lot of filtered out requests. </p></li>
<li><p>You misunderstand <a href="http://doc.scrapy.org/en/latest/topics/spiders.html?highlight=crawlspider#crawlsp... | 0 | 2016-07-14T12:12:21Z | [
"python",
"pagination",
"scrapy"
] |
Appengine Search API: Exclude one document field from search | 38,373,407 | <p>In the search document I have two fields which have value as Yes or No.</p>
<p>field1 - have value as Yes or No
field2 - have value as Yes or No</p>
<p>from function foo(), I want to search a document which have value as "no" and it should not search in field1.</p>
<p>How to archive this ?</p>
| 0 | 2016-07-14T11:48:29Z | 38,381,484 | <p>If you just say "no", you'll search all fields in the document. However, if you prefix your term with a field name like "field2:no" you will only search the values of that field.</p>
| 0 | 2016-07-14T18:20:49Z | [
"python",
"google-app-engine",
"full-text-search"
] |
Tkinter : How to center the window title | 38,373,621 | <p>I am creating a project using tkinter and when I create a window, I couldn't seem to get the window title to center itself (Like most programs nowadays). Here's the example code:</p>
<pre><code>from tkinter import *
root = Tk()
root.title("Window Title".center(110))# Doesn't seem to work
root.mainloop()
</code></... | 2 | 2016-07-14T11:58:32Z | 38,373,712 | <p>There is nothing you can do. Tkinter has no control over how the window manager or OS displays the titles of windows other than to specify the text. </p>
| 1 | 2016-07-14T12:03:01Z | [
"python",
"tkinter",
"title",
"centering"
] |
Tkinter : How to center the window title | 38,373,621 | <p>I am creating a project using tkinter and when I create a window, I couldn't seem to get the window title to center itself (Like most programs nowadays). Here's the example code:</p>
<pre><code>from tkinter import *
root = Tk()
root.title("Window Title".center(110))# Doesn't seem to work
root.mainloop()
</code></... | 2 | 2016-07-14T11:58:32Z | 38,375,718 | <p>I came up with a trick that does the job and it consists in simply adding as much blank space before the title:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
root.title(" Window Title")# Add the blank space
frame = tk.Frame(root, width=8... | -1 | 2016-07-14T13:34:35Z | [
"python",
"tkinter",
"title",
"centering"
] |
Tkinter : How to center the window title | 38,373,621 | <p>I am creating a project using tkinter and when I create a window, I couldn't seem to get the window title to center itself (Like most programs nowadays). Here's the example code:</p>
<pre><code>from tkinter import *
root = Tk()
root.title("Window Title".center(110))# Doesn't seem to work
root.mainloop()
</code></... | 2 | 2016-07-14T11:58:32Z | 38,377,381 | <p>More adding onto what Billal suggested is this example that adjust depending on the window size. I still wouldn't recommend it since it's just a hack for visual aesthetics but if you really want to have it.</p>
<pre><code>import tkinter as tk
def center(e):
w = int(root.winfo_width() / 3.5) # get root width an... | -1 | 2016-07-14T14:49:11Z | [
"python",
"tkinter",
"title",
"centering"
] |
How to get python to constantly check for key combinations even if it is in the background? | 38,373,696 | <p>I was thinking of coding a script that will run in the background of my computer that will detect key combinations to start specific tasks.</p>
<p>For example, the user presses Ctrl+Alt+F1 then the browser starts. However, I cannot seem to find a way to detect these combinations while the script is running in the b... | -3 | 2016-07-14T12:02:24Z | 38,373,849 | <p>I think the <a href="https://pypi.python.org/pypi/pyHook" rel="nofollow"><code>pyHook</code></a> library is what you're looking for:</p>
<blockquote>
<p>The pyHook package provides callbacks for global mouse and keyboard events in Windows. Python applications register event handlers for user input events such as ... | 1 | 2016-07-14T12:09:51Z | [
"python",
"pc"
] |
Class with changing __hash__ still works with dictionary access | 38,373,881 | <p>What I did is obviously not something that one would want to do, rather, I was just testing out implementing <code>__hash__</code> for a given class. </p>
<p>I wanted to see if adding a phony 'hashable' class to a dictionary, then changing it's hash value would then result in it not being able to access it. </p>
<... | 10 | 2016-07-14T12:11:09Z | 38,376,661 | <p>This is a strange bit of fate. Several bits of CPython machinery have thwarted you. The three issues at play are:</p>
<ol>
<li>The initial size of the array that backs a <code>dict</code> is 8 <sup>[1]</sup></li>
<li>All objects in CPython have memory addresses that are modulo 8 <sup>[2]</sup></li>
<li>The <code>di... | 5 | 2016-07-14T14:17:19Z | [
"python",
"python-3.x",
"dictionary"
] |
Class with changing __hash__ still works with dictionary access | 38,373,881 | <p>What I did is obviously not something that one would want to do, rather, I was just testing out implementing <code>__hash__</code> for a given class. </p>
<p>I wanted to see if adding a phony 'hashable' class to a dictionary, then changing it's hash value would then result in it not being able to access it. </p>
<... | 10 | 2016-07-14T12:11:09Z | 38,378,755 | <p>I have a possible explanation:</p>
<p>According to this source: <a href="http://www.laurentluce.com/posts/python-dictionary-implementation/" rel="nofollow">http://www.laurentluce.com/posts/python-dictionary-implementation/</a> only few last bits of the hash are used when the table holding the dict elements is small... | 3 | 2016-07-14T15:49:48Z | [
"python",
"python-3.x",
"dictionary"
] |
Save image temporarily using io for pre-processing without using disk resources | 38,373,942 | <p>My current project requires that i deal with uploaded files(mostly images) for pre-processing before i save them.</p>
<p>So far my main method has been to upload to Amazon s3 then download and work on them.</p>
<p>This is not ideal because i do not really need to save the uploaded image but rather the final produc... | 0 | 2016-07-14T12:14:28Z | 38,377,441 | <p>If you want to integrate an image you've uploaded in a PDF, you may want this kind of thing:</p>
<pre><code>from io import BytesIO
from PIL import Image
from reportlab.pdfgen import canvas
def upload_view(request):
image = request.FILES['image']
imagebuffer = BytesIO()
for chunk in image.chunks():
... | 0 | 2016-07-14T14:52:06Z | [
"python",
"django",
"io"
] |
Save image temporarily using io for pre-processing without using disk resources | 38,373,942 | <p>My current project requires that i deal with uploaded files(mostly images) for pre-processing before i save them.</p>
<p>So far my main method has been to upload to Amazon s3 then download and work on them.</p>
<p>This is not ideal because i do not really need to save the uploaded image but rather the final produc... | 0 | 2016-07-14T12:14:28Z | 38,879,080 | <p><code>Image.open()</code> expects a filename or a file like object (with <code>read()</code>, <code>seek()</code>, and <code>tell()</code> methods). So you have to give the <code>buffer</code> object to <code>Image.open()</code>. Not closed and rewinded to the beginning.</p>
<pre><code>def temp_file(f):
return ... | 0 | 2016-08-10T16:38:15Z | [
"python",
"django",
"io"
] |
How to import images in django models from csv/excel? | 38,374,004 | <p>This is my model.</p>
<pre><code>class Product(models.Model)
id = models.AutoField(max_length=10, primary_key=True)
name = models.CharField(max_length=60)
summary = models.TextField(max_length=200)
image = models.FileField(upload_to='product_images', blank=True)
</code></pre>
<p>I know how to impo... | -3 | 2016-07-14T12:17:56Z | 38,375,214 | <p><a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.FileField" rel="nofollow">FileField</a> is just a reference to a file. It does not put a file into the database as is sometimes mistakenly believed.</p>
<p>Assuming that you have already got the code written for reading through the C... | 1 | 2016-07-14T13:11:41Z | [
"python",
"django",
"excel",
"csv",
"django-file-upload"
] |
How to import images in django models from csv/excel? | 38,374,004 | <p>This is my model.</p>
<pre><code>class Product(models.Model)
id = models.AutoField(max_length=10, primary_key=True)
name = models.CharField(max_length=60)
summary = models.TextField(max_length=200)
image = models.FileField(upload_to='product_images', blank=True)
</code></pre>
<p>I know how to impo... | -3 | 2016-07-14T12:17:56Z | 38,408,610 | <p>I solved it by saving the name of the image in the csv and just uploading the name in the field like this:</p>
<pre><code>...
product.image = "product_images" + namefromcsv
</code></pre>
<p>then I uploaded all the images in the media folder inside <code>product_images</code> .</p>
<p>And it worked very well. </p... | 0 | 2016-07-16T06:50:24Z | [
"python",
"django",
"excel",
"csv",
"django-file-upload"
] |
Flask-SQLAlchemy - how do sessions work with multiple databases? | 38,374,005 | <p>I'm working on a Flask project and I am using Flask-SQLAlchemy.<br>
I need to work with multiple already existing databases.<br>
I created the "app" object and the SQLAlchemy one:<br></p>
<pre><code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
</code><... | 0 | 2016-07-14T12:18:00Z | 38,375,161 | <p>Flask-SQLAlchemy uses a <a href="https://github.com/mitsuhiko/flask-sqlalchemy/blob/master/flask_sqlalchemy/__init__.py#L134" rel="nofollow">customized session</a> that handles bind routing according to given <a href="http://flask-sqlalchemy.pocoo.org/latest/binds/#referring-to-binds" rel="nofollow"><code>__bind_key... | 4 | 2016-07-14T13:09:37Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
HTTP status code 200 vs 202 | 38,374,019 | <p>I have a <code>Python</code>+<code>requests</code> script. </p>
<p><em>Steps script should execute</em>:</p>
<ul>
<li>sent file to DB;</li>
<li>approve this file (change file state in DB);</li>
<li>download file.</li>
</ul>
<p><em>The constraint</em>: </p>
<p><strong>Only approved file could be downloaded</stron... | 2 | 2016-07-14T12:19:14Z | 38,374,229 | <p>It depends on your server implementation and your server decides how <code>202</code> will be processed.</p>
<blockquote>
<p><strong>202 Accepted</strong></p>
<p>The request has been accepted for processing, but the processing has
not been completed. The request might or might not eventually be acted
upo... | 5 | 2016-07-14T12:29:39Z | [
"python",
"http",
"python-requests",
"http-status-codes"
] |
python-Can we use tempfile with subprocess to get non buffering live output in python app | 38,374,063 | <p>I am trying to run one python file from python windows application.For that I have used <code>subprocess</code>.For getting live streaming output on app console I have tried the below statements.</p>
<p>With PIPE</p>
<pre><code>p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
... | 0 | 2016-07-14T12:21:52Z | 38,413,861 | <p>I understand you're frustration. It looks like you've almost come to the answer yourself.</p>
<p>I'm building on the answer from <a href="http://stackoverflow.com/a/18422264/3991139">this SO post</a>. But that answer doesn't use <code>TemporaryFile</code> and also I used the tail follow method from <a href="http://... | 0 | 2016-07-16T17:38:14Z | [
"python",
"python-2.7"
] |
Finding the average of dataframe column only until end of day (datetime-indexed) | 38,374,097 | <p>I have a <code>DataFrame</code> object that is indexed by <code>datetime</code>. Let us say my object looks like this: </p>
<pre><code> DateTime A
2016-07-01 08:30:00 5
2016-07-01 09:28:17 6
2016-07-01 14:09:11 9
2016-07-01 22:33:44 10
2016-07-02 08:30:00 20
2016-07-02 15:00:00 30
</c... | 3 | 2016-07-14T12:23:19Z | 38,376,253 | <p>Create a custom function to <code>apply</code> with</p>
<pre><code>def nowTilEODMean(d):
cond1 = df.index >= d.name
cond2 = df.index.day == d.name.day
return df.A.loc[cond1 & cond2].mean()
df['B'] = df.apply(nowTilEODMean, axis=1)
df
</code></pre>
<p><a href="http://i.stack.imgur.com/DhJaS.png"... | 2 | 2016-07-14T13:59:08Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
Variable not defined during data analysis | 38,374,347 | <p>I'm new to programming and I've looked at previous answers to this question but none seem relevant to this specific query.</p>
<p>I'm learning to analyse data with python.</p>
<p>This is the code: </p>
<pre><code>import pandas as pd
import os
os.chdir('/Users/Benjy/Documents/Python/Data Analysis Python')
uname... | 0 | 2016-07-14T12:34:19Z | 38,380,556 | <p>I think this will work: <code>mean_ratings=data.pivot_table('rating',index='title',columns='gender',aggfunc='ââmean')</code></p>
| 1 | 2016-07-14T17:27:20Z | [
"python",
"pandas",
"undefined"
] |
Efficient way to generate partitions with value pair of a list >15 elements | 38,374,462 | <p>I am generating a list of partitions from a list of elements (akin to partitions of a set or set partitions). The problem is for each of these partitions I need to assigned a random number indicating their value so I can run some computations on later on the output data consisting of a partition = value pair. </p>
... | 0 | 2016-07-14T12:39:10Z | 38,374,560 | <p>Your issue here is that you're combining a generator with turning it into a list, which <em>totally</em> negates any benefit from creating a generator.</p>
<p>Instead, you should just be writing out directly from your generator.</p>
<pre><code>from collections import defaultdict
import random
import csv
elements ... | 1 | 2016-07-14T12:43:31Z | [
"python",
"arrays",
"list",
"partitioning"
] |
get encoding specified in magic line / shebang (from within module) | 38,374,489 | <p>If I specify the character encoding (as suggested by <a href="http://www.python.org/dev/peps/pep-0263/" rel="nofollow">PEP 263</a>) in the "magic line" or shebang of a python module like</p>
<pre><code># -*- coding: utf-8 -*-
</code></pre>
<p>can I retrieve this encoding from within that module?</p>
<p>(Working o... | 4 | 2016-07-14T12:40:11Z | 38,374,721 | <p>I'd borrow the Python 3 <a href="https://hg.python.org/cpython/file/v3.5.2/Lib/tokenize.py#l357" rel="nofollow"><code>tokenize.detect_encoding()</code> function</a> in Python 2, adjusted a little to match Python 2 expectations. I've changed the function signature to accept a filename and dropped the inclusion of the... | 5 | 2016-07-14T12:50:28Z | [
"python",
"python-2.7",
"encoding",
"character-encoding"
] |
How can I read multiple lines from a text area using a python API script? | 38,374,546 | <p>I'm currently working on a python script and part of the input I'm getting is a text area. The user inputs a multi-line value and I need to use each line separately. So the input from the user would look something like this:</p>
<pre><code>value1
value2
value3
value4
</code></pre>
<p>And I need to put them each in... | 0 | 2016-07-14T12:42:42Z | 38,374,949 | <p>If the input is a string separated by a new-line character you could use the <em>splitlines()</em> method:</p>
<pre><code>text = 'value1\nvalue2\nvalue3\nvalue4'
var1, var2, var3, var4 = text.splitlines()
</code></pre>
<p>This will put them in separate variables but you'll get an error if there's less or more than... | 3 | 2016-07-14T13:00:19Z | [
"python"
] |
Selenium python click icon next to a certain text | 38,374,621 | <p>I have the following structure, where I am trying to click the second trash icon which is a button next to Test1.</p>
<pre><code><tr class=âng-scopeâ>
<td class=âng-scopeâ></td>
<td class=âng-scopeâ></td>
<td class=âng-scopeâ>
<span class=âng-bindi... | 1 | 2016-07-14T12:46:15Z | 38,374,920 | <p>I'm not very clear whether you want the button or the icon...
here is for the i tag</p>
<p>try </p>
<pre><code>//i[@class='glyphicon glyphicon-trash' and ../../../td/span/text() = "Test1"]
</code></pre>
<p>ps note also that:</p>
<pre><code><span class="ng-binding">Test1</span>
</code></pre>
<p>and</... | 0 | 2016-07-14T12:58:41Z | [
"python",
"selenium",
"xpath"
] |
Selenium python click icon next to a certain text | 38,374,621 | <p>I have the following structure, where I am trying to click the second trash icon which is a button next to Test1.</p>
<pre><code><tr class=âng-scopeâ>
<td class=âng-scopeâ></td>
<td class=âng-scopeâ></td>
<td class=âng-scopeâ>
<span class=âng-bindi... | 1 | 2016-07-14T12:46:15Z | 38,376,061 | <p>To select the button in the row having the text:</p>
<pre><code>//tr[.//text()='Test1']//button
</code></pre>
<p>To select the button in cell 4 in the row having the text in cell 3:</p>
<pre><code>//tr[td[3]//text()='Test1']/td[4]//button
</code></pre>
<p>To select the cell having the text and then the button in... | 0 | 2016-07-14T13:50:14Z | [
"python",
"selenium",
"xpath"
] |
True parallelism in Python | 38,374,629 | <p>Is it possible to have true parallelism in python due to the presence of GIL? As far as I know each thread acquires the GIL before executing while other threads wait until the GIL is released. Why have GIL if it is such a bottleneck</p>
| 2 | 2016-07-14T12:46:44Z | 38,374,749 | <p>Python, the language does not necessarily enforce GIL. It's the different implementations of the language which may or may not have GIL. </p>
<p>CPython (the de-facto implementation) has GIL. So you can not have truly parallel threads while you're using it. However, you can use multi processing to gain parallelism.... | 5 | 2016-07-14T12:51:24Z | [
"python",
"multiprocessing",
"gil"
] |
True parallelism in Python | 38,374,629 | <p>Is it possible to have true parallelism in python due to the presence of GIL? As far as I know each thread acquires the GIL before executing while other threads wait until the GIL is released. Why have GIL if it is such a bottleneck</p>
| 2 | 2016-07-14T12:46:44Z | 38,374,895 | <p>If you want to learn about the GIL in python, I'd suggest to start reading here:</p>
<p><a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">https://wiki.python.org/moin/GlobalInterpreterLock</a></p>
<p>See the section <em>Eliminating the GIL</em> for an explanation why python still has the ... | 1 | 2016-07-14T12:57:37Z | [
"python",
"multiprocessing",
"gil"
] |
Filtering a Pivot table by non pivot dataframe column | 38,374,677 | <p>I have a dataframe (df) </p>
<pre><code> id company sector currency price
0 BBG.MTAA.MS.S MEDIASET SPA Communications EUR 4.334000
1 BBG.MTAA.TIT.S TELECOM ITALIA SPA Communications EUR 1.091000 ... | 1 | 2016-07-14T12:48:21Z | 38,375,705 | <p>Use <code>dropna(subset=['price']</code> ahead of your pivot.</p>
<pre><code>df.dropna(subset=['price']).pivot_table(index=['sector'], aggfunc='count')
</code></pre>
<p><a href="http://i.stack.imgur.com/k1Bkl.png" rel="nofollow"><img src="http://i.stack.imgur.com/k1Bkl.png" alt="enter image description here"></a><... | 2 | 2016-07-14T13:33:45Z | [
"python",
"pandas"
] |
How to add alias target in zone file using dnspython? | 38,374,753 | <p>I am generating zone files for the route-53 hosted zones using boto3 and dnspython library.I am succesfully able to generate A/CNAME/MX/TXT Record Sets using <strong>dnspython library(1.14.0)</strong>.
However ,since it does not have any implementation of ALIAS TARGET (A Record).I am getting this error:</p>
<pre><c... | 0 | 2016-07-14T12:51:33Z | 38,581,378 | <p>You are right that the AWS "Alias" record is not a standard DNS record type. </p>
<p>If you are trying to generate a plain standard DNS zone file using records in the Route53 hosted zone, the closest standard record type would be a CNAME record. However, your generated zone file will not behave exactly the same way... | 0 | 2016-07-26T05:05:46Z | [
"python",
"dns",
"amazon-route53",
"boto3",
"dnspython"
] |
Invalid Syntax in print | 38,374,785 | <pre><code>print("inventory[", start,":", finish, "] is", end=" ")
</code></pre>
<p>This line of code has my program stuck. It didn't like the spacing so I eliminated it and now it is flagging the colon as invalid syntax. It is straight from my textbook and is a lesson about slicing lists. What am I missing?</p>
| 0 | 2016-07-14T12:52:35Z | 38,375,365 | <p>For me this code works perfectly if <code>start</code> and <code>finish</code> have been defined.</p>
<p>This error can originate from a SyntaxError in the line before the print. Most certainly you are missing a parens or a bracket.</p>
<p>As an example consider the following code:</p>
<pre><code>print(42 # closi... | 1 | 2016-07-14T13:17:59Z | [
"python",
"list",
"python-3.x",
"slice"
] |
Pandas and matplotlib not showing proper dates as Index, title issue and app crashes | 38,374,897 | <p>My code used to generate a graph based on a CSV is not working as expected.
The first issue is that if I run the code straightfrom the IDLE to generate the graph it works, but if I just run the script.py python app craches.
The second is, the dates are not showing the correct format (format is DD-MM-YYYY) or not sh... | 0 | 2016-07-14T12:57:38Z | 38,375,085 | <p>To answer a couple of your questions:</p>
<p>Pandas automatically uses the best date format for you. You have a couple of month of data so it chooses the date format you see. Also as all plots share the same dates, so the dates are only shown in the lowest graph only.</p>
<p>To get rid of the extra space, remove t... | 0 | 2016-07-14T13:05:58Z | [
"python",
"pandas",
"matplotlib"
] |
Converted value of a int variable to string and assigning it to a new variable is becomes zero | 38,374,924 | <p>I've written a python module which gets the count of records available in a file and stores it into a variable. Later I need this value to be converted to string and compare with a user supplied value. Surprisingly, the int converted to string using python str() function is becoming zero. Could someone let me know h... | -2 | 2016-07-14T12:58:52Z | 38,375,036 | <p>On Unix, the return value of os.system is the exit status of the process, so 0 means the process exited without errors. You should use something like the example below:</p>
<pre><code>proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
tmp = proc.stdout.read()
</code></pre>
| 2 | 2016-07-14T13:04:09Z | [
"python",
"string"
] |
grabbing the api dictionary json with python | 38,375,023 | <p>I was following this tutorial on api grabbing with python:</p>
<p><a href="https://www.youtube.com/watch?v=pxofwuWTs7c" rel="nofollow">https://www.youtube.com/watch?v=pxofwuWTs7c</a></p>
<p>The url gives:</p>
<pre><code>{"date":"1468500743","ticker":{"buy":"27.96","high":"28.09","last":"27.97","low":"27.69","sell... | 0 | 2016-07-14T13:03:30Z | 38,375,166 | <p>I think you just misread the payload returned by the server. In this case the <code>ticker</code> key is not of type <code>list</code> in the dictionary converted by the <code>json</code> module.</p>
<p>So You should do the following</p>
<pre><code>import urllib2
import json
url = 'https://www.okcoin.cn/api/v1/ti... | 4 | 2016-07-14T13:09:54Z | [
"python"
] |
Sample orientation in the class, clustered by k-means in Python | 38,375,062 | <p>I've got some clustered classes, and a sample with a prediction. Now, i want to know the "orientation" of the sample, which varies from 0 to 1, where 0 - right in the class center, 1 - right on the class border(radius). I guess, it's going to be</p>
<p><code>orientation=dist_from_center/class_radius</code></p>
<p>... | 0 | 2016-07-14T13:04:52Z | 38,375,229 | <p>The way you're defining the orientation to us seems like you've got the right idea. If you use the farthest distance from the center as the denominator, then you'll get 0 as your minimum (cluster center) and 1 as your maximum (the farthest distance) and a linear distance in-between.</p>
| 1 | 2016-07-14T13:12:36Z | [
"python",
"scikit-learn",
"k-means"
] |
regex in python: how to use variable string in pattern? | 38,375,234 | <p>I can match a string from a list of string, like this:</p>
<pre><code>keys = ['a', 'b', 'c']
for key in keys:
if re.search(key, line):
break
</code></pre>
<p>the problem is that I would like to match a pattern made from regular expression + string that I would specify. Something like this:</p>
<pre><co... | 0 | 2016-07-14T13:12:43Z | 38,375,470 | <pre><code>re.search('\['+re.escape(key)+']', line):
</code></pre>
<p>this will match <code>[key]</code>. Note that <code>re.escape</code> was added to prevent that characters within <code>key</code> are interpreted as regex.</p>
| 1 | 2016-07-14T13:22:40Z | [
"python",
"regex"
] |
Performance of numpy.random.choice | 38,375,321 | <p><strong><em>I updated the code and the timings.</em></strong></p>
<p>I'm trying to improve the performance of a function in my code. I must generate a list with random elements. However, different parts of the list must be filled with elements taken from different sets. An example of the code is below. I must gener... | 1 | 2016-07-14T13:16:08Z | 38,376,220 | <p>That <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html" rel="nofollow"><code>np.random.choice</code></a> with its optional argument <code>replace</code> being set as <code>True</code> returns randomly chosen elements from the input array and the elements could be repeated. We ... | 1 | 2016-07-14T13:56:53Z | [
"python",
"performance",
"numpy"
] |
Create a 2D array (3D plot) from two 1D arrays (2D plots) in Python (for calculating the Hilbert spectrum) | 38,375,414 | <p>I would like to calculate the <a href="https://en.wikipedia.org/wiki/Hilbert%E2%80%93Huang_transform" rel="nofollow">Hilbert spectrum</a> as a 3D plot (i.e. 2D array) in Python. The Hilbert spectrum is a function of the form <code>time x frequency -> amplitude</code> which assigns each time and frequency pair an ... | 1 | 2016-07-14T13:20:19Z | 38,431,151 | <p>following: <a href="http://matplotlib.org/examples/mplot3d/trisurf3d_demo2.html" rel="nofollow">http://matplotlib.org/examples/mplot3d/trisurf3d_demo2.html</a></p>
<pre><code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.tri as mtri
a_x = [1,2,3]
a_y1 = [1,2,1]
a_y2 = [4... | 0 | 2016-07-18T07:44:08Z | [
"python",
"numpy",
"spectrum"
] |
cannot use graph.data() in neo4j v3 | 38,375,472 | <p>I am trying to run the code:</p>
<pre><code>from py2neo import Graph
graph = Graph(config['DATABASE']['ENDPOINT'])
graph.data("MATCH (u:Users) return u.id, u.email LIMIT 4")
</code></pre>
<p>however I get the error message: </p>
<pre><code>AttributeError: 'Graph' object has no attribute 'data'
</code></pre>
<p>T... | 0 | 2016-07-14T13:22:44Z | 38,375,889 | <p>I suppose you are not on the version 3 of py2neo, try to upgrade : </p>
<pre><code>pip install py2neo --upgrade
</code></pre>
<p>This simple script works fine :</p>
<pre><code>from py2neo import Graph
graph = Graph(host="localhost")
d = graph.data("MATCH (t:TwitterAccount) RETURN t.user_screen_name LIMIT 4")
pri... | 1 | 2016-07-14T13:42:13Z | [
"python",
"neo4j",
"py2neo"
] |
cannot use graph.data() in neo4j v3 | 38,375,472 | <p>I am trying to run the code:</p>
<pre><code>from py2neo import Graph
graph = Graph(config['DATABASE']['ENDPOINT'])
graph.data("MATCH (u:Users) return u.id, u.email LIMIT 4")
</code></pre>
<p>however I get the error message: </p>
<pre><code>AttributeError: 'Graph' object has no attribute 'data'
</code></pre>
<p>T... | 0 | 2016-07-14T13:22:44Z | 38,390,353 | <p><code>Graph.data</code> was added in 3.1.1. If you don't have that, it won't be available.</p>
| 0 | 2016-07-15T07:31:46Z | [
"python",
"neo4j",
"py2neo"
] |
'str' object has no attribute | 38,375,551 | <p>I'm trying to open a column in excel and move all the values from it's cells into a list. </p>
<pre><code>def open_excel(col, excel_file):
open_file = openpyxl.load_workbook(excel_file)
sheet_object = open_file.get_sheet_names()[0]
cell_vals = []
col_num = column_index_from_string(start_col)
for ce... | -2 | 2016-07-14T13:26:33Z | 38,375,606 | <p>You have a <em>sheet name</em>, a string object, assigned to <code>sheet_object</code>:</p>
<pre><code>sheet_object = open_file.get_sheet_names()[0]
</code></pre>
<p><code>get_sheet_names()</code> returns a sequence of strings, not of objects; it just returns <a href="https://openpyxl.readthedocs.io/en/default/api... | 2 | 2016-07-14T13:29:18Z | [
"python",
"excel",
"attributeerror",
"strerror"
] |
Can't download image through python script | 38,375,558 | <p>I have written a script to download a single image from xkcd comics website. But the script normally runs and don't download any image. What's the problem ? Any help would be appreciated. Here's the code:</p>
<pre><code>#! python3
import requests, os, bs4
url = 'http://xkcd.com' # starting rule
os.makedirs('xkcd... | -4 | 2016-07-14T13:26:54Z | 38,376,069 | <p>Your problem is that you save the image in your exception block, un-indent that. Simpler way of downloading file object is to use shutil.</p>
<pre><code>import requests, os, bs4, shutil
url = 'http://xkcd.com' # starting rule
if not os.path.exists('xkcd'):
os.makedirs('xkcd') # store comics in ./xkcd
# Do... | 0 | 2016-07-14T13:50:27Z | [
"python",
"beautifulsoup"
] |
python "ImportError: No module named xyz" on shared hosting | 38,375,698 | <p>Similar questions have been asked on SO, I tried to follow their solution but so far no success.
I have downloaded gspread from <a href="https://github.com/burnash/gspread" rel="nofollow">here</a> to use it in my project. </p>
<ul>
<li>Locally in mac + eclipse + pydev everything works fine. </li>
<li><p>When I cop... | 0 | 2016-07-14T13:33:36Z | 38,409,679 | <p>Thanks to the comments, installing pip and then installing gspread using pip solved the problem. </p>
<pre><code>pip install gspread
</code></pre>
<p>The command above is mentioned in the <a href="https://github.com/burnash/gspread" rel="nofollow">gspread documentation</a>.</p>
| 0 | 2016-07-16T09:27:35Z | [
"python",
"python-import"
] |
Django Call method in template and use the return (,,) | 38,375,716 | <p>I Guys,
I begin with Django, I would like an object to return its statistics and displays them directly in the HTML template.
For that, my object method. get_stat (self) returns a list and 3 dictionary.
How can I use these data returned? I can see the array in the method call {{}} I can not use them in {% %} and us... | 0 | 2016-07-14T13:34:31Z | 38,377,003 | <p>get_stat(self) should return a dictionary {"list_1":[2, 1, 0, 1, 0], "dict_1":{'Cours xy': 1}} and then you can do:</p>
<pre><code>{% for adviser in advisers %}
{% with ad_stat=adviser.get_stat %}
{{ad_stat.list_1}}
{{ad_stat.dict_1}}
....
{% endfor %}
{% endfor %}
</code></pre>
<p>Is t... | 0 | 2016-07-14T14:31:59Z | [
"python",
"django",
"templates"
] |
Django Call method in template and use the return (,,) | 38,375,716 | <p>I Guys,
I begin with Django, I would like an object to return its statistics and displays them directly in the HTML template.
For that, my object method. get_stat (self) returns a list and 3 dictionary.
How can I use these data returned? I can see the array in the method call {{}} I can not use them in {% %} and us... | 0 | 2016-07-14T13:34:31Z | 38,377,347 | <p>Define your method <code>get_stat</code> as a property to call it in template:</p>
<pre><code>class Adviser(models.Model):
TYPES_CHOICES = (('PRF', _('Professor')),
('MGR', _('Manager')),)
@property
def get_stat(self):
some queries to create tables
return (list_stat1,tab_st... | 0 | 2016-07-14T14:47:55Z | [
"python",
"django",
"templates"
] |
Pythonic way of closing range after last iteration | 38,375,925 | <p>I have a code style problem and I'm looking for a pythonic implementation of what I wrote below.</p>
<p>The (simplified) code I posted iterates through a sequence and returns ranges. Each range starts and ends with a specific condition. Ranges cannot be overlapping. I'm using a variable <code>active</code> to track... | 3 | 2016-07-14T13:44:01Z | 38,376,208 | <p>Simple way to it is to edit the inner condition:</p>
<pre><code> condition2 = i % 13 == 0
if active and (condition2 or i == input_length-1))
active = False
# do some additional calculations...
results.append((start, i if condition2 else i + 1))
</code></pre>
<p>and remove the outer.<... | 1 | 2016-07-14T13:56:24Z | [
"python",
"python-3.x",
"iteration"
] |
Pythonic way of closing range after last iteration | 38,375,925 | <p>I have a code style problem and I'm looking for a pythonic implementation of what I wrote below.</p>
<p>The (simplified) code I posted iterates through a sequence and returns ranges. Each range starts and ends with a specific condition. Ranges cannot be overlapping. I'm using a variable <code>active</code> to track... | 3 | 2016-07-14T13:44:01Z | 38,390,962 | <p>I found a nice way how to do that:</p>
<pre><code>import itertools as it
il = 100
results = []
def fun1():
active = False
start = None
for i in range(il):
condition = i % 9 == 0
if not active and condition:
active = True
start = i
condition2 = i % 13 == 0... | 0 | 2016-07-15T08:04:13Z | [
"python",
"python-3.x",
"iteration"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.