reload tableview on click of picker element with updated data in titanium - javascript

I have a json response like this which is coming from API call.
`{
"id": "7",
"issue_title": "Apr - May 2015",
"issue_no": "Issue 1.4",
"cover_image_url": "http://www.link.org/apr--may-2015-7.jpg",
"synopsis_pdf_url": "",
"advertisers_pdf_url": "",
"issue_date": "01-04-2015",
"issue_year": "2015"
},
{
"id": "3",
"issue_title": "Feb-Mar 2015",
"issue_no": "Issue 1.3",
"cover_image_url": "http://www.link.org/febmar-2015-3.jpg",
"synopsis_pdf_url": "http://www.link.org/febmar-2015-3.pdf",
"advertisers_pdf_url": "http://www.link.org/febmar-2015-3.pdf",
"issue_date": "01-02-2015",
"issue_year": "2015"
},
{
"id": "2",
"issue_title": "Dec 2014 - Jan 2015",
"issue_no": "Issue 1.2",
"cover_image_url": "http://www.link.org/dec-2014--jan-2015-2.jpg",
"synopsis_pdf_url": "",
"advertisers_pdf_url": "",
"issue_date": "01-12-2014",
"issue_year": "2014"
},
{
"id": "1",
"issue_title": "Oct - Nov 2014",
"issue_no": "Issue 1.1",
"cover_image_url": "http://www.link.org/oct--nov-2014-1.jpg",
"synopsis_pdf_url": "",
"advertisers_pdf_url": "",
"issue_date": "01-10-2014",
"issue_year": "2014"
}`
Now I am retreiving issue_year which I am displaying in picker.
I want if a user clicks on issue_year the table data should display only records which have same issue_year.
Like if 2014 is clicked from picker it should display only 3rd and 4th record.
Now from controller I am passing object which jsonResponse[i] in the picker when picker data is prepared so as to retreive the same in its click but I am getting undefined.
js code is as follows
function openpastIssues(e) {
var url = "http://example.com/api/past_year_issue.aspx";
var jsonResponse;
var response;
var data = [];
var pickerData = [];
var singleData = [];
var row;
var xhr = Ti.Network.createHTTPClient({
onload : function() {
// parse the retrieved data, turning it into a JavaScript object
Ti.API.info("From Past Issues (function): " + this.responseText);
jsonResponse = JSON.parse(this.responseText);
var rowHeight = 150;
// just pick the right height here
var imageRowIsFull = false;
var myImage;
var issuelbl;
var row = Ti.UI.createTableViewRow({
width : Ti.UI.SIZE,
height : Ti.UI.SIZE,
layout : "horizontal"
});
for (var i = 0; i < jsonResponse.length; i++) {
var tView = Ti.UI.createView({
width : Ti.UI.SIZE,
height : Ti.UI.SIZE,
left : "5%",
right : "5%",
top : "5",
bottom : "5",
backgroundColor : "#A9F5A9",
//backgroundColor : "black",
layout : "vertical"
});
issuelbl = Ti.UI.createLabel({
color : 'blue',
text : jsonResponse[i].issue_title,
height : "auto",
width : "auto",
left : "3%",
font : {
fontSize : 13
},
});
tView.add(issuelbl);
myImage = Ti.UI.createImageView({
width : 120,
//left : "5%",
//right : "5%",
top : "5",
//bottom:"5",
height : 150,
image : jsonResponse[i].cover_image_url,
obj : jsonResponse[i]
});
tView.add(myImage);
try {
myImage.addEventListener('click', function(e) {
Ti.API.info('Clicked data = ' + JSON.stringify(e.source.obj));
var jsonRes = e.source.obj;
Alloy.createController('singleissue', jsonRes);
});
} catch(e) {
}
row.add(tView);
//row.add(myImage);
imageRowIsFull = false;
if ((i + 1) % 2 == 0) {//this will add a new row every 2 items.
imageRowIsFull = true;
data.push(row);
row = Ti.UI.createTableViewRow({
width : Ti.UI.SIZE,
height : Ti.UI.SIZE,
layout : "horizontal",
filterCriteria :jsonResponse[i].issue_year
});
}
pickerData[i] = Ti.UI.createPickerRow({
title : jsonResponse[i].issue_year,
obj : jsonResponse[i]
});
}
if (!imageRowIsFull) {//do not forget to add the last row
data.push(row);
}
//table.setData(data); 
$.issueTable.setData(data);
$.picker.add(pickerData);
},
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000
});
xhr.open("GET", url);
xhr.send();
}
$.picker.addEventListener('change', function(e) {
Ti.API.info('From picker ' + e.source.obj);
});
xml file
<Alloy>
<Window id="winpast" class="container" title="Past issues" onOpen="openpastIssues">
<View id="view2" width="Ti.UI.FILL" height="Ti.UI.FILL" backgroundColor="#A9F5A9" >
<View id="viewcheck1" >
<Label id="title" width="Ti.UI.SIZE" text="Past Issues" height="Ti.UI.SIZE" textAlign="Ti.UI.TEXT_ALIGNMENT_CENTER"></Label>
<ImageView id="menuImg" image="/images/menu.png" onClick="showsideBar" left="5"></ImageView>
<Picker id="picker" selectionIndicator="true" height="Ti.UI.SIZE" width="Ti.UI.SIZE" right="10">
</Picker>
</View>
<View id="tablePast" width="Ti.UI.FILL" height="Ti.UI.FILL" top="40">
<TableView id="issueTable" scrollable="true"></TableView>
</View>
<View id="viewBelow" width="150" height="Ti.UI.FILL" backgroundColor="#A9A5A9" left="-150" visible="false" top="40">
<TableView id="menuTable"></TableView>
</View>
</View>
</Window>
</Alloy>
Basically I want to display a records of particular year selected from picker.
Can anyone please help on this.
I have spent a lot of time on this.

You can make an NSMUtableArray and repopulate it depending on the values of "issue_year". You can use NSPredicate for sorting through your json

Related

show tooltip for each point of highcharts network graph in Angular

I am building networkgraphs using highcharts and highcharts-angular on my Angular application. I am able to display the graph with datalabels successfully. Now, I have to show some tooltip data when I hover on each point/node of the graph. How can I do it? How can I show a tooltip corresponding to each point of the graph?
As of now, I am using the below options to draw the graph and show the tooltip. This tooltip, is showing same information when I hover any point. I need to show a different data for each point. How can I do it?
chartOptions = {
"chart": {
"type": "networkgraph",
"height": "100%"
},
"title": {
"text": "Network graph demo"
},
"subtitle": {
"text": "A Force-Directed Network Graph in Highcharts"
},
"plotOptions": {
"networkgraph": {
"keys": ["from", "to"],
"layoutAlgorithm": {
"enableSimulation":true
}
}
},
"series": [
{
"dataLabels": {
"enabled": true,
"linkFormat": ""
},
"data": [{"from" : "a", "to": "b"},
{"from": "a", "to": "c"},
{"from": "a", "to": "d"} ],
"marker" : {"radius" : 18}
}
],
"tooltip" :
{
"enabled" : true,
"formatter" : function() {
return "<div> <span> My tooltip information </span> </div>"
}
}
}
I use console.log() to explore the objects available to me within the Highcharts API
You'll see in the console output all the accessible information, within which name seems to be what you're after?
Try this:
"tooltip" :
{
"enabled" : true,
"formatter" : function() {
console.log(this.point)
return this.point.name
}
}
Update below, is this close to what you're after?
"tooltip" :
{
"enabled" : true,
"useHTML" : true,
"formatter" : function() {
let linkFrom_li = '';
let linkTo_li = '';
let tooltipHTML = '';
for (let i = 0; i < this.point.linksTo.length; i++) {
linkFrom_li = linkFrom_li + `<li>${this.point.linksTo[i].from}</li>`;
}
for (let i = 0; i < this.point.linksFrom.length; i++) {
linkTo_li = linkTo_li + `<li>${this.point.linksFrom[i].to}</li>`;
}
tooltipHTML = tooltipHTML + `<b>Links from [${this.point.name}]</b>:<ul>${linkFrom_li}</ul>`;
tooltipHTML = tooltipHTML + `<b>Links to [${this.point.name}]</b>:<ul>${linkTo_li}</ul>`;
return tooltipHTML;
}
}

Aggregate data for months in chart.js - PHP, MySQL, JS

I'm newbie to js and data aggregating for charts and it would be great to know how to aggregate data in a chart collecting them for months. In the example I'm trying to sum the money data for each employee id for months but the result is always passed like singular queries.
Here it is my code in js:
$(document).ready(function() {
/**
* call the data.php file to fetch the result from db table.
*/
$.ajax({
url : "http://localhost:8888/site/function/data.php",
type : "GET",
success : function(data){
console.log(data);
var importo = {
TRCLRT76T08F704F : [],
NGLLSN80T03F839Y : []
};
var len = data.length;
for (var i = 0; i < len; i++) {
if (data[i].cf == "TRCLRT76T08F704F") {
importo.TRCLRT76T08F704F.push(data[i].importo);
}
else if (data[i].cf == "NGLLSN80T03F839Y") {
importo.NGLLSN80T03F839Y.push(data[i].importo);
}
}
//get canvas
var ctx = $("#line-chartcanvas");
var data = {
labels : ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"],
datasets : [
{
label : "TRCLRT76T08F704F importo",
data : importo.TRCLRT76T08F704F,
backgroundColor : "blue",
borderColor : "lightblue",
fill : false,
lineTension : 0,
pointRadius : 5
},
{
label : "NGLLSN80T03F839Y importo",
data : importo.NGLLSN80T03F839Y,
backgroundColor : "green",
borderColor : "lightgreen",
fill : false,
lineTension : 0,
pointRadius : 5
}
]
};
var options = {
title : {
display : true,
position : "top",
text : "Line Graph",
fontSize : 18,
fontColor : "#111"
},
legend : {
display : true,
position : "bottom"
}
};
var chart = new Chart( ctx, {
type : "line",
data : data,
options : options
} );
},
error : function(data) {
console.log(data);
}
});
Here it is the function to call the db in data.php
$query = sprintf("SELECT cf, mese, importo FROM table WHERE `anno` = '2017' AND `importo` > '0' ORDER BY stamp_start");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}

Changing image of a node based on JSON data it contains with vis.js without DataSet being defined

I'm working with Vis.js in a django project. I have a network created and I need to be able to to have nodes images change based on the JSON data they hold. I'm having issues doing this because of the whole DataSet needing to be defined in order to use nodes.update etc. I'm unable to predefine the nodes as it's based on the return of another object so the number of nodes are random. The node and edge properties are added in a Django view.
Here's my code:
Django snibbet:
#login_required
def project_detail(request, project_id):
"""
Project detail, include graphical representation: modules in this project
:param request:
:param project_id:
:return:
"""
all_edges = request.GET.get('all_edges', '')
draw_invisible_button = ''
network_nodes = []
network_edges = []
tc_keys = []
projects = Project.objects.all()
project = get_object_or_404(Project, pk=project_id)
testcases = project.testcaseresults_set.latest('updated').results
user = request.user
user.humanresource.project = project
user.humanresource.save()
for tc in testcases:
data = tc['data']
tc_keys.append(data)
for m in project.modules:
network_nodes.append({
'id': m.id,
'label': m.name,
})
for d, n in zip(network_nodes, tc_keys):
d['data'] = n
for edge in project.edges_between_modules:
try:
if edge.properties[EDGE_TYPES_INVISIBLE_KEY] == 'on':
draw_invisible_button = 'true'
if not all_edges:
continue
except KeyError:
pass
if not check_edge_in_set(edge, network_edges):
network_edges.append({
'id': edge.id,
'to': edge.to_node.module.id,
'from': edge.from_node.module.id,
'label': 1,
'edge_name': edge.from_node.name + '-' + edge.to_node.name,
'type': edge.type.name,
'to_node': edge.to_node.name,
'from_node': edge.from_node.name,
'priority': edge.priority,
'properties': edge.properties
})
context = {
'projects': projects,
'project': project,
'all_edges': all_edges,
'draw_invisible_button': draw_invisible_button,
'module_new_form': ModuleForm(project_id=project.id),
'module_import_form': UploadForm(),
'edge_types': EdgeType.objects.all(),
'edge_priority': Edge.PRIORITY_CHOICES,
'network_nodes': json.dumps(network_nodes),
'network_edges': json.dumps(network_edges),
'edges_between_modules': network_edges
}
return render(request, 'graphs/project/project_detail.html', context)
Template nodes and edges reference snibbet:
<script>
var nodes = {{ network_nodes|safe }};
var edges = {{ network_edges|safe }};
</script>
This is an example of what the nodes JSON array looks like:
[{"id": 1540, "data": [], "label": "AccountFound"}, {"id": 1541, "data": [], "label": "AccountNotFound"}, {"id": 1542, "data": [], "label": "AddANI"}, {"id": 1543, "data": [], "label": "AutoPay"}, {"id": 1544, "data": [], "label": "AutoPayAccount"}, {"id": 1545, "data": [{"tcs_cannot_route": "This edge cannot be routed: MenuPrompt/MenuPromptWC property 'Outputs' not found", "title": "Route from 'GetCallerDetail' to 'GreetingDefault'"}, {"tcs_cannot_route": "This edge cannot be routed: MenuPrompt/MenuPromptWC property 'Outputs' not found", "title": "Route from 'DNISGreeting' to 'HOOCheck'"}, {"tcs_cannot_route": "This edge cannot be routed: MenuPrompt/MenuPromptWC property 'Outputs' not found", "title": "Route from 'GreetingDefault' to 'HOOCheck'"}, {"tc_steps": [{"content": "APN: 8552929487, HollyBrowser: , ", "expected": ""}], "title": "Route from 'Start' to 'GetCallerDetail'", "pre_conditions": []}, {"tcs_cannot_route": "This edge cannot be routed: MenuPrompt/MenuPromptWC property 'Outputs' not found", "title": "Route from 'GetCallerDetail' to 'DNISGreeting'"}], "label": "Start - Greeting"}, {"id": 1546, "data": [], "label": "Transfer"}]
This is my drawfunction:
function draw_project_graph() {
// create a network
var container = document.getElementById('module_in_project');
//var nodes = new vis.DataSet("{{ network_nodes|escapejs }}");
// provide the data in the vis format
var data = {
nodes: nodes,
edges: edges
};
var options = {
nodes: {
shape: 'image',
image: image_url + 'blue-infrastructure-graphics_11435264594_o.png',
//image: image_url + 'west-ivr-graphic_11435724503_o.png',
size: 25
},
edges: {
color: '#000',
length: 190,
arrows: 'to',
arrowStrikethrough: false
},
width: '100%',
height: '800px'
};
// initialize your network!
var network = new vis.Network(container, data, options);
var n = JSON.stringify("{{ network_nodes|escapejs }}");
var node = JSON.parse(n);
console.log(node);
$.each(JSON.parse(node), function(idx, obj){
var details = obj.data;
var id = obj.id;
for (var i = 0; i < details.length; ++i){
for(var ind in details[i]){
if(ind === 'tcs_cannot_route'){
console.log(id);
}
}
}
});
network.on('click', function(params){
//console.log(params.nodes)
if (!$.isEmptyObject(params.nodes)) {
var current = '',
tmp = window.location.href.split('/');
for (var i = 0; i < tmp.length - 3; i++) {
current += tmp[i] + '/'
}
$('#module_in_project').css('cursor', 'progress');
window.location.href = current + 'project_module_detail/' + params.nodes;
} else if (!$.isEmptyObject(params.edges)){
//console.log(params.edges)
$('a[href="#projectEdges"]').click();
$('a[href="#project-edge-{0}"]'.format(params.edges)).click();
$('.edges-between-modules').show();
$('.edges-between-modules-contents').hide();
} else {
$('a[href="#projectModules"]').click();
}
})
}
I need to change:
image: image_url + 'blue-infrastructure-graphics_11435264594_o.png',
To:
image: image_url + 'yellow-infrastructure-graphics_o.png',
When "data": [] contains 'tcs_cannot_route' and only the effected node the other nodes need to remain the same. Any help would be greatly appreciated!
UPDATE:
Of course this was on my mind over the weekend and I solved it right away this morning by making a small change in my template.
from:
<script>
var nodes = {{ network_nodes|safe }};
var edges = {{ network_edges|safe }};
</script>
to:
<script>
var nodes = new vis.DataSet({{ network_nodes|safe }});
var edges = new vis.DataSet({{ network_edges|safe }});
</script>
Then in my $.each I was able to add nodes.update()
$.each(JSON.parse(node), function(idx, obj){
var details = obj.data;
var id = obj.id;
for (var i = 0; i < details.length; ++i){
for(var ind in details[i]){
if(ind === 'tcs_cannot_route'){
console.log(id);
**nodes.update([{id:id, image: image_url + 'yellow-infrastructure-graphics_o.png'}])**
}
}
}
});

Populate grid with row/column coordinates in extjs

I'm trying to populate an extjs grid with data from json. The values I need to populate in the cells are in an object that gives the row and column number. I'm not sure how to get the values into the correct cells with this json structure.
Here is the json:
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/reports"
}
},
"columns" : [ {
"softwareBuild" : {
"buildId" : 10,
"generation" : "Alpha",
"build" : "1.0"
},
"eventTypeDisplay" : "Event Name 1"
}, {
"softwareBuild" : {
"buildId" : 10,
"generation" : "Beta",
"build" : "2.0"
},
"eventTypeDisplay" : "Event Name 1"
}],
"entries" : [ {
"row" : 0,
"column" : 0,
"value" : 10
}, {
"row" : 0,
"column" : 1,
"value" : 20
}, {
"row" : 1,
"column" : 0,
"value" : 30
}, {
"row" : 1,
"column" : 1,
"value" : 40
} ],
"rows" : [ {
"metricTypeId" : 1,
"metricName" : "Name 1",
"source" : "1",
}, {
"metricTypeId" : 2,
"metricName" : "Name 2",
"source" : "2",
}]
}
Here is the grid view:
Ext.create('Ext.grid.Panel', {
renderTo: document.body,
store: 'DataStore',
width: 400,
height: 200,
title: 'Software Metrics',
columns: [
{
text: 'Dynamic Column Name',
dataIndex: ''
}
]
});
Here is the model and store:
Ext.define('DataModel', {
extend: 'Ext.data.Model',
fields: [ 'value', 'generation', 'build', 'metricName', 'source' ]
});
Ext.define('DataStore', {
extend: 'Ext.data.Store'
model: 'DataModel',
proxy: {
type: 'rest',
url : 'api/reports'
}
});
Another question I have is how to populate the column headers with the "build" value from the columns array in the json object. And how to populate the cells in the first column with "metricName" from the rows array. But that could be for another question.
This is a process that will take time so I'll tell you what you need to do:
1 - Get your JSON structure and assign it to a variable, you should probably use Ext.Ajax.request for this.
2 - Loop through the columns object and create another object that is a valid column format for ExtJS something like:
var columns = [{
text : '1.0',
dataIndex: 'Alpha'
},{
text: '2.0',
dataIndex : 'Beta'
}];
3 - Apply the columns to your grid using grid.reconfigure(columns);
4 - Your model should have fields : ['Alpha', 'Beta']
5 - Your store should use a memory proxy now since your grabbed the data using Ext.Ajax.request.
6 - Loop through your entries object and get the total number of rows that should be added.
var entries = [{
"row" : 0,
"column" : 0,
"value" : 10
}, {
"row" : 0,
"column" : 1,
"value" : 20
}, {
"row" : 1,
"column" : 0,
"value" : 30
}, {
"row" : 1,
"column" : 1,
"value" : 40
}];
var rows = [];
for (var i=0;i<entries.length;i++) {
var currentRow = entries[i].row,
currentColumn = entries[i].column,
columnName = columns[currentColumn].dataIndex;
if(currentRow > rows.length - 1) {
rows.length = currentRow + 1;
}
if (!rows[currentRow]) rows[currentRow] = {};
rows[currentRow][columnName] = entries[i].value;
}
7 - Add assign the rows value to your store using store.loadRawData
Fiddle: https://fiddle.sencha.com/#fiddle/t2g

Javascript: Split array of arrays into multiple arrays

serious problem here, I have an array like this:
[[0,50],[0,68],[1,26],[2,9],[2,32]]
The form I need is to split this array into two separated arrays like this:
array1 = [[0,50][1,0][2,9]]
array2 = [[0,68][1,26][2,32]]
Yeah you are right guys, I need that to build flot chart.
If anybody interested in source of data this is how it looks in firebase:
{
"1433203200000" : {
"-JpgJnANTpQFprRieImv" : {
"events" : 5,
"name" : "Home office",
"returningVisitors" : 9,
"totalVisitors" : 50
},
"-JqsQjFTjHpzKqWgE_KJ" : {
"events" : 10,
"name" : "Samin Place",
"returningVisitors" : 32,
"totalVisitors" : 68
}
},
"1433289600000" : {
"-JqsQjFTjHpzKqWgE_KJ" : {
"name" : "Samin Place",
"newVisitors" : 1,
"returningVisitors" : 25,
"totalVisitors" : 26
}
},
"1433376000000" : {
"-JpgJnANTpQFprRieImv" : {
"events" : 5,
"name" : "Home office",
"returningVisitors" : 9,
"totalVisitors" : 9
},
"-JqsQjFTjHpzKqWgE_KJ" : {
"events" : 10,
"name" : "Samin Place",
"returningVisitors" : 32,
"totalVisitors" : 32
}
}
}
The point is loop each timestamp and each child, there we have totalVisitors that's the value I need for my chart.
BONUS
As you can see first timestamp have two childs thats fine, but second timestamp have only one child - "-JqsQjFTjHpzKqWgE_KJ" so I need to add null value for missing one into new array (in our example it's array1 second position).
That's what I'm calling CHALLENGE :)
Any help is very appreciated, thanks for attention.
Edit:
maybe if it can help to someone this is chart which I need
here is link
X-axis - are timestamps
Y-axis - totalVisitors value
Lines - every unique timestamp child
I created jsfiddle for you. Please tell, is it what you need?
http://jsfiddle.net/1vdryy3L/1/
// first, we'll get all possible keys ('key' is e.g. "-JpgJnANTpQFprRieImv")
var keys = [];
for (var i in data) {
for (var j in data[i]) {
if (keys.indexOf(j) == -1) {
keys.push(j);
}
}
}
var result = {}, tmp, k;
for (i in keys) {
tmp = []; k = 0;
for (var j in data) {
if (data[j][keys[i]]) {
tmp.push([k, data[j][keys[i]].totalVisitors]);
} else {
tmp.push([k, 0]);
}
k++;
}
result['array' + i] = tmp;
}
console.log(JSON.stringify(result));
Something like this should work provided that you are using jQuery. If you are not simply replace the jquery statements with standard js ones. (I have prepared a jsfiddle: jsfiddle:
var first = []
var second = [];
var my_data = {
"1433203200000" : {
"-JpgJnANTpQFprRieImv" : {
"events" : 5,
"name" : "Home office",
"returningVisitors" : 9,
"totalVisitors" : 50
},
"-JqsQjFTjHpzKqWgE_KJ" : {
"events" : 10,
"name" : "Samin Place",
"returningVisitors" : 32,
"totalVisitors" : 68
}
},
"1433289600000" : {
"-JqsQjFTjHpzKqWgE_KJ" : {
"name" : "Samin Place",
"newVisitors" : 1,
"returningVisitors" : 25,
"totalVisitors" : 26
}
},
"1433376000000" : {
"-JpgJnANTpQFprRieImv" : {
"events" : 5,
"name" : "Home office",
"returningVisitors" : 9,
"totalVisitors" : 9
},
"-JqsQjFTjHpzKqWgE_KJ" : {
"events" : 10,
"name" : "Samin Place",
"returningVisitors" : 32,
"totalVisitors" : 32
}
}
}
var count = 0;
$.each(my_data, function(key, value){
if (value["-JpgJnANTpQFprRieImv"]){
first.push([count, value["-JpgJnANTpQFprRieImv"]["totalVisitors"]])
} else {
first.push([count, 0])
}
if (value["-JqsQjFTjHpzKqWgE_KJ"]){
second.push([count, value["-JqsQjFTjHpzKqWgE_KJ"]["totalVisitors"]])
} else {
second.push([count, 0])
}
count++;
});

Categories

Resources