Pages

2009-12-31

Set master volume by command line (e.g. in a rc script)

Get Volume:

amixer get Master

Set Volume:

amixer set Master 75%


That's it!

New framebuffer size settings in Grub2 (vga=xxx is obsolete)

Set desired console resolution in /etc/default/grub

GRUB_GFXMODE=1200x1024x16

Add the following line in /etc/grub.d/00_header

set gfxpayload=keep

Directly after this one: set gfxmode=${GRUB_GFXMODE}



Now update grub:

update-grub


That's it!

Set up SNMP Listener on Windows


Install SNMP:

Control Panel -> Software -> Add Windows Components -> Management & Monitoring Tools -> Simple Network Management Protocol

Set up SNMP:


services.msc -> SNMP Service
-> Traps -> public
-> Security -> Community public & Allow SNMP packages from YOUR_TRUSTED_HOSTS

Set up Firewall:

Windows Firewall -> Exceptions (Inbound Connections) -> Allow Port 161 (UDP)

That's it!



Capture and handle CTRL + C with SWT


Add the following listener to yor list, table or any other widget:


        private Listener myKeyListener() {
                return new Listener() {
                        public void handleEvent(Event e) {
                                if(!(e.keyCode == 'c' && e.stateMask == SWT.CTRL)) return;
                                System.out.println("CTRL + C");
                               // Do what you want to do now

                        }
                };
        }

That's it!

2009-11-04

Indeterminate progress bar as popup window

A small indeterminate progress bar. Use like this:

pleaseWait wait = new pleaseWait();
wait.start();

/* some long operation */

wait.stop();

--- cut here –--

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;

public class pleaseWait extends Thread {

        public void run() {
                Display display = new Display();
                Shell shell = new Shell(display, SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL);
                shell.setText("Please wait...");

                ProgressBar bar = new ProgressBar(shell, SWT.INDETERMINATE);
                bar.setBounds(1, 0, 200, 20);
                bar.setMaximum(5);
                bar.setMinimum(0);

                shell.pack();

                Monitor primary = display.getPrimaryMonitor();
                Rectangle bounds = primary.getBounds();
                Rectangle rect = shell.getBounds();

                int x = bounds.x + (bounds.width - rect.width) / 2;
                int y = bounds.y + (bounds.height - rect.height) / 2;

                shell.setLocation(x, y);
                shell.open();

                while (!shell.isDisposed()) {
                        if (!display.readAndDispatch())
                                display.sleep();
                }
        }
}
--- cut here –--



2009-11-03

Read XML file, set a node value by XPATH and save the XML file w/ Perl


use XML::XPath;
use XML::XPath::XMLParser;


# Load XML Structure
my $xml_file_name = 'somewhere/somefile.xml';
my $xp = XML::XPath->new(filename => $xml_file_name);


# Set Value of an XPATH node
my $new_value = “My New Value”;
set_node($xp,'/SomeRoot/SomeChild/SomeTag[@symbol="SomeAttribute"]', $new_value);


# Save modified XML file
my $nodeSet = $xp->find("/");
my $xml_file_content = $nodeSet->get_node(1)->toString;


# Preserve xml entities
$ xml_file_content =~s/&#/&#/g; 


# Save file
open(XML,"> $xml_file_name") or die "ERROR: Can't open $xml_file_name \n$!";
print XML $xml_file_name;
close XML;


sub set_node {
        my $xp = shift @_;
        my $xpath=shift @_;
        my $xvalue=shift @_;


my $nodeset = $xp->find($xpath);
         foreach my $node ($nodeset->get_nodelist) {
                $xp->setNodeText($xpath,$xvalue);
         }
}


Convert plain text to HTML&XML escaped entities w/ Perl


sub xmlize {
       # unpack byte-by-byte (set to "U0U*" in case of UTF-8)

        my $format="C*"; 
           my @output;
        while($line=shift @_) {
                my @array=map {
                        if($_>127) {
                                sprintf("&#%04ld;",$_);
                        }
                        else {
                                sprintf("%s",chr($_));
                        }
                }unpack($format,$line);
                push(@output,join "", @array);
        }
        return join "",@output;
}






Sort SWT Table by a column reagardless the column count


Create a table, add columns and the following listener to each column:


private Listener TableSortListener(final Table table) {
            return new Listener() {
                public void handleEvent(Event e) {
                    TableItem[] items = table.getItems();
                    Collator collator = Collator.getInstance(Locale.getDefault());
                    TableColumn column = (TableColumn)e.widget;
                    int index = 0;
                   
                    // Get selected column
                    for(int i=0;i<table.getColumnCount();i++)
                         if(column == table.getColumn(i)) index=i;


                    // Set sort direction
                    int cmp =-1;         
                    if(table.getSortDirection() == SWT.UP) cmp = 1;
                   
                    for (int i = 1; i < items.length; i++) {
                        String value1 = items[i].getText(index);
                        for (int j = 0; j < i; j++){
                            String value2 = items[j].getText(index);
                            if (collator.compare(value1, value2) * cmp < 0) {
                                
                                 // Cache Strings
                                 String[] values = new String[table.getColumnCount()] ;
                                 for(int c=0;c<table.getColumnCount();c++) values[c] = items[i].getText(c);
        
                                // Cache Data & Images
                                String data = (String) items[i].getData();
                                org.eclipse.swt.graphics.Image image = items[i].getImage();
                               
                                // Redraw
                                items[i].dispose();
                                TableItem item = new TableItem(table, SWT.NONE, j);
                                item.setText(values);
                                item.setData(data);
                                item.setImage(image);
                               
                                items = table.getItems();
                                break;
                            }
                        }
                    }

                    table.setSortColumn(column);
                    table.setSortDirection((table.getSortDirection() == SWT.UP)? SWT.DOWN : SWT.UP);
                }
            };
        }

2009-10-19

Install a recent JRE as prerequisite in an InstallAware Package

I wanted to deploy a Java application as an InstallAware Package, however I wanted to provide a more recent JRE as 1.6.1 provided with IA9.

These are the steps:

1. Download the most recent JRE and place them somewhere in your project's directory (e.g.: C:\Project\FileBag). My directory contents looked like this:

  • jre-6u16-windows-i586.exe
  • jre-6u16-windows-x64.exe
2. Create a file bag inside IA:

Set Variable FILEBAG to

Define File Bag : C:\Project\FileBag\*.*, get runtime location of files into variable FILEBAG


2. Check if the OS is 32 or 64 bit:

Get System Setting Windows in 64 bit Mode into WIN_64BIT

if Variable WIN_64BIT Equals TRUE
   Set x64 - Native 64 bit Windows, AMD64 and EM64T Architectures - installation mode
end


3. Add a check for JRE in the prerequisite check section:

Read Registry Key HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\1.6\JavaHome into JRE

if Variable JRE Equals
   Set Variable PREREQ to TRUE
   Set Variable PRELIST to $PRELIST$$NEWLINE$Java(TM) SE Runtime Environment 6
end

3. Add JRE installation in prerequisite installation section:
if Variable JRE Equals

   Set Variable PROGRESSTEXT to Java(TM) SE Runtime Environment 6
   Set Variable JRERES to
   Set Variable JREERR to
   Set Variable JRE_INSTALLER to



   if Variable WIN_64BIT Equals TRUE
      Set Variable JRE_INSTALLER to $FILEBAG$\jre-6u16-windows-x64.exe
   else
      Set Variable JRE_INSTALLER to $FILEBAG$\jre-6u16-windows-i586.exe
   end


   Run Program $JRE_INSTALLER$ /s /v"/qnADDLOCAL=ALL UPDATE=1 IEXPLORER=1 NETSCAPE6=1 MOZILLA=1 REBOOT=Suppress JAVAUPDATE=0 WEBSTARTICON=0 EULA=1" (WAIT, get result into variable JRERES)


   if Variable JRERES not Equals 0
       MessageBox: $TITLE$ Setup, Java(TM) SE Runtime Environment 6 installation has failed.$NEWLINE$$NEWLINE$$JREERR$$NEWLINE$$NEWLINE$$TITLE$ Setup cannot continue.
       Terminate Installation
   else
       Read Registry Key HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\1.6\JavaHome into JRE


   end
end

That's it!

2009-10-17

Random Wallpaper in Gnome using wallpapoz and directory scan script

I wanted my Gnome wallpaper to switch through my picture collection randomly and also display only those pictures which are in landscape mode with an aspect ration about 16:9 or 16:10.

I didn't find anything doing it out of the box, but wallpapoz was a good start. It works fine, you can add singe pictures or directories to the configuration and even diferent sets for each workplace.

However it is boring to click thorugh a deep hierarchy of picture folders and subfolders to add pictures to the collection manually and there's still no possibility to take landscape pictures only.

So I had a look at the .wallpapoz/wallpapoz.xml file and realized how simple this file is structured. The files are listed line by line enclosed in a file tag.

Then I used the identify command line utility from ImageMagick package which prints out the pictures attributes like resolution - there I was, everything ready to write a shell script which woud go with find trough a given top level directory, execute the identify command on each image and pipe the output to awk which takes only JPEGs  with a landscape aspect ratio 16:9 - 16:10 so 1.5 to 1.8. and print everything to a temporary file.

Then the skeleton of wallpapoz.xml with the desired preferences like randomize, stretch and scale are taken and echo'ed to the STDOUT as well as the contens of the temporary file containing the file listing.

As simply as that, copy the shell script somewhere and run it like:

wallpapoz.sh > ~/.wallpapoz.xml

and restart the daemon_wallpapoz.

And this is the script:

---- cut here ---
if [ $# -lt 1 ]
then
     echo "Usage: `basename $0` directory\ containing\ images OR"
     echo "Usage: `basename $0` \"directory containing\images\""
     exit 1
fi
TEMPFILE=/tmp/wallpapoz.tmp.$$
find "$*" -type f -exec identify {} \; 2>/dev/null \
| awk -F'JPEG|x' '
{
        if(NF==4) {
                split($3,arr," ");
                if(arr[2]>arr[1]) {
                        ratio = arr[2]/arr[1];
                        if(ratio>1.5 && ratio <1.8) {
                                print $1;
                        }
                }
        }
}' \
| sed "s/ *$//g"|sed "s/^.*$/      <file><\/file>/g" > $TEMPFILE
echo '<?xml version="1.0" encoding="utf-8"?>'
echo '<!DOCTYPE Wallpapoz>'
echo '<wallpapoz interval="2" random="1" style="1" type="workspace">'
echo '    <workspace name="Umbenennen" no="1">'
cat $TEMPFILE
echo '   </workspace>'
echo '    <workspace name="Umbenennen" no="2">'
cat $TEMPFILE
echo '    </workspace>'
echo '    <workspace name="Umbenennen" no="3">'
cat $TEMPFILE
echo '    </workspace>'
echo '    <workspace name="Umbenennen" no="4">'
cat $TEMPFILE
echo '    </workspace>'
echo '</wallpapoz>'
rm $TEMPFILE

---- cut here ---


That's it!

2009-10-08

Enable BitLocker without TPM chip in Windows 7

In order to encrypt your drives with Bitlocker in Windows 7 without TPM chip you need to choose an alternative way to pass the authentication, e.g. saving the key on a USB thumb drive.

Run gpedit.msc in Administrator mode and navigate to Local Computer Policy -> Computer Configuration ->  Administrative Templates -> Windows Components ->  BitLocker Drive Encryption -> Operationg System Drives 

"Require additional authentication at startup" to "Enabled"

Proceed with BitLocker encryption in the Control Panel.

That's it.

2009-10-07

Don't display user name on a locked computer in Windows Vista/7

To make Windows Vista and Windows 7 not show the name of the logged on user on a locked workstation (e.g. to improve the security on your box), you have to set the corresponding local group policy.


Run secpol.msc in Administrator mode and navigate to Security Settings -> Local Policies -> Security Options and set the policy:

"Interactive logon: Display user information when the session is locked" to "Do not display user information"

That's it.

2009-10-06

Start HDDLifePro minimized using VBS

I've ran recently in a Pro version of HDDLife from a magazine and it appeared pretty handy for me. The program shows  (when started and minimized) the current HDD temperature in the tray.

There's an option to run it on Windows start, however there's no option to start it minimized.

This can be solved with a small VB script like this:


Set WshShell = WScript.CreateObject("Wscript.Shell")
WshShell.Run """C:\Program Files (x86)\zoneLINK\HDDlife\HDDlifePro.exe""", 7 ,True


I enclosed the binary path with three double quotes because of the parenthesis in the path (x86) and chose startup mode 6 (minimized).

Detailed information for Shell.Run() is documented on MSDN



Just add a shortcut to this script to the Startup folder in the start menu.

That's it!

2009-10-03

Start Nautilus with Windows + E keyboard shortcut

To get nautilus to popup by keyboard combination WINKEY + E like Windows Explorer in Windows you need to do the following:

1. run gconf-editor
2. navigate to apps -> metacity -> global_keybindings
3. set key run_command_1 to e
4. navigate to apps -> metacity -> keybinding_commands
5. set key command_1 to nautilus
6. close gconf-editor
7. Hit WINKEY + E and nautilus will pop up

That's it!

2009-09-29

Input Error: There is no script engine for file extension ".vbs".

I associated Notepad++ with the VBS extension which was a BIG mistake - cscript and wcsript denied execution of vbs scripts with the following message:

Input Error: There is no script engine for file extension ".vbs".

Running Windows 7 I wasn't sure whether it helps, but followed the instuctions on this link, the registration of the dll didn't change much, but the fix of the vbs file association under this link did the magic. Regedit of Windows 7 complained however that now all information could be written in the registry, but wcscript and csript accepted to run vbs scripts again.


That's it!

Shell function to print "du -s" output in ascending order of the size

I ran in a problem where a du -sh output showed me the disk usage in human readable format (GB, MB, etc) but the output order was based on file names and not on the size. So I wrote this little awk (gawk) wrapper:

Declaration:

function duh_sorted {
    du -s $*|sort -n|\
    awk 'BEGIN { m = 1024; g = m*m; t=g*m} { \
    \
    if($1>t) { human_size=$1/t; unit="TB"; } \
    else { \
        if($1>g) { human_size=$1/g; unit="GB"; } \
        else { \
            if($1>m) { human_size=$1/m; unit="MB"; } \
            else { human_size=$1; unit="KB";} \
            } \
    } \
    printf("%4ld %c\t%s\n", human_size,unit,$2)
    }'
}

Usage:

$ duh_sorted /data/nfs/*

   8 K  /data/nfs/scripts
  32 K  /data/nfs/extensions
 151 M  /data/nfs/patches
 197 M  /data/nfs/logs
   3 G  /data/nfs/filerepo
  14 G  /data/nfs/mondo

 
$ duh_sorted /
 44 G  /


That's it!

2009-09-28

Parse XML file with Xpath in Java

Parse XML file MyxmlFile.xml with Xpath "/File/Tag[@name='myAttName']/SubTag" and wrtie the result in mySubTagContent:


DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse (new File("MyxmlFile.xml"));


// normalize text representation
doc.getDocumentElement().normalize ();


Node myNode = SelectNode("/File/Tag[@name='myAttName']/SubTag");


if(myNode!=null) String mySubTagContent = myNode.getTextContent());


private Node SelectNode(String path) throws XPathExpressionException {
    Node child; XPathFactory xpf = XPathFactory.newInstance();
    XPath xp = xpf.newXPath();
    child = (Node) (xp.evaluate(path,doc, XPathConstants.NODE));
    return child;
}

That's it!

RegExp pattern matching with Java

Match String s with regular expression r:

import java.util.regex.Pattern;

public boolean RegMatch(String s, String r) {
    Pattern p = Pattern.compile(r);
    return p.matcher(s).matches();
}


That's it!

Get PID of an application by its listening TCP port using Win32 API

--- PidByPort.cpp Start ---

#include <winsock2.h>
#include <malloc.h>
#include "iphlpapi_2.h"
#include <stdio.h>

long GetPIDbyPort(long port) {


    long ret = 0; PVOID pTCPTable = NULL; DWORD size = 0; DWORD result = 0; result = pGetExtendedTcpTable(NULL, &size, true, AF_INET, TCP_TABLE_OWNER_MODULE_ALL, 0); while(result == ERROR_INSUFFICIENT_BUFFER){
      if(pTCPTable != NULL){
        free(pTCPTable);
      }
      pTCPTable = malloc(size); result = pGetExtendedTcpTable(pTCPTable, &size, true, AF_INET, TCP_TABLE_OWNER_MODULE_ALL, 0); if(result != NO_ERROR){
        printf("Failed to get TCP Table %s\n", GetLastError()); free(pTCPTable); return ret;
      }
    } if(result != NO_ERROR){
      printf("Failed to get size estimation %s\n", GetLastError()); return ret;
    } for(DWORD i = 0; i < ((PMIB_TCPTABLE_OWNER_MODULE)pTCPTable)->dwNumEntries; i++){
      MIB_TCPROW_OWNER_MODULE module = ((PMIB_TCPTABLE_OWNER_MODULE)pTCPTable)->table[i]; if(port==htons((short)module.dwLocalPort)) {
        #ifdef DEBUG printf("PID = %d, ", module.dwOwningPid); printf("State = %s\n ", g_mibTCPState[module.dwState]); printf(" LocalAddress = %d.%d.%d.%d, ", (htonl(module.dwLocalAddr) >> 24) & 0xFF, (htonl(module.dwLocalAddr) >> 16) & 0xFF, (htonl(module.dwLocalAddr) >> 8)& 0xFF, (htonl(module.dwLocalAddr)) & 0xFF); printf("LocalPort = %u,\n ", htons((short)module.dwLocalPort)); if(module.dwState != MIB_TCP_STATE_LISTEN){
          printf(" RemoteAddress = %d.%d.%d.%d, ", (htonl(module.dwRemoteAddr) >> 24) & 0xFF, (htonl(module.dwRemoteAddr) >> 16) & 0xFF, (htonl(module.dwRemoteAddr) >> 8) & 0xFF, (htonl(module.dwRemoteAddr)) & 0xFF); printf("RemotePort = %u\n ", htons((short)module.dwRemotePort));
        } printf(" TimeStamp = %I64d, ", module.liCreateTimestamp); printf(" ULONGLONG = UnDocumentedMeaning\n"); printf("\n"); #endif ret=module.dwOwningPid;
      }
    } if(pTCPTable != NULL) {
      free(pTCPTable);
    } return ret;
} --- PidByPort.cpp End -- --- iphlpapi_2.h Start --- #include <Iprtrmib.h> char* g_mibTCPState[] = {
    "???", "MIB_TCP_STATE_CLOSED", "MIB_TCP_STATE_LISTEN", "MIB_TCP_STATE_SYN_SENT", "MIB_TCP_STATE_SYN_RCVD", "MIB_TCP_STATE_ESTAB", "MIB_TCP_STATE_FIN_WAIT1", "MIB_TCP_STATE_FIN_WAIT2", "MIB_TCP_STATE_CLOSE_WAIT", "MIB_TCP_STATE_CLOSING", "MIB_TCP_STATE_LAST_ACK", "MIB_TCP_STATE_TIME_WAIT", "MIB_TCP_STATE_DELETE_TCB" };
typedef enum {
    TCP_TABLE_BASIC_LISTENER, TCP_TABLE_BASIC_CONNECTIONS, TCP_TABLE_BASIC_ALL, TCP_TABLE_OWNER_PID_LISTENER, TCP_TABLE_OWNER_PID_CONNECTIONS, TCP_TABLE_OWNER_PID_ALL, TCP_TABLE_OWNER_MODULE_LISTENER, TCP_TABLE_OWNER_MODULE_CONNECTIONS, TCP_TABLE_OWNER_MODULE_ALL } TCP_TABLE_CLASS, *PTCP_TABLE_CLASS;
DWORD (WINAPI *pGetExtendedTcpTable)(
    PVOID pTcpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, TCP_TABLE_CLASS TableClass, ULONG Reserved );
--- iphlpapi_2.h End--- --- Compiling --- cl -c PidByPort.cpp /D"_CRT_SECURE_NO_DEPRECATE" /EHcs /DDEBUG

That's it!

2009-09-27

Allow root to login in GDM

To configure GDM to allow root login, the /etc/gdm/gdm.conf-custom file needs to be modified. If the file doe not exist, just make a copy of /etc/gdm/gdm.conf

The reason to use this file instead of the /etc/gdm/gdm.conf file is the the latter can be changed during an update, and in later versions of GDM, the gdm.conf-custom file has been provided for user overrides of settings.

Add the following entry in the [security] section:
AllowRoot=true
PS: If you want to login as root using a remote X session, just add the following entry:

AllowRemoteRoot=true

Restart GDM, that's it.

Create an application shortcut in Gnome Application menu

Suppose you want to run an third party application from the Gnome Application panel which was compiled from a tarball for instance and does not appear in the menu.

Create a text file /usr/share/applications/<APP_NAME>.desktop with your favoured editor (e.g. vi) with the following content:

[Desktop Entry]
Name=Shortcut's name
Comment=Shortcut's tool tip text
Exec=Absolute path to the executable
Icon=Absolute path to the application icon file (e.g. PNG)
Terminal=false (or true if you want to run it in a terminal)
Type=Application
Categories=Application;Network;

Categories can be AudioVideo, FileTransfer, etc. To get an idea of avaliable categories, just grep in the existing shortcuts for categories:

# grep Categories /usr/share/applications/*.desktop

That's it!

Flash Player plugin for Iceweasel in Debian

It's a matter of the correct symbolic link to enable the flash player
plugin of your choice.
Just symlink the libflashplayer.so to the plugin directory of the
browser, e.g.:
ln -s /etc/alternatives/libflashplayer.s /usr/lib/iceweasel/plugins
That's it!

Enable Firefox Java plugin in Solaris

Suppose you installed a recent Firefox e.g. from http://www.sunfreeware.com and want to use it with a Java plugin, e.g. for Navisphere, BEA Admin Console or other management UI's.
Get a JRE which suits with your needs and install it on your Solarix
box. Then create a symbolic link to the plugins directory of you Firefox
installation, for instance:
# ln -s <JRE>/plugin/sparc/ns7/libjavaplugin_oji.so /opt/sfw/firefox/plugins
Start your Firefox and connect to the URL which needs the Java Plugin.
That's it!

Don't display last user name in Windows Vista & Windows 7

To make Windows Vista and Windows 7 forget the name of the last logged in user (e.g. to improve the security on your box), you have to set the corresponding local group policy.

Run secpol.msc in Administrator mode and navigate to Security Settings -> Local Policies -> Security Options and set the policy:

"Interactive Logon: Don't display last user name" to "Enable"

That's it.

PS: You can enable CTRL-ALT-DELETE before the logon mask in the same area. Just set the policy :

"Interactive logon: Do not require CTRL+ALT+DEL" to "Disable"

Enable administrative shares in Windows Vista & Windows 7

The administrative shares are disabled in Windows Vista & Windows 7 by default. In order to access your drives remotely, addressing them like \\hostname\C$ or \\hostname\D$, you have to add a key to the policy hive in the registry:
  • run regedit.exe (in Administrator mode)
  • navigate to
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system

  • create a new DWORD value and name it LocalAccountTokenFilterPolicy
  • set the value of LocalAccountTokenFilterPolicy to 1
  • reboot and try to access your administrativ shares (e.g. \\localhost\c$)
That's it!

Allow ping in Windows Vista & Windows 7

The ICMP echo request (ping) is blocked in the Windows Firewall in Windows Vista and Windows 7 by default. The quickest way to add end exception is to run netsh.exe from command propmpt rather than clicking your way through wf.msc

Open up command prompt (cmd.exe) in Administrator mode and type in the following command:
> netsh firewall set icmpsetting 8 enable

That's it, your box should be pingabble from now on.