Friday, December 19, 2014

Node.JS Error "Cannot find module '...'"

Setting up NodeJS is generally a smooth process. There is one thing need to be taken care of manually: set up environment variable NODE_PATH. This variable must point to the npm global installation location, otherwise you NodeJS application may have problem starting with error message like this:
Error: Cannot find module 'XXX'

In Windows, the easiest way is to go Computer > Properties > Advanced System Settings > Environment Variables > User Variables > New

After the configuration, need to exit the current command line and start a new one in order to see the environment variable in effect.

Wednesday, November 19, 2014

IIS Error: Cannot write configuration file

Symptom

When trying to change IIS configuration, got this error message:
Filename:
    \\?\C:\Windows\System32\inetsrv\config\applicationHost.config
    Error: Cannot write configuration file

Error Message

Diagnosis

Turns out root cause of the problem is a full C: drive.

Windows Explorer

Solution

Luckily, this is a virtual machine with some spare disk capacity. So it's just a matter of allocating more resource, then extend C: drive.


Wednesday, November 05, 2014

Flex TextArea problem in DataGrid

Problem

Flex 4 TextArea does not take multi-line entry when used as editor in DataGrid.

Solution

Add editorUsesEnterKey="true" attribute to the column with TextArea editor.


P.S.

The solution is straightforward. But the route to finding this solution kind of proves open source or at least show your customer the source code is very important.

I first suspect the enter key is intercepted by DataGrid, but it appears that keydown event is intercepted by DataGrid before the TextArea. Some Googling with various keyword combination did not turn up anything interesting.

Not sure where to start, I added a itemEditEnd event handler to the DataGrid, and set a breakpoint there. After walking through the stack, I saw the following code segment, and thus the solution above pops out. Now I can simply go to documentation of editorUsedEnterKey and make sure this is what I want.

(Code of interest from DataGrid.as)
    /**
     *  @private
     */
    private function editorKeyDownHandler(event:KeyboardEvent):void
    {
        // ESC just kills the editor, no new data
        if (event.keyCode == Keyboard.ESCAPE)
        {
            endEdit(DataGridEventReason.CANCELLED);
        }
        else if (event.ctrlKey && event.charCode == 46)
        {   // Check for Ctrl-.
            endEdit(DataGridEventReason.CANCELLED);
        }
        else if (event.charCode == Keyboard.ENTER && event.keyCode != 229)
        {
            // multiline editors can take the enter key.
            if (!_editedItemPosition)
                return;

            if (columns[_editedItemPosition.columnIndex].editorUsesEnterKey)
                return;

            // Enter edits the item, moves down a row
            // The 229 keyCode is for IME compatability. When entering an IME expression,
            // the enter key is down, but the keyCode is 229 instead of the enter key code.
            // Thanks to Yukari for this little trick...
            if (endEdit(DataGridEventReason.NEW_ROW) && !dontEdit)
            {
                findNextEnterItemRenderer(event);
                if (focusManager)
                    focusManager.defaultButtonEnabled = false;
            }
        }
    }

Thursday, August 21, 2014

Ubuntu LTS 12 on VMWare Player Showing Multiple Columns of Identical Screens

Symptoms

After updating to Kernel 3.2.0.67 and reboot, my screen is showing three columns of duplicated desktop. 

Environment: 

  • VMWare Player 6.0.3
  • Ubuntu: 12.04 LTS, Kernel 3.2.0.67 (post upgrade version, I'm not sure what was the version before my upgrade)
  • The VM image was created way back in a very old VMWare Player, started from Ubuntu 10. It has been kept up-to-date by applying Ubuntu patches and eventually to 12.04 LTS. Turn out this probably was the root cause of all the troubles

Solution

After some Google search and reading up on posts, I was eventually lead to the following thread:
Guest display split into identical panes
Flip to page 2, on post 17 from thellstrom, there is the solution that worked for me. I used solution 1b mentioned in the post, and after reboot, everything is back to normal.

Cause

So, based on the article, root cause of the problem is due to VM created on old version of player with virtualHW version 7. I updated the config file from version 7 to 9, and everything appears to be working now.

Thursday, August 14, 2014

Wednesday, August 13, 2014

Lua in Visual Studio 2013


Build Lua for Windows using Visual Studio 2013 is a very straightforward task.

Project to build lua.exe:
  1. Create Project > Visual C++ > Empty Project
  2. Add Existing Item ...
    • Select all files under src except luac.c
  3. Project Property > All Configurations > Configuration Properties > C/C++ > Preprocessor > Preprocess Definitions, add: _CRT_SECURE_NO_WARNINGS

That is it.

To build luac.exe, simply repeat above steps. When selecting files, select all files, except lua.c.

Friday, August 08, 2014

JSmol Widget for ExtJS 5

Live Demo of JSmol Widget for ExtJS 5
Screenshot of the Demo Page Running in Google Chrome

Background

Jmol

Jmol is an open-source viewer for three-dimensional chemical structures, with features for chemicals, crystals, materials and biomolecules. Features include reading a variety of file types and output from quantum chemistry programs, and animation of multi-frame files and computed normal modes from quantum programs.

JSmol

JSmol is a JavaScript framework that allows web developers to create pages that utilize either Java or HTML5 (no Java), at will. This enables Jmol to display interactive 3D molecular structures on devices that do not have Java installed, or for which Java is not available (such as smart phones and some tablet computers, e.g. iPad) or has not been installed because of concerns for Java being a security threat.

I have used Jmol for a few years now. But, over the past few years, due to concerns of security threat? Running Java applet in a browse is getting harder and harder. Shelling out money to buy certificate for open source software is, well, at most a hard sell.

So, JSmol to the rescue, pure JavaScript HTML5 application, works on IE, Firefox, Chrome, and even iPad. What is the catch? At least it does not live well with ExtJS on the same web page. You will get weired error messages like 'Uncaught TypeError: Cannot read property '***' of null'. My guess is JSmol has changed prototype of some basic types.

Problem

  • Jmol:   can no longer be used in any major browser without compiling with a trusted certificate
  • JSmol: not compatible with ExtJS, and I suspect may have problem with a lot of other libraries as well

Solution

iframe! It gives the web page the needed firewall between ExtJS page and JSmol page.

I have implemented a basic ExtJS 5 Widget that will inject an iframe, then inject JSmol code to render molecule models.
Demo page source code:
Widget Source Code:

This widget takes JmolConfig object, and will pass it along to the JSmol app in the iframe. For details of the parameters, please refer to: Jmol JavaScript Object/Info.

One more thing, the component has a "safe" option. Because the code to inject JSmol to iframe does not work in Firefox and IE 9. If "safe" is true, it will simply set iframe src to a pre-existing page that host JSmol library. I used this page: A bare bone JSmol Demo Page. Problem with my page is that it is static and does not honor the JSmolConfig passed to the widget. Now it is up to you to pass along the JSmolConfig to a dynamic page.

Just for fun, below is a screenshot of Jmol's official demo from one of my computers.

Github: mirror master -> gh-pages


  1. Navigate to the project page
  2. To the left of branch dropdown, click "Compare, review, create a pull request";
  3. Select: Base: gh-pages, Compare: master
  4. Create pull request
  5. Merge pull request
  6. Confirm merge
Done!

Tuesday, August 05, 2014

Windows 3 Nostalgia

Must see for Windows 3 nostalgia. :) http://www.michaelv.org/, everything done using HTML, and actually works.
Calculator

Dos Prompt, try DIR

Media Player

Minesweeper, it works too!!

Notepad, you can even save the text file

Finally, where it all begins, Program Manager

Monday, August 04, 2014

Namespace in ActionScript (how to get ObjectProxy's object)

Example, to get raw object of ObjectProxy, your code has to be something like this:

var op:ObjectProxy = new ObjectProxy({a: 1});
var obj:Object = op.object_proxy::object; //get what you wanted 
obj = op.object; //you get undefined here

Actionscript's documentation did not show any namespace qualification. Flash builder's debugger will show correct content in "op.object". All these leads to confusion. So, hopefully this little note can save somebody an hour of head scratching.

Tuesday, July 01, 2014

Why Sweatband/Helmet/Cap Could Make Better Wearable Than Watch

Compare to a wrist watch, sweatband/helmet/cap wearable provides the following advantages:

  • Speaker
    • Close to ears, can have wired earphone
    • Or simple a speaker close to head bone might work well
  • Microphone: being at fixed distance from your mouth, and close to head bones, the microphone can be designed to be efficient. Compare to watch, you no longer need to raise your hand to talk
  • Camera: head is always more stable, and provides good stabilization for human vision, thus better for camera too.
    • More stable than watch
    • Better view of the world around you (imaging playing tennis, rowing boat or skiing, a camera on the watch won't deliver much quality)
    • Panorama with multiple cameras is possible
  • Ambient Light Sensor: wrist watch are frequently under sleeves or in pockets, it just cannot give an accurate reading of the user's actual ambient light. However a sensor on the head enjoys all the day light a user might enjoy
  • Physiology Measurements: there are way more vital signs that can be measured near brain than on the wrist
    • Skin resistance change: monitor sweating
    • EEG (brain waves): measure brain activities, alertness, attention and focus, etc. Might be good for mediation, board games, ...
    • EOG/ENG: Eye movements tracking, can be used to diagnose dizziness, balance problem, ...
    • Hear rate: pulse can be taken from temple
    • Blood pressure: can be taken from temple
    • Blood oxygen level: can be taken from temple
    • Body temperature
  • Movements tracking: because they are on head rather than wrist, they subject to less swing or up and downs, can track human movements more accurately
    • Orientation tracking is more accurate (in terms of North/South/East/West and also Up/Down. You will have more confidence in telling the user is in upside down position.)
    • Acceleration is more accurate. For example, when basketball player go for a slam dunk, their hand movements will be very complicated, and you won't know how much power they put in the jump, or how high their jump is, but a sweatband (LeBron James?) can give very accurate reading;


Disadvantages?

  • The electronics on sweatband has to be feather light
  • Not suitable for work place in the current western culture (while wearing watch at work is widely acceptable, wearing a band or cap at work is still a bold fashion statement)
  • The user cannot see it (Oh, maybe something like Google Glass, but retractable will solve this problem)
Potential Applications
  • Yoga training
  • Meditation training
  • Sleep disorder assistance: it knows your toss and turns, you blood oxygen level change, heart rate change and eye movement changes (rapid eye movement sleeping), ...
  • Patient assistance: dizziness, epilepsy early warning
  • Sports life panorama video 
  • Athlete training assistance: tracking and feedback on gait, gravity center change, speed, acceleration, fatigue, ...
  • Car Black Box: it is no longer necessary, just make sure your cap power is on
  • ...
(Published on July 1, 2014, All Rights Reserved)

Wednesday, June 04, 2014

Apple's Swift language - first impressions

Just a quick first impression.
Pros:

  • Lots of language sugar, should reduce some boilerplate code
Cons:
  • Deviation from JSON format see to be arbitrary decision. Why not 

let people = {"Anna": 67, "Beto": 8, "Jack": 33, "Sam": 25}

  • Plenty other seemingly arbitrary decisions that are not intuitive. E.g. 
    • Use let to make a constant and var to make variable (why not const vs var?)
    • func getName() -> String, why not func getName() : String?
  • The biggest problem probably is still same as Object-C, you learn it to only write client program for one vendor's hardware. Will Swift ever be open and adopted on server side or other vendors?

Wednesday, May 28, 2014

Coldfusion 9 CFQuery problem

Environment:

  • Coldfusion 9.1.1.274733
  • MS SQL Server 10.50.1600


Symptoms
Here is a really weired and rare problem. With a CFQuery tag like this:
<cfquery datasource="..." dbtype="ODBC" name="local.qry" result="local.result"></cfquery>
I'm getting error message like these:
Element QRY is undefined in LOCAL
Or
Variable QRY is undefined.

After some digging, I found the cause, and subsequently an interesting solution.

Cause
I ran the query in SQL Server Management Studio. The "Results" grid is showing no rows. The real interesting thing is that the "Messages" panel actually has a warning which took me a while to notice:
Warning: Null value is eliminated by an aggregate or other SET operation.


So if all the following conditions are met, my query variable will became undefined, instead of an cfquery object with no row.
  • Result is empty
  • A warning is shown when run the query in SQL Management Studio
Solution
In the SQL query add this line on top to suppress warning:
SET ANSI_WARNINGS OFF;
(I found this solution here: https://forums.adobe.com/thread/577811?start=0&tstart=0)

Thursday, May 01, 2014

Github Public Repository Created to Illustrate Selenium WebDriver + ExtJS + JUnit

I posted a series about ExtJS testing using Selenium WebDriver and JUnit. They turned out to be pretty popular. Some reader want to see more implementation details. I committed a Github public repository with complete implementation of the core concepts described in my post. Here is the link:
Github Public RepoSJTXE(Selenium Javascript Testing eXtension for ExtJS)


By the way, you might also consider testing using Jamine and PhantomJS. They are better for blazing fast unit testing. Not quite fit for GUI testing though.

Friday, March 07, 2014

Mutli-line String Literal in Java

Eclipse Preferences: Java > Editor > Typing, check "Escape text when pasting into a string literal". Once turned on, it automatically add "\r\n" when I am pasting multi-line string into a string literal. Very nice.

Wednesday, March 05, 2014

Windows PowerShell Script to Delete Old Files

Just starting to dab into PowerShell script after it has been in the wild for 8 years. Turns out to be surprisingly good. First you have a nice editor (PowerShell ISE), second is the vast amount of cmdlets that make coding go fast.

Here is a script to delete old files that are 30 days or older. It used to take at least 40 lines of VBS to achieve.

Before you get too excited, a few things to be aware of:
  • Availability of PowerShell: WindowsXP may not have it, and Windows 7 may only have it up to version 2. So, if you found some exciting cmdlets, chances are they are not available on your OS by default
  • Executing a PowerShell file takes extra effort. It's forbidden by default. So you have to do either of the following:
    • Open PowerShell, and execute this command: 
         Set-ExecutionPolicy RemoteSigned
    • Or, when running a file use this command line (notice full path to the ps1 file has to be provided here): 
         PowerShell.exe -ExecutionPolicy ByPass c:\scripts\myScript.ps1


Tuesday, February 11, 2014

Read MS Access File into CFQuery

Here is code snippet that will read arbitrary Microsoft Access file, and return the result in CFQuery. No Coldfusion data source is required.

Environment:
- Coldfusion 9, 64-bit

Notice, in the snippet, there is a dump of all DB drivers loaded by Coldfusion. So, if you ever need access to other dynamic data connection, just swap out the connection string in the sample.

Friday, February 07, 2014

TaskKill vs. PSKill

I've been using PSKill for at least 7 years now. Just today, I found out TASKKILL is actually better than PSKILL in all fronts. I should finally stop using PSKILL. My finding is that TASKKILL in Windows 7 has all the features that PSKILL provides, plus the following advantages:

  • No download needed
  • No user agreement needed for the first time user (which is a big plus for server side automated execution)
  • Can kill *ALL* processes with the image name (compare to PSKILL only kill one of them. So with PSKILL, I will need to repeatedly invoke it until all the processes are gone. This is no fun when you are trying to run in automatically on a server.)
  • Richer command line options

Thursday, January 16, 2014

ExtJS Grid Cell Rendered with Mixed Image and Text

Rendering

To render mixed image and text in ExtJS grid, I found the following two approaches

  • Implement custom renderer, return a value like this 
      <img src="..."/>you text content
  • Use CSS to add background image to the cell (see Reference)
Problem: misaligned columns in the first approach
However, when I examine a grid with "locked" columns, I starting to see problem in the first implementation. Often times, the locked columns and floating columns are misaligned. Turns out image tag in the cell will cause grid to adjust row hight. However, ExtJS does not adjust fixed columns and floating columns together. So, if there is image in fixed column only, it will frequently make it taller than the floating columns, thus causing misalignment. To solve this problem, I added the following style to the image tag:

   margin-top: -4px;
   margin-bottom: -4px;

Event Handling

The image in the cell is usually an active component. In order to intercept the click event, I found two good approaches, again.
  • In JS code, hookup event handlers to the image component, and fire event from there. Refer to implementation of ActionColumn (ExtJS source grid\column\Action.js)
  • Change the selType of grid to 'cellmodel', and add select event listener




Reference

Displaying an Image Inside an Ext JS GridPanel Cell http://miamicoder.com/2009/displaying-an-image-inside-an-ext-js-gridpanel-cell-part-2/

Friday, January 10, 2014

New Years Resolution: do not update to .NET 4.5.1

Ok, just kidding. Should not be a new year's resolution. But serious, it was causing me nightmares over the holiday season. All of a sudden, several clients starting to have problem using an ActiveX control in IE (to be precise, ChartFx 6/7 ActiveX controls). After some really boring days researching, installing/uninstalling/reinstalling and testing, I finally found out .NET 4.5.1 was causing the problem.

I have no idea why it's a problem, but I know if I uninstall 4.5.1 and rollback to 4.5.0, then all the problems are gone. So, it's official, .NET 4.5.1 update is banned.

Problem with Intranet Web Site Content?

Did your Intranet web application users complain about your website not working at all? Here is one of the root cause: IE running in emulation mode of older browsers. It will mess up some JavaScript functions that relies on relative new features.

Symptoms


  • Your clients use IE
  • Only have problem when using Intranet like URLs
  • JavaScript console shows weried error messages like: 'JSON' is undefined
  • IE 11 Emulation (or IE10 document mode) is showing IE 7 or older or even quirk mode (however, if you see Edge then the solution I provide below won't help you)
  • DOM view showing your nice HTML5 doc type being commented out
IE commented out doctype

Root Cause

IE option "Display intranet sites in Compatibility View" forced it to emulate behavior of older browser for Intranet web applications, regardless what is in the web page's header.

Solution

This worked for me: change IIS HTTP header
  • In IIS admin, go to the folder or file that you want to enable IE "Edge" mode
  • Click "HTTP Response Headers"
  • Click "Add", and type Name: X-UA-Compatible, Value: IE=edge

HTTP Header that will fix the problem