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 |
|---|---|---|---|---|---|---|---|---|---|
When will python while loop break?
| 39,312,493
|
<p>I'm new to python or coding in general. And encountered some while loop question in the following code.</p>
<hr>
<pre><code>a = int(input('input a number here: '))
def largest_factor(x):
factor = x - 1
while factor > 0:
if x % factor == 0:
return factor
factor -= 1
print(factor)
largest_factor(a)
</code></pre>
<hr>
<p>I'm using python 3.5, and in my understanding, the loop will not break until 0 > 0, so I put the print(factor) to exam that, however, it stopped at the largest factor(e.g. when x = 100, factor prints from 99 all the way to 50, and stopped), and did not reach 0. Is the return statement killed the while loop? Thank you for your time.</p>
| -1
|
2016-09-04T00:24:15Z
| 39,312,671
|
<p>There are two ways to leave this loop, waiting until the while statement terminates or by returning the factor.</p>
| 0
|
2016-09-04T01:03:52Z
|
[
"python",
"python-3.x"
] |
When will python while loop break?
| 39,312,493
|
<p>I'm new to python or coding in general. And encountered some while loop question in the following code.</p>
<hr>
<pre><code>a = int(input('input a number here: '))
def largest_factor(x):
factor = x - 1
while factor > 0:
if x % factor == 0:
return factor
factor -= 1
print(factor)
largest_factor(a)
</code></pre>
<hr>
<p>I'm using python 3.5, and in my understanding, the loop will not break until 0 > 0, so I put the print(factor) to exam that, however, it stopped at the largest factor(e.g. when x = 100, factor prints from 99 all the way to 50, and stopped), and did not reach 0. Is the return statement killed the while loop? Thank you for your time.</p>
| -1
|
2016-09-04T00:24:15Z
| 39,313,354
|
<p>Your assumption is correct. Once the loop hits the return statement, the function will end. Since 100 is divisible by 50, the loop ends with the function ending.</p>
| 0
|
2016-09-04T03:45:33Z
|
[
"python",
"python-3.x"
] |
Mock property return value gets overridden when instantiating mock object
| 39,312,530
|
<h2>Background</h2>
<p>I'm trying to set up a test fixture for an application I'm writing in which one of my classes is replaced with a mock. I'm happy to leave most of the attributes of the mock class as the default <code>MagicMock</code> instances (where I'm only interested in making assertions about their usage), but the class also has a property that I want to provide a specific return value for.</p>
<p>For reference, this is the outline of the class I'm trying to patch:</p>
<pre><code>class CommunicationService(object):
def __init__(self):
self.__received_response = Subject()
@property
def received_response(self):
return self.__received_response
def establish_communication(self, hostname: str, port: int) -> None:
pass
def send_request(self, request: str) -> None:
pass
</code></pre>
<h2>Problem</h2>
<p>The difficulty I'm having is that when I patch <code>CommunicationService</code>, I also try to set a <code>PropertyMock</code> for the <code>received_response</code> attribute that will return a specific value. When I instantiate this class in my production code, however, I'm finding that calls to <code>CommunicationService.received_response</code> are returning the default <code>MagicMock</code> instances instead of the specific value I want them to return.</p>
<p>During test setup, I do the following:</p>
<pre><code>context.mock_comms_exit_stack = ExitStack()
context.mock_comms = context.mock_comms_exit_stack.enter_context(
patch('testcube.comms.CommunicationService', spec=True))
# Make 'received_response' observers subscribe to a mock subject.
context.mock_received_response_subject = Subject()
type(context.mock_comms).received_response = PropertyMock(return_value=context.mock_received_response_subject)
# Reload TestCube module to make it import the mock communications class.
reload_testcube_module(context)
</code></pre>
<p>In my production code (invoked after performing this setup):</p>
<pre><code># Establish communication with TestCube Web Service.
comms = CommunicationService()
comms.establish_communication(hostname, port)
# Wire plugins with communications service.
for plugin in context.command.plugins:
plugin.on_response = comms.received_response
plugin.request_generated.subscribe(comms.send_request)
</code></pre>
<p>I expect <code>comms.received_response</code> to be an instance of <code>Subject</code> (the return value of the property mock). However, instead I get the following: </p>
<pre><code><MagicMock name='CommunicationService().received_response' id='4580209944'>
</code></pre>
<p>The problem seems to be that the mock property on the instance returned from the patch method works fine, but <em>mock properties get messed up when creating a new instance of the patched class</em>.</p>
<h2>SSCCE</h2>
<p>I believe that the snippet below captures the essence of this problem. If there's a way to modify the script below to make it so that <code>print(foo.bar)</code> returns <code>mock value</code>, then hopefully it'll show how I can resolve the problem in my actual code.</p>
<pre><code>from contextlib import ExitStack
from unittest.mock import patch, PropertyMock
class Foo:
@property
def bar(self):
return 'real value'
exit_stack = ExitStack()
mock_foo = exit_stack.enter_context(patch('__main__.Foo', spec=True))
mock_bar = PropertyMock(return_value='mock value')
type(mock_foo).bar = mock_bar
print(mock_foo.bar) # 'mock value' (expected)
foo = Foo()
print(foo.bar) # <MagicMock name='Foo().bar' id='4372262080'> (unexpected - should be 'mock value')
exit_stack.close()
</code></pre>
| 1
|
2016-09-04T00:31:31Z
| 39,312,746
|
<p>The following line:</p>
<pre><code>type(mock_foo).bar = mock_bar
</code></pre>
<p>mocks <code>mock_foo</code> which, at that point, is the return value of <code>enter_context</code>. If I understand <a href="https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack.enter_context" rel="nofollow">the documentation</a> correctly it means you're now actually handling the result of <code>__enter__</code> of the return value of <code>patch('__main__.Foo', spec=True)</code>.</p>
<p>If you change that line to:</p>
<pre><code>type(Foo.return_value).bar = mock_bar
</code></pre>
<p>then you'll mock the property <code>bar</code> of instances of <code>Foo</code> (as the return value of calling a class is an instance). The second print statement will then print <code>mock value</code> as expected.</p>
| 1
|
2016-09-04T01:24:57Z
|
[
"python",
"python-3.x",
"mocking",
"python-mock"
] |
Get "super(): no arguments" error in one case but not a similar case
| 39,312,553
|
<pre><code>class Works(type):
def __new__(cls, *args, **kwargs):
print([cls,args]) # outputs [<class '__main__.Works'>, ()]
return super().__new__(cls, args)
class DoesNotWork(type):
def __new__(*args, **kwargs):
print([args[0],args[:0]]) # outputs [<class '__main__.doesNotWork'>, ()]
return super().__new__(args[0], args[:0])
Works() # is fine
DoesNotWork() # gets "RuntimeError: super(): no arguments"
</code></pre>
<p>As far as I can see, in both cases super._new__ receives the class literal as first argument, and an empty tuple as the 2nd.</p>
<p>So why does one give an error and the other not?</p>
| 1
|
2016-09-04T00:35:54Z
| 39,313,448
|
<p>The zero-argument form of <code>super</code> requires that the method containing it have an explicit (i.e., non-varargs) first argument. This is suggested by <a href="https://docs.python.org/3.1/library/functions.html?#super" rel="nofollow">an older version of the docs</a> (emphasis added):</p>
<blockquote>
<p>The zero argument form automatically searches the stack frame for the class (<code>__class__</code>) <strong>and the first argument</strong>.</p>
</blockquote>
<p>For some reason this note was removed in later versions of the docs. (It might be worth raising a doc bug, because the docs are quite vague about how zero-argument <code>super</code> works and what is required for it to work.)</p>
<p>See also <a href="https://bugs.python.org/issue15753" rel="nofollow">this Python bug report</a> (which is unresolved, and not clearly accepted as even a bug). The upshot is that zero-argument <code>super</code> is magic, and that magic fails in some cases. As suggested in the bug report, if you want to accept only varargs, you'll need to use the explicit two-argument form of <code>super</code>.</p>
| 2
|
2016-09-04T04:04:01Z
|
[
"python",
"super"
] |
Python: Properly formatting JSON parameters into a proper http request with markit on demand api
| 39,312,560
|
<p>I am having trouble formatting my request properly in order to use the markitondemand InteractiveChart API. How can I properly do this?</p>
<p>reference: <a href="http://dev.markitondemand.com/MODApis/" rel="nofollow">http://dev.markitondemand.com/MODApis/</a></p>
<p>Here is an example of a proper request:</p>
<pre><code>http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters=%7B%22Normalized%22%3Afalse%2C%22NumberOfDays%22%3A10%2C%22DataPeriod%22%3A%22Day%22%2C%22Elements%22%3A%5B%7B%22Symbol%22%3A%22AAPL%22%2C%22Type%22%3A%22price%22%2C%22Params%22%3A%5B%22c%22%5D%7D%5D%7D
</code></pre>
<p>Here is my code constructing a request:</p>
<pre><code>import requests
import json
url2 = 'http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json'
elements = [
{
'Symbol': 'GOOG',
'Type': 'price',
'Params': {'price': ['c']},
}
]
req_obj = {
'Normalized': 'false',
'NumberOfDays': 3,
'DataPeriod': 'Day',
'Elements': elements
}
resp = requests.get(url2, params={'parameters': json.dumps(req_obj)})
</code></pre>
<p>and here is the output when I log the resp.url :</p>
<pre><code>http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters=%7B%22Elements%22%3A+%5B%7B%22Type%22%3A+%22price%22%2C+%22Params%22%3A+%7B%22price%22%3A+%5B%22c%22%5D%7D%2C+%22Symbol%22%3A+%22GOOG%22%7D%5D%2C+%22NumberOfDays%22%3A+3%2C+%22DataPeriod%22%3A+%22Day%22%2C+%22Normalized%22%3A+%22false%22%7D
</code></pre>
<p>What am I doing wrong here?</p>
| 1
|
2016-09-04T00:37:09Z
| 39,312,597
|
<p>Your url end point (by the looks of it) should just be:</p>
<pre><code>url2 = 'http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart
</code></pre>
<p>Then, make your request:</p>
<pre><code>resp = requests.get(url2, params=json.dumps({'parameters': req_obj}))
</code></pre>
<p>Then <code>requests</code> will properly handle the <code>?</code> and any <code>&</code> if they were required.</p>
| 0
|
2016-09-04T00:46:58Z
|
[
"python",
"json"
] |
Python: Properly formatting JSON parameters into a proper http request with markit on demand api
| 39,312,560
|
<p>I am having trouble formatting my request properly in order to use the markitondemand InteractiveChart API. How can I properly do this?</p>
<p>reference: <a href="http://dev.markitondemand.com/MODApis/" rel="nofollow">http://dev.markitondemand.com/MODApis/</a></p>
<p>Here is an example of a proper request:</p>
<pre><code>http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters=%7B%22Normalized%22%3Afalse%2C%22NumberOfDays%22%3A10%2C%22DataPeriod%22%3A%22Day%22%2C%22Elements%22%3A%5B%7B%22Symbol%22%3A%22AAPL%22%2C%22Type%22%3A%22price%22%2C%22Params%22%3A%5B%22c%22%5D%7D%5D%7D
</code></pre>
<p>Here is my code constructing a request:</p>
<pre><code>import requests
import json
url2 = 'http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json'
elements = [
{
'Symbol': 'GOOG',
'Type': 'price',
'Params': {'price': ['c']},
}
]
req_obj = {
'Normalized': 'false',
'NumberOfDays': 3,
'DataPeriod': 'Day',
'Elements': elements
}
resp = requests.get(url2, params={'parameters': json.dumps(req_obj)})
</code></pre>
<p>and here is the output when I log the resp.url :</p>
<pre><code>http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters=%7B%22Elements%22%3A+%5B%7B%22Type%22%3A+%22price%22%2C+%22Params%22%3A+%7B%22price%22%3A+%5B%22c%22%5D%7D%2C+%22Symbol%22%3A+%22GOOG%22%7D%5D%2C+%22NumberOfDays%22%3A+3%2C+%22DataPeriod%22%3A+%22Day%22%2C+%22Normalized%22%3A+%22false%22%7D
</code></pre>
<p>What am I doing wrong here?</p>
| 1
|
2016-09-04T00:37:09Z
| 39,312,724
|
<p>Your <em>url</em>, <em>params</em> and logic are wrong, what you want is:</p>
<pre><code>url2 = 'http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json'
elements = [
{
'Symbol': 'GOOG',
'Type': 'price',
"Params":["c"] # not 'Params': {'price': ['c']}
}
]
req_obj = {"parameters": {'Normalized': 'false',
'NumberOfDays': 3,
'DataPeriod': 'Day',
'Elements': elements
}}
from urllib import urlencode
resp = requests.get(url2, params=urlencode(req_obj))
print(resp.json())
</code></pre>
<p>if we run the code:</p>
<pre><code>In [12]: import requests
In [13]: import json
In [14]: url2 = 'http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json'
In [15]: elements = [
....: {
....: 'Symbol': 'GOOG',
....: 'Type': 'price',
....: "Params":["c"]
....: }
....: ]
In [16]: req_obj = {"parameters": {'Normalized': 'false',
....:
....: 'NumberOfDays': 3,
....: 'DataPeriod': 'Day',
....: 'Elements': elements
....: }}
In [17]: from urllib import urlencode
In [18]: resp = requests.get(url2, params=urlencode(req_obj))
In [19]: print(resp.json())
{u'Positions': [0, 1], u'Dates': [u'2016-09-01T00:00:00', u'2016-09-02T00:00:00'], u'Labels': None, u'Elements': [{u'Currency': u'USD', u'Symbol': u'GOOGL', u'Type': u'price', u'DataSeries': {u'close': {u'maxDate': u'2016-09-02T00:00:00', u'max': 796.46, u'minDate': u'2016-09-01T00:00:00', u'values': [791.4, 796.46], u'min': 791.4}}, u'TimeStamp': None}]}
</code></pre>
<p>You can keep also the python Booleans etc.. calling dumps on just the inner data: </p>
<pre><code>req_obj = {'Normalized': False,
'NumberOfDays': 3,
'DataPeriod': 'Day',
'Elements': elements
}
resp = requests.get(url2, params={'parameters': json.dumps(req_obj)})
</code></pre>
<p>But it is as easy to just use the strings and forget dumps.</p>
| 0
|
2016-09-04T01:18:18Z
|
[
"python",
"json"
] |
Large table access from c++ functions with boost::python
| 39,312,595
|
<p>I'm generating a very large lookup table in C++ and using it from a variety of C++ functions. These functions are exposed to python using boost::python. </p>
<p>When not used as part of a class the desired behaviour is achieved. When I try and use the functions as part of a class written in just python I run in to issues accessing the lookup table.</p>
<pre><code> ------------------------------------
C++ for some numerical heavy lifting
------------------------------------
include <boost/python>
short really_big_array[133784630]
void fill_the_array(){
//Do some things which populate the array
}
int use_the_array(std::string thing){
//Lookup a few million things in the array depending on thing
//Return some int dependent on the values found
}
BOOST_PYTHON_MODULE(bigarray){
def("use_the_array", use_the_array)
def("fill_the_array", fill_the_array)
}
---------
PYTHON Working as desired
---------
import bigarray
if __name__ == "__main__"
bigarray.fill_the_array()
bigarray.use_the_array("Some Way")
bigarray.use_the_array("Some Other way")
#All works fine
---------
PYTHON Not working as desired
---------
import bigarray
class BigArrayThingDoer():
"""Class to do stuff which uses the big array,
use_the_array() in a few different ways
"""
def __init__(self,other_stuff):
bigarray.fill_the_array()
self.other_stuff = other_stuff
def use_one_way(thing):
return bigarray.use_the_array(thing)
if __name__ == "__main__"
big_array_thing_doer = BigArrayThingDoer()
big_array_thing_doer.use_one_way(thing)
#Segfaults or random data
</code></pre>
<p>I think I am probably not exposing enough to python to make sure the array is accessible at the right times, but im not quite sure exactly what I shoudld be exposing. Equally likely that there is some sort of problem involving ownership of the lookup table.</p>
<p>I dont ever need to manipulate the lookup table except via the other c++ functions.</p>
| 0
|
2016-09-04T00:45:38Z
| 39,316,248
|
<p>Missing a self in a definition. Used key word arguments where I should probably have used keyword only arguments so got no error when running.</p>
| 0
|
2016-09-04T11:09:08Z
|
[
"python",
"c++",
"boost-python"
] |
Python Syntax Non-ASCII character 'xe6' in file (added #-*-coding:utf-8 -*- )
| 39,312,596
|
<p>I want to use Python to read the .csv.</p>
<p>At start I search the answer to add the </p>
<pre><code>#!/usr/bin/python
#-*-coding:utf-8 -*-
</code></pre>
<p>so that can avoid the problem of encoding, but it is still wrong, giving the syntax error:</p>
<blockquote>
<p>SyntaxError: Non-ASCII character 'xe6' in file csv1.py on line2, but no encoding declared: </p>
</blockquote>
<p>My code:</p>
<pre><code>#!/usr/bin/python
# -*-coding:utf-8 -*-
import csv
with open('wtr1.csv', 'rb') as f:
for row in csv.reader(f):
print row
</code></pre>
| -1
|
2016-09-04T00:46:00Z
| 39,313,862
|
<p>You've got two different errors here. This answer relates to the <code>with</code> warning. The other error is the ascii encoding error.</p>
<p>You appear to be using a very old version of python (2.5). The <code>with</code> statement is not enabled by default in python 2.5. Instead you have to declare a the top of the file that you wish to use it. Your file should now look like:</p>
<pre><code>#!/usr/bin/python
# -*-coding:utf-8 -*-
from __future__ import with_statement
import csv
with open('wtr1.csv', 'rb') as f:
for row in csv.reader(f):
print row
</code></pre>
| 0
|
2016-09-04T05:40:44Z
|
[
"python"
] |
SVM; training data doesn't contain target
| 39,312,609
|
<p>I'm trying to predict whether a fan is going to turn out to a sporting event or not. My data (pandas DataFrame) consists of fan information (demographic's, etc.), and whether or not they attended the last 10 matches (g1_attend - g10_attend).</p>
<pre><code>fan_info age neighborhood g1_attend g2_attend ... g1_neigh_turnout
2717 22 downtown 0 1 .47
2219 67 east side 1 1 .78
</code></pre>
<p>How can I predict if they're going to attend g11_attend, when g11_attend doesn't exist in the DataFrame?</p>
<p>Originally, I was going to look into applying some of the basic models in scikit-learn for classification, and possibly just add a g11_attend column into the DataFrame. This all has me quite confused for some reason. I'm thinking now that it would be more appropriate to treat this as a time-series, and was looking into other models.</p>
| 1
|
2016-09-04T00:49:48Z
| 39,312,747
|
<p>You are correct, you can't just add a new category (ie output class) to a classifier -- this requires something that does time series.</p>
<p>But there is a fairly standard technique for using a classifier on times-series. Asserting (conditional) Time Independence, and using windowing.</p>
<p>In short we are going to make the assumption that whether or not someone attends a game depends only on variables we have captured, and not on some other time factor (or other factor in general).
i.e. we assume we can translate their history of games attended around the year and it will still be the same probability.
This is clearly wrong, but we do it anyway because machine learning techneques will deal with some noised in the data.
It is clearly wrong because some people are going to avoid games in winter cos it is too cold etc.</p>
<p>So now on the the classifier:</p>
<p>We have inputs, and we want just one output.
So the basic idea is that we are going to train a model,
that given as input whether they attended the <strong>first 9 games</strong>, predicts if they will attend the <strong>10th</strong></p>
<p>So out inputs are <sup>1</sup> <code>age</code>, <code>neighbourhood</code>, <code>g1_attend</code>, <code>g2_attend</code>,... <code>g9_attend</code>
and the output is <code>g10_attend</code> -- a binary value.</p>
<p>This gives us training data.</p>
<p>Then when it it time to test it we move everything accross: switch <code>g1_attend</code> for <code>g2_attend</code>, and <code>g2_attend</code> for <code>g3_attend</code> and ... and <code>g9_attend</code> for <code>g10_attend</code>.
And then our prediction output will be for <code>g11_attend</code>.</p>
<p>You can also train several models with different window sizes.
Eg only looking at the last 2 games, to predict attendance of the 3rd.
This gives you a lot more trainind data, since you can do.
<code>g1,g2</code>-><code>g3</code> and <code>g2,g3</code>-><code>g4</code> etc for each row.</p>
<p>You could train a bundle of different window sizes and merge the results with some ensemble technique. </p>
<p>In particular it is a good idea to train <code>g1,...,g8</code>-> <code>g9</code>,
and then use that to predict <code>g10</code> (using <code>g2,...,g9</code> as inputs)
to check if it is working.</p>
<p>I suggest in future you may like to ask these questions on <a href="http://stats.stackexchange.com/">Cross Validated</a>. While this may be on topic on stack overflow, it is more on topic there, and has a lot more statisticians and machine learning experts.</p>
<hr>
<p><sup>1</sup> I suggest discarding <code>fan_id</code> for now as an input. I just don't think it will get you anywhere, but it is beyond this question to explain why.</p>
| 2
|
2016-09-04T01:25:04Z
|
[
"python",
"pandas",
"scikit-learn",
"modeling"
] |
Changing values of indexes by magnitude
| 39,312,677
|
<p>I'm trying to make a flexible algorithm that will take values out of a 50 by 50 array (which contains pixel values from a fits image) if they are too high.
they are too high (in python). The first thing I tried to do was this:</p>
<pre><code>file = pf.open('/Users/Vofun/desktop/file.fits')
data = np.array(file[0].data)
for pixellist in range (len(data)):
if data[pixellist] > 50:
data[pixellist] = 10:
</code></pre>
<p>of course, that didn't work, and I got</p>
<blockquote>
<p>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</p>
</blockquote>
<p>the problem is, if I do that, I have no idea how to tell it which value to replace if I use a.any(). So far I think what I'll need is:</p>
<pre><code>if a.any(data) > 50:
</code></pre>
<p>and then a line of code telling it to replace the value with ten, but I'm not sure how to tell it to do that for the pixel it found, because I'm kind of terrible at coding. How would I reduce the value of the indexes based on if their value exceeds 50?</p>
| 0
|
2016-09-04T01:04:27Z
| 39,313,380
|
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean-array-indexing" rel="nofollow">boolean indexing</a> to change your data.</p>
<pre><code>import numpy as np
a = np.random.random_integers(40, 60, (5,5))
>>> a
array([[58, 58, 43, 56, 54],
[59, 40, 42, 52, 45],
[50, 60, 43, 48, 52],
[55, 48, 57, 41, 47],
[57, 55, 43, 54, 42]])
>>>
>>> a > 50
array([[ True, True, False, True, True],
[ True, False, False, True, False],
[False, True, False, False, True],
[ True, False, True, False, False],
[ True, True, False, True, False]], dtype=bool)
>>>
>>> a[a > 50] = 0
>>> a
array([[42, 0, 0, 0, 48],
[ 0, 46, 0, 0, 49],
[50, 0, 0, 44, 43],
[46, 46, 0, 43, 49],
[ 0, 0, 0, 0, 48]])
>>>
</code></pre>
| 1
|
2016-09-04T03:51:19Z
|
[
"python",
"python-2.7",
"numpy",
"multidimensional-array"
] |
I have a list of a part of a filename, for each one I want to go through the files in a directory that matches that part and return the filename
| 39,312,704
|
<p>So, let's say I have a directory with a bunch of filenames.
for example:</p>
<p>Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a<br>
AP Physics C - Dot Product-Wvhn_lVPiw0.m4a<br>
An Introduction to the Dot Product-X5DifJW0zek.m4a </p>
<p>Now let's say I have a list, of only the keys, which are at the end of the file names:</p>
<p><code>['fodZTqRhC24', 'Wvhn_lVPiw0, 'X5DifJW0zek']</code></p>
<p>How can I iterate through my list to go into that directory and search for a file name containing that key, and then return me the filename? </p>
<p>Any help is greatly appreciated!</p>
| -1
|
2016-09-04T01:12:09Z
| 39,312,763
|
<p>Here is an example: </p>
<p>ls: list of files in a given directory</p>
<p>names: list of strings to search for</p>
<pre><code>import os
ls=os.listdir("/any/folder")
n=['Py', 'sql']
for file in ls:
for name in names:
if name in file:
print(file)
</code></pre>
<p>Results :</p>
<pre><code>.PyCharm50
.mysql_history
zabbix2.sql
.mysql
PycharmProjects
zabbix.sql
</code></pre>
| 0
|
2016-09-04T01:28:41Z
|
[
"python"
] |
I have a list of a part of a filename, for each one I want to go through the files in a directory that matches that part and return the filename
| 39,312,704
|
<p>So, let's say I have a directory with a bunch of filenames.
for example:</p>
<p>Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a<br>
AP Physics C - Dot Product-Wvhn_lVPiw0.m4a<br>
An Introduction to the Dot Product-X5DifJW0zek.m4a </p>
<p>Now let's say I have a list, of only the keys, which are at the end of the file names:</p>
<p><code>['fodZTqRhC24', 'Wvhn_lVPiw0, 'X5DifJW0zek']</code></p>
<p>How can I iterate through my list to go into that directory and search for a file name containing that key, and then return me the filename? </p>
<p>Any help is greatly appreciated!</p>
| -1
|
2016-09-04T01:12:09Z
| 39,312,774
|
<p>Assuming you know which directory that you will be looking in, you could try something like this:</p>
<pre><code>import os
to_find = ['word 1', 'word 2'] # list containing words that you are searching for
all_files = os.listdir('/path/to/file') # creates list with files from given directory
for file in all_files: # loops through all files in directory
for word in to_find: # loops through target words
if word in file:
print file # prints file name if the target word is found
</code></pre>
<p>I tested this in my directory which contained these files:</p>
<pre><code>Helper_File.py
forms.py
runserver.py
static
app.py
templates
</code></pre>
<p>... and i set <code>to_find</code> to <code>['runserver', 'static']</code>...</p>
<p>and when I ran this code it returned:</p>
<pre><code>runserver.py
static
</code></pre>
<p>For future reference, you should make at least some sort of attempt at solving a problem prior to posting a question on Stackoverflow. It's not common for people to assist you like this if you can't provide proof of an attempt.</p>
| 0
|
2016-09-04T01:30:40Z
|
[
"python"
] |
I have a list of a part of a filename, for each one I want to go through the files in a directory that matches that part and return the filename
| 39,312,704
|
<p>So, let's say I have a directory with a bunch of filenames.
for example:</p>
<p>Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a<br>
AP Physics C - Dot Product-Wvhn_lVPiw0.m4a<br>
An Introduction to the Dot Product-X5DifJW0zek.m4a </p>
<p>Now let's say I have a list, of only the keys, which are at the end of the file names:</p>
<p><code>['fodZTqRhC24', 'Wvhn_lVPiw0, 'X5DifJW0zek']</code></p>
<p>How can I iterate through my list to go into that directory and search for a file name containing that key, and then return me the filename? </p>
<p>Any help is greatly appreciated!</p>
| -1
|
2016-09-04T01:12:09Z
| 39,312,865
|
<p>Here's a way to do it that allows for a selection of weather to match based on placement of text.</p>
<pre><code>import os
def scan(dir, match_key, bias=2):
'''
:0 startswith
:1 contains
:2 endswith
'''
matches = []
if not isinstance(match_key, (tuple, list)):
match_key = [match_key]
if os.path.exists(dir):
for file in os.listdir(dir):
for match in match_key:
if file.startswith(match) and bias == 0 or file.endswith(match) and bias == 2 or match in file and bias == 1:
matches.append(file)
continue
return matches
print scan(os.curdir, '.py'
</code></pre>
| 0
|
2016-09-04T01:48:47Z
|
[
"python"
] |
I have a list of a part of a filename, for each one I want to go through the files in a directory that matches that part and return the filename
| 39,312,704
|
<p>So, let's say I have a directory with a bunch of filenames.
for example:</p>
<p>Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a<br>
AP Physics C - Dot Product-Wvhn_lVPiw0.m4a<br>
An Introduction to the Dot Product-X5DifJW0zek.m4a </p>
<p>Now let's say I have a list, of only the keys, which are at the end of the file names:</p>
<p><code>['fodZTqRhC24', 'Wvhn_lVPiw0, 'X5DifJW0zek']</code></p>
<p>How can I iterate through my list to go into that directory and search for a file name containing that key, and then return me the filename? </p>
<p>Any help is greatly appreciated!</p>
| -1
|
2016-09-04T01:12:09Z
| 39,312,900
|
<p>Thanks a lot guys, Once I thought about it, I think I was making it harder than I had to with regex. Sorry about not trying it first. Thank you all once again. I think I have it. </p>
<pre><code>audio = ['Scalar Product or Dot Product (Hindi)-fodZTqRhC24.m4a',
'An Introduction to the Dot Product-X5DifJW0zek.m4a',
'AP Physics C - Dot Product-Wvhn_lVPiw0.m4a']
keys = ['fodZTqRhC24', 'Wvhn_lVPiw0', 'X5DifJW0zek']
file_names = []
for Id in keys:
for name in audio:
if Id in name:
file_names.append(name)
combined = zip(keys,file_names)
combined
</code></pre>
| 1
|
2016-09-04T01:57:02Z
|
[
"python"
] |
Python 2.7- fastest way to apply function to 2 columns of a pandas data frame
| 39,312,737
|
<p>I need to check if a string that is in one column of a pandas data frame is in another.
Example data:</p>
<pre><code>aa=['mma', 'sdas', 'asdsad']*1000
t=pd.DataFrame(aa)
a=['m', 'f', 'n']*1000
t1=pd.DataFrame(a)
t2=pd.concat([t,t1], axis=1)
t2.columns=['texto', 'textito']
</code></pre>
<p>With a lambda function I get what I need, but it's too slow:</p>
<pre><code>t2['veo1'] = t2.apply(lambda row: int(row['textito'] in row['texto']),axis=1)
</code></pre>
<blockquote>
<p>t2[:10]</p>
</blockquote>
<pre><code> texto textito veo1
0 mma m 1
1 sdas f 0
2 asdsad n 0
3 mma m 1
4 sdas f 0
5 asdsad n 0
6 mma m 1
7 sdas f 0
8 asdsad n 0
9 mma m 1
</code></pre>
<p>Is there a way to do this faster?</p>
<p>Thanks.</p>
| 2
|
2016-09-04T01:22:04Z
| 39,313,328
|
<p>If space is plentiful, you could create a new DataFrame by applying <code>set</code> to the original. Then the membership test would be much faster than using <code>in</code> with the strings.</p>
<pre><code># setup
aa=['mma', 'sdas', 'asdsad']*1000
t=pd.DataFrame(aa)
a=['m', 'f', 'n']*1000
t1=pd.DataFrame(a)
df=pd.concat([t,t1], axis=1)
df.columns=['a', 'b']
# new DataFrame using the set of the relevant columns
df2 = df.applymap(set)
# new column based on the membership test
df['v'] = df2.b <= df2.a
>>> df[:10]
a b v
0 mma m True
1 sdas f False
2 asdsad n False
3 mma m True
4 sdas f False
5 asdsad n False
6 mma m True
7 sdas f False
8 asdsad n False
9 mma m True
>>>
</code></pre>
| 1
|
2016-09-04T03:39:29Z
|
[
"python",
"string",
"performance",
"function",
"pandas"
] |
Python 2.7- fastest way to apply function to 2 columns of a pandas data frame
| 39,312,737
|
<p>I need to check if a string that is in one column of a pandas data frame is in another.
Example data:</p>
<pre><code>aa=['mma', 'sdas', 'asdsad']*1000
t=pd.DataFrame(aa)
a=['m', 'f', 'n']*1000
t1=pd.DataFrame(a)
t2=pd.concat([t,t1], axis=1)
t2.columns=['texto', 'textito']
</code></pre>
<p>With a lambda function I get what I need, but it's too slow:</p>
<pre><code>t2['veo1'] = t2.apply(lambda row: int(row['textito'] in row['texto']),axis=1)
</code></pre>
<blockquote>
<p>t2[:10]</p>
</blockquote>
<pre><code> texto textito veo1
0 mma m 1
1 sdas f 0
2 asdsad n 0
3 mma m 1
4 sdas f 0
5 asdsad n 0
6 mma m 1
7 sdas f 0
8 asdsad n 0
9 mma m 1
</code></pre>
<p>Is there a way to do this faster?</p>
<p>Thanks.</p>
| 2
|
2016-09-04T01:22:04Z
| 39,313,959
|
<p>Use a comprehension and <code>zip</code></p>
<pre><code>t2['veo1'] = [int(a in b) for a, b in zip(t2.textito, t2.texto)]
</code></pre>
<p><strong><em>Better answer per @Ninja Puppy</em></strong></p>
<pre><code>t2['veo1'] = pd.Series([a in b for a, b in zip(t2.textito, t2.texto)], dtype=int)
</code></pre>
<p><strong><em>Even Better answer per @Ninja Puppy</em></strong></p>
<pre><code>from operator import contains;
t2['veo1'] = pd.Series(map(contains, t2.texto, t2.textito), dtype=int)
</code></pre>
<hr>
<p>Per @Ninja Puppy's suggestion. Using <code>set</code> and checking for subset works in this particular situation with single character strings. However, it would also return <code>True</code> for <code>'www'</code> in <code>'word'</code> which probably isn't what you want.</p>
<pre><code>set('www') <= set('word')
True
</code></pre>
<p>Also</p>
<pre><code>set('not') <= set('stone')
True
</code></pre>
<p>When</p>
<pre><code>'not' in 'stone'
False
</code></pre>
<hr>
<h3>Timing</h3>
<p><a href="http://i.stack.imgur.com/MkKXg.png" rel="nofollow"><img src="http://i.stack.imgur.com/MkKXg.png" alt="enter image description here"></a></p>
<p><strong><em>Special Note</em></strong></p>
<p>Thanks to @Ninja Puppy</p>
<p><a href="http://i.stack.imgur.com/gao0D.png" rel="nofollow"><img src="http://i.stack.imgur.com/gao0D.png" alt="enter image description here"></a></p>
<p>Notice that if we assign the <code>bool</code> values from the comprehension to a <code>pd.Series</code> and let a vectorized operation take care of the conversion to <code>int</code>, we can shave off some time.</p>
<p>We can get even more efficient if we import the <code>contains</code> operator and use python's <code>map</code></p>
| 2
|
2016-09-04T05:55:20Z
|
[
"python",
"string",
"performance",
"function",
"pandas"
] |
Find all combination that sum to N when multiplies by index
| 39,312,764
|
<p>Given a number of items (<em>n</em>), what is the most efficient way to generate all possible lists [a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>] of non-negative integers under the condition that:</p>
<p>1*a<sub>1</sub> + 2*a<sub>2</sub> + 3*a<sub>3</sub> + ... + n*a<sub>n</sub> = n </p>
<p>using Python?</p>
<p>So for example, given an n of 5, the following combinations are:</p>
<p>[0,0,0,0,1]</p>
<p>[1,0,0,1,0]</p>
<p>[0,1,1,0,0]</p>
<p>[2,0,1,0,0]</p>
<p>[1,2,0,0,0]</p>
<p>[3,1,0,0,0]</p>
<p>[5,0,0,0,0]</p>
<p>I've implemented a brute-force method that generates all permutations and then checks if the list meets the above requirement, but is there a more efficient way to do this?</p>
| -1
|
2016-09-04T01:28:48Z
| 39,312,998
|
<p>A "greedy" algorithm works well for this. I'm using Python 3 here:</p>
<pre><code>def pick(total):
def inner(highest, total):
if total == 0:
yield result
return
if highest == 1:
result[0] = total
yield result
result[0] = 0
return
for i in reversed(range(total // highest + 1)):
result[highest - 1] = i
newtotal = total - i * highest
yield from inner(min(highest - 1, newtotal),
newtotal)
result = [0] * total
yield from inner(total, total)
</code></pre>
<p>Then, e.g.,</p>
<pre><code>for x in pick(5):
print(x)
</code></pre>
<p>displays:</p>
<pre><code>[0, 0, 0, 0, 1]
[1, 0, 0, 1, 0]
[0, 1, 1, 0, 0]
[2, 0, 1, 0, 0]
[1, 2, 0, 0, 0]
[3, 1, 0, 0, 0]
[5, 0, 0, 0, 0]
</code></pre>
<p>Like most recursive algorithms, it does a more-or-less obvious thing, then recurses to solve the (sub)problem that remains.</p>
<p>Here <code>inner(highest, total)</code> means to find all the decompositions of <code>total</code> using integers no larger than <code>highest</code>. How many copies of <code>highest</code> can we use? The more-than-less obvious answer is that we can use 0, 1, 2, ..., up to (and including) <code>total // highest</code> copies, but no more than that. Unless <code>highest</code> is 1 - then we have to use exactly <code>total</code> copies of 1.</p>
<p>However many copies we use of <code>highest</code>, the subproblem remaining is to decompose whatever remains of the total using integers no larger than <code>highest - 1</code>. Passing <code>min(highest - 1, newtotal)</code> instead of <code>highest - 1</code> is an optimization, since it's pointless trying any integer larger than the new total.</p>
| 2
|
2016-09-04T02:18:53Z
|
[
"python",
"algorithm",
"permutation",
"combinatorics"
] |
Create dictionary from multi-dimensional list without duplicating keys
| 39,312,794
|
<p>I'd like to take a list of tuples with multiple elements and turn it into a multi-dimensional dictionary without repeating keys. So if the following is my original list:</p>
<pre><code>myList = [('jeep', 'red', 2002, 4), ('jeep', 'red', 2003, 6), ('jeep', 'blue', 2003, 4), ('bmw', 'black', 2015, 8)]
</code></pre>
<p>I would want to take the above and turn it into a dictionary in this format:</p>
<pre><code>{'jeep':
{'red': [
[2002, 4],
[2003, 6]]
'blue': [
[2003, 4]]
},
'bmw':
{'black': [
[2015, 8]]
}
}
</code></pre>
<p>I seemed to be on the right path with Python's defaultdict, but I can't seem to completely solve this. Thanks!</p>
| 2
|
2016-09-04T01:34:50Z
| 39,312,820
|
<p>Using a lot of <code>dict.setdefault</code>...</p>
<pre><code>myList = [('jeep', 'red', 2002, 4), ('jeep', 'red', 2003, 6), ('jeep', 'blue', 2003, 4), ('bmw', 'black', 2015, 8)]
d = {}
for model, colour, year, month in myList:
d.setdefault(model, {}).setdefault(colour, []).append([year, month])
</code></pre>
<p>For each item in <code>myList</code>, either get the current dictionary for the model or create the key with a new empty dict, then with that dict, either retrieve the list for that colour, or set the key with a new empty list, then append the year and month as a 2-element list to that list...</p>
<p>Gives you <code>d</code>:</p>
<pre><code>{'bmw': {'black': [[2015, 8]]},
'jeep': {'blue': [[2003, 4]], 'red': [[2002, 4], [2003, 6]]}}
</code></pre>
| 4
|
2016-09-04T01:38:38Z
|
[
"python",
"dictionary",
"defaultdict"
] |
Create dictionary from multi-dimensional list without duplicating keys
| 39,312,794
|
<p>I'd like to take a list of tuples with multiple elements and turn it into a multi-dimensional dictionary without repeating keys. So if the following is my original list:</p>
<pre><code>myList = [('jeep', 'red', 2002, 4), ('jeep', 'red', 2003, 6), ('jeep', 'blue', 2003, 4), ('bmw', 'black', 2015, 8)]
</code></pre>
<p>I would want to take the above and turn it into a dictionary in this format:</p>
<pre><code>{'jeep':
{'red': [
[2002, 4],
[2003, 6]]
'blue': [
[2003, 4]]
},
'bmw':
{'black': [
[2015, 8]]
}
}
</code></pre>
<p>I seemed to be on the right path with Python's defaultdict, but I can't seem to completely solve this. Thanks!</p>
| 2
|
2016-09-04T01:34:50Z
| 39,313,069
|
<p>Since what you want is essentially a tree data structure with a certain number of levels with lists for leaves, I'd be more explicit about it all by encapsulating the details inside a custom dictionary subclass because it could make the conversion extremely simple.</p>
<p>Here's a generic version of the data structure applied to your data:</p>
<pre><code>class TreeContainer(dict):
def __init__(self, max_levels, leaf_factory=lambda: None, level=1):
self.max_levels = max_levels
self.level = level
self.leaf_factory = leaf_factory
def __missing__(self, key):
if self.level < self.max_levels: # need another level?
value = self[key] = type(self)(self.max_levels, self.leaf_factory,
self.level+1)
else:
value = self[key] = self.leaf_factory()
return value
myList = [("jeep", "red", 2002, 4), ("jeep", "red", 2003, 6),
("jeep", "blue", 2003, 4), ("bmw", "black", 2015, 8)]
vehicles = TreeContainer(2, list)
for model, color, year, month in myList: # convert list to dictionary
vehicles[model][color].append([year, month])
from pprint import pprint
pprint(vehicles)
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>{'bmw': {'black': [[2015, 8]]},
'jeep': {'blue': [[2003, 4]], 'red': [[2002, 4], [2003, 6]]}}
</code></pre>
| 1
|
2016-09-04T02:37:16Z
|
[
"python",
"dictionary",
"defaultdict"
] |
Selecting data in parenthesis
| 39,312,852
|
<p>I have a list of movies in a csv file, 100rows x 1column that looks like this:</p>
<pre><code>1. Mulholland Drive (David Lynch, 2001)
</code></pre>
<p>I'm trying to get rid of the number in the front, put the title, director, and year in each column. I did:</p>
<pre><code>rank = pd.read_csv("/Users/...csv", header = 0)
rank.columns = ['1']
rank['1'] = rank['1'].str[3:]
</code></pre>
<p>to get rid of all the numbers in the front, so next, I wanted to separate what's in the parenthesis by:</p>
<pre><code>rank = rank[rank.find("(")+1:rank.find(")")]
</code></pre>
<p>but am getting:</p>
<pre><code>AttributeError: 'DataFrame' object has no attribute 'find'
</code></pre>
| 2
|
2016-09-04T01:46:26Z
| 39,312,899
|
<p>If they're always definitely in that format, for instance - mocking up a file with just the given example (not that if you've got brackets or commas etc... etc... that don't match the format - this'll break):</p>
<pre><code>rank = pd.read_csv('somefile.csv', header=None, names=['film'])
df = rank.film.str.extract('(?:\d+\.\s+)(.*?)\((.*?),\s+(\d+)\)', expand=True)
</code></pre>
<p>Which'll give you:</p>
<pre><code> 0 1 2
0 Mulholland Drive David Lynch 2001
</code></pre>
| 3
|
2016-09-04T01:56:59Z
|
[
"python",
"pandas",
"slice",
"parentheses"
] |
Running webdriver with Firefox Python
| 39,312,903
|
<p>I'm writing a program that will search a website for specific entries inside of articles, I'm using selenium webdriver for Python.</p>
<p>While attempting to connect to the site I get this exception:</p>
<pre><code>Traceback (most
recent call last):
File "search.py", line 26, in <module>
test.search_for_keywords()
File "search.py", line 13, in search_for_keywords
browser = webdriver.Firefox()
File "C:\Python27\lib\site-packages\selenium-3.0.0b2-py2.7.egg\selenium\webdriver\firefox\webdriver.py", line 65, in __init__
self.service.start()
File "C:\Python27\lib\site-packages\selenium-3.0.0b2-py2.7.egg\selenium\webdriver\common\service.py", line 86, in start
self.assert_process_still_running()
File "C:\Python27\lib\site-packages\selenium-3.0.0b2-py2.7.egg\selenium\webdriver\common\service.py", line 99, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service geckodriver unexpectedly exited. Status code was: 2
</code></pre>
<p>It's saying that the webdriver unexpectedly exited. How can I fix this issue? I'm trying to connect with firefox version 48.0 with python version 2.7.12</p>
| 0
|
2016-09-04T01:57:29Z
| 39,312,915
|
<p>I fixed this, I deleted the <code>egg</code> that was installed and reinstalled selenium, it works perfectly now.</p>
| 1
|
2016-09-04T02:00:29Z
|
[
"python",
"selenium",
"firefox",
"exception",
"selenium-webdriver"
] |
How to convert string timestamp values to datetime64 dtype
| 39,312,930
|
<p>The resulting DataFrame below lists the <strong>Timestamp</strong> values as the strings:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Time':['00:00:00:19','02:11:00:07','02:00:40:23']})
</code></pre>
<p>What method to use to convert these string values to datetime64 so the sum() and mean() functions could be applied to the column?</p>
<p>Below is the screenshot of the DataFrame as it shown in Notebook:</p>
| 0
|
2016-09-04T02:04:13Z
| 39,313,017
|
<p>It's probably not the best way, but it's functional:</p>
<pre><code>durations = (df.Time.str.split(':', expand=True).applymap(int) * [24*60*60, 60*60, 60, 1]).sum(axis=1).apply(pd.Timedelta, unit='s')
</code></pre>
<p>Gives you:</p>
<pre><code>0 0 days 00:00:19
1 3 days 08:00:07
2 2 days 00:40:23
dtype: timedelta64[ns]
</code></pre>
<p>And <code>durations.sum()</code> will give you <code>Timedelta('5 days 08:40:49')</code></p>
<p>Okay - slightly easier:</p>
<pre><code>df.Time.str.replace('(\d+):(.*)', r'\1 days \2').apply(pd.Timedelta)
</code></pre>
| 1
|
2016-09-04T02:22:03Z
|
[
"python",
"dataframe"
] |
How to get rid of multiple whitespace AND account for a newline
| 39,312,939
|
<p>Say I have an input of <code>"Hello my name is \\n Bill"</code></p>
<pre><code>my_str = ' '.join(my_str.split())
</code></pre>
<p>So this will join the letters and give me <code>"Hello my name is\nBill"</code> when I print it all on one line. What I want it to print is:</p>
<pre><code>Hello my name is
Bill
</code></pre>
<p>to the terminal.</p>
| 1
|
2016-09-04T02:08:42Z
| 39,313,047
|
<p>You problem is you don't have a newline char, you have two <em>backslashes</em> and an <code>n</code> i.e the backslash is escaped so after splitting you need to do a replace:</p>
<pre><code>In [10]: s = "Hello my name is \\n Bill"
In [11]: print(" ".join(s.split()))
Hello my name is \n Bill
In [12]: print(" ".join(s.split()).replace("\\n","\n"))
Hello my name is
Bill
</code></pre>
<p>Or use <em>.decode("string_escape")</em>:</p>
<pre><code>In [15]: s = "Hello my name is \\n Bill"
In [16]: print" ".join(s.split())
Hello my name is \n Bill
In [17]: print(" ".join(s.split()).decode("string_escape"))
Hello my name is
Bill
</code></pre>
<p>As Kirby mentioned in a comment, if you are creating the strings don't escape the backslash, if the data is from another source use one of the methods above.</p>
| 2
|
2016-09-04T02:32:18Z
|
[
"python",
"whitespace",
"removing-whitespace"
] |
How can I maximize my figure on matplotlib python using macOS?
| 39,312,957
|
<pre><code>fig, ax = plt.subplots(figsize=(16,8),dpi=100,subplot_kwn {'projection':nccrs.PlateCarree()})
ax.set_global()
plt.subplots_adjust(left=0.04, bottom=0.02, right=0.96, top=0.96)
# set a figure window's title
fig2 = plt.gcf()
fig2.canvas.set_window_title('Metheoros 1.0')
mng = plt.get_current_fig_manager()
mng.Maximize(True)
</code></pre>
<p>I Tried this, but didn't work on mac</p>
| 0
|
2016-09-04T02:11:04Z
| 39,314,263
|
<p>The first line should have an equals sign in place of the n in subplot_kwn:</p>
<pre><code>fig, ax = plt.subplots(figsize=(16,8),dpi=100,subplot_kw= {'projection':ccrs.PlateCarree()})
</code></pre>
<p>You might want to check what you have imported cartopy.crs as, because that may cause problems as well. </p>
<hr>
<p><strong>EDIT:</strong></p>
<p>So I did quite a bit of digging, and found that in mng has a method called 'full_screen_toggle', so in theory, you could call <code>mng.full_screen_toggle()</code> followed by <code>mng.show()</code>. I tried that, but that seemed to have no effect. I dug through the source code and found that the Mac OS X backend does not have a fullscreen function implemented (as far as I can tell). </p>
<p>That means that you'll have to use a different backend. You can change backends by calling <code>plt.switch_backend('backend')</code> where backend is your desired backend. This function accepts the following arguments: </p>
<blockquote>
<p>'pdf', 'pgf', 'Qt4Agg', 'GTK', 'GTKAgg', 'ps', 'agg', 'cairo', 'MacOSX', 'GTKCairo', 'WXAgg', 'template', 'TkAgg', 'GTK3Cairo', 'GTK3Agg', 'svg', 'WebAgg', 'CocoaAgg', 'emf', 'gdk', 'WX'</p>
</blockquote>
| 0
|
2016-09-04T06:44:28Z
|
[
"python",
"osx",
"matplotlib"
] |
How can I maximize my figure on matplotlib python using macOS?
| 39,312,957
|
<pre><code>fig, ax = plt.subplots(figsize=(16,8),dpi=100,subplot_kwn {'projection':nccrs.PlateCarree()})
ax.set_global()
plt.subplots_adjust(left=0.04, bottom=0.02, right=0.96, top=0.96)
# set a figure window's title
fig2 = plt.gcf()
fig2.canvas.set_window_title('Metheoros 1.0')
mng = plt.get_current_fig_manager()
mng.Maximize(True)
</code></pre>
<p>I Tried this, but didn't work on mac</p>
| 0
|
2016-09-04T02:11:04Z
| 39,321,764
|
<pre><code># -*- coding: UTF-8 -*-
'''
Created on 4 de set de 2016
@author: VladimirCostadeAlencar
'''
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure
import wx
class CanvasPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
self.canvas = FigureCanvas(self, 0, self.figure)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.SetSizer(self.sizer)
self.Fit()
def draw(self):
from ler_csv import ler_csv
from plotar_csv04 import plotar_pontos
nomearq = 'gps01.csv'
print 'Reading points...'
coords = ler_csv(nomearq)
figure, ax = plotar_pontos(self, coords)
print 'Plotting on Wx...'
self.canvas = FigureCanvas(self, 0, figure)
if __name__ == "__main__":
app = wx.PySimpleApp()
fr = wx.Frame(None, title='Metheoros v1.0 - 2016')
panel = CanvasPanel(fr)
panel.draw()
fr.Maximize(True)
fr.Show()
app.MainLoop()
</code></pre>
| 0
|
2016-09-04T21:45:46Z
|
[
"python",
"osx",
"matplotlib"
] |
Mapping a list as dictionary values
| 39,312,969
|
<p>I have a list of strings called lst which contains name, city, and email addresses for three people in such order. I have a dictionary called data that only contains keys.</p>
<pre><code>lst = ['James','New York','james@email.com','Matt','San Francisco','matt@email.com','Jessica','Los Angeles','jessica@email.com']
data = {
"Name": None,
"City": None,
"email": None
}
</code></pre>
<p>I would like to map lst items as values in data and produce a new list of dictionaries as below,</p>
<pre><code>newlst = [{
"Name": "James",
"City": "New York",
"email": "james@email.com"
},
{
"Name": "Matt",
"City": "San Francisco",
"email": "matt@email.com"
},
{
"Name": "Jessica",
"City": "Los Angeles",
"email": "jessica@email.com"
}]
</code></pre>
<p>I know how to add a single value to a specific key in a dictionary like data["Name"] = "James" but how would I achieve this by using list/dict comprehension or iteration?</p>
| -1
|
2016-09-04T02:13:35Z
| 39,313,032
|
<p>Here it is.</p>
<pre><code>lst = ['James','New York','james@email.com','Matt','San Francisco','matt@email.com','Jessica','Los Angeles','jessica@email.com']
newlst = []
for i in xrange( 0, len(lst), 3 ):
d = {}
d['Name'] = lst[i]
d['City'] = lst[i+1]
d['Email'] = lst[i+2]
newlst.append( d )
print newlst
</code></pre>
<p>Output:</p>
<pre><code>[{'City': 'New York', 'Email': 'james@email.com', 'Name': 'James'},
{'City': 'San Francisco', 'Email': 'matt@email.com', 'Name': 'Matt'},
{'City': 'Los Angeles', 'Email': 'jessica@email.com', 'Name': 'Jessica'}]
</code></pre>
<p>Using comprehension:</p>
<pre><code>lst = ['James','New York','james@email.com','Matt','San Francisco','matt@email.com','Jessica','Los Angeles','jessica@email.com']
newlst = [{'Name':lst[i], 'City':lst[i+1], 'Email':lst[i+2]} for i in xrange(0,len(lst),3)]
</code></pre>
| 4
|
2016-09-04T02:26:33Z
|
[
"python",
"list",
"dictionary",
"list-comprehension"
] |
Mapping a list as dictionary values
| 39,312,969
|
<p>I have a list of strings called lst which contains name, city, and email addresses for three people in such order. I have a dictionary called data that only contains keys.</p>
<pre><code>lst = ['James','New York','james@email.com','Matt','San Francisco','matt@email.com','Jessica','Los Angeles','jessica@email.com']
data = {
"Name": None,
"City": None,
"email": None
}
</code></pre>
<p>I would like to map lst items as values in data and produce a new list of dictionaries as below,</p>
<pre><code>newlst = [{
"Name": "James",
"City": "New York",
"email": "james@email.com"
},
{
"Name": "Matt",
"City": "San Francisco",
"email": "matt@email.com"
},
{
"Name": "Jessica",
"City": "Los Angeles",
"email": "jessica@email.com"
}]
</code></pre>
<p>I know how to add a single value to a specific key in a dictionary like data["Name"] = "James" but how would I achieve this by using list/dict comprehension or iteration?</p>
| -1
|
2016-09-04T02:13:35Z
| 39,313,065
|
<p>Here's an approach using list comprehension. The idea is that we create a dictionary based on a zip of the keys and three values of a time.</p>
<pre><code>lst = [
'James', 'New York', 'james@email.com',
'Matt', 'San Francisco', 'matt@email.com',
'Jessica', 'Los Angeles', 'jessica@email.com',
]
keys = [
'Name',
'City',
'email',
]
newlst = [
dict(zip(keys, values)) for values in [iter(lst)] * len(keys)
]
print(newlst)
</code></pre>
<p><strong>Output</strong>:</p>
<pre><code>[
{'City': 'New York', 'Name': 'James', 'email': 'james@email.com'},
{'City': 'San Francisco', 'Name': 'Matt', 'email': 'matt@email.com'},
{'City': 'Los Angeles', 'Name': 'Jessica', 'email': 'jessica@email.com'}
]
</code></pre>
<p><code>[iter(lst)] * len(keys)</code> will return chunks of 3 values at a time from the list. <code>zip(keys, values)</code> will then produce an iterator of tuples containing a key and corresponding value. Finally, <code>dict()</code> will turn this into a dictionary to be inserted into <code>newlst</code>. This loops until the list is exhausted.</p>
| 5
|
2016-09-04T02:36:45Z
|
[
"python",
"list",
"dictionary",
"list-comprehension"
] |
Is there a Python equivalent to MATLAB 'time' function?
| 39,313,045
|
<p>I'm porting a MATLAB R2011b code to Python 3.5.1.
The original MATLAB code, which was written around 10 years ago, contains a 'time' function as bellow:</p>
<pre><code>t_x=time(x,fsample);
</code></pre>
<p>The output is:</p>
<pre><code>debug> x
x =
-0.067000 -0.067000 -0.068000 -0.069000 -0.069000 -0.070000 -0.070000 -0.071000 -0.071000 -0.072000
debug> fsample
fsample = 10000
debug> t_x
t_x =
0.00000 0.10000 0.20000 0.30000 0.40000 0.50000 0.60000 0.70000 0.80000 0.90000
</code></pre>
<p>I'd like to do the same thing in Python, but I cannot find any equivalent function in Python. (The function name 'time' is too general that it's hard to search on Google.) It seems this 'time' function returns 1000/fsample (e.g., if fsample=10000, then 0.1) multiplied by the index of 'x'. Does anyone know a similar function in Python?</p>
<p>... Please note that this 'time' function is different from the 'time' function introduced in MATLAB R2014b:
[<a href="http://www.mathworks.com/help/matlab/ref/time.html?searchHighlight=time&s_tid=gn_loc_drop][1]" rel="nofollow">http://www.mathworks.com/help/matlab/ref/time.html?searchHighlight=time&s_tid=gn_loc_drop][1]</a></p>
| 0
|
2016-09-04T02:31:24Z
| 39,313,197
|
<p>It should be simple enough to implement a similar function.</p>
<p>For numpy arrays</p>
<pre><code>import numpy as np
def time(x, fsample):
return np.linspace(0, (1000/fsample)*(len(x) - 1), num=len(x))
</code></pre>
<p>For simple python lists</p>
<pre><code>def time(x, fsample):
return [i*(1000/fsample) for i in range(len(x))]
</code></pre>
| 2
|
2016-09-04T03:12:02Z
|
[
"python",
"matlab",
"time"
] |
grouping and summing multiindex dataframe in pandas
| 39,313,103
|
<p>I have a dataframe like this. </p>
<pre><code>df1=pd.DataFrame({"A":np.random.randint(1,10,4),"B":np.random.randint(1,10,4),"C":list('abba')})
df1.index.name="first"
df2=pd.DataFrame({"A":np.random.randint(1,10,5),"B":np.random.randint(1,10,5),"C":list('aaabb')})
df2.index.name="second"
df=pd.concat([df1,df2], keys=['first', 'second'])
df
A B C
first 0 6 5 a
1 2 2 b
2 1 6 b
3 6 9 a
second 0 6 6 a
1 9 9 a
2 8 4 a
3 7 2 b
4 9 8 b
</code></pre>
<p>I would like to get grouping and summing result like this.
the (key= column "C")</p>
<pre><code> first second
A B A B
a 15 14 23 19
b 3 8 16 10
</code></pre>
<p>How can I get this result ?</p>
| 2
|
2016-09-04T02:46:25Z
| 39,313,379
|
<p>One way to do this would be:</p>
<pre><code>In [126]: df1=pd.DataFrame({"A":np.random.randint(1,10,4),"B":np.random.randint(1,10,4),"C":list('abba')})
In [127]: df2=pd.DataFrame({"A":np.random.randint(1,10,5),"B":np.random.randint(1,10,5),"C":list('aaabb')})
In [128]: df1
Out[128]:
A B C
0 7 9 a
1 1 3 b
2 7 7 b
3 1 2 a
In [129]: df2
Out[129]:
A B C
0 3 1 a
1 3 1 a
2 7 3 a
3 9 7 b
4 9 1 b
In [130]: df = pd.concat({"first": df1.groupby('C').sum(), "second": df2.groupby('C').sum()}, axis = 1)
In [131]: del df.index.name
In [132]: df
Out[132]:
first second
A B A B
a 8 11 13 5
b 8 10 18 8
</code></pre>
| 0
|
2016-09-04T03:50:42Z
|
[
"python",
"pandas"
] |
grouping and summing multiindex dataframe in pandas
| 39,313,103
|
<p>I have a dataframe like this. </p>
<pre><code>df1=pd.DataFrame({"A":np.random.randint(1,10,4),"B":np.random.randint(1,10,4),"C":list('abba')})
df1.index.name="first"
df2=pd.DataFrame({"A":np.random.randint(1,10,5),"B":np.random.randint(1,10,5),"C":list('aaabb')})
df2.index.name="second"
df=pd.concat([df1,df2], keys=['first', 'second'])
df
A B C
first 0 6 5 a
1 2 2 b
2 1 6 b
3 6 9 a
second 0 6 6 a
1 9 9 a
2 8 4 a
3 7 2 b
4 9 8 b
</code></pre>
<p>I would like to get grouping and summing result like this.
the (key= column "C")</p>
<pre><code> first second
A B A B
a 15 14 23 19
b 3 8 16 10
</code></pre>
<p>How can I get this result ?</p>
| 2
|
2016-09-04T02:46:25Z
| 39,313,798
|
<p>You can use <code>groupby</code> with a list of things that look like arrays. You want to use the first level of the index and column <code>'C'</code>.</p>
<pre><code>df.groupby([df.index.get_level_values(0), df.C]).sum() \
.unstack().stack(0).T.rename_axis(None)
</code></pre>
<p><a href="http://i.stack.imgur.com/4pMin.png" rel="nofollow"><img src="http://i.stack.imgur.com/4pMin.png" alt="enter image description here"></a></p>
| 2
|
2016-09-04T05:27:41Z
|
[
"python",
"pandas"
] |
phantomjs + selenium in python proxy-auth not working
| 39,313,109
|
<p>I'm trying to set a proxy for webscraping using selenium + phantomjs. I'm using python. </p>
<p>I've seen in many places that there is a bug in phantomjs such that proxy-auth does not work. </p>
<pre><code>from selenium.webdriver.common.proxy import *
from selenium import webdriver
from selenium.webdriver.common.by import By
service_args = [
'--proxy=http://fr.proxymesh.com:31280',
'--proxy-auth=USER:PWD',
'--proxy-type=http',
]
driver = webdriver.PhantomJS(service_args=service_args)
driver.get("https://www.google.com")
print driver.page_source
</code></pre>
<p>Proxy mesh suggests using the following instead: </p>
<blockquote>
<p>page.customHeaders={'Proxy-Authorization': 'Basic '+btoa('USERNAME:PASSWORD')};</p>
</blockquote>
<p>but I'm not sure how to translate that into python. </p>
<p>This is what I currently have: </p>
<pre><code>from selenium import webdriver
import base64
from selenium.webdriver.common.proxy import *
from selenium import webdriver
from selenium.webdriver.common.by import By
service_args = [
'--proxy=http://fr.proxymesh.com:31280',
'--proxy-type=http',
]
headers = { 'Proxy-Authorization': 'Basic ' + base64.b64encode('USERNAME:PASSWORD')}
for key, value in enumerate(headers):
webdriver.DesiredCapabilities.PHANTOMJS['phantomjs.page.customHeaders.{}'.format(key)] = value
driver = webdriver.PhantomJS(service_args=service_args)
driver.get("https://www.google.com")
print driver.page_source
</code></pre>
<p>but it doesn't work. </p>
<p>Any suggestions for how I could get this to work?</p>
| 4
|
2016-09-04T02:48:06Z
| 39,639,557
|
<p>I'm compiling answers from:
<a href="http://stackoverflow.com/questions/37331684/how-to-correctly-pass-basic-auth-every-click-using-selenium-and-phantomjs-webd">How to correctly pass basic auth (every click) using Selenium and phantomjs webdriver</a>
as well as:
<a href="http://stackoverflow.com/questions/16740188/base64-b64encode-error">base64.b64encode error</a></p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import base64
service_args = [
'--proxy=http://fr.proxymesh.com:31280',
'--proxy-type=http',
]
authentication_token = "Basic " + base64.b64encode(b'username:password')
capa = DesiredCapabilities.PHANTOMJS
capa['phantomjs.page.customHeaders.Proxy-Authorization'] = authentication_token
driver = webdriver.PhantomJS(desired_capabilities=capa, service_args=service_args)
driver.get("http://...")
</code></pre>
| 2
|
2016-09-22T12:49:37Z
|
[
"python",
"selenium",
"proxy",
"phantomjs"
] |
relationship between the binary executables and the rest of the python installation
| 39,313,175
|
<p>I have python version 3.4 installed on my computer. One part of the installation is the directory with the binary executables: </p>
<pre><code> /Library/Frameworks/Python.framework/Versions/3.4/bin/
</code></pre>
<p>As far as I understand it, these binary executables constitute the framework, which makes it possible for the computer to understand, e.g., what it means, if I type in the command </p>
<pre><code> import numpy
</code></pre>
<p>But I don't yet fully understand the the relationship between the binary executables and the rest of the python installation (e.g. the python modules and packages such as numpy). Why don't the files in the numpy package need to be executable binaries? </p>
<p>I would like to have an explanation of this from scratch/"for dummies".</p>
<p>Is there a good reference or can somebody write one?</p>
<p>Thank you in advance.</p>
| 0
|
2016-09-04T03:06:21Z
| 39,313,264
|
<p>In simple terms, <code>python</code> and <code>pip</code> are binary executables. </p>
<p><code>numpy</code> is a module. </p>
<p>You cannot run a command called <code>numpy</code> from the terminal, therefore it is not a binary executable. </p>
<p>Some python packages are binary executables and you can execute them directly from the command line </p>
| 1
|
2016-09-04T03:25:35Z
|
[
"python",
"binaryfiles"
] |
Calculate bytes between two hex offsets
| 39,313,181
|
<p>In Python, I'm trying to extract some data from a binary file. I know the offsets of my data. They are always the same. For instance, written beneath is the first 4 offsets and the converted offset as a decimal value.</p>
<ul>
<li>Offset1 - 0x00000409 - 1033</li>
<li>Offset2 - 0x0000103A - 4154</li>
<li>Offset3 - 0x00001C6B - 7275</li>
<li>Offset4 - 0x0000289C - 10396</li>
</ul>
<p>I know that each offset (after the first one), is 3121 decimals apart, so is there a way I can just skip to the next offset? How do I move 3121 decimals to the next offset?</p>
<p>There are 128 offsets that I need to extract. I hope there is a way of dynamically determining the difference (number of bytes) between offsets?</p>
<p>I can then get the same data each time, using 0x100 to extract 256 characters from the offset.</p>
| 0
|
2016-09-04T03:07:57Z
| 39,313,298
|
<p>use <code>file.seek()</code> to skip between locations in a file. In this case, to go to the next location in the file, you would use <code>file.seek(3121, 1)</code> which seeks 3121 bytes ahead relative to the current position.</p>
<p>EDIT: I didn't realize you were changing the file position after opening it, so it should actually be 2685 bytes that you're seeking ahead each time, to account for the 256 you read.</p>
| 1
|
2016-09-04T03:30:40Z
|
[
"python",
"binary",
"hex",
"offset",
"bytecode"
] |
What is the correct way to use and logical operator in python for multiple conditions?
| 39,313,185
|
<p>I'm trying to brute-force a projecteuler questions before I improve my code. I can't get multiple condition and logical operator working in my loop. Here is the code, editor shows no errors but it simply don't increase condition value so obviously some of the conditions are wrong. Can some one show me the correct way to use multiple and logical operators?</p>
<pre><code>i = 20
while (i % 2 != 0 and i % 3 != 0 and i % 4 != 0 and i % 5 != 0 and
i % 6 != 0 and i % 7 != 0 and i % 8 != 0 and i % 9 != 0 and
i % 10 != 0 and i % 11 != 0 and i % 12 != 0 and i % 13 != 0 and
i % 14 != 0 and i % 15 != 0 and i % 16 != 0 and i % 17 != 0 and
i % 18 != 0 and i % 19 != 0 and i % 20 != 0):
i = i + 20
else:
print(i)
</code></pre>
| 0
|
2016-09-04T03:08:35Z
| 39,313,317
|
<p>It looks like you're trying to find the smallest number which is a multiple of all integers from 1 to 20 inclusive. You're starting with 20, and you want to keep going up by 20 until your condition is met.</p>
<p>It's easier to see the problem in a smaller case. Say we only cared about 2, 3, and 4.</p>
<p>We want to find a number i for which </p>
<pre><code>i % 2 == 0 and i % 3 == 0 and i % 4 == 0
</code></pre>
<p>But the negation of this is either</p>
<pre><code>not (i % 2 == 0 and i % 3 == 0 and i % 4 == 0)
</code></pre>
<p>or, distributing the <code>not</code>,</p>
<pre><code>i % 2 != 0 or i % 3 != 0 or i % 4 != 0
</code></pre>
<p>In other words, if <em>any</em> of the numbers fail to divide evenly, you want to increase by 20, not if <em>all</em> of them fail to. </p>
<p>20, for example, is divisible by 2, so <code>i % 2 != 0</code> is False, so you have <code>False and i % 3 != 0 and.. etc</code>, which will still be false. A working version of your code would look like</p>
<pre><code>i = 20
while any(i % num != 0 for num in range(2,21)):
i += 20
</code></pre>
<p>where I've used a generator expression to avoid all the duplication. Note thought that this will be <em>very much</em> slower than using the math trick they want you to use, because the final answer has 9 digits..</p>
| 1
|
2016-09-04T03:36:52Z
|
[
"python",
"operators",
"brute-force",
"logical"
] |
Variable is not defined in the function
| 39,313,224
|
<pre><code>import random
def game(n):
while counter < n:
n1 = random.randrange(1,10)
n2 = random.randrange(1,10)
counter = 0
print (str(n1) + " + " + str(n1))
answer = input("Enter answer: ")
if answer == n1+n2:
print("Correct.")
else:
print("Incorrect.")
counter += 1
pass
</code></pre>
<p>The error is in this line below telling that n1 is not defined.</p>
<pre><code>print (str(n1) + " + " + str(n1))
</code></pre>
| -2
|
2016-09-04T03:17:27Z
| 39,313,459
|
<p>Here's what you need to fix:</p>
<ol>
<li>Your indentation is all over the place.</li>
<li>You were trying use <code>counter</code> as part of your condition in your loop before you even gave it a value.</li>
<li>Because you created <code>n1</code> and <code>n2</code> inside of the body of your while loop, after every guess <code>n1</code> and <code>n2</code> will be created again and assigned different values. I'm not sure if you wanted that to happen, but if you did you can simply move those 2 lines back inside the loop.</li>
<li>You weren't properly breaking out of your loop if the user guessed the correct answer. That's why I added <code>break</code>. That will end the loop upon a successful answer. Also, you don't need <code>pass</code> if the answer is incorrect. The loop will continue until it receives a correct answer or when it reaches the value of <code>counter</code>.</li>
</ol>
<p>Anyways, here is a fixed/working version of your code.</p>
<pre><code>import random
def game(n):
counter = 0
n1 = random.randrange(1,10)
n2 = random.randrange(1,10)
while counter < n:
# move creation of n1, n2 here if you want #'s to change after every guess
print ('{} + {}'.format(n1, n2))
answer = input("Enter answer: ")
if answer == int(n1 + n2):
print("Correct.")
break
else:
print("Incorrect.")
counter += 1
</code></pre>
<p>You should really read up on some basic Python topics, such as indentation, <code>while</code> loops, and variables.</p>
<p>Hope this helps!</p>
<p>Finally, here are 2 tests. One of which I successfully guess the correct answer and the other I guess until the counter is reached.</p>
<pre><code>4 + 9
Enter answer: 3
Incorrect.
4 + 9
Enter answer: 2
Incorrect.
4 + 9
Enter answer: 1
Incorrect.
9 + 8
Enter answer: 17
Correct.
</code></pre>
<p>In both of these examples I called the function with <code>game(3)</code>.</p>
| 0
|
2016-09-04T04:07:11Z
|
[
"python",
"variables",
"scope",
"definition"
] |
Slicing after convolution , -1 index does not work
| 39,313,232
|
<p>After going through the N-Dimensional array convolution in Python found here on <a href="http://stackoverflow.com/questions/39220929/python-convolution-with-different-dimension"> SO</a>
I now face a problem around which I cannot wrap my head.
The convolution provided by from <code>scipy.ndimage</code> does not allow to select the 'valid' part of the convolution like Matlab's <code>convn</code> so we need to slice out the valid part. </p>
<pre><code>"valid = [slice(kernel.shape[0]//2, -kernel.shape[0]//2), slice(kernel.shape[1]//2, -kernel.shape[1]//2)]"
</code></pre>
<p>With a kernel size of [2x2], I not sure as to why I do not get a valid slice for a convolution of image [24x24] with the kernel. </p>
<pre><code>z = convolve(image,kernel)[valid]
</code></pre>
<p>In return I get a [22x22] image, where I was expecting a [23x23] image.
I thus checked the values of the slice and it seems that -1 does not work here.</p>
<p>Doing a manual slice</p>
<pre><code>convolve(image,kernel)[1:-1,1:-1] ---> Gives 22x22
convolve(image,kernel)[1:,1:] ---> Gives 23x23
</code></pre>
<p>So the question is... How come -1 gives the last item of a simple array but in my case of slicing it ignores it?</p>
<pre><code>a= np.array([100,101,102])
a[-1]
102
</code></pre>
| 1
|
2016-09-04T03:19:01Z
| 39,313,303
|
<p>In Python the upper bound of a slice is open</p>
<pre><code>In [699]: np.arange(5)
Out[699]: array([0, 1, 2, 3, 4])
In [700]: np.arange(5)[:4]
Out[700]: array([0, 1, 2, 3])
In [701]: np.arange(5)[:-1]
Out[701]: array([0, 1, 2, 3])
In [702]: np.arange(5)[1:-1]
Out[702]: array([1, 2, 3])
</code></pre>
<p>In all Python cases, list and arrays, <code>slice(1,-1)</code> removes both the first and the last item. <code>slice(1,None)</code> (same as <code>x[1:]</code>) removes just the first.</p>
<p>By itself the <code>-1</code> means the last; in a slice it means <code>up to, but including, the last</code>.</p>
<pre><code>In [703]: np.arange(5)[-1]
Out[703]: 4
</code></pre>
<p>I assume the problem is just about slicing, and applies to any array regardless of whether it comes from a convolution or not.</p>
| 4
|
2016-09-04T03:32:09Z
|
[
"python",
"numpy",
"scipy"
] |
python lambda raises variable not defined error with multiple arguments
| 39,313,318
|
<p>When trying to write a one line Fibonacci sequence that I understand, I'm having an issue with <code>fib = lambda a, b: b, a + b</code> as <code>"'b' is not defined"</code></p>
<p>However, when I do <code>sum = a, b, c: a + b + c</code> I get no errors. <code>sum(1, 2, 3)</code> runs perfectly and returns <code>6</code>.</p>
<p>I've researched global variables and found that if I set a and b to Null before starting, it doesn't give me an error, but is there a way not to do this?</p>
| 0
|
2016-09-04T03:37:02Z
| 39,313,353
|
<p>You need to put parentheses around the lambda body:</p>
<pre><code>fib = lambda a, b: (b, a + b)
</code></pre>
<p>Otherwise Python thinks it is this:</p>
<pre><code>fib = (lambda a, b: b), a + b
</code></pre>
<p>Incidentally, there's no real purpose in using <code>lambda</code> if you're just going to assign the function to a name.</p>
| 4
|
2016-09-04T03:44:41Z
|
[
"python",
"python-3.x",
"lambda"
] |
Probabilistic agent traversing a 4x4 grid world with joint probability distribution
| 39,313,407
|
<p>Iâm trying to solve a probabilistic agent for a simple board game from the book A Modern Approach to AI, but am having some trouble with the basic math and mostly the full joint distribution, so Iâm asking for some pointers.</p>
<p>The board is 4x4 squares
There is 1 monster and 2 pits somewhere on the board
The monster and pits give out a stench/breeze in its adjacent squares giving the agent clues if there are pits/monsters nearby</p>
<p>Rooms written as tuples of their coordinate on the grid: (x,y) from 1-4</p>
<p>For example:</p>
<p>Rooms (1, 1), (1, 2), (2, 1) is visited and we found
breezes in rooms (1, 2) and (2, 1)</p>
<p>This tells me that there could be pits in either room adjacent to (1, 2) and (2, 1)</p>
<p>P is Probability of a pit
This variable is uniformly distributed over the 4x4 grid (16 rooms) in the beginning so we get a probability of 0.2 that there is a Pit or a Monster per square</p>
<p>B is whether there is a breeze or stench in the visited rooms (which means the probability of it being a pit next to them is higher</p>
<p>The full joint distribution should then be P(P11, â¦, P44, B11, B12, B21)</p>
<p>The product rule gives us that </p>
<p>P(P11, â¦, P44, B11, B12, B21) =</p>
<p>P(B11, B12, B21 | P11, â¦, P44) P(P11, â¦, P44)</p>
<p><a href="http://i.stack.imgur.com/U2jmg.png" rel="nofollow">Product Rule on Full Joint Distribution</a></p>
<p>So far so good, but it is here that I canât seem to take the next step.</p>
<p>The second term I have since its evenly distributed probability of 0.2 over the rooms.
But for the first term there should be 1 if the rooms with breeze (B21 and B12) is adjacent to a pit/monster. But what are the numbers for B? And how do I get that? </p>
<p>The AIMA book states: âThe first term is the conditional probability distribution of a breeze configuration, given a pit configuration; its values are 1 if the breezes are adjacent to the pits and 0 otherwiseâ</p>
<p>Iâm been struggling with this for days and making no headway. Any help would be appreciated.</p>
| 2
|
2016-09-04T03:57:03Z
| 39,316,486
|
<p>The Bxy values are indicators of whether or not a breeze was observed in a cell xy. They're formally defined as:</p>
<p>Bxy = 1 if and only if a breeze was observed in (x, y),<br>
Bxy = 0 otherwise</p>
<p>So, in your example situation, we already know that<br>
B11 = 0, B12 = 1, B21 = 1</p>
<p>Similarly, the variables P11, P12, ..., P44 are also binary variables, where Pxy = 1 if and only if there is a pit in the cell (x, y).</p>
<p>Now to have a look at that first term, which I believe is what your question is about, the thing that you didn't understand:</p>
<p><strong>P</strong>(B11, B12, B21 | P11, ..., P44)</p>
<p>This is the conditional probability distribution of making the observations (B11, B12, B21) given that there are pits located in the cells (x, y) where Pxy = 1.</p>
<p>In the example situation, you are able to fill in the values for B11, B12, and B21. You know that B11 = 0, and B12 = B21 = 1 (because that's what was observed). You don't know in which locations the pits are, so you cannot directly fill in the Pxy values specifically for your situation. However, you <em>can</em> fill in those values for any arbitrary situation you can think of.</p>
<p>You can say "ok, let's assume there is only a pit in location (1, 3)". Then we have P13 = 1, and all other Pxy = 0. For such a specific situation, it is also possible to compute the probability of that specific situation happening (which would be 0, because you can't observe a breeze in (2, 1) if there's only a pit in (1, 3)). </p>
<p>If you repeat this for all possible situations you can imagine, you can combine the results to get more interesting answers, such as the probability of there being a pit in a certain location, given the observations you made. That's what the text further down is about though, and I believe that's no longer what your question was about.</p>
| 0
|
2016-09-04T11:35:37Z
|
[
"python",
"artificial-intelligence",
"probability",
"agent"
] |
__init__() compared to __init__.py
| 39,313,413
|
<p>I am working on a game right now but I really hate having a few thousand lines to scroll through when finding a bug to fix or a new feature has stuffed up another function. I have kept everything in one main class and when I looked into writing each function into a different file, I had one problem, I couldn't find anything</p>
<pre><code>class game:
def __init__( self ):
self.foo = "Foo"
def function( self, bar ):
self.bar = bar
</code></pre>
<p>so if we put it into a file system, it should look something like this</p>
<p><strong>game/</strong></p>
<ul>
<li><p><strong>__init__.py</strong></p></li>
<li><p><strong>function.py</strong></p></li>
</ul>
<p>and I do not know how to pass self or function into either init or funtion. Is there some sort of
__brackets
__ = ( self, bar ) code that will help me, or will I continue to have to scroll through heaps of code?</p>
| 0
|
2016-09-04T03:57:56Z
| 39,313,575
|
<p>I was wrong in my comment, you can do as you describe, but as @Ignacio stated its not good code design. Here's an example anyway because I was curious:</p>
<pre><code>#Empty my_game 'class'
class my_game:
pass
#Function you can put in a different file and import here
#Will become set as the new init function to 'my_game'
def my_games_init(self,x,y):
self.x = x
self.y = y
#Assigning 'my_games_init' function to be used as init of 'my_game' class
my_game.__init__ = my_games_init
#Make a 'my_game' instance and show that it's x and y methods were set
g = my_game(1,2)
print g.x
print g.y
</code></pre>
| 0
|
2016-09-04T04:33:58Z
|
[
"python",
"filesystems",
"init"
] |
Does python have an equivalent to Javascript's 'btoa'
| 39,313,421
|
<p>I'm trying to find an exact equivalent to javascript's function 'btoa', as I want to encode a password as base64. It appears that there are many options however, as listed here: </p>
<p><a href="https://docs.python.org/3.4/library/base64.html" rel="nofollow">https://docs.python.org/3.4/library/base64.html</a></p>
<p>Is there an exact equivalent to 'btoa' in python? </p>
| 2
|
2016-09-04T03:58:57Z
| 39,313,581
|
<p>Python's <a href="https://docs.python.org/3.4/library/base64.html" rel="nofollow">Base64</a>:</p>
<pre><code>import base64
encoded = base64.b64encode('Hello World!')
print encoded
# value of encoded is SGVsbG8gV29ybGQh
</code></pre>
<p>Javascript's <a href="http://www.w3schools.com/jsref/met_win_btoa.asp" rel="nofollow">btoa</a>:</p>
<pre><code>var str = "Hello World!";
var enc = window.btoa(str);
var res = enc;
// value of res is SGVsbG8gV29ybGQh
</code></pre>
<p>As you can see they both produce the same result.</p>
| 3
|
2016-09-04T04:34:51Z
|
[
"python",
"base64"
] |
The use of recursion in merge sort for python
| 39,313,492
|
<p>I am learning merge sort in python, and I am a little confused by the implementation of the following program. According to my understanding, when <code>mergeSort ([3,1], compare)</code> is implemented, it splits into <code>mergeSort([3], compare)</code> and <code>mergeSort([1], compare)</code>. and then <code>merge([3],[1], compare)</code> should be called, so that the <code>print</code> statement should be <code>left = [1,3]</code>, but the program actually prints out <code>left = [3,1]</code>, same for other <code>print</code> statements, why? Thank you very much.</p>
<pre><code>def merge(left, right, compare):
"""Assumes left and right are sorted lists and compare defines an ordering
on the elements.
Returns a new sorted (by compare list containing the same elements as
(left + right) would contain."""
result = []
i,j = 0, 0
while i < len(left) and j < len(right):
if compare(left[i], right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i += 1
while (j < len(right)):
result.append(right[j])
j += 1
return result
import operator
def mergeSort(L, compare = operator.lt):
"""Assumes L is a list, compare defines an ordering on elements of L
Returns a new sorted list containing the same elements as L"""
if len(L) < 2:
return L[:]
else:
middle = len(L)//2
print "middle =", middle
left = mergeSort(L[:middle], compare)
print "left = ", L[:middle]
right = mergeSort(L[middle:], compare)
print "right = ", L[middle:]
return merge(left, right, compare)
</code></pre>
<hr>
<pre><code>>>> L = [3,1,2,5,4,9,6,7,8]
>>> mergeSort(L, compare = operator.lt)
middle = 4
middle = 2
middle = 1
left = [3]
right = [1]
left = [3, 1]
middle = 1
left = [2]
right = [5]
right = [2, 5]
left = [3, 1, 2, 5]
middle = 2
middle = 1
left = [4]
right = [9]
left = [4, 9]
middle = 1
left = [6]
middle = 1
left = [7]
right = [8]
right = [7, 8]
right = [6, 7, 8]
right = [4, 9, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
| 2
|
2016-09-04T04:13:50Z
| 39,313,542
|
<p>This code prints <code>L</code> as it is being recursively split apart. It doesn't actually print the result of any merges. You can see the result of each merge by changing the line</p>
<pre><code>return merge(left, right, compare)
</code></pre>
<p>to</p>
<pre><code>merged = merge(left, right, compare)
print "merged = ", merged
return merged
</code></pre>
| 0
|
2016-09-04T04:27:48Z
|
[
"python",
"recursion",
"mergesort"
] |
The use of recursion in merge sort for python
| 39,313,492
|
<p>I am learning merge sort in python, and I am a little confused by the implementation of the following program. According to my understanding, when <code>mergeSort ([3,1], compare)</code> is implemented, it splits into <code>mergeSort([3], compare)</code> and <code>mergeSort([1], compare)</code>. and then <code>merge([3],[1], compare)</code> should be called, so that the <code>print</code> statement should be <code>left = [1,3]</code>, but the program actually prints out <code>left = [3,1]</code>, same for other <code>print</code> statements, why? Thank you very much.</p>
<pre><code>def merge(left, right, compare):
"""Assumes left and right are sorted lists and compare defines an ordering
on the elements.
Returns a new sorted (by compare list containing the same elements as
(left + right) would contain."""
result = []
i,j = 0, 0
while i < len(left) and j < len(right):
if compare(left[i], right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i += 1
while (j < len(right)):
result.append(right[j])
j += 1
return result
import operator
def mergeSort(L, compare = operator.lt):
"""Assumes L is a list, compare defines an ordering on elements of L
Returns a new sorted list containing the same elements as L"""
if len(L) < 2:
return L[:]
else:
middle = len(L)//2
print "middle =", middle
left = mergeSort(L[:middle], compare)
print "left = ", L[:middle]
right = mergeSort(L[middle:], compare)
print "right = ", L[middle:]
return merge(left, right, compare)
</code></pre>
<hr>
<pre><code>>>> L = [3,1,2,5,4,9,6,7,8]
>>> mergeSort(L, compare = operator.lt)
middle = 4
middle = 2
middle = 1
left = [3]
right = [1]
left = [3, 1]
middle = 1
left = [2]
right = [5]
right = [2, 5]
left = [3, 1, 2, 5]
middle = 2
middle = 1
left = [4]
right = [9]
left = [4, 9]
middle = 1
left = [6]
middle = 1
left = [7]
right = [8]
right = [7, 8]
right = [6, 7, 8]
right = [4, 9, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
| 2
|
2016-09-04T04:13:50Z
| 39,313,574
|
<p>This is the problem:</p>
<pre><code> print "left = ", L[:middle] # content of L before sorting
</code></pre>
<p>Replace this line and other analogous <code>print</code> statements with:</p>
<pre><code> print "left = ", left # actual result of mergeSort
</code></pre>
| 2
|
2016-09-04T04:33:52Z
|
[
"python",
"recursion",
"mergesort"
] |
The use of recursion in merge sort for python
| 39,313,492
|
<p>I am learning merge sort in python, and I am a little confused by the implementation of the following program. According to my understanding, when <code>mergeSort ([3,1], compare)</code> is implemented, it splits into <code>mergeSort([3], compare)</code> and <code>mergeSort([1], compare)</code>. and then <code>merge([3],[1], compare)</code> should be called, so that the <code>print</code> statement should be <code>left = [1,3]</code>, but the program actually prints out <code>left = [3,1]</code>, same for other <code>print</code> statements, why? Thank you very much.</p>
<pre><code>def merge(left, right, compare):
"""Assumes left and right are sorted lists and compare defines an ordering
on the elements.
Returns a new sorted (by compare list containing the same elements as
(left + right) would contain."""
result = []
i,j = 0, 0
while i < len(left) and j < len(right):
if compare(left[i], right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i += 1
while (j < len(right)):
result.append(right[j])
j += 1
return result
import operator
def mergeSort(L, compare = operator.lt):
"""Assumes L is a list, compare defines an ordering on elements of L
Returns a new sorted list containing the same elements as L"""
if len(L) < 2:
return L[:]
else:
middle = len(L)//2
print "middle =", middle
left = mergeSort(L[:middle], compare)
print "left = ", L[:middle]
right = mergeSort(L[middle:], compare)
print "right = ", L[middle:]
return merge(left, right, compare)
</code></pre>
<hr>
<pre><code>>>> L = [3,1,2,5,4,9,6,7,8]
>>> mergeSort(L, compare = operator.lt)
middle = 4
middle = 2
middle = 1
left = [3]
right = [1]
left = [3, 1]
middle = 1
left = [2]
right = [5]
right = [2, 5]
left = [3, 1, 2, 5]
middle = 2
middle = 1
left = [4]
right = [9]
left = [4, 9]
middle = 1
left = [6]
middle = 1
left = [7]
right = [8]
right = [7, 8]
right = [6, 7, 8]
right = [4, 9, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
| 2
|
2016-09-04T04:13:50Z
| 39,313,577
|
<pre><code>left = mergeSort(L[:middle], compare)
print "left = ", left
right = mergeSort(L[middle:], compare)
print "right = ", right
</code></pre>
<p>This should work.</p>
| 1
|
2016-09-04T04:34:19Z
|
[
"python",
"recursion",
"mergesort"
] |
Directing output from cron (calls) bash (calls) python3
| 39,313,645
|
<p>I have a simple python script, <code>test.py</code>, which prints the date and time and then raises an error. </p>
<p>I have a bash function defined in <code>.bash_profile</code> and named <code>test()</code>, which calls the script with </p>
<pre><code>$ python3 ~/test.py
</code></pre>
<p>Finally, I have a cron line set to call the <code>test()</code> bash function once a minute for testing with </p>
<pre><code>test >> ~/$(date +\%Y-\%m-\%d_\%H:\%M:\%S).log 2>&1
</code></pre>
<p>When I run the python script or the bash function, I correctly get both the print and the error to the terminal. When cron calls the python script directory, it logs correctly. But when cron calls the bash function, nothing is written to the log file. </p>
<p><strong>Question</strong></p>
<p>How do I correctly direct the output of the python script to the log file when cron calls the bash function?</p>
| 0
|
2016-09-04T04:49:40Z
| 39,314,211
|
<p>First of all <code>test</code> is a bad name for a function as almost all shells have <code>test</code> builtin and also there is external <code>test</code> command available in almost all systems.</p>
<p>Now, when you run something in <code>cron</code>, unlike starting of a login and/or interactive shell session no session startup script is read hence the function defined in <code>~/.bash_profile</code> (<code>source</code>-d while starting login session) is not being available.</p>
<p>Note that, many systems do not use <code>bash</code> to run <code>cron</code> scripts, for example Ubuntu uses <code>dash</code>. Anyway, the <code>test</code> you are executing in <code>cron</code> is presumably that shell's builtin <code>test</code> command which will return exit code 1 without any argument.</p>
| 2
|
2016-09-04T06:38:00Z
|
[
"python",
"bash",
"cron"
] |
Directing output from cron (calls) bash (calls) python3
| 39,313,645
|
<p>I have a simple python script, <code>test.py</code>, which prints the date and time and then raises an error. </p>
<p>I have a bash function defined in <code>.bash_profile</code> and named <code>test()</code>, which calls the script with </p>
<pre><code>$ python3 ~/test.py
</code></pre>
<p>Finally, I have a cron line set to call the <code>test()</code> bash function once a minute for testing with </p>
<pre><code>test >> ~/$(date +\%Y-\%m-\%d_\%H:\%M:\%S).log 2>&1
</code></pre>
<p>When I run the python script or the bash function, I correctly get both the print and the error to the terminal. When cron calls the python script directory, it logs correctly. But when cron calls the bash function, nothing is written to the log file. </p>
<p><strong>Question</strong></p>
<p>How do I correctly direct the output of the python script to the log file when cron calls the bash function?</p>
| 0
|
2016-09-04T04:49:40Z
| 39,322,249
|
<p>Why not just put the following line directly in your <code>crontab,</code> and eliminate the <em><code>test()</code> bash function</em> middleman?</p>
<pre><code>* * * * 1 /usr/bin/python3 /home/myname/test.py >> ~/$(date +\%Y-\%m-\%d_\%H:\%M:\%S).log 2>&1
</code></pre>
| 0
|
2016-09-04T23:12:11Z
|
[
"python",
"bash",
"cron"
] |
How does python interpreter run the code line by line in the following code?
| 39,313,677
|
<p>I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file <code>ex1.py</code>,</p>
<pre><code>print "Hello world"
12variable = 'bye'
print 12variable
</code></pre>
<p>Now according to the working of interpreter, the interpreter would run the first line i.e. it prints hello world first and then show the syntax error in the next line (line-by-line working). Hence the expected output is:</p>
<pre><code>Hello world
12variable = 'bye'
^
SyntaxError: invalid syntax
</code></pre>
<p>But the actual output is -</p>
<pre><code>12variable = 'bye'
^
SyntaxError: invalid syntax
</code></pre>
<p>Why it is not printing <code>Hello World</code> at the first?</p>
| 2
|
2016-09-04T04:58:06Z
| 39,313,702
|
<p>Because your understanding of the interpreter is faulty. While it is possible for the behaviour you are describing to occur for a subset of errors it is not the common case for many (most?) errors.</p>
<p>If the interpreter can construct what it thinks is a valid program but there is an error at run time then what you are describing will happen.</p>
<p>Since the case you are pointing at is a syntax error that prevents a valid program being constructed the behaviour is as you see it.</p>
| 1
|
2016-09-04T05:04:22Z
|
[
"python",
"syntax-error",
"interpreter"
] |
How does python interpreter run the code line by line in the following code?
| 39,313,677
|
<p>I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file <code>ex1.py</code>,</p>
<pre><code>print "Hello world"
12variable = 'bye'
print 12variable
</code></pre>
<p>Now according to the working of interpreter, the interpreter would run the first line i.e. it prints hello world first and then show the syntax error in the next line (line-by-line working). Hence the expected output is:</p>
<pre><code>Hello world
12variable = 'bye'
^
SyntaxError: invalid syntax
</code></pre>
<p>But the actual output is -</p>
<pre><code>12variable = 'bye'
^
SyntaxError: invalid syntax
</code></pre>
<p>Why it is not printing <code>Hello World</code> at the first?</p>
| 2
|
2016-09-04T04:58:06Z
| 39,313,711
|
<p>It's a myth that Python is a fully interpreted language. When CPython runs a script the source code is parsed (this is where it will catch syntax errors), and compiled into bytecode (sometimes these are cached in your directory as <code>.pyc</code> files) before anything is executed. In this regard Python is not all that fundamentally different than Java or C# other than that it doesn't spend much time doing any optimizations, and I believe the bytecode is interpreted one instruction at a time, instead of being JITed to machine code (unless you're using something like PyPy).</p>
| 3
|
2016-09-04T05:06:01Z
|
[
"python",
"syntax-error",
"interpreter"
] |
How does python interpreter run the code line by line in the following code?
| 39,313,677
|
<p>I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file <code>ex1.py</code>,</p>
<pre><code>print "Hello world"
12variable = 'bye'
print 12variable
</code></pre>
<p>Now according to the working of interpreter, the interpreter would run the first line i.e. it prints hello world first and then show the syntax error in the next line (line-by-line working). Hence the expected output is:</p>
<pre><code>Hello world
12variable = 'bye'
^
SyntaxError: invalid syntax
</code></pre>
<p>But the actual output is -</p>
<pre><code>12variable = 'bye'
^
SyntaxError: invalid syntax
</code></pre>
<p>Why it is not printing <code>Hello World</code> at the first?</p>
| 2
|
2016-09-04T04:58:06Z
| 39,313,813
|
<p>It depends on how you run the Python interpréter. If you give it a full source file, it will first parse the whole file and convert it to bytecode before execution any instruction. But if you feed it line by line, it will parse and execute the code <em>bloc by bloc</em>:</p>
<ul>
<li><code>python script.py</code> : parse full file</li>
<li><code>python < script.py</code> : parse and execute by bloc</li>
</ul>
<p>The latter is typically the way you use it interactively or through a GUI shell like <code>idle</code>.</p>
| 3
|
2016-09-04T05:30:31Z
|
[
"python",
"syntax-error",
"interpreter"
] |
pandas dropping of words in dataframe
| 39,313,680
|
<p>I have a sample dataframe that I wish to drop all words and keep the values. </p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5FQ 1.047 S$55.3 UG44.2 as of 02/Jun/2016 S$8.2 mm
</code></pre>
<p>Is it possible to drop words and keep all the numbers? IE: to get the desired results below:</p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5 1.047 55.3 44.2 8.2
</code></pre>
| 1
|
2016-09-04T04:59:28Z
| 39,313,796
|
<p>One way would be to do:</p>
<pre><code>In [212]: df
Out[212]:
Column1 Column2 Column3 Column4 Column5
0 5FQ 1.047 S$55.3 UG44.2 as of 02/Jun/2016 S$8.2 mm
In [213]: df.apply(lambda x: x.astype(str).str.extract(r'(\d+\.?\d*)', expand=True).astype(np.float))
Out[213]:
Column1 Column2 Column3 Column4 Column5
0 5.0 1.047 55.3 44.2 8.2
</code></pre>
| 3
|
2016-09-04T05:27:34Z
|
[
"python",
"regex",
"dataframe"
] |
pandas dropping of words in dataframe
| 39,313,680
|
<p>I have a sample dataframe that I wish to drop all words and keep the values. </p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5FQ 1.047 S$55.3 UG44.2 as of 02/Jun/2016 S$8.2 mm
</code></pre>
<p>Is it possible to drop words and keep all the numbers? IE: to get the desired results below:</p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5 1.047 55.3 44.2 8.2
</code></pre>
| 1
|
2016-09-04T04:59:28Z
| 39,313,799
|
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow"><code>pd.Series.extract</code></a>:</p>
<pre><code>In [28]: for c in df:
df[c] = df[c].str.extract('(\d+\.?\d*)', expand=False)
....:
In [29]: df
Out[29]:
Column1 Column2 Column3 Column4 Column5
0 5 1.047 55.3 44.2 8.2
</code></pre>
<p>Note that this is a bit brittle, as in <code>Column4</code> it works because the date appeared after the quantity. Your question doesn't specify anything more precise, though.</p>
| 3
|
2016-09-04T05:27:45Z
|
[
"python",
"regex",
"dataframe"
] |
Python Profiling: What does "method 'poll' of 'select.poll' objects"?
| 39,313,762
|
<p>I have profiled my python code using python's <code>cProfile</code> module and got the following results:</p>
<pre><code> ncalls tottime percall cumtime percall filename:lineno(function)
13937860 96351.331 0.007 96351.331 0.007 {method 'poll' of 'select.poll' objects}
13930480 201.012 0.000 201.012 0.000 {built-in method posix.read}
13937860 180.207 0.000 97129.916 0.007 connection.py:897(wait)
13937860 118.066 0.000 96493.283 0.007 selectors.py:356(select)
6968925 86.243 0.000 97360.129 0.014 queues.py:91(get)
13937860 76.067 0.000 194.402 0.000 selectors.py:224(register)
13937860 64.667 0.000 97194.582 0.007 connection.py:413(_poll)
13930480 64.365 0.000 279.040 0.000 connection.py:374(_recv)
31163538/17167548 64.083 0.000 106.596 0.000 records.py:230(__getattribute__)
13937860 57.454 0.000 264.845 0.000 selectors.py:341(register)
...
</code></pre>
<p>Obviously, my program spends most of its running time in the <code>method 'poll' of 'select.poll' objects</code>. However, I have no clue when and why this method is called and what I have to change in my program in order to reduce these method calls. </p>
<p>So, what could I look for to avoid this bottleneck in my code?</p>
<p>I am using 64bit python 3.5 with numpy and <a href="https://pypi.python.org/pypi/sharedmem/0.3" rel="nofollow">sharedmem</a> on a Linux server.</p>
| 0
|
2016-09-04T05:20:00Z
| 39,313,825
|
<p>It's part of the python library. It's used to read events from I/O. By definition it will wait for events so it will take longer. Not something that you should be changing.</p>
| 0
|
2016-09-04T05:34:47Z
|
[
"python",
"methods",
"profiling"
] |
Python Profiling: What does "method 'poll' of 'select.poll' objects"?
| 39,313,762
|
<p>I have profiled my python code using python's <code>cProfile</code> module and got the following results:</p>
<pre><code> ncalls tottime percall cumtime percall filename:lineno(function)
13937860 96351.331 0.007 96351.331 0.007 {method 'poll' of 'select.poll' objects}
13930480 201.012 0.000 201.012 0.000 {built-in method posix.read}
13937860 180.207 0.000 97129.916 0.007 connection.py:897(wait)
13937860 118.066 0.000 96493.283 0.007 selectors.py:356(select)
6968925 86.243 0.000 97360.129 0.014 queues.py:91(get)
13937860 76.067 0.000 194.402 0.000 selectors.py:224(register)
13937860 64.667 0.000 97194.582 0.007 connection.py:413(_poll)
13930480 64.365 0.000 279.040 0.000 connection.py:374(_recv)
31163538/17167548 64.083 0.000 106.596 0.000 records.py:230(__getattribute__)
13937860 57.454 0.000 264.845 0.000 selectors.py:341(register)
...
</code></pre>
<p>Obviously, my program spends most of its running time in the <code>method 'poll' of 'select.poll' objects</code>. However, I have no clue when and why this method is called and what I have to change in my program in order to reduce these method calls. </p>
<p>So, what could I look for to avoid this bottleneck in my code?</p>
<p>I am using 64bit python 3.5 with numpy and <a href="https://pypi.python.org/pypi/sharedmem/0.3" rel="nofollow">sharedmem</a> on a Linux server.</p>
| 0
|
2016-09-04T05:20:00Z
| 39,314,087
|
<p>After doing some experiments I figured it out: My program does most of its work wrapped in sharedmem's parallel map method:</p>
<pre><code>with sharedmem.MapReduce() as pool:
pool.map(myMethod, argumentList)
</code></pre>
<p>However, <code>myMethod</code> does not appear anywhere in the profile log. Moreover, no method called from within <code>myMethod</code> is being profiled properly. Instead, all time the program spends in <code>myMethod</code> goes under <code>method 'poll' of 'select.poll' objects</code> in the log. That is, profiling does not work well with sharedmem's <code>map</code> method and I have to find a different way to optimize my program.</p>
| 0
|
2016-09-04T06:18:14Z
|
[
"python",
"methods",
"profiling"
] |
UnicodeEncodeError Only When Script is Run as a Subprocess
| 39,313,780
|
<p>I'm running my main script in Python 3.5 using the Spyder IDE, and I want to import functions from a script that happens to only work in Python 3.4. So I was recommended to run this second script as a subprocess like so:</p>
<pre><code>import subprocess
cmd = [r'c:\python34\pythonw.exe', r'C:\users\John\Desktop\scraper.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print(stdout)
print(stderr)
</code></pre>
<p>The script being called is an example from NikolaiT's Web engine scraper:</p>
<pre><code># -*- coding: utf-8 -*-
import sys
from GoogleScraper import scrape_with_config, GoogleSearchError
from GoogleScraper.database import ScraperSearch, SERP, Link
def basic_usage():
# See in the config.cfg file for possible values
config = {
'SCRAPING': {
'use_own_ip': 'True',
'search_engines': 'baidu',
'num_pages_for_keyword': 3
},
'keyword': 'è¹æ',
'SELENIUM': {
'sel_browser': 'chrome',
},
'GLOBAL': {
'do_caching': 'False'
}
}
try:
sqlalchemy_session = scrape_with_config(config)
except GoogleSearchError as e:
print(e)
# let's inspect what we got
link_list = []
for serp in sqlalchemy_session.serps:
#print(serp)
for link in serp.links:
#print(link)
link_list.append(link.link)
return link_list
links = basic_usage()
print("test")
for link in links:
print(link)
</code></pre>
<p>This script works just fine when running it in Python 3.4's IDLE IDE, but when running it as a subprocess as above, I get the following UnicodeEncodeError printed from my main script:</p>
<p>\python34\scripts\googlescraper\GoogleScraper\caching.py", line 413,
in parse_all_cached_files store_serp_result(serp, self.config) </p>
<p>File "c:\python34\scripts\googlescraper\GoogleScraper\output_converter.py", line 123, in store_serp_result pprint.pprint(data) </p>
<p>File "c:\python34\lib\pprint.py", line 52, in pprint printer.pprint(object) </p>
<p>File "c:\python34\lib\pprint.py", line 139, in pprint self._format(object, self._stream, 0, 0, {}, 0) </p>
<p>File "c:\python34\lib\pprint.py", line 193, in _format allowance + 1, context, level) </p>
<p>File "c:\python34\lib\pprint.py", line 268, in _format write(rep) </p>
<p>File "c:\python34\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: \'charmap\' codec can\'t encode characters in position 1-2: character maps to undefined'</p>
<p>Why would this only happen when running it indirectly? Thanks for any help, clarification questions, or suggestions for improvement in framing my question.</p>
| 0
|
2016-09-04T05:23:46Z
| 39,314,123
|
<p>In short, your issue is as follows:</p>
<ul>
<li>Python IDE fully supports UTF-8 encoding, and that's why your invoked script runs fine there.</li>
<li>On the other hand, when opening a subprocess, since you are on Windows, you are using Windows1252 charset by default, which doesn't support part of your output.</li>
</ul>
<p>Quick solution: If you invoke the script as <code>python foobar.py</code> on Windows command line, you can run <code>chcp 65001</code> before invoking the script; if you use Spyder IDE, there should be a setting that allows you to set file / project encoding to UTF-8.</p>
<p>(You may also try adding <code># -*- coding: utf-8 -*-</code> to the top of your main Python script.)</p>
| 0
|
2016-09-04T06:23:08Z
|
[
"python",
"subprocess"
] |
Sentinel object and it's applications?
| 39,313,943
|
<p>I know in python the builtin object() returns a sentinel object. I'm curious to what it is, but mainly it's applications. </p>
<p>Thanks.</p>
| 0
|
2016-09-04T05:52:40Z
| 39,314,200
|
<p><code>object</code> is the base class that all other classes inherit from in python 3. There's not a whole lot you can do with a plain old object. However an object's <em>identity</em> could be useful. For example the <a href="https://docs.python.org/3/library/functions.html#iter" rel="nofollow">iter</a> function takes a <code>sentinel</code> argument that signals went to stop termination. We could supply an object() to that.</p>
<pre><code>sentinel = object()
def step():
inp = input('enter something: ')
if inp == 'stop' or inp == 'exit' or inp == 'done':
return sentinel
return inp
for inp in iter(step, sentinel):
print('you entered', inp)
</code></pre>
<p>This will ask for input until the user types stop, exit, or done. I'm not exactly sure when <code>iter</code> with a sentinel is more useful than a generator, but I guess it's interesting anyway.</p>
<p>I'm not sure if this answers your question. To be clear, this is just a possible application of <code>object</code>. Fundamentally its existence in the python language has nothing to do with it being usable as a sentinel value (to my knowledge).</p>
| 1
|
2016-09-04T06:36:00Z
|
[
"python"
] |
python..I am stuck with one of the functions for and while loop
| 39,314,011
|
<p>I need to create a game to be played n times and adds numbers from 0 to 10. First number is entered by the player, second is generated by the program. After that the player has to guess the answer. If it is correct the program prints'correct' and same for the opposite('incorrect').In the end of the game the program prints how many correct answers the player got out of n times.
The game runs n times</p>
<pre><code>>>> game(3) #will run 3 times
</code></pre>
<p>I got all of it working correct but then how do I get the last part which is the program counts the correct answers and get the message printed?
Thank you!</p>
<pre><code>import random
def game(n):
for _ in range(n):
a=eval(input('Enter a number:'))
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=eval(input('Enter your answer:'))
result=a+b
count=0
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
</code></pre>
| -1
|
2016-09-04T06:06:22Z
| 39,314,066
|
<p>Value of <code>count</code> is reinitialize every time to zero </p>
<pre><code>def game(n):
count=0 # declare count here
for _ in range(n): # you can use some variable here instead of _ to increase code clarity
a=int(input('Enter a number:')) # As suggested use int instead of eval read end of post
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=int(input('Enter your answer:'))
result=a+b
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print(count)
</code></pre>
<p>reason eval is insecure because <code>eval</code> can execute the code given as input eg.</p>
<pre><code> x = 1
eval('x + 1')
</code></pre>
<p>user can give input like this which will result in 2 even more dangerous,the user can also give commands as input which can harm your system, if you have <code>sys import</code> then the below code can delete all your files</p>
<pre><code>eval(input())
</code></pre>
<p>where this <code>os.system('rm -R *')</code> command can be given as input </p>
| 0
|
2016-09-04T06:15:56Z
|
[
"python"
] |
python..I am stuck with one of the functions for and while loop
| 39,314,011
|
<p>I need to create a game to be played n times and adds numbers from 0 to 10. First number is entered by the player, second is generated by the program. After that the player has to guess the answer. If it is correct the program prints'correct' and same for the opposite('incorrect').In the end of the game the program prints how many correct answers the player got out of n times.
The game runs n times</p>
<pre><code>>>> game(3) #will run 3 times
</code></pre>
<p>I got all of it working correct but then how do I get the last part which is the program counts the correct answers and get the message printed?
Thank you!</p>
<pre><code>import random
def game(n):
for _ in range(n):
a=eval(input('Enter a number:'))
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=eval(input('Enter your answer:'))
result=a+b
count=0
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
</code></pre>
| -1
|
2016-09-04T06:06:22Z
| 39,314,122
|
<p>Do not use <code>eval</code>. You expect an integer from the user, use <code>int</code>. </p>
<p>Then move the <code>count</code> variable outside the loop to avoid recreating new <code>count</code> variables with every iteration and resetting the value to zero.</p>
<pre><code>def game(n):
count = 0
for _ in range(n):
a = int(input('Enter a number:'))
b = random.randrange(0,10)
print(a,'+',b,'=')
answer = int(input('Enter your answer:'))
result = a + b
if answer != result:
print('Incorrect')
else:
count = count + 1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
</code></pre>
<p>The use of <code>int</code> will also help you properly handle exceptions when the user input is not an integer. See <a href="https://docs.python.org/2/tutorial/errors.html" rel="nofollow">Handling exceptions</a>.</p>
<p>P.S. On using <code>eval</code>: <a href="http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice">Is using eval in Python a bad practice?</a></p>
| 0
|
2016-09-04T06:23:08Z
|
[
"python"
] |
do I need lock to protect mutli-thread race condition in my code
| 39,314,024
|
<p>Using Python 2.7 on Windows, and will use Jython which support true multi-threading. The method <code>sendMessage</code> is used to receive message from a specific client, and the client may send the same message to a few other clients (which is what parameter <code>receivers</code> is for, and <code>receivers</code> is a list). The method <code>receiveMessage</code> is used to receive message for a specific client, which are sent from other clients.</p>
<p>The question is whether I need any locks for method <code>sendMessage</code> and <code>receiveMessage</code>? I think there is no need, since even if a client X is receiving its message, it is perfect fine for another client Y to append to message pool to deliver message to client X. And I think for defaultdict/list, append/pop are both atomic and no need for protection.</p>
<p>Please feel free to correct me if I am wrong.</p>
<pre><code>from collections import defaultdict
class Foo:
def __init__(self):
# key: receiver client ID, value: message
self.messagePool = defaultdict(list)
def sendMessage(self, receivers, message):
# check valid for receivers
for r in receivers:
self.messagePool[r].append(message)
def receiveMessage(self, clientID):
result = []
while len(self.messagePool[clientID]) > 0:
result.append(self.messagePool[clientID].pop(0))
return result
</code></pre>
| 1
|
2016-09-04T06:08:54Z
| 39,343,271
|
<p>Race conditions is about two or more threads changing some global states at the same time.</p>
<p>In your code for <code>sendMessage</code>, you are changing <code>self.messagePool[r]</code>, which is a global object. Hence, <code>self.messagePool[r]</code> should be locked before appending a new item.</p>
<p>Same with your <code>receiveMessage</code> function.</p>
<p><code>list.append</code> and <code>list.pop</code> are armotized O(1) and O(1) operations, so it rarely would cause any race condition. However, the risk is still there.</p>
| 2
|
2016-09-06T07:42:15Z
|
[
"python",
"multithreading",
"python-2.7",
"jython"
] |
do I need lock to protect mutli-thread race condition in my code
| 39,314,024
|
<p>Using Python 2.7 on Windows, and will use Jython which support true multi-threading. The method <code>sendMessage</code> is used to receive message from a specific client, and the client may send the same message to a few other clients (which is what parameter <code>receivers</code> is for, and <code>receivers</code> is a list). The method <code>receiveMessage</code> is used to receive message for a specific client, which are sent from other clients.</p>
<p>The question is whether I need any locks for method <code>sendMessage</code> and <code>receiveMessage</code>? I think there is no need, since even if a client X is receiving its message, it is perfect fine for another client Y to append to message pool to deliver message to client X. And I think for defaultdict/list, append/pop are both atomic and no need for protection.</p>
<p>Please feel free to correct me if I am wrong.</p>
<pre><code>from collections import defaultdict
class Foo:
def __init__(self):
# key: receiver client ID, value: message
self.messagePool = defaultdict(list)
def sendMessage(self, receivers, message):
# check valid for receivers
for r in receivers:
self.messagePool[r].append(message)
def receiveMessage(self, clientID):
result = []
while len(self.messagePool[clientID]) > 0:
result.append(self.messagePool[clientID].pop(0))
return result
</code></pre>
| 1
|
2016-09-04T06:08:54Z
| 39,343,544
|
<p>I suggest to use <code>Queue</code> instead of <code>list</code>. It is designed for append\pop in threads with locking.</p>
| 4
|
2016-09-06T07:56:49Z
|
[
"python",
"multithreading",
"python-2.7",
"jython"
] |
do I need lock to protect mutli-thread race condition in my code
| 39,314,024
|
<p>Using Python 2.7 on Windows, and will use Jython which support true multi-threading. The method <code>sendMessage</code> is used to receive message from a specific client, and the client may send the same message to a few other clients (which is what parameter <code>receivers</code> is for, and <code>receivers</code> is a list). The method <code>receiveMessage</code> is used to receive message for a specific client, which are sent from other clients.</p>
<p>The question is whether I need any locks for method <code>sendMessage</code> and <code>receiveMessage</code>? I think there is no need, since even if a client X is receiving its message, it is perfect fine for another client Y to append to message pool to deliver message to client X. And I think for defaultdict/list, append/pop are both atomic and no need for protection.</p>
<p>Please feel free to correct me if I am wrong.</p>
<pre><code>from collections import defaultdict
class Foo:
def __init__(self):
# key: receiver client ID, value: message
self.messagePool = defaultdict(list)
def sendMessage(self, receivers, message):
# check valid for receivers
for r in receivers:
self.messagePool[r].append(message)
def receiveMessage(self, clientID):
result = []
while len(self.messagePool[clientID]) > 0:
result.append(self.messagePool[clientID].pop(0))
return result
</code></pre>
| 1
|
2016-09-04T06:08:54Z
| 39,357,991
|
<p>I think this question is already well-answered for CPython <a href="http://stackoverflow.com/questions/17682484/is-collections-defaultdict-thread-safe">here</a> and <a href="http://stackoverflow.com/questions/6319207/are-lists-thread-safe">here</a> (basically, you're safe because of GIL, although nothing in documentation (like on <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict</a> or <a href="https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" rel="nofollow">list</a>) officially says about that). But I understand your concern about Jython, so let's solve it using some official source, like <a href="https://hg.python.org/jython/" rel="nofollow">Jython source code</a>. A pythonic <code>list</code> is a <a href="https://hg.python.org/jython/file/tip/src/org/python/core/PyList.java" rel="nofollow">javaish <code>PyList</code></a> there with this kind of code:</p>
<pre><code>public void append(PyObject o) {
list_append(o);
}
final synchronized void list_append(PyObject o) {
...
}
public PyObject pop(int n) {
return list_pop(n);
}
final synchronized PyObject list_pop(int n) {
...
}
</code></pre>
<p>And as we have these methods <a href="http://stackoverflow.com/questions/1085709/what-does-synchronized-mean">synchronized</a>, we can be sure that list appends and pops are also thread-safe with Jython. Thus, your code seems to be safe wrt threading.</p>
<p>Although <code>Queue</code> suggestion is still valid one, it really is more appropriate for this use case.</p>
| 3
|
2016-09-06T21:18:06Z
|
[
"python",
"multithreading",
"python-2.7",
"jython"
] |
python : ImportError: No module named utils with clean_string
| 39,314,115
|
<p>Note: I have already check question with same error as mine but mine is different i want to ask if "clean_string, clean_number, clean_text, clean_float, clean_int"</p>
<p><strong><code>agency_id = scrapy.Field(serializer=clean_string)</code></strong></p>
<p>are some in built function in python or i have to import to make it work</p>
<p>I am new in python just doing some programming stuffs.</p>
<p>Below i my code snippet</p>
<pre><code>from .utils import clean_string, clean_number, clean_text, clean_float, clean_int
from six.moves.urllib.parse import urljoin
class MyItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
agency_id = scrapy.Field(serializer=clean_string)
</code></pre>
<p>when i run above code it give me error </p>
<pre><code>**ImportError: No module named utils**
</code></pre>
<p>can you help with it have i to install <strong>clean_string</strong> or something </p>
| 1
|
2016-09-04T06:22:23Z
| 39,314,228
|
<p>As per our discussion, please install <code>python -m pip install pyes</code></p>
<p>do it as below:</p>
<pre><code>from pyes import utils
# use it like below
class MyItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
agency_id = scrapy.Field(serializer=utils.clean_string)
</code></pre>
<p>(or)</p>
<pre><code>from pyes.utils import clean_string
# use it like below
class MyItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
agency_id = scrapy.Field(serializer=clean_string)
</code></pre>
<p>you cannot use <code>from .utils import clean_string</code> because it looks for <code>utils</code> in current working directory. Instead either use <code>from django import utils</code> (or) use <code>from pyes.utils import clean_string</code></p>
| 0
|
2016-09-04T06:40:07Z
|
[
"python"
] |
Why \ is used at the end of print statement in python?
| 39,314,252
|
<p>Consider the code:</p>
<pre><code>firstName = raw_input("Your fist Name: ")
lastName = raw_input("Your last Name: ")
print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>In line 3, what is the use of <code>\</code> ?</p>
| 0
|
2016-09-04T06:43:27Z
| 39,314,268
|
<p>It allows you to do a line break and continue your statement on the next line</p>
| 1
|
2016-09-04T06:45:02Z
|
[
"python",
"syntax"
] |
Why \ is used at the end of print statement in python?
| 39,314,252
|
<p>Consider the code:</p>
<pre><code>firstName = raw_input("Your fist Name: ")
lastName = raw_input("Your last Name: ")
print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>In line 3, what is the use of <code>\</code> ?</p>
| 0
|
2016-09-04T06:43:27Z
| 39,314,270
|
<p>The <code>\</code> tells Python that the statement continues on the next line. So, the <code>print</code> statement doesn't end on the first line, it continues on the next.</p>
<pre><code>print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>Is the same as:</p>
<pre><code>print "Hello %s, May I call youMr. %s?" % (firstName,lastName)
</code></pre>
| 1
|
2016-09-04T06:45:10Z
|
[
"python",
"syntax"
] |
Why \ is used at the end of print statement in python?
| 39,314,252
|
<p>Consider the code:</p>
<pre><code>firstName = raw_input("Your fist Name: ")
lastName = raw_input("Your last Name: ")
print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>In line 3, what is the use of <code>\</code> ?</p>
| 0
|
2016-09-04T06:43:27Z
| 39,314,274
|
<p>The <code>\</code> character is used to break up long lines so they're easier to read and manage. The third and fourth lines could have been written as a single line without the <code>\</code> instead: </p>
<pre><code>print "Hello %s, May I call youMr. %s?" % (firstName,lastName)
</code></pre>
<p>(note there is no space between "you" and "Mr." in the original post either)</p>
| 1
|
2016-09-04T06:45:15Z
|
[
"python",
"syntax"
] |
Why \ is used at the end of print statement in python?
| 39,314,252
|
<p>Consider the code:</p>
<pre><code>firstName = raw_input("Your fist Name: ")
lastName = raw_input("Your last Name: ")
print "Hello %s, May I call you" \
"Mr. %s?" % (firstName,lastName)
</code></pre>
<p>In line 3, what is the use of <code>\</code> ?</p>
| 0
|
2016-09-04T06:43:27Z
| 39,314,276
|
<p>to make you able to spilt a single line of string to many lines.</p>
| 1
|
2016-09-04T06:45:32Z
|
[
"python",
"syntax"
] |
Where does `pip` install libraries compared to where `python` from terminal runs?
| 39,314,282
|
<p>I'm trying to install <code>python's scikit learn</code> for some machine learning, and it appears to do it successfully (i.e. it is already installed). However, when I try to actually use it in <code>python</code> in the terminal, it gives me an error, as shown below. </p>
<pre><code>23:39 $ sudo pip install sklearn
The directory '/Users/username/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/username/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting sklearn
Requirement already satisfied (use --upgrade to upgrade): scikit-learn in /Library/Python/2.7/site-packages (from sklearn)
Installing collected packages: sklearn
Successfully installed sklearn-0.0
â /usr/bin
23:42 $ python
Python 2.7.12rc1 (v2.7.12rc1:13912cd1e7e8, Jun 11 2016, 15:32:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sklearn
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/sklearn/__init__.py", line 57, in <module>
from .base import clone
File "/Library/Python/2.7/site-packages/sklearn/base.py", line 11, in <module>
from .utils.fixes import signature
File "/Library/Python/2.7/site-packages/sklearn/utils/__init__.py", line 11, in <module>
from .validation import (as_float_array,
File "/Library/Python/2.7/site-packages/sklearn/utils/validation.py", line 16, in <module>
from ..utils.fixes import signature
File "/Library/Python/2.7/site-packages/sklearn/utils/fixes.py", line 324, in <module>
from scipy.sparse.linalg import lsqr as sparse_lsqr
File "/usr/local/lib/python2.7/site-packages/scipy/sparse/linalg/__init__.py", line 112, in <module>
from .isolve import *
File "/usr/local/lib/python2.7/site-packages/scipy/sparse/linalg/isolve/__init__.py", line 6, in <module>
from .iterative import *
File "/usr/local/lib/python2.7/site-packages/scipy/sparse/linalg/isolve/iterative.py", line 7, in <module>
from . import _iterative
ImportError: dlopen(/usr/local/lib/python2.7/site-packages/scipy/sparse/linalg/isolve/_iterative.so, 2): Symbol not found: ___addtf3
Referenced from: /usr/local/opt/gcc/lib/gcc/6/libquadmath.0.dylib
Expected in: /usr/lib/libSystem.B.dylib
in /usr/local/opt/gcc/lib/gcc/6/libquadmath.0.dylib
>>> exit()
â /usr/bin
23:43 $ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
</code></pre>
<p>I think that there must be some difference between where the packages are installed by <code>pip install <package name></code> and where they are actually accessed when I call <code>python</code> in the terminal. </p>
<p>What is the difference between:</p>
<p>1) where packages are installed via <code>pip install <package name></code>? </p>
<p>AND</p>
<p>2) where the packages are searched for when calling <code>python</code> from the terminal? </p>
<p>I put the results of <code>which python</code> at the bottom because I think that might be useful.
Also, guys I'm using Mac OS El Capitan version 10.11.4. </p>
| 0
|
2016-09-04T06:46:14Z
| 39,314,463
|
<p>This problem doesn't have anything to do with python package paths. It is due to the unresolved symbol <code>___addtf3</code> which is a GCC software floating point routine provided by a <code>gfortran</code> library. A <a href="https://github.com/JuliaLang/julia/issues/636" rel="nofollow">similar issue with a different application</a> (completely unrelated to python) was solved by properly setting the <code>DYLD_LIBRARY_PATH</code> environment variable. Of course you must have those libraries installed on your system, which may be the real problem in your case.</p>
| 0
|
2016-09-04T07:13:23Z
|
[
"python",
"python-2.7",
"terminal",
"scikit-learn"
] |
Openerp, how to make a unique record
| 39,314,292
|
<p>I am currently working with <code>hr_holidays</code> (aka <code>Leave Management</code>) Module and I need to add leave allocation as a unique record for given type of leave.</p>
<p>I have added one extra condition in the <code>create()</code> function and that result in not allowing any making leave request to be made. </p>
<p>Following is my <code>create()</code> function: </p>
<pre><code> def create(self, cr, uid, values, context=None):
#-------what I have added starting from here------
hol_stat=values['holiday_status_id']
emp_id=values['employee_id']
n_allo=values['test_allocation']
ids=self.pool.get('hr.holidays').search(cr, uid, [('holiday_status_id','=', hol_stat),('employee_id','=', emp_id),('type','=','add')], context=context)
if ids:
raise osv.except_osv(_('Warning!'),_('Already allocated leaves .'))
# ------end from here-----
""" Override to avoid automatic logging of creation """
if context is None:
context = {}
context = dict(context, mail_create_nolog=True)
if ('date_from' in values and 'date_to' in values):
define_holidays = self.pool.get('company.holidays').search(cr, uid, ['|',('date', '=', values['date_from']),('date', '=', values['date_to'])])
if define_holidays:
raise osv.except_osv(_('Warning!'),_('You need not to apply leaves one Company holidays.'))
else:
return super(hr_holidays, self).create(cr, uid, values, context=context)
else:#mani
return super(hr_holidays, self).create(cr, uid, values, context=context)
</code></pre>
<p><strong>Question</strong></p>
<p>How can I alter my <code>create()</code> function to achieve the unique record requirement?</p>
| 0
|
2016-09-04T06:47:49Z
| 39,316,446
|
<p>Instead of doing a search anytime you want to create a new record, enforce a <code>UniqueConstraint</code> on the database, that wouldn't allow duplicate records to be created, with this</p>
<pre><code>_sql_constraints = [
('unique_hol_empid_type', 'unique(holiday_status_id, employee_id, type)', 'Error: Already allocated leaves'),
]
</code></pre>
<p>the unique constraint is a combination of the three columns you want, and <code>unique_hol_empid_type</code> is the name we gave to the constraint (at the database layer) and the error will be raised anytime a record violates that constraint.</p>
| 1
|
2016-09-04T11:31:08Z
|
[
"python",
"python-2.7",
"openerp"
] |
ordinal suffix of the letter of a word python 3.5.
| 39,314,327
|
<pre><code>import random
import string
import sys
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = [x for x in string.ascii_lowercase if x not in vowels]
SelectedWords = ['TRAILER', 'LAPTOP', 'SUNFLOWER', 'SKIPPING', 'AIRPLANE', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'WAGON', 'QUESTION', 'LAGOON', 'CAT', 'DUCK', 'GOANNA', 'POSTER', 'FUTURE', 'PRINCESS', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'RUNNING', 'SPEAKER', 'QUICKLY']
word_map = {x:{'consonants':len([y for y in x.lower() if y in consonants]), 'vowels':len([y for y in x.lower() if y in vowels]), 'letters':len(x)} for x in SelectedWords}
</code></pre>
<p>the below is part of a loop that creates random questions from 4 choices and then assigns a word to those questions. </p>
<p>For this question when the program might get a results of what is the letter 5 of hospital, the user would then input a answer and then get a correct or incorrect response. What I'm trying to do is get the ordinal suffix of the letter as well . So the question could be "what is the 5th letter of hospital"</p>
<pre><code> n = random.randint(1, len(x))
correct = x[n-1]
if sys.version.startswith('3'):
ans = str(input('What is letter {} of "{}"?'.format(n, x)))
else:
ans = str(raw_input('What is letter {} of "{}"?'.format(n, x)))
</code></pre>
| -3
|
2016-09-04T06:53:31Z
| 39,314,419
|
<p>If you are looking to convert 1 => 1st, 2 => 2nd, 3 => 3rd, etc... this is the easiest way I can think of. This special cases 1, 2, 3 and all numbers ending in 1, 2 or 3 except 11, 12 and 13.</p>
<pre><code>num_suffix = lambda x: "{}{}".format(x, {1: "st", 2: "nd", 3: "rd"}.get(0 if 10 > x > 14 else x % 10, "th"))
for i in range(1, 40):
print("{} => {}".format(i, num_suffix(i))
1 => 1st
2 => 2nd
3 => 3rd
4 => 4th
5 => 5th
6 => 6th
7 => 7th
8 => 8th
9 => 9th
10 => 10th
11 => 11th
12 => 12th
13 => 13th
14 => 14th
15 => 15th
16 => 16th
17 => 17th
18 => 18th
19 => 19th
20 => 20th
21 => 21st
22 => 22nd
23 => 23rd
24 => 24th
25 => 25th
26 => 26th
27 => 27th
28 => 28th
29 => 29th
30 => 30th
31 => 31st
32 => 32nd
33 => 33rd
34 => 34th
35 => 35th
36 => 36th
37 => 37th
38 => 38th
39 => 39th
</code></pre>
<p>And I think 0 is actually 0th, but not sure. You could special case that as well.</p>
| 2
|
2016-09-04T07:06:24Z
|
[
"python",
"python-3.x"
] |
ordinal suffix of the letter of a word python 3.5.
| 39,314,327
|
<pre><code>import random
import string
import sys
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = [x for x in string.ascii_lowercase if x not in vowels]
SelectedWords = ['TRAILER', 'LAPTOP', 'SUNFLOWER', 'SKIPPING', 'AIRPLANE', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'WAGON', 'QUESTION', 'LAGOON', 'CAT', 'DUCK', 'GOANNA', 'POSTER', 'FUTURE', 'PRINCESS', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'RUNNING', 'SPEAKER', 'QUICKLY']
word_map = {x:{'consonants':len([y for y in x.lower() if y in consonants]), 'vowels':len([y for y in x.lower() if y in vowels]), 'letters':len(x)} for x in SelectedWords}
</code></pre>
<p>the below is part of a loop that creates random questions from 4 choices and then assigns a word to those questions. </p>
<p>For this question when the program might get a results of what is the letter 5 of hospital, the user would then input a answer and then get a correct or incorrect response. What I'm trying to do is get the ordinal suffix of the letter as well . So the question could be "what is the 5th letter of hospital"</p>
<pre><code> n = random.randint(1, len(x))
correct = x[n-1]
if sys.version.startswith('3'):
ans = str(input('What is letter {} of "{}"?'.format(n, x)))
else:
ans = str(raw_input('What is letter {} of "{}"?'.format(n, x)))
</code></pre>
| -3
|
2016-09-04T06:53:31Z
| 39,314,421
|
<p>Here is the full revised code. There will obviously be issues with numbers larger than 10, it would be possible to either add numbers to the map or write a function with rules to determine what the correct ordinal suffix would be based on the current map but I know that the original OP didn't want any more than one function. Either way this should help.</p>
<pre><code>import random
import string
import sys
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = [x for x in string.ascii_lowercase if x not in vowels]
SelectedWords = ['TRAILER', 'LAPTOP', 'SUNFLOWER', 'SKIPPING', 'AIRPLANE', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'WAGON', 'QUESTION', 'LAGOON', 'CAT', 'DUCK', 'GOANNA', 'POSTER', 'FUTURE', 'PRINCESS', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'RUNNING', 'SPEAKER', 'QUICKLY']
word_map = {x:{'consonants':len([y for y in x.lower() if y in consonants]), 'vowels':len([y for y in x.lower() if y in vowels]), 'letters':len(x)} for x in SelectedWords}
ordinal_map = {1:'st', 2:'nd', 3:'rd', 4:'th', 5:'th', 6:'th', 7:'th', 8:'th', 9:'th', 10:'th'}
def start_test(number_questions):
current_question = 0
correct_questions = 0
if number_questions > len(SelectedWords):
number_questions = len(SelectedWords)
sample_questions = random.sample(SelectedWords, number_questions)
print sample_questions
print(' Test 1 START')
print ('---------------------')
for x in sample_questions:
print ("Question {}/{}:".format(current_question+1, number_questions))
print ('---------------------')
current_question += 1
q_type = random.randint(1, 4)
if q_type == 1:
correct = word_map[x]['letters']
ans = input('How many letters does "{}" contain?'.format(x))
elif q_type == 2:
correct = word_map[x]['vowels']
ans = input('How many vowels does "{}" contain?'.format(x))
elif q_type == 3:
correct = word_map[x]['consonants']
ans = input('How many consonants does "{}" contain?'.format(x))
else:
n = random.randint(1, len(x))
correct = x[n-1]
if sys.version.startswith('3'):
ans = str(input('What is the {}{} letter of "{}"?'.format(n, ordinal_map[int(n)], x)))
else:
ans = str(raw_input('What is the {}{} letter of "{}"?'.format(n, ordinal_map[int(n)], x)))
if str(ans).lower() == str(correct).lower():
print('Well done correct! :)')
correct_questions += 1
else:
print('Wrong :(')
print ('You have completed your test!')
print (" Score {}/{}:".format(correct_questions , number_questions))
try_again = input('Would you like to try again? (y/n)').lower()
if try_again == 'y' or try_again == 'yes':
start_test(number_questions)
start_test(9)
</code></pre>
| 0
|
2016-09-04T07:06:26Z
|
[
"python",
"python-3.x"
] |
Best practice for predicting values from model with Chainer
| 39,314,364
|
<p>With <a href="http://chainer.org/" rel="nofollow">Chainer</a>, I have created <code>model.pkl</code> with <em>Iris Datasets</em> (<a href="https://github.com/silwyb/train-iris" rel="nofollow">https://github.com/silwyb/train-iris</a>). So I can evaluate datasets, but I don't know the best way to output predicted values. </p>
<p>Please tell me how to predict. Just a function name would also be welcome.</p>
| -1
|
2016-09-04T06:58:52Z
| 39,325,789
|
<p>The following works.
<a href="https://github.com/silwyb/train-iris/blob/master/predict.py" rel="nofollow">silwyb/train-iris/predict.py</a></p>
<pre><code>def predict(x_test):
x = Variable(x_test)
h1 = F.dropout(F.relu(model.l1(x)))
h2 = F.dropout(F.relu(model.l2(h1)))
y = model.l3(h2)
return np.argmax(y.data)
</code></pre>
| 0
|
2016-09-05T07:37:11Z
|
[
"python",
"chainer"
] |
Javascript date string to python datetime object
| 39,314,501
|
<p>The current datetime is passed via an <strong>ajax request</strong> to a <strong>django backend</strong> where it will be stored in the database. To store it in the database, the date must first be converted to a <code>datetime</code> object which can be done for a date of the in UTC format (Eg. <code>Sun, 04 Sep 2016 07:13:06 GMT</code>) easily by the following statement:</p>
<pre><code>>>> from datetime import datetime
>>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT", "%a, %d %b %Y %H:%M:%S %Z")
</code></pre>
<p>However in such a method, there is no preservation of the user's timezone.</p>
<p>The javascript <code>Date</code> constructor call i.e. <code>new Date()</code> returns a date in the following format:</p>
<pre><code>Sun Sep 04 2016 12:38:43 GMT+0530 (IST)
</code></pre>
<p>which gives an error when converting to datetime object.</p>
<pre><code>>>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)", "%a, %d %b %Y %H:%M:%S %Z")
ValueError: time data 'Sun Sep 04 2016 12:46:07 GMT+0530 (IST)' does not match format '%a, %d %b %Y %H:%M:%S %Z'
</code></pre>
<p>1) How to resolve this problem?
2) Is there any better way to approach it?</p>
| 1
|
2016-09-04T07:21:23Z
| 39,314,850
|
<p>Your first problem is that the input has a different format. But unfortunatelly for you, that is not your only problem and it wouldn't work even if you fixed that.</p>
<p>The truth is that even the first format would fail with a different timezone:</p>
<pre><code>datetime.strptime("Sun, 04 Sep 2016 07:13:06 IST", "%a, %d %b %Y %H:%M:%S %Z")
</code></pre>
<p>fails with:</p>
<pre><code>ValueError: time data 'Sun, 04 Sep 2016 07:13:06 IST' does not match format '%a, %d %b %Y %H:%M:%S %Z'
</code></pre>
<p><code>strptime</code> just isn't good enough for handling timezones.</p>
<p>Check these answers for your options:</p>
<ul>
<li><a href="http://stackoverflow.com/a/12282040/389289">Answer to <em>Convert timestamps with offset to datetime obj using strptime</em></a></li>
<li><a href="http://stackoverflow.com/a/8525115/389289">Answer to <em>Python strptime() and timezones?</em></a></li>
</ul>
| 0
|
2016-09-04T08:08:44Z
|
[
"javascript",
"python",
"django",
"datetime"
] |
Javascript date string to python datetime object
| 39,314,501
|
<p>The current datetime is passed via an <strong>ajax request</strong> to a <strong>django backend</strong> where it will be stored in the database. To store it in the database, the date must first be converted to a <code>datetime</code> object which can be done for a date of the in UTC format (Eg. <code>Sun, 04 Sep 2016 07:13:06 GMT</code>) easily by the following statement:</p>
<pre><code>>>> from datetime import datetime
>>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT", "%a, %d %b %Y %H:%M:%S %Z")
</code></pre>
<p>However in such a method, there is no preservation of the user's timezone.</p>
<p>The javascript <code>Date</code> constructor call i.e. <code>new Date()</code> returns a date in the following format:</p>
<pre><code>Sun Sep 04 2016 12:38:43 GMT+0530 (IST)
</code></pre>
<p>which gives an error when converting to datetime object.</p>
<pre><code>>>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)", "%a, %d %b %Y %H:%M:%S %Z")
ValueError: time data 'Sun Sep 04 2016 12:46:07 GMT+0530 (IST)' does not match format '%a, %d %b %Y %H:%M:%S %Z'
</code></pre>
<p>1) How to resolve this problem?
2) Is there any better way to approach it?</p>
| 1
|
2016-09-04T07:21:23Z
| 39,314,936
|
<p>You can use python's <code>dateutil</code> module to parse your date.</p>
<pre><code>from dateutil import parser
parser.parse("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)")
</code></pre>
<p>It gives the output as a datetime object:</p>
<pre><code>datetime.datetime(2016, 9, 4, 7, 13, 6, tzinfo=tzoffset(u'IST', -19800))
</code></pre>
| 0
|
2016-09-04T08:22:41Z
|
[
"javascript",
"python",
"django",
"datetime"
] |
join two pandas pivot tables
| 39,314,505
|
<p>Considering two similar pandas pivot tables, how to join these two tables on their indexes e.g. <code>country</code>. For example: </p>
<pre><code>df1.pivot_table(index='country', columns='year', values=['rep','sales'], aggfunc='first')
rep sales
year 2013 2014 2015 2016 2013 2014 2015 2016
country
fr None kyle claire None None 10 20 None
uk kyle None None john 12 None None 10
usa None None None john None None None 21
df2.pivot_table(index='country', columns='year', values=['rep','sales'], aggfunc='first')
rep sales
year 2013 2014 2015 2016 2013 2014 2015 2016
country
fr 120 marc debbie None None 0 56 None
uk marc None 100 peter 45 None 65 10
ca 89 None None peter None 33 None 78
</code></pre>
| 1
|
2016-09-04T07:22:04Z
| 39,314,754
|
<blockquote>
<p>How to join these tables</p>
</blockquote>
<p>Is vague. There are many ways to join these tables.</p>
<h3>Setup</h3>
<pre><code>idx = pd.Index(['fr', 'uk', 'usa'], name='country')
col = pd.MultiIndex.from_product([['rep', 'sales'], range(2013, 2017)],
names=[None, 'year'])
p1 = pd.DataFrame([
[None, 'kyle', 'claire', None, None, 10, 20, None],
['kyle', None, None, 'john', 12, None, None, 10],
[None, None, None, 'john', None, None, None, 21]
], idx, col, object)
p2 = pd.DataFrame([
[120, 'marc', 'debbie', None, None, 0, 56, None],
['marc', None, 100, 'peter', 45, None, 65, 10],
[89, None, None, 'peter', None, 33, None, 78]
], idx, col, object)
</code></pre>
<hr>
<h3>Likely Solutions</h3>
<pre><code>p1.combine_first(p2)
</code></pre>
<p><a href="http://i.stack.imgur.com/GqhE6.png" rel="nofollow"><img src="http://i.stack.imgur.com/GqhE6.png" alt="enter image description here"></a></p>
<hr>
<pre><code>pd.concat([p1, p2], axis=1, keys=['p1', 'p2'])
</code></pre>
<p><a href="http://i.stack.imgur.com/BcHEp.png" rel="nofollow"><img src="http://i.stack.imgur.com/BcHEp.png" alt="enter image description here"></a></p>
| 1
|
2016-09-04T07:55:49Z
|
[
"python",
"pandas",
"join"
] |
CSV delimiter doesn't work properly [Python]
| 39,314,544
|
<pre><code>import csv
base='eest1@mail.ru,username1\
test2@gmail.com,username2\
test3@gmail.com,username3\
test4@rambler.ru,username4\
test5@ya.ru,username5'
parsed=csv.reader(base, delimiter=',')
for p in parsed:
print p
</code></pre>
<p>Returns:</p>
<pre><code>['e']
['e']
['s']
['t']
['1']
['@']
['m']
['a']
['i']
['l']
['.']
['r']
['u']
['', '']
</code></pre>
<p>etc...</p>
<p>How I can get data separated by comma ?
('test1@gmail.com', 'username1'),
('test2@gmail.com', 'username2'),
...</p>
| 0
|
2016-09-04T07:27:47Z
| 39,314,628
|
<p>I think csv only works with file like objects. You can use StringIO in this case.</p>
<pre><code>import csv
import StringIO
base='''eest1@mail.ru,username
test2@gmail.com,username2
test3@gmail.com,username3
test4@rambler.ru,username4
test5@ya.ru,username5'''
parsed=csv.reader(StringIO.StringIO(base), delimiter=',')
for p in parsed:
print p
</code></pre>
<p>OUTPUT</p>
<pre><code>['eest1@mail.ru', 'username']
['test2@gmail.com', 'username2']
['test3@gmail.com', 'username3']
['test4@rambler.ru', 'username4']
['test5@ya.ru', 'username5']
</code></pre>
<p>Also, your example string does not have newlines, so you would get</p>
<pre><code>['eest1@mail.ru', 'usernametest2@gmail.com', 'username2test3@gmail.com', 'username3test4@rambler.ru', 'username4test5@ya.ru', 'username5']
</code></pre>
<p>You can use the <code>'''</code> like I did, or change your <code>base</code> like</p>
<pre><code>base='eest1@mail.ru,username\n\
test2@gmail.com,username2\n\
test3@gmail.com,username3\n\
test4@rambler.ru,username4\n\
test5@ya.ru,username5'
</code></pre>
<p><strong>EDIT</strong><br>
According to the docs, the argument can be either a file-like objet OR a list. So this works too</p>
<pre><code>parsed=csv.reader(base.splitlines(), delimiter=',')
</code></pre>
| 2
|
2016-09-04T07:38:08Z
|
[
"python",
"csv"
] |
CSV delimiter doesn't work properly [Python]
| 39,314,544
|
<pre><code>import csv
base='eest1@mail.ru,username1\
test2@gmail.com,username2\
test3@gmail.com,username3\
test4@rambler.ru,username4\
test5@ya.ru,username5'
parsed=csv.reader(base, delimiter=',')
for p in parsed:
print p
</code></pre>
<p>Returns:</p>
<pre><code>['e']
['e']
['s']
['t']
['1']
['@']
['m']
['a']
['i']
['l']
['.']
['r']
['u']
['', '']
</code></pre>
<p>etc...</p>
<p>How I can get data separated by comma ?
('test1@gmail.com', 'username1'),
('test2@gmail.com', 'username2'),
...</p>
| 0
|
2016-09-04T07:27:47Z
| 39,315,289
|
<p>Quoting <a href="https://docs.python.org/3/library/csv.html#csv.reader" rel="nofollow">official docs on csv module</a> (<strong>emphasis mine</strong>):</p>
<blockquote>
<p><code>csv.reader(csvfile, dialect='excel', **fmtparams)</code></p>
<p>Return a reader object which will iterate over lines in the given
<code>csvfile</code>. <strong><code>csvfile</code> can be any object which supports the iterator
protocol and returns a string each time its <code>__next__()</code> method is
called â file objects and list objects are both suitable.</strong></p>
</blockquote>
<p>Strings supports iterator, but it yields <em>characters</em> from string one by one, not lines from multi-line string.</p>
<pre><code>>>> s = "abcdef"
>>> i = iter(s)
>>> next(i)
'a'
>>> next(i)
'b'
>>> next(i)
'c'
</code></pre>
<p>So the task is to create iterator, which would yield <em>lines</em> and not <em>characters</em> on each iterations. Unfortunately, your string literal is not a multiline string.</p>
<pre><code>base='eest1@mail.ru,username1\
test2@gmail.com,username2\
test3@gmail.com,username3\
test4@rambler.ru,username4\
test5@ya.ru,username5'
</code></pre>
<p>is equivalent to:</p>
<pre><code>base = 'eest1@mail.ru,username1test2@gmail.com,username2test3@gmail.com,username3test4@rambler.ru,username4test5@ya.ru,username5
</code></pre>
<p>Esentially you do not have information required to parse that string correctly. Try using multiline string literal instead:</p>
<pre><code>base='''eest1@mail.ru,username1
test2@gmail.com,username2
test3@gmail.com,username3
test4@rambler.ru,username4
test5@ya.ru,username5'''
</code></pre>
<p>After this change you may split your string by newlines characters and everything should work fine:</p>
<pre><code>parsed=csv.reader(base.splitlines(), delimiter=',')
for p in parsed:
print(p)
</code></pre>
| 1
|
2016-09-04T09:07:17Z
|
[
"python",
"csv"
] |
Python - Unable to detect face and eye?
| 39,314,610
|
<p>I am trying to create a face and eye detection using OpenCV library. This is the code I been working with. It's running smoothly with no errors but the only problem is not showing any results no faces and eyes are found with this code </p>
<pre><code>import cv2
import sys
import numpy as np
import os
# Get user supplied values
imagePath = sys.argv[1]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier('C:\Users\Karthik\Downloads\Programs\opencv\sources\data\haarcascades\haarcascad_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('C:\Users\Karthik\Downloads\Programs\opencv\sources\data\haarcascades\haarcascade_eye.xml')
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)
print "Found {0} faces!".format(len(faces))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = image[y:y+h, x:x+w]
eyes = eyeCascade.detectMultiscale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0, 255, 0), 2)
cv2.imshow("Faces found", image)
print image.shape
cv2.waitKey(0)
</code></pre>
| 2
|
2016-09-04T07:35:11Z
| 39,319,534
|
<p>For me it works in my jupyter notebook on Ubuntu 15.10 using OpenCV 3.1.0-dev with python 3.4</p>
<p>Could it be, that you have a simple typo?</p>
<p><code>haarcascad_frontalface_default.xml</code> => <code>haarcascade_frontalface_default.xml</code></p>
<p>and here: </p>
<p><code>eyes = eyeCascade.detectMultiscale(roi_gray)</code>
=> <code>eyeCascade.detectMultiScale(roi_gray)</code></p>
<p>That's my working code:</p>
<pre class="lang-py prettyprint-override"><code>%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import cv2
import sys
import numpy as np
import os
# Create the haar cascade
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('haarcascade_eye.xml')
# Read the image
image = cv2.imread('lena.png', 0)
if image is None:
raise ValueError('Image not found')
# Detect faces in the image
faces = faceCascade.detectMultiScale(image)
print('Found {} faces!'.format(len(faces)))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), 255, 2)
roi = image[y:y+h, x:x+w]
eyes = eyeCascade.detectMultiScale(roi)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)
plt.figure()
plt.imshow(image, cmap='gray')
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/EzAjT.png" rel="nofollow"><img src="http://i.stack.imgur.com/EzAjT.png" alt="enter image description here"></a> </p>
| 2
|
2016-09-04T17:18:36Z
|
[
"python",
"opencv",
"numpy",
"face-detection",
"eye-detection"
] |
How to trigger an event using pyquery python
| 39,314,627
|
<p>I'm trying to automate a headless web browser using python and packages like pyquery, beautiful soup, requests, mechanize.</p>
<p>But so far I haven't found a right way to trigger a click event on a button. For example, to fill an online form, I'm able to insert values in the text fields, but not able to click on the Submit/Send button. </p>
| -2
|
2016-09-04T07:38:08Z
| 39,314,823
|
<p>According to the <a href="https://pypi.python.org/pypi/pyquery" rel="nofollow">docs</a>, pyquery isn't a library to interact with JS code (at least not yet). It is used to parse HTML Docs like beautiful soup.</p>
<p>As Nehal suggested, <a href="http://selenium-python.readthedocs.io/" rel="nofollow">selenium</a> is your best bet. </p>
| 1
|
2016-09-04T08:04:33Z
|
[
"python",
"beautifulsoup",
"mechanize",
"pyquery"
] |
How to get the updates from XML file in Python?
| 39,314,688
|
<p>I am a newbie to Python. I have an XML file in the server which will be updated by a device with notifications periodically like below.</p>
<pre><code><notifications
xmlns="http://XXXXX">
<notification>
<received>2016-09-04T13:48:57Z</received>
<source-address>x.x.x.x</source-address>
<notification-type>type-1</notification-type>
<message>message-1</message>
</notification>
<notification>
<received>2016-09-04T13:49:21Z</received>
<source-address>X.X.X.X</source-address>
<notification-type>type-2</notification-type>
<message>message-2</message>
</notification>
<notification>
<received>2016-09-04T13:52:38Z</received>
<source-address>X.X.X.X</source-address>
<notification-type>type-3</notification-type>
<message>message-3</message>
</notification>
<notification>
<received>2016-09-04T14:01:21Z</received>
<source-address>X.X.X.X</source-address>
<notification-type>type-4</notification-type>
<message>message-4</message>
</notification>
<notification>
<received>2016-09-04T14:01:51Z</received>
<source-address>X.X.X.X</source-address>
<notification-type>type-5</notification-type>
<message>message-5</message>
</notification>
</notifications>
</code></pre>
<p>I am interested in getting the values of <code><notification-type> and <message></code> whenever device post notification on to this file. Is there a way I can do this in Python?</p>
| -1
|
2016-09-04T07:46:22Z
| 39,315,503
|
<p>two separate issues â first issue is monitoring a file for changes ⦠this looks like itâs been addressed </p>
<ul>
<li><a href="http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python">How do I watch a file for changes using Python?</a> </li>
<li><a href="http://stackoverflow.com/questions/597903/monitoring-files-directories-with-python">Monitoring files/directories with python</a></li>
</ul>
<p>second is reading the XML file in Python </p>
<pre><code>import xml.etree.ElementTree as Et
def process(notification):
received = notification[0].text
print (received)
notification_type = notification[2].text
print (notification_type)
xml = Et.ElementTree()
xml.parse('notifications.xml')
root = xml.getroot()
for notification in root:
process(notification)
</code></pre>
| 0
|
2016-09-04T09:31:18Z
|
[
"python",
"xml",
"notifications"
] |
How to make this code a bit less memory consuming yet simple?
| 39,314,695
|
<p>To return a particular line from a txt file for further manipulation, also the file that must be opened by this function is quite big ~ 500 lines so creating a list and then printing a particular line seemed pretty absurd. Can you please suggest me an alternative? The code is as follows :</p>
<pre><code>def returnline(filename, n):
ofile = open(filename, 'r')
filelist = ofile.readlines()
return filelist[n - 1].strip('\n')
</code></pre>
| 0
|
2016-09-04T07:48:26Z
| 39,314,995
|
<p>If your files are not many thousands of lines, I wouldn't worry about optimizing that bit, however, what you can do is simply keep reading the file until you've reached the line you want, and stop reading from there on; that way, when the file is, say, 5000 lines, and you want the 10th line, you'll only have to read 10 lines. Also, you need to close the file after opening and reading from it.</p>
<p>So all in all, something like this:</p>
<pre><code>def line_of_file(fname, linenum):
# this will ensure the file gets closed
# once the with block exits
with open(fname, 'r') as f:
# skip n - 1 lines
for _ in xrange(linenum - 1):
f.readline()
return f.readline().strip('\n')
</code></pre>
<p>Alternatively, generators (lazy lists, kind of) might provide better performance:</p>
<pre><code>from itertools import islice
def line_of_file(fname, linenum):
with open(fname, 'r') as f:
# (lazily) read all lines
lines = f.xreadlines()
# skip until the line we want
lines = islice(lines, linenum - 1, linenum)
# read the next line (the one we want)
return next(lines)
</code></pre>
<p>...which can be shortened to:</p>
<pre><code>from itertools import islice
def line_of_file(fname, linenum):
with open(fname, 'r') as f:
return next(islice(f.xreadlines(),
linenum - 1,
linenum))
</code></pre>
<p>(In Python 2.x, <code>islice(xs, n, m)</code> is like <code>xs[n:m]</code> except <code>islice</code> works on generators; see <a href="https://docs.python.org/2/library/itertools.html#itertools.islice" rel="nofollow">https://docs.python.org/2/library/itertools.html#itertools.islice</a>)</p>
| 1
|
2016-09-04T08:29:39Z
|
[
"python",
"python-2.7",
"file-handling"
] |
Access elements of 2D list
| 39,314,858
|
<p>I have a list of variables in python and I would like to be able to access the index of individual values in each row and column. Because I am new to python, I do not know if there is another way to access the index or select individual values by row and column.</p>
<p>The only way I have found so far is to use the pandas library, but I cannot use pandas because of a problem in installation. Please advise me on how to create a dataframe(without using pandas) or any other data structure so that I can access its values by their index, by row and column.</p>
<p>Let's say I have the following list: (Actually when I try to find the data structure type, python says it is a list.</p>
<pre><code>(['Name' 'Age' 'Smoking' 'Grade'])
(['Joh' 23 'No' 90])
(['Zak' 25 'No' 89])
(['Suz' 24 'Yes' 80])
(['Sus' 26 'Yes' 83])
</code></pre>
<p>Let's say we name it "habits"</p>
<p>I would like to access individual values, such as habits[3,2] and I would like to have the result as 80 which is located at the 3rd index of rows and at the 2nd index of columns.</p>
| 0
|
2016-09-04T08:09:34Z
| 39,314,915
|
<p>What you want is a list of lists.</p>
<p>This is how you can make one:</p>
<pre><code>data = [[1, 2, 3, 4],
['blue', 'green', 'red', 'yellow']]
data.append(['elephant', 'donkey', 'cat'])
</code></pre>
<p>This is how you access its contents:</p>
<pre><code>data[0] # [1, 2, 3, 4]
data[0][0] # 1
data[1][2] # 'red'
</code></pre>
| 0
|
2016-09-04T08:19:35Z
|
[
"python",
"indexing",
"data-structures"
] |
How to download using wget one by one in a loop in python
| 39,314,891
|
<p>I have following code written which downloads from a page:</p>
<pre><code>import urllib2,os
from bs4 import BeautifulSoup
page = urllib2.urlopen('http://somesite.com')
soup = BeautifulSoup(page)
for a in soup.find_all('a', href=True):
if "tutorials" in a['href']:
os.system('wget ' + a['href'])
</code></pre>
<p>The issue is above command is it downloads all links altogether from the page. I want to download videos one by one. Is that possible? Please help me.</p>
| 1
|
2016-09-04T08:13:58Z
| 39,314,924
|
<p>Use the subprocess.call module instead of os.system.</p>
<pre><code>subprocess.call(['wget' , a['href']])
</code></pre>
| 1
|
2016-09-04T08:21:23Z
|
[
"python",
"loops",
"wget"
] |
Python generate and return tuples in a non-list form
| 39,314,913
|
<pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append([x, y])
pos[i] = tuple(pos[i])
return pos
</code></pre>
<p>my input is:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>What I want is to return tuples but not a list:</p>
<pre><code>>>> tuple_gen(0,1,5)
(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)
</code></pre>
<p>Because I want to form a list that includes different kind of tuples:</p>
<pre><code>>>> [tuple_gen(0,1,5), tuple_gen(0,2,6)]
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2)]
</code></pre>
<p>I want a short and clearest solution.</p>
<p>*note that I don't want to use any <code>extend</code> or <code>append</code> to merge those lists because I need so many tuples</p>
| 0
|
2016-09-04T08:19:20Z
| 39,314,961
|
<p>You are currently returning a list of tuples:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>You could return a tuple of tuples with <code>return tuple(pos)</code>.</p>
<p>That is what you asked for, but it won't help you for this use case:</p>
<pre><code>[tuple_gen(0,1,5), tuple_gen(0,2,6)]
</code></pre>
<p>That will still be a list of two tuples of tuples.</p>
<p>What you really need is to return a list, as you do, and then concatenate those lists later:</p>
<pre><code>tuple_gen(0,1,5) + tuple_gen(0,2,6)
</code></pre>
| 1
|
2016-09-04T08:25:24Z
|
[
"python",
"arrays",
"list",
"tuples",
"unpack"
] |
Python generate and return tuples in a non-list form
| 39,314,913
|
<pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append([x, y])
pos[i] = tuple(pos[i])
return pos
</code></pre>
<p>my input is:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>What I want is to return tuples but not a list:</p>
<pre><code>>>> tuple_gen(0,1,5)
(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)
</code></pre>
<p>Because I want to form a list that includes different kind of tuples:</p>
<pre><code>>>> [tuple_gen(0,1,5), tuple_gen(0,2,6)]
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2)]
</code></pre>
<p>I want a short and clearest solution.</p>
<p>*note that I don't want to use any <code>extend</code> or <code>append</code> to merge those lists because I need so many tuples</p>
| 0
|
2016-09-04T08:19:20Z
| 39,314,980
|
<p>You can't do that exactly as you said, But you have some options, first is chaining the result of your functions:</p>
<pre><code>>>> a = [(1, 1), (2, 1)]
>>> b = [(3, 1), (4, 1), (5, 1)]
>>>
>>> a + b
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
>>> # Or using itertools.chain
>>> from itertools import chain
>>>
>>> list(chain(a, b))
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>Secondly if you are in python3.5+ you can use advanced unpacking:</p>
<pre><code>>>> a = [(1, 1), (2, 1)]
>>> b = [(3, 1), (4, 1), (5, 1)]
>>> [*a, *b]
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>Which for functions you can do:</p>
<pre><code>[*tuple_gen(0,1,5), *tuple_gen(0,2,6)]
</code></pre>
| 1
|
2016-09-04T08:27:37Z
|
[
"python",
"arrays",
"list",
"tuples",
"unpack"
] |
Python generate and return tuples in a non-list form
| 39,314,913
|
<pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append([x, y])
pos[i] = tuple(pos[i])
return pos
</code></pre>
<p>my input is:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>What I want is to return tuples but not a list:</p>
<pre><code>>>> tuple_gen(0,1,5)
(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)
</code></pre>
<p>Because I want to form a list that includes different kind of tuples:</p>
<pre><code>>>> [tuple_gen(0,1,5), tuple_gen(0,2,6)]
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2)]
</code></pre>
<p>I want a short and clearest solution.</p>
<p>*note that I don't want to use any <code>extend</code> or <code>append</code> to merge those lists because I need so many tuples</p>
| 0
|
2016-09-04T08:19:20Z
| 39,315,052
|
<p>You need a container, which holds your tuples. You are thinking of list or scheme like tuples, which are linked lists. The tuples in python are expensive in creating, joining and appending. You should use lists for this purposes. You can take an list and just join it.</p>
<pre><code>tuple_gen(0,1,5) + tuple_gen(0,2,6)
</code></pre>
<p>Or you can join your tuples outsite your gen function.</p>
<pre><code>def tuple_gen(x, y, num):
for i in range(num):
x += 1
yield (x,y)
x = []
for i in tuple_gen(0,1,5):
x.append(i)
for i in tuple_gen(0,2,6):
x.append(i)
</code></pre>
<p>There are other container for python - even a linked list. Almost all are implemented as a list with some additionals.</p>
| 0
|
2016-09-04T08:38:01Z
|
[
"python",
"arrays",
"list",
"tuples",
"unpack"
] |
Python generate and return tuples in a non-list form
| 39,314,913
|
<pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append([x, y])
pos[i] = tuple(pos[i])
return pos
</code></pre>
<p>my input is:</p>
<pre><code>>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
</code></pre>
<p>What I want is to return tuples but not a list:</p>
<pre><code>>>> tuple_gen(0,1,5)
(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)
</code></pre>
<p>Because I want to form a list that includes different kind of tuples:</p>
<pre><code>>>> [tuple_gen(0,1,5), tuple_gen(0,2,6)]
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2)]
</code></pre>
<p>I want a short and clearest solution.</p>
<p>*note that I don't want to use any <code>extend</code> or <code>append</code> to merge those lists because I need so many tuples</p>
| 0
|
2016-09-04T08:19:20Z
| 39,315,352
|
<p>You just need to change the way you're calling <code>tuple_gen</code>. Here's an example, with a slightly improved version of <code>tuple_gen</code>:</p>
<pre><code>def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append((x, y))
return pos
bases = (
(0, 1, 5),
(0, 2, 6),
)
a = [t for args in bases for t in tuple_gen(*args)]
print(a)
</code></pre>
<p><strong>output</strong></p>
<pre><code>[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2)]
</code></pre>
<p>An alternative is to create a generator that yields all the desired tuples:</p>
<pre><code>def make_tuples(bases):
for x, y, num in bases:
yield from ((i, y) for i in range(x + 1, num + x + 1))
bases = (
(0, 1, 5),
(0, 2, 6),
)
a = list(make_tuples(bases))
print(a)
</code></pre>
<p>Depending on your actual needs, you may be able to avoid creating a list (thus saving RAM) and just use the tuples as they are created. Eg,</p>
<pre><code>for t in make_tuples(bases):
print(t)
</code></pre>
<p><strong>output</strong></p>
<pre><code>(1, 1)
(2, 1)
(3, 1)
(4, 1)
(5, 1)
(1, 2)
(2, 2)
(3, 2)
(4, 2)
(5, 2)
(6, 2)
</code></pre>
| 0
|
2016-09-04T09:14:33Z
|
[
"python",
"arrays",
"list",
"tuples",
"unpack"
] |
Python Error TypeError: unsupported operand type(s) for +: 'function' and 'function'
| 39,314,935
|
<p>I know there is some stuff online about this error but whatever I try just doesn't seem to fix it. I just started learning Python yesterday and am an absolute beginner so please don't judge my script. It is just a simple script wanting to take the order of a customer from a restaurant and just calculate the total price of the meal. It's pretty cheesy but I would love some help. I can not get my script to calculate the total cost of the meal and whatever I try, it just doesn't work. Could you please tell me what I am doing wrong and how to calculate the total cost of the meal based on what the customer chooses. Also If they pick an item that is not on the menu, the program closes instead of letting them try again. Why? I would greatly appreciate your help. :) THANKS</p>
<p>Here is a picture of the cost error I get when running the script in terminal.
<img src="http://i.stack.imgur.com/Hrst4.png" alt="Error1"></p>
<p>Here is a picture of what I get if I type something that is not on the menu.
<img src="http://i.stack.imgur.com/hVhO5.png" alt="Error2"></p>
<p>Here is my script.</p>
<p>Note, I have aded the items from the menu just to show you what they are and their cost.</p>
<pre><code> Apple = 3
Banana = 4
Kiwi = 2
Peach = 5
Hamburger = 12
Parma = 22
Steak = 24
Sandwhich = 10
Cream = 3
Cake = 8
Moose = 2
Soda = 3
Beer = 8
Wine = 12
def Fruit():
print("Welcome to The Buttler's Pantery")
Fruit = raw_input("what fruit would you like today?")
if (Fruit == "Apple"):
Main()
elif (Fruit == "Banana"):
Main()
elif (Fruit == "Kiwi"):
Main()
elif (Fruit == "Peach"):
Main()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Main():
Main = raw_input("what Main would you like today?")
if (Main == "Hamburger"):
Dessert()
elif (Main == "Parma"):
Dessert()
elif (Main == "Steak"):
Dessert()
elif (Main == "Sandwhich"):
Dessert()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Dessert():
Dessert = raw_input("what Dessert would you like today?")
if (Dessert == "Cream"):
Beverage()
elif (Dessert == "Cake"):
Beverage()
elif (Dessert == "Moose"):
Beverage()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Beverage():
Beverage = raw_input("what Beverage would you like today?")
if (Beverage == "Soda"):
print(add(num1, num2, num3, num4))
elif (Beverage == "Beer"):
print(add(num1, num2, num3, num4))
elif (Beverage == "Wine"):
print(add(num1, num2, num3, num4))
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def add(num1, num2, num3, num4):
return num1 + num2 + num3 + num4
def num1():
if (Fruit == "Apple"):
num1 = 3
elif (Fruit == "Banana"):
num1 = 4
elif (Fruit == "Kiwi"):
num1 = 2
elif (Fruit == "Peach"):
num1 = 5
else: num1 = 0
def num2():
if (Main == "Hamburger"):
num2 = 12
elif (Main == "Parma"):
num2 = 22
elif (Main == "Steak"):
num2 = 24
elif (Main == "Sandwhich"):
num2 = 10
else: num2 = 0
def num3():
if (Dessert == "Cream"):
num3 = 3
elif (Dessert == "Cake"):
num3 = 8
elif (Dessert == "Moose"):
num3 = 2
else: num3 = 0
def num4():
if (Beverage == "Soda"):
num4 = 3
elif (Beverage == "Beer"):
num4 = 8
elif (Beverage == "Wine"):
num4 = 12
else: num4 = 0
Fruit()
</code></pre>
| 1
|
2016-09-04T08:22:27Z
| 39,314,984
|
<p>You are redifining your function names with your local variable names</p>
<p>No wonder why there is a mixup.</p>
<p>I know visual basic uses to do that for return values but you cannot do that in python.</p>
<p>Just rename your local variables (the ones assigned to result of raw_input and it will be ok</p>
| 2
|
2016-09-04T08:28:06Z
|
[
"python",
"typeerror"
] |
Python Error TypeError: unsupported operand type(s) for +: 'function' and 'function'
| 39,314,935
|
<p>I know there is some stuff online about this error but whatever I try just doesn't seem to fix it. I just started learning Python yesterday and am an absolute beginner so please don't judge my script. It is just a simple script wanting to take the order of a customer from a restaurant and just calculate the total price of the meal. It's pretty cheesy but I would love some help. I can not get my script to calculate the total cost of the meal and whatever I try, it just doesn't work. Could you please tell me what I am doing wrong and how to calculate the total cost of the meal based on what the customer chooses. Also If they pick an item that is not on the menu, the program closes instead of letting them try again. Why? I would greatly appreciate your help. :) THANKS</p>
<p>Here is a picture of the cost error I get when running the script in terminal.
<img src="http://i.stack.imgur.com/Hrst4.png" alt="Error1"></p>
<p>Here is a picture of what I get if I type something that is not on the menu.
<img src="http://i.stack.imgur.com/hVhO5.png" alt="Error2"></p>
<p>Here is my script.</p>
<p>Note, I have aded the items from the menu just to show you what they are and their cost.</p>
<pre><code> Apple = 3
Banana = 4
Kiwi = 2
Peach = 5
Hamburger = 12
Parma = 22
Steak = 24
Sandwhich = 10
Cream = 3
Cake = 8
Moose = 2
Soda = 3
Beer = 8
Wine = 12
def Fruit():
print("Welcome to The Buttler's Pantery")
Fruit = raw_input("what fruit would you like today?")
if (Fruit == "Apple"):
Main()
elif (Fruit == "Banana"):
Main()
elif (Fruit == "Kiwi"):
Main()
elif (Fruit == "Peach"):
Main()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Main():
Main = raw_input("what Main would you like today?")
if (Main == "Hamburger"):
Dessert()
elif (Main == "Parma"):
Dessert()
elif (Main == "Steak"):
Dessert()
elif (Main == "Sandwhich"):
Dessert()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Dessert():
Dessert = raw_input("what Dessert would you like today?")
if (Dessert == "Cream"):
Beverage()
elif (Dessert == "Cake"):
Beverage()
elif (Dessert == "Moose"):
Beverage()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Beverage():
Beverage = raw_input("what Beverage would you like today?")
if (Beverage == "Soda"):
print(add(num1, num2, num3, num4))
elif (Beverage == "Beer"):
print(add(num1, num2, num3, num4))
elif (Beverage == "Wine"):
print(add(num1, num2, num3, num4))
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def add(num1, num2, num3, num4):
return num1 + num2 + num3 + num4
def num1():
if (Fruit == "Apple"):
num1 = 3
elif (Fruit == "Banana"):
num1 = 4
elif (Fruit == "Kiwi"):
num1 = 2
elif (Fruit == "Peach"):
num1 = 5
else: num1 = 0
def num2():
if (Main == "Hamburger"):
num2 = 12
elif (Main == "Parma"):
num2 = 22
elif (Main == "Steak"):
num2 = 24
elif (Main == "Sandwhich"):
num2 = 10
else: num2 = 0
def num3():
if (Dessert == "Cream"):
num3 = 3
elif (Dessert == "Cake"):
num3 = 8
elif (Dessert == "Moose"):
num3 = 2
else: num3 = 0
def num4():
if (Beverage == "Soda"):
num4 = 3
elif (Beverage == "Beer"):
num4 = 8
elif (Beverage == "Wine"):
num4 = 12
else: num4 = 0
Fruit()
</code></pre>
| 1
|
2016-09-04T08:22:27Z
| 39,315,022
|
<p>You shouldn't name functions the same as variables, i.e. the fruit function should look like this:</p>
<pre><code>def Fruit():
print("Welcome to The Buttler's Pantery")
global fruit
fruit = raw_input("what fruit would you like today?")
if (fruit == "Apple"):
Main()
elif (fruit == "Banana"):
Main()
elif (fruit == "Kiwi"):
Main()
elif (fruit == "Peach"):
Main()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
Fruit()
</code></pre>
<p>Also note the <code>global</code>, it makes <code>fruit</code> accesable outside the function <code>Fruit()</code>. If you'd apply these changes to all functions, it should work</p>
<p>If you also want to let peaople try again, you could simply call the function again, like in the function <code>Fruit()</code>.</p>
<p>Hope this helps!</p>
| 1
|
2016-09-04T08:34:01Z
|
[
"python",
"typeerror"
] |
Python Error TypeError: unsupported operand type(s) for +: 'function' and 'function'
| 39,314,935
|
<p>I know there is some stuff online about this error but whatever I try just doesn't seem to fix it. I just started learning Python yesterday and am an absolute beginner so please don't judge my script. It is just a simple script wanting to take the order of a customer from a restaurant and just calculate the total price of the meal. It's pretty cheesy but I would love some help. I can not get my script to calculate the total cost of the meal and whatever I try, it just doesn't work. Could you please tell me what I am doing wrong and how to calculate the total cost of the meal based on what the customer chooses. Also If they pick an item that is not on the menu, the program closes instead of letting them try again. Why? I would greatly appreciate your help. :) THANKS</p>
<p>Here is a picture of the cost error I get when running the script in terminal.
<img src="http://i.stack.imgur.com/Hrst4.png" alt="Error1"></p>
<p>Here is a picture of what I get if I type something that is not on the menu.
<img src="http://i.stack.imgur.com/hVhO5.png" alt="Error2"></p>
<p>Here is my script.</p>
<p>Note, I have aded the items from the menu just to show you what they are and their cost.</p>
<pre><code> Apple = 3
Banana = 4
Kiwi = 2
Peach = 5
Hamburger = 12
Parma = 22
Steak = 24
Sandwhich = 10
Cream = 3
Cake = 8
Moose = 2
Soda = 3
Beer = 8
Wine = 12
def Fruit():
print("Welcome to The Buttler's Pantery")
Fruit = raw_input("what fruit would you like today?")
if (Fruit == "Apple"):
Main()
elif (Fruit == "Banana"):
Main()
elif (Fruit == "Kiwi"):
Main()
elif (Fruit == "Peach"):
Main()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Main():
Main = raw_input("what Main would you like today?")
if (Main == "Hamburger"):
Dessert()
elif (Main == "Parma"):
Dessert()
elif (Main == "Steak"):
Dessert()
elif (Main == "Sandwhich"):
Dessert()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Dessert():
Dessert = raw_input("what Dessert would you like today?")
if (Dessert == "Cream"):
Beverage()
elif (Dessert == "Cake"):
Beverage()
elif (Dessert == "Moose"):
Beverage()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Beverage():
Beverage = raw_input("what Beverage would you like today?")
if (Beverage == "Soda"):
print(add(num1, num2, num3, num4))
elif (Beverage == "Beer"):
print(add(num1, num2, num3, num4))
elif (Beverage == "Wine"):
print(add(num1, num2, num3, num4))
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def add(num1, num2, num3, num4):
return num1 + num2 + num3 + num4
def num1():
if (Fruit == "Apple"):
num1 = 3
elif (Fruit == "Banana"):
num1 = 4
elif (Fruit == "Kiwi"):
num1 = 2
elif (Fruit == "Peach"):
num1 = 5
else: num1 = 0
def num2():
if (Main == "Hamburger"):
num2 = 12
elif (Main == "Parma"):
num2 = 22
elif (Main == "Steak"):
num2 = 24
elif (Main == "Sandwhich"):
num2 = 10
else: num2 = 0
def num3():
if (Dessert == "Cream"):
num3 = 3
elif (Dessert == "Cake"):
num3 = 8
elif (Dessert == "Moose"):
num3 = 2
else: num3 = 0
def num4():
if (Beverage == "Soda"):
num4 = 3
elif (Beverage == "Beer"):
num4 = 8
elif (Beverage == "Wine"):
num4 = 12
else: num4 = 0
Fruit()
</code></pre>
| 1
|
2016-09-04T08:22:27Z
| 39,315,235
|
<p>You used functions to define num1,num2... values , which becomes local variables . whereas you should have made these variables out of function . And use those variables in other functions using the keyword 'global'. </p>
<p>here's the edited code : </p>
<pre><code>Apple = 3
Banana = 4
Kiwi = 2
Peach = 5
Hamburger = 12
Parma = 22
Steak = 24
Sandwhich = 10
Cream = 3
Cake = 8
Moose = 2
Soda = 3
Beer = 8
Wine = 12
num1 = 0
num2 = 0
num3 = 0
num4 = 0
def Fruit():
global num1
print("Welcome to The Buttler's Pantery")
Fruit = raw_input("what fruit would you like today?")
if (Fruit == "Apple"):
num1 = 3
Main()
elif (Fruit == "Banana"):
num1 = 4
Main()
elif (Fruit == "Kiwi"):
num1 = 2
Main()
elif (Fruit == "Peach"):
num1 = 5
Main()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Main():
global num2
Main = raw_input("what Main would you like today?")
if (Main == "Hamburger"):
num2 = 12
Dessert()
elif (Main == "Parma"):
num2 = 22
Dessert()
elif (Main == "Steak"):
num2 = 24
Dessert()
elif (Main == "Sandwhich"):
num2 = 10
Dessert()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Dessert():
global num3
Dessert = raw_input("what Dessert would you like today?")
if (Dessert == "Cream"):
num3 = 3
Beverage()
elif (Dessert == "Cake"):
num3 = 8
Beverage()
elif (Dessert == "Moose"):
num3 = 2
Beverage()
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def Beverage():
global num1
global num2
global num3
global num4
Beverage = raw_input("what Beverage would you like today?")
if (Beverage == "Soda"):
num4 = 3
print(add(num1,num2,num3,num4))
elif (Beverage == "Beer"):
num4 = 8
print(add(num1,num2,num3,num4))
elif (Beverage == "Wine"):
num4 = 12
print(add(num1,num2,num3,num4))
else:
print("Sorry, but it appears that the item you have ordered is not on the menu")
def add(a,b,c,d) :
return a+b+c+d
Fruit()
</code></pre>
| 1
|
2016-09-04T09:00:27Z
|
[
"python",
"typeerror"
] |
Why does my linear regression get nan values instead of learning?
| 39,314,946
|
<p>I'm running the following code:</p>
<pre><code>import tensorflow as tf
# data set
x_data = [10., 20., 30., 40.]
y_data = [20., 40., 60., 80.]
# try to find values for w and b that compute y_data = W * x_data + b
# range is -100 ~ 100
W = tf.Variable(tf.random_uniform([1], -1000., 1000.))
b = tf.Variable(tf.random_uniform([1], -1000., 1000.))
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# my hypothesis
hypothesis = W * X + b
# Simplified cost function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# minimize
a = tf.Variable(0.1) # learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost) # goal is minimize cost
# before starting, initialize the variables
init = tf.initialize_all_variables()
# launch
sess = tf.Session()
sess.run(init)
# fit the line
for step in xrange(2001):
sess.run(train, feed_dict={X: x_data, Y: y_data})
if step % 100 == 0:
print step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W), sess.run(b)
print sess.run(hypothesis, feed_dict={X: 5})
print sess.run(hypothesis, feed_dict={X: 2.5})
</code></pre>
<p>and that is result follow </p>
<pre><code>0 1.60368e+10 [ 4612.54003906] [ 406.81304932]
100 nan [ nan] [ nan]
200 nan [ nan] [ nan]
300 nan [ nan] [ nan]
400 nan [ nan] [ nan]
500 nan [ nan] [ nan]
600 nan [ nan] [ nan]
700 nan [ nan] [ nan]
800 nan [ nan] [ nan]
900 nan [ nan] [ nan]
1000 nan [ nan] [ nan]
1100 nan [ nan] [ nan]
1200 nan [ nan] [ nan]
1300 nan [ nan] [ nan]
1400 nan [ nan] [ nan]
1500 nan [ nan] [ nan]
1600 nan [ nan] [ nan]
1700 nan [ nan] [ nan]
1800 nan [ nan] [ nan]
1900 nan [ nan] [ nan]
2000 nan [ nan] [ nan]
[ nan]
[ nan]
</code></pre>
<p>I don't understand why this result is <code>nan</code>?</p>
<p>If i change the initial data to this</p>
<pre><code>x_data = [1., 2., 3., 4.]
y_data = [2., 4., 6., 8.]
</code></pre>
<p>Then it was working no problem. Why is that?</p>
| 0
|
2016-09-04T08:23:58Z
| 39,315,068
|
<p>You are overflowing float32 because the learning rate is too high for your problem, and instead of converging the weight variable (<code>W</code>) is oscillating towards larger and larger magnitudes on each step of gradient descent.</p>
<p>If you change</p>
<pre><code>a = tf.Variable(0.1)
</code></pre>
<p>to </p>
<pre><code>a = tf.Variable(0.001)
</code></pre>
<p>the weights should converge better. You will probably want to increase number of iterations (to ~ 50000) too.</p>
<p>Picking a good learning rate is often the first challenge when implementing or using a machine learning algorithm. Getting increased loss values instead of converging to a minimum is usually a sign that learning rate is too high.</p>
<p>In your case the specific problem of fitting to the line is made more vulnerable to diverging weights when you use larger magnitudes in the training data. This is one reason why it is common to normalise data prior to training in e.g. neural networks.</p>
<p>In addition your starting weight and bias are given a very large range, which means they can be very far from ideal values and have very large loss values and gradients at the start. Picking a good range for initial values is another critical thing to get right as you look at more advanced learning algorithms.</p>
| 0
|
2016-09-04T08:40:53Z
|
[
"python",
"tensorflow"
] |
Manipulation of values in Pandas via Regex
| 39,315,053
|
<p>This is actually a follow up question of <a href="http://stackoverflow.com/questions/39313680/pandas-dropping-of-words-in-dataframe/39313796?noredirect=1#comment65960430_39313796">here</a>. I had not been clear in my previous question, and since it has been answered, I felt it was better to post a new question instead. </p>
<p>I have a dataframe like below:</p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5FQ 1.047 S$55.3 UG44.2 as of 02/Jun/2016 S$8.2 mm
600 (1.047) S$23.3 AG5.6 as of 02/Jun/2016 S$58 mm
KI2 1.695 S$5.35 RR59.5 as of 02/Jun/2016 S$705 mm
88G 0.0025 S$(5.3) NW44.2 as of 02/Jun/2016 S$112 mm
60G 5.63 S$78.4 UG21.2 as of 02/Jun/2016 S$6.21 mm
90F (5.562) S$(88.3) IG46.2 as of 02/Jun/2016 S$8 mm
</code></pre>
<p>I am trying to use <code>regex</code> to drop all the words and letters, only keeping the numbers. However, if the number is enclosed within a <code>()</code>, I would like to make it a negative number instead.</p>
<p><strong>Desired output</strong></p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5 1.047 55.3 44.2 8.2
600 -1.047 23.3 5.6 58
2 1.695 5.35 59.5 705
88 0.0025 -5.3 44.2 112
60 5.63 78.4 21.2 6.21
90 -5.562 -88.3 46.2 8
</code></pre>
<p>Would this be possible? I've tried playing around with this code, but was not sure what the appropriate <code>regex</code> combination should be. </p>
<pre><code>df.apply(lambda x: x.astype(str).str.extract(r'(\d+\.?\d*)', expand=True).astype(np.float))
</code></pre>
| 4
|
2016-09-04T08:38:02Z
| 39,315,181
|
<p>You could come up with:</p>
<pre><code>import re
def onlynumbers(value):
if value.startswith('('):
return '-' + value
rx = re.compile(r'\d+[\d.]*')
try:
return rx.search(value).group(0)
except:
return value
df.applymap(onlynumbers)
</code></pre>
<p>This returns:
<a href="http://i.stack.imgur.com/lggpH.png" rel="nofollow"><img src="http://i.stack.imgur.com/lggpH.png" alt="enter image description here"></a></p>
| 2
|
2016-09-04T08:54:37Z
|
[
"python",
"regex",
"pandas",
"dataframe"
] |
Manipulation of values in Pandas via Regex
| 39,315,053
|
<p>This is actually a follow up question of <a href="http://stackoverflow.com/questions/39313680/pandas-dropping-of-words-in-dataframe/39313796?noredirect=1#comment65960430_39313796">here</a>. I had not been clear in my previous question, and since it has been answered, I felt it was better to post a new question instead. </p>
<p>I have a dataframe like below:</p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5FQ 1.047 S$55.3 UG44.2 as of 02/Jun/2016 S$8.2 mm
600 (1.047) S$23.3 AG5.6 as of 02/Jun/2016 S$58 mm
KI2 1.695 S$5.35 RR59.5 as of 02/Jun/2016 S$705 mm
88G 0.0025 S$(5.3) NW44.2 as of 02/Jun/2016 S$112 mm
60G 5.63 S$78.4 UG21.2 as of 02/Jun/2016 S$6.21 mm
90F (5.562) S$(88.3) IG46.2 as of 02/Jun/2016 S$8 mm
</code></pre>
<p>I am trying to use <code>regex</code> to drop all the words and letters, only keeping the numbers. However, if the number is enclosed within a <code>()</code>, I would like to make it a negative number instead.</p>
<p><strong>Desired output</strong></p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5 1.047 55.3 44.2 8.2
600 -1.047 23.3 5.6 58
2 1.695 5.35 59.5 705
88 0.0025 -5.3 44.2 112
60 5.63 78.4 21.2 6.21
90 -5.562 -88.3 46.2 8
</code></pre>
<p>Would this be possible? I've tried playing around with this code, but was not sure what the appropriate <code>regex</code> combination should be. </p>
<pre><code>df.apply(lambda x: x.astype(str).str.extract(r'(\d+\.?\d*)', expand=True).astype(np.float))
</code></pre>
| 4
|
2016-09-04T08:38:02Z
| 39,315,362
|
<pre><code>r1 = r'\((\d+\.?\d*)\)'
r2 = r'(-?\d+\.?\d*)'
df.stack().str.replace(r1, r'-\1', 1) \
.str.extract(r2, expand=False).unstack()
</code></pre>
<p><a href="http://i.stack.imgur.com/tVR5u.png" rel="nofollow"><img src="http://i.stack.imgur.com/tVR5u.png" alt="enter image description here"></a></p>
| 4
|
2016-09-04T09:15:49Z
|
[
"python",
"regex",
"pandas",
"dataframe"
] |
Manipulation of values in Pandas via Regex
| 39,315,053
|
<p>This is actually a follow up question of <a href="http://stackoverflow.com/questions/39313680/pandas-dropping-of-words-in-dataframe/39313796?noredirect=1#comment65960430_39313796">here</a>. I had not been clear in my previous question, and since it has been answered, I felt it was better to post a new question instead. </p>
<p>I have a dataframe like below:</p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5FQ 1.047 S$55.3 UG44.2 as of 02/Jun/2016 S$8.2 mm
600 (1.047) S$23.3 AG5.6 as of 02/Jun/2016 S$58 mm
KI2 1.695 S$5.35 RR59.5 as of 02/Jun/2016 S$705 mm
88G 0.0025 S$(5.3) NW44.2 as of 02/Jun/2016 S$112 mm
60G 5.63 S$78.4 UG21.2 as of 02/Jun/2016 S$6.21 mm
90F (5.562) S$(88.3) IG46.2 as of 02/Jun/2016 S$8 mm
</code></pre>
<p>I am trying to use <code>regex</code> to drop all the words and letters, only keeping the numbers. However, if the number is enclosed within a <code>()</code>, I would like to make it a negative number instead.</p>
<p><strong>Desired output</strong></p>
<pre><code>Column1 Column2 Column3 Column4 Column5
5 1.047 55.3 44.2 8.2
600 -1.047 23.3 5.6 58
2 1.695 5.35 59.5 705
88 0.0025 -5.3 44.2 112
60 5.63 78.4 21.2 6.21
90 -5.562 -88.3 46.2 8
</code></pre>
<p>Would this be possible? I've tried playing around with this code, but was not sure what the appropriate <code>regex</code> combination should be. </p>
<pre><code>df.apply(lambda x: x.astype(str).str.extract(r'(\d+\.?\d*)', expand=True).astype(np.float))
</code></pre>
| 4
|
2016-09-04T08:38:02Z
| 39,315,643
|
<p><strong>UPDATE:</strong> <code>$1,005A</code> --> <code>1005</code> (example in 1st row, column <code>Column3</code>)</p>
<pre><code>In [131]: df
Out[131]:
Column1 Column2 Column3 Column4 Column5
0 5FQ 1.047 $1,005A UG44.2 as of 02/Jun/2016 S$8.2 mm
1 600 (1.047) S$23.3 AG5.6 as of 02/Jun/2016 S$58 mm
2 KI2 1.695 S$5.35 RR59.5 as of 02/Jun/2016 S$705 mm
3 88G 0.0025 S$(5.3) NW44.2 as of 02/Jun/2016 S$112 mm
4 60G 5.63 S$78.4 UG21.2 as of 02/Jun/2016 S$6.21 mm
5 90F (5.562) S$(88.3) IG46.2 as of 02/Jun/2016 S$8 mm
In [132]: to_replace = [r'\(([\d\.]+)\)', r'.*?([\d\.\,\-]+).*', ',']
In [133]: vals = [r'-\1', r'\1', '']
In [134]: df.replace(to_replace=to_replace, value=vals, regex=True)
Out[134]:
Column1 Column2 Column3 Column4 Column5
0 5 1.047 1005 44.2 8.2
1 600 -1.047 23.3 5.6 58
2 2 1.695 5.35 59.5 705
3 88 0.0025 -5.3 44.2 112
4 60 5.63 78.4 21.2 6.21
5 90 -5.562 -88.3 46.2 8
</code></pre>
<p><strong>OLD answer:</strong></p>
<p>Yet another solution, which uses only <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow">DataFrame.replace()</a> method:</p>
<pre><code>In [28]: to_replace = [r'\(([\d\.]+)\)', r'.*?([\d\.-]+).*']
In [29]: vals = [r'-\1', r'\1']
In [30]: df.replace(to_replace=to_replace, value=vals, regex=True)
Out[30]:
Column1 Column2 Column3 Column4 Column5
0 5 1.047 55.3 44.2 8.2
1 600 -1.047 23.3 5.6 58
2 2 1.695 5.35 59.5 705
3 88 0.0025 -5.3 44.2 112
4 60 5.63 78.4 21.2 6.21
5 90 -5.562 -88.3 46.2 8
</code></pre>
| 2
|
2016-09-04T09:50:50Z
|
[
"python",
"regex",
"pandas",
"dataframe"
] |
How to install xgboost in python on Mac?
| 39,315,156
|
<p>I am a newbie and learning python. Can someone help me- how to install xgboost in python. Im using Mac 10.11. I read online and did the below mentioned step, but not able to decode what to do next: </p>
<pre><code>pip install xgboost -
</code></pre>
| 0
|
2016-09-04T08:51:46Z
| 39,315,516
|
<p>For a newbie learning python and Machine Learning on Mac, I would strongly recommand to install Anaconda first (<a href="https://www.continuum.io/downloads" rel="nofollow">install doc)</a>.</p>
<blockquote>
<p>Anaconda is a freemium open source distribution of the Python and R
programming languages for large-scale data processing, predictive
analytics, and scientific computing, that aims to simplify package
management and deployment.</p>
</blockquote>
<p>If you installed Anaconda for Python 2.7, then you should have no troubles installing XGBoost with:</p>
<pre><code>conda install -c aterrel xgboost=0.4.0
</code></pre>
<p>If you already have Anaconda installed and that your pip XGBoost installation failed, you should try:</p>
<pre><code>conda remove xgboost
conda install -c aterrel xgboost=0.4.0
</code></pre>
| 0
|
2016-09-04T09:33:15Z
|
[
"python",
"xgboost"
] |
PyInstaller won't install, Python 3.6.0a4 and x64 Windows
| 39,315,160
|
<p>I have said Python version (from <a href="https://www.python.org/downloads/windows/" rel="nofollow">https://www.python.org/downloads/windows/</a>), and x64 Windows 10.
Every time I try to execute "pip install pyinstaller" it crashes with an error:</p>
<pre><code>C:\WINDOWS\system32>pip install pyinstaller
Collecting pyinstaller
Using cached PyInstaller-3.2.tar.gz
Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\users\jskurski\appdata\local\programs\python\python36\lib\site-packages (from pyinstaller)
Collecting pefile (from pyinstaller)
Using cached pefile-2016.3.28.tar.gz
Collecting pypiwin32 (from pyinstaller)
Using cached pypiwin32-219.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\jskurski\AppData\Local\Temp\pip-build-y9lsbd5f\pypiwin32\setup.py", line 121
print "Building pywin32", pywin32_version
^
SyntaxError: Missing parentheses in call to 'print'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\jskurski\AppData\Local\Temp\pip-build-y9lsbd5f\pypiwin32\
</code></pre>
<p>So, for me it seems there is a version msmatch or something. Unofortunately, I can not figure it out myself.</p>
<p>Any suggestions?
Has anybody sucessfully used PyInstaller with latest 3.6 Python on Windows? Or maybe I should downgrade Python to older version?</p>
<p>edit: tested on another PC (same enviroment) and it was the same.</p>
<p>edit2: seems to work on 3.5.2 version, so it's probably a way to go, for now.</p>
| 0
|
2016-09-04T08:52:12Z
| 39,317,550
|
<p>As cdarke pointed out, you are running python 2 code on Python 3.</p>
<p>Try this instead:</p>
<pre><code>pip3 install pyinstaller
</code></pre>
| 0
|
2016-09-04T13:43:14Z
|
[
"python",
"windows",
"64bit",
"pyinstaller"
] |
I can't replicate the code from book "Mastering pandas for Finance" - Zipline - KeyError: 'Cost'
| 39,315,267
|
<p>I'm reading the book "Mastering pandas for Finance". Up until where the Zipline module is involved all was very smooth and interesting, but now when I need to recreate the books code in the Jupyter Notebook, I'm getting and error from Zipline library.</p>
<p>The book's code is:</p>
<pre><code>import zipline as zp
import zipline.utils.factory as zpf
import pandas as pd
import pandas_datareader.data as web
import numpy as np
# dates
from datetime import datetime
# zipline has its own method to load data from Yahoo! Finance
data = zpf.load_from_yahoo(stocks=['AAPL'],
indexes={},
start=datetime(1990, 1, 1),
end=datetime(2014, 1, 1),
adjusted=False)
class BuyApple(zp.TradingAlgorithm):
""" Simple trading algorithm that does nothing
but buy one share of AAPL every trading period.
"""
trace=False
def __init__(self, trace=False):
BuyApple.trace = trace
super(BuyApple, self).__init__()
def initialize(context):
if BuyApple.trace: print("---> initialize")
if BuyApple.trace: print(context)
if BuyApple.trace: print("<--- initialize")
def handle_data(self, context):
if BuyApple.trace: print("---> handle_data")
if BuyApple.trace: print(context)
self.order("AAPL", 1)
if BuyApple.trace: print("<-- handle_data")
result = BuyApple(trace=True).run(data['2000-01-03':'2000-01-07'])
</code></pre>
<p>After running it, I get long list of errors, but the last line in the Jupyter Notebook cell is:</p>
<pre><code>/Users/***/anaconda/lib/python3.4/site-packages/zipline/finance/commission.py in __repr__(self)
83 .format(class_name=self.__class__.__name__,
84 cost_per_share=self.cost_per_share,
---> 85 min_trade_cost=self.min_trade_cost)
86
87 def calculate(self, order, transaction):
KeyError: 'cost'
</code></pre>
<p>This code is supposed to run a very simple strategy, just buying AAPL every day, but it doesn't work. I think something is amiss within the Zipline and something changes since the book was written.
I managed to make it run, but with no transactions being made at all. It just shows some data not related to the orders because no order are made and they are not made since I don't instantiate the class BuyApple.</p>
<p>I'm new to Python and to pandas and to Zipline as well, so if someone could shed some light as to why this is not working, it's great.
I'm on Python 3.4 and Zipline 1.0.1</p>
| 0
|
2016-09-04T09:04:56Z
| 39,417,446
|
<p>I am using Python 2.7 and Zipline 0.7.0 Since I have 32 bit OS and Zipline future releases are focused on 64 bit I cannot upgrade Zipline on my system. The code ran perfectly well on my system. Perhaps the code is compatible with older Zipline version. Are you using windows? Why is there Python3.4 between lib and sitepackages? I am using Anaconda as well but my path is Anaconda/lib/sitepackages/zipline</p>
| 0
|
2016-09-09T18:11:06Z
|
[
"python",
"pandas",
"algorithmic-trading",
"zipline"
] |
ImportError: No module named 'theano'
| 39,315,270
|
<p>I have installed (/library/python/2.7/site-packages) theano on my mac and still get this error.</p>
<p><strong>My code is</strong></p>
<pre><code>import theano
theano.test()
</code></pre>
<p><strong>and the error</strong></p>
<pre><code>Traceback (most recent call last):
File "/Users/mac/Downloads/n.py", line 1, in <module>
import theano
ImportError: No module named 'theano'
</code></pre>
<p>I did install theano using pip install theano for python 2.7. </p>
<p>Any idea on why its throwing up the error.</p>
<p>Also I installed Anaconda and it throws the same error as working on idle.</p>
| 1
|
2016-09-04T09:05:24Z
| 39,317,160
|
<p>I had the same problem trying to install pygame, i'm using python 3.4.1 so I'm not 100% sure this will work for you</p>
<p>Here is my folder: C:\Python34\Scripts<a href="http://i.stack.imgur.com/xoYJZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/xoYJZ.png" alt="enter image description here"></a></p>
<p><strong>The problem:</strong>
This will of course be different for you, but this is what I did anyway:
I did <code>pip install pygame</code> and it seemed to work but when I tried <code>import pygame</code> I got the same error as you</p>
<p><strong>My solution:</strong>
instead of installing pygame with pip, I did <code>pip3 install pygame</code> and it worked! so for you, look at what files you have in this folder <strong>/library/python/2.7/site-packages</strong> and try all of them, try <code>pip2 install theano</code>, try <code>pip2.7 install theano</code>, try <code>pip3 install theano</code>, try everything!</p>
<p>Again I'm not certain this will work for python 2.7, but its worth a try :)</p>
| 1
|
2016-09-04T12:59:35Z
|
[
"python",
"theano"
] |
Python Query properties of dict by value
| 39,315,396
|
<p>I'm trying to get the count of properties in a dict where poi == true. I've included a C# example for reference, followed by my python code. </p>
<p>What's the correct way of doing this in Python?</p>
<p>C#:</p>
<pre><code>enron_data.where(x => x.poi == true).count()
</code></pre>
<p>In Python:</p>
<pre><code>i = 0
for key,value in enron_data.items():
if value["poi"]:
i = i + 1
print i
</code></pre>
<p>enron_data Sample:</p>
<pre><code>{'METTS MARK': {'salary': 365788, 'to_messages': 807, 'deferral_payments': 'NaN', 'total_payments': 1061827, 'exercised_stock_options': 'NaN', 'bonus': 600000, 'restricted_stock': 585062, 'shared_receipt_with_poi': 702, 'restricted_stock_deferred': 'NaN', 'total_stock_value': 585062, 'expenses': 94299, 'loan_advances': 'NaN', 'from_messages': 29, 'other': 1740, 'from_this_person_to_poi': 1, 'poi': False, 'director_fees': 'NaN', 'deferred_income': 'NaN', 'long_term_incentive': 'NaN', 'email_address': 'mark.metts@enron.com', 'from_poi_to_this_person': 38}}
</code></pre>
| 1
|
2016-09-04T09:19:27Z
| 39,315,441
|
<p>You could use the <code>iter_items()</code> function like so:</p>
<pre><code>i = 0
for key,value in enron_data.iter_items():
if value["poi"]:
i = i + 1
print i
</code></pre>
<p>OR</p>
<pre><code>i = 0
for key,value in enron_data.iter_items():
i += int(value["poi"])
print i
</code></pre>
| 0
|
2016-09-04T09:24:03Z
|
[
"python"
] |
Python Query properties of dict by value
| 39,315,396
|
<p>I'm trying to get the count of properties in a dict where poi == true. I've included a C# example for reference, followed by my python code. </p>
<p>What's the correct way of doing this in Python?</p>
<p>C#:</p>
<pre><code>enron_data.where(x => x.poi == true).count()
</code></pre>
<p>In Python:</p>
<pre><code>i = 0
for key,value in enron_data.items():
if value["poi"]:
i = i + 1
print i
</code></pre>
<p>enron_data Sample:</p>
<pre><code>{'METTS MARK': {'salary': 365788, 'to_messages': 807, 'deferral_payments': 'NaN', 'total_payments': 1061827, 'exercised_stock_options': 'NaN', 'bonus': 600000, 'restricted_stock': 585062, 'shared_receipt_with_poi': 702, 'restricted_stock_deferred': 'NaN', 'total_stock_value': 585062, 'expenses': 94299, 'loan_advances': 'NaN', 'from_messages': 29, 'other': 1740, 'from_this_person_to_poi': 1, 'poi': False, 'director_fees': 'NaN', 'deferred_income': 'NaN', 'long_term_incentive': 'NaN', 'email_address': 'mark.metts@enron.com', 'from_poi_to_this_person': 38}}
</code></pre>
| 1
|
2016-09-04T09:19:27Z
| 39,315,466
|
<p>it's not right, since when never value["poi"] has a value that not false, i will increment by 1, so you should do:</p>
<pre><code>i = 0
for key,value in enron_data.iter_items():
if value["poi"] == True:
i = i + 1
print i
</code></pre>
| 0
|
2016-09-04T09:27:22Z
|
[
"python"
] |
Python Query properties of dict by value
| 39,315,396
|
<p>I'm trying to get the count of properties in a dict where poi == true. I've included a C# example for reference, followed by my python code. </p>
<p>What's the correct way of doing this in Python?</p>
<p>C#:</p>
<pre><code>enron_data.where(x => x.poi == true).count()
</code></pre>
<p>In Python:</p>
<pre><code>i = 0
for key,value in enron_data.items():
if value["poi"]:
i = i + 1
print i
</code></pre>
<p>enron_data Sample:</p>
<pre><code>{'METTS MARK': {'salary': 365788, 'to_messages': 807, 'deferral_payments': 'NaN', 'total_payments': 1061827, 'exercised_stock_options': 'NaN', 'bonus': 600000, 'restricted_stock': 585062, 'shared_receipt_with_poi': 702, 'restricted_stock_deferred': 'NaN', 'total_stock_value': 585062, 'expenses': 94299, 'loan_advances': 'NaN', 'from_messages': 29, 'other': 1740, 'from_this_person_to_poi': 1, 'poi': False, 'director_fees': 'NaN', 'deferred_income': 'NaN', 'long_term_incentive': 'NaN', 'email_address': 'mark.metts@enron.com', 'from_poi_to_this_person': 38}}
</code></pre>
| 1
|
2016-09-04T09:19:27Z
| 39,315,484
|
<p>Say you have a dictionary where each value indeed has a <code>poi</code> key (which your question implies):</p>
<pre><code>enron_data = {'foo': {'poi': True}, 'bar': {'poi': False}}
</code></pre>
<p>Then this will sum the number of <code>True</code> entries:</p>
<pre><code>sum(1 if e['poi'] else 0 for e in enron_data.values())
</code></pre>
| 1
|
2016-09-04T09:29:13Z
|
[
"python"
] |
Python Query properties of dict by value
| 39,315,396
|
<p>I'm trying to get the count of properties in a dict where poi == true. I've included a C# example for reference, followed by my python code. </p>
<p>What's the correct way of doing this in Python?</p>
<p>C#:</p>
<pre><code>enron_data.where(x => x.poi == true).count()
</code></pre>
<p>In Python:</p>
<pre><code>i = 0
for key,value in enron_data.items():
if value["poi"]:
i = i + 1
print i
</code></pre>
<p>enron_data Sample:</p>
<pre><code>{'METTS MARK': {'salary': 365788, 'to_messages': 807, 'deferral_payments': 'NaN', 'total_payments': 1061827, 'exercised_stock_options': 'NaN', 'bonus': 600000, 'restricted_stock': 585062, 'shared_receipt_with_poi': 702, 'restricted_stock_deferred': 'NaN', 'total_stock_value': 585062, 'expenses': 94299, 'loan_advances': 'NaN', 'from_messages': 29, 'other': 1740, 'from_this_person_to_poi': 1, 'poi': False, 'director_fees': 'NaN', 'deferred_income': 'NaN', 'long_term_incentive': 'NaN', 'email_address': 'mark.metts@enron.com', 'from_poi_to_this_person': 38}}
</code></pre>
| 1
|
2016-09-04T09:19:27Z
| 39,315,497
|
<p>I'd probably do something like this assuming that the <code>poi</code> is always <code>True</code> or <code>False</code>. </p>
<pre><code>sum(int(v['poi']) for v in enron_data.values())
</code></pre>
<p><code>enron_data.values()</code> gives you an iterator that will return values of the dictionary. We're not interested in the keys. For each one, we get the value of the <code>'poi'</code> key. That's what </p>
<pre><code>[v['poi'] for v in enron_data.values()]
</code></pre>
<p>will give you. Assuming that <code>v['poi']</code> is always <code>True</code> or <code>False</code>, I convert it to an integer using <code>int()</code>. <code>int(True)</code> is <code>1</code> and <code>int(False)</code> is <code>0</code>. So, if I run this, I will get a list of <code>1</code>s and <code>0</code>s. Then I <code>sum</code> the entire list to get the count of <code>1</code>s (i.e. <code>True</code>s) using the <code>sum</code> builtin. I drop the <code>[</code> and <code>]</code> because I'm just going to iterate over the list and not index it or anything.</p>
<p>Here's another alternative that occurred to me.</p>
<pre><code>sum(1 for v in enron_data.values() if v['poi'] is True)
</code></pre>
| 4
|
2016-09-04T09:30:14Z
|
[
"python"
] |
infinite while loop in python when integer compared with range
| 39,315,460
|
<p>my while code:</p>
<pre><code>i=0
a = range(100)
while i < range(100):
print i
i += 9
</code></pre>
<p>this goes into an infinite loop...may i know why?</p>
<p>is it because an integer is compared to the list?
but what happens when i becomes greater than 99?</p>
<p>shouldnt it come out of the while loop?</p>
<p>below code works fine as expected:</p>
<pre><code>i=0
a = range(100)
a_len = len(a)
while i < a_len:
print i
i += 9
</code></pre>
| 0
|
2016-09-04T09:26:44Z
| 39,315,491
|
<p>Sadly in Python 2.x, an <code>int</code> is always less than a <code>list</code> (even if that list is empty).</p>
<pre><code>>>> 9 < []
True
</code></pre>
<p>What you want to be doing is using the 3-argument form of <code>range</code> so you have a <em>start</em>, a <em>stop</em> and a <em>step</em>, eg:</p>
<pre><code>for i in range(0, 100, 9):
print i
</code></pre>
| 7
|
2016-09-04T09:29:45Z
|
[
"python",
"python-2.7",
"while-loop"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.