Scanf and Printf in JS - javascript

I'm studying to a Championship in Brazil. But I need help because I will do this in JS, but the problem is, they ask to answer with Scanf and Printf. How can I do this in JS? Thanks.
Ps: Its not document.write or something, need Scanf and Printf, if it dont exist in JS, please, let me some link and i will study how works syntax of Scanf and Printf.

First of all...
JavaScript is a general purpose programming language which can be executed in multiple different environments. Each one has it's own way of processing input and output operations.
As you didn't specify which competition is that, I'll assume you're talking about OBI, promoted by UNICAMP (the only one I know that accepts JS solutions and require standard I/O on them). If this is the case, a development environment called Saci is used to run and evaluate JavaScript submissions.
If you want to learn more about writing JS code for the Saci environment, you can search here.
Now, answering your question, two methods are used for standard I/O operations in this environment: scanf and printf. They work like C input/output methods with a few differences.
Writing with printf()
This method work exactly like its C equivalent. You'll see it in the following format:
printf(format, ...);
The first parameter is a string containing the text to be written to stdout. It can optionally contain embedded format tags that will be replaced by the values you specify in the next parameters.
Here's an example:
let x = 34;
printf("%d is an integer\n", x);
Reading with scanf()
This method will work like its C equivalent with two differences: each variable must be specified in quotes, and it'll only work with global variables. You'll find this method in the following format:
scanf(format, ...);
The first parameter is a string containing the format tags used to assign each value to its corresponding variable, which should be informed in the next parameters.
Here's an example:
let x, y;
scanf("%d%d", "x", "y");

console.log stuff supports the format specifiers a little, but not that useful.
If you are finding one for web browsers, you can use sprintf.js and prompt().
If you are finding one for Node.js:
Is there a sprintf equivalent for node.js
C scanf equivalent in nodejs

Related

Is it possible to convert string from AppleScript to array in typescript?

I execute AppleScript in typescript which returns string(but it actually contains array). Is it possible to convert this string to array of items in typescript?
This is the code that returns string of array from AppleScript
import { Detail } from "#raycast/api";
import {runAppleScript} from 'run-applescript';
import { spawnSync } from "child_process";
async function spacesArray(): Promise<String> {
const out = spawnSync("defaults read com.pradeepb28.spacesfor myNewArray", { shell: true });
return String(out.output[1]).trim();
}
result(in string format):
(
abc,
abcd,
abcdef
)
return String(out.output[1]).trim().split(",");
The run-applescript module calls out to the command-line osascript, which, as you’ve discovered, is lousy for passing complex arguments and results.
If you wish to parse its output directly, you will need to add the -ss flag to the osascript command. That will format the output as AppleScript literals, which can be reliably parsed. The default output format is “human-readable”, which is ambiguous at best.
Another option would be for your AppleScript code to format the list of strings as a JSON string and return that, which you can trivially parse using JSON.parse(). AppleScript doesn’t have built-in JSON support, but you can call Cocoa’s NSJSONSerialization class via the AppleScript-ObjC bridge. It’s a bit more work, but it’s robust. This would be your safest route as it avoids introducing any additional dependencies and JSON data is well understood.
A third option would be to avoid osascript and call NSAppleScript from JS via the objc bridge. The objc bridge itself is a bit rough and unfinished (I have a PR on that but its author is busy with other work), but may be adequate for your needs. Unpacking the NSAppleEventDescriptors returned by -[NSAppleScript executeAndReturnError:] is tedious, but reliable.
The last option is to ditch AppleScript entirely and use nodeautomation to do your application scripting directly from JS. However, while nodeautomation works well (I use it in my own work) I provide no warranty or free support.
Sorry there’s no really good solutions, but given how thoroughly Apple wrecked Mac Automation it’s a miracle it’s still alive at all.
I was able to solve this by manual parser:
removed spaces, removed \n and removed open brackets

Encoding/Decoding Javascript in Nashorn

I use the technique described here:
http://scriptasylum.com/tutorials/encode-decode.html
In a nutshell, one has a javascript file that looks like this, where the actual javascript is encoded:
document.write( unescape( 'escaped string' ) ); dF('encoded javascript');
I now want to run that same .js module under Nashorn, but Nashorn does not have a document object. Therefore, I can not do document.write().
Note: It is well known that this technique is easily bypassed and people modest technical ability can still look at the actual code. My use case does not require strong security so that is not a concern. That said, Please consider answers on why one should not do this as off topic. Thanks.
Basically, that code breaks down into two parts:
Un-obfuscate the string via unescape.
Write the string out via document.write.
It sounds like you want to use the string directly for some reason.
You have at least two options:
You can provide a document object to the scripting engine with a write method that accepts a string. Then you can do with it what you like. (Or substitute document.write before evaluating the string with any function you want called.)
Remove the document.write( and the corresponding ) at the end and have the engine evaluate the string and hand it to you directly as the result of ScriptEngine#eval.
Either way, you'll end up with a string that you can then do something with.

Go templating engine that also runs in the browser

I'm developing a web application with Go on the server, and the router will use PushState, so the server will also have to be able to render my templates. That means that I'll need a templating engine that works with Go and Javascript. The only one I've come across so far is Mustache, but it doesn't seem to be able to handle lowercase properties of structs, and there also doesn't seem to be a possibility to provide custom names like JSON:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
So, is there a templating engine that is available in both Go and JavaScript, and that can handle lowercase struct properties?
As the comments above state, you can't expect any 3rd party library to be able to read lowercase properties on your struct, but it appears you are trying to use tags to represent alternative representations of your struct (as you can with the encoding/json library).
What you can do is use something like github.com/fatih/structs to convert your structs to maps and then range through to lowercase all of your keys (copying the values and removing the uppercase versions) and pass it into mustache.Render() as your context. If you want to use struct tags like the encoding/json library does, you'd have to use the reflect package and write a struct-to-map function that takes into account the tags on the struct (basic example given in the documentation here). There are some SO answers on how to write a struct-to-map function using reflection, which you can improve upon to add struct tag handling as you need.
To answer your question, I don't think this is something a current templating library does that also works with javascript, but it shouldn't be too hard to get working with mustache given the idea above.

howto get a JSON (or equivalent) representation of a JavaScript *code file* (the code, as a string, in input)?

Everything is in the title! ^^
I know about some SourceCode browsers for js; they usually permit to find some small stuff when the code relatively abides in structure by the current informal js coding norm.
(eg, use of the new operator, functions mainly created through definitions (F foo() {}) rather than through expression statements or literal objects (var foo = F(){}, { foo: F(){} }), etc; norm i precisely happen not to do adhere to).
but, what would truly interest me would be a full parsing of the code, a tool returning, for example, a JSON file containing the whole code, that is, all the statements, function calls, even the parameters of the function calls (usually forgotten in js sourcebrowsers, because those objects are de facto anonymous objects/functions; however they are precisely abundantly used in functional-like programming, and thus get invisible to all source browsers i met)
the purpose of course would be to create from that JSONized code, my own source browser, that would hopefully go farther than the average one, and would meet my needs to browse my code easily, see also easily, which variable is defined where, and some other stuff that might enhance my coding experience.
anyhow; i'm not particularly attached to the JSON format, altho of course since i'd code my source browser in JS, it'd be the immediate easy input, but any other data representation format is OK, what matters is a parser that transforms code into a mouthpiece object¹.
Anything looking and doing sth like that (eg a L/Hinter with a more verbose and informative output, or else) is welcome ;)
thanks in advance :)
¹ "object": an object as JS defines it, ie, an abstract data alike or identical to a dictionary; not an object as class-based OO languages define it (class instances)
I think you are searching for a standard to represent javascript code as an abstract syntax tree (AST). There is a widely used standard for javascript AST and it is called ESTree. There is an active community supporting the standardization project and it is updated for new versions of javascript.
Alternatively, there is also Shift AST that offers a slightly different standard AST, and it has an online real time parsing tool.
Implementations of AST generators usually provide a Parser with a parse() method that take your javascript code as a string parameter value, and they return an abstract syntax tree object as defined by the standard.
For example passing this code:
c = a + b;
Will produce this AST:
type: "Script"
directives:[]
statements:
0:
type: "ExpressionStatement"
expression:
type: "AssignmentExpression"
binding:
type: "BindingIdentifier"
name: "c"
expression:
type: "BinaryExpression"
left:
type: "IdentifierExpression"
name: "a"
operator: "+"
right:
type: "IdentifierExpression"
name: "b"
Finally, there are code generators to perform the reverse procedure: when having an AST and wanting to generate javascript code from that.
An updated and well maintained implementation of an ESTree parser can be found here.

lightweight javascript to javascript parser

How would I go about writing a lightweight javascript to javascript parser. Something simple that can convert some snippets of code.
I would like to basically make the internal scope objects in functions public.
So something like this
var outer = 42;
window.addEventListener('load', function() {
var inner = 42;
function magic() {
var in_magic = inner + outer;
console.log(in_magic);
}
magic();
}, false);
Would compile to
__Scope__.set('outer', 42);
__Scope__.set('console', console);
window.addEventListener('load', constructScopeWrapper(__Scope__, function(__Scope__) {
__Scope__.set('inner', 42);
__Scope__.set('magic',constructScopeWrapper(__Scope__, function _magic(__Scope__) {
__Scope__.set('in_magic', __Scope__.get('inner') + __Scope__.get('outer'));
__Scope__.get('console').log(__Scope__.get('in_magic'));
}));
__Scope__.get('magic')();
}), false);
Demonstation Example
Motivation behind this is to serialize the state of functions and closures and keep them synchronized across different machines (client, server, multiple servers). For this I would need a representation of [[Scope]]
Questions:
Can I do this kind of compiler without writing a full JavaScript -> (slightly different) JavaScript compiler?
How would I go about writing such a compiler?
Can I re-use existing js -> js compilers?
I don't think your task is easy or short given that you want to access and restore all the program state. One of the issues is that you might have to capture the program state at any moment during a computation, right? That means the example as shown isn't quite right; that captures state sort of before execution of that code (except that you've precomputed the sum that initializes magic, and that won't happen before the code runs for the original JavaScript). I assume you might want to capture the state at any instant during execution.
The way you've stated your problem, is you want a JavaScript parser in JavaScript.
I assume you are imagining that your existing JavaScript code J, includes such a JavaScript parser and whatever else is necessary to generate your resulting code G, and that when J starts up it feeds copies of itself to G, manufacturing the serialization code S and somehow loading that up.
(I think G is pretty big and hoary if it can handle all of Javascript)
So your JavaScript image contains J, big G, S and does an expensive operation (feed J to G) when it starts up.
What I think might serve you better is a tool G that processes your original JavaScript code J offline, and generates program state/closure serialization code S (to save and restore that state) that can be added to/replace J for execution. J+S are sent to the client, who never sees G or its execution. This decouples the generation of S from the runtime execution of J, saving on client execution time and space.
In this case, you want a tool that will make generation of such code S easiest. A pure JavaScript parser is a start but isn't likely enough; you'll need symbol table support to know which function code is connected a function call F(...), and which variable definition in which scope corresponds to assignments or accesses to a variable V. You may need to actually modify your original code J to insert points of access where the program state can be captured. You may need flow analysis to find out where some values went. Insisting all of this in JavaScript narrows your range of solutions.
For these tasks, you will likely find a program transformation tool useful. Such tools contain parsers for the langauge of interest, build ASTs representing the program, enable the construction of identifier-to-definition maps ("symbol tables"), can carry out modifications to the ASTs representing insertion of access points, or synthesis of ASTs representing your demonstration example, and then regenerate valid JavaScript code containing the modified J and the additions S.
Of all the program transformation systems that I know about (which includes all the ones at the Wikipedia site), none are implemented in JavaScript.
Our DMS Software Reengineering Toolkit is such a program transformation system offering all the features I just described. (Yes, its big and hoary; it has to be to handle the complexities of real computer languages). It has a JavaScript front end that contains a complete JavaScript parser to ASTs, and the machinery to regenerate JavaScript code from modified or synthesized ASTs. (Also big and hoary; good thing that hoary + hoary is still just hoary). Should it be useful, DMS also provides support for building control and dataflow analysis.
If you want something with a simple interface, you could try node-burrito: https://github.com/substack/node-burrito
It generates an AST using the uglify-js parser and then recursively walks the nodes. All you have to do is give a single callback which tests each node. You can alter the ones you need to change, and it outputs the resulting code.
I'd try to look for an existing parser to modify. Perhaps you could adapt JSLint/JSHint?
There is a problem with the rewriting above, you're not hoisting the initialization of magic to the top of the scope.
There's a number of projects out there that parse JavaScript.
Crock's Pratt parser which works well on JavaScript that fits within "The good parts" and less well on other JS.
The es-lab parser based on ometa which handles the full grammar including a lot of corner cases that Crock's parser misses. It may not perform as well as Crock's.
narcissus parser and evaluator. I don't have much experience with this.
There are also a number of high-quality lexers for JavaScript that let you manipulate JS at the token level. This can be tougher than it sounds though since JavaScript is not lexically regular, and predicting semicolon insertion is difficult without a full parse.
My es5-lexer is a carefully constructed and efficient lexer for EcmaScript 5 that provides the ability to tokenize JavaScript. It is heuristic where JavaScript's grammar is not lexically regular but the heuristic is very good and it provides a means to transform a token stream so that an interpreter is guaranteed to interpret it the way the lexer interpreted the tokens so if you don't trust your input, you can still be sure that the interpretation underlying the security transformations is sound even if not correct according to the spec for some bizarre inputs.
Your problem seams to be in same family of problems as what is solved with the JS Opfuscators and JS Compressors -- they as well as you need to be able to parse and reformat the JS to an equivalent script;
There was a good discussion on obfuscators here and the possible solution to your problem could be to leverage the parse and generator part from one of the FOSS versions.
One callout, your example code does not take into account the scopes of the variables you want to set/get and that will eventually become a problem that you will have to solve.
Addition
Given the scope problem for closure defined functions, you are probably unlikely to be able to solve this problem as a static parsing problem, as the scope variables outside the closure will have to be imported/exported to resolve/save and re-instantiate scope. Hence you may need to dig into the evaluation engine itself, and perhaps get the V8 engine and make a hack to the interpreter itself -- that is assuming that you do not need this to be generic cross all script engines and that you can tie it down to a single implementation which you control.

Categories

Resources