How to Listen Keys in JScript.Net - jscript.net

What I wish is to catch the keypress using JScript .NET, and compile the code using that jsc.exe.
So, is there any equivalent of "addEventListener("keyDown", keyCheck)" from FLASH actionscript. Or GetAsyncKeyState() from C++.
And what library do I have to use?
Please be kind enough to share a small, simple example.

Here's a simple solution if you're writing a console app.
import System;
Console.Write("Press the M key... ");
var key:ConsoleKeyInfo;
while (1) {
while (!Console.KeyAvailable) {
System.Threading.Thread.Sleep(1);
}
key = Console.ReadKey(1);
if (key.Key == ConsoleKey.M) break;
}
Console.Write("Accepted.");
Read more about ConsoleKeyInfo.
If you need GetAsyncKeyState(), it is possible to access the method in JScript.NET. A couple days ago I came across a JScript.NET function that exposes Win32 API methods via P/Invoke. Here it is, slightly modified for simpler syntax (allowing pass-through of arguments from API function definitions).
import System;
import System.Reflection;
import System.Reflection.Emit;
// Invoke a Win32 P/Invoke call.
// credit: http://cx20.main.jp/blog/hello/2013/03/07/hello-win32-api-jscript-net-world/
function InvokeWin32(dllName:String, returnType:Type, methodName:String, params:Object[]) {
var paramTypes:Type[] = new Type[params.length];
for (var i:int in params) {
paramTypes[i] = params[i].GetType();
}
// Begin to build the dynamic assembly
var domain = AppDomain.CurrentDomain;
var name = new System.Reflection.AssemblyName('PInvokeAssembly');
var assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
var module = assembly.DefineDynamicModule('PInvokeModule');
var type = module.DefineType('PInvokeType',TypeAttributes.Public
+ TypeAttributes.BeforeFieldInit);
// Define the actual P/Invoke method
var method = type.DefineMethod(methodName, MethodAttributes.Public
+ MethodAttributes.HideBySig + MethodAttributes.Static +
MethodAttributes.PinvokeImpl, returnType, paramTypes);
// Apply the P/Invoke constructor
var ctor = System.Runtime.InteropServices.DllImportAttribute.GetConstructor(
[System.String]
);
var attr = new System.Reflection.Emit.CustomAttributeBuilder(ctor, [dllName]);
method.SetCustomAttribute(attr);
// Create the temporary type, and invoke the method.
var realType = type.CreateType();
return realType.InvokeMember(methodName, BindingFlags.Public + BindingFlags.Static
+ BindingFlags.InvokeMethod, null, null, params);
}
With this function, you can expose Win32 DLL methods with the following syntax. (See? Told you it was simpler.)
// ShowWindowAsync(hWnd:IntPtr, nCmdShow:int);
function ShowWindowAsync(... args:Object[]):boolean {
return InvokeWin32("user32.dll", System.Boolean, "ShowWindowAsync", args);
}
// GetWindowLong(hWnd:IntPtr, nIndex:int);
function GetWindowLong(... args:Object[]):int {
return InvokeWin32("user32.dll", System.Int32, "GetWindowLong", args);
}
// FindWindowEx(parentHandle:IntPtr, childAfter:IntPtr,
// lclassName:IntPtr, windowTitle:String);
function FindWindowEx(... args:Object[]):IntPtr {
return InvokeWin32("user32.dll", System.IntPtr, "FindWindowEx", args);
}
And I've never used GetAsyncKeyState(); but since it's a user32.dll method, I'm guessing it'll work the same way. (Edit: It does.)
// GetAsyncKeyState(vKey:int);
function GetAsyncKeyState(... args:Object[]):short {
return InvokeWin32("user32.dll", System.Int16, "GetAsyncKeyState", args);
}
Then for a trivial example:
import System; // for Console methods
import System.Windows.Forms; // for Keys object constants
Console.Write("Press the M key... ");
// while the M key is not being pressed, sleep
while (!GetAsyncKeyState(Keys.M)) {
System.Threading.Thread.Sleep(1);
}
// flush input buffer
while (Console.KeyAvailable) Console.ReadKey(1);
Console.WriteLine("Accepted.");

Related

How to see the value of a top level empty getter without running the code in Swift?

public var O_RDONLY: Int32 { get }
When I'm looking at stuff inside Darwin.sys.* or Darwin.POSIX.* for example, a lot of these constants are defined as getters. But how does one see the actual value without evaluating the code?
public var O_RDONLY: Int32 { get }
is what the Swift importer generates from the macro definition
#define O_RDONLY 0x0000 /* open for reading only */
in the <sys/fcntl.h> include file. Although this is a fixed value, known at compile time, the Swift importer does not show the value in the generated Swift interface.
Note also that a macro definition in a C header file may depend on other macros, and on other “variables” such as compiler flags, the processor architecture, etc.
I am not aware of a way to navigate to that C definition from a Swift file, or any other way to show the defined value in a pure Swift project. As a workaround, one can
add a C file to the project,
use the macro in some C function, and
“jump to definition” from there.
I ended up with the following solution:
const fs = require('fs');
const { exec } = require("child_process");
const getterRegEx = /^(.*)public var (.+): (.+) { get }(.*)$/;
const code = String(fs.readFileSync('./generatedSwift.swift'));
const lines = code.split('\n').map((line, i) => {
const arr = getterRegEx.exec(line);
if (arr) {
const [all, prefix, constant, type, suffix] = arr;
return `print("let ${constant}: ${type} = ", ${constant}, separator: "")`;
}
return `print("""\n${line}\n""")`;
});
lines.unshift('import Foundation');
fs.writeFileSync('./regeneratedSwift.swift', lines.join('\n'));
exec('swift ./regeneratedSwift.swift', (err, stdout, stderr) => {
if (err) {
console.error(`exec error: ${err}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
Copy definitions generated by the XCode and save into a file named generatedSwift.swift the run node index.js in the same folder.
The output will contain the Swift code where all
public var Constant: Type { get }
are replaced with
let Constant = Value
and all other lines will remain the same.

How to globally add a custom locator to Protractor?

I wrote a custom locator for Protractor that finds anchor elements by their ui-sref value. In my specs I just used by.addLocator to add the custom locator, but I figured this might be a cool thing to publish and have other people use it.
The goal is to add this custom locator to the global Protractor object so it can be used in any of your specs.
My initial approach was to add this functionality in the onPrepare block of the Protractor config. Something like the pseudocode below:
onPrepare: function () {
require('ui-sref-locator')(protractor); // The protractor object is available here.
}
That require statement would just execute this function:
function (ptorInstance) {
ptorInstance.by.addLocator('uiSref', function (toState, opt_parentElement) {
var using = opt_parentElement || document;
var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
var result = undefined;
if (possibleAnchors.length === 0) {
result = null;
} else if (possibleAnchors.length === 1) {
result = possibleAnchors[0];
} else {
result = possibleAnchors;
}
return result;
});
};
The problem is that by is not defined on the protractor object available in the onPrepare block. This means that I cannot use the .addLocator method.
Try the following:
function () {
by.addLocator('uiSref', function (toState, opt_parentElement) {
...
By should be in the global scope.
The protractor object passed to the onPrepare block has a By property. That By property has an inherited enumerable property named addLocator. My understanding of JavaScript is pretty shallow so it really threw me off that when I console.log'ed the protractor.By it returned {}, but if I did for (var propName in protractor.By) it would show me all the "hidden" properties. I'm still struggling to understand that bit.
Working code:
onPrepare: function () {
require('ui-sref-locator')(protractor); // The protractor object is available here.
}
The require would execute the function below:
function (ptor) {
ptor.By.addLocator('linkUiSref', function (toState, opt_parentElement) {
var using = opt_parentElement || document;
var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
var result = undefined;
if (possibleAnchors.length === 0) {
result = null;
} else if (possibleAnchors.length === 1) {
result = possibleAnchors[0];
} else {
result = possibleAnchors;
}
return result;
});
};

"this" in a prototype method does not always refer to the prototype of the object itself?

Most of the times all I have to do with JavaScript is just add some dynamics to simple HTML. Recently, however, after discovering CoffeeScript, I got interested in *Object Oriented JavaScript". Here is some code in CoffeeScript.
class MyClass
constructor: (title, purpose)->
#title = typeof title is undefined ? "My Class" : title
#purpose = typeof purpose is undefined ? "None" : purpose
#myMethod()
myMethod: ->
_getTitle = #getTitle
_getPurpose = #getPurpose
$(window).click ->
_getTitle()
_getPurpose()
return
return
getTitle: ->
_title = #title
window.console.log "Title of the class this object belongs to is: #{_title}"
return
getPurpose: ->
_purpose = #purpose
window.console.log "Purpose of creating this class is: #{_purpose}"
return
title = ""
purpose = ""
myObject = new MyClass("Testbed", "to test Object Oriented JavaScript")
For those who prefer JavaScript, here is the compiled (?) JavaScript.
var MyClass, myObject;
MyClass = (function() {
var purpose, title;
function MyClass(title, purpose) {
var _ref, _ref1;
this.title = (_ref = typeof title === void 0) != null ? _ref : {
"My Class": title
};
this.purpose = (_ref1 = typeof purpose === void 0) != null ? _ref1 : {
"None": purpose
};
this.myMethod();
}
MyClass.prototype.myMethod = function() {
var _getPurpose, _getTitle;
_getTitle = this.getTitle;
_getPurpose = this.getPurpose;
$(window).click(function() {
_getTitle();
_getPurpose();
});
};
MyClass.prototype.getTitle = function() {
var _title;
_title = this.title;
window.console.log("Title of the class this object belongs to is: " + _title);
};
MyClass.prototype.getPurpose = function() {
var _purpose;
_purpose = this.purpose;
window.console.log("Purpose of creating this class is: " + _purpose);
};
title = "";
purpose = "";
return MyClass;
})();
myObject = new MyClass("Testbed", "to test Object Oriented JavaScript");
Sorry about the long code. I had to try to keep it interesting. The thing is, this code outputs:
Title of the class this object belongs to is: undefined
Purpose of creating this class is: undefined
whereas I was expecting it to output:
Title of the class this object belongs to is: Testbed
Purpose of creating this class is: to test Object Oriented JavaScript
And I could've sworn this was how it worked when I last tinkered with it (around six months ago). I learnt that in a method that is part of the prototype of an object, this refers to the prototype itself. And this.something would actually point to object.something. Whereas in this example, inside myObject.myMethod(), this behaves as it should and this.getTitle() refers to myObject.getTitle(). Inside myObject.getTitle(), however, this refers to window. Why?
Is it because getTitle() was called inside a $(window).click() handler? But why would that change the context? getTitle() is still a property of myObject.
Also, you see what I am trying to accomplish here. How could I accomplish that?
There are several problems.
1) You never return anything from .getPurpose or .getTitle
2) You should create a reference to this in myMethod. i.e. var me = this and then inside the event listener call me.getTitle() and me.getPurpose(). This is needed because inside the event listener (window onclick), this refers to the window and not the object.
3) It looks like your ternary expressions are always evaluating to false. You need to rethink them.
P.S. I looked at the straight JS version

Calling class function within a constructor isn't being recognised

Answer:
It turns out I had neglected to use the new keyword when creating the class instance. The code in the question itself is fine.
Question:
I have a fairly simple class where the constructor calls another method on the class (editor_for_node). The call happens inside a jQuery each() loop, but I've also tried moving it outside.
define ['jquery'], ($) ->
class Editor
constructor: (#node, #data, #template) ->
#node.widgets().each (i, elem) =>
data = if #data then #data[i] else null
node = $(elem)
#editor_for_node node, data
editor_for_node: (node, data) ->
console.log 'hello!'
return {
'Editor': Editor,
}
When the line #editor_for_node node, data gets called, I get an error (in Firebug) saying this.editor_for_node is not a function.
I really can't see why this isn't working properly, the only possible source of weirdness that I can see is my use of require.js's define function at the start.
Edit: Generated output
(function() {
define(['jquery'], function($) {
var Editor;
Editor = (function() {
Editor.name = 'Editor';
function Editor(node, data, template) {
var _this = this;
this.node = node;
this.data = data;
this.template = template;
this.node.widgets().each(function(i, elem) {
data = _this.data ? _this.data[i] : null;
node = $(elem);
return _this.editor_for_node(node, data);
});
}
Editor.prototype.editor_for_node = function(node, data) {
return console.log('hello!');
};
return Editor;
})();
return {
'Editor': Editor
};
});
}).call(this);
First: Which version of CoffeeScript are you using? The fat arrow has been a source of bugs in certain previous releases.
If you're using the latest (1.3.1), then I'm going to go ahead and say that this is an indentation issue. When I copy and paste your code, it works fine. Are you mixing tabs and spaces? Verify that the compiled output contains the line
Editor.prototype.editor_for_node = ...
Update: See the comments on this answer. Turns out the problem was that the new keyword wasn't being used when invoking the constructor.

IronRuby performance issue while using Variables

Here is code of very simple expression evaluator using IronRuby
public class BasicRubyExpressionEvaluator
{
ScriptEngine engine;
ScriptScope scope;
public Exception LastException
{
get; set;
}
private static readonly Dictionary<string, ScriptSource> parserCache = new Dictionary<string, ScriptSource>();
public BasicRubyExpressionEvaluator()
{
engine = Ruby.CreateEngine();
scope = engine.CreateScope();
}
public object Evaluate(string expression, DataRow context)
{
ScriptSource source;
parserCache.TryGetValue(expression, out source);
if (source == null)
{
source = engine.CreateScriptSourceFromString(expression, SourceCodeKind.SingleStatement);
parserCache.Add(expression, source);
}
var result = source.Execute(scope);
return result;
}
public void SetVariable(string variableName, object value)
{
scope.SetVariable(variableName, value);
}
}
and here is problem.
var evaluator = new BasicRubyExpressionEvaluator();
evaluator.SetVariable("a", 10);
evaluator.SetVariable("b", 1 );
evaluator.Evaluate("a+b+2", null);
vs
var evaluator = new BasicRubyExpressionEvaluator();
evaluator.Evaluate("10+1+2", null);
First Is 25 times slower than second. Any suggestions? String.Replace is not a solution for me.
I do not think the performance you are seeing is due to variable setting; the first execution of IronRuby in a program is always going to be slower than the second, regardless of what you're doing, since most of the compiler isn't loaded in until code is actually run (for startup performance reasons). Please try that example again, maybe running each version of your code in a loop, and you'll see the performance is roughly equivalent; the variable-version does have some overhead of method-dispatch to get the variables, but that should be negligible if you run it enough.
Also, in your hosting code, how come you are holding onto ScriptScopes in a dictionary? I would hold onto CompiledCode (result of engine.CreateScriptSourceFromString(...).Compile()) instead -- as that will help a lot more in repeat runs.
you can of course first build the string something like
evaluator.Evaluate(string.format("a={0}; b={1}; a + b + 2", 10, 1))
Or you can make it a method
if instead of your script you return a method then you should be able to use it like a regular C# Func object.
var script = #"
def self.addition(a, b)
a + b + 2
end
"
engine.ExecuteScript(script);
var = func = scope.GetVariable<Func<object,object,object>>("addition");
func(10,1)
This is probably not a working snippet but it shows the general idea.