Keen.io how to use savedQueries() to chart graph - javascript

I'm trying to use savedQueries to draw graph without success. Is savedQueries only used to CRUD queries in Keen or can it actually be used to chart graph as well?? Keys removed from the code, sorry for the inconvenience.
var client = new Keen({
projectId: keen.project,
writeKey: keen.writeKey,
readKey: keen.readKey,
masterKey: keen.masterKey
});
var savedQueries = client.savedQueries();
savedQueries.get("monthly-active-users", function(err, response) {
if (err) {
console.log(err);
}
console.log(response);
var chart1 = new Keen.Dataviz()
.el(document.getElementById('chart'))
.chartType("area")
.colors(["#6ab975"])
.title("Monthly Active Users")
.prepare();
chart1
.data(response)
.render();
});
response obj from saved query
{
"refresh_rate": 0,
"user_last_modified_date": "2017-06-09T18:51:59.676000+00:00",
"last_modified_date": "2017-06-09T18:51:59.676000+00:00",
"query_name": "monthly-active-users",
"urls": {
"cached_query_url": "/3.0/projects/58f6fb8a90b3659264951b8d/queries/saved/monthly-active-users",
"cached_query_results_url": "/3.0/projects/58f6fb8a90b3659264951b8d/queries/saved/monthly-active-users/result"
},
"created_date": "2017-04-25T23:52:45.685000+00:00",
"query": {
"filters": [
{
"operator": "ne",
"property_name": "user_id",
"property_value": "guest"
},
{
"operator": "not_contains",
"property_name": "fromState",
"property_value": "app"
},
{
"operator": "not_contains",
"property_name": "user_email",
"property_value": "#giblib.com"
},
{
"operator": "not_contains",
"property_name": "fromState",
"property_value": "app.auth_postregister"
}
],
"analysis_type": "count_unique",
"timezone": "US/Pacific",
"group_by": null,
"force_exact": null,
"timeframe": "this_2_months",
"target_property": "user_id",
"interval": "monthly",
"event_collection": "user-page-access"
},
"run_information": null,
"metadata": {
"visualization": {
"chart_type": "areachart"
},
"display_name": "Monthly Active Users"
}
}

I noticed that you did not include the Keen.ready() function. Also, I recommend using client.run instead of client.get because it runs the query and gets the result.
I went ahead and created an example JSFiddle: https://jsfiddle.net/pn14bs0L/2/
Keen.ready(function() {
client.run("test-saved-query", function(err, response) {
if (err) {
// there was an error
} else {
var chart1 = new Keen.Dataviz()
.el(document.getElementById('my_chart'))
.chartType("areachart")
.colors(["#6ab975"])
.title("Monthly Active Users")
.prepare();
chart1
.data(response)
.render();
}
});
});
You can see this working with some test data in the JSFiddle.
Note: I assumed you were using keen-js here and not keen-dataviz.js.

Related

prebid.js ad is not getting rendered

I have setup prebid.js with single adaptor configured on test page. I am getting the ad response from adaptor and I can see the pbjs.getBidResponses() object is present still ad is not getting rendered on the page.
you can visit test page
standard prebid setup as follows
JAVSCRIPT
var sizes = [
[300, 250]
];
var PREBID_TIMEOUT = 1000;
var FAILSAFE_TIMEOUT = 3000;
var adUnits = [{
code: '/19968336/header-bid-tag-1',
mediaTypes: {
banner: {
sizes: sizes
}
},
bids: [{
bidder: 'incrementx',
params: {
placementId: 'PNX-HB-R787915V41024E'
}
}]
}];
// ======== DO NOT EDIT BELOW THIS LINE =========== //
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
googletag.cmd.push(function () {
googletag.pubads().disableInitialLoad();
});
var pbjs = pbjs || {};
pbjs.que = pbjs.que || [];
pbjs.que.push(function () {
pbjs.addAdUnits(adUnits);
pbjs.requestBids({
bidsBackHandler: initAdserver,
timeout: PREBID_TIMEOUT
});
});
function initAdserver() {
if (pbjs.initAdserverSet) return;
pbjs.initAdserverSet = true;
googletag.cmd.push(function () {
pbjs.setTargetingForGPTAsync && pbjs.setTargetingForGPTAsync();
googletag.pubads().refresh();
});
}
// in case PBJS doesn't load
setTimeout(function () {
initAdserver();
}, FAILSAFE_TIMEOUT);
googletag.cmd.push(function () {
googletag.defineSlot('/19968336/header-bid-tag-1', sizes, 'div-1')
.addService(googletag.pubads());
googletag.pubads().collapseEmptyDivs();
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
HTML
<div id='div-1'>
<script type='text/javascript'>
googletag.cmd.push(function () {
googletag.display('div-1');
});
</script>
</div>
ADAPTOR Response
{
"vzhPlacementId": "<placement-id>",
"bid": "<bid>",
"adWidth": "300",
"adHeight": "250",
"cpm": "0.017442",
"ad": "<ad-tag>",
"slotBidId": "<slot-id>",
"statusText": "Vertoz:Success"
}
pbjs.getBidResponses() output
{
"/19968336/header-bid-tag-1": {
"bids": [
{
"bidderCode": "incrementx",
"width": 300,
"height": 250,
"statusMessage": "Bid available",
"adId": "389575b4d6d5f1",
"requestId": "2b7446c2969f1f",
"transactionId": "a6a81b3e-8cf7-4d71-bc7e-34c283e1a746",
"auctionId": "4455d9a4-4364-4f9d-bd1a-d7f0a7fd56e4",
"mediaType": "banner",
"source": "client",
"cpm": 0.017442,
"currency": "USD",
"ttl": 300,
"creativeId": 0,
"netRevenue": false,
"meta": {
"mediaType": "banner",
"advertiserDomains": [],
"dchain": {
"ver": "1.0",
"complete": 0,
"nodes": [
{
"name": "incrementx"
}
]
}
},
"ad": "<ad-tag>",
"adapterCode": "incrementx",
"originalCpm": "0.017442",
"originalCurrency": "USD",
"responseTimestamp": 1656921876245,
"requestTimestamp": 1656921875927,
"bidder": "incrementx",
"adUnitCode": "/19968336/header-bid-tag-1",
"timeToRespond": 318,
"pbLg": "0.00",
"pbMg": "0.00",
"pbHg": "0.01",
"pbAg": "0.00",
"pbDg": "0.01",
"pbCg": "",
"size": "300x250",
"adserverTargeting": {
"hb_bidder": "incrementx",
"hb_adid": "389575b4d6d5f1",
"hb_pb": "0.00",
"hb_size": "300x250",
"hb_source": "client",
"hb_format": "banner",
"hb_adomain": ""
},
"status": "targetingSet"
}
]
}
}
pbjs.getAllPrebidWinningBids() & pbjs.getAllWinningBids() output
[]
this is the output I am getting
not able to find the issue, there is only 1 adaptor integrated so in all cases the bid should win, not sure am I missing something in setup?. Any help would be appreciated, thank you
Because this line is a copy from the prebid.org docs:
googletag.defineSlot('/19968336/header-bid-tag-1', sizes, 'div-1')
I don't think you have your own GAM account configured correctly.
You'll need to have a GAM account and switch the first parameter of defineSlot to be your own GAM ad unit code.
You'll want to follow the postbid instructions if you want to avoid using GAM.

Manipulating MongoDB response NodeJS

I made a "little" query for mongodb to join two collections and retrieve data.
The game: insert 2 or 3 params on a URL
-include can be 0,1 or 2.
0 exclusive
1 inclusive
2 return all
-netcode: is a key to filter data
-group: another optional keys, that works with the first param "include"
-My query works perfectly, returns in a way how much times a event happened in a certain group.
-The problem? I can't work with the result of mongo db, i need to parse it to JSON.
I'm not so clever at JS, so i don't know where to put it. Since i work in corporation, some of the code was already done.
Well my output is this:
{
"events": [
{
"_id": {
"group": "GFS-CAJEROS-INFINITUM-TELDAT-M1",
"event": "SNMP DOWN"
},
"incidencias": 1
},
{
"_id": {
"group": "GFS-CAJEROS-MPLS",
"event": "Proactive Interface Input Utilisation"
},
"incidencias": 1209
},
{
"_id": {
"group": "GFS-CAJEROS-MPLS",
"event": "Proactive Interface Output Utilisation"
},
"incidencias": 1209
},
{
"_id": {
"group": "GFS-CAJEROS-MPLS",
"event": "Proactive Interface Availability"
},
"incidencias": 2199
},
{
"_id": {
"group": "GFS-SUCURSALES-HIBRIDAS",
"event": "Proactive Interface Output Utilisation"
},
"incidencias": 10
},
But i want it fused in a JSON format, like this: check the int value is next for the name of the event.
[
{
"group": "GFS-CAJEROS-MPLS",
"Proactive Interface Input Utilisation" : "1209",
"Proactive Interface Output Utilisation" : "1209",
"Proactive Interface Availability" : "2199",
},
{
"group": "GFS-SUCURSALES-HIBRIDAS",
"Proactive Interface Output Utilisation" : "10",
},
I'm using Nodejs and the mongodb module, since i dont know how this function exactly works, i don't know how to manage the response, ¿there is a better way to do this? like to get the json file, using another js to generate it?
This is the code i'm using, basically is the important part:
var events = db.collection('events');
events.aggregate([
{ $match : { netcode : data.params.netcode } },
{
$lookup:
{
from: "nodes",
localField: "name",
foreignField: "name",
as: "event_joined"
}
},
{ $unwind: {path: "$event_joined"} },
{ $match : {"event_joined.group" :
{$in:
[
groups[0] ,
groups[1] ,
groups[2] ,
groups[3] ,
groups[4] ,
groups[5] ,
groups[6] ,
groups[7] ,
groups[8] ,
groups[9] ,
]
}
}
},
{ $group : { _id : {group:"$event_joined.group", event:"$event"}, incidencias: { $sum: 1} } },
])
.toArray( function(err, result) {
if (err) {
console.log(err);
} else if (result) {
data.response.events = result;
} else {
console.log("No result");
}
You should add another $group to your pipeline {_id: "$_id.group", events: {$push : {name: "$_id.event", incidencias: "$incidencias"}}}
Then change the structure of your data on the JS code with "Array.map".
data.response.events = data.response.events.map(function (eve){
var obj = {
"group": eve.group
};
eve.events.forEach(function (e){
obj[e.name] = e.incidencias
})
return obj;
})

d3pie error: no data supplied on d3pie.js

I am using rails, and gathering some data to make pie charts. I am just using ruby objects (so no JSON), and using d3pie. First, I make a helper function. Then I make a javascript function using that helper, and pass it in the dom. Here's my code;
helper.rb
def options_data_to_d3(options_data)
d3_data = []
options_data.each do |key, value|
d3_data.push( { label: key.option.as_json, value: value.as_json } )
end
return JSON.pretty_generate(d3_data)
end
this takes the ruby hash, and makes it into json
js function
function dataPieChart(id, data) {
var config = {
"header": {
"title": {
"text": "Quiz Questions",
"fontSize": 18,
"font": "verdana"
},
"size": {
"canvasHeight": 400,
"canvasWidth": 500
},
"data": {
"content": data
},
"labels": {
"outer": {
"pieDistance": 32
}
}
}
}
var pie = new d3pie(id, config);
}
passing into the view
<div id="quizQuestionOptionPie<%= question.id %>"></div>
<script type="text/javascript">dataPieChart("quizQuestionOptionPie<%= question.id %>", <%= raw options_data_to_d3(data[:options]) %>);
</script>
when I call a console log in the javascript function to see what data is, I get the correct output that both d3pie and d3 are looking for, yet I am still getting the error
d3pie error: no data supplied.
does anyone see something wrong with my code, or something I am missing? any help is appreciated.
You config option is bracketed incorrectly (everything is a child of "header"). You really meant:
var config = {
"header": {
"title": {
"text": "Quiz Questions",
"fontSize": 18,
"font": "verdana"
},
},
"size": {
"canvasHeight": 400,
"canvasWidth": 500
},
"data": {
"content": data
},
"labels": {
"outer": {
"pieDistance": 32
}
}
};

How can I filter results in typeahead.js using a second variable?

I am trying to filter results using Typeahead.js. I can currently filter the results using a field called activity_title. This works fine.
How can I filter my results by a second value? In this case, I would like to select only the results that have a certain value for activity_level. I need to set this when the typeahead is initialised rather than hard coding it into the Bloodhound initialisation (e.g. I don't want to use url: 'api/activity/&range=1,3')
I have the following valid JSON that I access remotely:
{
"meta": [
{
"name": "activity_id",
"table": "table",
"max_length": 4
},
{
"name": "activity_title",
"table": "table",
"max_length": 91
},
{
"name": "activity_level",
"table": "table",
"max_length": 2
}
],
"detail": [
{
"activity_id": "57",
"activity_title": "Help old ladies to cross the road.",
"activity_level": "2"
},
{
"activity_id": "58",
"activity_title": "Help mum with the washing up.",
"activity_level": "3"
},
{
"activity_id": "59",
"activity_title": "Shine my shoes",
"activity_level": "1"
},
{
"activity_id": "60",
"activity_title": "Put the bins out",
"activity_level": "1"
}
]
}
I set up a Bloodhound instance like this:
var activities = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.activity_title);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '/api/activity/',
filter: function(data) {
return $.map(data['detail'], function(detail) {
return {
activity_id: detail.activity_id,
activity_title: detail.activity_title,
objective_level: detail.objective_level
};
});
}
}
});
I use Typeahead.js to do a lookup on the data as I type.
$( document ).on( "focus", ".typeahead-init", function() {
// + '&range=' + minimum + ',' + maximum
var minimum = $('#group-level-min-1').val();
var maximum = $('#group-level-max-1').val();
$(this).typeahead({
highlight: true
},
{
name: 'activity_title',
displayKey: 'activity',
source: activities.ttAdapter(),
templates: {
header: '<div class="header-name">Activities</div>',
empty: [
'<div class="empty-message">',
'No activities match your search',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<div class="typeahead-activity" id="typeahead-activity-{{activity_id}}"><strong>{{objective_level}}</strong> - {{activity_title}}</div>')
}
})
//info on binding selection at https://github.com/twitter/typeahead.js/issues/300
.bind('typeahead:selected', function(obj, datum, name) {
var target = $(this).closest('.activity-container');
var activityId = datum['activity_id'];
var url = '/api/activity/id/'+activityId;
$(target).children('.activity-id').val(activityId);
//http://runnable.com/UllA9u8MD5wiAACj/how-to-combine-json-with-handlebars-js-for-javascript-ajax-and-jquery
var raw_template = $('#activity-output').html();
// Compile that into an handlebars template
var template = Handlebars.compile(raw_template);
// Fetch all data from server in JSON
$.get(url,function(data,status,xhr){
$.each(data,function(index,element){
// Generate the HTML for each post
var html = template(element);
// Render the posts into the page
target.append(html);
});
});
});
$(this).removeClass("typeahead-init");
$(this).focus();
});
This has been cobbled together from several answers on Stackoverflow and others. Any help greatly appreciated.

How get extra information from json?

I use can.Component to dispay JSON on the page.
can.Component.extend({
tag: "some-app",
scope: {
items: new Items.List({}),
displayedItems: function () {
...
return items;
}
},
helpers: {
...
},
events: {
"{Items} created": function (Items, ev, newItem) {
...
}
}
})
How can I get "meta" section of received JSON (below) to the scope or helpers?
{
"data": [
{
"description": "Some text",
"id": 1,
"measurement": "pcs",
"name": "Name of item",
"resource_uri": "/api/v1/item/1/"
},
{....}, {....}
}
],
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 3
}
}
I can get it in console with Items.findAll().then(function(info){console.log(info.attr('meta'))}) , but I'm noob in (can.)js and can't understand how to get it in the place I need.
Instead of this:
scope: {
items: new Items.List({})
}
make the request:
scope: {
items: Items.findAll()
}
There are other ways to do this as well, in the template(not advised), or creating the request in another controller or component and passing in to the instantiation of the component.
If you want more specifics, you would nee to update your question with more details on your model.

Categories