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 |
|---|---|---|---|---|---|---|---|---|---|
Timer without threading in python? | 38,583,559 | <p>I am new to programming and would like to add a counter that deducts 1 from your score every two seconds. (so that I have to answer quickly to make my score increase)</p>
<pre><code>chr
import random
import time
radians2 = None
ans = None
score = 0
radians1 = ['0', 'Ï/6', 'Ï/3', 'Ï/4', 'Ï/2', '2Ï/3', '3Ï/4',... | 3 | 2016-07-26T07:25:12Z | 38,583,976 | <p>You can use a corutine if you dont want to use any thread, each time you call the next method of the generator it will yield the elapsed time:</p>
<pre><code>def timer():
prev_time = new_time = 0
while True:
prev_time, new_time = new_time, time.clock()
time_delta = new_time - prev_time
... | 1 | 2016-07-26T07:48:57Z | [
"python",
"multithreading"
] |
Issue while running interactive GUI with xlwings | 38,583,603 | <p>I have built a GUI (with PyQt5) which allow me to read an CSV, made some basic actions and send it to Excel.</p>
<p>Then, I integrated this GUI into Excel using xlwings but I have a problem. When I am using the GUI, I can't manipulate the data in Excel. I assume it's because my macro is still running. </p>
<p>Is t... | 0 | 2016-07-26T07:27:32Z | 38,845,651 | <p>Finaly I got a solution.</p>
<p>I modify the ExecuteWindows sub to add an optional argument like this :</p>
<pre><code>Sub ExecuteWindows(IsFrozen As Boolean, PythonCommand As String, PYTHON_WIN As String, LOG_FILE As String, SHOW_LOG As Boolean, Optional PYTHONPATH As String, Optional WaitOnReturnBool As Boolean)... | 0 | 2016-08-09T08:28:08Z | [
"python",
"xlwings"
] |
Python - read json object over TCP connection (using regex?) | 38,583,622 | <p>My client sends json objects over TCP. Each object is with the following form:</p>
<pre><code>{
"message" => "{\"timestamp\":\"2016-07-21T01:20:04.392799-0400\",\"in_iface\":\"docker0\",\"event_type\":\"alert\",\"src_ip\":\"172.17.0.2\",\"dest_ip\":\"172.17.0.3\",\"proto\":\"ICMP\",\"icmp_type\":0,\"icmp_... | -1 | 2016-07-26T07:28:30Z | 38,584,072 | <p>You may use the <a href="https://docs.python.org/2/library/socketserver.html" rel="nofollow">SocketServer</a> package. The documentation gives small examples which may be useful for you. Here is an extended example for a tcp server:</p>
<pre><code>import SocketServer
import os
import logging
import json
FORMAT = '... | 0 | 2016-07-26T07:54:12Z | [
"python",
"json",
"tcp"
] |
Python - read json object over TCP connection (using regex?) | 38,583,622 | <p>My client sends json objects over TCP. Each object is with the following form:</p>
<pre><code>{
"message" => "{\"timestamp\":\"2016-07-21T01:20:04.392799-0400\",\"in_iface\":\"docker0\",\"event_type\":\"alert\",\"src_ip\":\"172.17.0.2\",\"dest_ip\":\"172.17.0.3\",\"proto\":\"ICMP\",\"icmp_type\":0,\"icmp_... | -1 | 2016-07-26T07:28:30Z | 38,584,095 | <p>You can use flaskRESTful. Feel free to dig into the docs: <a href="http://flask-restful-cn.readthedocs.io/en/0.3.4/" rel="nofollow">http://flask-restful-cn.readthedocs.io/en/0.3.4/</a></p>
<p>Especially the full example gives you enough information to achieve your goal: (<a href="http://flask-restful-cn.readthedocs... | 0 | 2016-07-26T07:55:12Z | [
"python",
"json",
"tcp"
] |
Python: Is it possible for an object to change itself to something else? | 38,583,694 | <pre><code>class Myclass(object):
def get_val(self):
return 100
my_obj = MyClass()
data = {
'key_1': my_obj,
... # other fields
}
</code></pre>
<p>Later I need to change the object to it's value, I could only iterate the dictionary like this, maybe recursively:</p>
<pre><code>for key in data:
... | -2 | 2016-07-26T07:33:27Z | 38,584,300 | <p>Objects cannot replace any/all references of themselves with something else. Period.</p>
<p>However if you need to have a dictionary of pointer objects (have some form of <code>.get()</code> method to return the actual data) then just overriding the <code>__getitem__</code> method of a <code>dict</code> subclass wi... | 0 | 2016-07-26T08:04:58Z | [
"python",
"pointers",
"reference"
] |
get descriptive statistics of numpy ndarray | 38,583,738 | <p>I use the following code to create a numpy-ndarray. The file has 9 columns. I explicitly type each column:</p>
<pre><code>dataset = np.genfromtxt("data.csv", delimiter=",",dtype=('|S1', float, float,float,float,float,float,float,int))
</code></pre>
<p>Now I would like to get some descriptive statistics for each co... | 1 | 2016-07-26T07:36:14Z | 38,584,483 | <p>This is not a pretty solution, but it get the job done. The problem is that by specifying multiple dtypes, you are essentially making a 1D-array of tuples (actually <code>np.void</code>), which cannot be described by stats as it includes multiple different types, incl. strings.</p>
<p>This could be resolved by eith... | 1 | 2016-07-26T08:14:33Z | [
"python",
"numpy",
"multidimensional-array",
"scipy"
] |
get descriptive statistics of numpy ndarray | 38,583,738 | <p>I use the following code to create a numpy-ndarray. The file has 9 columns. I explicitly type each column:</p>
<pre><code>dataset = np.genfromtxt("data.csv", delimiter=",",dtype=('|S1', float, float,float,float,float,float,float,int))
</code></pre>
<p>Now I would like to get some descriptive statistics for each co... | 1 | 2016-07-26T07:36:14Z | 38,595,905 | <p>The question of how to deal with mixed data from <code>genfromtxt</code> comes up often. People expect a 2d array, and instead get a 1d that they can't index by column. That's because they get a structured array - with different dtype for each column.</p>
<p>All the examples in the <code>genfromtxt</code> doc sho... | 1 | 2016-07-26T17:01:57Z | [
"python",
"numpy",
"multidimensional-array",
"scipy"
] |
How to get notified the latest recv in socket(python) | 38,583,806 | <pre><code>sock.setblocking(0)
ready = select.select([sock], [], [], timeout)
try:
if ready[0]:
status = sock.recv(1024)
return status
else:
print "Time out Occured, Disconnecting..."
</code></pre>
<p>I have socket receive function which receives whenever some status gets changed in cli... | 2 | 2016-07-26T07:40:34Z | 38,784,634 | <p>If you need background IO, spawning a new thread to handle IO is probably the easiest method:</p>
<pre><code>import socket
import threading
import queue
class ClientReceiver(threading.Thread):
RECV_BUF_SIZE = 1024
QUEUE_SIZE = 2
def __init__(self, sock, recv_buf_size=None, queue_size=None, *args, **kw... | 0 | 2016-08-05T08:27:30Z | [
"python"
] |
Displaying array values in contour plots | 38,583,863 | <p>I have an array A which contains values that I plot using X and Y as the coordinate axes, using</p>
<pre><code>plt.contourf(X,Y,A)
</code></pre>
<p>I'd like to know how I could obtain the values of A when I hover my cursor over a certain (X,Y) point in the plot, or any other alternative to this where I could obtai... | 0 | 2016-07-26T07:43:32Z | 38,584,474 | <p>You have to use <code>format_coord</code> property of axis object:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = np.arange(25).reshape(5,5)
X = np.arange(5)
Y = np.arange(5)
X,Y = np.meshgrid(X,Y)
plt.contourf(X,Y,A)
nrows, ncols = A.shape
def f... | 1 | 2016-07-26T08:13:56Z | [
"python",
"numpy",
"matplotlib"
] |
Hierarchical foreign key selector in Django admin | 38,583,865 | <p>Let's say I have some models like this:</p>
<pre><code>class Country(models.Model):
name = models.TextField()
class City(models.Model):
country = models.ForeignKey(Country)
name = models.TextField()
class Person(models.Model):
city = models.ForeignKey(City)
name = models.TextField()
</code></p... | 0 | 2016-07-26T07:43:36Z | 38,585,119 | <p>ya it is possible to do if you create a page of your own, load one country and its states by default, then if you select a country do a ajax call to repopulate the cities, i will suggest angular js for the same.</p>
| 0 | 2016-07-26T08:48:11Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Hierarchical foreign key selector in Django admin | 38,583,865 | <p>Let's say I have some models like this:</p>
<pre><code>class Country(models.Model):
name = models.TextField()
class City(models.Model):
country = models.ForeignKey(Country)
name = models.TextField()
class Person(models.Model):
city = models.ForeignKey(City)
name = models.TextField()
</code></p... | 0 | 2016-07-26T07:43:36Z | 38,585,341 | <p>It is possible, but not out of the box.</p>
<p>You'll have to make and ajax request after the user selects the country to fetch the cities related to that country and so on.</p>
<p>You will need a view on django that returns the cities given a country in a format that makes it easy to parse on javascript or build ... | 0 | 2016-07-26T08:57:27Z | [
"python",
"django",
"django-models",
"django-admin"
] |
python pandas-how to apply function according to another column's value | 38,583,896 | <p>I've got a DataFrame like the image:</p>
<p><a href="http://i.stack.imgur.com/sdmgt.png" rel="nofollow"><img src="http://i.stack.imgur.com/sdmgt.png" alt="enter image description here"></a></p>
<p>I need to add another column to DataFrame to calculate the "gram" for every product,according to diffierent Unit of th... | -1 | 2016-07-26T07:45:13Z | 38,584,021 | <p>IIUC if in column <code>UNIT</code> are only <code>lb</code> and <code>oz</code> use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>
<pre><code>df['gram'] = np.where(df.UNIT == 'lb', df.number / 0.0022046, df.number / 0.035274)
<... | 1 | 2016-07-26T07:51:31Z | [
"python",
"pandas"
] |
How to access the second site (site_id = 2) from Django | 38,583,947 | <p>I have a project in Django that is monitoring some licenses. For this project, SITE_ID is 1 and domain name is by default <strong>example.com</strong>.</p>
<p>If I create another domain name and I want to make another project that is using that domain, How can I access that site?</p>
<p>In browser how I can access... | 1 | 2016-07-26T07:47:36Z | 38,591,294 | <p>The domain name is just indicative here, if you launched your first site on 127.0.0.1:8080 (with <code>python manage.py runserver 127.0.0.1:8080</code>, you can, for instance, launch the second on <code>127.0.0.1:4242</code>. However it maybe advisable to launch it on another IP address (or domain name) to avoid sha... | 0 | 2016-07-26T13:31:04Z | [
"python",
"django",
"django-admin",
"django-cms",
"django-settings"
] |
Pandas : remove SOME duplicate values based on conditions | 38,584,061 | <p>I have a dataset :</p>
<pre><code>id url keep_if_dup
1 A.com Yes
2 A.com Yes
3 B.com No
4 B.com No
5 C.com No
</code></pre>
<p>I want to remove duplicates, i.e. keep first occurence of "url" field, <strong>BUT</strong> keep duplicates if the field "keep_if_dup" is YES.</p>
<p>... | 3 | 2016-07-26T07:53:50Z | 38,584,174 | <p>You can pass multiple boolean conditions to <code>loc</code>, the first keeps all rows where col 'keep_if_dup' == 'Yes', this is <code>or</code>ed (using <code>|</code>) with the inverted boolean mask of whether col 'url' column is duplicated or not:</p>
<pre><code>In [79]:
df.loc[(df['keep_if_dup'] =='Yes') | ~df[... | 3 | 2016-07-26T07:58:43Z | [
"python",
"pandas",
"duplicates"
] |
What version of âunittest2â is needed for Python 3.4 features? | 38,584,080 | <p>What version of the <code>unittest2</code> library do I need for the <a href="https://docs.python.org/3.4/whatsnew/3.4.html#unittest" rel="nofollow">new features in Python 3.4's <code>unittest</code></a>?</p>
<p>The third-party <a href="https://pypi.python.org/pypi/unittest2/" rel="nofollow"><code>unittest2</code> ... | 1 | 2016-07-26T07:54:30Z | 38,695,321 | <p>I've done a bit of digging in the repository, and it looks like:</p>
<ul>
<li><p>Subtests were added in 0.6.0 (<a href="https://hg.python.org/unittest2/rev/0daffa9ee7c1" rel="nofollow">this commit</a>)</p></li>
<li><p>SkipTest was added in 0.6.0 (<a href="https://hg.python.org/unittest2/rev/f0946b0ba890" rel="nofol... | 0 | 2016-08-01T09:27:47Z | [
"python",
"python-2.7",
"python-unittest",
"backport"
] |
Imputer on some Dataframe columns in Python | 38,584,184 | <p>I am learning how to use Imputer on Python.</p>
<p>This is my code:</p>
<pre><code>df=pd.DataFrame([["XXL", 8, "black", "class 1", 22],
["L", np.nan, "gray", "class 2", 20],
["XL", 10, "blue", "class 2", 19],
["M", np.nan, "orange", "class 1", 17],
["M", 11, "green", "class 3", np.nan],
["M", 7, "red", "class 1", ... | 1 | 2016-07-26T07:59:20Z | 38,584,568 | <p>I think you want to specify the axis for the imputer, then transpose the array it returns:</p>
<pre><code>import pandas as pd
import numpy as np
df=pd.DataFrame([["XXL", 8, "black", "class 1", 22],
["L", np.nan, "gray", "class 2", 20],
["XL", 10, "blue", "class 2", 19],
["M", np.nan, "orange", "class 1", 17],
["M"... | 0 | 2016-07-26T08:20:18Z | [
"python",
"scikit-learn",
"missing-data"
] |
Imputer on some Dataframe columns in Python | 38,584,184 | <p>I am learning how to use Imputer on Python.</p>
<p>This is my code:</p>
<pre><code>df=pd.DataFrame([["XXL", 8, "black", "class 1", 22],
["L", np.nan, "gray", "class 2", 20],
["XL", 10, "blue", "class 2", 19],
["M", np.nan, "orange", "class 1", 17],
["M", 11, "green", "class 3", np.nan],
["M", 7, "red", "class 1", ... | 1 | 2016-07-26T07:59:20Z | 38,587,837 | <p>This is because <code>Imputer</code> usually uses with DataFrames rather than Series. A possible solution is:</p>
<pre><code>imp=Imputer(missing_values="NaN", strategy="mean" )
imp.fit(df[["price"]])
df["price"]=imp.transform(df[["price"]]).ravel()
# Or even
imp=Imputer(missing_values="NaN", strategy="mean" )
df[... | 0 | 2016-07-26T10:49:45Z | [
"python",
"scikit-learn",
"missing-data"
] |
Manipulating csv data file using python | 38,584,365 | <p>I want to work with data of NBA. That is why I have to make comparison. I need to get home win percentage. However it cannot convert string to int.</p>
<pre><code>results["HomeWin"]=int(results["Home Team"])<int(results["OT?"])
y_true=results["HomeWin"].values
print("Home win percentage is{0:.1f}%".format(100*re... | 0 | 2016-07-26T08:08:41Z | 38,584,396 | <p>You need cast by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>Series.astype</code></a> <code>string</code> numbers to <code>int</code>:</p>
<pre><code>results["HomeWin"] = results["Home Team"].astype(int) < results["OT?"].astype(int)
</code></pre>... | 1 | 2016-07-26T08:09:58Z | [
"python",
"csv",
"pandas"
] |
Python generator to read large CSV file | 38,584,494 | <p>I need to write a Python generator that yields tuples (X, Y) coming from two different CSV files. </p>
<p>It should receive a batch size on init, read line after line from the two CSVs, yield a tuple (X, Y) for each line, where X and Y are arrays (the columns of the CSV files).</p>
<p>I've looked at examples of la... | 0 | 2016-07-26T08:15:13Z | 38,584,783 | <p>You can have a generator, that reads lines from two different csv readers and yield their lines as pairs of arrays. The code for that is:</p>
<pre><code>import csv
import numpy as np
def getData(filename1, filename2):
with open(filename1, "rb") as csv1, open(filename2, "rb") as csv2:
reader1 = csv.read... | 1 | 2016-07-26T08:31:32Z | [
"python",
"csv",
"numpy",
"bigdata"
] |
Customizing the QScrollbar in PyQt | 38,584,550 | <p>Usually the default QScrollBar's from PyQt are too small for high dpi displays. That's why it can be necessary to adjust them. And once you're doing it anyway, why not take benefit from the aesthetic improvements you can make?</p>
<p>This is how you can tweak the 'look and feel' of your QScrollBar:</p>
<pre><code>... | 0 | 2016-07-26T08:18:59Z | 38,607,016 | <p>I don't know how to use style sheets achieve it.</p>
<p>I created three qss files.</p>
<p>a.qss </p>
<pre><code> QScrollBar:vertical{
background: black;
width: 10px;
}
</code></pre>
<p>b.qss</p>
<pre><code> QScrollBar:vertical{
background: black;
width: 10px;
}
QScrollBar::add-page:verti... | 1 | 2016-07-27T07:54:10Z | [
"python",
"qt",
"pyqt",
"pyqt5"
] |
Pandas SQL equivalent of update where group by | 38,584,710 | <p>Despite looking for this, I cannot find the correct way to get an equivalent of this query working in pandas.</p>
<pre><code>update product
set maxrating = (select max(rating)
from rating
where source = 'customer'
and product.sku = rating.sku
... | 3 | 2016-07-26T08:28:21Z | 38,585,458 | <p>You can do the following :</p>
<pre><code>In [127]: df = pd.merge(rating, product, on='sku')
In [128]: df1 = df[df['maxrating'] == 0].groupby('sku').agg({'rating': np.max}).reset_index().rename(columns={'rating': 'maxrating'})
In [129]: df2 = df[df['maxrating'] != 0][['sku', 'maxrating']].drop_duplicates(keep='fi... | 1 | 2016-07-26T09:02:15Z | [
"python",
"sql",
"pandas",
"dataframe"
] |
Pandas SQL equivalent of update where group by | 38,584,710 | <p>Despite looking for this, I cannot find the correct way to get an equivalent of this query working in pandas.</p>
<pre><code>update product
set maxrating = (select max(rating)
from rating
where source = 'customer'
and product.sku = rating.sku
... | 3 | 2016-07-26T08:28:21Z | 38,585,530 | <h3>All together</h3>
<pre><code>product.maxrating = product.maxrating.replace(0, np.nan)
missing = product.loc[product.maxrating.isnull(), 'sku']
missingmax = rating.groupby(missing, as_index=False).rating.agg({'maxrating': 'max'})
product.update(missingmax)
</code></pre>
<p>First, let's start with nulls instead of ... | 3 | 2016-07-26T09:05:14Z | [
"python",
"sql",
"pandas",
"dataframe"
] |
Pandas SQL equivalent of update where group by | 38,584,710 | <p>Despite looking for this, I cannot find the correct way to get an equivalent of this query working in pandas.</p>
<pre><code>update product
set maxrating = (select max(rating)
from rating
where source = 'customer'
and product.sku = rating.sku
... | 3 | 2016-07-26T08:28:21Z | 38,585,600 | <p>try this:</p>
<pre><code>In [220]: product.ix[product.maxrating == 0, 'maxrating'] = product.sku.map(rating.groupby('sku')['rating'].max())
In [221]: product
Out[221]:
maxrating sku
0 5 1
1 3 2
2 1 3
</code></pre>
<p>or using common mask:</p>
<pre><code>In [222]: mask = (p... | 4 | 2016-07-26T09:08:10Z | [
"python",
"sql",
"pandas",
"dataframe"
] |
Python, Requests Session, HTML head not showing | 38,584,769 | <p>I am playing with the requests module in python and I am stuck with a problem. </p>
<p>I use requests to login on a website (<a href="http://coinplants.com" rel="nofollow">http://coinplants.com</a>) using the Session class. After the login I am trying to read the html of the page and I realized that the response ob... | 0 | 2016-07-26T08:30:54Z | 38,584,907 | <p>Print out the req.url which is getting and then try to scrap that url using get. </p>
<pre><code>url = r.url
req = s.get(url)
print req.text
</code></pre>
<p>See is it resolving your issue or not. If not then go to the r.url in browser and inspect the element using whatever browser you are comfortable and see whet... | -1 | 2016-07-26T08:37:23Z | [
"python",
"html",
"python-requests"
] |
Python, Requests Session, HTML head not showing | 38,584,769 | <p>I am playing with the requests module in python and I am stuck with a problem. </p>
<p>I use requests to login on a website (<a href="http://coinplants.com" rel="nofollow">http://coinplants.com</a>) using the Session class. After the login I am trying to read the html of the page and I realized that the response ob... | 0 | 2016-07-26T08:30:54Z | 38,585,170 | <p>When i understand you right you are looking for the headers of the page. </p>
<p>when you type</p>
<p><code>print r.headers</code></p>
<p>you should get the headers of the page. </p>
<p>Or did i understand your question wrong? </p>
<p>This page is very helpfull to learn more about the request module.
<a href="... | 0 | 2016-07-26T08:50:29Z | [
"python",
"html",
"python-requests"
] |
SVC (support vector classification) with categorical (string) data as labels | 38,584,829 | <p>I use <code>scikit-learn</code> to implement a simple supervised learning algorithm. In essence I follow the tutorial <a href="http://scikit-learn.org/stable/tutorial/basic/tutorial.html#learning-and-predicting" rel="nofollow">here</a> (but with my own data).</p>
<p>I try to fit the model:</p>
<pre><code>clf = svm... | 1 | 2016-07-26T08:33:49Z | 38,586,533 | <p>you can try this code:</p>
<pre><code>from sklearn import svm
X = [[0, 0], [1, 1],[2,3]]
y = ['A', 'B','C']
clf = svm.SVC(gamma=0.001, C=100.)
clf.fit(X, y)
clf.predict([[2,3]])
</code></pre>
<p>output:
array(['C'],
dtype='|S1')</p>
<p>You should take the dependent variable (y) as 'list'.</p>
| 0 | 2016-07-26T09:49:53Z | [
"python",
"machine-learning",
"scikit-learn",
"svm"
] |
SVC (support vector classification) with categorical (string) data as labels | 38,584,829 | <p>I use <code>scikit-learn</code> to implement a simple supervised learning algorithm. In essence I follow the tutorial <a href="http://scikit-learn.org/stable/tutorial/basic/tutorial.html#learning-and-predicting" rel="nofollow">here</a> (but with my own data).</p>
<p>I try to fit the model:</p>
<pre><code>clf = svm... | 1 | 2016-07-26T08:33:49Z | 38,589,729 | <p>Take a look at <a href="http://scikit-learn.org/stable/modules/preprocessing.html#encoding-categorical-features" rel="nofollow">http://scikit-learn.org/stable/modules/preprocessing.html#encoding-categorical-features</a> <code>section 4.3.4 Encoding categorical features.</code></p>
<p>In particular, look at using t... | 1 | 2016-07-26T12:18:33Z | [
"python",
"machine-learning",
"scikit-learn",
"svm"
] |
Replace a zero sequence with other value | 38,584,956 | <p>I have a big dataset (> 200k) and I am trying to replace zero sequences with a value. A zero sequence with more than 2 zeros is an artifact and should be removed by setting it to np.NAN.</p>
<p>I have read <a href="http://stackoverflow.com/questions/36522220/searching-a-sequence-in-a-numpy-array">Searching a sequen... | 4 | 2016-07-26T08:39:45Z | 38,585,443 | <p>Well that's basically a <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.binary_closing.html" rel="nofollow"><code>binary closing operation</code></a> with a threshold requirement on the closing gap. Here's an implementation based on it -</p>
<pre><code># Pad with ones so... | 3 | 2016-07-26T09:01:28Z | [
"python",
"numpy"
] |
Replace a zero sequence with other value | 38,584,956 | <p>I have a big dataset (> 200k) and I am trying to replace zero sequences with a value. A zero sequence with more than 2 zeros is an artifact and should be removed by setting it to np.NAN.</p>
<p>I have read <a href="http://stackoverflow.com/questions/36522220/searching-a-sequence-in-a-numpy-array">Searching a sequen... | 4 | 2016-07-26T08:39:45Z | 38,585,721 | <p>Here is a function you can use for your lists:</p>
<pre><code>import numpy as np
def replace(a_list):
for i in xrange(len(a_list) - 2):
print a_list[i:i+3]
if (a_list[i] == 0 and a_list[i+1] == 0 and a_list[i+2] == 0) or (a_list[i] is np.NaN and a_list[i+1] is np.NaN and a_list[i+2] == 0):
... | 1 | 2016-07-26T09:13:33Z | [
"python",
"numpy"
] |
Replace a zero sequence with other value | 38,584,956 | <p>I have a big dataset (> 200k) and I am trying to replace zero sequences with a value. A zero sequence with more than 2 zeros is an artifact and should be removed by setting it to np.NAN.</p>
<p>I have read <a href="http://stackoverflow.com/questions/36522220/searching-a-sequence-in-a-numpy-array">Searching a sequen... | 4 | 2016-07-26T08:39:45Z | 38,585,752 | <p>you could use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow">groupby</a> of the <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow">itertools</a> package</p>
<pre><code>import numpy as np
from itertools import groupby
l = np.array([0, 1, 0, 0, -6, ... | 1 | 2016-07-26T09:15:13Z | [
"python",
"numpy"
] |
Django can't display images saved in media folder | 38,585,001 | <p>I save uploaded files in a media root called /img/:</p>
<pre><code>MEDIA_ROOT = os.path.join(BASE_DIR, 'img')
MEDIA_URL = '/img/'
</code></pre>
<p>And use this template to display every image in that folder:</p>
<pre><code>{% load staticfiles %}
<ul>
{% for post in latest_post %}
<li>{{ post.id }... | 0 | 2016-07-26T08:42:35Z | 38,585,332 | <p>Create a folder in your base directory by the name static and store all your css, img, js etc files in it in their respective folders, like this:</p>
<pre><code>.
âââ css
âââ fonts
âââ icons
âââ img
âââ js
</code></pre>
<p>Run python manage.py collectstatic, this collects all your sta... | 0 | 2016-07-26T08:57:12Z | [
"python",
"django",
"django-templates"
] |
how to keep the leading 0 in Python | 38,585,138 | <p>I'm extracting one number from an XLS file : </p>
<pre><code>var = workBook.sheet_by_index(3).cell_value(4,1)
var = 0136
type(var) = float
</code></pre>
<p>when I'm trying to print the var i got always different results : </p>
<pre><code>print(int(var)) = 136
print(str(var)) = 136.0
</code></pre>
<p>I donât f... | 0 | 2016-07-26T08:49:08Z | 38,585,184 | <p>Try formatting </p>
<pre><code>print('{:04d}'.format(136))
# Returns 0136
</code></pre>
<p>In your case:</p>
<pre><code>var = 136
print('{:04d}'.format(var))
# Returns: 0136
</code></pre>
| 1 | 2016-07-26T08:51:09Z | [
"python"
] |
Preventing application from being closed when a file is open in Python | 38,585,259 | <p>I have a timer based application that might write a short line to a file every 8 hours. The file doesn't stay open for the 8 hour duration, I just open it, write and close it. If it helps, I open the file for writing only, not appending, so the previous data in it doesn't need to be saved.</p>
<p>What would happen ... | 1 | 2016-07-26T08:53:59Z | 38,585,496 | <blockquote>
<p>What would happen if the user closes the application through task
manager while the file is open for writing? </p>
</blockquote>
<p>Unless you have an exit handler for the program, the program would most likely close immediately. If the user terminates the program, it would close instantly.</p>
<b... | 1 | 2016-07-26T09:03:53Z | [
"python",
"file",
"atomic"
] |
Numpy I/O: convert % percentage to float between 0 and 1 | 38,585,336 | <h1>The thing I want to do:</h1>
<p><strong>Convert string representing percentage xx% to a float between 0 and 1</strong></p>
<h1>My code:</h1>
<pre><code>#a. general case
data = "1, 2.3%, 45.\n6, 78.9%, 0"
names = ("i", "p", "n")
a = np.genfromtxt(io.BytesIO(data.encode()), names = names, delimiter = ",")
print (a... | 1 | 2016-07-26T08:57:21Z | 38,585,440 | <p>You can't split a <em>bytes-like</em> object with a <code>str</code> object viz <code>'%'</code>. Append a <code>b</code> to the start of the <em>strip</em> string to make it a bytes object.</p>
<pre><code>convertfunc = lambda x: float(x.strip(b"%"))/100
# ^
b = np.genfromtxt(io... | 1 | 2016-07-26T09:01:14Z | [
"python",
"numpy",
"python-3.5",
"converters"
] |
resample in pandas with the method in a variable | 38,585,417 | <p>Pandas changed its resample API on version 18.1. The reduction methods are no longer a argument to the resample method, but they are their own methods.</p>
<p>Example:</p>
<pre><code>import pandas as pd
import numpy as np
rng = pd.date_range('1/1/2012', periods=100, freq='S')
ts = pd.Series(np.random.randint(0, 5... | 3 | 2016-07-26T09:00:12Z | 38,585,774 | <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.aggregate.html" rel="nofollow"><code>Resampler.agg</code></a>:</p>
<pre><code>print (ts.resample('5Min').agg('sum'))
</code></pre>
<hr>
<pre><code>print (ts.resample('5Min').sum())
2012-01-01 24223
Fr... | 3 | 2016-07-26T09:16:18Z | [
"python",
"datetime",
"pandas",
"dataframe",
"resampling"
] |
resample in pandas with the method in a variable | 38,585,417 | <p>Pandas changed its resample API on version 18.1. The reduction methods are no longer a argument to the resample method, but they are their own methods.</p>
<p>Example:</p>
<pre><code>import pandas as pd
import numpy as np
rng = pd.date_range('1/1/2012', periods=100, freq='S')
ts = pd.Series(np.random.randint(0, 5... | 3 | 2016-07-26T09:00:12Z | 38,586,346 | <p>segregate <code>how</code> and <code>fill_method</code> and pass them through <code>getattr</code>:</p>
<pre><code>def my_func(dummy_df, freq="10Min", how="last",
label="right", closed="right", fill_method="ffill"):
resample = dummy_df.resample(freq, label=label, closed=closed)
return getattr(ge... | 2 | 2016-07-26T09:41:35Z | [
"python",
"datetime",
"pandas",
"dataframe",
"resampling"
] |
ModelMultipleChoiceField CheckboxSelectMultiple Select a valid choice. That choice is not one of the available choices | 38,585,477 | <p>So the problem is that when I try to post data on the server.
The form correctly lists checkboxes. However, when I select something and then submit the form, I'll get the form error:</p>
<pre><code>Select a valid choice. That choice is not one of the available choices
</code></pre>
<p>forms.py</p>
<pre><code>clas... | -1 | 2016-07-26T09:03:06Z | 38,585,753 | <p>The problem is that your field does not match the widget. You are using a <code>ModelChoiceField</code> (for choosing one choice) with <code>CheckboxSelectMultiple</code> widget (for choosing multiple choices).</p>
<p>Since you have a many-to-many field in your models, you want a <a href="https://docs.djangoproject... | 0 | 2016-07-26T09:15:17Z | [
"python",
"django",
"forms"
] |
Replace character only on specific occurrence | 38,585,585 | <p>I have some tab-separated values in a list looking something like this:</p>
<pre><code>A B C|D E F|G|H|I J|K|L M N
1 2 3|4 5 6|7|8|9 1|2|3 4 5
</code></pre>
<p>I want to replace the first occurrence of "|" in the 5th column so that the output becomes</p>
<pre><code>A B... | 0 | 2016-07-26T09:07:33Z | 38,585,668 | <p>One way:</p>
<pre><code>line = 'A\tB\tC|D\tE\tF|G|H|I\tJ|K|L\tM\tN'
columns = line.split('\t')
columns[4] = columns[4].replace("|", "\t", 1)
new_line = '\t'.join(columns)
print(new_line) # Output: A B C|D E F G|H|I J|K|L M N
</code></pre>
| 3 | 2016-07-26T09:11:08Z | [
"python"
] |
Using google cloud datastore emulator with dev_appserver | 38,585,619 | <p>I've been reading between the lines and trying to interface dev_appserver.py with the new 'non-legacy' google cloud datastore emulator.</p>
<p>My main motivation is to integrate my appengine projects with my google cloud dataflow pipeline while I am developing on my local machine.</p>
<p>This is the procedure to s... | 3 | 2016-07-26T09:08:58Z | 38,648,659 | <p>Actually gcloud datastore emulator and dev_appserver points to two different endpoints. the localhost:8000 is the default dev_appserver admin console, while the datastore emulator have a different console url which could be found in print outs when it starts.</p>
<p>I assume the admin console you are accessing belo... | 2 | 2016-07-29T00:17:20Z | [
"python",
"google-app-engine",
"google-cloud-platform",
"google-cloud-datastore"
] |
Using google cloud datastore emulator with dev_appserver | 38,585,619 | <p>I've been reading between the lines and trying to interface dev_appserver.py with the new 'non-legacy' google cloud datastore emulator.</p>
<p>My main motivation is to integrate my appengine projects with my google cloud dataflow pipeline while I am developing on my local machine.</p>
<p>This is the procedure to s... | 3 | 2016-07-26T09:08:58Z | 38,776,485 | <p>We recently ran into this same issue. One thing to look at is the output of the command:</p>
<pre><code>(gcloud beta emulators datastore env-init --no-legacy)
</code></pre>
<p>The problem we had was that when we ran the emulator the emulator was choosing say port 8607 but the env-init method was returning a differ... | 0 | 2016-08-04T20:03:45Z | [
"python",
"google-app-engine",
"google-cloud-platform",
"google-cloud-datastore"
] |
pygame blinking screen fix | 38,585,658 | <p>My code that shows a scoreboard always blinks because of me making the background white. But I want that to stop. So is there a way to make pygame do all this drawing and filling without the display updating, and when the drawing is done it shows the new result so I don't have to see every step and thereby the blink... | 1 | 2016-07-26T09:10:53Z | 38,623,046 | <p>If you have a while loop that displays your window(which i assume you do), then your probably calling either <code>pygame.display.flip()</code> in the loop or <code>pygame.display.update()</code>. So you should not have to call <code>pygame.display.update()</code> in your score function too. Remove the <code>pygame.... | 0 | 2016-07-27T20:57:06Z | [
"python",
"pygame"
] |
Changing a character in a string in python | 38,585,659 | <p>Before reading this question, i would like to post a disclaimer.</p>
<p>I have read that we have functions which can directly replace the character in a string(string.replace),i just want to try the manual method for doing this.</p>
<p>Here's the code that i just wrote.</p>
<pre><code>string = bytearray("abc'defg... | -1 | 2016-07-26T09:10:55Z | 38,588,141 | <p>As others have mentioned there are better ways to do this, but I guess it makes sense as a learning exercise to explore how <code>bytearray</code> works.</p>
<p>Your <code>if</code> tests will never succeed. Those tests assume that a <code>bytearray</code> is an array of single character strings, but that's not cor... | 0 | 2016-07-26T11:04:06Z | [
"python",
"python-3.x",
"bytearray"
] |
Tokenizing in pig (using python udf) | 38,585,671 | <p>Here is what i have done to tokenize in pig,
<strong>My pig script</strong></p>
<pre><code>--set the debugg mode
SET debug 'off'
-- Registering the python udf
REGISTER /home/hema/phd/work1/coding/myudf.py USING streaming_python as myudf
RAWDATA =LOAD '/home/hema/temp' USING TextLoader() AS content;
LOWERCASE_DATA ... | 0 | 2016-07-26T09:11:16Z | 38,591,539 | <p>Use REPLACE for '_' and '|' and then use TOKENIZE for tokens.</p>
<pre><code>NEW_TOKENIZED_DATA =FOREACH TOKENINZED_DATA GENERATE REPLACE(REPLACE($0,'_',''),'|','');
TOKENS = FOREACH NEW_TOKENIZED_DATA GENERATE TOKENIZE($0);
DUMP TOKENS;
</code></pre>
| 0 | 2016-07-26T13:41:22Z | [
"python",
"hadoop",
"apache-pig",
"nltk"
] |
Tokenizing in pig (using python udf) | 38,585,671 | <p>Here is what i have done to tokenize in pig,
<strong>My pig script</strong></p>
<pre><code>--set the debugg mode
SET debug 'off'
-- Registering the python udf
REGISTER /home/hema/phd/work1/coding/myudf.py USING streaming_python as myudf
RAWDATA =LOAD '/home/hema/temp' USING TextLoader() AS content;
LOWERCASE_DATA ... | 0 | 2016-07-26T09:11:16Z | 39,889,761 | <pre><code>from pig_util import outputSchema
import nltk
import re
@outputSchema('word:chararray')
def special_tokenize(input):
#splitting camel-case here
temp_data = re.sub(r'(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])'," ",input)
tokens = nltk.word_tokenize(temp_data.encode('utf-8'))
final_to... | 0 | 2016-10-06T07:14:24Z | [
"python",
"hadoop",
"apache-pig",
"nltk"
] |
Storing entries in a very large database | 38,585,719 | <p>I am writing a Django application that will have entries entered by users of the site. Now suppose that everything goes well, and I get the expected number of visitors (unlikely, but I'm planning for the future). This would result in hundreds of millions of entries in a single PostgreSQL database.</p>
<p>As iterati... | 0 | 2016-07-26T09:13:30Z | 38,587,539 | <p>Store one at a time until you absolutely cannot anymore, then design something else around your specific problem.</p>
<p>SQL is a declarative language, meaning "give me all records matching X" doesn't tell the db server <em>how</em> to do this. Consequently, you have a lot of ways to help the db server do this qui... | 1 | 2016-07-26T10:36:39Z | [
"python",
"django",
"database",
"postgresql",
"saas"
] |
Setting colour scale to log in a contour plot | 38,585,876 | <p>I have an array A which I have plotted in a contour plot using X and Y as coordinate axes,</p>
<pre><code>plt.contourf(X,Y,A)
</code></pre>
<p><a href="http://i.stack.imgur.com/cc1zf.png" rel="nofollow"><img src="http://i.stack.imgur.com/cc1zf.png" alt="Contour plot of A"></a></p>
<p>Problem is, the values in A v... | 1 | 2016-07-26T09:21:56Z | 38,586,157 | <p>A similar question was already asked for log-scaling the colors in a <code>scatter</code> plot: <a href="http://stackoverflow.com/questions/17201172/a-logarithmic-colorbar-in-matplotlib-scatter-plot">A logarithmic colorbar in matplotlib scatter plot</a></p>
<p>As is it was indicated there, there is an article in ma... | 1 | 2016-07-26T09:33:11Z | [
"python",
"matplotlib"
] |
Setting colour scale to log in a contour plot | 38,585,876 | <p>I have an array A which I have plotted in a contour plot using X and Y as coordinate axes,</p>
<pre><code>plt.contourf(X,Y,A)
</code></pre>
<p><a href="http://i.stack.imgur.com/cc1zf.png" rel="nofollow"><img src="http://i.stack.imgur.com/cc1zf.png" alt="Contour plot of A"></a></p>
<p>Problem is, the values in A v... | 1 | 2016-07-26T09:21:56Z | 38,586,222 | <p>You can do this:</p>
<pre><code>from matplotlib import colors
plt.contourf(X, Y, A, norm=colors.LogNorm())
plt.colorbar()
put.show()
</code></pre>
<p>or</p>
<pre><code>from matplotlib import ticker
plt.contourf(X, Y, A, locator=ticker.LogLocator())
plt.colorbar()
put.show()
</code></pre>
| 1 | 2016-07-26T09:36:29Z | [
"python",
"matplotlib"
] |
Django: DateTimeField to string using L10N | 38,586,044 | <p>Using the Django template tags, a DateTimeField will look like this:</p>
<pre><code>July 25, 2016, 7:11 a.m.
</code></pre>
<p>Problem is, my website has an infinite scroll and new data come through AJAX, and so I can't use Django's template tags for that. Using this to get the date:</p>
<pre><code>str(self.date_c... | 0 | 2016-07-26T09:28:34Z | 38,587,385 | <p>Actually you can still use Django's built in <code>date</code> filter for an ajax response. Inside your view utilise the <code>render_to_string</code> then send as json (assuming your js expects json). </p>
<pre><code>import json
from django.template.loader import render_to_string
class YourAjaxResponseView(View):... | 1 | 2016-07-26T10:30:15Z | [
"python",
"django",
"datetime",
"datetime-format"
] |
Django: DateTimeField to string using L10N | 38,586,044 | <p>Using the Django template tags, a DateTimeField will look like this:</p>
<pre><code>July 25, 2016, 7:11 a.m.
</code></pre>
<p>Problem is, my website has an infinite scroll and new data come through AJAX, and so I can't use Django's template tags for that. Using this to get the date:</p>
<pre><code>str(self.date_c... | 0 | 2016-07-26T09:28:34Z | 38,587,584 | <p>You can format field on backend with <code>self.date_created.strftime("%B %d, %Y, %I:%M %p")</code> or you can format it on frontend</p>
<pre><code>var dateCreated = new Date(item.date_created);
dateCreated.toLocaleString()
</code></pre>
| 1 | 2016-07-26T10:38:25Z | [
"python",
"django",
"datetime",
"datetime-format"
] |
Django pre-save signal | 38,586,282 | <p>I have a pre-save signal for one of my models. This pre-save signal does some background API activity to syndicate new and updated objects to service providers and return meaningless data for us to store as references in the places of the original data.</p>
<p>The new and update methods are different in the API.</p... | 0 | 2016-07-26T09:39:03Z | 38,587,225 | <blockquote>
<p>When creating an object, does anything get passed to update_fields?</p>
</blockquote>
<p><a href="https://github.com/django/django/blob/271bfe65d986f5ecbaeb7a70a3092356c0a9e222/django/db/models/query.py#L399" rel="nofollow">No</a>. </p>
<blockquote>
<p>When updating an object, do all fields get pa... | 0 | 2016-07-26T10:22:07Z | [
"python",
"django",
"python-3.x",
"signals",
"django-1.9"
] |
Error- Unable to install flask-mysql | 38,586,296 | <p>I tried installing mysql client for flask i get an error, I am using python 3.4. I have also tried installing mysql using pip install mysql same result.
<code>pip install flask-mysql</code>
If you have any questions please ask me i have also tried upgrading the wheel and setup tools still it produce same result. </... | 0 | 2016-07-26T09:39:35Z | 38,586,511 | <p>Flask-mysql <a href="https://github.com/cyberdelia/flask-mysql/issues/8" rel="nofollow">does not have</a> Python 3 support, see <a href="https://www.reddit.com/r/Python/comments/3ik1w7/flaskmysql_vs_flaskmysqldb/cuhn213" rel="nofollow">here</a>. You can use <a href="https://github.com/admiralobvious/flask-mysqldb" r... | 1 | 2016-07-26T09:49:06Z | [
"python",
"mysql",
"flask"
] |
How to execute an entire Javascript program from within a Python script | 38,586,396 | <p>So I am currently working on a project that involves the google maps API. In order to display data on this, the file needs to be in a geojson format. So far in order to accomplish this, I have been using two programs, 1 in javascript that converts a .json to a CSV, and another that converts a CSV to a geojson file, ... | 0 | 2016-07-26T09:43:50Z | 38,588,135 | <p>While this is not exactly what you are asking for, propably using <a href="https://docs.python.org/3/library/json.html" rel="nofollow">json</a> and <a href="https://pypi.python.org/pypi/geojson" rel="nofollow">geojson</a> is easier. (If you dont want to use nodejs or the like)</p>
| 1 | 2016-07-26T11:03:54Z | [
"javascript",
"python",
"json",
"csv",
"geojson"
] |
How to execute an entire Javascript program from within a Python script | 38,586,396 | <p>So I am currently working on a project that involves the google maps API. In order to display data on this, the file needs to be in a geojson format. So far in order to accomplish this, I have been using two programs, 1 in javascript that converts a .json to a CSV, and another that converts a CSV to a geojson file, ... | 0 | 2016-07-26T09:43:50Z | 38,633,221 | <p>I was able to write a conversion script, and it's working now, thanks!</p>
| 0 | 2016-07-28T10:04:34Z | [
"javascript",
"python",
"json",
"csv",
"geojson"
] |
Matplotlib : Could not convert string to float | 38,586,488 | <p>I am trying to plot informations from this DataFrame :</p>
<pre><code> sold not_sold success_rate
category PriceBucket PriceBucketTitle
Papeterie 0 [0, 2] 42401 471886 17.130
1 (2, 3] 28627 360907 17.... | 2 | 2016-07-26T09:48:09Z | 38,586,933 | <p>I did this:</p>
<pre><code>fig, ax = plt.subplots()
plt.title('Success Rate By Category')
ax2 = ax.twinx()
lmnew = last_merge.reset_index().set_index('PriceBucketTitle')
lmnew.sold.plot.bar(color='None', ax=ax2)
lmnew.not_sold.plot.bar(color='None', edgecolor='red', hatch='/', ax=ax2)
lmnew.success_rate.plot(color... | 2 | 2016-07-26T10:08:04Z | [
"python",
"python-2.7",
"pandas",
"matplotlib",
"data-visualization"
] |
django1.9 does not load css from static admin | 38,586,503 | <p>I am currently using django version 1.9. I try to create a new superuser then I run the server and try to login through the browser by navigating to 127.0.0.1:8000/admin, but the django admin page seem does not have any css. When i do inspect element in the browser itself I come to know that it link to two css files... | 0 | 2016-07-26T09:48:47Z | 38,589,575 | <p>You have to set STATIC_ROOT, STATIC_URL and STATICFILES_DIRS in settings.py as below:</p>
<pre><code>BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
</code></pre>
<p>and then t... | 1 | 2016-07-26T12:12:02Z | [
"python",
"django",
"python-3.x",
"django-1.9"
] |
django1.9 does not load css from static admin | 38,586,503 | <p>I am currently using django version 1.9. I try to create a new superuser then I run the server and try to login through the browser by navigating to 127.0.0.1:8000/admin, but the django admin page seem does not have any css. When i do inspect element in the browser itself I come to know that it link to two css files... | 0 | 2016-07-26T09:48:47Z | 38,590,339 | <p>If you are using django-rest-framework see <a href="http://www.django-rest-framework.org/#quickstart." rel="nofollow">this</a>. </p>
<p>You need to add it as,</p>
<pre><code>INSTALLED_APPS = (
...
'rest_framework',
)
</code></pre>
<p>and in urls.py:</p>
<pre><code>urlpatterns = [
...
url(r'^api-a... | 0 | 2016-07-26T12:48:22Z | [
"python",
"django",
"python-3.x",
"django-1.9"
] |
Error in Hosting ReadTheDocs in house Server in python3 | 38,586,585 | <p>I am trying to install readthedocs in local system (Ubuntu 14.04 ) in python3 virtual env from the instructions given in this <a href="http://read-the-docs.readthedocs.io/en/latest/install.html" rel="nofollow">link</a></p>
<p>When I ran <strong>pip3 install -r requirements.txt</strong> , I got an error for Distutil... | 0 | 2016-07-26T09:52:38Z | 38,586,773 | <p>The read the docs code does not support Python 3 yet. The <a href="http://read-the-docs.readthedocs.io/en/latest/install.html" rel="nofollow">installation instructions</a> explicitly say to use Python 2.7:</p>
<blockquote>
<p>First, obtain Python 2.7 and virtualenv </p>
</blockquote>
<p>However, it should still ... | 1 | 2016-07-26T10:00:20Z | [
"python",
"python-sphinx",
"read-the-docs"
] |
pandas multiindex selecting...how to get the right (restricted to selection) index | 38,586,640 | <p>I am struggeling to get the right (restricted to the selection) index when using the methode <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofollow">xs</a> by pandas to select specific data in my dataframe. Let me demonstrate, what I am doing:</p>
<pre><code>print(df)... | 2 | 2016-07-26T09:55:00Z | 38,587,181 | <p>This is a known <strong>feature</strong> not bug. pandas preserves all of the index information. You can determine which of the levels are expressed and at what location via the <code>labels</code> attribute.</p>
<p>If you are looking to create an index that is fresh and just contains the information relevant to ... | 2 | 2016-07-26T10:20:16Z | [
"python",
"pandas",
"select",
"multi-index"
] |
What is the mechanism behind strip() function followed by a slice notation in python? | 38,586,686 | <p>For example</p>
<pre><code>sentence = "hello world"
stripped1 = sentence.strip()[:4]
stripped2 = sentence.strip()[3:8]
print (stripped1)
print (stripped2)
</code></pre>
<p>Output:</p>
<pre><code>hell
lo worl
</code></pre>
<p>Here strip( ) is a function object. So it should either take parameters or be followed b... | -1 | 2016-07-26T09:56:58Z | 38,586,745 | <p>Python executes <code>_result = sentence.strip()[:4]</code> as several <em>separate</em> steps:</p>
<pre><code>_result = sentence # look up the object "sentence" references
_result = _result.strip # attribute lookup on the object found
_result = _result() # call the result of the attribute lookup
_resul... | 2 | 2016-07-26T09:58:58Z | [
"python",
"string",
"list",
"strip"
] |
Is it possible to call 2nd parent class method by using child class object reference inside python in case of inheritance? If yes then how? | 38,586,700 | <p>Iâm recently started exploring python technology. I found a problem when I doing my exercise.</p>
<p>Suppose we have two class with different name but with same name method is exist in both class with no arguments. Example:</p>
<pre><code>class Parent_1: # define parent class
def myMethod(self):
prin... | 0 | 2016-07-26T09:57:36Z | 38,586,932 | <p>You can call the unbound function and pass the <code>self</code> parameter explicitly:</p>
<pre><code>Parent_2.myMethod(c)
</code></pre>
| 2 | 2016-07-26T10:08:02Z | [
"python",
"inheritance"
] |
Celery: How to get the task completed time from AsyncResult | 38,586,767 | <p>I need to trace the status for the tasks. i could get the 'state', 'info' attribute from the AsyncResult obj. however, it looks there's no way to get the 'done_date'. I use MySQL as result backend so i could find the <code>date_done</code> column in the <code>taskmeta</code> table, but how could i get the task done ... | 0 | 2016-07-26T09:59:50Z | 38,587,766 | <p>You can get it from the <code>_cache</code> object of the AsyncResult after you have called <code>res.result</code></p>
<p>for example</p>
<p><code>res._cache['date_done']</code></p>
| 0 | 2016-07-26T10:46:29Z | [
"python",
"celery"
] |
Python: Multiple Consensus sequences | 38,586,800 | <p>starting from a list of dna sequences, I must have in return all the possible consensus (the resulting
sequence with the highest nucleotide frequency in each position) sequences. If in some positions the nucleotides have
the same highest frequency, I must obtain all possible combinations with the highest frequency... | 1 | 2016-07-26T10:01:46Z | 38,587,322 | <p>I'm sure there are better ways but this is a simple one:</p>
<pre><code>bestseqs = [[]]
for i in range(n):
d = {N:profile[N][i] for N in ['T','G','C','A']}
m = max(d.values())
l = [N for N in ['T','G','C','A'] if d[N] == m]
bestseqs = [ s+[N] for N in l for s in bestseqs ]
for s in bestseqs:
pr... | 0 | 2016-07-26T10:26:33Z | [
"python",
"bioinformatics",
"rosalind"
] |
Mayavi Animated surface plot | 38,586,887 | <p>I'm using Mayavi to create a surface plot that animates in real time. Currently I'm just making random 2d arrays. The figure only appears when the for loop has completed.</p>
<p>My code is below:</p>
<pre><code>import numpy as np
from mayavi import mlab
import time
height, width = 360, 640
img = np.asarray(np.ran... | 2 | 2016-07-26T10:06:10Z | 38,785,499 | <p>What code editor are you using?
When I run this code in IDLE for Python 2.7 it updates with each iteration, just as you would expect it to. However, I have the problem you describe in Enthought Canopy code editor. I do not know the reason for this. </p>
| 0 | 2016-08-05T09:10:41Z | [
"python",
"animation",
"plot",
"surface",
"mayavi"
] |
Can someone explain me short _linear function from TensorFlow RNN code? | 38,586,970 | <p>Here the core(mb) function of tensorflow RNN implimentation</p>
<p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn_cell.py#L846-L891" rel="nofollow">Linear map:</a></p>
<pre><code>def _linear(args, output_size, bias, bias_start=0.0, scope=None):
"""Linear map: sum_i(args[i... | 2 | 2016-07-26T10:09:43Z | 40,038,417 | <p>Linear computes sum_i(args[i] * W[i]) + bias where W is a list of matrix variables of size n x outputsize and bias is a variable of size outputsize. </p>
<p>Tensorflow uses the transpose notation: row vector on the left times the transpose of the matrix. So in linear the args are a list of row vectors. </p>
... | 0 | 2016-10-14T08:24:02Z | [
"python",
"tensorflow",
"recurrent-neural-network"
] |
Create a dictionary that is associated with lists and update this through a loop | 38,587,083 | <p>I am using python2.7. I have a file which contains a chromosomal location and an experiment ID. I have got this information stored at the moment in two lists:</p>
<pre><code>unique_locations - containing a single value for each location
location_exp - containing lists of [location, experiment]
</code></pre>
<p>The... | 2 | 2016-07-26T10:15:24Z | 38,587,765 | <p>If I do understand you correctly
(if locations can be used as dict keys)</p>
<p>you could do:</p>
<pre><code>location_experiments={}
for location, experiment in location_exp:
location_experiments.setdefault(location,[]).append(experiment)
</code></pre>
| 2 | 2016-07-26T10:46:25Z | [
"python",
"arrays",
"list",
"dictionary"
] |
Create a dictionary that is associated with lists and update this through a loop | 38,587,083 | <p>I am using python2.7. I have a file which contains a chromosomal location and an experiment ID. I have got this information stored at the moment in two lists:</p>
<pre><code>unique_locations - containing a single value for each location
location_exp - containing lists of [location, experiment]
</code></pre>
<p>The... | 2 | 2016-07-26T10:15:24Z | 38,587,778 | <p>I haven't run this, so apologies if it fails.
if you say it's a list of lists like [ [location, experiment], [location, experiment] ] then:</p>
<pre><code>locationList = {}
for item in unique_experiment:
location = item[0]
exp = item[1]
if location not in locationList:
locationList[location] = [... | 1 | 2016-07-26T10:47:04Z | [
"python",
"arrays",
"list",
"dictionary"
] |
Create a dictionary that is associated with lists and update this through a loop | 38,587,083 | <p>I am using python2.7. I have a file which contains a chromosomal location and an experiment ID. I have got this information stored at the moment in two lists:</p>
<pre><code>unique_locations - containing a single value for each location
location_exp - containing lists of [location, experiment]
</code></pre>
<p>The... | 2 | 2016-07-26T10:15:24Z | 38,587,791 | <p>Try defaultdict, ie:</p>
<pre><code>from collections import defaultdict
unique_locations = ["location1", "location2"]
location_exp = [
("location1", "experiment1"),
("location1", "experiment2"),
("location1", "experiment3"),
("location2", "experiment2"),
("location2", "experiment3"),
("loca... | 2 | 2016-07-26T10:47:39Z | [
"python",
"arrays",
"list",
"dictionary"
] |
Create a dictionary that is associated with lists and update this through a loop | 38,587,083 | <p>I am using python2.7. I have a file which contains a chromosomal location and an experiment ID. I have got this information stored at the moment in two lists:</p>
<pre><code>unique_locations - containing a single value for each location
location_exp - containing lists of [location, experiment]
</code></pre>
<p>The... | 2 | 2016-07-26T10:15:24Z | 38,588,364 | <p>Here is another working example, using built-in <code>dict</code> and <code>groupby</code> from <code>itertools</code>:</p>
<pre><code>>>> from itertools import groupby
>>> d = {}
>>> location_exp = [
("location1", "experiment1"),
("location1", "experiment2"),
("location1", "e... | 1 | 2016-07-26T11:14:52Z | [
"python",
"arrays",
"list",
"dictionary"
] |
Calculating all combinations of nested lists based on logical expression | 38,587,123 | <p>Let's assume I have a action list, which can contain three different type of actions:</p>
<p>Type A: can contain all types of actions (disjunction)<br>
Type B: can contain all types of actions (<strong>ordered</strong> conjunction)<br>
Type C: cannot contain subactions. This is the level I want to have at the end.<... | 1 | 2016-07-26T10:17:13Z | 38,588,301 | <p>There is also a <a href="https://docs.python.org/library/stdtypes.html#set-types-set-frozenset" rel="nofollow">set type</a> in Python which support set operations - if you do not care about ordering.</p>
| 0 | 2016-07-26T11:11:49Z | [
"python",
"nested",
"logical-operators",
"itertools"
] |
Calculating all combinations of nested lists based on logical expression | 38,587,123 | <p>Let's assume I have a action list, which can contain three different type of actions:</p>
<p>Type A: can contain all types of actions (disjunction)<br>
Type B: can contain all types of actions (<strong>ordered</strong> conjunction)<br>
Type C: cannot contain subactions. This is the level I want to have at the end.<... | 1 | 2016-07-26T10:17:13Z | 38,588,718 | <p>Sadly, itertools isn't of much help here. The following recursive beast seems to do the job however:</p>
<pre><code>def combinations(actions):
if len(actions)==1:
action= actions[0]
try:
actions= type_a[action]
except KeyError:
try:
actions= type_b... | 1 | 2016-07-26T11:30:13Z | [
"python",
"nested",
"logical-operators",
"itertools"
] |
Elastic doesn't find the last word in the sentence with the dot in the end | 38,587,250 | <p>I use the Elastic with the following settings:</p>
<pre><code>ES = {
"mappings": {
ES_DOC_TYPE: {
"properties": {
"message": {
"type": "string",
"analyzer": "liza_analyzer",
"include_in_all": False
}
}
}
},
"settings": {... | 1 | 2016-07-26T10:23:03Z | 38,591,526 | <p>Your pattern is wrong. It should be:</p>
<pre><code>"pattern": "(\.\s*)|[\s,\[\]\(\)\"\!\'\?\`\*\;\:\/<>«»\#]+"
</code></pre>
| 0 | 2016-07-26T13:40:45Z | [
"python",
"elasticsearch"
] |
not sure how to get the username password (if statement) working | 38,587,271 | <p>Right, I have changed a whole load of things and hopefully corrected some errors. The error message is now: >> for row in teacherbooklist:
TypeError: 'int' object is not iterable</p>
<pre><code> username = input("Enter Username: ")
password = input("Enter Password: ")
with open('teacherbook_login.txt', 'w') a... | -1 | 2016-07-26T10:24:02Z | 38,587,343 | <p>You can't have a conditional expression with a <code>for</code> loop.</p>
<p>You also have a <code>SyntaxError</code>; <code>if</code> should use equality (<code>==</code>), not assignment (<code>=</code>):</p>
<pre><code>if username == teacherbooklist[1] and password == teacherbooklist[2]:
for field in row: ... | 1 | 2016-07-26T10:27:41Z | [
"python"
] |
not sure how to get the username password (if statement) working | 38,587,271 | <p>Right, I have changed a whole load of things and hopefully corrected some errors. The error message is now: >> for row in teacherbooklist:
TypeError: 'int' object is not iterable</p>
<pre><code> username = input("Enter Username: ")
password = input("Enter Password: ")
with open('teacherbook_login.txt', 'w') a... | -1 | 2016-07-26T10:24:02Z | 38,588,837 | <p>python doesn't support <code>if</code> in <code>for</code> statement.</p>
<pre><code>In [45]: a
Out[45]: [1, 2, 3, 4]
In [46]: for i in a if i>1:
....: print i
....:
File "<ipython-input-46-637488df9e78>", line 1
for i in a if i>1:
^
SyntaxError: invalid syntax
</co... | 0 | 2016-07-26T11:36:12Z | [
"python"
] |
Installing Python Qt4 on bluemix | 38,587,491 | <p>I am trying to run a webscraping application using bluemix and python. The webscrape needs to happen on javascript generated elements and so I am using a python script that makes use of the PyQt4 library. The script relies on these imports to work:</p>
<pre><code>import os
from PyQt4.QtGui import *
from PyQt4.QtC... | 0 | 2016-07-26T10:34:51Z | 38,594,540 | <p>Why not just use the PyQt installation instructions?</p>
<p>If you need to use <code>requirements.txt</code> you can find a prepackaged python .whl for your environment <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyqt4" rel="nofollow">here</a>. You should be able to either put the url directly into your <co... | 0 | 2016-07-26T15:51:04Z | [
"python",
"pyqt",
"ibm-bluemix"
] |
Python implementation of Multiple-Choice Knapsack | 38,587,503 | <p>I have been searching for python implementation of multiple choice knapsack problem. So far I have found a java implementation in github: <a href="https://github.com/tmarinkovic/multiple-choice-knapsack-problem" rel="nofollow">https://github.com/tmarinkovic/multiple-choice-knapsack-problem</a></p>
<p>And a psedu-co... | 0 | 2016-07-26T10:35:12Z | 38,591,442 | <p>An interesting topic. Check out these sites:</p>
<ol>
<li><p><a href="http://www.diku.dk/~pisinger/codes.html" rel="nofollow">David Pisinger's optimization codes</a></p></li>
<li><p><a href="https://github.com/kzyma?tab=repositories" rel="nofollow">Ken Zyma</a></p></li>
</ol>
<p>If you are familiar with the C/C++ ... | 0 | 2016-07-26T13:37:18Z | [
"python",
"algorithm",
"knapsack-problem"
] |
Naming method: send_auto_reply() vs send_autoreply() | 38,587,600 | <p>I am unsure whether to name a method <code>send_auto_reply()</code> or <code>send_autoreply()</code>.</p>
<p>What guidelines can be applied here?</p>
<p>It's Python, but AFAIK this should not matter.</p>
| 0 | 2016-07-26T10:38:58Z | 38,587,644 | <p>There is no such word as <code>autoreply</code> so you should name it as <code>send_auto_reply</code></p>
| 2 | 2016-07-26T10:40:51Z | [
"python",
"naming-conventions",
"naming"
] |
Converting str data to file object in Python | 38,587,699 | <p>I am posting videos to Google Cloud Buckets and a signed PUT url does the trick. However, if the file size is greater than 10MB it will not work, so I found an open source that will allow me to do this however, it uses a file like object.</p>
<pre><code>def read_in_chunks(file_object, chunk_size=65536):
while True:... | 0 | 2016-07-26T10:43:31Z | 38,587,821 | <p>Use <a href="https://docs.python.org/2/library/stringio.html" rel="nofollow"><code>StringIO</code></a>:</p>
<pre><code>data= StringIO(data)
read_in_chunks(data)
</code></pre>
| 1 | 2016-07-26T10:49:19Z | [
"python",
"json",
"file",
"object",
"typeconverter"
] |
Converting str data to file object in Python | 38,587,699 | <p>I am posting videos to Google Cloud Buckets and a signed PUT url does the trick. However, if the file size is greater than 10MB it will not work, so I found an open source that will allow me to do this however, it uses a file like object.</p>
<pre><code>def read_in_chunks(file_object, chunk_size=65536):
while True:... | 0 | 2016-07-26T10:43:31Z | 38,587,909 | <p>A so called 'file-like' object is in most cases just an object that implements the Python buffer interface; that is, has methods like <code>read</code>, <code>write</code>, <code>seek</code>, and so on.</p>
<p>The standard library module for buffer interface tools is called <a href="https://docs.python.org/3/librar... | 2 | 2016-07-26T10:53:03Z | [
"python",
"json",
"file",
"object",
"typeconverter"
] |
Amazon SWF to schedule task | 38,588,000 | <p>We are simulating a workflow for our requirement where we want to execute same task 10 times in a workflow. After 10th time workflow will be marked completed.</p>
<p>The problem is we want to specify interval for execution which will be varied based on the execution count. e.g. 5 minute for 1st execution, 10 minute... | 0 | 2016-07-26T10:57:09Z | 38,601,627 | <p>There is no delay option when scheduling an activity. The solution is to schedule a timer with delay based on activity execution count and when the timer fires schedule an activity execution.</p>
| 0 | 2016-07-26T23:50:51Z | [
"python",
"boto",
"amazon-swf"
] |
stop connecting points in pandas time series plot | 38,588,010 | <p>I have some data in a pandas series and when I type</p>
<pre><code> mydata.head()
</code></pre>
<p>I get:</p>
<pre><code> BPM
timestamp
2015-04-07 02:24:00 96.0
2015-04-07 02:24:00 96.0
2015-04-07 02:24:00 95.0
2015-04-07 02:24:00 95.0
2015-04-07 02:24:00 95.0
</code></pre>... | 0 | 2016-07-26T10:57:43Z | 38,588,480 | <p>Just tell <code>matplotlib</code> to plot markers instead of lines. For example,</p>
<pre><code>import matplotlib.pyplot as pyplot
fig, ax = pyplot.subplots()
ax.plot(my data, '+')
</code></pre>
<p>If you prefer another marker, you can change it (<a href="http://matplotlib.org/1.4.1/api/markers_api.html" rel="nof... | 1 | 2016-07-26T11:19:25Z | [
"python",
"pandas",
"matplotlib",
"series"
] |
extract specific lines out of file (PYTHON) | 38,588,105 | <p>i have a big problems in extracting lines out of a text file:
My text file ist built like the following:</p>
<pre><code>BO_ 560 VR_Sgn_1: ALMN
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
BO _ 561 VSet_Current : ACM
SG_2_ Vr_set
SG_3 Dars
BO_ 4321 CDSet_tr : APL
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
SG_1_ Vr_1
SG... | 0 | 2016-07-26T11:02:36Z | 38,588,772 | <p>You need to skip further processing of the line when you see <code>BO_ or BO _</code> </p>
<p>I am not sure if you only want for first block or all.</p>
<p>Does below option solve your problem.</p>
<pre><code>show_line = False
with open("test.txt") as f:
for line in f:
line = line.strip("... | 0 | 2016-07-26T11:33:21Z | [
"python",
"raspberry-pi"
] |
extract specific lines out of file (PYTHON) | 38,588,105 | <p>i have a big problems in extracting lines out of a text file:
My text file ist built like the following:</p>
<pre><code>BO_ 560 VR_Sgn_1: ALMN
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
BO _ 561 VSet_Current : ACM
SG_2_ Vr_set
SG_3 Dars
BO_ 4321 CDSet_tr : APL
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
SG_1_ Vr_1
SG... | 0 | 2016-07-26T11:02:36Z | 38,588,881 | <p>If what you want is to output all the blocks between "BO's" you can do something like this:</p>
<pre><code>with open("test.txt") as f:
for line in f:
if line.startswith("BO"):
print ""
else:
print line
</code></pre>
| 0 | 2016-07-26T11:38:03Z | [
"python",
"raspberry-pi"
] |
extract specific lines out of file (PYTHON) | 38,588,105 | <p>i have a big problems in extracting lines out of a text file:
My text file ist built like the following:</p>
<pre><code>BO_ 560 VR_Sgn_1: ALMN
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
BO _ 561 VSet_Current : ACM
SG_2_ Vr_set
SG_3 Dars
BO_ 4321 CDSet_tr : APL
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
SG_1_ Vr_1
SG... | 0 | 2016-07-26T11:02:36Z | 38,589,029 | <p>I think there's problem with:</p>
<pre><code>elif line.startswith("\n")
</code></pre>
<p>You want to wait for next "BO_" instead of EOL to disable show_line, try this:</p>
<pre><code>show_line = False
with open("test.txt") as f:
for line in f:
if line.startswith("BO_ 560"):
show_line = Tru... | 1 | 2016-07-26T11:45:28Z | [
"python",
"raspberry-pi"
] |
flask's application context and global connection | 38,588,147 | <p>I need to create a connection pool to database which can be reused by requests in Flask. The documentation(<code>0.11.x</code>) suggests to use <code>g</code>, the application context to store the database connections. </p>
<p>The issue is application context is created and destroyed before and after each request. ... | 2 | 2016-07-26T11:04:21Z | 38,588,552 | <p>No, you'll have to have some kind of global connection pool. <code>g</code> lets you share state across a request, so between various templates and functions called to handle a request, without having to pass that 'global' state around, but it is not meant to be a replacement for module-global variables (which have ... | 1 | 2016-07-26T11:22:51Z | [
"python",
"flask",
"global"
] |
Issue creating user-generated buttons in maya | 38,588,362 | <p>I'm trying to create a script for maya that essentially makes quick selection sets as indices inside a list.</p>
<p>I've got it storing and loading the information with buttons that already exist, but I want the user to be able to generate new buttons if the default number of selection sets is insufficient.</p>
<p... | 0 | 2016-07-26T11:14:41Z | 38,679,588 | <p>In case anyone has a similar issue, I'll post the solution that we (I and some friends from school) figured out.
Using <code>partial</code> resolved the issue of all newly generated buttons using the same index.
The other issue (not being able to generate new buttons after a selection was loaded) was due to the pare... | 0 | 2016-07-30T23:59:04Z | [
"python",
"list",
"function",
"button",
"maya"
] |
Django background executor | 38,588,436 | <p>I am trying to run multiple tasks in queue. The tasks come on user input. What i tried was creating a singleton class with ThreadPoolExecutor property and adding tasks into it. The tasks are added fine, but it looks like only the first addition of set of tasks works. The following are added but not executed.</p>
<p... | 0 | 2016-07-26T11:18:07Z | 38,589,289 | <p>I used multiprocess in one of my project without using celery, cause i think it was overkill for my use.
Maybe you could do something like this:</p>
<pre><code>from multiprocessing import Process
class MyQueuProcess(Process):
def __init__(self):
super(MyQueuProcess, self).__init__()
self.tasks... | 0 | 2016-07-26T11:58:27Z | [
"python",
"django",
"executor"
] |
How to numpy searchsorted bisect a range of 2 values on 1 column and get min value in 2nd column | 38,588,490 | <p>So I have a 2 column numpy array of integers, say:</p>
<pre><code>tarray = array([[ 368, 322],
[ 433, 420],
[ 451, 412],
[ 480, 440],
[ 517, 475],
[ 541, 503],
[ 578, 537],
[ 607, 567],
[ 637, 599],
[ 666, 628],
[ 696, 660],
[ 7... | 2 | 2016-07-26T11:19:44Z | 38,836,495 | <p>This appears to achieve your intended goals, using the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author):</p>
<pre><code>import numpy_indexed as npi
# to vectorize the concatenation of the slice ranges, we construct all indices ... | 1 | 2016-08-08T18:51:15Z | [
"python",
"numpy"
] |
FaceDetection in python using OpenCV | 38,588,599 | <p>I have written the following code in order to detect "presence of a face/faces" in python under OpenCV.</p>
<pre><code>import cv2
import sys
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened(): # try to get the first fra... | 0 | 2016-07-26T11:25:07Z | 38,634,451 | <p>You have to add <code>vc.release()</code> just before the last two lines. It would be something like:</p>
<pre><code>vc.release()
cv2.destroyWindow("preview")
cv2.destroyAllWindows()
</code></pre>
| 0 | 2016-07-28T11:01:24Z | [
"python",
"opencv"
] |
How to send request to a website through POST request? | 38,588,619 | <p>My purpose is to write a python script which returns the facebook ID when a url is given as input. I found this <a href="http://findmyfbid.com/" rel="nofollow">website</a> which does the same thing.</p>
<p>I want to ask:</p>
<p>1) Is it possible that I send a POST request myself which will include the url entered ... | 0 | 2016-07-26T11:26:01Z | 38,588,880 | <p>Well the easiest answer would be for you to use <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a><br>
you can install it using </p>
<pre><code>pip install requests
</code></pre>
<p>the normal usage would be ( assuming you're using python 3) : </p>
<pre><code>import requests
p... | 1 | 2016-07-26T11:38:03Z | [
"python",
"post",
"web-development-server"
] |
Why is prediction not plotted? | 38,588,668 | <p>Here is my code in Python 3:</p>
<pre><code>from sklearn import linear_model
import numpy as np
obj = linear_model.LinearRegression()
allc = np.array([[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]])
X=allc[:,0]
X=X.reshape(-1, 1)
Y=X.reshape(X.shape[0],-1)
obj.fit(X, Y)
print(obj.predict(7))
import matplotlib.pyplot as... | 0 | 2016-07-26T11:27:53Z | 38,589,417 | <p>The plot method is taking an array for the X-axis and an array for the Y-axis, and draws a <strong>line</strong> according to those arrays. You tried to draw a <strong>point</strong> using a method for <strong>lines</strong>...<br></p>
<p>For your code to work (I have tested it and it worked) switch this line:</p>
... | 1 | 2016-07-26T12:04:22Z | [
"python",
"python-3.x",
"numpy",
"matplotlib",
"linear-regression"
] |
python program debugging product of adjacent numbers | 38,588,675 | <p>I am currently working on project Euler question 8, which asks to find the largest product of 13 adjacent numbers in a 1000 digit long number. I imported the numpy prod function to compute products. It seems to work without the while loop but with the while loop it gives out a weird error message. can someone please... | 0 | 2016-07-26T11:28:11Z | 38,589,714 | <p>You could start by converting the multiline string <code>z</code> into a list of digits through a list comprehension and the built-in function <code>int()</code>:</p>
<pre><code>z = """73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737... | 1 | 2016-07-26T12:17:48Z | [
"python",
"debugging",
"numpy"
] |
Python - What's the proper way to unittest methods in a different class? | 38,588,804 | <p>I've written a module called Consumer.py, containing a class (Consumer). This class is initialized using a configuration file thay contains different parameters it uses for computation and the name of a loq que used for logging.</p>
<p>I want to write unit tests for this class so i've made a script called test_Cons... | 0 | 2016-07-26T11:34:51Z | 38,589,343 | <p>I'm not sure if that's what you're searching for, but you could add your tests at the end of your file like this :</p>
<pre><code>#!/usr/bin/python
...
class TestConsumerMethods(...):
...
if __name__ == "__main__":
# add your tests here.
</code></pre>
<p>This way, by executing the file containing the cl... | 0 | 2016-07-26T12:01:24Z | [
"python"
] |
Python - What's the proper way to unittest methods in a different class? | 38,588,804 | <p>I've written a module called Consumer.py, containing a class (Consumer). This class is initialized using a configuration file thay contains different parameters it uses for computation and the name of a loq que used for logging.</p>
<p>I want to write unit tests for this class so i've made a script called test_Cons... | 0 | 2016-07-26T11:34:51Z | 38,589,463 | <p>Don't make a global object to test against, as it opens up the possibility that some state will get set on it by one test, and affect another.</p>
<p>Each test should run in isolation and be completely independent from others.</p>
<p>Instead, either create the object in your test, or have it automatically created ... | 2 | 2016-07-26T12:07:00Z | [
"python"
] |
ERROR with Pyalgotrade | 38,588,813 | <pre><code>from pyalgotrade import strategy
from pyalgotrade.feed import csvfeed
from pyalgotrade.technical import ma
from pyalgotrade.bar import Frequency
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument):
strategy.BacktestingStrategy.__init__(self, feed, 1000)
#... | 0 | 2016-07-26T11:35:06Z | 39,030,224 | <p>The problem is that you're using a regular Feed class instead of a BarFeed. Try using this: <a href="https://github.com/gbeced/pyalgotrade/blob/master/pyalgotrade/barfeed/csvfeed.py#L190" rel="nofollow">https://github.com/gbeced/pyalgotrade/blob/master/pyalgotrade/barfeed/csvfeed.py#L190</a></p>
| 0 | 2016-08-19T02:27:28Z | [
"python",
"pyalgotrade"
] |
rounding errors in Python floor division | 38,588,815 | <p>I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:</p>
<pre><code>>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
</code></pre>
<p>This happens on both Python 2 and ... | 29 | 2016-07-26T11:35:11Z | 38,589,033 | <p>That's because there is no 0.4 in python (floating-point finite representation) it's actually a float like <code>0.4000000000000001</code> which makes the floor of division to be 19.</p>
<pre><code>>>> floor(8//0.4000000000000001)
19.0
</code></pre>
<p>But the true division (<code>/</code>) <a href="https... | 9 | 2016-07-26T11:45:40Z | [
"python",
"python-2.7",
"python-3.x",
"floating-point",
"rounding"
] |
rounding errors in Python floor division | 38,588,815 | <p>I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:</p>
<pre><code>>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
</code></pre>
<p>This happens on both Python 2 and ... | 29 | 2016-07-26T11:35:11Z | 38,589,356 | <p>Ok after a little bit of research I have found this <a href="https://bugs.python.org/issue27463" rel="nofollow">issue</a>.
What seems to be happening is, that as @khelwood suggested <code>0.4</code> evaluates internally to <code>0.40000000000000002220</code>, which when dividing <code>8.0</code> yields something sl... | 10 | 2016-07-26T12:01:54Z | [
"python",
"python-2.7",
"python-3.x",
"floating-point",
"rounding"
] |
rounding errors in Python floor division | 38,588,815 | <p>I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:</p>
<pre><code>>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
</code></pre>
<p>This happens on both Python 2 and ... | 29 | 2016-07-26T11:35:11Z | 38,589,543 | <p>@jotasi explained the true reason behind it.</p>
<p>However if you want to prevent it, you can use <code>decimal</code> module which was basically designed to represent decimal floating point numbers exactly in contrast to binary floating point representation.</p>
<p>So in your case you could do something like:</p... | 10 | 2016-07-26T12:10:42Z | [
"python",
"python-2.7",
"python-3.x",
"floating-point",
"rounding"
] |
rounding errors in Python floor division | 38,588,815 | <p>I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:</p>
<pre><code>>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
</code></pre>
<p>This happens on both Python 2 and ... | 29 | 2016-07-26T11:35:11Z | 38,589,899 | <p>As you and khelwood already noticed, <code>0.4</code> cannot be exactly represented as a float. Why? It is two fifth (<code>4/10 == 2/5</code>) which does not have a finite binary fraction representation.</p>
<p>Try this:</p>
<pre><code>from fractions import Fraction
Fraction('8.0') // Fraction('0.4')
# or equ... | 20 | 2016-07-26T12:26:58Z | [
"python",
"python-2.7",
"python-3.x",
"floating-point",
"rounding"
] |
rounding errors in Python floor division | 38,588,815 | <p>I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:</p>
<pre><code>>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
</code></pre>
<p>This happens on both Python 2 and ... | 29 | 2016-07-26T11:35:11Z | 38,594,002 | <p>After checking the semi-official sources of the float object in cpython on github (<a href="https://github.com/python/cpython/blob/966b24071af1b320a1c7646d33474eeae057c20f/Objects/floatobject.c">https://github.com/python/cpython/blob/966b24071af1b320a1c7646d33474eeae057c20f/Objects/floatobject.c</a>) one can underst... | 6 | 2016-07-26T15:25:20Z | [
"python",
"python-2.7",
"python-3.x",
"floating-point",
"rounding"
] |
Concatenating features to word embedding at the input layer during run time | 38,588,869 | <p>Suppose I obtain an input matrix after embedding lookup which looks like:</p>
<p>[ [[<code>0.5, 0.25, 0.47, 0.86</code>], [<code>0.8. 0.12, 0.63, 0.97</code>], [<code>0.7, 0.47, 0.32, 0.01</code>]], ..., [[...]] ] i.,e each embedding is of dim = 4 and sentence length be 3 as given in the mentioned case.</p>
<p>How... | -1 | 2016-07-26T11:37:35Z | 38,593,036 | <p>In Tensorflow you can create a placeholder of the desired shape [x, y, 2] and then concatenate it to the input Tensor using tf.concat. Assuming 'inputs' is your [x, y, z] embedding Tensor, you can do something like this:</p>
<pre><code>features = tf.placeholder(tf.float32, [x, y, 2])
new_inputs = tf.concat(2, [inpu... | 2 | 2016-07-26T14:43:48Z | [
"python",
"tensorflow",
"deep-learning",
"theano",
"feature-extraction"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.