Animating circles getting clipped using D3.js with Ruby on Rails - ruby-on-rails-4

I am trying to animate some SVG circles across the entire body element of a webpage, but they seem to be getting clipped when they reach this line, <%= yield %> in the application.html.erb of the RoR app.
The application.html.erb looks like the following,
<!DOCTYPE html>
<html>
<head>
<title>KegCop</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<%= favicon_link_tag 'favicon.ico' %>
<%= render 'layouts/ie_shim' %>
</head>
<body>
<%= render 'layouts/nav' %>
<div id="container-fluid">
<%= render 'layouts/bubbles' %>
<%= yield %>
<%= render 'layouts/footer' %>
</div>
<%= render 'layouts/google_analytics' %>
<%= render 'layouts/beer_background' %>
<%= audio_tag("/audios/bottle-open.ogg", autoplay: true, controls: false) %>
</body>
</html>
And the D3.js script that animates the bubbles, _bubbles.html.erb
w = window.innerWidth,
h = window.innerHeight;
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
var circle = svg.selectAll("circle")
.data(d3.range(70).map(function(datum,interval) {
return {
x: interval*20,
y: 0,
dx: 5,
dy: -3 * (Math.random()+1),
mu: Math.random()*2
};
}))
.enter().append("svg:circle")
.attr("r", 2.5)
.attr("fill","blue")
.attr("opacity",".5");
var text = svg.append("svg:text")
.attr("x", 20)
.attr("y", 20);
var start = Date.now(),
frames = 0;
d3.timer(function()
{
// Update the FPS meter.
var now = Date.now(), duration = now - start;
text.text(~~(++frames * 1000 / duration));
if (duration >= 1000) frames = 0, start = now;
// Update the circle positions.
circle
.attr("cx", function(d) { d.x += Math.random()*3*Math.sin(Math.random()*3*d.x + Math.random()*10); if (d.x > w) d.x -= w; else if (d.x < 0) d.x += w; return d.x; })
.attr("cy", function(d) { d.y += d.dy ; if (d.y > h) d.y -= h; else if (d.y < 0) d.y += h; return d.y; })
.attr("r",function(d)
{
return (d.y < 100) ? d3.select(this).attr("r") : d.mu*500/d.y;
});
});
Update:
Below is what I would expect to see, but it is clipping off at the bottom of the form elements on the webpage I am working with.
http://jsfiddle.net/ipatch/4C8c8/8/

I ended up changing <div id="container-fluid"> to <div class="wrapper"> and changing the wrapper CSS style to position: absolute and now the "bubbles" / SVG circles are animating across the entire <body> element of the page.
The key was setting the wrapper class to a position of absolute.

Related

why do other charts on my webpage are not showing eventho there is no syntax error in PhP and charts.js?

I made a dashboard on my website that has 3 different visualization charts, the data is from my database, and the problem that I'm encountering is that the other two are not showing eventhough the first one shows itself. moreover, if I hide or remove the first chart, the second one appears, but the third one still doesn't show. refer to images below:
First Chart Shows the following two are not.
The second chart only shows itself when I delete the code of the first chart.
The 3rd chart is the same case as 2nd, needed to remove the first and second charts just to see the third one.
here is my code:
<!--CHARTS-->
<!--BAR CHART-->
<div class="container-fluid px-4">
<?php
// Attempt select query execution
try{
$barsql = "SELECT * FROM castro_rentals.unit";
$barresult = $pdo->query($barsql);
if($barresult->rowCount() > 0) {
$price = array();
$unit_no = array();
while($row = $barresult->fetch()) {
$price[] = $row["price"];
$unit_no[] = $row["unit_no"];
}
unset($barresult);
} else {
echo "No records matching your query were found.";
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $barsql. " . $e->getMessage());
}
// Close connection
unset($pdo);
?>
<div class="card mb-4">
<!--BAR CHART-->
<div class="card-header">
<i class="fas fa-chart-bar me-1"></i>
Unit Prices
</div>
<div class="card-body">
<canvas id="myBarChart" width="100%" height="50"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
//SETUP BLOCK
const price = <?php echo json_encode($price); ?>;
const unit_no = <?php echo json_encode($unit_no); ?>;
const data = {
labels: unit_no,
datasets: [{
label: 'Price',
data: price,
backgroundColor: ['rgba(57, 43, 90, .6)'],
borderColor:'rgb(57, 43, 90)',
borderWidth: 2
}]
};
//CONFIG BLOCK
const config = {
type: 'bar',
data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
//RENDER BLOCK
const myBarChart = new Chart(
document.getElementById('myBarChart'),
config
);
</script>
<div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div>
</div>
<div class="row">
<div class="col-lg-6">
<!--LINE CHART-->
<?php
include('config/dbcon.php');
// Attempt select query execution
try{
$linesql = "SELECT * FROM castro_rentals.payment";
$lineresult = $pdo->query($linesql);
if($lineresult->rowCount() > 0) {
$amount = array();
$paymentdate = array();
while($row = $lineresult->fetch()) {
$amount[] = $row["amount"];
$paymentdate[] = $row["paymentdate"];
}
unset($lineresult);
} else {
echo "No records matching your query were found.";
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $linesql. " . $e->getMessage());
}
// Close connection
unset($pdo);
?>
<div class="card mb-4">
<div class="card-header">
<i class="fas fa-chart-line me-1"></i>
Monthly Income
</div>
<div class="card-body">
<canvas id="myLineChart" width="100%" height="50"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
//SETUP BLOCK
const amount = <?php echo json_encode($amount); ?>;
const paymentdate = <?php echo json_encode($paymentdate); ?>;
const data = {
labels: paymentdate,
datasets: [{
label: 'Amount',
data: amount,
backgroundColor: ['rgba(57, 43, 90, .6)'],
borderColor:'rgb(57, 43, 90)',
borderWidth: 2
}]
};
//CONFIG BLOCK
const config = {
type: 'line',
data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
//RENDER BLOCK
const myLineChart = new Chart(
document.getElementById('myLineChart'),
config
);
</script>
<div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div>
</div>
</div>
<!--PIE CHART-->
<div class="col-lg-6">
<!--PIE CHART-->
<?php
include('config/dbcon.php');
// Attempt select query execution
try{
$piesql = "SELECT * FROM castro_rentals.property";
$pieresult = $pdo->query($piesql);
if($pieresult->rowCount() > 0) {
$propertyname = array();
$paymentdate = array();
while($row = $pieresult->fetch()) {
$propertyname[] = $row["propertyname"];
$propertytype[] = $row["propertytype"];
}
unset($pieresult);
} else {
echo "No records matching your query were found.";
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $piesql. " . $e->getMessage());
}
// Close connection
unset($pdo);
?>
<div class="card mb-4">
<div class="card-header">
<i class="fas fa-chart-pie me-1"></i>
# of Property Type
</div>
<div class="card-body">
<canvas id="myPieChart" width="100%" height="50"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
//SETUP BLOCK
const propertyname = <?php echo json_encode($propertyname); ?>;
const propertytype = <?php echo json_encode($propertytype); ?>;
const data = {
labels: propertytype,
datasets: [{
label: 'propertyname',
data: propertyname,
backgroundColor: ['rgba(57, 43, 90, .6)'],
borderColor:'rgb(57, 43, 90)',
borderWidth: 2
}]
};
//CONFIG BLOCK
const config = {
type: 'pie',
data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
//RENDER BLOCK
const myPieChart = new Chart(
document.getElementById('myPieChart'),
config
);
</script>
<div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div>
</div>
</div>
</div>
The only thing I tried to do is to play with the <div> before the <canvas> I thought it wouldn't show because of spacing and size problems but I tried modifying, removing, resizing them, it still didn't show.

googlecharts error- Invalid row type for row 0

I am gettting this below error when i try to draw a line graph. i dont understand where i am doing wrong
ReferenceError: CAE is not defined
[ "January 16",CAE,18],
Nationa...ers.jsp (line 11, col 36)
Error: Invalid row type for row 0
Here is my code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var theData = [ // Start of JavaScript data object
<%
Class.forName("oracle.jdbc.OracleDriver").newInstance();
String connectionURL = "someurl";
Connection connection = null;
connection = DriverManager.getConnection(connectionURL);
PreparedStatement ps = connection.prepareStatement("SELECT TRIM(TO_CHAR(order_date, 'Month')) ||' '|| TO_CHAR(order_date, 'yy') month, order_channel, total FROM ( SELECT order_date, order_channel, COUNT(*) total FROM order_channel WHERE order_date >= TO_DATE('01-Jan-2016', 'dd-Mon-yyyy') GROUP BY order_date, order_channel) ORDER BY TO_DATE(order_date), order_channel");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
%>
[ "<%= rs.getString(1)%>",<%= rs.getString(2)%>,<%= rs.getString(3)%>],
<%
};
// End of JavaScript object holding the data
%>
];
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:['corechart', 'Bar']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([['Month', 'OrderChannel', 'Total']].concat(theData), false);
var options = {
title: 'National Monthly Orders',
hAxis: {
title: 'Month of Orderdate'
},
vAxis: {
title: 'Distinct count'
},
legend:{position:'none'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1000px; height: 350px;"></div>
</body>
</html>
looks like the second column should be type: 'string'
try this...
["<%= rs.getString(1)%>", "<%= rs.getString(2)%>", <%= rs.getString(3)%>]
vs.
["<%= rs.getString(1)%>", <%= rs.getString(2)%>, <%= rs.getString(3)%>]

if statement within underscore loop

I'm trying to add this if statement in a loop in an underscore template:
<% _.each( looks, function( listItem, index ){ %>
<% if(_.contains(firstBatch, listItem.id)){ %>
<% if (index % 2 == 0) { %>
<div class="large-6 column overlay-col">
<% } else { %>
<div class=" column overlay-col">
<% } % %>
<% } %>
<% }) %>
Basically it's to detect if index is an even number, but I get this console error:
SyntaxError: missing : after property id
if (index % 2 === 0) {
what's wrong with code?
I think your syntax has a bozo on line 7:
<% } % %>
What's that extra percent?
This becomes apparent when you remove all the decoration around the function:
_.each( looks, function( listItem, index ){
if(_.contains(firstBatch, listItem.id)){
if (index % 2 == 0) {
<div class="large-6 column overlay-col">
} else {
<div class=" column overlay-col">
} %
}
})

Activeadmin Rails 4 TypeError: $(...).fullCalendar is not a function

Am using rails 4 in my application with active admin gem. i am using fullcalender to show the events.
my code is below index.html.erb
<br />
<div class="link_back">
<%= link_to "Back", meeting_rooms_path, class: "btn-sm btn-primary" %>
</div>
<br />
<%= render 'errors' %>
<p>
<%=link_to 'Create Event', new_event_url(meeting_room_id: params["meeting_room_id"]), :id => 'new_event' %>
</p>
<br />
<!-- <div>
<div class='calendar'></div>
</div> -->
<div>
<div id='calendar'>
</div>
</div>
<div id = "desc_dialog" class="dialog" style ="display:none;">
<div id = "event_desc">
</div>
<br/>
<br/>
<div id = "event_actions">
<span id = "edit_event"></span>
<span id = "delete_event"></span>
</div>
</div>
<div id = "create_event_dialog" class="dialog" style ="display:none;">
<div id = "create_event">
</div>
</div>
<script>
// page is now ready, initialize the calendar...
$('#new_event').click(function(event) {
event.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
beforeSend: function() {
$('#loading').show();
},
complete: function() {
$('#loading').hide();
},
success: function(data) {
$('#create_event').replaceWith(data['form']);
$('#create_event_dialog').dialog({
title: 'New Event',
modal: true,
width: 500,
close: function(event, ui) { $('#create_event_dialog').dialog('destroy') }
});
}
});
});
$('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
//defaultView: 'agendaWeek',
defaultView: 'month',
height: 500,
slotMinutes: 15,
loading: function(bool){
if (bool)
$('#loading').show();
else
$('#loading').hide();
},
events: "/events/get_events?meeting_room_id=<%= params[:meeting_room_id]%>",
timeFormat: 'h:mm t{ - h:mm t} ',
dragOpacity: "0.5",
eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc){
// if (confirm("Are you sure about this change?")) {
moveEvent(event, dayDelta, minuteDelta, allDay);
// }
// else {
// revertFunc();
// }
},
eventResize: function(event, dayDelta, minuteDelta, revertFunc){
// if (confirm("Are you sure about this change?")) {
resizeEvent(event, dayDelta, minuteDelta);
// }
// else {
// revertFunc();
// }
},
eventClick: function(event, jsEvent, view){
if ((<%= current_user.id %>) == event.user_id){
showEventDetails(event);
}
},
});
</script>
the same fullcalender i have used with normal rails 4 applicaiton its working fine.
but with activeadmin its throwing the javascript error as,
TypeError: $(...).fullCalendar is not a function
and the calender is not displaying in view
Because of this error am not able to continue pls help ..
You are not importing fullcalendar js and css files, add these lines
in app/assets/javascripts/active_admin.js.coffee
#= require fullcalendar
in app/assets/javascripts/active_admin.css.scss
#import "fullcalendar"

Groovy/Grails - Need to retrieve List index value

I need to retrieve the index position of each value in a list I have. I'm doing this so that I can display a gsp table with alternating row background colors. For example:
(list.indexVal % 2) == 1 ? 'odd' : 'even'
How can I get the index position number of each item in a Groovy list? Thanks!
According the documentation, the g:each tag in the gsp view allows the "status" variable
where grails store the iteration index in.
Example:
<tbody>
<g:each status="i" in="${itemList}" var="item">
<!-- Alternate CSS classes for the rows. -->
<tr class="${ (i % 2) == 0 ? 'a' : 'b'}">
<td>${item.id?.encodeAsHTML()}</td>
<td>${item.parentId?.encodeAsHTML()}</td>
<td>${item.type?.encodeAsHTML()}</td>
<td>${item.status?.encodeAsHTML()}</td>
</tr>
</g:each>
</tbody>
Any of g:each, eachWithIndex, or for loops can be used.
But, for this specific case, the index value is not needed. Using css pseudo-classes is recommended:
tr:nth-child(odd) { background: #f7f7f7; }
tr:nth-child(even) { background: #ffffff; }
If you still need to get the index, options are:
<g:each status="i" in="${items}" var="item">
...
</g:each>
<% items.eachWithIndex { item, i -> %>
...
<% } %>
<% for (int i = 0; i < items.size(); i++) { %>
<% def item = items[i] %>
...
<% } %>