Microsoft Word Macro – Change all images to same size (width and height) and add borderline to them

Often times you are required to write up some document in MS Word. And you have added bunch of images, and you need to add image borders and resize them all to the same size.
Here is the MS Word macro code to automate this:

Sub ChangeImageSizeAndBorder()
'
' ChangeImageSizeAndBorder Macro
'
'
Dim iShape As InlineShape

For Each iShape In ActiveDocument.InlineShapes
    With iShape
        .Width = InchesToPoints(2)
        .Height = InchesToPoints(1.5)
        With .Borders(wdBorderLeft)
            .LineStyle = wdLineStyleSingle
            .LineWidth = wdLineWidth050pt
            .Color = wdColorAutomatic
        End With
    End With
Next iShape

End Sub

The above code will set all borders – in case it doesn’t, apply .Borders part to wdBorderRight/wdBorderTop/wdBorderBottom;

I recommend the following book for MS Word automation:
Mastering VBA for Office 2010

For better writing I recommend this book:
Chicago Manual Style 16th Edition

Setting up perfect Development machine on Ubuntu 12.04

Often times you need a fresh copy of Linux to work with for a certain project, but you hate the process of setting it all up. My approach is to create VirtualBox appliance and to import it whenever I am dealing with a new project that requires a fresh copy of the system. I save my appliance to GoogleDrive and wherever I happen to find myself, I simply download the appliance, import it into my VirtualBox and I can work on my project immediately.

1. Installing VM on a VirtualBox
Go to http://www.ubuntu.com/download/desktop
Download appropriate 12.04 image
VirtualBox > Machine > New > Follow onScreen instructions.

2. Installing Guest Additions
Machine > Install Guest Additions
Restart
Switch to Seamless Mode

3. Settings – Change File displays to List View
Open Navigator
Edit > Preferences > View > View New folders Using: List View

4. Installing Yakuake
Open terminal

sudo apt-get install yakuake

Start Yakuake and use F12 from now on to open/close terminal.

5. Installing Chrome
Download Chrome from https://www.google.com/intl/en/chrome/browser/

sudo dpkg -i google-chrome-stable_current_amd64.deb
sudo apt-get -f install

List of chrome plugins to install:
1 – Xmarks
2 – Snap Links Lite
3 – Close tabs to the right
4 – Close tabs to the left
5 – Do not track me
6 – Google Dictionary
7 – Group tabs by domain
8 – Links extractor
9 – Maskme password manager
10 – Proxy Switchy
11 – Combine all tabs into one tab
12 – Page Ruler
13 – Advanced Rest Client
14 – Add Block Plus
15 – Google translate
16 – Window Resizer
17 – Resolution Test
18 – Web Developer

6. Installing Oracle Java 6 / Java 7 and switching between them

Download Java 7.0_40 from:
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html

Download Java 6.0_45 from:
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase6-419409.html#jdk-6u45-oth-JPR

sudo mkdir -p /usr/lib/jvm
sudo mv jdk-7u21-linux-i586.tar.gz /usr/lib/jvm
cd /usr/lib/jvm
sudo tar zxvf jdk-7u21-linux-i586.tar.gz
# for version 6
# chmod +x jdk-6u45-linux-x64.bin
# ./jdk-6u45-linux-x64.bin
# sudo mv /jdk1.6.0_45 /usr/lib/jvm
# sudo rm jdk-7u21-linux-i586.tar.gz # optional
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0_21/bin/javac" 1
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0_21/bin/java" 1
sudo update-alternatives --set "javac" "/usr/lib/jvm/jdk1.7.0_40/bin/javac"
sudo update-alternatives --set "java" "/usr/lib/jvm/jdk1.7.0_40/bin/java"
# sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.6.0_45/bin/javac" 1 # for version 6
# sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.6.0_45/bin/java" 1 # for version 6
# sudo update-alternatives --set "javac" "/usr/lib/jvm/jdk1.6.0_45/bin/javac" # for version 6
# sudo update-alternatives --set "java" "/usr/lib/jvm/jdk1.6.0_45/bin/java" # for version 6
sudo sublime /etc/profile

Append to the end of file:

JAVA_HOME=/usr/lib/jvm/jdk1.7.0_40 # jdk1.6.0_45
PATH=$PATH:$JAVA_HOME/bin
export JAVA_HOME
export PATH

Reload user profile:

. /etc/profile # source /etc/profile

7. Installing Sublime Text 2 – Package Managera, etc.

Download Sublime Text 2 from: http://www.sublimetext.com/2

tar xf Sublime\ Text\ 2.0.1\ x64.tar.bz2
sudo mv Sublime\ Text\ 2 /opt/
sudo ln -s /opt/Sublime\ Text\ 2/sublime_text /usr/bin/sublime
sudo sublime /usr/share/applications/sublime.desktop

Input the following

	[Desktop Entry]
	Version=1.0
	Name=Sublime Text 2
	# Only KDE 4 seems to use GenericName, so we reuse the KDE strings.
	# From Ubuntu's language-pack-kde-XX-base packages, version 9.04-20090413.
	GenericName=Text Editor

	Exec=gksudo sublime
	Terminal=false
	Icon=/opt/Sublime Text 2/Icon/48x48/sublime_text.png
	Type=Application
	Categories=TextEditor;IDE;Development
	X-Ayatana-Desktop-Shortcuts=NewWindow

	[NewWindow Shortcut Group]
	Name=New Window
	Exec=sublime -n
	TargetEnvironment=Unity

Change default editor:

sudo sublime /usr/share/applications/defaults.list

And replace all occurrences of gedit.desktop with sublime.desktop

Enter your licence:

—– BEGIN LICENSE —–
Company Name
Single User License
your-licence-code
—— END LICENSE ——

Install Package Manager – https://sublime.wbond.net/installation#st2
Press: Ctrl + `

Execute:

import urllib2,os; pf='Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler( ))); open( os.path.join( ipp, pf), 'wb' ).write( urllib2.urlopen( 'http://sublime.wbond.net/' +pf.replace( ' ','%20' )).read()); print( 'Please restart Sublime Text to finish installation')

Press Ctrl+Shift+P > Install
to start installing packages

Install plugins:

  1. SFTP
  2. TrailingSpaces
  3. Emmet
  4. InsertNums
  5. SideBarEnhancements
  6. HTML tidy
  7. Javascript tidy

Enter SFTP licence SFTP Package > User Settings > SFTP
{
“email”: “email@email.com”,
“product_key”: “your-licence-number”
}

Customize ST2 USer seetings – I like to trim trailing spaces on save: Preferences > Seetings-Default and set:
“trim_trailing_white_space_on_save”: true,

8. Installing Apache, MySQL and PHP

sudo apt-get update
sudo apt-get install mysql-server mysql-client apache2-mpm-prefork php5 libapache2-mod-php5 php5-mysql php5-gd

You will get prompted to enter the MySQL password for root, remember that password for later.

If apache2 somehow fails to start with a Segmentation Fault, remove /etc/apache2/mods-enabled/php4.*

To enable .htaccess overriding PHP options, you need to edit
/etc/apache2/sites-available/default
and change

AllowOverride None

to

AllowOverride Options

for Directory /var/www

sudo sublime /var/www/aha.php

Go to http://localhost/aha.php – If you get PHP info page – you have done it right.

9. Installing Eclipse

wget http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/kepler/R/eclipse-jee-kepler-R-linux-gtk-x86_64.tar.gz&mirror_id=189

tar xzf eclipse-jee-kepler-R-linux-gtk-x86_64.tar.gz
mv eclipse /opt/
sudo chown -R root:root eclipse
sudo chmod -R +r eclipse
sudo touch /usr/bin/eclipse
sudo chmod 755 /usr/bin/eclipse
sudo sublime /usr/bin/eclipse

Input the following:

	#!/bin/sh
	export ECLIPSE_HOME="/opt/eclipse"
	$ECLIPSE_HOME/eclipse $*

To create shortcut:

sudo sublime /usr/share/applications/eclipse.desktop

Input the following:

	[Desktop Entry]
	Encoding=UTF-8
	Name=Eclipse
	Comment=Eclipse IDE
	Exec=gksudo eclipse
	Icon=/opt/eclipse/icon.xpm
	Terminal=false
	Type=Application
	Categories=GNOME;Application;Development;
	StartupNotify=true

10. Installing MySQL WorkBench

Download MySQL Workbench from: http://dev.mysql.com/downloads/mirror.php?id=414356

sudo dpkg -i mysql-workbench-community-6.0.7-1ubu1204-amd64.deb
wget https://launchpad.net/ubuntu/+archive/primary/+files/libzip1_0.9.3-1_amd64.deb
sudo dpkg -i libzip1_0.9.3-1_amd64.deb
wget http://launchpadlibrarian.net/94808408/libmysqlclient16_5.1.58-1ubuntu5_amd64.deb
sudo dpkg -i libmysqlclient16_5.1.58-1ubuntu5_amd64.deb
sudo apt-get -f install
sudo /usr/share/applications/sublime mysql-workbench.desktop

Input the following:

	[Desktop Entry]
	Name=MySQL Workbench
	Comment=MySQL Database Design, Administration and Development Tool
	Exec=gksudo mysql-workbench
	Terminal=false
	Type=Application
	Icon=mysql-workbench
	MimeType=application/vnd.mysql-workbench-model;
	Categories=GTK;Database;Development;

11. Installing XCHAT

sudo apt-get install xchat

12. Installing VLC

sudo apt-get install vlc

13. Installing QbitTorrent

sudo add-apt-repository ppa:hydr0g3n/ppa
sudo apt-get update && sudo apt-get install qbittorrent

14. Setting up Python 3.x
By default you have Python 2.7.3 installed
You can install Python3 with:

sudo apt-get install python3

than you can call it with:

python3 -version

15. Setting up PyCharm IDE – Community edition is free
The PyCharm IED is state of the art Python IED and I love to use it. It is worth the money ($99) and if you are Python developer you can profit a lot. Besides commercial version, you are able to download community version. Commercial version has advantages such as working with modern web development frameworks, such as Django, Flask, Google App Engine, Pyramid, web2py and support for smart multi-language and cross-technology, covering Python, JavaScript, CoffeeScript, TypeScript, HTML/CSS, Cython, Template languages and more.
Go to http://www.jetbrains.com/pycharm/ – Download it, unzip it

16. Setting up PostgreSQL

apt-get update
sudo apt-get install postgresql postgresql-contrib
su - postgres
createuser --pwprompt

Now lets create a database and put some records into it and test if it works

createdb reufdb

Open psql console:

psql -h localhost reufdb reuf

Create a table and insert some records:

CREATE TABLE potluck (name VARCHAR(20), food VARCHAR(30), confirmed CHAR(1), signup_date DATE);
INSERT INTO potluck (name, food, confirmed, signup_date) VALUES('Muhamed', 'Halilovic', 'N', '2012-04-11');
INSERT INTO potluck (name, food, confirmed, signup_date) VALUES('Reuf', 'Reufovic', 'Y', '2012-04-11');

List out tables:

\dt

Select records:

SELECT * FROM potluck;

Update records:

UPDATE potluck set confirmed = 'Y' WHERE name = 'Muhamed';

Delete records:

DELETE FROM potluck WHERE name = 'Reuf' ;

Add columns to table and remove columns from table:

ALTER TABLE potluck ADD email VARCHAR(40);
ALTER TABLE potluck DROP email;

17. Connecting to PostgreSQL from Python
Go to http://python.projects.pgfoundry.org and download the python postgresql module. Unpack the download and do the following:

python3 ./setup.py install

Test it out:

import postgresql
db = postgresql.open("pq://reuf:qw@localhost/reufdb")
row = db.prepare("SELECT name, food, confirmed, signup_date FROM potluck;").first()
row()

18. Installing pgadmin

sudo apt-get install pgadmin3

CodeIgniter PDF Image Preview with Imagick

1. Application Setup – Requierments

Ubuntu 12.X+
LAMP
Imagemagick
Ghostscript
CI 2.1

2. Setting up LAMP and Imagemagick

In this section you can find instructions on how to set up LAMP on Ubuntu. Make sure you have set-up/installed all of these on the machine planned to be used in testing.

Perform these steps in the given order:

sudo apt-get install tasksel
sudo tasksel install lamp-server
sudo apt-get install php-pear
sudo apt-get install phpmyadmin
sudo apt-get update #(for update libraries, and packages)
sudo apt-get autoremove #(for remove obsolete things)
sudo apt-get install libmagickwand-dev #(for the libraries of ImageMagick)
sudo apt-get install imagemagick #(for the core class Imagick)
sudo apt-get install ghostscript #(if not already installed)
sudo apt-get install
sudo pecl install imagick #(for create the binaries, and conections in beetween)
sudo echo "extension=imagick.so" > /etc/php5/apache2/php.ini
sudo service apache2 restart

4. The Code

1. Unpack codeigniter instance under /var/www/ciupload directory.

2. Make sure /var/www/ciupload/uploads and /var/www/ciupload/uploads/image_preview are writeable:


chmod 777 /var/www/ciupload/uploads
chmod 777 /var/www/ciupload/uploads/image_previews

Create CI Controller:

upload.php

<?php
/**
 * www.reuf.ba
 *
 * A pdf to image thumnbials conversion class
 *
 * @package             Deafault
 * @author              Reuf
 * @copyright           Copyright (c) 2013, www.reuf.ba
 * @license             GPL 2.0
 * @link                http://www.reuf.ba
 * @since               Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

//Remove error reporting
ini_set('display_errors', 'Off');
error_reporting(0);
define('MP_DB_DEBUG', false);

// ------------------------------------------------------------------------

/**
 * Upload Class - converts pdf file into a set of thumnails based on different types of sizes
 *
 * @package     Default
 * @subpackage  None
 * @category    Controller
 * @author      Reuf
 * @link        http://codeigniter.com/user_guide/libraries/pagination.html
 */
class Upload extends CI_controller {

        /**
         * Constant that defines directory where pdf files should be uploaded
         */
        const PDF_UPLOAD_DIR = 'uploads/';

        /**
         * Constant that defines directory where image thumbnails should be generated
         */
        const IMAGE_PREVIEWS_UPLOAD_DIR = 'uploads/image_previews/';

        /**
         * Constructor
         *
         * @access      public
         * @param       array   initialization parameters
         */
        function __construct() {
            log_message('info', "Entering constructor");
            parent::__construct();
            // load helper
            $this->load->helper('form');
            log_message('info', "Exiting constructor");
        }

        /**
         * Gets rendered when initially called
         *
         * @access      public
         * @param       array   initialization parameters
         * @return      void
         */
        public function index() {
                // load view
                log_message('info', "Entering index page");
                $this->load->view('upload_form', array('error'=>''));
                log_message('info', "Exiting index page");
        }

        /**
         * Uploads a pdf file
         *
         * @access      public
         * @param       none
         * @return      CI view
         */
        public function do_upload(){
            log_message('info', "Entering do_upload method");
            $config['upload_path']=self::PDF_UPLOAD_DIR;
            $config['allowed_types']='pdf';
            $config['max_size']="20000";
            $config['overwrite']=TRUE; // Will overwrite files with same name
            $this->load->library('upload',$config);

            if (!$this->upload->do_upload()){
                    $error = array('error'=>$this->upload->display_errors());
                    $this->load->view('upload_form',$error);
            } else {
                    $data['upload_data'] = $this->upload->data();
                    $im = new Imagick($data['upload_data']['full_path']);
                    $data['number_pages'] = $im->getNumberImages();
                    $data['height'] = $this->input->post('height');
                    $data['width'] = $this->input->post('width');
                    log_message('info', "Upload data file name: ".$data['upload_data']['file_name']);
                    for($i=0; $i<$data['number_pages']; $i++) {
                        try {

                            $data['image_'][$i] = $this->convert_pdf_to_thumbnail( $data['upload_data']['file_name'], $i, $data['width'], $data['height']);
                            log_message('info', "Successfuly created image preview for pdf page: ".($i+1));

                        } catch (Exception $e) {

                            log_message('error', "There was an error converting pdf page to thumnail: ".$e);

                        }

                    }

                    $this->load->view('upload_success',$data);

            }

            log_message('info', "Exiting do_upload method");
        }

        /**
         * Converts specific page within a pdf into a preview thumnail.
         *
         * @access      protected
         * @param       $file_name - The filename of the PDF
         * @param       $page_number - the page inside of pdf which needs to be converted
         * @param       $width - the width to be used for scalling down
         * @param       $height - the height to be used for scalling down
         * @return      relative path to generated thumbnail
         */
        protected function convert_pdf_to_thumbnail($file_name, $page_number, $width, $height){
                log_message('info', "Entering convert_pdf_to_thumbnail method");
                try {

                    $im = new Imagick(self::PDF_UPLOAD_DIR.$file_name.'['.$page_number.']');
                    $im->setImageFormat('jpg');
                    $im->setCompression(Imagick::COMPRESSION_JPEG);
                    $im->setCompressionQuality(80);
                    $im->setImageBackgroundColor('white');
                    $im = $im->flattenImages();
                    $im->resizeImage($width,$height, Imagick::FILTER_UNDEFINED, 0.9, true);
                    $fileRelativeLocation = self::IMAGE_PREVIEWS_UPLOAD_DIR.preg_replace("/\\.[^.\\s]{3,4}$/", "", $file_name).'_'.$page_number.'_'.$width.'X'.$height.'.jpg';
                    $fileHandle = getcwd() .'/'. $fileRelativeLocation;
                    $im->writeImage($fileHandle);// Write to disk
                    $im->clear();
                    $im->destroy();

                } catch (Exception $e) {

                    log_message('error', "There was an error using Imagick library on given path: ".$e);

                }

                log_message('info', "Exiting convert_pdf_to_thumbnail method");

                return $fileRelativeLocation;

        }
}
?>

Create CI View-s:

upload_form.php

<?php
 echo $error;
?>

<?php
 echo form_open_multipart('upload/do_upload');

 $data_form = array('name'=>'userfile');
 echo "<br>Choose PDF:<br>";
 echo form_upload($data_form);
 echo "<br>Height:<br>";

$data = array(
 'name' => 'height',
 'id' => 'height',
 'value' => '300',
 'maxlength' => '100',
 'size' => '50',
 'style' => 'width:50',
 'type' => 'number',
 );
 echo form_input($data);
 echo "<br>Width:<br>";

$data = array(
 'name' => 'width',
 'id' => 'width',
 'value' => '300',
 'maxlength' => '100',
 'size' => '50',
 'style' => 'width:50',
 'type' => 'number',
 );
 echo form_input($data);
 echo "<br>";
 echo form_submit('', 'Preview')
 echo form_close();
?>

upload_success.php

<h3>
 Your file has been successfully uploaded, here is the preview:
</h3>
<ul>
<?php
 for($i=0; $i<$number_pages; $i++) {
 echo "<br><br>Page ".($i+1).":<br><img src=\"".base_url().$image_[$i]."\" style=\"border:1px solid #021a40;\"></img>";
 }
?>
</ul>
<p><a href="<?=base_url()?>index.php/upload">Preview another pdf</a></p>

3. Setting up Virtual Hosts (Optional)

https://www.digitalocean.com/community/articles/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts

4. Running

1. Open: http://localhost/ciupload/index.php/upload

2. Locate some pdf file and click Preview button.

5. Results

Chose pdf page:

UploadForm

The resulting preview:

Results

6. Resources

[Imagemagick download]

http://www.imagemagick.org/script/binary-releases.php#unix

[Ghostscript]

http://pages.cs.wisc.edu/~ghost/

[CodeIgniter]

http://ellislab.com/codeigniter