Semi(Auto) Code Generating with Python/Java/etc - javascript

Before anyone down votes or call out as duplicate. I searched for code generation, auto code complete, code complete with python, and code automation with Java/Python and every results I have got were not relevant to task I want to achieve.
I am free to use any language but Java or Python are preferred due to various libraries and api support.
Task I have is: need to write a program that outputs *.js file and in that file I am going to have a same function printed many time as number of inputs.
Here Only thing that changes is name of the function and to speak.
n These two inputs are passed in as CSV file like column one is NAME and Column two is MESSAGE(to speak)
---------------------------------- output.js -------------------------------
module.exports = {
john: john,
tony: tony,
laura: laura
};
function john(assistant) {
let toSpeak = "Here something goes for John";
assistant.setContext("navigator", 1, {"mynavigator": OPTIONS});
return askAssistant(toSpeak, assistant);
function tony(assistant) {
let toSpeak = "whatever is message for tony";
assistant.setContext("navigator", 1, {"mynavigator": OPTIONS});
return askAssistant(toSpeak, assistant);
function laura(assistant) {
let toSpeak = "I think you got where I am going with";
assistant.setContext("navigator", 1, {"mynavigator": OPTIONS});
return askAssistant(toSpeak, assistant)
-----------------------------output.js------------------------------------------
I am not asking anyone to code this for me rather suggest me a tool that would help me achieve this task. I will sincerely appreciate your kind feedback

I can think of two approaches you could take.
The first approach is to use print statements in your favourite programming language to print out the required text. And, of course, wrap some of those print statements in for-loops to iterate over the list of (name, message) tuples. This approach is straightforward and does not require use of any third-party code-generation tools.
The second approach is to use a template engine, such as Apache Velocity (for Java).

Related

Is there a binding file for EcmaScript/Javascript

for a project, I want to write a program to generate "valid" and random javascript code, by "valid" I mean don't generate javascript code which are going to throw an error. For example if my program call the javascript function every():
var arr1 = [ 1, 2, "foo"]
/* this is the case I want to avoid */
arr1.every([3,4,5])
/* this is one of the case that I want */
arr1.every(function() { /* do stuff here */ })
(I know I can't produce 100% valid javascript code, but my goal is to produce the most valid javascript code possible)
To do this, I need to know for every function what arguments are excepted by the function the, what the function return.
I've tried to scrape msdn-javascript-reference to have a list of all buits-in objects and functions and have an idea about what they except and then build a db. But this is hard because msdn isn't well structured for scrapping because and provide information in an unstructured format. So is there a site, or db where I can have all javascript bindings ?
Thank you !

How do create a related search terms?

I'm working on a school project in code.org for my CS class. I'm trying to build an app that is about the bird.(We are learning about list/arrays, loops, and traversals)
In the project I'm trying to build a search box where people can type the name of the bird and in the next page will show up the information about the bird. (Those information are from the code.org data library, it has a lot of lists of datasets that you can use to build your app)
The code looks like this:
// code.org is using ES5
var birdSearch = getText('searchInput');
for(var i = 0; i < birdNameList.length; i++) {
if (birdSearch === birdNameList[i]) {
setText('birdNameOutput', birdNameList[i]);
setText('birdDietOuput', birdDietList[i]);
setText('birdImageOutput', birdImageList[i]);
}
But I'm afraid that no one will know those bird's name because you have to search the exactly same name in the list, then my app will be useless. So I am thinking to build a thing that will show the most related name depends on the user input.
It's like if you put 'Am' in the search box and it will show 'American Goldfinch', 'American Purple Gallinule' ... under the search box.
For example:
search box: Am______
do you mean: American Goldfinch
American Purple Gallinule
...
great first question and welcome! There are a lot of things here that you may wish to consider, such as the event that triggers the search - does the search happen when you click a button or when text is typed? If it is the latter then you may also want to think about debouncing the event, which is essentially adding a slight delay to calling the method to prevent it firing too many times and causing performance related issues, though I realise that this is probably a bit further on in your learning, but definitely something worth investigating as your learning progresses.
However, to get to the point of your question, I think it is probably best to look at a filter method to filter the array of results, with something like this:
const birdSearch = getText('searchInput');
const searchList = birdNameList.filter(function(bird) {
return bird.includes('birdSearch');
});
setText('suggestionBox', 'Do you mean: ' + searchList.join(', ') + '?');
Hopefully that should give you a starter for ten!

How to prevent script injection attacks

Intro
This topic has been the bane of many questions and answers on StackOverflow -and in many other tech-forums; however, most of them are specific to exact conditions and even worse: "over-all" security in script-injection prevention via dev-tools-console, or dev-tools-elements or even address-bar is said to be "impossible" to protect. This question is to address these issues and serve as current and historical reference as technology improves -or new/better methods are discovered to address browser security issues -specifically related to script-injection attacks.
Concerns
There are many ways to either extract -or manipulate information "on the fly"; specifically, it's very easy to intercept information gathered from input -to be transmitted to the server - regardless of SSL/TLS.
intercept example
Have a look here
Regardless of how "crude" it is, one can easily use the principle to fabricate a template to just copy+paste into an eval() in the browser console to do all kinds of nasty things such as:
console.log() intercepted information in transit via XHR
manipulate POST-data, changing user-references such as UUIDs
feed the target-server alternative GET (& post) request information to either relay (or gain) info by inspecting the JS-code, cookies and headers
This kind of attack "seems" trivial to the untrained eye, but when highly dynamic interfaces are in concern, then this quickly becomes a nightmare -waiting to be exploited.
We all know "you can't trust the front-end" and the server should be responsible for security; however - what about the privacy/security of our beloved visitors? Many people create "some quick app" in JavaScript and either do not know (or care) about the back-end security.
Securing the front-end as well as the back-end would prove formidable against an average attacker, and also lighten the server-load (in many cases).
Efforts
Both Google and Facebook have implemented some ways of mitigating these issues, and they work; so it is NOT "impossible", however, they are very specific to their respective platforms and to implement requires the use of entire frameworks plus a lot of work -only to cover the basics.
Regardless of how "ugly" some of these protection mechanisms may appear; the goal is to help (mitigate/prevent) security issues to some degree, making it difficult for an attacker. As everybody knows by now: "you cannot keep a hacker out, you can only discourage their efforts".
Tools & Requirements
The goal is to have a simple set of tools (functions):
these MUST be in plain (vanilla) javascript
together they should NOT exceed a few lines of code (at most 200)
they have to be immutable, preventing "re-capture" by an attacker
these MUST NOT clash with any (popular) JS frameworks, such as React, Angular, etc
does NOT have to be "pretty", but readable at least, "one-liners" welcome
cross-browser compatible, at least to a good percentile
Runtime Reflection / Introspection
This is a way to address some of these concerns, and I don't claim it's "the best" way (at all), it's an attempt.
If one could intercept some "exploitable" functions and methods and see if "the call" (per call) was made from the server that spawned it, or not, then this could prove useful as then we can see if the call came "from thin air" (dev-tools).
If this approach is to be taken, then first we need a function that grabs the call-stack and discard that which is not FUBU (for us by us). If the result of this function is empty, hazaa! - we did not make the call and we can proceed accordingly.
a word or two
In order to make this as short & simple as possible, the following code examples follow DRYKIS principles, which are:
don't repeat yourself, keep it simple
"less code" welcomes the adept
"too much code & comments" scare away everybody
if you can read code - go ahead and make it pretty
With that said, pardon my "short-hand", explanation will follow
first we need some constants and our stack-getter
const MAIN = window;
const VOID = (function(){}()); // paranoid
const HOST = `https://${location.host}`; // if not `https` then ... ?
const stak = function(x,a, e,s,r,h,o)
{
a=(a||''); e=(new Error('.')); s=e.stack.split('\n'); s.shift(); r=[]; h=HOSTPURL; o=['_fake_']; s.forEach((i)=>
{
if(i.indexOf(h)<0){return}; let p,c,f,l,q; q=1; p=i.trim().split(h); c=p[0].split('#').join('').split('at ').join('').trim();
c=c.split(' ')[0];if(!c){c='anon'}; o.forEach((y)=>{if(((c.indexOf(y)==0)||(c.indexOf('.'+y)>0))&&(a.indexOf(y)<0)){q=0}}); if(!q){return};
p=p[1].split(' '); f=p[0]; if(f.indexOf(':')>0){p=f.split(':'); f=p[0]}else{p=p.pop().split(':')}; if(f=='/'){return};
l=p[1]; r[r.length]=([c,f,l]).join(' ');
});
if(!isNaN(x*1)){return r[x]}; return r;
};
After cringing, bare in mind this was written "on the fly" as "proof of concept", yet tested and it works. Edit as you whish.
stak() - short explanation
the only 2 relevant arguments are the 1st 2, the rest is because .. laziness (short answer)
both arguments are optional
if the 1st arg x is a number then e.g. stack(0) returns the 1st item in the log, or undefined
if the 2nd arg a is either a string -or an array then e.g. stack(undefined, "anonymous") allows "anonymous" even though it was "omitted" in o
the rest of the code just parses the stack quickly, this should work in both webkit & gecko -based browsers (chrome & firefox)
the result is an array of strings, each string is a log-entry separated by a single space as function file line
if the domain-name is not found in a log-entry (part of filename before parsing) then it won't be in the result
by default it ignores filename / (exactly) so if you test this code, putting in a separate .js file will yield better results than in index.html (typically) -or whichever web-root mechanism is used
don't worry about _fake_ for now, it's in the jack function below
now we need some tools
bore() - get/set/rip some value of an object by string reference
const bore = function(o,k,v)
{
if(((typeof k)!='string')||(k.trim().length<1)){return}; // invalid
if(v===VOID){return (new Function("a",`return a.${k}`))(o)}; // get
if(v===null){(new Function("a",`delete a.${k}`))(o); return true}; // rip
(new Function("a","z",`a.${k}=z`))(o,v); return true; // set
};
bake() - shorthand to harden existing object properties (or define new ones)
const bake = function(o,k,v)
{
if(!o||!o.hasOwnProperty){return}; if(v==VOID){v=o[k]};
let c={enumerable:false,configurable:false,writable:false,value:v};
let r=true; try{Object.defineProperty(o,k,c);}catch(e){r=false};
return r;
};
bake & bore - rundown
These are failry self-explanatory, so, some quick examples should suffice
using bore to get a property: console.log(bore(window,"XMLHttpRequest.prototype.open"))
using bore to set a property: bore(window,"XMLHttpRequest.prototype.open",function(){return "foo"})
using bore to rip (destroy carelessly): bore(window,"XMLHttpRequest.prototype.open",null)
using bake to harden an existing property: bake(XMLHttpRequest.prototype,'open')
using bake to define a new (hard) property: bake(XMLHttpRequest.prototype,'bark',function(){return "woof!"})
intercepting functions and constructions
Now we can use all the above to our advantage as we devise a simple yet effective interceptor, by no means "perfect", but it should suffice; explanation follows:
const jack = function(k,v)
{
if(((typeof k)!='string')||!k.trim()){return}; // invalid reference
if(!!v&&((typeof v)!='function')){return}; // invalid callback func
if(!v){return this[k]}; // return existing definition, or undefined
if(k in this){this[k].list[(this[k].list.length)]=v; return}; //add
let h,n; h=k.split('.'); n=h.pop(); h=h.join('.'); // name & holder
this[k]={func:bore(MAIN,k),list:[v]}; // define new callback object
bore(MAIN,k,null); let f={[`_fake_${k}`]:function()
{
let r,j,a,z,q; j='_fake_'; r=stak(0,j); r=(r||'').split(' ')[0];
if(!r.startsWith(j)&&(r.indexOf(`.${j}`)<0)){fail(`:(`);return};
r=jack((r.split(j).pop())); a=([].slice.call(arguments));
for(let p in r.list)
{
if(!r.list.hasOwnProperty(p)||q){continue}; let i,x;
i=r.list[p].toString(); x=(new Function("y",`return {[y]:${i}}[y];`))(j);
q=x.apply(r,a); if(q==VOID){return}; if(!Array.isArray(q)){q=[q]};
z=r.func.apply(this,q);
};
return z;
}}[`_fake_${k}`];
bake(f,'name',`_fake_${k}`); bake((h?bore(MAIN,h):MAIN),n,f);
try{bore(MAIN,k).prototype=Object.create(this[k].func.prototype)}
catch(e){};
}.bind({});
jack() - explanation
it takes 2 arguments, the first as string (used to bore), the second is used as interceptor (function)
the first few comments explain a bit .. the "add" line simply adds another interceptor to the same reference
jack deposes an existing function, stows it away, then use "interceptor-functions" to replay arguments
the interceptors can either return undefined or a value, if no value is returned from any, the original function is not called
the first value returned by an interceptor is used as argument(s) to call the original and return is result to the caller/invoker
that fail(":(") is intentional; an error will be thrown if you don't have that function - only if the jack() failed.
Examples
Let's prevent eval from being used in the console -or address-bar
jack("eval",function(a){if(stak(0)){return a}; alert("having fun?")});
extensibility
If you want a DRY-er way to interface with jack, the following is tested and works well:
const hijack = function(l,f)
{
if(Array.isArray(l)){l.forEach((i)=>{jack(i,f)});return};
};
Now you can intercept in bulk, like this:
hijack(['eval','XMLHttpRequest.prototype.open'],function()
{if(stak(0)){return ([].slice.call(arguments))}; alert("gotcha!")});
A clever attacker may then use the Elements (dev-tool) to modify an attribute of some element, giving it some onclick event, then our interceptor won't catch that; however, we can use a mutation-observer and with that spy on "attribute changes". Upon attribute-change (or new-node) we can check if changes were made FUBU (or not) with our stak() check:
const watchDog=(new MutationObserver(function(l)
{
if(!stak(0)){alert("you again! :D");return};
}));
watchDog.observe(document.documentElement,{childList:true,subtree:true,attributes:true});
Conclusion
These were but a few ways of dealing with a bad problem; though I hope someone finds this useful, and please feel free to edit this answer, or post more (or alternative/better) ways of improving front-end security.

How does SpeechSynthesis return a chosen list of languages?

Good Morning everybody,
I am still working on a questionnaire for illiterate people. For that I am using a Text to Speech application (thanks to #JO3-W3B-D3V)
The Problem is that the questionnaire will be developped in several languages, which means, that the text to speech application has to support several languages as well.
SpeechSynthesis.getVoices()
If I understood it correctly, the function above returns a list of all objects representing all the available voices on the current device. Now to my questions:
Is there a way to return a selection of these languages? For example, the listshould not return all 15 languages which are available on the device, but only 4 chosen ones?
Is there a way to add more languages to the device? I am using Chrome. If I understood it correctly Chromes gets the languages from Microsoft and Google. Therefore Chrome should display new language-option if I add a new language to my operation system (Windows 10). Is that assupmtion correct? I am asking because I did that already and nothing changed, so I might be missing something.
Hope my questions make sense :)
Have a great day!
Explained
Okay, so I'll answer this in two parts, considering the fact that you've kinda asked two questions, both are relatively simple & straightforward thankfully.
Question One
You've asked how to get _ chosen languages that you'd like to support, well that's simple, it's as easy as manipulating an array, within my example I've used the reduce function, fairly straightforward stuff.
P.S. For the sake of some form of consistence, I've written this snippet in a very similar fashion to the one that I wrote in the other question that you asked regarding speechSynthesis.
Assumptions
As stated within the code comments, I've written this snippet in such a way that there's no duplicated entries, i.e. within the snippet below, you will end up with a list that only contains one entity that supports the English language. In other words, you won't have both en-GB & en-US, of course you can change this, I just assumed that you'd want this type of feature, of course this is down to you & your requirements entirely.
// IIFE for the sake of it.
(function() {
"use strict";
// This is a simple list of languages that you wish to support.
var supportedLanguages = ['en', 'de', 'es', 'fr'];
var languages = [];
// This is essentially similar to jQuery's $.ready.
var ready = function(callback) {
var d = document,
s = d.readyState;
// DOMContentLoaded was fired
if (s == "complete" || s == "loaded" || s == "interactive") {
callback();
} else {
if (d.addEventListener) {
d.addEventListener("DOMContentLoaded", callback, false);
} else {
d.attachEvent("onDOMContentLoaded", callback);
}
}
};
// This is just a simple function to process whether or not you'd like to
// push a voice onto the array or not.
var shouldPush = function(array, object) {
var language = object.lang || '';
var snipped = language.substring(0, 2);
// Generate a list of all of the known languages.
var languageList = array.map(function(object) {
return object.lang;
});
// Create a list of short hand language names.
var snippedList = languageList.map(function(language) {
return language.substring(0, 2);
});
// Save having a bloated if statement, personally I find this
// more readable.
//
// Only push relevant ones, saves having any duplicated entities, i.e.
// this will not allow for both en-US & en-GB to be among the list,
// this can be altered, this is merely based on an assumption that you
// wouldn't want both en-US & en-GB, etc.
var isToPush = !snippedList.includes(snipped) &&
!languageList.includes(language) &&
supportedLanguages.includes(snipped);
// If true, push to array.
if (isToPush) {
array.push(object);
}
// Then of course return the array object.
return array;
};
// This is essentially the list of voices that you've picked to support.
var getSelectedLanguages = function() {
languages = speechSynthesis.getVoices().reduce(shouldPush, []);
};
// A starting point for this snippet.
var start = function() {
speechSynthesis.onvoiceschanged = function() {
getSelectedLanguages();
console.log(languages);
};
};
// Run the code when ready.
ready(start);
})();
Question Two
I'm not entirely sure if there's a "clean & easy" way to do this, having conducted my own research on the matter I've found that it looks like this would require some form of tinkering. One of the better sources of information that I've found is this question.
Having further looked into this question, it looks like Artyom also suggests that there's no simple way to achieve this, it looks like you can only add a language by installing the language into the operating system, so I'm lead to believe.
Conclusion
One possible idea is that you could, and I emphasise the word could possibly do this via implementing an API of your own, however I can't imagine this would be a solid or reliable implementation, as my conclusion is based on research suggests in order for an additional language to be included, the user is somewhat responsible for that, as it looks like it needs the user to have _ language installed on their OS in order for speechSynthesis to make use of _ language.
I actually find it a little odd that it appears that there's little/no formal documentation on this subject, rather I've just found mostly informal documentation, suggestions and assumptions. This could however be down to my lack of investigation, bear in mind that I've spent ~15 minutes at most looking into this issue.
Sources
A link to flaviocopes.com regarding speechSynthesis.
A link to Artyom.js, a library for speech related APIs.
A link to a previous stack overflow question similar to the second part of this question.
A link to a medium article.
MDN documentation.
A treehouse blog post.
While I may not have the answer that you desire for your second question, I hope that this entire answer has helped in some form or another! :)

Getting an enum from backend and use it as a string in javascript

Today I had a rather heathed discussion with a java backend developer. I do the frontend side with jsangular. His rest service sends me an object that includes an enum. I get this as a string and need to show it in an angular grid.
The enums are very self explainable.
Examples what I get:
Person = {gender: "MAN", position: "IS_EMPLOYED"}
In the view I have to show the following:
man is employed
So i solved it in a simple and generic way:
Person.gender.toLowerCase () + ' ' + Person.position.toLowerCase ().replace ('_', ' ')
He found this terrible programming and demanded that I would make a mapper with if else or switch
So: If(Person.gender==="MAN") return "man"
Else if....
The label name is always the same as the enum name (only lower case and space instead of underscore)
He went on a rampage that it was bad coding and basically terrible and a sin against god...
So my question is this bad/good practice (so a b/w story) or rather acceptable and defendable in some cases?
Typed on my phone so I couldn't put the code examples in the right tags..
There are a few ways to look at this:
Mapping is more robust:
He is right in saying that there should be a complete mapping function. This allows you to handle errors (i.e. if the response you get for position is "banana", you should probably not just throw that out there). This is especially important in backend development when you are probably working with a strict schema.
Scale Matters:
There is nothing technically wrong with your approach. If there are a small number of entries or if the user base or application scope is small, it may not matter much. It doesn't really conform to best practices, but it works, and if that is all that matters, it might be enough. Although you should always strive for best practices, you need to keep the big picture in mind.
Efficiency:
One approach may be more efficient than the other. The difference may be negligible. In web dev, speed is a priority, and if both approaches get the same result but one is much faster, choose that one.
It'd probably be a better idea to make a client-enum map - then just send back the actual value. So you could have:
var personTypes: {
"1": "Is Employed",
..
}
Then simply send 1 back as the enum and use the lookup object:
console.log("Person status: " + personTypes[Person.position]);
Which also makes it easier to display a list of types - pick a new one, and simply send the enum back:
<select ng-model="personTypeEnum" ng-options="enum as type for (enum, type) in personTypes"></select>
Check in your console with printing object.
example if object is person then if you are rendering this object as json, gender(enum) would be as
{"success":true,"person":[{"class":"person","id":26,"comment":null,"gender":{"enumType":"com.project.Person$Gender","name":"MEN"},
so u can print person.gender.name, which will give MEN

Categories

Resources