Wednesday, October 3, 2012

Excel: Useful function & tips



1. Links


Excel Trick : What is the use of $ sign ?
http://techathand.net/random-post/excel-trick-what-is-the-use-of-sign/197/

VBA & Excel:
http://www.functionx.com/vbaexcel/index.htm

Excel all functions
http://www.techonthenet.com/excel/formulas/index.php

2. Contents


Monday, September 24, 2012

java: Multi instances of TopComponent



1. Links
DevFaqNonSingletonTopComponents: http://wiki.netbeans.org/DevFaqNonSingletonTopComponents


2. Google note
Keyword should NOT be TopComponents, but TopComponent


3. Detail

DevFaqNonSingletonTopComponents


How can I change my TopComponent to not be a singleton (NB version up to 6.9)?

The "New Window Component" wizard in the NetBeans IDE generates a singleton TopComponent. That's fine for windows that there should only be one of. Particularly if you are creating some kind of editor, you will want to create multiple instances of your TopComponent.

The really easy way

If you have not already used the New Window template to create your TopComponent subclass, don't.
Instead, use New > JPanel Form. Once the new JPanel is created, switch to the Code tab, and replace extends javax.swing.JPanel with extends TopComponent. Then do the following things:
  • Override getPersistenceType().
    • If you do not want your components reopened on restart
      • return PERSISTENCE_NEVER—that is all you need to do to make sure they are not preserved across restarts.
    • If you do want your components reopened on restart, then
      • return PERSISTENCE_ONLY_OPENED from getPersistenceType()
      • Add the following slightly-cryptic annotation to the class: @ConvertAsProperties(dtd = "-//com.yourmodule.yourpackage//YourTopComponent//EN", autostore = false), replacing the package and class name with your own. This identifies a DTD. You do not need to define the DTD. You just need to give it a unique namespace that nothing else is using. Package and class name work well for that.
      • Add two additional methods (you are not overriding anything and they can be package-private, like serialization methods):
        • void writeProperties(Properties p) - here we will call p.put() passing enough information to reconstruct your component on restart. If we are editing a file, we might save the path to the file. If we are viewing a URL, we might save the URL. If we want to be particularly fastidious, we might save the scroll position, or what line the editor caret was on , or anything else useful to restore the state of our component.
        • void readProperties(Properties p) - here we will reading whatever keys we wrote out in writeProperties and (re)initializing the component to its pre-shutdown state. This method will be called on startup to restore our component to its pre-shutdown state as best can be done. If we were, say, editing a file that no longer exists, the appropriate thing to do is throw an exception.

If you already have a generated singleton TopComponent subclass

The good news is that you won't have to write any code -- you'll just have to delete some of the code that was generated for you.
In your TopComponent's .java source file:
  • Delete the static instance variable, which ought to be declared a few lines above the constructor.
  • Make sure your TopComponent class is public
  • Make sure your TopComponent has a no-argument constructor which is public
  • Delete the getDefault() method (typically somewhere around the middle of the file)
  • Delete the findInstance() method (which typically follows the getDefault() method)
  • Update the persistence code which saves your component's state on shutdown and restores it on restart to reopen your component as follows
    • Locate the getPersistenceType method and change its return value to either TopComponent.PERSISTENCE_NEVER or TopComponent.PERSISTENCE_ONLY_OPENED (see below for why).
    • If you have methods called writeReplace()and an inner class called ResolvableHelper (NetBeans 6.8 and earlier):
      • Delete the writeReplace() method (typically towards the end of the file)
      • Delete the ResolvableHelper inner class (typically towards the end of the file)
    • If you do not want persistence across restarts — you are returning PERSISTENCE_NEVER from getPersistenceType()
      • If you have a @ConvertAsProperties annotation and readProperties(Properties) and writeProperties(Properties) methods, delete the annotation and both methods
    • If do want persistence across restarts — you are returning PERSISTENCE_ONLY_OPENED fromgetPersistenceType()
      • If you already have the @ConvertAsProperties annotation and readProperties(Properties) and writeProperties(Properties) methods just leave them there
      • If you do not have the annotation and those methods, implement them as described in the previous section
Next we will need to delete the metadata that registers the component:
  • For version 6.9 of NetBeans:
    • Delete the settings XML file for your component. If your component class is MyWindow then that file will be in the same folder and will be called MyWindowSettings.xml.
    • Delete the wstcrf ("window system TopComponent reference") XML file in that folder. If your component class is MyWindow then that file will be named MyWindowWstcrf.xml
    • Edit your module's [DevFaqModulesLayerFile| layer.xml file] to
      • Remove any references to either of these files (just use Ctrl-F to search for e.g. MyWindowSettings.xml and MyWindowWstcrf.xml). They will be in <file> tags.
      • If you have removed a <file> entry, and it was the only entry in that folder, you can remove the XML for parent folder (and its parent if it is now empty, and so forth)
      • Find where an Action is registered for to open your (formerly) singleton TopComponent
        • NetBeans 6.9 and later:
          • Look for an <file> registered in Actions/Windowin the XML file. It will have an <attr> element that refers to your TopComponent class, e.g. <attr name="component" methodvalue="com.foo.MyWindow.findInstance"/>. Delete the entire <file> entry.
          • Look for <file> entry for a .shadow file in Actions/Menu in the XML, with its originalFile pointing to the file entry you just deleted. Delete the .shadow <file> too.
        • NetBeans 6.8 and earlier:
          • There will be an Action class in your sources which is registered, e.g. MyWindowAction.java. Delete the java source file.
          • Look for an <file> registered in Actions/Windowin the XML file. It will be a <file> whose name is the munged fully-qualified class name of the Action you just deleted, e.g. com-foo-MyWindowAction.instance. Delete the <file> entry for it
          • Look for <file> entry for a .shadow file in Actions/Menu in the XML, with its originalFile pointing to the file entry you just deleted. Delete the .shadow <file> too.

Creating And Opening Your TopComponents

Now that you have deleted the actions for your TopComponent, presumably they will be created some other way (for example, from a file's popup menu). You can create new instances of your TopComponent, open them and give them focus as follows:
TopComponent win = new MyTopComponent();
win.open();
win.requestActive(); 
If you wrote your persistence code correctly, your components will magically reopen on restart with no further work.

What About PERSISTENCE_ALWAYS?

There is one other value you can return from TopComponent.getPersistenceType(). That value is TopComponent.PERSISTENCE_ALWAYS.
While it is legal to return this value from a non-singleton TopComponent, it is almost never what you want to do. What will happen if you do this is:
  • Every instance of your component that is ever created will be persisted on shutdown, forever
    • Even if it is closed
    • Even if nothing can use it, or it represents a file that was deleted, or is in some other way invalid
    • Even if no code will ever be able to find it and open it again
  • One every restart, forever
    • Every instance of your component that has ever existed will be read back from disk
      • Each one will slow down startup a little bit
      • Each one will be wasting disk space
PERSISTENCE_ALWAYS is for singleton components that need to be remembered forever across restarts. Don't use it for non-singletons.

If you do not have any persistence code, but your components are reopening on restart...

You are returning either PERSISTENCE_ONLY_OPENED or PERSISTENCE_ALWAYS from getPersistenceType(). If there is no persistence code, but you are returning one of these values, NetBeans will use plain old Java serialization to store and reload your component.
Either use PERSISTENCE_NEVER or write persistence code as described above. Serialization is slower and more fragile than proper persistence, and is never a good option for production code.

Sunday, September 23, 2012

Noway: Đổi bác sĩ dùng google translate




Các bước để đổi bác sĩ:

1. Vào trang web http://www.helfo.no
- Chọn tab đầu tiên PRIVATPERSON (PRIVATE). Chọn Fastlegeordningen (RGP Scheme) ở phía dưới bên trái màn hình.
- Hoặc có thể google translate với link http://www.helfo.no, rồi chọn RGP Scheme

2. Login và đổi bác sĩ
- Chọn Klikk her for å bytte fastlege (innlogging via MinID) để đổi bác sĩ
- Xuất hiện một trang web bắt log in dùng MinID (từ đây hình như đa số dùng tiếng Anh, sướng)
- Sử dụng số Norwegian ID đã được cung cấp và password đã đăng ký trước đó để log in
- Hệ thống bắt nhập vào password (được gửi đến số mobile phone đã đăng ký) gồm 5 ký tự

3. Đổi bác sĩ
- Chọn Bytt (Replace - thay đổi bác sĩ)
- Một danh sách các bác sĩ hiện ra, lọc các bác sĩ ở khu vực mình sinh sống bằng cách chọn phần Søk etter fastleger.
- Chọn bác sĩ mong muốn còn chỗ trống (phần Ledig - Available) rồi chọn Velg (Select)
- Chọn Bekreft (Confirm) để xác nhận.

Thursday, September 13, 2012

Java: Working with Scenic View


1. Links
http://fxexperience.com/scenic-view/

2. How to work with it

- Start ScenicView.jar (double click)
- Configure by locating necessary .jar files (if necessary paths are not correct and required)
- Add library to your project: Right click your project, select Properties then click Libraries category. At the Compile tab, select Add JAR/Folder
- import com.javafx.experiments.scenicview.ScenicView;
- Add this to your code: ScenicView.show(scene);
- Run your JavaFX project and see

Note: Do not select  Run in Browser option, Select Run Standalone (Project Properties/Run group)

Monday, September 10, 2012

DirectShow: screen capture recorder



1. Link


Screen capture recorder
This program allows one to "record" your desktop, or even stream it, with the help of VLC.

http://sourceforge.net/projects/screencapturer/files/

Friday, August 24, 2012

Windows: Installation



1.


1. WinXP SP3 SATA:
- Info: Microsoft.Windows.XP.Professional.SP3.Integrated.August.2012.SATA.By.Maher.[www.nomaher.com]
- Torrent: http://isohunt.com/torrent_details/407039761/windows+xp+sp3+sata?tab=summary
- Key: MR49R-DRJXX-M6PX2-V96BF-8CKBJ

2. Win7

Monday, August 20, 2012

Video: Subtitle



1. Links

http://www.brighthub.com/computing/windows-platform/articles/41466.aspx


2. Source links

1. Open Subtitles Database - http://www.opensubtitles.org/
2. My Subtitles - http://www.mysubtitles.com/
3. DivX Subtitles - http://www.divxsubtitles.net/
4. Movie Subtitles - http://www.moviesubtitles.org/

Friday, August 17, 2012

Java: Running .jar file from command prompt


1. Links
 http://stackoverflow.com/questions/394616/running-jar-file-in-windows
http://www.wikihow.com/Run-a-.Jar-Java-File

Test.jar

java -jar test.jar



Thursday, August 16, 2012

Windows: Useful tools for debugging


1. List
Dependency Walker: http://www.dependencywalker.com/
Process Explorer: http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx, http://en.wikipedia.org/wiki/Process_Explorer

2. Links


Windows: How to use Dependency Walker



Note
Be careful with 32 or 64 bit version

Links
http://www-archive.mozilla.org/quality/help/dependency-walker.html

How to use Dependency Walker (depends.exe)

  1. Learn about Dependency Walker
    • Mozilla is a modular application composed of functions from many libraries (.DLLs).
    • Dependency Walker is an application that builds a hierarchical tree diagram of other programs and all dependent modules. For each module found, it lists all the functions that are exported by that module, and which of those functions are actually being called by other modules.
    • Logs from Dependency Walker can help people solve a few troubling problems. Often users are missing libraries or have the wrong version, this should be easily interpretable from dependency walker output. In other cases, just seeing where mozilla dies can allow triagers to guess what should happen next which enables them to suggest the likely problem.
    • For more information see the distribution site or read its online help.
  2. Download Dependency Walker (for Windows) from http://dependencywalker.com/
  3. Expand it (using winzip or your favorite zip handling application)
  4. Run depends.exe
  5. Open the application which you need to profile
    • Drag the application into the Depency Walker window
    • Drag the application to the Dependency Walker application
    • Type Ctrl-O [or navigate to File>Open...]
      • Enter the path to the appropriate application (usually) mozilla.exe
      • Browse to the appropriate application
  6. Press F7 [or navigate to Profile>Start Profiling...]
  7. Enter parameters for the application (probably -console, possibly -p profilename, possibly -mail ...)
  8. If this is your first time, and unless otherwise instructed, check all the boxes
  9. Select <OK>
  10. The application should now run as usual. In some instances, mozilla might not come to the front, in which case you should alt-tab to it, or minimize dependency walker, or use the taskbar or ...
  11. When you have quit using the application which dependency walker is profiling [or as otherwise instructed] return to dependency walker.
  12. Save the log
    1. Type Ctrl-S [or navigate to File>Save]
    2. Enter a filename
  13. Return to bugzilla and select "Create a new attachment"
  14. See helping with QA for more information about creating an attachment using bugzilla

Command Line syntax for depends.exe

Some people are afraid of graphical interfaces. If you are one of them, please try this instead:
c:\windows> depends /pa1 /pd"c:\program files\mozilla" /pr"-console" /od"desktop\mozilla.dwi" "c:\program files\mozilla\mozilla.exe"
This version is for those of you who prefer html documentation over .hlp
c:\windows> depends /c /a 1 /f 1 /u 1 /ps 1 /pp 1 /po 1 /ph 1 /pl 1 /pg 1 /pt 1 /pn 1 /pe 1 /pm 1 /pf 1 /pc 1 /pb /pd"c:\program files\mozilla" /pr"-console" /od"desktop\mozilla.dwi" "c:\program files\mozilla\mozilla.exe"
Later options override earlier options so /pa1 /pc0 will run Dependency Walker with all options except for pc (Automatically open and profile child processes).

Tuesday, August 14, 2012

Internet: How to configure Internet Connection Sharing in Windows XP


Link http://support.microsoft.com/kb/306126

How to configure Internet Connection Sharing in Windows XP

Article ID: 306126 - View products that this article applies to.
This article was previously published under Q306126

To continue receiving security updates for Windows, make sure you're running Windows XP with Service Pack 3 (SP3). For more information, refer to this Microsoft web page: Support is ending for some versions of Windows

On This Page

INTRODUCTION

This article describes how to set up and use the Internet Connection Sharing feature in Microsoft Windows XP. With Internet Connection Sharing, you can use networked computers to share a single connection to the Internet.

How to use Internet Connection Sharing

To use Internet Connection Sharing to share your Internet connection, the host computer must have one network adapter that is configured to connect to the internal network, and one network adapter or modem that is configured to connect to the Internet.

On the host computer

On the host computer, follow these steps to share the Internet connection:
  1. Log on to the host computer as Administrator or as Owner.
  2. Click Start, and then click Control Panel.
  3. Click Network and Internet Connections.
  4. Click Network Connections.
  5. Right-click the connection that you use to connect to the Internet. For example, if you connect to the Internet by using a modem, right-click the connection that you want under Dial-up.
  6. Click Properties.
  7. Click the Advanced tab.
  8. Under Internet Connection Sharing, select the Allow other network users to connect through this computer's Internet connection check box.
  9. If you are sharing a dial-up Internet connection, select the Establish a dial-up connection whenever a computer on my network attempts to access the Internet check box if you want to permit your computer to automatically connect to the Internet.
  10. Click OK. You receive the following message:
    When Internet Connection Sharing is enabled, your LAN adapter will be set to use IP
    address 192.168.0.1. Your computer may lose connectivity with other computers on
    your network. If these other computers have static IP addresses, it is a good idea to set them
    to obtain their IP addresses automatically. Are you sure you want to enable Internet
    Connection Sharing?
  11. Click Yes.
The connection to the Internet is shared to other computers on the local area network (LAN). The network adapter that is connected to the LAN is configured with a static IP address of 192.168.0.1 and a subnet mask of 255.255.255.0

To view a video about how to configure the host computer for Internet Connection Sharing, click the Play button (
Play

    button
) on the following Windows Media Player viewer:




Note To view this video, you must use Windows Media Player 7.0 or later.

For additional information about how to obtain Windows Media Player version 7.1, click the following article number to view the article in the Microsoft Knowledge Base:
299321 Description and availability of Windows Media Player 7.1

On the client computer

To connect to the Internet by using the shared connection, you must confirm the LAN adapter IP configuration, and then configure the client computer. To confirm the LAN adapter IP configuration, follow these steps:
  1. Log on to the client computer as Administrator or as Owner.
  2. Click Start, and then click Control Panel.
  3. Click Network and Internet Connections.
  4. Click Network Connections.
  5. Right-click Local Area Connection, and then click Properties.
  6. Click the General tab, click Internet Protocol (TCP/IP) in the This connection uses the following items list, and then click Properties.
  7. In the Internet Protocol (TCP/IP) Properties dialog box, click Obtain an IP address automatically (if it is not already selected), and then click OK.

    Note You can also assign a unique static IP address in the range of 192.168.0.2 to 192.168.0.254. For example, you can assign the following static IP address, subnet mask, and default gateway:
       IP Address      192.168.0.2
       Subnet mask     255.255.255.0
       Default gateway 192.168.0.1
         
  8. In the Local Area Connection Properties dialog box, click OK.
  9. Quit Control Panel.
To view a video about how to confirm the LAN adapter IP configuration, click the Play button (
Play button
) on the following Windows Media Player viewer:




Note To view this video, you must use Windows Media Player 7.0 or later.

For additional information about how to obtain Windows Media Player version 7.1, click the following article number to view the article in the Microsoft Knowledge Base:
299321 Description and availability of Windows Media Player 7.1
To configure the client computer to use the shared Internet connection, follow these steps:
  1. Click Start, and then click Control Panel.
  2. Click Network and Internet Connections.
  3. Click Internet Options.
  4. In the Internet Properties dialog box, click the Connections tab.
  5. Click the Setup button.

    The New Connection Wizard starts.
  6. On the Welcome to the New Connection Wizard page, click Next.
  7. Click Connect to the Internet, and then click Next.
  8. Click Set up my connection manually, and then click Next.
  9. Click Connect using a broadband connection that is always on, and then click Next.
  10. On the Completing the New Connection Wizard page, click Finish.
  11. Quit Control Panel.
When you now start Microsoft Internet Explorer, the client computer will try to connect to the Internet by using the host computer's shared Internet connection.

To view a video of how to configure the client computer to use the shared Internet connection, click the Play button (
Play

    button
) on the following Windows Media Player viewer:




Note To view this video, you must use Windows Media Player 7.0 or later.

For additional information about how to obtain Windows Media Player version 7.1, click the following article number to view the article in the Microsoft Knowledge Base:
299321 Description and availability of Windows Media Player 7.1

Troubleshooting

When you turn on Internet Connection Sharing on the host computer, the host computer's LAN adapter is automatically assigned the IP address of 192.168.0.1. Therefore, one of the following situations may occur:
  • IP address conflict
    Each computer on the LAN must have a unique IP address. If more than one computer has the same IP address, an IP conflict occurs, and one of the network adapters turns off until the conflict is resolved. To resolve this conflict, configure the client computer to automatically obtain an IP address, or assign it a unique IP address.
  • Loss of network connectivity
    If your network is configured with a different IP address range than Internet Connection Sharing uses, you will lose network connectivity with the host computer. To resolve this issue, configure the client computers to automatically obtain an IP address, or assign each client computer a unique IP address in the range of 192.168.0.2 to 192.168.0.254.



REFERENCES

For additional information about Internet Connection Sharing, click the following article numbers to view the articles in the Microsoft Knowledge Base:
234815 Description of Internet Connection Sharing
308021 Resources for troubleshooting Internet Connection Sharing in Windows XP
308006 Troubleshooting Internet Connection Sharing in Windows XP
310563 Description of Internet Connection Sharing in Windows XP

Thursday, July 26, 2012

VC++: Capture camera using DirectShow note (AMCAP)


See my SkyDrive email from Noël Danjou & SkyDrive folder (Works/Sources)

Add below (or similar) to Tools/Options.../Projects and Sosutions/VC++ Directories/

- Win32/Include files:
C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\baseclasses
C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\common
C:\Program Files\Microsoft SDKs\Windows\v7.1\Include

Build this project in both Debug & Release mode (C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\baseclasses\baseclasses.sln) before adding to Win32/Libraty files
- Win32/Libraty files:
C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\baseclasses\Debug

Refer to HowToInstall.txt

Thursday, July 19, 2012

Java: VLCJ full screen playback


1. Links
http://forum.videolan.org/viewtopic.php?f=32&t=85597




2. Code

import uk.co.caprica.vlcj.player.embedded.DefaultFullScreenStrategy;
...

    public VlcjMediaHandler(JPanel panel) {
        params = new VlcParamsBuilder();
        statusProperty = new SimpleObjectProperty<PlayState>(PlayState.STOPPED);
    JFrame f = new JFrame();
    f.setContentPane(panel);
//    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(800, 600);
        factory = new MediaPlayerFactory("--no-video-title-show");
//        mediaPlayer = factory.newEmbeddedMediaPlayer();
        mediaPlayer = factory.newEmbeddedMediaPlayer(new DefaultFullScreenStrategy(f));
            f.setVisible(true);
            mediaPlayer.setFullScreen(true);
    }
   
  /*  public static synchronized VlcjMediaHandler getSingletonVlcjMedia() {
        if (vlcjMedia == null) {
            vlcjMedia = new VlcjMediaHandler();
    }
    return vlcjMedia;
    }
    */






public class Controls extends JPanel{

    VlcjMediaHandler media = new VlcjMediaHandler(this);

.....
}

Tuesday, July 17, 2012

Good for Theora

Good for Theora
    public String[] buildWithoutPreview() {
        List<String> params = new ArrayList<String>();       
        params.add(":dshow-adev=none");
        params.add(String.format(":dshow-vdev=%s", getDeviceName()));
        params.add(String.format(":dshow-aspect-ratio=%s", getAspectRatio()));
        params.add(":live-caching=300");
        if(width > 0 && height > 0)
            params.add(String.format(":dshow-size=%dx%d", width, height));
/*        StringBuilder chain = new StringBuilder(":sout=#");
        chain.append("duplicate{dst='")
             .append(buildTranscodeParams())
             .append("'}");
        params.add(chain.toString());     
*/
//params.add(String.format(":sout=#transcode{vcodec=h264,vb=1024,fps=15,scale=0,width=%d,height=%d}", width, height));
//params.add(String.format(":std{access=file,mux=mp4,dst='C:\\test.mp4'}"));
        params.add(String.format(":sout=#transcode{vcodec=theo,vb=1024,fps=15,scale=0,width=%d,height=%d}:std{access=file,mux=ogg,dst='C:\\testTheo.mp4'}", width, height));
//        params.add(String.format(":sout=#transcode{vcodec=h264,vb=1024,fps=15,scale=0,width=%d,height=%d}:std{access=file,mux=mp4,dst='C:\\test.mp4'}", width, height));
        String[] result = params.toArray(new String[params.size()]);
        logger.log(Level.INFO, Arrays.toString(result));

//        params.add(String.format(":sout=#transcode{vcodec=h264,vb=512,fps=%d,scale=0,width=%d,height=%d,acodec=mpga,ab=128,channels=2,samplerate=44100}:std{access=file,mux=mp4,dst='C:\\test.mp4'}", getFramerate(), width, height));
//        String[] result = {"sout=#transcode{vcodec=h264,vb=1024,fps=15,scale=0,width=1280,height=720,acodec=mpga,ab=128,channels=2,samplerate=44100}:std{access=file,mux=mp4,dst='C:\\test.mp4'}"};
        return result;
    }

Thursday, July 12, 2012

Java: Safe javafx code in swing application



Example

        media.statusProperty().addListener(new javafx.beans.value.ChangeListener<PlayState>(){

            @Override
            public void changed(ObservableValue<? extends PlayState> ov, PlayState oldValue, final PlayState newValue) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if(newValue == PlayState.STOPPED)
                            cameraConfig.setEnableControls(true);
                        else
                            cameraConfig.setEnableControls(false);

                        switch(newValue) {
                            case PLAYING:
                                playButton.setIcon(iconPause);
                                stopButton.setEnabled(true);
                                playButton.setEnabled(true);
                                recordButton.setEnabled(false);
                                slider.setEnabled(true);
                                previewCheckBox.setEnabled(false);
                                previewCheckBox.setSelected(false);
                                break;
                            case RECORDING:
                                playButton.setIcon(iconPlay);
                                stopButton.setEnabled(true);
                                playButton.setEnabled(false);
                                recordButton.setEnabled(false);
                                slider.setEnabled(false);
                                previewCheckBox.setEnabled(false);
                                break;
                            case PAUSED:
                                playButton.setIcon(iconPlay);
                                stopButton.setEnabled(true);
                                playButton.setEnabled(true);
                                recordButton.setEnabled(false);
                                slider.setEnabled(true);
                                break;
                            case STOPPED:
                                resetControls();
                                break;
                            default:    // should never happened
                                break;
                        }
                    }
                });
            }
           
        });



Wednesday, July 4, 2012

Java: Javafx tracking variable status using addListener

    public enum PlayState {
        STOPPED, PAUSED, PLAYING, RECORDING, PREVIEWING
    };
...

    private final ObjectProperty<PlayState> statusProperty;
...
    public ObjectProperty<PlayState> statusProperty() {
        return statusProperty;
    }
...



        media.statusProperty().addListener(new javafx.beans.value.ChangeListener<PlayState>(){

            @Override
            public void changed(ObservableValue<? extends PlayState> ov, PlayState oldValue, PlayState newValue) {
                switch(newValue) {
                    case PLAYING:
                        playButton.setIcon(iconPause);
                        stopButton.setEnabled(true);
                        playButton.setEnabled(true);
                        recordButton.setEnabled(false);
                        slider.setEnabled(true);
                        previewCheckBox.setEnabled(false);
                        previewCheckBox.setSelected(false);
                        break;
                    case RECORDING:
                        playButton.setIcon(iconPlay);
                        stopButton.setEnabled(true);
                        playButton.setEnabled(false);
                        recordButton.setEnabled(false);
                        slider.setEnabled(false);
                        previewCheckBox.setEnabled(false);
                        break;
                    case PAUSED:
                        playButton.setIcon(iconPlay);
                        stopButton.setEnabled(true);
                        playButton.setEnabled(true);
                        recordButton.setEnabled(false);
                        slider.setEnabled(true);
                        break;
                    case STOPPED:
                        playButton.setIcon(iconPlay);
                        stopButton.setEnabled(false);
                        playButton.setEnabled(true);
                        recordButton.setEnabled(true);
                        slider.setEnabled(false);
                        slider.setValue(0);
                        previewCheckBox.setEnabled(true);
                        lStartRecordTime = -1;
                        break;
                    default:    // should never happened
                        break;
                }

            }
           
        });

Java: Recording screen using VLCJ lib



Recording screen

    private void doRecordScreen() {
        mediaPlayer.prepareMedia("screen://", " :screen-fps=10.000000 :live-caching=300");
        mediaPlayer.play();
        statusProperty.set(PlayState.PREVIEWING);
    }



Monday, July 2, 2012

Java: Add icon to a JPanel



Using a JLabel as a container

    private Icon iconMcLogo = new ImageIcon(getClass().getResource("control/mclogo.png"));
    private final JLabel lbMcLogo = new JLabel("    ");

Constructor:
        lbMcLogo.setIcon(iconMcLogo);
        panel.add(lbMcLogo);


Something more than that

 package com.marinecyb.arch.nbm.videograbber;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;

public class CameraConfig extends JPanel{

    private Icon iconMcLogo = new ImageIcon(getClass().getResource("control/mclogo.png"));
    private final JLabel lbMcLogo = new JLabel("    ");

    private final JLabel lbFps = new JLabel("FPS");
    private final JLabel lbCameraSize = new JLabel("Size");
    private final JComboBox cbCameras = new JComboBox();
    private final JComboBox cbFps = new JComboBox();
    private final JComboBox cbCameraSize = new JComboBox();
    private final JButton btRefreshCameras = new JButton("Refresh");
    private final JButton btAdvancedProperties = new JButton("Advanced Properties");
    private String sSelectedCamera = "";
    private static String[] cameraList;
    private static String[] fpsList = {"25", "30"};
    private static String[] sizeListMS = {"640x480", "800x600", "1024x768", "1280x720"};
    private static String[] sizeListHP = {"640x480", "800x600", "1024x768", "1280x720"};
    private static String[] sizeListStandard = {"640x480", "800x600", "1024x768"};

    public CameraConfig(){
        super();

        lbMcLogo.setIcon(iconMcLogo);
        updateCameras();
        initFps();
        updateSize();

        btRefreshCameras.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateCameras();
            }
        });

        cbCameras.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                sSelectedCamera = (String)cbCameras.getSelectedItem();
                if(sSelectedCamera != null){
                    MediaProperties.setCameraName((String)cbCameras.getSelectedItem());
                }
            }
        });

        cbFps.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                MediaProperties.setFrameRate(Integer.parseInt((String)(String)cbFps.getSelectedItem()));
            }
        });

        cbCameraSize.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                MediaProperties.setImageSize((String)cbCameraSize.getSelectedItem());
            }
        });

        btAdvancedProperties.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new CameraInfoProvider().showAdvancedProperties(MediaProperties.getCameraIndex());
            }
        });

        addControls();
    }

    private void updateCameras(){
        cameraList = new CameraInfoProvider().getConnectedCameras();
        cbCameras.removeAllItems();
        String sCameraName = MediaProperties.getCameraName();
        int iFound = -1;
        for(int i = 0; i < cameraList.length; i++){
            cbCameras.addItem(cameraList[i]);
           
            if(sCameraName != null && sCameraName.contains(cameraList[i]))
                iFound = i;
        }

        if(iFound >= 0)
            cbCameras.setSelectedItem(MediaProperties.getCameraName());
        else{
            cbCameras.setSelectedIndex(0);
            MediaProperties.setCameraName((String)cbCameras.getSelectedItem());
        }

        sSelectedCamera = (String)cbCameras.getSelectedItem();
    }

    private void initFps(){
        int iFps = MediaProperties.getFrameRate();
        for(int i = 0; i < fpsList.length; i++){
            cbFps.addItem(fpsList[i]);
            if(iFps == Integer.parseInt(fpsList[i]))
                cbFps.setSelectedIndex(i);
        }
    }

    private void updateSize(){
        int localWidth = MediaProperties.getImageWidth();
        int localHeight = MediaProperties.getImageHeight();
        String localSize = String.valueOf(localWidth) + "x" + String.valueOf(localHeight);

        if(cbCameraSize != null)
            cbCameraSize.removeAllItems();
        if(sSelectedCamera == null){
            return;
        }
        if (sSelectedCamera.contains("Microsoft")){
            for(int i = 0; i < sizeListMS.length; i++)
                cbCameraSize.addItem(sizeListMS[i]);
        }
        else if (sSelectedCamera.contains("HP")){
            for(int i = 0; i < sizeListHP.length; i++)
                cbCameraSize.addItem(sizeListHP[i]);
        }
        else{
            for(int i = 0; i < sizeListStandard.length; i++)
                cbCameraSize.addItem(sizeListStandard[i]);
        }

        cbCameraSize.setSelectedItem(localSize);
    }

    public void addControls(){
        this.add(lbMcLogo);
        this.add(btRefreshCameras);
        this.add(cbCameras);
        this.add(lbFps);
        this.add(cbFps);
        this.add(lbCameraSize);
        this.add(cbCameraSize);
        this.add(btAdvancedProperties);
    }

    public void toggle(){
        this.setVisible(!this.isVisible());
    }
}

Monday, June 11, 2012

Java: Using VLC to play & record video data from webcam



1. Links

25 things you can do with VLC Media player!
http://www.unixmen.com/22-things-you-can-do-with-vlc/

http://gofree.com/Tutorials/VLCVideoWebcam.php
http://newcome.wordpress.com/2010/01/17/recording-webcam-videos-with-vlc-media-player/
Codec code
http://wiki.videolan.org/Codec

Sometimes Asked Questions
http://code.google.com/p/vlcj/wiki/SAQ

Chapter 3.  Advanced streaming using the command line
http://www.videolan.org/doc/streaming-howto/en/ch03.html

Play video in Java
http://www.informit.com/guides/content.aspx?g=java&seqNum=658

Sample java code
http://code.google.com/p/vlcj/source/browse/trunk/vlcj/src/test/java/uk/co/caprica/vlcj/test/basic

Sample using Theora encorder:
http://en.flossmanuals.net/ogg-theora/encoding/vlc/

                    .append("vcodec=theo,")
                    .append("mux=ps,"), //or ogg


2. Source

    private String buildTranscodeParams(){
        StringBuilder chain = new StringBuilder()
                .append("transcode{")
                    .append("vcodec=WMV2,")
                    .append("vb=").append(getBitrate()).append(",")
                    .append("fps=").append(getFramerate()).append(",")
                    .append("scale=1");
                    if(width > 0 && height > 0)
                        chain.append(",")
                             .append("width=").append(width).append(",")
                             .append("height=").append(height);
                chain.append("acodec=wma2,")
                .append("ab=128,")
                .append("channels=2");
                chain.append("}")
                .append(":standard{")
                    .append("access=file,")
                    .append("mux=asf,")
                    .append("dst=").append(getDestination()).append("}");
          return chain.toString();
    }




Wednesday, June 6, 2012

Java: Create tab in Property



1. Links
http://platform.netbeans.org/tutorials/nbm-nodesapi2.html#separate-property-groups


2. Example

public class ValueNode extends AbstractNode implements PropertyChangeListener, NodeListener {
...

    @Override
    protected Sheet createSheet() {
        Sheet sheet = super.createSheet();
        monitor = new Sheet.Set();
        monitor.setDisplayName("Monitor");
        monitor.setName("Monitor");
        sheet.put(monitor);

        control = new Sheet.Set();
        control.setDisplayName("Control");
        control.setName("Control");
        sheet.put(control);

        gui = new Sheet.Set();
        gui.setDisplayName("User interface settings");
        gui.setName("User interface");
        sheet.put(gui);

        signalFailure = new Sheet.Set();
        signalFailure.setDisplayName("Signal Failure");
        signalFailure.setName("SignalFailure");
//        sheet.put(signalFailure);

        if (ioSignal != null) { // IO signal {
            ioSignalScaling = new Sheet.Set();
            ioSignalScaling.setDisplayName("Scaling");
            ioSignalScaling.setName("Scaling");
            Properties.IOSignal(value, monitor, control, gui, signalFailure, ioSignalScaling, ioSignal);
            ioSignalScaling.setValue("tabName", "Scaling properties");
            sheet.put(ioSignalScaling);
            signalFailure.setValue("tabName", "Signal Failure properties");
            sheet.put(signalFailure);
        }else{
            if (value.getType().equals(Value.Type.SIGNAL)) {
                Properties.signal(value, monitor, control, gui, signalFailure);
            } else if (value.getType().equals(Value.Type.PARAMETER)) {
                Properties.parameter(value, monitor, control, gui, signalFailure);
            }
        }
      
        return sheet;
    }

...
}


Tuesday, May 29, 2012

boost: new functions for me



1. Links

bind
http://www.boost.org/doc/libs/1_49_0/libs/bind/bind.html




Friday, May 25, 2012

What is the difference between UDP and TCP internet protocols?


1. Links

http://www.cyberciti.biz/faq/key-differences-between-tcp-and-udp-protocols/

Q. Can you explain the difference between UDP and TCP internet protocol (IP) traffic and its usage with an example?
A. Transmission Control Protocol (TCP) and User Datagram Protocol (UDP)is a transportation protocol that is one of the core protocols of the Internet protocol suite. Both TCP and UDP work at transport layer TCP/IP model and both have very different usage.

Difference between TCP and UDP

TCPUDP
Reliability: TCP is connection-oriented protocol. When a file or message send it will get delivered unless connections fails. If connection lost, the server will request the lost part. There is no corruption while transferring a message.Reliability: UDP is connectionless protocol. When you a send a data or message, you don't know if it'll get there, it could get lost on the way. There may be corruption while transferring a message.
Ordered: If you send two messages along a connection, one after the other, you know the first message will get there first. You don't have to worry about data arriving in the wrong order.Ordered: If you send two messages out, you don't know what order they'll arrive in i.e. no ordered
Heavyweight: - when the low level parts of the TCP "stream" arrive in the wrong order, resend requests have to be sent, and all the out of sequence parts have to be put back together, so requires a bit of work to piece together.Lightweight: No ordering of messages, no tracking connections, etc. It's just fire and forget! This means it's a lot quicker, and the network card / OS have to do very little work to translate the data back from the packets.
Streaming: Data is read as a "stream," with nothing distinguishing where one packet ends and another begins. There may be multiple packets per read call.Datagrams: Packets are sent individually and are guaranteed to be whole if they arrive. One packet per one read call.
Examples: World Wide Web (Apache TCP port 80), e-mail (SMTP TCP port 25 Postfix MTA), File Transfer Protocol (FTP port 21) and Secure Shell (OpenSSH port 22) etc.Examples: Domain Name System (DNS UDP port 53), streaming media applications such as IPTV or movies, Voice over IP (VoIP), Trivial File Transfer Protocol (TFTP) and online multiplayer games etc

Further readings

Thursday, May 24, 2012

Windows timer


1. Links

Timers Tutorial
http://www.codeproject.com/Articles/1236/Timers-Tutorial


Queue Timers

The last kind of Windows - supported timers that we are going to read about in this article is queue timers. They were introduced with Windows 2000.
Queue timers are lightweight kernel objects that reside in timer queues. Like most timers, they enable us to specify the callback function to be called when the specified due time arrives. In this case, the operation is performed by a thread in the Windows thread pool.
Here, for the sake of simplicity, we are not going to create our timer queues. Instead, we will put our queue timers into default timer queue, provided by the OS.
First, we need to create a timer and add it to the default timer queue. For this, we'll make a call to:
BOOL CreateTimerQueueTimer(PHANDLE phNewTimer, HANDLE TimerQueue , 
 WAITORTIMERCALLBACK Callback, PVOID Parameter, DWORD DueTime, 
 DWORD Period, ULONG Flags); 

Arguments

  • phNewTimer - Pointer to a handle; this is an out value
  • TimerQueue - Timer queue handle. For the default timer queue, NULL
  • Callback - Pointer to the callback function
  • Parameter - Value passed to the callback function
  • DueTime - Time (milliseconds), before the timer is set to the signaled state for the first time
  • Period - Timer period (milliseconds). If zero, timer is signaled only once
  • Flags - One or more of the next values (table taken from MSDN):
WT_EXECUTEINTIMERTHREAD The callback function is invoked by the timer thread itself. This flag should be used only for short tasks or it could affect other timer operations.
WT_EXECUTEINIOTHREAD The callback function is queued to an I/O worker thread. This flag should be used if the function should be executed in a thread that waits in an alertable state. The callback function is queued as an APC. Be sure to address reentrancy issues if the function performs an alertable wait operation.
WT_EXECUTEINPERSISTENTTHREAD The callback function is queued to a thread that never terminates. This flag should be used only for short tasks or it could affect other timer operations. Note that currently no worker thread is persistent, although no worker thread will terminate if there are any pending I/O requests.
WT_EXECUTELONGFUNCTION Specifies that the callback function can perform a long wait. This flag helps the system to decide if it should create a new thread.
WT_EXECUTEONLYONCE The timer will be set to the signaled state only once.

Return Value

  • Nonzero if the function succeeds
The callback function is really pretty simple:
VOID CALLBACK WaitOrTimerCallback(PVOID lpParameter, BOOLEAN TimerOrWaitFired); 

Arguments

  • lpParameter - Pointer to user-defined data
  • TimerOrWaitFired - always TRUE for timer callbacks
To cancel a queue timer, use the function:
BOOL DeleteTimerQueueTimer(HANDLE TimerQueue, HANDLE Timer, HANDLE CompletionEvent); 

Arguments

  • TimerQueue - A handle to the (default) timer queue
  • Timer - A handle to the timer
  • CompletionEvent - A handle to an optional event to be signaled when the function is successful and all callback functions have completed. Can be NULL.

Return Value

  • Nonzero if the function succeeds
The example for queue timers is given below:
void CTimersDlg::OnButtonBegin()
{
 .
 .
 .
    // create the timer

 BOOL success = ::CreateTimerQueueTimer(
  &m_timerHandle,
  NULL,
  TimerProc,
  this,
  0,
  elTime,
  WT_EXECUTEINTIMERTHREAD);
}

void CTimersDlg::OnButtonStop()
{
    // destroy the timer
 DeleteTimerQueueTimer(NULL, m_timerHandle, NULL);
 CloseHandle (m_timerHandle);
}

void CTimersDlg::QueueTimerHandler() // called every elTime milliseconds
{
// do what you want to do, but quickly
 .
 .
 .
}

void CALLBACK TimerProc(void* lpParametar,
                                    BOOLEAN TimerOrWaitFired)
    {
    // This is used only to call QueueTimerHandler
    // Typically, this function is static member of CTimersDlg
    CTimersDlg* obj = (CTimersDlg*) lpParametar;
    obj->QueueTimerHandler();
    } 
As you can see, queue timers are pretty easy to use. I can also add that they are very accurate, and "resource friendly".
As I noted at the beginning of this chapter, queue timers are supported on Windows 2000 and later. If you do not want to support older Windows versions, they are perfect, and should be used instead of multimedia timers.

Conclusion

What's the moral of the whole story?
When you decide that you need a timer in your application, choosing between the different timer variants should not be that hard. Follow these simple rules:
  1. If you want your application to work on every 32 bit Windows platform, you do not need high precision, and the callback operation is fast enough not to disrupt the UI responsiveness, use a standard Win32 timer.
  2. If you want your application to work on every 32 bit Windows platform, and you need high precision, use the multimedia timer.
  3. If you want your application to work on Windows 98/NT4 and later, you need low system overhead, and can afford to block the calling thread, use the waitable timer.
  4. If you want a high-precision, low-overhead, non-blocking timer that will work on Windows 2000 and later, use the queue timer.








// Trying with new implementation

void CALLBACK TimerProc(void* lpParametar, BOOLEAN TimerOrWaitFired){
    // This is used only to call step()
    // Typically, this function is static member of AbstractEngine
    AbstractEngine* obj = (AbstractEngine*) lpParametar;
    obj->step();
}

int AbstractEngine::activate(){
    winACStepsRun = 0;

    if (engineCanBeActivated) {
        if(!modelThreadRunning){
            startModelThread();
            Logger::info("Engine activated, model thread started.");
            if ( router->getTcpServer() ){
                router->getTcpServer()->startServer();
            } else {
                Logger::warning("Cannot start TCP server.");
                return 1;
            }

    BOOL success = ::CreateTimerQueueTimer(
        &m_timerHandle,
        NULL,
        TimerProc,
        this,
        0,
        10,
        WT_EXECUTEINTIMERTHREAD);
        }
    } else {
        Logger::warning("Engine could not be activated.");
        return 2;
    }

    return 0;
}