Missing "translate.js" in Google Cloud Translate API - javascript

I decided to use Google Cloud Translation API for my project. Everything seemed fine until the moment I tried to run their script. It always says that I need to "Use require([])".
Right after I add square brackets inside my require's argument, it says I have to remove braces around Translate variable, 'cause it's not a constructor (though, in Google's script it is coded SO). I do that, and I get even more errors. Like this:
I dunno how to fix that. Spent whole days trying to figure out what's wrong, but haven't done any progress ever since. Maybe, I'm lacking the translate.js file, since it indicates that on the 2nd picture. But I did everything as said in Quickstart tutorial on Google's official website, and the following command (npm install #google-cloud/translate) does download many packages, but doesn't do anything justice, meaning, it doesn't download any translate.js or something of that sort.
The source code is below:
index.html:
<html>
<head>
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
<script src="test.js"></script>
</head>
<body><script>main()</script></body>
</html>
test.js:
async function main(
projectId = 'text-analyzer-1571113830391' // Your GCP Project Id
) {
// [START translate_quickstart]
// Imports the Google Cloud client library
const Translate = require(['#google-cloud/translate']);
// Instantiates a client
const translate = new Translate({projectId});
// The text to translate
const text = 'Hello, world!';
// The target language
const target = 'ru';
// Translates some text into Russian
const [translation] = await translate.translate(text, target);
console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);
}
// [END translate_quickstart]

Thanks to #Kolban, I've recalled that Node.js is a server-side API, and it can't do any logic in a browser. To do that, you have to use some third-party product like Webpack to transform your code or, either way, make REST calls via Ajax. Thanks again, Kolban!
The topic can be closed.

Related

JavaScript Import / export fail

I made a little script to just highlight for myself some words automatically because I am useing Html format to write personal notes.
It works if I let everything in the same file but it's impossible to understand how to import and export works; I even downloaded a sample package from here and it doesn't work either.
I know there is big packaging existing to do the same thing but I just want to push a simple "js" file in the same folder and let it do the work, I just need to import/export to don't have to rewrite each time I modify the common ".js" (for coloring).
Perhaps I don't use the good keyword, but I don't find any correct information.
I will let a basic sample of my code (for the while they are in the same folder)
//csharp.js
import "./ColorText.js"
function foo(){
const blueWords = ["Task", "TaskScheduler", "void"];
var xx = document.getElementsByClassName("csharp");
for (i=0;i<xx.length;i++){
var str=xx[i].innerHTML;
ColorTextInBlue(xx[i], "Task");
}
}
I tried this part even with "//target..." to disable it.
export{ColorTextInBlue};
function ColorTextInBlue(target, str)
{
target.innerHTML=target.innerHTML.replace(new RegExp(str, 'g'),
"<font color=\"#0000FF\">"+str+"</font>");
}
HTML part
<!-- Scripts -->
<script type="module" src="./ColorText.js" ></script>
<script src="./CSharp.js" ></script>
I read there is something about a javascript revision but it's not clear at all.
If possible modify directly the code to see how it must be done.
Code edited to remove the dot, the second loop and to simplify the code.

JS code working when ran in a node context but Uncaught ReferenceError in console

I am just working my way through this tutorial: https://ethereum.org/en/developers/tutorials/getting-started-with-ethereum-development-using-alchemy/
Npm dependencies installed without any issues and here is the code I am trying to run:
const { createAlchemyWeb3 } = require("#alch/alchemy-web3");
const web3 = createAlchemyWeb3(
"https://eth-mainnet.alchemyapi.io/v2/1aZ1ZWH9087FqTnSSr7TI8ACFFgsIbcF"
)
async function main() {
const { createAlchemyWeb3 } = require("#alch/alchemy-web3")
const web3 = createAlchemyWeb3("https://eth-mainnet.alchemyapi.io/v2/1aZ1ZWH9087FqTnSSr7TI8ACFFgsIbcF")
const blockNumber = await web3.eth.getBlockNumber()
console.log("My first exercise! The latest block number is " + blockNumber)
}
main()
When loading it in the browser, I get Uncaught ReferenceError but when running the script file in command line using node, all works as expected.
What would be causing this? TIA :)
After looking at the tutorial link I'm fairly confident that the code you have is not meant for the browser. What you have is code for node.js. Specifically, the browser does not understand require().
It is possible to make what you wrote work on the browser if you use something like Webpack or Browserify - these are javascript compilers that compiles javascript to javascript. That may look weird at first, if you are writing javascript then why would you want to compile it to javascript? Well, one of the things they allow you to do is to use some features that your browser may not support, for example require() or new proposed language features.
However, I'm not going down that path. Instead I would like to encourage you to read the alchemy-web3 documentation because I think that's an important skill to learn for javascript developers.
If you google "alchemy-web3" one of the top results would be it's github page: https://github.com/alchemyplatform/alchemy-web3. Go to the github page and have a quick read. Alternatively (and I do this more often than google) you can go to https://www.npmjs.com/ and search for "alchemy-web3". You will get this page: https://www.npmjs.com/package/#alch/alchemy-web3
They're both the same page but npmjs will not give results that are not javascript libraries. If you glance at the alchemy-web3 page you will see some examples for how to use it. This is why I think learning to find and read library documentation is an important skill for a javascript programmer - because unlike most other languages most javascript libraries tend to have good handwritten documentation.
If you read the documentation you will see how to use it in a browser. Instead of doing a require() you include the alchemy-web3 library in a script tag:
<!DOCTYPE html>
<!-- Name this file something like Testing.html: -->
<!-- In HTML we do this instead of require() -->
<script src="https://cdn.jsdelivr.net/npm/#alch/alchemy-web3#latest/dist/alchemyWeb3.min.js"></script>
<script>
// Now your script:
const web3 = AlchemyWeb3.createAlchemyWeb3(
"https://eth-mainnet.alchemyapi.io/v2/1aZ1ZWH9087FqTnSSr7TI8ACFFgsIbcF"
)
async function main() {
const web3 = AlchemyWeb3.createAlchemyWeb3("https://eth-mainnet.alchemyapi.io/v2/1aZ1ZWH9087FqTnSSr7TI8ACFFgsIbcF")
const blockNumber = await web3.eth.getBlockNumber()
console.log("My first exercise! The latest block number is " + blockNumber)
// In the browser you can also output to the DOM:
document.body.innerHTML += "My first exercise! The latest block number is " + blockNumber
}
main()
</script>
Note: as mentioned in the documentation, in the browser use AlchemyWeb3.createAlchemyWeb3()

Moving created files with JXA

I'm new to JXA scripting, but I'm attempting to troubleshoot some older scripts currently in place here at work. They loop through an InDesign document and create several PDFs based on it. Previously, they would be stored in a folder called "~/PDFExports". However, this doesn't work with 10.10.
If I change the code to just place the PDFs in "~/", it works fine. From there, I'd like to move the files to "~/PDFExports", but I can't seem to find an answer on how to do that. I've seen things about making calls to ObjC, or to call Application('Finder'), but neither work - they both return undefined.
Am I just missing something basic here, or is it really this hard to simply move a file with JXA?
EDIT: Some syntax for how I'm creating the folder in question and how I'm attempting to work with Finder.
//This is called in the Main function of the script, on first run.
var exportFolder = new Folder(exportPath);
if(!exportFolder.exists) {
exportFolder.create();
}
//This is called right after the PDF is created. file is a reference to the
actual PDF file, and destination is a file path string.
function MoveFile(file,destination){
var Finder = Application("Finder");
Application('Finder').move(sourceFile, { to: destinationFolder });
alert("File moved");
}
Adobe apps have long included their own embedded JS interpreter, JS API, and .jsx filename extension. It has nothing to do with JXA, and is not compatible with it.
InDesign's JSX documentation:
http://www.adobe.com/devnet/indesign/documentation.html#idscripting
(BTW, I'd also strongly advise against using JXA for Adobe app automation as it has a lot of missing/broken features and application compatibility problems, and really isn't fit for production work.)
Here's the link to Adobe's InDesign Scripting forum, which is the best place to get help with JSX:
https://forums.adobe.com/community/indesign/indesign_scripting
You could use Cocoa to create the folder
var exportFolder = $.NSHomeDirectory().stringByAppendingPathComponent("PDFExports")
var fileManager = $.NSFileManager.defaultManager
var folderExists = fileManager.fileExistsAtPath(exportFolder)
if (!folderExists) {
fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(exportFolder, false, $(), $())
}
and to move a file
var success = fileManager.moveItemAtPathToPathError(sourceFile, destinationLocation, $());
if (success) alert("File moved");
Consider that destinationLocation must be the full path including the file name
and both sourceFile and destinationLocation must be NSString objects like exportFolder
Could it be that the folder is missing ? Could be your reference to the folder object not valid ? Any syntax to show ?
I will share some of what I learned about JXA move and duplicate methods. I am not a professional programmer just an attorney that is passionate about automation. My comments come from much trial and error, reading whatever I could find online, and A LOT of struggle. The move method does not work well with Finder. Use the System Events move method instead. The duplicate method in Finder works just fine. The duplicate method does not work well in system events. This is a modified snippet from a script I wrote showing move() using System Events.
(() => {
const strPathTargetFile = '/Users/bretfarve/Documents/MyFolderA/myFile.txt';
const strPathFolder = '/Users/bretfarve/Documents/MyFolderB/';
/* System Events Objects */
const SysEvents = Application('System Events');
const objPathFolder = SysEvents.aliases[strPathFolder];
SysEvents.move(SysEvents.aliases.byName(strPathTargetFile), {to: objPathFolder});
})();

IPython: Adding Javascript scripts to IPython notebook

As a part of a project, I need to embedd some javascripts inside an IPython module.
This is what I want to do:
from IPython.display import display,Javascript
Javascript('echo("sdfds");',lib='/home/student/Gl.js')
My Gl.js looks like this
function echo(a){
alert(a);
}
Is there some way so that I can embed "Gl.js" and other such external scripts inside the notebook, such that I dont have to include them as 'lib' argument everytime I try to execute some Javascript code which requires to that library.
As a very short-term solution, you can make use of the IPython display() and HTML() functions to inject some JavaScript into the page.
from IPython.display import display, HTML
js = "<script>alert('Hello World!');</script>"
display(HTML(js))
Although I do not recommend this over the official custom.js method, I do sometimes find it useful to quickly test something or to dynamically generate a small JavaScript snippet.
Embedding D3 in an IPython Notebook
https://blog.thedataincubator.com/2015/08/embedding-d3-in-an-ipython-notebook/
To summarize the code.
Import the script:
%%javascript
require.config({
paths: {
d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min'
}
});
Add an element like this:
%%javascript
element.append("<div id='chart1'></div>");
Or this:
from IPython.display import Javascript
#runs arbitrary javascript, client-side
Javascript("""
window.vizObj={};
""".format(df.to_json()))
IPython Notebook: Javascript/Python Bi-directional Communication
http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/
A more extensive post explaining how to access Python variables in JavaScript and vice versa.
I've been fighting with this problem for several days now, here's something that looks like it works; buyer beware though, this is a minimal working solution and it's neither pretty nor optimal - a nicer solution would be very welcome!
First, in .ipython/<profile>/static/custom/myScript.js, we do some require.js magic:
define(function(){
var foo = function(){
console.log('bar');
}
return {
foo : foo
}
});
Copy this pattern for as many functions as you like. Then, in .ipython/<profile>/static/custom/custom.js, drag those out into something persistent:
$([IPython.events]).on('notebook_loaded.Notebook', function(){
require(['custom/myScript'], function(custom){
window.foo = custom.foo;
} );
});
Yes, I am a horrible person for throwing stuff on the window object, namespace things as you deem appropriate. But now in the notebook, a cell like
%%javascript
foo();
should do exactly what it looks like it should, without the user having to explicitly import your JS. I would love to see a simpler solution for this (plz devs can we plz have $.getScript('/static/custom/util.js'); in custom.js to load up a bunch of global JS functions) - but this is the best I've got for now. This singing and dancing aside, HUGE ups to the IPython notebook team, this is an awesome platform!
Not out of the box by installing a package, at least for now.
The way to do it is to use custom.js and jQuery getScript to inject the js into the notebook.
I explicitly stay vague on how to do it, as it is a dev feature changing from time to time.
What you should know is that the static folder in user profile is merged with webserver static assets allowing you to access any file that are in this folder by asking for the right url.
Also this question has been asked a few hours ago on IPython weekly video "lab meeting" broadcasted live and disponible on youtube (you might have a longer answer), I've opened discussion with the author of the question here
For some reason, I have problems with IPython.display.Javascript. Here is my alternative, which can handle both importing external .js files and running custom code:
from IPython.display import display, HTML
def javascript(*st,file=None):
if len(st) == 1 and file is None:
s = st[0]
elif len(st) == 0 and file is not None:
s = open(file).read()
else:
raise ValueError('Pass either a string or file=.')
display(HTML("<script type='text/javascript'>" + s + "</script>"))
Usage is as follows:
javascript('alert("hi")')
javascript(file='Gl.js')
javascript('echo("sdfds")')
You can use IJavascript (a Javascript kernel for Jupyter notebooks).
I was interested in calling JavaScript from a Jupyter code (Python) cell to process strings, and have the processed string output in the (same) code cell output; thanks to Inject/execute JS code to IPython notebook and forbid its further execution on page reload and Why cannot python call Javascript() from within a python function? now I have this example:
from IPython.display import display, Javascript, Markdown as md, HTML
def js_convert_str_html(instring_str):
js_convert = """
<div id="_my_special_div"></div>
<script>
var myinputstring = '{0}';
function do_convert_str_html(instr) {{
return instr.toUpperCase();
}}
document.getElementById("_my_special_div").textContent = do_convert_str_html(myinputstring);
</script>
""".format(instring_str)
return HTML(js_convert)
jsobj = js_convert_str_html("hello world")
display(jsobj)
Note that the JavaScript-processed string does not get returned to Python per se; rather, the JavaScript itself creates its own div, and adds the result of the string conversion to it.

Javascript Build Tools To Toggle Urls/Variables Between Production/Deployment

I am beginning my first big javascript project! I had a question about deployment. I am using ajax calls to a webservice. To set this up I have a static JS file with code like:
var API_URL_ROOT = 'http://api.example.com/';
var IN_DEVELOPMENT = True;
if (IN_DEVELOPMENT) {
API_URL_ROOT = 'http://localhost.com/api';
}
$.get(API_URL_ROOT)
I am using python/fabric to deploy. I was wondering if there were any prebuilt tools for handling the static analysis/manipulation of the javascript files., Right now it leaves toggling up to the commiters
I was planning on a deployment process like:
issue deploy command
"build" JS, by setting all values to production values (ie. IN_DEVELOPMENT = False)
Minify JS
Deploy code to production servers
I was thinking of just using sed or something to do the IN_DEVELPMENT = False replacement. I have looked at some of the popular minification tools and none seem to offer this sort of functionality.
I would assume that this is a pretty common problem for applications. How is it usually handled? Any help would be appreciated. Thank you
I recently read an article on hackernews from mozilla:
In the Mozilla Persona code base, we frequently expose difficult to
test private functions to the public interface, clearly marking the
extra functions as part of a test API. While other developers are
still able to call these private functions, the author’s intentions
are clear.
...
publicFunction: function() {
return "publicFunction can be invoked externally but "
+ privateFunction();
}
// BEGIN TESTING API
,
privateFunction: privateFunction
// END TESTING API
};
// privateFunction is now accessible via the TESTING API
function privateFunction() {
...
Code between the // BEGIN TESTING API and //END TESTING API
pseudo-markers can be removed for production during the build process.
So other companies are definitely doing this. Are there premade tools to facilitate the JS build proccess that can remove this code? I glanced at a number of their projects on github and didn't see any. Thank you
We are using dojo
And in dojo you can use conditional exclusions for the build version of your js in order to exclude parts of your code that you would not want in your build js. Hope this helps.
eg:
var API_URL_ROOT = 'http://api.example.com/';
//>>excludeStart("dev",!pragmas.dev);
var IN_DEVELOPMENT = True;
//>>excludeEnd("dev");
if (IN_DEVELOPMENT) {
API_URL_ROOT = 'http://localhost.com/api';
}
$.get(API_URL_ROOT)

Categories

Resources