ImageMagick: PDF to JPG Conversion Error

Problem

I tried to convert a PDF file to a JPG image using convert.exe from ImageMagick and got the following error:

$ convert Foobar.pdf Foobar.jpg
convert: `%s' (%d) "gswin32c.exe" -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dEPSCrop -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pnmraw" -dTextAlphaBits=4 -dGraph
icsAlphaBits=4 "-r72x72"  "-sOutputFile=C:/Users/Joe/AppData/Local/Temp/magick-p1m2jxT1" "-fC:/Users/Joe/AppData/Local/Temp/magick-tf9Qz_d_" "-fC:/Users/Joe/AppData/Local/Temp/magick-sa
5AGTv3" @ error/utility.c/SystemCommand/2093.
convert: Postscript delegate failed `Foobar.pdf': No such file or directory @ error/pdf.c/ReadPDFImage/645.
convert: missing an image filename `Foobar.jpg' @ error/convert.c/ConvertImageCommand/2970.

Solution

It looks like the input or output filenames are missing or have some problem. Look closer and it is an error caused by gswin32c.exe. ImageMagick uses gswin32c.exe from the Ghostscript package to convert PDF files. So, to fix this error make sure that:

  1. Ghostscript package is installed.
  2. The directory containing gswin32c.exe is in the PATH environment variable.

Point Distributions

A variety of point distributions are used in computer graphics and computational geometry to test out algorithms. Below are a few common point distributions and code to generate points in 3D. Assume that random() is a random function that returns a floating point value in the range (0.0-1.0).

Uniform Distribution

Uniform distribution is the most common distribution used in practice. Generate point using random values of x, y and z.

x = random();
y = random();
z = random();

Sphere Distribution

A sphere has only surface and no volume. So, we restrict points to the surface of a sphere.

do {
    x = random() - 0.5;
    y = random() - 0.5;
    z = random() - 0.5;

    d = ( x * x ) + ( y * y ) + ( z * z );

} while ( ( d < ( 0.45 * 0.45 ) || ( d > ( 0.5 * 0.5) ) ) );

Half Sphere Distribution

Calling it a half-sphere and not a hemisphere, since it does not have the planar surface in the middle. It is just a sphere sliced off about the middle.

do {
    x = random() - 0.5;
    y = random() - 0.5;
    z = random() - 0.5;

    d = ( x * x ) + ( y * y ) + ( z * z );

} while ( ( z >= 0.2 ) || ( d < ( 0.45 * 0.45 ) ) || ( d > ( 0.5 * 0.5) ) );

Ball Distribution

A ball is a filled sphere, it is full of points inside.

do {
    x = random() - 0.5;
    y = random() - 0.5;
    z = random() - 0.5;

    d = ( x * x ) + ( y * y ) + ( z * z );

} while ( d > ( 0.49 * 0.49 ) );

Empty Ball Distribution

Empty ball is the subtraction of a ball from a cube. Everything outside the ball is filled and the inside core is empty.

do {
    x = random() - 0.5;
    y = random() - 0.5;
    z = random() - 0.5;

    d = ( x * x ) + ( y * y ) + ( z * z );

} while ( d < ( 0.45 * 0.45 ) );

Ellipsoid Distribution


Ellipsoid has a surface but no volume inside.

a = 0.5;
b = 0.5;
c = 0.2;

do {
    x = random() - 0.5;
    y = random() - 0.5;
    z = random() - 0.5;

    d = ( ( x * x ) / ( a * a ) ) + ( ( y * y ) / ( b * b ) ) + ( ( z * z ) / ( c * c ) );

} while ( ( d <= 1.4 ) || ( d >= 1.5 ) );

Pancake Distribution

Pancake is a filled ellipsoid.

a = 0.5;
b = 0.5;
c = 0.2;

do {
    x = random() - 0.5;
    y = random() - 0.5;
    z = random() - 0.5;

    d = ( ( x * x ) / ( a * a ) + ( y * y ) / ( b * b ) + ( z * z ) / ( c * c );

} while ( d >= 1.0 );

C++: STL Stack

The C++ STL provides a simple stack. This is not a STL container, but is rather called a container adapter. That is, it is a simple interface built upon a real STL container.

Using STL stack is super-easy. Push elements using push(). To get the top element call top() and to pop the top element (without returning it) use pop(). So, typically top() and pop() would be used together. empty() is used to check if stack is empty.

#include <stack>
using namespace std;

stack<int> istack;
istack.push( 10 );
int i = istack.top(); // 10
istack.pop();
bool isEmpty = istack.empty(); // true

Visual C++: #pragma message

What if a programmer wants to draw attention to certain sections of code in certain source files? This could be for oneself or other team members. It could be certain work-in-progress, debugging or warning messages to watch out for. This could be for today or when one comes back to this code a long time later in the future.

One elegant and convenient way to achieve this is by using #pragma message. When the compiler finds a #pragma message, it outputs the message string to the Output window of Visual Studio. #pragma message strings can be left at the sections of code one wants to be signaled about. This way, even if a programmer comes back to some very old code, as soon as he compiles it the compiler signals him about certain information to watch out for in the code.

Using #pragma message is easy, like this:

// Foo.cpp
// ... Lots of Foo code ...

#pragma message( "HACK: Count of foo items updated! REMOVE later!" )
extern int debugCount;
++debugCount;

// ... Lots of Foo code ...

#pragma message can be tweaked to also output other information like the filename, line number and timestamp. Please see the MSDN article on #pragma message for more on that.

Note: The #pragma message output by the compiler can easily get lost in the Output window if the code produces lots of other warnings and errors. So, this is yet another reason why it is a good habit to make sure the code compiles with ZERO warnings and errors! ;-)

Visual Leak Detector: Investigate Memory Leaks in Visual C++

Memory leaks are a part of life in C++. By default, Visual C++ looks for memory leaks when the program is executed in Debug mode. If any memory leaks are found when the program exits, it reports them in the Output window like this:

Detected memory leaks!
Dumping objects ->
{1372} normal block at 0x04BE1058, 136 bytes long.
Data: < 3-kt*-k        > 9C 33 2D 6B 74 2A 2D 6B C8 11 BE 04 00 00 00 00
Object dump complete.
The program '[408] Foobar.exe: Native' has exited with code 0 (0x0).

The leak information that it spits out is about memory blocks. The information that can be gleaned from this output is:

  • Memory block allocation number: 1372
  • Memory block type: normal
  • Memory block starting address: 0x04BE1058
  • Memory block size: 136 bytes
  • First 16 bytes of memory block data

This memory leak detection by Visual C++, which is always enabled in Debug mode, is very useful since it will always find a leak if it exists. Once the leak is known however, it is hard to figure out the source of the leak by examining the above information.

More probing along this line can be done using the definitions and calls from crtdbg.h. This is quite cumbersome and cannot always point out the source of the leak. Comprehensive information on this can be found in the MSDN article on Memory Leak Detection and Isolation.

Visual Leak Detector

Visual Leak Detector (VLD) is an open-source alternative to investigate these memory leaks. Using it is very simple and straightforward:

  • Download and install VLD. The installer will prompt about adding its bin path (C:\...\Visual Leak Detector\bin) to the PATH environment variable. Accept it or add it manually yourself. Either way, you will need to log out and log back in for the addition to the PATH to take effect. vld.dll and dbghelp.dll, from the bin directory need to be available on the system path.
  • Make sure the Visual C++ project is in Debug mode.
  • Add the VLD include path (C:\...\Visual Leak Detector\include) to the Include Directories of the project.
  • Add the VLD lib path (C:\...\Visual Leak Detector\lib) to the Additional Library Directories of the project.
  • Add #include <vld.h> to any of the C++ source files in the project. This header will bring in vld.lib during the linking stage.
  • Rebuild the project and execute the compiled program in Debug mode. On program exit, VLD will print out the memory leak information it detected in the Output window.

The memory leak information printed by VLD looks like this:

---------- Block 1199 at 0x04BE1058: 136 bytes ----------
Call Stack:
d:\Foobar\FooLog.cpp (26): FooLog::getInstance
d:\Foobar\FooMain.cpp (75): FooMain::init
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (578): __tmainCRTStartup
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (403): WinMainCRTStartup
0x759A3677 (File and line number not available): BaseThreadInitThunk
0x770C9D42 (File and line number not available): RtlInitializeExceptionChain
0x770C9D15 (File and line number not available): RtlInitializeExceptionChain
Data:
9C 33 2D 6B    74 2A 2D 6B    C8 11 BE 04    00 00 00 00     .3-kt*-k ........
00 00 00 00    70 14 BB 6C    70 14 BB 6C    00 00 00 00     ....p..l p..l....
00 00 00 00    68 14 BB 6C    68 14 BB 6C    00 00 00 00     ....h..l h..l....
00 00 00 00    6C 14 BB 6C    6C 14 BB 6C    20 12 BE 04     ....l..l l..l....
00 00 00 00    CD 00 CD CD    00 00 00 00    01 CD CD CD     ........ ........
68 14 BB 6C    78 33 2D 6B    00 00 00 00    00 00 00 00     h..lx3-k ........
00 00 00 00    01 02 00 00    06 00 00 00    00 00 00 00     ........ ........
00 00 00 00    00 00 00 00    88 11 BE 04    5C 10 BE 04     ........ ....\...
00 00 00 00    20 CD CD CD                                   ........ ........

We can note the following information from this output:

  • The block allocation number output by Visual C++ leak detection and by VLD do not necessarily match.
  • The memory block address and size information of Visual C++ and VLD match. This confirms that this VLD information is about the same memory block as that reported by Visual C++. This is useful when the program has multiple memory leaks. The programmer can then match each of the Visual C++ memory leak to the corresponding VLD memory leak information.
  • VLD provides a lot of information: the entire call stack trace with function call names, source code filenames and line numbers. It also prints out a lot more data from the memory block.

By looking at the sourecode filename and the line number in it, the programmer should be able to get solid leads to the memory leak and hopefully be able to fix it. :-)

Visual C++: Iterator Checks and Slow STL Code

Visual C++ turns on a lot of checking on STL iterators when compiled in Debug mode. This is very helpful since any mistake with an iterator leads immediately to an exception with a helpful exception message. This can catch latent bugs much much earlier while programming.

However, this huge amount of security is sometimes not tolerable by everyone. For certain applications the debug mode with all the iterator checking turned on can be extremely slow, to the point of being useless. I faced a similar problem and so had to investigate to find the reason for the slow behaviour. I discovered that there are 2 mutually exclusive checking mechanisms in the STL of Visual C++: checked iterators and iterator debugging.

Checked Iterators

Checked iterators is controlled by the preprocessor definition _SECURE_SCL. SCL is Microsoft jargon for Standard C++ Library. So, this is a feature by Microsoft to provide some amount of minimal security on the usage of STL iterators. The overhead of _SECURE_SCL is so low that by default it is ON for both Release and Debug modes. So, _SECURE_SCL is rarely the cause of your program being slow. It should be left at its default options.

Iterator Debugging

Iterator debugging is a whole another beast. It involves a lot more intensive checking on the validity of iterators. It does this both when iterators are dereferenced and when containers change internally. This was implemented by Dinkumware, who are the creators of the STL implementation that Visual C++ ships with.

By default, iterator debugging is turned ON for Debug mode and OFF for Release mode. Typically it is not slow for Debug mode, but if the C++ code has a lot of loops over STL containers and uses iterators heavily, then it can make everything very slow. How slow can it get? This is the difference I saw in one of my programs compiled in Debug mode:

Iterator Debugging ON: 51.83 sec
Iterator Debugging OFF: 0.27 sec

Yes, iterator debugging was a jaw-dropping 192 times slower! Not just that, at ~52 seconds of execution, this program was unusable for my purpose!

Iterator debugging is controlled by the preprocessor definition _HAS_ITERATOR_DEBUGGING. To turn off iterator debugging, add _HAS_ITERATOR_DEBUGGING=0 to the Preprocessor Definitions in C++ → Preprocessor section of the project properties.

References:

  • STL Iterator Debugging and Secure SCL video on Channel 9 by Stephan T. Lavavej. A must watch video for anyone using STL on Visual C++. Stephan explains both Secure SCL and Iterator Debugging and how they are implemented internally in the library. Also explained is when and which of these options to turn ON or OFF.

Visual C++: Keyboard Shortcuts

Every programmer has his favorite keyboard shortcuts. Here are mine for Visual C++, from most used to least used, with some comments:

  • Jump to definition: F12
  • Jump to declaration: Ctrl + F12
  • Jump back (from any earlier jump): Ctrl + -
    • The above 3 keyboard shortcuts are my key tools to peek into and understand any C++ code.
  • Compile currently open .cpp file: Ctrl + F7
    • Every C++ programmer knows how frustratingly slow C++ compilers are! It is faster to first compile the currently modified file and proceed with a full solution build only if this succeeds. I typically keep compiling the current file while incrementally modifying a file and do a full build only much later when that part is completely coded.
  • Build solution: F7
  • Execute with debugging support: F5
  • Execute without debugging support: Ctrl + F5
  • Add or remove breakpoint on current line: F9
  • Find in entire solution and list in Find Results window: Ctrl + Shift + F
    • The normal find (Ctrl + F and F3) only jumps to one result and the user can jump around from there. I find the listing of all occurrences in a separate window much more useful. I can see all the files where it is used and also see one line of usage in them. This is very useful to understand and refactor code.
  • Full Screen: Alt + Shift + Enter
    • Visual Studio non-editor windows take too much space and combined with the Windows taskbar, they are all huge distractions while coding and debugging. So, I always work in full screen mode and switch back to normal size only to fix compile errors. But, the above default keyboard shortcut is hard to enter without causing side-effects, since it has Enter in it. So, I map this action to Ctrl + M, Ctrl + M instead. That is, keeping Ctrl pressed and press M twice. This is the keyboard shortcut for full screen in Eclipse. I find it easier to type and remember: M → Maximize :-)
  • Delete line: Shift + Del
    • Useful while deleting many lines of code, which happens almost all the time.
  • Add or remove bookmark: Ctrl + K, Ctrl + K
    • Easy to remember: bookmark ends with a K :-) I find it very useful to leave a breadcrumb trail of bookmarks on lines where I need to modify or check code.
  • Jump to next bookmark: Crtl + K, Ctrl  + N
    • To follow the breadcrumb trail of bookmarks.

TortoiseSVN: Right-Click Context Menus Not Available

Problem: You install TortoiseSVN and find that the right-click context menus and icon overlays are not available!

Solution: Check if you have installed 32-bit TortoiseSVN on 64-bit Windows 7. If yes, uninstall it and install the 64-bit TortoiseSVN.

Explanation:

TortoiseSVN installs itself as an extension to Windows Explorer. The 64-bit Windows Explorer on a 64-bit Windows 7 installation cannot load or communicate with 32-bit TortoiseSVN to display context menus relative to the selected files and directories.

C++: A Typical Class Layout

How the class is laid out in the header file is important for understanding it. This is the typical layout of the C++ classes I write these days:

// Foo.h
#ifndef FOO_H
#define FOO_H

// Headers
#include "Bar.h"

// Forward Declarations
class Joe;

// The Class
class Foo
{
    ////
    // Public Members
    ////

public:

    // *** Types

    typedef int FooValType;
    enum FooItemType
    {
        FOO_ITEM_0,
        // ...
    };

    // *** Methods

    // Constructors-Destructors
    Foo();
    ~Foo();

    // Get-Set-ers
    FooValType val() const;

    // Other methods
    void process( const Joe& ) const;

    // Friends
    friend std::ostream& operator << ( std::ostream&, const Foo& );

    ////
    // Private Members
    ////

private:

    // *** Data

    FooValType _val;

    // *** Methods

    void _process() const;
};

// *** Inline Functions

inline const FooValType& Foo::val() const
{
    return _val;
}

#endif // FOO_H

Book: The Mythical Man-Month

A staggering 35 years after it was first published The Mythical Man-Month: Essays in Software Engineering by Frederick R. Brooks Jr. remains the most important book a software engineer should read. I had been putting off reading the book for many years and finally gave in since it was one of the texts for the Software Engineering course I am teaching at university. My full review of the book can be found here.