Adding Folium Popup Information to table beside map - python

I am building a map website using Pandas, Django and Folium, with popups displaying information about servers in locations.
I am looking to include all the information that would display on a popup beside the map in a table.
Here is an example popup
I want it in a table like this table view
Currently the table is a for loop iterating over a pandas dataframe. But that displays each row in the dataframe, not information about the specific marker, like the popup does.
The code look like:
locations = Location.objects.values()
loc_data = pd.DataFrame(locations)
for index, location_info in loc_data.iterrows():
# Popup design through Iframe - html variable contains basic html to redesign the popup
html=f"""
<h1>{location_info['hostname']}</h1>
<p>Node Attributes:
<ul>
<li>Structure Name: {location_info["structurename"]}</li>
<li>Domain: {location_info["domain"]}</li>
<li>IP Address: {location_info["ip"]}</li>
<li>Persona: {location_info["personas"]}</li>
</ul>
{location_info["cube"]}
</p>
Login to cube
"""
# Initialise the iframe as a variable and set the popup to be the iframe
iframe = folium.IFrame(html=html, width=350, height=270)
popup = folium.Popup(iframe, max_width=2650)
# Add Markers to the map based on criteria
if location_info["cube"] == "Industrial Cube North":
folium.Marker([location_info["latitude"], location_info["longitude"]], popup=popup, icon=folium.Icon(color='darkred'), tooltip=f'''{location_info["hostname"]}''').add_to(m)
elif location_info["cube"] == "Industrial Cube South":
folium.Marker([location_info["latitude"], location_info["longitude"]], popup=popup, icon=folium.Icon(color='green'), tooltip=f'''{location_info["hostname"]}''').add_to(m)
m=m._repr_html_() #updated
context = {'map': m, 'loc_data': loc_data}
return render(request, 'maps/map.html', context)
This is my html Django template: template
I think it needs some sort of on click event listener to display? Is this possible? Does anyone have any pointers?
EDIT - I have tried passing popup to context but its not iterable.. I also tried iframe but it displays a connection error screen

Related

Sphinx: button inside literalinclude blocks

I have a desktop application and a user guide written in Sphinx. The API is explained with the use of code blocks that are imported with literalinclude blocks.
What I would like to have is a button inside or close to each code block. The button is intended for opening the respective example in our application.
What I have achieved so far (see below) is a button above the code block, that I have to include manually every time I use a literalinclude statement.
How can I put the button inside the code block rather than above?
A particularly beautiful result would be a transparent button like Chris Holdgraf's Sphinx copybutton. But at the moment I would already be happy to have the button as it is located in the top right corner of the code block.
Minimal example of how things are right now
The button is rendered above the code block. But I want to have it inside (at the top right corner).
Folder structure:
conf.py
index.rst
source_file.py
load_source.py
Content of index.rst:
:load_example:`source_file.py`
.. literalinclude:: source_file.py
Content of source_file.py:
import numpy as np
print "hello extension"
for i in range(3):
print np.sin(i)
Content of load_souce.py extension file:
from docutils import nodes
# HTML code to generate button
button_raw = """
<script>
function openScriptFunction() {
callBackHandler.openScript("%s");
}
</script>
<button onclick="openScriptFunction()">Load %s</button>
"""
def setup(app):
app.add_role('load_example', load_example_script)
def load_example_script(name, rawtext, text, lineno, inliner, options={}, content=[]):
node = nodes.raw(rawsource = button_raw%(text, text), text = button_raw%(text, text), format="html")
return [node], []
This extension is included in the conf.py by extensions = ['load_source']

How can I hide code and rerun all cells in a jupyter notebook?

I'd like to add some sort of functionality at the beginning of a Jupyter Notebook that hides / shows all cells and reruns all cells. What I'd like to end up with is a set of charts that are refreshed when all cells are re-run.
The details and what I've tried:
The post IPython - Run all cells below from a widget shows how you can add a button to rerun all cells below. And the post How to hide code from cells in ipython notebook visualized with nbviewer?. With this setup in two different cells I end up with this:
When the cells are collapsed it looks like this:
And this works pretty well, but I'm just really curious if it's possible to format the buttons so that they look the same. And maybe it's possible to align them as output from the same cell? I've tried to do just that by having the two snippets in the same cell, but now it seems that the Hide button is overwritten by the Refresh button:
Snippet 1:
from IPython.display import HTML
HTML('''<script>
function code_toggle() {
if (code_shown){
$('div.input').hide('500');
$('#toggleButton').val('Show code')
} else {
$('div.input').show('500');
$('#toggleButton').val('Hide code')
}
code_shown = !code_shown
}
$( document ).ready(function(){
code_shown=false;
$('div.input').hide()
});
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show code"></form>''')
from IPython.display import Javascript, display
from ipywidgets import widgets
def run_all(ev):
display(Javascript('IPython.notebook.execute_cells_below()'))
button = widgets.Button(description="Refresh")
button.on_click(run_all)
display(button)
And now I end up with this:
Output 1:
Does anyone know how to make this a bit more elegant?
I really hope someone is able to provide a better answer, but having tried and failed for a couple of hours, I've found this:
By simply mixing a few parts of the two snippets in the question, I'm able to set up a Refresh button in the same format as the Hide Code buttion:
Ouptput / Notebook View:
But this still requiers two code snippets in two different cells, as well as some test code in a third cell:
Cell / snippet 1:
from IPython.display import HTML
HTML('''<script>
function code_toggle() {
if (code_shown){
$('div.input').hide('500');
$('#toggleButton').val('Display code')
} else {
$('div.input').show('500');
$('#toggleButton').val('Hide Code')
}
code_shown = !code_shown
}
$( document ).ready(function(){
code_shown=false;
$('div.input').hide()
});
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Display code"></form>''')
Cell / snippet 2:
HTML('''<script>
</script>
<form action="javascript:IPython.notebook.execute_cells_below()"><input type="submit" id="toggleButton" value="Refresh"></form>''')
Cell / snippet 3:
try: x
except NameError: x = None
if x is None:
x = 0
print(x)
else:
x = x + 1
print(x)
However, I'm still not able to display the two buttons beautifully side by side, and the display flickers when I hit Refresh.

Pagination in web2py

I have a web2py database with 20 entries and I would like to show only 5 entries per page.
My controller is-
def viewallposts():
if not request.vars.page:
redirect(URL(vars={'page':1}))
else:
page = int(request.vars.page)
start = (page-1)*5
end = page*5
user = auth.user_id
image=db().select(db.posts.ALL, orderby=~db.posts.created_on, limitby=(start,end))
return dict(user=user, image=image)
The next button in my .html file is -
<button><a href={{=URL(vars={'page':int(request.vars.page)+1})}}>Next</a></button>
But, I only see the first 5 entries and when I click next, it doesn't go to the next page. Where have I gone wrong?
The <button> in your View might be the issue. Try it this way:
<a class="btn btn-default" href="{{=URL(vars={'page':int(request.vars.page)-1})}}">Next</a>

Edit response logo in web2py

I am trying to edit the default logo to my own in my MODEL(menu.py).
The default code for the logo is:
response.logo = A(B('web',SPAN(2),'py'),XML('™ '), _class="brand", _href="http://www.web2py.com/")
How would I change this line to display my own logo? For instance, the url for the logo might be something like "http://www.web2py.com/init/static/images/logo_lb.png"
Just change the content of the anchor tag to include the image:
response.logo = A(IMG(_src=URL('static', 'images/logo_lb.png'),
_href=URL('default', 'index'))
Note, you don't really need to use response.logo at all. You can instead just put the relevant HTML directly in the layout.html view.

Calling function on unlike event of facebook

I have been calling a function to run a query in to the database on a like event of facebook like button on my python site .And it is working absolutely fine .
FB.Event.subscribe('edge.create', function(href, widget)
But the problem is I need to use a another query of update on unlike event of the facebook button.
<script>
FB.Event.subscribe('edge.create', function(href, widget) {
top.window.location = 'http://pydev.abc.com/surpriseme/';
});
</script>
<div class="suprise">
<div class="suprise_con">
<div class="fb-like" style="overflow:hidden;" data-href="https://www.facebook.com/VivaAviesta" data-send="false" data-layout="button_count" data-width="100" data-show-faces="false"></div>
<span style="margin-left:5px;"> Like Us to Reveal</span>
</div>
</div>
For the url surprise me I have added a functionin views :
def surpriseme(request):
if request.user.is_authenticated():
cursor = connection.cursor()
cursor.execute("INSERT "......." (name,facebook_id,category,user_id) VALUES ('Abcd',1,'',%s)",[request.user.id])
#return HttpResponse("success")
return redirect("/showroom/")
Can anyone help in calling another function at the unlike event?
Actually the thing is that the person who has not liked the face book button on our site will not be able to see few of the products and once he/she hits like button they can see the products.
Now what I need is if anyone again unlike the button will should not be able to see products , which is not working at the moment.
calll like this
<script type="text/javascript">
window.fbAsyncInit=function() {
FB.Event.subscribe('edge.remove', function(href, widget) {
top.window.location = '{{baseurl}}/surprisemeunlike/';
});
FB.Event.subscribe('edge.create', function(href, widget) {
top.window.location = '{{baseurl}}/surpriseme/';
var url = '{{baseurl}}/surpriseme/';
});
}
</script>
Ok I got the answer, there is another event fron facebook :
FB.Event.unsubscribe('edge.create', handleResponse);
We can call another function on this event .
<script>
FB.Event.unsubscribe('edge.create', function(href, widget) {
top.window.location = 'http://pydev.abc.com/surpriseunlike/';
});
</script>
and it is working fine for me now .
"Like Gating" isn't against the terms of service and is used by many brands. It worked well under FBML, but it isn't reliable for an actual lockdown on the current API options. Facebook only prohibits requiring a like for contest entries (unless you use an approved vendor to run the contest).
If you actually want to require people to "Like" , you should be using their Graph API and 'realtime updates' https://developers.facebook.com/docs/reference/api/realtime/ Your javascript function will only work if someone likes or unlikes on that same page. It won't handle people liking or unliking in other browser windows or different time periods, which undermines your intent.
But if someone Likes your page and then unlikes it - so what? They already saw your special content.

Categories