- Prison Code Breaker Diary -

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

Categories

Showing posts with label Programming. 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.

Linux bash shell provides 2 types of test:
+ ( -ot ) : is other than
+ ( -nt ) : is newer than


#!/bin/sh

if [ "$file1" -nt "$file2" ]
then
    echo -e "$file1 is newer than $file2"
else
    echo -e "$file1 is older than $file2"
fi

I write this bash script to automate the process of creating Linux libraries in C/C++

#!/bin/bash

clear

echo -e "##########################################"
echo -e "#     LIBRARY AUTO-CREATOR by [JaPh]     #"
echo -e "#========================================#"
echo -e "Usage: `basename $0` lib_name type path   "
echo -e "Example: "
echo -e " + creating libraries from hello.c in current directory"
echo -e " `basename $0` hello C . "
echo -e " + creating libraries from bye.cpp to '/opt/lib' directory"
echo -e "   `basename $0` bye C++ /opt/lib"
echo -e "Feel free to contact, pete.houston.17187@gmail.com\n"

ARG=3

if [ "$#" -ne "$ARG" ]
then
 echo -e "[?] wrong input arguments!"
 exit
fi

libname=lib"$1"

if [ "$2" == "C" ]
then
 filename="$1.c"
 compiler="gcc"
elif [ "$2" == "C++" ]
then
 filename="$1.cpp"
 compiler="g++"
else
 echo -e "[?] unknown filetype"
 exit
fi

echo -e "< Static Library: $libname.a >"
command="$compiler -Wall -c $filename"
echo -e "\$ $command"
if [ !`$command` ]
then
 echo -e ".created: $1.o"
else
 echo -e ".[?] cannot create object $1.o"
 exit
fi

echo -e "\$ ar -cvq $libname.a $1.o"
ar -cvq $libname.a $1.o
echo -e ".created: $libname.a"
echo -e "< Static Library '$libname.a' created ! >"

rm -f $1.o
echo -e "< Shared Object Library: $libname.so.1.0 >"
command="$compiler -Wall -fPIC -c $1.c"
echo -e "\$ $command"
if [ !`$command` ]
then
 echo -e ".created: $1.o"
else
 echo -e ".[?] cannot create object $1.o"
 exit
fi

command="$compiler -shared -Wl,-soname,$libname.so.1 -o $libname.so.1.0 $1.o"
echo -e "\$ $command"
if [ !`$command` ]
then
 echo -e ".created: $libname.so.1.0"
else
 echo -e ".[?] cannot create shared object $libname.so.1.0"
 exit
fi

ln -sf $libname.so.1.0 $libname.so
ln -sf $libname.so.1.0 $libname.so.1

echo -e "< Shared Object Library '$libname.so.1.0' created ! >"

if [ "$3" != "." ]
then
 mv $libname.* "$3"
 echo -e "[!] All files moved to $3"
fi


STATIC LIBRARY (.a)

+ Compile

$ gcc -Wall -c *.c
+ Create library
$ ar -cvq libtest *.o
+ List files in library
$ ar -t libtest.a
+ Linking with library
$ gcc -o executable-name prog.c libtest.a
$ gcc -o executable-name prog.c -L/path/to/library-dir -ltest


Shared Object: DYNAMICALLY LINKED LIBRARY

+ Compile object
$ gcc -Wall -fPIC -c *.c
+ Create shared object
$ gcc -shared -Wl,-soname,libtest.so.1 -o libtest.so.1.0 -o *.o
+ Move library to destination
$ mv libtest.so.1.0 /path/to/lib-dir
+ Allow naming convention like -ltest
$ ln -sf /path/to/lib-dir/libtest.so.1.0 /path/to/lib-dir/libtest.so
+ Allow run-time binding to work
$ ln -sf /path/to/lib-dir/libtest.so.1.0 /path/to/lib-dir/libtest.so.1
+ Testing executable file dependencies
$ ldd executable-file


Reference: Yo-Linux

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++.

libcurl - the multiprotocol file transfer library

libcurl is a free and easy-to-use client-side URL transfer library, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS, FILE, IMAP, SMTP, POP3 and RTSP. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos4), file transfer resume, http proxy tunneling and more!

libcurl is highly portable, it builds and works identically on numerous platforms, including Solaris, NetBSD, FreeBSD, OpenBSD, Darwin, HPUX, IRIX, AIX, Tru64, Linux, UnixWare, HURD, Windows, Amiga, OS/2, BeOs, Mac OS X, Ultrix, QNX, OpenVMS, RISC OS, Novell NetWare, DOS and more...

libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported, fast, thoroughly documented and is already used by many known, big and successful companies and numerous applications.

Homepage: http://curl.haxx.se/libcurl/

First, download and install cURL library package.
Then, use the utility 'curl-config' to get the compile options need for cURL program

$ curl-config --cflags
$ curl-config --libs

This is a simple program that retrieve a web page:

#include <stdio.h>
#include <curl/curl.h>
int main()
{
 CURL *curl;
 CURLcode res;
 
 curl = curl_easy_init();
 if(curl) {
  curl_easy_setopt(curl, CURLOPT_URL, "xjaphx.blogspot.com");
  res = curl_easy_perform(curl);
  
  curl_easy_cleanup(curl);
 }
 return 0;
}

Try to compile with this option:

$ gcc -o curl_simple curl_simple.c `curl-config --libs`
$ ./curl_simple

The header is needed in program `#include `, you can find its location by this


$ whereis curl
$ whereis curl.h

Probably, it will be /usr/bin/curl /usr/include/curl
While compile, you need to specify the linking library, that's why I set option `curl-config --libs`.
If you run this command alone


$ curl-config --libs
-lcurl
That's the result. Instead, you can compile like this

$ gcc -o curl_simple curl_simple.c -lcurl

Which gives the same result.

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.

Commonly, it's very hard for beginners to learn a new thing, especially this case, it's PowerShell. However, if you can see through its core, know the basics, and know how to search for helps or reference, it will be getting easier.
It took me about a week to learn the basis and understand the PowerShell concepts.
1. Using MSDN or MS Technet for PowerShell references.
2. Make use of some functions that provide helps.

There are two commands I use: Get-Command and Get-Help.

1. Get-Command: this function shows a list of commands being available at current session.
You can try by just typing: Get-Command, the list will show itself like this:

CommandType     Name                                 Definition                          
-----------     ----                                 ----------                          
Alias           %                                    ForEach-Object                      
Alias           ?                                    Where-Object                        
Function        A:                                   Set-Location A:                     
Alias           ac                                   Add-Content                         
Cmdlet          Add-Computer                         Add-Computer [-DomainName] 
Cmdlet          Add-Content                          Add-Content [-Path]  [-...
Cmdlet          Add-History                          Add-History [[-InputObject] 
Cmdlet          Add-Member                           Add-Member [-MemberType] 
Cmdlet          Add-PSSnapin                         Add-PSSnapin [-Name]  [...
Cmdlet          Add-Type                             Add-Type [-TypeDefinition] 

As you can see, there are 3 properties shown up: CommandType, Name, and Definition.
There are 3 types of commands: Alias, Cmdlet and Function.
+ Cmdlet: these are the core of PowerShell, it is the real command created to use.
+ Alias: these are just the other names of Cmdlets for instant call.
+ Function: these are the already written Cmdlets for instant access when you don't want to re-type the Cmdlet that are long.
Example, list all of commands that are Cmdlets:
PS> Get-Command -CommandType Cmdlet

2. Get-Help: this command provides help about PowerShell Cmdlets and concepts.
Example, if I want to get information about Get-Command, I  type
PS> Get-Help Get-Command

To get examples about the command,

PS> Get-Help Get-Command -examples

To get details about the coomand,

PS> Get-Help Get-Command -detailed

To get full info about the command,

PS> Get-Help Get-Command -full

Hope this post may help someone finding PowerShell a bit easier to learn!

All information about the environment variable is stored in '$env'.
When you want to retrieve info about any variable, you can follow the syntax

$env:<variable_name>

Here's an example how to use it:


PS C:\> $env:windir
C:\Windows

PS C:\> $env:path
C:\Perl\site\bin;C:\Perl\bin;C:\Program Files\ActiveState Perl Dev Kit 8.0\bin;
C:\Program Files\Borland\Delphi7\Bin;C:\Program Files\Borland\Delphi7\Projects\
Bpl\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;c:\Program Files\M
icrosoft SQL Server\90\Tools\binn\;C:\Web\PHP;C:\Web\PHP\ext;C:\Web\MySQL\bin;C
:\Program Files\QuickTime\QTSystem\;C:\GTK\bin;C:\Program Files\Microsoft Visua
l Studio 8\VC\bin;C:\Program Files\Java\jdk1.6.0_18\bin;C:\GTK2-16\bin;C:\Windo
ws\System32\WindowsPowerShell\v1.0\;C:\Program Files\GTK2-Runtime\bin;C:\BC5\BI
N;C:\Program Files\Nmap;C:\Program Files\Common Files\Nero\Lib\

It's a damn cool thing when you want to save something into HTML format.
Windows PowerShell provides this function through [ConvertTo-HTML] Cmdlets.

Example, if I want to save my list of current processes into HTML format

PS > Get-Process | ConvertTo-HTML | Out-File ProcessHTML.html

Another great thing is that it provides the way how you can format the output the HTML file through these 3 arguments: -head, -body, and -title.
Here, another example of formatting the output

$format_head = "<title> PROCESS LIST </title>"
$format_head += "<style>
"
$format_head += "TABLE { border-width:2px;border-style:solid}"
$format_head += "TH {border-width:1px;border-style:solid}"
$format_head += "TD {border-width:2px;border-style:solid}"
$format_head += "</style>"

$format_body = "<center> PROCESS LIST </center>"

Get-Process | ConvertTo-HTML -head $format_head -body $format_body | Out-File processHTML.html

By default, you cannot execute any remote PowerShell script (extension: PS1).
However, you can set execution right to run any script on your system by calling the Set-ExecutionPolicy command

PS C:\Data> Set-ExecutionPolicy RemoteSigned

Execution Policy Change
The execution policy helps protect you from scripts that you do not
trust. Changing the execution policy might expose you to the security
risks described in the about_Execution_Policies help topic. Do you want
 to change the execution policy?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y
PS C:\Data>


After that, you can run any .ps1 script as you like.

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.

In Perl, the floating-point number can be written in the form like this: 1E+01, 23.45e-02, 8.567E+32 ...
The letter 'E' or 'e' denotes the exponent.

Here the case:

my $var_1 = 11E+30;
my $var_2 = 11e30;
my $small_number = 0.00001; # or 1e-05

print "First case: $var_1 - $var_2 + $small_number = ".($var_1 - $var_2 + $small_number)."\n";
print "Second case: $var_1 + $small_number - $var_2 = ".($var_1 + $small_number - $var_2)."\n";
Here the result:
First case: 1.1e+031 - 1.1e+031 + 1e-005 = 1e-005
Second case: 1.1e+031 + 1e-005 - 1.1e+031 = 0
So how does it actually work?
I can explain it like this.
At line 5, $var_1 and $var_2 is eliminated down to 0 since they're equal in value, thus, adding a small value will be kept.
At line 6, $var_1 will be adding the $small_number, but because the value is too small compared to the other side, then it is considered as 0; so, the next substract to $var_2 will be 0 in result.

Check another example to see if the value is too small
my $too_small = 1e-999;
print "value is $too_small\n";
The result is 0 certainly, as I explained above.

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.

use constant
HACK
#???
=> 1
;($p, $h)
=
split ( ' ',
chr(112). "E". join('',

('T' . chr(0144) ) ) .chr(0x20) .
# <<END>>
join('', ('QmOt' , 'S'.###*&#^$(&
'uoH' ) )
#(*$)) WHAT THE HELL#$-~#msl39$#
)
;
qw [
/ 7h1s i5 5o 4nN0y1nG /
{ 4 rE4L }

]
;++$p;#
$h =
#--fosortc
(reverse $h
);chop($h); xJAPHx:
++$h
; print lc
join ( ' '
, (${\${\${\$p}}}
, ${\$h} )
)
;