Sorted duration time for Google Table Chart - google-visualization

I want to sort the column 2 (duration) descending or ascending.
This is the code:
https://jsfiddle.net/guilhermelight1/no7xvnLu/13/
#table_div tbody tr td:nth-child(3){
text-transform: uppercase;
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['table']}]}"></script>
<div id="table_div"></div>
google.setOnLoadCallback(drawTable);
function drawTable() {
var opts = {sendMethod: 'auto'};
var query = new google.visualization.Query('https://spreadsheets.google.com/tq?key=1mYtjx7_EP3k888Ep7oU92wk5J24EZn4UWwxKZAkFhHY&sheet=B', opts);
query.setQuery("select A,B,C ");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var formatter = new google.visualization.DateFormat({pattern: 'HH:mm'});
formatter.format(data, 2);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true});
}

assuming the decimal column represents seconds
the following snippet uses a DataView to add a calculated column for sorting...
google.charts.load('current', {
callback: drawTable,
packages:['table']
});
function drawTable() {
var opts = {sendMethod: 'auto'};
var query = new google.visualization.Query('https://spreadsheets.google.com/tq?key=1mYtjx7_EP3k888Ep7oU92wk5J24EZn4UWwxKZAkFhHY&sheet=B', opts);
query.setQuery("select A,B,C ");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var formatter = new google.visualization.DateFormat({pattern: 'hh:mm:ss'});
var timeColumn = 2;
var viewColumns = [];
var view = new google.visualization.DataView(data);
for (var i = 0; i < data.getNumberOfColumns(); i++) {
viewColumns.push(i);
}
viewColumns.push({
label: data.getColumnLabel(timeColumn),
type: 'date',
calc: function (dt, row) {
var dateValue = new Date();
dateValue = new Date(dateValue.getFullYear(), dateValue.getMonth(), dateValue.getDate());
dateValue = new Date(dateValue.getTime() + (dt.getValue(row, timeColumn) * 1000));
return {
v: dateValue,
f: formatter.formatValue(dateValue)
};
}
});
view.setColumns(viewColumns);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(view, {showRowNumber: true});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div"></div>

Related

How to get Facebook post likes?

I Am trying to retrieve FB Post Likes and Reactions using Graph API. The code that I used to retrieve the 'LIKE','LOVE','HAHA' of a post is shared below.
<script type="text/javascript">
var postID = '';
var access_token = '';
var refreshTime = 1;
var defaultCount = 0;
var reactions = ['LIKE', 'LOVE', 'HAHA'].map(function (e) {
var code = 'reactions_' + e.toLowerCase();
return 'reactions.type(' + e + ').limit(0).summary(total_count).as(' + code + ')'
}).join(',');
function refreshCounts() {
var url = 'https://graph.facebook.com/v2.8/?ids=' + postID + '&fields=' + reactions + '&access_token=' + access_token;
$.getJSON(url, function(res){
var v1 = res[postID].reactions_like.summary.total_count;
var v2 = res[postID].reactions_love.summary.total_count;
var v3 = res[postID].reactions_haha.summary.total_count;
$('#counter1').text(v1);
$('#counter2').text(v2);
$('#counter3').text(v3);
});
}
$(document).ready(function(){
setInterval(refreshCounts, refreshTime * 3000);
refreshCounts();
});
</script>
But the code showing two {} instead of the result.
Why don't you using javascript SDK?
var postID = $('#post_id').val();
FB.api(
'/' + postID + '/',
'GET',
{
"fields": "reactions.type(LIKE).limit(0).summary(1).as(like),reactions.type(WOW).limit(0).summary(1).as(wow),reactions.type(SAD).limit(0).summary(1).as(sad),reactions.type(LOVE).limit(0).summary(1).as(love),reactions.type(HAHA).limit(0).summary(1).as(haha),reactions.type(ANGRY).limit(0).summary(1).as(angry)",
"access_token": "token"
},
function (response) {
console.log(response);
var like_count = response.like.summary.total_count;
var love_count = response.love.summary.total_count;
var wow_count = response.wow.summary.total_count;
var haha_count = response.haha.summary.total_count;
var sad_count = response.sad.summary.total_count;
var angry_count = response.angry.summary.total_count;
}
);
This worked for me

Stacked column Google chart overlapping label inside the column

I'm using stacked column google chart but annotation or label of each column of graph is overlapping as like the image below:
My code is as below:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="chart_divgraph" style="width: 750px; height:500px;"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script language="javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization32);
function drawVisualization32() {
// Some raw data (not necessarily accurate)
/*var jsonData = $.ajax({
url: "getndata.php?cntnew=Ghatwar",
dataType: "json",
async: false
}).responseText;*/
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable({"cols":[{"id":"","label":"Caste Section","pattern":"","type":"string"},{"id":"","label":"Private","pattern":"","type":"number"},{"id":"","label":"Community","pattern":"","type":"number"},{"id":"","label":"Open Defecation","pattern":"","type":"number"}],"rows":[{"c":[{"v":"SC","f":null},{"v":"0","f":null},{"v":"1","f":null},{"v":"47","f":null}]},{"c":[{"v":"ST","f":null},{"v":"3","f":null},{"v":"7","f":null},{"v":"51","f":null}]},{"c":[{"v":"OBC","f":null},{"v":"5","f":null},{"v":"6","f":null},{"v":"84","f":null}]},{"c":[{"v":"GEN","f":null},{"v":"17","f":null},{"v":"1","f":null},{"v":"26","f":null}]}],"p":null});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: getpercentage,
sourceColumn: 1,
type: "string",
role: "annotation" },
2,
{ calc: getpercentagesecond,
sourceColumn: 2,
type: "string",
role: "annotation" },
3,
{ calc: getpercentagethird,
sourceColumn: 3,
type: "string",
role: "annotation" }])
function getpercentage(data, rowNum){
var firstval = data.getValue(rowNum, 1)
var secondval = data.getValue(rowNum, 2)
var thirdval = data.getValue(rowNum, 3)
var datavalueplus = parseInt(firstval) + parseInt(secondval) + parseInt(thirdval);
var finalpercentage = Math.abs( (firstval/datavalueplus)*100 ) ;
var numb = finalpercentage.toFixed(2);
return (numb + "%");
}
function getpercentagesecond(data, rowNum){
var firstval = data.getValue(rowNum, 1)
var secondval = data.getValue(rowNum, 2)
var thirdval = data.getValue(rowNum, 3)
var datavalueplus = parseInt(firstval) + parseInt(secondval) + parseInt(thirdval);
var finalpercentage = Math.abs( (secondval/datavalueplus)*100 ) ;
var numb = finalpercentage.toFixed(2);
return (numb + "%");
}
function getpercentagethird(data, rowNum){
var firstval = data.getValue(rowNum, 1)
var secondval = data.getValue(rowNum, 2)
var thirdval = data.getValue(rowNum, 3)
var datavalueplus = parseInt(firstval) + parseInt(secondval) + parseInt(thirdval);
var finalpercentage = Math.abs( (thirdval/datavalueplus)*100 ) ;
var numb = finalpercentage.toFixed(2);
return (numb + "%");
}
var options = {
title : 'Use of toilets across different prevailing caste section in village',
seriesType: 'bars',
/* width: 600,
height: 400,*/
/* bar: { groupWidth: 20 }, */
vAxis: {
/*minValue: 0,*/
/* scaleType: 'mirrorLog',*/
viewWindowMode:'pretty',
},
isStacked:"percent"
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_divgraph'));
chart.draw(view, options);
}
</script>
</body>
</html>
I tried various solution on stackoverflow but didn't get result. Can any one help my on this please? Thanks in advance

google maps marker load via ajax and infocontent

In my app I have a google map and I want to add many marker on it and so I load the data via ajax (I'm in Django). I have the probem with infocontent and the 'click' event on the marker load via ajax: When I do 'click' on the marker nothing happened. This is my code:
function initialize() {
var latlng = new google.maps.LatLng({{lat}}, {{long}});
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapCanvas"), myOptions);
var contentString = '<div id="content">{{name}}<br><span style="font-size:10px;">{{road}}</span><br><span style="font-size:10px;">{{city}} ({{prov}})</span></div>';
var infowindow_strutt = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: '{{name}}'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow_strutt.open(map,marker);
});
var markers = [];
var markers_strutt = [];
var markers_concor = [];
var icon_strutt = {
url: 'http://icons.iconarchive.com/icons/graphicloads/colorful-long-shadow/24/Home-icon.png'
};
var icon_concor = {
url: 'http://icons.iconarchive.com/icons/graphicloads/100-flat/24/home-icon.png'
};
var marker_concor
var marker_strutt
map.addListener('bounds_changed', function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
$.ajax({
url: '/api/get_marker/',
cache: false,
data: {
'fromlat': southWest.lat(),
'tolat': northEast.lat(),
'fromlng': southWest.lng(),
'tolng': northEast.lng()
},
dataType: 'json',
type: 'GET',
async: false,
success: function (data) {
if (data) {
$.each(data, function (i, item) {
if (item.type = 1) {
var marker_concor = new google.maps.Marker({
position: new google.maps.LatLng(item.lat, item.lng),
icon: icon_concor,
map: map,
draggable: false
});
} else if (item.type = 2) {
var marker_strutt = new google.maps.Marker({
position: new google.maps.LatLng(item.lat, item.lng),
icon: icon_strutt,
map: map,
draggable: false
});
//Create an infoWindow
var infowindow_strutt = new google.maps.InfoWindow();
//set the content of infoWindow (the name)
infowindow_strutt.setContent(item.name);
//add click listner to marker which will open infoWindow
map.addListener(marker_strutt, 'click', function() {
infowindow_strutt.open(marker_strutt); // click on marker opens info window
});
}
markers_concor.push(marker_concor);
markers_strutt.push(marker_strutt);
if (marker_strutt) {
marker_strutt.setMap(map);
}
if (marker_concor) {
marker_concor.setMap(map);
}
});
}
}
});
});
}
jQuery(document).ready(function(e) {
initialize();
});
Where is the issue? Thanks a lot
EDIT: View code
def view_get_marker(request):
id = 24
list_id = []
list_marker = []
list_id.append(id)
# type 1 data
A_list = tab_A.objects.filter(id_struttura=id).filter(lat__gt=request.GET.get('fromlat'), lat__lt=request.GET.get('tolat')).filter(lng__gt=request.GET.get('fromlng'), lng__lt=request.GET.get('tolng'))
for a in A_list:
list_marker.append([a.lat, a.lng, a.name, a.road, a.city, a.id, 1])
list_id.append(a.id)
# type 2 data
B_list = list(tab_B.objects.all().values_list('lat','lng','name','road','city','id').exclude(lng__isnull=True).exclude(id__in=lista_id).filter(lat__gt=request.GET.get('fromlat'), lat__lt=request.GET.get('tolat')).filter(lng__gt=request.GET.get('fromlng'), lng__lt=request.GET.get('tolng')))
for lat, lng, name, road, city, id in B_list:
list_marker.append([lat, lng, name, road, city, id, 2])
if request.is_ajax():
results = []
for row in list_marker:
h_json = {}
h_json['lat'] = row[0]
h_json['lng'] = row[1]
h_json['name'] = unicode(row[2])
h_json['road'] = unicode(row[3])
h_json['city'] = unicode(row[4])
h_json['id'] = row[5]
h_json['type'] = row[6]
results.append(h_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
EDIT 2:
I found the solution. The problem was in the event 'click' declaration. The right way is this:
google.maps.event.addListener(marker_strutt, 'click', (function(marker_strutt, i) {
return function() {
infowindow.setContent('my content');
infowindow.open(map, marker_strutt);
}
})(marker_strutt, i));
In this way I have the popoup!

How can i catch mouse wheel direction using famo.us scrollSync?

I want to know wheel direction using "famo.us" scrollSync.
but i can't search exact solution.
my code is below. please give me a solution.
var Engine = require("famous/core/Engine");
var Surface = require("famous/core/Surface");
var ScrollSync = require("famous/inputs/ScrollSync");
var mainContext = Engine.createContext();
var start = 0;
var update = 0;
var end = 0;
var scrollSync = new ScrollSync(function() {
return [0,0];
});
Engine.pipe(scrollSync);
var contentTemplate = function() {
return "<div>Start Count: " + start + "</div>" +
"<div>End Count: " + end + "</div>" +
"<div>Update Count: " + update + "</div>";
};
var surface = new Surface({
size: [undefined, undefined],
classes: ['grey-bg'],
content: contentTemplate()
});
scrollSync.on("start", function() {
surface.setContent(contentTemplate());
});
scrollSync.on("update", function(data) {
surface.setContent(contentTemplate());
});
scrollSync.on("end", function() {
surface.setContent(contentTemplate());
});
mainContext.add(surface);
There are a couple things I did to get your code to work. First just use surface.pipe(scrollSync) to get events scroll sync, and next, actually update the variables for start, update, and end. I also added a direction variable where I inspect the delta property of the event to determine the direction you are moving your mousewheel.
Here is the example.. Hope it helps!
var Engine = require("famous/core/Engine");
var Surface = require("famous/core/Surface");
var ScrollSync = require("famous/inputs/ScrollSync");
var mainContext = Engine.createContext();
var start = 0;
var update = 0;
var end = 0;
var direction = undefined;
var scrollSync = new ScrollSync();
var contentTemplate = function() {
return "<div>Start Count: " + start + "</div>" +
"<div>End Count: " + end + "</div>" +
"<div>Update Count: " + update + "</div>" +
"<div>Direction: " + direction + "</div>";
};
var surface = new Surface({
size: [undefined, undefined],
classes: ['grey-bg'],
content: contentTemplate()
});
surface.pipe(scrollSync);
scrollSync.on("start", function() {
start += 1;
surface.setContent(contentTemplate());
});
scrollSync.on("update", function(data) {
update += 1;
delta = data['delta'];
direction = delta[0] == 0 ? (delta[1] > 0 ? "down" : "up") : (delta[0] > 0 ? "right" : "left") ;
surface.setContent(contentTemplate());
});
scrollSync.on("end", function() {
end += 1;
surface.setContent(contentTemplate());
});
mainContext.add(surface);

Mark list item as viewed/read in SharePoint 2013

When a user views an item in SharePoint list, I need to capture that it has been viewed and who viewed the item (in additional columns). Is there a way to do that?
I did this by adding a script editor web part and inserting this script in there:
<script type="text/javascript" src="/jquery-1.10.2.min.js"></script>
<script src="/jquery.SPServices-2013.02a.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () { ExecuteOrDelayUntilScriptLoaded(loadConstants, "sp.js"); });
function loadConstants() {
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
function onSuccess(data, request){
var loginName = data.d.Title;
var docurl = document.URL;
var beginindex = docurl.indexOf('?ID=') + 4;
var endindex = docurl.indexOf('&Source=');
var itemid = docurl.substring(beginindex, endindex);
var ctx = new SP.ClientContext("your website url");
var oList = ctx.get_web().get_lists().getByTitle('your library name');
this.oListItem = oList.getItemById(itemid);
this.oListItem.set_item('Read', loginName + ' ' + getTodayDate());
this.oListItem.update();
ctx.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onError(error) {
alert("error");
}
function getTodayDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = mm+'/'+dd+'/'+yyyy;
return today;
}
}
</script>