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 |
---|---|---|---|---|---|---|---|---|---|
Categorical values on the x-axis with xlsxwriter
| 39,499,563 |
<p>I have a plot that needs names as the values for the x-axis. I imagine this is accomplished via the set_x_axis function for chart objects but can't find the proper key in the documentation (<a href="http://xlsxwriter.readthedocs.io/chart.html#set_x_axis" rel="nofollow">http://xlsxwriter.readthedocs.io/chart.html#set_x_axis</a>). The following code produces the graph below:</p>
<pre><code>chart = workbook.add_chart({'type':'scatter'})
colLetter = alphabet[1] #alphabet is list of alphabet
for ii in range(4):
colLetter = alphabet[ii+1]
chart.add_series({
'name': '=Sheet1!$%s$1'%colLetter,
'categories': '=Sheet1!$A$2:$A$'+str(lastRowNumber),
'values': '=Sheet1!$%s$2:$%s$6'%(colLetter, colLetter),
})
chart.set_title({'name': 'Cityblock'})
chart.set_x_axis({'name': 'Subject'})
chart.set_y_axis({'name': 'Distance'})
chart.set_style(11)
worksheet.insert_chart('F1', chart)
</code></pre>
<p><a href="http://i.stack.imgur.com/lH2om.png" rel="nofollow"><img src="http://i.stack.imgur.com/lH2om.png" alt="enter image description here"></a></p>
<p>Any suggestions? I'm using xlsxwriter with python 2.7.</p>
| 1 |
2016-09-14T20:59:33Z
| 39,505,730 |
<p>Just set the series categories to point to the strings, or numbers, or dates that you wish to plot.</p>
<p>For example:</p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()
# Add a column chart.
chart = workbook.add_chart({'type': 'column'})
# Write some data to add to plot on the chart.
worksheet.write_column('A1', ['Bob', 'Eve', 'Ann'])
worksheet.write_column('B1', [5, 10, 7])
# Configure the chart.
chart.add_series({'categories': '=Sheet1!$A$1:$A$3',
'values': '=Sheet1!$B$1:$B$3'})
# Insert the chart into the worksheet.
worksheet.insert_chart('D1', chart)
workbook.close()
</code></pre>
<p>Output:</p>
<p><a href="http://i.stack.imgur.com/fQQHo.png" rel="nofollow"><img src="http://i.stack.imgur.com/fQQHo.png" alt="enter image description here"></a></p>
| 1 |
2016-09-15T07:52:32Z
|
[
"python",
"xlsxwriter"
] |
Making swarmplot points bigger
| 39,499,576 |
<p>I would like to make the data points on my swarmplot larger. The code I have is:</p>
<pre><code>sns.swarmplot(x="Heart", y="FirstPersonPronouns", hue="Speech", data=df)
sns.set_context("notebook", font_scale=1.8)
</code></pre>
<p>I have tried scatter_kws but get </p>
<pre><code>Attribute error: unknown property scatter_kws.
</code></pre>
| 0 |
2016-09-14T21:00:36Z
| 39,500,752 |
<p>From the swarmplot docstring:</p>
<pre><code>Signature: seaborn.swarmplot(x=None, y=None, hue=None, data=None,
order=None, hue_order=None, split=False, orient=None, color=None,
palette=None, size=5, edgecolor='gray', linewidth=0, ax=None,
**kwargs)
Docstring: Draw a categorical scatterplot with non-overlapping points.
[snip]
Parameters
----------
x, y, hue : names of variables in ``data`` or vector data, optional
Inputs for plotting long-form data. See examples for interpretation.
data : DataFrame, array, or list of arrays, optional
Dataset for plotting. If ``x`` and ``y`` are absent, this is
interpreted as wide-form. Otherwise it is expected to be long-form. [snip]
</code></pre>
<p>And then:</p>
<pre><code>size : float, optional
Diameter of the markers, in points. (Although ``plt.scatter`` is used
to draw the points, the ``size`` argument here takes a "normal"
markersize and not size^2 like ``plt.scatter``.
</code></pre>
| 2 |
2016-09-14T22:44:45Z
|
[
"python",
"seaborn"
] |
"Compiling" Python to run on another machine
| 39,499,599 |
<p>I have created a simple-medium complexity script written in Python using Pycharm on my laptop and I wish to run this on my Raspberry Pi using Crontab. All of my past programming experience has been with C++ and C# in Windows and so I would normally just do a build of the project and it all gets compiled and linked into a single executable file.</p>
<p>For Python how do you "compile" the script so that it can be run on another PC? I use some external libraries (requests and ImgurClient) which I had to install using the Pycharm app. I guess I'm correct in thinking that these need to be taken across to the RaspPi too? My script is in two files and so do I need to copy both of these files across? Is there a way to build them into a single file to use easily?</p>
<p>This is my first script which I've written just from my knowledge of other languages and a bit of Googling. Just don't know how to proceed now that I have the actual script.</p>
| 0 |
2016-09-14T21:02:50Z
| 39,499,638 |
<p>Python does not need to compile as it is an interpretive language. You will be fine running it on another machine as long as you aren't making system calls. System calls will only become a problem if you are trying to do things like use windows commands on a linux machine.</p>
<p>Just copy those two files over to the pi and run like normal. Or from the terminal</p>
<pre><code>python program.py
</code></pre>
| 0 |
2016-09-14T21:06:26Z
|
[
"python",
"cron",
"pycharm"
] |
"Compiling" Python to run on another machine
| 39,499,599 |
<p>I have created a simple-medium complexity script written in Python using Pycharm on my laptop and I wish to run this on my Raspberry Pi using Crontab. All of my past programming experience has been with C++ and C# in Windows and so I would normally just do a build of the project and it all gets compiled and linked into a single executable file.</p>
<p>For Python how do you "compile" the script so that it can be run on another PC? I use some external libraries (requests and ImgurClient) which I had to install using the Pycharm app. I guess I'm correct in thinking that these need to be taken across to the RaspPi too? My script is in two files and so do I need to copy both of these files across? Is there a way to build them into a single file to use easily?</p>
<p>This is my first script which I've written just from my knowledge of other languages and a bit of Googling. Just don't know how to proceed now that I have the actual script.</p>
| 0 |
2016-09-14T21:02:50Z
| 39,499,644 |
<p>Use PyInstaller. In the terminal, to create a stand alone exe just use a command like this:</p>
<pre><code>pyinstaller -F myscript.py
</code></pre>
| 0 |
2016-09-14T21:06:51Z
|
[
"python",
"cron",
"pycharm"
] |
"Compiling" Python to run on another machine
| 39,499,599 |
<p>I have created a simple-medium complexity script written in Python using Pycharm on my laptop and I wish to run this on my Raspberry Pi using Crontab. All of my past programming experience has been with C++ and C# in Windows and so I would normally just do a build of the project and it all gets compiled and linked into a single executable file.</p>
<p>For Python how do you "compile" the script so that it can be run on another PC? I use some external libraries (requests and ImgurClient) which I had to install using the Pycharm app. I guess I'm correct in thinking that these need to be taken across to the RaspPi too? My script is in two files and so do I need to copy both of these files across? Is there a way to build them into a single file to use easily?</p>
<p>This is my first script which I've written just from my knowledge of other languages and a bit of Googling. Just don't know how to proceed now that I have the actual script.</p>
| 0 |
2016-09-14T21:02:50Z
| 39,499,656 |
<p>You can "compile" python files to <code>.pyc</code> but you would still need the python interpreter on the RaspPi to run them.</p>
<p>On a PC that does not have Python, you can create a standalone executable using <code>py2exe</code>, but the executable must then run on Windows.</p>
<p>You have to install a python interpreter on your raspberry Pi, or create an executable with <code>py2exe</code> which targets raspberry Pi (if py2exe exists on that platform), that would be on another raspberry Pi :)</p>
<p>Another alternative would be <code>Cython</code>, but with external libraries as complex as the ones you want to use that would be a really difficult route.</p>
<p><a href="https://www.raspberrypi.org/documentation/usage/python" rel="nofollow">Python on Raspberry Pi</a></p>
<p><a href="http://stackoverflow.com/questions/304883/what-do-i-use-on-linux-to-make-a-python-program-executable">Creating python exes on Linux</a></p>
| 0 |
2016-09-14T21:07:35Z
|
[
"python",
"cron",
"pycharm"
] |
"Compiling" Python to run on another machine
| 39,499,599 |
<p>I have created a simple-medium complexity script written in Python using Pycharm on my laptop and I wish to run this on my Raspberry Pi using Crontab. All of my past programming experience has been with C++ and C# in Windows and so I would normally just do a build of the project and it all gets compiled and linked into a single executable file.</p>
<p>For Python how do you "compile" the script so that it can be run on another PC? I use some external libraries (requests and ImgurClient) which I had to install using the Pycharm app. I guess I'm correct in thinking that these need to be taken across to the RaspPi too? My script is in two files and so do I need to copy both of these files across? Is there a way to build them into a single file to use easily?</p>
<p>This is my first script which I've written just from my knowledge of other languages and a bit of Googling. Just don't know how to proceed now that I have the actual script.</p>
| 0 |
2016-09-14T21:02:50Z
| 39,499,690 |
<p>As the other answers have said, you can just run your code on the Pi, because Python code is interpreted and not complied.</p>
<p>That being said, you will need to install any python packages, like the ImgurClient beforehand. If you did this with PyCharm on you PC, you will likely have to use <a href="http://www.pythonforbeginners.com/basics/python-pip-usage" rel="nofollow">pip</a> on the Pi.</p>
| 0 |
2016-09-14T21:10:19Z
|
[
"python",
"cron",
"pycharm"
] |
"Compiling" Python to run on another machine
| 39,499,599 |
<p>I have created a simple-medium complexity script written in Python using Pycharm on my laptop and I wish to run this on my Raspberry Pi using Crontab. All of my past programming experience has been with C++ and C# in Windows and so I would normally just do a build of the project and it all gets compiled and linked into a single executable file.</p>
<p>For Python how do you "compile" the script so that it can be run on another PC? I use some external libraries (requests and ImgurClient) which I had to install using the Pycharm app. I guess I'm correct in thinking that these need to be taken across to the RaspPi too? My script is in two files and so do I need to copy both of these files across? Is there a way to build them into a single file to use easily?</p>
<p>This is my first script which I've written just from my knowledge of other languages and a bit of Googling. Just don't know how to proceed now that I have the actual script.</p>
| 0 |
2016-09-14T21:02:50Z
| 39,499,735 |
<p>I don't know if you are gonna be able to run the python script in your other environment, specially if the script uses external libraries (.whl) that you normally install with pip.</p>
<p>A good option to run the script on a clean environment is to use virtualenv:</p>
<p><a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">https://virtualenv.pypa.io/en/stable/</a></p>
<p>"It creates an environment that has its own installation directories, that doesnât share libraries with other virtualenv environments (and optionally doesnât access the globally installed libraries either)"</p>
<p>And then install only the necessary librarys to run your script. If you export this new environment, you will probably be able to run your script without any problems.</p>
| 0 |
2016-09-14T21:14:47Z
|
[
"python",
"cron",
"pycharm"
] |
"Compiling" Python to run on another machine
| 39,499,599 |
<p>I have created a simple-medium complexity script written in Python using Pycharm on my laptop and I wish to run this on my Raspberry Pi using Crontab. All of my past programming experience has been with C++ and C# in Windows and so I would normally just do a build of the project and it all gets compiled and linked into a single executable file.</p>
<p>For Python how do you "compile" the script so that it can be run on another PC? I use some external libraries (requests and ImgurClient) which I had to install using the Pycharm app. I guess I'm correct in thinking that these need to be taken across to the RaspPi too? My script is in two files and so do I need to copy both of these files across? Is there a way to build them into a single file to use easily?</p>
<p>This is my first script which I've written just from my knowledge of other languages and a bit of Googling. Just don't know how to proceed now that I have the actual script.</p>
| 0 |
2016-09-14T21:02:50Z
| 39,499,743 |
<p>If you have Python installed on your Raspberry Pi, then from the shell, you just need to run:</p>
<pre><code># This installs pip (Python installer) as well as the requests library
sudo apt-get install python-pip
</code></pre>
<p>Once that is installed, run:</p>
<pre><code># To install the ImgurClient
pip install imgurpython
</code></pre>
<p>Then you can just run your script at the shell by typing:</p>
<pre><code>python your_script_name.py
</code></pre>
<hr>
<p>If you do not already have Python installed, just run the following command to install it before the others:</p>
<pre><code>sudo apt-get install python
</code></pre>
| 1 |
2016-09-14T21:15:13Z
|
[
"python",
"cron",
"pycharm"
] |
Python: how to get text from html file
| 39,499,693 |
<p>I have a folder with some <code>html-file</code> with</p>
<pre><code>import os
indir = 'html/'
for root, dirs, filenames in os.walk(indir):
for f in filenames:
page = open(f)
</code></pre>
<p>But it returns me <code>IOError: [Errno 2] No such file or directory: '0out.html'.</code></p>
<p>But there are files <code>0out.html, 1out.html, 2out.html</code>.
I also try <code>codecs</code> but it return this error too.
Where is an error there?</p>
| -1 |
2016-09-14T21:11:01Z
| 39,499,713 |
<p>You need to prepend the path to the file.</p>
<pre><code>import os
indir = 'html/'
for root, dirs, filenames in os.walk(indir):
for f in filenames:
page = open(os.path.join(indir ,f)) # <-- note the added path
</code></pre>
<p>Without it, you are trying to open a file named <code>0out.html</code> which is a peer to your <code>indir</code>. When you prepend the path, you indicate that it is a child.</p>
| 0 |
2016-09-14T21:12:35Z
|
[
"python",
"html"
] |
Override ipython exit function - or add hooks in to it
| 39,499,748 |
<p>In my project <a href="http://github.com/rochacbruno/manage" rel="nofollow">manage</a>, I am embedding iPython with:</p>
<pre><code>from IPython import start_ipython
from traitlets.config import Config
c = Config()
c.TerminalInteractiveShell.banner2 = "Welcome to my shell"
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
start_ipython(argv=[], user_ns={}, config=c)
</code></pre>
<p>It works well and opens my iPython console, but to leave ipython I can just type <code>exit</code> or <code>exit()</code> or press <code>ctrl+D</code>.</p>
<p>What I want to do is to add an <code>exit hook</code> or replace that <code>exit</code> command with something else.</p>
<p>Lets say I have a function.</p>
<pre><code>def teardown_my_shell():
# things I want to happen when iPython exits
</code></pre>
<p>How do I register that function to be executed when I <code>exit</code> or even how to make <code>exit</code> to execute that function?</p>
<p>NOTE: I tried to pass <code>user_ns={'exit': teardown_my_shell}</code> and doesn't work.</p>
<p>Thanks.</p>
| 2 |
2016-09-14T21:16:03Z
| 39,499,913 |
<p>Googling <a href="https://www.google.com/search?q=ipython%20exit%20hook" rel="nofollow">IPython exit hook</a> turns up <a href="http://ipython.readthedocs.io/en/stable/api/generated/IPython.core.hooks.html?highlight=core.hooks#module-IPython.core.hooks" rel="nofollow"><code>IPython.core.hooks</code></a>. From that documentation, it looks like you can define an exit hook in an <a href="https://ipython.org/ipython-doc/2/config/extensions/index.html" rel="nofollow">IPython extension</a> and register it with the IPython instance's <code>set_hook</code> method:</p>
<pre><code># whateveryoucallyourextension.py
import IPython.core.error
def shutdown_hook(ipython):
do_whatever()
raise IPython.core.error.TryNext
def load_ipython_extension(ipython)
ipython.set_hook('shutdown_hook', shutdown_hook)
</code></pre>
<p>You'll have to add the extension to your <code>c.InteractiveShellApp.extensions</code>.</p>
| 2 |
2016-09-14T21:29:02Z
|
[
"python",
"shell",
"ipython"
] |
Override ipython exit function - or add hooks in to it
| 39,499,748 |
<p>In my project <a href="http://github.com/rochacbruno/manage" rel="nofollow">manage</a>, I am embedding iPython with:</p>
<pre><code>from IPython import start_ipython
from traitlets.config import Config
c = Config()
c.TerminalInteractiveShell.banner2 = "Welcome to my shell"
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
start_ipython(argv=[], user_ns={}, config=c)
</code></pre>
<p>It works well and opens my iPython console, but to leave ipython I can just type <code>exit</code> or <code>exit()</code> or press <code>ctrl+D</code>.</p>
<p>What I want to do is to add an <code>exit hook</code> or replace that <code>exit</code> command with something else.</p>
<p>Lets say I have a function.</p>
<pre><code>def teardown_my_shell():
# things I want to happen when iPython exits
</code></pre>
<p>How do I register that function to be executed when I <code>exit</code> or even how to make <code>exit</code> to execute that function?</p>
<p>NOTE: I tried to pass <code>user_ns={'exit': teardown_my_shell}</code> and doesn't work.</p>
<p>Thanks.</p>
| 2 |
2016-09-14T21:16:03Z
| 39,502,890 |
<p>First thanks to @user2357112, I learned how to create an extension and register a hook, but I figured out that <code>shutdown_hook</code>is deprecated.</p>
<p>The right way is simply.</p>
<pre><code>import atexit
def teardown_my_shell():
# things I want to happen when iPython exits
atexit.register(teardown_my_shell)
</code></pre>
| 2 |
2016-09-15T03:58:37Z
|
[
"python",
"shell",
"ipython"
] |
Missing .DLL files Anaconda 4.1.1 32-bit
| 39,499,756 |
<p>I've installed <strong>Anaconda 4.1.1 32-bit</strong> on our <strong>Windows 2003 Server</strong>. </p>
<p>When I try to run a program through the command prompt it gives me the following error message:</p>
<pre><code>..\python.exe is not a valid Win32 application
</code></pre>
<p>After searching around for a bit, I downloaded dependency walker to take a look at what is missing and it looks like <strong>wer.dll</strong> and <strong>ieshims.dll</strong> have a problem opening. </p>
<p>I can't make heads nor tails of this. </p>
| 0 |
2016-09-14T21:16:45Z
| 39,499,894 |
<p>Those .dll files appear to have been removed by IE8. You should be able to restore them by installing Visual C++ 2005 SP1</p>
<pre><code>https://www.microsoft.com/en-au/download/details.aspx?id=26347
</code></pre>
<p>Attributed from:</p>
<p><a href="http://stackoverflow.com/a/23484851/3006366">http://stackoverflow.com/a/23484851/3006366</a></p>
| 0 |
2016-09-14T21:27:10Z
|
[
"python",
"dll",
"anaconda",
"windows-2003-webserver"
] |
django attribute error : object has no attribute 'get_bound_field'
| 39,499,798 |
<p>Apparently a form being loaded on my template is requiring a field that isn't being passed to it. </p>
<p>Can anyone tell me what is causing this error?</p>
<p>Error occurs during template rendering</p>
<pre><code>In template C:\django\projectname\static\templates\link_list.html, error at line 114
'UserProfile' object has no attribute 'get_bound_field'
104
105 </p>
106
107 </form>
108 </div>
109 <div id="make-offer" style="display: none">
110
111 <p>Make an offer</p>
112 <form class=".formLayout" name="offer-form" action="" method="post" enctype="multipart/form-data">
113 {% csrf_token %}
114 {{ form.as_table }}
115 <input type="submit" class="data" style="font-family: VT323; font-size: 50%" value="Submit" />
116 </form>
117 </div>
118 </div>
119 </div>
120 </div>
</code></pre>
<p>This is served by the following view:</p>
<pre><code>def link(request):
print("trying to authenticate...")
if request.user.is_authenticated():
user_profile = UserProfile.objects.get(user=request.user)
else:
return render(request, 'login.html')
if request.method == "POST":
print("request was a post.")
if request.is_ajax():
...
else:
if request.method == "POST":
form = OfferForm(request.POST, request.FILES, maker_id=user_profile.id)
if form.is_valid():
if request.POST.get('location'):
offer = form.save()
offer.save()
offer.maker = maker
offer.save()
else:
print form.errors
return render(request, "link_list.html", {'form' : form} )
else:
form = OfferForm(maker_id=user_profile.id)
print("request wasn't ajax.")
data = {'form': form}
return render(request, 'link_list.html', data)
</code></pre>
<p>Here are the relevant models and forms: </p>
<pre><code>class OfferForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
maker_id = kwargs.pop('maker_id')
super(OfferForm, self).__init__(*args, **kwargs)
maker = UserProfile.objects.get(id=maker_id)
self.fields['maker'] = maker
class Meta:
model = Offer
fields = [
"name",
"value",
"description",
"tags",
"location",
"service",
"icon",
]
widgets = {
'name': forms.TextInput(
attrs={'id': 'name', 'class': '.formLayout', 'style': 'font-family: VT323; font-size: 60%', 'required': True, 'placeholder': 'name'}
),
'value': forms.TextInput(
attrs={'id': 'value', 'class': '.formLayout', 'style': 'font-family: VT323; font-size: 60%', 'required': True, 'placeholder': 'value'}
),
'description': forms.TextInput(
attrs={'id': 'description', 'class': '.formLayout', 'style': 'font-family: VT323; font-size: 60%', 'required': True, 'placeholder': 'description'}
),
'tags': forms.TextInput(
attrs={'id': 'tags', 'class': '.formLayout', 'style': 'font-family: VT323; font-size: 60%', 'required': True, 'placeholder': 'tags'}
),
'location': forms.TextInput(
attrs={'id': 'location', 'class': 'geo', 'data-geo': 'location', 'required': False, 'placeholder': 'leave blank to use your location'}
),
'service': forms.CheckboxInput(
attrs={'id': 'service', 'class': '.formLayout', 'required': False}
),
}
</code></pre>
<p>models.py</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True, null=True)
location = models.CharField(max_length=200, null=True)
longitude = models.FloatField(null=True)
latitude = models.FloatField(null=True)
credit = models.FloatField(default=0, null=True)
picture = models.ImageField(upload_to=upload_location, blank=True)
def __unicode__(self):
return self.user.username
class Offer(models.Model):
name = models.CharField(max_length=120)
description = models.CharField(max_length=120)
value = models.FloatField(default=0.0)
tags = models.CharField(max_length=120, null=True)
maker = models.ForeignKey(UserProfile, null=True)
def __unicode__(self):
return self.name
</code></pre>
| 1 |
2016-09-14T21:20:06Z
| 39,500,348 |
<p>In your form you're getting a UserProfile object and then assigning it as a field. But it's not a field, it's a model object.</p>
<p>I don't know what you're trying to do there, but don't assign that object to the fields dict.</p>
| 1 |
2016-09-14T22:04:06Z
|
[
"python",
"django",
"models"
] |
Ansible tower-cli on Windows 10 - tower-cli' is not recognized as an internal or external command
| 39,499,819 |
<p>From this link: <a href="https://github.com/ansible/tower-cli/" rel="nofollow">https://github.com/ansible/tower-cli/</a>, you install tower-cli with pip install ansible-tower-cli but when you go to run a command like: <code>tower-cli config host www.myWebsite.com</code>, </p>
<p>You get this error: <code>tower-cli' is not recognized as an internal or external command, 14-Sep-2016 15:41:49 operable program or batch file.</code></p>
<p>I know that error means that <strong><em>I need to add the location of that executable to the windows PATH</em></strong> which I thought i did with:</p>
<p><a href="http://i.stack.imgur.com/l1B6G.png" rel="nofollow"><img src="http://i.stack.imgur.com/l1B6G.png" alt="enter image description here"></a></p>
<p>But still same error, any ideas?</p>
| 0 |
2016-09-14T21:21:42Z
| 39,579,619 |
<p>If you run the command python in your windows shell and get that error, 'python' is not recognized as an internal or external command, operable program or bathc file, then do this: </p>
<p><em>Replace <strong>python</strong> with <strong>py</em></strong>, so type <code>py</code> in the command prompt and it'll work.</p>
<pre><code>Again type "py" NOT "python" in your command prompt and it should work !
</code></pre>
| 0 |
2016-09-19T18:14:58Z
|
[
"python",
"pip",
"ansible",
"ansible-playbook",
"ansible-tower"
] |
Why declare a list twice in __init__?
| 39,499,823 |
<p>I'm reading through the Python Docs, and, under <a href="https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes" rel="nofollow">Section 8.4.1</a>,
I found the following <code>__init__</code> definition (abbreviated):</p>
<pre><code>class ListBasedSet(collections.abc.Set):
''' Alternate set implementation favoring space over speed
and not requiring the set elements to be hashable. '''
def __init__(self, iterable):
self.elements = lst = []
for value in iterable:
if value not in lst:
lst.append(value)
</code></pre>
<p>The part I don't get is the <code>self.elements = lst = []</code> line. Why the double assignment?</p>
<p>Adding some print statements:</p>
<pre><code>def __init__(self, iterable):
self.elements = lst = []
print('elements id:', id(self.elements))
print('lst id:', id(lst))
for value in iterable:
if value not in lst:
lst.append(value)
</code></pre>
<p>Declaring one:</p>
<pre><code>ListBasedSet(range(3))
elements id: 4741984136
lst id: 4741984136
Out[36]: <__main__.ListBasedSet at 0x11ab12fd0>
</code></pre>
<p>As expected, they both point to the same PyObject.</p>
<p>Is brevity the only reason to do something like this? If not, why? Something to do with reentrancy?</p>
| 0 |
2016-09-14T21:21:51Z
| 39,500,256 |
<p>I'd call this a case of premature optimization; you don't save <em>that much</em> by eliminating the dot, especially for large input iterables; here's some timings:</p>
<p>Eliminating the dot:</p>
<pre><code>%timeit ListBasedSet(range(3))
The slowest run took 4.06 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.05 µs per loop
%timeit ListBasedSet(range(30))
100000 loops, best of 3: 18.5 µs per loop
%timeit ListBasedSet(range(3000))
10 loops, best of 3: 119 ms per loop
</code></pre>
<p>While, with the dot (i.e replace <code>lst</code> with <code>self.elements</code>:</p>
<pre><code>%timeit ListBasedSet(range(3))
The slowest run took 5.97 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.48 µs per loop
%timeit ListBasedSet(range(30))
10000 loops, best of 3: 22.8 µs per loop
%timeit ListBasedSet(range(3000))
10 loops, best of 3: 118 ms per loop
</code></pre>
<p>As you can see, as we increase the size of the input iterable, the difference in time pretty much disappears, the appending and membership testing pretty much cover any gains. </p>
| 0 |
2016-09-14T21:55:32Z
|
[
"python",
"python-3.x",
"documentation",
"reentrancy"
] |
celery task unable to import ImportError of a module from inside the project
| 39,499,893 |
<p>I would like to note that the following error only occurs when ran through a celery worker.
with the following command in the terminal:</p>
<pre><code>celery -A MarketPlaceTasks worker --loglevel=info
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/celery/app/trace.py", line 218, in trace_task
R = retval = fun(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/celery/app/trace.py", line 398, in __protected_call__
return self.run(*args, **kwargs)
File "/home/nick/mpcrawler2/MarketPlaceTasks.py", line 65, in get_item_data
logger, request, run_data, store_config, app_config = setup_task(payload)
File "/home/nick/mpcrawler2/MarketPlaceTasks.py", line 33, in setup_task
store_config = ConfigReader.read_store_config(request.Store)
File "/home/nick/mpcrawler2/shared/ConfigReader.py", line 22, in read_store_config
from singletons.StoreData import StoreData
File "/home/nick/mpcrawler2/singletons/StoreData.py", line 3, in <module>
from models.StoreConfig import StoreConfig
File "/home/nick/mpcrawler2/models/StoreConfig.py", line 3, in <module>
from enums.MpStores import MpStore
ImportError: No module named enums.MpStores
</code></pre>
<p>I have all my enums in a separate module. The module looks like this, and is located inside the same directory as the project:</p>
<p><a href="http://i.stack.imgur.com/VDANU.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/VDANU.jpg" alt="enum directory screenshot"></a></p>
<p>Whenever I run the project via pycharm or terminal everything seems to work as intended.</p>
<p>The worker's starting point looks like this:</p>
<pre><code>from celery import Celery
app = Celery('tasks', broker='*some ampq address here*')
</code></pre>
<p>The <code>__init__.py</code> file is empty. The enum files look like this:</p>
<pre><code>from enum import Enum
# noinspection SpellCheckingInspection
class MpStore(Enum):
somevalue = 1
someothervalue = 2
etc = 3
</code></pre>
<p>As I'm using Python 2.7 I'm using <a href="https://pypi.python.org/pypi/enum34" rel="nofollow"><code>enum34</code></a> that was installed using pip.</p>
<p>Please let me know if there's anything else I should provide in the question.</p>
| 1 |
2016-09-14T21:27:09Z
| 39,500,575 |
<p>Well it seems like some sort of work around but following the advice in this answer:
<a href="http://stackoverflow.com/questions/4655526/how-to-accomplish-relative-import-in-python/4656228#4656228">How to accomplish relative import in python</a></p>
<p>I moved most of the project inside a "main" module containing all of them. and then i was able to:
instead of <code>from enums.MpStore import MpStore</code><br>
I now use <code>from stuff.enums.MpStore import MpStore</code> "stuff" being the new module name. </p>
<p>I would love to hear of a better way though...</p>
| 0 |
2016-09-14T22:26:01Z
|
[
"python",
"python-2.7",
"enums",
"celery",
"celery-task"
] |
Is there a standard way to tell py.test to run against specific code?
| 39,499,937 |
<p>I'm trying to run a Python project's unit tests using py.test. Until recently I've used nose and it ran the tests against my local source code instead of the installed package, but py.test seems to want to run against the installed package, meaning I have to run <code>python setup.py install</code> before every test run.</p>
<p>The project is organized like so:</p>
<pre><code>/project
/project
__init__.py
project_file.py
/test
__init__.py
/test_project
test_project_file.py
</code></pre>
<p>The only way I've found to get py.test to run against the local code is to run <code>python -m pytest</code> in the top /project folder. It's very strange, as running <code>py.test</code> in the same location runs against the installed code. According to <a href="http://doc.pytest.org/en/latest/usage.html#cmdline" rel="nofollow">the docs</a> these commands ought to be equivalent, and --version returns the same info for both.</p>
<p>Is there a standard way to tell py.test to run against specific code? I haven't been able to find a clear answer in py.test's documentation.</p>
| 0 |
2016-09-14T21:30:39Z
| 39,519,231 |
<p>My first mistake was setting up my project using <code>python setup.py install</code> instead of <code>python setup.py develop</code>. Pytest expects you to use the latter, which seems like good practice anyway.</p>
<p>If it's necessary to run against local code when the same code is installed, there does seem to be a way to do it. <a href="http://stackoverflow.com/a/34520971/2626755">This SO post</a> mentions a "hidden feature" of pytest, where you can put a conftest.py file in your root directory to tell pytest to run using your local code. Pytest seems to use the location of your overall configuration file to determine what it thinks your root directory is. This file is pytest.ini in my case.</p>
<p>As a curiosity, I believe that <code>python -m pytest</code> running using the local code where <code>py.test</code> did not was due to Python's default behavior of adding the directory that it's called in to sys.path.</p>
| 0 |
2016-09-15T19:48:30Z
|
[
"python",
"python-2.7",
"unit-testing",
"testing",
"py.test"
] |
Terminating a subprocess with KeyboardInterrupt
| 39,499,959 |
<p>I'm using Python to call a C++ program using the subprocess module. Since the program takes some time to run, I'd like to be able to terminate it using Ctrl+C. I've seen a few questions regarding this on StackOverflow but none of the solutions seem to work for me.</p>
<p>What I would like is for the subprocess to be terminated on KeyboardInterrupt. This is the code that I have (similar to suggestions in other questions):</p>
<pre><code>import subprocess
binary_path = '/path/to/binary'
args = 'arguments' # arbitrary
call_str = '{} {}'.format(binary_path, args)
proc = subprocess.Popen(call_str)
try:
proc.wait()
except KeyboardInterrupt:
proc.terminate()
</code></pre>
<p>However, if I run this, the code is hung up waiting for the process to end and never registers the KeyboardInterrupt. I have tried the following as well:</p>
<pre><code>import subprocess
import time
binary_path = '/path/to/binary'
args = 'arguments' # arbitrary
call_str = '{} {}'.format(binary_path, args)
proc = subprocess.Popen(call_str)
time.sleep(5)
proc.terminate()
</code></pre>
<p>This code snippet works fine at terminating the program, so it's not the actual signal that's being sent to terminate that is the problem.</p>
<p>How can I change the code so that the subprocess can be terminated on KeyboardInterrupt?</p>
<p>I'm running Python 2.7 and Windows 7 64-bit. Thanks in advance!</p>
<p>Some related questions that I tried:</p>
<p><a href="http://stackoverflow.com/questions/19807134/python-sub-process-ctrlc">Python sub process Ctrl+C</a></p>
<p><a href="http://stackoverflow.com/questions/33496416/kill-subprocess-call-after-keyboardinterrupt">Kill subprocess.call after KeyboardInterrupt</a></p>
<p><a href="http://stackoverflow.com/questions/1603658/kill-subprocess-when-python-process-is-killed">kill subprocess when python process is killed?</a></p>
| 0 |
2016-09-14T21:32:31Z
| 39,500,096 |
<p>My ugly but successfull attempt on Windows:</p>
<pre><code>import subprocess
import threading
import time
binary_path = 'notepad'
args = 'foo.txt' # arbitrary
proc = None
done = False
def s():
call_str = '{} {}'.format(binary_path, args)
global done
global proc
proc = subprocess.Popen(call_str,stdout=subprocess.PIPE)
proc.wait()
done = True
t = threading.Thread(target=s)
t.start()
try:
while not done:
time.sleep(0.1)
except KeyboardInterrupt:
print("terminated")
proc.terminate()
</code></pre>
<p>Create a thread where the subprocess runs. Export the <code>proc</code> variable.</p>
<p>Then wait forever in a non-active loop. When CTRL+C is pressed, the exception is triggered. Inter-process communication (ex: <code>proc.wait()</code>) is conflicting with CTRL+C handling otherwise. When running in a thread, no such issue.</p>
<p>note: I have tried to avoid this time loop using <code>threading.lock()</code> but stumbled on the same CTRL+C ignore.</p>
| 1 |
2016-09-14T21:44:09Z
|
[
"python",
"windows",
"subprocess",
"interrupt",
"terminate"
] |
Terminating a subprocess with KeyboardInterrupt
| 39,499,959 |
<p>I'm using Python to call a C++ program using the subprocess module. Since the program takes some time to run, I'd like to be able to terminate it using Ctrl+C. I've seen a few questions regarding this on StackOverflow but none of the solutions seem to work for me.</p>
<p>What I would like is for the subprocess to be terminated on KeyboardInterrupt. This is the code that I have (similar to suggestions in other questions):</p>
<pre><code>import subprocess
binary_path = '/path/to/binary'
args = 'arguments' # arbitrary
call_str = '{} {}'.format(binary_path, args)
proc = subprocess.Popen(call_str)
try:
proc.wait()
except KeyboardInterrupt:
proc.terminate()
</code></pre>
<p>However, if I run this, the code is hung up waiting for the process to end and never registers the KeyboardInterrupt. I have tried the following as well:</p>
<pre><code>import subprocess
import time
binary_path = '/path/to/binary'
args = 'arguments' # arbitrary
call_str = '{} {}'.format(binary_path, args)
proc = subprocess.Popen(call_str)
time.sleep(5)
proc.terminate()
</code></pre>
<p>This code snippet works fine at terminating the program, so it's not the actual signal that's being sent to terminate that is the problem.</p>
<p>How can I change the code so that the subprocess can be terminated on KeyboardInterrupt?</p>
<p>I'm running Python 2.7 and Windows 7 64-bit. Thanks in advance!</p>
<p>Some related questions that I tried:</p>
<p><a href="http://stackoverflow.com/questions/19807134/python-sub-process-ctrlc">Python sub process Ctrl+C</a></p>
<p><a href="http://stackoverflow.com/questions/33496416/kill-subprocess-call-after-keyboardinterrupt">Kill subprocess.call after KeyboardInterrupt</a></p>
<p><a href="http://stackoverflow.com/questions/1603658/kill-subprocess-when-python-process-is-killed">kill subprocess when python process is killed?</a></p>
| 0 |
2016-09-14T21:32:31Z
| 39,503,654 |
<p>I figured out a way to do this, similar to Jean-Francois's answer with the loop but without the multiple threads. The key is to use Popen.poll() to determine if the subprocess has finished (will return None if still running). </p>
<pre><code>import subprocess
import time
binary_path = '/path/to/binary'
args = 'arguments' # arbitrary
call_str = '{} {}'.format(binary_path, args)
proc = subprocess.Popen(call_str)
try:
while proc.poll() is None:
time.sleep(0.1)
except KeyboardInterrupt:
proc.terminate()
raise
</code></pre>
<p>I added an additional raise after KeyboardInterrupt so the Python program is also interrupted in addition to the subprocess. </p>
<p>EDIT: Changed pass to time.sleep(0.1) as per eryksun's comment to reduce CPU consumption.</p>
| 2 |
2016-09-15T05:24:16Z
|
[
"python",
"windows",
"subprocess",
"interrupt",
"terminate"
] |
How to find element with specific parent?
| 39,499,976 |
<p>I have some HTML like:</p>
<pre><code><div class='cl1'>
<div class='cl2'>text_1</div>
<div class='cl3'>
<div class='cl2'>text_2</div>
</div>
</div>
</code></pre>
<p>I need to find any items of cl2 class that have cl1 as parent, so i need to get <strong>text_1</strong> but not <strong>text_2</strong>. In simple css it should be like this:</p>
<pre><code>'div.cl1>div.cl2'
</code></pre>
<p>but I use <em>robobrowser</em> and <em>BeautifulSoup</em>, and when I try</p>
<pre><code>soup.select('div.cl1>div.cl2')
</code></pre>
<p>it says that css selector is wrong.</p>
| 2 |
2016-09-14T21:33:54Z
| 39,500,233 |
<p>One possible solution would be:</p>
<pre><code>from bs4 import BeautifulSoup
data = """
<div class='cl1'>
<div class='cl2'>text_1</div>
<div class='cl3'>
<div class='cl2'>text_2</div>
</div>
</div>
"""
soup = BeautifulSoup(data)
divs = [div
for div in soup.find_all("div", {'class': 'cl2'})
if 'cl1' in div.parent["class"]]
# [<div class="cl2">text_1</div>]
</code></pre>
| 0 |
2016-09-14T21:53:49Z
|
[
"python",
"css-selectors",
"beautifulsoup",
"robobrowser"
] |
How to find element with specific parent?
| 39,499,976 |
<p>I have some HTML like:</p>
<pre><code><div class='cl1'>
<div class='cl2'>text_1</div>
<div class='cl3'>
<div class='cl2'>text_2</div>
</div>
</div>
</code></pre>
<p>I need to find any items of cl2 class that have cl1 as parent, so i need to get <strong>text_1</strong> but not <strong>text_2</strong>. In simple css it should be like this:</p>
<pre><code>'div.cl1>div.cl2'
</code></pre>
<p>but I use <em>robobrowser</em> and <em>BeautifulSoup</em>, and when I try</p>
<pre><code>soup.select('div.cl1>div.cl2')
</code></pre>
<p>it says that css selector is wrong.</p>
| 2 |
2016-09-14T21:33:54Z
| 39,501,209 |
<p>You selector is on the right track, you just need to space out the classes i.e <code>div.cl1>div.cl2</code> should be <code>div.cl1 > div.cl2</code>:</p>
<pre><code>In [5]: from bs4 import BeautifulSoup
In [6]: html = """<div class='cl1'>
<div class='cl2'>text_1</div>
<div class='cl3'>
<div class='cl2'>text_2</div>
</div>
</div>"""
In [7]: soup = BeautifulSoup(html, "html.parser")
In [8]: soup.select_one("div.cl1 > div.cl2") # good
Out[8]: <div class="cl2">text_1</div>
In [9]: print(soup.select_one("div.cl1>div.cl2")) # bad
None
</code></pre>
| 1 |
2016-09-14T23:42:22Z
|
[
"python",
"css-selectors",
"beautifulsoup",
"robobrowser"
] |
Python joke or chat error
| 39,500,093 |
<p>when i run this, if i type chat it runs the punchline from the joke above how do i fix this?
<a href="http://i.stack.imgur.com/1oXAp.png" rel="nofollow">enter image description here</a></p>
<pre><code>print ("whats your name?")
firstname = input()
print ("hello,", firstname)
print ("what's your surname?")
surname = input()
fullname = (firstname +" "+ surname)
print ("hello,", fullname)
print ("what shall i call you on a daily basis?")
name = input()
print ("Glad to meet you,", name)
print ("is there anything you would like to do?")
print (" you can 'hear a joke' or 'have a chat'")
question = input("joke or chat?")
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
if question == "chat":
print("what games do you like?")
game = input()
print ("NO way i love,", game)
</code></pre>
| -3 |
2016-09-14T21:43:53Z
| 39,500,143 |
<p>Your spacing / indentation is off:</p>
<pre><code>if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
</code></pre>
<p>In your code should be:</p>
<pre><code>if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
</code></pre>
<p><strong>PS:</strong> You should use more than 1 space for indenting to make it easier to read. Such as:</p>
<pre><code>if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
</code></pre>
| 1 |
2016-09-14T21:47:33Z
|
[
"python"
] |
Python joke or chat error
| 39,500,093 |
<p>when i run this, if i type chat it runs the punchline from the joke above how do i fix this?
<a href="http://i.stack.imgur.com/1oXAp.png" rel="nofollow">enter image description here</a></p>
<pre><code>print ("whats your name?")
firstname = input()
print ("hello,", firstname)
print ("what's your surname?")
surname = input()
fullname = (firstname +" "+ surname)
print ("hello,", fullname)
print ("what shall i call you on a daily basis?")
name = input()
print ("Glad to meet you,", name)
print ("is there anything you would like to do?")
print (" you can 'hear a joke' or 'have a chat'")
question = input("joke or chat?")
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
if question == "chat":
print("what games do you like?")
game = input()
print ("NO way i love,", game)
</code></pre>
| -3 |
2016-09-14T21:43:53Z
| 39,500,152 |
<p>In the absence of proper indentation, Python is assuming that the lines</p>
<pre><code>idk = input()
print ("Dead!!! LOL!!!!")
</code></pre>
<p>are outside the <code>if</code> statement. Indent them like you did for the <code>print</code> statement for the punchline.</p>
| 1 |
2016-09-14T21:48:19Z
|
[
"python"
] |
Swap every Nth element of two lists
| 39,500,214 |
<p>I have two lists as:</p>
<pre><code>l1 = [1, 2, 3, 4, 5, 6]
l2 = ['a', 'b', 'c', 'd', 'e', 'f']
</code></pre>
<p>I need to swap every <code>N</code>th element of these lists. For example if <code>N=3</code>, desired result is:</p>
<pre><code>l1 = [1, 2, 'c', 4, 5, 'f']
l2 = ['a', 'b', 3, 'd', 'e', 6]
</code></pre>
<p>I can do it via <code>for</code> loop and swap every <code>N</code>th element as:</p>
<pre><code>>>> for i in range(2,len(l1),3):
... l1[i], l2[i] = l2[i], l1[i]
...
>>> l1, l2
([1, 2, 'c', 4, 5, 'f'], ['a', 'b', 3, 'd', 'e', 6])
</code></pre>
<p>I want to know whether there is much more efficient way to achieve it. May be without <code>for</code> loop.</p>
<p>Note: Length of both lists will be same.</p>
| -2 |
2016-09-14T21:52:21Z
| 39,500,221 |
<p>We can achieve that via <code>list slicing</code> as:</p>
<pre><code>>>> l1[2::3], l2[2::3] = l2[2::3], l1[2::3]
>>> l1, l2
([1, 2, 'c', 4, 5, 'f'], ['a', 'b', 3, 'd', 'e', 6])
</code></pre>
| 1 |
2016-09-14T21:53:05Z
|
[
"python",
"list",
"swap"
] |
numpy binning: how to get array indexes satisfying a predicate
| 39,500,218 |
<p>I have a vector <code>g</code> of values of length 1024 and a smaller vector <code>f</code> of size 32 defining bin boundaries. <code>v</code> and <code>f</code> are sorted in ascending order. I want to return an array of vectors i.e <code>[v_1,v_2,v_3,...]</code> of length <code>len(f)</code> such that each vector <code>v_i</code> contains indices of <code>g</code> between <code>f_i</code> and <code>f_i + 1</code>. Is there a NumPy way to do such a thing that does not involve looping?</p>
| 0 |
2016-09-14T21:52:43Z
| 39,500,568 |
<p>first things first:</p>
<pre><code>import numpy as np
</code></pre>
<p>let's say you have your data <code>g</code>:</p>
<pre><code>g = sorted((1e3 * np.random.random(1024)).astype(int))
</code></pre>
<p>and your bins <code>f</code>:</p>
<pre><code>f = sorted((1e3 * np.random.random(32)).astype(int))
</code></pre>
<p>you can use <code>numpy.digitize</code>, which return the bin indices in <code>f</code> where each element of <code>g</code> belongs:</p>
<pre><code>dg = np.digitize(g,f)
</code></pre>
<p>The resulting vector is going to contains list of different sizes so you might want to store it is a list:</p>
<pre><code>for i in range(len(f)): v.append(np.argwhere(dg == i))
</code></pre>
| 0 |
2016-09-14T22:25:13Z
|
[
"python",
"numpy"
] |
numpy binning: how to get array indexes satisfying a predicate
| 39,500,218 |
<p>I have a vector <code>g</code> of values of length 1024 and a smaller vector <code>f</code> of size 32 defining bin boundaries. <code>v</code> and <code>f</code> are sorted in ascending order. I want to return an array of vectors i.e <code>[v_1,v_2,v_3,...]</code> of length <code>len(f)</code> such that each vector <code>v_i</code> contains indices of <code>g</code> between <code>f_i</code> and <code>f_i + 1</code>. Is there a NumPy way to do such a thing that does not involve looping?</p>
| 0 |
2016-09-14T21:52:43Z
| 39,502,590 |
<p>You can use <code>searchsorted</code> to find the sorted positions of <code>f</code> in <code>g</code>. These give the lower and upper bounds of the ranges that you want:</p>
<p>For example,</p>
<pre><code>In [42]: g
Out[42]:
array([ 1, 11, 19, 20, 21, 32, 36, 41, 47, 53, 54, 55, 65, 66, 69, 74, 76,
87, 89, 94])
In [43]: f
Out[43]: [0, 10, 20, 50, 100]
In [44]: binedges = g.searchsorted(f)
In [45]: binedges
Out[45]: array([ 0, 1, 3, 9, 20])
</code></pre>
<p>The array <code>binedges</code> gives you all the information that you need: the range of indices for bin <code>k</code> is <code>range(binedges[k], binedges[k+1])</code>.</p>
<p>Here's how you could create an explicit list of the indices in each bin:</p>
<pre><code>In [46]: rngs = [list(range(binedges[k], binedges[k+1])) for k in range(len(binedges)-1)]
In [47]: rngs
Out[47]: [[0], [1, 2], [3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]
</code></pre>
| 1 |
2016-09-15T03:14:44Z
|
[
"python",
"numpy"
] |
Pandas: how to get the unique values of a column that contains a list of values?
| 39,500,258 |
<p>Consider the following dataframe</p>
<pre><code>df = pd.DataFrame({'name' : [['one two','three four'], ['one'],[], [],['one two'],['three']],
'col' : ['A','B','A','B','A','B']})
df.sort_values(by='col',inplace=True)
df
Out[62]:
col name
0 A [one two, three four]
2 A []
4 A [one two]
1 B [one]
3 B []
5 B [three]
</code></pre>
<p>I would like to get a column that keeps track of all the unique strings included in <code>name</code> for each combination of <code>col</code>.</p>
<p>That is, the expected output is</p>
<pre><code>df
Out[62]:
col name unique_list
0 A [one two, three four] [one two, three four]
2 A [] [one two, three four]
4 A [one two] [one two, three four]
1 B [one] [one, three]
3 B [] [one, three]
5 B [three] [one, three]
</code></pre>
<p>Indeed, say for group A, you can see that the unique set of strings included in <code>[one two, three four]</code>, <code>[]</code> and <code>[one two]</code> is <code>[one two]</code></p>
<p>I can obtain the corresponding number of unique values using <a href="http://stackoverflow.com/questions/38355931/pandas-how-to-get-the-unique-number-of-values-in-cells-when-cells-contain-list">Pandas : how to get the unique number of values in cells when cells contain lists?</a> : </p>
<pre><code>df['count_unique']=df.groupby('col')['name'].transform(lambda x: list(pd.Series(x.apply(pd.Series).stack().reset_index(drop=True, level=1).nunique())))
df
Out[65]:
col name count_unique
0 A [one two, three four] 2
2 A [] 2
4 A [one two] 2
1 B [one] 2
3 B [] 2
5 B [three] 2
</code></pre>
<p>but replacing <code>nunique</code> with <code>unique</code> above fails.</p>
<p>Any ideas?
Thanks!</p>
| 3 |
2016-09-14T21:55:34Z
| 39,500,391 |
<p>Try:</p>
<pre><code>uniq_df = df.groupby('col')['name'].apply(lambda x: list(set(reduce(lambda y,z: y+z,x)))).reset_index()
uniq_df.columns = ['col','uniq_list']
pd.merge(df,uniq_df, on='col', how='left')
</code></pre>
<p>Desired output:</p>
<pre><code> col name uniq_list
0 A [one two, three four] [one two, three four]
1 A [] [one two, three four]
2 A [one two] [one two, three four]
3 B [one] [three, one]
4 B [] [three, one]
5 B [three] [three, one]
</code></pre>
| 2 |
2016-09-14T22:08:02Z
|
[
"python",
"pandas"
] |
Pandas: how to get the unique values of a column that contains a list of values?
| 39,500,258 |
<p>Consider the following dataframe</p>
<pre><code>df = pd.DataFrame({'name' : [['one two','three four'], ['one'],[], [],['one two'],['three']],
'col' : ['A','B','A','B','A','B']})
df.sort_values(by='col',inplace=True)
df
Out[62]:
col name
0 A [one two, three four]
2 A []
4 A [one two]
1 B [one]
3 B []
5 B [three]
</code></pre>
<p>I would like to get a column that keeps track of all the unique strings included in <code>name</code> for each combination of <code>col</code>.</p>
<p>That is, the expected output is</p>
<pre><code>df
Out[62]:
col name unique_list
0 A [one two, three four] [one two, three four]
2 A [] [one two, three four]
4 A [one two] [one two, three four]
1 B [one] [one, three]
3 B [] [one, three]
5 B [three] [one, three]
</code></pre>
<p>Indeed, say for group A, you can see that the unique set of strings included in <code>[one two, three four]</code>, <code>[]</code> and <code>[one two]</code> is <code>[one two]</code></p>
<p>I can obtain the corresponding number of unique values using <a href="http://stackoverflow.com/questions/38355931/pandas-how-to-get-the-unique-number-of-values-in-cells-when-cells-contain-list">Pandas : how to get the unique number of values in cells when cells contain lists?</a> : </p>
<pre><code>df['count_unique']=df.groupby('col')['name'].transform(lambda x: list(pd.Series(x.apply(pd.Series).stack().reset_index(drop=True, level=1).nunique())))
df
Out[65]:
col name count_unique
0 A [one two, three four] 2
2 A [] 2
4 A [one two] 2
1 B [one] 2
3 B [] 2
5 B [three] 2
</code></pre>
<p>but replacing <code>nunique</code> with <code>unique</code> above fails.</p>
<p>Any ideas?
Thanks!</p>
| 3 |
2016-09-14T21:55:34Z
| 39,500,774 |
<p>Here is the solution </p>
<pre><code>df['unique_list'] = df.col.map(df.groupby('col')['name'].sum().apply(np.unique))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/S8IdI.png" rel="nofollow"><img src="http://i.stack.imgur.com/S8IdI.png" alt="enter image description here"></a></p>
| 3 |
2016-09-14T22:47:11Z
|
[
"python",
"pandas"
] |
Manually add legend Items Python matplotlib
| 39,500,265 |
<p>I am using matlibplot and I would like to manually add items to the legend that are a color and a label. I am adding data to to the plot to specifying there would lead to a lot of duplicates.</p>
<p>My thought was to do:</p>
<pre><code> ax2.legend(self.labels,colorList[:len(self.labels)])
plt.legend()
</code></pre>
<p>Where self.labels is the number of items I want legend lables for that takes a subset of the large color list. However this yields nothing when I run it.</p>
<p>Am I missing anything?</p>
<p>Thanks</p>
| 0 |
2016-09-14T21:55:58Z
| 39,500,357 |
<p>Have you checked the <a href="http://matplotlib.org/users/legend_guide.html" rel="nofollow">Legend Guide</a>?</p>
<p>For practicality, I quote the example from the <a href="http://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artists" rel="nofollow">guide</a>.</p>
<blockquote>
<p>Not all handles can be turned into legend entries automatically, so it
is often necessary to create an artist which can. Legend handles donât
have to exists on the Figure or Axes in order to be used.</p>
<p>Suppose we wanted to create a legend which has an entry for some data
which is represented by a red color:</p>
</blockquote>
<pre><code>import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/mFZhR.png" rel="nofollow"><img src="http://i.stack.imgur.com/mFZhR.png" alt="enter image description here"></a></p>
<p><strong>Edit</strong></p>
<p>To add two patches you can do this:</p>
<pre><code>import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
red_patch = mpatches.Patch(color='red', label='The red data')
blue_patch = mpatches.Patch(color='blue', label='The blue data')
plt.legend(handles=[red_patch, blue_patch])
</code></pre>
<p><a href="http://i.stack.imgur.com/T1QLU.png" rel="nofollow"><img src="http://i.stack.imgur.com/T1QLU.png" alt="enter image description here"></a></p>
| 2 |
2016-09-14T22:05:15Z
|
[
"python",
"matplotlib"
] |
Behavior of ndarray.data for views in numpy
| 39,500,356 |
<p>I am trying to understand the meaning of <code>ndarray.data</code> field in numpy (see <a href="http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#memory-layout" rel="nofollow">memory layout</a> section of the reference page on N-dimensional arrays), especially for views into arrays. To quote the documentation:</p>
<blockquote>
<p>ndarray.data -- Python buffer object pointing to the start of the arrayâs data</p>
</blockquote>
<p>According to this description, I was expecting this to be a pointer to the C-array underlying the instance of ndarray.</p>
<p>Consider <code>x = np.arange(5, dtype=np.float64)</code>. </p>
<p>Form <code>y</code> as a view into <code>x</code> using a slice: <code>y = x[3:1:-1]</code>. </p>
<p>I was expecting <code>x.data</code> to point at location of <code>0.</code> and <code>y.data</code> to point at the location of <code>3.</code>. I was expecting the memory pointer printed by <code>y.data</code> to thus be offset by <code>3*x.itemsize</code> bytes from the memory pointer printed by <code>x.data</code>, but this does not appear to be the case:</p>
<pre><code>>>> import numpy as np
>>> x = np.arange(5, dtype=np.float64)
>>> y = x[ 3:1:-1]
>>> x.data
<memory at 0x000000F2F5150348>
>>> y.data
<memory at 0x000000F2F5150408>
>>> int('0x000000F2F5150408', 16) - int('0x000000F2F5150348', 16)
192
>>> 3*x.itemsize
24
</code></pre>
<p>The <code>'data'</code> key in <code>__array_interface</code> dictionary associated with the ndarray instance behaves more like I expect, although it may itself not be a pointer:</p>
<pre><code>>>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0]
24
</code></pre>
<blockquote>
<p>So this begs the question, what does the <code>ndarray.data</code> give? </p>
</blockquote>
<p>Thanks in advance.</p>
| 1 |
2016-09-14T22:05:12Z
| 39,500,532 |
<p><code><memory at 0x000000F2F5150348></code> is a <code>memoryview</code> object located at address <code>0x000000F2F5150348</code>; the buffer it provides access to is located somewhere else.</p>
<p>Memoryviews provide a number of operations described in the <a href="https://docs.python.org/3/library/stdtypes.html#typememoryview" rel="nofollow">relevant official documentation</a>, but at least on the Python-side API, they do not provide any way to access the raw address of the memory they expose. Particularly, the <code>at whatevernumber</code> number is not what you're looking for.</p>
| 3 |
2016-09-14T22:20:53Z
|
[
"python",
"python-3.x",
"numpy"
] |
Behavior of ndarray.data for views in numpy
| 39,500,356 |
<p>I am trying to understand the meaning of <code>ndarray.data</code> field in numpy (see <a href="http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#memory-layout" rel="nofollow">memory layout</a> section of the reference page on N-dimensional arrays), especially for views into arrays. To quote the documentation:</p>
<blockquote>
<p>ndarray.data -- Python buffer object pointing to the start of the arrayâs data</p>
</blockquote>
<p>According to this description, I was expecting this to be a pointer to the C-array underlying the instance of ndarray.</p>
<p>Consider <code>x = np.arange(5, dtype=np.float64)</code>. </p>
<p>Form <code>y</code> as a view into <code>x</code> using a slice: <code>y = x[3:1:-1]</code>. </p>
<p>I was expecting <code>x.data</code> to point at location of <code>0.</code> and <code>y.data</code> to point at the location of <code>3.</code>. I was expecting the memory pointer printed by <code>y.data</code> to thus be offset by <code>3*x.itemsize</code> bytes from the memory pointer printed by <code>x.data</code>, but this does not appear to be the case:</p>
<pre><code>>>> import numpy as np
>>> x = np.arange(5, dtype=np.float64)
>>> y = x[ 3:1:-1]
>>> x.data
<memory at 0x000000F2F5150348>
>>> y.data
<memory at 0x000000F2F5150408>
>>> int('0x000000F2F5150408', 16) - int('0x000000F2F5150348', 16)
192
>>> 3*x.itemsize
24
</code></pre>
<p>The <code>'data'</code> key in <code>__array_interface</code> dictionary associated with the ndarray instance behaves more like I expect, although it may itself not be a pointer:</p>
<pre><code>>>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0]
24
</code></pre>
<blockquote>
<p>So this begs the question, what does the <code>ndarray.data</code> give? </p>
</blockquote>
<p>Thanks in advance.</p>
| 1 |
2016-09-14T22:05:12Z
| 39,500,603 |
<p>Generally the number displayed by <code>x.data</code> isn't meant to be used by you. <code>x.data</code> is the buffer, which can be used in other contexts that expect a buffer.</p>
<pre><code>np.frombuffer(x.data,dtype=float)
</code></pre>
<p>replicates your <code>x</code>. </p>
<pre><code>np.frombuffer(x[3:].data,dtype=float)
</code></pre>
<p>this replicates <code>x[3:]</code>. But from Python you can't take <code>x.data</code>, add 192 bits (3*8*8) to it, and expect to get <code>x[3:]</code>.</p>
<p>I often use the <code>__array_interface__['data']</code> value to check whether two variables share a data buffer, but I don't use that number for any thing. These are informative numbers, not working values.</p>
<p>I recently explored this in</p>
<p><a href="http://stackoverflow.com/questions/39376892/creating-a-numpy-array-directly-from-array-interface/39377877#39377877">Creating a NumPy array directly from __array_interface__</a></p>
| 2 |
2016-09-14T22:28:54Z
|
[
"python",
"python-3.x",
"numpy"
] |
How to get a vertex list of differences between two graphs in igraph
| 39,500,358 |
<p>I'm trying to get a list of vertex that are present or missing from a graph 1 against another graph 2. I'm wondering if there any helper method in igraph to do it or if would be necessary to build a own. Thank you.</p>
| 1 |
2016-09-14T22:05:24Z
| 39,500,735 |
<p>I don't think there's a builtin method within graph that does what you want. However, it is straightforward to make your own.</p>
<p>I'm going to make the reasonable assumption here that the unique identifier of a vertex is the 'name' property that igraph encourages users to use. Essentially, you make two sets of the names of vertices in graph1 and the names of vertices in graph2 and compute their difference. Then you can search graph1 for the vertex that corresponds to that name and add it to a list to return:</p>
<pre><code>def find_diff(graph1, graph2):
"""
Returns list of vertices that are present in graph1 but missing in graph2
"""
set_v1 = set(graph1.vs['name']) # set of names of vertices in graph1
set_v2 = set(graph2.vs['name']) # set of names of vertices in graph2
diff = set_v1 - set_v2
result = []
for vname in diff:
result.append(graph1.vs.find(name=vname)) # find vertex that corresponds to name in graph1 and append it to list
return result
</code></pre>
<p>The above code is for clarity. You can actually do it in a faster and shorter way. Here's a one liner:</p>
<pre><code>def find_diff(graph1, graph2):
"""
Returns list of vertices that are present in graph1 but missing in graph2
"""
return [vx for vx in graph1.vs if vx['name'] not in graph2.vs['name']]
</code></pre>
| 0 |
2016-09-14T22:42:40Z
|
[
"python",
"igraph"
] |
Reducing database operation time Django/ Mysql
| 39,500,404 |
<p>So, the thing is I am having a moderately large list of emails ~ 250,000 entries.</p>
<p>I have another table containing list of invalid emails ~ 50,000 which i need to remove (mark inactive) from 1st table. For that I have ran a simple django function which is taking 3-4 seconds in each loop. The code is:</p>
<pre><code>def clean_list():
id = 9
while id<40000:
i = Invalid.objects.get(id=id)
y = i.email.strip()
f = IndiList.objects.get(email__contains=y)
f.active = False
f.save()
id +=1
</code></pre>
<p>What would be a better way to do it? Either a SQL query or a better piece of django code or some other way.</p>
<p>Help!</p>
| 0 |
2016-09-14T22:09:20Z
| 39,501,863 |
<p>There are a couple optimisations you might want to take a look at. Instead of looping over a get for each object try getting a values list:</p>
<p><code>queryset = Invalid.objects.filter(id__range=(9,40000))
queryset_list = queryset.values_list('email' flat=True)</code></p>
<p><a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values-list" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values-list</a></p>
<p>then looping over the values list and doing a .get() on the email. At the end you can also do:</p>
<p><code>f.active = False
f.save(update_fields=['active'])</code></p>
<p>Which will only update the boolean field.
<a href="https://docs.djangoproject.com/en/1.10/ref/models/instances/#updating-attributes-based-on-existing-fields" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/instances/#updating-attributes-based-on-existing-fields</a></p>
<p>Also try to find a way to .get() the object via id or some other field than string if possible.</p>
| 1 |
2016-09-15T01:17:49Z
|
[
"python",
"mysql",
"django",
"database"
] |
Reducing database operation time Django/ Mysql
| 39,500,404 |
<p>So, the thing is I am having a moderately large list of emails ~ 250,000 entries.</p>
<p>I have another table containing list of invalid emails ~ 50,000 which i need to remove (mark inactive) from 1st table. For that I have ran a simple django function which is taking 3-4 seconds in each loop. The code is:</p>
<pre><code>def clean_list():
id = 9
while id<40000:
i = Invalid.objects.get(id=id)
y = i.email.strip()
f = IndiList.objects.get(email__contains=y)
f.active = False
f.save()
id +=1
</code></pre>
<p>What would be a better way to do it? Either a SQL query or a better piece of django code or some other way.</p>
<p>Help!</p>
| 0 |
2016-09-14T22:09:20Z
| 39,502,431 |
<p>Untested:</p>
<pre><code>IndiList.objects.filter(email__in=Invalid.objects.only('email').all()).update(active=False)
</code></pre>
<p>I am not sure if Django is smart enough to build a subquery from that, if not, then this should do:</p>
<pre><code>IndiList.objects.filter(email__in=Invalid.objects.all().values_list('email', flat=True)).update(active=False)
</code></pre>
<p>The problem with the second approach is that it will generate 2 queries instead of one, and inject 50,000 ids into the second sql query string, so I would much rather just use raw sql at this point:</p>
<pre><code>from django.db import connection
cursor = connection.cursor()
cursor.execute = 'UPDATE indilist SET active=false WHERE email IN (SELECT email FROM invalid)'
</code></pre>
| 1 |
2016-09-15T02:50:27Z
|
[
"python",
"mysql",
"django",
"database"
] |
Reducing database operation time Django/ Mysql
| 39,500,404 |
<p>So, the thing is I am having a moderately large list of emails ~ 250,000 entries.</p>
<p>I have another table containing list of invalid emails ~ 50,000 which i need to remove (mark inactive) from 1st table. For that I have ran a simple django function which is taking 3-4 seconds in each loop. The code is:</p>
<pre><code>def clean_list():
id = 9
while id<40000:
i = Invalid.objects.get(id=id)
y = i.email.strip()
f = IndiList.objects.get(email__contains=y)
f.active = False
f.save()
id +=1
</code></pre>
<p>What would be a better way to do it? Either a SQL query or a better piece of django code or some other way.</p>
<p>Help!</p>
| 0 |
2016-09-14T22:09:20Z
| 39,507,823 |
<p>After a few iterations, i used this function which was more than <strong>1000 times faster.</strong></p>
<pre><code>def clean_list3():
pp = Invalid.objects.filter(id__gte=9)
listd = [oo.email.strip() for oo in pp]
for e in IndiList.objects.all():
if e.email.strip() in listd:
e.active=False
e.save()
print(e.id)
</code></pre>
<p>The trick is simple, instead of hitting database every time, I saved the 250,000 objects in a queryset in memory. and also the list of emails from invalid list in memory. </p>
<p>And then i had to hit database only when we found matching emails so as to save it as inactive.</p>
| 0 |
2016-09-15T09:41:02Z
|
[
"python",
"mysql",
"django",
"database"
] |
Report number of assertions in pyTest
| 39,500,416 |
<p>I am using <code>pytest</code> for writing some tests at integration level. I would like to be able to also report the number of assertions done on each test case. By default, <code>pytest</code> will only report the number of test cases which have passed and failed.</p>
| 0 |
2016-09-14T22:10:35Z
| 39,559,306 |
<p>On assertion further execution of test is aborted. So there will always be 1 assertion per test.</p>
<p>To achieve what you want you will have to write your own wrapper over assertion to keep track. At the end of the test check if count is >0 then raise assertion.
The count can be reset to zero either the <code>setup</code> or at <code>teardown</code> of test.</p>
| 0 |
2016-09-18T15:24:12Z
|
[
"python",
"integration-testing",
"py.test"
] |
Opening Pycharm from terminal with the current path
| 39,500,438 |
<p>If you give in the command "atom ." in the terminal, the Atom editor opens the current folder and I am ready to code.</p>
<p>I am trying to achieve the same with Pycharm using Ubuntu: get the current directory and open it with Pycharm as a project.</p>
<p>Is there way to achieve this by setting a bash alias?</p>
| 1 |
2016-09-14T22:12:25Z
| 39,500,482 |
<p>This works for me:</p>
<pre><code>alias atom_pycharm='~/pycharm/bin/pycharm.sh .'
</code></pre>
<p>Maybe you installed it to a different path, though - <code>locate</code> your <code>pycharm.sh</code> file and modify accordingly. </p>
<p>You have the usual bash tricks: if you want to run in the background, append an <code>&</code>, redirect stdout/stderr where you want etc.</p>
| 0 |
2016-09-14T22:17:24Z
|
[
"python",
"bash",
"command-line",
"pycharm"
] |
Opening Pycharm from terminal with the current path
| 39,500,438 |
<p>If you give in the command "atom ." in the terminal, the Atom editor opens the current folder and I am ready to code.</p>
<p>I am trying to achieve the same with Pycharm using Ubuntu: get the current directory and open it with Pycharm as a project.</p>
<p>Is there way to achieve this by setting a bash alias?</p>
| 1 |
2016-09-14T22:12:25Z
| 39,500,506 |
<p>PyCharm can be launched using the <code>charm</code> command line tool (which can be installed while getting started with PyCharm the first time).</p>
<p><code>charm .</code></p>
| 3 |
2016-09-14T22:18:27Z
|
[
"python",
"bash",
"command-line",
"pycharm"
] |
How to access grand childs of a node using XPath in Python Selenium?
| 39,500,465 |
<p>I am preparing a web-scrapping script which supposed to find list of attorneys in an area through a business directory web-site. I use chrome driver to fill out search keywords and the area values. </p>
<p>Since some of the hits don't have phone number, I would like to iterate through list of DIVs corresponding to search results and then check if the it has the phone number as a grand grand child and if yes then I get the phone number too otherwise I leave that field blank. </p>
<p>I have come up with two ways to do it as per below code. </p>
<pre><code>import time
import json as js
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
url = 'http://www.yellowpages.com/search?search_terms=Divorce+Attorneys&geo_location_terms=sun+diego'
RsultsList = []
driver = webdriver.Chrome()
driver.get(url)
ThereIsNext = True
while ThereIsNext:
# find ads.
nAddResults = len( driver.find_elements_by_xpath("//div[@class='result flash-ad']"))
#print 'add size = %d' % nAddResults
for i in range(nAddResults):
phone1 = driver.find_elements_by_xpath("//div[@class='result flash-ad']/div[1]/div[1]/div[2]/div[1]/ul[1]/li[1]")[i].text
BusinessName1 = driver.find_elements_by_xpath("//div[@class='result flash-ad']//a[@class='business-name']")[i].text
elem = driver.find_elements_by_xpath("//div[@class='result flash-ad']")
phone2 = elem.find_element_by_xpath("/div[1]/div[1]/div[2]/div[1]/ul[1]/li[1]")[i].text
BusinessName2 = elem.find_element_by_xpath("//a[@class='business-name']")
</code></pre>
<p>The first one is prone to error as records with no phone no. do NOT necessary show up at the end. So I come up with the second way. However, I get the below error message if try the second.</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\XXXX\documents\visual studio 2015\Projects\PythonApplication3\
PythonApplication3\AtorneyList.py", line 23, in <module>
phone2 = elem.find_element_by_xpath("/div[1]/div[1]/div[2]/div[1]/ul[1]/li[1
]").text
AttributeError: 'list' object has no attribute 'find_element_by_xpath'
Press any key to continue . . .
</code></pre>
<p>Please let me know what I am missing. I have checked <a href="http://stackoverflow.com/questions/9548523/how-do-i-find-node-and-its-child-nodes-using-selenium-with-python?s=1%7C1.1269">this</a> and <a href="http://stackoverflow.com/questions/9548523/how-do-i-find-node-and-its-child-nodes-using-selenium-with-python/9548919?s=2%7C0.1580#9548919">that</a> already and couldn't understand.</p>
<p>Much appreciate it.</p>
<p>Thanks</p>
| 0 |
2016-09-14T22:15:25Z
| 39,500,996 |
<p>Actually <code>find_elements()</code> returns either list of <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" rel="nofollow"><code>WebElement</code></a> or empty list. You're storing this result into a list variable name <code>elem</code>.</p>
<blockquote>
<p>AttributeError: 'list' object has no attribute 'find_element_by_xpath'</p>
</blockquote>
<p>This occurs because you're going to find nested <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" rel="nofollow"><code>WebElement</code></a> on <code>elem</code> list that's why <strong>you're calling as <code>elem.find_element_by_xpath()</code> which is absolutely wrong.</strong></p>
<p>Actually <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.find_element" rel="nofollow"><code>find_element()</code></a> or <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.find_elements" rel="nofollow"><code>find_elements</code></a> is used to search the element on the <strong>page context</strong> or the <strong>context of the <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" rel="nofollow"><code>WebElement</code></a></strong> instead of <code>list</code>. </p>
<p>So you should try to find list of <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" rel="nofollow"><code>WebElement</code></a> from <code>driver</code> means page context and then iterate to find further nested <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" rel="nofollow"><code>WebElement</code></a> using this element context as below :-</p>
<pre><code>elems = driver.find_elements_by_xpath("//div[@class='result flash-ad']")
for elem in elems:
phone2 = elem.find_element_by_xpath(".//div[1]/div[1]/div[2]/div[1]/ul[1]/li[1]").text
BusinessName2 = elem.find_element_by_xpath(".//a[@class='business-name']").text
</code></pre>
| 1 |
2016-09-14T23:13:36Z
|
[
"python",
"selenium",
"xpath",
"web-scraping"
] |
Django Migration Process for Elasticbeanstalk / Multiple Databases
| 39,500,513 |
<p>I am developing a small web application using Django and Elasticbeanstalk.
I created a EB application with two environments (staging and production), created a RDS instance and assigned it to my EB environments. </p>
<p>For development I use a local database, because deploying to AWS takes quite some time.</p>
<p>However, I am having troubles with the migrations. Because I develop and test locally every couple of minutes, I tend to have different migrations locally and on the two environments.</p>
<p>So once I deploy the current version of the app to a certain environment, the "manage.py migrate" fails most of the times because tables already exist or do not exist even though they should (because another environment already created the tables).</p>
<p>So I was wondering how to handle the migration process when using multiple environments for development, staging and production with some common and some exclusive database instances that might not reflect the same structure all the time?</p>
<p>Should I exclude the migration files from the code repository and the eb deployment and run makemigrations & migrate after every deployment? Should I not run migrations automatically using the .ebextensions and apply all the migrations manually through one of the instances?</p>
<p>What's the recommended way of using the same Django application with different database instances on different environments?</p>
| 1 |
2016-09-14T22:18:49Z
| 39,500,763 |
<p>Seems that you might have deleted the table or migrations at some point of time.</p>
<p>When you run makemigrations, django create migratins and when you run migrate, it creates database whichever is specified in settings file.</p>
<p>One thing is if you keep on creating migrations and do not run it in a particular database, it will be absolutely fine. Whenever you switch to databsse and run migrations, it will handle it as every database will store the point upto which migrations have been run until now in django-migrations table and will start running next migrations only.</p>
<p>To solve your problem, you can delete all databases and migration files and start afresh as you are perhaps testing right now. Things will go fine untill you delete a migration or a database in any of the server.</p>
<p>If you have precious data, you should get into migration files and tables to analyse and manage things.</p>
| 1 |
2016-09-14T22:45:44Z
|
[
"python",
"django",
"amazon-web-services",
"elastic-beanstalk",
"django-migrations"
] |
Name "userInput" cannot be defined
| 39,500,567 |
<p>i'm practicing some Python and i'm having some trouble trying to compare userInput would selected word in a hangman game. </p>
<pre><code># User guess input (single char)
# Exception handling to limit input to letters between a-z
while True:
userInput = str(input('Please guess a letter:'))
if len(userInput) == 1:
if not re.match("^[a-z]*$", userInput):
print("Error! Only letters a-z allowed!")
continue
break
else:
print("Error! Please input a single letter!")
continue
# Comparing array with input
for i in range(len(selWord)):
if(userInput == selWord[i]):
</code></pre>
<p>The problem lies in the in the last line:</p>
<pre><code> if(userInput == selWord[i]):
</code></pre>
<p>It states that "The name 'userInput' is not defined." however when I try to print outside the initial while loop, it works fine. </p>
| 1 |
2016-09-14T22:25:09Z
| 39,501,373 |
<blockquote>
<p>set userInput = None above while loop</p>
</blockquote>
<p>This was the solution, thank you everyone!</p>
| 1 |
2016-09-15T00:04:23Z
|
[
"python",
"python-3.x"
] |
Sparse matrix slicing using list of int
| 39,500,649 |
<p>I'm writing a machine learning algorithm on huge & sparse data (my matrix is of shape (347, 5 416 812 801) but very sparse, only 0.13% of the data is non zero. </p>
<p>My sparse matrix's size is 105 000 bytes (<1Mbytes) and is of <code>csr</code> type.</p>
<p>I'm trying to separate train/test sets by choosing a list of examples indices for each.
So I want to split my dataset in two using :</p>
<pre><code>training_set = matrix[train_indices]
</code></pre>
<p>of shape <code>(len(training_indices), 5 416 812 801)</code>, still sparse</p>
<pre><code>testing_set = matrix[test_indices]
</code></pre>
<p>of shape <code>(347-len(training_indices), 5 416 812 801)</code> also sparse</p>
<p>With <code>training_indices</code> and <code>testing_indices</code> two <code>list</code> of <code>int</code></p>
<p>But <code>training_set = matrix[train_indices]</code> seems to fail and return a <code>Segmentation fault (core dumped)</code></p>
<p>It might not be a problem of memory, as I'm running this code on a server with 64Gbytes of RAM.</p>
<p>Any clue on what could be the cause ?</p>
| 1 |
2016-09-14T22:33:52Z
| 39,500,986 |
<p>I think I've recreated the <code>csr</code> row indexing with:</p>
<pre><code>def extractor(indices, N):
indptr=np.arange(len(indices)+1)
data=np.ones(len(indices))
shape=(len(indices),N)
return sparse.csr_matrix((data,indices,indptr), shape=shape)
</code></pre>
<p>Testing on a <code>csr</code> I had hanging around:</p>
<pre><code>In [185]: M
Out[185]:
<30x40 sparse matrix of type '<class 'numpy.float64'>'
with 76 stored elements in Compressed Sparse Row format>
In [186]: indices=np.r_[0:20]
In [187]: M[indices,:]
Out[187]:
<20x40 sparse matrix of type '<class 'numpy.float64'>'
with 57 stored elements in Compressed Sparse Row format>
In [188]: extractor(indices, M.shape[0])*M
Out[188]:
<20x40 sparse matrix of type '<class 'numpy.float64'>'
with 57 stored elements in Compressed Sparse Row format>
</code></pre>
<p>As with a number of other <code>csr</code> methods, it uses matrix multiplication to produce the final value. In this case with a sparse matrix with 1 in selected rows. Time is actually a bit better.</p>
<pre><code>In [189]: timeit M[indices,:]
1000 loops, best of 3: 515 µs per loop
In [190]: timeit extractor(indices, M.shape[0])*M
1000 loops, best of 3: 399 µs per loop
</code></pre>
<p>In your case the extractor matrix is (len(training_indices),347) in shape, with only <code>len(training_indices)</code> values. So it is not big.</p>
<p>But if the <code>matrix</code> is so large (or at least the 2nd dimension so big) that it produces some error in the matrix multiplication routines, it could give rise to segmentation fault without python/numpy trapping it.</p>
<p>Does <code>matrix.sum(axis=1)</code> work. That too uses a matrix multiplication, though with a dense matrix of 1s. Or <code>sparse.eye(347)*M</code>, a similar size matrix multiplication?</p>
| 1 |
2016-09-14T23:12:00Z
|
[
"python",
"scipy",
"segmentation-fault",
"sparse-matrix"
] |
I'm having trouble trying to read the numbers (0 - 10) into a list in Python 3 using CSV file and in a column format.
| 39,500,668 |
<p>I first wrote the numbers in a column into a CSV file but having trouble with the reading part. I want to make into one list and make sure that the numbers are converted into ints</p>
<pre><code>f = open('numbers.csv', 'r')
with f:
reader = csv.reader(f)
for column in reader:
print(column)
</code></pre>
<p>This is what I wrote for my code and here is my output but how do I make it into a list and convert the numbers into integers?</p>
<p>Column:</p>
<pre><code>['0']
['1']
['2']
['3']
['4']
['5']
['6']
['7']
['8']
['9']
['10']
</code></pre>
| 0 |
2016-09-14T22:35:47Z
| 39,500,704 |
<pre><code>numlist = list()
f = open('numbers.csv', 'r')
with f:
reader = csv.reader(f)
for column in reader:
numlist.append( int(column[0]) )
print( numlist )
</code></pre>
| 0 |
2016-09-14T22:39:05Z
|
[
"python",
"numbers"
] |
I'm having trouble trying to read the numbers (0 - 10) into a list in Python 3 using CSV file and in a column format.
| 39,500,668 |
<p>I first wrote the numbers in a column into a CSV file but having trouble with the reading part. I want to make into one list and make sure that the numbers are converted into ints</p>
<pre><code>f = open('numbers.csv', 'r')
with f:
reader = csv.reader(f)
for column in reader:
print(column)
</code></pre>
<p>This is what I wrote for my code and here is my output but how do I make it into a list and convert the numbers into integers?</p>
<p>Column:</p>
<pre><code>['0']
['1']
['2']
['3']
['4']
['5']
['6']
['7']
['8']
['9']
['10']
</code></pre>
| 0 |
2016-09-14T22:35:47Z
| 39,500,864 |
<p>You just need to iterate over each <code>row</code> in your <code>file</code>, cast the first <code>column</code> to <code>int</code> using <code>int()</code> and then add to a <code>list</code>. Here is compact version:</p>
<pre><code>with open('numbers.csv', 'r') as numbers_file:
reader = csv.reader(numbers_file)
int_list = [int(row[0]) for row in reader]
print int_list
</code></pre>
<p><strong>EDIT</strong>:</p>
<p>If you want a <code>column</code> list or <code>nested</code> list, just loop over both <code>columns</code> and <code>rows</code> for the <em>general</em> case:</p>
<pre><code>int_list = [[int(col) for col in row] for row in reader]
</code></pre>
<p>or in your <em>particular</em> case where you just want the <code>first/only</code> element of each row, just cast the <code>element</code> to a <code>list</code>:</p>
<pre><code>int_list = [[int(row[0])] for row in reader]
</code></pre>
| 0 |
2016-09-14T22:58:37Z
|
[
"python",
"numbers"
] |
Reduce dictionary of deque to single boolean
| 39,500,827 |
<p>I want d to evaluate to <code>True</code> iff all values in <code>d</code> are empty</p>
<pre><code>from collections import deque
d = {'a': deque([1,2,3]), 'b': deque([1,2,3]), 'c': deque([1,2,3])}
</code></pre>
<p>I've tried <code>reduce</code> but I'm clearly missing something important. </p>
<p>Thanks in advance! </p>
| 1 |
2016-09-14T22:54:59Z
| 39,504,138 |
<p>As Peter Wood kindly pointed out, <code>not any(d.values())</code> does the trick nicely. </p>
| 1 |
2016-09-15T06:10:40Z
|
[
"python",
"python-2.7"
] |
Find the indicies of common tuples in two list of tuples without loop in Python
| 39,500,876 |
<p>How can one find the indexes of the common tuples in two list of tuples?</p>
<pre><code>tuplelist1 = [("a","b"), ("c","d"), ("e","f"), ("g","h")]
tuplelist2 = [("c","d"),("e","f")]
</code></pre>
<p>So the indices in tuplelist1 that are common with tupplelist2 are indices 1 and 2.</p>
<p>Is there a way to figure this out without a loop? Is there a way to do this with sets or list comprehension, for instance?</p>
<p>Thanks!</p>
| -1 |
2016-09-14T22:59:37Z
| 39,500,933 |
<p>With a list comprehension, you could do</p>
<pre><code>indices_of_shared = [index for (index, pair) in enumerate(tuplelist1) if pair in tuplelist2]
</code></pre>
| 2 |
2016-09-14T23:04:56Z
|
[
"python",
"list",
"indexing",
"tuples",
"indices"
] |
Spell Checking a column in Python/Pandas/PyEnchant
| 39,500,899 |
<p>I'm trying to use Pyenchant to spell check each entry in a column called pets in a pandas dataframe called house.</p>
<pre><code>import enchant
dict = enchant.Dict("en_US")
for pets in house:
[pets] = dict.suggest([pets])[0]
</code></pre>
<p>When I run this code, I get an error about not passing bytestrings to Pyenchant. Not sure what to do. Full error text below:</p>
<blockquote>
<p>File "myfile", line 20, in
[pets] = dict.suggest([pets])[0]
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/enchant/<strong>init</strong>.py", line 662, in suggest
word = self._StringClass(word)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/enchant/utils.py", line 152, in <strong>new</strong>
raise Error("Don't pass bytestrings to pyenchant")
enchant.errors.Error: Don't pass bytestrings to pyenchant</p>
</blockquote>
<p>How can I fix this? Thanks.</p>
| 0 |
2016-09-14T23:02:07Z
| 39,502,018 |
<p>If your dataframe contains bytestrings, you will need to decode them before you pass them to <code>enchant</code>; you can do this with <code>.str.decode('utf-8')</code>. Then to apply your function, the cleanest way to approach this type of situation is usually to use <code>map</code> across your Series rather than iterating. (Also you shouldn't shadow the keyword <code>dict</code>):</p>
<pre><code>checker = enchant.Dict("en_US")
house = pd.Series([b'caat', b'dogg'])
#decode the bytestrings
house = house.str.decode('utf-8')
#map the spell checker
house.map(lambda x: checker.suggest(x)[0])
# Out[19]:
# 0 cat
# 1 dog
# dtype: object
</code></pre>
| 0 |
2016-09-15T01:43:58Z
|
[
"python",
"pandas",
"pyenchant"
] |
Initializing many objects in an elegant way
| 39,500,940 |
<p>I'm looking for a elegant way to initialize many objects.</p>
<p>Let's say that I have a <code>Utils</code> module, which has an interface to SVN, Git, Make and other stuff.</p>
<p>Currently, I'm doing it like this:</p>
<pre><code>from Utils.Config import Config, Properties
from Utils.Utils import PrettyPrint, SVN, Make, Bash, Git
class Build(object):
def __init__(self):
self.config = Config()
self.make = Make()
self.env = Properties()
self.svn = SVN()
self.git = Git()
self.bash = Bash()
self.pretty_print = PrettyPrint()
</code></pre>
<p>and.. well, it doesn't looks good. </p>
<p>Is there any way to do this in more elegant way? I suppose that it can be a design problem, but I have no idea how to solve this.</p>
<p>I was thinking about creation <code>Base class</code> which will init all of these classes inside the <code>Utils</code> module. What do you think?</p>
| 3 |
2016-09-14T23:05:58Z
| 39,501,272 |
<p>I wouldn't create a class and place it as a base, <em>that seems like overkill, too bulky of an approach</em>.</p>
<p>Instead, you could create an auxiliary, helper, function that takes <code>self</code> and <code>setattr</code> on it. An example of this with a couple of objects from <a href="https://docs.python.org/3/library/collections.html" rel="nofollow"><code>collections</code></a> would look like this:</p>
<pre><code>from collections import UserString, deque, UserDict
def construct(instance, classes = (UserString, deque, UserDict)):
for c in classes:
setattr(instance, c.__name__.lower(), c([]))
</code></pre>
<p>Your case also fits nicely since your objects don't have some initial value required, so you can generalize and treat them in the same way :-).</p>
<p>Now your sample class can just call <code>construct()</code> with the defaults in <code>__init__</code> and be done with:</p>
<pre><code>class Foo:
def __init__(self):
construct(self)
</code></pre>
<p>the <code>construct</code> function could of course be defined in <code>Utils</code> as required or, as a method in the class. </p>
| 3 |
2016-09-14T23:49:44Z
|
[
"python",
"python-3.x"
] |
Scrapy response have backslashes into element attributes
| 39,501,019 |
<p>I run the following code in a Scrapy Shell, to scrape data using a POST request:</p>
<pre><code>url = 'http://www.ldg.co.uk/wp-admin/admin-ajax.php'
data = {'action': 'wpp_property_overview_pagination',
'wpp_ajax_query[show_children]': 'true',
'wpp_ajax_query[disable_wrapper]': 'true',
'wpp_ajax_query[pagination]': 'off',
'wpp_ajax_query[per_page]': '10',
'wpp_ajax_query[query][property_category]': 'residential',
'wpp_ajax_query[query][listing_type]': 'rent',
'wpp_ajax_query[query][sort_by]': 'price_rent',
'wpp_ajax_query[query][sort_order]': 'ASC',
'wpp_ajax_query[query][pagi]': '0--10',
'wpp_ajax_query[sorter]': '',
'wpp_ajax_query[sort_by]': 'price_rent',
'wpp_ajax_query[sort_order]': 'ASC',
'wpp_ajax_query[template]': 'ajax',
'wpp_ajax_query[requested_page]': '2'}
request = FormRequest(url, formdata = data)
fetch(request)
</code></pre>
<p>I know that inside the response are elements with the class <code>"property-thumb"</code>, I've checked it by using Chrome Dev Tools, reading the response content. So, I try to scrape data using the XPath <code>//*[@class="property-thumb"]</code>, this XPath is right (I use a Chrome plugin to check it with the content loaded into the page), but it isn't right if I try to use it from the Scrapy Shell:</p>
<pre><code>In [10]: response.xpath('//*[@class="property-thumb"]')
Out[10]: []
</code></pre>
<p>I have noticed that <code>response.body</code> comes with a lot of backslashes, so I've figured out that the correct XPath should be <code>//*[@class=\'\\"property-thumb\\"\']</code>:</p>
<pre><code>In [11]: response.xpath('//*[@class=\'\\"property-thumb\\"\']')
Out[11]:
[<Selector xpath='//*[@class=\'\\"property-thumb\\"\']' data=u'<div class=\'\\"property-thumb\\"\'>\\n '>,
<Selector xpath='//*[@class=\'\\"property-thumb\\"\']' data=u'<div class=\'\\"property-thumb\\"\'>\\n '>,
<Selector xpath='//*[@class=\'\\"property-thumb\\"\']' data=u'<div class=\'\\"property-thumb\\"\'>\\n '>]
</code></pre>
<p>I think there is a problem with the way Scrapy manages strings from responses. Also, I think that those backslashes can generate more problems when scraping. Why do this happen? How can I solve it to use normal XPaths?</p>
| 1 |
2016-09-14T23:16:03Z
| 39,501,745 |
<p>There is a very simple solution, you get <a href="http://www.w3schools.com/json/" rel="nofollow"><em>json</em></a> back <em>not html</em>:</p>
<pre><code>url = 'http://www.ldg.co.uk/wp-admin/admin-ajax.php'
data = {'action': 'wpp_property_overview_pagination',
'wpp_ajax_query[show_children]': 'true',
'wpp_ajax_query[disable_wrapper]': 'true',
'wpp_ajax_query[pagination]': 'off',
'wpp_ajax_query[per_page]': '10',
'wpp_ajax_query[query][property_category]': 'residential',
'wpp_ajax_query[query][listing_type]': 'rent',
'wpp_ajax_query[query][sort_by]': 'price_rent',
'wpp_ajax_query[query][sort_order]': 'ASC',
'wpp_ajax_query[query][pagi]': '0--10',
'wpp_ajax_query[sorter]': '',
'wpp_ajax_query[sort_by]': 'price_rent',
'wpp_ajax_query[sort_order]': 'ASC',
'wpp_ajax_query[template]': 'ajax',
'wpp_ajax_query[requested_page]': '2'}
import requests
print(requests.post(url, data).json())
</code></pre>
<p>Which would give you:</p>
<pre><code>{u'display': u' <section class="property-card new-post">\n <div class="property-thumb">\n <a class="property-image" href="http://www.ldg.co.uk/residential/1-bedroom-property-for-rent-lisson-street-marylebone-london-101588004937/" title="Lisson Street, Marylebone, London">\n <img src="http://www.ldg.co.uk/wp-content/uploads/2016/08/IMG_4427_6_large.jpg" alt="Lisson Street, Marylebone, London thumbnail">\n\n </a>\n </div><!-- /.property-thumb -->\n\n <div class="property-content">\n <header class="property-title">\n <h2>\n <a href="http://www.ldg.co.uk/residential/1-bedroom-property-for-rent-lisson-street-marylebone-london-101588004937/">Lisson Street, Marylebone, London</a>\n </h2>\n </header>\n \n <span class="property-style-tenure"></span>\n <div class="property-details">\n\n \n <div class="property-price">\n <div class="property-style-tenure"><span></span></div>\xa3420<small>/pw</small>\n <span class="fees-link-wrapper">+ <a target="_blank" href="http://www.ldg.co.uk/residential/property-lettings/fees-and-charges/">fees</a></span>\n </div>\n \n \n <div class="property-features">\n <div class="property-feature">\n <div class="property-living_rooms">\n <span class="esf-icon esf-32 esf-icon-living_rooms"></span>\n 1 Reception </div>\n </div>\n \n <div class="property-feature">\n <div class="property-bedrooms">\n <span class="esf-icon esf-32 esf-icon-bedrooms"></span>\n 1 Bedroom </div>\n </div>\n \n <div class="property-feature">\n <div class="property-bathrooms">\n <span class="esf-icon esf-32 esf-icon-bathrooms"></span>\n 1 Bathroom </div>\n </div>\n </div><!-- /.property-features -->\n\n\n <div class="property-media">\n <a href="http://www.ldg.co.uk/wp-content/uploads/2016/09/FLP_4427_1_large-743x1024.png" target="_blank" class="alternative-link fancybox " rel="fancybox-group">View Floor Plan</a>\n \n <span class="separator">|</span>\n <a href="http://media2.jupix.co.uk/v3/clients/1588/properties/4427/MED_4427_6235.pdf" target="_blank" class="alternative-link">Download Brochure</a>\n </div><!-- /.property-media -->\n\n <div class="property-read-more">\n <a href="http://www.ldg.co.uk/residential/1-bedroom-property-for-rent-lisson-street-marylebone-london-101588004937/" class="btn btn-sm lighter-dark-primary-color">\n View Details\n </a>\n </div>\n </div><!-- /.property-details -->\n </div><!-- /.property-content -->\n </section>\n <section class="property-card new-post">\n <div class="property-thumb">\n <a class="property-image" href="http://www.ldg.co.uk/residential/1-bedroom-property-for-rent-riding-house-street-fitzrovia-london-101588003963/" title="Riding House Street, Fitzrovia, London">\n <img src="http://www.ldg.co.uk/wp-content/uploads/2016/09/IMG_3453_10_large.jpg" alt="Riding House Street, Fitzrovia, London thumbnail">\n\n </a>\n </div><!-- /.property-thumb -->\n\n <div class="property-content">\n <header class="property-title">\n <h2>\n <a href="http://www.ldg.co.uk/residential/1-bedroom-property-for-rent-riding-house-street-fitzrovia-london-101588003963/">Riding House Street, Fitzrovia, London</a>\n </h2>\n </header>\n \n <span class="property-style-tenure"></span>\n <div class="property-details">\n\n \n <div class="property-price">\n <div class="property-style-tenure"><span></span></div>\xa3425<small>/pw</small>\n <span class="fees-link-wrapper">+ <a target="_blank" href="http://www.ldg.co.uk/residential/property-lettings/fees-and-charges/">fees</a></span>\n </div>\n \n \n <div class="property-features">\n <div class="property-feature">\n <div class="property-living_rooms">\n <span class="esf-icon esf-32 esf-icon-living_rooms"></span>\n 1 Reception </div>\n </div>\n \n <div class="property-feature">\n <div class="property-bedrooms">\n <span class="esf-icon esf-32 esf-icon-bedrooms"></span>\n 1 Bedroom </div>\n </div>\n \n <div class="property-feature">\n <div class="property-bathrooms">\n <span class="esf-icon esf-32 esf-icon-bathrooms"></span>\n 1 Bathroom </div>\n </div>\n </div><!-- /.property-features -->\n\n\n <div class="property-media">\n <a href="http://www.ldg.co.uk/wp-content/uploads/2016/09/FLP_3453_1_large-724x1024.png" target="_blank" class="alternative-link fancybox " rel="fancybox-group">View Floor Plan</a>\n \n <span class="separator">|</span>\n <a href="http://media2.jupix.co.uk/v3/clients/1588/properties/3453/MED_3453_6286.pdf" target="_blank" class="alternative-link">Download Brochure</a>\n </div><!-- /.property-media -->\n\n <div class="property-read-more">\n <a href="http://www.ldg.co.uk/residential/1-bedroom-property-for-rent-riding-house-street-fitzrovia-london-101588003963/" class="btn btn-sm lighter-dark-primary-color">\n View Details\n </a>\n </div>\n </div><!-- /.property-details -->\n </div><!-- /.property-content -->\n </section>\n <section class="property-card new-post">\n <div class="property-thumb">\n <a class="property-image" href="http://www.ldg.co.uk/residential/1-bedroom-property-for-rent-grays-inn-road-bloomsbury-london-101588004443/" title="Grays Inn Road, Bloomsbury, London">\n <img src="http://www.ldg.co.uk/wp-content/uploads/2016/08/IMG_3933_1_large.jpg" alt="Grays Inn Road, Bloomsbury, London thumbnail">\n\n </a>\n </div><!-- /.property-thumb -->\n\n <div class="property-content">\n <header class="property-title">\n <h2>\n <a href="http://www.ldg.co.uk/residential/1-bedroom-property-for-rent-grays-inn-road-bloomsbury-london-101588004443/">Grays Inn Road, Bloomsbury, London</a>\n </h2>\n </header>\n \n <span class="property-style-tenure"></span>\n <div class="property-details">\n\n \n <div class="property-price">\n <div class="property-style-tenure"><span></span></div>\xa3430<small>/pw</small>\n <span class="fees-link-wrapper">+ <a target="_blank" href="http://www.ldg.co.uk/residential/property-lettings/fees-and-charges/">fees</a></span>\n </div>\n \n \n <div class="property-features">\n <div class="property-feature">\n <div class="property-living_rooms">\n <span class="esf-icon esf-32 esf-icon-living_rooms"></span>\n 1 Reception </div>\n </div>\n \n <div class="property-feature">\n <div class="property-bedrooms">\n <span class="esf-icon esf-32 esf-icon-bedrooms"></span>\n 1 Bedroom </div>\n </div>\n \n <div class="property-feature">\n <div class="property-bathrooms">\n <span class="esf-icon esf-32 esf-icon-bathrooms"></span>\n 1 Bathroom </div>\n </div>\n </div><!-- /.property-features -->\n\n\n <div class="property-media">\n \n <a href="http://media2.jupix.co.uk/v3/clients/1588/properties/3933/MED_3933_5539.pdf" target="_blank" class="alternative-link">Download Brochure</a>\n </div><!-- /.property-media -->\n\n <div class="property-read-more">\n <a href="http://www.ldg.co.uk/residential/1-bedroom-property-for-rent-grays-inn-road-bloomsbury-london-101588004443/" class="btn btn-sm lighter-dark-primary-color">\n View Details\n </a>\n </div>\n </div><!-- /.property-details -->\n </div><!-- /.property-content -->\n </section>\n ', u'wpp_query': {u'starting_row': 10, u'pagination': u'off', u'show_layout_toggle': False, u'current_page': u'2', u'requested_page': u'2', u'show_children': u'true', u'sortable_attrs': {u'menu_order': u'Default'}, u'sort_by': u'price_rent', u'sort_order': u'ASC', u'ajax_call': True, u'template': u'ajax', u'per_page': u'10', u'query': {u'sort_by': u'price_rent', u'pagi': u'10--10', u'listing_type': u'rent', u'sort_order': u'ASC', u'property_category': u'residential'}, u'sorter': u'', u'disable_wrapper': u'true', u'properties': {u'total': 60, u'results': [u'793240', u'836654', u'793035', u'793044', u'793078', u'793307', u'792965', u'793054', u'792811', u'793344']}`}}
</code></pre>
<p>The extra backslashes are there to escape the quotes etc.. Once you <code>json.loads()</code> the content the extra slashes so in your case call loads on the body:</p>
<pre><code> import json
request = FormRequest(url, formdata = data)
js = json.loads(fetch(request).body)
</code></pre>
<p>And to just get the html you would use the key <code>html = js["display"]</code>.</p>
| 1 |
2016-09-15T00:59:18Z
|
[
"python",
"python-2.7",
"xpath",
"web-scraping",
"scrapy"
] |
Regex interpretaion in Django tutorial
| 39,501,066 |
<p>despite being familiar with the basics of regex, the tutorial for <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial03/#writing-more-views" rel="nofollow">Django 1.10</a> does not go into much detail about how some regex generates dynamic links.
I am looking at this specific snippet under the polls/urls.py: </p>
<pre><code>url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
</code></pre>
<p>Could someone go into detail about how that regex is interpreted? The quantifiers at the start of the capture group, <code>(?P<question_id></code> do not make sense to me. Specifically, how does Django know that <code><question_id></code> is a foreign key?</p>
| 1 |
2016-09-14T23:21:50Z
| 39,501,099 |
<p>The <code>(?P<<em>name</em>><em>...</em>)</code> means that this regex has a <em>named capture group</em>, unlike the <code>(...)</code> syntax, which is a numbered capture group. Django takes the named parameters and passes them to your view.</p>
| 0 |
2016-09-14T23:28:20Z
|
[
"python",
"regex",
"django"
] |
Regex interpretaion in Django tutorial
| 39,501,066 |
<p>despite being familiar with the basics of regex, the tutorial for <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial03/#writing-more-views" rel="nofollow">Django 1.10</a> does not go into much detail about how some regex generates dynamic links.
I am looking at this specific snippet under the polls/urls.py: </p>
<pre><code>url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
</code></pre>
<p>Could someone go into detail about how that regex is interpreted? The quantifiers at the start of the capture group, <code>(?P<question_id></code> do not make sense to me. Specifically, how does Django know that <code><question_id></code> is a foreign key?</p>
| 1 |
2016-09-14T23:21:50Z
| 39,501,107 |
<p><strong><code>^(?P<question_id>[0-9]+)/$</code></strong></p>
<pre><code>^ assert position at start of the string
(?P<question_id>[0-9]+) Named capturing group "question_id"
[0-9]+ match a single character present in the list below:
Quantifier: + Between one and unlimited times, as many times as possible,
giving back as needed [greedy]
0-9 a single character in the range between 0 and 9
$ assert position at end of the string
</code></pre>
<p>Demo and full explanation: <a href="https://regex101.com/r/zV3rZ1/1" rel="nofollow">https://regex101.com/r/zV3rZ1/1</a></p>
| 0 |
2016-09-14T23:29:19Z
|
[
"python",
"regex",
"django"
] |
Regex interpretaion in Django tutorial
| 39,501,066 |
<p>despite being familiar with the basics of regex, the tutorial for <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial03/#writing-more-views" rel="nofollow">Django 1.10</a> does not go into much detail about how some regex generates dynamic links.
I am looking at this specific snippet under the polls/urls.py: </p>
<pre><code>url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
</code></pre>
<p>Could someone go into detail about how that regex is interpreted? The quantifiers at the start of the capture group, <code>(?P<question_id></code> do not make sense to me. Specifically, how does Django know that <code><question_id></code> is a foreign key?</p>
| 1 |
2016-09-14T23:21:50Z
| 39,501,151 |
<p>The <code>(?P<question_id>.*)</code> Says everything captured by the regex inside the parenthesis will be in a named group called question_id. It can be directly addressed. So the regex doesn't know it is a foreign key or anything of the sort, just that there is a group named <code>question_id</code>. The parenthesis isn't really matched in the incoming string.</p>
<p>The <code>[0-9]+</code> matches and numeric string 1 or more digits long. </p>
<p><code>^</code> is the start of the string. <code>$</code> is the end of the string. <code>^, $, (?P<question_id>, and )</code> are somewhat meta and aren't impacted by the string so much as the string's position and how the regex extracted groups will be referenced. </p>
<p>The captured group is passed to the view (detail in this case) as a keyword argument and it's up to the view to make use of it in a meaningful way. </p>
| 2 |
2016-09-14T23:34:04Z
|
[
"python",
"regex",
"django"
] |
Regex interpretaion in Django tutorial
| 39,501,066 |
<p>despite being familiar with the basics of regex, the tutorial for <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial03/#writing-more-views" rel="nofollow">Django 1.10</a> does not go into much detail about how some regex generates dynamic links.
I am looking at this specific snippet under the polls/urls.py: </p>
<pre><code>url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
</code></pre>
<p>Could someone go into detail about how that regex is interpreted? The quantifiers at the start of the capture group, <code>(?P<question_id></code> do not make sense to me. Specifically, how does Django know that <code><question_id></code> is a foreign key?</p>
| 1 |
2016-09-14T23:21:50Z
| 39,501,219 |
<p>It captures [0-9]+ under the name question_id. Then it passes the captured number to the view function as a parameter. You can try it with re functions. It is not Django specific.</p>
<pre><code>>>> import re
>>> re.match(r'^(?P<question_id>[0-9]+)/$', '122/').groupdict()
{'question_id': '122'}
</code></pre>
| 0 |
2016-09-14T23:43:40Z
|
[
"python",
"regex",
"django"
] |
ImportError: No module named downsample
| 39,501,152 |
<p>I am using Theano. The OS is Ubuntu. The Theano is UPTODATE. I am wondering why I am getting by <code>from theano.tensor.signal.downsample import max_pool_2d</code> command.</p>
<p><code>ImportError: No module named downsample</code>.</p>
| 2 |
2016-09-14T23:34:17Z
| 39,501,251 |
<p>The <code>downsample</code> module has been moved to <code>pool</code>, so try declaring it as:</p>
<pre><code>from theano.tensor.signal.pool import pool_2d
</code></pre>
<p>After changing delete your theano cache with the command:</p>
<pre><code>theano-cache purge
</code></pre>
| 1 |
2016-09-14T23:47:05Z
|
[
"python",
"module",
"theano"
] |
Python Project Euler digit fifth powers
| 39,501,154 |
<p><a href="https://projecteuler.net/problem=30" rel="nofollow">Here is the problem</a>:</p>
<blockquote>
<p>Surprisingly there are only three numbers that can be written as the
sum of fourth powers of their digits:</p>
<p>1634 = 1^4 + 6^4 + 3^4 + 4^4<br>
8208 = 8^4 + 2^4 + 0^4 + 8^4<br>
9474 = 9^4 + 4^4 + 7^4 + 4^4 </p>
<p>As 1 = 1^4 is not a sum it is not included.</p>
<p>The sum of these numbers is 1634 + 8208 + 9474 = 19316.</p>
<p>Find the sum of all the numbers that can be written as the sum of
fifth powers of their digits.</p>
</blockquote>
<p>And here is my code:</p>
<pre><code>summ = 0
digit_sum = 0
i = 0
while i < 1000000:
j = list(str(i))
for x in j:
digit = int(x) ** 5
digit_sum += digit
if digit_sum == i:
summ += i
print(i)
else:
digit_sum = 0
i += 1
print(summ)
</code></pre>
<p>Can anyone find out that why I miss a value 4151 which should be one of the correct answer? </p>
| 0 |
2016-09-14T23:35:16Z
| 39,501,262 |
<p>The problem in your code is you forgot to reset the <code>digit_sum</code> when you got an answer.
Put <code>digit_sum = 0</code> before <code>j = list(str(i))</code>. You also start with <code>i = 0</code>. I suggest to start with <code>i = 10</code> since the first 2 digit number is 10.</p>
<p>use this:</p>
<pre><code>[i for i in range(10, 1000000) if i == sum(int(d) ** 5 for d in str(i))]
</code></pre>
<p>equivalent with:</p>
<pre><code>[4150, 4151, 54748, 92727, 93084, 194979]
</code></pre>
<p>using sum:</p>
<pre><code>sum(i for i in range(10, 1000000) if i == sum(int(d) ** 5 for d in str(i)))
</code></pre>
<p>equivalent with:</p>
<pre><code>443839
</code></pre>
| 0 |
2016-09-14T23:48:23Z
|
[
"python",
"loops",
"sum",
"project",
"digit"
] |
Python Project Euler digit fifth powers
| 39,501,154 |
<p><a href="https://projecteuler.net/problem=30" rel="nofollow">Here is the problem</a>:</p>
<blockquote>
<p>Surprisingly there are only three numbers that can be written as the
sum of fourth powers of their digits:</p>
<p>1634 = 1^4 + 6^4 + 3^4 + 4^4<br>
8208 = 8^4 + 2^4 + 0^4 + 8^4<br>
9474 = 9^4 + 4^4 + 7^4 + 4^4 </p>
<p>As 1 = 1^4 is not a sum it is not included.</p>
<p>The sum of these numbers is 1634 + 8208 + 9474 = 19316.</p>
<p>Find the sum of all the numbers that can be written as the sum of
fifth powers of their digits.</p>
</blockquote>
<p>And here is my code:</p>
<pre><code>summ = 0
digit_sum = 0
i = 0
while i < 1000000:
j = list(str(i))
for x in j:
digit = int(x) ** 5
digit_sum += digit
if digit_sum == i:
summ += i
print(i)
else:
digit_sum = 0
i += 1
print(summ)
</code></pre>
<p>Can anyone find out that why I miss a value 4151 which should be one of the correct answer? </p>
| 0 |
2016-09-14T23:35:16Z
| 39,501,312 |
<p>4150 is also in solutions. The digit_sum is not set to 0 before 4151 step. You should set digit_sum = 0 in each step.</p>
<pre><code>summ = 0
digit_sum = 0
i = 0
while i < 1000000:
digit_sum = 0 # should be set in each step
j = list(str(i))
for x in j:
digit = int(x) ** 5
digit_sum += digit
if digit_sum == i:
summ += i
print(i)
i += 1
print(summ)
</code></pre>
| 0 |
2016-09-14T23:55:50Z
|
[
"python",
"loops",
"sum",
"project",
"digit"
] |
Python Project Euler digit fifth powers
| 39,501,154 |
<p><a href="https://projecteuler.net/problem=30" rel="nofollow">Here is the problem</a>:</p>
<blockquote>
<p>Surprisingly there are only three numbers that can be written as the
sum of fourth powers of their digits:</p>
<p>1634 = 1^4 + 6^4 + 3^4 + 4^4<br>
8208 = 8^4 + 2^4 + 0^4 + 8^4<br>
9474 = 9^4 + 4^4 + 7^4 + 4^4 </p>
<p>As 1 = 1^4 is not a sum it is not included.</p>
<p>The sum of these numbers is 1634 + 8208 + 9474 = 19316.</p>
<p>Find the sum of all the numbers that can be written as the sum of
fifth powers of their digits.</p>
</blockquote>
<p>And here is my code:</p>
<pre><code>summ = 0
digit_sum = 0
i = 0
while i < 1000000:
j = list(str(i))
for x in j:
digit = int(x) ** 5
digit_sum += digit
if digit_sum == i:
summ += i
print(i)
else:
digit_sum = 0
i += 1
print(summ)
</code></pre>
<p>Can anyone find out that why I miss a value 4151 which should be one of the correct answer? </p>
| 0 |
2016-09-14T23:35:16Z
| 39,501,315 |
<p>The answer to your question is that you don't reset <code>digit_sum</code> every time, only when <code>digit_sum != i</code>. If you remove the <code>else</code> statement, it should work correctly.</p>
<pre><code>if digit_sum == i:
summ += i
print(i)
digit_sum = 0
i += 1
</code></pre>
| -1 |
2016-09-14T23:55:57Z
|
[
"python",
"loops",
"sum",
"project",
"digit"
] |
Efficient Python Pandas Stock Beta Calculation on Many Dataframes
| 39,501,277 |
<p>I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta (<a href="http://stackoverflow.com/questions/34802972/python-pandas-calculate-rolling-stock-beta-using-rolling-apply-to-groupby-object">Python pandas calculate rolling stock beta using rolling apply to groupby object in vectorized fashion</a>) however when used in my code below takes over 2.5 hours! Considering I can run the exact same calculations in SQL tables in under 3 minutes this is too slow.</p>
<p>How can I improve the performance of my below code to match that of SQL? I understand Pandas/python has that capability. My current method loops over each row which I know slows performance but I am unaware of any aggregate way to perform a rolling window beta calculation on a dataframe.</p>
<p>Note: the first 2 steps of loading the CSVs into individual dataframes and calculating daily returns only takes ~20seconds. All my CSV dataframes are stored in the dictionary called 'FilesLoaded' with names such as 'XAO'.</p>
<p>Your help would be much appreciated!
Thank you :)</p>
<pre><code>import pandas as pd, numpy as np
import datetime
import ntpath
pd.set_option('precision',10) #Set the Decimal Point precision to DISPLAY
start_time=datetime.datetime.now()
MarketIndex = 'XAO'
period = 250
MinBetaPeriod = period
# ***********************************************************************************************
# CALC RETURNS
# ***********************************************************************************************
for File in FilesLoaded:
FilesLoaded[File]['Return'] = FilesLoaded[File]['Close'].pct_change()
# ***********************************************************************************************
# CALC BETA
# ***********************************************************************************************
def calc_beta(df):
np_array = df.values
m = np_array[:,0] # market returns are column zero from numpy array
s = np_array[:,1] # stock returns are column one from numpy array
covariance = np.cov(s,m) # Calculate covariance between stock and market
beta = covariance[0,1]/covariance[1,1]
return beta
#Build Custom "Rolling_Apply" function
def rolling_apply(df, period, func, min_periods=None):
if min_periods is None:
min_periods = period
result = pd.Series(np.nan, index=df.index)
for i in range(1, len(df)+1):
sub_df = df.iloc[max(i-period, 0):i,:]
if len(sub_df) >= min_periods:
idx = sub_df.index[-1]
result[idx] = func(sub_df)
return result
#Create empty BETA dataframe with same index as RETURNS dataframe
df_join = pd.DataFrame(index=FilesLoaded[MarketIndex].index)
df_join['market'] = FilesLoaded[MarketIndex]['Return']
df_join['stock'] = np.nan
for File in FilesLoaded:
df_join['stock'].update(FilesLoaded[File]['Return'])
df_join = df_join.replace(np.inf, np.nan) #get rid of infinite values "inf" (SQL won't take "Inf")
df_join = df_join.replace(-np.inf, np.nan)#get rid of infinite values "inf" (SQL won't take "Inf")
df_join = df_join.fillna(0) #get rid of the NaNs in the return data
FilesLoaded[File]['Beta'] = rolling_apply(df_join[['market','stock']], period, calc_beta, min_periods = MinBetaPeriod)
# ***********************************************************************************************
# CLEAN-UP
# ***********************************************************************************************
print('Run-time: {0}'.format(datetime.datetime.now() - start_time))
</code></pre>
| 4 |
2016-09-14T23:50:04Z
| 39,503,417 |
<p><strong><em>Generate Random Stock Data</em></strong><br>
20 Years of Monthly Data for 4,000 Stocks</p>
<pre><code>dates = pd.date_range('1995-12-31', periods=480, freq='M', name='Date')
stoks = pd.Index(['s{:04d}'.format(i) for i in range(4000)])
df = pd.DataFrame(np.random.rand(480, 4000), dates, stoks)
</code></pre>
<hr>
<pre><code>df.iloc[:5, :5]
</code></pre>
<p><a href="http://i.stack.imgur.com/DCpxf.png" rel="nofollow"><img src="http://i.stack.imgur.com/DCpxf.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>Roll Function</em></strong><br>
Returns groupby object ready to apply custom functions<br>
See <a href="http://stackoverflow.com/a/37491779/2336654">Source</a> </p>
<pre><code>def roll(df, w):
# stack df.values w-times shifted once at each stack
roll_array = np.dstack([df.values[i:i+w, :] for i in range(len(df.index) - w + 1)]).T
# roll_array is now a 3-D array and can be read into
# a pandas panel object
panel = pd.Panel(roll_array,
items=df.index[w-1:],
major_axis=df.columns,
minor_axis=pd.Index(range(w), name='roll'))
# convert to dataframe and pivot + groupby
# is now ready for any action normally performed
# on a groupby object
return panel.to_frame().unstack().T.groupby(level=0)
</code></pre>
<hr>
<p><strong><em>Beta Function</em></strong><br>
Use closed form solution of OLS regression<br>
Assume column 0 is market<br>
See <a href="http://stats.stackexchange.com/a/23132/114499">Source</a></p>
<pre><code>def beta(df):
# first column is the market
X = df.values[:, [0]]
# prepend a column of ones for the intercept
X = np.concatenate([np.ones_like(X), X], axis=1)
# matrix algebra
b = np.linalg.pinv(X.T.dot(X)).dot(X.T).dot(df.values[:, 1:])
return pd.Series(b[1], df.columns[1:], name='Beta')
</code></pre>
<hr>
<p><strong><em>Demonstration</em></strong></p>
<pre><code>rdf = roll(df, 12)
betas = rdf.apply(beta)
</code></pre>
<hr>
<p><strong><em>Timing</em></strong></p>
<p><a href="http://i.stack.imgur.com/t6lvj.png" rel="nofollow"><img src="http://i.stack.imgur.com/t6lvj.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>Validation</em></strong><br>
Compare calculations with OP</p>
<pre><code>def calc_beta(df):
np_array = df.values
m = np_array[:,0] # market returns are column zero from numpy array
s = np_array[:,1] # stock returns are column one from numpy array
covariance = np.cov(s,m) # Calculate covariance between stock and market
beta = covariance[0,1]/covariance[1,1]
return beta
</code></pre>
<hr>
<pre><code>print(calc_beta(df.iloc[:12, :2]))
-0.311757542437
</code></pre>
<hr>
<pre><code>print(beta(df.iloc[:12, :2]))
s0001 -0.311758
Name: Beta, dtype: float64
</code></pre>
<hr>
<p><strong><em>Note the first cell</em></strong><br>
Is the same value as validated calculations above</p>
<pre><code>betas = rdf.apply(beta)
betas.iloc[:5, :5]
</code></pre>
<p><a href="http://i.stack.imgur.com/V9RGy.png" rel="nofollow"><img src="http://i.stack.imgur.com/V9RGy.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>Response to comment</em></strong><br>
Full working example with simulated multiple dataframes</p>
<pre><code>num_sec_dfs = 4000
cols = ['Open', 'High', 'Low', 'Close']
dfs = {'s{:04d}'.format(i): pd.DataFrame(np.random.rand(480, 4), dates, cols) for i in range(num_sec_dfs)}
market = pd.Series(np.random.rand(480), dates, name='Market')
df = pd.concat([market] + [dfs[k].Close.rename(k) for k in dfs.keys()], axis=1).sort_index(1)
betas = roll(df.pct_change().dropna(), 12).apply(beta)
for c, col in betas.iteritems():
dfs[c]['Beta'] = col
dfs['s0001'].head(20)
</code></pre>
<p><a href="http://i.stack.imgur.com/5RuJ9.png" rel="nofollow"><img src="http://i.stack.imgur.com/5RuJ9.png" alt="enter image description here"></a></p>
| 3 |
2016-09-15T04:59:23Z
|
[
"python",
"algorithm",
"performance",
"pandas"
] |
Efficient Python Pandas Stock Beta Calculation on Many Dataframes
| 39,501,277 |
<p>I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta (<a href="http://stackoverflow.com/questions/34802972/python-pandas-calculate-rolling-stock-beta-using-rolling-apply-to-groupby-object">Python pandas calculate rolling stock beta using rolling apply to groupby object in vectorized fashion</a>) however when used in my code below takes over 2.5 hours! Considering I can run the exact same calculations in SQL tables in under 3 minutes this is too slow.</p>
<p>How can I improve the performance of my below code to match that of SQL? I understand Pandas/python has that capability. My current method loops over each row which I know slows performance but I am unaware of any aggregate way to perform a rolling window beta calculation on a dataframe.</p>
<p>Note: the first 2 steps of loading the CSVs into individual dataframes and calculating daily returns only takes ~20seconds. All my CSV dataframes are stored in the dictionary called 'FilesLoaded' with names such as 'XAO'.</p>
<p>Your help would be much appreciated!
Thank you :)</p>
<pre><code>import pandas as pd, numpy as np
import datetime
import ntpath
pd.set_option('precision',10) #Set the Decimal Point precision to DISPLAY
start_time=datetime.datetime.now()
MarketIndex = 'XAO'
period = 250
MinBetaPeriod = period
# ***********************************************************************************************
# CALC RETURNS
# ***********************************************************************************************
for File in FilesLoaded:
FilesLoaded[File]['Return'] = FilesLoaded[File]['Close'].pct_change()
# ***********************************************************************************************
# CALC BETA
# ***********************************************************************************************
def calc_beta(df):
np_array = df.values
m = np_array[:,0] # market returns are column zero from numpy array
s = np_array[:,1] # stock returns are column one from numpy array
covariance = np.cov(s,m) # Calculate covariance between stock and market
beta = covariance[0,1]/covariance[1,1]
return beta
#Build Custom "Rolling_Apply" function
def rolling_apply(df, period, func, min_periods=None):
if min_periods is None:
min_periods = period
result = pd.Series(np.nan, index=df.index)
for i in range(1, len(df)+1):
sub_df = df.iloc[max(i-period, 0):i,:]
if len(sub_df) >= min_periods:
idx = sub_df.index[-1]
result[idx] = func(sub_df)
return result
#Create empty BETA dataframe with same index as RETURNS dataframe
df_join = pd.DataFrame(index=FilesLoaded[MarketIndex].index)
df_join['market'] = FilesLoaded[MarketIndex]['Return']
df_join['stock'] = np.nan
for File in FilesLoaded:
df_join['stock'].update(FilesLoaded[File]['Return'])
df_join = df_join.replace(np.inf, np.nan) #get rid of infinite values "inf" (SQL won't take "Inf")
df_join = df_join.replace(-np.inf, np.nan)#get rid of infinite values "inf" (SQL won't take "Inf")
df_join = df_join.fillna(0) #get rid of the NaNs in the return data
FilesLoaded[File]['Beta'] = rolling_apply(df_join[['market','stock']], period, calc_beta, min_periods = MinBetaPeriod)
# ***********************************************************************************************
# CLEAN-UP
# ***********************************************************************************************
print('Run-time: {0}'.format(datetime.datetime.now() - start_time))
</code></pre>
| 4 |
2016-09-14T23:50:04Z
| 39,565,919 |
<p>Using a generator to improve memory efficiency</p>
<p><strong><em>Simulated data</em></strong> </p>
<pre><code>m, n = 480, 10000
dates = pd.date_range('1995-12-31', periods=m, freq='M', name='Date')
stocks = pd.Index(['s{:04d}'.format(i) for i in range(n)])
df = pd.DataFrame(np.random.rand(m, n), dates, stocks)
market = pd.Series(np.random.rand(m), dates, name='Market')
df = pd.concat([df, market], axis=1)
</code></pre>
<p><strong><em>Beta Calculation</em></strong> </p>
<pre><code>def beta(df, market=None):
# If the market values are not passed,
# I'll assume they are located in a column
# named 'Market'. If not, this will fail.
if market is None:
market = df['Market']
df = df.drop('Market', axis=1)
X = market.values.reshape(-1, 1)
X = np.concatenate([np.ones_like(X), X], axis=1)
b = np.linalg.pinv(X.T.dot(X)).dot(X.T).dot(df.values)
return pd.Series(b[1], df.columns, name=df.index[-1])
</code></pre>
<p><strong><em>roll function</em></strong><br>
This returns a generator and will be far more memory efficient</p>
<pre><code>def roll(df, w):
for i in range(df.shape[0] - w + 1):
yield pd.DataFrame(df.values[i:i+w, :], df.index[i:i+w], df.columns)
</code></pre>
<p><strong><em>Putting it all together</em></strong> </p>
<pre><code>betas = pd.concat([beta(sdf) for sdf in roll(df.pct_change().dropna(), 12)], axis=1).T
</code></pre>
<hr>
<h1>Validation</h1>
<p><strong><em>OP beta calc</em></strong></p>
<pre><code>def calc_beta(df):
np_array = df.values
m = np_array[:,0] # market returns are column zero from numpy array
s = np_array[:,1] # stock returns are column one from numpy array
covariance = np.cov(s,m) # Calculate covariance between stock and market
beta = covariance[0,1]/covariance[1,1]
return beta
</code></pre>
<p><strong><em>Experiment setup</em></strong></p>
<pre><code>m, n = 12, 2
dates = pd.date_range('1995-12-31', periods=m, freq='M', name='Date')
cols = ['Open', 'High', 'Low', 'Close']
dfs = {'s{:04d}'.format(i): pd.DataFrame(np.random.rand(m, 4), dates, cols) for i in range(n)}
market = pd.Series(np.random.rand(m), dates, name='Market')
df = pd.concat([market] + [dfs[k].Close.rename(k) for k in dfs.keys()], axis=1).sort_index(1)
betas = pd.concat([beta(sdf) for sdf in roll(df.pct_change().dropna(), 12)], axis=1).T
for c, col in betas.iteritems():
dfs[c]['Beta'] = col
dfs['s0000'].head(20)
</code></pre>
<p><a href="http://i.stack.imgur.com/W8WLk.png" rel="nofollow"><img src="http://i.stack.imgur.com/W8WLk.png" alt="enter image description here"></a></p>
<pre><code>calc_beta(df[['Market', 's0000']])
0.0020118230147777435
</code></pre>
<p><strong><em>NOTE:</em></strong><br>
The calculations are the same</p>
| 0 |
2016-09-19T05:26:03Z
|
[
"python",
"algorithm",
"performance",
"pandas"
] |
How to convert lat/lon points in pandas and see whether they fall in some boundary polygons?
| 39,501,303 |
<p>I have a Pandas dataframe <code>df</code> like this:</p>
<pre><code> id lat lon
jhg 2.7 3.5
ytr 3.1 3.5
...
</code></pre>
<p>I also have a Geopandas dataframe <code>poly</code> with some polygons. Now, I would like to only plot the points in <code>df</code> that are <em>inside</em> some polygon. So I should be able to do something like <code>poly.intersects(p)</code>, where <code>p</code> is a Shapely <code>Point</code>. But I'm doing something wrong;</p>
<pre><code>from shapely.geometry import Point
for index, row in df.iterrows():
t = poly.intersects(Point(row.lon, row.lat))
</code></pre>
<p>What would be the best way to pass a dataframe with lat/lon points and plot them overlayed to <code>poly</code>? Notice that I could define a range of min/max lat/lon, but that also prints dots outside <code>poly</code> but inside the (bigger) bounding box.</p>
| 4 |
2016-09-14T23:54:35Z
| 39,501,858 |
<p>Your starting point:</p>
<pre><code>import pandas as pd
from shapely.geometry import box
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
from shapely.geometry import Point
import seaborn as sns
import numpy as np
# some pretend data
data = {'lat':[2.7,3.5,1.4,2.3,.9,1.9], 'lon':[1.2,.9,1.9,2.2,3,1.1]}
df = pd.DataFrame(data)
# the 'bounding' polygon
poly = box(1,1,2,2)
patches = PatchCollection([Polygon(poly.exterior)], facecolor='red', linewidth=.5, alpha=.5)
# plot the bounding box
fig, ax = sns.plt.subplots(1, figsize=(4,4))
ax.add_collection(patches, autolim=True)
# plot the lat/lon points
df.plot(x='lat',y='lon', kind='scatter',ax=ax)
plt.show()
</code></pre>
<p>The figures looks something like this:</p>
<p><a href="http://i.stack.imgur.com/vXVsG.png" rel="nofollow"><img src="http://i.stack.imgur.com/vXVsG.png" alt="enter image description here"></a></p>
<p>One way to get rid of the unwanted points would be to use a boolean mask:</p>
<pre><code>#probably more efficient ways to do this, but this works
mask = [poly.intersects(Point(lat,lon)) for lat,lon in zip(df.lat,df.lon)]
df = df[mask]
# make new plot (must make a new 'patch' object)
patches1 = PatchCollection([Polygon(poly.exterior)], facecolor='red', linewidth=.5, alpha=.5)
fig1, ax1 = sns.plt.subplots(1, figsize=(4,4))
ax1.add_collection(patches1, autolim=True)
# make the axis bounds the same
ax1.set_xlim(ax.get_xlim())
ax1.set_ylim(ax.get_ylim())
# plot the lat/lon points
df.plot(x='lat',y='lon', kind='scatter',ax=ax1)
plt.show()
</code></pre>
<p>Gives me this image.</p>
<p><a href="http://i.stack.imgur.com/Rn4o5.png" rel="nofollow"><img src="http://i.stack.imgur.com/Rn4o5.png" alt="enter image description here"></a></p>
<p>Note that you could make a boolean mask in other, faster ways such whether lat is above the highest point in the polygon. Those might not be perfect by themselves, but could reduce the problem so you don't have call <code>intersects()</code> as many times.</p>
<p>[edit:If your polygon is a rectangle,] another way (as you suggested in your question) would be to just 'crop' the image around the bounding polygon. This is a much faster solution since you won't have to call that <code>intersects()</code> function over and over. To trim the image based on the bounding polygon, you can insert this right before <code>plt.plot()</code>:</p>
<pre><code>ax.set_xlim((np.min(poly.exterior.xy[0]),np.max(poly.exterior.xy[0])) )
ax.set_ylim((np.min(poly.exterior.xy[1]),np.max(poly.exterior.xy[1])) )
</code></pre>
<p>Gives the following:</p>
<p><a href="http://i.stack.imgur.com/R4Y6j.png" rel="nofollow"><img src="http://i.stack.imgur.com/R4Y6j.png" alt="enter image description here"></a></p>
| 1 |
2016-09-15T01:16:55Z
|
[
"python",
"pandas",
"matplotlib",
"geopandas"
] |
How do I sum the rows of my dataframe so it only sums values based on the month, day, or year. Then form a report with all the results
| 39,501,354 |
<p>I am analyzing stock data from yahoo finance, I currently have my DataFrame = Df
filtered to show only the days for the month of march, since 1991. I want to be able to find out what the monthly returns are for march by year. Or any other combination of months i.e. what is the returns from January to March since 1991. I would also like that broken down by year.</p>
<p>I would also like to be able to do the day as well i.e. how much has apples stock changed on all the Fridays since 1991. This would be another sample question</p>
<p>I am trying to get this to where I can print an actual paper copy that breaks it all down by year; like a report.</p>
<p>I have tried reading the multindexing tutorials and group by on pandas.pydata.org/ but it is very confusing, and I am not for sure if this
is what I need. </p>
<p>This is my current code</p>
<pre><code>from pandas_datareader import data as dreader
import pandas as pd
from datetime import datetime
import dateutil.parser
from tkinter import *
# Sets the max rows that can be displayed
# when the program is executed
pd.options.display.max_rows = 120
# df is the name of the dataframe, it is
# reading the csv file containing data loaded
# from yahoo finance(Date,Open,High,Low,Close
# volume,adj close,)the name of the ticker
# is placed before _data.csv i.e. the ticker aapl
# would have a csv file named aapl_data.csv.
df = pd.read_csv("cde_data.csv")
# resets the index back to the pandas default
# i.e. index starts at 0 for the first row and
# 1 for the second and continues by one till the
# end of the data in the above csv file.
df.reset_index()
# the following code will allow for filtering of the datafram
# based on the year, day of week (dow), and month. It then gets
# applied to the dataframe and then can be used to sort data i.e
# print(df[(df.year == 2015) & (df.month == 5) & (df.dow == 4)])
# which will give you all the days in the month of May(df.month == 5),
# that fall on a Thursday(df.dow == 4), in the year 2015
# (df.year == 2015)
#
# Month Dow Year
# January = 1 Monday = 1 The year will be dispaly in a four
# February = 2 Tuesday = 2 digit format i.e. 2015
# March = 3 Wednesday = 3
# April = 4 Thursday = 4
# May = 5 Friday = 5
# June = 6
# July = 7
# August = 8
# September = 9
# October = 10
# November = 11
# December = 12
def year(x):
return(x.year)
def dow(x):
return(x.isoweekday())
def month(x):
return(x.month)
df.Date = df.Date.apply(dateutil.parser.parse)
df['year'] = df.Date.apply(year)
df['dow'] = df.Date.apply(dow)
df['month'] = df.Date.apply(month)
# The code below has a total of five sections all labeled by number.
# They are #1, #2, #3, #4, #5. Number one adds new columns to the df
# and populates them with data, number two filters out all the days
# that the market went down or flat for the day, number three filters
# out all of the days that the market went up or flat, number four
# filters all of the days that the market went up or down, and
# number five drops the excess columns and concats steps #2, #3, & #4.
# 1
# there are five columns that are being added, up_down, up, down,
# flat, and %chg. up, down, and flat are temporary and will be
# deleted later on the other two up_down, and %chg will be permeant.
# The up_down column is derived from taking the 'close' column minus the
# 'open'column, this tells you how much the stock has moved for the day.
# The 'up' column is temporary and has a value of 'up' for all the rows
# of the DataFrame df. The 'down' column is temporary and has a value of
# 'down' for all the rows of the DataFrame df. The 'down' column is
# temporary and has a value of 'flat' for all the rows of the DataFrame
# df. The '%chg' column is calculated by taking the results of the
# 'up_down' divided by the 'close' column, and then times 100, which
# turns it into a percentage show what percent the stock moved up or
# down for the day. All of the columns added below are added to the
# DataFrame called df, which contains a a csv file(see code lines 14-20
# for information on the csv file contained in the DataFrame df).
df['up'] = 'up'
df['down'] = 'down'
df['flat'] = 'flat'
df['up_down'] = df['Close'] - df['Open']
df['%chg'] = ((df['up_down']/df['Close'])*100)
# 2
# df column[up_down] is first filtered on the greater than zero
# criteria from the year 1984 on up and then is turned into df2.
# If the up_down column is greater than zero than this means that
# the stock went up. Next df3 is set = to df2['up'], df3 now holds
# just the days where the asset went up
df2= (df[(df.year > 1984) & (df.up_down > 0)])
df3 = df2['up']
# 3
# df column[up_down] is first filtered on the less than zero
# criteria from the year 1984 on up and then is turned into df4.
# If the up_down column is less than zero than this means that
# the stock went Down. Next df5 is set = to df4['down'], df5 now holds
# just the days where the asset went down
df4= (df[(df.year > 1984) & (df.up_down < 0)])
df5 = df4['down']
# 4
# df column[up_down] is first filtered on the equal to zero
# criteria from the year 1984 on up and then is turned into df6.
# If the up_down column is equal to zero than this means that
# the stock did not move. Next df7 is set = to df6['flat'],df5
# now holds just the days where the asset did not move at all
df6= (df[(df.year > 1984) & (df.up_down == 0)])
df7 = df6['flat']
# 5
# The code below starts by droping the columns 'up', 'down', and 'flat'.
# These were temporary and were used to help filter data in the above
# code in sections two, three, and four. Finally we concat the
# DataFrames df, df3, df5, and df7. We now have new 'up', 'down' and
# 'flat' columns that only display up, down, or flat when the criteria
# is true.
df = df.drop(['up'], axis = 1)
df = df.drop(['down'], axis = 1)
df = df.drop(['flat'], axis = 1)
df = pd.concat([df,df3,df5,df7],axis =1, join_axes=[df.index])
# The difference between the close of current day and the previous day
# non percentage
df['Up_Down'] = df.Close.diff()
# The percentage of change on the Up_Down column
df['%Chg'] = ((df['up_down']/df['Close'])*100)
# How much the current opening price has moved up from the previous
# opening price in terms of percentage,
df['Open%pd'] = df.Open.pct_change()*100
# How much the current high price has moved up from the previous high
# price in terms of percentage.
df['High%pd'] = df.High.pct_change()*100
# How much the current low price has moved up from the previous low
# price in terms of percentage
df['Low%pd'] = df.Low.pct_change()*100
# How much the current close price has moved up from the previous close
# price in terms of percentage
df['Close%pd'] = df.Close.pct_change()*100
# How much the current volume price has moved up from the previous days
# volume in terms of percetage
df['Volume%pd'] = df.Volume.pct_change()*100
# Both columns take the percentage of change from open to high and open
# to low
df['High%fo'] = ((df.High - df.Open)/(df.Open))*100
df['Low%fo'] = ((df.Open - df.Low) / (df.Open))*100
# Takes the difference from the high price and the low price non
# percentage
df['HighLowRange'] = df.High - df.Low
# Measures how much the range the high minus low has changed verses the
# previous day
df['HighLowRange%pd'] = df.HighLowRange.pct_change()*100
# df now is equal to only the months of March and only has the date and
# Close%pd column
df=df[['Date','Close%pd']][(df.month == 3)]
print(df)
</code></pre>
<p>This is what df prints (All the days of March since 1991) For an example</p>
<pre><code> Date Close%pd
223 1991-03-01 2.097902
224 1991-03-04 1.369863
225 1991-03-05 -2.702703
226 1991-03-06 1.388889
227 1991-03-07 0.000000
228 1991-03-08 6.164384
229 1991-03-11 -4.516129
230 1991-03-12 0.675676
231 1991-03-13 2.684564
232 1991-03-14 -2.614379
233 1991-03-15 -1.342282
234 1991-03-18 -7.482993
235 1991-03-19 0.000000
236 1991-03-20 0.735294
237 1991-03-21 0.000000
238 1991-03-22 0.000000
239 1991-03-25 -0.729927
240 1991-03-26 0.000000
241 1991-03-27 0.735294
242 1991-03-28 0.000000
476 1992-03-02 0.000000
477 1992-03-03 0.000000
478 1992-03-04 0.000000
479 1992-03-05 0.000000
480 1992-03-06 0.000000
481 1992-03-09 -3.174603
482 1992-03-10 2.459016
483 1992-03-11 0.000000
484 1992-03-12 -1.600000
485 1992-03-13 0.813008
486 1992-03-16 -1.612903
487 1992-03-17 -1.639344
488 1992-03-18 -2.500000
489 1992-03-19 1.709402
490 1992-03-20 -1.680672
491 1992-03-23 -1.709402
492 1992-03-24 -1.739130
493 1992-03-25 2.654867
494 1992-03-26 -0.862069
495 1992-03-27 4.347826
496 1992-03-30 -1.666667
497 1992-03-31 -1.694915
728 1993-03-01 2.000000
729 1993-03-02 0.980392
730 1993-03-03 0.000000
731 1993-03-04 1.941748
732 1993-03-05 1.904762
733 1993-03-08 1.869159
734 1993-03-09 0.000000
735 1993-03-10 0.000000
736 1993-03-11 -1.834862
737 1993-03-12 3.738318
738 1993-03-15 4.504505
739 1993-03-16 -1.724138
740 1993-03-17 0.000000
741 1993-03-18 2.631579
742 1993-03-19 0.000000
743 1993-03-22 5.128205
744 1993-03-23 0.000000
745 1993-03-24 2.439024
... ... ...
6023 2014-03-10 -3.372835
6024 2014-03-11 -0.943396
6025 2014-03-12 2.761905
6026 2014-03-13 -1.019462
6027 2014-03-14 1.029963
6028 2014-03-17 -1.853568
6029 2014-03-18 4.815864
6030 2014-03-19 -2.792793
6031 2014-03-20 1.297498
6032 2014-03-21 -0.548948
6033 2014-03-24 -7.083717
6034 2014-03-25 0.198020
6035 2014-03-26 -8.003953
6036 2014-03-27 0.214823
6037 2014-03-28 3.215434
6038 2014-03-31 -3.530633
6269 2015-03-02 2.226027
6270 2015-03-03 0.670017
6271 2015-03-04 -4.991681
6272 2015-03-05 -2.101576
6273 2015-03-06 -10.017889
6274 2015-03-09 -5.367793
6275 2015-03-10 -6.722689
6276 2015-03-11 4.504505
6277 2015-03-12 1.293103
6278 2015-03-13 1.063830
6279 2015-03-16 6.315789
6280 2015-03-17 -5.544554
6281 2015-03-18 8.805031
6282 2015-03-19 -3.853565
6283 2015-03-20 7.014028
6284 2015-03-23 0.561798
6285 2015-03-24 1.862197
6286 2015-03-25 -3.473492
6287 2015-03-26 -1.325758
6288 2015-03-27 -3.262956
6289 2015-03-30 -3.968254
6290 2015-03-31 -2.685950
6521 2016-03-01 -1.295337
6522 2016-03-02 4.986877
6523 2016-03-03 12.250000
6524 2016-03-04 0.668151
6525 2016-03-07 11.061947
6526 2016-03-08 -7.370518
6527 2016-03-09 1.720430
6528 2016-03-10 3.382664
6529 2016-03-11 2.862986
6530 2016-03-14 -2.783300
6531 2016-03-15 -1.226994
6532 2016-03-16 9.730849
6533 2016-03-17 3.207547
6534 2016-03-18 2.193784
6535 2016-03-21 3.041145
6536 2016-03-22 0.694444
6537 2016-03-23 -9.482759
6538 2016-03-24 0.571429
6539 2016-03-28 3.030303
6540 2016-03-29 4.963235
6541 2016-03-30 -1.050788
6542 2016-03-31 -0.530973
[568 rows x 2 columns]
Press any key to continue . . .
</code></pre>
| 2 |
2016-09-15T00:00:44Z
| 39,501,542 |
<p>As in the comments, you can find monthly totals using groupby:</p>
<pre><code>#change the previous last line of code to this
df=df[['Date','year','month','Close%pd']][(df.month == 3)]
#make a new dataframe
new_df = df.groupby(['year','month']).sum()
</code></pre>
<p>An alternative method would be to use the <code>resample</code> command (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow">docs</a>). This is probably the best way to go for weekly totals especially since you don't have a variable indicating the 'week of the year' which is what you would pass into groupby.</p>
<pre><code>df = df.resample('W', how='sum') #weekly totals
df = df.resample('M', how='sum') #monthly totals
</code></pre>
| 1 |
2016-09-15T00:29:09Z
|
[
"python",
"pandas",
"dataframe",
"report",
"filtering"
] |
How to call a method from a class with inheritence on an object of the base class?
| 39,501,400 |
<p>I have two classes. One inherits the other:</p>
<pre><code>class A(object):
def __init__(self):
self.attribute = 1
class B(A):
def get_attribute(self):
return self.attribute
</code></pre>
<p>I would like to be able to call methods from B on objects of type A. I cannot edit class A (it is a built in class). When I try to call a method from B, there is an AttributeError. </p>
<pre><code>a = A()
a.get_attribute()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
a.get_attribute()
AttributeError: 'A' object has no attribute 'get_attribute'
</code></pre>
<p>Is there a way to call methods from B without explicitly declaring the data to be of type B?</p>
| -1 |
2016-09-15T00:09:34Z
| 39,501,775 |
<p>While it is discouraged to do you can use any method like a function. In your case it would be</p>
<pre><code>B.get_attribute(a)
</code></pre>
<p>Of cause the method has to be compatible with the type of <code>a</code>.</p>
| 0 |
2016-09-15T01:04:04Z
|
[
"python",
"python-2.7"
] |
SQL Query output formatting URL in python
| 39,501,424 |
<p>I am new to python. I am writing a script which queries the database for a URL string. Below is my snippet.</p>
<pre><code>db.execute('select sitevideobaseurl,videositestring '
'from site, video '
'where siteID =1 and site.SiteID=video.VideoSiteID limit 1')
result = db.fetchall()
for row in result:
videosite= row[0:2]
print videosite
</code></pre>
<p>It gives me baseURL from a table and the video site string from another table.
output: <code>('http://www.youtube.com/watch?v={0}', 'uqcSJR_7fOc')</code></p>
<p>I wish to format the output by removing the braces, quotes and commas and replace the {0} from baseURL with sitestring: uqcSJR_7fOc.
something like: <a href="https://www.youtube.com/watch?v=uqcSJR_7fOc" rel="nofollow">https://www.youtube.com/watch?v=uqcSJR_7fOc</a> in the final output and wish to write this to a file. </p>
<p>Thanks for your time and help in advance.</p>
| 0 |
2016-09-15T00:11:54Z
| 39,501,465 |
<p>Use <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow"><code>str.format</code></a>.</p>
<pre><code>db.execute('select sitevideobaseurl,videositestring '
'from site, video '
'where siteID =1 and site.SiteID=video.VideoSiteID limit 1')
result = db.fetchall()
for row in result:
videosite= row[0:2]
print videosite[0].format(videosite[1])
</code></pre>
| 0 |
2016-09-15T00:17:59Z
|
[
"python",
"sql",
"url",
"formatting"
] |
SQL Query output formatting URL in python
| 39,501,424 |
<p>I am new to python. I am writing a script which queries the database for a URL string. Below is my snippet.</p>
<pre><code>db.execute('select sitevideobaseurl,videositestring '
'from site, video '
'where siteID =1 and site.SiteID=video.VideoSiteID limit 1')
result = db.fetchall()
for row in result:
videosite= row[0:2]
print videosite
</code></pre>
<p>It gives me baseURL from a table and the video site string from another table.
output: <code>('http://www.youtube.com/watch?v={0}', 'uqcSJR_7fOc')</code></p>
<p>I wish to format the output by removing the braces, quotes and commas and replace the {0} from baseURL with sitestring: uqcSJR_7fOc.
something like: <a href="https://www.youtube.com/watch?v=uqcSJR_7fOc" rel="nofollow">https://www.youtube.com/watch?v=uqcSJR_7fOc</a> in the final output and wish to write this to a file. </p>
<p>Thanks for your time and help in advance.</p>
| 0 |
2016-09-15T00:11:54Z
| 39,501,518 |
<p>You can use a "replace" command in either Sql or Python.</p>
<pre><code>str_url = str_url.replace('[','')
str_url = str_url.replace(']','')
str_url = str_url.replace('?','')
</code></pre>
<p>Something like this in Python which is the easier of the two to do.</p>
<p>Repeat for as many characters as you want to chop out </p>
<p>My str_url is your "videosite".</p>
| 0 |
2016-09-15T00:26:49Z
|
[
"python",
"sql",
"url",
"formatting"
] |
Python 3.5.2 Roman Numeral Quiz
| 39,501,452 |
<p>So I am doing this assignment for school. I have to create a quiz like game that will prompt a user to add roman numerals together and input their answer. It will then check the user's answer with the correct answer and tell the user if they got it right or wrong.</p>
<p>So far I have this:</p>
<pre><code>class RomanNumeral:
index = 0
while index < len(integer_list) - 1:
#if a lower number is first, it should be subtracted, like IX,
#the one should be subtracted, but the 10 added
if integer_list[index] < integer_list[index + 1]:
r_integer -= integer_list[index]
else:
r_integer += integer_list[index]
index += 1
#Always add the last number
r_integer += integer_list[index]
#Store r_integer as an instance data item
self.__integer = r_integer
return
def main():
roman1 = RomanNumeral('random')
roman2 = RomanNumeral('random')
correct_answer = roman1 + roman2
main()
</code></pre>
<p>But when I run it, i get this error:</p>
<pre><code>r_integer += integer_list[index]
UnboundLocalError: local variable 'r_integer' referenced before assignment
</code></pre>
<p>Any suggestions on how to fix this issue? </p>
<p>As well, I need help overloading the <strong>int</strong> method to change the roman numerals to integers so that they can be added together. </p>
| 1 |
2016-09-15T00:16:53Z
| 39,501,473 |
<p>Your error says</p>
<pre><code>local variable 'r_integer' referenced before assignment
</code></pre>
<p>This means you tried to use a variable before you defined it. Define <code>r_integer</code> to 0 (or some other number) before the <code>while</code> loop and your problem should be fixed.</p>
| 0 |
2016-09-15T00:19:24Z
|
[
"python",
"roman-numerals"
] |
Python 3.5.2 Roman Numeral Quiz
| 39,501,452 |
<p>So I am doing this assignment for school. I have to create a quiz like game that will prompt a user to add roman numerals together and input their answer. It will then check the user's answer with the correct answer and tell the user if they got it right or wrong.</p>
<p>So far I have this:</p>
<pre><code>class RomanNumeral:
index = 0
while index < len(integer_list) - 1:
#if a lower number is first, it should be subtracted, like IX,
#the one should be subtracted, but the 10 added
if integer_list[index] < integer_list[index + 1]:
r_integer -= integer_list[index]
else:
r_integer += integer_list[index]
index += 1
#Always add the last number
r_integer += integer_list[index]
#Store r_integer as an instance data item
self.__integer = r_integer
return
def main():
roman1 = RomanNumeral('random')
roman2 = RomanNumeral('random')
correct_answer = roman1 + roman2
main()
</code></pre>
<p>But when I run it, i get this error:</p>
<pre><code>r_integer += integer_list[index]
UnboundLocalError: local variable 'r_integer' referenced before assignment
</code></pre>
<p>Any suggestions on how to fix this issue? </p>
<p>As well, I need help overloading the <strong>int</strong> method to change the roman numerals to integers so that they can be added together. </p>
| 1 |
2016-09-15T00:16:53Z
| 39,501,497 |
<p>You need to initialize <code>r_integer</code> before the <code>while</code> loop. Added to your code below the ##### comment </p>
<pre><code> #Add if the number is greater than the one that follows, otherwise
#subtract r_integer = 0
#Stands for roman integer or the integer equivalent of the roman string
index = 0
##### Initialize r_integer before the while loop
r_integer = 0
while index < len(integer_list) - 1:
#if a lower number is first, it should be subtracted, like IX,
#the one should be subtracted, but the 10 added
if integer_list[index] < integer_list[index + 1]:
r_integer -= integer_list[index]
else:
r_integer += integer_list[index]
index += 1
#Always add the last number
r_integer += integer_list[index]
</code></pre>
| 0 |
2016-09-15T00:23:38Z
|
[
"python",
"roman-numerals"
] |
Python 3.5.2 Roman Numeral Quiz
| 39,501,452 |
<p>So I am doing this assignment for school. I have to create a quiz like game that will prompt a user to add roman numerals together and input their answer. It will then check the user's answer with the correct answer and tell the user if they got it right or wrong.</p>
<p>So far I have this:</p>
<pre><code>class RomanNumeral:
index = 0
while index < len(integer_list) - 1:
#if a lower number is first, it should be subtracted, like IX,
#the one should be subtracted, but the 10 added
if integer_list[index] < integer_list[index + 1]:
r_integer -= integer_list[index]
else:
r_integer += integer_list[index]
index += 1
#Always add the last number
r_integer += integer_list[index]
#Store r_integer as an instance data item
self.__integer = r_integer
return
def main():
roman1 = RomanNumeral('random')
roman2 = RomanNumeral('random')
correct_answer = roman1 + roman2
main()
</code></pre>
<p>But when I run it, i get this error:</p>
<pre><code>r_integer += integer_list[index]
UnboundLocalError: local variable 'r_integer' referenced before assignment
</code></pre>
<p>Any suggestions on how to fix this issue? </p>
<p>As well, I need help overloading the <strong>int</strong> method to change the roman numerals to integers so that they can be added together. </p>
| 1 |
2016-09-15T00:16:53Z
| 39,501,773 |
<p>You aren't using the integer defined for self. Try adding a declaration after </p>
<pre><code> r_string = r_string.upper()
</code></pre>
<p>Add </p>
<pre><code>r_integer = self.__integer
</code></pre>
<p>That way you have a local copy to work with. </p>
<p>However you do need to overload the integer method which is answered in <a href="http://stackoverflow.com/q/11575393/5721740" title="this post">this post</a></p>
| 0 |
2016-09-15T01:03:38Z
|
[
"python",
"roman-numerals"
] |
(Python) Stop thread with raw input?
| 39,501,529 |
<p><strong>EDIT 9/15/16:</strong> In my original code (still posted below) I tried to use <code>.join()</code> with a function, which is a silly mistake because it can only be used with a thread object. I am trying to
(1) continuously run a thread that gets data and saves it to a file
(2) have a second thread, or incorporate queue, that will stop the program once a user enters a flag (i.e. "stop"). It doesn't interrupt the data gathering/saving thread. </p>
<p>I need help with multithreading. I am trying to run two threads, one that handles data and the second checks for a flag to stop the program.</p>
<p>I learned by trial and error that I can't interrupt a while loop without my computer exploding. Additionally, I have abandoned my GUI code because it made my code too complicated with the mulithreading.</p>
<p>What I want to do is run a thread that gathers data from an Arduino, saves it to a file, and repeats this. The second thread will scan for a <strong>flag</strong> -- which can be a raw_input? I can't think of anything else that a user can do to stop the data acquisition program. </p>
<p>I greatly appreciate any help on this. Here is my code (much of it is pseudocode, as you can see):</p>
<pre><code>#threading
import thread
import time
global flag
def monitorData():
print "running!"
time.sleep(5)
def stopdata(flag ):
flag = raw_input("enter stop: ")
if flag == "stop":
monitorData.join()
flag = "start"
thread.start_new_thread( monitorData,())
thread.start_new_thread( stopdata,(flag,))
</code></pre>
<p>The error I am getting is this when I try entering "stop" in the IDLE. </p>
<p><em>Unhandled exception in thread started by
Traceback (most recent call last):
File "c:\users\otangu~1\appdata\local\temp\IDLE_rtmp_h_frd5", line 16, in stopdata
AttributeError: 'function' object has no attribute 'join'</em></p>
<p>Once again I really appreciate any help, I have taught myself Python so far and this is the first huge wall that I've hit. </p>
| 2 |
2016-09-15T00:27:58Z
| 39,501,789 |
<p>This is not possible. The thread function has to finish. You can't join it from the outside.</p>
| 0 |
2016-09-15T01:05:52Z
|
[
"python",
"multithreading"
] |
(Python) Stop thread with raw input?
| 39,501,529 |
<p><strong>EDIT 9/15/16:</strong> In my original code (still posted below) I tried to use <code>.join()</code> with a function, which is a silly mistake because it can only be used with a thread object. I am trying to
(1) continuously run a thread that gets data and saves it to a file
(2) have a second thread, or incorporate queue, that will stop the program once a user enters a flag (i.e. "stop"). It doesn't interrupt the data gathering/saving thread. </p>
<p>I need help with multithreading. I am trying to run two threads, one that handles data and the second checks for a flag to stop the program.</p>
<p>I learned by trial and error that I can't interrupt a while loop without my computer exploding. Additionally, I have abandoned my GUI code because it made my code too complicated with the mulithreading.</p>
<p>What I want to do is run a thread that gathers data from an Arduino, saves it to a file, and repeats this. The second thread will scan for a <strong>flag</strong> -- which can be a raw_input? I can't think of anything else that a user can do to stop the data acquisition program. </p>
<p>I greatly appreciate any help on this. Here is my code (much of it is pseudocode, as you can see):</p>
<pre><code>#threading
import thread
import time
global flag
def monitorData():
print "running!"
time.sleep(5)
def stopdata(flag ):
flag = raw_input("enter stop: ")
if flag == "stop":
monitorData.join()
flag = "start"
thread.start_new_thread( monitorData,())
thread.start_new_thread( stopdata,(flag,))
</code></pre>
<p>The error I am getting is this when I try entering "stop" in the IDLE. </p>
<p><em>Unhandled exception in thread started by
Traceback (most recent call last):
File "c:\users\otangu~1\appdata\local\temp\IDLE_rtmp_h_frd5", line 16, in stopdata
AttributeError: 'function' object has no attribute 'join'</em></p>
<p>Once again I really appreciate any help, I have taught myself Python so far and this is the first huge wall that I've hit. </p>
| 2 |
2016-09-15T00:27:58Z
| 39,501,792 |
<p>You're looking for something like this:</p>
<pre><code>from threading import Thread
from time import sleep
# "volatile" global shared by threads
active = True
def get_data():
while active:
print "working!"
sleep(3)
def wait_on_user():
global active
raw_input("press enter to stop")
active = False
th1 = Thread(target=get_data)
th1.start()
th2 = Thread(target=wait_on_user)
th2.start()
th1.join()
th2.join()
</code></pre>
<p>You made a few obvious and a few less obvious mistakes in your code. First, join is called on a thread object, not a function. Similarly, join doesn't kill a thread, it waits for the thread to finish. A thread finishes when it has no more code to execute. If you want a thread to run until some flag is set, you normally include a loop in your thread that checks the flag every second or so (depending on how precise you need the timing to be).</p>
<p>Also, the threading module is preferred over the lower lever thread module. The latter has been removed in python3.</p>
| 0 |
2016-09-15T01:06:33Z
|
[
"python",
"multithreading"
] |
(Python) Stop thread with raw input?
| 39,501,529 |
<p><strong>EDIT 9/15/16:</strong> In my original code (still posted below) I tried to use <code>.join()</code> with a function, which is a silly mistake because it can only be used with a thread object. I am trying to
(1) continuously run a thread that gets data and saves it to a file
(2) have a second thread, or incorporate queue, that will stop the program once a user enters a flag (i.e. "stop"). It doesn't interrupt the data gathering/saving thread. </p>
<p>I need help with multithreading. I am trying to run two threads, one that handles data and the second checks for a flag to stop the program.</p>
<p>I learned by trial and error that I can't interrupt a while loop without my computer exploding. Additionally, I have abandoned my GUI code because it made my code too complicated with the mulithreading.</p>
<p>What I want to do is run a thread that gathers data from an Arduino, saves it to a file, and repeats this. The second thread will scan for a <strong>flag</strong> -- which can be a raw_input? I can't think of anything else that a user can do to stop the data acquisition program. </p>
<p>I greatly appreciate any help on this. Here is my code (much of it is pseudocode, as you can see):</p>
<pre><code>#threading
import thread
import time
global flag
def monitorData():
print "running!"
time.sleep(5)
def stopdata(flag ):
flag = raw_input("enter stop: ")
if flag == "stop":
monitorData.join()
flag = "start"
thread.start_new_thread( monitorData,())
thread.start_new_thread( stopdata,(flag,))
</code></pre>
<p>The error I am getting is this when I try entering "stop" in the IDLE. </p>
<p><em>Unhandled exception in thread started by
Traceback (most recent call last):
File "c:\users\otangu~1\appdata\local\temp\IDLE_rtmp_h_frd5", line 16, in stopdata
AttributeError: 'function' object has no attribute 'join'</em></p>
<p>Once again I really appreciate any help, I have taught myself Python so far and this is the first huge wall that I've hit. </p>
| 2 |
2016-09-15T00:27:58Z
| 39,502,488 |
<p>The error you see is a result of calling join on the function. You need to call <code>join</code> on the <code>thread</code> object. You don't capture a reference to the thread so you have no way to call <code>join</code> anyway. You should <code>join</code> like so.</p>
<pre><code>th1 = thread.start_new_thread( monitorData,())
# later
th1.join()
</code></pre>
<p>As for a solution, you can use a <code>Queue</code> to communicate between threads. The queue is used to send a quit message to the worker thread and if the worker does not pick anything up off the queue for a second it runs the code that gathers data from the arduino.</p>
<pre><code>from threading import Thread
from Queue import Queue, Empty
def worker(q):
while True:
try:
item = q.get(block=True, timeout=1)
q.task_done()
if item == "quit":
print("got quit msg in thread")
break
except Empty:
print("empty, do some arduino stuff")
def input_process(q):
while True:
x = raw_input("")
if x == 'q':
print("will quit")
q.put("quit")
break
q = Queue()
t = Thread(target=worker, args=(q,))
t.start()
t2 = Thread(target=input_process, args=(q,))
t2.start()
# waits for the `task_done` function to be called
q.join()
t2.join()
t.join()
</code></pre>
<p>It's possibly a bit more code than you hoped for and having to detect the queue is empty with an exception is a little ugly, but this doesn't rely on any global variables and will always exit promptly. That wont be the case with <code>sleep</code> based solutions, which need to wait for any current calls to <code>sleep</code> to finish before resuming execution.</p>
<p>As noted by someone else, you should really be using <code>threading</code> rather than the older <code>thread</code> module and also I would recommend you learn with python 3 and not python 2. </p>
| 0 |
2016-09-15T02:59:14Z
|
[
"python",
"multithreading"
] |
Use enumerate to find indices of all words with letter 'x'
| 39,501,531 |
<p>How use enumerate to help find the indices of all words containing 'x' </p>
<p>Thank you</p>
<pre><code>wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()
indices=[]
for (index, value) in enumerate(wordList):
if value == 'x':
print("These locations contain words containing the letter 'x':\n",indices)
</code></pre>
| -1 |
2016-09-15T00:28:03Z
| 39,501,599 |
<p>Your code is almost complete:</p>
<pre><code>for (index, value) in enumerate(wordList):
if 'x' in value:
indices.append(index)
</code></pre>
<p>This checks, for every single word, if there is an <code>x</code> in it. If so, it adds the index to <code>indices</code>.</p>
| 1 |
2016-09-15T00:37:15Z
|
[
"python",
"python-3.x"
] |
Add values to bottom of DataFrame automatically with Pandas
| 39,501,554 |
<p>I'm initializing a DataFrame:</p>
<pre><code>columns = ['Thing','Time']
df_new = pd.DataFrame(columns=columns)
</code></pre>
<p>and then writing values to it like this:</p>
<pre><code>for t in df.Thing.unique():
df_temp = df[df['Thing'] == t] #filtering the df
df_new.loc[counter,'Thing'] = t #writing the filter value to df_new
df_new.loc[counter,'Time'] = dftemp['delta'].sum(axis=0) #summing and adding that value to the df_new
counter += 1 #increment the row index
</code></pre>
<p>Is there are better way to add new values to the dataframe each time without explicitly incrementing the row index with 'counter'?</p>
| 2 |
2016-09-15T00:30:44Z
| 39,502,967 |
<p>If I'm interpreting this correctly, I think this can be done in one line:</p>
<pre><code>newDf = df.groupby('Thing')['delta'].sum().reset_index()
</code></pre>
<p>By grouping by 'Thing', you have the various "t-filters" from your for-loop. We then apply a <code>sum()</code> to 'delta', but only within the various "t-filtered" groups. At this point, the dataframe has the various values of "t" as the indices, and the sums of the "t-filtered deltas" as a corresponding column. To get to your desired output, we then bump the "t's" into their own column via <code>reset_index()</code>.</p>
| 3 |
2016-09-15T04:08:22Z
|
[
"python",
"pandas"
] |
UnboundLocalError: Says variable isn't defined before being used
| 39,501,627 |
<p>when i run my game function i get this error:</p>
<pre><code> Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "hog.py", line 162, in play
if is_swap(score0,score1)== True and who == 0:
File "hog.py", line 121, in is_swap
elif swap1 == score0:
UnboundLocalError: local variable 'swap1' referenced before assignment
</code></pre>
<p>Here are the two functions referenced in the error(first the parent, then child function):</p>
<pre><code>def play(strategy0, strategy1, score0=0, score1=0, goal=GOAL_SCORE):
"""Simulate a game and return the final scores of both players, with
Player 0's score first, and Player 1's score second.
A strategy is a function that takes two total scores as arguments
(the current player's score, and the opponent's score), and returns a
number of dice that the current player will roll this turn.
strategy0: The strategy function for Player 0, who plays first
strategy1: The strategy function for Player 1, who plays second
score0 : The starting score for Player 0
score1 : The starting score for Player 1
"""
who = 0 # Which player is about to take a turn, 0 (first) or 1 (second)
# BEGIN Question 5
while score0 <= goal and score1 <= goal:
#Palyerx Turn
if who == 0:
score0 += take_turn(strategy0(score0,score1), score1, select_dice(score0,score1))
elif who == 1:
score1 += take_turn(strategy1(score1,score0), score0, select_dice(score1,score0))
print(score0,score1)
#Swine Swap
if is_swap(score0,score1)== True and who == 0:
temp = score0
score0 = score1
score1 = temp
elif is_swap(score1,score0) == True and who == 1:
temp = score1
score1 = score0
score0 = temp
who = other(who)
# END Question 5
return score0, score1
def is_swap(score0, score1):
"""Return True if ending a turn with SCORE0 and SCORE1 will result in a
swap.
Swaps occur when the last two digits of the first score are the reverse
of the last two digits of the second score.
"""
# BEGIN Question 4
#If scores are equal there is no need to flip
if score0 == score1:
return True
#Flipping Score0
if score0 >= 10 and score0 < 100:
s0String = str(score0)
x = s0String[0]
y = s0String[1]
swap0 = int(y+x)
elif score0 < 10:
x = '0'
y = str(score0)
swap0 = int(y+x)
elif score0 > 100:
s0String = str(score0)
x = s0String[0]
y = s0String[1]
z = s0String[2]
swap0 = int(z+y)
#Flipping Score1
if score1 >= 10 and score1 < 100:
s1String = str(score1)
i = s1String[0]
j = s1String[1]
swap1 = int(j+i)
elif score1 < 10:
i = '0'
j = str(score1)
swap1 = int(j+i)
elif score1 > 100:
s1String = str(score1)
i = s1String[0]
j = s1String[1]
f = s1String[2]
swap1 = int(f+j)
#Swapping Scores Bases on Flipped equivelence
if swap0 == score1:
return True
elif swap1 == score0:
return True
else:
return False
</code></pre>
<p>I'm not sure what it wants. As it stands swap0 is defiend before it is used in the is swap function, and it is being called correctly in play.</p>
| -1 |
2016-09-15T00:41:48Z
| 39,501,733 |
<p>None of the branches of your <code>if</code>/<code>elif</code> logic handle the situation where <code>score1</code> is exactly 100. This leaves <code>swap1</code> undefined, leading to the error you've described.</p>
<p>To avoid this, make sure your different conditions cover all branches. Often this is easiest if you leave the last branch a regular <code>else</code> rather than an <code>elif</code>. You can also simplify your conditions by changing the order you check them in, like this:</p>
<pre><code>if score1 < 10:
i = '0'
j = str(score1)
swap1 = int(j+i)
elif score1 < 100:
s1String = str(score1)
i = s1String[0]
j = s1String[1]
swap1 = int(j+i)
else: # score1 >= 100
s1String = str(score1)
i = s1String[0]
j = s1String[1]
f = s1String[2]
swap1 = int(f+j)
</code></pre>
| 1 |
2016-09-15T00:57:29Z
|
[
"python"
] |
'int' object has no attribute '__getitem__' on a non-integer object
| 39,501,670 |
<p>In looking at other answers to this issue I found that the object was usually an integer so i constructed a simple example showing it is not and integer (or so I think), <strong>this code:</strong></p>
<pre><code>import numpy as np
a=np.arange(2,10)
print '1: ', a
print '2: ', a.size
print '3: ', a[3:] #this shows this is not an integer
print '3a: ', len(a[3:]) #len works
print '4: ', a.size[3:] #but yet size does not work
</code></pre>
<p><strong>yields:</strong> ============</p>
<pre><code>1: [2 3 4 5 6 7 8 9]
2: 8
3: [5 6 7 8 9]
4:
------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-5c4b06ceceba> in <module>()
4 print '2: ', a.size
5 print '3: ', a[3:] *#this shows this is not an integer*
----> 6 print '4: ', a.size[3:] *#but yet size does not work*
TypeError: 'int' object has no attribute '__getitem__'
</code></pre>
<p>======================</p>
<p>As you can see a[3:] is not an integer - what am I doing wrong?</p>
| -2 |
2016-09-15T00:48:38Z
| 39,501,716 |
<p>If you want the size of <code>a[3:]</code> then try:</p>
<pre><code>>>> a[3:].size
5
</code></pre>
<p>By writing <code>a.size[3:]</code> what you are trying to do is <code>index</code> over an <code>integer</code> as <code>a.size</code> is an <code>integer</code>.</p>
| 2 |
2016-09-15T00:54:21Z
|
[
"python"
] |
Is subclassing from object the same as defining type as metaclass?
| 39,501,774 |
<p>This is an old-style class:</p>
<pre><code>class OldStyle:
pass
</code></pre>
<p>This is a new-style class:</p>
<pre><code>class NewStyle(object):
pass
</code></pre>
<p>This is also a new-style class:</p>
<pre><code>class NewStyle2:
__metaclass__ = type
</code></pre>
<p>Is there any difference whatsoever between <code>NewStyle</code> and <code>NewStyle2</code>?</p>
<p>I have the impression that the only effect of inheriting from <code>object</code> is actually to define the <code>type</code> metaclass, but I cannot find any confirmation of that, other than that I do not see any difference.</p>
| 5 |
2016-09-15T01:03:51Z
| 39,987,578 |
<p>Pretty much yes, there's no difference between <code>NewStyle</code> and <code>NewStyle2</code>. Both are of type <code>type</code> while <code>OldStyle</code> of type <code>classobj</code>.</p>
<p>If you subclass from object, the <a href="https://hg.python.org/cpython/file/2.7/Python/ceval.c#l4949" rel="nofollow"><code>__class__</code> of <code>object</code> (meaning <code>type</code>) is going</a> to be used; if you supply a <a href="https://hg.python.org/cpython/file/2.7/Python/ceval.c#l4944" rel="nofollow"><code>__metaclass__</code> that is going to get picked up</a>.</p>
<p>If nothing is supplied as <code>__metaclass__</code> and you don't inherit from <code>object</code>, <a href="https://hg.python.org/cpython/file/2.7/Python/ceval.c#l4961" rel="nofollow"><code>Py_ClassType</code> is assigned as the metaclass</a> for you.</p>
<p>In all cases, <code>metaclass.__new__</code> is going to get called. For <code>Py_ClassType.__new__</code> it follows the semantics defined (I've never examined them, really) and for <a href="https://hg.python.org/cpython/file/2.7/Objects/typeobject.c#l2164" rel="nofollow"><code>type.__new__</code> it makes sure to pack <code>object</code></a> in the bases of your class.</p>
<p>Of course, a similar effect is achieved by:</p>
<pre><code>cls = type("NewStyle3", (), {})
</code></pre>
<p>where a call is immediately made to <code>type</code>; it's just a bigger hassle :-)</p>
| 2 |
2016-10-11T22:10:15Z
|
[
"python",
"python-2.7",
"python-internals",
"new-style-class"
] |
Python multiprocessing silent failure with class
| 39,501,785 |
<p>the following does not work using python 2.7.9, but also does not throw any error or exception. is there a bug, or can multiprocessing not be used in a class?</p>
<pre><code>from multiprocessing import Pool
def testNonClass(arg):
print "running %s" % arg
return arg
def nonClassCallback(result):
print "Got result %s" % result
class Foo:
def __init__(self):
po = Pool()
for i in xrange(1, 3):
po.apply_async(self.det, (i,), callback=self.cb)
po.close()
po.join()
print "done with class"
po = Pool()
for i in xrange(1, 3):
po.apply_async(testNonClass, (i,), callback=nonClassCallback)
po.close()
po.join()
def cb(self, r):
print "callback with %s" % r
def det(self, M):
print "method"
return M+2
if __name__ == "__main__":
Foo()
</code></pre>
<p>running prints this: </p>
<pre><code>done with class
running 1
running 2
Got result 1
Got result 2
</code></pre>
<p>EDIT: THis seems related, but it uses <code>.map</code>, while I specifically am needing to use <code>apply_async</code> which seems to matter in terms of how multiprocessing works with class instances (e.g. I dont have a picklnig error, like many other questions related to this) - <a href="http://stackoverflow.com/questions/29009790/python-how-to-do-multiprocessing-inside-of-a-class">Python how to do multiprocessing inside of a class?</a></p>
| 1 |
2016-09-15T01:05:14Z
| 39,501,851 |
<p>I'm pretty sure it can be used in a class, but you need to protect the call to <code>Foo</code> inside of a clause like:</p>
<p><code>if name == "__main__":</code></p>
<p>so that it only gets called in the main thread. You may also have to alter the <code>__init__</code> function of the class so that it accepts a pool as an argument instead of creating a pool.</p>
<p>I just tried this</p>
<pre><code>from multiprocessing import Pool
#global counter
#counter = 0
class Foo:
def __init__(self, po):
for i in xrange(1, 300):
po.apply_async(self.det, (i,), callback=self.cb)
po.close()
po.join()
print( "foo" )
#print counter
def cb(self, r):
#global counter
#print counter, r
counter += 1
def det(self, M):
return M+2
if __name__ == "__main__":
po = Pool()
Foo(po)
</code></pre>
<p>and I think I know what the problem is now. Python isn't multi-threaded; global interpreter lock prevents that. Python is using multiple processes, instead, so the sub-processes in the Pool don't have access to the standard output of the main process. </p>
<p>The subprocesses also are unable to modify the variable <code>counter</code> because it exists in a different process (I tried running with the <code>counter</code> lines commented out and uncommented). Now, I do recall seeing cases where global state variables get altered by processes in the pool, so I don't know all of the minutiae. I do know that it is, in general, a bad idea to have global state variables like that, if for no other reason than they can lead to race conditions and/or wasted time with locks and waiting for access to the global variable.</p>
| 0 |
2016-09-15T01:16:24Z
|
[
"python",
"class",
"multiprocessing"
] |
Python multiprocessing silent failure with class
| 39,501,785 |
<p>the following does not work using python 2.7.9, but also does not throw any error or exception. is there a bug, or can multiprocessing not be used in a class?</p>
<pre><code>from multiprocessing import Pool
def testNonClass(arg):
print "running %s" % arg
return arg
def nonClassCallback(result):
print "Got result %s" % result
class Foo:
def __init__(self):
po = Pool()
for i in xrange(1, 3):
po.apply_async(self.det, (i,), callback=self.cb)
po.close()
po.join()
print "done with class"
po = Pool()
for i in xrange(1, 3):
po.apply_async(testNonClass, (i,), callback=nonClassCallback)
po.close()
po.join()
def cb(self, r):
print "callback with %s" % r
def det(self, M):
print "method"
return M+2
if __name__ == "__main__":
Foo()
</code></pre>
<p>running prints this: </p>
<pre><code>done with class
running 1
running 2
Got result 1
Got result 2
</code></pre>
<p>EDIT: THis seems related, but it uses <code>.map</code>, while I specifically am needing to use <code>apply_async</code> which seems to matter in terms of how multiprocessing works with class instances (e.g. I dont have a picklnig error, like many other questions related to this) - <a href="http://stackoverflow.com/questions/29009790/python-how-to-do-multiprocessing-inside-of-a-class">Python how to do multiprocessing inside of a class?</a></p>
| 1 |
2016-09-15T01:05:14Z
| 39,501,991 |
<p>Processes don't share state or memory by default, each process is an independent program. You need to either 1) use threading 2) use <a href="https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">specific types capable of sharing state</a> or 3) design your program to avoid shared state and rely on return values instead.</p>
<p>Update</p>
<p>You have two issues in your code, and one is masking the other.</p>
<p>1) You don't do anything with the result of the <code>apply_async</code>, I see that you're using callbacks, but you still need to catch the results and handle them. Because you're not doing this, you're not seeing the error caused by the second problem.</p>
<p>2) Methods of an object cannot be passed to other processes... I was really annoyed when I first discovered this, but there is an easy workaround. Try this:</p>
<pre><code>from multiprocessing import Pool
def _remote_det(foo, m):
return foo.det(m)
class Foo:
def __init__(self):
pass
po = Pool()
results = []
for i in xrange(1, 3):
r = po.apply_async(_remote_det, (self, i,), callback=self.cb)
results.append(r)
po.close()
for r in results:
r.wait()
if not r.successful():
# Raises an error when not successful
r.get()
po.join()
print "done with class"
def cb(self, r):
print "callback with %s" % r
def det(self, M):
print "method"
return M+2
if __name__ == "__main__":
Foo()
</code></pre>
| 1 |
2016-09-15T01:40:24Z
|
[
"python",
"class",
"multiprocessing"
] |
why is 2 printed as a prime when if statement says it should not be
| 39,501,839 |
<p>i know 2 is a prime number (btw), but when this code is ran it doesn't match the if statement condition <code>if n % x == 0</code>. but <code>2 % 2 == 0</code> so it should be a equal </p>
<pre><code>for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
</code></pre>
| 0 |
2016-09-15T01:14:47Z
| 39,501,909 |
<p>From the Python documentation of <a href="https://docs.python.org/3/library/stdtypes.html#typesseq-range" rel="nofollow"><code>range()</code></a></p>
<blockquote>
<p>For a positive <em>step</em>, the contents of a range <code>r</code> are determined by the formula <code>r[i] = start + step*i</code> where <code>i >= 0</code> and <code>r[i] < stop</code>.</p>
<p>A range object will be empty if <code>r[0]</code> does not meet the value constraint.</p>
</blockquote>
<p>So when <code>n = 2</code>, <code>range(2, n)</code> is an empty range, because <code>r[0]</code> is <code>2</code> and that doesn't meet the constraint <code>2 < 2</code>. Therefore <code>for</code> loop never runs, so it never breaks, and as a result, the <code>else:</code> block is executed and reports that it's prime.</p>
| 5 |
2016-09-15T01:25:03Z
|
[
"python",
"python-3.x"
] |
Create a Ansible dictionary which keeps order
| 39,501,901 |
<p>How could I create dictionary with order?</p>
<p>I have dictionary as </p>
<pre><code>vars:
myDict:
Bob: 30
Alice: 20
</code></pre>
<p>How could I keep <code>"Bob"</code> in front of <code>"Alice"</code>? Ansible orders this map for me based on key letters</p>
| 0 |
2016-09-15T01:23:59Z
| 39,504,343 |
<p>There is no way to do this. Please, search for "python dict order".</p>
<p>You can only replace your original dict with a list:</p>
<pre><code>myListofDict:
- key: Bob
value: 30
- key: Alice
value: 20
</code></pre>
| 0 |
2016-09-15T06:27:21Z
|
[
"python",
"ansible"
] |
How to automatically input using python Popen and return control to command line
| 39,501,950 |
<p>I have a question regarding subprocess.Popen .I'm calling a shell script and provide fewinputs. After few inputs ,I want user running the python script to input.</p>
<p>Is it possible to transfer control from Popen process to command line.</p>
<p>I've added sample scripts</p>
<p>sample.sh</p>
<pre><code>echo "hi"
read input_var
echo "hello" $input_var
read input_var1
echo "Whats up" $input_var1
read input_var2
echo "Tell something else" $input_var2
</code></pre>
<p>test.py</p>
<pre><code>import os
from subprocess import Popen, PIPE
p=Popen([path to sample.sh],stdin=PIPE)
#sample.sh prints asks for input
p.stdin.write("a\n")
#Prompts for input
p.stdin.write("nothing much\n")
#After the above statement ,User should be able to prompt input
#Is it possible to transfer control from Popen to command line
</code></pre>
<p>Output of the program python test.py </p>
<pre><code>hi
hello a
Whats up b
Tell something else
</code></pre>
<p>Please suggest if any alternate methods available to solve this</p>
| 0 |
2016-09-15T01:33:04Z
| 39,519,093 |
<p>As soon as your last <code>write</code> is executed in your python script, it will exit, and the child shell script will be terminated with it. You request seems to indicate that you would want your child shell script to keep running and keep getting input from the user. If that's the case, then <code>subprocess</code> might not be the right choice, at least not in this way. On the other hand, if having the python wrapper still running and feeding the input to the shell script is enough, then you can look at something like this:</p>
<pre><code>import os
from subprocess import Popen, PIPE
p=Popen(["./sample.sh"],stdin=PIPE)
#sample.sh prints asks for input
p.stdin.write("a\n")
#Prompts for input
p.stdin.write("nothing much\n")
# read a line from stdin of the python process
# and feed it into the subprocess stdin.
# repeat or loop as needed
line = raw_input()
p.stdin.write(line+'\n')
# p.stdin.flush() # maybe not needed
</code></pre>
<p>As many might cringe at this, take it as a starting point. As others have pointed out, stdin/stdout interaction can be challenging with subprocesses, so keep researching.</p>
| 1 |
2016-09-15T19:40:03Z
|
[
"python",
"shell",
"command-line"
] |
Comparing dates in template Django
| 39,501,953 |
<p>I have two dates in a template that I need to compare in an if statement.</p>
<p>Date1 is from the created field of a data element {{ endjob.created|date:"Y-m-d" }} that is displayed as 2016-09-12</p>
<p>Date2 if from an array {{ pay_period.periods.0.0 }} that is displayed as 2016-09-04</p>
<p>Therefore I am trying to ask to display information only if Date1 >= Date2 but I do not get any data.</p>
<p>Can you help me with how to clash dates in templates in Django</p>
<p>This is my code:</p>
<pre><code><tbody>
{% for endjob in endjob %}
{% if endjob.created|date:"Y-m-d" >= pay_period.periods.0.0 %}
<tr>
<td><a href="{{ endjob.get_absolute_url }}" title="Goto Form">{{ endjob.event.name }}</a><br /></td>
<td>{{ endjob.event.job_no}} <br /></td>
<td>{{ endjob.event.job_type}} <br /></td>
<td>{{ endjob.code }} <br /></td>
<td>{{ endjob.crewid }}<br /></td>
<td>{{ endjob.workers }}<br /></td>
<td>{{ endjob.created|user_tz:user|date:"M j, Y" }}<br /></td>
</tr>
{% endif %}
{% endfor %}
</code></pre>
<p></p>
| 0 |
2016-09-15T01:33:54Z
| 39,502,426 |
<p>You are probably comparing two different data types which is why you are not getting anything. By doing <code>endjob.created|date:"Y-m-d"</code>,you are converting <code>endjob.created</code> to a string. Yes, <code>{{ pay_period.periods.0.0 }}</code> is displayed as the string '2016-09-04'. That is what the <code>{{ }}</code> thing does. However in the expression <code>endjob.created|date:"Y-m-d" >= pay_period.periods.0.0</code>, you are comparing a string VS the original data type of <code>pay_period.periods.0.0</code>.</p>
<p>To solve this, just make sure the datatypes match upon comparison. You can probably get away with <code>endjob.created|date:"Y-m-d" >= pay_period.periods.0.0|date:"Y-m-d"</code>, but I do not recommend it. Unless there is a very good reason you must do it this way, I suggest doing the comparison elsewhere other than on the template level, and then pass a boolean or call a boolean attribute instead like <a href="http://stackoverflow.com/a/3798865/4284628">so</a>.</p>
| 0 |
2016-09-15T02:49:50Z
|
[
"python",
"django"
] |
python making a live output of cpu usage
| 39,501,982 |
<p>So I would like to make a python program that displays the computers cpu usage in real time. So far I am using the psutil module to find cpu usage but I'm not sure how to represent the output visualy.</p>
<pre><code>import psutil
x=(2)
while x>0:
cpu = psutil.cpu_percent(interval=1, percpu=False)
print(cpu)
</code></pre>
<p>I was wondering if anyone had any ideas on how i could display the results.</p>
| -1 |
2016-09-15T01:38:29Z
| 39,502,386 |
<p>tkinter is a simple gui package that comes bundled with python. You could use that.</p>
<p>Or you could <code>sys.stdout.write</code> to print the result without a <code>\n</code> every second or so, with <code>\r</code> at the beginning to bring the character cursor to the beginning of the line. This would make a refreshing single line terminal display.</p>
| 0 |
2016-09-15T02:42:04Z
|
[
"python",
"psutil"
] |
How to create a new numpy array from a calculation of elements within an existing numpyarray
| 39,502,021 |
<p>I'm a Python and Numpy newbie...and I'm stuck. I'm trying to create a new numpy array from the log returns of elements in an existing numpy array (i.e. new array = old array(with ln(x/x-1)). I was not using Pandas dataframe because I plan to incorporate the correlations of the returns (i.e. "new array) into a large monte carlo simulation. Open to suggestions if this is not the right path.</p>
<p>This is the closest result I found in stackflow search, but it is not working:
<a href="http://stackoverflow.com/questions/30087636/what-is-the-most-efficient-way-to-get-log-returns-in-numpy">What is the most efficient way to get log returns in numpy</a></p>
<p>My guess is that I need to pass in the elements of the existing array but I thought using arrays and functions within Numpy was the whole benefit of moving away from Pandas series and Python base code. Appreciate help and feedback!</p>
<p>code link(I'm new so stackflow won't let me embed images): <a href="http://i.stack.imgur.com/wkf56.png" rel="nofollow">http://i.stack.imgur.com/wkf56.png</a></p>
| 0 |
2016-09-15T01:44:23Z
| 39,502,040 |
<p>Numpy as <code>log</code> function, you can apply it directly to an array. The return value will be a new array of the same shape. Keep in mind that the input should be an array of positive values with <code>dtype == float</code>.</p>
<pre><code>import numpy
old_array = numpy.random.random(5.) * 10.
new_array = numpy.log(old_array / (old_array - 1.))
print type(old_array)
# <type 'numpy.ndarray'>
print old_array.dtype
# float64
print old_array
# [ 8.56610175 6.40508542 2.00956942 3.33666968 8.90183905]
print new_array
# [ 0.12413478 0.16975202 0.68839656 0.35624651 0.11916237]
</code></pre>
| 1 |
2016-09-15T01:46:56Z
|
[
"python",
"arrays",
"numpy"
] |
While statment loop in python
| 39,502,051 |
<p>I am learning python, and I am stuck in an infinite while loop in the following code.</p>
<pre><code>A = input("Hello what is your name? ")
D = input("What is today's date? ")
B = input("Did you have a good day [y/N]")
while B != "y" or B != "Y" or B != "N" or B != "n":
B = input("Did you have a good day [y/N]")
else:
if B == "Y" or B == "y":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a good day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
elif B == "N" or "n":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a bad day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
</code></pre>
<p>The problem happens when B is compared to see if it is equal to Y, y, N, or n
but it still no matter what input I give it for B sticks me into the while statement and keeps me there.</p>
| 0 |
2016-09-15T01:47:57Z
| 39,502,086 |
<p>The issue is that you are doing <code>while B != "y" or B != "Y" or B != "N" or B != "n":</code></p>
<p>With <code>or</code> it returns true if either of its options are true. So if B="N"
<code>b!="N" or b!=n"</code> is true because b still isn't "n"</p>
<p>You can solve this by replacing all the <code>or</code>s with <code>and</code>s to get this
<code>while B != "y" and B != "Y" and B != "N" and B != "n":</code></p>
| 0 |
2016-09-15T01:54:20Z
|
[
"python",
"while-loop"
] |
While statment loop in python
| 39,502,051 |
<p>I am learning python, and I am stuck in an infinite while loop in the following code.</p>
<pre><code>A = input("Hello what is your name? ")
D = input("What is today's date? ")
B = input("Did you have a good day [y/N]")
while B != "y" or B != "Y" or B != "N" or B != "n":
B = input("Did you have a good day [y/N]")
else:
if B == "Y" or B == "y":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a good day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
elif B == "N" or "n":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a bad day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
</code></pre>
<p>The problem happens when B is compared to see if it is equal to Y, y, N, or n
but it still no matter what input I give it for B sticks me into the while statement and keeps me there.</p>
| 0 |
2016-09-15T01:47:57Z
| 39,502,093 |
<p>The problem is here:</p>
<pre><code>while B != "y" or B != "Y" or B != "N" or B != "n":
</code></pre>
<p><code>B</code> is <em>always</em> not equal to one of those. If it's "y" it is not equal to the other three, and so on. And since you are using <code>or</code> to combine these conditions, the loop continues if any one is true, which, as we've seen, is always the case.</p>
<p>Rewrite using <code>and</code>:</p>
<pre><code>while B != "y" and B != "Y" and B != "N" and B != "n":
</code></pre>
<p>Or apply DeMorgan's law (factor the <code>not</code> out of the expression and swap <code>and</code>/<code>or</code>):</p>
<pre><code>while not (B == "y" or B == "Y" or B == "N" or B == "n"):
</code></pre>
<p>Or best of all, write it the Python way:</p>
<pre><code>while B.lower() not in "yn":
</code></pre>
<p>(This also accepts an empty answer, which according to your prompt is equivalent to "N". To handle this, just convert your <code>elif</code> to a plain <code>else</code>, without a condition.)</p>
| 2 |
2016-09-15T01:55:41Z
|
[
"python",
"while-loop"
] |
While statment loop in python
| 39,502,051 |
<p>I am learning python, and I am stuck in an infinite while loop in the following code.</p>
<pre><code>A = input("Hello what is your name? ")
D = input("What is today's date? ")
B = input("Did you have a good day [y/N]")
while B != "y" or B != "Y" or B != "N" or B != "n":
B = input("Did you have a good day [y/N]")
else:
if B == "Y" or B == "y":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a good day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
elif B == "N" or "n":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a bad day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
</code></pre>
<p>The problem happens when B is compared to see if it is equal to Y, y, N, or n
but it still no matter what input I give it for B sticks me into the while statement and keeps me there.</p>
| 0 |
2016-09-15T01:47:57Z
| 39,502,095 |
<p>This line</p>
<pre><code>elif B == "N" or "n":
</code></pre>
<p>Should be</p>
<pre><code>elif B == "N" or B == "n":
</code></pre>
<p>You should use condition, simply <code>"n"</code> (non empty string) means <code>true</code></p>
| 0 |
2016-09-15T01:55:49Z
|
[
"python",
"while-loop"
] |
While statment loop in python
| 39,502,051 |
<p>I am learning python, and I am stuck in an infinite while loop in the following code.</p>
<pre><code>A = input("Hello what is your name? ")
D = input("What is today's date? ")
B = input("Did you have a good day [y/N]")
while B != "y" or B != "Y" or B != "N" or B != "n":
B = input("Did you have a good day [y/N]")
else:
if B == "Y" or B == "y":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a good day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
elif B == "N" or "n":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a bad day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
</code></pre>
<p>The problem happens when B is compared to see if it is equal to Y, y, N, or n
but it still no matter what input I give it for B sticks me into the while statement and keeps me there.</p>
| 0 |
2016-09-15T01:47:57Z
| 39,502,099 |
<p>Lets use a simplified version of your while loop.</p>
<pre><code>while B != "Y" or B != "y":
# ...
</code></pre>
<p>There is no way that this will ever evaluate to <code>False</code>.</p>
<p>If B was set to <code>Y</code> then <code>B != "Y"</code> would be <code>False</code>, but <code>B != "y"</code> would be <code>True</code>.</p>
<p>I think, in this case, it might be cleaner to do something like</p>
<pre><code>while B not in ["y", "Y", "n", "N"]:
# ...
</code></pre>
<p>Which will then repeat until the input is one of the characters in your list.</p>
<p><em>EDIT: Some other answers have suggested using <code>while B not in "yYnN"</code> or equivalents. This works here because all of your expected responses are one character. If you decide later to accept <code>"yes"</code> as a response, then you will have to use a list like I have shown above.</em></p>
| 1 |
2016-09-15T01:56:12Z
|
[
"python",
"while-loop"
] |
While statment loop in python
| 39,502,051 |
<p>I am learning python, and I am stuck in an infinite while loop in the following code.</p>
<pre><code>A = input("Hello what is your name? ")
D = input("What is today's date? ")
B = input("Did you have a good day [y/N]")
while B != "y" or B != "Y" or B != "N" or B != "n":
B = input("Did you have a good day [y/N]")
else:
if B == "Y" or B == "y":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a good day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
elif B == "N" or "n":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a bad day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
</code></pre>
<p>The problem happens when B is compared to see if it is equal to Y, y, N, or n
but it still no matter what input I give it for B sticks me into the while statement and keeps me there.</p>
| 0 |
2016-09-15T01:47:57Z
| 39,502,176 |
<p>This is the simplest solution!</p>
<pre><code>while B not in "YNyn":
</code></pre>
| 0 |
2016-09-15T02:06:36Z
|
[
"python",
"while-loop"
] |
pypyodbc execute delete query error "Function sequence error"
| 39,502,054 |
<p>I was able to execute the delete SQL query in Python with pypyodbc as below</p>
<pre><code>cur.execute("delete from table_a where a ='a';").commit()
</code></pre>
<p>However, I failed to run the delete SQL with a subquery</p>
<pre><code>cur.execute("delete from table_a where a in ( select a from table_b );").commit()
</code></pre>
<p>will return </p>
<pre><code>pypyodbc.Error: ('HY010', '[HY010] [unixODBC][Driver Manager]Function sequence error')
</code></pre>
<p>How could I run a delete SQL with subquery?</p>
| 0 |
2016-09-15T01:48:16Z
| 39,520,923 |
<p>The cause of this issue is pypyodbc not work with the delete command that actually delete nothing.</p>
<p>If I run "delete from table_a where a ='a';" twice, first time it will success and second time return error.</p>
<p>To run delete command with subquery, I need to check whether subquery really have records.</p>
| 0 |
2016-09-15T21:54:53Z
|
[
"python",
"sql",
"vertica",
"pypyodbc"
] |
in Python, is there a way to break a wrapping, centered text prhase so that there is not a single word left hanging under a long string?
| 39,502,057 |
<p>in Python, is there a way to break a wrapping, centered text prhase so that there is not a single word left hanging under a long string?</p>
<p>Example, assuming this is centered:</p>
<p>**West Dakota Department of Fish and </p>
<pre><code> Game**
</code></pre>
<p>The word "Game" is short, and the string above is long. Does not look good as a header for a website. Would like a method to instead display the following:</p>
<p>**West Dakota Department</p>
<p>of Fish and Game**</p>
<p>Maybe using javascript?</p>
| 0 |
2016-09-15T01:49:01Z
| 39,502,185 |
<p>a couple of things, you could get fancy and parse the length of the longest sub-string as well rather than specifying the format width (eg. ^20) in the centering portion of the expression</p>
<pre><code>>>> import textwrap
>>> a = "West Dakota Department of Fish and Game"
>>> wdth = int(len(a)/2)
>>> args = textwrap.wrap(a, wdth)
>>> print(("{!s:^20}\n"*len(args)).format(*args))
West Dakota
Department of Fish
and Game
</code></pre>
| 0 |
2016-09-15T02:07:55Z
|
[
"python"
] |
Use strings in a list as variable names in Python
| 39,502,079 |
<p>I have a list of string elements like <code>user_contract = ['ZNZ6','TNZ6','ZBZ6']</code></p>
<p>I have a data set which has nested list structure like <code>data = [[1,2,3],[4,5,6],[7,8,9]]</code></p>
<p>I want to assign each of the <code>user_contract</code> strings as variable names for each of the <code>data</code> nested list, in the respective order. </p>
<p>I know I can do this manually by typing <code>ZNZ6, TNZ6, ZBZ6 = data</code>. I don't think this is flexible enough, and I would have to manually change this line every time I change the names in <code>user_contract</code>.</p>
<p>Is there a way where I can make use of the <code>user_contract</code> variable to assign data to each of its elements?</p>
| 0 |
2016-09-15T01:52:47Z
| 39,502,114 |
<p>Please try if this code can help you. </p>
<pre><code>user_contract = ['ZNZ6','TNZ6','ZBZ6']
data = [[1,2,3],[4,5,6],[7,8,9]]
dictionary = dict(zip(user_contract, data))
print(dictionary)
</code></pre>
<p>It creates a dictionary from the two lists and prints it:</p>
<pre><code>python3 pyprog.py
{'ZBZ6': [7, 8, 9], 'ZNZ6': [1, 2, 3], 'TNZ6': [4, 5, 6]}
</code></pre>
| 0 |
2016-09-15T01:59:02Z
|
[
"python",
"list"
] |
Use strings in a list as variable names in Python
| 39,502,079 |
<p>I have a list of string elements like <code>user_contract = ['ZNZ6','TNZ6','ZBZ6']</code></p>
<p>I have a data set which has nested list structure like <code>data = [[1,2,3],[4,5,6],[7,8,9]]</code></p>
<p>I want to assign each of the <code>user_contract</code> strings as variable names for each of the <code>data</code> nested list, in the respective order. </p>
<p>I know I can do this manually by typing <code>ZNZ6, TNZ6, ZBZ6 = data</code>. I don't think this is flexible enough, and I would have to manually change this line every time I change the names in <code>user_contract</code>.</p>
<p>Is there a way where I can make use of the <code>user_contract</code> variable to assign data to each of its elements?</p>
| 0 |
2016-09-15T01:52:47Z
| 39,502,116 |
<p>You can use a dictionary comprehension to assign the values:</p>
<pre><code>myvars = {user_contract[i]: data[i] for i in len(user_contract}
</code></pre>
<p>Then you can access the values like so</p>
<pre><code>myvars['TNZ6']
> [1, 2, 3]
</code></pre>
| 0 |
2016-09-15T01:59:17Z
|
[
"python",
"list"
] |
Use strings in a list as variable names in Python
| 39,502,079 |
<p>I have a list of string elements like <code>user_contract = ['ZNZ6','TNZ6','ZBZ6']</code></p>
<p>I have a data set which has nested list structure like <code>data = [[1,2,3],[4,5,6],[7,8,9]]</code></p>
<p>I want to assign each of the <code>user_contract</code> strings as variable names for each of the <code>data</code> nested list, in the respective order. </p>
<p>I know I can do this manually by typing <code>ZNZ6, TNZ6, ZBZ6 = data</code>. I don't think this is flexible enough, and I would have to manually change this line every time I change the names in <code>user_contract</code>.</p>
<p>Is there a way where I can make use of the <code>user_contract</code> variable to assign data to each of its elements?</p>
| 0 |
2016-09-15T01:52:47Z
| 39,502,764 |
<p>You can use <code>exec</code> to evaluate expressions and assign to variables dynamically:</p>
<pre><code>>>> names = ','.join(user_contract)
>>> exec('{:s} = {:s}'.format(names, str(data)))
</code></pre>
| 0 |
2016-09-15T03:39:17Z
|
[
"python",
"list"
] |
Gmail API messages.modify 40x slower than IMAP?
| 39,502,142 |
<p>I'm creating an app to move messages around in a user's inbox. Currently I'm using the Gmail API to do so, but I've noticed that making requests to the API is markedly slower than using IMAP. </p>
<p>The method is straightforward: I'm sending a batch of modify requests to change the labels on a group of emails in order to move them around. My message throughput using the Gmail API is 3.3 messages/second. For comparison, IMAP throughput is 130 messages/second.</p>
<p>Here's how I'm currently using BatchHttpRequests:</p>
<pre><code>batch = BatchHttpRequest()
for gmailId in gmailIds:
batch.add(self.service.users().messages().modify(userId=self.user.email, id=gmailId, body=labels))
try:
batch.execute()
except errors.HttpError, error:
log_this_error(self.user.email, error.resp.status)
</code></pre>
<p>and here is my IMAP code that accomplishes the same task:</p>
<pre><code># imap_conn is the user's authed connection
status, count = imap_conn.select(oldMailboxLabel)
if status == "OK":
count = int(count[0])
if count > 0:
messageNumbers = range(1, count + 1)
messageNumbers = ",".join(map(str, messageNumbers))
imap_conn.copy(messageNumbers, newMailboxLabel)
imap_conn.close()
imap_conn.delete(oldMailboxLabel)
else:
imap_conn.close()
else:
count = 0
</code></pre>
<p>I'm already batching and gzipping my requests, and I've tried using fields to limit the amount of information that is returned. All of which is suggested on their <a href="https://developers.google.com/gmail/api/guides/performance" rel="nofollow">performance tips</a> page. I'm struggling to understand why the requests take so long to complete. Any suggestions would be greatly appreciated!</p>
| 1 |
2016-09-15T02:02:31Z
| 39,519,295 |
<p>Reading through the GMail API you seem to be doing it "right". I'm going to guess that because GMail is itself a mail client the GMail API is targeted at writing toy mail clients while IMAP is better designed for the efficient bulk work of a fully functional mail client.</p>
<p>If you're moving <em>every</em> message from an old label to a new label, perhaps instead <a href="https://developers.google.com/gmail/api/v1/reference/users/labels/update" rel="nofollow">rename the label using Users.labels.update</a>?</p>
<p>If not, you can reduce the number of requests by doing by <a href="https://developers.google.com/gmail/api/v1/reference/users/threads/modify" rel="nofollow">by thread</a> instead of by message.</p>
<p>Or just use IMAP.</p>
| 0 |
2016-09-15T19:52:22Z
|
[
"python",
"imap",
"gmail-api"
] |
Python Turtle - Is it possible to prevent the crash at the end
| 39,502,170 |
<p>this is my code. I am using the turtle module to just write some text on the screen for a project for school. But whenever I do this, the program crashes/stops responding and I was wondering if it is possible to prevent this from happening.</p>
<pre><code>import turtle
screen = turtle.Screen()
screen.screensize(500, 500, "pink")
drawingpen = turtle.Turtle()
drawingpen.color("black")
drawingpen.penup()
drawingpen.setposition(-300, -300)
drawingpen.pendown()
drawingpen.pensize(3)
for side in range(4):
drawingpen.forward(600)
drawingpen.left(90)
drawingpen.hideturtle()
y = 243
for x in range(10):
drawingpen.penup()
drawingpen.color("black")
drawingpen.setposition(0, y)
drawingpen.pendown()
drawingpen.write("Test", False, align="center", font=("Arial", 18, "normal"))
drawingpen.hideturtle()
y = y - 57
</code></pre>
| 0 |
2016-09-15T02:06:00Z
| 39,502,226 |
<p>Your code hasn't crashed, it just ran out of code to process. The code that is there is working fine and as expected.</p>
<p>To see what I mean add:</p>
<pre><code>print("END") #Python 3
print "END" #Python 2
</code></pre>
<p>to the end of your code. You will see the console prints the word "END" after your text is finished printing.
But a nicer way might be to add:</p>
<pre><code>screen.exitonclick()
</code></pre>
<p>to the end. This will close the window when you click on it.</p>
| 2 |
2016-09-15T02:14:03Z
|
[
"python",
"python-2.7"
] |
Make executable symbolic link in Python?
| 39,502,197 |
<p>I have a file called <code>client.py</code>. I created a symbolic link called <code>incro</code> using </p>
<pre><code>ln -s client.py incro
</code></pre>
<p>How do I make this script executable and move it to my bin (I'm on Linux using Ubuntu, with a bash terminal), under the name of <code>incro</code>? So that I will be able to run</p>
<pre><code>incro
</code></pre>
<p>I have the proper sha-bang. What else do I need to do?</p>
| 0 |
2016-09-15T02:09:13Z
| 39,502,237 |
<p>In Linux to make a file executable you will need to set the file with the following command:</p>
<pre><code>chmod +x [filename]
</code></pre>
<p>This will make the file executable to root, user, and group owners.</p>
<p>To make the file executable from any directory you will need to make sure that the directory is listed in your PATH. </p>
<pre><code>echo $PATH
</code></pre>
<p>will show you which path you should move your file or symbolic link to. There are also ways to add any path to the PATH but you will likely find convention to add your executables to /usr/local/bin. Just validate that it is in your path using the command above.</p>
| 1 |
2016-09-15T02:16:14Z
|
[
"python",
"bash",
"bin"
] |
Make executable symbolic link in Python?
| 39,502,197 |
<p>I have a file called <code>client.py</code>. I created a symbolic link called <code>incro</code> using </p>
<pre><code>ln -s client.py incro
</code></pre>
<p>How do I make this script executable and move it to my bin (I'm on Linux using Ubuntu, with a bash terminal), under the name of <code>incro</code>? So that I will be able to run</p>
<pre><code>incro
</code></pre>
<p>I have the proper sha-bang. What else do I need to do?</p>
| 0 |
2016-09-15T02:09:13Z
| 39,502,262 |
<p>Put the link in your <code>bin</code> directory, not the current directory:</p>
<pre><code>ln -s $PWD/client.py ~/bin/incro
</code></pre>
<p>You should also have <code>~/bin</code> in your <code>$PATH</code> so that you can run programs that are in there.</p>
<p>And if the script isn't already executable, add that:</p>
<pre><code>chmod +x client.py
</code></pre>
| 1 |
2016-09-15T02:20:38Z
|
[
"python",
"bash",
"bin"
] |
Make executable symbolic link in Python?
| 39,502,197 |
<p>I have a file called <code>client.py</code>. I created a symbolic link called <code>incro</code> using </p>
<pre><code>ln -s client.py incro
</code></pre>
<p>How do I make this script executable and move it to my bin (I'm on Linux using Ubuntu, with a bash terminal), under the name of <code>incro</code>? So that I will be able to run</p>
<pre><code>incro
</code></pre>
<p>I have the proper sha-bang. What else do I need to do?</p>
| 0 |
2016-09-15T02:09:13Z
| 39,513,585 |
<p>By default symbolic links follow file permissions so you don't make symbolic link executable, but simply make your client.py file executable.</p>
<p>Command:</p>
<pre><code>ln -s client.py incro
</code></pre>
<p>Creates relative symbolic link so you can't simply copy or move it to other directory.
To make link movable create link to file with absolute path. For example:</p>
<pre><code>ln -s /home/guest/client.py incro
</code></pre>
<p>Or simply create link directly in your <code>bin</code> directory.</p>
| 1 |
2016-09-15T14:22:51Z
|
[
"python",
"bash",
"bin"
] |
lambda python function with external library psycopg2 - No module named psycopg2
| 39,502,265 |
<p>Error Message - No module named psycopg2<br>
File used in zip - <a href="https://github.com/jkehler/awslambda-psycopg2" rel="nofollow">https://github.com/jkehler/awslambda-psycopg2</a> <br>
Code Snippet -<br></p>
<pre><code> #!/usr/bin/python
import psycopg2
import sys
import pprint
import datetime
def lambda_handler(event, context):
#Connect to RedShift
conn_string = "dbname='XXXX' port='5439' user='XXX' password='XXXX' host='XXXXXXXXXXXX'";
conn = psycopg2.connect(conn_string);
cursor = conn.cursor();
cursor.execute("begin transaction");
cursor.execute("truncate table XXXX");
cursor.execute("truncate table XXXX");
cursor.execute("truncate table XXXX");
cursor.execute("delete from XXXX");
cursor.execute("insert into XXXX");
cursor.execute("truncate table XXXX");
cursor.execute("truncate table XXXX");
cursor.execute("truncate table XXXX");
cursor.execute("end transaction");
conn.commit();
conn.close();
</code></pre>
<p><br>Extracted and Copied psycopg2 in windows into my AWS Lambda zip package along-with my python file and site packages.<br>
Did I miss anything?</p>
<p><strong>EDIT</strong>
<br>Recreated the package with zipping the file on Amazon Linux. Still same error.</p>
| 1 |
2016-09-15T02:21:19Z
| 39,502,387 |
<p>psycopg2 is a compiled module. Copying the Windows version won't work because Lambda runs on top of Amazon Linux. According to <a href="https://aws.amazon.com/blogs/compute/running-executables-in-aws-lambda/" rel="nofollow">the docs</a> it is possible to run native executables and libraries on lambda, but you'll need to find a way to build psycopg2 for that platform and statically link all its libraries or bundle the dynamic libs. This is likely to be challenging unless you're familiar with the C and Python toolchain or someone else has already done it for you.</p>
| 1 |
2016-09-15T02:42:17Z
|
[
"python",
"python-2.7",
"lambda",
"aws-lambda",
"amazon-lambda"
] |
Regular expression to replace all occurrences of U.S
| 39,502,301 |
<p>I'm trying to write a regular expression to replace all occurrences of U.S. . Here's what I thought would work.</p>
<pre><code>string = re.sub(r'\bU.S.\b', 'U S ', string)
</code></pre>
<p>When I run this it only finds the first occurrence. Why is this and how can I resolve this issue. Thanks </p>
| 0 |
2016-09-15T02:27:37Z
| 39,502,369 |
<p>The problem is that <code>.</code> has special meaning in regular expressions (it matches any character), so it needs to be escaped.</p>
<pre><code>string = re.sub(r'\bU\.S\.', 'U S ', string)
</code></pre>
<p>Also, you shouldn't use <code>\b</code> after <code>.</code>. <code>\b</code> matches between a word and non-word character. Since <code>.</code> is a non-word character, it will only match if the <code>.</code> is followed by a word character, e.g. <code>U.S.foo</code>, but not <code>U.S. currency</code> because the <code>.</code> is followed by space, which isn't a word character.</p>
<p><a href="http://ideone.com/ZPtTDc" rel="nofollow">DEMO</a></p>
| 2 |
2016-09-15T02:38:23Z
|
[
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.