Invalid JSON payload received. Unable to parse number (Google Vision API) - json

I'm getting the error:
Invalid JSON payload received. Unable to parse number. INVALID_ARGUMENT
I got the key and everything and I'm still having the same error return. A few suggestions are resizing the image first to less fit the 4MB image limit.
I also tried emulating the same JSON request coming from their docs. But still have the same issue.
https://cloud.google.com/vision/docs/drag-and-drop
Here's the code I'm using: (I got the sample from Akshay Kadam)
me.detection_types = {
LABEL_DETECTION: 'label',
DOCUMENT_TEXT_DETECTION: 'text',
LOGO_DETECTION: 'logo',
LANDMARK_DETECTION: 'landmark'
};
var api_key = '';
$scope.takePicture = function(){
var options = {
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
targetWidth: 150,
targetHeight: 150,
correctOrientation: true,
cameraDirection: 0,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
quality: 25
};
$cordovaCamera.getPicture(options).then(function(imagedata){
me.current_image = "data:image/jpeg;base64," + imagedata;
me.image_description = '';
me.locale = '';
var vision_api_json = {
"requests":[
{
"image":{
"content": imagedata
},
"imageContext": {
"cropHintsParams": {
"aspectRatios": [
0.8,
1,
1.2
]
}
},
"features":[
{
"type": me.detection_type,
"maxResults": 1
}
]
}
]
}
var file_contents = JSON.stringify(vision_api_json);
$cordovaFile.writeFile(
cordova.file.applicationStorageDirectory,
'file.json',
file_contents,
true
).then(function(result){
var headers = {
'Content-Type': 'application/json'
};
options.headers = headers;
var server = 'https://vision.googleapis.com/v1/images:annotate?key=' + api_key;
var filePath = cordova.file.applicationStorageDirectory + 'file.json';
$cordovaFileTransfer.upload(server, filePath, options, true)
.then(function(result){
alert(JSON.stringify(result))
var res = JSON.parse(result.response);
var key = me.detection_types[me.detection_type] + 'Annotations';
me.image_description = res.responses[0][key][0].description;
}
Need help. Thank you!
UPDATE:
I tried adding Content-Length and was still having the same problem.

Related

FinBox.com logging in with UrlFetchApp to access another link?

I can't log in successfully from Google Apps Script despite looking for solutions hours long, including many entries in SoF.
The login process sends a POST request to this url: https://finbox.com/_/api/v5/tokens
Input of the credentials happens here: https://finbox.com/login/email
Response code is 400.
Any help will be really appreciated :)
So far I ended up with this:
function testFinBoxWithCredentials(stock = "AAPL") {
var options = {
method: 'post',
contentType: 'application/json',
payload: {
email: 'xxxxxxxxx',
password: 'xxxxxxxxx'
},
muteHttpExceptions: true,
followRedirects: false
};
const response = UrlFetchApp.fetch("https://finbox.com/_/api/v5/tokens", options);
Logger.log(response.getResponseCode());
if ( response.getResponseCode() == 200 ) {
Logger.log("Couldn't login.");
}
else if ( response.getResponseCode() == 302 ) {
Logger.log("Logged in successfully");
var cookie = response.getAllHeaders()['Set-Cookie'];
Logger.log(cookie);
//Access then a link like https://finbox.com/NASDAQGS:AAPL
/* var cookies = response.getAllHeaders()['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].split( ';' )[0];
};
url2 = "https://finbox.com/NASDAQGS:AAPL";
options2 = {
"method": "get",
"headers": {
"Cookie": cookies.join(';')
}
}
var response2 = UrlFetchApp.fetch(url2, options2);
var content = response2.getContentText();
Logger.log(content)*/
} ```

Chrome extension can't find USB printer device

I am building chrome application for POS Terminal printers. The problem that I have is that chrome application for some reason can't find USB device and I am not sure why it is not working. I tried few methods (converted hexadecimal vendor/product ID to decimal, used hexadecimal product/vendor id to connect to USB printer) and all of the reports that device can't be found...
EDIT:
I got this error from device log:
Failed to open device: Operation not supported or unimplemented on this platform
Does someone know where is the problem?
Here is details about printer (DATECS DPP 255):
Manifest:
{
"manifest_version": 2,
"name": "Thermal Printer Extension",
"description": "Thermal Printer Extension for ESC/POS Commands",
"version": "1.0",
"app": {
"background": {
"scripts": ["main.js"]
}
},
"permissions": ["usb", "notifications"],
"optional_permissions": [
{
"usbDevices": [
{
"vendorId": 65520, "productId": 98
}
]
}
],
"externally_connectable": {
"matches": ["http://localhost:3000/*"]
}
}
main.js
chrome.runtime.onMessageExternal.addListener(function (stuff) {
if(stuff){
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
var port = 0;
var endpoint = 0x01;
// needs to be set in optional permissions for each VID/PID pair
var device = {vendorId: 0xfff0, productId: 0x0062};
// var device = {vendorId: 65520, productId: 98};
String.prototype.toBytes = function() {
var arr = [];
for (var i=0; i < this.length; i++) {
arr.push(this[i].charCodeAt(0));
}
return arr;
}
// setting variables for printing, array for data, and calculations
var alignLeft = [0x01B, 0x061, 0];
var alignCenter = [0x01B, 0x061, 1];
var alignRight = [0x01B, 0x061, 2];
var endPrint = [0x01B, 0x064, 2];
// enter new line
var lineFeed = [0x00A];
var buzz = [07];
var drawLineMiddle = "________________________________________________".toBytes();
var drawLineSmall = "________________________________".toBytes();
var horizontalTab = [0x009];
var cutpaperFull = [0x01D, 0x056, 1];
var cutpaperPartial = [0x01D, 0x056, 0];
function createAnything() {
var anything = alignCenter;
anything = anything.concat("Awesome Chrome Extension".toBytes());
anything = anything.concat(lineFeed);
anything = anything.concat(drawLineMiddle);
anything = anything.concat(stuff.stuffToPrint.toBytes());
anything = anything.concat(lineFeed);
return anything;
}
function createReceipt(devices) {
var data = [];
data = data.concat(createAnything());
data = data.concat(endPrint);
data = data.concat(cutpaperPartial);
var buffer = new Uint8Array(data).buffer;
var transferinfo = {direction: "out", endpoint: endpoint, data: buffer };
chrome.usb.bulkTransfer({handle: devices[0].handle, vendorId: devices[0].vendorId, productId: devices[0].productId}, transferinfo, function(response) {
if (response.resultCode == 0) {
chrome.usb.closeDevice({handle: devices[0].handle, vendorId: devices[0].vendorId, productId: devices[0].productId}, chrome.notifications.create("4", {type: "basic", iconUrl: "icon.png", title: "Success!", message: "Printing receipt..."}, function() {console.log("Success!")}));
} else {
console.log("Error ", response);
}
});
}
var connect = function(callback) {
chrome.permissions.getAll(function(p) {
if (p.permissions.indexOf("usb") >= 0) {
//construct permission object for our device
var obj = { usbDevices: [device] };
//now request the permissions
chrome.permissions.request({ permissions: [obj] }, function(granted) {
if (granted) {
chrome.usb.findDevices(device, function(devices) {
if (devices && devices.length > 0) {
//use the first found device
var foundDevice = devices[0];
//now lets reset the device
chrome.usb.resetDevice(foundDevice, function() {
//perform some error checking to make sure we reset the device
if ( ! chrome.runtime.lastError) {
//now claim the interface using the port we specified
chrome.usb.claimInterface(foundDevice, port, function() {
if ( ! chrome.runtime.lastError) {
callback(devices);
} else {
throw chrome.runtime.lastError.message;
}
});
} else {
throw chrome.runtime.lastError.message;
}
});
} else {
chrome.notifications.create("1", {type: "basic", iconUrl: "icon.png", title: "Error", message: "Device not found!"}, function() {console.warn("Device not found!")});
console.warn("Device not found!");
}
});
} else {
chrome.notifications.create("2", {type: "basic", iconUrl: "icon.png", title: "Error", message: "USB Permission not granted."}, function() {console.warn("USB Permission not granted.")});
console.warn("USB Permission not granted.");
}
});
} else {
chrome.notifications.create("3", {type: "basic", iconUrl: "icon.png", title: "Error", message: "No USB permissions granted."}, function() {console.warn("No USB permissions granted.")});
console.warn("No USB permissions granted.");
}
});
}
connect(createReceipt);
}
});

HighCharts : Xaxis lables misplaced

I want to label xaxis with values from JSON data that is happening but it is printing it at wrong place as shown in screenshot :
Here only seven values are present its labeled in that manner but actual data is plotted by leaving a gap of one. For example at 11th there is value and then again at 13t so total seven values but taking 14 places and label properly taking there first seven places how to match labels and bar graph
Following is my code snippet :
var obj = data[$("#host").val()].stats_vol.result.sectoutput;
var my_data_list = [];
var my_data_list1 = [];
var my_data_list2 = [];
var volumes = [];
for(var key in obj) {
var avg_latency = parseInt(obj[key].avg_latency);
var read_latency = parseInt(obj[key].read_latency);
var write_latency = parseInt(obj[key].write_latency);
console.log(key);
volumes.push(key);
my_data_list.push('Average Latency', parseInt(avg_latency));
my_data_list1.push('Read Latency', parseInt(read_latency));
my_data_list2.push('Write Latency', parseInt(write_latency));
}
$('#graphcontainer3').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Volume Level Latency'
},
yAxis: {
tickInterval: 100,
title: {
text: 'Latency(ms)'
}
},
xAxis: {
categories: volumes,
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} ms</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 2
}
},
series: [{
name: 'Average latency',
data: my_data_list,
}, {
name: 'Read Latency',
data: my_data_list1,
}, {
name: 'Write Latency ',
data: my_data_list2,
}]
});
Can anyone help me in this code to make this work fine???
I rectified the problem by myself :) It just I was giving labels two times
var obj = data[$("#host").val()].stats_vol.result.sectoutput;
var my_data_list3 = [];
var my_data_list1 = [];
var my_data_list2 = [];
var volumes = [];
for(var key in obj) {
var avg_latency = parseInt(obj[key].avg_latency);
var read_latency = parseInt(obj[key].read_latency);
var write_latency = parseInt(obj[key].write_latency);
console.log(avg_latency);
volumes.push(key);
my_data_list3.push(parseInt(avg_latency)); //here no need to give label again as it is done my volume(key)
my_data_list1.push( parseInt(read_latency));
my_data_list2.push(parseInt(write_latency));
}
This is what I was expecting as output .Hope it might be helpful for someone else hence answered.

Unable to format JSON from WCF for HighCharts?

My WCF returns this JSON and i want to bind to HighCharts Pie
Original from WCF -[{"AllRecordsUrl":"http:\/\/EMS\/sites\/IST\/report.aspx","EMSCenterName":"IST","EMSCenterUrl":"http:\/\/EMS\/sites\/IST","Count":2},{"AllRecordsUrl":"http:\/\/EMS\/sites\/LSS\/report.aspx","EMSCenterName":"LSS","EMSCenterUrl":"http:\/\/EMS\/sites\/LSS","Count":17}]
If i hardCode it in cart series as data: [....] it works but the dynamic proccesed data does not..
After processing - [{name: 'IST' , url: 'http://EMS/sites/IST/report.aspx' , y: 2 },{name: 'LSS' , url: 'http://EMS/sites/LSS/report.aspx' , y: 16 }]
Even after processing it to what i showed above highcharts Pie won't work with my data..
I am not sure what is wrong here, would appreciate some guidance
Here's what is done so far ...
function getDataForHub(json) {
var realArray = $.makeArray(json);
//debugger;
//console.log(JSON.stringify(realArray));
var obj = $.parseJSON(JSON.stringify(realArray));
var chartData = [];
$.each(realArray, function (index, item) {
var final;
var element;
var sB = '';
var name = '';
var url = '';
var y = '';
var color = '';
for (element in item) {
if (element == 'EMSCenterName') {
name = 'name' + ": " + "'" + item[element] + "'";
}
if (element == 'AllRecordsUrl') {
url = 'url' + ": " + "'" + item[element] + "'";
}
if (element == 'Count') {
y = 'y' + ": " + item[element];
}
}
sB = name + ' , ' + url + ' , ' + y ;
//console.log(sB);
var elements = [];
//adding each to an array before being pushed to th final array,
elements.push(sB);
chartData.push(elements);
});
return chartData;
}
And here is my Pie
$(function () {
LoadSodByKey("sp.ui.dialog.js", null);
var stdWidth = 530;
var stdHeight = 200;
Highcharts.setOptions({
colors: ['#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
$('#containerpie').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: true,
height: stdHeight + 120,
width: stdWidth + stdHeight
},
title: {
text: 'Records per Program'
},
tooltip: {
pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
/*formatter: function () {
return '<b>' + this.point.name;
}*/
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
},
showInLegend: false
}
},
series: [{
type: 'pie',
size: stdHeight,
data:[{name: 'IST' , url: 'http://EMS/sites/IST/report.aspx' , y: 2 },{name: 'LSS' , url: 'http://EMS/sites/LSS/report.aspx' , y: 16 }],
point: {
events: {
click: function(e) {
//alert(e.point.url);
var options = {
url: e.point.url,
title: e.point.name,
allowMaximize: true,
showClose: true,
width: 1100,
height: 500,
dialogReturnValueCallback: function (result, returnValue) {
//location.reload(true);
}
}
SP.UI.ModalDialog.showModalDialog(options);
e.preventDefault();
}
}
}
}]
});
var data = GetData();});
function GetData(){
var chart = $('#containerpie').highcharts();
series = chart.series[0];
//Ajax call to WCF service
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
crossDomain: false,
url: 'http://EMS/_vti_bin/EMSDashboard.svc/GetEMSCenterDataForHub',
data: null,
dataType: 'json',
success: function (response) {
var dynamicData = getDataForHub(response);
//this doesnot work
//series.data = dynamicData;
//even this does not work
//series.data.push(dynamicData)
//Wrong, wrong, wrong
//series.data.push(eval('[' +dynamicData +']'));
//gives me count of two but the chart does not load wiht dynamic data
console.log(series.data.length);
},
error: function (message) {
alert(message.statusText);
}
});
}
Thanx
FIXED:
Here's how
mistake = I had set up a static chart and was trying to use the same with $AJAX call where the chart was already created without the "data" being created, instead now the "data" array is created first and then the chart is created using chart = new Highcharts.Chart({....})
Also removed all client side preprocessing of the JSON received from WCF i.e my server object has additional Properties for Highchart rendering such to get ..
[{"name":"IST","url":"http:\/\/<XXXX>\/sites\/IST\/ASASA.aspx","y":2},
{"name":"LASS","url":"http:\/\/<XXXX>\/sites\/LASS\/ASASA.aspx","y":17}]

Parse json from bandsintown API

I have trouble to parse and show events from Bands in Town´s API in my appcelerator mobile app. (iOS)
This is my bands event that i want to show in a table.
http://api.bandsintown.com/artists/Lucy%20Seven/events.json?api_version=2.0&app_id=LucySeven
And this is the code that i have for showing it
var win = Ti.UI.currentWindow;
win.hideNavBar();
Ti.UI.backgroundColor = '#050505';
var url = "http://api.bandsintown.com/artists/Lucy%20Seven/events.json? api_version=2.0&app_id=LucySeven"
var table = Ti.UI.createTableView({
backgroundColor: '#050505',
separatorColor:'#110000',
});
var tableData = [];
var json, artists, name, picture, title, description;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
// Ti.API.debug(this.responseText);
json = JSON.parse(this.responseText);
for (i = 0; i < json.data.length; i++) {
data = json.data[i];
row = Ti.UI.createTableViewRow({
height:'100dp',
backgroundColor: '#050505',
separatorColor:'#110000',
});
var name = Ti.UI.createLabel({
text: title,
font:{
fontSize:'17dp',
fontWeight:'bold'
},
height:'auto',
left:'90dp',
top:'20dp',
color:'#eee',
touchEnabled:true
});
row.add(name);
var start = Ti.UI.createLabel({
text: description,
font:{
fontSize:'12dp'
},
height:'auto',
left:'90dp',
bottom:'20dp',
color:'#eee',
touchEnabled:true
});
row.add(start);
// Avatar
var img = Ti.UI.createImageView({
image : thumb_url ,
width : 70,
height : 70,
top : 5,
bottom : 5,
borderRadius: 5,
borderColor: '#eee',
left : 5
});
row.add(img);
tableData.push(row);
}
table.setData(tableData);
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout:5000
});
xhr.open("GET", url);
xhr.send();
There is a API responses for json here:
http://www.bandsintown.com/api/responses#events-json
I really cant see what is wrong... Maybe im to blind to see what i have missed?
I would appreciate if someone could point me in the right direction on this.
i have tried with: data.title data.artists.title title artists.titel and so on but nothing have shown up in my tableview.....
Thanx
//R
What's the value of this.responseText and what's the value of json after JSON.parse? In the JSON response I don't see a data property so I'm not sure what json.data is supposed to be. Also in Ti.UI.createLabel you give test: title but title is never given a value.
I suspect what you really want in your for loop is this:
json = JSON.parse( this.responseText ); // `json` will be an array of objects
for (i = 0; i < json.length; i++) {
data = json[ i ];
// ...
var name = Ti.UI.createLabel( {
text: data.title,
// ...
} );
}
The key to debugging this is the same as debugging many things—find out what data you have at each step (I've never used Titanium but it must have something like console.log at the very least) and figure out how it differs from what you expect.