- Prison Code Breaker Diary -

=> aka: Nhật Kí Code Tù

Categories

Showing posts with label Note. Show all posts

#include 

#define CreateFunction( FunctionName, Operator, Type ) \
  Type FunctionName( Type a, Type b ) \
  { \
   return a Operator b; \
  }

CreateFunction( Add, +, int )
CreateFunction( Sub, -, float )
CreateFunction( Mul, *, long )

using std::cout;
using std::endl;

int main( )
{

 cout << "CreateFunction(Add, +, int)"    << endl
   << "10 + 15 = "   << Add( 10, 15 )    << endl
   << "CreateFunction(Sub, -, float)"   << endl
   << "12.4 - 4.34 = " << Sub( 12.4, 4.34 )  << endl
   << "CreateFunction(Mul, *, long)"    << endl
   << "40 * 123 = "   << Mul( 40, 123 )   << endl;

 return 0;
}
The 3 lines
CreateFunction( Add, +, int )
CreateFunction( Sub, -, float )
CreateFunction( Mul, *, long )

will be expanded during compile time.

A well-known trick under GNU/C.

This site might be helpful to someone interesting in embedded programming:
+ http://www.embedded.com/books , including the books references

#!/bin/bash
#Valentin Heinitz, www.heinitz-it.de, 2008-11-13
#Reader for MS Windows 3.1 Ini-files
#Usage: inireader.sh
# e.g.: inireader.sh win.ini ERRORS DISABLE
# would return value "no" from the section of win.ini
#[ERRORS]
#DISABLE=no
INIFILE=$1
SECTION=$2
ITEM=$3
cat $INIFILE | sed -n /^\[$SECTION\]/,/^\[.*\]/p | grep "^[:space:]*$ITEM[:space:]*=" | sed s/.*=[:space:]*//

I got it from here.

Original Discussion -> [Cviet]

Code Relax #3 [ by rox_rook ]

- Write a class that allows operator overloading as long as possible and no syntax error.
Example, the following expression must be evaluated:

+++++++++++++++++++++++++++++++x; // must be valid and evaluated
- Language in use: C++

Solution [ by me ]

#include <iostream>

using namespace std;

template< typename X >
class MyOperator {
    private:
        X value;
    public:
        MyOperator( X _value = 0 ) : value(_value) { };
       
        MyOperator& operator+() {
            ++value;
        }
        MyOperator& operator++() {
            ++value;
        }

        X getValue() const { return value; }
};

int main( )
{
    MyOperator<int> x(7);
    ++++++++++++++++++++++++++++++++++x;
    cout << x.getValue() << endl;
   
    MyOperator<double> j(1.4);
    +++++++++++++++j;
    cout << j.getValue() << endl;

    return 0;
}


Evaluation
- The keyword 'operator' in C++ can be use to make cool things. I just found out about this 'til today testing it.

Original Discussion: -> [Cviet]

Code Relax #2 [ by rox_rook  ]

Given a template to get sum below

template< typename T >
inline
T calculate_sum_of_element( const T* i, const T* e )
{
    T sum = T( ); // a zero value for any type
    while( i != e )
    {
        sum += *i;
        ++i;
    }

    return sum;
}

Try this on int and char array

#include <iostream>

using namespace std;

template< typename T >
inline
T calculate_sum_of_element( const T* i, const T* e )
{
    T sum = T( ); // a zero value for any type
    while( i != e )
    {
        sum += *i;
        ++i;
    }

    return sum;
}

int main( )
{
    int int_ary[ 3 ] = { 1, 2, 3 };
    cout << calculate_sum_of_element( int_ary, int_ary + 3 ) << endl;
    
    char char_ary[ 3 ] = { 'a', 'b', 'c' };
    cout << calculate_sum_of_element( char_ary, char_ary + 3 ) << endl;
    return 0;
}

The result for int is 6 as expected; however, for char it supposed to be 97 + 98 + 99 = 294, but the character '&' is printed out.

Requirement
+ Re-write the given template function to make char data type return an int value
+ Language in use: C++

Solution [ by author, rox_rook ]

#include <iostream>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

template< typename T >
class Trait;

template< >
class Trait< char >
{
public :
    typedef int SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< short >
{
public :
    typedef short SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< unsigned >
{
public :
    typedef unsigned SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< double >
{
public :
    typedef double SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< int >
{
public :
    typedef int SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< typename T >
inline
typename Trait< T >::SumType calculate_sum_of_element( const T* i, const T* e )
{
    typedef typename Trait< T >::SumType SumType; // create shortcut, less typo
    SumType sum = Trait< T >::zero( );
    while( i != e )
    {
        sum += *i;
        ++i;
    }

    return sum;
}

int main( )
{
    char char_ary[ 3 ] = { 'a', 'b', 'c' };
    cout << calculate_sum_of_element( char_ary, char_ary + 3 ) << endl;
    double d_ary[ 3 ] = { 1.1, 2.2 , 3.3 };
    cout << calculate_sum_of_element( d_ary , d_ary + 3 ) << endl;    
    int i_ary[ 3 ] = { 1, 2 , 3 };
    cout << calculate_sum_of_element( i_ary , i_ary + 3 ) << endl;      
}


Evaluation
- It's freaking unthinking of....lol

Original Topic Discussion => [Cviet]

Relax #1 [ by me ]

Given 3 functions:

int add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }

Implement the following program:
+ Prompt user to input 1 of 4 strings: "add", "sub", "mul" or "end"; otherwise, start program again; "end" to exit.
+ Then, prompt user to input 2 numbers
+ Output result in this form

A [operator] B = [result]

Operator must be one of the following '+', '-' and '*', according to its own function, which means string "add" match add() function ....

Requirement
+ Must use function pointer
+ Call function according to its name, call add() if user prompt "add"....so on.
+ Language to use: C, C++

Demo output

> type 'add', 'sub', 'mul' or 'end': add
 a = 1
 b = 2
 1 + 2 = 3
> type 'add', 'sub', 'mul' or 'end': sub
 a = 6
 b = 4
 6 - 4 = 2
> type 'add', 'sub', 'mul' or 'end': mul
 a = 12
 b = 1
 12 * 1 = 12
> type 'add', 'sub', 'mul' or 'end': end

PROGRAM ENDED ! 


Solution #1 [ by me ]


Code in C as following:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE    1024

//
// #struct JFUNC
//
struct JFUNC {
    char *name;                 // function name
    int (*func)(int, int);      // pointer to function
    char sign;                  // sign of function, '+', '-', '*'
};

//
// #function        say()
// #purpose         format output with given params
//
void say( int (*func)(int,int), int _a, int _b, char _ )
{
    printf(" %d %c %d = %d\n", _a, _, _b, func( _a, _b ) );
}

//
// #function        input()
// #purpose         get input from user
//
void input( int *a, int *b ) {
    printf(" a = "); scanf("%d%*c", a);
    printf(" b = "); scanf("%d%*c", b);
}

//
// #function        add(),sub(),mul()
// #purpose         provide regular calculation
//
int add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }
//int div( int _a, int _b ) { return _a / _b; }

/* ENTRY POINT */
int main( )
{
    // init array of 3 structs
    struct JFUNC calc[3] = {
        { "add", add, '+' },
        { "sub", sub, '-' },
        { "mul", mul, '*' }
    };
    int a, b; // input from user
    int idx; // index of struct JFUNC array
    char *key = (char *)malloc( MAX_SIZE * sizeof(char) ); // string to get from user
    do {
   
        printf("> type 'add', 'sub', 'mul' or 'end': " );
        // get input, exactly 4 bytes
        fgets( key, MAX_SIZE, stdin );     

        // iterate through array to get correct function
        for( idx = 0; idx < 3; ++idx ) {
            // if function name is matched
            if( strcmp(calc[idx].name, key) == 0 ) {
                // get input
                input( &a, &b );
                // output
                say( calc[idx].func, a, b, calc[idx].sign );
            }
        }
    // end program if "end" prompted
    } while ( strcmp(key, "end") != 0 );
   
    // free memory
    free( key );
   
    printf(" PROGRAM ENDED!\n");
    // program return
    return 0;
}

Code in C++ as following

#include <iostream>

using namespace std;

//
// #struct JFUNC
//
struct JFUNC {
    string name;                    // function name
    int (*func)(int, int);      // pointer to function
    char sign;                  // sign of function, '+', '-', '*'
};

//
// #function        say()
// #purpose         format output with given params
//
void say( int (*func)(int,int), int _a, int _b, char _ )
{
    cout << " " << _a << " " << _ << " " << _b << " = " << func( _a, _b ) << "\n";
}

//
// #function        input()
// #purpose         get input from user
//
void input( int *a, int *b ) {
    cout << " a = "; cin >> *a;
    cout << " b = "; cin >> *b;
}

//
// #function        add(),sub(),mul()
// #purpose         provide regular calculation
//
int add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }
//int div( int _a, int _b ) { return _a / _b; }

/* ENTRY POINT */
int main( )
{
    // init array of 3 structs
    struct JFUNC calc[3] = {
        { "add", add, '+' },
        { "sub", sub, '-' },
        { "mul", mul, '*' }
    };
    int a, b; // input from user
    int idx; // index of struct JFUNC array
    string key; // string to get from user
    do {
   
        cout << "> type 'add', 'sub', 'mul' or 'end': ";
        // get input, exactly 4 bytes
        cin >> key;

        // iterate through array to get correct function
        for( idx = 0; idx < 3; ++idx ) {
            // if function name is matched
            if( calc[idx].name == key ) {
                // get input
                input( &a, &b );
                // output
                say( calc[idx].func, a, b, calc[idx].sign );
            }
        }
    // end program if "end" prompted
    } while ( key != "end" );
   

    cout << " PROGRAM ENDED!\n";
    // program return
    return 0;
}

Solution #2 [ by tauit_dnmd ]

/*
  UITs:UITstudent.com
  Coder:tauit_dnmd.
*/
#include<iostream>
#include<string>
using namespace std;
typedef int (*MyType)(int,int);

int  add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }

int (*GetFunctionVerSion1(string s,char &oper))(int,int) 
{
        if(s=="add"){oper='+'; return &add;}
        if(s=="sub"){oper='-';return ⊂}
        if(s=="mul"){oper='*'; return &mul;}
}

MyType GetFunctionVerSion2(string s,char &oper)
{
        if(s=="add"){oper='+'; return &add;}
        if(s=="sub"){oper='-';return ⊂}
        if(s=="mul"){oper='*'; return &mul;}
}

int main()
{
    int (*uitstudent)(int,int)=NULL;//define 
    int a,b;
    string myoperator;//operator
    char UITs;
    do
    {
        do
        {
            cout<<"type 'add' 'sub' 'mul' or 'end':"; 
            cin>>myoperator;
            if(myoperator=="add"||myoperator=="sub"||myoperator=="mul"||myoperator=="end") break;
        }while(1);
        if(myoperator!="end")
        {
            uitstudent=GetFunctionVerSion1(myoperator,UITs);//Or uitstudent=GetFunctionVerSion2(myoperator,UITs);
            cout<<"a= ";cin>>a;
            cout<<"b= ";cin>>b;
            cout<<"a "<<UITs<<" b = "<<(*uitstudent)(a,b)<<endl;
        }
    }while(myoperator!="end");
    cout<<"UITs:PROGRAM END!"<<endl;
    return 0;
}  


Solution #3 [ by QuangHoang ]

#include <iostream>
#include <string>
#include <map>
using namespace std;

typedef int (*func)( int, int );

int add( int _a, int _b ) { return _a + _b; }
int sub( int _a, int _b ) { return _a - _b; }
int mul( int _a, int _b ) { return _a * _b; }

map <string, func> fmap;
map <string, func>::iterator it;

void initMap()
{
    fmap["add"] = add;
    fmap["sub"] = sub;
    fmap["mul"] = mul;
}

bool result(string oper)
{
    bool ok = false;
    for ( it=fmap.begin() ; it != fmap.end(); it++ )
        if ( oper == (*it).first ) ok = true;

    if ( !ok ) return false;
   

    int a, b;
    cout << "a = "; cin >> a;
    cout << "b = "; cin >> b;

    cout << a << " " << oper << " " << b << " = " << fmap[oper]( a,b ) << endl;
   
    cin.ignore();
    return true;
}

string label()
{
    string lbl;

    for ( it=fmap.begin() ; it != fmap.end(); it++ )
        lbl += "'" + (*it).first + "', ";

    return lbl;
}

int main()
{
    initMap();
    string oper;

    cout << "> type " << label() << "or 'end': ";
    do
    {
        getline(cin,oper);
        if (oper == "end") break;  

        if (!result(oper))
            cout << "> retype " << label() << "or 'end': ";
        else cout << "> type " << label() << "or 'end': ";

    } while (true);

    cout << "\nPROGRAM ENDED !";
    return 0;
}


Solution #4 [ by rox_rook ]

#include <iostream>
#include <map>
#include <string>


int add( int a, int b ) { return a + b; }
int sub( int a, int b ) { return a - b; }
int mul( int a, int b ) { return a * b; }
int end( int a, int b ) { return 0;     } // dummy func

typedef int( *FUNC )( int , int );

int main()
{
    std::map< std::string, std::pair< char, FUNC > > _func;

    _func[ "add" ] = std::make_pair< char, FUNC >( '+', add );
    _func[ "sub" ] = std::make_pair< char, FUNC >( '-', sub );
    _func[ "mul" ] = std::make_pair< char, FUNC >( '*', mul );
    _func[ "end" ] = std::make_pair< char, FUNC >( ' ', end );

    std::string user_repl;
    int a, b;

    do {
        std::cout << "> type 'add', 'sub', 'mul' or 'end' : ";
        std::cin >> user_repl;
        if( user_repl == "end" )
            break;
        std::cout << "> 'a' 'b' : ";
        std::cin >> a >> b;
        std::cout << a << _func[ user_repl ].first << b << "=" << _func[ user_repl ].second( a, b ) << "\n";
    }
    while( 1 );

    return 0;
}


Evaluation

- Solution #1: My approach follows the traditions of C, calling function by name through a structure, which is mentioned in C-faq under section 20.6 ( Read C-Faq 20.6 )
- Solution #2: It's kinda handy in matching strings.
- Solution #3: mapping, but not really satisfy requirements.
- Solution #4: mapping using value of pair template, it's short, clear and understandable. I think it's the best solution under C++.

I accidentally found it here: http://bytes.com/topic/c/answers/561589-print-1-100-without-loops-c-c

#include 
#include 

void (*f[2])(int);

void
printnum(int n)
{
        printf("%d\n", n);
        int i;
        i = ++n <= 100;
        (*f[i])(n);
}

void
done(int n)
{
        exit(0);
}

int
main(void)
{
        int n = 1;

        f[0] = &done;
        f[1] = &printnum;

        printnum(n);

        return 1;
}


These functions are usually used when dealing with binary data: open, read, write, close, seek and binmode.

I've written this perl script to generate a random binary file:

#!/bin/perl -w

use strict;

use constant RANGE => 0xFF;

if( $#ARGV != 1 ) {
    print "Error: no argument input!\n";
    print "Usage: > perl $0 FILE_NAME MAX_BYTES\n";
    print "Example: > perl $0 data.bin 255\n";
    exit;
}

my $file = $ARGV[0];
my $max_bytes = $ARGV[1];

my $cnt = 0;

open FILE,">", $file or die $!;

while( $cnt < $max_bytes ) {
    print FILE chr(int(rand(RANGE)));
    ++$cnt;
}

close FILE;

print "Binary file '$file' ($max_bytes bytes) generated!\n";

binmode() is not in used, so how does it work? Because I generate random value in ASCII so I can easily convert it into its according character, then simply write into file. It does sound weird but it actually works! The case of using binmode() and just print the number, it doesn't write the binary as expected. I don't understand why ???? The next script is to read a binary file and print out the hex code of each character inside.
#!/bin/perl -w

use strict;

if( @ARGV != 2 ) {
    print
     "Error: wrong arguments input!\n",
 "Usage: > perl $0 FILE BYTES\n",
 "Example: > perl $0 data.bin 255\n";
    exit;
}

my $file = $ARGV[0];
my $bytes = $ARGV[1];

open FILE, "<", $file or die $!;
#binmode FILE;

my $cnt = 0;
while( $cnt < $bytes ) {
    read FILE, my $byte, 1;
    print  sprintf("%02X", ord($byte)). " ";
    ++$cnt;
}
close FILE;
print "\n";


I use read() to get each byte then re-format into hex then print().
I don't use binmode() but it still does work well.

So I think I just don't need binmode() even though it's a binary case.

It's been a while since MSDN get a new face. However, I prefer the old one because it's easier to navigate to what I'm looking for.

For PowerShell reference, it's right here: http://technet.microsoft.com/en-us/library/bb978526.aspx

There're 2 ways to run your VBScript or JScript under Windows, either through CScript.exe or WScript.exe
What's the difference about those two?
- They are all almost the same, just different in the way displaying the output. While CScript.exe displays output in a Console, WScript.exe display the output in a Dialog.

Well, when you run the script, the default host will be chosen certainly. But you can switch between them.

If you want CScript.exe to be the default host

cmd> CScript //H:CScript

or WScript to be the default one

cmd> WScript //H:WScript

It's included inside Windows Management Framework RC (released on 8/13/2009).

You can download it from here:
https://connect.microsoft.com/windowsmanagement/Downloads/DownloadDetails.aspx?DownloadID=21267

But I'm not sure this is the latest.

On exponentiation, don't take the number too big like: 10 ** 99999 ... otherwise, u will get unexpected result or 1.#INF

The remainder operator doesn't apply for floating-point number, but if you do then they all will be round-off into the closest integers, then apply the operator.

I'm talking about the conditional statement IF.
Here is the definition:

IF (exp) {
   (statement)
}
Try this example:
$age = 23; 
if ( $age == 23 ) {
   print "I am 23 years-old", '\n'
}
Certainly perl evaluates the expression is TRUE since $age is assigned to the value '23'.
How about this case:
if ( $age = 23 ) {
   print "I am 23 years-old", '\n'
}
Still you've got the result printed. But how do you explain what perl does to this evaluation?

1. First, $age is assigned to value '23'.
2. The expression is evaluted whether it is TRUE or FALSE, which means, $age is ZERO or non-ZERO. So, it's TRUE right here because '23' is definitely not '0'.
3. Statement 'print' is called.

Rewrite the explanation into the code itself:
$age = 23;
if ($age) {
   print "I am 23 years-old", '\n'
} 

If u try with constants assignment, u'll get error
if ( 20 = 55 ) {    
    print "is it ok?", '\n'
}

Found = in conditional, should be ==
(W syntax) You said

if ($foo = 123)

when you meant

if ($foo == 123)

(or something like that).

Can't modify constant item in scalar assignment
A fatal error (trappable)
You aren't allowed to assign to the item indicated, or otherwise try
to change it, such as with an auto-increment.

Same results but different operators mean differences.

I'm mentioning about the '=' and the '==' operators with different means, applied to all logical cases.

I used to install ActiveState Perl because I thought it's the best Perl distribution on Windows. However, several days ago I've found out that Strawberry Perl is also port to Windows.
After a try, I feel like Strawberry Perl is much more better than ActiveState Perl.
Like what?

- Well, ActiveState Perl is commercial, then you're limited to use only from its vendor repositories. It would be a trouble if you want to install some packages from CPAN to your system. Yes, very limited!
- On the other hand, Strawberry Perl is an open-source, community-developed package, very light and useful, supporting all the most needed package for programmers and developers. Yes, it's free! Additionally, you can access CPAN shell and install any package from CPAN easily. It's quick and convenient in many ways.

Programming .NET is one of the first thing I've learned myself long ago, but only available in Windows Operating System.
Somehow, the Mono Project has made .NET Framework become a cross-platform environment that you can freely programming .NET for Windows, Linux, MacOS...in that system directly. Also, you can write a .NET program for Linux under Windows and vice-versa. It's really a great achievement that Mono Project has reached. I expect that Mono Project will achieve more impressive goals with .NET technology in the future as it develops.
I write this guide as a journal in programming .NET under Linux environment by using Mono Project.
You may take this as a reference for Gtk#.

1 - Documentation and Reference:
Here the list that I read and reference from:
Gtk# Tutorial Page by Mono
Mono Documentation Library (equivalent to MSDN)
Mono: A Developer's Notebook (Edd Dumbill, Niel M. Bornstein) - A great book, worth to buy for two reasons:
+ It's the only book on Mono up to this time.
+ It's written as a developer's journal style, so it's really easy to catch the authors' mind concepts.

2 - Programming Gtk# Journal

Lesson 1: Say Hello
Lesson 2: Hello Gtk# (using Form)
Lesson 3: MonoDevelop IDE vs. manual text coding w/ commands. (to be updated...)


Feel free to comment!
Have fun!

There are some terminology that you need to know.

1. Malware
2. Virtual Machine
3. Snapshot
4. Disassembler
5. Portable Executable

If there is any more term related, I will post it here.

Have fun!

A note on x86 Registers

Intel x86's registers can be divided into several categories:

  • General-purpose registers
  • Segment registers
  • Program flow control registers
  • Other registers.
General-purpose registers include EAX, EBX, ECX, EDX, ESP EBP, ESI, and EDI. They are not all equal in their usage, and some instructions assign them special functionality. Segment registers are used to point to different seg-ments of process address space.Their functions are as follows: CS points to the beginning of a code segment; SS is a stack segment; DS, ES, FS, GS, and various other data segments, for example, the segment where static data is kept. Many processor instructions implicitly use one of these segment registers, so usually we will not need to mention them in our code. If you want to be more precise, instead of an address in memory these registers contain references to internal processor tables that are used to support virtual memory.

EIP: Extended Instruction Pointer. When you call a function, this pointer is saved on the stack for later use. When the function returns, this saved address is used to determine the location of the next executed instruction.

ESP: Extended Stack Pointer. This points to the current position on the stack and allows things to be added to and removed from the stack using push and pop operations or direct stack pointer manipulations.

EBP: Extended Base Pointer. This register usually stays the same throughout the execution of a function. It serves as a static point for referencing stack-based information such as variables and data in a function using offsets.This pointer usually points to the top of the stack for a function.

Reference from:
  • Buffer Overflow Attacks: Detect, Exploit, Prevent (by James C. Foster, Vitaly Osipov, Nish Bhalla, Niels Heinen)