Tuesday, February 28, 2017

Linux Commands

Tags
Commands:

1.cd(Change Directory):
cd                               :for home directory
cd name of directory :will move the control to that directory
cd ..                            :move out of the current directory
cd ../..                         :move out two times of the current directory

2.ls:

ls                                :List the contents of current Directory
ls -a                            :List all the files including hidden files

Example of cd and ls:


3.pwd(Print Working Directory):

pwd                            :print the current working directory
Example:


4.man : command is used for getting details of any command

Example:
5. mkdir : command is used for making a directory/folder in the current directory

Example:
6.rm : command is used for deletion of a file
   rmdir: command is used for deletion of a directory/folder
   rm -r: command is used for deletion of a non empty folder/directory
Example:
7.history: command is used to check all the previous commands used
Example:

8.whoami: command is used to find username
9. uname: command reports basic information about computer hardware and software
Example:

10.top: top command is used to see the currently running  processes with ram usage
Example:

11.gedit:  gedit is used to create a file
Syntax : gedit file name
Example:
12.touch: this command is used to create an empty file
Syntax: touch filename
Example:
13.cat : cat command is used to show the comments of any file in terminal
Example:
this command can also be used to create a file

Syntax:  cat > file name   (Replace the previous contents)
              cat >> file name (append the file)
Example:
14.vi : this command is used to create a file in terminal using vi editor
Syntax: vi filename
Example:
In Vi Editor First Press i To Start Writing
Then For Ending Press ESC key the use any of following
:wq - for closing and saving file
:q!-   for closing without saving
:w-    for saving only

15.cp : command is used to copy file
Syntax: cp source file destination file
Example:
16.mv : command is used to move one file to another location
Syntax: mv source destination
 Can also be used for renaming a file
Example:
17.diff : this command is used to find difference between two files
Syntax: diff file1 file2
Example:



This command also tells how to make two files identical

c - change the contents
a - append the contents
d - delete the contents

18.more:  this command is used to view the contents of file
      Syntax: more filename

19.head :  this command is used to view the first 10 lines of file
       Syntax: head filename
Here we can also specify the no of lines required
            For ex: head -3 filename will print three first lines

20. tail  :   this command is used to view the last 10 lines of file

In this we can also specify the no of lines
            For ex: tail -3 filename   will view the last three lines

Example:
21. df  :  this command is used to view the memory available and used by various drives
            for ex : df -h
-h for Human readable format
we can also specify ant particular drive to get info about that only.

22. du : this command is used to get the memory occupied by a particular directory with a list of all subdirectories.

For ex :  du -sh Directory
Here s for simple only Directory no subdirectory listing,h for human readable

Example:
 23. lsblk: this command print all block devices all tell the type of device

Example:
 24. htop: htop command is used to view the currently running processes of the particular user

Example:

Monday, February 27, 2017

Transmission Media and Tools

Tags
Transmission Media:  Transmission media is the mean through which we send out data from one place to another.The first layer of connection networks,OSI seven layer model is dedicated to the transmission media.

1.Guided Transmission Media:
     
     a.Coaxial Cable:
     b.Twisted Pair Cable:
      c.Optical Fibre:
2.Unguided Transmission media:
        a.Radio Waves
        b.Micro waves
        c.Infrared


Tools:

Crimping Tool:
Connectors:

a.RJ 45 and RJ 11:
b.ST,SC,F and  LC:

Networking Devices

Tags
Networking Devices are components used to connect computers or other devices together so that they can share files or resources like printers .Devices may be used to setup a LAN network or in connecting different LAN Networks.


1.Network Interface Card(Lan Adapter):

2.Hub:

3.Switches:









4.Router:
5.Bridges:
6.Host:
7.Repeaters:
8.Modem:

Saturday, February 25, 2017

Pythagorean Triplets Java

Tags
A Pythagorean Triplet is a set of 3 values a, b and c such that the sum of squares of a and b is equal to  square of c.
(a*a) + (b*b)  = (c*c)
Following Program Displays the Pythagorean Triplets upto a user desired value.

import java.util.Scanner;
public class Triplets {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int a, b, c;
        System.out.println("Enter the value of n: ");
        int n = in.nextInt();
        System.out.println("Pythagorean Triplets upto " + n + " are:\n");
        for (a = 1; a <= n; a++) {
            for (b = a; b <= n; b++) {
                for (c = 1; c <= n; c++) {
                    if (a * a + b * b == c * c) {
                        System.out.print(a + ", " + b + ", " + c);
                        System.out.println();
                    }
                   
                    else
                        continue;                  
                }
            }
        }
    }
}




Friday, February 24, 2017

Inclusion Exclusion Principle

Tags
Inclusion Exclusion Principle is Used to Calculate Cardinality of Union or Intersection of Sets

For Example:
n(a or b)=n(a)+n(b)-n(a&b)

Following Code will calculate the Intersection of Sets Using Inclusion Exclusion Principle

Code:

//Program to Calculate Cardinality of Intersection of sets Using Inclusion Exclusion Principle
import java.util.*;
public class IncExcP 
{
    public static void main(String[] nt) 
    {
        Scanner in=new Scanner (System.in);
        System.out.print("Enter Number of sets: ");
        int n=in.nextInt();
        int [][] s=new int[n][];
        System.out.println("Enter Cardinality Type Wise (i.e:Singles,Pairs,Triples etc): ");
        for(int i=1;i<n;i++)
        {  s[i]=new int[choose(n,i)];
            for(int j=0;j<choose(n,i);j++)
            {
                s[i][j]=in.nextInt();
            }
            if(i==n-1)
            {
                break;
            }
            System.out.println("Enter Next Type");
        }
        System.out.print("Enter Value of Union:");
        int u=in.nextInt();
        int [] sum=new int[n];
        for(int i=1;i<n;i++)
        {
            for(int j=0;j<choose(n,i);j++)
            {
                sum[i]=sum[i]+s[i][j];
            }
        }
        int x=u;
        for(int i=1;i<n;i=i+2)
        {
            x=x-sum[i];
        }
        for(int i=2;i<n;i=i+2)
        {
            x=x+sum[i];
        }
        if(n%2==0)
        {
            x=-x;
        }
        System.out.println("Intersection: "+x);
    }
    public static int choose(int n,int i)
    {   int result=1;
        for(int j=1;j<=i;j++)
        {
            result=result*(n-j+1)/j;
        }
        return result;
    }
}

Output:
For example:


Thursday, February 16, 2017

Telephone Database (Persistent Variables) Python

Tags
Following Code will help in maintaining a telephone database including following commands

1.whois phonenumber -tell the details of a particular Number

2. add phonenumber information-add the new number with the information

3.search keyword-return all numbers having keyword in their information

4.delete-deleting any number from database

5.quit-Halt the application

Code::

import string
import shelve

database=shelve.open("information.db")
print("Commands are: whois,add,search,delete or quit")
c=0
line=input("Command: ")
while line!='quit':
    words=line.lower().split()
    if line=="":
        print("Commands are: whois,add,search,delete or quit")
    elif words[0] =='whois':
        if words[1] in database:
            print(words[1],":",string.capwords(database[words[1]]))
        else:
            print("Not Found Try again!!")
    elif words[0]=='add':
        if words[1] in database:
            print("Already Present")
        else:
            database[words[1]]=" ".join(words[2:])
    elif words[0]=='search':
        for e in database:
            if database[e].find(words[1])!=-1:
                c=1
                print(e,":",string.capwords(database[e]))
                
        if c==0:
            print("Keyword Not found Try again!!")
    elif words[0]=="delete":
        if words[1] in database:del database[words[1]]
        else:print("Not Found Try again!!")
    else:
        print("Command Not Found Please Try again!!")
    line=input("Command: ")
database.close()

Output::

 

Wednesday, February 15, 2017

A Concordance Python

Tags
A concordance is an alphabetical listing of the words in a text String,along with the line numbers on which each word occurs.

Code::

def count(line,dct,linenumber):
    for word in line.split():
        lst=dct.get(word,[])
        lst.append(linenumber)
        dct[word]=lst

line=input("Enter text,quit to end: ")
linenumber=0
dct={}
while line!='quit':
    linenumber+=1
    count(line,dct,linenumber)
    line=input()
for el in sorted(dct.keys()):
    print(el,":",dct[el])

Output::

Tuesday, February 14, 2017

Tabulating Club Dues Python

Tags
Following Code will tabulate the dues of Members of Club :

Code::

def main():
    fre={}
    print("Enter Dues ,enter quit to end")
    while True:
        line=input()
        if(line=='quit'):break
        words=line.split(':')
        fre[words[0]]=fre.get(words[0],0)+int(words[1])
    for name in fre:
        print(name+" has Paid Rs",fre[name],"in dues")

main()

Output::

Word Frequency Python

Tags
Following code will give the frequency of occurrence of words in text:

Code::

def main():
    fre={}
    print("Enter Text ,enter quit to end the text")
    while True:
        line=input()
        if(line=='quit'):break
        for el in line.split():
            fre[el]=fre.get(el,0)+1
    print (fre)

main()

    
Output::

Monday, February 13, 2017

Eliza Python

Tags
ELIZA is an early natural language processing computer program created from 1964 to 1966[1] at the MIT Artificial Intelligence Laboratory by Joseph Weizenbaum.[2] Created to demonstrate the superficiality of communication between man and machine.

Code::         #a short example u can increase the conditions 

def reply(line,words):
    if len(words)==0: return "You have to talk to me "
    elif "mother"in words:return "Tell me more about your mother "
    elif "father" in words :return "Tell me more about your father "
    elif words[0]=='i' and words[1]=='feel': return "Why do you feel that way? "
    elif words[-1]=='?': return "What do u want to know? "
    elif words[0]=='i' and words[1]=='think': return "Do you really think so? "
    elif "question" in words:return "What's the question? "
    elif "love" in words:return "I must tell you,Love is Very Complicated Agree? "
    elif "agree" in words:return "Do you agree always with this much ease? "
    elif "no" in words: return"Nice!!,Tell me more "
    else: return "Tell me more "

name=input("Hello, Welcome to NT Therapy Center,What's Your name? ")
print("Type quit to exit")
line=input("Hello "+name+" How can we help you? ")
while line!='quit':
    line=line.lower()
    words=line.split()
    replied=reply(line,words)

    line=input(replied)

Output::

Message Encryption and Decryption Python

Tags
Suppose you want to send a message to a friend,but you don't want other people to be able to read it
To do this you must disguise the text in some fashion.This Process is called Encryption.The reverse process is called Decryption.

Code::

def encrypt(msg):
    result=''
    for c in msg:
        result=result+" "+str(ord(c))
    return result

def decrypt(msg):
    result=''
    for c in msg.split():
        result=result+chr(int(c))
    return result


msg=input("Enter Secret Message: ")
emsg=encrypt(msg)
print("Encrypted Message: "+emsg)

print("Decrypted Message: "+decrypt(emsg))

Output::


Another method is using rotate 13 i.e convert the entered character to character 13 place ahead that character.


Code::                                                                                                                                       

def char13(c):
    alph="abcdefghijklmnopqrstuvwxyz"
    index=alph.find(c)
    index=(index+13)%26
    return alph[index]

def encrypt(text):
    result=''
    for c in text.lower():
        if 'a'<=c<='z':result=result+char13(c)
        else: result=result+c
    return result

msg=input("Enter Secret Message: ")
emsg=encrypt(msg)
print("Encrypted Message: "+emsg)
print("Decrypted Message: "+encrypt(emsg))


Output::                      
                                                                                                             





Date Conversion from One Format To Another Python

Tags
Following Code will convert date entered in one format to another:

Code::

def converter(date):
    day,month,year=date.split('/')
    monthnames=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    return monthnames[int(month)-1]+" "+day+","+year

date=input("Enter Date in DD/MM/YYYY format : ")
print ("Entered Date: "+converter(date))

Output::


Palindrome Testing Recursively Python

Tags
Entered string is Palindrome or not can be tested using Recursion as Shown by Following Code::

Code::

def isletter(c):     #function to check that character c is a letter or not
    return ('a'<=c<='z')or ('A'<=c<='Z')

def paltest(line):
    if len(line)<=1:return True
    elif not isletter(line[0]):return paltest(line[1:])      #ignoring first not letter
    elif not isletter(line[-1]):return paltest(line[:-1])    #ignoring last not letter
    elif line[0].lower()!=line[-1].lower():return False      
    else:return paltest(line[1:len(line)-1])                 #palindrome testing recursive call


string=input("Enter any String: ")
if(paltest(string)) : print("Yes,Palindrome")
else: print("Not,Palindrome")

Output::

Saturday, February 11, 2017

Case Conversion Python

Tags
Following Code Will Convert The Case of Entered String 
i.e lower to UPPER and UPPER to lower



Code::

def conversion(l):
    li=list(l)
    for i in range(0,len(l)):
        if 'a'<=li[i]<='z': li[i]=chr(ord(li[i])-32)
        elif 'A'<=li[i]<='Z': li[i]=chr(ord(li[i])+32)
    stri=''
    return stri.join(li)

s=input("Enter String: ")
print(conversion(s))


Output::


Standard Deviation Calculator Python

Tags
The Standard Deviation is a measure of how spread out numbers are.

Standard Deviation is a quantity expressing by how much the members of a group differ from the mean value for the group.
Its symbol is σ (the greek letter sigma)
Following Code will calculate the Standard Deviation:

Code::
import math
def average(l):             #function to calculate average(mean)
    total=0.0
    for i in l:
        total=total+int(i)
    if(len(l)==0): return 0
    else: return(total/len(l))
    
def standardeviation(l,ave):       #function to calculate standard deviation
    diff=0.0
    for i in l:
        x=int(i)-ave
        diff=diff+x*x
    if(len(l)==0): return 0
    else :return(math.sqrt(diff/len(l)))    


lst=[]
num=input("Enter Values ,enter -1 to end:")
while num!='-1':
    lst.append(num)
    num=input()
ave=average(lst)
print("Average is:",ave)
sd=standardeviation(lst, ave)
print("Standard Deviation :",sd)
        
Output::

Friday, February 10, 2017

Anagram Checking

Tags
An Anagram is a word, phrase, or name formed by rearranging the letters of another, such as Hitler woman, formed from mother in law.


Following Code Will Check if the entered Strings are Anagrams or Not ::

Code::

import java.util.*;
public class Anagram 
{
    public static void main(String[] nt) 
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter First String: ");
        String s1=in.nextLine();
        System.out.print("Enter Second String: ");
        String s2=in.nextLine();
        check(s1,s2);              //function to check if the entered strings are anagram
    }
    static void check(String a,String b)
    {   boolean status=true;
        a=a.replaceAll(" ", "");      //removing white spaces from strings
        b=b.replaceAll(" ", ""); 
        char[] s1=a.toLowerCase().toCharArray();    //converting string to character array
        char[] s2=b.toLowerCase().toCharArray();
        if(s1.length!=s2.length)
        {
            status=false;
        }
        else
        {
            Arrays.sort(s1);               //sorting array
            Arrays.sort(s2);
            if(!Arrays.equals(s1, s2))        //checking characters
            {
               status=false;
            }
        }
        if(status)
        {
            System.out.println("Yes these are Anagrams");
        }
        else
        {
            System.out.println("No these are not Anagrams");
        }
    }

}
Output::


More Examples::

  • Debit card = Bad credit
  • Dormitory = Dirty Room
  • The earthquakes = The queer shakes
  • Astronomer = Moon starrer
  • Punishments = Nine Thumps
  • School master = The classroom


Thursday, February 9, 2017

Perfect Number Java

Tags
Perfect numbera positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3. Other perfect numbers are 28, 496, and 8,128. 

Code::

import java.util.*;
public class PerfectNumber 
{

    
    public static void main(String[] nt) 
    {
       Scanner in= new Scanner(System.in);
       System.out.print("Enter any Number: ");
       int n=in.nextInt();
       int temp=n;
       int sum=0;
       for(int i=1;i<n;i++)
       {
           if(temp%i==0)
           {
               sum=sum+i;
           }
       }
       if(sum==n)
       {
           System.out.println("Yes it is a Perfect Number");
       }
       else
       {
           System.out.println("No it is not a Perfect Number");
       }
    }
    

}

Output::