Using Microsoft Translator using Javascript/AJAX - ajax

Trying to figure out how to use the MS Translator API to use the MS Translator but running into problems.
I don't have the ability to serve up a Node, PHP or other server to securely provide the ClientID or ClientSecret at this time so I'm trying to do it simply with straight HTML and Javascript for now.
I'm trying to use this AJAX as recommended by MS API but I believe this is looking for the server to provide the authentication. Looking for help to figure out how to right this with HTML/JS without the server side authentication. Thanks!
function translate() {
var from = "en", to = "es", text = "hello world";
var s = document.createElement("script");
s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
"?appId=" + settings.appID +
"&from=" + encodeURIComponent(from) +
"&to=" + encodeURIComponent(to) +
"&text=" + encodeURIComponent(text) +
"&oncomplete=mycallback";
document.body.appendChild(s);
}
function mycallback(response) {
alert(response);
}

Try using appId=8B841CA7C1A03443682C52AD07B7775A7BD5B3AA
This works fine for me, I found that on the other thread. Sorry if this is not what you are looking for. I have to admit the authentication is the difficult part, I even tried using the script found at the MDSN page on translate, http://msdn.microsoft.com/en-us/library/ff512406.aspx
I couldn't comment with my 26 rep points, so I am writing here as my answer. Thanks.

Related

Debugging webOS TV service

I'm currently developing a webOS TV application which includes a background running service. I'm having trouble getting logs to print in the NodeJS console.
I have no prior experience working with Node so I'm unsure whether any additional modules are required to get this done(but I highly doubt it, and the docs don't seem to suggest so.)
As of now my service side code is as follows;
var Service = require('webos-service');
var service = new Service("com.nuwan.helloworld.service");
// code to keep the service from being terminated
var keepAlive;
service.activityManager.create("keepAlive", function(activity) {
keepAlive = activity;
});
service.activityManager.complete(keepAlive, function(activity) {
console.log("completed activity");
});
// hello command implementation
service.register("hello", function(message) {
var response = message.respond({
data: "Hello, " + message.payload.name + "!"
});
});
It would be great if someone could give me some pointers.
As it is right now, I'm not getting any output whatsoever on the Node Profiler console.
The way i did it ( i don't know if that's the only way) to debug the code is through the chromium debugger eg.
This is a generic image to see from where you are going to check the code.

Telegram Bot Random Images (How to send random images with Telegram-Bot)

const TeleBot = require('telebot');
const bot = new TeleBot({
token: 'i9NhrhCQGq7rxaA' // Telegram Bot API token.
});
bot.on(/^([Hh]ey|[Hh]oi|[Hh]a*i)$/, function (msg) {
return bot.sendMessage(msg.from.id, "Hello Commander");
});
var Historiepics = ['Schoolfotos/grr.jpg', 'Schoolfotos/boe.jpg',
'Schoolfotos/tobinsexy.jpg'];
console.log('Historiepics')
console.log(Math.floor(Math.random() * Historiepics.length));
var foto = Historiepics[(Math.floor(Math.random() * Historiepics.length))];
bot.on(/aap/, (msg) => {
return bot.sendPhoto(msg.from.id, foto);
});
bot.start();
The result I'm getting from this is just one picture everytime, but if I ask for another random picture it keeps showing me the same one without change.
I recently figured this out, so I'll drop an answer for anyone that runs into this issue.
The problem is with Telegram's cache. They cache images server side so that they don't have to do multiple requests to the same url. This protects them from potentially getting blacklisted for too many requests, and makes things snappier.
Unfortunately if you're using an API like The Cat API this means you will be sending the same image over and over again. The simplest solution is just to somehow make the link a little different every time. This is most easily accomplished by including the current epoch time as a part of the url.
For your example with javascript this can be accomplished with the following modifications
bot.on(/aap/, (msg) => {
let epoch = (new Date).getTime();
return bot.sendPhoto(msg.from.id, foto + "?time=" + epoch);
});
Or something similar. The main point is, as long as the URL is different you won't receive a cached result. The other option is to download the file and then send it locally. This is what Telebot does if you pass the serverDownload option into sendPhoto.

how to use xml file in ajax chat?

I want to build a website like Facebook style, and for start i am building a chat system using ajax. For now, all the messages that are sent to the chat system are saved in a xml file which looks like this:
<messages>
<message from="jhon" time="2:00">Hi!</message>
</messages>
My question is if it is fine to use the xml file like i do here, or a database is the solution. Can someone explain to me how to use xml in the right way also in the chat or a messages system if it is necessary at all?
Thank you!
I made an exercise (for school) that worked in a simular way:
<post>
<time>15:25</time>
<name>myUserName</name>
<message>testbla</message>
</post>
I used a PHP-script (provided by the teacher) to write in the file (in the format like before) each time there is a new message being sent by the user. While it was working well, there were a few problems I encountered:
In order to keep the chat updated, I had to reload the chat 3600 times per hour. This is no problem. However, because I was using XML, I had to download the file 3600x per hour, which is definitely not an elegant solution; with only a few messages, the site consumed about 20-40 MB data each hour. (you do the math!)
There were also issues with the special chars that conflicted to XML: <, > and &. I had to either escape them, remove them from the user input OR use CDATA to prevent XML from crashing due to syntax errors. (XML is very sensitive for this!) Additional difficulty was to prevent that others could send bad code. Generally, try to eliminate this while updating your XML-file.
With the above in mind, I would recommend searching for a more elegant solution than XML; JSON might be lighter to handle. Alternatively, MYSQL/PHP allow you to send only the last messages, so you don't have to send the whole file over and over again. (I don't have any PHP/MYSQL-expertise at this moment, so I cannot help you with that right now)
You asked how you could make your XML-chat happen. To give you some direction, I will give you some snippets of my code (with jQuery):
/* this function gets chat logs from XML and manipulate the content to a
div used for the chat-content. It is being evaluated each second by
an interval that calls the function each 1000 ms. (not included in this code) */
function getChatLogs() {
var chatLogs = "";
$.ajax({
url: "chat_log.xml",
success: function(data) {
$(data).find("post").each(function() {
var timeMessage = $(this).find("time").text();
var nameSender = $(this).find("name").text();
var contentMessage = $(this).find("message").text();
chatLogs += "<article><time>" + timeMessage + "</time> <strong>" + nameSender + "</strong> <p>" + contentMessage+ "</p></article>";
});
$("#chat").html(chatLogs);
}
});
}
/* this function handles messages being send by the user */
function sendInput(keyCode) {
if(keyCode === 13 && $("#post").val() != "") {
var name = localStorage.getItem("username"); // I used localstorage fo username
var time = currentTime();
var message = $("#post").val();
$.ajax({
type: "POST",
url: "save.php",
data: {"name": name, "time": time, "message": message},
success: function(data) {
$("#post").val(""); // (clear the chat-input)
}
});
}
}
Bonus tip: you XML-file MUST be well formed. You can easily check if this is the case by opening the XML-file straight in Chrome. If there are issues, it will give an error.

why does socket.io error 500 with express.io?

Why does socket.io now give 500 (Internal Server Error) with express.io??
client side:
$(document).ready(function(){
$.getScript("http://www.mysite.com:8000/socket.io/socket.io.js",function(){
var socket = io.connect('http://www.mysite.com:8000'); //<<--error
socket.emit('ready');
});});
server side:
var express = require('express.io')
, engine = express().http().io();
engine.use(express.cookieParser());
engine.use(express.session({secret:'monkey'}));
engine.all('/',function(req,res,next){res.header("Access-Control-Allow-Origin","*");res.header("Access-Control-Allow-Headers","X-Requested-With");next();});
engine.get('/', function(req, res) {
req.session.loginDate = new Date().toString()
res.sendfile(__dirname)
});
engine.listen(8000);
engine.io.route('ready',function(socket){console.log('hellooooooooooo');});
I am following the docs on https://github.com/techpines/express.io, I have only changed two things: cross domain and app is called engine instead. I just can't see the problem Has anyone else got this to work?
Note: it's not using express.js it's using express.io (more compatable with socket.io)
It's like socket.io is not their listening on the server even though engine = express().http().io(); io is socket.io
I faced a similar problem, but I fixed it by copying and pasting the code sample in express.io sample code, and it worked. Then I compared them to check what the problem could be and observed that order of the code matters.
This order results in an error:
static
cookieParser
session
But when I followed the code provided in the sample code, I found out that this order works:
cookieParser
session
static
Hopefully this will also help you.
I believe the posted example is failing because you're using the call res.sendfile(__dirname) without supplying a filename.
This is coming from express.io, notice it uses res.sendfile(__dirname + '/client.html'):
express = require('express.io')
app = express().http().io()
// Setup your sessions, just like normal.
app.use(express.cookieParser())
app.use(express.session({secret: 'monkey'}))
// Session is automatically setup on initial request.
app.get('/', function(req, res) {
req.session.loginDate = new Date().toString()
res.sendfile(__dirname + '/client.html')
})

Node js - Creating persistent private chat rooms

I've been reading so much a bout node js lately, and the chat capabilities seem very nice. However, the only chat examples I've seen basically broadcast a chat server to a fixed URL (like a meeting room). Is it possible to use node js in part to create a chat client more like gchat? - where a chat window is popped up on the current page and then persists through multiple pages. Has anyone seen an example of this yet?
If not, suggestions for other technologies to use for this purpose (I know that's been answered in other questions)?
Thanks.
I'll give you a pseudo implementation relying on jquery and now to abstract away tedious IO and tedious DOM manipulation from the solution.
// Server
var nowjs = require('now');
var everyone = nowjs.initialize(httpServer);
everyone.now.joinRoom = function(room) {
nowjs.getGroup(room).addUser(this.user.clientId);
}
everyone.now.leaveRoom = function(room) {
nowjs.getGroup(room).removeUser(this.user.clientId);
}
everyone.now.messageRoom = function(room, message) {
nowjs.getGroup(room).now.message(message);
}
// Client
var currRoom = "";
$(".join").click(function() {
currRoom = ...
now.joinRoom(currRoom);
});
$(".send").click(function() {
var input = ...
now.messageRoom(currRoom, input.text());
});
now.messageRoom = function(message) {
$("messages").append($("<div></div>").text(message));
};
I only just noticed myself that the new version of nowjs (0.5) has the group system in build. This basically does what you want for you. No hassle.
If you want you can remove the nowjs dependency and replace it with 100/200 lines of code. I'll leave that as an exercise for the user.
Take a look at AjaxIM: https://github.com/freq32/AjaxIM
This is a facebook-style chat application (think friends list, small persistent chat bar at the bottom of the screen, popup chats) based on nodejs.

Resources