I was wondering how to convert Variable-length binary data(255216255224016747073700110010100255) to a jpeg or png to the web browser?
Example Code:
var Connection = require('tedious').Connection;
var config = {
"userName": "user#server.database.windows.net",
"password": "pswd",
"server": "server.database.windows.net",
"options": {
"database": "db",
"encrypt": true,
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
console.log("Connected");
}
);
var Request = require('tedious').Request;
var result,
resG;
function sendResponse() {
var vals;
// Convert to string then array
var resultA = result.toString().split(',');
// Now I can loop through the data returned
resultA.forEach(function(val, index, ar) {
if(vals == null) {
vals = val;
} else {
vals += val;
}
});
resG.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': vals.length});
//console.log(vals);
//resG.end("<img src=\"data:image/jpg;base64," + vals + "\" />");
// Output data returned from db as string
resG.end("" + vals);
}
function executeStatement() {
request = new Request("SELECT Photos FROM dbo.tbl WHERE FarmerFirstName='someName' AND FarmerLastName='someLastName'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
result = column.value;
});
});
request.on('doneInProc', function(rowCount, more) {
// Got everything needed from db move on to sending a response
sendResponse();
});
connection.execSql(request);
}
var http = require('http'),
director = require('director');
var router = new director.http.Router({
"/": {
get: executeStatement
}
});
var server = http.createServer(function (req, res) {
// set global res var
resG = res;
router.dispatch(req, res, function (err) {
if (err) {
res.writeHead(404);
res.end();
}
});
});
server.listen(80);
I'm using tedious for my db connector and director as my router.
The result is already an array of bytes for the Image. You do not need to do any fancy transformations on it. This should work.
function sendResponse() {
resG.writeHead(200, {'Content-Type': 'image/jpeg', 'Content-Length': result.length});
resG.end(new Buffer(result));
}
or if you want to serve it as part of an HTML page, this:
function sendResponse() {
resG.writeHead(200, {'Content-Type': 'text/html'});
var vals = (new Buffer(result)).toString('base64')
resG.end("<html><body>" +
"<img src=\"data:image/jpg;base64," + vals + "\" />" +
"</body></html>");
}
Related
I try to set up plugin ckeditor/ckeditor5-export-pdf on my Laravel App But I cant do this. I still get issues like: Uncaught TypeError: Failed to resolve module specifier "#ckeditor/ckeditor5-export-pdf/src/exportpdf". Relative references must start with either "/", "./", or "../".
I did all steps as in docs: https://ckeditor.com/docs/ckeditor5/latest/features/export-pdf.html#configuration But when I try use import ExportPdf from '#ckeditor/ckeditor5-export-pdf/src/exportpdf'; I get the error like above. Please help. Maybe some have stuck on this issue before
import ExportPdf from '#ckeditor/ckeditor5-export-pdf/src/exportpdf';
console.log(ExportPdf);
$(document).ready(function () {
/*function ExportPdf(editor) {
editor.execute('exportPdf');
}*/
function SimpleUploadAdapter(editor) {
editor.plugins.get('FileRepository').createUploadAdapter = function(loader) {
return {
upload: function() {
return loader.file
.then(function (file) {
return new Promise(function(resolve, reject) {
// Init request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/admin/instructions/ckmedia', true);
xhr.setRequestHeader('x-csrf-token', window._token);
xhr.setRequestHeader('Accept', 'application/json');
xhr.responseType = 'json';
// Init listeners
var genericErrorText = `Couldn't upload file: ${ file.name }.`;
xhr.addEventListener('error', function() { reject(genericErrorText) });
xhr.addEventListener('abort', function() { reject() });
xhr.addEventListener('load', function() {
var response = xhr.response;
if (!response || xhr.status !== 201) {
return reject(response && response.message ? `${genericErrorText}\n${xhr.status} ${response.message}` : `${genericErrorText}\n ${xhr.status} ${xhr.statusText}`);
}
$('form').append('<input type="hidden" name="ck-media[]" value="' + response.id + '">');
resolve({ default: response.url });
});
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
loader.uploadTotal = e.total;
loader.uploaded = e.loaded;
}
});
}
// Send request
var data = new FormData();
data.append('upload', file);
data.append('crud_id', {{ $instruction->id ?? 0 }});
xhr.send(data);
});
})
}
};
}
}
var allEditors = document.querySelectorAll('.ckeditor');
for (var i = 0; i < allEditors.length; ++i) {
ClassicEditor.create(
allEditors[i], {
extraPlugins: [SimpleUploadAdapter, /*ExportPdf*/],
/*toolbar: [
'exportPdf', '|',
],
exportPdf: {
stylesheets: [
'./path/to/fonts.css',
'EDITOR_STYLES',
'./path/to/style.css'
],
fileName: 'my-file.pdf',
converterOptions: {
format: 'A4',
margin_top: '20mm',
margin_bottom: '20mm',
margin_right: '12mm',
margin_left: '12mm',
page_orientation: 'portrait'
}
}*/
}
);
}
});
</script>```
I solved my problem with https://ckeditor.com/ckeditor-5/online-builder/ Builded what I want and setup it on my App
I am trying to accomplish this:
I have a spell checker in the middleware. In case the user's input text does not match the corrected text, I would like to confirm the corrected text with the user before proceeding. I tried several approaches but have not been able to achieve this. Here's the code I wrote:
app.js:
var builder = require('botbuilder');
var restify = require('restify');
var spellService = require('./spell-service')
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create connector and listen for messages
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());
var bot = new builder.UniversalBot(connector, function (session) {
session.beginDialog('search');
});
bot.dialog('search', [
function (session, args, next) {
builder.Prompts.text(session, 'Type the name of a company you would like to search');
}
]);
//=========================================================
// Spell checker
//=========================================================
const dontCorrectIdentifier = "dontCorrect";
bot.use({
botbuilder: function (session, next) {
if (session.message.text.startsWith(dontCorrectIdentifier)) {
session.message.text = session.message.text.replace(dontCorrectIdentifier, "");
next();
} else {
spellService
.getCorrectedText(session.message.text)
.then(function (text) {
if (session.message.text !== text) {
var msg = new builder.Message(session)
.text("Did you mean \"" + text + "\"?")
.suggestedActions(builder.SuggestedActions.create(session, [
builder.CardAction.postBack(session, dontCorrectIdentifier + text, "Yes"),
builder.CardAction.postBack(session, dontCorrectIdentifier + session.message.text, "No")
]
));
builder.Prompts.text(session, msg);
}
next();
})
.catch(function (error) {
console.error(error);
next();
});
}
}
});
spell-service.js
// from https://dev.cognitive.microsoft.com/docs/services/56e73033cf5ff80c2008c679/operations/56e73036cf5ff81048ee6727
var request = require('request');
var SPELL_CHECK_API_URL = 'https://api.cognitive.microsoft.com/bing/v7.0/SpellCheck?mkt=en-US&mode=proof',
SPELL_CHECK_API_KEY = 'MY KEY';
/**
* Gets the correct spelling for the given text
* #param {string} text The text to be corrected
* #returns {Promise} Promise with corrected text if succeeded, error otherwise.
*/
exports.getCorrectedText = function (text) {
return new Promise(function (resolve, reject) {
if (text) {
var requestData = {
url: SPELL_CHECK_API_URL,
headers: {
"Ocp-Apim-Subscription-Key": SPELL_CHECK_API_KEY
},
form: {
text: text
},
json: true
};
request.post(requestData, function (error, response, body) {
if (error) {
reject(error);
} else if (response.statusCode != 200) {
reject(body);
} else {
var previousOffset = 0;
var result = '';
for (var i = 0; i < body.flaggedTokens.length; i++) {
var element = body.flaggedTokens[i];
// append the text from the previous offset to the current misspelled word offset
result += text.substring(previousOffset, element.offset);
// append the first suggested correction instead of the misspelled word
result += element.suggestions[0].suggestion;
// Increment the offset by the length of the misspelled word
previousOffset = element.offset + element.token.length;
}
// Append the text after the last misspelled word.
if (previousOffset < text.length) {
result += text.substring(previousOffset);
}
resolve(result);
}
});
} else {
resolve(text);
}
})
};
Based on Gary's suggestion, here's the right way to do this:
bot.use({
botbuilder: function (session, next) {
if (session.message.text.startsWith(dontCorrectIdentifier)) {
session.message.text = session.message.text.replace(dontCorrectIdentifier, "");
next();
} else {
spellService
.getCorrectedText(session.message.text)
.then(function (text) {
if (session.message.text !== text) {
var msg = new builder.Message(session)
.text("Did you mean \"" + text + "\"?")
.suggestedActions(builder.SuggestedActions.create(session, [
builder.CardAction.postBack(session, dontCorrectIdentifier + text, "Yes"),
builder.CardAction.postBack(session, dontCorrectIdentifier + session.message.text, "No")
]
));
session.send(msg);
} else {
next();
}
})
.catch(function (error) {
console.error(error);
next();
});
}
}
});
Modify the logic flow in the builder middle, which works fine on my side:
bot.use({
botbuilder: (session, next) => {
if (session.message.text.startsWith(dontCorrectIdentifier)) {
session.message.text = session.message.text.replace(dontCorrectIdentifier, "");
next();
} else {
var text = session.message.text;
var msg = new builder.Message(session)
.text("Did you mean \"" + text + "\"?")
.suggestedActions(builder.SuggestedActions.create(session, [
builder.CardAction.postBack(session, dontCorrectIdentifier + text, "Yes"),
builder.CardAction.postBack(session, dontCorrectIdentifier + session.message.text, "No")
]));
session.send(msg);
}
},
})
Use session.send(msg); replace builder.Prompts.text(session, msg).
And remove next() in the else condition.
You need to append text parameter in URL. I tried this in curl:
curl -v -X GET https://api.cognitive.microsoft.com/bing/v7.0/SpellCheck?mkt=en-US&mode=proof&text=hollo%2Cwrld
The other thing is hyphen between spell and service in your .js file. You can probably try to check json response first to see if you are getting correction back.
Using ionic,
I am trying to create an image blob from URI and have tried several codes but failed.
Here is where I implement the imagepicker in ionic:
$cordovaImagePicker.getPictures(options)
.then(function (results) {
console.log(results[0]);
var datablob = $scope.dataURItoBlob(results[0]);
technique 1 (create the blob):
$scope.dataURItoBlob = function(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
return new Blob([new Uint8Array(array)], {
type: mimeString
});
}
technique 2 (create the blob):
$scope.dataURItoBlob = function(dataURI) {
var arr = dataURI.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
Both techniques does not work. Please help! thank you very much.
$cordovaImagePicker.getPictures(options)
.then(function (results) {
console.log(results[0]);
dataURItoBlob(results[0], function(url){
var datablob = url;
}, function(error){
console.error(error);
})
})
function dataURItoBlob(path, cb, error) {
resolveLocalFileSystemURL(path, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
if (typeof cb === 'function') {
cb(this.result)
}
};
reader.readAsDataURL(file);
}, function (err) {
if (typeof error === 'function') {
error(err)
}
});
});
}
Needs to cordova-plugin-file
const {Cc,Ci,Cr} = require("chrome");
function TracingListener() {
//this.receivedData = [];
}
function CCIN(cName, ifaceName) {
return Cc[cName].createInstance(Ci[ifaceName]);
}
function CCSV(cName, ifaceName){
if (Cc[cName])
// if fbs fails to load, the error can be _CC[cName] has no properties
return Cc[cName].getService(Ci[ifaceName]);
};
TracingListener.prototype =
{
originalListener: null,
receivedData: null, // array for incoming data.
onDataAvailable: function(request, context, inputStream, offset, count)
{
this.originalListener.onDataAvailable(request, context,inputStream, offset, count);
},
onStartRequest: function(request, context) {
this.receivedData = [];
this.originalListener.onStartRequest(request, context);
//thechannel.setRequestHeader("X-Hello", "World", false);
//this part of code will stop the request
/*request.QueryInterface(Ci.nsIHttpChannel);
var cookie=request.getRequestHeader("Cookie");
console.log("cookie="+cookie);*/
var postText = this.readPostTextFromRequest(request, context);
console.log("postText="+postText111);
},
onStopRequest: function(request, context, statusCode)
{
//this part of code will successfullly print the cookie
/*request.QueryInterface(Ci.nsIHttpChannel);
var cookie=request.getRequestHeader("Cookie");
console.log("cookie="+cookie);*/
this.originalListener.onStopRequest(request, context, statusCode);
},
QueryInterface: function (aIID) {
if (aIID.equals(Ci.nsIStreamListener) ||
aIID.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_NOINTERFACE;
},
readPostTextFromRequest : function(request, context) {
try
{
var is = request.QueryInterface(Ci.nsIUploadChannel).uploadStream;
if (is)
{
var ss = is.QueryInterface(Ci.nsISeekableStream);
var prevOffset;
if (ss)
{
prevOffset = ss.tell();
ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
}
// Read data from the stream..
var charset = "UTF-8";
var text = this.readFromStream(is, charset, true);
// Seek locks the file so, seek to the beginning only if necko hasn't read it yet,
// since necko doesn't seek to 0 before reading (at lest not till 459384 is fixed).
if (ss && prevOffset == 0)
ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
return text;
}
else {
//dump("Failed to Query Interface for upload stream.\n");
}
}
catch(exc)
{
//dumpError(exc);
}
return null;
},
readFromStream : function(stream, charset, noClose) {
var sis = CCSV("#mozilla.org/binaryinputstream;1", "nsIBinaryInputStream");
sis.setInputStream(stream);
var segments = [];
for (var count = stream.available(); count; count = stream.available())
segments.push(sis.readBytes(count));
if (!noClose)
sis.close();
var text = segments.join("");
return text;
}
}
hRO = {
observe: function(request, aTopic, aData){
try {
if (aTopic == "http-on-examine-response") {
request.QueryInterface(Ci.nsIHttpChannel);
//if (request.originalURI && piratequesting.baseURL == request.originalURI.prePath && request.originalURI.path.indexOf("/index.php?ajax=") == 0) {
var newListener = new TracingListener();
request.QueryInterface(Ci.nsITraceableChannel);
newListener.originalListener = request.setNewListener(newListener);
//}
}
} catch (e) {
/*dump("\nhRO error: \n\tMessage: " + e.message + "\n\tFile: " + e.fileName + " line: " + e.lineNumber + "\n");*/
}
},
QueryInterface: function(aIID){
if (aIID.equals(Ci.nsIObserver) ||
aIID.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_NOINTERFACE;
},
};
var observerService = Cc["#mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
observerService.addObserver(hRO,
"http-on-examine-response", false);
My question is: the same lines of code:
request.QueryInterface(Ci.nsIHttpChannel);
var cookie=request.getRequestHeader("Cookie");
console.log("cookie="+cookie);
performs different results in onStartRequest and onStopRequest, why?
I can read the cookie in onStopRequest but fails in onStartRequest. I don't think the request is not ready in onStartRequest because I can read the postText in onStartRequest.
I've written my first program with racer. It displays a simple text box manually bound to 'col.doc.prop' path. When I change the value, it does not apply to the store at server.
What causes my subscribed model not to get sync with server?
Server code:
var fs = require('fs');
var io = require('socket.io');
var racer = require('racer');
var mongo = require('racer-db-mongo');
racer.use(mongo);
racer.js({
entry: __dirname + '/client.js'
}, function(err, js) {
return fs.writeFileSync(__dirname + '/script.js', js);
});
var express = require('express');
var server = express.createServer();
server.use(express.static(__dirname));
server.get('/', function(req, res)
{
var model = store.createModel();
model.subscribe('col.doc', function(err, doc)
{
var prop = doc.get('prop');
if (!prop)
{
doc.set('prop', 123);
store.flush();
}
model.ref('_doc', doc);
model.bundle(function(bundle)
{
var client = require('fs').readFileSync('./client.html', 'utf-8');
client = client.replace('_init_', bundle.toString());
res.send(client);
});
});
});
var store = racer.createStore(
{
listen: server,
db:
{
type: 'Mongo',
uri: 'mongodb://localhost/racerdb'
}
});
store.set('col.doc.prop', 123);
store.flush();
server.listen(3001);
Client code:
useRacer = function()
{
var socket = io.connect('http://localhost:3001');
var racer = require('racer');
process.nextTick(function() {
racer.init(this.init, socket);
return delete this.init;
});
racer.on('ready', function(model)
{
addListener = document.addEventListener ? function(el, type, listener) {
return el.addEventListener(type, listener, false);
} : function(el, type, listener) {
return el.attachEvent('on' + type, function(e) {
return listener(e || event);
});
};
var element = document.getElementById('prop');
var listener = function()
{
var val = element.value;
model.set('col.doc.prop', val);
};
addListener(element, 'keyup', listener);
var upgrade = function(id, value)
{
if (model.connected)
{
var prop = model.get('col.doc.prop');
element.value = prop;
}
else
model.socket.socket.connect();
};
model.on('connectionStatus', upgrade);
model.on('set', 'con.*', upgrade);
});
};
The problem solved by changing some lines of the client code:
model.set('col.doc.prop', val) ==> model.set('_doc.prop', val)
model.get('col.doc.prop') ==> model.get('_doc.prop')
model.on('set', 'con.', upgrade) ==> model.on('set', '', upgrade)