Get json data to html - arrays

I have a json data from a mysql table that is queried from a php script. The json data is coming correctly like this:
{"result":[["id","name","origin_count","destination_count"],[1,"A S Peta",0,0],[2,"Aachara",0,0],[3,"Aanjangaon",0,0],[4,"Aanjar",0,0], [5,"Aathankarai",0,0],[6,"Abu",0,0],[7,"Abu Road",0,0],[8,"Achanta",0,0], [9,"Addanki",0,0],[10,"Addavaram",0,0],[11,"Adipur",0,0]]}
I tried this code to get the data. But I cant able to access it.
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script>
$.getJSON("http://hex.com/cities.json",
function (data) {
var tr = data.result
for (var i = 0; i < data.result.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data.result[i].id + "</td>");
$(tr).append("<td>" + data.result[i].name + "</td>");
$(tr).append("<td>" + data.result[i].origin_count + "</td>");
$('.table1').append(tr);
}
});
</script>
<table class="table1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Origin</th>
</tr>
</table>
</body>
Please help me

You can modify your function like below
$.getJSON("http://hex.com/cities.json",
function(data) {
var tbody = $('.table1');
$.each(data.result, function(i, e) {
if (i > 0)
var tr = $('<tr>');
$('<td>').html(e[0]).appendTo(tr); // Id
$('<td>').html(e[1]).appendTo(tr); // Name
$('<td>').html(e[2]).appendTo(tr); // Origin
tbody.append(tr);
});
}
);
Here is Output from given json data
var data = {
"result": [
["id", "name", "origin_count", "destination_count"],
[1, "A S Peta", 0, 0],
[2, "Aachara", 0, 0],
[3, "Aanjangaon", 0, 0],
[4, "Aanjar", 0, 0],
[5, "Aathankarai", 0, 0],
[6, "Abu", 0, 0],
[7, "Abu Road", 0, 0],
[8, "Achanta", 0, 0],
[9, "Addanki", 0, 0],
[10, "Addavaram", 0, 0],
[11, "Adipur", 0, 0]
]
};
var tbody = $('.table1');
$.each(data.result, function(i, e) {
if (i > 0)
var tr = $('<tr>');
$('<td>').html(e[0]).appendTo(tr); // Id
$('<td>').html(e[1]).appendTo(tr); // Name
$('<td>').html(e[2]).appendTo(tr); // Origin
tbody.append(tr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Origin</th>
</tr>
</table>

<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script>
$.getJSON("http://hex.com/cities.json",
function (data) {
var tr = data.result
for (var i = 1; i < data.result.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data.result[i][0] + "</td>");
$(tr).append("<td>" + data.result[i][1] + "</td>");
$(tr).append("<td>" + data.result[i][2] + "</td>");
$('.table1').append(tr);
}
});
</script>
<table class="table1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Origin</th>
</tr>
</table>
</body>
Just change the 'data.result[i].id' to 'data.result[i][0] and for other columns.

You have a data structured like this
{
"result": [
["id", "name", "origin_count", "destination_count"],
[1, "A S Peta", 0, 0],
[2, "Aachara", 0, 0],
[3, "Aanjangaon", 0, 0],
[4, "Aanjar", 0, 0],
[5, "Aathankarai", 0, 0],
[6, "Abu", 0, 0],
[7, "Abu Road", 0, 0],
[8, "Achanta", 0, 0],
[9, "Addanki", 0, 0],
[10, "Addavaram", 0, 0],
[11, "Adipur", 0, 0]
]
}
It is a valid JSON object, but what are you trying to do:
$(tr).append("<td>" + data.result[i].id + "</td>");
You try to access ith elemnent of array, but next, you try to get specific property, but you do not have properties in your subarrays. There are only values as array elements.
I suggest you to change (if possible) response format to similar to this, since it is much easier to iterate and access deeper nested data.
{
"result": [{
"id": 2,
"name": "Aachara",
"origin_count": 0,
"destination_count": 0
},
{
"id": 3,
"name": "Aanjangaon",
"origin_count": 0,
"destination_count": 0
} ...
]
}
And then it would be possible to access values by a dot operator
data.result[i].id

Related

react-google-chart not highlighted the mexicon states while in geochart mode

I am using react-google-chart. As per knowledge i am trying my level best to get the result but i stuck in the maxico states.Below is the code that i used please review it
I am trying to highlight the Mexican states but don't know where I am doing mistakes.
const [geoDataMX, setgeoDataMX] = useState([
["RegionCode",'State', 'Popularity'],
["MX-CH",'MX-CH', 0],
["MX-SO",'MX-SO', 0],
["MX-CO",'MX-Coahuila', 0],
["MX-DG",'MX-Durango', 0],
["MX-OA",'MX-Oaxaca', 0],
["MX-TM",'MX-Tamaulipas', 0],
["MX-JA",'Jalisco', 0],
["MX-ZA",'Zacatecas', 0],
["MX-BS",'Baja California Sur', 0],
["MX-CS",'Chiapas', 0],
["MX-VE",'Veracruz', 0],
["MX-BC",'Baja California', 0],
["MX-NL",'Nuevo Leon', 0],
["MX-GR",'Guerrero', 0],
["MX-SL",'San Luis Potosi', 0],
["MX-MI",'Michoacan', 0],
["MX-SI",'Sinaloa', 0],
["MX-CM",'Campeche', 0],
["MX-QR",'Quintana Roo', 0],
["MX-YU",'Yucatan', 0],
["MX-PU",'Puebla', 0],
["MX-GT",'Guanajuto', 0],
["MX-NA",'Nayarit', 0],
["MX-TB",'Tabasco', 0],
["MX-EM",'Mexico', 0],
["MX-HG",'Hidalgo', 0],
["MX-QT",'Queretaro', 0],
["MX-CL",'Colima', 0],
["MX-AG",'Aguascalientes', 0],
["MX-MO",'Morelos', 0],
["MX-TL",'Tlaxcala', 0],
["MX-DF",'Mexico City', 0]
]);
const [optionsMX] = useState({
sizeAxis: { minValue: 0, maxValue: 100 },
region: 'MX',
colorAxis: {
colors: ['#f5f5f5', 'red'],
values: [0, 19]
},
dataMode: 'markers',
resolution: 'provinces',
legend: 'yes',
});
<Chart
width={'100%'}
height={'100%'}
chartType="GeoChart"
data={geoDataMX}
options={optionsMX}
/>
Please help me to find out the error.

how can i create a multidimentianal array that is completely editable in react?

so I am having some trouble creating a multidimensional array that is completely editable. I have static data now set up in a table:
export const scores = [
[0, 0, 4, 4, 0, 4],
[0, 0, 4, 4, 4, 7],
[0, 1, 4, 4, 4, 7],
[0, 4, 7, 7, 7, 7],
[0, 0, 0, 0, 2, 7],
];
I'm thinking I need to convert it to state, and make the data table static but i'm not sure on what the best approach would be for this. essentually I am looking to make each cell of this table editable and update as the values are entered.
The basic idea is to do a nested loop. On you change handler for each element, may sure to make a copy of both the row and the entire grid so that you don't mutate old state.
The following accomplishes this with buttons for each element, but could be adapted for other input types.
const {useState, Fragment} = React;
const initial = [
[0, 0, 4, 4, 0, 4],
[0, 0, 4, 4, 4, 7],
[0, 1, 4, 4, 4, 7],
[0, 4, 7, 7, 7, 7],
[0, 0, 0, 0, 2, 7],
];
const App = () => {
const [scores, setScores] = useState(initial);
return scores.map((row, i) => {
return (
<Fragment key={i}>
{row.map((el, j) => {
return (
<button
key={i + "-" + j}
onClick={() => {
const rowCopy = [...row];
rowCopy[j] = el + 1;
const gridCopy = [...scores];
gridCopy[i] = rowCopy;
setScores(gridCopy);
}}
>
{el}
</button>
);
})}
<br />
</Fragment>
);
});
};
// Render it
ReactDOM.render(
<App />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Tensorflow.js cropping image return zeros tensor

I have a custom model which takes in cropped faces from BlazeFace Model then outputs a prediction of 3 classes.
Before sending them to my custom model I resize the cropped faces to be of shape [1,224,224,3]
Output at every prediction:
Float32Array [
6.522771905936864e-11,
3.698188456857654e-12,
1,
]
Code for resizing the cropped faces and making predictions:
const getPrediction = async tensor => {
if (!tensor) {
console.log("Tensor not found!");
}
// Load both models
const bfModel = await blazeFaceModel;
const returnTensors = true;
const faces = await bfModel
.estimateFaces(tensor, returnTensors)
.catch(e => console.log(e));
// Reshape tensor from rank 3 to rank 4
const tensorReshaped = tensor.reshape([1, 224, 224, 3]);
const scale = {
height: styles.camera.height / tensorDims.height,
width: styles.camera.width / tensorDims.width
};
// Faces is an array of objects
if (!isEmpty(faces)) {
// Setting faces in state
setModelFaces({ faces });
}
//Looping over array of objects in faces
faces.map((face, i) => {
const { topLeft, bottomRight } = face;
const width = Math.floor(
bottomRight.dataSync()[0] - topLeft.dataSync()[0] * scale.width
);
const height = Math.floor(
bottomRight.dataSync()[1] - topLeft.dataSync()[1] * scale.height
);
const boxes = tf
.concat([topLeft.dataSync(), bottomRight.dataSync()])
.reshape([-1, 4]);
// Cropping out faces from original tensor
const crop = tf.image.cropAndResize(
tensorReshaped,
boxes,
[0],
[height, width]
);
// Resize cropped faces to [1,224,224,3]
const alignCorners = true;
const imageResize = tf.image.resizeBilinear(
crop,
[224, 224],
alignCorners
);
makePrediction(imageResize);
});
};
// Make predictions on the tensors
const makePrediction = async image => {
if (!image) {
console.log("No input!");
}
const model = await loadedModel;
const prediction = await model.predict(image, { batchSize: 1 });
if (!prediction || isEmpty(prediction)) {
console.log("Prediction not available");
}
console.log(prediction);
console.log(prediction.dataSync());
};
EDIT
I tried changing the batch size when making predictions to 1 and still the same issue
I tried reconverting the keras model to tfjs format and still the same issue
I tried disposing of the tensor after making a prediction but still there is an error
So i printed out the tensors of the resized faces and its a lot of 0's
Tensor before prediction
Tensor
[[[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
...
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]]]
undefined
Tensor during prediction
Tensor
[[[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
...
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
...,
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]]]
undefined
boxes of tf.image.cropAndResize are normalized coordinates between 0 and 1. Therefore topLeft and bottomRight should be normalized by using [imageWidth, imageHeight]
normalizedTopLeft = topLeft.div(tensor.shape.slice(-3, -2))
// slice will get [h, w] of a tensor of shape [b, h, w, ch] or [h, w, ch]
// do likewise for bottomRight
// use normalizedTopLeft instead of topLeft for cropping

ng-repeat with array of arrays

I have dynamic inputData array (length can be between 0 and 10 or 15) that looks something like this:
$scope.inputData = [
[1, 2, 3, 4, 5, 6, 7];
[1, 2, 3, 4, 5, 6, 7];
[1, 2, 3, 4, 5, 6, 7];
[1, 2, 3, 4, 5, 6, 7];
[1, 2, 3, 4, 5, 6, 7];
[1, 2, 3, 4, 5, 6, 7];
]
I need to generate td in the table with ng-repeat so I could have an only first item from each "sub-array" in the first iteration. Then only second item from each "sub-array", etc.. So table should be
th th th th th th
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
...
And ng repeat should switch indexes in each iteration.
// first iteration:
<td ng-repeat="item in inputData track by $index">{{item[0]}}</td>
// second iteration:
<td ng-repeat="item in inputData track by $index">{{item[1]}}</td>
...
Can I somehow solve this only using ng-repeat or should I sort my arrays in the controller?
Try this:
angular.module('app', []).controller('ctrl', function($scope) {
$scope.inputData = [
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7]
]
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<table ng-app='app' ng-controller='ctrl'>
<tbody>
<tr ng-repeat='array in inputData' ng-init='parentIndex=$index'>
<td ng-repeat='item in array'>{{array[parentIndex]}}
<td>
</tr>
</tbody>
</table>
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Example</title>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script>
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
var items = [
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7]
];
$scope.items_transpose = transpose(items);
function transpose(a) {
// Calculate the width and height of the Array
var w = a.length || 0;
var h = a[0] instanceof Array ? a[0].length : 0;
// In case it is a zero matrix, no transpose routine needed.
if(h === 0 || w === 0) { return []; }
/**
* #var {Number} i Counter
* #var {Number} j Counter
* #var {Array} t Transposed data is stored in this array.
*/
var i, j, t = [];
// Loop through every item in the outer array (height)
for(i=0; i<h; i++) {
// Insert a new row (array)
t[i] = [];
// Loop through every item per item in outer array (width)
for(j=0; j<w; j++) {
// Save transposed data.
t[i][j] = a[j][i];
}
}
return t;
}
});
</script>
</head>
<body ng-controller="MainCtrl">
<table>
<tr ng-repeat="item in items_transpose track by $index">
<td ng-repeat="i in item track by $index">{{i}}</td>
</tr>
</table>
</body>
</html>

which tasks can simple perceptron perform?

I'm trying to teach simple single neuron perceptron to recognize repetitive sequences of 1.
here is data I use to teach it:
learning_signals = [
[[1, 1, 0, 0], 1],
[[1, 1, 0, 1], 1],
[[1, 1, 1, 0], 1],
[[0, 1, 1, 0], 1],
[[0, 1, 1, 1], 1],
[[0, 0, 1, 1], 1],
[[1, 0, 1, 1], 1],
[[0, 0, 0, 0], 0],
[[1, 0, 0, 0], 0],
[[0, 1, 0, 0], 0],
[[0, 0, 1, 0], 0],
[[0, 0, 0, 1], 0],
[[1, 0, 1, 0], 0],
[[1, 0, 0, 1], 0],
# [[0, 1, 0, 1], 0],
This is the array of learning templates each of them are array of data and correct result for that data.
As you see. last row commented - if I do uncomment it - perceptron will fail to learn. without it perceptron does not work right in case with "0101". So the question is:
Is this task can be solved with single neuron perceptron or should I use few layered perceptron?
How can I determine which tasks can be solved with such a simple perceptron? Are there any rule that I can apply to my task and say that it could be done with simple perceptron?
here is the code of perceprton written in coffeescript:
class window.Perceptron
weights: []
calc: (signal) ->
#neuron.calc signal
adjust: ->
foo: 0.1
calc: (signal) ->
sum = 0
for s, i in signal
sum += s*#weights[i]
if sum>0.5 then return 1 else return 0
sum
learn: (templates) ->
#weights = []
for i in [1..templates[0][0].length]
#weights.push Math.random()
li = 0
max_li = 50000
console.log #weights
while true
gerror = 0
li++
for template, i in templates
res = #calc template[0]
# console.log "result: #{res}"
error = template[1] - res
gerror += Math.abs error
for weight, i in #weights
#weights[i] += #foo*error*template[0][i]
if ((gerror == 0) || li > max_li) then break
if gerror == 0
console.log "Learned in #{li} iterations"
else
console.log "Learning failed after #{max_li} iterations"
console.log #weights

Resources