Thursday, 26 April 2018

python - The message packer reads a string

The message packer reads a string

You need to implement a Message Packer. The message packer reads a string

Rules:

  • adds two chars ZZ to mark the beginning of the message
  • add number 0 to mark the end of the message.
  • The input string is reversed inside the message.
  • If the input string contains char Z then it is replaced by # in the message. The lower case character z is retained
  • If the input string contains numeric character 0 then it is replaced by $.
  • Only lower case letter ([a-z]), upper case letter ([A-Z]) and numeric characters ([0-9]) are accepted. If the string contains any other characters an error message Invalid String
  • Maximum number of characters accepted in the string is 8. If the number exceeds 8 then Exceeded Limit   is output

Sample:

  • Input : You need to read a string from STDIN.
  • Output :  Message Packed as per rules above or Invalid String or Exceeded Limit is  printed.

  • Input: PQRS
  • Output: ZZSRQP0

  • Input: ABbcZdz
  • Output: ZZzd#cbBA0

  • Input: X1340yZ
  • Output: ZZ#y$431X0

  • Input: AB*D1$34
  • Output: Invalid String

  • Input: ABCD12345
  • Output: Exceeded Limit

Program:

def main():
    message = raw_input("Enter value :")

    count = 0
    reverse = ''.join(reversed(message))    # Reversed the string , must need join

    lis = list(reverse)          # Reverse the string

    lengh = len(reverse)
    if lengh > 8:                # Length should be less than 8
        print "Exceeded Limit"
        return

    count = 0
    for char in lis:
        if char == 'Z':
            lis[count] = '#'
        elif char == '0':
            lis[count] = '$'
        elif not (char.isupper() or char.islower() or char.isdigit()):
            print "Invalid String"
            return
        count = count + 1

    lis.append('0')
    lis = ['Z'] + lis                 # Append the Z to the begging of the list
    lis = ['Z'] + lis

    result = ''.join(lis)            # Convert list to the string

    print result

main()

Output:

acp_python$ python messagePacker.py
Enter value :ABbcZdz
ZZzd#cbBA0
acp_python$ vi messagePacker.py
acp_python$ python messagePacker.py
Enter value :X1340yZ
ZZ#y$431X0
acp_python$ python messagePacker.py
Enter value :AB*D1$34
Invalid String
acp_python$ python messagePacker.py
Enter value :ABCD12345
Exceeded Limit

python - Password validity checker using python

Password validity checker using python


  • You need to implement a password validity checker.  A password is valid if all the given rules are satisfied, else it is invalid.
    •  At least 1 (one) lower case letter ([a-z]) is present
    •  At least 1 numeric character ([0-9]) is present  
    •  At least 1 (one) upper  case letter ([A-Z]) is present
    •  At least 1 character from [$#@] is present
    •  Minimum and Maximum length allowed must be 6 and 12 respectively
  • Input : You need to read a string from STDIN and check if it is a valid or invalid password.
  • Output : The string valid or invalid printed.

  • Test Cases:

    • Input: ABCDa$$$$$56
    • Output: valid

    • Input: 12345abcd111
    • Output: invalid
    • Input: 2w3E*
    • Output: invalid

Program:

def main():
    password = raw_input("Enter value :")

    digit = 0
    upper = 0
    lower = 0
    special = 0
    flag_len = 0

    for char in password:
        if char.isdigit():
            digit = 1
        if char.isupper():
            upper = 1
        if char.islower():
            lower = 1
        if char == '$' or  char == '#' or char == '@':
            special = 1

    length = len(password)
    if length >= 6 and length <= 12:
        flag_len = 1

    if digit and upper and lower and special and flag_len:
       print "valid"
    else:
       print "invalid"

main()


Output:

python$ python passwordVali.py
Enter value :Velraj
invalid
python$
python$
python$ python passwordVali.py
Enter value :Velraj12#
valid

Monday, 23 April 2018

how to run system command in c

how to run system command in c

  • Use system( ) to run the command if input and output are not important.
  • Use popen( ) if control on either input or output is needed.

System:

  • system() is used to invoke an operating system command from a C/C++ program.
  • int system(const char *command);
    • stdlib.h  is needed

  • Using system(), we can execute any command that can run on terminal if operating system allows. 
  • For example, we can call system(“dir”) on Windows and system(“ls”) to list contents of a directory.

Example Program:

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

int main () {
    char command[256];

    strcpy( command, "ls -l" );
    system(command);
   
    return 0;
}

Output:

sample$ ./a.out
total 156
-rw-rw-r-- 1 labuser labuser     159 Dec 18 21:59 '
-rw-rw-r-- 1 labuser labuser     338 Aug  3  2017 ]
-rw-rw-r-- 1 labuser labuser    1035 May 16  2017 access.c
-rwxrwxr-x 1 labuser labuser    8688 Apr 23 21:52 a.out
-rw-rw-r-- 1 labuser labuser     231 May 16  2017 array_init.c
-rw-rw-r-- 1 labuser labuser     585 May 19  2017 array_size.c
-rw-rw-r-- 1 labuser labuser     347 Aug 30  2017 assert.c
-rw-rw-r-- 1 labuser labuser     992 Jan 31 21:14 backtrace.c


Friday, 6 April 2018

How to use gprof to generate gmon.out while running the program

How to use gprof to generate gmon.out while running the program

  • The function "monstartup" is used to reinitialize the data block used by gmon to collect profile data.
  • The function "_mcleanup"  writes profile data to gmon.out
  • Change the current direct to /tmp to place the gmon.out to the default folder /tmop
  • After finish the test revert the current folder.
  • Send the SIGUSR2  signal to the process to generate the gmon.out file.
  • Generate the gmon.out file
    • send the signal using below
      • $kill -s SIGUSR2 26908
  • See the output in below folder
    • $cd /tmp

Example Program:

Program file 1: gprof_test-signal.c

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


#include <dirent.h>
#include <sys/gmon.h>
#include <signal.h>
#include <string.h>

void write_gmon_out_file();
void sigusr2_handler(int sig);
void gprof_init(void);

/* Beginning and end of our code segment.  */
extern void _start (void), etext (void);

/*
 * This function uses APIs from the gmon library which is part of the
 * the standard glibC library, to force write the profile data.
 * The function "monstartup" is used to reinitialize the data block
 * used by gmon to collect profile data.
 * The function "_mcleanup"  writes profile data to gmon.out
 */
void write_gmon_out_file (void)
{
    char *gmon_dir = "/tmp";
    char originalDir[256];

    if (getcwd(originalDir, 256) == '\0') {
        printf("Failed to get original working directory... \n");
        memset(originalDir, 0, 256);
    }
    else {
        printf("Original Dir = %s \n", originalDir);
    }

    if (chdir(gmon_dir) == 0) {
        printf("Successfully changed to dir = %s \n", gmon_dir);
    }
    else {
        printf("Failed to change to dir = %s \n", gmon_dir);
    }

    _mcleanup();
    monstartup((unsigned long ) &_start, (unsigned long ) &etext);

    if (originalDir[0] != 0) {
        printf("Switching to original working dir ...\n");
        chdir(originalDir);
    }

    return ;
}

void sigusr2_handler(int sig)
{
    printf("Received Signal: %d\n", sig);
    write_gmon_out_file() ;
    signal(SIGUSR2, sigusr2_handler) ;
}
void gprof_init(void)
{
    signal(SIGUSR2, sigusr2_handler) ;
    printf("GPROF SIGNAL HANDLER INITIALIZED\r\n");
    sleep(5);
}
void new_func1(void);

void func1(void)
{
    printf("\n Inside func1 \n");
    int i = 0;

    //exit(0);
    sleep(10);
    for(;i<0xffffffff;i++);
    new_func1();

    return;
}

static void func2(void)
{
    printf("\n Inside func2 \n");
    int i = 0;

    for(;i<0xffffffaa;i++);
    return;
}

int main(void)
{
    printf("\n Inside main()\n");
    int i = 0;

     gprof_init();
    for(;i<0xffffff;i++);
    func1();
    func2();

    return 0;
}

Program 2: gprof_test_2.c

//test_gprof_new.c
#include<stdio.h>

void new_func1(void)
{
    printf("\n Inside new_func1()\n");
    int i = 0;

    for(;i<0xffffffee;i++);

    return;
}

Output:

Execute the program:
gprof$ ./a.out

 Inside main()
GPROF SIGNAL HANDLER INITIALIZED

 Inside func1

Received Signal: 12
Original Dir = /home/labuser/velrajk/sample/gprof
Successfully changed to dir = /tmp
Switching to original working dir ...

---- output file.
$cd /tmp
$ ls gmon.out 
gmon.out
$