mardi 14 mai 2019

AutoHotKey script for Conan C/C++ package manager

Conan is a powerful binary package manager (https://conan.io/), but under Window it has from my point of view a small issue. In fact it's not so related to Conan itself but maybe more to Visual Studio.

As soon as you start build a complex software component that has a huge folder depth, Visual Studio may have issue during its link step. And as Conan replace your source folder in its 'data' folder (often located in C:\Users\...\.conan\data\modulename\version\ .....) you may be forced to use a specific Conan feature to correctly build a module under Window.

That feature is call "short_paths".

class module(ConanFile):
              ..... modules settings....
              short_paths = True
              .......


With that attribute Conan used to build and locate your package in a folder with a shorter depth (example, C:\.conan\n0wd_4uo). In the original Conan local repository you will find files named ".conan_link".

C:\Users\.....\.conan\data\NAME\VERSION\...\...\package\ID\.conan_link

It's a simple text file, but when you need to browse your package content it will be cumbersome o open it and copy/paste the folder URI in the explorer.

What's why I created a small AutoHotKey script to simplify that task. If that script is running in the background, you just have to select a .conan_link file and press 'F1' to follow the link in your explorer window.

Easy to setup and it save a lot of time.


mercredi 6 décembre 2017

Trigger a Breakpoint and attach a debugger (Just-In-time Debugger)

Debugging program made to procress stdin data to stdout may be a mess, because piping data while running the debugger from Visual Studio is not easy.

A well known trick was to insert an interruption 3 into the code to trigger a break, see My favorite interruption

__asm int 3;

But as inline assembly is not supported by the x64 visual studio compiler, you may consider using the _debugbreak() function instead.

https://msdn.microsoft.com/fr-fr/library/f408b4et.aspx

#include
....

main() {  
   __debugbreak();  
}  

But I was facing an interesting  issue where that instruction was finally just terminate the program, instead of triggering a message box like the following



I found that there is several registry key which can be use to configure what we want to do in case of crash, break, etc...


  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug 
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
By default, in the AeDebug key, you should find a value "Debugger" set to "C:\WINDOWS\system32\vsjitdebugger.exe" -p %ld -e %ld.

So if you see that a break isnot trigger or catch by the Just-in-Time Debugger, just add another value called Auto, of type REG_SZ  and set its value to 1.

Regards, 


mercredi 11 mai 2016

Do it at compile time !


I found that picture this morning in the CodeProject daily mail and I was thinking about the answer I will give ! And for me the best is let the compiler work as much as possible.... so :







vendredi 17 avril 2015

Bash script: extract info from ffmpeg output.

Hi,
I already script that a several time and I think it's will be a good time to take a note and save a bit my mind for the next time !

When we use ffmpeg in some complex script in which we pipe decoded frame into another process i.e an encoder, it's really useful to get all input video and audio info. But from the ffmpeg -i output there is several regular expression that you can use:

  • Extract widthxheigth:
RESINFO=`$FFMPEGCMD -i $INPUTFILE 2>&1 | grep Stream | grep -oP ', \K[0-9]+x[0-9]+'`






  •  Extract frame-rate:
FPS=`$FFMPEGCMD -i $INPUTFILE 2>&1 | grep Stream | sed -n "s/.*, \(.*\) tb.*/\1/p"`





  • Split RESINFO into Width and Heigth
WIDTH=`echo $RESINFO | grep -oP '^\K[0-9]+'`
HEIGHT=`echo $RESINFO | grep -oP '\K[0-9]+$'`

Feel free to comment and add request/proposal if you think that there is a better/other way to do it !

mercredi 25 mars 2015

My favorite 'interruption' ...

Today, I made by mistake an interesting commit ! In fact, I'm working on a simple command line program and that program is design to process data read from the standard input and for my own convenience I added at the beginning of the main a piece of code that some of my teammate didn't know! So let me introduce to you the well known 'interruption 3'.....

#if defined(WIN32) || defined(WIN64)
  __asm int 3;
#endif


int is the asm instruction you use to generate a software interruption. Under windows the interruption 3 execution will trigger a breakpoint and from the outside you will have the usual popup saying:


click "debug" and select debugger you want use :)

It's a trick I often use when I want to also stop at start-up  or at a fixed code point during a dev phase.

mercredi 25 février 2015

Some 'tricks' about ::ftruncate (for windows & linux)

Hi, as today was an interesting development day, where I (with a good advice of one of my teammate) resolved a weird issue, I think it's the good time to write something on that topic because even after some 'Googling' I didn't find anything.

Let's simplify the context.

We just want to open a file, write some text and close it. Later that file will be open again, we will read the text already present and run some text manipulation and rewrite the file.

As the file size and the amount of data we used were small, we use a real simple implementation that we can summarize with the following code.


#include
#include
#include

#include
#include
using namespace std;

int main() {
int fd = -1;
fd = ::open("sample.txt", O_CREAT | O_RDWR, S_IRWXG | S_IRWXO | S_IRWXU);
char* txt = "a small text to fill the file";
::write(fd, txt, strlen(txt));
::close(fd);

fd = ::open("sample.txt", O_CREAT | O_RDWR , S_IRWXG | S_IRWXO | S_IRWXU);
struct stat data;
bool ret = 0 == ::fstat(fd, &data);
if(ret && data.st_size>0)
{
  char* buf = new char[data.st_size+1]; 

  size_t bytesRead = ::read(fd, &buf[0], data.st_size); 
  delete [] buf; 
}
::ftruncate(fd, 0); 
char* txt2 = "another small text to fill the file"; *
::write(fd, txt2, strlen(txt2));
::close(fd); 
 return 0;

Note the call to 'ftruncate' function, we use it to remove the file content. I know that in a real simple code I could have done that in a several others ways (i.e. ::open with O_TRUNC) but consider the fact that our file is shared across multiple process and that the real implementation is a bit more complex.

But let's continue.... The point is that is didn't work as expected. In fact, if the file type was 'ASCII text' after the 1st write, after the second write the file mode changed to 'data' and it wrote the text 'in-binary'. If we don't perform the 'read' or the 'ftruncate' the file type was still the same 'ASCII text'. The solution came from the following: if we 'read' the whole file the reach the end and it may be possible that the file descriptor is in a strange state where it can find the file mode. So we just added a 'seek' before the call to 'ftruncate' and the issues was gone.

i.e. lseek(fd, 0, SEEK_SET);

Easy, but really weird and I didn't find any question and page mentioning that kind of issue ! but there is one :)

That post is related to the question I asked here

vendredi 23 janvier 2015

ffmpeg: all concatenation methods don't lead to a correct file

As I used recently ffmpeg to concatente some really huge video files coming from a CamCorder, I discovered that even if they looks really similar the "Concat protocol" and "Concat demuxer"describe in "Concatenating media files" didn't lead to the same result and that the "Concat demuxer" approach introduced some weird PTS (presentation time stamp) at files boundaries.


As I spend several hour comparing the different way to do that, I can now recommend to use one of those 2 simple methods if you have to concatenate files with the following properties:
  • if they use the same container and codecs
  • if they are consecutive in a way their PTS should not have discontinuities

copy /B 1.MTS+2.MTS out.MTS

or

ffmpeg -i "concat:1.MTS|2.MTS" -an -vcodec copy out.ts
 It should be fast and it should not introduce weird PTS between 1 and 2 !

Observed with:

ffmpeg version N-68482-g92a596f Copyright (c) 2000-2014 the FFmpeg developers
  built on Dec 16 2014 02:53:08 with gcc 4.9.2 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libblu
ray --enable-libbs2b --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrw
b --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-aacenc --
enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-decklink --enable-zlib
  libavutil      54. 15.100 / 54. 15.100
  libavcodec     56. 15.100 / 56. 15.100
  libavformat    56. 15.105 / 56. 15.105
  libavdevice    56.  3.100 / 56.  3.100
  libavfilter     5.  3.101 /  5.  3.101
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  1.100 /  1.  1.100
  libpostproc    53.  3.100 / 53.  3.100

CMAKE script retro-compatibility

Hi,

I didn't post anything for a while, but in since few days, I found several topic for which I would like to write something (It's like a reminder for me ...)

I worked on product that we build on several different linux platform (Centos/Ubuntu/ etc ...). We use cmake and someone updated a script in a way it couldn't work anymore with older version of cmake (prior to 2.8.3). As I implemented a work-around, I wanted to share it because it was an annoying issue.

In cmake v2.8.3, a new "Useful variable" was introduced CMAKE_CURRENT_LIST_DIR.
If you had to use a cmake script in which that variable is used, cmake will not complain, it will just consider the variable as empty.

The work-around use the other function of cmake to initialize that value and let the rest of your script unchanged.

if("${CMAKE_CURRENT_LIST_DIR}" STREQUAL "")
message(STATUS "work-around to get the current folder for cmake version prior to 2.8.3")
get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
endif()


It's quit simple, first I test if the value is empty, and if it's true I use get_filename_component cmake command to extract the current folder path from the CMAKE_CURRENT_LIST_FILE cmake variable.


lundi 5 janvier 2015

C++ STL copy and lvalue

 

A common mistake when using STL object and algorithm is to assume implementation details. For example when we use the ostringstream class, it may be easy to assume that the object contain a string member and that the str() function must return that data. If we just think like that and don’t look deeper at the str() function declaration, we can write the following code and suppose that the output will be correct.

std::ostringstream os; os << 1234 << std::endl;

std::copy(os.str().begin(), os.str().end(), std::back_inserter(outputContainer));

But it will not be correct and you cannot rely on the compiler to detect the issue because the syntax is correct. We pass 2 iterator on a string, but the issue is that they are not iterator on the ‘same’ string.

The function declaration of str() is:

string str() const;
and it means 2 things:


  1. the ostringstream object will not be modified by the call

  2. the returned string object is an lvalue (return by copy).

you can also read that post in which that trap is fully detailed….


But to summarize, every call to str() return a different string so the the begin and end iterator we provided in the previous piece of code aren’t related to the same string.


The only correct way to manage that situation is to create a copy of the string like below or to use your own ostringstream version like describe in that post.


 


std::ostringstream os; os << 1234 << std::endl;


std::string acpy = os.str();


std::copy(acpy.begin(), acpy.end(), std::back_inserter(outputContainer));


The conclusion is that when you use a STL object or an algorithm take attention at the declaration because if you don’t you may fall in some traps.

vendredi 10 octobre 2014

Why sometimes I really hate MACROS



I have sometimes a mixed feeling about MACROS, but today I found 2 reason to hate them a bit more than I like them!

 

I fact I work with a library and I wanted to define a simple C++ mapping table to translate one on that library enum into other value (as int), so I wrote:

static std::map<LibName::Level, int> LibLevelToExternalLevel_Map = boost::assign::map_list_of(LibName::INFO, 40000)(LibName::TRACE, 30000)(LibName::WARNING, 60000)(LibName::CONTROL, 40000/*map on INFO*/)(LibName::ERROR, 70000);

Note that modern C++ provide the initializer list but I’m still in the old age, using C++9… the shame on me !


And to get back on my topic, as I compiled that code, one of my compiler started to complain. From GCC POV that code was ok but from VC98.

(380) : error C2589: 'constant' : illegal token on right side of '::'

As often in that case, you can suspect 2 things:


  • compiler bug
  • preprocessor bug

I try to find which “LibName::XXXX” label caused the issue and I found that ERROR was the root of the problem….. And after more investigation I found that a windows.h file was include at some point in the .h tree I used for that cpp file.


You may be not aware, but if you include <windows.h> a macro ERROR will be define and it was the root of my issue. A naming collision…. And it’s not the 1st time I had collision in that cpp file. The lib I use also has a class with an API (public function member) call GetMessage, but to build under windows I have to un define a macro for a while….

#ifdef WIN32
#ifdef _UNICODE
#define GetMessage   GetMessageW
#else
#define GetMessage   GetMessageA
#endif
#endif

So to conclude and keep in mind a good rules to prevent that kind of naming conflict or collision, I would just advice follow a simple convention no ‘full’ uppercase in identifier name (function, variable, enum, etc….)  see google coding style

jeudi 28 août 2014

C#: Enum and Attributes …

 

Today I had to update a system with a new kind of device. A device setup is a bit complex and when they start they look into a configuration file and try to transform/cast some “System.Configuration.ConfigurationManager.ConnectionStrings” into their corresponding Enum value in the system.

My Enum looks like:

public enum DeviceType
{
[Description("Apple IPod")]
IPOD = 1,
[Description("Apple iPad")]
APPLE_IPAD,
[Description("Google Glass")]
GGlass,
[Description("Surface")]
MS_SURFACE,
[Description("MS Surface PRO")]
MS_SURFACE_PRO,
[Description("Unknow")]
UNKNOW = 1000
}



After the addition of the “Google Glass” device … I quickly discovered that in several place I have to add an additional else in an already too long if-else sequence to handle the conversion of the string in an Enum value.

if(MyDeviceType == Device.IPOD.ToString())
MyDeviceType = DeviceType.IPOD;
else if(MyDeviceType == Device.APPLE_IPAD.ToString())
MyDeviceType = DeviceType.APPLE_IPAD;

etc...



If think it looks like that just because too many developers doesn’t master the language  they use and first I would say that from my point of view I’m not a master but just a developer aware some useful functionalities of C# and one I like is the template and how you can explore the types/values and check if they have attribute.


So to simply, improve the code and add a bit of flexibility in the configuration string we use I decided to add an “Helpers” method in that system to definitely solve that issue.

public static class Helpers
{
public static T GetValueFromDescription<T>(string description)
{
var type = typeof(T);
if (!type.IsEnum) throw new InvalidOperationException();
foreach (var field in type.GetFields())
{
if (field.Name == description)
return (T)field.GetValue(null);

var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute != null)
{
if (attribute.Description == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", "description");

}
}



As you can see, it’s really easy to read. If T is an Enum, we iterate over all field in the Enum. If the string match with a filed name (i.e “IPOD”, “APPLE_IPAD”) it’s OK, we return the field value. If it doesn’t match we look for a Description Attribute. Those attribute are really useful to provide a human readable description for Enum value, class data member, etc… So here if the config string match with a config attribute it’s also OK and due to that “IPOD” and “Apple IPod” return the same Enum value (Flexibility !).


And now if I replace all the existing if-else sequence by something like:

type = DeviceType.UNKNOW;
try
{
type = ExtensionMethods.GetValueFromDescription<DeviceType>(configuration_string);
}
catch (Exception ) //silently ...
{
type = DeviceType.UNKNOW;
}



It looks better from my point of view and next time we will a new device type all the mapping code is ready, no update to do !


The only thing I really regret is that all those cool device are only here for the example and I don’t have or work with them …. Snif Snif !

vendredi 1 août 2014

A coding exercise: The Caesar’s Cipher

 

As one of my holidays book is “Digital Fortress” from the very well-known Dan Brown (he is the author of “The Da Vinci code”) I found interesting to implement by my self some of the message encryption method he describe in that book.

 

To describe a bit the story, the “Digital Fortress” in an unbreakable cipher and it’s potential availability is a cataclysm for the NSA. And in its introduction the author present the NSA and what the crypto science is.

 

He say that the “Caesar’s Cipher” was one of the first known ciphering technic. And after looking Wikipedia it looks like the method he described wasn’t the same. The “Caesar’s Cypher” is typically a method based on a fixed alphabet shift, but he talked about a box based method using a “magic square” (search for the “Caesar’s box cipher”).

My code is really simple, in the first implementation I made I just represented spaces by ‘_’ but you can also choose to remove all spaces using:

inputMsg.erase(remove(inputMsg.begin(), inputMsg.end(), ' '), inputMsg.end());

The trick is to find the root X of the message length and after you draw a square of X*X, write your message character by character (1 per cell) from the top-left corner to bottom-right corner and transpose the table.

auto inL = inputMsg.size();
auto sqrtInL = (unsigned int)(sqrt(inL) + .5);
auto codeL = sqrtInL * sqrtInL;

out = string(codeL, '_');
for(auto ui = 0 ; ui < sqrtInL ; ++ui) {
for(auto = 0 ; uj < sqrtInL ; ++uj) {
if(ui*sqrtInL+uj < inL) {
out[uj*sqrtInL+ui] = (in[ui*sqrtInL+uj] != ' ') ? in[ui*sqrtInL+uj] : '_' ;
}
}
}

mardi 15 juillet 2014

Why my Win 7 in Virtual-Box was still running a time update ….. ?

 

That point puzzled me for at least 20minutes so I think I need to write something about it in order fix that in my memory.

I used to perform Product validation on Virtual Machines but when last Friday I had to do some test of how a license system is robust against system date & time change, I met a strange behavior!

I tried to change the date on the VM as on my own workstation (after disabling the Windows Time Service (a.k.a W32Time)) but every time I tried the clock got back in sync after few seconds and I didn’t know why. I was searching for a setting in my Virtual Box Host configuration but finally after some tests, I found that my VM was running a specific windows service called “VirtualBox Guest Addition Service”.

His description is really clear:

“Manages VM runtime information, time synchronization, remote sysprep execution and miscellaneous utilities for guest operating systems.”

So if like me you always setup the Guest addition for all VM you create, remember that service and that it use your host date & time to re-sync the guest date & time.

jeudi 24 avril 2014

The new VS’2013 may be a bit buggy …

In one hand I would say that moving from the old VS’2008 to the new VS’2013 was really fine, because even for a low-level programmer like me (in the project I’m working for, I only use C and C++) the editor’s improvements are really great !
But in another hand as in every software, there is still some bug. I only worked 2 or 3 days with VS’13 but I found 2 bug I reported through the MS Connect portal.
1) The C compiler has a terrible bug and I think that bug is a major issue, because it prevent the build of a tons of good C99 open source code.
for the VS’13 C compiler the following code is wrong and it report the following error:
typedef struct { int j; } test_t;

int f(test_t **p_pool, int i)
{
    if (i <= 0)
        return -1;

    test_t *pool;   
    *p_pool = pool;

    return i;
}



and the error is : 'test_t' : illegal use of this type as an expression

in fact, it looks like the compiler fails to interpret test_t as a type if the if-then statement body before isn’t surrounded by a some {}, for any other basic type, I mean int, char etc…. there is no problem but with all defined type containing “_t” (size_t, prtrdiff_t, uint8_t, etc….) it fails !

A workaround if to rewrite the code as:
typedef struct { int j; } test_t;

int f(test_t **p_pool, int i)
{
    if (i <= 0) {
        return -1;
    }

    test_t *pool;   
    *p_pool = pool;

    return i;
}



But it’s a pain to do that on a huge C/C99 code base.

Updated 2014 April 29th: An answer from MS dev team say that a fix will be available with the next update ... Good to hear!

2) the project property page has been improved with several new option, but switching from Debug to Release configuration directly from the property page may be disappointing, see below what’s may happen when you are doing a that.

Step to reproduce:


  • open a C/C++ project configuration property pages

  • switch the Configuration (Debug to Release or vice-versa)

  • now select another entry in the property tree and look. Below for example I was initially in Release / on C/C++->Preprocessor, I first switched to Debug and clicked on Language.

VS2013PropertyPagesBug1

Hopefully if you switch-back or if you close the pages and re-open then directly with “Debug” Configuration, the option will be back !

mercredi 16 avril 2014

The worst optimization I ever made….

As a programmer I often try to simplify the code and reduce the number of operation, but few days ago I made a big mistake.

In a video processing system, I replaced the following line, we use for each frame to compute its Presentation TimeStamp (a.k.a its PTS):

curr_pts = first_pts + nb_frame * duration;

by a simple addition

curr_pts += duration;
and curr_pts was initialized with first_pts.

Now let say that all those values are floating point number (double or float).
In the floating point number world, those 2 code aren’t really equivalent due to the error accumulation.

That problem is well known and a solution to minimize the error is the Kahan’s summation algorithm.

Take a look here on Ideone at a small test code I made to demonstrate it…..

But basically if we compute the delta between the 1st version and the 2nd version, we get 3.14042e-05 and with the Kahan’s algorithm we get only a delta of 1.74623e-09.

A big mistake and a big reminder that floating point computation aren’t so easy ….

lundi 7 avril 2014

Class/Struct definition local to a function.


You may know or not that defining a class or struct inside a function is possible but you may not be aware of all the issue you will meet when using that with the old C++98.
First thing, if you are using C++11 you can pass away, because in all case that feature will be correctly handle by recent compiler and debugger.
Now if your are still using a C++98 compiler or an old GCC, stay here and read the following:)

Definition in a function

In most case the following code will be Ok.

int function() { 
   typedef struct myStruct { 
       int num; 
       myStruct (int n): num(n){} 
       myStruct(const myStruct&amp; ro):num(ro.num){} 
    } mystruct_t; 

  mystruct_t t(2);

  return t.num;
} 


But want will happened if you try to use that struct with an STL’s container, like vector, deque, etc….. Example

int function() { 
   typedef struct myStruct { 
       int num; 
       myStruct (int n): num(n){} 
       myStruct(const myStruct&amp; ro):num(ro.num){} 
    } mystruct_t; 

  std::deque<mystruct_t> dq(10, mystruct_t(2));
  
   return dq[0].num;
} 

In fact here we have 2 different scenario:
  1. you are using GCC and it will not compile, because it’s not a C++98 compliant code
  2. you are using VC++2008 and it will compile, but you will meet weird debugger behavior on that piece of code.

Explanation

In C++98, you cannot use local class or struct with template type. This restriction is part of the standard. The reasoning was originally that local structures don't really have a names and thus it would be impossible to instantiate a template with them.

So as said if VC++2008 allow that code to compile, you will not be able to see what you have in your deque… Like in the snapshot below.

DebuggerError

My conclusion

Try to avoid that kind of code until you get the new C++11, because the portability across platform is not guarantee by the standard and that debugging and maintaining them is really hard. Define your class or struct outside of the function.

jeudi 13 mars 2014

Step-by-step through C++ Template

As some of my teammate always complain that template-based code are really hard to understand and that they would prefer coding without, I will try here to explain how it works and propose some complexity-growing example.

NOTE1: that post will be periodically update....
NOTE2: that post/tutorial is design in a way to can do all exercise without local compiler, I wrote a solution using Ideone, so create your account and write your own solution for all exercise.

A first look at the template syntax <> and their usage:

We using template and/or writing template you "can" meet the < CONTENT > syntax
Where Content can be:
  • class T / typename T
  • A data type, which maps to T
  • An integral specification
  • An integral constant/pointer/reference which maps to specification mentioned above.

1st Example

Imagine we want a function to multiply by 2 an integer

int mulByTwo(int v) { return v*2;}

And we can write int I = mulByTwo(2);

Now we also want mulByTwo but for float and we avoid code duplication.
Question: Write only one function MulByTwo to deal with:

int I = mulByTwo(2);
double D = mulByTwo(2.0);

Solution: here

Observe basic/simple "type deduction" error message

Now using the 1st example, what's happen if you call:
string S = mulByTwo("blahblah....");

Now build a function Sum, range-based to deal with iterator and pointer of any kind !

Tips: an iterator is just a simple base class implementing some operator like: ++,--,+=,-=,*, ->, [], etc...

Add the end with only 1 function, you should be able to execute:

int main() {
    int testArray[5] = {0,1,2,3,4};
    vector v = {0, 1, 2, 3, 4};
    vector s = {"hello", " ", "world"};
  
    cout << Sum(v.begin(), v.end()), cout << endl;
    cout << Sum(testArray, testArray + sizeof(testArray)/sizeof(testArray[0])), cout << endl;
    cout << Sum(s.begin(), s.end()), cout << endl;
  
    return 0;
}


Solution: here

How to use integral template

as for type deduction, the compiler will prepare everything at the compilation time.

Example: template&ltint&gt struct example { static double value = N * 2.0; }
If we write: cout << example&lt5&gt::value;

Exercise: Use that to compute factoriel&lt5&gt at compile time
Solution: here.

------ > followings section are under construction <------------------------ br="">

Solving ambiguity / Explicit Template Arg Specification

 

Default template  argument


Template and Specialization




vendredi 7 février 2014

char ** conversion to string

First, I would say it was a long time without posting anything, but I’m a bit in trouble in my personal life. And finally today as I was working on a command line implementation I realize that it’s a good practice to log (wherever you want …) the command line argument used to run a command line executable.

And as I was writing the code to do that, I was thinking that some developer may have create some complex code with loop display the command line argument that we have in argv. But in fact if you can use C++ STL and also the powerful BOOST Framework, it use only 2 lines of code (or even less).

So let start, first cmd line arguments are from the main function point of view an array of char*. So the 1st thing to do convert that in the C++ world.

vector<string> cmdline(argv+1, argv+argc);

Ok now we have STL object we all know on which we can easily iterate to concatenate each string and insert a delimiter (a simple space “ ”). But instead of using a complex loop I prefer using an efficient BOOST string algorithm call join.

#include "boost/algorithm/string.hpp"

….

string cl = boost::algorithm::join(cmdline, " ")

now you can dump the argument passed to your command line with a cout or any logging system you want.

And have a nice weekend.

vendredi 27 décembre 2013

C++: How to handle exception in CTOR

Yesterday I was reading that thread on Linkedin, and I realized once again that the exception handling in/or around a constructor(CTOR) is still an obscure topic as only one commenter mentioned the correct try-catch form for CTOR that can handle every exception even those coming from the initialization list.
The main problem when an exception occur during a CTOR is what have we to do for cleaning memory allocated on the heap.
To summarize the easiest way to handle exception, I produced the following example.

The output will be (I added some comments:
  • object_t CTOR ==> object_t allocation in our initializer list put in a smart_ptr (1)
  •  test_t CTOR ==> here we enter in the test_t CTOR Impl
  • object_t CTOR ==> we allocated a new object (2)
  • … here we have thrown the exception
  • object_t DTOR ==> the smart pointer object is on the stack, so the stack unwinding run and the memory allocation (1) is cleaned
  • here we handle our dynamic allocation ==> we are now in the CTOR catch section, as we have correctly ordered our data member we can check `if (ptr != nullptr)` and delete it if needed.
  • object_t DTOR ==> now the memory allocation (2) is released.
  • exception just to test... ==> as we have and should always RETHROW the exception, we catch it!

Conclusion: If we based all our class on that model, there is no reason anymore to fear about memory leaks.

mardi 24 décembre 2013

Use Beyond Compare as SVN diff tool under Linux

Today a quick note on that topic as I extended my own configuration with that tricks. BeyondCompare is a well known tool to compare and merge different  version file.

I used it a lot combined with ToirtoiseSVN, but as I worked more and more under linux using Remote Workstation, I would also use it. But I mainly work on remote workstation using a putty prompt. I will not describe here how to setup bcompare on a linux workstation, but it’s the 1st thing todo.

Next you have to follow my previous post to redirect the all X application to your local (I mean Windows 7 in my case) X11 server.

Now when you run “svn diff” on a file, you expect to use bcompare. To achieve that goal, follow me step by step.

cd ~

touch .subversion/bcompare_svn.sh

nano .subversion/bcompare_svn.sh

COPY/PASTE the folllowing in that script:

#!/bin/bash

/usr/bin/bcompare $6 $7 &

exit 0

Set execution permission

chmod 755 .subversion/bcompare_svn.sh

nano .subversion/config

Add that line just after “# diff-cmd = diff_program (diff, gdiff, etc.)”


diff-cmd=/home/YOURFOLDER/.subversion/bcompare_svn.sh

And done !

Now at each svn diff  command you start, BeyondCompare will start and display on the own PC.