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 |
|---|---|---|---|---|---|---|---|---|---|
SimpleITK N4BiasFieldCorrection, not working with any data type | 39,999,646 | <p>Just installed the latest version of SimpleITK and I'm trying to run a simple code as:</p>
<pre><code>im = sitk.ReadImage('img.nii.gz')
im_bin = sitk.ReadImage('img_bin.nii.gz')
im_bfc = sitk.N4BiasFieldCorrection(im, im_bin)
</code></pre>
<p>the error is </p>
<pre><code>RuntimeError: Exception thrown in SimpleIT... | 1 | 2016-10-12T13:18:06Z | 40,004,118 | <p>In answering my question, I found that the errors raised do not seem to be related to the real cause. If the mask is made with a threshold with sitk as</p>
<pre><code>bth = sitk.BinaryThresholdImageFilter()
img_bin = bth.Execute(img)
img_bin = -1 * (img_mask - 1)
im_bfc = sitk.N4BiasFieldCorrection(im, im_bin)
... | 0 | 2016-10-12T16:50:18Z | [
"python"
] |
Incorrect reindexing when Summer Time shifts by 1 hour | 39,999,694 | <p>I am trying to solve a 1 hour time shift which happens for US daylight saving time zone.</p>
<p>This of part of a time series (snipping below)</p>
<pre><code> In [3] eurusd
Out[3]:
BID-CLOSE
TIME
1994-03-28 22:00:00 1.15981
1994-03-29 22:00:00 ... | 1 | 2016-10-12T13:20:00Z | 39,999,983 | <p>I am guessing that your date index is time zone naive.</p>
<p>first set the time zone, I will assume they are UTC</p>
<pre><code>eurusd = eurusd.tz_localize('UTC')
</code></pre>
<p>then you can convert them to whatever time zone you like such has</p>
<pre><code>eurusd = eurusd.tz_convert('America/New_York')
</co... | 1 | 2016-10-12T13:31:57Z | [
"python",
"pandas",
"quantitative-finance"
] |
can we call python script in node js and run node js to get call? | 39,999,710 | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>python.py
from pymongo import MongoClient
from flask import Flask
app = Flask(__name__)
host = "10.0.0.10"
port = 8085
... | 1 | 2016-10-12T13:20:40Z | 40,000,080 | <p><a href="http://www.zerorpc.io/" rel="nofollow">ZERORPC</a> is a really nifty library built on top of ZeroMQ. This is probably the easiest way to make call python code from Node.</p>
<p>For a really simple approach and non-robust approach, you could use a tmp file to write the python commands from Node. With an eve... | 0 | 2016-10-12T13:35:47Z | [
"android",
"python",
"node.js"
] |
Skip debug instructions (and their content) if logging is set to INFO | 39,999,767 | <p>I have a program in which I wrote logs both as info and debug.</p>
<p>Since the debug contains also calls to slow functions, my program is running slow even if I set debugging to INFO.</p>
<p>Is it possible to completely skip those line from computation?</p>
<p>in the next example 10 seconds have to pass before t... | 1 | 2016-10-12T13:22:45Z | 39,999,839 | <p>You could check if the logger is enabled for such a level with the <a href="https://docs.python.org/2/library/logging.html#logging.Logger.isEnabledFor" rel="nofollow"><code>isEnabledFor</code></a> method:</p>
<pre><code>if logger.isEnabledFor(logging.DEBUG):
logger.debug("aaa", time.sleep(10))
logger.debug(... | 1 | 2016-10-12T13:25:56Z | [
"python",
"logging"
] |
Skip debug instructions (and their content) if logging is set to INFO | 39,999,767 | <p>I have a program in which I wrote logs both as info and debug.</p>
<p>Since the debug contains also calls to slow functions, my program is running slow even if I set debugging to INFO.</p>
<p>Is it possible to completely skip those line from computation?</p>
<p>in the next example 10 seconds have to pass before t... | 1 | 2016-10-12T13:22:45Z | 39,999,857 | <p>You shouldn't have logging inside debug commands. If you must, then in order to skip it you must branch your code.</p>
<pre><code>import logging.handlers
import sys
import time
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging_stream_handler = logging.StreamHandler(sys.stdout)
logging_stream_handl... | 0 | 2016-10-12T13:27:16Z | [
"python",
"logging"
] |
PyMongo .find() Special Characters | 39,999,976 | <p>So I have set up a database in MongoDB and a majority of documents contain a special code which can begin with a * and finish with a #. When I use the following query on the MongoDb command line, it works fine but when I try to use it in a python script, it doesn't work.</p>
<pre><code>cursor = collect.find({$and:[... | 0 | 2016-10-12T13:31:33Z | 40,000,389 | <p>If you want to query using a regular expression, then you have to create a Python regular expression object. Note that in this case the string should not be surrounded by <code>//</code>.</p>
<pre><code>import re
cursor = collect.find({'$and':[{"key":re.compile('.*\*.*')},{"key":re.compile('.*\#.*')}]})
</code></pr... | 0 | 2016-10-12T13:49:45Z | [
"python",
"mongodb",
"pymongo"
] |
QMenu displays incorrectly when setParent called | 40,000,081 | <p>I want to create a function to build a context menu that can be dynamically added to a window's menubar. Consider the following minimal example for adding a simple QMenu:</p>
<pre><code>from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainW... | 1 | 2016-10-12T13:35:50Z | 40,002,859 | <p>The way you're calling <code>setParent</code> resets the window flags, so do this instead:</p>
<pre><code> menu.setParent(self, menu.windowFlags())
</code></pre>
| 3 | 2016-10-12T15:44:43Z | [
"python",
"qt",
"pyqt",
"qmenu",
"qmenubar"
] |
Python handle 'NoneType' object has no attribute 'find_all' error with if else statement | 40,000,090 | <p>I am using beautifulsoup4 to grab stock data and send to a spreadsheet in python. The problem I am having is that I cannot get my loop to skip over attributes that return None. So what I am needing is the code to add null values to rows where
attribute would return none.</p>
<pre><code>//my dictionay for storing d... | -1 | 2016-10-12T13:36:09Z | 40,109,751 | <p>You have used the <code>data</code> variable for two different things. The second usage overwrote your dictionary. It is simpler to just use <code>html.text</code> in the call to <code>soup.find()</code>. Try the following:</p>
<pre><code>import requests
import bs4
# My dictionary for storing data
data = {
... | 0 | 2016-10-18T13:33:04Z | [
"python",
"csv",
"dictionary",
"beautifulsoup",
"nonetype"
] |
Memory error when ploting large array | 40,000,192 | <p>I have a problem while ploting big data on python 2.7, with spyder.</p>
<p>X, Y and Z are about 560,000 array length... wich is a lot! </p>
<pre><code># ======
## plot:
fig = plt.figure("Map 3D couleurs")
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_trisurf(Xs, Ys, Zs, cmap=cm.jet, linewidth=0)
fig.... | 0 | 2016-10-12T13:40:42Z | 40,000,530 | <p>try to read file partly and do not set data at once
for example put just one datum in a line
then read a tuple (x,y,z) and draw and repeat that </p>
| -1 | 2016-10-12T13:56:11Z | [
"python",
"python-2.7",
"memory",
"matplotlib"
] |
Memory error when ploting large array | 40,000,192 | <p>I have a problem while ploting big data on python 2.7, with spyder.</p>
<p>X, Y and Z are about 560,000 array length... wich is a lot! </p>
<pre><code># ======
## plot:
fig = plt.figure("Map 3D couleurs")
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_trisurf(Xs, Ys, Zs, cmap=cm.jet, linewidth=0)
fig.... | 0 | 2016-10-12T13:40:42Z | 40,018,621 | <p>Do you need the amount of detail from a length <code>560'000</code> array? If not, you could easily sub-sample the arrays, using for example:</p>
<pre><code>n = 1000 # sample every n-th data point
surf = ax.plot_trisurf(Xs[::n], Ys[::n], Zs[::n], cmap=cm.jet, linewidth=0)
</code></pre>
| 2 | 2016-10-13T10:36:16Z | [
"python",
"python-2.7",
"memory",
"matplotlib"
] |
Import excel file in python and identify cells of which the content is strikethrough | 40,000,239 | <p>I want to read in many Excel documents and I would like to receive at least one important bit of information on the format. However, I am afraid that there is no tool for it, so my hope is on you!</p>
<p>Each excel file that I am reading in contains a few cells that of which the content is strikethrough. For those ... | 0 | 2016-10-12T13:42:52Z | 40,000,906 | <p>You have to open the workbook with <code>formatting_info</code> kwarg as <code>True</code>. Then, get <code>the</code> XF object of the cells and get the <code>Font</code> object. The <code>struck_out</code> attribute is what you're looking for. An example:</p>
<pre><code>workbook = xlrd.open_workbook(filename, for... | 0 | 2016-10-12T14:13:23Z | [
"python",
"excel",
"fonts",
"strikethrough"
] |
How to make post request in Django TastyPie using ApiKeyAuthentication | 40,000,273 | <p>I have resource like this:</p>
<pre><code>class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
resource_name = 'entry'
allowed_methods = ['post']
authentication = ApiKeyAuthentication()
authorization = Authorization()
</code></pre>
<p>And try to... | 0 | 2016-10-12T13:44:35Z | 40,000,554 | <p>from documentation:</p>
<blockquote>
<p>Authorization: ApiKey daniel:204db7bcfafb2deb7506b89eb3b9b715b09905c8</p>
</blockquote>
<p>your request must be like this:</p>
<pre><code>requests.post('http://localhost/api/entry/',
json={"key1": "value1",
"key2": "value2"},
... | 1 | 2016-10-12T13:57:17Z | [
"python",
"django",
"tastypie"
] |
Pip not installing package properly | 40,000,314 | <p>So I am trying to get hmmlearn working in Jupyter, and I have come across an error while installing Hmmlearn using <code>pip</code>. I have tried this <a href="http://stackoverflow.com/questions/38575860/error-compiling-c-code-for-python-hmmlearn-package">solution</a>, but it didn't work. </p>
<p>It seems to me tha... | 0 | 2016-10-12T13:46:50Z | 40,000,766 | <p>Looking at your error message I guess that you have downloaded the hmmlearn package from GIT. Have you tried using a wheel (*.whl) file instead? You can download one from <a href="https://pypi.python.org/pypi/hmmlearn#downloads" rel="nofollow">here</a>. Check out which version fits your python installation.</p>
<p>... | 0 | 2016-10-12T14:06:34Z | [
"python",
"pip",
"jupyter",
"hmmlearn"
] |
Pip not installing package properly | 40,000,314 | <p>So I am trying to get hmmlearn working in Jupyter, and I have come across an error while installing Hmmlearn using <code>pip</code>. I have tried this <a href="http://stackoverflow.com/questions/38575860/error-compiling-c-code-for-python-hmmlearn-package">solution</a>, but it didn't work. </p>
<p>It seems to me tha... | 0 | 2016-10-12T13:46:50Z | 40,016,817 | <p>So i figured out what the problem was. my active python enviroment was python 3.5, as i was manually transferring the installed files to my enviroment, it failed because i had the wrong version. I had to change my active python enviroment: using <code>activate <my_enviroment_name></code> after that i could jus... | 0 | 2016-10-13T09:13:14Z | [
"python",
"pip",
"jupyter",
"hmmlearn"
] |
Mouse Recorder - how to detect mouse click in a while loop? with win32api | 40,000,353 | <p>I want to build a mouse recorder that records the actions and movement the mouse makes.</p>
<p>the problem is i didn't find a way to detect a mouse press in a while loop with win32api.</p>
<p>So i am trying to use two threads to do the job.</p>
<hr>
<p><strong>EDIT- Taken a bit different approach , writing the d... | 0 | 2016-10-12T13:48:19Z | 40,114,070 | <p>Why separate files when it is easier to record one file in the first place? Just put the lines from the different threads into a queue and write the contents of said queue in the main thread into a file:</p>
<pre><code>#!/usr/bin/env python
# coding: utf8
from __future__ import absolute_import, division, print_fun... | 0 | 2016-10-18T17:01:07Z | [
"python",
"multithreading",
"python-2.7",
"python-3.x",
"python-multithreading"
] |
Scrapy not calling parse function with start_requests | 40,000,368 | <p>I am fairly new to Python and Scrapy, but something just seems not right. According to documentation and example, re-implementing <em>start_requests</em> function will cause Scrapy to use return of <em>start_requests</em> instead of <em>start_urls</em> array variable.</p>
<p>Everything works fine with <em>start_url... | 0 | 2016-10-12T13:48:54Z | 40,001,042 | <p>Using <strong>dont_merge_cookies</strong> attribute in the <strong>meta</strong> dictionary would solve this issue.</p>
<pre><code> def start_requests(self):
logging.log(logging.INFO, "Loading requests")
yield Request(url='http://www.hearthpwn.com/decks/646673-s31-legend-2eu-3asia-smorc-hunter',... | 0 | 2016-10-12T14:19:10Z | [
"python",
"request",
"scrapy"
] |
Scrapy not calling parse function with start_requests | 40,000,368 | <p>I am fairly new to Python and Scrapy, but something just seems not right. According to documentation and example, re-implementing <em>start_requests</em> function will cause Scrapy to use return of <em>start_requests</em> instead of <em>start_urls</em> array variable.</p>
<p>Everything works fine with <em>start_url... | 0 | 2016-10-12T13:48:54Z | 40,005,679 | <pre><code>2016-10-12 15:33:41 [scrapy] DEBUG: Redirecting (302) to <GET http://www.hearthpwn.com/decks/646673-s31-legend-2eu-3asia-smorc-hunter?cookieTest=1> from <GET http://www.hearthpwn.com/decks/646673-s31-legend-2eu-3asia-smorc-hunter>
2016-10-12 15:33:41 [scrapy] DEBUG: Redirecting (302) to <GET h... | 0 | 2016-10-12T18:18:09Z | [
"python",
"request",
"scrapy"
] |
How to query RethinkDB based on the current time | 40,000,448 | <p>I'm trying to write a 'controller' program for a RethinkDB database which continuously dumps to JSON and deletes data which is older than 3 days, using RethinkDB's changefeed feature. </p>
<p>The problem is that the query 'hangs' from the current time, which is evaluated using <code>datetime.utcnow()</code> (or, al... | 0 | 2016-10-12T13:52:18Z | 40,038,907 | <p>I finally worked around the problem by doing the dumps in 'batch' mode rather than continuously using <code>changes()</code>. (To wit, I'm using the <a href="https://pypi.python.org/pypi/schedule" rel="nofollow">schedule</a> module).</p>
<p>Here is the script:</p>
<pre><code>import json
import rethinkdb as r
impor... | 0 | 2016-10-14T08:49:46Z | [
"python",
"rethinkdb"
] |
In Python application, can't find where a item comes from | 40,000,451 | <p>I'm trying to understand how web the framework <strong>web2py</strong> works, and there is this item called <code>request.client</code> in <code>access.py</code> that I can't figure out where it comes from. I retrieved the code from <a href="https://github.com/web2py/web2py/blob/0d646fa5e7c731cb5c392adf6a885351e77e4... | 1 | 2016-10-12T13:52:40Z | 40,000,623 | <p>When trying to figure out how an item has been imported into Python, you need to look at the explicit <code>import</code> statements in the file of interest. In well-written code, this will be obvious.</p>
<p>If you import the object of interest into a python shell, then you could use the <code>.__file__</code> att... | 0 | 2016-10-12T14:00:26Z | [
"python",
"web2py"
] |
In Python application, can't find where a item comes from | 40,000,451 | <p>I'm trying to understand how web the framework <strong>web2py</strong> works, and there is this item called <code>request.client</code> in <code>access.py</code> that I can't figure out where it comes from. I retrieved the code from <a href="https://github.com/web2py/web2py/blob/0d646fa5e7c731cb5c392adf6a885351e77e4... | 1 | 2016-10-12T13:52:40Z | 40,001,380 | <p>The file to which you link, <code>access.py</code>, mentions the name <code>request</code> for the first time on line 13:</p>
<pre><code>http_host = request.env.http_host.split(':')[0]
</code></pre>
<p>This symbol, <code>request</code>, is not <code>import</code>ed from anywhere. This is an unorthodox way of writ... | 2 | 2016-10-12T14:35:38Z | [
"python",
"web2py"
] |
In Python application, can't find where a item comes from | 40,000,451 | <p>I'm trying to understand how web the framework <strong>web2py</strong> works, and there is this item called <code>request.client</code> in <code>access.py</code> that I can't figure out where it comes from. I retrieved the code from <a href="https://github.com/web2py/web2py/blob/0d646fa5e7c731cb5c392adf6a885351e77e4... | 1 | 2016-10-12T13:52:40Z | 40,002,707 | <p>As explained <a href="http://web2py.com/books/default/chapter/29/04/the-core#API" rel="nofollow">here</a>, web2py model, controller, and view files are executed by the framework in an environment that has already been populated with the core API objects, include <code>request</code>, <code>response</code>, <code>ses... | 2 | 2016-10-12T15:36:42Z | [
"python",
"web2py"
] |
How to encode bytes in JSON? json.dumps() throwing a TypeError | 40,000,495 | <p>I am trying to encode a dictionary containing a string of bytes with <code>json</code>, and getting a <code>is not JSON serializable error</code>.</p>
<p>Sample code:</p>
<pre><code>import base64
import json
data={}
encoded = base64.encodebytes(b'data to be encoded')
data['bytes']=encoded
print(json.dumps(data))... | 1 | 2016-10-12T13:54:34Z | 40,000,564 | <p>The JSON format only supports <em>unicode strings</em>. Since Base64 encodes bytes to ASCII-only bytes, you can use that codec to decode the data:</p>
<pre><code>encoded = base64.encodestring(b'data to be encoded')
data['bytes'] = encoded.decode('ascii')
</code></pre>
| 5 | 2016-10-12T13:57:39Z | [
"python",
"json",
"python-3.x"
] |
Indexing variables and adding month to variable name in python3.5 | 40,000,595 | <p>I'm trying to set up a list of variables to work with in a linear programming problem. For this I'd like to work with some index values to make the code significantly shorter and easier to read. I'd tried something as:</p>
<pre><code>from datetime import *
months = ["Unknown", "January", "February", "March", "Apri... | 0 | 2016-10-12T13:59:15Z | 40,000,689 | <p>Use: </p>
<pre><code>d["string{0}".format(x)]=("Production in %s" % months[d])
</code></pre>
| 0 | 2016-10-12T14:03:25Z | [
"python",
"python-3.x"
] |
Indexing variables and adding month to variable name in python3.5 | 40,000,595 | <p>I'm trying to set up a list of variables to work with in a linear programming problem. For this I'd like to work with some index values to make the code significantly shorter and easier to read. I'd tried something as:</p>
<pre><code>from datetime import *
months = ["Unknown", "January", "February", "March", "Apri... | 0 | 2016-10-12T13:59:15Z | 40,001,831 | <p>That's simple, and you have already done it once in your code!</p>
<pre><code>for x in range(1,13):
d["string{0}".format(x)]="Production in {}".format(months[x])
for key, value in d.items():
print(key, value)
</code></pre>
<p>Output:</p>
<pre><code>string5 Production in May
string4 Production in April
st... | 1 | 2016-10-12T14:55:19Z | [
"python",
"python-3.x"
] |
How to ping from a tuple? | 40,000,617 | <p>How can I ping a list of hosts from a tuple and store the response into another tuple, list?</p>
<p>I know how to ping a single host:</p>
<pre><code>hostname = "10.0.0.250" #example
response = os.system("ping -c 1 " + hostname)
</code></pre>
| 0 | 2016-10-12T14:00:09Z | 40,000,681 | <p>You can simply use a <em>list comprehension</em> / <em>generator expression</em> (for tuple), given a tuple of hostnames:</p>
<pre><code>hostnames = ("10.0.0.250", "10.0.0.240", ...)
responses = tuple(os.system("ping -c 1 " + h) for h in hostnames)
</code></pre>
| 2 | 2016-10-12T14:03:10Z | [
"python"
] |
How to ping from a tuple? | 40,000,617 | <p>How can I ping a list of hosts from a tuple and store the response into another tuple, list?</p>
<p>I know how to ping a single host:</p>
<pre><code>hostname = "10.0.0.250" #example
response = os.system("ping -c 1 " + hostname)
</code></pre>
| 0 | 2016-10-12T14:00:09Z | 40,000,715 | <pre><code>hostnames = ["10.0.0.1", "10.0.0.2"]
# Can use a tuple instead of list.
responses = [os.system("ping -c 1 " + hostname) for hostname in hostnames]
# You can enwrap the list comprehension in a call to the tuple() function
# to make `responses` a tuple instead of list.
</code></pre>
| 1 | 2016-10-12T14:04:24Z | [
"python"
] |
python pandas-possible to compare 3 dfs of same shape using where(max())? is this a masking issue? | 40,000,718 | <p>I have a dict containing 3 dataframes of identical shape. I would like to create:</p>
<ol>
<li>a 4th dataframe which identifies the largest value from the original 3 at each coordinate - so dic['four'].ix[0,'A'] = MAX( dic['one'].ix[0,'A'], dic['two'].ix[0,'A'], dic['three'].ix[0,'A'] )</li>
<li><p>a 5th with the s... | 2 | 2016-10-12T14:04:31Z | 40,001,247 | <p>The 1st question is easy to answer, you could use the <code>numpy.maximum()</code> function to find the element wise maximum value in each cell, across multiple dataframes</p>
<pre><code>dic ['four'] = pd.DataFrame(np.maximum(dic['one'].values,dic['two'].values,dic['three'].values),columns = list('ABC'))
</code></p... | 0 | 2016-10-12T14:29:31Z | [
"python",
"pandas",
"numpy",
"max",
"where"
] |
python pandas-possible to compare 3 dfs of same shape using where(max())? is this a masking issue? | 40,000,718 | <p>I have a dict containing 3 dataframes of identical shape. I would like to create:</p>
<ol>
<li>a 4th dataframe which identifies the largest value from the original 3 at each coordinate - so dic['four'].ix[0,'A'] = MAX( dic['one'].ix[0,'A'], dic['two'].ix[0,'A'], dic['three'].ix[0,'A'] )</li>
<li><p>a 5th with the s... | 2 | 2016-10-12T14:04:31Z | 40,001,276 | <p>consider the <code>dict</code> <code>dfs</code> which is a dictionary of <code>pd.DataFrame</code>s</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
dfs = dict(
one=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
two=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
three=pd... | 3 | 2016-10-12T14:30:24Z | [
"python",
"pandas",
"numpy",
"max",
"where"
] |
How to fix matplotlib's subplots when the entire layout can not be filled? | 40,000,784 | <p>I would like to plot a DataFrame with say 29 columns, so I use the matplotlib's "subplots" command using 5x6 layout, (5x6 = 30 > 29)</p>
<p>fig, ax = plt.subplots(5,6)</p>
<p>However, when I plot all of the columns, the last subplot (i.e., row=5, col = 6) is empty because there is no data to show there. Is there a... | 0 | 2016-10-12T14:07:30Z | 40,000,893 | <p>Try this</p>
<pre><code>fig.delaxes(axs[5,6])
plt.show()
</code></pre>
| 2 | 2016-10-12T14:12:40Z | [
"python",
"pandas",
"matplotlib"
] |
Python Logging for a module shared by different scripts | 40,000,929 | <p>I like the python logging infrastructure and I want to use it for a number of different overnight jobs that I run. A lot of these jobs use module X let's say. I want the logging for module X to write to a log file not dependent on module X, but based on the job that ultimately led to calling functionality in modul... | 0 | 2016-10-12T14:14:24Z | 40,001,073 | <p>You could probably use as many RotatingFileHandler(s) as different modules you have and setup their filenames accordingly </p>
<p><a href="https://docs.python.org/2/library/logging.handlers.html" rel="nofollow">https://docs.python.org/2/library/logging.handlers.html</a></p>
<p>-Edit- </p>
<p>Based on the comment ... | 0 | 2016-10-12T14:21:01Z | [
"python",
"logging"
] |
Python Logging for a module shared by different scripts | 40,000,929 | <p>I like the python logging infrastructure and I want to use it for a number of different overnight jobs that I run. A lot of these jobs use module X let's say. I want the logging for module X to write to a log file not dependent on module X, but based on the job that ultimately led to calling functionality in modul... | 0 | 2016-10-12T14:14:24Z | 40,002,919 | <p>I believe you should just follow the standard set up for library code:</p>
<p>Say you have a package <code>mypkg</code> and you want this package to log information while letting the user of the package decide which level of logging to use and where the output should go.</p>
<p>The <code>mypkg</code> should <stron... | 2 | 2016-10-12T15:48:04Z | [
"python",
"logging"
] |
Python in SPSS - KEEP variables | 40,001,022 | <p>I have selected the variables I need based on a string within the variable name. I'm not sure how to keep only these variables from my SPSS file. </p>
<pre><code>begin program.
import spss,spssaux
spssaux.OpenDataFile(r'XXXX.sav')
target_string = 'qb2'
variables = [var for var in spssaux.GetVariableNamesList() if t... | 0 | 2016-10-12T14:18:05Z | 40,003,749 | <p>Have you tried reversing the order of the SAVE OUTFILE and ADD FILES commands? I haven't run this in SPSS via Python, but in standard SPSS, your syntax will write the file to disk, and then select the variables for the active version in memory--so if you later access the saved file, it will be the version before you... | 2 | 2016-10-12T16:29:17Z | [
"python",
"spss"
] |
Python in SPSS - KEEP variables | 40,001,022 | <p>I have selected the variables I need based on a string within the variable name. I'm not sure how to keep only these variables from my SPSS file. </p>
<pre><code>begin program.
import spss,spssaux
spssaux.OpenDataFile(r'XXXX.sav')
target_string = 'qb2'
variables = [var for var in spssaux.GetVariableNamesList() if t... | 0 | 2016-10-12T14:18:05Z | 40,005,505 | <ol>
<li>You'll want to use the <code>ADD FILES FILE</code> command before the <code>SAVE</code> for your saved file to be the "reduced" file</li>
<li>I think your very last line in the python program should be trying to join the elements in the list <code>vars</code>. For example: <code>%( " ".join(vars) )</code> </li... | 1 | 2016-10-12T18:08:23Z | [
"python",
"spss"
] |
Python in SPSS - KEEP variables | 40,001,022 | <p>I have selected the variables I need based on a string within the variable name. I'm not sure how to keep only these variables from my SPSS file. </p>
<pre><code>begin program.
import spss,spssaux
spssaux.OpenDataFile(r'XXXX.sav')
target_string = 'qb2'
variables = [var for var in spssaux.GetVariableNamesList() if t... | 0 | 2016-10-12T14:18:05Z | 40,022,078 | <p>It appears that the problem has been solved, but I would like to point out another solution that can be done without writing any Python code. The extension command SPSSINC SELECT VARIABLES defines a macro based on properties of the variables. This can be used in the ADD FILES command. </p>
<p>SPSSINC SELECT VARI... | 1 | 2016-10-13T13:15:47Z | [
"python",
"spss"
] |
Why is there no output showing in this python code? | 40,001,080 | <pre><code>man=[]
other=[]
try:
data=open('sketch.txt')
for each_line in data:
try:
(role,line_spoken) = each_line.split(':',1)
line_spoken= line_spoken.strip()
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
... | -1 | 2016-10-12T14:21:24Z | 40,001,654 | <p>The indentation in your screenshot is different from your question. In your question you claimed your code was this (with some bits trimmed out):</p>
<pre><code>try:
# Do something
except IOError:
# Handle error
try:
# Write to man_data.txt and other_data.txt
except IOError:
# Handle error
</code></... | 2 | 2016-10-12T14:47:01Z | [
"python",
"python-3.x"
] |
numpy.float64 is not iterable | 40,001,301 | <p>I'm trying to print a function which uses several parameters from numpy array's and lists, but I keep getting the error "numpy.float 64 object is not iterable". I've looked at several questions on the forum about this topic and tried different answers but none seem to work (or I might be doing something wrong I'm st... | -1 | 2016-10-12T14:31:31Z | 40,001,458 | <p>I suspect the problem is here:</p>
<pre><code>sum((.5*h[k]*(p[i]-d[i])* (p[i]/d[i])*(t[k])**2))
</code></pre>
<p>The end result of that expression is a float, isn't it? What is the sum() for?</p>
| 2 | 2016-10-12T14:39:00Z | [
"python",
"function",
"numpy",
"iterable"
] |
NameError when importing function from another script? | 40,001,314 | <p>I am having difficulty importing a function from another script. Both of the scripts below are in the same directory. Why can't the function from another script handle an object with the same name (<code>arr</code>)?</p>
<p><strong>evens.py</strong></p>
<pre><code>def find_evens():
return [x for x in arr if x ... | -1 | 2016-10-12T14:32:37Z | 40,001,775 | <p>Modules in python have separate namespaces. The qualified names <code>evens.arr</code> and <code>import_evens.arr</code> are separate entities. In each module, using just the name <code>arr</code> refers to the one local to it, so <code>arr</code> in <code>import_evens</code> is actually <code>import_evens.arr</code... | 3 | 2016-10-12T14:52:34Z | [
"python",
"python-import"
] |
Remove Quotation mark from in between of the String but from 0th index and -1th index | 40,001,326 | <p>I want to remove quotation mark from this string:</p>
<pre><code>'"Hello World - October 1 Not Trending Twitter """"""""""""""""Spark 2, sparkCSV parser"""""""""""""""" - DDSAD"""""""""""'
</code></pre>
<p>Output should be</p>
<pre><code>'"Hello World - October 1 Not Trending Twitter Spark 2, sparkCSV parser - DD... | 0 | 2016-10-12T14:33:14Z | 40,001,513 | <p>Take the string and replace the <code>'"'</code> with <code>''</code>; then place them back in <code>'""'</code> with <code>'"{}"'.format</code>:</p>
<pre><code>s = '"Hello World - October 1 Not Trending Twitter """"""""""""""""Spark 2, sparkCSV parser"""""""""""""""" - DDSAD"""""""""""'
r = '"{}"'.format(s.replace... | 3 | 2016-10-12T14:41:05Z | [
"python",
"string",
"python-3.x"
] |
Find all the occurences of a string in an imperfect text | 40,001,336 | <p>I am trying to find a string within a long text extracted from a PDF file, and get the string's position in the text, and then return 100 words before the string and 100 after.
The problem is that the extraction is not perfect, so I am having a problem like this:</p>
<p>The query string is "test text"</p>
<p>The t... | 1 | 2016-10-12T14:33:35Z | 40,001,524 | <p>If you're looking for the position of the text within the string, you can use <a href="https://docs.python.org/2/library/string.html" rel="nofollow"><code>string.find()</code></a>.</p>
<pre><code>>>> query_string = 'test text'
>>> text = 'This is atest textwith a problem'
>>> if query_str... | 2 | 2016-10-12T14:41:27Z | [
"python"
] |
Find all the occurences of a string in an imperfect text | 40,001,336 | <p>I am trying to find a string within a long text extracted from a PDF file, and get the string's position in the text, and then return 100 words before the string and 100 after.
The problem is that the extraction is not perfect, so I am having a problem like this:</p>
<p>The query string is "test text"</p>
<p>The t... | 1 | 2016-10-12T14:33:35Z | 40,001,602 | <p>You did not specify all your requirements but this works for your current problem. The program prints out <code>9 and 42</code>, which are the beginning of two occurrences of the <code>test text</code>.</p>
<pre><code>import re
filt = re.compile("test text")
for match in filt.finditer('This is atest textwith a pro... | 3 | 2016-10-12T14:44:28Z | [
"python"
] |
Find all the occurences of a string in an imperfect text | 40,001,336 | <p>I am trying to find a string within a long text extracted from a PDF file, and get the string's position in the text, and then return 100 words before the string and 100 after.
The problem is that the extraction is not perfect, so I am having a problem like this:</p>
<p>The query string is "test text"</p>
<p>The t... | 1 | 2016-10-12T14:33:35Z | 40,001,852 | <p>You might have a look at the <a href="https://pypi.python.org/pypi/regex" rel="nofollow">regex</a> module which allows for 'fuzzy' matching:</p>
<pre><code>>>> import regex
>>> s='This is atest textwith a problem'
>>> regex.search(r'(?:text with){e<2}', s)
<regex.Match object; span=... | 1 | 2016-10-12T14:57:00Z | [
"python"
] |
Find all the occurences of a string in an imperfect text | 40,001,336 | <p>I am trying to find a string within a long text extracted from a PDF file, and get the string's position in the text, and then return 100 words before the string and 100 after.
The problem is that the extraction is not perfect, so I am having a problem like this:</p>
<p>The query string is "test text"</p>
<p>The t... | 1 | 2016-10-12T14:33:35Z | 40,002,884 | <p>You could take the following kind of approach. This first attempts to split the whole text into words, and keeps note of the index of each word. </p>
<p>Next it iterates through the text looking for <code>test text</code> with possible 0 or more spaces between. For each match it notes the start and then creates a l... | 3 | 2016-10-12T15:45:56Z | [
"python"
] |
Python loop to iterate through elements in an XML and get sub-elements values | 40,001,345 | <p>I am working with an XML being read from aN API that has several hotel locations. Each individual hotel has a "hotel code" element that is a value unique to each hotel in the XML output and I would like to GET the "latitude" and "longitude" attributes for each hotel. My code right now can parse through the XML and ... | 1 | 2016-10-12T14:34:12Z | 40,003,333 | <p>You could place the result of your XML file in to an iterable structure like a dictionary.
I've taken your sample xml data and placed it into a file called hotels.xml. </p>
<pre><code>from xml.dom import minidom
hotels_position = {}
dom = minidom.parse('hotels.xml')
hotels = dom.getElementsByTagName("hotel")
for... | 0 | 2016-10-12T16:09:06Z | [
"python",
"xml",
"api",
"urllib2",
"minidom"
] |
Find and print only the first ORF in fasta | 40,001,347 | <p>How to find only the first start_codon for each frame. In the code below it is giving me all start_codon position.</p>
<pre><code>from Bio.SeqRecord import SeqRecord
from Bio import SeqIO
def test(seq, start, stop):
start = ["ATG"]
start_codon_index = 0
for frame in range(0,3):
for i in range(fr... | 0 | 2016-10-12T14:34:14Z | 40,001,548 | <p>If you have a DNA string and you want to find the first occurrence of an "ATG" sequence, the easiest is to just do: </p>
<pre><code>DNA = "ACCACACACCATATAATGATATATAGGAAATG"
print(DNA.find("ATG"))
</code></pre>
<p>Prints out <code>15</code>, note that the indexing in python starts from 0</p>
<p>In case you consid... | 0 | 2016-10-12T14:42:23Z | [
"python"
] |
Integration with Scipy giving incorrect results with negative lower bound | 40,001,402 | <p>I am attempting to calculate integrals between two limits using python/scipy.</p>
<p>I am using online calculators to double check my results (<a href="http://www.wolframalpha.com/widgets/view.jsp?id=8c7e046ce6f4d030f0b386ea5c17b16a" rel="nofollow">http://www.wolframalpha.com/widgets/view.jsp?id=8c7e046ce6f4d030f0b... | 0 | 2016-10-12T14:36:25Z | 40,002,922 | <p>I am guessing this has to do with the infinite bounds. scipy.integrate.quad is a wrapper around quadpack routines.</p>
<p><a href="https://people.sc.fsu.edu/~jburkardt/f_src/quadpack/quadpack.html" rel="nofollow">https://people.sc.fsu.edu/~jburkardt/f_src/quadpack/quadpack.html</a></p>
<p>In the end, these routine... | 1 | 2016-10-12T15:48:11Z | [
"python",
"numpy",
"scipy",
"integration"
] |
Filtering plain models on their relation to a subclass of a django polymorphic model? | 40,001,574 | <p>I have a plain Django model that has a ForeignKey relation to a django-polymorphic model. </p>
<p>Let's call the first <code>PlainModel</code> that has a <code>content</code> ForeignKey field to a polymorphic <code>Content</code> model with subtypes <code>Video</code> and <code>Audio</code> (simplified example).</p... | 1 | 2016-10-12T14:43:27Z | 40,002,929 | <p>You can do this by first getting all the <code>PlainModel</code> instances that have a <code>Video</code> subtype, and then querying for the foreign key relationships that are in that queryset:</p>
<pre><code>content_videos = Content.objects.instance_of(Video)
plain_model_videos = PlainModel.objects.filter(content_... | 0 | 2016-10-12T15:48:36Z | [
"python",
"django",
"django-polymorphic"
] |
Python error in sorting a list | 40,001,632 | <p>I simply want to sort a list... and I have a 2 parameter lamda
Here is my simple code:</p>
<pre><code>I.sort(key = lambda x, y: x.finish - y.finish)
</code></pre>
<p>And the compiler return this error</p>
<pre><code>builtins.TypeError: <lambda>() missing 1 required positional argument: 'y'
</code></pre>
| -1 | 2016-10-12T14:46:03Z | 40,001,673 | <p>You are trying to use <code>key</code> function as a <code>cmp</code> function (removed in Python 3.x), but don't you mean to simply sort by the "finish" attribute:</p>
<pre><code>I.sort(key=lambda x: x.finish)
</code></pre>
<p>Or, with the <a href="https://docs.python.org/3/library/operator.html#operator.attrgett... | 2 | 2016-10-12T14:47:43Z | [
"python",
"sorting"
] |
Spark Connector MongoDB - Python API | 40,001,640 | <p>I'd like pull data from Mongo by Spark, especially by PySpark..
I have found official guide from Mongo <a href="https://docs.mongodb.com/spark-connector/python-api/" rel="nofollow">https://docs.mongodb.com/spark-connector/python-api/</a></p>
<p>I have all prerequisites:</p>
<ul>
<li>Scala 2.11.8</li>
<li>Spark 1.6... | 0 | 2016-10-12T14:46:38Z | 40,002,940 | <p>It looks like an error I'd expect to see if I were using code compiled in a different version of Scala. Have you tried running it with <code>--packages org.mongodb.spark:mongo-spark-connector_2.10:1.1.0</code>?</p>
<p>By default in Spark 1.6.x is compiled against Scala 2.10 and you have to manually build it for Sc... | 1 | 2016-10-12T15:49:03Z | [
"python",
"mongodb",
"scala",
"apache-spark",
"pyspark"
] |
Get a random sample of a dict | 40,001,646 | <p>I'm working with a big dictionary and for some reason I also need to work on small random samples from that dictionary. How can I get this small sample (for example of length 2)? </p>
<p>Here is a toy-model:</p>
<pre><code>dy={'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
</code></pre>
<p>I need to perform some task on dy w... | 0 | 2016-10-12T14:46:49Z | 40,002,638 | <p>Given your example of:</p>
<pre><code>dy = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
</code></pre>
<p>Then the sum of all the values is more simply put as:</p>
<pre><code>s = sum(dy.values())
</code></pre>
<p>Then if it's not memory prohibitive, you can sample using:</p>
<pre><code>import random
values = list(dy.val... | 2 | 2016-10-12T15:33:11Z | [
"python",
"dictionary",
"random",
"python-3.4"
] |
Mac OS X Cannot install packages with pip anymore | 40,001,729 | <p>I have completely screwed up my Python environment. My first big mistake was always installing packages using sudo and not using virtual environments. I'm not exactly sure what happened, but at some point I was not able to install certain packages anymore, possibly because of some dependency problems.</p>
<p>I deci... | 0 | 2016-10-12T14:50:54Z | 40,037,767 | <p>The system Python is in <code>/usr/bin/</code>, not <code>/usr/local/bin/</code>, as you noted when you ran <code>which python</code>. Type <code>python --version</code> and it should tell you which version you're running.</p>
<p>In regards to your Python environment, I would recommend you ditch using the system en... | 2 | 2016-10-14T07:49:28Z | [
"python",
"osx",
"python-2.7",
"pip"
] |
Python/Numpy: problems with type conversion in vectorize and item | 40,001,868 | <p>I am writing a function to extract values from datetimes over arrays. I want the function to operate on a Pandas DataFrame or a numpy ndarray. </p>
<p>The values should be returned in the same way as the Python datetime properties, e.g. </p>
<pre><code>from datetime import datetime
dt = datetime(2016, 10, 12, 13... | 0 | 2016-10-12T14:57:32Z | 40,004,667 | <p>In Py3 the error is <code>OverflowError: Python int too large to convert to C long</code>.</p>
<pre><code>In [215]: f=np.vectorize(nd_func,otypes=[int])
In [216]: f(dts)
...
OverflowError: Python int too large to convert to C long
</code></pre>
<p>but if I change the datetime units, it runs ok</p>
<pre><code>In ... | 2 | 2016-10-12T17:20:56Z | [
"python",
"datetime",
"numpy"
] |
Python 2.7 function with keyword arguments in superclass: how to access from subclass? | 40,001,876 | <p>Are keyword arguments handled somehow specially in inherited methods? </p>
<p>When I call an instance method with keyword arguments from the class it's defined in, all goes well. When I call it from a subclass, Python complains about too many parameters passed. </p>
<p>Here's the example. The "simple" methods don'... | 2 | 2016-10-12T14:57:48Z | 40,001,925 | <p>You need to use **kwargs when you call the method, it takes no positional args, just <em>keyword arguments</em>:</p>
<pre><code> self.aKWMethod(**kwargs)
</code></pre>
<p>Once you do, it works fine:</p>
<pre><code>In [2]: aClass().aSimpleMethod('this')
...: aSubClass().anotherSimpleMethod('that')
...: aClas... | 1 | 2016-10-12T15:00:10Z | [
"python",
"python-2.7",
"inheritance",
"variadic"
] |
Python 2.7 function with keyword arguments in superclass: how to access from subclass? | 40,001,876 | <p>Are keyword arguments handled somehow specially in inherited methods? </p>
<p>When I call an instance method with keyword arguments from the class it's defined in, all goes well. When I call it from a subclass, Python complains about too many parameters passed. </p>
<p>Here's the example. The "simple" methods don'... | 2 | 2016-10-12T14:57:48Z | 40,001,931 | <p>When you do <code>self.aKWMethod(kwargs)</code>, you're passing the whole dict of keyword arguments as a single positional argument to the (superclass's) <code>aKWMethod</code> method.</p>
<p>Change that to <code>self.aKWMethod(**kwargs)</code> and it should work as expected.</p>
| 1 | 2016-10-12T15:00:18Z | [
"python",
"python-2.7",
"inheritance",
"variadic"
] |
Python 2.7 function with keyword arguments in superclass: how to access from subclass? | 40,001,876 | <p>Are keyword arguments handled somehow specially in inherited methods? </p>
<p>When I call an instance method with keyword arguments from the class it's defined in, all goes well. When I call it from a subclass, Python complains about too many parameters passed. </p>
<p>Here's the example. The "simple" methods don'... | 2 | 2016-10-12T14:57:48Z | 40,002,053 | <p>Just to demonstrate in the simplest terms possible what is going wrong, note that this error has nothing to do with inheritance. Consider the following case:</p>
<pre><code>>>> def f(**kwargs):
... pass
...
>>> f(a='test') # works fine!
>>> f('test')
Traceback (most recent call last):... | 1 | 2016-10-12T15:06:07Z | [
"python",
"python-2.7",
"inheritance",
"variadic"
] |
Cannot get psycopg2 to work, but installed correctly. Mac OS | 40,001,881 | <p>I'm trying to work with psycopg2 natively on Mac. It installs fine, with no errors at least, but when i import it get an error message.</p>
<p>I've seen dozens of threads with similar issues and solutions that vary massively and just seem excessive for such a common module. </p>
<p>can anyone help? </p>
<pre><cod... | 0 | 2016-10-12T14:58:07Z | 40,032,074 | <p>Thanks guys. </p>
<p>@maxymoo I went with your suggestion. I have installed anaconda2. The install updated my path to include /anaconda/bin. </p>
<p>Then using the navigator I installed pyscopg2. Now I am able to use this in the shebang and my scripts execute fine and i'm able to import this module. </p>
<pre><co... | 0 | 2016-10-13T22:29:09Z | [
"python",
"osx",
"psycopg2"
] |
Python - Access column based on another column value | 40,001,888 | <p>I have the following dataframe in python</p>
<pre><code>+-------+--------+
| Value | Number |
+-------+--------+
| true | 123 |
| false | 234 |
| true | 345 |
| true | 456 |
| false | 567 |
| false | 678 |
| false | 789 |
+-------+--------+
</code></pre>
<p>How do I conduct an operation whi... | 0 | 2016-10-12T14:58:24Z | 40,001,910 | <p><code>df.loc[df['Value'],'Number']</code> should work assuming the dtype for 'Value' are real booleans:</p>
<pre><code>In [68]:
df.loc[df['Value'],'Number']
Out[68]:
0 123
2 345
3 456
Name: Number, dtype: int64
</code></pre>
<p>The above uses boolean indexing, here the boolean values are a mask against t... | 1 | 2016-10-12T14:59:37Z | [
"python",
"pandas"
] |
Reading named command arguments | 40,001,892 | <p>Can I use <code>argparse</code> to read named command line arguments that do not need to be in a specific order? I browsed through the <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">documentation</a> but most of it focused on displaying content based on the arguments provided (such as <code... | 0 | 2016-10-12T14:58:44Z | 40,002,281 | <p>The answer is <strong>yes</strong>. A quick look at <a href="https://docs.python.org/3.6/library/argparse.html?highlight=argparse#module-argparse" rel="nofollow">the argparse documentation</a> would have answered as well.</p>
<p>Here is a very simple example, argparse is able to handle far more specific needs.</p>
... | 0 | 2016-10-12T15:16:54Z | [
"python",
"python-3.x",
"arguments"
] |
Reading named command arguments | 40,001,892 | <p>Can I use <code>argparse</code> to read named command line arguments that do not need to be in a specific order? I browsed through the <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">documentation</a> but most of it focused on displaying content based on the arguments provided (such as <code... | 0 | 2016-10-12T14:58:44Z | 40,002,420 | <p>You can use the <a href="https://docs.python.org/2/howto/argparse.html#introducing-optional-arguments" rel="nofollow">Optional Arguments</a> like so:</p>
<pre><code>import argparse, sys
parser=argparse.ArgumentParser()
parser.add_argument('--bar', help='Do the bar option')
parser.add_argument('--foo', help='Foo t... | 1 | 2016-10-12T15:22:46Z | [
"python",
"python-3.x",
"arguments"
] |
How to check whether the sum exists for a given path in a tree | 40,002,118 | <p>I want to check if the sum of values in any path from the start node to the </p>
<p>leaf node exists.</p>
<p>For example suppose I have startNode is say a 7 and the sumTarget is 15 if the tree is: </p>
<pre><code> a-7
b - 1 e- 8
c - 2
d -9
</code></pre>
<p>Then since 7 +8 equals 15 it would ... | 0 | 2016-10-12T15:09:32Z | 40,003,444 | <p>assuming that your node class looks something like this:</p>
<pre><code>class Node:
def __init__(self, value = 0, children = None):
self.value = value
self.children = [] if children is None else children
</code></pre>
<p>then this method should do the trick:</p>
<pre><code>def doesSumExist(sta... | 1 | 2016-10-12T16:14:49Z | [
"python",
"data-structures",
"binary-tree"
] |
How to check whether the sum exists for a given path in a tree | 40,002,118 | <p>I want to check if the sum of values in any path from the start node to the </p>
<p>leaf node exists.</p>
<p>For example suppose I have startNode is say a 7 and the sumTarget is 15 if the tree is: </p>
<pre><code> a-7
b - 1 e- 8
c - 2
d -9
</code></pre>
<p>Then since 7 +8 equals 15 it would ... | 0 | 2016-10-12T15:09:32Z | 40,003,524 | <p>In that case I think what you're searching for is something like the following:</p>
<pre><code>def doesSumExist(startNode, sumTarget, currentSum):
totalSum = currentSum
if startNode is not Null:
if totalSum + startNode.value == sumTarget: #If this node completes the sum
return True
... | 1 | 2016-10-12T16:18:01Z | [
"python",
"data-structures",
"binary-tree"
] |
First selenium program not working | 40,002,159 | <p>I've just loaded <code>Python</code> <code>Selenium</code> into my <code>Ubuntu</code> system and I'm following the Getting Started tutorial on <a href="http://selenium-python.readthedocs.io/getting-started.html#simple-usage" rel="nofollow">ReadTheDocs</a>. When I run this program:</p>
<pre><code>from selenium imp... | 0 | 2016-10-12T15:11:10Z | 40,002,396 | <p>Looks like there's a problem with the webdriver - do you have Firefox installed on your RasPi?</p>
<p>(If not, this might help: <a href="https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=150438" rel="nofollow">https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=150438</a>)</p>
| 0 | 2016-10-12T15:21:36Z | [
"python",
"python-2.7",
"selenium"
] |
First selenium program not working | 40,002,159 | <p>I've just loaded <code>Python</code> <code>Selenium</code> into my <code>Ubuntu</code> system and I'm following the Getting Started tutorial on <a href="http://selenium-python.readthedocs.io/getting-started.html#simple-usage" rel="nofollow">ReadTheDocs</a>. When I run this program:</p>
<pre><code>from selenium imp... | 0 | 2016-10-12T15:11:10Z | 40,002,559 | <p>I think you are using selenium 2.53.6</p>
<p>The issue is compatibility of firefox with selenium, since firefox>= 48 need Gecko Driver(<a href="https://github.com/mozilla/geckodriver" rel="nofollow">https://github.com/mozilla/geckodriver</a>) to run testcases on firefox. or you can downgrade the firefox to 46..from... | 0 | 2016-10-12T15:29:51Z | [
"python",
"python-2.7",
"selenium"
] |
Python nested dictionary with SQL insert | 40,002,162 | <p>I have generated a very large dictionary after processing an XML file, and I am looking extract from this dictionary and to insert columns and values into my mySQL database table.</p>
<p>I am using Python 3.</p>
<p>The dictionary is nested; here's a simplistic example of what I have:</p>
<pre><code>d ={'Test1'{'T... | 0 | 2016-10-12T15:11:18Z | 40,002,349 | <p>You can iterate over <code>d.values()</code> and use the <code>.keys()</code> and <code>.values()</code> methods on the nested dictionaries to get the columns and values:</p>
<pre><code>for v in d.values():
cols = v.keys()
vals = v.values()
sql = "INSERT INTO Parameters ({}) VALUES ({})".format(
... | 2 | 2016-10-12T15:19:47Z | [
"python",
"python-3.x",
"dictionary"
] |
Python nested dictionary with SQL insert | 40,002,162 | <p>I have generated a very large dictionary after processing an XML file, and I am looking extract from this dictionary and to insert columns and values into my mySQL database table.</p>
<p>I am using Python 3.</p>
<p>The dictionary is nested; here's a simplistic example of what I have:</p>
<pre><code>d ={'Test1'{'T... | 0 | 2016-10-12T15:11:18Z | 40,002,680 | <p>Iterating over a dictionary actually iterates over the keys. <code>for k in d:</code> is equivalent to <code>for k in d.keys():</code>. You are looking for the <code>values</code> or <code>items</code> methods, which will actually return the key and the value as a tuple:</p>
<pre><code>for k, v in d.items():
# ... | 0 | 2016-10-12T15:35:19Z | [
"python",
"python-3.x",
"dictionary"
] |
Resuming an optimization in scipy.optimize? | 40,002,172 | <p>scipy.optimize presents many different methods for local and global optimization of multivariate systems. However, I have a very long optimization run needed that may be interrupted (and in some cases I may want to interrupt it deliberately). Is there any way to restart... well, any of them? I mean, clearly one c... | 0 | 2016-10-12T15:11:38Z | 40,006,867 | <p>The general answer is no, there's no general solution apart from, just as you say, starting from the last estimate from the previous run.</p>
<p>For differential evolution specifically though, you can can instantiate the <code>DifferentialEvolutionSolver</code>, which you can pickle at checkpoint and unpickle to re... | 0 | 2016-10-12T19:31:13Z | [
"python",
"scipy",
"mathematical-optimization"
] |
Resuming an optimization in scipy.optimize? | 40,002,172 | <p>scipy.optimize presents many different methods for local and global optimization of multivariate systems. However, I have a very long optimization run needed that may be interrupted (and in some cases I may want to interrupt it deliberately). Is there any way to restart... well, any of them? I mean, clearly one c... | 0 | 2016-10-12T15:11:38Z | 40,059,852 | <p>The following can save and restart from a previous <code>x</code>,
but I gather you want to save and restart more state, e.g. gradients, too; can you clarify that ?</p>
<p>See also <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.basinhopping.html" rel="nofollow">basinhopping</a>,
which h... | 0 | 2016-10-15T13:52:04Z | [
"python",
"scipy",
"mathematical-optimization"
] |
error to pass value in query Django | 40,002,187 | <p>Hi everyone I have problem with this query in Django</p>
<pre><code> projects_name = str(kwargs['project_name']).split(',')
status = str(kwargs['status'])
list_project = tuple(projects_name)
opc_status = {'jobs_running':'running', 'jobs_pending':'pending', 'cpus_used':'cpu'}
if status in opc_status.... | 0 | 2016-10-12T15:12:52Z | 40,002,682 | <p>You could try this:</p>
<pre><code># Build a comma-separated string of all items in list_project
data_list = ', '.join([item for item in list_project])
query = 'SELECT %s FROM proj_cpus WHERE project in (%s)'
# Supply the parameters in the form of a tuple
cursor.execute(query, (key, data_list))
</code></pre>
<p>... | 0 | 2016-10-12T15:35:22Z | [
"python",
"django"
] |
fit_transform with the training data and transform with the testing | 40,002,232 | <p>As the title says, I am using <code>fit_transform</code> with the <code>CountVectorizer</code> on the training data .. and then I am using <code>tranform</code> only with the testing data ... will this gives me the same as using <code>fit</code> only on the training and <code>tranform</code> only on the testing data... | 0 | 2016-10-12T15:14:50Z | 40,002,626 | <p>The answer is <strong>YES</strong> :</p>
<p><code>fit_transform</code> is equivalent to <code>fit</code> followed by <code>transform</code>, but more efficiently implemented. <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.tex... | 1 | 2016-10-12T15:32:31Z | [
"python",
"scikit-learn"
] |
Django: KeyError triggered in forms.py | 40,002,239 | <p>Making a card app. User can make a deck and put cards in that deck. Decks and cards have an 'owner' field in their models to state who the user is.</p>
<p>forms.py</p>
<pre><code>class CardForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
# Pop() removes 'user' from the kwargs dictionary and popula... | 1 | 2016-10-12T15:14:58Z | 40,002,599 | <p>You should pass <code>owner</code> for POST requests, as you already do for GET requests.</p>
<pre><code>if request.method == "POST":
form = CardForm(request.POST, owner=request.user)
</code></pre>
| 0 | 2016-10-12T15:31:34Z | [
"python",
"django"
] |
Can subclasses in Python inherit parent class decorator | 40,002,241 | <p>If I apply a decorator to a class:</p>
<pre><code>from flask.ext.restful import Resource
@my_decorator()
class Foo(Resource): ...
</code></pre>
<p>Will it be automatically applied to any subclass methods as well? For example, will it be <em>magically</em> applied to <code>a_foobar_method</code>?</p>
<pre><code>c... | 0 | 2016-10-12T15:15:05Z | 40,002,375 | <p>Decorators do not "mark" the decorated class in any way. There is no way to tell if you wrote</p>
<pre><code>@decorator
class Foo:
pass
</code></pre>
<p>or</p>
<pre><code>class Foo:
pass
Foo = decorator(Foo)
</code></pre>
<p>simply by looking at <code>Foo</code> itself. Decorators are just applied at th... | -1 | 2016-10-12T15:20:50Z | [
"python",
"python-decorators"
] |
Can subclasses in Python inherit parent class decorator | 40,002,241 | <p>If I apply a decorator to a class:</p>
<pre><code>from flask.ext.restful import Resource
@my_decorator()
class Foo(Resource): ...
</code></pre>
<p>Will it be automatically applied to any subclass methods as well? For example, will it be <em>magically</em> applied to <code>a_foobar_method</code>?</p>
<pre><code>c... | 0 | 2016-10-12T15:15:05Z | 40,002,452 | <p>In short, no.</p>
<pre><code>@my_decorator
class Foo(Resource): ...
</code></pre>
<p>is simply shorthand for</p>
<pre><code>class Foo(Resource): ...
Foo = my_decorator(Foo)
</code></pre>
<p>If the only time you ever use <code>Foo</code> is to define <code>FooBar</code>, then together your two pieces of code are ... | 2 | 2016-10-12T15:24:08Z | [
"python",
"python-decorators"
] |
pandas left join - why more results? | 40,002,355 | <p>How is it possible that a pandas left join like</p>
<pre><code>df.merge(df2, left_on='first', right_on='second', how='left')
</code></pre>
<p>increases the data frame from 221309 to 1388680 rows?</p>
<h1>edit</h1>
<p>shape of df 1 (221309, 83)</p>
<p>shape of df2 (7602, 6)</p>
| 1 | 2016-10-12T15:20:04Z | 40,002,535 | <p>As <a href="http://stackoverflow.com/questions/40002355/pandas-left-join-why-more-results/40002535#comment67282514_40002355">@JonClements has already said in the comment</a> it's a result of duplicated entries in the columns used for merging/joining. Here is a small demo:</p>
<pre><code>In [5]: df
Out[5]:
a b
... | 4 | 2016-10-12T15:28:35Z | [
"python",
"pandas",
"join",
"dataframe",
"left-join"
] |
How to manipulate a huge CSV file in python | 40,002,369 | <p>I have a CSV file more than 16G, each row is the text data. When I was encoding (e.g. one-hot-encode) the whole CSV file data, my process was killed due to the memory limitation. Is there a way to process this kind of "big data"? </p>
<p>I am thinking that split the whole CSV file into multiple "smaller" files, the... | -1 | 2016-10-12T15:20:36Z | 40,002,530 | <p>Your question does not state what language you are using to handle this CSV file. I will reply using C#, but I imagine that the strategy will work equally well for Java too.</p>
<p>You can try using the <code>StreamReader</code> class to read the file line-by-line. That should take care of the read side of things.<... | 0 | 2016-10-12T15:28:19Z | [
"python",
"csv",
"encoding",
"bigdata"
] |
How to manipulate a huge CSV file in python | 40,002,369 | <p>I have a CSV file more than 16G, each row is the text data. When I was encoding (e.g. one-hot-encode) the whole CSV file data, my process was killed due to the memory limitation. Is there a way to process this kind of "big data"? </p>
<p>I am thinking that split the whole CSV file into multiple "smaller" files, the... | -1 | 2016-10-12T15:20:36Z | 40,003,734 | <p>This has been discussed in <a href="http://stackoverflow.com/questions/33689456/reading-huge-csv-files-efficiently?rq=1">Reading huge csv files efficiently?</a></p>
<p>Probably the most reasonable thing to do with a 16GB csv file would not to load it all into memory, but read and process it line by line:</p>
<pre... | 0 | 2016-10-12T16:28:31Z | [
"python",
"csv",
"encoding",
"bigdata"
] |
QScintilla based text editor in PyQt5 with clickable functions and variables | 40,002,373 | <p>I am trying to make a simple texteditor with basic syntax highlighting, code completion and clickable functions & variables in PyQt5. My best hope to achieve this is using the QScintilla port <br>
for PyQt5.<br>
I have found the following QScintilla-based texteditor example on the Eli Bendersky website (<a href=... | 0 | 2016-10-12T15:20:48Z | 40,002,879 | <p>Syntax highlighting is just a matter of running a lexer on the source file to find tokens, then attribute styles to it. A lexer has a very basic understanding of a programming language, it only understands what is a number literal, a keyword, an operator, a comment, a few others and that's all. This is a somewhat si... | 2 | 2016-10-12T15:45:38Z | [
"python",
"python-3.x",
"pyqt",
"pyqt5",
"qscintilla"
] |
QScintilla based text editor in PyQt5 with clickable functions and variables | 40,002,373 | <p>I am trying to make a simple texteditor with basic syntax highlighting, code completion and clickable functions & variables in PyQt5. My best hope to achieve this is using the QScintilla port <br>
for PyQt5.<br>
I have found the following QScintilla-based texteditor example on the Eli Bendersky website (<a href=... | 0 | 2016-10-12T15:20:48Z | 40,006,957 | <p>I got a helpful answer from Matic Kukovec through mail, that I would like to share here. Matic Kukovec made an incredible IDE based on QScintilla: <a href="https://github.com/matkuki/ExCo" rel="nofollow">https://github.com/matkuki/ExCo</a>. Maybe it will inspire more people to dig deeper into QScintilla (and clickab... | 0 | 2016-10-12T19:37:09Z | [
"python",
"python-3.x",
"pyqt",
"pyqt5",
"qscintilla"
] |
Append output function to multiple lists | 40,002,416 | <p>I want to execute a function with different parameter values. I have the following snippet of code which works perfectly well:</p>
<pre><code>tau = np.arange(2,4.01,0.1)
R = []
P = []
T = []
L = []
D = []
E = []
Obj = []
for i, tenum in enumerate(tau):
[r, p, t, l, d, e, obj] = (foo.cvxEDA(edaN, 1./fs, tenum, 0... | 0 | 2016-10-12T15:22:42Z | 40,002,571 | <pre><code>tau = np.arange(2,4.01,0.1)
results = [[] for _ in range(7)]
for i, tenum in enumerate(tau):
data = foo.cvxEDA(edaN, 1./fs, tenum, 0.7, 10.0, 0.0008, 0.01)
for r,d in zip(results, data):
r.append(d)
r, p, t, l, d, e, _obj = results
</code></pre>
| 3 | 2016-10-12T15:30:18Z | [
"python",
"list",
"python-2.7",
"append"
] |
Append output function to multiple lists | 40,002,416 | <p>I want to execute a function with different parameter values. I have the following snippet of code which works perfectly well:</p>
<pre><code>tau = np.arange(2,4.01,0.1)
R = []
P = []
T = []
L = []
D = []
E = []
Obj = []
for i, tenum in enumerate(tau):
[r, p, t, l, d, e, obj] = (foo.cvxEDA(edaN, 1./fs, tenum, 0... | 0 | 2016-10-12T15:22:42Z | 40,002,592 | <p>You can turn a generator object into a list object by just passing it to the <code>list()</code> function so maybe this will do what you want:</p>
<pre><code>res = []
for i, tenum in enumerate(tau):
res.append(list(foo.cvxEDA(edaN, 1./fs, tenum, 0.7, 10.0, 0.0008, 0.01)))
</code></pre>
<p>Even shorter with a li... | 3 | 2016-10-12T15:31:23Z | [
"python",
"list",
"python-2.7",
"append"
] |
How to vectorize hinge loss gradient computation | 40,002,509 | <p>I'm computing thousands of gradients and would like to vectorize the computations in Python. The context is SVM and the loss function is Hinge Loss. Y is Mx1, X is MxN and w is Nx1.</p>
<pre><code> L(w) = lam/2 * ||w||^2 + 1/m Sum i=1:m ( max(0, 1-y[i]X[i]w) )
</code></pre>
<p>The gradient of this is</p>
<pre><co... | 1 | 2016-10-12T15:27:14Z | 40,029,763 | <p>you have two vectors A and B, and you want to return array C, such that C[i] = A[i] if B[i] < 1 and 0 else, consequently all you need to do is</p>
<pre><code>C := A * sign(max(0, 1-B)) # suprisingly similar to the original hinge loss, right?:)
</code></pre>
<p>since</p>
<ul>
<li>if B < 1 then 1-B > 0, thus ... | 1 | 2016-10-13T19:52:03Z | [
"python",
"optimization",
"machine-learning"
] |
pandas: compare sum over two time periods? | 40,002,511 | <p>I have a dataframe that looks like this:</p>
<pre><code> prod_code month items cost
0 040201060AAAIAI 2016-05-01 5 572.20
1 040201060AAAKAK 2016-05-01 164 14805.19
2 040201060AAALAL 2016-05-01 13465 14486.07
</code></pre>
<p>I would like to first group by the first four... | 1 | 2016-10-12T15:27:18Z | 40,002,847 | <p>You can create a month group variable based on whether the months are <code>Jan-Feb</code> or <code>Mar-Apr</code> and then group by the code and month group variable, summarize the cost and calculate the difference:</p>
<pre><code>import numpy as np
import pandas as pd
df['month_period'] = np.where(pd.to_datetime(... | 1 | 2016-10-12T15:44:00Z | [
"python",
"pandas"
] |
Python: convert some encoding to russian alphabet | 40,002,546 | <p>I have list with unicode</p>
<pre><code>lst = [u'\xd0\xbe', u'/', u'\xd0\xb8', u'\xd1\x81', u'\xd0\xb2', u'\xd0\xba', u'\xd1\x8f', u'\xd1\x83', u'\xd0\xbd\xd0\xb0', u'____', u'|', u'\xd0\xbf\xd0\xbe', u'11', u'search', u'\xd0\xbe\xd1\x82', u'**modis**', u'15', u'\xd0\xa1', u'**avito**', u'\xd0\xbd\xd0\xb5', u'[\xd0... | 0 | 2016-10-12T15:29:16Z | 40,003,034 | <p>It appears that the elements of your list are byte strings encoded in UTF-8, yet they are of type <code>str</code> (or <code>unicode</code> in Python 2).</p>
<p>I used the following to convert them back into proper UTF-8:</p>
<pre><code>def reinterpret(string):
byte_arr = bytearray(ord(char) for char in string... | 1 | 2016-10-12T15:54:04Z | [
"python",
"unicode",
"encoding",
"utf-8"
] |
Python: convert some encoding to russian alphabet | 40,002,546 | <p>I have list with unicode</p>
<pre><code>lst = [u'\xd0\xbe', u'/', u'\xd0\xb8', u'\xd1\x81', u'\xd0\xb2', u'\xd0\xba', u'\xd1\x8f', u'\xd1\x83', u'\xd0\xbd\xd0\xb0', u'____', u'|', u'\xd0\xbf\xd0\xbe', u'11', u'search', u'\xd0\xbe\xd1\x82', u'**modis**', u'15', u'\xd0\xa1', u'**avito**', u'\xd0\xbd\xd0\xb5', u'[\xd0... | 0 | 2016-10-12T15:29:16Z | 40,003,035 | <p>Your data is a <a href="https://en.wikipedia.org/wiki/Mojibake" rel="nofollow">Mojibake</a>, incorrectly decoded from UTF-8 bytes as Latin-1 or CP1252.</p>
<p>You can repair this by manually reverting that process:</p>
<pre><code>repaired = [elem.encode('latin1').decode('utf8') for elem in lst]
</code></pre>
<p>b... | 1 | 2016-10-12T15:54:05Z | [
"python",
"unicode",
"encoding",
"utf-8"
] |
Calculating score of merged string | 40,002,581 | <p>I am trying to figure out how to calculate the score of two merged lists of names. I need to give one point for each character (including spaces between first and last name) plus one point for each vowel in the name. </p>
<pre><code>a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = ["a", "e",... | 1 | 2016-10-12T15:30:46Z | 40,002,730 | <pre><code>for first, second in gen:
name = " ".join(first, second)
score = 0
for letter in name:
if letter in vowel:
score += 1
score += len(name)
</code></pre>
<p>It's easier to have them as a string, you can then loop over that string. One point per character is easy, that's just... | 0 | 2016-10-12T15:38:11Z | [
"python",
"string",
"list"
] |
Calculating score of merged string | 40,002,581 | <p>I am trying to figure out how to calculate the score of two merged lists of names. I need to give one point for each character (including spaces between first and last name) plus one point for each vowel in the name. </p>
<pre><code>a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = ["a", "e",... | 1 | 2016-10-12T15:30:46Z | 40,002,895 | <p>So you first <code>zip</code> first and last names, then make then <code>str</code> with <code>' '</code> as separator. And then with <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> count how many times so called <em>vowel</em> char... | 0 | 2016-10-12T15:46:26Z | [
"python",
"string",
"list"
] |
What is the mistake here? | 40,002,588 | <p>These are my codes but it seems to be correct,but it doesn't work,please help </p>
<pre><code>HEADER_XPATH = ['//h1[@class="story-body__h1"]//text()']
AUTHOR_XPATH = ['//span[@class="byline__name"]//text()']
PUBDATE_XPATH = ['//div/@data-datetime']
WTAGS_XPATH = ['']
CATEGORY_XPATH = ['//span[@rev="news... | -2 | 2016-10-12T15:31:07Z | 40,005,562 | <p>Your spider is just badly structured and because of that it does nothing.<br>
The <code>scrapy.Spider</code> spider requires <code>start_urls</code> class attribute which should contains list of urls that the spider will use to start the crawl, all of these urls will callback to class method <code>parse</code> whic... | 0 | 2016-10-12T18:12:48Z | [
"python",
"python-3.x",
"scrapy",
"web-crawler",
"scrapy-spider"
] |
Selenium, Python. Gives no such element: Unable to locate element error whether the button is there | 40,002,614 | <p>I am working on my test case which includes sending values to the input fields for buying tickets. But for this case selenium gives me unable to locate element error while I am trying to locate input field named itemq_3728, the problem is the page is changing the name of input field every time it reopens the page.</... | 0 | 2016-10-12T15:31:58Z | 40,003,230 | <p>Hope this will help assuming only numeric path of name changes after pageload:
'<code>//td[@class="bms_restype_qty"]//input[starts-Ââwith(@name,"itemq")]'</code></p>
| 0 | 2016-10-12T16:04:00Z | [
"python",
"google-chrome",
"selenium",
"xpath"
] |
Selenium, Python. Gives no such element: Unable to locate element error whether the button is there | 40,002,614 | <p>I am working on my test case which includes sending values to the input fields for buying tickets. But for this case selenium gives me unable to locate element error while I am trying to locate input field named itemq_3728, the problem is the page is changing the name of input field every time it reopens the page.</... | 0 | 2016-10-12T15:31:58Z | 40,004,646 | <p>You can locate it using <code>cssSelector</code> as below :-</p>
<pre><code>driver.find_element_by_css_selector("td.bms_restype_qty > input[type='text']")
</code></pre>
<p>Or if you're interested to locate this element using <code>xpath</code> you can locate it wrt <code>Gen Ad</code> name column text as below ... | 0 | 2016-10-12T17:19:47Z | [
"python",
"google-chrome",
"selenium",
"xpath"
] |
python scikit linear-regression weird results | 40,002,632 | <p>im new to python.</p>
<p>Im tring to plot, using matplotlib, the results from linea regression.</p>
<p>I've tried with some basic data and it worked, but when i try with the actual data, the regression line is compltetely wrong. I think im doing something wrong with the fit() or predict() functions.</p>
<p>this i... | 0 | 2016-10-12T15:32:53Z | 40,003,677 | <p>You seem to be including the target values <code>A[:, 1]</code> in your training data. The fitting command is of the form <code>regr.fit(X, y)</code>.</p>
<p>You also seem to have a problem with this line:</p>
<blockquote>
<p><code>plt.plot(A[:,1],regr.predict(A), color='blue',linewidth=3)</code></p>
</blockquot... | 0 | 2016-10-12T16:26:03Z | [
"python",
"matplotlib",
"scikit-learn"
] |
Reject user input if criteria not met in Python | 40,002,645 | <p>I know this question is similar to one I have already asked, but it is an extension and so justified its own space :-)</p>
<p>I am a Python newbie writing a code which takes input from a user and then stores that user input in an array (to do more stuff with later), provided two criteria are met:</p>
<p>1) The tot... | 0 | 2016-10-12T15:33:32Z | 40,002,725 | <p>You'll simply need to cast to float before you do subtraction:</p>
<pre><code>if float(s) - 1 > 1.0:
</code></pre>
<p>This way, you can subtract 1 from the float value of <code>s</code></p>
<p><strong>EDIT:</strong> I would also make the following changes to your code in order to function more correctly.</p... | 2 | 2016-10-12T15:37:53Z | [
"python",
"loops",
"input"
] |
Reject user input if criteria not met in Python | 40,002,645 | <p>I know this question is similar to one I have already asked, but it is an extension and so justified its own space :-)</p>
<p>I am a Python newbie writing a code which takes input from a user and then stores that user input in an array (to do more stuff with later), provided two criteria are met:</p>
<p>1) The tot... | 0 | 2016-10-12T15:33:32Z | 40,002,840 | <p>One way you can assure the input type is with a try/except condition to exit a loop:</p>
<pre><code>while True:
a1 = raw_input('Enter concentration of hydrogen (in decimal form): ')
a2 = raw_input('Enter concentration of chlorine (in decimal form): ')
a3 = raw_input('Enter concentration of calcium (in ... | 2 | 2016-10-12T15:43:33Z | [
"python",
"loops",
"input"
] |
Reject user input if criteria not met in Python | 40,002,645 | <p>I know this question is similar to one I have already asked, but it is an extension and so justified its own space :-)</p>
<p>I am a Python newbie writing a code which takes input from a user and then stores that user input in an array (to do more stuff with later), provided two criteria are met:</p>
<p>1) The tot... | 0 | 2016-10-12T15:33:32Z | 40,003,795 | <p>Your code is a bit confused. I'm sure that someone could pick holes in the following but give it a whirl and see if it helps. </p>
<p>Initially putting the questions into a list, allows you to ask and validate the input one at a time within a single loop, exiting the loop only when all of the questions have been... | 1 | 2016-10-12T16:32:32Z | [
"python",
"loops",
"input"
] |
Getting element by undefinied tag name | 40,002,652 | <p>I'm parsing an xml document in Python using minidom. </p>
<p>I have an element:</p>
<pre><code><informationRequirement>
<requiredDecision href="id"/>
</informationRequirement>
</code></pre>
<p>The only thing I need is value of href in subelement but its tag name can be different (for example <... | 0 | 2016-10-12T15:33:40Z | 40,006,370 | <p>If you're always guaranteed to have one subelement, just grab that element:</p>
<pre><code>element.childNodes[0].attributes['href'].value
</code></pre>
<p>However, this is brittle. A (perhaps) better approach could be:</p>
<pre><code>hrefs = []
for child in element.childNodes:
if child.tagName.startswith('requ... | 0 | 2016-10-12T18:59:58Z | [
"python",
"xml-parsing",
"minidom"
] |
Refreshing QGraphicsScene pyqt - Odd results | 40,002,664 | <p>I am trying to build a simple node graph in pyqt. I am having some trouble with a custom widget leaving artifacts and not drawing correctly when moved by the mouse. See images below:</p>
<p><a href="https://i.stack.imgur.com/KBMoP.png" rel="nofollow"><img src="https://i.stack.imgur.com/KBMoP.png" alt="Before I move... | 0 | 2016-10-12T15:34:39Z | 40,023,399 | <p>So my issue was that I was not scaling the bounding box in "object space"... To following changes fix my issue.</p>
<pre><code> def boundingRect(self):
"""Bounding."""
# Added .5 for padding
return QtCore.QRectF(-.5,
-.5,
self.width ... | 0 | 2016-10-13T14:10:34Z | [
"python",
"qt",
"canvas",
"pyqt",
"graphics2d"
] |
Letter Game Challenge Python | 40,002,754 | <p>A word game awards points for the letters used in a word. The lower the frequency of the letter in the English language, the higher the score for the letter. Write a program that asks the user to input a word. The program should then output the score for the word according to the following rules:</p>
<p><img src... | -1 | 2016-10-12T15:39:30Z | 40,059,702 | <p>To loop through the letters of a word use a for loop:</p>
<pre><code>for letter in word_input:
</code></pre>
<p>You will need to look up the score for each letter. Try using a dictionary:</p>
<pre><code>scores = {"e": 1,
"a": 2,
#etc
</code></pre>
<p>Then you can look the score of a letter w... | 0 | 2016-10-15T13:38:46Z | [
"python",
"python-3.x"
] |
Django Multi-App Database Router not working | 40,002,781 | <p>I'm doing a project using Django 1.10 and Python 2.7.</p>
<p>I have read and tried to implement database routing according to <a href="https://docs.djangoproject.com/en/1.10/topics/db/multi-db/#using-routers" rel="nofollow">this page</a>. I have also read up on a lot of different tutorials and other stackoverflow q... | 1 | 2016-10-12T15:40:36Z | 40,003,844 | <p>check if this works for you:</p>
<p><strong>settings.py</strong></p>
<pre><code>DB_Mapping = {
"cancellation": "cancellation_db",
"driveractivity": "driveractivity_db",
...
}
</code></pre>
<p><strong>router.py</strong></p>
<pre><code>from project.settings import DB_Mapping
class MyRouter(object):
... | 0 | 2016-10-12T16:35:48Z | [
"python",
"django"
] |
Numpy choose without replacement along specific dimension | 40,002,821 | <p>Without replacement I'm choosing k elements from a sample n distinct times according to a specified distribution.</p>
<p>The iterative solution is simple:</p>
<pre><code>for _ in range(n):
np.random.choice(a, size=k, replace=False, p=p)
</code></pre>
<p>I can't set <code>size=(k, n)</code> because I would sam... | 2 | 2016-10-12T15:42:44Z | 40,003,823 | <p>So the full iterative solution is:</p>
<pre><code>In [158]: ll=[]
In [159]: for _ in range(10):
...: ll.append(np.random.choice(5,3))
In [160]: ll
Out[160]:
[array([3, 2, 4]),
array([1, 1, 3]),
array([0, 3, 1]),
...
array([0, 3, 0])]
In [161]: np.array(ll)
Out[161]:
array([[3, 2, 4],
[1, 1, 3... | 0 | 2016-10-12T16:34:25Z | [
"python",
"numpy"
] |
Numpy choose without replacement along specific dimension | 40,002,821 | <p>Without replacement I'm choosing k elements from a sample n distinct times according to a specified distribution.</p>
<p>The iterative solution is simple:</p>
<pre><code>for _ in range(n):
np.random.choice(a, size=k, replace=False, p=p)
</code></pre>
<p>I can't set <code>size=(k, n)</code> because I would sam... | 2 | 2016-10-12T15:42:44Z | 40,003,884 | <p>Here are a couple of suggestions.</p>
<ol>
<li><p>You can preallocate the <code>(n, k)</code> output array, then do the choice multiple times:</p>
<pre><code>result = np.zeros((n, k), dtype=a.dtype)
for row in range(n):
result[row, :] = np.random.choice(a, size=k, replace=False, p=p)
</code></pre></li>
<li><p>... | 0 | 2016-10-12T16:37:54Z | [
"python",
"numpy"
] |
Wait for page redirect Selenium WebDriver (Python) | 40,002,826 | <p>I have a page which loads dynamic content with ajax and then redirects after a certain amount of time (not fixed). How can i force selenium webdriver to wait for the page to redirect then immediately after go to a different link?</p>
<pre><code>import time
from selenium import webdriver
from selenium.webdriver.comm... | 0 | 2016-10-12T15:42:59Z | 40,003,165 | <p>You can create a custom <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow">Expected Condition to wait</a> for the URL to change:</p>
<pre><code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
wait = WebDriverWait(driver, 10)
... | 1 | 2016-10-12T16:00:41Z | [
"python",
"selenium",
"selenium-webdriver",
"webdriver"
] |
Remove newline characters that appear between curly brackets | 40,002,880 | <p>I'm currently writing a text processing script which contains static text and variable values (surrounded by curly brackets). I need to be able to strip out newline characters but only if they appear between the curly brackets:</p>
<p><code>Some text\nwith a {variable\n} value"</code></p>
<p>to:</p>
<p><code>Some... | 1 | 2016-10-12T15:45:40Z | 40,002,947 | <p>You may pass the match object to a lambda in a <code>re.sub</code> and replace all newlines inside <code>{...}</code>:</p>
<pre><code>import re
text = 'Some text\nwith a {variable\n} value"'
print(re.sub(r'{.*?}', lambda m: m.group().replace("\n", ""), text, flags=re.DOTALL))
</code></pre>
<p>See <a href="http://i... | 2 | 2016-10-12T15:49:38Z | [
"python",
"regex",
"python-3.x"
] |
Remove newline characters that appear between curly brackets | 40,002,880 | <p>I'm currently writing a text processing script which contains static text and variable values (surrounded by curly brackets). I need to be able to strip out newline characters but only if they appear between the curly brackets:</p>
<p><code>Some text\nwith a {variable\n} value"</code></p>
<p>to:</p>
<p><code>Some... | 1 | 2016-10-12T15:45:40Z | 40,003,041 | <p>Assuming you have un-nested, balanced brackets you can use this lookahead regex to replace newline between <code>{...}</code>:</p>
<pre><code>>>> s = "Some text\nwith a {variable\n} value"
>>> print re.sub(r'\n(?=[^{}]*})', '', s)
Some text
with a {variable} value
</code></pre>
<p><code>(?=[^{}]*... | 1 | 2016-10-12T15:54:22Z | [
"python",
"regex",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.