Use of console.time - google-closure-compiler

I'm creating an application with Google Closure Library and its Compiler. To debug values I use console.log(). Compiling this will throw the following exception JSC_UNDEFINED_VARIABLE. variable console is undeclared at .... To solve this error, I just had to use window.console.log() instead.
I also want to measure the time that a function takes. Firebug has two nice functions console.time(name) and console.timeEnd(name) to do that very easily. Unfortunately the Closure Compiler does not support these functions throwing the following warning JSC_INEXISTENT_PROPERTY. Property time never defined on Window.prototype.console at .... Unfortunately you cannot solve this warning with prepending window.
I also had a look at the library, but goog.debug.Console has not the function that I need.
Another solution I have used before was something like the following
var start = new Date();
// do something
var end = new Date();
// do some calculation to get the ms for both start and end
var startMS = ....;
var endMS = .....;
// get the difference and print it
var difference = (endMS - startMS) / 1000;
console.log('Time taken for something: ' + difference);
This is a little bit too much code, if you use it very often, and the version with the two functions would be great:
window.console.time("timeTaken");
// do something
window.console.timeEnd("timeTaken");
This prints out the MS between start and end. But as mentioned above, this doesn't work with the closure compiler. Does anyone have a solution for this, how I can use these two functions window.console.time() and window.console.timeEnd()? Or maybe another solution that goog.closure provides, but I haven't found?

You just need to added them to the externs you are using.

If you don't want to/can't use externs, you can easily reference "undeclared" objects with the string-based properties:
window['console']['log']('Hello Console!');
window['console']['time']('timeTaken');
...
But you have to be careful, because the second line might throw an error if the time property does not exist or it's not a function.

Related

Doing CallOrder of Fake on itself with argument validation

How do i do a call order verification of a fake with argument validation in sinon.js?
It is the same fake which is called multiple times with different arguments...
something like below
let someFake = sinon.fake();
someFake(1);
someFake(2);
someFake(3);
sinon.assert.callOrder(someFake.calledWith(1), someFake.calledWith(2),
someFake.calledWith(3));
You are essentially using the wrong API for the job, so it's no wonder you are not getting the expected results :) If you look at the docs for callOrder you will see that the signature is using spy1, spy2, .., which indicates that it is meant to be used by more than one spy. A fake is implementation wise also a Spy, so all bits of the Spy API also applies to a Fake. From the docs:
The created fake Function, with or without behavior has the same API as a sinon.spy
A sidenode, that is a bit confusing, is that the docs often use the term "fake" to apply to any fake object or function, not functions created using the sinon.fake API specifically, although, that should not be an issue in this particular case.
With regards to your original question, the Spy API has got you covered since Sinon 1.0 here. You use getCall(n) to return the nth call. There are lots of interactive examples in the docs for this, but essentially you just do this:
// dumbed down version of https://runkit.com/fatso83/stackoverflow-66192966
const fake = sinon.fake();
fake(1);
fake(20);
fake(300);
sinon.assert.calledThrice(fake);
assertEquals(1, fake.getCall(0).args[0])
assertEquals(20, fake.secondCall.args[0])
assertEquals(300, fake.lastCall.args[0])
function assertEquals(arg1,arg2){
if(arg1 !== arg2) {
throw new Error(`Expected ${arg1} to equal ${arg2}`);
}
console.log(`${arg1} equal ${arg2}: OK`)
}
<script src="https://cdn.jsdelivr.net/npm/sinon#latest/pkg/sinon.js"></script>

SysCTypes errors when using NetCDF.chpl?

I have a simple Chapel program to test the NetCDF module:
use NetCDF;
use NetCDF.C_NetCDF;
var f: int = ncopen("ppt2020_08_20.nc", NC_WRITE);
var status: int = nc_close(f);
and when I compile with:
chpl -I/usr/include -L/usr/lib/x86_64-linux-gnu -lnetcdf hello.chpl
it produces a list of errors about SysCTypes:
$CHPL_HOME/modules/packages/NetCDF.chpl:57: error: 'c_int' undeclared (first use this function)
$CHPL_HOME/modules/packages/NetCDF.chpl:77: error: 'c_char' undeclared (first use this function)
...
Would anyone see what my error is? I tried adding use SysCTypes; to my program, but that didn't seem to have an effect.
Sorry for the delayed response and for this bad behavior. This is a bug that's crept into the NetCDF module which seems not to have been caught by Chapel's nightly testing. To work around it, edit $CHPL_HOME/modules/packages/NetCDF.chpl, adding the line:
public use SysCTypes, SysBasic;
within the declaration of the C_NetCDF module (around line 50 in my copy of the sources). If you would consider filing this bug as an issue on the Chapel GitHub issue tracker, that would be great as well, though we'll try to get this fixed in the next release in any case.
With that change, your program almost compiles for me, except that nc_close() takes a c_int argument rather than a Chapel int. You could either lean on Chapel's type inference to cause this to happen:
var f = ncopen("ppt2020_08_20.nc", NC_WRITE);
or explicitly declare f to be of type c_int:
var f: c_int = ncopen("ppt2020_08_20.nc", NC_WRITE);
And then as one final note, I believe you should be able to drop the -lnetcdf from your chpl command-line as using the NetCDF module should cause this requirement to automatically be added.
Thanks for bringing this bug to our attention!

Qt error is printed on the console; how to see where it originates from?

I'm getting this on the console in a QML app:
QFont::setPointSizeF: Point size <= 0 (0.000000), must be greater than 0
The app is not crashing so I can't use the debugger to get a backtrace for the exception. How do I see where the error originates from?
If you know the function the warning occurs in (in this case, QFont::setPointSizeF()), you can put a breakpoint there. Following the stack trace will lead you to the code that calls that function.
If the warning doesn't include the name of the function and you have the source code available, use git grep with part of the warning to get an idea of where it comes from. This approach can be a bit of trial and error, as the code may span more than one line, etc, and so you might have to try different parts of the string.
If the warning doesn't include the name of the function, you don't have the source code available and/or you don't like the previous approach, use the QT_MESSAGE_PATTERN environment variable:
QT_MESSAGE_PATTERN="%{function}: %{message}"
For the full list of variables at your disposal, see the qSetMessagePattern() docs:
%{appname} - QCoreApplication::applicationName()
%{category} - Logging category
%{file} - Path to source file
%{function} - Function
%{line} - Line in source file
%{message} - The actual message
%{pid} - QCoreApplication::applicationPid()
%{threadid} - The system-wide ID of current thread (if it can be obtained)
%{qthreadptr} - A pointer to the current QThread (result of QThread::currentThread())
%{type} - "debug", "warning", "critical" or "fatal"
%{time process} - time of the message, in seconds since the process started (the token "process" is literal)
%{time boot} - the time of the message, in seconds since the system boot if that can be determined (the token "boot" is literal). If the time since boot could not be obtained, the output is indeterminate (see QElapsedTimer::msecsSinceReference()).
%{time [format]} - system time when the message occurred, formatted by passing the format to QDateTime::toString(). If the format is not specified, the format of Qt::ISODate is used.
%{backtrace [depth=N] [separator="..."]} - A backtrace with the number of frames specified by the optional depth parameter (defaults to 5), and separated by the optional separator parameter (defaults to "|"). This expansion is available only on some platforms (currently only platfoms using glibc). Names are only known for exported functions. If you want to see the name of every function in your application, use QMAKE_LFLAGS += -rdynamic. When reading backtraces, take into account that frames might be missing due to inlining or tail call optimization.
On an unrelated note, the %{time [format]} placeholder is quite useful to quickly "profile" code by qDebug()ing before and after it.
I think you can use qInstallMessageHandler (Qt5) or qInstallMsgHandler (Qt4) to specify a callback which will intercept all qDebug() / qInfo() / etc. messages (example code is in the link). Then you can just add a breakpoint in this callback function and get a nice callstack.
Aside from the obvious, searching your code for calls to setPointSize[F], you can try the following depending on your environment (which you didn't disclose):
If you have the debugging symbols of the Qt libs installed and are using a decent debugger, you can set a conditional breakpoint on the first line in QFont::setPointSizeF() with the condition set to pointSize <= 0. Even if conditional breakpoints don't work you should still be able to set one and step through every call until you've found the culprit.
On Linux there's the tool ltrace which displays all calls of a binary into shared libs, and I suppose there's something similar in the M$ VS toolbox. You can grep the output for calls to setPointSize directly, but of course this won't work for calls within the lib itself (which I guess could be the case when it handles the QML internally).

Compiler confused about mock object

I'm using OCMock to aid in Test Driven Development I am doing for an iPad application using Xcode. I have test code like this:
id mock = [OCMockObject mockForProtocol:#protocol(SomeProtocol)];
Vector direction = { 1.0f, 2.0f, 3.0f };
[[mock expect] setDirection:direction];
When I try to compile, I'm getting warnings and errors like this:
warning: multiple methods named 'setDirection:' found
error: sending'Vector' to parameter of incompatible type
'UISwipeGestureRecognizerDirection' (aka 'enum
UISwipeGestureRecognizerDirection')
Obviously the compiler is not able to determine what type of object the mock is supposed to be. I'm not sure how to specify that it should deal with the setDirection method from the SomeProtocol protocol instead of a setDirection method from another class.
What can be done to make a test case like this build successfully?
Qualifying the mock with a cast will eliminate the ambiguity:
[(id<SomeProtocol>)[mock expect] setDirection:direction];
For the OCMock 3 modern syntax:
id protocolMock = OCMProtocolMock(#protocol(MYProtocol));
OCMExpect([(id <MYProtocol>)protocolMock ambiguousMethod]);

How to make a non-blocking pipe from the command-line in Solaris?

I'm trying to write a lua script that reads input from other processes and analyzes it. For this purpose I'm using io.popen and it works as expected in Windows, but on Unix(Solaris) reading from io.popen blocks, so the script just waits there until something comes along instead of returning immediately...
As far as I know I can't change the functionality of io.popen from within the script, and if at all possible I would rather not have to change the C code, because then the script will then need to be bound with the patched binary.
Does that leave me with any command-line solutions?
Ok got no answers so far, but for posterity if someone needs a similar solution I did the following more or less
function my_popen(name,cmd)
local process = {}
process.__proc = assert(io.popen(cmd..">"..name..".tmp", 'r'))
process.__file = assert(io.open(name..".tmp", 'r'))
process.lines = function(self)
return self.__file:lines()
end
process.close = function(self)
self.__proc:close()
self.__file:close()
end
return process
end
proc = my_popen("somename","some command")
while true
--do stuf
for line in proc:lines() do
print(line)
end
--do stuf
end
Your problems seems to be related to buffering. For some reason the pipe is waiting for some data to be read before it allows the opened program to write more to it, and it seems to be less than a line. What you can do is use io.popen(cmd):read"*a" to read everything. This should avoid the buffering problem. Then you can split the returned string in lines with for line in string.gmatch("[^\n]+") do someting_with(line) end.
Your solution consist in dumping the output of the process to a file, and reading that file. You can replace your use or io.popen with io.execute, and discard the return value (just check it's 0).

Resources