About

Siamnet is a collection of articles I write or collect - generally technology oriented, but may include other topics such as origami, games, recipes, ...


Select the maximum value of varchar column with numeric entries

If you have a table with a varchar column containing integers and you want to find the maximum value, use the following query replacing <column> and <table> with appropriate values,

mysql> select max(cast(<column> as unsigned)) from <table>;

The following would work in Oracle,

select max(cast(<column> as decimal)) from <table>;

References

Posted on 2012-02-06 by asiam [See MySQL-SelectMaxValueWhereColumnIsVarchar]

Convert an integer to base 26 starting with base 'a' instead of '0'

public static String base26(int num) {
    if (num < 0) {
        throw new IllegalArgumentException("Only positive numbers are supported");
    }
    StringBuilder s = new StringBuilder("aaaaaaa");
    for (int pos = 6; pos >= 0 && num > 0 ; pos--) {
        char digit = (char) ('a' + num % 26);
        s.setCharAt(pos, digit);
        num = num / 26;
    }
    return s.toString();
}

This will always return a word with 7 characters because of StringBuilder("aaaaaaa"). Since the length of aaaaaaa is 7, we start the for loop int pos at 6.

If you wanted 10 character words, use the following snippet,

StringBuilder s = new StringBuilder("aaaaaaaaaa");
    for (int pos = 9; pos >= 0 && num > 0 ; pos--) {

References

Posted on 2012-02-06 by asiam [See Java-ConvertIntegerToBase26]

See your top ten used commands in BASH

$ history | awk '{print $2}' | awk 'BEGIN {FS="|"}{print $1}' | sort | uniq -c | sort -nr | head

References

Posted on 2012-01-31 by asiam [See Bash-ViewYourTopTenUsedCommands]

Insert the last arguments of a previous command into the current (BASH)

If your first command is,

$ cp file.txt /path/to/where/you/want/to/copy/a/file

Say you want to cd into that directory, just type,

$ cd (type ESC .)

Basically type ESC followed by a period (.).

References

Posted on 2012-01-31 by asiam [See Bash-InsertLastCommandsArgumentsInCurrentCommand]

Show all of your current key bindings in BASH

$ bind -p

Posted on 2012-01-31 by asiam [See Bash-ShowKeyBindings]

VIM Cheat Sheet

Command Description
:shell Access a shell prompt. Run exit to return to VIM.
%!awk '{print NR,$0}' Add literal line numbers to a text file.
:syntax enable Add syntax highlighting.
ctrl+a ] puts you in copy/paste mode in screen.

Then put your cursor on a start position, hit space, put marker at last position, hit space again to exit copy/paste mode.

Now in vi or whatever, hit ctrl+a ] and that will paste the contents you copied.
Copy and paste mode. Do this while in a screen session and the contents can be pasted into VIM.
yy to copy, then p to paste the line below the cursors current line. Copy and paste a line.
set autoindent Auto-indent when typing code.
set laststatus=2 Always display the status line.
Place your cursor on the 1st row, then hit shift + v, then type j to move your cursor to the last row. Now type a right angle (>). Indent further by hitting a period (.). Indent blocks of text.
Place your cursor on the number (last digit) and hitting ctrl + a. Increment an integer.
set hlsearch Highlight all matches of a search.
Put your cursor on a character and type ga. Get the hex, dec and oct codes of a character.
% While the cursor is on a curly brace, bracket or parentheses hit % and it will show you the opening or closing counterpart.
While editing a document, just issue :X and you will then be prompted to enter a key (password).

After saving your document, when you open it again, you will have to enter the password.

To remove the encryption, open your document with the correct password and issue :set key= and that will remove it.
Encrypt a document.
u Undo last change (can be repeated to undo preceding commands).
U Return the line to its original state (undo all changes in current line).
control + R Redo changes which were undone (undo the undo's).
r!<command> where <command> is a shell command. e.g. r!date Insert a commands output into the document at the current cursor position. e.g. r!date will put the current date in the document.
man subject | ul -i | vi - where subject is a man page. Read a man page while in VIM.
set paste Don't add extra lines when pasting documents. Usually if a document has tabs you will get ever increasing tabs at the beginning of each successive line.
Open your files with vim file1 file2 file3. When you're inside VIM. issue the command :bn to go to the next file, and :bp to go to the previous.

Type :buffers to see all open files and their corresponding buffer number. Type :b3 to go to the 3rd buffer (file).
Open multiple files at once.
:e file2.txt Open another file while a file is open.
''':%nu Show line numbers temporarily.
* or % Search for the next word or previous word respectively for the word under your cursor.
Hold Shift and type zz Save and quit fast.
Add the following to your ~/.vimrc.

set viminfo='10,\"100,:20,%,n~/.viminfo
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif
Return cursor to last position in file when opening.
. Repeat a command.
:1,$s/[ <tab>]*$// Remove all white space from the end of every line in a file.
tabstop Set tabstop to tell vim how many columns a tab counts for. Linux kernel code expects each tab to be eight columns wide. Visual Studio expects each tab to be four columns wide. This is the only command here that will affect how existing text displays.
expandtab When expandtab is set, hitting Tab in insert mode will produce the appropriate number of spaces.
shiftwidth Set shiftwidth to control how many columns text is indented with the reindent operations (<< and >>) and automatic C-style indentation.
softtabstop Set softtabstop to control how many columns vim uses when you hit Tab in insert mode. If softtabstop is less than tabstop and expandtab is not set, vim will use a combination of tabs and spaces to make up the desired spacing. If softtabstop equals tabstop and expandtab is not set, vim will always use tabs. When expandtab is set, vim will always use the appropriate number of spaces.
ddp Swap the current and next line.
Open a file with vi -O file1 file2

control W l to switch to right window.
control W h to switch to left window.
Split screen.
:set number Show line numbers.
:set showmatch Show matching brace after entering the last one.
:set textwidth=80

Enter gq) to justify the current line.
Justify lines.
ctrl+n Auto complete word after typing a few characters.
:! tidy -mi -xml -utf8 Tidy a file.
e Move to the end of a word.
w Move forward to the beginning of a word.
3w Move forward three words.
b Move backward to the beginning of a word.
3b Move backward three words.
$ Move to the end of the line.
<End> Same as $
0 Move to the beginning of the line.
<Home> Same as 0
) Jump forward one sentence.
( Jump backward one sentence.
} Jump forward one paragraph.
{ Jump backward one paragraph.
H Jump to the top of the display.
M Jump to the middle of the display.
L Jump to the bottom of the display.
'm Jump to the beginning of the line of mark m.
`m Jump to the location of mark m.
G Jump to end of file.
1G Jump to beginning of file.
50G Jump to line 50.
'' Return to the line where the cursor was before the latest jump.
`` Return to the cursor position before the latest jump (undo the jump).
% Jump to corresponding item, e.g. from an open brace to its matching closing brace.

References

Posted on 2012-01-31 by asiam [See Vim-CheatSheet]

How to encrypt and decrypt strings

<?php
function cipher_encrypt($data, $password) {
    return openssl_encrypt($data, "AES-256-CBC", $password, false, "344u1J#Zs591z7^7");
}

function cipher_decrypt($data, $password) {
    return openssl_decrypt($data, "AES-256-CBC", $password, false, "344u1J#Zs591z7^7");
}

To use the method, pass the data you want to encrypt along with a password and vice versa for decrypting.

<?php
$encrypt_me = "This will be encrypted.";
$password = "My secret password.";
$encrypted = cipher_encrypt($encrypt_me, $password);
$decrypted = cipher_decrypt($encrypted, $password);

You can get a list of all available cipher methods with the openssl_get_cipher_methods() function. The initialization vector (iv) for each cipher method may require a different length. We're using AES-256-CBC in the example above which requires a 16 character iv.

<?php
var_dump(openssl_get_cipher_methods());

References

Posted on 2012-01-30 by asiam [See Php-EncryptAndDecryptFunctions]

How to exclude files or directories with git

In your working copy, open .git/info/exclude.

Say your project contains some sort of data folder at src/main/resources/data and you want to exclude all files in that data directory.

You would add a line like this to .git/info/exclude.

/src/main/resources/data/*

Posted on 2012-01-27 by asiam [See Git-ExcludeFilesOrDirectories]

How to justify lines in Vim

Set your text width. For this example, we'll use 80 characters.

:set textwidth=80

Now put your cursor on a line to justify and type the following command,

Or you can type gq and then a direction such as j or k.

References

Posted on 2012-01-24 by asiam [See Vim-HowToJustifyLines]

How to push tags to master

$ git push --tags -u origin master

Posted on 2012-01-17 by asiam [See Git-PushingTagsToMaster]

How to mount a second hard drive image in VirtualBox

First create an image and attach it to your VM via the VirtualBox under Settings, then Storage.

Add an attachment to the Sata controller. Add Hard Disk

Then boot up your VM and add the following line, or similar, to your /etc/fstab file. The following is an example of mounting /dev/sdb1 to foobar's home directory. The file system is ext4 with default options.

/dev/sdb1   /home/foobar  ext4    defaults    0   0

Posted on 2012-01-10 by asiam [See VirtualBox-MountSecondHarddriveImage]

Clever way to Zebra Strip table rows with jQuery

Create your tables as you normally would.

In your CSS, add two classes: odd and even,

.odd {

}

.even {
    background-color:#dfdfdf;
}

Then add the following jquery code,

$(document).ready(function(){
    $("tr:odd").addClass("odd");
    $("tr:even").addClass("even");
});

This will automatically add the odd class to odd rows and even to even rows.

If you have multiple tables you should add a class to your <table /> elements so that the the first row is always the even class,

$(document).ready(function(){
    $("table.someclass tr:odd").addClass("odd");
    $("table.someclass tr:even").addClass("even");
});

References

Posted on 2012-01-09 by asiam [See Javascript-Jquery-ZebraStriping]

Get a list of all sequences or views in Oracle

select * from all_sequences;

Similarly you can get all views with,

select * from all_views;

Posted on 2012-01-04 by asiam [See Oracle-GetListOfAllSequences]

Zip like files into chunks

Say you have a folder of images and you want to create zip files that contain X number of files.

Just add to the glob brace list of file extensions.

<?php

// The number of files to chunk (+1) e.g. 19 will result in zips of 20 files.
$num_files = 19;
$a_files = glob("*.{jpg,jpeg,JPG,JPEG,gif,GIF,png,PNG,tif,TIF,tiff,TIFF}", GLOB_BRACE);

function zipFiles($zipfiles) {
    //print("IF cnt=$cnt\n");
    $zipfiles = rtrim($zipfiles, " ");
    $curdate = date("Y-m-d-H-i-s-") . preg_replace("/ */", "", microtime());
    print("zip i-$curdate.zip \"$zipfiles\"\n\n");
    exec("zip i-$curdate.zip \"$zipfiles\"");
    exec("rm -f \"$zipfiles\"");
    $GLOBALS['zipfiles'] = "";
    $GLOBALS['cnt'] = 0;
}

$cnt = 0;
$zipfiles = "";
foreach ($a_files as $k=>$pic) {
    if ( $cnt > $num_files ) {
        zipFiles($zipfiles);
    } else {
        //print("ELSE cnt=$cnt\n");
        $zipfiles .= "\"{Wiki.Php-ZipLikeFilesIntoChunks$pic}\" ";
        $cnt++;
    }
}

if ( $zipfiles != "" ) {
    zipFiles($zipfiles);
}

Posted on 2011-12-28 by asiam [See Php-ZipLikeFilesIntoChunks]

How to calculate a umask for files

The umask will be 663 for this example. i.e. rw-rw--wx

The initial file permission is 666. i.e. rw-rw-rw-

The complement of the umask is 114. i.e. --x--xr--

Basically you want to take the complement of the owner, group and other parts from the initial and complements.

initial     rw-rw-rw-
complement  --x--xr--
result      ------r--

So the result is 004 for files created.

Setting the umask for directories

When setting the umask for directories use an initial permission of 777.

References

Posted on 2011-12-21 by asiam [See Linux-HowToCalculateUmask]

Find big files from a terminal

Find in gigs

$ find / -size +1G -exec ls -l {} \;

or

Find in megs

find / -size +100M -exec ls -l {} \;

Here's a nice little script to find big files

#!/bin/bash

dir=$1;
size=$2;

if [[ $dir == "-h" || $dir == "--help" || $dir == "-H" ]]; then
    echo "Usage: findBigFiles <directory>";
    echo "       findBigFiles <directory> -s";
    echo "       findBigFiles -s";
    echo "       findBigFiles";
    echo "";
    echo " -s Include file size in report.";
    echo "";
    echo "If no directory or option is included, the current directory will";
    echo "be used.";
    echo "";
    echo "If only -s is used, the current directory will be scanned.";
    exit 0;
fi

if [[ $dir != "" && $size == "-s" ]]; then
    size="-s";
else
    size="";
fi

if [[ $dir == "-s" ]]; then
    size="-s";
    dir=".";
else
    size="";
fi

if [[ "${dir}" == "" ]]; then
    dir=".";
fi

function findBigFiles {
    dir=$1;
    if [[ -e $dir ]]; then
        cd $dir;
        ls | while read file; do
            if [[ -e "$file" ]]; then
                num=`find "$file" -type f | wc -l`;
                if [[ $size == "-s" ]]; then
                    echo "${num} `du -sh "${file}"` `pwd`/${file}";
                else
                    echo "${num} `pwd`/${file}";
                fi
            fi
        done
        num=`ls | wc -l`;
        echo "${num} `pwd`";
    fi
}

findBigFiles $dir | sort -g > /tmp/findBigFiles.log;

echo "Have a look at /tmp/findBigFiles.log";

Also See

UNIX-FindingBigFiles

Posted on 2011-12-21 by asiam [See Linux-FindBigFiles]

Loop over files in a directory that contain spaces

#!/bin/bash

ls | while read file; do
    echo $file;
done

References

Posted on 2011-12-21 by asiam [See Linux-LoopOverFilesInDirectoryThatContainSpaces]

Sort a file by numeric order

Say you have the following file, test.txt,

4 blah blah
45 something else
35 blah
1 and more

If you ran sort test.txt, you would get,

1 blah blah
45 something else
35 blah
4 and more

If you want the number column to be sorted, run sort -g test.txt, which outputs,

1 blah blah
4 and more
35 blah
45 something else

References

  • man sort

Posted on 2011-12-21 by asiam [See Linux-SortFileByNumericOrder]

Very simple popup box with curved edges and a transparent background

/**
 * These styles are used for help popups or whatever else you need them for.
 */

span#hov_span1 {
        position:relative;
        }
div.hov_div {
        display:none;
        }
span#hov_span1:hover div.hov_div {
    /* minimum styles */
    display:block;
    position:absolute;
    top:0;
    left:0;
    /* extra fancying style */
    width:200px;
    overflow:auto;
    background-color:#f8f3d2;
    border:1px solid #6d6e70;
    margin:0;
    padding:8px;
    /* the topleft corner is still a hard right angle */
    -webkit-border-radius:8px;
    -moz-border-radius:8px;
    -moz-box-shadow:4px 4px 4px silver;
    -webkit-box-shadow:4px 4px 4px silver;
    -o-box-shadow:4px 4px 4px silver;
    box-shadow:4px 4px 4px silver;
    opacity:0.9;
    -ms-filter:'alpha(opacity=90)';
    filter:alpha(opacity=90);
}
<html>
<head>
<title>Popup test</title>
<style type="text/css">
/**
 * Enter the styles above into this style block
 */

</style>
</head>
<body>
<span id="hov_span1">Some word or image<div class="hov_div">Here is the content that will popup.</div></span>
</body>
</html>

So you should only see "Some word or image" and when you hover over that, the div with class hov_div will popup.

Posted on 2011-12-18 by asiam [See Css-SimplePopUpBox]

How to set a system property with Spring

The following Spring bean entry will set the system property your.system.property to The_System_Property_Value.

You can have as many <prop /> elements as you need.

<!--
This bean adds the xml.catalog.files from the kms config into the system properties.
-->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject">
                <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
                        <property name="targetClass" value="java.lang.System" />
                        <property name="targetMethod" value="getProperties" />
                </bean>
        </property>
        <property name="targetMethod" value="putAll" />
        <property name="arguments">
                <util:properties>
                        <prop key="your.system.property">The_System_Property_Value</prop>
                </util:properties>
        </property>
</bean>

References

Posted on 2011-12-14 by asiam [See Java-Spring-HowToSetSystemProperty]

Set Chrome browser to search your bookmarks

Go to Tools > Options > Basic > Default Search Manage. Under Other search engines there will be an entry where you can define a search. For the Add a new search engine field enter Chrome Bookmarks. For the Keyword field enter b. For the URL with %s in place of the query enter chrome://bookmarks/?#q=%s.

If you Google Search or something else is your default search provider, you can type b something and it will search your bookmarks for something instead of Google.

References

Posted on 2011-12-13 by asiam [See Chrome-DefaultToSearchBookmarks]

How to create an XML Document with JDOM

package org.siamnet;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class RssExampleDocument {

        public void main() {
                Element rootElement = new Element("rss");
                rootElement.setAttribute("version", "1.0");
                rootElement.setAttribute("encoding", "utf-8");

                Document xml = new Document();

                xml.setRootElement(rootElement);

                Element channel = new Element("channel");
                xml.getRootElement().addContent(channel);

                Element title = new Element("title");
                title.setText("This is a title.");
                channel.addContent(title);

                Element description = new Element("description");
                description.setText("This is a description.");
                channel.addContent(description);

                Element language = new Element("language");
                language.setText("en-us");
                channel.addContent(language);

                Element copyright = new Element("copyright");
                copyright.setText("2011");
                channel.addContent(copyright);

                Element lastBuildDate = new Element("lastBuildDate");
                lastBuildDate.setText("2011");
                channel.addContent(lastBuildDate);

                Element ttl = new Element("ttl");
                ttl.setText("30");
                channel.addContent(ttl);

                Element item = new Element("item");
                item.addContent(new Element("title").setText("Title"));
                item.addContent(new Element("description").setText("Description"));
                item.addContent(new Element("pubDate").setText("2011-11-11 11:11:11"));
                item.addContent(new Element("link").setText("http://www.example.com/"));
                channel.addContent(item);

                XMLOutputter xmlOutput = new XMLOutputter();
                xmlOutput.setFormat(Format.getPrettyFormat());

                System.out.println(String.format("xmlOutput = %s", xmlOutput.outputString(xml)));
        }
}

This will output,

<?xml version="1.0" encoding="UTF-8"?>
<rss version="1.0" encoding="utf-8">
  <channel>
    <title>This is a title.</title>
    <description>This is a description.</description>
    <language>en-us</language>
    <copyright>2011</copyright>
    <lastBuildDate>2011</lastBuildDate>
    <ttl>30</ttl>
    <item>
      <title>Title</title>
      <description>Description</description>
      <pubDate>2011-11-11 11:11:11</pubDate>
      <link>http://www.example.com/</link>
    </item>
  </channel>
</rss>

References

Posted on 2011-12-12 by asiam [See Java-ExampleCreateXmlDocumentWithJdom]

Simple HTTP Server with python

Change to any directory and execute the following command,

$ python -m SimpleHTTPServer

and instantly an HTTP server will be started on port 8000.

You can then go to any web browser and open http://localhost:8000 » and browse the directory via HTTP.

References

Posted on 2011-12-06 by asiam [See Python-SimpleHttpServer]






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.