NODE RED http request - post image via API (Face++) - http

I have similar problem to this post
I get an image via a file buffer node. It works fine if this node goes into an visual-recognition node of ibm watson.
I also wanted to use this image to post it into another API. Therefore I use the http request node with URL = https://api-us.faceplusplus.com/facepp/v3/detect
And in front of it I use a function node to create header and body for this http request. It works very good. But I'm not able to "attach" the image to it.
I don't know the correct syntax. It's the line with "image_file".
var image = msg.payload;
msg.headers = {};
msg.headers["content-type"] ='application/x-www-form-urlencoded';
msg.payload = {};
msg.payload['api_key'] = 'zrxC';
msg.payload['api_secret'] = 's3UN';
msg.payload['image_file'] = image;
msg.payload['return_landmark'] = '1';
msg.payload['return_attributes'] = 'gender,age,emotion,beauty,skinstatus';
return msg;
If I use a different image input (url), it works.
msg.payload['image_url'] = 'http://picture.com/pic.jpg";
Soooo...syntax ;)
Maybe its also a problem, because the image needs another content-type. Is it possible to give different body parts different content-types?
Edit: I tried something with multipart http requests...here is my whole flow.
[{"id":"6c6e1506.29cf2c","type":"tab","label":"Flow 3","disabled":false,"info":""},{"id":"b84cd67b.aaaee8","type":"http response","z":"6c6e1506.29cf2c","name":"","x":971,"y":602,"wires":[]},{"id":"a220ce16.64fcb","type":"http in","z":"6c6e1506.29cf2c","name":"Get Home Page","url":"/homepage","method":"get","upload":false,"swaggerDoc":"","x":441,"y":590,"wires":[["c46a3f0a.a30cb"]]},{"id":"c46a3f0a.a30cb","type":"template","z":"6c6e1506.29cf2c","name":"Form and Response Template","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":" <html>\n <body>\n <form action=\"/classify\" method=\"post\" enctype=\"multipart/form-data\">\n <input type=\"file\" name=\"pic\" accept=\"image/*\"><br>\n <input type=\"submit\" value=\"Submit\">\n </form> \n <div>Classifications:</div>\n <div>\n {{#result}}\n <table>\n <tr>\n <th>Class</th>\n <th>Score</th>\n <th>Type</th>\n </tr>\n {{#images}}\n {{#.}}\n {{#classifiers}}\n {{#.}}\n {{#classes}}\n {{#.}}\n <tr>\n <td>{{class}}</td>\n <td>{{score}}</td> \n <td>{{&type_hierarchy}}</td>\n </tr> \n {{/.}} \n {{/classes}} \n {{/.}} \n {{/classifiers}}\n {{/.}}\n {{/images}}\n </table>\n {{/result}}\n </div>\n </body>\n</html>","x":720.5,"y":600,"wires":[["b84cd67b.aaaee8"]]},{"id":"ee17076b.7b9038","type":"function","z":"6c6e1506.29cf2c","name":" Determine File Path","func":"if (msg.req.files) {\n var files = Object.keys(msg.req.files);\n msg.payload = msg.req.files[files[0]][0].path; \n}\nreturn msg;","outputs":1,"noerr":0,"x":321.5,"y":737,"wires":[["d8385fe9.3b5d4"]]},{"id":"b4bcb13e.bd4a","type":"visual-recognition-v3","z":"6c6e1506.29cf2c","name":"","apikey":"3738dbb4a5ae703eb3d23285127f8a21233e6566","image-feature":"classifyImage","lang":"en","x":701,"y":716,"wires":[["95fdb967.895c98","c46a3f0a.a30cb"]]},{"id":"95fdb967.895c98","type":"debug","z":"6c6e1506.29cf2c","name":"","active":true,"tosidebar":true,"console":false,"complete":"result","x":912.5,"y":760,"wires":[]},{"id":"d8385fe9.3b5d4","type":"file-buffer","z":"6c6e1506.29cf2c","name":"","mode":"asBuffer","x":511,"y":793,"wires":[["b4bcb13e.bd4a","7b398291.92ee0c"]]},{"id":"5c0e525d.d8230c","type":"httpInMultipart","z":"6c6e1506.29cf2c","name":"Classify Image","url":"/classify","method":"post","fields":"[{ \"name\":\"pic\"}]","swaggerDoc":"","x":117,"y":774,"wires":[["ee17076b.7b9038"]]},{"id":"4d5c181f.bdcbe8","type":"http request","z":"6c6e1506.29cf2c","name":"face++","method":"POST","ret":"obj","url":"https://api-us.faceplusplus.com/facepp/v3/detect","tls":"","x":797,"y":928,"wires":[["11b9d42c.ae40ec"]]},{"id":"11b9d42c.ae40ec","type":"debug","z":"6c6e1506.29cf2c","name":"","active":true,"tosidebar":true,"console":true,"tostatus":false,"complete":"payload","x":1005,"y":927,"wires":[]},{"id":"7b398291.92ee0c","type":"function","z":"6c6e1506.29cf2c","name":"set payload and headers","func":"var image = msg.payload;\n\n\nmsg.headers = {};\nmsg.headers[\"content-type\"] ='application/x-www-form-urlencoded';\n\nmsg.payload = {};\nmsg.payload['api_key'] = 'z8lK8AM2u7X9CfI5PodNcFYv0OPq3rxC';\nmsg.payload['api_secret'] = 's33uL-coCxnDZn_naWMceZh-Xko1QSUN';\nmsg.payload['image_file'] = [image]; \nmsg.payload['return_landmark'] = '1';\nmsg.payload['return_attributes'] = 'gender,age,emotion,beauty,skinstatus';\n\n\nreturn msg;\n","outputs":1,"noerr":0,"x":560,"y":933,"wires":[["4d5c181f.bdcbe8"]]}]
My problem is to send the image to the red highlighted API.

To push a buffer as a field you need use the node-red-contrib-http-request-multipart to set the content-type in the headers to multipart/form-data.
Then you need to make sure the msg.payload object matches the input needed for the request node:
var image = msg.payload;
msg.headers = {};
msg.headers["content-type"] ='multipart/form-data';
msg.payload = {};
msg.payload['api_key'] = 'zrxC';
msg.payload['api_secret'] = 's3UN';
msg.payload['image_file'] = image;
msg.payload['return_landmark'] = '1';
msg.payload['return_attributes'] = 'gender,age,emotion,beauty,skinstatus';
return msg;

Related

xpages view panel display computed icon

I'm trying to display an icon in a view panel based on a column value. This page will display if I only display the column value and/or use a static database image. If however I try to compute the image based on the column value I get an Http Code 500 error. Looking at the error-log I see two errors, the first is CLFAD0211E: Exception thrown and the second CLFAD0246E: Exception occurred servicing request for .
I have reviewed this simple explanation on how to add a dynamic icon (https://www.youtube.com/watch?v=27MvLDx9X34) and other similar articles and still not working. Below is the code for the computed icon.
var urlFull:XSPUrl = new XSPURL(database.getHttpURL());
var url = urlFull.getHost();
var path = "/icons/vwicn";
// var idx = rowData.getColumnValues().get(1); Removed for testing
var idx = "82.0"; //Hard coded the value for testing
if (idx < 10){
path += ("00" + idx).left(3);
}else if (idx < 100){
path += ("0" + idx).left(3);
}else {
path += idx.left(3);
}
path += ".gif";
//path = "/icons/vwicn082.gif"; I have also tried hard coding the path value - still a no go
url = setPath(path);
url.removeAllParameters();
return url.toString();
The view panel is configured as xp:viewPanel rows="40" id="viewPanel1" var="rowData".
Any suggestions on what to look for or a better option to compute a view panel icon would be appreciated.
Cheers!!!
You have a typo: url = setPath(path);should be url.setPath(path);

google api .net client v3 getting free busy information

I am trying to query free busy data from Google calendar. Simply I am providing start date/time and end date/time. All I want to know is if this time frame is available or not. When I run below query, I get "responseOBJ" response object which doesn't seem to include what I need. The response object only contains start and end time. It doesn't contain flag such as "IsBusy" "IsAvailable"
https://developers.google.com/google-apps/calendar/v3/reference/freebusy/query
#region Free_busy_request_NOT_WORKING
FreeBusyRequest requestobj = new FreeBusyRequest();
FreeBusyRequestItem c = new FreeBusyRequestItem();
c.Id = "calendarresource#domain.com";
requestobj.Items = new List<FreeBusyRequestItem>();
requestobj.Items.Add(c);
requestobj.TimeMin = DateTime.Now.AddDays(1);
requestobj.TimeMax = DateTime.Now.AddDays(2);
FreebusyResource.QueryRequest TestRequest = calendarService.Freebusy.Query(requestobj);
// var TestRequest = calendarService.Freebusy.
// FreeBusyResponse responseOBJ = TestRequest.Execute();
var responseOBJ = TestRequest.Execute();
#endregion
Calendar API will only ever provide ordered busy blocks in the response, never available blocks. Everything outside busy is available. Do you have at least one event on the calendar
with the given ID in the time window?
Also the account you are using needs to have at least free-busy access to the resource to be able to retrieve availability.
I know this question is old, however I think it would be beneficial to see an example. You will needed to actually grab the Busy information from your response. Below is a snippet from my own code (minus the call) with how to handle the response. You will need to utilized your c.Id as the key to search through the response:
FreebusyResource.QueryRequest testRequest = service.Freebusy.Query(busyRequest);
var responseObject = testRequest.Execute();
bool checkBusy;
bool containsKey;
if (responseObject.Calendars.ContainsKey("**INSERT YOUR KEY HERE**"))
{
containsKey = true;
if (containsKey)
{
//Had to deconstruct API response by WriteLine(). Busy returns a count of 1, while being free returns a count of 0.
//These are properties of a dictionary and a List of the responseObject (dictionary returned by API POST).
if (responseObject.Calendars["**YOUR KEY HERE**"].Busy.Count == 0)
{
checkBusy = false;
//WriteLine(checkBusy);
}
else
{
checkBusy = true;
//WriteLine(checkBusy);
}
if (checkBusy == true)
{
var busyStart = responseObject.Calendars["**YOUR KEY HERE**"].Busy[0].Start;
var busyEnd = responseObject.Calendars["**YOUR KEY HERE**].Busy[0].End;
//WriteLine(busyStart);
//WriteLine(busyEnd);
//Read();
string isBusyString = "Between " + busyStart + " and " + busyEnd + " your trainer is busy";
richTextBox1.Text = isBusyString;
}
else
{
string isFreeString = "Between " + startDate + " and " + endDate + " your trainer is free";
richTextBox1.Text += isFreeString;
}
}
else
{
richTextBox1.Clear();
MessageBox.Show("CalendarAPIv3 has failed, please contact support\nregarding missing <key>", "ERROR!");
}
}
My suggestion would be to break your responses down by writing them to the console. Then, you can "deconstruct" them. That is how I was able to figure out "where" to look within the response. As noted above, you will only receive the information for busyBlocks. I used the date and time that was selected by my client's search to show the "free" times.
EDIT:
You'll need to check if your key exists before attempting the TryGetValue or searching with a keyvaluepair.

OpenLayer Popups for markers imported from google spreadsheet

I'm looking for a way to use framecloud type popup with my current setup. Unfortunately all my attempts have either not worked or will only work on the most recently placed maker.
In the course of trying to get it to work I have converted my original script from using Markers to using Vectors to placing the marker points (as I've seen that it's easier to customize vectors than markers.)
Now which ever one I can get to work I'll use, but after working on this for a few days I'm at my wits end and need a helping hand in the right direction.
My points are pulled from a google spreadsheet using tabletop.js. The feature is working how I wish it to, with the markers being placed on their respective layer based on a field I called 'type'.
While I have a feeling that might have been the source of my problem with the Markers type layer, I'm not sure how to fix it.
You can view the coding through these pages
(Links removed due to location change.)
Thanks for all help in advance.
I finally got it to work. For anyone in a similar situation here's my final code for the layers. I did change the names of the layers from what they are originally and blacked out the spreadsheet I used, but the changes should be noticeable.
//
//// Set 'Markers'
//
var iconMarker = {externalGraphic: 'http://www.openlayers.org/dev/img/marker.png', graphicHeight: 21, graphicWidth: 16};
var iconGeo = {externalGraphic: './images/fortress.jpg', graphicHeight: 25, graphicWidth: 25};
var iconAero = {externalGraphic: './images/aeropolae.jpg', graphicHeight: 25, graphicWidth: 25}; // Image is the creation of DriveByArtist: http://drivebyartist.deviantart.com/
var vector1 = new OpenLayers.Layer.Vector("1");
var vector2 = new OpenLayers.Layer.Vector("2");
var vector3 = new OpenLayers.Layer.Vector("3");
// Pulls map info from Spreadsheet
//*
Tabletop.init({
key: 'http://xxxxxxxxxx', //Spreadsheet URL goes here
callback: function(data, tabletop) {
var i,
dataLength = data.length;
for (i=0; i<dataLength; i++) { //following are variables from the spreadsheet
locName = data[i].name;
locLon = data[i].long;
locLat = data[i].lat;
locInfo = data[i].info;
locType = data[i].type; // Contains the following string in the cell, which provides a pre-determined output based on provided information in the spreadsheet: =ARRAYFORMULA("<h2>"&B2:B&"</h2><b>"&G2:G&"</b><br /> "&C2:C&", "&D2:D&"<br />"&E2:E&if(ISTEXT(F2:F),"<br /><a target='_blank' href='"&F2:F&"'>Read More...</a>",""))
locLonLat= new OpenLayers.Geometry.Point(locLon, locLat);
switch(locType)
{
case "Geopolae":
feature = new OpenLayers.Feature.Vector(
locLonLat,
{description:locInfo},
iconGeo);
vector1.addFeatures(feature);
break;
case "POI":
feature = new OpenLayers.Feature.Vector(
locLonLat,
{description:locInfo},
iconMarker);
vector2.addFeatures(feature);
break;
case "Aeropolae":
feature = new OpenLayers.Feature.Vector(
locLonLat,
{description:locInfo},
iconAero);
vector3.addFeatures(feature);
break;
}
}
},
simpleSheet: true
});
map.addLayers([vector1, vector2, vector3]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
//Add a selector control to the vectorLayer with popup functions
var controls = {
selector: new OpenLayers.Control.SelectFeature(Array(vector1, vector2, vector3), { onSelect: createPopup, onUnselect: destroyPopup })
};
function createPopup(feature) {
feature.popup = new OpenLayers.Popup.FramedCloud("pop",
feature.geometry.getBounds().getCenterLonLat(),
null,
'<div class="markerContent">'+feature.attributes.description+'</div>',
null,
true,
function() { controls['selector'].unselectAll(); }
);
feature.popup.autoSize = true;
feature.popup.minSize = new OpenLayers.Size(400,100);
feature.popup.maxSize = new OpenLayers.Size(400,800);
feature.popup.fixedRelativePosition = true;
feature.popup.overflow ="auto";
//feature.popup.closeOnMove = true;
map.addPopup(feature.popup);
}
function destroyPopup(feature) {
feature.popup.destroy();
feature.popup = null;
}
map.addControl(controls['selector']);
controls['selector'].activate();
}

youtube api upload "Cannot close stream until all bytes are written"

I am using the youtube api to direct upload videos like this:
YouTubeRequestSettings setting = new YouTubeRequestSettings("devpa", key, "user", "pass");
YouTubeRequest req = new YouTubeRequest(setting);
Video ytv = new Video();
ytv.Title = "test video1";
ytv.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema));
ytv.Keywords = "test, dev";
ytv.Description = "this is a test video";
ytv.YouTubeEntry.Private = true;
ytv.YouTubeEntry.MediaSource = new MediaFileSource(Server.MapPath("PATH"), "video/mp4");
Video createdVideo = req.Upload(ytv);
But every time i get this error:
Cannot close stream until all bytes are written
Even though *i am uploading small videos with different extinctions (flv,mp4 ..etc) *, what is the problem?
Thanks
You need to set timeout. Like ytv.TimeOut = 100000000;
Actually set the instance of
YouTubeRequestSettings.Timeout = [A LARGER NUMBER]
That's the setting you'll want to use.

adobe acrobat XI pro javascript

i am calling an javascript function when out of focus on the form field. So what i am tying to do is the if i ticked required this field as required field it will have a red border around it, can i write a script to remove the required option when there are value inside the field?
var thisValue = this.getField("companyName").value;
var regexLetter = /[A-Z]+$/;
var Icon = "0"; //0 — Error (default) // 1 — Warning // 2 — Question // 3 — Status
var Type = "0"; //0 — OK (default) // 1 — OK, Cancel // 2 — Yes, No // 3 — Yes, No, Cancel
if (thisValue == ""){
app.alert({
cMsg:"this is an warning",
cTitle: "thsi is title",
nIcon: Icon,
nType: Type
})
} else if(!regexLetter.test(thisValue)){
app.alert('Type alphanumeric character');
}
This is going to be rather late, but this is how I do it in my documents:
var _companyName = this.getField("CompanyName");
_companyName.required = (_companyName.value === "");
You can also impose other dependencies, like:
var _companyName = this.getField("CompanyName"),
_companyLicense = this.getField("CompanyLicense");
_companyLicense = ((_companyLicense === "")
&& (_companyName !== ""));
Having your scripts split into a couple of files could help. I use a "shared" script which contains a vast majority of the logic and the a "specific" script to round of each individual document. Also, make sure when adding the scripts to just name them 1, 2, 3, etc. in the correct order or Acrobat will be stupid. Hope this helps you.

Resources