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 |
|---|---|---|---|---|---|---|---|---|---|
How to plot odd even square wave using python | 38,896,496 | <p>I am using the below python codes so as to generates a square wave at one specific position. For Eg: you enter 0, the signal is high<a href="http://i.stack.imgur.com/4Ivso.png" rel="nofollow">1</a> only between 0 and 1[Odd=High]. You enter 1, the output is high<a href="http://i.stack.imgur.com/4Ivso.png" rel="nofoll... | 0 | 2016-08-11T12:31:54Z | 38,896,958 | <p>Don't use <code>;</code>.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def SquareWave(n,xmin=0,xmax=10,ymin=-2,Nx=1000,ymax=2,offset=1):
x=np.sort(np.concatenate([np.arange(xmin, xmax)-1E-6,np.arange(xmin, xmax)+1E-6]))
#You can use np.linspace(xmin,xmax,Nx) if you want the intermedi... | 1 | 2016-08-11T12:52:48Z | [
"python",
"numpy",
"matplotlib"
] |
SQLAlchemy: is it possible to operate Query without bounding to session? | 38,896,499 | <p>I want to execute the same SQL query from different processes by SQLAlchemy.
As I understand I must create new Session in every process. So for each new session I must recreate query:</p>
<pre><code>session.query(...).filter(...)
etc.
</code></pre>
<p>It seems logical to save fully formed query separately from ses... | 1 | 2016-08-11T12:32:06Z | 38,896,879 | <p>You can use <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.with_session" rel="nofollow"><code>with_session</code></a>:</p>
<pre><code>query = session.query(...).filter(...)
query.with_session(new_session)
</code></pre>
<p>It is also possible to create a query without a boun... | 1 | 2016-08-11T12:49:41Z | [
"python",
"session",
"sqlalchemy",
"python-3.4"
] |
adding value to dict using keys list | 38,896,828 | <p>Consider the scenario in which list contains key of a dict</p>
<pre><code>x = {'a':{'b': 1}}
lst = ['a','c']
value = {'d': 3}
</code></pre>
<p>Using the keys present in the list <code>lst</code> is there a way to add an entry in the dict <code>x</code> . </p>
<p><strong>Expected Result:</strong></p>
<pre><code>x... | 0 | 2016-08-11T12:47:19Z | 38,897,180 | <p>Use a loop an a temporary dictionary_variable:</p>
<pre><code>tmp_dict = x
for key in lst[:-1]:
tmp_dict = tmp_dict[key]
tmp_dict[lst[-1]] = value
print x
</code></pre>
<p>Notice, that the loop over all keys except the last one, since we need the last key for the assignment operation.</p>
| 0 | 2016-08-11T13:02:02Z | [
"python",
"python-2.7"
] |
adding value to dict using keys list | 38,896,828 | <p>Consider the scenario in which list contains key of a dict</p>
<pre><code>x = {'a':{'b': 1}}
lst = ['a','c']
value = {'d': 3}
</code></pre>
<p>Using the keys present in the list <code>lst</code> is there a way to add an entry in the dict <code>x</code> . </p>
<p><strong>Expected Result:</strong></p>
<pre><code>x... | 0 | 2016-08-11T12:47:19Z | 38,897,259 | <p>Philipp's answer is good. </p>
<p>But here is my attempt to give you the <em>exact</em> answer you expected.</p>
<pre><code>x = {'a':{'b' : 1}}
lst=['a','c']
value = {'d':3}
x[lst[0]][lst[1]] = value
print(x)
>> {'a': {'c': {'d': 3}, 'b': 1}}
</code></pre>
| 1 | 2016-08-11T13:05:30Z | [
"python",
"python-2.7"
] |
Python->Beautifulsoup->Webscraping->Looping over URL (1 to 53) and saving Results | 38,896,893 | <p><a href="http://livingwage.mit.edu/">Here is the Website I am trying to scrape http://livingwage.mit.edu/</a></p>
<p>The specific URLs are from </p>
<pre><code>http://livingwage.mit.edu/states/01
http://livingwage.mit.edu/states/02
http://livingwage.mit.edu/states/04 (For some reason they skipped 03)
...all the... | 5 | 2016-08-11T12:50:07Z | 38,897,186 | <blockquote>
<p>Problem 1: These are the things that I want in the desired output, but how can I get python to give it to me in a string format rather than HTML like above?</p>
</blockquote>
<p>You can get the text by simply by doing something on the lines of:</p>
<pre><code>state_name=states.find('h1').text
</code... | 2 | 2016-08-11T13:02:21Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Python->Beautifulsoup->Webscraping->Looping over URL (1 to 53) and saving Results | 38,896,893 | <p><a href="http://livingwage.mit.edu/">Here is the Website I am trying to scrape http://livingwage.mit.edu/</a></p>
<p>The specific URLs are from </p>
<pre><code>http://livingwage.mit.edu/states/01
http://livingwage.mit.edu/states/02
http://livingwage.mit.edu/states/04 (For some reason they skipped 03)
...all the... | 5 | 2016-08-11T12:50:07Z | 38,897,405 | <p>Just get all the states from the initial page, then you can select the second table and use the <em>css classes</em> <em>odd results</em> to get the <em>tr</em> you need, there is no need to slice as the class names are unique:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
from urllib.parse import u... | 5 | 2016-08-11T13:12:17Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Python - How to improve efficiency of complex recursive function? | 38,896,939 | <p>In <a href="https://www.youtube.com/watch?v=jcKRGpMiVTw" rel="nofollow">this video</a> by Mathologer on, amongst other things, infinite sums there are 3 different infinite sums shown at 9:25, when the video freezes suddenly and an elephant diety pops up, challenging the viewer to find "the probable values" of the ex... | 1 | 2016-08-11T12:51:44Z | 38,897,580 | <p>You can store the results of the <code>run1</code>, <code>run2</code> and <code>run3</code> functions in arrays to prevent them from being recalculated every time, since in your example, <code>main(1)</code> calls <code>run1(1)</code>, which calls <code>run3(2)</code> and <code>run2(2)</code>, which in turn call <co... | 1 | 2016-08-11T13:20:03Z | [
"python",
"performance",
"math",
"recursion",
"optimization"
] |
Python - How to improve efficiency of complex recursive function? | 38,896,939 | <p>In <a href="https://www.youtube.com/watch?v=jcKRGpMiVTw" rel="nofollow">this video</a> by Mathologer on, amongst other things, infinite sums there are 3 different infinite sums shown at 9:25, when the video freezes suddenly and an elephant diety pops up, challenging the viewer to find "the probable values" of the ex... | 1 | 2016-08-11T12:51:44Z | 38,897,615 | <p>With some memoization, You could get up to the stack overflow:</p>
<pre><code>from decimal import Decimal as D, getcontext # for accurate results
def main(c): # faster code when functions defined locally (I think)
mrun1 = {} # store partial results of run1, run2 and run3
# This have not been... | 0 | 2016-08-11T13:21:45Z | [
"python",
"performance",
"math",
"recursion",
"optimization"
] |
using Plotly with pycharm | 38,897,010 | <p>I am trying to use <strong>Plotly</strong> with <strong>pycharm</strong> when I run the code (which I toke from the Ploty getting started <a href="https://plot.ly/python/getting-started/#initialization-for-offline-plotting" rel="nofollow">page</a> on terminal it is OK but when I use it with pycharm I get error: </p... | 0 | 2016-08-11T12:54:55Z | 38,897,187 | <p>In Pycharm you have to download it. </p>
<p>Go to File --> Settings -->Project --> Project Interpreter --> on the plus right site--> search for your module and download it!</p>
<p>Thats it!!</p>
| 0 | 2016-08-11T13:02:22Z | [
"python",
"pycharm",
"plotly"
] |
using Plotly with pycharm | 38,897,010 | <p>I am trying to use <strong>Plotly</strong> with <strong>pycharm</strong> when I run the code (which I toke from the Ploty getting started <a href="https://plot.ly/python/getting-started/#initialization-for-offline-plotting" rel="nofollow">page</a> on terminal it is OK but when I use it with pycharm I get error: </p... | 0 | 2016-08-11T12:54:55Z | 39,269,308 | <p>Your script is named <code>plotly.py</code>. In the first line where you import plotly it loads your script and not the plotly package. Change the name of your script to <code>plot.py</code> or something other than plotly and it should work.</p>
| 1 | 2016-09-01T10:38:23Z | [
"python",
"pycharm",
"plotly"
] |
Escape all metacharacters in Python | 38,897,045 | <p>I need to search for patterns which may have many metacharacters. Currently I use a long regex.</p>
<pre><code>prodObjMatcher=re.compile(r"""^(?P<nodeName>[\w\/\:\[\]\<\>\@\$]+)""", re.S|re.M|re.I|re.X)
</code></pre>
<p>(my actual pattern is very long so I just pasted some relevant portion on which I n... | 0 | 2016-08-11T12:56:39Z | 38,897,689 | <p>Look, your pattern can be reduced to</p>
<pre><code>r"""^(?P<nodeName>[]\w/:[<>@$]+).*?"""
</code></pre>
<p>Note that you do not have to ever escape any non-word character in the character classes, except for shorthand classes, <code>^</code>, <code>-</code>, <code>]</code>, and <code>\</code>. There a... | 2 | 2016-08-11T13:25:15Z | [
"python",
"regex",
"metacharacters"
] |
Tensorflow: tensor multiplication row-by-row with more different matrices | 38,897,084 | <p>I have a matrix A which is defined as a tensor in tensorflow, of n rows and p columns. Moreover, I have say k matrices B1,..., Bk with p rows and q columns. My goal is to obtain a resulting matrix C of n rows and q columns where each row of C is the matrix product of the corresponding row in A with one of the B matr... | 0 | 2016-08-11T12:58:17Z | 38,903,735 | <p>This is a bit tricky and there are probably better solutions. Taking your first example, my approach computes C as follows:</p>
<pre><code>C = diag([0,1,1,0]) * A * B1 + diag([1,0,0,1]) * A * B2
</code></pre>
<p>where <code>diag([0,1,1,0])</code> is the diagonal matrix having vector <code>[0,1,1,0]</code> in its d... | 0 | 2016-08-11T18:30:39Z | [
"python",
"machine-learning",
"tensorflow",
"deep-learning",
"matrix-multiplication"
] |
Tensorflow: tensor multiplication row-by-row with more different matrices | 38,897,084 | <p>I have a matrix A which is defined as a tensor in tensorflow, of n rows and p columns. Moreover, I have say k matrices B1,..., Bk with p rows and q columns. My goal is to obtain a resulting matrix C of n rows and q columns where each row of C is the matrix product of the corresponding row in A with one of the B matr... | 0 | 2016-08-11T12:58:17Z | 38,904,771 | <p>Just do 2 matrix multiplications</p>
<pre><code>A1 = A[0:3:3,...] # this will get the first last index of your original but just make a new matrix
A2 = A[1:2]
</code></pre>
<p>in tensorflow</p>
<pre><code>A1 = tf.constant([matrix elements go here])
A2 = tf.constant([matrix elements go here])
B = ...
B1 = tf.matm... | 0 | 2016-08-11T19:36:43Z | [
"python",
"machine-learning",
"tensorflow",
"deep-learning",
"matrix-multiplication"
] |
Axes Subplot y size | 38,897,091 | <p>I have two subplots that share the x-axes. The first one has data and a fit function, in the second one is the difference between the data and the fit function. In the figure both subplots have the same y axis size (in pixels). Now i want the y axis of the data and the fit to be bigger than the axis of the errors. m... | 1 | 2016-08-11T12:58:36Z | 38,900,223 | <p>Take a look at <a href="http://stackoverflow.com/questions/10388462/matplotlib-different-size-subplots">this example, using gridspec</a>. I believe it is exactly what you want. Below is the example adopted for your case. <strong>Edited to also share the x-axis</strong></p>
<pre><code>import numpy as np
import mat... | 0 | 2016-08-11T15:14:48Z | [
"python",
"matplotlib"
] |
Python reverse escape characters | 38,897,289 | <p>I want to convert the escaped characters back to the original form:</p>
<pre><code>>>> myString="\\10.10.10.10\view\a"
>>> myString
'\\10.10.10.10\x0biew\x07'
>>>desiredString=fun(myString)
>>>print desiredString
'\\10.10.10.10\view\a'
</code></pre>
<p>I researched quite a lot a... | 1 | 2016-08-11T13:07:00Z | 38,897,400 | <pre><code>myString=r"\\10.10.10.10\view\a"
myString
'\\\\10.10.10.10\\view\\a'
print myString
\\10.10.10.10\view\a
</code></pre>
<p>r'...' is byte strings</p>
| 0 | 2016-08-11T13:12:12Z | [
"python",
"string",
"escaping",
"character",
"backslash"
] |
Python reverse escape characters | 38,897,289 | <p>I want to convert the escaped characters back to the original form:</p>
<pre><code>>>> myString="\\10.10.10.10\view\a"
>>> myString
'\\10.10.10.10\x0biew\x07'
>>>desiredString=fun(myString)
>>>print desiredString
'\\10.10.10.10\view\a'
</code></pre>
<p>I researched quite a lot a... | 1 | 2016-08-11T13:07:00Z | 38,897,585 | <p>The <code>\v</code> and <code>\a</code> are interpreted as specials characters while printing. Don't worry, just add another backslash to avoid this.</p>
<pre><code>>>> myString="\\10.10.10.10\\view\\a"
>>> print(myString)
\10.10.10.10\view\a
</code></pre>
<p>Edit:
Or use <a href="https://docs.py... | 0 | 2016-08-11T13:20:21Z | [
"python",
"string",
"escaping",
"character",
"backslash"
] |
Python reverse escape characters | 38,897,289 | <p>I want to convert the escaped characters back to the original form:</p>
<pre><code>>>> myString="\\10.10.10.10\view\a"
>>> myString
'\\10.10.10.10\x0biew\x07'
>>>desiredString=fun(myString)
>>>print desiredString
'\\10.10.10.10\view\a'
</code></pre>
<p>I researched quite a lot a... | 1 | 2016-08-11T13:07:00Z | 38,900,247 | <p>Ideally you should use the python builtin string functions or parsing properly your input data so you'd avoid these post-transformations. In fact, these custom solutions are not encouraged at all, but here you go:</p>
<pre><code>def fun(input_str):
cache = {
'\'':"\\'",
'\"':'\\"',
'\a':... | 1 | 2016-08-11T15:15:47Z | [
"python",
"string",
"escaping",
"character",
"backslash"
] |
Pip Wheel and coverage: command not found error | 38,897,291 | <p>I want to use wheels on my Linux server as it seems much faster, but when I do:</p>
<pre><code>pip install wheel
pip wheel -r requirements_dev.txt
</code></pre>
<p>Which contains the following packages</p>
<pre><code>nose
django_coverage
coverage
</code></pre>
<p>I get <strong>coverage: command not found</st... | 1 | 2016-08-11T13:07:04Z | 38,897,336 | <p>Can you try this?</p>
<pre><code>virtualenv venv
source venv/bin/activate
pip -r install requirement.txt
</code></pre>
<p>Also getting this with using wheel:-</p>
<pre><code>pip wheel -r check.txt
Collecting nose (from -r check.txt (line 1))
Using cached nose-1.3.7-py2-none-any.whl
Saved ./nose-1.3.7-py2-none... | 3 | 2016-08-11T13:09:24Z | [
"python",
"django",
"python-3.x",
"pip",
"wheel"
] |
Pip Wheel and coverage: command not found error | 38,897,291 | <p>I want to use wheels on my Linux server as it seems much faster, but when I do:</p>
<pre><code>pip install wheel
pip wheel -r requirements_dev.txt
</code></pre>
<p>Which contains the following packages</p>
<pre><code>nose
django_coverage
coverage
</code></pre>
<p>I get <strong>coverage: command not found</st... | 1 | 2016-08-11T13:07:04Z | 38,897,519 | <p>Installing from wheels is what pip already does by default. <code>pip wheel</code> is for <em>creating</em> wheels from your requirements file.</p>
| 1 | 2016-08-11T13:17:16Z | [
"python",
"django",
"python-3.x",
"pip",
"wheel"
] |
Can I use an iterable which reads a file in parallel_bulk? | 38,897,373 | <p>Currently I have a function which reads a file in chunks, does some work (parsing, formating) and then <code>yeilds</code> the data in the format for the <code>elasticsearch</code> bulk loader.</p>
<p>Currently I'm using <a href="http://elasticsearch-py.readthedocs.io/en/master/helpers.html" rel="nofollow"><code>st... | 1 | 2016-08-11T13:11:05Z | 38,909,059 | <p>Short answer : <code>parallel_bulk</code> sends data to elasticsearch concurrently. </p>
<p>From the code snippet <a href="https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch/helpers/__init__.py#L229" rel="nofollow">here</a>: we see that <code>parallel_bulk</code> concurrently sends chunks of acti... | 1 | 2016-08-12T02:46:21Z | [
"python",
"elasticsearch"
] |
How to remove filters in advance search in odoo | 38,897,375 | <p>I want to remove filters which are in advance search in odoo tree views. Its easy to remove filters and group by which display in top of tree view. But in advance search all filters are displaying, and i want some of them, and other ones want to remove, is there any solution to remove advance filters in odoo?</p>
| 1 | 2016-08-11T13:11:08Z | 38,905,738 | <p>As far as i can see <a href="https://github.com/odoo/odoo/blob/8.0/addons/web/static/src/js/search.js#L1989" rel="nofollow">here</a> <code>models.Model</code> <code>fields_get()</code> is called to get the advanced search field list. You should either work around the javascript code or override the <code>fields_get(... | 1 | 2016-08-11T20:40:44Z | [
"python",
"filter",
"openerp",
"odoo-8"
] |
Customize logging for external/third-party libs | 38,897,399 | <p>I followed the advice of the django docs, and use logging like this:</p>
<pre><code>import logging
logger = logging.getLogger(__name__)
def today(...):
logger.info('Sun is shining, the weather is sweet')
</code></pre>
<p>With my current configuration, the output looks like this:</p>
<pre><code>2016-08-11 14:... | 12 | 2016-08-11T13:12:09Z | 38,898,076 | <p>That's because they're using the root logger (which is what you get by default when you just do </p>
<pre><code>import logging
logging.info("Hi! I'm the root logger!")
</code></pre>
<p>If you want to do something different you have two (or three) options. The best would be to use the <a href="https://docs.python.... | 3 | 2016-08-11T13:41:46Z | [
"python",
"django",
"logging"
] |
Customize logging for external/third-party libs | 38,897,399 | <p>I followed the advice of the django docs, and use logging like this:</p>
<pre><code>import logging
logger = logging.getLogger(__name__)
def today(...):
logger.info('Sun is shining, the weather is sweet')
</code></pre>
<p>With my current configuration, the output looks like this:</p>
<pre><code>2016-08-11 14:... | 12 | 2016-08-11T13:12:09Z | 38,899,045 | <p>As Wayne Werner suggested, I would use the Log Record format options. Here's an example.</p>
<p>File 1: <code>external_module</code></p>
<pre><code>import logging
def third_party():
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
logger.info("Hello from %s!"%__name__)
</code></pr... | 3 | 2016-08-11T14:22:33Z | [
"python",
"django",
"logging"
] |
Is there a faster way of doing full row comparisons on a small pandas dataframe than using loops and iloc? | 38,897,449 | <p>I have a large number of small pandas dataframes on which I have to do full row comparisons and write the results into new dataframes which will get concatenated later.</p>
<p>For the row comparisons I'm doing a double loop over the length of the dataframe using iloc. I don't know if there is a faster way, the way ... | 1 | 2016-08-11T13:14:26Z | 38,897,941 | <p>Don't use pandas. Use dictionaries and save it:</p>
<pre><code>def compare_values(x,y):
if x>y: return 1
elif x<y: return -1
else: return 0
def processFrames(P):
d_A2B = dict(zip(P["A"],P["B"]))
d_A2C = dict(zip(P["A"],P["C"]))
keys = list(d_A2B.keys())
d_ind2key = dict(zip(range(len(keys)),ke... | 1 | 2016-08-11T13:36:48Z | [
"python",
"performance",
"pandas",
"dataframe",
"vectorization"
] |
Is there a faster way of doing full row comparisons on a small pandas dataframe than using loops and iloc? | 38,897,449 | <p>I have a large number of small pandas dataframes on which I have to do full row comparisons and write the results into new dataframes which will get concatenated later.</p>
<p>For the row comparisons I'm doing a double loop over the length of the dataframe using iloc. I don't know if there is a faster way, the way ... | 1 | 2016-08-11T13:14:26Z | 38,898,073 | <p>You can use:</p>
<pre><code>#cross join
P['one'] = 1
df = pd.merge(P,P, on='one')
df = df.rename(columns={'A_x':'T1','A_y':'T2'})
#remove duplicates
df = df[df.T1 != df.T2]
df.reset_index(drop=True, inplace=True)
#creates new columns
df['T3'] = 1
df['T4'] = (df.C_x > df.C_y).astype(int).replace({0:-1})
df['T5'... | 1 | 2016-08-11T13:41:43Z | [
"python",
"performance",
"pandas",
"dataframe",
"vectorization"
] |
Is there a faster way of doing full row comparisons on a small pandas dataframe than using loops and iloc? | 38,897,449 | <p>I have a large number of small pandas dataframes on which I have to do full row comparisons and write the results into new dataframes which will get concatenated later.</p>
<p>For the row comparisons I'm doing a double loop over the length of the dataframe using iloc. I don't know if there is a faster way, the way ... | 1 | 2016-08-11T13:14:26Z | 38,898,722 | <p>Here's an approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> -</p>
<pre><code>def processFrames1_broadcasting(P):
N = len(P)
N_range = np.arange(N)
valid_mask = (N_range[:,None] != N_range).ravel()
colB = P.B.va... | 3 | 2016-08-11T14:08:47Z | [
"python",
"performance",
"pandas",
"dataframe",
"vectorization"
] |
While loop check one condition before the other | 38,897,684 | <p>I'm new to programming, and I want to write some code like </p>
<pre><code>while(condition_A and condition_B):
#Do something
</code></pre>
<p>But each time I run the while loop, I want to check condition A first, and if condition A works then check condition B. For example, condition A checks if condition B ... | -1 | 2016-08-11T13:25:04Z | 38,897,758 | <p>It looks like you're using python.
You actually had the answer yourself:</p>
<pre><code>while(condition_A and condition_B):
#Do something
</code></pre>
| 1 | 2016-08-11T13:28:46Z | [
"python",
"loops",
"while-loop"
] |
Enumeration of k-means clusters | 38,897,779 | <pre><code>sample=['he buy fish','he buy bread','the pizza is die'
,'the man buy pizza','mcdonald is there','there is a boy',
'who beat the man','burger and pizza']
fidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=200000, min_df=0.2, stop_words='english',use_idf=True)
vect=TfidfVectorizer(min_df=1)
x=vect.fi... | -3 | 2016-08-11T13:29:39Z | 38,906,826 | <p>k-means by <em>design</em> is a randomized algorithm.</p>
<p>It begins with <em>random</em> centers. And by running it multiple times, you can get different solutions. Some may be better than others - that is good.</p>
<p>Because it is randomized, it is not defined which cluster is cluster #0, #1, etc. - they <em>... | 0 | 2016-08-11T22:04:57Z | [
"python",
"cluster-analysis",
"data-mining",
"k-means"
] |
Find if IP address is in range of addresses | 38,897,835 | <p>I am trying to build a service responsible for geo location of IP addresses. The open database of IP addresses is a CSV file of the following format: starting_ip, ending_ip, region</p>
<p>So I was thinking about converting IPs to integers, and trying to see if a given integer is within ranges of starting and ending... | 1 | 2016-08-11T13:31:58Z | 38,897,921 | <p>Assuming the ranges are non-overlapping, you could sort them once by <code>ip_start</code> and then use binary search to find a candidate range. Once you've found a candidate range, all you have to do is check whether the IP address falls between <code>ip_start</code> and <code>ip_end</code>.</p>
<p>You could use t... | 2 | 2016-08-11T13:35:34Z | [
"python"
] |
Find if IP address is in range of addresses | 38,897,835 | <p>I am trying to build a service responsible for geo location of IP addresses. The open database of IP addresses is a CSV file of the following format: starting_ip, ending_ip, region</p>
<p>So I was thinking about converting IPs to integers, and trying to see if a given integer is within ranges of starting and ending... | 1 | 2016-08-11T13:31:58Z | 38,899,393 | <p>I would suggest you persist the data once sorted in whatever usable format you like but using a <a href="http://www.grantjenks.com/docs/sortedcontainers/introduction.html" rel="nofollow">sortedtcontainers</a> <em>SortedDict</em> will allow you to do the comparison in <em>log n</em> time once you have a sorted collec... | 0 | 2016-08-11T14:37:13Z | [
"python"
] |
Change x-axis (xlim) on holoviews histogram | 38,897,845 | <p>In matplotlib we can change the limits of the x-axis with the xlim() method. Is there an equivalent method in HoloViews?</p>
<p>I searched the <a href="http://ioam.github.io/holoviews/Tutorials/Options" rel="nofollow">HV options page</a>, but didn't find anything that seemed to do this.</p>
<p>I created the image ... | 1 | 2016-08-11T13:32:23Z | 39,036,534 | <p>HoloViews will usually just use the bounds of the data you give it. So the easiest way to change the bounds of a histogram is to change it in the np.histogram call itself:</p>
<pre><code>frequencies, edges = np.histogram(values, 10, range=(0.002, 0.016))
hv.Histogram(frequencies, edges)
</code></pre>
<p>If you sim... | 1 | 2016-08-19T10:18:05Z | [
"python",
"holoviews"
] |
Ensure that a version of some package is newer than version x | 38,897,897 | <p>is there a better way in python to ensure a script runs only with a version of a module newer than x as this?</p>
<pre><code>import somemodule
assert int(somemodule.__version__[0]) > 1 # would enforce a version of at least 2.0
</code></pre>
<p>In perl one would do it like:</p>
<pre><code>use somemodule 2.0
</c... | 1 | 2016-08-11T13:34:22Z | 38,899,910 | <p>Why do you really have to convert to int. <strong>I know this is not pythonic way of doing it</strong>, but it definitely works</p>
<pre><code>>>> assert('0.0.8' > '1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert('0.0.8' > '0... | 0 | 2016-08-11T14:59:17Z | [
"python",
"import"
] |
How to have python audibly read text | 38,897,943 | <p>I just can't figure it out....I know how <code>python</code> can recognize my voice but I don't know how to make <code>python</code> read text audibly.</p>
<pre><code>from time import sleep
import sys
print("Tell me something...")
LOL = input()
sleep(2)
print("Thinking...")
sleep(2)
if LOL == 'Hey' or LOL == 'Hell... | -2 | 2016-08-11T13:36:51Z | 38,898,108 | <p>Assuming you are running under windows and you have pip installed, run <code>pip install speech</code> on a CMD window (run cmd with start menu and type cmd) after speech has installed stick <code>import speech</code> at the top of your python program. under your <code>if</code> statement put <code>speech.say('Hello... | 0 | 2016-08-11T13:43:04Z | [
"python",
"speech-recognition"
] |
How to have python audibly read text | 38,897,943 | <p>I just can't figure it out....I know how <code>python</code> can recognize my voice but I don't know how to make <code>python</code> read text audibly.</p>
<pre><code>from time import sleep
import sys
print("Tell me something...")
LOL = input()
sleep(2)
print("Thinking...")
sleep(2)
if LOL == 'Hey' or LOL == 'Hell... | -2 | 2016-08-11T13:36:51Z | 38,898,847 | <p>Just make sure you have installed the speech library.</p>
<pre><code>pip install speech
</code></pre>
<p>Then import it at the top of the python script </p>
<pre><code>import speech
</code></pre>
<p>Then for what ever you want it to say, do: </p>
<pre><code>speech.say("Text you want it to speak here")
</code></... | 0 | 2016-08-11T14:14:05Z | [
"python",
"speech-recognition"
] |
Pulling from List using If/Else statement - Python | 38,898,155 | <p>I want to match the correct terms from my list. Here is my code: </p>
<pre><code>stuff = ["cat", "dog", "house", "cat", "mouse"]
for item in stuff:
if "house" in item:
print "house good"
if "cat" in item:
print "cat good"
if "dog" in item:
print "dog good"
else:
prin... | -1 | 2016-08-11T13:45:21Z | 38,898,210 | <p>You should make all the conditions part of the same statement, by using <code>elif</code>. Currently the else only applies to the last condition.</p>
<pre><code>if "house" in item:
print "house good"
elif "cat" in item:
print "cat good"
elif "dog" in item:
print "dog good"
else:
print "nothing else"... | 2 | 2016-08-11T13:47:26Z | [
"python",
"list"
] |
Pulling from List using If/Else statement - Python | 38,898,155 | <p>I want to match the correct terms from my list. Here is my code: </p>
<pre><code>stuff = ["cat", "dog", "house", "cat", "mouse"]
for item in stuff:
if "house" in item:
print "house good"
if "cat" in item:
print "cat good"
if "dog" in item:
print "dog good"
else:
prin... | -1 | 2016-08-11T13:45:21Z | 38,898,227 | <p>You should be using <code>elif</code>, like so:</p>
<pre><code>for item in stuff:
if "house" in item:
print "house good"
elif "cat" in item:
print "cat good"
elif "dog" in item:
print "dog good"
else:
print "nothing else"
</code></pre>
<p>Otherwise the <code>else</co... | 3 | 2016-08-11T13:47:43Z | [
"python",
"list"
] |
Pulling from List using If/Else statement - Python | 38,898,155 | <p>I want to match the correct terms from my list. Here is my code: </p>
<pre><code>stuff = ["cat", "dog", "house", "cat", "mouse"]
for item in stuff:
if "house" in item:
print "house good"
if "cat" in item:
print "cat good"
if "dog" in item:
print "dog good"
else:
prin... | -1 | 2016-08-11T13:45:21Z | 38,898,352 | <p>you must use elif condition like :</p>
<pre><code>stuff = ["cat", "dog", "house", "cat", "mouse"]
for item in stuff:
if "house" in item:
print ("house good")
elif "cat" in item:
print ("cat good")
elif "dog" in item:
print ("dog good")
else:
print ("nothing else")
</... | 0 | 2016-08-11T13:53:19Z | [
"python",
"list"
] |
Pulling from List using If/Else statement - Python | 38,898,155 | <p>I want to match the correct terms from my list. Here is my code: </p>
<pre><code>stuff = ["cat", "dog", "house", "cat", "mouse"]
for item in stuff:
if "house" in item:
print "house good"
if "cat" in item:
print "cat good"
if "dog" in item:
print "dog good"
else:
prin... | -1 | 2016-08-11T13:45:21Z | 38,898,608 | <p>Other answers suggest that you should be using a <code>elif</code> statement to fix your code. This is perfectly reasonable. However, I just wanted to point out that with a slight refactoring of your code you can make it simpler, more readable, and more extendable:</p>
<pre><code>stuff = ["cat", "dog", "house", "ca... | 0 | 2016-08-11T14:04:28Z | [
"python",
"list"
] |
Pulling from List using If/Else statement - Python | 38,898,155 | <p>I want to match the correct terms from my list. Here is my code: </p>
<pre><code>stuff = ["cat", "dog", "house", "cat", "mouse"]
for item in stuff:
if "house" in item:
print "house good"
if "cat" in item:
print "cat good"
if "dog" in item:
print "dog good"
else:
prin... | -1 | 2016-08-11T13:45:21Z | 38,899,023 | <p>Try not to use 'in', if I was you I will try to use '=='.</p>
<p>But judging that it is already in the list, so you won't need the 'for' part I guess, just 'if xxx in stuff'</p>
<p>Hope this helps!</p>
| 0 | 2016-08-11T14:21:28Z | [
"python",
"list"
] |
Testing sub-domains in my localhost using Django | 38,898,346 | <p>I set up django-subdomains following this <a href="http://django-subdomains.readthedocs.io/en/latest/" rel="nofollow">guide</a>.</p>
<p>I set my subdomain urlconfs as follows:</p>
<pre><code>SUBDOMAIN_URLCONFS = {
None: 'mysite.urls',
'www': 'mysite.urls',
'shop': 'mysite.urls.shop',
'blog': 'mysi... | 0 | 2016-08-11T13:53:11Z | 38,899,026 | <p>The missing part of the equation here is DNS. As far as the browser is concerned, <code>foo.example.org</code> and <code>example.org</code> are two different hostnames. The name <code>foo.example.org</code> could point to a different ip address entirely from <code>example.org</code>.</p>
<p>The relationship between... | 1 | 2016-08-11T14:21:33Z | [
"python",
"django",
".htaccess",
"django-subdomains"
] |
Refactoring Tensorflow FLAGS | 38,898,433 | <p>After using many python scripts with the same Tensorflow FLAGS, I got tired of updating multiple flags for each change and so decided to refactor <code>tf.app.flags</code> into a separate class which I could reuse across scripts. </p>
<p>However, for some strange reason, whenever I use <code>self.flags</code> in a ... | 0 | 2016-08-11T13:56:40Z | 38,902,147 | <p>It seems there's an internal method called <code>_parse_flags()</code> which is called <a href="https://github.com/tensorflow/tensorflow/blob/297ca67a8a06bb7128476761cfee8d56145ee49a/tensorflow/python/platform/flags.py#L40" rel="nofollow">on first access</a>. You could call it manually after you update it</p>
<p>IE... | 0 | 2016-08-11T16:55:39Z | [
"python",
"tensorflow"
] |
Debugging Python and C++ exposed by boost together | 38,898,459 | <p>I can debug Python code using <code>ddd -pydb prog.py</code>. All the python command line arguments can be passed too after <code>prog.py</code>. In my case, many classes have been implemented in C++ that are exposed to python using <code>boost-python</code>. I wish I could debug python code and C++ together. For ex... | 14 | 2016-08-11T13:57:43Z | 39,012,185 | <p>I found out how to debug the C++ part while running python. (realized it while reading about process ID detection in Python book..).<br>
First you run the python program which includes C++ programs. At the start of the python program, use raw_input() to make the program wait for you input. But just before that do <c... | 4 | 2016-08-18T07:23:10Z | [
"python",
"c++",
"debugging",
"boost",
"ddd-debugger"
] |
Is there a way of drawing non-canvas lines in Tkinter? | 38,898,484 | <p><p>Hi !
<p>I've been looking all over StackExchange and some other forums for an answer to my question but I couldn't find anything relevant, so here I am, posting my question.
<p>What I'm trying to do is to draw lines that are on the same layer as other Tkinter widgets. I'm currently coding an interface where certa... | 0 | 2016-08-11T13:58:33Z | 38,901,412 | <p>Your only reasonable choice for drawing lines is the canvas. Without the canvas you can simulate horizontal or vertical lines using a separator and <code>place</code>, but you can't do diagonal lines.</p>
| 0 | 2016-08-11T16:11:45Z | [
"python",
"canvas",
"tkinter",
"tkinter-canvas",
"custom-widgets"
] |
Python len not working | 38,898,586 | <p>In the code below, I am trying to use len(list) to count the number of strings in an array in each of the tags variables from the while loop. When i did a sample list parameter on the bottom, list2, it printed 5 which works, but when i did it with my real data,it was counting the characters in the array, not the num... | -4 | 2016-08-11T14:03:31Z | 38,898,642 | <p>Your list construction <code>list = "[" + tags.strip('[]') + "]"</code> creates a <code>string</code>, <strong>not</strong> a <code>list</code>. So yes, <code>len</code> works, it counts the characters in your string.</p>
<p>Your tags construction looks a bit off, you have a dictionary of data (<code>data['alerts']... | 4 | 2016-08-11T14:05:47Z | [
"python",
"list",
"python-2.7"
] |
Python len not working | 38,898,586 | <p>In the code below, I am trying to use len(list) to count the number of strings in an array in each of the tags variables from the while loop. When i did a sample list parameter on the bottom, list2, it printed 5 which works, but when i did it with my real data,it was counting the characters in the array, not the num... | -4 | 2016-08-11T14:03:31Z | 38,898,658 | <pre><code>list = "[" + tags.strip('[]') + "]"
print list
print len(list)
</code></pre>
<p>Ironically, <code>list</code> is a string, not a list. That's why calling <code>len</code> on it "was counting the characters in the array"</p>
| 1 | 2016-08-11T14:06:22Z | [
"python",
"list",
"python-2.7"
] |
Python len not working | 38,898,586 | <p>In the code below, I am trying to use len(list) to count the number of strings in an array in each of the tags variables from the while loop. When i did a sample list parameter on the bottom, list2, it printed 5 which works, but when i did it with my real data,it was counting the characters in the array, not the num... | -4 | 2016-08-11T14:03:31Z | 38,898,795 | <p>you need to make sure that your variable is a list rather than a str,
try:</p>
<pre><code>print(type(yourList))
</code></pre>
<p>if it shows that it is a str, then try this:</p>
<pre><code>len(list[yourList)
</code></pre>
<p>hope this answers your question</p>
<p>and when you want to establish a list variable, ... | 0 | 2016-08-11T14:12:05Z | [
"python",
"list",
"python-2.7"
] |
bypass known exception of mysql in python | 38,898,601 | <p>I am trying to bypass "<strong>Cannot delete or update a parent row: a foreign key constraint fails</strong>" inside my python script.
So I am planning to drop all tables but this error throws up due to inter relationship.</p>
<p>My query is I need to get this automated and i know I am gonna come with the same err... | 0 | 2016-08-11T14:04:08Z | 38,899,086 | <p>I tried the following snip and it worked, thanks anyways.</p>
<pre><code> if cham == "drop table":
db = MySQLdb.connect(host = _host, user = _user,db = _db, passwd = _pass )
cursor = db.cursor()
cursor.execute("show tables")
for i in cursor.fetchall():
... | 0 | 2016-08-11T14:24:27Z | [
"python",
"mysql-python"
] |
Python 3.4.3: os.system does not run my ping "command" | 38,898,704 | <p>I made this script to just write the ip or name of the host after clicking on it.... but in python 3.4.3 the code simply do not run the ping; I can input the ip, but it do not run the ping....</p>
<p>I've tried to enter both ways. ex.: "127.0.0.1" or 127.0.0.1</p>
<p>it run in python 2.7, but want it working in a ... | -1 | 2016-08-11T14:08:13Z | 38,898,773 | <p><code>input</code> is different between python 2.7 and python 3.</p>
<p>In python 2 it evaluates the return, I bet you enter your string between simple quotes.</p>
<p>In python 3, it returns a string (like <code>raw_input</code> did)</p>
<p>Just enter your value without quotes and it will work.</p>
| 1 | 2016-08-11T14:11:17Z | [
"python"
] |
Python 3.4.3: os.system does not run my ping "command" | 38,898,704 | <p>I made this script to just write the ip or name of the host after clicking on it.... but in python 3.4.3 the code simply do not run the ping; I can input the ip, but it do not run the ping....</p>
<p>I've tried to enter both ways. ex.: "127.0.0.1" or 127.0.0.1</p>
<p>it run in python 2.7, but want it working in a ... | -1 | 2016-08-11T14:08:13Z | 38,899,401 | <h1>Popen solution:</h1>
<pre><code>from subprocess import Popen, PIPE
p = Popen(['ping', '-c 1', 'www.google.com'], stdout=PIPE)
while True:
line = p.stdout.readline()
if not line:
break
print(line)
</code></pre>
<h1>sh.ping solution:</h1>
<pre><code>import sh
for line in sh.ping('www.google.com... | 1 | 2016-08-11T14:37:34Z | [
"python"
] |
Python 3.4.3: os.system does not run my ping "command" | 38,898,704 | <p>I made this script to just write the ip or name of the host after clicking on it.... but in python 3.4.3 the code simply do not run the ping; I can input the ip, but it do not run the ping....</p>
<p>I've tried to enter both ways. ex.: "127.0.0.1" or 127.0.0.1</p>
<p>it run in python 2.7, but want it working in a ... | -1 | 2016-08-11T14:08:13Z | 38,918,516 | <p>Actually, I give up to try it.....
I will use in python 2.7, which runs it well....</p>
<p>Thanks</p>
| 0 | 2016-08-12T12:55:35Z | [
"python"
] |
non-categorical dataframe to categorical data for seaborn plotting boxplots, swarmplots, stripplots etc | 38,898,744 | <p>Im running into a confusion with categorical data plots, which is probably because I dont really understand the concept.</p>
<p>I have a dataframe:</p>
<pre><code> A B C
0 1.438161 -0.210454 -1.983704
1 -0.283780 -0.371773 0.017580
2 0.552564 -0.610548 0.257276
3 1.931332 0.649179 -1... | 2 | 2016-08-11T14:09:27Z | 38,899,176 | <p>I think you need parameter <code>data</code>:</p>
<pre><code>sns.boxplot(data=df)
</code></pre>
<p><a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.swarmplot.html" rel="nofollow">Docs</a>:</p>
<blockquote>
<p>data : DataFrame, array, or list of arrays, optional</p>
<p>Dataset for p... | 2 | 2016-08-11T14:28:03Z | [
"python",
"pandas",
"seaborn"
] |
non-categorical dataframe to categorical data for seaborn plotting boxplots, swarmplots, stripplots etc | 38,898,744 | <p>Im running into a confusion with categorical data plots, which is probably because I dont really understand the concept.</p>
<p>I have a dataframe:</p>
<pre><code> A B C
0 1.438161 -0.210454 -1.983704
1 -0.283780 -0.371773 0.017580
2 0.552564 -0.610548 0.257276
3 1.931332 0.649179 -1... | 2 | 2016-08-11T14:09:27Z | 38,899,620 | <p>IIUC, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> to convert one of the variables into categorical format to aid in the plotting of <code>swarmplots</code> and <code>stripplots</code>.</p>
<pre><code>In [3]: df_sns = pd.melt(df, v... | 1 | 2016-08-11T14:47:16Z | [
"python",
"pandas",
"seaborn"
] |
pyNastran type error | 38,898,789 | <p>I get the following TypeError using pyNastran.
Any idea on how to solve it?
I am using python 2.6.6
Thanks</p>
<pre><code>#!/usr/bin/python
import sys
sys.path.append('/folder/six1100')
sys.path.append('/folder/pyNastran')
from pyNastran.bdf.bdf import BDF
bdf = BDF()
bdf.readBDF('file.bdf')
-> Error:
File "... | 0 | 2016-08-11T14:11:49Z | 39,023,090 | <p>I happen to work with the author of pyNastran (he is sitting right next to me). He said to post in the main GitHub discussion forum for pyNastran. I am sorry to have posted this as an answer, I do not as of yet have enough rep on Stack Overflow to add comments.</p>
| 0 | 2016-08-18T16:18:29Z | [
"python",
"nastran"
] |
Drawing circles around a certain area with opencv | 38,898,828 | <p>I am working on a code which accesses my camera, turns the output into grayscale, applies a gaussian blur finds the brightest area/pixel and circles it.
Everything but the drawing-a-circle-part works fine. The command I am trying to use does nothing for me. Does anybody have an idea?
I am working with opencv, pyth... | 0 | 2016-08-11T14:13:24Z | 38,899,041 | <p>You are trying to draw a colour circle on gray image ,
instead you can make the circle on the original colour frame</p>
<pre><code>cv2.circle(frame, maxLoc, 10, (255, 0, 0) )
cv2.imshow("spot",frame)
</code></pre>
| 0 | 2016-08-11T14:22:16Z | [
"python",
"opencv",
"numpy",
"camera",
"gaussianblur"
] |
best way to check download duration of a file from multiple urls in python (threading or async)? | 38,898,839 | <p>What is the best way to check the download duration of a file from like 50 urls? I would like to download from each file using my entire bandwidth, should i use multi threading or co-routines or just plain old synchronous way? why?</p>
<p>This is the code i use to check the download duration from a single url:</p>
... | 0 | 2016-08-11T14:13:54Z | 38,899,060 | <p>Multithreading and coroutines in Python are still restricted by the <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">Global Interpreter Lock (GIL)</a> to only run one Python instruction at a time. If Python code uses multithreading or coroutines on regular Python code that just performs a ... | 0 | 2016-08-11T14:23:11Z | [
"python",
"multithreading",
"asynchronous"
] |
'for' statements should use the format 'for x in y': while iterating over value retrieved from dictionary using django template | 38,899,059 | <p>I have a context dictionary entry <code>objectives</code> that maps objective query objects to a list of tests that belong to that objective. Example code:</p>
<pre><code>objectives = Objective.objects.filter(requirement=requirement)
context_dict["requirements"][requirement] = objectives
for objective in objective... | 0 | 2016-08-11T14:23:06Z | 38,899,218 | <p>You cannot user <code>{{...}}</code> inside the <code>{%...%}</code></p>
<p>What you can try is changing your filter to an assignment tag and using that value in the loop</p>
<pre><code>@register.assignment_tag
def get_item(dictionary, key):
return dictionary.get(key)
</code></pre>
<p>And then in your templ... | 2 | 2016-08-11T14:30:03Z | [
"python",
"django",
"dictionary"
] |
'for' statements should use the format 'for x in y': while iterating over value retrieved from dictionary using django template | 38,899,059 | <p>I have a context dictionary entry <code>objectives</code> that maps objective query objects to a list of tests that belong to that objective. Example code:</p>
<pre><code>objectives = Objective.objects.filter(requirement=requirement)
context_dict["requirements"][requirement] = objectives
for objective in objective... | 0 | 2016-08-11T14:23:06Z | 38,900,876 | <p>You already have an answer, but note that dropping the <code>{{ }}</code> tags and keeping everything else the same would have worked fine. </p>
<pre><code>{% for test in objectives|get_item:objective %}
</code></pre>
| 0 | 2016-08-11T15:44:22Z | [
"python",
"django",
"dictionary"
] |
How can I raise an exception through Tornado coroutines incorrectly called? | 38,899,114 | <p>I have a scenario with Tornado where I have a coroutine that is called from a non-coroutine or without yielding, yet I need to propagate the exception back.</p>
<p>Imagine the following methods:</p>
<pre><code>@gen.coroutine
def create_exception(with_yield):
if with_yield:
yield exception_coroutine()
... | 0 | 2016-08-11T14:25:35Z | 38,904,937 | <p>If you're curious why this isn't working, it's because no_coroutine_create_exception contains a yield statement. Therefore it's a generator function, and calling it does <em>not</em> execute its code, it only creates a generator object:</p>
<pre><code>>>> no_coroutine_create_exception(True)
<generator o... | -1 | 2016-08-11T19:48:15Z | [
"python",
"python-2.7",
"asynchronous",
"tornado"
] |
How can I raise an exception through Tornado coroutines incorrectly called? | 38,899,114 | <p>I have a scenario with Tornado where I have a coroutine that is called from a non-coroutine or without yielding, yet I need to propagate the exception back.</p>
<p>Imagine the following methods:</p>
<pre><code>@gen.coroutine
def create_exception(with_yield):
if with_yield:
yield exception_coroutine()
... | 0 | 2016-08-11T14:25:35Z | 38,928,739 | <p>What you're asking for is impossible in Python because the decision to <code>yield</code> or not is made by the calling function after the coroutine has finished. The coroutine must return without raising an exception so it can be <code>yielded</code>, and after that it is no longer possible for it to raise an excep... | 0 | 2016-08-13T02:51:45Z | [
"python",
"python-2.7",
"asynchronous",
"tornado"
] |
IntelliJ + Python plugin: Python remote interpreter gets created without classpath, does not work | 38,899,173 | <p>When I create a new remote Python interpreter, IntelliJ doesn't find any dependencies to my code and doesn't seem to index any libraries. Most of the code is red. I think I've pinpointed that to the "classpath" being completely empty, which is unlike some other Python SDKs that I have added (local ones). Some of the... | 1 | 2016-08-11T14:27:53Z | 39,558,752 | <p>As a workaround, I copied every entry from the local python interpreter classpath to the remote one and everything seems to work</p>
<p>Edit:</p>
<p>Actually, I don't know what triggered it, but some days after I wrote this, I noticed that IDEA started downloading source files from the server. I went to the interp... | 1 | 2016-09-18T14:31:18Z | [
"python",
"intellij-idea"
] |
Python performing calculations while comparing dictionaries | 38,899,178 | <p>I am new to Python and am trying to perform counts and calculations by comparing two dictionaries but having trouble presenting it together. Is there a way to perform the below during my first iteration of printing the keys and values together?</p>
<p>I would like to:</p>
<p>1.) Check if a key in dictionary x is i... | 1 | 2016-08-11T14:28:08Z | 38,899,628 | <p>Here's one option:</p>
<pre><code>from collections import namedtuple
trained = {'Dog': 4, 'Cat': 3, 'Bird': 1, 'Fish': 12, 'Mouse': 19}
untrained = {'Cat': 2, 'Mouse': 7, 'Dog': 4}
Score = namedtuple('Score', ('total', 'percent', 'na... | 1 | 2016-08-11T14:47:36Z | [
"python",
"dictionary"
] |
Merge dataframes without matching column | 38,899,341 | <p>I have the following two dataframes:</p>
<pre><code>df1:
column_01 value_01
aaa 1
bbb 2
df2:
column_02 value_02
ccc 3
ddd 4
</code></pre>
<p>I need to merge the dataframes such that the rows in <code>df1</code> are duplicated to contain a row for every row in <code>df2</code>. ... | 2 | 2016-08-11T14:34:51Z | 38,899,384 | <p>You can use create new columns with some scalar value and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> by these columns:</p>
<pre><code>df1['one'] = 1
df2['one'] = 1
print (pd.merge(df1, df2, on='one').drop('one', axis=1))
column_01 ... | 2 | 2016-08-11T14:36:53Z | [
"python",
"pandas",
"dataframe",
"merge",
"cross-join"
] |
Python, Pyautogui, and CTRL-C | 38,899,566 | <p>I am attempting to complete a simple process of opening a web/browser based document, selecting a field within said document, and then copying it so that it goes into my operating system's clipboard. Here's the specs :</p>
<p>Windows 7
Google Chrome ( latest stable )
Python 3.5
pyautogui for keyboard/mouse control... | 0 | 2016-08-11T14:44:43Z | 39,489,938 | <p>I have also discovered this issue on a different automation script, and have been working on troubleshooting it for several days. I'm also on Python 3.5 and Windows 7. I can rule out that it has anything to do with Google Chrome, as my particular script is actually working with SAP.</p>
<p>The documentation for pya... | 1 | 2016-09-14T12:00:58Z | [
"python"
] |
How to round floats to scaled integers? | 38,899,592 | <p>to further explain my title: I have an array of floats which I want to round, HOWEVER, I want to round the numbers to a number that isn't the closest integer. For example, let's say I want the numbers to be rounded to the nearest integer that is a multiple of 2. This is what I have:</p>
<pre><code>Temp = np.around(... | 2 | 2016-08-11T14:45:55Z | 38,899,846 | <p>Following is one way of doing it:</p>
<pre><code>import math
data = [0.9, 1.1, 10.2, 7.4]
rounded_numbers = []
for num in data:
rounded_up_num = math.ceil(num)
if rounded_up_num % 2 == 0:
rounded_num = rounded_up_num
else:
rounded_num = math.floor(num)
rounded_numbers.append(in... | 1 | 2016-08-11T14:56:17Z | [
"python",
"math",
"floating-point",
"rounding"
] |
How to round floats to scaled integers? | 38,899,592 | <p>to further explain my title: I have an array of floats which I want to round, HOWEVER, I want to round the numbers to a number that isn't the closest integer. For example, let's say I want the numbers to be rounded to the nearest integer that is a multiple of 2. This is what I have:</p>
<pre><code>Temp = np.around(... | 2 | 2016-08-11T14:45:55Z | 38,899,994 | <p>A multiple of two is straightforward:</p>
<pre><code>x = np.array([0.9, 1.1, 10.2, 7.4])
2*np.round(x/2) # array([ 0., 2., 10., 8.])
</code></pre>
<p>But there's not a universal approach to this. For example there's no obvoius "round to the nearest Fibonacci number". Consider the formula for multiple of... | 3 | 2016-08-11T15:03:38Z | [
"python",
"math",
"floating-point",
"rounding"
] |
Turtle Graphics not Working on Pycharm | 38,899,612 | <p>I have been trying to use turtle python graphics in Pycharm Community Edition, but it keeps giving me an error for import turtle. My code is so far:</p>
<pre><code> import turtle
t=turtle.Pen()
</code></pre>
<p>And it gives me an error for that.
Then I do something like:</p>
<pre><code> t.forward(50)
... | -2 | 2016-08-11T14:46:58Z | 38,910,998 | <p>There's nothing wrong with your code when run from the command line with Python 3 or Python 2. You didn't name your own program file "<strong>turtle.py</strong>" by any chance did you? If so, rename it to something else and try again.</p>
<pre><code>import turtle
t = turtle.Pen()
t.speed('fast')
t.forward(50)
... | 0 | 2016-08-12T06:05:29Z | [
"python",
"pycharm",
"turtle-graphics"
] |
Continue isnt working properly | 38,899,696 | <p>I do need help in solving my code.
Below python code 'continue' is not working properly</p>
<pre><code>dicemp = {'12345':''}
while(1):
choice = int(input("Please enter your choice\n"))
if (choice == 1):
empno = input("Enter employee number: ")
for i in dicemp.keys():
if i == em... | -4 | 2016-08-11T14:50:16Z | 38,899,780 | <p>Your <code>continue</code> is moving the <code>for</code> loop on to its next iteration, which would have happened anyway. If you need to continue the outer loop, you can do something like this:</p>
<pre><code>while True:
choice = int(input("Please enter your choice\n"))
if choice == 1:
empno = inp... | 2 | 2016-08-11T14:53:10Z | [
"python",
"while-loop",
"continue"
] |
How to display special characters in the CMD part of python | 38,899,740 | <p>I have a python program that returns a large amount of info from an API. The info contains special characters like the TM sign and the â
symbol. When the code is run in the IDLE interface it works exactly as it should returning all information however when the program is run in the CMD-Like interface it crashes be... | 1 | 2016-08-11T14:51:32Z | 39,754,124 | <p>CMD can not display those characters you must convert them</p>
| -1 | 2016-09-28T17:32:04Z | [
"python",
"special-characters"
] |
Process request thread error with Flask Application? | 38,899,790 | <p>This might be a long shot, but here's the error that i'm getting:</p>
<pre><code> File "/home/MY NAME/anaconda/lib/python2.7/SocketServer.py", line 596, in process_request_thread
self.finish_request(request, client_address)
File "/home/MY NAME/anaconda/lib/python2.7/SocketServer.py", line 331, in finish_requ... | 12 | 2016-08-11T14:53:47Z | 38,946,605 | <p>I had similar problem and having a proper web server solved the issue. I used UWSGI with nginx</p>
| 1 | 2016-08-14T21:01:41Z | [
"python",
"flask",
"geopy"
] |
Process request thread error with Flask Application? | 38,899,790 | <p>This might be a long shot, but here's the error that i'm getting:</p>
<pre><code> File "/home/MY NAME/anaconda/lib/python2.7/SocketServer.py", line 596, in process_request_thread
self.finish_request(request, client_address)
File "/home/MY NAME/anaconda/lib/python2.7/SocketServer.py", line 331, in finish_requ... | 12 | 2016-08-11T14:53:47Z | 38,977,386 | <p>Sounds like it is running out of file handles (default limit is 1024 for regular users) which you can check by running <code>grep 'open' /proc/<webapp pid></code> for limit and <code>ls -1 /proc/<pid>/fd | wc -l</code> for currently open file handles.</p>
<p>I think your code is not sending a correct re... | 3 | 2016-08-16T14:18:44Z | [
"python",
"flask",
"geopy"
] |
Browsermob HTTPS requests with Auth Headers | 38,900,002 | <p>I'm trying to use Browsermob proxy to capture information about requests.
Have it working for HTTP requests and HTTPS requests that don't have an authorization header.</p>
<pre><code> if(product == 'Product'):
headers = {
'Authorization': 'Bearer %s' % accessToken()
}
http_proxy ... | 1 | 2016-08-11T15:04:10Z | 39,539,680 | <p>From the error log, I'm guessing it's one of two problems:</p>
<ol>
<li><p>a bug in browsermob. Try upgrading to a newer version</p></li>
<li><p>a mismatch between the domain browsermob thinks it's running against, and the domain you're connecting to. try switching to your explicit ip as the hostname - ie: "127.0.0... | 0 | 2016-09-16T20:31:41Z | [
"python",
"proxy",
"request",
"browsermob",
"browsermob-proxy"
] |
Python Writing lists to csv | 38,900,013 | <p>how can i write the results which are in the print statement to a csv file, every time the loop runs the result to be added to the next row. The result contains a lists.</p>
<pre><code>def func_high(i):
swing_low = data_file.iloc[i].Low
date = data_file.iloc[i].Date
while i < len(data_file):
... | 1 | 2016-08-11T15:04:48Z | 38,900,096 | <p>If the result is a pandas <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#writing-to-csv-format" rel="nofollow">Series or DataFrame</a> you should just be using the <code>to_csv</code> method.</p>
| 0 | 2016-08-11T15:08:52Z | [
"python",
"csv",
"pandas"
] |
Python Writing lists to csv | 38,900,013 | <p>how can i write the results which are in the print statement to a csv file, every time the loop runs the result to be added to the next row. The result contains a lists.</p>
<pre><code>def func_high(i):
swing_low = data_file.iloc[i].Low
date = data_file.iloc[i].Date
while i < len(data_file):
... | 1 | 2016-08-11T15:04:48Z | 38,900,780 | <p>The easiest is to use Pandas.</p>
<pre><code>import pandas as pd
mylist = [1, 2, 3, 4]
df = pd.Series(mylist)
df.to_csv('filename.csv')
</code></pre>
<p>You have to turn the list into a Series/dataframe.</p>
| 0 | 2016-08-11T15:39:53Z | [
"python",
"csv",
"pandas"
] |
Python Writing lists to csv | 38,900,013 | <p>how can i write the results which are in the print statement to a csv file, every time the loop runs the result to be added to the next row. The result contains a lists.</p>
<pre><code>def func_high(i):
swing_low = data_file.iloc[i].Low
date = data_file.iloc[i].Date
while i < len(data_file):
... | 1 | 2016-08-11T15:04:48Z | 38,903,367 | <p>You could change <code>print</code> to <code>yield</code>, and use a <code>csv.writer</code> (I made a few other edits to your function so I could follow the logic easier).</p>
<pre><code>import csv
i = 0
def func_high(i):
swing_low = data_file.iloc[i].Low
date = data_file.iloc[i].Date
while i <... | 1 | 2016-08-11T18:09:58Z | [
"python",
"csv",
"pandas"
] |
Python Writing lists to csv | 38,900,013 | <p>how can i write the results which are in the print statement to a csv file, every time the loop runs the result to be added to the next row. The result contains a lists.</p>
<pre><code>def func_high(i):
swing_low = data_file.iloc[i].Low
date = data_file.iloc[i].Date
while i < len(data_file):
... | 1 | 2016-08-11T15:04:48Z | 38,921,934 | <p>If you're using a pandas data frame, see one of the other answers that deals with that. If not, using a CSV writer can be good too. However, for completeness, I'll point out that sometimes the simplest approach is to just write the data directly. Not knowing what goes into the data structures in your sample code, I'... | 0 | 2016-08-12T15:49:17Z | [
"python",
"csv",
"pandas"
] |
Two implementations of a module with a same name-import problems | 38,900,099 | <p>I use two libraries built on top of caffe: crf-rnn(<a href="https://github.com/torrvision/crfasrnn/tree/master/python-scripts" rel="nofollow">https://github.com/torrvision/crfasrnn/tree/master/python-scripts</a>) and hed(<a href="https://github.com/s9xie/hed/blob/master/examples/hed/" rel="nofollow">https://github.c... | 1 | 2016-08-11T15:08:58Z | 38,900,215 | <p>I have seen your last edit, and I must say that changing/tampering with python <code>sys.path</code> is necessary in your context but not sufficient here: you have to rename one of the <code>caffe</code> packages.</p>
<p>Ex: if the <code>caffe</code> package is a directory called <code>caffe</code> containing a <co... | 1 | 2016-08-11T15:14:23Z | [
"python",
"import",
"package",
"caffe"
] |
Two implementations of a module with a same name-import problems | 38,900,099 | <p>I use two libraries built on top of caffe: crf-rnn(<a href="https://github.com/torrvision/crfasrnn/tree/master/python-scripts" rel="nofollow">https://github.com/torrvision/crfasrnn/tree/master/python-scripts</a>) and hed(<a href="https://github.com/s9xie/hed/blob/master/examples/hed/" rel="nofollow">https://github.c... | 1 | 2016-08-11T15:08:58Z | 39,042,054 | <p>OK, so I found the least sophisticated solution possible: I wrote two scripts, one for crf-rnn producing the blobs that I ran on the full dataset just once and stored the output. </p>
<p>Then I wrote the second script, with hed edge detector that I use every time I detect and track objects.</p>
| 0 | 2016-08-19T14:53:27Z | [
"python",
"import",
"package",
"caffe"
] |
Scikit-learn Imputer Reducing Dimensions | 38,900,132 | <p>I have a dataframe with 332 columns. I want to impute values to be able to use scikit-learn's decision tree classifier. My problem is that the column of the resulting data from imputer function is only 330. </p>
<pre><code>from sklearn.preprocessing import Imputer
imp = Imputer(missing_values='NaN', strategy='mean'... | 0 | 2016-08-11T15:10:23Z | 38,904,266 | <p>According to the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html" rel="nofollow">documentation of <code>sklearn.preprocessing.Imputer</code></a>:</p>
<blockquote>
<p>When axis=0, columns which only contained missing values at fit are discarded upon transform.</p>
</blo... | 0 | 2016-08-11T19:03:57Z | [
"python",
"scikit-learn"
] |
Tic Tac toe game keeps getting invalid syntax | 38,900,167 | <p>I was trying to make a tic tac toe game in python and invalid syntax keeps coming up on the line with <code>first.upper()</code> after the "1". I even moved the code around and it was still after "1". How do I fix my code?</p>
<pre><code>first == input("Would u like to go first? 1 is Yes 2 is No \n")
if first.uppe... | -1 | 2016-08-11T15:12:21Z | 38,900,220 | <p>In python, whenever you use an "if" statement, you must follow it up with ':' before going to the next line.
So it should be :</p>
<pre><code>if first.upper() == "1":
place == input("You are X where do u want to place it? \n")
</code></pre>
| 3 | 2016-08-11T15:14:41Z | [
"python"
] |
Tic Tac toe game keeps getting invalid syntax | 38,900,167 | <p>I was trying to make a tic tac toe game in python and invalid syntax keeps coming up on the line with <code>first.upper()</code> after the "1". I even moved the code around and it was still after "1". How do I fix my code?</p>
<pre><code>first == input("Would u like to go first? 1 is Yes 2 is No \n")
if first.uppe... | -1 | 2016-08-11T15:12:21Z | 38,900,230 | <pre><code>first = input("Would u like to go first? 1 is Yes 2 is No \n")
if first.upper() == 1:
place = input("You are X where do u want to place it? \n")
</code></pre>
<p>Try that</p>
| 0 | 2016-08-11T15:15:08Z | [
"python"
] |
Python recognizing one directory as module but not another? | 38,900,185 | <p>My project looks like this:</p>
<pre><code>W:\a\lot\of\stuff\Automation
|__ __init__.py
|__ A
| |_ __init__.py
| |_ aLotOfFiles.py
|
|__ B
| |_ __init__.py
| |_ aLotOfFiles.py
|
|__ C
|_ __init__.py
|_ myFile.py
</code></pre>
<p>where I'm working on <code>myFile.py</code>. In it I am using a lot of... | 0 | 2016-08-11T15:13:14Z | 38,901,265 | <p>Found the problem.</p>
<p>Apparently there was an older version of the same workspace somewhere else higher up in the path hierarchy, and it worked when I used modules which were also there, but not when I used new ones... </p>
| 0 | 2016-08-11T16:04:55Z | [
"python",
"python-2.7",
"python-import"
] |
Flattening a list with lists and items: List comprehension with nested for loops and if else condition | 38,900,235 | <p>I want to flatten a list of lists and items.
The below code works only for a list of lists</p>
<pre><code>def flatten(li):
return [item for sublist in li for item in sublist]
</code></pre>
<p>It would work on </p>
<pre><code>[[1],[2,3],[4]]
</code></pre>
<p>but not</p>
<pre><code>[[1],[2,3],[4],5]
</code></pre>... | 1 | 2016-08-11T15:15:15Z | 38,900,498 | <pre><code>from itertools import chain
def flatten(li):
if isinstance(li, list):
li = [flatten(x) for x in li]
return list(chain(*li))
else:
return [li]
def flatten2(li):
return list(chain(*[[x] if not isinstance(x, list) else flatten2(x) for x in li]))
</code></pre>
<p>it even wo... | 0 | 2016-08-11T15:26:56Z | [
"python",
"list"
] |
Flattening a list with lists and items: List comprehension with nested for loops and if else condition | 38,900,235 | <p>I want to flatten a list of lists and items.
The below code works only for a list of lists</p>
<pre><code>def flatten(li):
return [item for sublist in li for item in sublist]
</code></pre>
<p>It would work on </p>
<pre><code>[[1],[2,3],[4]]
</code></pre>
<p>but not</p>
<pre><code>[[1],[2,3],[4],5]
</code></pre>... | 1 | 2016-08-11T15:15:15Z | 38,900,676 | <pre><code>def flatten(li):
return [ x for x in li if isinstance(x,int) ] + [item for sublist in li if isinstance(sublist,list) for item in sublist]
</code></pre>
| 1 | 2016-08-11T15:35:01Z | [
"python",
"list"
] |
Flattening a list with lists and items: List comprehension with nested for loops and if else condition | 38,900,235 | <p>I want to flatten a list of lists and items.
The below code works only for a list of lists</p>
<pre><code>def flatten(li):
return [item for sublist in li for item in sublist]
</code></pre>
<p>It would work on </p>
<pre><code>[[1],[2,3],[4]]
</code></pre>
<p>but not</p>
<pre><code>[[1],[2,3],[4],5]
</code></pre>... | 1 | 2016-08-11T15:15:15Z | 38,901,454 | <p>As other users have suggested, using a recursive function to flatten the list works really well in this case. But here is a one line list comprehension (<em>albeit not the most efficient</em>).</p>
<pre><code>from collections import Iterable
l = [{},2,[41,123,'str'],32,(4324),3,1,(212,3213),[2]]
print [num for subi... | 2 | 2016-08-11T16:14:28Z | [
"python",
"list"
] |
Can't download mldata of sklearn | 38,900,246 | <pre><code>from sklearn.datasets import fetch_mldata
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
X_digits, _,_, Y_digits = fetch_mldata("MNIST Original").values()`
</code></pre>
<p>After running it, I get:</p>
<p><img src="http://i.stack.imgur.com/mGT5A.jpg" alt="Image description"></p>
| 0 | 2016-08-11T15:15:40Z | 38,934,955 | <p>I guess that the problem is temporary and related to mldata.org server. So try again later.</p>
| 0 | 2016-08-13T16:51:42Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Can't download mldata of sklearn | 38,900,246 | <pre><code>from sklearn.datasets import fetch_mldata
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
X_digits, _,_, Y_digits = fetch_mldata("MNIST Original").values()`
</code></pre>
<p>After running it, I get:</p>
<p><img src="http://i.stack.imgur.com/mGT5A.jpg" alt="Image description"></p>
| 0 | 2016-08-11T15:15:40Z | 39,051,071 | <p>So, it's the problem of the sever.
Next morning I can download...</p>
<p>Another way, after I downloading it I find the datafile name is <em>mnist-original.mat</em>, so you can go to gihub.com and search for the name to down the data file.</p>
| 0 | 2016-08-20T06:14:40Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Removing the text only if it is between the two strings in a file using sed or python | 38,900,308 | <p>I've to remove text between to words in a file.</p>
<ol>
<li>Ex: if the two strings are hello, world and the string is <code>"hey!! hello beautiful world"</code> ,</li>
</ol>
<p>my expected output : <code>"hey!! "</code>.</p>
<p>I could achieve this using</p>
<pre><code>re.sub('\nhello.*?world','', i , flags=re... | -2 | 2016-08-11T15:18:35Z | 38,900,437 | <p>You can use this negative lookahead pattern in <code>python</code> (sed doesn't support look arounds):</p>
<pre><code>regex = re.compile(r'hello(?:(?!hello).)*?world', re.DOTALL)
str = re.sub(regex, '', str)
</code></pre>
<p><a href="https://regex101.com/r/rO9vV2/2" rel="nofollow">RegEx Demo</a></p>
<p><code>(?:... | 0 | 2016-08-11T15:24:25Z | [
"python",
"bash",
"sed"
] |
Removing the text only if it is between the two strings in a file using sed or python | 38,900,308 | <p>I've to remove text between to words in a file.</p>
<ol>
<li>Ex: if the two strings are hello, world and the string is <code>"hey!! hello beautiful world"</code> ,</li>
</ol>
<p>my expected output : <code>"hey!! "</code>.</p>
<p>I could achieve this using</p>
<pre><code>re.sub('\nhello.*?world','', i , flags=re... | -2 | 2016-08-11T15:18:35Z | 38,906,660 | <p>sed is for simple subsitutions on individual lines, that is all. If you want to do it with a standard UNIX tool though then there's awk:</p>
<pre><code>$ cat file
"hey!! hello beautiful world"
"hey!! hello, how are you? hello beautiful world, bye"
$ awk -v RS='world' -v ORS= 'match($0,/(.*)hello/,a){$0=a[1]}1' fil... | 0 | 2016-08-11T21:49:26Z | [
"python",
"bash",
"sed"
] |
Python GetHostId.py getting sys.argv[1] IndexError: list index out of range | 38,900,341 | <p>i am working on a python script to be a multi tool for getting DNS information on servers in a enterprise env. so far the script i have is using python 3.5. i am using argparse for creating command line options, which i am trying to create an if/ elif / else statement which contains the different selections. the mai... | 0 | 2016-08-11T15:20:11Z | 38,900,602 | <p>I've had this problem long time ago. To fix this I've changed</p>
<pre><code>parser.add_argument("-a", "--address", default="fqdn", help="Gets IP address from host name.")
</code></pre>
<p>in</p>
<pre><code>parser.add_argument("-a", "--address", default="fqdn", help="Gets IP address from host name.", dest=ipfromh... | 0 | 2016-08-11T15:31:28Z | [
"python",
"network-programming"
] |
Convert complex NumPy array into (n, 2)-array of real and imaginary parts | 38,900,344 | <p>I have a complex-valued NumPy array that I'd like to convert into a contiguous NumPy array with real and imaginary parts separate.</p>
<p>This</p>
<pre><code>import numpy
u = numpy.array([
1.0 + 2.0j,
2.0 + 4.0j,
3.0 + 6.0j,
4.0 + 8.0j
])
u2 = numpy.ascontiguousarray(numpy.vstack((u.real, u... | 0 | 2016-08-11T15:20:14Z | 38,901,020 | <p>You can use <code>dstack</code>:</p>
<pre><code>np.dstack((u.real, u.imag))[0]
#Out[210]:
#array([[ 1., 2.],
# [ 2., 4.],
# [ 3., 6.],
# [ 4., 8.]])
</code></pre>
| 1 | 2016-08-11T15:51:47Z | [
"python",
"arrays",
"numpy"
] |
Convert complex NumPy array into (n, 2)-array of real and imaginary parts | 38,900,344 | <p>I have a complex-valued NumPy array that I'd like to convert into a contiguous NumPy array with real and imaginary parts separate.</p>
<p>This</p>
<pre><code>import numpy
u = numpy.array([
1.0 + 2.0j,
2.0 + 4.0j,
3.0 + 6.0j,
4.0 + 8.0j
])
u2 = numpy.ascontiguousarray(numpy.vstack((u.real, u... | 0 | 2016-08-11T15:20:14Z | 38,901,102 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html" rel="nofollow"><code>column_stack</code></a> and stack the two 1-D arrays as columns to make a single 2D array.</p>
<pre><code>In [9]: np.column_stack((u.real,u.imag))
Out[9]:
array([[ 1., 2.],
[ 2., 4.],
... | 3 | 2016-08-11T15:56:15Z | [
"python",
"arrays",
"numpy"
] |
Convert complex NumPy array into (n, 2)-array of real and imaginary parts | 38,900,344 | <p>I have a complex-valued NumPy array that I'd like to convert into a contiguous NumPy array with real and imaginary parts separate.</p>
<p>This</p>
<pre><code>import numpy
u = numpy.array([
1.0 + 2.0j,
2.0 + 4.0j,
3.0 + 6.0j,
4.0 + 8.0j
])
u2 = numpy.ascontiguousarray(numpy.vstack((u.real, u... | 0 | 2016-08-11T15:20:14Z | 38,902,227 | <p>None of the alternatives are <code>native</code> or save on reshape, transposes etc.</p>
<p>For example internally <code>column_stack</code> converts its inputs to 2d 'column' arrays. Effectively it is doing</p>
<pre><code>In [1171]: np.concatenate((np.array(u.real,ndmin=2).T,np.array(u.imag,ndmin=2).T),axis=1)
O... | 1 | 2016-08-11T17:00:59Z | [
"python",
"arrays",
"numpy"
] |
Printing a non concordant position within a string | 38,900,468 | <p>I am writing a program that analyzes and parses consensus sequences. I have successfully gotten the analyzing and parsing to work and the program tells me whether two sequences are concordant or not. </p>
<p>I want to add an additional feature, if the two sequences are not concordant, I want it to tell me the posit... | 0 | 2016-08-11T15:25:39Z | 38,900,733 | <p>In your else statement you could loop through the sequence string and then print the index when the characters don't match.</p>
<p>Something like:</p>
<pre><code>else:
for i in range(0, len(h1)):
if h1[i] == h2[i]:
continue
else:
print i
break
</code></pre>
| 0 | 2016-08-11T15:37:33Z | [
"python",
"string",
"python-2.7",
"printing",
"position"
] |
How to reduce the number of samples in audio data array using python | 38,900,475 | <p>I am plotting an audio samples amplitude at every frame present in that sample something like this:</p>
<pre><code>sound = AudioSegment.from_mp3("test.mp3")
print(len(sound))
print(len(sound.raw_data))
data = np.fromstring(sound.raw_data, dtype=np.int16)
left, right = data[0::2], data[1::2]
plt.plot(left)
</code></... | 0 | 2016-08-11T15:25:53Z | 38,919,019 | <p>In pydub, <code>len(sound)</code> is the duration in milliseconds, where <code>len(sound.raw_data)</code> would be the number of bytes of total audio data. </p>
<p>If you are working with CD-quality sound (44.1kHz, 16 bit, stereo) you would expect each millisecond to be roughly 44 samples (44100 / 1000), and two by... | 0 | 2016-08-12T13:20:15Z | [
"python",
"numpy",
"audio",
"matplotlib",
"pydub"
] |
How to choose the features that describe x% of all information in data while using Incremental principal components analysis (IPCA)? | 38,900,495 | <p>I'd like to use the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.IncrementalPCA.html#sklearn.decomposition.IncrementalPCA" rel="nofollow">Incremental principal components analysis</a> (IPCA) to reduce my feature space such that it contains x% of information.</p>
<p>I would use the... | 0 | 2016-08-11T15:26:41Z | 38,907,564 | <p>You can get the percentage of explained variance from each of the components of your PCA using <code>explained_variance_ratio_</code>. For example in the iris dataset, the first 2 principal components account for 98% of the variance in the data:</p>
<pre><code>import numpy as np
from sklearn import decomposition
fr... | 0 | 2016-08-11T23:22:43Z | [
"python",
"machine-learning",
"scikit-learn",
"pca"
] |
How to create a new color image with python Imaging? | 38,900,511 | <p>I want to create a new image, with color in background. </p>
<p>This working: </p>
<pre><code>img = Image.new('RGB', (width,height), "red")
</code></pre>
<p>But I want to customize the color. , when I change "red" by "(228,150,150) it doesn't working.... </p>
<p>Have you an idea to do this?</p>
| 0 | 2016-08-11T15:27:19Z | 38,900,699 | <p>This is working for me. Note that the color tuple is not between quotes.</p>
<pre><code>from PIL import Image
img = Image.new('RGB', (300, 200), (228, 150, 150))
img.show()
</code></pre>
<p>If it does not work for you, which version of Python and which version of PIL are you using?</p>
| 0 | 2016-08-11T15:36:00Z | [
"python",
"python-imaging-library"
] |
python - decorate a generator | 38,900,512 | <p>I have a function in 2 different version which read a large file (I make it simple here and read a very small excel file). </p>
<p><code>Version 1:</code> Read the whole file and return the list of rows<br>
<code>Version 2:</code> Read it line by line with help of generator</p>
<p>I want to decorate the output ... | 0 | 2016-08-11T15:27:19Z | 38,903,417 | <p>decorator are suppose to work a taking the result of the function manipulate it and give the new result, so knowing what is the result is the key, in this case, for that example the result is <code>[['val11', 'val12', 'val13'], ['val21', 'val22', 'val23']]</code> for version 1 and a generator with the elements of th... | 1 | 2016-08-11T18:12:46Z | [
"python",
"generator",
"decorator"
] |
Referring capture group in re.match() in python | 38,900,564 | <p>Hi this is the string I want to match</p>
<p><code>mystr = "mykey/20161010/20161010"</code></p>
<p>so far my <code>regex</code> is like this</p>
<p><code>re.match("mykey/([2-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9])/[.]*", mystr)</code></p>
<p>As you can see, I am using One <code>Capture group</code>. I want to rep... | 0 | 2016-08-11T15:29:17Z | 38,900,684 | <pre><code>mykey\/([2-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9])\/\1
</code></pre>
<p>Use <code>\1</code> - to capture the exact match produced by the first capturing group which is <code>[2-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9]</code> in this case.</p>
<p>Shorter version of the same would be </p>
<pre><code>mykey\/([2-... | 2 | 2016-08-11T15:35:17Z | [
"python",
"regex",
"python-2.7"
] |
python-tarantool call parameters | 38,900,621 | <p>I want to call box.space.auth_user:auto_increment{"8", 7, 7, 7} from python script.
This is what I do in python</p>
<pre><code>import tarantool
connection = tarantool.connect('127.0.0.1', 3303)
connection.call('box.space.auth_user:auto_increment', ("8", 7, 7, 7))
</code></pre>
<p>And then I get the error:</p>
<pr... | 1 | 2016-08-11T15:32:26Z | 39,185,623 | <p>It's not a bug, please use <code>[["8", 7, 7, 7]]</code> or <code>(("8", 7, 7, 7), )</code>.</p>
<pre><code>In [4]: connection.call('box.space.auth_user:auto_increment', [["8", 7, 7, 7]])
Out[4]:
- [1, '8', 7, 7, 7]
</code></pre>
<p>tarantool-python uses array to show that it's arguments, so it was analog for <cod... | 0 | 2016-08-27T20:49:39Z | [
"python",
"call",
"tarantool"
] |
Converting a list of list into a dictionary based on common values in python | 38,900,637 | <p>I have a list of list in python as follows:</p>
<pre><code>a = [['John', 24, 'teacher'],['Mary',23,'clerk'],['Vinny', 21, 'teacher'], ['Laura',32, 'clerk']]
</code></pre>
<p>The idea is to create a dict on the basis of their occupation as follows:</p>
<pre><code>b = {'teacher': {'John_24': 'true', 'Vinny_21' 'tru... | 1 | 2016-08-11T15:32:51Z | 38,900,759 | <p>You can use a defaultdict:</p>
<pre><code>a = [['John', 24, 'teacher'],['Mary',23,'clerk'],['Vinny', 21, 'teacher'], ['Laura',32, 'clerk']]
from collections import defaultdict
dct = defaultdict(defaultdict)
for name, age, occ in a:
dct[occ][name + "_" + age] = "true"
</code></pre>
<p>Output:</p>
<pre><co... | 2 | 2016-08-11T15:38:42Z | [
"python",
"list",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.