How do I save an image from an API response in Hive? - json

JSON data:
{
"id":"1",
"class_id":"2",
"name":"bebeneo 204",
"price":"16",
"barcode":"72900000000",
"item_img":"file/db_1p6.gif"
},
I receive through the API the name of the image (the item_img field). To be able to display the image, a server name must be placed before its name (EX: https://www.imageserver.com/file/db_1p6.gif). I want to save this image in Hive database.

var decodedJson = json.decode(jsonStringHere);
var box = Hive.box('myBox');
box.put('imageUrl', 'https://www.imageserver.com/${decodedJson['item_img']}');
And to get it back
var imageUrl = box.get('imageUrl');
print('This is the image url: $imageUrl');

Related

Crossfilter - Loading a JSON file from localStorage

I'm fairly new to Javascript and I'm trying to create a simple bar chart with d3.js using some data saved in the localStorage.
The data in the localStorage is acquired by the following function:
function logScore() {
var name = prompt("Please enter your name to add to the high scores list:");
var score = game.count;
var gameDate = today;
var scoreObj = { name: name, score: score, date: gameDate };
scoresArray.push(scoreObj);
window.localStorage.setItem('scoresRecord', JSON.stringify(scoresArray));
}
In a separate Javascript file, I parse the JSON object in order to store the object in an array.
var scoreData = JSON.parse(window.localStorage.getItem('scoresRecord'));
queue()
.defer(d3.json, "scoreData")
.await(makeGraph);
function makeGraph(error, scoreData) {
var ndx = crossfilter(scoreData);
var name_dim = ndx.dimension(dc.pluck('name'));
var score_dim = ndx.dimension(dc.pluck('score'));
var date_dim = ndx.dimension(dc.pluck('date'));
dc.barChart("#high-score-chart")
.width(300)
.height(150)
.margins({ top: 10, right: 50, bottom: 30, left: 50 })
.dimension(date_dim)
.group(score_dim)
.transitionDuration(500)
.x(d3.scale.ordinal())
.xUnits(dc.units.ordinal)
.xAxisLabel("Date")
.yAxisLabel("Score");
dc.renderAll();
}
Once loaded, I then try to use the data in a d3.js barchart using crossfilter, but I get the below error from the console:
https://ifd-project-simon-georgefairbairn.c9users.io/scoreData 404 (Not Found)
I think I'm loading the data correctly, but I wondered if anyone would be able to let me know if I can use crossfilter and d3.js with a JSON object stored in localStorage, and if so how?
Thanks for taking the time to read my problem - hoping someone can help!
If you're able to get the data synchronously, loading it from local storage, then you don't need queue() and d3.json
You should be able to do
var scoreData = JSON.parse(window.localStorage.getItem('scoresRecord'));
var ndx = crossfilter(scoreData);
The error you're getting indicates that d3.json is trying to do an HTTP request for the data. In this case, you don't need d3.json because JSON parsing is built into the language.
If you were using CSV data, then you might use the synchronous parse version d3.csv.parse. There is no d3.json.parse because it's provided directly by the language.

Flickr API returning unavailable image Windows Phone

Hi I'm new to Windows Phone and the flickr API's.
I've been trying to get some images and display them on the panorama view with this code:
var baseUrl = string.Format(flickString, flickrAPIKey);
string flickrResult = await client.GetStringAsync(baseUrl);
FlickrData flickrApiData = JsonConvert.DeserializeObject<FlickrData>(flickrResult);
if(flickrApiData.stat == "ok")
{
foreach (Photo data in flickrApiData.photos.photo)
{
// To retrieve one photo
// http://farm{farmid}.staticflickr.com/{server-id}/{id}_{secret}{size}.jpeg
//string photoUrl = "http://farm{0}.staticflickr.com/{1}/{2}_{3}_o.jpeg";
//string photoUrl = "http://farm{0}.staticflickr.com/{1}/{2}_{3}_b.jpeg";
string photoUrl = "http://farm{0}.staticflickr.com/{0}/{0}_{0}_n.jpeg";
string baseFlickrUrl = string.Format(photoUrl,
data.farm,
data.server,
data.id,
data.secret);
flickr1Image.Source = new BitmapImage(new Uri(baseFlickrUrl));
break;
}
}
I've tried trying different farms & servers etc but every time it still returns "This image is unavailable at this time". I dont know what I'm doing wrong here, appreciate some help.
Thanks
After Running your link, it turns out that the image extension should use jpg instead of jpeg
But I would strongly recommend you to use the extra field to get the respective url directly by using the extra attribute in the API
extras (Optional)
A comma-delimited list of extra information to fetch for each returned record.
you can use either of those: url_sq, url_t, url_s, url_q, url_m, url_n, url_z, url_c, url_l, url_o

Display images using Base64 and Node.js

I'm trying to get some blob files (images) and then display it on the screen using base64.
This is my node.js code:
var queryimage = "SELECT iproduct FROM images";
connection.query(queryimage, function(err, rows, fields){
socket.emit('image_prova', new Buffer(rows, 'binary').toString('base64'));
});
Then I'm getting the suposed string:
websocket.on('image_prova', function(data){
$('#imagehere').append('<img src=data:image/jpeg;base64,'+data+' />');
});
The image is not being displayed and the string given is: AA==
I don't understand why...!
You are passing rows instead of rows[0] to Buffer. You only requested one, but it is still an array, so you need to access the one you actually want.
If that doesn't work, let me know.

How do I convert an html table to an Excel File?

I'm trying to get my page Data.aspx to return an html table, but I want that table to be in an excel format. This is my code so far.
In the Data.aspx Load:
Response.Clear()
Select Case lstrCmd
Case "summary"
Response.Write(Summary())
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Case "export"
Response.ContentType = "application/ms-excel"
Response.AddHeader("Content-Disposition", "attachment;filename=" & _
mstrProjectName & ".xls")
Response.Write(SummaryExport())
End Select
Response.End()
So the add header is where I'm puzzled. This is something another peice of my software uses, but I'm not sure if it will work..
the jquery that calls this is using ajax:
function btnSubmitExport_Click() {
var compID = $("#ddlCompanies").val();
var projectID = $("#ddlProjects").val();
var startDate = $("#txtStartDate").val();
var endDate = $("#txtEndDate").val();
var compName = $("#ddlCompanies :selected").text();
var projectName = $("#ddlProjects :selected").text();
$("#content").html("<div class='loading'>loading...</div>");
$.ajax({
url: "Data.aspx",
data: {
CompanyID: compID,
ProjectID: projectID,
CompanyName: compName,
ProjectName: projectName,
StartDate: startDate,
EndDate: endDate,
Cmd: "export"
},
success: function(html) {
$("#content").html(html);
},
error: function(response) {
alert(response);
}
});
}
So, typically, when I request this data, I just throw the resulting html into a "content" div on my default.aspx page.. but I want that html to be an excel file!
Any hints or thoughts on this would be helpful.
I see the same question in other places, but not any answers that help me with my existing code..
If you have an html text contains Table tag in it, simple save it with extension of XLS and Microsoft Excel will open it like a charm! And also as I've seen, you want user to download the file, not to show its content in the page. You should redirect page on your ASPX page directly (without using JQuery). I'd suggest you to use network monitor in the developer tools to see what's happening.
Cheers
Normaly you would need to use this header
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "filename=excelfile.xls"
Print all the output as you want it in this specific page and that would be it.
Research on these headers and you will be fine.

Exchange EWS MailItem shows attachment but doesn't let me retrieve the fileattachment

I'm trying to load a file attachment (its an image file) from an exchange email.
`
foreach (EmailMessage item in findResults.Items)
{
if (item.HasAttachments)
{
var something = item.Attachments[0];
foreach (Attachment attachment in item.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fattach = (FileAttachment)attachment;`
For some reason, even though the item has an attachment (I can confirm this by logging into the web interface), it does not allow me to retrieve the fileattachment.
It shows up as null. Why would an item have an attachment in the collection BUT not have it be retrievable?
I had a similar problem that not all properties are set, so you need to call LoadPropertiesForItems method from the Exchange service itself to load the extra data like attachments.
for example if you want to load all the attachments of the item x and the exchange service instance is s then:
List<Item> xlist = new List<Item>();
xlist.Add(x);
s.LoadPropertiesForItems(xlist,PropertySet.FirstClassProperties);
When binding to the Item, you need to specify the Attachments property. The following code sample should help:
PropertySet propertySet = new PropertySet(ItemSchema.Subject, ItemSchema.Attachments);
Item item = Item.Bind(service, itemId, propertySet);
you missed to load the attachment. Please see the below example for idea
EmailMessage msgInfo = null;
foreach (Item msgItemInfo in msgItemWithNotification)
{
msgInfo = EmailMessage.Bind(exchange, msgItemInfo.Id);
foreach (Attachment attachment in msgInfo.Attachments)
{
if( attachment is FileAttachment)
{
FileAttachment fattach = attachment as MSEWS.FileAttachment;
fattach.Load();
Stream excelFileStream = new System.IO.MemoryStream(fattach.Content);
}
}
}