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 |
|---|---|---|---|---|---|---|---|---|---|
Small Example for pyserial using Threading | 39,127,158 | <p>Can anyone please give me a small and simple example on how to use threading with pyserial communication.
I am googling for over three days and I am still illeterate and I dont even have a working piece of code which integrate both of them</p>
<p>Basically I am aiming to use threading in this scenario:</p>
<p>Have... | 0 | 2016-08-24T15:14:11Z | 39,127,369 | <p>There's no factual basis for the claim by <code>Task2</code>:</p>
<pre><code>print "I stopped Task 1 to start and execute Thread 2"
</code></pre>
<p>Your implementation starts one thread then immediately starts the other <em>without</em> stopping the first. This means that the <code>ser.read</code> and <code>ser.... | 0 | 2016-08-24T15:25:28Z | [
"python",
"multithreading",
"pyserial"
] |
How to mask an image out of gray noise? | 39,127,211 | <p>I have the following raw image that I want to mask. I want just the circular shaped (almost) orange/brown structure to be masked white. How do I go about doing it?</p>
<p><a href="http://imgur.com/a/HNmRn" rel="nofollow">http://imgur.com/a/HNmRn</a></p>
<p>I've tried thresholding, but I don't want the lower thresh... | 0 | 2016-08-24T15:17:16Z | 39,127,360 | <p>You could try converting into HSV colorspace and threshold for color. But you might not be able to remove the threshold as a variable, as every image has slight variations in the lighting. From experience I can tell you that sometimes you can generously extend the threshold to fit most of the stuff you want. But a m... | 1 | 2016-08-24T15:25:07Z | [
"python",
"opencv",
"image-processing",
"computer-vision"
] |
How to mask an image out of gray noise? | 39,127,211 | <p>I have the following raw image that I want to mask. I want just the circular shaped (almost) orange/brown structure to be masked white. How do I go about doing it?</p>
<p><a href="http://imgur.com/a/HNmRn" rel="nofollow">http://imgur.com/a/HNmRn</a></p>
<p>I've tried thresholding, but I don't want the lower thresh... | 0 | 2016-08-24T15:17:16Z | 39,153,346 | <p>Use Hough circle transform to find the the circle that separate the eye and the gray area.</p>
<p>The basic idea is to run Hough circle transfor and then finding the circle that has the biggest difference in values between the inside of the circles and outside.</p>
<p>The result:
<a href="http://i.stack.imgur.com/... | 1 | 2016-08-25T19:30:13Z | [
"python",
"opencv",
"image-processing",
"computer-vision"
] |
Gspread - Can Not Retrieve Spreadsheets | 39,127,224 | <p>I am trying to use Gspread in Python2.7 to retrieve spreadsheets. I seem to be able to login but whenever I issue the command</p>
<pre><code>gc.openall()
</code></pre>
<p>it just returns an empty list. I have given the service account admin access to everything and the sheets api is enabled in my google console. C... | 1 | 2016-08-24T15:18:03Z | 39,128,653 | <p>I can think of mainly 2 issues that could be at play here. First gspread may only access google sheets that are at the root of the google drive. To circumvent that, I strongly recommend moving to v4 google api python client instead of gspread.</p>
<p>If you do have google sheets in the root my guess is that you are... | 1 | 2016-08-24T16:31:56Z | [
"python",
"google-spreadsheet",
"google-sheets-api",
"gspread"
] |
Items vs item loaders in scrapy | 39,127,256 | <p>i'm pretty new to scrapy, I know that items are used to populate scraped data, but i cant understand the difference between items and item loaders. I tried to read some example codes, they used item loaders to store instead of items and i cant understand why. Scarpy documentation wasn't clear enough for me. Can anyo... | 0 | 2016-08-24T15:19:28Z | 39,130,517 | <p>I really like the official explanation in the docs:</p>
<blockquote>
<p>Item Loaders provide a convenient mechanism for populating scraped
Items. Even though Items can be populated using their own
dictionary-like API, Item Loaders provide a much more convenient API
for populating them from a scraping proces... | 1 | 2016-08-24T18:24:13Z | [
"python",
"web-scraping",
"scrapy",
"scrapy-spider"
] |
Retrieving data using Beautiful Soup | 39,127,272 | <p>So I've been trying to retrieve some data using BeautifulSoup but I've hit a brick wall.</p>
<pre><code><tr data-name="A Color Similar to Slate">
<th class="unique"><a href="/item/5052/6/223d382afee2ac6857d3298b800652e0" class="item-link"><span style='color: #7D6D00'>A Color ... | 0 | 2016-08-24T15:20:41Z | 39,127,363 | <pre><code>similar_color = soup.find('tr', {'data-name': 'A Color Similar to Slate'})
for value in similar_color.find_all('td'):
print(value.text)
</code></pre>
<p>Should result in:</p>
<pre><code>0/10
35,000
</code></pre>
<p>and so on, so forth. However, it seems like you want to grab the text value sometimes,... | 1 | 2016-08-24T15:25:10Z | [
"python",
"beautifulsoup"
] |
Retrieving data using Beautiful Soup | 39,127,272 | <p>So I've been trying to retrieve some data using BeautifulSoup but I've hit a brick wall.</p>
<pre><code><tr data-name="A Color Similar to Slate">
<th class="unique"><a href="/item/5052/6/223d382afee2ac6857d3298b800652e0" class="item-link"><span style='color: #7D6D00'>A Color ... | 0 | 2016-08-24T15:20:41Z | 39,127,378 | <p>In case you will use it on other HTML style files:</p>
<pre><code>from bs4 import BeautifulSoup
html= """<tr data-name="A Color Similar to Slate">
<th class="unique"><a href="/item/5052/6/223d382afee2ac6857d3298b800652e0" class="item-link"><span style='color: #7D6D00'>A Color... | 0 | 2016-08-24T15:25:56Z | [
"python",
"beautifulsoup"
] |
Filter in template to arrange data specifically in django | 39,127,316 | <p>How can I use a filter in my template to put the values in a row where the key matches. </p>
<p>So for example all values in Inner OD key row 1 should have values for that key
then in row two the should have all values of Outter OD key for row 2 values. </p>
<p>Any help would be greatly appreciated </p>
<p>Here... | 0 | 2016-08-24T15:22:50Z | 39,129,118 | <p>Alright then here we go. This is how you loop over a dictionary in an html page using Django:</p>
<pre><code><tbody>
<tr>
{% for desc in dim_description.all %}
<th> {{ desc }}</th>
{% endfor %}
</tr>
{% for key, values in reading_desc.items %}
&l... | 1 | 2016-08-24T16:59:32Z | [
"python",
"django",
"python-2.7"
] |
Python Pandas - Add a new column with value based on first and last name in multiple columns | 39,127,354 | <p>Although I'm still a beginner myself, I'm trying to explain some Pandas fundamentals to colleagues who usually manipulate CSV files with Excel.</p>
<p>I hit a wall with my ability to find a "good" answer for solving a given problem I'd like to use as an example.</p>
<p>I have a CSV file like this:</p>
<pre><code>... | 1 | 2016-08-24T15:24:29Z | 39,127,520 | <p>Not the easiest introduction to Pandas...</p>
<pre><code>df['StartsWithJorK'] = 'BooHiss'
starting_letters = ['j', 'k']
df.loc[(df.First.str[0].str.lower().isin(starting_letters)) |
df.Last.str[0].str.lower().isin(starting_letters), 'StartsWithJorK'] = 'Yay!'
>>> df
Id First Last S... | 2 | 2016-08-24T15:33:57Z | [
"python",
"csv",
"pandas"
] |
Python Pandas - Add a new column with value based on first and last name in multiple columns | 39,127,354 | <p>Although I'm still a beginner myself, I'm trying to explain some Pandas fundamentals to colleagues who usually manipulate CSV files with Excel.</p>
<p>I hit a wall with my ability to find a "good" answer for solving a given problem I'd like to use as an example.</p>
<p>I have a CSV file like this:</p>
<pre><code>... | 1 | 2016-08-24T15:24:29Z | 39,127,602 | <p>If you don't mind importing <code>numpy</code> too, you can do</p>
<pre><code>import numpy as np
import pandas as pd
mask = df['Last'].str.match('[JjKk]') | df['First'].str.match('[JjKk]')
df['StartsWithJOrK'] = np.where(mask, 'Yay!', 'BooHiss')
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-over... | 2 | 2016-08-24T15:37:43Z | [
"python",
"csv",
"pandas"
] |
dealing with inf in list | 39,127,388 | <p>I have a list that I am trying to solve for a variable but is not working because I have inf in some of the elements in the list. How can I deal with the inf in the values so that I can solve for my variable m? When I run the code it says "Cannot convert 0 to int" so the solve command has an issue with the inf value... | 0 | 2016-08-24T15:26:49Z | 39,128,001 | <p>It's usually not a good idea to mix <code>sympy</code> and <code>numpy</code>. Sympy uses <code>oo</code> for infinity. You can use <code>.subs</code> to replace the <code>inf</code> with <code>oo</code>:</p>
<pre><code>from sympy import *
from numpy import inf
m = var('m')
A = [inf*m - 1, inf*m - 2, .1122*m - 7, 0... | 0 | 2016-08-24T15:58:43Z | [
"python",
"list",
"numpy",
"infinity"
] |
Comparing two dataframe values in python | 39,127,450 | <p>I have two dataframes <code>df1['LicId']</code> and <code>df2['LicId']</code>.</p>
<p><code>df1['LicId']</code> will always have one value</p>
<pre><code> LicId
0 abc1234
</code></pre>
<p>However <code>df2['LicId']</code> will have several Ids </p>
<pre><code> LicId
0 abc1234
1 xyz2345
</code></pre>
... | 1 | 2016-08-24T15:30:23Z | 39,128,384 | <p>You can match values with <code>isin()</code>:</p>
<pre><code>df1 = pd.DataFrame({'LicId':['abc1234', 'a', 'b']})
df2 = pd.DataFrame({'LicId':['abc1234', 'xyz2345', 'a', 'c']})
</code></pre>
<p><code>df1</code>:</p>
<pre><code> LicId
0 abc1234
1 a
2 b
</code></pre>
<p><code>df2</code>:</p>
<p... | 1 | 2016-08-24T16:17:56Z | [
"python",
"pandas",
"indexing",
"compare"
] |
How to select a value from Autolist (search suggestions) in Selenium Python | 39,127,468 | <p>Go to google.com</p>
<p>Type a keyword (as shown in this attachment) <a href="http://i.stack.imgur.com/uBD2c.jpg" rel="nofollow">http://i.stack.imgur.com/uBD2c.jpg</a></p>
<p>I want to select 3rd or 4th value from the search suggestions. What method should I use in selenium python ?</p>
| -1 | 2016-08-24T15:31:29Z | 39,127,879 | <p>Google search page contains a <code><div class="gstl_0 sbdd_a"></code></p>
<p>When you start typing into the search box, that div becomes populated with an <code><ul role="listbox"></code>. The <code><li></code> in that list contain the 4 suggestions. Pick one, and call the .click() method.</p>
| 0 | 2016-08-24T15:52:32Z | [
"python",
"python-2.7",
"python-3.x",
"selenium",
"pycharm"
] |
How to select a value from Autolist (search suggestions) in Selenium Python | 39,127,468 | <p>Go to google.com</p>
<p>Type a keyword (as shown in this attachment) <a href="http://i.stack.imgur.com/uBD2c.jpg" rel="nofollow">http://i.stack.imgur.com/uBD2c.jpg</a></p>
<p>I want to select 3rd or 4th value from the search suggestions. What method should I use in selenium python ?</p>
| -1 | 2016-08-24T15:31:29Z | 39,127,908 | <p>I don't know python, but i do have code in C# which i was able to succeed. You can give it try.</p>
<pre><code>IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("https://www.google.com/");
IWebElement txtboxSearch = driver.FindElement(By.Id("lst-ib"));
txtboxSearch.SendKeys("ap");
IList... | 1 | 2016-08-24T15:53:59Z | [
"python",
"python-2.7",
"python-3.x",
"selenium",
"pycharm"
] |
How to select a value from Autolist (search suggestions) in Selenium Python | 39,127,468 | <p>Go to google.com</p>
<p>Type a keyword (as shown in this attachment) <a href="http://i.stack.imgur.com/uBD2c.jpg" rel="nofollow">http://i.stack.imgur.com/uBD2c.jpg</a></p>
<p>I want to select 3rd or 4th value from the search suggestions. What method should I use in selenium python ?</p>
| -1 | 2016-08-24T15:31:29Z | 39,128,537 | <pre><code>from selenium import webdriver
import time
driver = webdriver.Chrome('Path to chromedriver\chromedriver.exe')
driver.get('http://google.com')
driver.maximize_window()
driver.find_element_by_name('q').send_keys('Shah') #pass whatever you want to search
time.sleep(5)
# to click on third element of search s... | 0 | 2016-08-24T16:25:23Z | [
"python",
"python-2.7",
"python-3.x",
"selenium",
"pycharm"
] |
How to use Future with map method of the Executor from dask.distrubuted (Python library)? | 39,127,531 | <p>I am running <a href="https://distributed.readthedocs.io/en/latest/index.html" rel="nofollow">dask.distributed</a> cluster. </p>
<p>My task includes chained computations, where the last step is a parallel processing of a list, created on previous steps, using <code>Executor.map</code> method. The length of the list... | 3 | 2016-08-24T15:34:22Z | 39,127,953 | <p>The crux of your problem seems to be here:</p>
<pre><code>m_list = e.submit(create_m_list)
m_result = e.map(process_m_list, m_list)
</code></pre>
<p>You are correct that you can not map a function over an individual future. You need to pass <code>map</code> a sequence. Dask doesn't know how many functions to sub... | 1 | 2016-08-24T15:56:20Z | [
"python",
"python-2.7",
"distributed",
"dask"
] |
What to do in order to use SQL in docker container deployed in cloud? | 39,127,617 | <p>Right now, I have a simple web server in Python, pacakaged in a docker container, Linux based. That container is deployed in a private openstack cloud and a volume is attached to the container, mounted.</p>
<p>The web server is saving data in a json file on the volume. However, I would like to replace that saving m... | 0 | 2016-08-24T15:38:26Z | 39,127,804 | <p>Disclaimer: I don't know anything about Openstack and answer this by thinking it will be similar to a dedicated Linux server. If that assumption should be wrong then there is probably a much better answer out there.</p>
<p>I suggest you use a separate container for the DB, preferably based on a well-known public im... | 0 | 2016-08-24T15:48:21Z | [
"python",
"sqlite",
"docker",
"openstack"
] |
How to designate Python unit tests as having database dependency or not? | 39,127,624 | <p>I am working on a project that has many "unit tests" that have hard dependencies that need to interact with the database and other APIs. The tests are a valuable and useful resource to our team, but they just cannot be ran independently, without relying on the functionality of other services within the test environm... | 1 | 2016-08-24T15:38:47Z | 39,128,992 | <p>You can define which test should be skipped with the <code>skipIf</code> decorator. In combinations with setting an environmental variable you can skip tests in some environments. An example:</p>
<pre><code>from unittest import skipIf
class MyTest(Testcase):
@skipIf(os.environ.get('RUNON') == 'jenkins', 'Does... | 2 | 2016-08-24T16:50:41Z | [
"python",
"unit-testing",
"continuous-integration",
"functional-testing"
] |
How to designate Python unit tests as having database dependency or not? | 39,127,624 | <p>I am working on a project that has many "unit tests" that have hard dependencies that need to interact with the database and other APIs. The tests are a valuable and useful resource to our team, but they just cannot be ran independently, without relying on the functionality of other services within the test environm... | 1 | 2016-08-24T15:38:47Z | 39,130,155 | <p>Here's another option. You could separate different test categories by directory. If you wanted to try this strategy, it may look something like:</p>
<p><code>python
-modules
unit
-pure unit test modules
functional
-other unit test modules
</code></p>
<p>In your testing pipeline, you can call your testing ... | 1 | 2016-08-24T18:03:04Z | [
"python",
"unit-testing",
"continuous-integration",
"functional-testing"
] |
Creating a django form which also uses database data as an option | 39,127,749 | <p>My question title isn't very good but what I am trying to create is a way to add students into a database table and in the same form add their parents details into another table. </p>
<p>The problem arises where 2 students have the same parents and I now have two sets of the same parent. Is there a way to select pa... | 0 | 2016-08-24T15:45:43Z | 39,128,552 | <p>If you want to select a parent from the parent table when you are creating a student you could try a <a href="http://www.w3schools.com/tags/tag_datalist.asp" rel="nofollow">http://www.w3schools.com/tags/tag_datalist.asp</a>.</p>
<p>This would require you to fetch all the parents from the database in your view, pas... | 0 | 2016-08-24T16:26:02Z | [
"python",
"mysql",
"django",
"django-forms",
"mariadb"
] |
How do I sort a dictionary in decreasing order based on values of the list as its value? | 39,127,884 | <p>I have a dictionary as below:</p>
<pre><code>{'Muguruza': [0, 0, 1, 12, 2, 15], 'Williams': [0, 1, 2, 15, 1, 12], 'Murray': [2, 2, 16, 143, 13, 142], 'Djokovic': [3, 1, 13, 142, 16, 143]}
</code></pre>
<p>I want to sort it in decreasing order based on the values in the corresponding list. </p>
<p>I have to print ... | -3 | 2016-08-24T15:52:51Z | 39,128,010 | <p>You can just compare python list with <code>></code> <code><</code> <code>=</code>. Simple as that. It will do the exact same thing as you want.
Also <code>operator</code> is a great way to sort dicts based on values</p>
<pre><code>dict = {'Muguruza': [0, 0, 1, 12, 2, 15], 'Williams': [0, 1, 2, 15, 1, 12], '... | 2 | 2016-08-24T15:59:17Z | [
"python"
] |
How do I sort a dictionary in decreasing order based on values of the list as its value? | 39,127,884 | <p>I have a dictionary as below:</p>
<pre><code>{'Muguruza': [0, 0, 1, 12, 2, 15], 'Williams': [0, 1, 2, 15, 1, 12], 'Murray': [2, 2, 16, 143, 13, 142], 'Djokovic': [3, 1, 13, 142, 16, 143]}
</code></pre>
<p>I want to sort it in decreasing order based on the values in the corresponding list. </p>
<p>I have to print ... | -3 | 2016-08-24T15:52:51Z | 39,128,157 | <p>You could do</p>
<pre><code>d={'Muguruza': [0, 0, 1, 12, 2, 15], 'Williams': [0, 1, 2, 15, 1, 12], 'Murray': [2, 2, 16, 143, 13, 142], 'Djokovic': [3, 1, 13, 142, 16, 143]}
for v,k in sorted((v,k) for k,v in d.items()):
print(k,"\t".join(v))
</code></pre>
| 0 | 2016-08-24T16:05:59Z | [
"python"
] |
How do I sort a dictionary in decreasing order based on values of the list as its value? | 39,127,884 | <p>I have a dictionary as below:</p>
<pre><code>{'Muguruza': [0, 0, 1, 12, 2, 15], 'Williams': [0, 1, 2, 15, 1, 12], 'Murray': [2, 2, 16, 143, 13, 142], 'Djokovic': [3, 1, 13, 142, 16, 143]}
</code></pre>
<p>I want to sort it in decreasing order based on the values in the corresponding list. </p>
<p>I have to print ... | -3 | 2016-08-24T15:52:51Z | 39,128,252 | <p>Here's a possible answer:</p>
<pre><code>import operator
data = {
'Muguruza': [0, 0, 1, 12, 2, 15],
'Williams': [0, 1, 2, 15, 1, 12],
'Murray': [2, 2, 16, 143, 13, 142],
'Djokovic': [3, 1, 13, 142, 16, 143]
}
output = reversed(sorted(data.items(), key=operator.itemgetter(1)))
print("\n".join([(i[0... | 1 | 2016-08-24T16:09:59Z | [
"python"
] |
How to reverse the order of rows in my dataframe using Python, But not reverse the index when saving it into another dataframe | 39,127,900 | <pre><code>[4
8
3
6]
</code></pre>
<p>into:</p>
<pre><code>[6
3
8
4]
</code></pre>
<p>Python adds the index values 0, 1, 2, 3 to the dataframe, so when I reverse the rows the index values also tag along so the index values of [6,3,8,4] are 4,3,2,1</p>
<p>The problem is when I plot the graph is not ordered in the... | 0 | 2016-08-24T15:53:26Z | 39,127,960 | <p>Seems like reset_index would solve that:</p>
<pre><code>df.iloc[::-1].reset_index(drop=True)
</code></pre>
<hr>
<pre><code>df = pd.DataFrame({'A': [4, 8, 3, 6]})
df
Out:
A
0 4
1 8
2 3
3 6
df.iloc[::-1].reset_index(drop=True)
Out:
A
0 6
1 3
2 8
3 4
</code></pre>
| 1 | 2016-08-24T15:56:38Z | [
"python",
"dataframe"
] |
twisted autobahn websocket being initialized twice with wss | 39,127,928 | <p>I have some websocket protocols implemented with Twisted, they work fine when I connect using "ws", but when I enable secure websockets, the <code>__init__</code> method is called twice. To more specific, it is called once, then the connection apparently fails, with connectionLost being called, then it the <code>__i... | 0 | 2016-08-24T15:54:47Z | 39,134,379 | <p>The recommend API these days is to use endpoints. Also, <code>twisted.internet.ssl.CertificateOptions</code> is the preferred API for TLS connections. So with those changes your code above would look like this:</p>
<pre><code>from datetime import datetime
from autobahn.twisted.websocket import WebSocketServerProtoc... | 1 | 2016-08-24T23:13:47Z | [
"python",
"websocket",
"twisted",
"autobahn"
] |
Raise error for undefined attributes in Jinja templates in Flask | 39,127,940 | <p>By default Flask renders empty values for undefined attributes in Jinja templates. I want to raise an error instead. How can I change this behavior in Flask?</p>
| 0 | 2016-08-24T15:55:33Z | 39,127,941 | <p>Set undefined behavior to Flask application:</p>
<pre><code>from flask import Flask
from flask import render_template
import jinja2
APP = Flask(__name__)
APP.jinja_env.undefined = jinja2.StrictUndefined
</code></pre>
<p>And now you can render the template as always, in my case it's a JSON file:</p>
<pre><code>re... | 0 | 2016-08-24T15:55:33Z | [
"python",
"flask",
"jinja2"
] |
Is there a working excel sheet module for Python 3.4? | 39,127,944 | <p>I've been looking around for a python module to work with excel sheets. So far I've come across the following:</p>
<ul>
<li>openpyxl</li>
<li>xlsxwriter</li>
<li>xlrd</li>
<li>xlwt</li>
<li>xlutils</li>
</ul>
<p>The issue I'm running into is that any time I import these modules I get an error saying that they don'... | -1 | 2016-08-24T15:55:42Z | 39,128,057 | <p>Most of these modules are still working with Python 3. All you need to do is to actually install them on your computer.</p>
<p>If you are not sure what to do, I suggest using a prepackaged Python distribution such as Anaconda which already includes most of them: <a href="https://docs.continuum.io/anaconda/excel" re... | 1 | 2016-08-24T16:01:21Z | [
"python",
"excel"
] |
How do I structure a database cache (memcached/Redis) for a Python web app with many different variables for querying? | 39,128,100 | <p>For my app, I am using Flask, however the question I am asking is more general and can be applied to any Python web framework.</p>
<p>I am building a comparison website where I can update details about products in the database. I want to structure my app so that 99% of users who visit my website will never need to ... | 2 | 2016-08-24T16:03:19Z | 39,128,415 | <p>I had this exact question myself, with a PHP project, though. My solution was to use ElasticSearch as an intermediate cache between the application and database.</p>
<p>The trick to this is the ORM. I designed it so that when Entity.save() is called it is first stored in the database, then the complete object (with... | 0 | 2016-08-24T16:19:36Z | [
"python",
"database",
"caching",
"redis",
"memcached"
] |
How do I structure a database cache (memcached/Redis) for a Python web app with many different variables for querying? | 39,128,100 | <p>For my app, I am using Flask, however the question I am asking is more general and can be applied to any Python web framework.</p>
<p>I am building a comparison website where I can update details about products in the database. I want to structure my app so that 99% of users who visit my website will never need to ... | 2 | 2016-08-24T16:03:19Z | 39,154,770 | <p>So a free eBook called "Redis in Action" by Josiah Carlson answered all of my questions. It it quite long, but after reading through, I have a fairly solid understanding of how to structure a caching architecture. It gives real world examples, such as a social network and a shopping site with tons of traffic. I will... | 0 | 2016-08-25T21:09:31Z | [
"python",
"database",
"caching",
"redis",
"memcached"
] |
Average of numpy array ignoring specified value | 39,128,145 | <p>I have a number of 1-dimensional numpy ndarrays containing the path length between a given node and all other nodes in a network for which I would like to calculate the average. The matter is complicated though by the fact that if no path exists between two nodes the algorithm returns a value of 2147483647 for that ... | 1 | 2016-08-24T16:05:18Z | 39,128,230 | <p>Why not using your usual numpy filtering for this?</p>
<pre><code>m = my_array[my_array != 2147483647].mean()
</code></pre>
<p>By the way, if you really want speed, your whole algorithm description seems certainly naive and could be improved by a lot.</p>
<p>Oh and I guess that you are calculating the mean becaus... | 3 | 2016-08-24T16:09:12Z | [
"python",
"arrays",
"performance",
"numpy",
"graph-tool"
] |
Average of numpy array ignoring specified value | 39,128,145 | <p>I have a number of 1-dimensional numpy ndarrays containing the path length between a given node and all other nodes in a network for which I would like to calculate the average. The matter is complicated though by the fact that if no path exists between two nodes the algorithm returns a value of 2147483647 for that ... | 1 | 2016-08-24T16:05:18Z | 39,128,324 | <pre><code>np.nanmean(np.where(my_array == 2147483647, np.nan, my_array))
</code></pre>
<p><strong>Timings</strong></p>
<pre><code>a = np.random.randn(100000)
a[::10] = 2147483647
%timeit np.nanmean(np.where(a == 2147483647, np.nan, a))
1000 loops, best of 3: 639 µs per loop
%timeit a[a != 2147483647].mean()
1000 ... | 1 | 2016-08-24T16:13:58Z | [
"python",
"arrays",
"performance",
"numpy",
"graph-tool"
] |
Average of numpy array ignoring specified value | 39,128,145 | <p>I have a number of 1-dimensional numpy ndarrays containing the path length between a given node and all other nodes in a network for which I would like to calculate the average. The matter is complicated though by the fact that if no path exists between two nodes the algorithm returns a value of 2147483647 for that ... | 1 | 2016-08-24T16:05:18Z | 39,129,048 | <p>One way would be to get the sum for all elements in one go and then removing the contribution from the invalid ones. Finally, we need to get the average value itself, divide by the number of valid elements. So, we would have an implementation like so -</p>
<pre><code>def mean_ignore_num(arr,num):
# Get count of... | 1 | 2016-08-24T16:54:58Z | [
"python",
"arrays",
"performance",
"numpy",
"graph-tool"
] |
Run python script right after RPi boot | 39,128,161 | <p>I'm relatively new to raspberry pi (5 days using it) and I've just finished to run my python script succesfully (called dogcare.py). Now I'm trying to execute this script right after my raspberry is turned on. I've been doing some research and I find different ways to do it:</p>
<ul>
<li>using /etc/profile</li>
<li... | 0 | 2016-08-24T16:06:12Z | 39,135,112 | <p>I have done a similar thing with my Raspi 2 as well which involved sending myself an email with the ip address of the pi so I could easily ssh/vnc to it.</p>
<p>My steps involved making a shell script which ran the python program.</p>
<pre><code>#!/bin/sh
cd pythonfiledirectory
sudo python pythonfile.py
cd /
</cod... | 0 | 2016-08-25T00:55:27Z | [
"python",
"linux",
"raspberry-pi"
] |
Graphviz installation error | 39,128,173 | <p>I am installing graphviz library or package in python using the command</p>
<pre><code>pip install graphviz error
</code></pre>
<p>but I am facing the the problem that show in image. please anyone help me in fixing this issue. </p>
<p><img src="http://i.stack.imgur.com/dxmYu.png" alt="Error message appear during... | 0 | 2016-08-24T16:06:32Z | 39,129,248 | <p>use vs prompt instead of cmd shell, or use</p>
<p><a href="https://www.microsoft.com/en-us/download/details.aspx?id=44266" rel="nofollow">https://www.microsoft.com/en-us/download/details.aspx?id=44266</a></p>
| 0 | 2016-08-24T17:07:26Z | [
"python",
"installation",
"graphviz"
] |
Large number of Unicode characters not rendering correctly in a kivy TextInput | 39,128,198 | <p>Question: How can I get all Unicode characters to render correctly in a TextInput using Kivy?</p>
<h2>More details below</h2>
<p>I'm generating random Unicode characters in a range between 0x0200 and 0x9990 which is massive the issue is that a large portion of the characters will not render correctly in a TextInpu... | 0 | 2016-08-24T16:07:29Z | 39,128,575 | <p>Your font does not seem to support these characters - switch to another one with support for that range (see <a href="https://en.wikipedia.org/wiki/Unicode_block" rel="nofollow">https://en.wikipedia.org/wiki/Unicode_block</a> for more info on what needs to be there)</p>
| 2 | 2016-08-24T16:27:35Z | [
"python",
"kivy",
"python-unicode"
] |
How to max regex non greedy working backwards | 39,128,213 | <p>I always assumed regex worked like this, but I guess I never hit a case like this until now and I'm not sure the best way to tackle it.</p>
<p>String to consider:</p>
<pre><code>apple
apple
apple
cat
</code></pre>
<p>I want to use something like apple.*?cat, however, this matches the first apple to the cat when I... | 1 | 2016-08-24T16:08:09Z | 39,128,260 | <p>You can use this negative lookahead based on <a href="http://www.rexegg.com/regex-quantifiers.html#tempered_greed" rel="nofollow">tempered greedy token</a> regex in python:</p>
<pre><code>reg = re.compile(r'apple(?:(?!apple).)*cat', re.DOTALL)
</code></pre>
<p><a href="https://regex101.com/r/sB9aG7/1" rel="nofollo... | 3 | 2016-08-24T16:10:28Z | [
"python",
"regex"
] |
PyEZ RPC options format differ between get_configuration and other calls | 39,128,268 | <p>When using RPC calls in PyEZ we add the parameters as named arguments like <code>rpc.get_interface_information(terse="True", interface-name="xe-0/0/0")</code>, however for configuration the options need to be within a dictionary like <code>rpc.get_configuration({"inherit":"inherit", "groups":"groups"})</code></p>
<... | 1 | 2016-08-24T16:10:52Z | 39,130,451 | <p>The best way to describe it is this:
With non-configuration rpcs, each of the items is it's own element and in PyEZ we use the parameters to determine that we are referencing elements.</p>
<pre><code><get-interface-information>
<routing-instance>routing-instance</routing-instance>
... | 2 | 2016-08-24T18:20:12Z | [
"python"
] |
PyEZ RPC options format differ between get_configuration and other calls | 39,128,268 | <p>When using RPC calls in PyEZ we add the parameters as named arguments like <code>rpc.get_interface_information(terse="True", interface-name="xe-0/0/0")</code>, however for configuration the options need to be within a dictionary like <code>rpc.get_configuration({"inherit":"inherit", "groups":"groups"})</code></p>
<... | 1 | 2016-08-24T16:10:52Z | 39,132,110 | <p>Adding to Edward's answer, I believe the PyEZ RPC calls are implemented using reflection (<code>__call__</code> method), so today it is not aware of valid RPC calls nor args. The way to make it aware would be to load the Netconf schema dynamically from the device and use that to map the named arg to a tag or an elem... | 0 | 2016-08-24T20:01:40Z | [
"python"
] |
In Python 3, convert np.array object type to float type, with variable number of object element | 39,128,514 | <p>I have a np.array with dtype as object. Each element here is a np.array with dtype as float and shape as (2,2) --- in maths, it is a 2-by-2 matrix. My aim is to obtain one 2-dimenional matrix by converting all the object-type element into float-type element. This can be better presented by the following example.</p>... | 1 | 2016-08-24T16:24:03Z | 39,128,686 | <p>Here's a quick way.</p>
<p>Your <code>A</code>:</p>
<pre><code>In [137]: A
Out[137]:
array([[array([[1, 1],
[1, 1]]), array([[2, 2],
[2, 2]])],
[array([[3, 3],
[3, 3]]), array([[4, 4],
[4, 4]])]], dtype=object)
</code></pre>
<p>Use <a href="http://docs.scipy.org/doc/numpy/refer... | 2 | 2016-08-24T16:33:42Z | [
"python",
"arrays",
"matlab",
"numpy"
] |
In Python 3, convert np.array object type to float type, with variable number of object element | 39,128,514 | <p>I have a np.array with dtype as object. Each element here is a np.array with dtype as float and shape as (2,2) --- in maths, it is a 2-by-2 matrix. My aim is to obtain one 2-dimenional matrix by converting all the object-type element into float-type element. This can be better presented by the following example.</p>... | 1 | 2016-08-24T16:24:03Z | 39,129,026 | <p>Your <code>vstack/hstack</code> could be written more compactly, and generally as</p>
<pre><code>In [132]: np.vstack((np.hstack(a) for a in A))
Out[132]:
array([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4]])
</code></pre>
<p>since <code>for a in A</code> iterates on the <code>rows</... | 2 | 2016-08-24T16:53:32Z | [
"python",
"arrays",
"matlab",
"numpy"
] |
Unable to merge multiIndexed pandas dataframes | 39,128,620 | <p>I believe I am ultimately looking for a way to change the dtype of data frame indices. Please allow me to explain:</p>
<p>Each df is multi-indexed on (the same) four levels. One level consists of mixed labels of integers, integer and letters (like D8), and just letters. </p>
<p>However, for df1, the integers w... | 1 | 2016-08-24T16:30:13Z | 39,128,892 | <p>One way to change the level values is to build a new MultiIndex and re-assign it to <code>df.index</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
{'index':[ 26, 30, 46, 48, 72, '1C', '5M', '7D', '7Y',
'8F', '8J', 'AN', 'AS', 'C3', 'CA'],
'foo':1, 'bar':2})
df = df.set_index... | 1 | 2016-08-24T16:45:27Z | [
"python",
"pandas"
] |
Problems when opening xlsx with openpyxl | 39,128,640 | <p>I have a xlsx file and I tried to load this file using openpyxl</p>
<pre><code>from openpyxl import load_workbook
wb = load_workbook('/home/file_path/file.xlsx')
</code></pre>
<p>But I get this error:</p>
<pre><code>"wb = load_workbook(new_file)"): expected string or buffer
</code></pre>
<p>new_file is a variab... | -2 | 2016-08-24T16:31:18Z | 39,128,741 | <p>The syntaxe is:</p>
<pre><code>wb = load_workbook(filename='file.xlsx', read_only=True)
</code></pre>
<p>The <code>read_only</code> keyword is not required.</p>
| 0 | 2016-08-24T16:36:35Z | [
"python",
"xlsx",
"openpyxl"
] |
return Find_element_by_name as a string In Python | 39,128,641 | <p>I need some help form all of you, so I have something like this:</p>
<pre><code>element = driver.find_element_by_name("SiteMinderVarForm")
print (element)
</code></pre>
<p>When I execute the program I receive:</p>
<blockquote>
<p>selenium.webdriver.remote.webelement.WebElement (session="d49d6df9305f2e92eb81aed5... | 1 | 2016-08-24T16:31:28Z | 39,129,433 | <p>From your question, it seems like you want the text value contained in the webelement. You can use the webelement.getAttribute("value") method. If you want to get the name attribute of the webelement with name SiteMinderVarForm:</p>
<pre><code>element = driver.find_element_by_name("SiteMinderVarForm")
value = eleme... | 0 | 2016-08-24T17:18:36Z | [
"python",
"string",
"selenium",
"selenium-webdriver",
"return"
] |
pandas module to trim columns in python | 39,128,643 | <p>Any idea why below code can't keep the first column of my csv file? I would like to keep several columns in a new csv file, first column included. And if I select the name of first column to be on new file.<br>
I get an error :</p>
<blockquote>
<p>"Type" not index.</p>
</blockquote>
<pre><code>import pandas as ... | 0 | 2016-08-24T16:31:34Z | 39,128,748 | <p>You are better off by specifying the columns to read from your csv file.</p>
<pre><code>pd.read_csv('1.csv', names=keep_col).to_csv("2.csv", index=False)
</code></pre>
<p>Do you have any special characters in your first column?</p>
| 0 | 2016-08-24T16:37:07Z | [
"python",
"csv",
"pandas"
] |
pandas module to trim columns in python | 39,128,643 | <p>Any idea why below code can't keep the first column of my csv file? I would like to keep several columns in a new csv file, first column included. And if I select the name of first column to be on new file.<br>
I get an error :</p>
<blockquote>
<p>"Type" not index.</p>
</blockquote>
<pre><code>import pandas as ... | 0 | 2016-08-24T16:31:34Z | 39,129,063 | <p>Try <code>f.columns.values.tolist()</code> and check the output of the first column. It sounds like there is an encoding issue when you are reading the CSV. You can try specifying the "encoding" option in your <code>pd.read_csv()</code> to see if that will get rid of the extra characters at the front. Otherwise, ... | 0 | 2016-08-24T16:56:05Z | [
"python",
"csv",
"pandas"
] |
pymetar.py metar weather library stopped working | 39,128,651 | <p>I was using Tobias Klausmann's pymetar.py to fetch airport weather metar reports. It stopped working.
<a href="http://www.nws.noaa.gov/om/notification/scn16-16wngccb.htm" rel="nofollow">http://www.nws.noaa.gov/om/notification/scn16-16wngccb.htm</a> They shut the service down.
<a href="http://weather.noaa.gov/pub/d... | 0 | 2016-08-24T16:31:55Z | 39,128,652 | <p>You can fix it by changing line 1047 in pymetar.py to
<a href="http://tgftp.nws.noaa.gov/data/observations/metar/decoded/" rel="nofollow">http://tgftp.nws.noaa.gov/data/observations/metar/decoded/</a>
Hope that helps you!</p>
| 0 | 2016-08-24T16:31:55Z | [
"python",
"weather",
"airport"
] |
Error while using Graphlab Create Jupyter | 39,128,663 | <p>I have recently upgraded the Graph Lab create version that I had. While running codes using the Jupyter console I came up with the following errors:</p>
<pre><code>from __future__ import division
import graphlab
import math
import string
**Error:
ACTION REQUIRED: Dependencies libstdc++-6.dll and libgcc_s_seh-1.dll... | 1 | 2016-08-24T16:32:32Z | 39,132,310 | <p>Firstly, make sure Jupyter notebook is CLOSED.</p>
<ol>
<li>Open the GraphLab Create Launcher and go to the 'TERMINAL' button.</li>
<li>Type in <code>import graphlab</code> (there may be an error message, just ignore it).</li>
<li>Now type in <code>graphlab.get_dependencies()</code></li>
</ol>
<p>The terminal will... | 0 | 2016-08-24T20:14:07Z | [
"python",
"ipython",
"jupyter-notebook",
"graphlab"
] |
Transitive reduction - Error with code - Python | 39,128,698 | <p>So I am trying to write a code to do transitive reduction of Acyclic graph.
So the elements are: </p>
<blockquote>
<p>(3, 5), (5, 2), (2, 1), (4, 2), (3, 1), (4, 1)</p>
</blockquote>
<p>This is what I have written so far: </p>
<pre><code>graph = [[3, 5],[5, 2],[2, 1],[4, 2],[3, 1],[4, 1]]
for i in range(len(g... | 0 | 2016-08-24T16:34:19Z | 39,129,455 | <p>I improved your code, I added a condition <code>if a in graph:</code> because in some cases the Transtive reduction appears and the element [i,k] doesn't exist. Also the function <code>pop()</code> removes an element by index, not by object like <code>remove()</code>.</p>
<pre><code>graph = [[3, 5],[5, 2],[2, 1],[4... | 1 | 2016-08-24T17:20:29Z | [
"python",
"list",
"graph",
"transitive-closure"
] |
Implementing HWID checking system for Python scripts? | 39,128,733 | <p>Let's say I was selling a software and I didn't want it to be leaked (of course using Python wouldn't be the greatest as all code is open but let's just go with it), I would want to get a unique ID that only the user's PC has and store it within a list in my script. Now every time someone executed the script it woul... | -1 | 2016-08-24T16:36:17Z | 39,129,406 | <p>Python has a unique id library <code>uuid</code>. <a href="https://docs.python.org/3.5/library/uuid.html" rel="nofollow">https://docs.python.org/3.5/library/uuid.html</a></p>
<pre><code>import uuid
# Create a uuid
customer_id = str(uuid.uuid4())
software_ids = [customer_id] # Store in a safe secure place
can_run =... | 0 | 2016-08-24T17:17:08Z | [
"python"
] |
Downloading a song through python-requests | 39,128,738 | <p>I was trying to make a script to download songs from internet. I was first trying to download the song by using "requests" library. But I was unable to play the song. Then, I did the same using "urllib2" library and I was able to play the song this time.</p>
<p>Can't we use "requests" library to download songs? If ... | 0 | 2016-08-24T16:36:28Z | 39,128,806 | <p>Use <code>doc.content</code> to save <a href="http://docs.python-requests.org/en/master/user/quickstart/#binary-response-content" rel="nofollow">binary data</a>:</p>
<pre><code>import requests
doc = requests.get('http://gaana99.com/fileDownload/Songs/0/28768.mp3')
with open('movie.mp3', 'wb') as f:
f.write(doc... | 3 | 2016-08-24T16:40:55Z | [
"python",
"httprequest",
"urllib2"
] |
Python Key Error With _ | 39,128,761 | <p>I'm getting a weird key error with Python dicts. My key is "B19013_001E" and I've named my dict "sf_tracts" with a nested dict "properties". Here is my code:</p>
<pre><code>x = "B19013_001E"
for tract in sf_tracts:
print tract["properties"][x]
</code></pre>
<p>With this, I get a KeyError: "B19013_001E"</p>
<p... | -1 | 2016-08-24T16:38:06Z | 39,128,891 | <p>You are assuming that the key exists in <em>all</em> dictionaries that the <code>tract in sf_tracts</code> loop produces. That assumption is incorrect.</p>
<p>Your second piece of code happens to work because you are essentially testing for the key to exist, albeit expensively. You could instead do this:</p>
<pre>... | 3 | 2016-08-24T16:45:23Z | [
"python",
"dictionary"
] |
Python Key Error With _ | 39,128,761 | <p>I'm getting a weird key error with Python dicts. My key is "B19013_001E" and I've named my dict "sf_tracts" with a nested dict "properties". Here is my code:</p>
<pre><code>x = "B19013_001E"
for tract in sf_tracts:
print tract["properties"][x]
</code></pre>
<p>With this, I get a KeyError: "B19013_001E"</p>
<p... | -1 | 2016-08-24T16:38:06Z | 39,128,893 | <p>Some of your tracts must be missing that particular key. In the first case, you're asking every tract to print the key, while in the second you're limiting the print operation to only those that have the key.</p>
| 1 | 2016-08-24T16:45:31Z | [
"python",
"dictionary"
] |
Is it necessary to divide a file into chunks for encryption | 39,128,855 | <p>I was reading the code for a <a href="https://github.com/z7ev3n/ransomware/blob/master/ransomcrypto.py" rel="nofollow">ransom ware</a>. As per the code, the author had divided the files into 64 kb chunks to encrypt . I am unable to understand why.</p>
| 1 | 2016-08-24T16:43:12Z | 39,128,936 | <p>Why is unknown and was a choice by the attack code writer.</p>
<p>It is not necessary to limit file sizes to 64KB using current encryption methods such as AES. Most implementations handle files of any size although it is wise to limit the size to 2^68 bytes for AES.</p>
| 0 | 2016-08-24T16:47:39Z | [
"python",
"encryption",
"cryptography",
"aes",
"pycrypto"
] |
Is it necessary to divide a file into chunks for encryption | 39,128,855 | <p>I was reading the code for a <a href="https://github.com/z7ev3n/ransomware/blob/master/ransomcrypto.py" rel="nofollow">ransom ware</a>. As per the code, the author had divided the files into 64 kb chunks to encrypt . I am unable to understand why.</p>
| 1 | 2016-08-24T16:43:12Z | 39,131,306 | <p>If you look at the code, the encryptor reads 1024 * blocksize of bytes (actually 16 KiB) as a single chunk and uses the same cipher object to encrypt each chunk separately. </p>
<p>This must be done in order to be able to encrypt large files, because some files are simply too large to be read in full into the memor... | 1 | 2016-08-24T19:11:10Z | [
"python",
"encryption",
"cryptography",
"aes",
"pycrypto"
] |
Python - Drop row if two columns are NaN | 39,128,856 | <p>This is an extension to <a href="http://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-of-certain-column-is-nan">this question</a>, where OP wanted to know how to drop rows where the values in a single column are NaN.</p>
<p>I'm wondering how I can drop rows where the values i... | 2 | 2016-08-24T16:43:13Z | 39,128,913 | <p>Any one of the following two:</p>
<pre><code>df.dropna(subset=[1, 2], how='all')
</code></pre>
<p>or </p>
<pre><code>df.dropna(subset=[1, 2], thresh=1)
</code></pre>
| 3 | 2016-08-24T16:46:26Z | [
"python",
"pandas",
"dataframe"
] |
Python - Drop row if two columns are NaN | 39,128,856 | <p>This is an extension to <a href="http://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-of-certain-column-is-nan">this question</a>, where OP wanted to know how to drop rows where the values in a single column are NaN.</p>
<p>I'm wondering how I can drop rows where the values i... | 2 | 2016-08-24T16:43:13Z | 39,128,984 | <p>Specify <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow"><code>dropna()</code></a> method:</p>
<pre><code>df.dropna(subset=[1,2], how='all')
</code></pre>
| 2 | 2016-08-24T16:50:14Z | [
"python",
"pandas",
"dataframe"
] |
How to generate and save POJO from H2O using Python | 39,128,865 | <p>I have a model created in H2O using Python. I want to generate a POJO of that model, and save it. </p>
<p>Say my model is called model_rf. </p>
<p>I have tried: </p>
<pre><code>h2o.save_model(model_rf, path='./pojo_test', force=False)
</code></pre>
<p>This create a directory called "pojo_test", which contains a ... | 0 | 2016-08-24T16:43:55Z | 39,129,724 | <p>Everything looks fine, it just looks like you need to change the <code>path</code> you used.</p>
<p>Instead of using the directory that <code>h2o.save_model</code> created, use a directory that you know exists and for which you know the path. As a first test you could just save to your desktop, for example use </p>... | 0 | 2016-08-24T17:37:26Z | [
"python",
"pojo",
"h2o"
] |
pyquery (lxml) not finding a tag in a well-structured XML document? | 39,128,909 | <p>I have an XML file that looks like <a href="https://clinicaltrials.gov/ct2/show/NCT00636649?displayxml=true" rel="nofollow">this</a>. The relevant bit is this: </p>
<pre><code><reference>
<citation>Vander Wal JS, Gang CH, Griffing GT, Gadde KM. Escitalopram for treatment of night eating syndrome: a 12... | 1 | 2016-08-24T16:46:10Z | 39,129,070 | <p>You can specifiy the parser to use and it will work:</p>
<pre><code>d = pq(text, parser='xml')
</code></pre>
| 0 | 2016-08-24T16:56:51Z | [
"python",
"lxml",
"pyquery"
] |
Kernel crashes when increasing iterations | 39,128,973 | <p>I am running a Python script using Spyder 2.3.9. I have a fairly large script and when running it through with (300x600) iterations (a loop inside another loop), everything appears to be working fine and takes approximately 40 minutes. But when I increase the number to (500x600) iterations, after 2 hours, the output... | 1 | 2016-08-24T16:49:34Z | 39,129,149 | <p><a href="https://github.com/spyder-ide/spyder/issues/3114" rel="nofollow">https://github.com/spyder-ide/spyder/issues/3114</a></p>
<p>It seems this issue has been opened on their GitHub profile, should be addressed soon given the repo record.</p>
<p>Some possible solutions:</p>
<ol>
<li><p>It may be helpful, if p... | 0 | 2016-08-24T17:01:12Z | [
"python",
"python-2.7",
"anaconda",
"spyder"
] |
Program works, but TypeError: 'int' object is not subscriptable is received. Why? | 39,129,057 | <p>This program checks to see if a string is a palindrome then returns true if it is. It works fine when I run it in the Python IDLE. But is not accepted on the online testing site, returning this error: "<strong>TypeError: 'int' object is not subscriptable</strong>"</p>
<pre><code>string="racecar"
def is_palindrome(s... | 0 | 2016-08-24T16:55:29Z | 39,129,517 | <p>You obviously want your function to only operate on strings, and unless you're using a quite new version of Python supporting type hints, you can't really tell Python that. So just cast to string right off the bat. Almost anything can be cast to a string and then your function will work no matter what it is passed, ... | 0 | 2016-08-24T17:24:39Z | [
"python",
"string",
"slice",
"typeerror"
] |
Pandas realization of leave one out encoding for categorical features | 39,129,085 | <p>I have recently watched a video from Owen Zhang kaggle rank 1 competitor:
<a href="https://youtu.be/LgLcfZjNF44" rel="nofollow">https://youtu.be/LgLcfZjNF44</a>
where he explains a technique of encoding categorical features to numerical which is called leave one out encoding. What he does to a categorical feature is... | 1 | 2016-08-24T16:57:38Z | 39,129,252 | <p>Replace each element of the Series with difference between the sum of the Series and the element, then divide by the length of the series minus 1. Assuming <code>s</code> is your Series:</p>
<pre><code>s = (s.sum() - s)/(len(s) - 1)
</code></pre>
<p>The resulting output:</p>
<pre><code>159812 39.00
464556 ... | 3 | 2016-08-24T17:07:51Z | [
"python",
"pandas",
"categorical-data"
] |
Pandas realization of leave one out encoding for categorical features | 39,129,085 | <p>I have recently watched a video from Owen Zhang kaggle rank 1 competitor:
<a href="https://youtu.be/LgLcfZjNF44" rel="nofollow">https://youtu.be/LgLcfZjNF44</a>
where he explains a technique of encoding categorical features to numerical which is called leave one out encoding. What he does to a categorical feature is... | 1 | 2016-08-24T16:57:38Z | 39,140,923 | <p>WIth help from @root I have found out that the fastest solution to this problem would be this kind of approach:</p>
<pre><code>cs = train.groupby(by=['Cliente_ID'])['Demanda_uni_equil'].sum()
cc = train['Cliente_ID'].value_counts()
boolean = (cc == 1)
index = boolean[boolean == True].index.values
cc.loc[boolean] +=... | 0 | 2016-08-25T09:01:27Z | [
"python",
"pandas",
"categorical-data"
] |
Add a delay while curl is downloading python script and then pipe to execute script? | 39,129,116 | <p>I just created a rickroll prank to play on friends and family. I want to be able to download the file from github using a curl command which works. My issue is that when I use a pipe and try to execute the script it does it right after curl gets executed and before it downloads the file.</p>
<p>This is the command ... | -1 | 2016-08-24T16:59:31Z | 39,132,600 | <p>Expanding on my comment.</p>
<p>There are several ways to chain commands using most shell languages (here I assume sh / bash dialect).</p>
<ul>
<li>The most basic: <code>;</code> will just run each command sequentially, starting the next one as the previous one completes.</li>
<li>Conditional chaining, <code>&... | 1 | 2016-08-24T20:34:55Z | [
"python",
"linux",
"curl",
"pipe"
] |
How to read Certification details in django Request Object? | 39,129,133 | <p>We are trying integrate with Azure store. Azure store calls our API(built in django restframework) and along with request payload they send Certification details in request. </p>
<p>But, I cannot see the certification details (X509Certificate) in Django request Header, body, cookies or session.</p>
<p>Can any one ... | 0 | 2016-08-24T17:00:30Z | 39,132,438 | <p>I don't know anything about X509 but a quick Google reveals <a href="https://github.com/novafloss/django-x509" rel="nofollow">this library</a> which will probably help you.</p>
| 1 | 2016-08-24T20:24:11Z | [
"python",
"django",
"django-rest-framework",
"x509certificate",
"azure-store"
] |
Python counts duplicates as uniques in csv file | 39,129,165 | <p>I've written a script that takes the html table from the executed offenders in Texas (can't post link due to restrictions but can be found in code for getcsv.py) and converts it into a csv file. Another script then counts up the races of each person. However, I've been having an issue where it counts all but one of ... | 0 | 2016-08-24T17:01:50Z | 39,129,256 | <p>Whitespaces are important. You have to strip them away, if the keys should be the same:</p>
<pre><code>with open('new.csv') as input_file:
next(input_file)
race = collections.Counter(row[8].strip()
for row in csv.reader(input_file, delimiter=','))
</code></pre>
| 2 | 2016-08-24T17:08:07Z | [
"python",
"csv"
] |
Tivix - angular-django-registration-auth with Ionic? | 39,129,184 | <p>I'm trying to create a user registration with Ionic and I installed Tivix's django backend, and the angular-django in eh front end. The thing is, I'm trying to incorporate it into Ionic. </p>
<p><a href="http://imgur.com/a/rpR65" rel="nofollow">Here's my app structure in Visual Studio</a></p>
<p><a href="http://im... | 0 | 2016-08-24T17:03:04Z | 39,184,507 | <p>Solved. <a href="https://creator.ionic.io/" rel="nofollow">Ionic Creator is your friend.</a></p>
| 0 | 2016-08-27T18:37:29Z | [
"python",
"angularjs",
"django",
"ionic-framework",
"django-rest-auth"
] |
how to use *and* in pandas loc API | 39,129,224 | <p>I try do use <em>and</em> in a <code>.loc</code> API::</p>
<pre><code>df = pd.DataFrame(dict(age=[99, 33, 33, 22, 33, 44],
aa2=[199, 3, 43, 22, 23, 54],
nom=['a', 'z', 'f', 'b', 'p', 'a'],))
df.loc[df.age>30]
# aa2 age nom
# 0 199 99 a
# 1 3 33 z
# 2 ... | 2 | 2016-08-24T17:05:52Z | 39,129,262 | <pre><code>>>> df.loc[(df.age>30) & (df.age > df.aa2)]
aa2 age nom
1 3 33 z
4 23 33 p
</code></pre>
| 3 | 2016-08-24T17:08:41Z | [
"python",
"pandas"
] |
how to use *and* in pandas loc API | 39,129,224 | <p>I try do use <em>and</em> in a <code>.loc</code> API::</p>
<pre><code>df = pd.DataFrame(dict(age=[99, 33, 33, 22, 33, 44],
aa2=[199, 3, 43, 22, 23, 54],
nom=['a', 'z', 'f', 'b', 'p', 'a'],))
df.loc[df.age>30]
# aa2 age nom
# 0 199 99 a
# 1 3 33 z
# 2 ... | 2 | 2016-08-24T17:05:52Z | 39,131,686 | <p>I do prefer a bit nicer and more readable <a href="https://pandas-docs.github.io/pandas-docs-travis/indexing.html#the-query-method-experimental" rel="nofollow">query()</a> method:</p>
<pre><code>In [3]: df.query('age > 30 and age > aa2')
Out[3]:
aa2 age nom
1 3 33 z
4 23 33 p
</code></pre>
<... | 2 | 2016-08-24T19:34:43Z | [
"python",
"pandas"
] |
How to make Django rest_framework Session Authentication case insensitive? | 39,129,289 | <p>I'm using Django rest framework basic authentication with the following code:</p>
<pre><code>class MyBasicAuthentication(BasicAuthentication):
def authenticate_header(self, request):
return 'xBasic realm="%s"' % self.www_authenticate_realm
class AuthView(APIView):
authentication_classes = (MyBasi... | 0 | 2016-08-24T17:10:02Z | 39,129,486 | <p>How about just choosing all upper or all lower case characters for the username stored in the database. IE for all uppercase:</p>
<pre><code>user = authenticate(username=str(request.user.username).upper(), password=request.user.password)
</code></pre>
<p>This way the input can be mixed case but the output in stan... | 0 | 2016-08-24T17:22:53Z | [
"python",
"django",
"authentication",
"django-rest-framework",
"case-insensitive"
] |
How to make Django rest_framework Session Authentication case insensitive? | 39,129,289 | <p>I'm using Django rest framework basic authentication with the following code:</p>
<pre><code>class MyBasicAuthentication(BasicAuthentication):
def authenticate_header(self, request):
return 'xBasic realm="%s"' % self.www_authenticate_realm
class AuthView(APIView):
authentication_classes = (MyBasi... | 0 | 2016-08-24T17:10:02Z | 39,129,918 | <p>The simplest way of doing this is standardizing the way you store the usernames (in upper or lower case as @Upsampled answered) which would mean that the authentication that occurs first would not have a problem. If you want to change all existing users to a particular case I would recommend this answer <a href="htt... | 0 | 2016-08-24T17:48:39Z | [
"python",
"django",
"authentication",
"django-rest-framework",
"case-insensitive"
] |
TypeError: object of type 'bool' has no len() - Odoo v9 community | 39,129,302 | <p>I still have this error on another part of the code:</p>
<pre><code>class invoice(models.Model):
_inherit = "account.invoice"
@api.multi
def send_xml_file(self):
# haciendolo para efacturadelsur solamente por ahora
host = 'https://www.efacturadelsur.cl'
post = '/ws/DTE.asmx' # HTTP/1.1
url = host +... | 0 | 2016-08-24T17:10:40Z | 39,131,549 | <p>To avoid dragging on the conversation in the comments, I am going to take a crack at an actual answer.</p>
<p>It seems like your object <code>self.sii_xml_request</code> can be either a). a string, or b). a boolean (<code>True</code> or <code>False</code>) (though please correct me if I am wrong).</p>
<p>You are g... | 1 | 2016-08-24T19:26:45Z | [
"python",
"openerp",
"odoo-9"
] |
TypeError: object of type 'bool' has no len() - Odoo v9 community | 39,129,302 | <p>I still have this error on another part of the code:</p>
<pre><code>class invoice(models.Model):
_inherit = "account.invoice"
@api.multi
def send_xml_file(self):
# haciendolo para efacturadelsur solamente por ahora
host = 'https://www.efacturadelsur.cl'
post = '/ws/DTE.asmx' # HTTP/1.1
url = host +... | 0 | 2016-08-24T17:10:40Z | 39,193,597 | <p>this kind of error when you get 'bool' in the message that means that you calling a function on an empty field so before you call any function check if the field has value first. because in odoo empty field contain False value not None i had this error many times every time i found out that i'm calling the function ... | 1 | 2016-08-28T16:48:25Z | [
"python",
"openerp",
"odoo-9"
] |
Why does printing a dataframe break python when constructed from numpy empty_like | 39,129,419 | <pre><code>import numpy as np
import pandas as pd
</code></pre>
<p>consider numpy array <code>a</code></p>
<pre><code>a = np.array([None, None], dtype=object)
print(a)
[None None]
</code></pre>
<p>And <code>dfa</code></p>
<pre><code>dfa = pd.DataFrame(a)
print(dfa)
0
0 None
1 None
</code></pre>
<p>Now co... | 10 | 2016-08-24T17:17:52Z | 39,131,997 | <p>As reported <a href="https://github.com/pydata/pandas/issues/14082">here,</a> this is a bug, which is fixed in the master branch of <code>pandas</code> / the upcoming <code>0.19.0</code> release.</p>
| 7 | 2016-08-24T19:54:46Z | [
"python",
"pandas",
"numpy"
] |
What is the correct format to upgrade pip3 when the default pip is pip2? | 39,129,450 | <p>I develop for both <code>Python 2</code> and <code>3.</code><br>
Thus, I have to use both <code>pip2</code> and <code>pip3.</code></p>
<p>When using <code>pip3 -</code> I receive this upgrade request (last two lines):</p>
<pre><code>$ pip3 install arrow
Requirement already satisfied (use --upgrade to upgrade): arr... | 2 | 2016-08-24T17:20:10Z | 39,129,467 | <p>Just use the <code>pip3</code> command you already have:</p>
<pre><code>pip3 install --upgrade pip
</code></pre>
<p>The installed <em>project</em> is called <code>pip</code>, always. The <code>pip3</code> command is tied to your Python 3 installation and is an alias for <code>pip</code>, but the latter is shadowed... | 7 | 2016-08-24T17:21:11Z | [
"python",
"python-3.x",
"cygwin",
"pip",
"python-3.4"
] |
Python 3: How can I align the the format of this data when it prints | 39,129,603 | <p>I would like the format of this data to me uniform for the user to read but I cannot with everything I have tried. Code here :</p>
<pre><code>def runModel():
global valueJuvenile, valueAdult, valueSenile,total, values
values = ''
total = valueSenile + valueJuvenile + valueAdult
values += 'G' + ', '
values += 'Juv' ... | 1 | 2016-08-24T17:29:39Z | 39,129,734 | <p>The <a href="https://docs.python.org/3.4/library/stdtypes.html#str.format" rel="nofollow"><code>format</code></a> function will do the trick.</p>
<p>Here an example on how to use it:</p>
<pre><code>>>> integer_var = 5
>>> float_var = 3.5
>>> print('{:6d} {:6.2f}'.format(integer_var, floa... | 2 | 2016-08-24T17:38:01Z | [
"python",
"python-3.x",
"formatting"
] |
Python 3: How can I align the the format of this data when it prints | 39,129,603 | <p>I would like the format of this data to me uniform for the user to read but I cannot with everything I have tried. Code here :</p>
<pre><code>def runModel():
global valueJuvenile, valueAdult, valueSenile,total, values
values = ''
total = valueSenile + valueJuvenile + valueAdult
values += 'G' + ', '
values += 'Juv' ... | 1 | 2016-08-24T17:29:39Z | 39,129,840 | <p>Use <code>format</code>. For example:</p>
<pre><code>def runModel(valueJuvenile, valueAdult, valueSenile,total, values):
header = ['G', 'Juv', 'Adu', 'Sen', 'Tot']
format = "{:5}, {:5}, {:5}, {:5}, {:5}".format
values = [format(*header)]
values.append(format(n, valueJuvenile, valueAdult, valueSenile... | 2 | 2016-08-24T17:43:13Z | [
"python",
"python-3.x",
"formatting"
] |
Python 3: How can I align the the format of this data when it prints | 39,129,603 | <p>I would like the format of this data to me uniform for the user to read but I cannot with everything I have tried. Code here :</p>
<pre><code>def runModel():
global valueJuvenile, valueAdult, valueSenile,total, values
values = ''
total = valueSenile + valueJuvenile + valueAdult
values += 'G' + ', '
values += 'Juv' ... | 1 | 2016-08-24T17:29:39Z | 39,129,899 | <p>You can use C style format strings, or the .format method.</p>
<p>As an example using C style format strings, you can do:</p>
<pre><code>print("%2i, %5.1f, %5.1f, %5.1f" % (3, 11.2, 5.0, 77.5))
print("%2i, %5.1f, %5.1f, %5.1f" % (11, 12.7, 11.4, 8.1))
</code></pre>
<p>This would give the following results:</p>
<... | 1 | 2016-08-24T17:47:27Z | [
"python",
"python-3.x",
"formatting"
] |
xpath query not grabbing any information - python | 39,129,791 | <p>I am trying to grab some information off <a href="http://www.mountainproject.com/v/my-other-woman-is-a-hand-crack/107465606" rel="nofollow">this page </a></p>
<p>but there are three pieces of data I have been unable to grab. The first is the grade, which is the '5.6' next to the YDS near the top. The second is FF... | 0 | 2016-08-24T17:40:47Z | 39,131,649 | <p>Not sure what framework you are using but this seems to work:</p>
<pre><code>from lxml import html
import urllib2
req = urllib2.Request('http://www.mountainproject.com/v/my-other-woman-is-a-hand-crack/107465606')
response = urllib2.urlopen(req)
data = response.read()
tree = html.fromstring(data)
grade = tree.xpath(... | 0 | 2016-08-24T19:32:30Z | [
"jquery",
"python",
"html",
"css",
"xpath"
] |
Sort list of mixed strings based on digits | 39,129,846 | <p>How do I sort this list via the numerical values? Is a regex required to remove the numbers or is there a more Pythonic way to do this?</p>
<pre><code>to_sort
['12-foo',
'1-bar',
'2-bar',
'foo-11',
'bar-3',
'foo-4',
'foobar-5',
'6-foo',
'7-bar']
</code></pre>
<p>Desired output is as follows:</p>
<pre><c... | 6 | 2016-08-24T17:43:34Z | 39,129,897 | <p>One solution is the following regex extraction:</p>
<pre><code>sorted(l, key=lambda x: int(re.search('\d+', x).group(0)))
</code></pre>
<hr>
<pre><code>>>> l
['12-foo', '1-bar', '2-bar', 'foo-11', 'bar-3', 'foo-4', 'foobar-5', '6-foo', '7-bar']
>>> sorted(l, key=lambda x: int(re.search('\d+', x)... | 10 | 2016-08-24T17:47:18Z | [
"python"
] |
Sort list of mixed strings based on digits | 39,129,846 | <p>How do I sort this list via the numerical values? Is a regex required to remove the numbers or is there a more Pythonic way to do this?</p>
<pre><code>to_sort
['12-foo',
'1-bar',
'2-bar',
'foo-11',
'bar-3',
'foo-4',
'foobar-5',
'6-foo',
'7-bar']
</code></pre>
<p>Desired output is as follows:</p>
<pre><c... | 6 | 2016-08-24T17:43:34Z | 39,129,940 | <p>If you don't want to use regex</p>
<pre><code>>>> l = ['12-foo', '1-bar', '2-bar', 'foo-11', 'bar-3', 'foo-4', 'foobar-5', '6-foo', '7-bar']
>>> sorted(l, key = lambda x: int(''.join(filter(str.isdigit, x))))
['1-bar', '2-bar', 'bar-3', 'foo-4', 'foobar-5', '6-foo', '7-bar', 'foo-11', '12-foo']
... | 4 | 2016-08-24T17:50:01Z | [
"python"
] |
Why can I connect to Azure MS SQL with tsql but not pymssql? | 39,129,928 | <p>Where I am today:</p>
<pre><code>TDSVER=7.3 tsql -H example.database.windows.net -U me -D ExampleDB -p 1433 -P notreallymypassword
</code></pre>
<p>This does not:</p>
<pre><code>>>> import pymssql
>>> pymssql.connect('example.database.windows.net', user='me', password='notreallymypassword', data... | 1 | 2016-08-24T17:49:33Z | 39,131,020 | <p>Your connection string doesn't look right. It should be something like:</p>
<pre><code>pymssql.connect(server='example.database.windows.net', user='me@example', password='notreallymypassword', database='ExampleDB')
</code></pre>
<p>Note that in your example call to <code>connect()</code>, you are missing a <code>s... | 0 | 2016-08-24T18:53:36Z | [
"python",
"azure",
"sql-azure",
"pymssql"
] |
Why can I connect to Azure MS SQL with tsql but not pymssql? | 39,129,928 | <p>Where I am today:</p>
<pre><code>TDSVER=7.3 tsql -H example.database.windows.net -U me -D ExampleDB -p 1433 -P notreallymypassword
</code></pre>
<p>This does not:</p>
<pre><code>>>> import pymssql
>>> pymssql.connect('example.database.windows.net', user='me', password='notreallymypassword', data... | 1 | 2016-08-24T17:49:33Z | 39,398,758 | <p>It looks like Gord was right: The problem was that <code>pymssql</code> wheel <em>does not have SSL bindings</em>.</p>
<p>I uninstalled it:</p>
<pre><code>python -m pip uninstall pymssql
</code></pre>
<p>Then installed it from source:</p>
<pre><code>python -m pip install --no-binary pymssql pymssql
</code></pre>... | 1 | 2016-09-08T19:26:55Z | [
"python",
"azure",
"sql-azure",
"pymssql"
] |
if allwords in title: match | 39,130,043 | <p>Using python3, i have a list of words like:
<code>['foot', 'stool', 'carpet']</code> </p>
<p>these lists vary in length from 1-6 or so. i have thousands and thousands of strings to check, and it is required to make sure that all three words are present in a title. where:
<code>'carpet stand upon the stool of foot b... | 1 | 2016-08-24T17:56:40Z | 39,130,067 | <p>You can use <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all()</code></a>:</p>
<pre><code>words = ['foot', 'stool', 'carpet']
title = "carpet stand upon the stool of foot balls."
matches = all(word in title for word in words)
</code></pre>
<p>Or, inverse the logic with not <... | 5 | 2016-08-24T17:58:08Z | [
"python",
"list",
"python-3.x",
"matching",
"word"
] |
Python: Inserting string into Mysql Database | 39,130,049 | <p>I am using Python with Mysql.</p>
<p>I have a string that looks something like this:</p>
<p>s = "1.xxxxxxxxx 2.xxxxxxxxx 3.xxxxxxxxx"</p>
<p>Now I want to insert this string in db with one line in one row. For example</p>
<ol>
<li>xxxxxxx</li>
<li>xxxxxxx</li>
<li>xxxxxxx</li>
</ol>
<p>Each line gets inserted i... | 1 | 2016-08-24T17:57:02Z | 39,130,773 | <p>The first thing you need to do is properly split the string. In this case, if your example data is correct, you can accomplish this by splitting on the space character:</p>
<pre><code>lines = string.split(' ')
</code></pre>
<p>Now, if I understand your code correctly, we need to insert only the lines that contain ... | 0 | 2016-08-24T18:39:33Z | [
"python",
"mysql"
] |
Button Widget Not Getting Destroyed While Trying To Remove From The Grid | 39,130,055 | <p>a. Have a scenario where I wanted to remove a button after few clicks.
b. But when the button reaches the last click, its not getting destroyed.
Code as given below:</p>
<pre><code>from tkinter import *
class test_button:
def __init__(self, master):
self.master = master
self.next_button = None... | 0 | 2016-08-24T17:57:23Z | 39,130,467 | <p>Change</p>
<pre><code>self.next_button = Button(root, background="orange red", activebackground="orangered3", text="Next Test Config", command=self.next_button_code).grid(row=1, column=1)
</code></pre>
<p>to:</p>
<pre><code>self.next_button = Button(root, background="orange red", activebackground="orangered3", te... | 1 | 2016-08-24T18:21:09Z | [
"python",
"python-2.7",
"tkinter"
] |
Fast/Memory-Conserving Manner to remove vectors from array if they are too close in Euclidean Space | 39,130,072 | <p>In order to make clustering a more feasible task, I want to remove items from an array if they have another item which is within some threshold in n-dimensional euclidean space. The input data into this truncation is an array of pixel-wise feature vectors. My first thought was to compute the pairwise euclidean dista... | 0 | 2016-08-24T17:58:23Z | 39,133,784 | <p>Depending on the number of dimensions n, number of points N, the size of the problem in each dimension L, and your acceptable separation distance d, one option would be to grid your space into boxes of dimension d and retain at most one point within each grid box. Memory requirement would change from O(N^2) to O((L/... | 0 | 2016-08-24T22:10:31Z | [
"python",
"arrays",
"algorithm",
"matrix",
"memory-management"
] |
Fast/Memory-Conserving Manner to remove vectors from array if they are too close in Euclidean Space | 39,130,072 | <p>In order to make clustering a more feasible task, I want to remove items from an array if they have another item which is within some threshold in n-dimensional euclidean space. The input data into this truncation is an array of pixel-wise feature vectors. My first thought was to compute the pairwise euclidean dista... | 0 | 2016-08-24T17:58:23Z | 39,135,221 | <p>A KD tree should be faster/more efficient than your base approach, and scipy has a nice implementation for your use case. The runtime is O(nlog(n)), and while I'm not sure about the memory use one would assume it's only storing the pairs you'll want to delete.</p>
<p>Pengiuno's recommendation of grid sampling metho... | 0 | 2016-08-25T01:11:20Z | [
"python",
"arrays",
"algorithm",
"matrix",
"memory-management"
] |
Fast/Memory-Conserving Manner to remove vectors from array if they are too close in Euclidean Space | 39,130,072 | <p>In order to make clustering a more feasible task, I want to remove items from an array if they have another item which is within some threshold in n-dimensional euclidean space. The input data into this truncation is an array of pixel-wise feature vectors. My first thought was to compute the pairwise euclidean dista... | 0 | 2016-08-24T17:58:23Z | 39,149,590 | <p>By Penguino's suggestion, I've gridded the hyperrectangle containing my points. Since the number of dimensions is undefined (I have multiple vector lengths that I'm dealing with at different points), I can't actually partition the space without recursion (I'm being slightly lazy with this), so I've created a workaro... | 0 | 2016-08-25T15:46:07Z | [
"python",
"arrays",
"algorithm",
"matrix",
"memory-management"
] |
How can I import data from this .dat file | 39,130,145 | <p>I have data in a file that looks like this:</p>
<p><img src="http://i.stack.imgur.com/8p9zG.png" alt="screenshot of the file"></p>
<p>As you can see the data is very neat, but it is not separated in a concise fashion, but rather a variable number of spaces between columns and some columns left blank. This makes it... | -2 | 2016-08-24T18:02:24Z | 39,130,709 | <p>try import it and see what you get.</p>
<pre><code>media = []
with open("filename.dat", "r") as f:
media.append(f.readlines())
for row in media:
do something with row
</code></pre>
<p>on 2nd thought it looks like it may be tab-delimited:</p>
<pre><code>import csv
with open("filename.dat", "rB") as f:
... | 0 | 2016-08-24T18:36:14Z | [
"python",
"excel",
"data-files"
] |
How can I import data from this .dat file | 39,130,145 | <p>I have data in a file that looks like this:</p>
<p><img src="http://i.stack.imgur.com/8p9zG.png" alt="screenshot of the file"></p>
<p>As you can see the data is very neat, but it is not separated in a concise fashion, but rather a variable number of spaces between columns and some columns left blank. This makes it... | -2 | 2016-08-24T18:02:24Z | 39,132,491 | <p>This is a fixed width file, so using pandas with python is the way to go:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_fwf.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_fwf.html</a></p>
| 0 | 2016-08-24T20:27:58Z | [
"python",
"excel",
"data-files"
] |
How to retrieve a GET variable with a hash in it | 39,130,162 | <p>I have the following variable that is passed in a url:</p>
<p><a href="http://localhost:8000/diff/?Platform=Comcast&PlatformID=7066191365225244112#S8" rel="nofollow">http://localhost:8000/diff/?Platform=Comcast&PlatformID=7066191365225244112#S8</a></p>
<p>I need to be able to extract the following:</p>
<p... | 2 | 2016-08-24T18:03:40Z | 39,130,195 | <p>Escape it in the query string, basically replace the hash with %23.</p>
<p>To answer your question in the comments, yes, there is a template tag that can help you with this. The syntax is</p>
<pre><code>{% url 'some-url-name' arg1=v1 arg2=v2 %}
</code></pre>
<p>Or, if you want to escape in code, you have several ... | 1 | 2016-08-24T18:05:46Z | [
"python",
"django"
] |
Django - get file from db by its url | 39,130,304 | <p>I am trying to implement a secure access to files. This is my view serving static files:</p>
<pre><code>from django.views.static import serve
class ServeStatic(LoginRequiredMixin, View):
login_url = reverse_lazy("login")
def dispatch(self, request, *args, **kwargs):
if request.user == Document.obj... | 0 | 2016-08-24T18:12:18Z | 39,130,728 | <p>First of all I will pass to <code>dispatch</code> cleaned data (after validation). I'm not saying you're not doing that. Next thing, I wouldn't use the same part of file path which locates files on your machine as it is in url. If you're using <code>Document</code> model, so you can change url to something which doe... | 1 | 2016-08-24T18:37:02Z | [
"python",
"django"
] |
matplotlib figure does not continue program flow after close event triggered inside tk app | 39,130,376 | <p>I've come across a really annoying difference between how windows and mac handles a python tk window and matplotlib figure close_event.</p>
<p>My problem is thus, </p>
<ol>
<li>I am trying to load a matplotlib figure from a tk button event. </li>
<li>I want the figure to show, and block the tk UI program flow whi... | 1 | 2016-08-24T18:15:30Z | 39,232,044 | <p>You can use <code>plt.ion()</code> to turn on Matplotlib's interactive mode, but this by itself will cause the program to continue without blocking the flow. To manually block the flow, use <code>self.fig.canvas.start_event_loop_default()</code> and <code>self.fig.canvas.stop_event_loop()</code> to pause the program... | 0 | 2016-08-30T15:50:26Z | [
"python",
"osx",
"matplotlib",
"tk"
] |
UnicodeDecodeError On Unicode File Read | 39,130,476 | <p>I have a problem where, when I execute a script which involved reading in data from a file that contains unicode code points, everything works fine. But when it is executed via another application, it is raising the following error:</p>
<blockquote>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in p... | 1 | 2016-08-24T18:21:46Z | 39,130,477 | <p>A hint to the problem came from the documentation of the <code>open</code> function:</p>
<blockquote>
<p>In text mode, if encoding is not specified the encoding used is
platform dependent: locale.getpreferredencoding(False) is called to
get the current locale encoding.
<a href="https://docs.python.org/3/lib... | 1 | 2016-08-24T18:21:46Z | [
"python",
"linux",
"python-3.x",
"unicode",
"cgi"
] |
What is the equivalent of list when using numpy? | 39,130,629 | <p>When I want to copy a list without linking to the same object I have to call list. So:</p>
<pre><code>a = [1, 2, 3]
b = list(a)
a == b
True
a is b
False
</code></pre>
<p>What would be the equivalent when I have a numpy array</p>
<pre><code>import numpy
a = numpy.ones(4)
b = XXX(a)?
</code></pre>
<p>Thanks in ... | 0 | 2016-08-24T18:31:12Z | 39,130,668 | <p>You can use the <code>[:]</code> pattern to copy an array or list (actually, just for lists and not for arrays. See Update below).</p>
<pre><code>a = np.ones(4)
b = a[:]
>>> b
array([ 1., 1., 1., 1.])
>>> id(a)
4606143744
>>> id(b)
4606143984
</code></pre>
<p><strong>Timings</stro... | -1 | 2016-08-24T18:33:49Z | [
"python",
"numpy"
] |
What is the equivalent of list when using numpy? | 39,130,629 | <p>When I want to copy a list without linking to the same object I have to call list. So:</p>
<pre><code>a = [1, 2, 3]
b = list(a)
a == b
True
a is b
False
</code></pre>
<p>What would be the equivalent when I have a numpy array</p>
<pre><code>import numpy
a = numpy.ones(4)
b = XXX(a)?
</code></pre>
<p>Thanks in ... | 0 | 2016-08-24T18:31:12Z | 39,130,678 | <p>Use the <code>copy</code>-method:</p>
<pre><code>b = a.copy()
</code></pre>
| 3 | 2016-08-24T18:34:35Z | [
"python",
"numpy"
] |
Performing a calculation to show Python has 53-bit precision | 39,130,645 | <p>May anyone provide guidance on how to perform a simple calculation in Python to roughly prove that the language implements 53 bit precision, as per IEEE 754? I don't have much to go on here other than this. I have tried to work off of the canonical example of 0.1 + 0.2, but no luck.</p>
| 1 | 2016-08-24T18:31:59Z | 39,130,752 | <p>Calculate the epsilon, such that <code>1.0 + eps == 1.0</code>:</p>
<pre><code>from itertools import count
eps = 1.0
for bits in count():
if 1.0+eps == 1.0:
break
eps *= 0.5
</code></pre>
| 3 | 2016-08-24T18:38:29Z | [
"python",
"math",
"bit",
"scientific-computing"
] |
Performing a calculation to show Python has 53-bit precision | 39,130,645 | <p>May anyone provide guidance on how to perform a simple calculation in Python to roughly prove that the language implements 53 bit precision, as per IEEE 754? I don't have much to go on here other than this. I have tried to work off of the canonical example of 0.1 + 0.2, but no luck.</p>
| 1 | 2016-08-24T18:31:59Z | 39,130,792 | <pre><code>>>> for i in range(100):
x = 2**i
if float(x) == float(x + 1):
print(i)
break
53
</code></pre>
<p>This works because <code>x</code> is an integer, and integers are unlimited in their bit range in Python.</p>
| 4 | 2016-08-24T18:40:28Z | [
"python",
"math",
"bit",
"scientific-computing"
] |
Performing a calculation to show Python has 53-bit precision | 39,130,645 | <p>May anyone provide guidance on how to perform a simple calculation in Python to roughly prove that the language implements 53 bit precision, as per IEEE 754? I don't have much to go on here other than this. I have tried to work off of the canonical example of 0.1 + 0.2, but no luck.</p>
| 1 | 2016-08-24T18:31:59Z | 39,131,499 | <p>Just to add a third example to the mix.</p>
<p>In IEEE 754, infinity is defined as setting all exponent bits to one
and all mantissa bits to to zero. With negative
infinity, the sign bit is also set to one. This means that the only zero bits will belong to the mantissa.</p>
<pre><code>import struct
def float_bin... | 1 | 2016-08-24T19:23:51Z | [
"python",
"math",
"bit",
"scientific-computing"
] |
What is the appropriate method to replace a dataframe with a subset using pandas.dataframe.query method()? | 39,130,679 | <p>This question is very similar to one I asked here:</p>
<p><a href="http://stackoverflow.com/questions/38087204/python-pandas-settingwithcopywarning-copies-vs-new-objects">Python Pandas SettingWithCopyWarning copies vs new objects</a></p>
<p>I'd like to understand how I can exclude records within a given dataframe ... | 2 | 2016-08-24T18:34:37Z | 39,131,469 | <p>I think this is a right approach if you don't need the data that was filtered out (reduced). You can also chain your "additional operations" (which is pretty efficient) like this:</p>
<pre><code> mydf = mydf.query('col1 == "A"').func1(...).func2(...).func3(...)
</code></pre>
<p><a href="https://pandas-docs.github.... | 2 | 2016-08-24T19:21:30Z | [
"python",
"pandas",
"dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.