title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Iterating over Multiple Lists in Python When the Lists are Different Lengths | 38,341,716 | <p>I have this table of data that I'm pulling from a MySQL database and trying to match up the rows and I am having trouble figuring out this last piece of it. I'm using Flask to pass three lists of dictionaries using 'izip_longest' to the Jinja template and then a for loop inside the Jinja template to go through the v... | 2 | 2016-07-13T02:29:05Z | 38,342,870 | <p>Not really sure what all this <code>S-Date</code>, <code>F-Date</code> business is, but I think what you want to know is how many total success and failures you have for each unique date.</p>
<p>I have a very simple solution for you in Python:</p>
<pre><code>from collections import defaultdict
from collections imp... | 1 | 2016-07-13T04:50:56Z | [
"python",
"mysql",
"for-loop",
"flask",
"jinja2"
] |
animation to translate polygon using matplotlib | 38,341,722 | <p>Goal is to draw a polygon, then translate it horizontally. This has to be shown as an animation. Following is my code:-</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
import time
import numpy as np
verts = np.array([
[0., -0.25],
[0.5,... | 2 | 2016-07-13T02:29:49Z | 38,342,379 | <p>With help from an <a href="http://stackoverflow.com/q/22649149/6557795">earlier post</a>, I was able to figure out how to do this:-</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import matplotlib.patches as patches
fig = plt.figure()
ax = fig.add_subplot... | 0 | 2016-07-13T03:51:23Z | [
"python",
"python-2.7",
"animation",
"matplotlib"
] |
SQLAlchemy-Marshmallow slow to query and serialize to JSON | 38,341,781 | <p>I am somewhat new to this, so if someone can help me, that would be awesome.</p>
<p>So I have some models set up in SQLAlchemy for a Flask app I am working on. I populated the db (currently SQLite) with some fake data while I am building the app and am kind of surprised how slow one of my calls is. </p>
<p>I hav... | 0 | 2016-07-13T02:38:30Z | 38,375,933 | <p>I would agree that 250ms is excessive, given that everything is local. I expect that the cause of the slowness is that multiple SQL queries are being executed in order to build the JSON. </p>
<p>Setting <code>SQLALCHEMY_ECHO = True</code> on the SQLAlchemy configuration will show you the SQL queries being generated... | 0 | 2016-07-14T13:44:20Z | [
"python",
"json",
"sqlalchemy",
"flask-sqlalchemy",
"marshmallow"
] |
Get AWS EC2 Spot instance launch time from within the instance itself in python | 38,341,784 | <p>I'm running a big fleet of EC2 spot instances. I need to know the current instance age (since launch time) from within each instance, using Python.
I'm using boto3</p>
| -1 | 2016-07-13T02:39:13Z | 38,622,203 | <p>By "within the EC2 instance", I assume you want to execute the python code on EC2 instance. Once you've working AWS python code, it doesn't matter on which computer/machine you run, it will work as long as system meets python and network requirements. </p>
<p>If you're looking for <code>launch_time</code>, you can ... | 0 | 2016-07-27T20:03:08Z | [
"python",
"amazon-web-services",
"amazon-ec2"
] |
Why is Django User being AnonymousUser when I make a request from a JS client but it is properly set when using Django Rest Framework ? | 38,341,810 | <p>I'm having an issue when trying to get the information of the user that is logged in in Django. My Login service looks like this: </p>
<pre><code>username = request.data['username']
password = request.data['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_act... | 0 | 2016-07-13T02:42:05Z | 38,347,527 | <blockquote>
<p>Should I set a cookie or something in the header of each request so Django knows which user am I? If so, how should it be that ?</p>
</blockquote>
<p>You definitively need the session cookie to be passed.</p>
<p>By default, it'll be <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#sessio... | 0 | 2016-07-13T09:20:00Z | [
"python",
"django",
"session",
"login",
"django-rest-framework"
] |
Is there a way to get which group is the one that matched in a regex. Prefer Javascript but Python OK too. | 38,341,829 | <p>Is there a way to get which group matches a regex? </p>
<p>for example (using js but could be re-expressed in Python etc):</p>
<p>`</p>
<pre><code>myRegex = /(this)|(that)|(other)/ig //describes 3 group captures
// The groups number (this==0, that==1, other==2) --> I'd like to get the capturing group numb... | 0 | 2016-07-13T02:43:31Z | 38,341,916 | <p>We can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec" rel="nofollow"><code>RegExp.exec</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex" rel="nofollow"><code>RegExp.lastIndex</code></a... | 0 | 2016-07-13T02:54:19Z | [
"javascript",
"python"
] |
scrapy IndexError: list index out of range but yes in scrapy shell | 38,341,976 | <p>Why would url = response.urljoin(link[0]) would produce 'IndexError: list index out of range' error? I understand what this error means.However, when i run the code in scrapy shell,it's ok. Why? Please help...</p>
<p>items.py</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-bab... | 0 | 2016-07-13T03:02:00Z | 38,342,080 | <blockquote>
<p>Why would url = response.urljoin(link[0]) would produce 'IndexError: list index out of range' error?</p>
</blockquote>
<p>Because <code>link</code> is an empty list.</p>
<blockquote>
<p>However, when i run the code in scrapy shell,it's ok</p>
</blockquote>
<p>Show us how you run the code when thi... | 0 | 2016-07-13T03:13:03Z | [
"python",
"scrapy",
"data-extraction"
] |
scrapy IndexError: list index out of range but yes in scrapy shell | 38,341,976 | <p>Why would url = response.urljoin(link[0]) would produce 'IndexError: list index out of range' error? I understand what this error means.However, when i run the code in scrapy shell,it's ok. Why? Please help...</p>
<p>items.py</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-bab... | 0 | 2016-07-13T03:02:00Z | 38,344,857 | <p>Why would url = response.urljoin(link[0]) would produce 'IndexError: list index out of range' error?
Because link is an empty list.
When the code is run, it won't extract anything meet the conditions of xpath. So, the link is an empty list, IndexError occured: list index out of range.</p>
| 0 | 2016-07-13T07:08:43Z | [
"python",
"scrapy",
"data-extraction"
] |
scrapy IndexError: list index out of range but yes in scrapy shell | 38,341,976 | <p>Why would url = response.urljoin(link[0]) would produce 'IndexError: list index out of range' error? I understand what this error means.However, when i run the code in scrapy shell,it's ok. Why? Please help...</p>
<p>items.py</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-bab... | 0 | 2016-07-13T03:02:00Z | 38,351,508 | <p>This Will work for you try this</p>
<pre><code>link = sel.xpath('.//h3/a/@href').extract()
</code></pre>
| 0 | 2016-07-13T12:17:00Z | [
"python",
"scrapy",
"data-extraction"
] |
UnicodeDecodeError: 'utf8' codec can't decode byte 0xf6 in position 178175077: invalid start byte | 38,342,033 | <p>I am trying to encode gerrit uid's to utf-8 and running into below error,it works most of time but randomly running into below error for some uid's,I have looked at similar posts on stackoverflow which suggest to ry ISO-8859-1 but utf-8 works most time for me,how to fix it?</p>
<pre><code>uid = Ia7324f6443b3db5d551... | 2 | 2016-07-13T03:07:45Z | 38,342,356 | <p>add <code># coding=utf-8</code> to first line of the python file.</p>
| 0 | 2016-07-13T03:47:59Z | [
"python",
"git",
"utf-8",
"decoding",
"gitpython"
] |
UnicodeDecodeError: 'utf8' codec can't decode byte 0xf6 in position 178175077: invalid start byte | 38,342,033 | <p>I am trying to encode gerrit uid's to utf-8 and running into below error,it works most of time but randomly running into below error for some uid's,I have looked at similar posts on stackoverflow which suggest to ry ISO-8859-1 but utf-8 works most time for me,how to fix it?</p>
<pre><code>uid = Ia7324f6443b3db5d551... | 2 | 2016-07-13T03:07:45Z | 38,356,187 | <p>Based on <a href="https://github.com/gitpython-developers/GitPython/issues/237" rel="nofollow">https://github.com/gitpython-developers/GitPython/issues/237</a> ,you can try something like below,use stdout_as_string=False</p>
<pre><code>if uID in repo.git.log(stdout_as_string=False)
</code></pre>
| 0 | 2016-07-13T15:41:45Z | [
"python",
"git",
"utf-8",
"decoding",
"gitpython"
] |
Pick the same value of many dictionary in python | 38,342,052 | <p>Recently I was given a problem from an interviewer who gave me a json file which looks like:</p>
<pre><code> {"id:"110235","symbol":"ccl","qty":"900","available":"35500","time":"2016-05-05T08:00:00.169646Z"}
{"id:"110235","symbol":"ccl","qty":"550","available":"16000","time":"2016-05-05T08:01:05.167356Z"}
{... | -1 | 2016-07-13T03:09:40Z | 38,342,138 | <p>Its not clear what the expected output format is, but if it can be a dictionary the following would be O(n) time.</p>
<pre><code>def sum_symbols(data):
symbols = {}
for row in data:
symbol = symbols["symbol"]
available = int(row["available"])
if symbol in symbols:
symbo... | 0 | 2016-07-13T03:20:40Z | [
"python",
"json"
] |
Pick the same value of many dictionary in python | 38,342,052 | <p>Recently I was given a problem from an interviewer who gave me a json file which looks like:</p>
<pre><code> {"id:"110235","symbol":"ccl","qty":"900","available":"35500","time":"2016-05-05T08:00:00.169646Z"}
{"id:"110235","symbol":"ccl","qty":"550","available":"16000","time":"2016-05-05T08:01:05.167356Z"}
{... | -1 | 2016-07-13T03:09:40Z | 38,342,200 | <pre><code>arr = [{"id": "110235", "symbol": "ccl", "qty": "900", "available": "35500", "time": "2016-05-05T08:00:00.169646Z"},
{"id": "110235", "symbol": "ccl", "qty": "550", "available": "16000", "time": "2016-05-05T08:01:05.167356Z"},
{"id": "110235", "symbol": "ssi", "qty": "1550", "available": "24000... | 0 | 2016-07-13T03:27:07Z | [
"python",
"json"
] |
Pick the same value of many dictionary in python | 38,342,052 | <p>Recently I was given a problem from an interviewer who gave me a json file which looks like:</p>
<pre><code> {"id:"110235","symbol":"ccl","qty":"900","available":"35500","time":"2016-05-05T08:00:00.169646Z"}
{"id:"110235","symbol":"ccl","qty":"550","available":"16000","time":"2016-05-05T08:01:05.167356Z"}
{... | -1 | 2016-07-13T03:09:40Z | 38,342,202 | <p>Here is a simple way of doing it:</p>
<pre><code>from collections import defaultdict
results = defaultdict(int)
for data in data_set:
results[data['symbol']] += int(data['available'])
for symbol, total in results.iteritems():
print('{} - {}'.format(symbol, total))
</code></pre>
| 2 | 2016-07-13T03:27:16Z | [
"python",
"json"
] |
how to iterate data from django in angularJs | 38,342,062 | <p>This is my data from django models</p>
<pre><code>subtaskList = [{'id':'1', 'name': 'sample name'},
{'id':'2', 'name': 'sample name 2'},
{'id':'3', 'name': 'sample name 3'}]
</code></pre>
<p>this is my code:</p>
<pre><code> var subtaskList = {{subtaskList}};
var tasks = [];
for (var i = 0; i < subt... | 0 | 2016-07-13T03:10:57Z | 38,342,185 | <p>There is nothing wrong with the Javascript portion of your code (assuming the following line is the actual code you have)</p>
<pre><code>tasks[tasks.length-1].push(subtaskList[i])
</code></pre>
<p>this will create an array of array of objects for you. so if it is not working it is probably in the HTML template of ... | 0 | 2016-07-13T03:25:49Z | [
"python",
"angularjs",
"django"
] |
Python - Getting A Page's Complete HTML Via Url / Request ERROR | 38,342,079 | <p>I'm trying to get the html of this page:</p>
<pre><code> url = 'http://www.metacritic.com/movie/oslo-august-31st/critic-reviews'
</code></pre>
<p>and I'm trying to get it using requests:</p>
<pre><code> oslo = requests.get(url)
</code></pre>
<p>but they seem to know that I'm accessing it this way and when I open... | 1 | 2016-07-13T03:13:03Z | 38,342,170 | <p>You need to specify a <a href="https://en.wikipedia.org/wiki/User_agent" rel="nofollow"><code>User-Agent</code> header</a> to get 200 response:</p>
<pre><code>import requests
url = 'http://www.metacritic.com/movie/oslo-august-31st/critic-reviews'
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (M... | 1 | 2016-07-13T03:23:41Z | [
"python",
"html",
"url",
"web-scraping",
"python-requests"
] |
How to access an external SFTP from Google Compute Engine | 38,342,126 | <p>I'm setting a process using python on GCE that must connect to my local SFTP and copy files from there.</p>
<p>I'm using pysftp but getting a SSH problem. What am I doing wrong?</p>
<pre><code>>>> import pysftp
>>> sftp = pysftp.Connection(host, username=user, password=pasw)
Exception Attrib... | 1 | 2016-07-13T03:19:36Z | 38,358,628 | <p>Manualy adding the SSH Key to known_hosts did the trick.</p>
<pre><code>$ ssh sftp.mydomain.com
</code></pre>
<p>Would appreciate if someone post a solution where pysftp do this automaticaly</p>
| 3 | 2016-07-13T17:54:10Z | [
"python",
"ssh",
"sftp",
"google-compute-engine",
"pysftp"
] |
Why np.load() couldn't read my ndarray data in pickled file? | 38,342,230 | <p>I am trying to analyze a tensor data, but I could not read the data in picked file by using np.load(). My python code is as follows:</p>
<pre><code>import pickle
import numpy as np
import sktensor as skt
import numpy.random as rn
data = np.ones((10, 8, 3), dtype='int32') # 3-mode count tensor of size 10 x 8 x 3
#... | 0 | 2016-07-13T03:30:54Z | 38,342,297 | <p>Don't use the pickle module to save NumPy arrays. Instead, use one of the methods here: <a href="http://docs.scipy.org/doc/numpy/reference/routines.io.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/routines.io.html</a></p>
<p>There's even one that uses pickle under the hood, for example:</p>
<pre>... | 0 | 2016-07-13T03:39:13Z | [
"python",
"numpy",
"pickle"
] |
Preflight CORS issue with javascript and python base http server | 38,342,284 | <p>I am having trouble getting the following java script to work.</p>
<pre><code>window.onload = function() {
mycallback(dataParm);
};
function mycallback(data) {
console.log(data);
return true;
}
var xhr = $.ajax({
url: connectionUri,
dataType: 'json',
type: 'GET',
headers: {
"Auth... | 0 | 2016-07-13T03:37:27Z | 40,065,643 | <p>I was having this same problem too! (Cross Origin Resource Sharing) is a header that has to be present in the apache httpd.conf or apache.conf or .htaccess configuration file. If you are on NGINX, you have to edit the defaults.conf or nginx.conf file It basically makes it so that the web server accepts HTTP requests... | 0 | 2016-10-16T00:34:00Z | [
"javascript",
"python",
"ajax",
"cors",
"preflight"
] |
Generating a (non-unique) Random list | 38,342,378 | <p>I am using Python 2.7 and I want to generate a non-unique list. I am trying:</p>
<pre><code>from random import randint
from random import random
a= random.sample(range(100),15)
print a
</code></pre>
<p>I get this error<br>
a= random.sample(range(100),15)
AttributeError: 'builtin_function_or_method' object has ... | -1 | 2016-07-13T03:51:19Z | 38,342,445 | <p>When you do <code>from random import random</code> you're actually importing the specific <a href="https://docs.python.org/2/library/random.html#random.random" rel="nofollow"><code>random.random()</code></a> function in the <code>random</code> module. You don't want to do this - you only want to import the module:</... | 1 | 2016-07-13T03:58:51Z | [
"python",
"aptana"
] |
Generating a (non-unique) Random list | 38,342,378 | <p>I am using Python 2.7 and I want to generate a non-unique list. I am trying:</p>
<pre><code>from random import randint
from random import random
a= random.sample(range(100),15)
print a
</code></pre>
<p>I get this error<br>
a= random.sample(range(100),15)
AttributeError: 'builtin_function_or_method' object has ... | -1 | 2016-07-13T03:51:19Z | 38,342,516 | <p>The reason you're getting an error is because you're importing the function <code>random.random</code> when you say <code>from random import random</code>. <code>random</code> is no longer the name of the module, it now refers to the function.</p>
<p>If you want to use the syntax <code>random.sample</code> you shou... | 0 | 2016-07-13T04:06:01Z | [
"python",
"aptana"
] |
Show Training Iteration Score for Logistic Regression Classifier sklearn | 38,342,476 | <p>I'm making a text classification using Logistic Regression classifier in sklearn.
it's working really nice. but now I'm curious about something.
is it possible to show training score for each iteration when the Logistic Regression train?
for example I'd like to show the training score for each iteration in format li... | 0 | 2016-07-13T04:01:57Z | 38,356,447 | <p>I don't think it is possible to get the output the way you want it to. At the best you can set <code>verbose=10</code> while initializing the classifier as <code>clf = LogisticRegression(verbose=10)</code>. This will just make the iterations of the <code>LibLinear</code> or the <code>Libfgs</code> solver verbose. Yo... | 0 | 2016-07-13T15:53:43Z | [
"python",
"machine-learning",
"scikit-learn",
"logistic-regression"
] |
copy columns from one excel to other and run the macro from python | 38,342,524 | <p>I am trying to copy all the columns from consolidated file to summary file and run a excel macro from python, summary file have columns from A to BB, and i want to copy only upto AI, I tried the below code but its not giving me any result</p>
<pre><code>wbpath = 'C:\\Users\\Summary.xlsb'
excel = Dispatch("Excel.App... | 0 | 2016-07-13T04:06:52Z | 38,345,947 | <p>There are a number of errors in your VBA code. First of all</p>
<pre><code>Set tColumn = Workbooks("C:\\Users\\Summary.xlsb").Worksheets(2).Columns("A2")
</code></pre>
<p>is not valid because <code>A2</code> is a cell reference, not a column reference. But you can't copy the whole of a column from one sheet into r... | 0 | 2016-07-13T08:06:13Z | [
"python",
"excel",
"vba",
"excel-vba"
] |
Python & Pandas: Strange behavior when Pandas plot histogram to a specific ax | 38,342,544 | <p>I want to plot pandas histogram to an axis, but the behavior is really strange. I don't know what's wrong here.</p>
<pre><code>fig1, ax1 = plt.subplots(figsize=(4,3))
fig2, ax2 = plt.subplots(figsize=(4,3))
fig3, ax3 = plt.subplots(figsize=(4,3))
# 1. This works
df['speed'].hist()
# 2. This doens't work
df['speed... | 1 | 2016-07-13T04:08:59Z | 38,342,883 | <p>The problem is that pandas determines which is the active figure by using <code>gcf()</code> to get the "current figure". When you create several figures in a row, the "current figure" is the last one created. But you are trying to plot to an earlier one, which causes a mismatch.</p>
<p>However, as you can see on... | 2 | 2016-07-13T04:51:59Z | [
"python",
"pandas",
"matplotlib",
"jupyter-notebook"
] |
Problems deploying simple Python script to keep running on Heroku | 38,342,563 | <p>I have a simple Python program that repeats the following process at 30 second intervals: uses the Gmail API to check my inbox, looks for a certain kind of mail, and if it is found, uses the Twilio API to call me.</p>
<p>I've been running this program on my machine, but I'd like for it to be running 24x7. A friend ... | 0 | 2016-07-13T04:11:59Z | 38,448,798 | <p>Note that the Heroku platform is designed for hosting web applications, not arbitrary daemons. When you look at the output of <code>heroku logs</code>, I imagine you'll see errors like "R10 Web process failed to bind". That's because Heroku expects your web process to listen for web requests by binding to the port p... | 0 | 2016-07-19T02:48:45Z | [
"python",
"heroku",
"deployment",
"procfile"
] |
faster way to replacing specific values per column, python | 38,342,589 | <p>I have a large-ish structure in as a pandas dataframe, shape = (2000, 200000) I want to replace all of the values of 2 in each column with that particular columns mean (excluding the 2 values). This is how I do it for small structures, but for larger ones it takes a significantly longer time. <code>Y</code> is the ... | 2 | 2016-07-13T04:15:00Z | 38,343,669 | <p>Since you are working with arithmetic operations, I would suggest offloading all those computations to NumPy, get the final result and create a dataframe, like so -</p>
<pre><code># Extract into an array
arr = Y.values
# Mask to set or not-set elements in array
mask = arr!=2
# Compute the mean vaalues for masked ... | 2 | 2016-07-13T05:57:49Z | [
"python",
"pandas"
] |
faster way to replacing specific values per column, python | 38,342,589 | <p>I have a large-ish structure in as a pandas dataframe, shape = (2000, 200000) I want to replace all of the values of 2 in each column with that particular columns mean (excluding the 2 values). This is how I do it for small structures, but for larger ones it takes a significantly longer time. <code>Y</code> is the ... | 2 | 2016-07-13T04:15:00Z | 38,344,024 | <p>Assuming your dataframe is <code>df</code>, Let:</p>
<pre><code>a = df.values
</code></pre>
<p>I'd calculate what the average is across non-twos with</p>
<pre><code>avg = (a.sum(0) - (a == 2).sum(0) * 2.) / (a != 2).sum(0)
</code></pre>
<p><code>(a == 2).sum(0)</code> is the number of <code>2</code>s in each col... | 2 | 2016-07-13T06:23:16Z | [
"python",
"pandas"
] |
PyCharm not recognizing Django project imports: from my_app.models import thing | 38,342,618 | <p>I just started testing out PyCharm on my existing Django project, and it doesn't recognize any imports from apps within my project:</p>
<p>in <code>my_app1/models.py</code>:</p>
<p><code>from my_app2.models import thing</code></p>
<p>"Unresolved reference 'my_app2'"</p>
<p>Why is this? My project's directory str... | 0 | 2016-07-13T04:18:56Z | 38,416,703 | <p>Now that I can take a look over you project structure I can tell you that the problem appears to be related to a missing <code>__init__.py</code> in your 'src' folder. Try adding an empty file named <code>__init__.py</code> in the root of 'src' folder.</p>
<p>Also, take a look to this <a href="http://stackoverflow.... | 0 | 2016-07-16T23:58:57Z | [
"python",
"django",
"pycharm",
"python-import"
] |
C# Socket: how to keep it open? | 38,342,736 | <p>I am creating a simple server (C#) and client (python) that communicate using sockets. </p>
<p>The server create a </p>
<pre><code>var listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)
</code></pre>
<p>then binds, listens in a infinite loop </p>
<pre><code>while (true... | -1 | 2016-07-13T04:35:17Z | 38,343,169 | <p>this is from MSDN(<a href="https://msdn.microsoft.com/en-us/library/5bb431f9(v=vs.110).aspx" rel="nofollow">Remarks on EndAccept</a>):</p>
<blockquote>
<p>Your callback method should invoke the EndAccept method. When your
application calls BeginAccept, the system usually uses a separate
thread to execute the ... | 0 | 2016-07-13T05:17:58Z | [
"c#",
"python",
"sockets"
] |
Tkinter : How to limit user to a number of functions | 38,342,741 | <p>I am creating a turtle program that gets the command from a text widget, then draws on a tkinter <code>Canvas</code>. But when I <code>eval()</code> that command from the <code>Text</code> widget, the program would become a Python Shell (It would even accept <code>print("Hello World")</code> as a turtle command)</p>... | 2 | 2016-07-13T04:35:58Z | 38,344,985 | <p>Avoid <code>eval()</code> -- instead consider a datastructure of legal commands and treat the code that implements those commands as data. I've implemented an example below with just the turtle module to keep it simple:</p>
<pre><code>import turtle
commands = {
'moveForward': lambda pixels: turtle.forward(pix... | 2 | 2016-07-13T07:16:10Z | [
"python",
"tkinter",
"command",
"turtle-graphics"
] |
Condensing python code for creating tkinter widgets | 38,342,753 | <p>I have a program that I'm designing to teach myself Python but have gotten stuck. I've run across a way to condense python code using % and a list of arguments to have it run as code and looping through the list of arguments until it's done, but can't seem to find it in the documentation or with Google, mostly becau... | 0 | 2016-07-13T04:38:07Z | 38,454,764 | <p>Thanks to Steven Summers in the comments for mentioning classes. I had no idea they were so powerful! I found this guide (<a href="https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/" rel="nofollow">https://jeffknupp.com/blog/2014/06/18/improve-your-python-python... | 0 | 2016-07-19T09:38:10Z | [
"python",
"python-2.7",
"tkinter"
] |
Delete from tuple | 38,342,817 | <pre><code>def distanceFromGPS(latitude1,longitude1,latitude2,longitude2):
R = 6371
dLat = math.radians(latitude2-latitude1)
dLon = math.radians(longitude2-longitude1)
a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLon/2) * math.sin(dLon/2) * math.cos(math.radians(latitude1)) * math.cos(math.radian... | 0 | 2016-07-13T04:45:00Z | 38,342,952 | <p>Touples are immutable so you can't use "del" to delete one of their items.</p>
<p>You can do this instead:</p>
<pre><code>mytouple = mytouple[:indexToDelete] + mytouple[indexToDelete+1:]
</code></pre>
<p>Another way would be to use lists (which are mutable and work with "del") instead of touples. Although that ca... | 1 | 2016-07-13T04:57:59Z | [
"python",
"python-2.7"
] |
Delete from tuple | 38,342,817 | <pre><code>def distanceFromGPS(latitude1,longitude1,latitude2,longitude2):
R = 6371
dLat = math.radians(latitude2-latitude1)
dLon = math.radians(longitude2-longitude1)
a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLon/2) * math.sin(dLon/2) * math.cos(math.radians(latitude1)) * math.cos(math.radian... | 0 | 2016-07-13T04:45:00Z | 38,343,218 | <p>I think a simple solution is the following:</p>
<pre><code>from itertools import product
a = [....]
results = set()
for pair in product(a, a):
left, right = pair
if distanceFromGPS(left[0], left[1], right[0], right[1]) > 1:
results.add(left)
</code></pre>
| 0 | 2016-07-13T05:21:52Z | [
"python",
"python-2.7"
] |
Sum values of tuples stored as key value pair in list by key | 38,342,908 | <p>I have a list like <code>[('a',2),('a',3),('b',3),('c',2),('b',4)]</code></p>
<p>I want to sum all similar keys and get <code>[('a',5),('c',2),('b',7)]</code> in any order is fine.</p>
<p>Is there a better way to do this instead of using a dictionary. Preferably using list comprehension something like <code>[i for... | 0 | 2016-07-13T04:54:23Z | 38,343,036 | <p>This is feasible alternatively with <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> in a list comprehension, although your approach seems fine and there is no inherent benefit to always using list comprehensions. Getting worked up about a... | 3 | 2016-07-13T05:05:50Z | [
"python",
"list",
"sum",
"tuples"
] |
Using files with python | 38,343,008 | <p>I am trying to use a txt file within my python code but I am unable to do so.
The problem asks to print the words which do not have a specific set of characters from the file. </p>
<pre><code>def give():
fin=open('words2.txt')
line=fin.readline()
for line in fin:
word=line.strip()
print ... | 0 | 2016-07-13T05:02:47Z | 38,343,352 | <p>As already pointed out, the indentation is wrong, also give() does not return anything so words is assigned a NoneType. </p>
| 0 | 2016-07-13T05:32:56Z | [
"python"
] |
Using files with python | 38,343,008 | <p>I am trying to use a txt file within my python code but I am unable to do so.
The problem asks to print the words which do not have a specific set of characters from the file. </p>
<pre><code>def give():
fin=open('words2.txt')
line=fin.readline()
for line in fin:
word=line.strip()
print ... | 0 | 2016-07-13T05:02:47Z | 38,343,391 | <p>You have to return a value in give() function..</p>
<pre><code>def give():
fin=open('words2.txt', 'r')
line=fin.readlines()
words = []
for line in fin:
word=line.split(" ")
for i in word:
print i
words.append(i)
return words
def enter(forbid):
words=gi... | 0 | 2016-07-13T05:36:08Z | [
"python"
] |
Using files with python | 38,343,008 | <p>I am trying to use a txt file within my python code but I am unable to do so.
The problem asks to print the words which do not have a specific set of characters from the file. </p>
<pre><code>def give():
fin=open('words2.txt')
line=fin.readline()
for line in fin:
word=line.strip()
print ... | 0 | 2016-07-13T05:02:47Z | 38,343,417 | <p>I've tried your code, but could not work anything out, so I took a program i wrote some time ago, as far as i can see, you open the file on the wrong way, here is my code:</p>
<pre><code>fo = open('your_file_name.txt','rt')
for line in fo:
print(line)
fo.close()
</code></pre>
<p>as you can see you did not add... | 0 | 2016-07-13T05:38:17Z | [
"python"
] |
Using files with python | 38,343,008 | <p>I am trying to use a txt file within my python code but I am unable to do so.
The problem asks to print the words which do not have a specific set of characters from the file. </p>
<pre><code>def give():
fin=open('words2.txt')
line=fin.readline()
for line in fin:
word=line.strip()
print ... | 0 | 2016-07-13T05:02:47Z | 38,343,995 | <p>I think I figured out what you want:</p>
<pre><code>#!/usr/bin/env python2
def give():
result = []
with open('words2.txt', mode='rt') as fin:
for line in fin:
result += line.split()
return result
def enter(forbid):
words = give()
for w in words:
if all([letter not i... | 3 | 2016-07-13T06:21:26Z | [
"python"
] |
How to get Python version string in exact same format as displayed at startup? | 38,343,058 | <p>When I start Python it prints a version string, for example:</p>
<pre><code>Python 2.7.10 (default, Jul 23 2015, 09:39:55)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
</code></pre>
<p>Is there an easy way to get that exact string? There are a whole bunch of functions in the platform package... | 0 | 2016-07-13T05:08:02Z | 38,343,059 | <p>This should generate the exact same output as the Python startup banner:</p>
<pre><code>import sys
print("Python %s on %s" % (sys.version, sys.platform))
</code></pre>
| 1 | 2016-07-13T05:08:02Z | [
"python",
"version"
] |
tensorflow change checkpoint location | 38,343,089 | <p>i was wondering if theres a way to indicate to your training models(in tensorflow) or to tensorflow configuration in general where to store checkpoint files, i was tranining a neural network and got the errors:
InternalError: Error writing (tmp) checkpoint file: /tmp/tmpn2cWXm/model.ckpt-500-00000-of-00001.tempstate... | 1 | 2016-07-13T05:10:17Z | 38,914,781 | <p>You can specify your save path as the second argument of <code>tf.train.Saver.save(sess, 'your/save/path', ...)</code>. Similarly, you can restore your previously saved variables passing your restore path as the second argument of <code>tf.train.Saver.restore(sess, 'your/restore/path')</code>.</p>
<p>Please, see <a... | 0 | 2016-08-12T09:41:14Z | [
"python",
"machine-learning",
"tensorflow"
] |
Something strange happen with python multiprocess | 38,343,090 | <p>I've just tested python multiprocessing for reading file or a global variable, but there is something strange happen.</p>
<p>for expample:</p>
<pre><code>import multiprocessing
a = 0
def test(lock, name):
global a
with lock:
for i in range(10):
a = a + 1
print "in ... | 1 | 2016-07-13T05:10:20Z | 38,343,175 | <p>Global variables are not shared between processes. When you create and start a new <code>Process()</code>, that process runs inside a separate "cloned" copy of the current Python interpreter. Updating the variable from within a <code>Process()</code> will only update the variable locally to the particular process it... | 1 | 2016-07-13T05:18:31Z | [
"python"
] |
Finding a name in a CSV file | 38,343,138 | <p>I have code that finds the input name in a CSV if it is present it says yes else no. But I entered a name present in the CSV yet it still says no.</p>
<p>Here is the code:</p>
<pre><code>import csv
f=open("student.csv","r")
reader=csv.reader(f)
for row in reader:
print
studentToFind = raw_input("Enter the nam... | 0 | 2016-07-13T05:13:53Z | 38,343,222 | <p>You've already iterated over the file once. When you try to loop over <code>reader</code> again there is nothing to loop over.</p>
<p>Instead don't even use the <code>csv</code> module and save the lines in the file into a list:</p>
<pre><code>with open("student.csv","r") as f:
lines = []
for line in f:
... | 0 | 2016-07-13T05:21:58Z | [
"python",
"csv"
] |
Finding a name in a CSV file | 38,343,138 | <p>I have code that finds the input name in a CSV if it is present it says yes else no. But I entered a name present in the CSV yet it still says no.</p>
<p>Here is the code:</p>
<pre><code>import csv
f=open("student.csv","r")
reader=csv.reader(f)
for row in reader:
print
studentToFind = raw_input("Enter the nam... | 0 | 2016-07-13T05:13:53Z | 38,343,256 | <p>Simply ask the question before you loop over the file:</p>
<pre><code>import csv
studentToFind = raw_input("Enter the name of student?")
f=open("student.csv","r")
reader=csv.reader(f)
found = "No"
for row in reader:
if studentToFind in row:
found = "Yes"
f.close()
print('{}'.format(found))
</code></... | 2 | 2016-07-13T05:24:56Z | [
"python",
"csv"
] |
Finding a name in a CSV file | 38,343,138 | <p>I have code that finds the input name in a CSV if it is present it says yes else no. But I entered a name present in the CSV yet it still says no.</p>
<p>Here is the code:</p>
<pre><code>import csv
f=open("student.csv","r")
reader=csv.reader(f)
for row in reader:
print
studentToFind = raw_input("Enter the nam... | 0 | 2016-07-13T05:13:53Z | 38,343,295 | <p>You've got a couple of issues:</p>
<p>First <code>reader</code> is empty at this point, since you've already looped over its elements. Reading from a <a href="https://docs.python.org/3/glossary.html#term-file-object" rel="nofollow">file</a> is a one-time deal, if you want to access its contents more than once you n... | 2 | 2016-07-13T05:27:48Z | [
"python",
"csv"
] |
Python 2.7: How to identify unique string from string in pandas dataframe and print designated value in a specified column based on the result? | 38,343,142 | <p>I have been researching similar questions but have not been able to find answers. I would appreciate if you could help me since I am new to programming and Python(2.7)..</p>
<p>So I have this panda dataframe.</p>
<p><strong>This is a data I have:</strong>
<a href="http://i.stack.imgur.com/i2R4i.png" rel="nofollow... | 3 | 2016-07-13T05:14:39Z | 38,343,609 | <h3>New Answer</h3>
<pre><code>dataframe = pd.DataFrame([['Age is 83,sex is man'],
['sex is woman,age is 74']],
columns=['info'])
mw = dataframe['info'].str.extract(r'sex is (woman|man)', expand=False)
pd.concat([dataframe, pd.get_dummies(mw).astype(int)], axis=1)
</... | 1 | 2016-07-13T05:53:34Z | [
"python",
"string",
"python-2.7",
"if-statement",
"pandas"
] |
Python 2.7: How to identify unique string from string in pandas dataframe and print designated value in a specified column based on the result? | 38,343,142 | <p>I have been researching similar questions but have not been able to find answers. I would appreciate if you could help me since I am new to programming and Python(2.7)..</p>
<p>So I have this panda dataframe.</p>
<p><strong>This is a data I have:</strong>
<a href="http://i.stack.imgur.com/i2R4i.png" rel="nofollow... | 3 | 2016-07-13T05:14:39Z | 38,344,134 | <p>This works</p>
<pre><code>import string
df['woman'] = df['info'].map(lambda x: x.translate(None, string.punctuation)).map(lambda x: 1 if 'woman' in x.lower().split() else 0)
df['man'] = df['info'].map(lambda x: x.translate(None, string.punctuation)).map(lambda x: 1 if 'man' in x.lower().split() else 0)
df
</code></... | 0 | 2016-07-13T06:29:42Z | [
"python",
"string",
"python-2.7",
"if-statement",
"pandas"
] |
Cython how to convert char** to const char**? | 38,343,239 | <p>I am trying to use Cython to write a wrapper around a C++ library. However, I am running into an issue now, as one of the functions in the library takes the parameter <code>const char**</code>. Apparently, C++ is unable to do this conversion, (<a href="http://stackoverflow.com/questions/2463473/why-am-i-getting-an-e... | 0 | 2016-07-13T05:23:53Z | 38,344,257 | <p>The following code compiles in cPython V20.0. Does that solve your problem?</p>
<pre><code># distutils: language = c++
from libc.stdlib cimport malloc
def f(x):
cdef const char** a = <const char**> malloc(len(x) * sizeof(char*))
for index, item in x:
a[index] = item
</code></pre>
| 1 | 2016-07-13T06:37:33Z | [
"python",
"c++",
"cython"
] |
Cython how to convert char** to const char**? | 38,343,239 | <p>I am trying to use Cython to write a wrapper around a C++ library. However, I am running into an issue now, as one of the functions in the library takes the parameter <code>const char**</code>. Apparently, C++ is unable to do this conversion, (<a href="http://stackoverflow.com/questions/2463473/why-am-i-getting-an-e... | 0 | 2016-07-13T05:23:53Z | 38,344,629 | <p>There is this old <a href="http://stackoverflow.com/a/17511714/5781248">answer</a> but I would implement <code>to_cstring_array</code> little bit differently (use of <code>strdup</code>, no <code>PyString_AsString</code>)</p>
<pre><code>from libc.stdlib cimport malloc, free
from libc.string cimport strdup
cdef cha... | 0 | 2016-07-13T06:58:03Z | [
"python",
"c++",
"cython"
] |
How to disable python stdout buffer in pycharm? | 38,343,337 | <p>I have known that with <code>-u</code>, the stdout buffer of python will be disabled. It works in sublime and bash, but in pycharm, I set <code>Run->Edit Configurations->Interpreter options->add -u</code>, it doesn't. My test code is as following:</p>
<pre><code># -*- encoding: utf-8 -*-
import sys
print "... | -1 | 2016-07-13T05:31:49Z | 38,362,588 | <p>I think the problem is not related to python buffered output: if you run your example in the console, the order would be correct.
IDE handles output of the script process and has to catch both stdout and stderr, but it's not possible to preserve order when both streams are intercepted.
Here are some relevant discuss... | 0 | 2016-07-13T22:13:27Z | [
"python",
"pycharm",
"stdout",
"stderr"
] |
Pandas make a new dataframe with the old column names | 38,343,419 | <p>I need some helps structure a data. So I have the following DataFrame (called df):
<a href="http://i.stack.imgur.com/NLbQv.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/NLbQv.jpg" alt="the original dataframe"></a></p>
<p>I want to group my dataframe based on Mean_CArea, Mean_CPressure, and Mean_Force. Howe... | 2 | 2016-07-13T05:38:25Z | 38,343,547 | <p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.swaplevel.html" rel="nofollow"><code>swaplevel</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by columns (<code>axis... | 2 | 2016-07-13T05:48:53Z | [
"python",
"pandas",
"dataframe",
"multiple-columns"
] |
Pandas make a new dataframe with the old column names | 38,343,419 | <p>I need some helps structure a data. So I have the following DataFrame (called df):
<a href="http://i.stack.imgur.com/NLbQv.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/NLbQv.jpg" alt="the original dataframe"></a></p>
<p>I want to group my dataframe based on Mean_CArea, Mean_CPressure, and Mean_Force. Howe... | 2 | 2016-07-13T05:38:25Z | 38,343,800 | <p>You want to use <code>xs</code></p>
<pre><code>df.xs('Mean_CArea', axis=1, level=1)
</code></pre>
<p>and </p>
<pre><code>df.xs('Mean_CPressure', axis=1, level=1)
</code></pre>
<p>and</p>
<pre><code>df.xs('Mean_Force', axis=1, level=1)
</code></pre>
| 2 | 2016-07-13T06:07:32Z | [
"python",
"pandas",
"dataframe",
"multiple-columns"
] |
python-eve generate _etag, _updated and _created | 38,343,440 | <p>I added data directly to mongodb and now i'm missing the _etag, _created and _updated fields. How do I generate these for documents that don't have them?</p>
<p>Thanks,</p>
| 1 | 2016-07-13T05:40:09Z | 38,344,543 | <p>A <code>GET</code> on those document will transparently get those meta for you. The two date fields will probably default to epoch; etag will be computed for you. This way you will then be able to make conditional requests (<code>PUT</code>, <code>PATH</code>, <code>DELETE</code>) on the documents, like they were in... | 0 | 2016-07-13T06:53:11Z | [
"python",
"mongodb",
"eve"
] |
Trying Deepdict, run gensim word2vec with pyspark | 38,343,475 | <pre><code>from deepdist import DeepDist
from gensim.models.word2vec import Word2Vec
from pyspark import SparkConf, SparkContext
conf = (SparkConf()
.setAppName("Work2Vec")
)
sc = SparkContext(conf=conf)
corpus = sc.textFile('AllText.txt').map(lambda s: s.split())
def gradient(model, sentences):
syn0, sy... | 0 | 2016-07-13T05:42:34Z | 38,731,848 | <p>Note that your copied and pasted code has a typo which is corrected with this pull request: <a href="https://github.com/dirkneumann/deepdist/pull/1" rel="nofollow">https://github.com/dirkneumann/deepdist/pull/1</a></p>
| 0 | 2016-08-02T23:07:09Z | [
"python",
"pyspark",
"gensim",
"word2vec"
] |
SQLAlchemy: session.close() or session.commit() | 38,343,515 | <p>I am newbie to SQLAlchemy. And now I need to query some data, as follows</p>
<pre><code>def get_xx():
sess = Session()
return sess.query(xx).filter(
xx.id == 3, xx.status == 1
).first()
</code></pre>
<p>The isolation level is <code>repeatable read</code> and autocommit is off; So I always get t... | 0 | 2016-07-13T05:46:33Z | 38,344,057 | <p>Your session commit and close is absolutely right what you have done. And in your source code you can try this..</p>
<pre><code>from operator import and_
def get_xx():
with auto_session() as sess:
return sess.query(xx).filter(and_(
xx.id == 3, xx.status == 1
)).first()
</code></pre>
| 0 | 2016-07-13T06:25:00Z | [
"python",
"sqlalchemy"
] |
SQLAlchemy: session.close() or session.commit() | 38,343,515 | <p>I am newbie to SQLAlchemy. And now I need to query some data, as follows</p>
<pre><code>def get_xx():
sess = Session()
return sess.query(xx).filter(
xx.id == 3, xx.status == 1
).first()
</code></pre>
<p>The isolation level is <code>repeatable read</code> and autocommit is off; So I always get t... | 0 | 2016-07-13T05:46:33Z | 38,348,049 | <p>after commit you can refresh the session and then close the session.</p>
<pre><code>@contextmanager
def auto_session():
sess = Session()
try:
yield sess
sess.commit()
sess.refresh()
except: # swallow any exception
sess.rollback()
finally:
sess.close()
from... | 0 | 2016-07-13T09:43:11Z | [
"python",
"sqlalchemy"
] |
Python how to call the result of a dictionary and pass the result to a few variables | 38,343,559 | <p>I have 3 variables x,y,z which will have different values depending on the outcome of 3 tests i am going to perform. So there will 8 possible outcomes of the tests. These 8 outcomes, will match to the corresponding results stored in a dictinary called dic. I will need to pass the corresponding results to the variabl... | 1 | 2016-07-13T05:49:41Z | 38,343,655 | <p>I would probably approach the problem a bit differently, at least for the three below lines</p>
<pre><code>outcome = [[0,3,1], [0,2,1,], [0,3,2], [0,2,1], [1,3,1], [1,3,2], [2,3,1], [3,3,1]]
dic = {'111':outcome[0], '110':outcome[1], '101':outcome[2], '100':outcome[3], '011':outcome[4], '010':outcome[5], '001':ou... | 1 | 2016-07-13T05:56:47Z | [
"python"
] |
Python how to call the result of a dictionary and pass the result to a few variables | 38,343,559 | <p>I have 3 variables x,y,z which will have different values depending on the outcome of 3 tests i am going to perform. So there will 8 possible outcomes of the tests. These 8 outcomes, will match to the corresponding results stored in a dictinary called dic. I will need to pass the corresponding results to the variabl... | 1 | 2016-07-13T05:49:41Z | 38,343,666 | <p>Perhaps something like this would be an improvement?</p>
<pre><code>fetch = requests.get('http://www.example.com')
match_M = 0 if re.search(r'something1...' , fetch.text) else 4
match_K = 0 if re.search(r'something2...' , fetch.text) else 2
match_T = 0 if re.search(r'something3...' , fetch.text) else 1
index = ma... | 1 | 2016-07-13T05:57:39Z | [
"python"
] |
If two variable values are identical then it is said to be sharing same memory | 38,343,650 | <p>If two variable values are identical then it is said to be sharing same memory...
so python follows shared memory concept ?....and if i change one value will it change another?</p>
| -4 | 2016-07-13T05:56:26Z | 38,343,967 | <p>See Python data model described <a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow">here</a> </p>
<blockquote>
<p>Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values ma... | 2 | 2016-07-13T06:19:02Z | [
"python",
"python-2.7"
] |
I want to match money amount with regex for indian currency without commas | 38,343,671 | <p>I want to match amount like <b><code>Rs. 2000 , Rs.2000 , Rs 20,000.00 ,20,000 INR 200.25 INR.</code> </b></p>
<p>Output should be
2000,2000,20000.00,20000,200.25</p>
<p>The regular expression i have tried is this</p>
<pre><code>(?:(?:(?:rs)|(?:inr))(?:!-{0,}|\.{1}|\ {0,}|\.{1}\ {0,}))(-?[\d,]+ (?:\.\d+)?)(?:[... | 5 | 2016-07-13T05:58:08Z | 38,344,154 | <p>I suggest using alternation group with capture groups inside to only match the numbers before or after your constant string values:</p>
<pre><code>(?:Rs\.?|INR)\s*(\d+(?:[.,]\d+)*)|(\d+(?:[.,]\d+)*)\s*(?:Rs\.?|INR)
</code></pre>
<p>See the <a href="https://regex101.com/r/rK7tL8/2" rel="nofollow">regex demo</a>.</... | 2 | 2016-07-13T06:31:05Z | [
"python",
"regex"
] |
I want to match money amount with regex for indian currency without commas | 38,343,671 | <p>I want to match amount like <b><code>Rs. 2000 , Rs.2000 , Rs 20,000.00 ,20,000 INR 200.25 INR.</code> </b></p>
<p>Output should be
2000,2000,20000.00,20000,200.25</p>
<p>The regular expression i have tried is this</p>
<pre><code>(?:(?:(?:rs)|(?:inr))(?:!-{0,}|\.{1}|\ {0,}|\.{1}\ {0,}))(-?[\d,]+ (?:\.\d+)?)(?:[... | 5 | 2016-07-13T05:58:08Z | 38,344,788 | <p>And another:</p>
<pre><code>(([\d+\,]+)(\.\d+)?\s\w{3}|(\w+\.?)\s?[\d+\,]+(\.?\d+))
</code></pre>
| 0 | 2016-07-13T07:05:54Z | [
"python",
"regex"
] |
I want to match money amount with regex for indian currency without commas | 38,343,671 | <p>I want to match amount like <b><code>Rs. 2000 , Rs.2000 , Rs 20,000.00 ,20,000 INR 200.25 INR.</code> </b></p>
<p>Output should be
2000,2000,20000.00,20000,200.25</p>
<p>The regular expression i have tried is this</p>
<pre><code>(?:(?:(?:rs)|(?:inr))(?:!-{0,}|\.{1}|\ {0,}|\.{1}\ {0,}))(-?[\d,]+ (?:\.\d+)?)(?:[... | 5 | 2016-07-13T05:58:08Z | 38,348,334 | <p>Though slightly out of scope, here's a fingerplay with the newer and far superior <strong><a href="https://pypi.python.org/pypi/regex" rel="nofollow"><code>regex</code></a></strong> module by <em>Matthew Barnett</em> (which has the ability of subroutines and branch resets):</p>
<pre><code>import regex as re
rx = r... | 2 | 2016-07-13T09:55:19Z | [
"python",
"regex"
] |
I want to match money amount with regex for indian currency without commas | 38,343,671 | <p>I want to match amount like <b><code>Rs. 2000 , Rs.2000 , Rs 20,000.00 ,20,000 INR 200.25 INR.</code> </b></p>
<p>Output should be
2000,2000,20000.00,20000,200.25</p>
<p>The regular expression i have tried is this</p>
<pre><code>(?:(?:(?:rs)|(?:inr))(?:!-{0,}|\.{1}|\ {0,}|\.{1}\ {0,}))(-?[\d,]+ (?:\.\d+)?)(?:[... | 5 | 2016-07-13T05:58:08Z | 38,375,254 | <p>I dont want to match commas in amount.</p>
<p>(?:Rs.?|INR)\s*(\d+(?:[.][^,]\d+)<em>)|(\d+(?:[.][^,]\d+)</em>)\s*(?:Rs.?|INR)</p>
<p>but this is not working</p>
| 0 | 2016-07-14T13:13:42Z | [
"python",
"regex"
] |
Getting 'str' object has no attribute 'is_authenticated' in Flask using Flask-Login | 38,343,717 | <p>I am trying to set up login for Flask using Flask-Login. I have a CouchDB for users; the customer documents have an object called "user".</p>
<pre><code>class User(UserMixin):
def __init__ (self, user) :
self.name = user['name']
self.password = user['password']
self.id= user['id']
... | 0 | 2016-07-13T06:02:13Z | 38,350,761 | <p>The <code>user_loader</code> function (in your case the logic is in <code>check_user</code>) should return <code>None</code> if a userid is not valid. In your case a string <code>"User not found in database"</code> is returned, which creates the exception you are encountering.</p>
<p>Return <code>None</code> if the... | 1 | 2016-07-13T11:41:33Z | [
"python",
"flask",
"flask-login"
] |
Lucas probable prime test | 38,343,738 | <p>I have been trying to implement the <a href="https://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test" rel="nofollow">Baillie-PSW primality test</a> for a few days, and have ran into some problems. Sepcifically when trying to use the <a href="https://en.wikipedia.org/wiki/Lucas_pseudoprime#Implementing_a_Luc... | 2 | 2016-07-13T06:03:50Z | 38,352,706 | <p>Here is my Lucas pseudoprimality test; you can run it at <a href="http://ideone.com/57Iayq" rel="nofollow">ideone.com/57Iayq</a>.</p>
<pre><code># lucas pseudoprimality test
def gcd(a,b): # euclid's algorithm
if b == 0: return a
return gcd(b, a%b)
def jacobi(a, m):
# assumes a an integer and
# m a... | 1 | 2016-07-13T13:09:46Z | [
"python",
"math",
"primes"
] |
tsne.fit_transform(final_embeddings(...) - ValueError: array must not contain infs or NaNs | 38,343,834 | <p>I have been running this <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/word2vec/word2vec_basic.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/word2vec/word2vec_basic.py</a> on ipython notebook but I am getting this e... | 0 | 2016-07-13T06:10:11Z | 38,406,400 | <p>Does your program download the data successfully? Did you see this output at all before the error messages?</p>
<pre><code>Found and verified text8.zip
Data size 17005207
Most common words (+UNK) [['UNK', 418391], ('the', 1061396), ('of', 593677), ('and', 416629), ('one', 411764)]
Sample data [5241, 3083, 12, 6, 19... | 0 | 2016-07-15T23:50:07Z | [
"python",
"python-2.7",
"tensorflow",
"deep-learning",
"jupyter-notebook"
] |
"-bash: python2: command not found" on OS X | 38,343,960 | <p>I'm trying to use <a href="https://github.com/Tamriel/quod_libet_import_itunes_ratings" rel="nofollow">this</a> script to import my iTunes library to another program. </p>
<p>At the step where I enter <code>python2 export_to_quod_libet.py</code>, I'm getting an error message that says that the <code>python2</code> ... | 0 | 2016-07-13T06:18:49Z | 38,347,054 | <p>Maybe you could try do define an alias. It seems that python2 is hardcoded somewhere in the script.</p>
<p>You could try (just an example):</p>
<pre><code>alias python2="python2.7"
</code></pre>
<p>and then run the script -- hope that helps.</p>
<p>Kind regards,
Julian</p>
| 1 | 2016-07-13T08:58:49Z | [
"python",
"bash",
"osx"
] |
DataFrame.sum returns Series and not a number | 38,343,972 | <p>My basic task is to take vector <code>x=[x1,x2,x3,x4]</code> (which in my case is presented by a row of a Pandas dataframe, lets say a row with an index = 1), multiply it by scalar <code>k</code> and to sum up the results -> <code>x1*k + x2*k + x3*k + x4*k</code>.</p>
<p>I did not find a function that would do it i... | 2 | 2016-07-13T06:19:29Z | 38,344,077 | <p>IIUC select row in <code>df</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="nofollow"><code>sum</code></a> and multiple by <code>k</c... | 2 | 2016-07-13T06:26:22Z | [
"python",
"pandas"
] |
How to manage temporary variables in Python 3.5? | 38,344,158 | <p>If i have many functions in python script, can i use same variable name for all those functions?
If yes, is it efficient? and how?
or
is it better to use different name for different functions?
Ex:</p>
<pre><code>def func1():
tmp = 1
........
def func2():
tmp = 2
........
def funcn():
tmp ... | -3 | 2016-07-13T06:31:18Z | 38,344,192 | <p>Each function creates a new scope. Since you aren't using <code>global</code> or <code>nonlocal</code>, none of the <code>tmp</code> will influence each other in any way so it is <em>safe</em> to keep using that name over and over in different functions.</p>
<p>With that said, names like <code>tmp</code> are not v... | 2 | 2016-07-13T06:33:36Z | [
"python"
] |
How to manage temporary variables in Python 3.5? | 38,344,158 | <p>If i have many functions in python script, can i use same variable name for all those functions?
If yes, is it efficient? and how?
or
is it better to use different name for different functions?
Ex:</p>
<pre><code>def func1():
tmp = 1
........
def func2():
tmp = 2
........
def funcn():
tmp ... | -3 | 2016-07-13T06:31:18Z | 38,344,354 | <p>Answer is "YES". In this case tmp is local to the function scope. so You can use same variable name for all the functions.But that doesn't mean, it stores values in same memory location. So we can not say it is efficient in storage complexity.And if we consider the running time, It does not depend on variable names.... | 0 | 2016-07-13T06:42:51Z | [
"python"
] |
python regex: extract special substring in a hyperlink | 38,344,399 | <p>I use python grabbed a series of hyperlinks, I want to extract specific character string from these hyperlinks.
the hyperlinks like below:
â<a href="http://tianqi.2345.com/hongkong/61063.htm" rel="nofollow">http://tianqi.2345.com/hongkong/61063.htm</a>â</p>
<p>it contains a city name(hongkong) and a city I... | 1 | 2016-07-13T06:45:28Z | 38,344,512 | <p>You've a simple syntax problem in <code>search</code> function, quotes are mismatched (<code>'</code> in the start of string and <code>"</code> at the end) and if you want to match a dot (<code>.</code> symbol in regex matches almost any character), you need to escape it. </p>
<pre><code>foundTagA = re.search("http... | 0 | 2016-07-13T06:51:16Z | [
"python",
"regex",
"beautifulsoup"
] |
python regex: extract special substring in a hyperlink | 38,344,399 | <p>I use python grabbed a series of hyperlinks, I want to extract specific character string from these hyperlinks.
the hyperlinks like below:
â<a href="http://tianqi.2345.com/hongkong/61063.htm" rel="nofollow">http://tianqi.2345.com/hongkong/61063.htm</a>â</p>
<p>it contains a city name(hongkong) and a city I... | 1 | 2016-07-13T06:45:28Z | 38,344,575 | <p>Another <em>alternate</em> would be to use <code>urlparse</code> (<a href="https://docs.python.org/2/library/urlparse.html" rel="nofollow">Python2 Doc</a> / <a href="https://docs.python.org/3/library/urllib.parse.html" rel="nofollow">Python3 Doc</a>)</p>
<pre><code># For Python 2
>>> from urlparse import u... | 1 | 2016-07-13T06:54:42Z | [
"python",
"regex",
"beautifulsoup"
] |
python regex: extract special substring in a hyperlink | 38,344,399 | <p>I use python grabbed a series of hyperlinks, I want to extract specific character string from these hyperlinks.
the hyperlinks like below:
â<a href="http://tianqi.2345.com/hongkong/61063.htm" rel="nofollow">http://tianqi.2345.com/hongkong/61063.htm</a>â</p>
<p>it contains a city name(hongkong) and a city I... | 1 | 2016-07-13T06:45:28Z | 38,344,613 | <pre><code>foundTagA = re.search('http://tianqi.2345.com/(?P<CityName>\w+?)/(?P<CityID>\d+?).htm', reNamedGroupTestStr)
</code></pre>
<p>Above code should work. </p>
<p>Instead of using <code>.</code> as wildcard search I use specific <code>\w</code> and <code>\d</code> to improve efficiency</p>
| 0 | 2016-07-13T06:57:05Z | [
"python",
"regex",
"beautifulsoup"
] |
python regex: extract special substring in a hyperlink | 38,344,399 | <p>I use python grabbed a series of hyperlinks, I want to extract specific character string from these hyperlinks.
the hyperlinks like below:
â<a href="http://tianqi.2345.com/hongkong/61063.htm" rel="nofollow">http://tianqi.2345.com/hongkong/61063.htm</a>â</p>
<p>it contains a city name(hongkong) and a city I... | 1 | 2016-07-13T06:45:28Z | 38,344,676 | <p>hope it help.</p>
<pre><code>import re
reNamedGroupTestStr = 'http://tianqi.2345.com/hongkong/61063.htm'
# \S matches any non-whitespace character
# \d matches any decimal digit ; equivalent to the set [0-9]
foundTagA = re.search("http://tianqi.2345.com/(?P<CityName>\S+?)/(?P<CityID>\d+?)\.htm", reNamed... | 0 | 2016-07-13T06:59:55Z | [
"python",
"regex",
"beautifulsoup"
] |
python regex: extract special substring in a hyperlink | 38,344,399 | <p>I use python grabbed a series of hyperlinks, I want to extract specific character string from these hyperlinks.
the hyperlinks like below:
â<a href="http://tianqi.2345.com/hongkong/61063.htm" rel="nofollow">http://tianqi.2345.com/hongkong/61063.htm</a>â</p>
<p>it contains a city name(hongkong) and a city I... | 1 | 2016-07-13T06:45:28Z | 38,344,810 | <p>You can just split:</p>
<pre><code>u = "http://tianqi.2345.com/hongkong/61063.htm"
_, nme, c_id = u.rsplit("/", 2)
print(nme, c_id.split(".", 1)[0])
</code></pre>
<p>Which will give you:</p>
<pre><code>hongkong 61063
</code></pre>
<p>If you want to check if the url startswith the host:</p>
<pre><code>if u.sta... | 1 | 2016-07-13T07:06:55Z | [
"python",
"regex",
"beautifulsoup"
] |
How to include dynamic time? | 38,344,487 | <p>I am trying to pull the logs with respect to time slots. The program below runs very fine when no. of hours are given and the logs in that range gets extracted. </p>
<p>But now I also what to include Start and end to be dynamically given. i.e. say between <code>8 am to 8pm</code> or <code>6am to 8am</code> and so ... | 2 | 2016-07-13T06:49:46Z | 38,511,749 | <p>try this:</p>
<pre><code>import pandas as pd
from datetime import datetime,time
import numpy as np
fn = r'D:\data\gDrive\data\.stack.overflow\2016-07\dart_small.csv'
cols = ['UserID','StartTime','StopTime', 'gps1', 'gps2']
df = pd.read_csv(fn, header=None, names=cols)
df['m'] = df.StopTime + df.StartTime
df['d']... | 1 | 2016-07-21T18:25:58Z | [
"python",
"csv",
"datetime",
"numpy",
"pandas"
] |
Pandas replace with dict issue | 38,344,511 | <p>I am making replace via dict on large series (3M records approx). Dict size is ~11k like this:</p>
<pre><code>data['TOBE'] = data['ASIS'].replace(zdict)
</code></pre>
<p>It takes a while and then i obtain an error of type mismatch:</p>
<pre><code>TypeError: Cannot compare types 'ndarray(dtype=object)' and 'str'
<... | 3 | 2016-07-13T06:51:11Z | 38,345,185 | <p>I see that what you are replacing with is a zdict data. If this represents <a href="https://pypi.python.org/pypi/zdict" rel="nofollow">this</a> Python framework, then would you consider trying to replace with a dummy data in string format instead with the zdict data. If this is possible then there might be a bug wit... | 1 | 2016-07-13T07:25:44Z | [
"python",
"pandas",
"replace"
] |
Pandas replace with dict issue | 38,344,511 | <p>I am making replace via dict on large series (3M records approx). Dict size is ~11k like this:</p>
<pre><code>data['TOBE'] = data['ASIS'].replace(zdict)
</code></pre>
<p>It takes a while and then i obtain an error of type mismatch:</p>
<pre><code>TypeError: Cannot compare types 'ndarray(dtype=object)' and 'str'
<... | 3 | 2016-07-13T06:51:11Z | 38,345,222 | <p>So my only hypotesis is that its an insufficient memory issue which is not processed by exception.</p>
<p>I am thinking of it because while replacing i get ~98% RAM usage. I have only 8 GB.</p>
<p>The chunk approach seems to work.</p>
| 0 | 2016-07-13T07:27:48Z | [
"python",
"pandas",
"replace"
] |
Implementing a custom counting system in Python | 38,344,626 | <p>In finance, futures contracts are usually represented by their expiry year and month. So for example, <code>201212</code> would be 2012 - December.</p>
<p>Some contracts, for example Corn, are only traded some months <code>[3,5,7,9,12]</code>, whereas sometimes, <em>you</em> might only want to trade the <code>[12]<... | 5 | 2016-07-13T06:57:56Z | 38,344,858 | <p>This should do it:</p>
<pre><code>def next_contract(contract, last=False):
d = pd.to_datetime(str(contract), format='%Y%m')
d += pd.offsets.MonthBegin(12 * (last * -2 + 1))
return int(d.strftime('%Y%m'))
</code></pre>
<h3>Demo</h3>
<pre><code>next_contract(201212)
201312
next_contract(201212, last=T... | 2 | 2016-07-13T07:08:45Z | [
"python",
"numpy",
"pandas"
] |
align audio files that start and end at different times | 38,344,701 | <p>I have audio recordings that starts and ends at different times. </p>
<pre><code>audio 1: -----t1--------------------------s1->time
audio 2: ---------t2----s2------------------->time
audio 3: ------------------------t3-------s3->time
</code></pre>
<p>audio 1 is the longest and it overlaps with both audio ... | -2 | 2016-07-13T07:01:00Z | 38,350,080 | <p>You could first use a python library to <strong>read the audio file</strong> (numpy or scipy for instance, see <a href="http://stackoverflow.com/a/26716031/3244382">http://stackoverflow.com/a/26716031/3244382</a>).</p>
<p>Then you have to <strong>determine t and s for each file</strong>. If the files are not too no... | 0 | 2016-07-13T11:13:01Z | [
"python",
"audio"
] |
How to do semantic keyword search with nlp | 38,344,740 | <p>I want to do SEMANTIC keyword search on list of topics with NLP(Natural Language Processing ). It would be very appreciable if you post any reference links or ideas.</p>
| 0 | 2016-07-13T07:03:33Z | 38,437,943 | <p>Your questions is somewhat vague but I will try nonetheless...</p>
<p>If I understand you correctly then what you want to do (depending on the effort you want to spend) is the following:</p>
<ol>
<li><p>Expand the keyword to a synonym list that you will use to search for in the topics (you can use WordNet for this... | 0 | 2016-07-18T13:25:57Z | [
"java",
"python",
"search",
"nlp",
"semantics"
] |
why i am getting AttributeError: 'module' object has no attribute 'set_trace' | 38,344,825 | <pre><code>import pdb
print("program started")
c=100
d=200
pdb.set_trace()
def fun(a,b):
print a,b
return a+b
fun(c,d)
for i in [1,2,3,4,5]:
print 10/i
print ("other statements in program")
print ("program ended")
</code></pre>
| -2 | 2016-07-13T07:07:22Z | 38,345,260 | <p>The python module <code>pdb</code> has a <code>set_trace()</code> function. Since your program is not finding it, it is importing something else. Almost certainly, you named your program (or another program in the same directory) <code>pdb.py</code>.</p>
| 0 | 2016-07-13T07:29:54Z | [
"python",
"pdb"
] |
why i am getting AttributeError: 'module' object has no attribute 'set_trace' | 38,344,825 | <pre><code>import pdb
print("program started")
c=100
d=200
pdb.set_trace()
def fun(a,b):
print a,b
return a+b
fun(c,d)
for i in [1,2,3,4,5]:
print 10/i
print ("other statements in program")
print ("program ended")
</code></pre>
| -2 | 2016-07-13T07:07:22Z | 38,345,634 | <p>it works fine for me</p>
<p>`</p>
<pre><code>[root@ebs-49393 tmp]# cat test.py
import json,pdb
buf = open('./a.txt').read()
j = json.loads(buf)
pdb.set_trace()
print j
[root@ebs-49393 tmp]# python test.py
> /tmp/test.py(5)<module>()
-> print j
(Pdb) list
1 import json,pdb
2 buf = open('./... | 0 | 2016-07-13T07:49:59Z | [
"python",
"pdb"
] |
Is there a comprehensive table of Python's "magic constants"? | 38,344,848 | <p>Where are <code>__file__</code>, <code>__main__</code>, etc. defined, and what are they officially called? <code>__eq__</code> and <code>__ge__</code> are "magic methods", so right now I'm just referring to them as "magic constants" but I don't even know if that's right.</p>
<p>Google search really isn't turning up... | 8 | 2016-07-13T07:08:28Z | 38,345,345 | <p>Short answer: <strong>no</strong>. For the longer answer, which got badly out of hand, keep reading...</p>
<hr>
<p>There is no comprehensive table of those <code>__dunder_names__</code> (also not their official title!), as far as I'm aware. There are a couple of sources:</p>
<ul>
<li><p>The only real <em>"magic c... | 11 | 2016-07-13T07:34:35Z | [
"python",
"python-3.x"
] |
python socket : server must send a message before recv | 38,344,970 | <p>In socket, I found that if server does not send any message before call recv(), server will be no response, whatever using mutilthread or not.
As the figure shows below:</p>
<p><a href="http://i.stack.imgur.com/fWj4C.png" rel="nofollow">enter image description here</a></p>
<p><a href="http://i.stack.imgur.com/ldM6... | 0 | 2016-07-13T07:15:27Z | 38,345,476 | <p>Thanks dsgdfg, I knew that I was wrong in client.py.
It's always call a recv() at first, so server.py should also send something to client.</p>
| 1 | 2016-07-13T07:41:02Z | [
"python",
"sockets"
] |
python socket : server must send a message before recv | 38,344,970 | <p>In socket, I found that if server does not send any message before call recv(), server will be no response, whatever using mutilthread or not.
As the figure shows below:</p>
<p><a href="http://i.stack.imgur.com/fWj4C.png" rel="nofollow">enter image description here</a></p>
<p><a href="http://i.stack.imgur.com/ldM6... | 0 | 2016-07-13T07:15:27Z | 38,345,500 | <pre><code># server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
pri... | 0 | 2016-07-13T07:41:54Z | [
"python",
"sockets"
] |
How to convert List of JSON frames to JSON frame | 38,345,004 | <p>I want to convert List of JSON object ot Single JSON frame</p>
<p>Here is my code</p>
<pre><code>for i in user1:
name=i.name
password=i.password
id1=i.id
user = { "name" : name,
"password" : password,
"id":id1}
user = json.dumps(user)
userid.append(user)
</code><... | 0 | 2016-07-13T07:17:05Z | 38,345,919 | <p><code>json.dumps()</code> returns a string, so you're append strings to <code>userid</code>âand thus end up with the list of strings shown. </p>
<p>If you want a dictionary of dictionaries using the <code>id</code> as the primary key, all you need is:</p>
<pre><code>users = {i.id: {"name": i.name, "password": i.... | 2 | 2016-07-13T08:04:33Z | [
"python",
"json",
"list",
"python-2.7"
] |
How to convert List of JSON frames to JSON frame | 38,345,004 | <p>I want to convert List of JSON object ot Single JSON frame</p>
<p>Here is my code</p>
<pre><code>for i in user1:
name=i.name
password=i.password
id1=i.id
user = { "name" : name,
"password" : password,
"id":id1}
user = json.dumps(user)
userid.append(user)
</code><... | 0 | 2016-07-13T07:17:05Z | 38,346,601 | <p>What I've done now is </p>
<pre><code>user = {}
name,password,id1 = [],[],[]
user1=session.query(User).all()
for i in user1:
name=i.name
password=i.password
id1=i.id
user.update({ id1:{
"name" : name,
"password" : password,
}
})
</code></pre>
<p>Thanks all ... | 0 | 2016-07-13T08:37:45Z | [
"python",
"json",
"list",
"python-2.7"
] |
binary tree add left and add right nodes not adding | 38,345,023 | <p>I'm reading the following data as part of an assignment into a <strong>binary tree</strong> (not a <strong>strict binary search tree</strong>):</p>
<pre><code>5
4 1 2
2 3 4
5 -1 -1
1 -1 -1
3 -1 -1
</code></pre>
<p>They're being read into three lists in python <code>self.key</code>, <code>self.left</code> and <code... | 0 | 2016-07-13T07:18:01Z | 38,364,679 | <p>Thanks I got it to work - I added the nodes <code>Node(key[i])</code> to a dictionary and <code>self.nodes[val] = [node, node.l, node.r]</code> and when adding the left and recursively searched the dictionary for inOrder, preOrder and postOrder tree traversals.</p>
<pre><code> class Node:
def __init__(self, val... | 0 | 2016-07-14T02:44:37Z | [
"python",
"algorithm",
"tree",
"binary-tree"
] |
Minor ticks for plot using Pandas | 38,345,127 | <p>So I am trying to get minor tick grid lines to get displayed but they don't seem to appear on the plot. An example code is </p>
<pre><code>data_temp = pd.read_csv(dir_readfile, dtype=float, delimiter='\t',
names = names, usecols=[0,1,2,3,4])
result = data_temp.groupby(['A', 'D']).agg({'B':'mea... | 3 | 2016-07-13T07:22:58Z | 38,346,709 | <p>Before <code>plt.show()</code> add <code>plt.minorticks_on()</code>.</p>
<p>If you want to add minor ticks for selected axis then use:</p>
<pre><code>ax = plt.gca()
ax.tick_params(axis='x',which='minor',bottom='off')
</code></pre>
| 3 | 2016-07-13T08:42:30Z | [
"python",
"numpy",
"pandas",
"matplotlib"
] |
How to use "create_web_element" method | 38,345,245 | <p>I got <code>chromedriver</code> version <code>2.9.248315</code> and found new method called <code>create_web_element(element_id)</code>. The only information I got from <code>help(driver.create_web_element)</code> is </p>
<blockquote>
<p>Creates a web element with the specified element_id.</p>
</blockquote>
<p>A... | 2 | 2016-07-13T07:29:04Z | 38,345,385 | <p><code>driver.create_web_element</code> only creates a <code>WebElement</code> object. It does not add this object to the DOM, therefore, it cannot be found with <code>find_element_by_id</code>.</p>
<p>If you want to create elements in the DOM, you can add elements using the <a href="http://www.w3schools.com/js/js_... | 3 | 2016-07-13T07:36:46Z | [
"python",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] |
With openpyxl how can I find out how many cells are merged in .xlsx | 38,345,407 | <p>I have sheet where the "heading" are in merged cells and the value is in the cells under the "heading", see example.</p>
<p>How can I count how many cells the heading spans? I need this to know where to start and stop reading the cells that belong to the "heading".</p>
<pre><code>+-----------+-----------+
| Headi... | 0 | 2016-07-13T07:37:38Z | 38,345,909 | <p>You could use a function in VBA in Excel, like below</p>
<pre><code>Public Function COLUMNSINMERGED(r As Excel.Range)
If r.MergeCells Then
COLUMNSINMERGED=r.MergeArea.Columns.Count
Debug.Print r.MergeArea.Address, "Cols : " & r.MergeArea.Columns.Count, "Rows : " & r.MergeArea.Rows.Count
else
COL... | -1 | 2016-07-13T08:04:11Z | [
"python",
"excel",
"openpyxl"
] |
Communicating to a process launched in the Terminal in UNIX through python | 38,345,481 | <p>I am creating a GUI to facilitate some of the task in UNIX.
I would like to launch a process throught Terminal in UNIX.
I used the module of </p>
<pre><code>subprocess.Popen()
</code></pre>
<p>to launch the process.
The problem is that when i launch the process, the process demands the user, their password.
I am... | 0 | 2016-07-13T07:41:12Z | 38,361,971 | <p>You should be able to use the <a href="https://pypi.python.org/pypi/pexpect" rel="nofollow">Pexpect</a> package to do this sort of thing. It has been detailed in other answers such as this one:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/15166973/sending-a-password-over-ssh-or-scp-with-subprocess-popen... | 0 | 2016-07-13T21:26:18Z | [
"python",
"wxpython",
"subprocess"
] |
Firefox is crashing and I am getting ConnectionResetError when used Python with Selenium | 38,345,646 | <p>I started working on a python script that is going to navigate through a webpage and going to take some necessary datas for me.</p>
<p>I found a code that uses selenium in it to navigate the internet.</p>
<p>The problem is, when I run the code, Firefox is crashing and I am getting the <strong>ConnectionResetError:... | 0 | 2016-07-13T07:50:32Z | 38,366,922 | <p>For those who wants to have an answer, 47 versioned Firefox browsers have a problem with this. So I've tried to owrk with a lower version then 47 and it worked.</p>
<p>I'd suggest if it is not necessary, use Chrome. (First you need to download the driver) That way you are not going to stuck with something like this... | 0 | 2016-07-14T06:25:35Z | [
"python",
"selenium"
] |
getting tag names at one level with Beautifulsoup for XML | 38,345,656 | <p>Related to this: <a href="http://stackoverflow.com/questions/19559191/getting-tag-names-with-beautifulsoup">Getting Tag Names with BeautifulSoup</a></p>
<p>I have an XML document, and I want to get all of the tags at a single level - so parsing</p>
<pre><code><parent>
<child>
</child>
<... | 1 | 2016-07-13T07:50:54Z | 38,345,998 | <p>Use the <a href="http://omz-software.com/pythonista/docs/ios/beautifulsoup_ref.html" rel="nofollow"><code>recursive</code></a> keyword</p>
<pre><code>for tag in document.findChildren(recursive=False):
print tag.name
</code></pre>
| 1 | 2016-07-13T08:08:58Z | [
"python",
"python-2.7",
"beautifulsoup",
"bs4"
] |
How to display certain parts of a list ? (Python) | 38,345,664 | <p>The basic salary is the third element of each object.</p>
<pre><code>employee_list = []
sales1 = SalesEmployee('1001', 'Alex', 2000.00, 20000.00, 8.00)
sales2 = SalesEmployee('1002', 'Mark', 1800.00, 22000.00, 6.00)
sales3 = SalesEmployee('1003', 'Fiona', 2500.00, 16000.00, 5.00)
part1 = PartTimeEmployee('2001',... | -3 | 2016-07-13T07:51:45Z | 38,347,208 | <p>if SalesEmployee and PartTimeEmployee has the same super class, define a function to display information</p>
<p>within this function, use typeof() to see if an object is SalesEmployee or PartTimeEmployee, then display information accordingly.</p>
<pre><code>class Employee
def show:
if(typeof(self) == PartTimeE... | 0 | 2016-07-13T09:05:41Z | [
"python"
] |
Best python module to generate a simple PNG graph based on a CSV | 38,345,670 | <p>Whats in your opinion the best module to generate a bar graph in png format based on the .CSV below? I am looking for something really sikmple because the idea is to attach it to an email that is also also sent by python. I am not interested in web/html visualisation, just a picture format. If you could also point m... | -1 | 2016-07-13T07:52:12Z | 38,345,751 | <p>You could do it like in this example <a href="https://plot.ly/pandas/bar-charts/" rel="nofollow">https://plot.ly/pandas/bar-charts/</a></p>
| -2 | 2016-07-13T07:56:23Z | [
"python",
"csv",
"graph"
] |
Twisted I/O archive files | 38,345,728 | <p>I'm having troubles writing asynchronous I/O program. What I'm trying to achieve is: dump json data into a temporary file so I can then use subprocess to create an archive of that file (with json data). However I figured out that I'm trying to tar an empty file from <code>tempfile.NamedTemporatyFile</code>.</p>
<pr... | 1 | 2016-07-13T07:55:09Z | 38,346,173 | <p>Close the file after you write to it and before launching the secondary thread.</p>
| 0 | 2016-07-13T08:17:01Z | [
"python",
"json",
"twisted",
"archive"
] |
Reading Data from MySql server in pandas data frame. Error in Getting (0,1) variable | 38,345,767 | <p>I have some data in MySql server and I am reading it in pandas datframe by this.</p>
<pre><code>mysql_cn = MySQLdb.connect(host='localhost',user='nxplr',passwd='fluffy',db='customer_tracker',port=3306)
cur_date = datetime.date(2016,5,22)
cur_date_str = cur_date.strftime('%Y-%m-%d')
#cur_date_str = '05/22/2016' ... | 0 | 2016-07-13T07:57:36Z | 38,347,466 | <p>try this:</p>
<pre><code>mysql_cn = MySQLdb.connect(host='localhost',user='nxplr',passwd='fluffy',db='customer_tracker',port=3306)
cur_date = datetime.date(2016,5,22)
qry = 'select * from customer_tracker.t_visit where walk_in_flag = 1 and visit_date = :1'
try:
visit_data = pd.read_sql(qry, con=mysql_cn, par... | 0 | 2016-07-13T09:17:18Z | [
"python",
"mysql",
"python-2.7",
"pandas"
] |
Can't pickle object error using SqlAlchemy | 38,345,816 | <p>I'm trying to store a mutable object in a postgresql database using SqlAlchemy. The class of the object is roughly:</p>
<pre><code>class Data(Mutable, object):
@classmethod
def coerce(cls, key, value):
return value
def __init__(self, foo, bar):
self._foo = foo # foo is an array of s... | 2 | 2016-07-13T08:00:07Z | 38,367,490 | <p>From reading <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/mutable.html#supporting-pickling" rel="nofollow">"Supporting Pickling"</a> it would seem you must provide at least the <code>__getstate__</code> method for custom mutable types:</p>
<blockquote>
<p>The developer responsibility here is only ... | 3 | 2016-07-14T06:59:00Z | [
"python",
"sqlalchemy",
"pickle"
] |
How do I append a dataframe to a specific level of another dataframe | 38,345,960 | <p>Consider these two dataframes:</p>
<pre><code>df1 = pd.DataFrame(np.arange(16).reshape(4, 4),
pd.MultiIndex.from_product([['a', 'b'], ['A', 'B']]),
['One', 'Two', 'Three', 'Four'])
df2 = pd.DataFrame(np.arange(8).reshape(2, 4),
['C', 'D'],
... | 1 | 2016-07-13T08:06:50Z | 38,345,961 | <p>First I reassign the index of <code>df2</code> with a <code>pd.MultiIndex</code> with the desired location in the first level of the index included in the new index.</p>
<pre><code>df2.index = pd.MultiIndex.from_product([['a'], df2.index])
</code></pre>
<p>then <code>concat</code></p>
<pre><code>pd.concat([df1, d... | 1 | 2016-07-13T08:06:50Z | [
"python",
"pandas",
"multi-index"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.