Flutter put request for Database - json

I am working on a Flutter app. we have a PSQL database, Node server on the background. On the Flutter app I am displaying some geometry which I fetch from the database successfully. Now after a modification on the geometry, such as lines, I want to be able to update the database via a put request.
Server goes like:
app.put('/api/shape/:id', async (req,res) =>{
let answer;
if( req.body.shape_type == "line"){
answer = await db.db.modify_line(req.params.id, req.body.info_shape);
}
res.send(answer);
});
And db.js file goes like:
modify_line : async function(id_shape, info_shape){
console.log(info_shape);
const result = await send_query("UPDATE line SET line = $2 WHERE id_shape = $1", [id_shape, info_shape]);
return(result);
},
On the Flutter app I do this:
_makeUpdateRequest() async {
var url = globals.URL + 'api/shape/' + globals.selectedShapeID.toString();
Map data;
if (globals.selectedType == globals.Type.line) {
String lseg = "(" + globals.pLines[globals.selectedLineIndex].p1.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p1.dy.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dy.toString() + ")";
data = {
'shape_type': 'line',
'info_shape': {
'id_shape': globals.selectedShapeID.toString(),
'line': lseg,
}
};
}
http.Response response;
try {
//encode Map to JSON
print("encode Map to JSON");
var body = json.encode(data);
print(body);
response =
await http.put(url,
headers: {
"Content-Type": "application/json"
},
body: body
).catchError((error) => print(error.toString()));
} catch (e) {
print(e);
}
return response;
}
Database "line" table contains a "shapeID" and "lseg" information on each row.
Currently I am getting an error when I try this code:
{ id_shape: '619',
line: '(19.5,100.6,20.5,50.9)' }
fail____error: invalid input syntax for type lseg: "{"id_shape":"619","line":"(-19.5,100.6,20.5,50.9)"}"
How shall I shape my lseg json?
Thanks

Well, it looks like to me you are passing the whole input_shape object to the SQL query, which looks like this, as per your console.log:
{
id_shape: '619',
line: '(19.5,100.6,20.5,50.9)'
}
Obviously, this is invalid for PostgreSQL.
I would say that your backend code should be more like this:
modify_line : async function(id_shape, info_shape){
console.log(info_shape);
const result = await send_query(
"UPDATE line SET line = $2 WHERE id_shape = $1",
// Reference "line" sub-object
[id_shape, info_shape.line],
);
return(result);
},
You should also pay attention to the Geometric types format for lines:
[ ( x1 , y1 ) , ( x2 , y2 ) ]
( ( x1 , y1 ) , ( x2 , y2 ) )
( x1 , y1 ) , ( x2 , y2 )
x1 , y1 , x2 , y2
I'm not 100% sure by reading this that your format (with leading and trailing parenthesis) is correct.

As the issue is solved, following is the answer:
DB.js is like:
modify_line : async function(id_shape, info_shape){
const result = await send_query("UPDATE line SET line = $2 WHERE id_shape = $1", [info_shape['id_shape'], info_shape['line']]);
return(result);
},
and Flutter app is like:
_makeUpdateRequest() async {
var url = globals.URL + 'api/shape/' + globals.selectedShapeID.toString();
Map data;
if (globals.selectedType == globals.Type.line) {
String lseg =
"[" + globals.pLines[globals.selectedLineIndex].p1.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p1.dy.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dy.toString() + "]";
data = {
'shape_type': 'line',
'info_shape': {
'id_shape': globals.selectedShapeID.toString(),
'line': lseg,
}
};
}
http.Response response;
try {
//encode Map to JSON
print("encode Map to JSON");
var body = json.encode(data);
print(body);
response =
await http.put(url,
headers: {
"Content-Type": "application/json"
},
body: body
).catchError((error) => print(error.toString()));
} catch (e) {
print(e);
}
return response;
}

Related

Showing the Val Acc in tensorflow.js

So I'm new to tensorflow.js and I have been trying to practice with an exercise.
I have a json dataset and I want to show the val acc but all the example that I could find had .csv data sets. I would appreciate it if anyone could send me a link to such an example so I can better understand or to explain it here in the answers.
Here is what I'm doing:
const trainingData = tf.tensor1d(horses.map(item =>
findAvg( filterOdds(item.prices))
))
const testingData = tf.tensor1d(horsesTesting.map(item =>
findAvg( filterOdds(item.prices))
));
const outputData = tf.tensor2d(horses.map(item => [
item.position === 1 ? 1 : 0,
item.position !== 1 ? 1 : 0,
// item.position != 1 ? 1 : 0,
]))
model.fit(trainingData, outputData, {epochs: 10})
.then((history) => {
// console.log(history)
model.predict(testingData).print()
})
Output: 4404ms 184us/step - acc=0.890 loss=0.0866 precision=0.00
what I found in the examples:
const trainingUrl1 = 'wdbc-train.csv';
// Take a look at the 'wdbc-train.csv' file and specify the column
// that should be treated as the label in the space below.
// HINT: Remember that you are trying to build a classifier that
// can predict from the data whether the diagnosis is malignant or benign.
const trainingData = tf.data.csv(trainingUrl1, {
columnConfigs: {
diagnosis: {
isLabel: true
}
}
});
const convertedTrainingData = // YOUR CODE HERE
trainingData.map(({xs, ys}) => {
return{ xs: Object.values(xs), ys: Object.values(ys)};
}).batch(10);
const testingUrl2 = 'wdbc-test.csv';
const testingData = tf.data.csv(testingUrl2, {
columnConfigs: {
diagnosis: {
isLabel: true
}
}
});
const convertedTestingData = // YOUR CODE HERE
testingData.map(({xs, ys}) => {
return{ xs: Object.values(xs), ys: Object.values(ys)};
}).batch(10);
await model.fitDataset(convertedTrainingData,
{epochs:35,
validationData: convertedTestingData,
callbacks:{
onEpochEnd: async(epoch, logs) =>{
console.info("Epoch: " + epoch + " Loss: " + logs.loss + " Accuracy: " + logs.acc + " val_acc " + logs.val_acc);
}
}});
Output:
Epoch: 1 Loss: 0.08664028346538544 Accuracy: 0.784 val_acc 0.919
There are two options for loading the dataset already discussed in this answer:
convert json to csv and then use the csvDataSet loader
create a custom loader using json. The csvDataSet loader here can help started
Regarding acc and val_acc, the first is for the training data and the second for the testing data

Invalid Json Response when accessing third-party service with Wix Corvid

I am attempting to gather details about real estate properties through an external API. I've gone over their documentation relentlessly but can not figure out why I am receiving the following error:
invalid json response body at https://api.gateway.attomdata.com/propertyapi/v1.0.0/property/expandedprofile?address1=34%20Karen%20Court&address2=Bridgeport20%CT reason: Unexpected token < in JSON at position
For reference, I am posting my code. If anyone can provide any input or guidance I would greatly appreciate it!
Backend Code:
import { fetch } from 'wix-fetch';
import { wixData } from 'wix-data';
export function getDetails(address, citystatezip) {
const url = 'https://api.gateway.attomdata.com/propertyapi/v1.0.0/property/expandedprofile?address1=' + address + "&address2=" + citystatezip;
let headers = {
"apikey": "xxxxxxxx",
"accept": "application/json"
};
let options = {
headers: headers
}
console.log("Url: " + url);
return fetch(url, { method: 'get' })
.then(response => {
return response.json();
})
.then((data) => {
console.log(data);
return data;
});
}
Page Code:
wixWindow.getCurrentGeolocation()
.then((obj) => {
let timestamp = obj.timestamp; // 1495027186984
let latitude = obj.coords.latitude; // 32.0971036
let longitude = obj.coords.longitude; // 34.774391099999995
let altitude = obj.coords.altitude; // null
let accuracy = obj.coords.accuracy; // 29
let altAccuracy = obj.coords.altitudeAccuracy; // null
let heading = obj.coords.heading; // null
let speed = obj.coords.speed;
console.log(obj)
reverse(latitude, longitude)
.then(geocode => {
console.log(geocode)
let id = geocode.results[0].place_id;
details(id)
.then(detailed => {
console.log(detailed)
$w("#input12").value = geocode.results[0].address_components[0].long_name + " " + geocode.results[0].address_components[1].long_name;
$w("#input10").value = geocode.results[0].address_components[3].long_name;
$w("#input11").value = geocode.results[0].address_components[5].long_name;
$w("#text37").text = geocode.results[0].formatted_address;
$w("#googleMaps2").location = {
"latitude": latitude,
"longitude": longitude,
"description": geocode.results[0].formatted_address
};
let address = geocode.results[0].address_components[0].long_name + " " + geocode.results[0].address_components[1].long_name;
let city = geocode.results[0].address_components[3].long_name;
let state = geocode.results[0].address_components[5].short_name;
let citystate = city +"%2C" + "%20" + state;
console.log(citystate)
const uri = address;
const encoded = encodeURI(uri);
console.log(encoded);
getDetails(encoded, citystate)
.then(got => {
console.log(got)
})
});
});
Thank you in advance for any input or guidance you can offer. I have spent hours trying to figure this out to no avail.
Stay safe and stay well 😊

Autodesk.DesignAutomation returning Unexpected token S in JSON at position 0 when calling the workitem api

I am facing a new issue with a fetch
handleSendToForge(e) {
e.preventDefault();
let formData = new FormData();
formData.append('data', JSON.stringify({
Width: this.state.Width,
Length: this.state.Length,
Depth: this.state.Depth,
Thickness: this.state.Thickness,
BottomThickness: this.state.BottomThickness,
rebarSpacing: this.state.rebarSpacing,
outputrvt: this.state.outputrvt,
bucketId: this.state.bucketId,
activityId: 'RVTDrainageWebappActivity',
objectId: 'template.rvt'
}));
this.setState({
form: formData
})
fetch('designautomation', {
method: 'POST',
body: formData,
//headers: {
// //'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
//},
})
.then(response => response.json())
.then(data => { console.log(data) })
.catch(error => console.log(error));
}
and the code for the controller is pretty standard and is slightly modified from one of the forge examples
[HttpPost]
[Route("designautomation")]
public async Task<IActionResult> Test([FromForm] StartWorkitemInput input)
{
JObject workItemData = JObject.Parse(input.data);
double Width = workItemData["Width"].Value<double>();
double Length = workItemData["Length"].Value<double>();
double Depth = workItemData["Depth"].Value<double>();
double Thickness = workItemData["Thickness"].Value<double>();
double BottomThickness = workItemData["BottomThickness"].Value<double>();
double rebarSpacing = workItemData["rebarSpacing"].Value<double>();
string outputrvt = workItemData["outputrvt"].Value<string>();
string activityId = workItemData["activityId"].Value<string>();
string bucketId = workItemData["bucketId"].Value<string>();
string objectId = workItemData["objectId"].Value<string>();
// basic input validation
string activityName = string.Format("{0}.{1}", NickName, activityId);
string bucketKey = bucketId;
string inputFileNameOSS = objectId;
// OAuth token
dynamic oauth = await OAuthController.GetInternalAsync();
// prepare workitem arguments
// 1. input file
dynamic inputJson = new JObject();
inputJson.Width = Width;
inputJson.Length = Length;
inputJson.Depth = Depth;
inputJson.Thickness = Thickness;
inputJson.BottomThickness = BottomThickness;
inputJson.rebarSpacing = rebarSpacing;
inputJson.outputrvt = outputrvt;
XrefTreeArgument inputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/aecom-bucket-demo-library/objects/{0}", objectId),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
}
};
// 2. input json
XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
{
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
},
Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")
};
// 3. output file
string outputFileNameOSS = outputrvt;
XrefTreeArgument outputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS),
Verb = Verb.Put,
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
}
};
// prepare & submit workitem
// the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem
//string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&bucketKey={2}&outputFileName={3}", OAuthController.FORGE_WEBHOOK_URL, browerConnectionId, bucketKey, outputFileNameOSS);
WorkItem workItemSpec = new WorkItem()
{
ActivityId = activityName,
Arguments = new Dictionary<string, IArgument>()
{
{ "rvtFile", inputFileArgument },
{ "jsonFile", inputJsonArgument },
{ "result", outputFileArgument }
///{ "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } }
}
};
DesignAutomationClient client = new DesignAutomationClient();
client.Service.Client.BaseAddress = new Uri(#"http://localhost:3000");
WorkItemStatus workItemStatus = await client.CreateWorkItemAsync(workItemSpec);
return Ok();
}
Any idea why is giving me this error? I have tested the api using postman and it works fine but when I try to call that from a button I keep receive this error. Starting the debug it seems that the url is written correctly. Maybe it is a very simple thing that i am missing.
Cheers!
OK solved...
I was missing to add the service in the Startup and also the Forge connection information (clientid, clientsecret) in the appsettings.json
Now I need to test the AWS deployment and I guess I am done!

Create JSON using for loop, Express.js

I'm newbie to express.js. I want to create a JSON using for loop. But the code returns object object. I don't know why. But for a single JSON, it returns as a JSON value. In this code, I have added a function to retrieve my JSON values from mongoDB. Please help me to complete this.
router.get('/', (req, res) => {
Followups.find({}).then(followupData => {
Staffs.find({}).then(staffData => {
Institutions.find({}).then(institutionData => {
var fcount = Object.keys(followupData).length;
var scount = Object.keys(staffData).length;
var icount = Object.keys(institutionData).length;
console.log(icount);
var jsonData = '';
function getStaffData(id) {
return staffData.filter(
function(staffData) {
return staffData._id == id;
}
);
}
function getInstitutionData(id) {
return institutionData.filter(
function(institutionData) {
return institutionData._id == id;
}
);
}
for (i=0; i<fcount; i++)
{
fstaffid = followupData[i].staffid;
fschoolid = followupData[i].schoolid;
staffDetails = getStaffData(fstaffid);
institutionDetails = getInstitutionData(fschoolid);
jsonData += {
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
}
}
console.log(jsonData);
res.render('followup', {followupData:followupData, jsonData: jsonData});
});
});
});
});
Problem solved by using concat
jsonData = jsonData.concat({
followupid : followupData[i]._id,
schoolid : followupData[i].schoolid,
staffid : followupData[i].staffid,
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
});
You can display the data of jsonData like:
console.log(JSON.stringify(jsonData));
object object means jsonData is a JSON object, you cannot display a JSON object directly. You must stringify it before doing this.
You may be able to find more about the issue after using JSON.stringify

Read csv to object of object for d3 [datamaps]

I'm using datamaps and would like to be able to read the data from a csv file.
The data format that datamaps is expecting is the following:
var loadeddata = {
"JPN":{Rate:17.5,fillKey:"firstCat"},
"DNK":{Rate:16.6,fillKey:"secondCat"}
};
I would like to read a csv file of the following structure and transform it into the format that datamaps is expecting:
ISO, Rate, fillKey
JPN, 17.5, firstCat
DNK, 16.6, secondCat
My 'best attempt' was using the following code:
var csvloadeddata;
d3.csv("simpledata.csv", function (error, csv) {
if (error) return console.log("there was an error loading the csv: " + error);
console.log("there are " + csv.length + " elements in my csv set");
var nestFunction = d3.nest().key(function(d){return d.ISO;});
csvloadeddata = nestFunction.entries(
csv.map(function(d){
d.Rate = +d.Rate;
d.fillKey = d.fillKey;
return d;
})
);
console.log("there are " + csvloadeddata.length + " elements in my data");
});
But this code generates a variable 'csvloadeddata' that looks like this:
var csvloadeddata = [
{"key": "JPN", "values": { 0: {Rate:17.5, fillKey:"firstCat"}} },
{"key": "DNK", values : { 1: {Rate:16.6,fillKey:"secondCat"}} }
];
What am I doing wrong?
Found the answer myself. If somebody is interested – this is what I ended up using:
<script>
d3.csv("simpledata.csv", function(error, csvdata1) {
globalcsvdata1 = csvdata1;
for (var i=0;i<csvdata1.length;i++)
{
globalcsvdata1[ globalcsvdata1[i].ISO] = globalcsvdata1[i] ;
//console.log(globalcsvdata1[i]);
delete globalcsvdata1[i].ISO;
delete globalcsvdata1[i] ;
}
myMap.updateChoropleth(globalcsvdata1);
}
);
var myMap = new Datamap({
element: document.getElementById('map'),
scope: 'world',
geographyConfig: {
popupOnHover: true,
highlightOnHover: false
},
fills: {
'AA': '#1f77b4',
'BB': '#9467bd',
defaultFill: 'grey'
}
});
</script>
</body>
The csv has the following structure:
ISO,fillKey
RUS,AA
USA,BB
Here is a working example: http://www.explainingprogress.com/wp-content/uploads/datamaps/uploaded_gdpPerCapita2011_PWTrgdpe/gdpPerCapita2011_PWTrgdpe.html