amCharts not displaying when the page loads in AngularJs - angularjs

I am using amCharts to display some data and calling this in my init function. The following is my code:
export default class ACtrl {
constructor($scope, $http, $state) {
var sampleCharts = function () {
let sampleChart;
let sampleBarGraph;
let sampleLine;
const writeAlarmsample = data => {
const {
total,
users
} = data;
// Set cumulative percentage
let runningTotal = 0;
users.forEach(user => {
runningTotal += user.assetAvailability;
user.cumulativePercentage = runningTotal / total * 100;
});
sampleChart.dataProvider = users;
sampleChart.write('userAvailability');
sampleChart.validateData();
};
function handleClick(event){
$state.go("app.userdetails", { userID: event.item.category });
}
// Alarm sample
AmCharts.ready(() => {
sampleChart = new AmCharts.AmSerialChart();
sampleChart.categoryField = "assetId";
//add click listener
sampleChart.addListener("clickGraphItem", handleClick);
var yAxis = new AmCharts.ValueAxis();
yAxis.position = "left";
sampleChart.addValueAxis(yAxis);
var yAxis2 = new AmCharts.ValueAxis();
yAxis2.position = "right";
sampleChart.addValueAxis(yAxis2);
sampleBarGraph = new AmCharts.AmGraph();
sampleBarGraph.valueField = "userAvailability";
sampleBarGraph.type = "column";
sampleBarGraph.fillAlphas = 1;
sampleBarGraph.lineColor = "#f0ab00";
sampleBarGraph.valueAxis = yAxis;
sampleChart.addGraph(sampleBarGraph);
sampleLine = new AmCharts.AmGraph();
sampleLine.valueField = "cumulativePercentage";
sampleLine.type = "line";
sampleLine.lineColor = "#cb0044";
sampleLine.valueAxis = yAxis2;
sampleChart.addGraph(sampleLine);
sampleChart.write('userAvailability');
$http.get(constants.LOCAL_HOST+"/dashboard/users")
.then(response => writeAlarmsample(response.data));
});
};
$scope.init = function() {
availabilityCharts();
};
})
}
The charts load fine when I hit the refresh button, but they are not loaded when the page gets loaded for the first time. I also have a refresh button which calls the function to load the charts even that does not load the charts. If I click on one of the chart items it takes me to details page and when I come back to this page the charts do not load. I have to click on refresh again to load the charts. Can anyone let me know what is the reason for this issue and how I can fix it.

Related

Tensorflow.js prediction result doesn't change

I trained my model with Google Teachable Machines (Image) and inclueded the model into my Ionic Angular app. I loaded the model successfully and used the camera preview for predicting the class which is shown in the image from the camera.
The picture which is displayed in the canvas changes properly but the predict()-method returns the same result for every call.
import * as tmImage from '#teachablemachine/image';
...
async startPrediction() {
this.model = await tmImage.load(this.modelURL, this.metadataURL);
this.maxPredictions = this.model.getTotalClasses();
console.log('classes: ' + this.maxPredictions); //works properly
requestAnimationFrame(() => {
this.loop();
});
}
async loop() {
const imageAsBase64 = await this.cameraPreview.takeSnapshot({ quality: 60 });
const canvas = document.getElementById('output') as HTMLImageElement;
//image changes properly, I checked it with a canvas output
canvas.src = 'data:image/jpeg;base64,' + imageAsBase64;
const prediction = await this.model.predict(canvas);
for (let i = 0; i < this.maxPredictions; i++) {
const classPrediction =
prediction[i].className + ': ' + prediction[i].probability.toFixed(2);
//probability doesn't change, even if I hold the camera close over a trained image
}
requestAnimationFrame(() => {
this.loop();
});
}
The prediction result is e.g.: class1 = 0.34, class2 = 0.66 but doesn't change.
I hope you could help me to find my bug, thanks in advance!
The image has probably not yet been loaded before you are calling the prediction model. It has been discussed here and there
function load(url){
return new Promise((resolve, reject) => {
canvas.src = url
canvas.onload = () => {
resolve(canvas)
}
})
}
await load(base64Data)
// then the image can be used for prediction

React Amchart - How to remove animation when loading charts

I am using amcharts in the React Hooks environment.
I'm using force-directed-tree.
https://www.amcharts.com/demos/force-directed-tree/
The data applied to the chart is filtered based on high values and then reapplying.
Every time the data is reapply, the chart is rendered and the animation continues to be applied.
How to remove animation when loading charts
Or we would appreciate it if you could tell us how to apply the scrollbar provided by amcharts to this chart.
useEffect(() => {
const chart = am4core.create('networkChart', am4plugins_forceDirected.ForceDirectedTree);
const networkSeries = chart.series.push(new am4plugins_forceDirected.ForceDirectedSeries());
chart.data = data;
chart.dataSource.updateCurrentData = true;
chart.animationPlayed = true;
chart.dataSource.reloadFrequency = 1000;
networkSeries.dataFields.id = 'name';
networkSeries.dataFields.value = 'value';
networkSeries.dataFields.name = 'name';
networkSeries.dataFields.children = 'children';
networkSeries.nodes.template.tooltipText = '{name}:{value}';
networkSeries.nodes.template.fillOpacity = 1;
networkSeries.manyBodyStrength = -20;
networkSeries.links.template.strength = 0.8;
networkSeries.links.template.distance = 1;
networkSeries.minRadius = am4core.percent(3);
networkSeries.maxRadius = am4core.percent(10);
networkSeries.nodes.template.label.text = '{name}';
networkSeries.fontSize = 12;
networkSeries.maxLevels = 4;
networkSeries.events.disableType('inited', function() {
networkSeries.animate(
{
property: 'velocityDecay',
to: 1,
},
3000,
);
});
// Add Legend
chart.legend = new am4charts.Legend();
chart.legend.labels.template.fill = am4core.color('#fff');
}, [data]);
I didn't want the these to be used, so I used the unuseTheme and passed the animation theme to it. This removed the animations with respect to the chart.
Example:
am4core.unuseTheme(am4themesAnimated);
To Add scrollbar
let chart = am4core.create("chartdiv", am4charts.XYChart);
...
let scrollbarX = new am4charts.XYChartScrollbar();
scrollbarX.series.push(networkSeries);
chart.scrollbarX = scrollbarX;
https://www.amcharts.com/docs/v4/tutorials/customizing-chart-scrollbar/

Update texture of mesh using ThreeJS & Dat.Gui

I would like the texture of my Mesh to update when clicked on function.
When you click on the 'UpdateMateria' function i'd like the mesh to dispose its current texture and add a new one.
Animation Loop
startAnimationLoop = () => {
const tableBoard = this.scene.getObjectByName('tableSurface');
tableBoard.material.map = this.updateMateria;
this.renderer.render(this.scene, this.camera);
this.requestID = window.requestAnimationFrame(this.startAnimationLoop);
};
Dat.Gui
userGUI = () => {
const update = {
updateMateria: function() {
alert('Changing');
this.material.dispose();
this.material.map = texture1();
}
}
this.gui = new dat.GUI();
const controls = function() {
this.title = new controls();
this.gui.add(update, 'updateMateria')
}
}
When i put the function straight into the 'Animation Loop' this actually updates the texture to the desired one, but the current version gives me 'TypeError: Cannot read property 'dispose' of undefined'
First, you can not use the this reference in updateMateria (probably updateMaterial???). Consider to safe the this reference in a variable outside of this function and use this variable instead. Besides, it's not necessary to dispose the material if you just want to change the texture.
userGUI = () => {
const scope = this;
const update = {
updateMateria: function() {
alert('Changing');
// scope.material.dispose();
scope.material.map = texture1();
}
}
this.gui = new dat.GUI();
const controls = function() {
this.title = new controls();
this.gui.add(update, 'updateMateria')
}
three.js R108

Adding check boxes in AmCharts

I am working o an AngularJs Application where I am using AmCharts.
const writeemp = data => {
const {
total,
employees,
} = data;
empChart.dataProvider = e;
empChart.write('emp');
empChart.validateData();
};
AmCharts.handleLoad();
var configChart = function () {
empChart = new AmCharts.AmSerialChart();
empChart.categoryField = "state";
empChart.labelRotation = 90;
var yAxis = new AmCharts.ValueAxis();
yAxis.position = "left";
empChart.addValueAxis(yAxis);
empBarGraph = new AmCharts.AmGraph();
empBarGraph.valueField = "count";
empBarGraph.type = "column";
empBarGraph.fillAlphas = 1;
empBarGraph.lineColor = "#f0ab00";
empBarGraph.valueAxis = yAxis;
empChart.addGraph(empBarGraph);
empChart.write('empChart');
$http.get(hostNameService.getHostName()+"/dashboard/employees/statecount")
.then(response => writeemp(response.data));
}
Code in html:
<div class='panel-body'>
<div id="empChart"></div>
</div>
This would return me the values of State on x-axis and count on y-axis. I wanted to add checkboxes which would filter my data in the chart. Each check box should represent the 'state' of the employee. If I uncheck a box then the data displayed should change in the chart. Can anyone let me know how I could achieve this.

accessing items in firebase

I'm trying to learn firebase/angularjs by extending an app to use firebase as the backend.
My forge looks like this
.
In my program I have binded firebaseio.com/projects to $scope.projects.
How do I access the children?
Why doesn't $scope.projects.getIndex() return the keys to the children?
I know the items are in $scope.projects because I can see them if I do console.log($scope.projects)
app.js
angular.module('todo', ['ionic', 'firebase'])
/**
* The Projects factory handles saving and loading projects
* from localStorage, and also lets us save and load the
* last active project index.
*/
.factory('Projects', function() {
return {
all: function () {
var projectString = window.localStorage['projects'];
if(projectString) {
return angular.fromJson(projectString);
}
return [];
},
// just saves all the projects everytime
save: function(projects) {
window.localStorage['projects'] = angular.toJson(projects);
},
newProject: function(projectTitle) {
// Add a new project
return {
title: projectTitle,
tasks: []
};
},
getLastActiveIndex: function () {
return parseInt(window.localStorage['lastActiveProject']) || 0;
},
setLastActiveIndex: function (index) {
window.localStorage['lastActiveProject'] = index;
}
}
})
.controller('TodoCtrl', function($scope, $timeout, $ionicModal, Projects, $firebase) {
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
var keys = $scope.projects.$getIndex();
console.log($scope.projects.$child('-JGTmBu4aeToOSGmgCo1'));
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("" + keys[0]);
});
// A utility function for creating a new project
// with the given projectTitle
var createProject = function(projectTitle) {
var newProject = Projects.newProject(projectTitle);
$scope.projects.$add(newProject);
Projects.save($scope.projects);
$scope.selectProject(newProject, $scope.projects.length-1);
};
// Called to create a new project
$scope.newProject = function() {
var projectTitle = prompt('Project name');
if(projectTitle) {
createProject(projectTitle);
}
};
// Called to select the given project
$scope.selectProject = function(project, index) {
$scope.activeProject = project;
Projects.setLastActiveIndex(index);
$scope.sideMenuController.close();
};
// Create our modal
$ionicModal.fromTemplateUrl('new-task.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope
});
$scope.createTask = function(task) {
if(!$scope.activeProject || !task) {
return;
}
console.log($scope.activeProject.task);
$scope.activeProject.task.$add({
title: task.title
});
$scope.taskModal.hide();
// Inefficient, but save all the projects
Projects.save($scope.projects);
task.title = "";
};
$scope.newTask = function() {
$scope.taskModal.show();
};
$scope.closeNewTask = function() {
$scope.taskModal.hide();
};
$scope.toggleProjects = function() {
$scope.sideMenuController.toggleLeft();
};
// Try to create the first project, make sure to defer
// this by using $timeout so everything is initialized
// properly
$timeout(function() {
if($scope.projects.length == 0) {
while(true) {
var projectTitle = prompt('Your first project title:');
if(projectTitle) {
createProject(projectTitle);
break;
}
}
}
});
});
I'm interested in the objects at the bottom
console.log($scope.projects)
Update
After digging around it seems I may be accessing the data incorrectly. https://www.firebase.com/docs/reading-data.html
Here's my new approach
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
console.log(snapshot.val()['-JGTdgGAfq7dqBpSk2ls']);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
I'm still not sure how to traverse the keys programmatically but I feel I'm getting close
It's an object containing more objects, loop it with for in:
for (var key in $scope.projects) {
if ($scope.projects.hasOwnProperty(key)) {
console.log("The key is: " + key);
console.log("The value is: " + $scope.projects[key]);
}
}
ok so val() returns an object. In order to traverse all the children of projects I do
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
var keys = Object.keys(snapshot.val());
console.log(snapshot.val()[keys[0]]);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
Note the var keys = Object.keys() gets all the keys at firebaseio.com/projects then you can get the first child by doing snapshot.val()[keys[0])

Resources