Monday, February 26, 2018

Atmel : Designer & Manufacturer of AVR, ARM and Intel microcontrollers

Atmel is an North America-based designer and manufacturer of semi-conductors founded in 1984.
The company focuses on Embedded Systems built around microcontrollers.

Its products include
Microcontrollers:
 1. 8-bit and 32-bit AVRs
 2. 32-bit ARM based uCs
 3. 8-bit Intel 8051 uC.
 4. RF devices including Wi-Fi
 5. EEPROM
 6. Flash Memory devices
 7. Security chips
 8. Touch sensors
 9. Controllers
 10. ASICs - Application Specific ICs , built on requirements of its customers.

Thanks
Happy developing!

Full Stack Developer : Sequence of Topics

The sequence of topics to be learnt to become a full stack developer is a minimum of :

I. Front-end Developer/ Web Designer:
-------------------------------------------------
1 .HTML and HTML5
2. CSS
3. Bootstrap 4 ( A CSS framework)
4. Responsive Design (so that your site fits to all size devices in the same way)
5. JavaScript
6. DOM Events
7. Dreamweaver

II. Back-end Developer/ Web Developer (App behaviour/Business Logic) :
----------------------------------------------------------------------------------------
1.  Node.js
2.  Express.js
3.  REST - Ajax, XHR (XMLHttpRequest()), JSON
4.  SQL language
5.  JQuery
6.  React JS
7.  Angular JS (for SPA - single page applications like Gmail)
8.  Database servers like MySQL/postgreSQL/MongoDB
9.  Chrome Dev Tools
10. SSL Certificates
-----------------------------------------------------------------------------

III. Git - To work remotely on projects with people , look at code bases of popular projects on GitHub .
----------------------------------------------------------------------------------------------------------------------------
IV. Web application Architecture
       a. AWS
       b. Azure
    PaaS like
       a. Hasura
       b. Heroku
----------------------------------------------------------------------------------------------------------------------
 V.  MVC
Is a software architecture - the structure of the system - that separates domain/application/business
logic (whatever you refer it as) from rest of the user interface. It does so by separating the  application into three parts
       a. The MODEL - Manages business logic and database. All that is not visible to user. Defines the fundamental behavior of the application. It can respond to REQUESTS for information and RESPOND to instructions to change the STATE of its information. In short it is the LOGIC and DATA- MANAGEMENT of the application.
       b. The VIEW - The user interface , all that is visible to the user. It will render data from the model to the UI and from UI to model (using forms).
       c. The CONTROLLER - Receives user inputs and makes calls to MODEL objects and the VIEW to perform appropriate actions.
-----------------------------------------------

VI. A good Computer Science background with topics like
1. Tree traversing
2. Sorting
3. Algorithm Analysis
4. Matrix Manipulation
5. Hash Tables
6. Queues and stacks
7. Objects and Arrays
---------------------------------------------------------------------------
VII. HTTP and REST

HTTP is a stateless application protocol on the internet - its what allows clients to
communicate with servers ( e.g. your javascript code can make an Ajax request to some
back-end code you have running on a server which will happen via HTTP.
--------------------------------------------------------------------------------------------------------------------

To add programming/computational/functional power to your UI ( User Interface) you need
JavaScript ( or any web scripting language like VBScript) and then connect your UI to a
database. So, you need to know SQL .
Then you need to create and configure your server. For that you will need Node.js and Express.js or PHP/ Python/Java.
And finally to enhance your front-end JS, you need jQuery and React JS. And if you want your web
application to be a single page applicatio like the gmail, you need to learn Angular JS.

Various options of web development stacks to choose from are:

1. WAMP - Windows (OS), Apache (Web server), MongoDB (nonSQL database server) and PHP.
2. MEAN - MongoDB, Express.js, Angular.js and Node.js - A all javascript stack

Thanks
Happy developing !

JavaScript : getElementById(" ") method

<!DOCTYPE html>
<html>
<body bgcolor="lightblue">

<h1>HAPPY BIRTHDAY YASH 2016 ON YOUR 11th BIRTHDAY</h1>

<p>Some birthday party pics.</p>

<p>You and your friends</p>

<button onclick="document.getElementById('myImage').src='IMG_20161006_200417.jpg'">switch photo</button>

<img id="myImage" src="IMG_20161006_213208.jpg" style="width:300px">

<button onclick="document.getElementById('myImage').src='IMG_20161006_213208.jpg'">switch back</button>
<img id="myImage" src="IMG_20161006_200604.jpg" style="width:300px">

<button onclick="document.getElementById('myImage').src='SINGH_ASHUTOSH.jpg' ">who's behind</button>

</body>
</html>

Thanks
Happy Scripting

JQuery : Most popular and powerful JavaScript Library

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").click(function(){
        $(this).hide();
    });
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

Thanks
Happy Scripting!

JavaScript : Form Validation check

<!DOCTYPE html>
<html>
<body>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
    var inpObj = document.getElementById("id1");
    if (inpObj.checkValidity() == false) {
        document.getElementById("demo").innerHTML = inpObj.validationMessage;
    } else {
        document.getElementById("demo").innerHTML = "Input OK";
    }
}
</script>

</body>
</html>

Thanks
Happy Scripting!

JavaScript : Form Validation

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Can Validate Input</h1>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x, text;

    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;

    // If x is Not a Number or less than one or greater than 10
    if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
    } else {
        text = "Input OK";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Thanks
Happy programming!

Fetching javascript from an External file

<!DOCTYPE html>
<html>
<body>

<h1>External JavaScript</h1>

<p id="demo">A Paragraph.</p>
<p id="memo">Yash Singh.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>
<button type="button" onclick="f1()">Do this</button>
<p>(f1() is stored in an external file called "myScript1.js")</p>


<script src="myScript.js"></script>
<script src="myScript1.js"></script>

</body>
</html>
Thanks
Happy programming!

Javascript : Confirmation

document.write(("I am your guide, Ashutosh !").length>20);
document.write(("I am your guide, Ashutosh !").length===27);
document.write(("I am your guide, Ashutosh !").substring(4,9));

prompt("What is java?");
prompt(" Doyou know programming?");
window.open("D:/Aa_javaScript/addElement.html");
</script>
<pre>
<h1>What is programming?</h1>
Programming is like writing a list of instructions to
the computer,
so it can do cool stuff with your information.

Programs can't yet make your bed,
but they can do math,
keep track of your bank account,
or send a message to a friend.

Data comes in various types. You have used two already!

a. numbers are quantities, just like you're used to.
You can do math with them.

b. strings are sequences of characters, like the letters a-z, spaces,
and even numbers. These are all strings: "Ryan", "4" and "What is your name?"
 Strings are extremely useful as labels, names, and content for your programs.

To make a number in your code, just write a number as numerals
 without quotes: 42, 190.12334.

To write a string, surround words with quotes: "What is your name?"

As you get started with programming, we will teach you many syntax rules.
This is sort of like the grammar of programming languages. Grammar first,
then programming poetry!

 Now, computers are very literal. Syntax needs to be in exactly the right
place for the computer to understand the code.

There are many mistakes in this code. Find them and fix them all.

You are doing what's called "debugging," a term popularized by Grace Hopper when she literally removed a moth from her computer.


</pre>
</body>
</html>

Thanks
Happy programming!

Javascript to change the STYLE of an element

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>


</body>
</html>
Thanks
Happy programming!

javaScript : Adding an HTML element to your webpage

<html>
<body id="b1">


<p id="a">webmakers.com</p>
<script>
function f1()
{

var newH=document.createElement("h1");
var node=document.createTextNode("Yash Singh");
newH.appendChild(node);
var body=document.getElementById("b1");
body.appendChild(newH);

}
</script>

<button type="button" onclick="f1()">Adds Header Element to body</button>

Thanks
Happy programming!

JavaScript program : Showing a hidden HTML element

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p>JavaScript can show hidden HTML elements.</p>

<p id="demo" style="display:none">Hello JavaScript!</p>

<button id = hi type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

</body>
</html>

Thanks
Happy programming!

'Tradulator' : A calculator made by me for Traders using Java Swing class

 import java.awt.event.*;
    import javax.swing.*;  
    public class Tradulator {
        static String firstnum, secondnum, summ;
        static float sum, firstn, secondn;
    public static void main(String[] args) {
        JFrame f=new JFrame("Tradulator");
        JLabel l1=new JLabel("Sale Price       : ");
        JLabel l2=new JLabel("Buy Price : ");
        JLabel l3=new JLabel("Result : ");
        l1.setBounds(50,50, 100,40);
        l2.setBounds(50,100, 100,40);
        l3.setBounds(50,150, 100,40);
        final JTextField tf1=new JTextField();
        tf1.setBounds(150,50, 100,40);
        final JTextField tf2=new JTextField();
        tf2.setBounds(150,100, 100,40);
        final JTextField tf3=new JTextField();
        tf3.setBounds(150,150, 100,40);
      
        JButton bPL=new JButton("P/L");
        bPL.setBounds(50,200,55,30);
        bPL.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                firstnum=tf1.getText();
                secondnum=tf2.getText();
                firstn=Float.parseFloat(firstnum);
                secondn=Float.parseFloat(secondnum);
                sum=firstn - secondn;
                summ=String.valueOf(sum);
                tf3.setText(summ);
            }
        });
      
        JButton bPLp=new JButton("P/L %");
        bPLp.setBounds(120,200,95,30);
        bPLp.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                firstnum=tf1.getText();
                secondnum=tf2.getText();
                firstn=Float.parseFloat(firstnum);
                secondn=Float.parseFloat(secondnum);
                sum=((firstn - secondn)/secondn)*100;
                summ=String.valueOf(sum);
                tf3.setText(summ);
            }
        });
      
        JButton bmul=new JButton("X");
        bmul.setBounds(50,250,55,30);
        bmul.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                firstnum=tf1.getText();
                secondnum=tf2.getText();
                firstn=Float.parseFloat(firstnum);
                secondn=Float.parseFloat(secondnum);
                sum=firstn*secondn;
                summ=String.valueOf(sum);
                tf3.setText(summ);
            }
        });
      
        JButton bdiv=new JButton("/");
        bdiv.setBounds(120,250,55,30);
        bdiv.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                firstnum=tf1.getText();
                secondnum=tf2.getText();
                firstn=Float.parseFloat(firstnum);
                secondn=Float.parseFloat(secondnum);
                sum=firstn/secondn;
                summ=String.valueOf(sum);
                tf3.setText(summ);
            }
        });
      
        JButton bclr=new JButton("Clear");
        bclr.setBounds(100,300,105,30);
        bclr.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                tf1.setText("");
                tf2.setText("");
                tf3.setText("");
            }
        });
      
        f.add(l1);
        f.add(tf1);
        f.add(l2);
        f.add(tf2);
        f.add(l3);
        f.add(tf3);
        f.add(bPL);
        f.add(bPLp);
        f.add(bmul);
        f.add(bdiv);
        f.add(bclr);
        f.setSize(400,400);
        f.setLayout(null);
        f.setVisible(true);
        //f.setBackground(Color.yellow);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    }

Output example





Thanks
Happy Developing !

Java swing program : Create frame by Inheritance

 //We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.
   
    import javax.swing.*; 
    public class SwingByInheritance extends JFrame{//inheriting JFrame 
   
    SwingByInheritance(String s){  // we must know which method should be used to display this string as frame title
    //JFrame f1=new JFrame(s);
    super(s);
    JButton b=new JButton("Submit");//create button 
    b.setBounds(130,100,100, 40); 
       
    add(b);//adding button on frame 
    setSize(400,500); 
    setLayout(null); 
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   
    //f1.add(b);//adding button on frame 
    //f1.setSize(400,500); 
    //f1.setLayout(null); 
    //f1.setVisible(true);
    //f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

   
    public static void main(String[] args) { 
    new SwingByInheritance("If all is done");
   
    JFrame f=new JFrame("But I want to label my frame hence I need JFrame constructor");
    JButton b1=new JButton("Click");
     b1.setBounds(130,100,100, 40);
    f.add(b1);   
    f.setSize(400,400);   
    f.setLayout(null);   
    f.setVisible(true);   
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   
    }
   
    } 

Thanks
Happy programming!

Java Swing : Frame construction inside Constructor

 //We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.
   
    import javax.swing.*; 
    public class SwingInsideConstructor { 
    JFrame f; 
    SwingInsideConstructor(){ 
    f=new JFrame("Music Book");//creating instance of JFrame 
             
    JButton b=new JButton("Open");//creating instance of JButton 
    b.setBounds(130,100,100, 40); 
             
    f.add(b);//adding button in JFrame 
             
    f.setSize(400,500);//400 width and 500 height 
    f.setLayout(null);//using no layout managers 
    f.setVisible(true);//making the frame visible
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    } 
     
    public static void main(String[] args) { 
    new SwingInsideConstructor(); 
    } 
    } 

Thanks
Happy programming!

Java Swing program : A button with Icon

 import javax.swing.*;     
    public class ButtonWithIcon{   
    ButtonWithIcon(){   
    JFrame f=new JFrame("ButtonWithIcon");           
    JButton b=new JButton(new ImageIcon("D:\\JavaSwing\\lcd.png"));   
    b.setBounds(50,100,230, 130);   
    f.add(b);   
    f.setSize(400,400);   
    f.setLayout(null);   
    f.setVisible(true);   
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        }        
    public static void main(String[] args) {   
        new ButtonWithIcon();   
    }   
    }   
Output

Thanks
Happy programming!

Java Swing : Button with Action - Mini Calculator

import java.awt.event.*; 
    import javax.swing.*;   
    public class ButtonWithAction {
        static String firstnum, secondnum, summ;
        static float sum, firstn, secondn;
    public static void main(String[] args) { 
        JFrame f=new JFrame("Calculator"); 
        JLabel l1=new JLabel("First number       : ");
        JLabel l2=new JLabel("Second number : ");
        JLabel l3=new JLabel("Result : ");
        l1.setBounds(50,50, 100,40);
        l2.setBounds(50,100, 100,40);
        l3.setBounds(50,150, 100,40);
        final JTextField tf1=new JTextField(); 
        tf1.setBounds(150,50, 100,40); 
        final JTextField tf2=new JTextField(); 
        tf2.setBounds(150,100, 100,40); 
        final JTextField tf3=new JTextField(); 
        tf3.setBounds(150,150, 100,40); 
        JButton bsum=new JButton("+"); 
        bsum.setBounds(50,200,55,30); 
        bsum.addActionListener(new ActionListener(){ 
        public void actionPerformed(ActionEvent e){ 
                firstnum=tf1.getText();
                secondnum=tf2.getText();
                firstn=Float.parseFloat(firstnum);
                secondn=Float.parseFloat(secondnum);
                sum=firstn + secondn;
                summ=String.valueOf(sum);
                tf3.setText(summ); 
            } 
        });
       
        JButton bdiff=new JButton("-"); 
        bdiff.setBounds(120,200,55,30); 
        bdiff.addActionListener(new ActionListener(){ 
        public void actionPerformed(ActionEvent e){ 
                firstnum=tf1.getText();
                secondnum=tf2.getText();
                firstn=Float.parseFloat(firstnum);
                secondn=Float.parseFloat(secondnum);
                sum=firstn - secondn;
                summ=String.valueOf(sum);
                tf3.setText(summ); 
            } 
        });
       
        JButton bmul=new JButton("X"); 
        bmul.setBounds(50,250,55,30); 
        bmul.addActionListener(new ActionListener(){ 
        public void actionPerformed(ActionEvent e){ 
                firstnum=tf1.getText();
                secondnum=tf2.getText();
                firstn=Float.parseFloat(firstnum);
                secondn=Float.parseFloat(secondnum);
                sum=firstn*secondn;
                summ=String.valueOf(sum);
                tf3.setText(summ); 
            } 
        });
       
        JButton bdiv=new JButton("/"); 
        bdiv.setBounds(120,250,55,30); 
        bdiv.addActionListener(new ActionListener(){ 
        public void actionPerformed(ActionEvent e){ 
                firstnum=tf1.getText();
                secondnum=tf2.getText();
                firstn=Float.parseFloat(firstnum);
                secondn=Float.parseFloat(secondnum);
                sum=firstn/secondn;
                summ=String.valueOf(sum);
                tf3.setText(summ); 
            } 
        });
       
        JButton bclr=new JButton("C"); 
        bclr.setBounds(100,300,55,30); 
        bclr.addActionListener(new ActionListener(){ 
        public void actionPerformed(ActionEvent e){ 
                tf1.setText("");
                tf2.setText("");
                //firstn=Float.parseFloat(firstnum);
                //secondn=Float.parseFloat(secondnum);
                //sum=firstn/secondn;
                //summ=String.valueOf(sum);
                tf3.setText(""); 
            } 
        });
       
        f.add(l1);
        f.add(tf1);
        f.add(l2);
        f.add(tf2);
        f.add(l3);
        f.add(tf3);
        f.add(bsum);
        f.add(bdiff);
        f.add(bmul);
        f.add(bdiv);
        f.add(bclr);
        f.setSize(400,400); 
        f.setLayout(null); 
        f.setVisible(true);
        //f.setBackground(Color.yellow);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    } 
    } 
Output
Thanks
Happy programming!

Java Swing Program: GUI

import javax.swing.*;

public class SwingExample
{
    public static void main(String[] S)
    {
        JFrame f=new JFrame();
        JButton b=new JButton("Profit");
        JTextField tf1=new JTextField();
        JTextField tf2=new JTextField();
        //JTextArea ta1=new JTextArea("Sell Price");
        //ta1.setBounds(20,120,100,40);
        tf1.setBounds(90,120,120,40);
        tf2.setBounds(90,60,120,40);
        b.setBounds(90,200,120,50);
        f.add(b);
        f.add(tf1);
        f.add(tf2);
        //f.add(ta1);
        f.setSize(600,600);
        f.setLayout(null);
        f.setVisible(true);
       
    }
}   
Thanks
Happy programming!

Java program : Use of 'this' keyword

class ThisConversion
{
    int x;        //These are INSTANCE variables
    String name;
    ThisConversion(int x, String name)  //here x and name are LOCAL variables of the Ctor
    {
        this.x=x;            //we use this keyword to convert LOCAL variables to INSTANCE variables
        this.name=name;        // If LOCAL and INSTANCE variables have SAME name, then we use 'this' keyword
    }
    void disp()
    {
        System.out.println(name +"  "+x);
    }
    public static void main(String[] args)
    {
        new ThisConversion(3,"yash ashutosh").disp();   //o/p yash3
       
    }
}

Thanks
Happy Computing!

Java program : Heterogenous Array

class HetrogenousArray
{  
    // USING ARRAY OF 'OBJECT' CLASS WE CAN CREATE AN ARRAY OF HETEROGENOUS ELEMENTS ALSO, BECAUSE 'OBJECT CLASS'
    // IS ROOT CLASS OF ALL CLASES IN JAVA
 
    public static void main(String[] args)
    { Object[] o=new Object[3];
       o[0]=new Emp(111,"Ashutosh");
       o[1]=new Student(222,"Yash");
       o[2]=new Integer(19);
      
       for(Object oo:o)
       { if(oo instanceof Emp)
        {    Emp e =(Emp)oo;
            System.out.println(e.id+"---"+e.name);
        }
       
         if(oo instanceof Student)
        {    Student s =(Student)oo;
            System.out.println(s.id+"---"+s.name);
        }
         if(oo instanceof Integer)
        {   
            System.out.println(oo);
        }
       }    
    }   
}

Thanks
Happy Computing!

Java program : Embedding SQL in java

import java.util.*;
class SqlSyntax_1
{
    public static void main(String[] args)
    {
            Scanner scanner=new Scanner(System.in);
            System.out.println("enter id");
            int id=scanner.nextInt();
            System.out.println("enter name");
            String name=scanner.next();
            System.out.println("enter salary");
            float salary=scanner.nextFloat();
            String q2="insert into "+name+" values("+id+" ,'"+name+"',"+ salary+")";
            System.out.println(q2);
    }
}

Thanks
Happy programming!

My first java application

import java.lang.System;
import java.lang.String;

class FirstApp

    static int a =100;
    float b = 7.9f;  //always use f constant with float values else you will get CTE
    static double d = 89.98;
   public static void main(String[] args)
   {   FirstApp f= new FirstApp();
  
    //STATIC variables can be Accessed in three ways, Recommed way using CLASS name.
     System.out.println("Ashutosh "+ a);  //DIRECT access
     System.out.println("Ashutosh "+ FirstApp.a);  //using CLASS NAME, RECOMMEDED way
     System.out.println("Ashutosh "+ f.a);   // using OBJECT REFERENCE VARIABLE
     System.out.println(f.b);
      System.out.println(d);
       //System.out.println(f.b);
     }
   
}

Thanks
Happy programming!

Sunday, February 25, 2018

Java program : Converting Arrays to Collection

// To CONVERT ARRAYS INTO 'COLLECTIONS'

import java.util.*;
class ArrayToCollection
{
    public static void main(String[] args)
    {
        String[] s ={"ashutosh", "kumar","Singh"};
        ArrayList<String> al =new ArrayList<String>(Arrays.asList(s));
        al.add("SE");
        al.add("WD");
       
        System.out.println(al);
    }
}

Thanks
Happy programming!

Java program : Calling Instance and Static variable/objects

// WE CAN CALL INSTANCE VARIABLES/METHODS USING CLASS NAME, IF WE HAVE A 'STATIC METHOD' WHICH 
// RETURNS A OBJECT OF THE CLASS

// IF WE WRITE SUCH "getOject()" METHOD IN EACH/ANY  CLASS THEN WE WILL BE ABLE/CAN TO ACCESS
//'INSTANCE VARIABLES/METHODS'  BY CLASS_NAME JUST LIKE WE CALL 'STAIC' METHODS USING CLASS_NAME
class InstanceCall
{   
    int a=100;                //INSTANCE VARIABLE
    static int b=200;         //STAIC  VARIABLE
    static InstanceCall getOject()  // THIS 'STATIC' METHOD RETURNS A OBJECT OF THE CLASS
    {
        InstanceCall InstanceCall=new InstanceCall();
        return InstanceCall;
    }
}

class CallInstance
{
    public static void main(String[] args)
    {
        System.out.println(InstanceCall.b);
        System.out.println(InstanceCall.getOject().a);  // WE ACCESS THE "STATIC" getOject() METHOD BY CLASS_NAME,
                                                 // WHICH RETURNS A OBJECT OF THAT CLASS, THEN WE ACCESS
                                                // THE "INSTANCE" VARIABLE 'a', USING THAT OBJECT
    }

}

Thanks
Happy programming!

Java program :Creating collections using ArrayList()

import java.util.*;

class Collection_ArrayList_3
{
    public static void main(String[] args)
    {
        Emp e1=new Emp(111,"AK");
        Emp e2=new Emp(222,"Singh");
        Emp e3=new Emp(333,"Software Engineer");
        Emp e4=new Emp(444,"Web Applications");
       
        ArrayList<Emp> al1=new ArrayList<Emp>();
        al1.add(e1);
        al1.add(e2);
       
        ArrayList<Emp> al2=new ArrayList<Emp>();
        al2.addAll(al1);
        al2.add(e3);
        al2.add(e4);
       
        System.out.println(al2.contains(e1));
        System.out.println(al2.containsAll(al1));
       
        al2.remove(e1);
        System.out.println(al2.contains(e1));
        System.out.println(al2.containsAll(al1));
       
        for(Emp e:al2)
        {
            System.out.println(e.id+"------"+e.name);
        }
       
    }
}   

Thanks
Happy programming!

Java program : Collections

import java.util.*;

class Collection_ArrayList_2
{  
    public static void main(String[] args)
    {
     ArrayList al =new ArrayList();
     al.add("Ashutosh");
     al.add(123);
     al.add("kumar");
     al.add(143);
     System.out.println(al);
     System.out.println(al.size());
     al.add(1,"Singh");
     System.out.println(al);
     System.out.println(al.size());
      al.remove(0);                  // using index
     System.out.println(al);
     System.out.println(al.size());
     //al.remove(10);
     Integer i=new Integer(143);      //ANOTHER WAY TO REMOVE A INTEGER DATA
     al.remove(i);
     System.out.println(al);
     System.out.println(al.size());
     al.remove("kumar");               //using specific object
     System.out.println(al);
     System.out.println(al.contains("ashutosh"));
     System.out.println(al.isEmpty());
     al.clear();
     System.out.println(al.isEmpty());
     }
   
}

Thanks
Happy programming!

Java program : Enum in Switch

class EnumInSwitch

    enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY} 
   
    public static void main(String args[])
    { 
        Day day=Day.MONDAY; 
 
        switch(day)
        { 
        case SUNDAY:  
        System.out.println("sunday"); 
        break; 
        case MONDAY:  
        System.out.println("monday"); 
        break; 
        default: 
        System.out.println("other day");
        }
    } 
}

Thanks
Happy programming!

Java program : Checked and Unchecked Exceptions

class CheckedException
{
    public static void main(String[] args) throws Exception
    {    Thread.sleep(3000);  //CHECKED exception
        System.out.println("Singh");
        System.out.println(10/0);    //UNCHECKED exception
        System.out.println("ashu");
    }


}

Thanks
Happy programming!

Java program : Constructor calling a Constructor

class CtorCallingCtor
{
    CtorCallingCtor()
    {   
        this(11);                             //To call ctor inside ctor we use 'this' keyword
        System.out.println("0 arg ctor");     // The 'this' statement MUST be the FIRST statement in the ctor
                                            // One ctor can call only ONE ctor in this way   
    }
   
    CtorCallingCtor(int m)
    {
        //this(); //CTE RECURSIVE CTOR INVOCATION NOT ALLOwED
        System.out.println("1 arg ctor  " + m);
    }

   
    public static void main(String[] args)
    {
        new CtorCallingCtor();
        new CtorCallingCtor(12);
    }   
}   

Thanks
Happy programming!

Java Program : Illustratingconcept of 'Collections' in java

import java.util.*;

class Collection_ArrayList_1
{  
    public static void main(String[] args)
    {
     ArrayList al =new ArrayList();
     al.add("Ashutosh");
     al.add(123);
     al.add("kumar");
     al.add(143);
     System.out.println(al);
     }
   
}

Thanks
Happy Programming!

Java Program : A retail shop Billing Software

import java.util.Scanner;
class Billing
{
    public static void main(String[] args)
    {
       
         float T=0;
       System.out.println("Welcome to Yashtosh Mart !\n");
 
 

    float t[];
   String itemName[];
  
   float quantity[];
   float rate[];
  
      String s; float k,r;
       System.out.println("input Name of item  <SPACE> Quantity <SPACE> rate press<ENTER>");
       Scanner scanner=new Scanner(System.in);
       for(int j=0;j
       itemName[]=scanner.next();
       quantity[]=scanner.next();
       rate[]=scanner.next();
   }
  for(int i=0;i<itemName.length;i++)
  {System.out.println(itemName[i]+" "+quantity[i]+" "+rate[i]+" "+"costing Rs."+quantity[i]*rate[i]);
      t[i]=quantity[i]*rate[i];

     T= T+t[i];
  
  }
  System.out.println("Your Grand Total = Rs."+T);
   

    }


}

Java program : Enumerator declared outside a class

//Enum declaration outside class



        enum Heroin {katrina,hema,madhuri,alka,sharmila,kareena,};
       
class EnumOutsideClass
{       
        public static void main(String[] args)
        {
        for(Heroin h:Heroin.values())
        {
                System.out.println(h);
        }
}        }

Thanks
Happy programming!

Java program : Abstraction using Abstract Classes

abstract class Abstraction
{
    abstract void m1();
    abstract void m2();
    abstract void m3();
}
abstract class Child extends Abstraction
{
     void m1()
     {System.out.println("m1 implemented in child");}
     void m3()
     {System.out.println("m3 implemented in child");}
   
     /*public static void main(String[] args)
     {
        Child c= new Child();
        c.m1();
     }*/


}
class WelcomeScreen extends Child
{
        void m2()
     {System.out.println("m2 implemented in WelcomeScreen");}
     public static void main(String[] args)
     {
        WelcomeScreen hs = new WelcomeScreen();
        Abstraction a = new WelcomeScreen();
        Child c = new WelcomeScreen();
       
        //Ashutosh--------;
       
        System.out.println("Ashutosh");
        hs.m1();
        hs.m2();
        hs.m3();
       
        System.out.println("Ashutosh kumar");
        a.m1();
        a.m2();
        a.m3();
       
       
        System.out.println("Ashutosh kumar Singh");
        c.m1();
        c.m2();
        c.m3();
     }
   
}   

Java program : Abstraction by using Interface

interface Inter
{
    void m1();
    void m2();
    void m3();

}
class ChildInter implements Inter
{
    public void m1()
    {System.out.println("m1");}
    public void m2(){}
    public void m3(){}
   
    public static void main(String[] args)
    {
        ChildInter ci=new ChildInter();
        ci.m1();
    }

}

Thanks
Happy programming!

Advanced Java program : JDBC Creating tables and inserting records DYNAMICALLY

//Creating tables and inserting records in a known/existing database DYNAMICALLY/i.e through Keyboard
//while the program is running

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class DynamicDatabase {

    public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
        // TODO Auto-generated method stub
        System.out.println("Ashutosh");
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost/mybooks","AKSingh", "ashutosh");
        Statement statement=connection.createStatement();
        Scanner scanner=new Scanner(System.in);
        System.out.println("enter table name you want to create");
        String tname= scanner.next();
        String q1="create table "+tname+"(id int, name varchar(50), salary float)";
        int x=statement.executeUpdate(q1);
        System.out.println("table is created"+tname+" "+x);
        while(true)
        {
            System.out.println("enter id");
            int id=scanner.nextInt();
            System.out.println("enter name");
            String name=scanner.next();
            System.out.println("enter salary");
            float salary=scanner.nextFloat();
            String q2="insert into "+tname+" values("+id+" ,'"+name+"',"+ salary+")";
            System.out.println(q2);
            statement.executeUpdate(q2);
            System.out.println("values are inserted succesfuly");
            System.out.println("do you want more records (yes/no)");
            String option =scanner.next();
            if(option.equals("no"))
            {
                break;
            }
       
        }
        Thread.sleep(15000);
        System.out.println("enter the table name you want to drop");
        String droptable= scanner.next();
        String q3="drop table "+droptable;
        System.out.println(q3);
        statement.executeUpdate(q3);
        System.out.println("table dropped sucessfuly");
        System.out.println("All operations completed sucessfuly");
       
       

    }

}

Thanks
Happy Programming!

Java program : Two dimensional Arrays

class ArrayTwoD
{
    static int[][] a={{11,22,33},{44,55,66}};
   
    public static void main(String[] args)
    {
        System.out.println(a[0][0]);
        System.out.println(a[1][0]);
        System.out.println(a[0][1]);
        System.out.println(a[1][1]);
        System.out.println(a[0][2]);
        System.out.println(a[1][2]);
    }
}

Advanced Java Program : JDBC connecting to a MySQL Database

import java.sql.*;
import java.io.*;
class CarsDb
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cars","AKSingh","ashutosh");
            Statement stmt = con.createStatement();
            ResultSet rs= stmt.executeQuery("select * from car_models");
            while(rs.next())
            {
                System.out.println(rs.getInt(1)+" "+rs.getString(2)+"   "+rs.getInt(3)+"   "+rs.getString(4)+"  "+
                rs.getInt(5));
            }   
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}
Thanks
Happy Programming!

Advanced Java program : JDBC interacting with a Database

import java.sql.*;
import java.io.*;

class Cars_db
{   
   
    public static void main(String[] args)
    {
        FileOutputStream f = new FileOutputStream("Cars database JDBCquery.txt");
        System.setOut(new PrintStream(f));
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cars","AKSingh","ashutosh");
            Statement stmt = con.createStatement();
            ResultSet rs= stmt.executeQuery("select * from car_models");
            while(rs.next())
            {
                System.out.println(rs.getInt(1)+" "+rs.getString(2)+"   "+rs.getInt(3)+"   "+rs.getString(4)+"  "+
                rs.getInt(5));
            }   
            con.close();
        }
       
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}
Thanks
Happy Programming!

Java program : Storing objects in Array

class Animal
{ {System.out.println("Animal");}
}
class Dog extends Animal
{ {System.out.println("Dog");}
}
class DogKid extends Dog
{ {System.out.println("DogKid");}
}
class ArrayInFamily
{       
       
        static void m1()
        {
           Animal[] a=new Animal[3];
          { a[0] = new Animal();
            a[2] = new DogKid();
            for(Animal aa:a )
                {
                    System.out.println(aa);
                }
          }
        } 
        public static void main(String[] args)
        {
                m1();
               
        }   
}   

Thanks
Happy programming!

Java program : Array as Argument

class ArrayAsArgument
{   
    static void m1(int a[])
    {
          for(int i=0;i<a.length;i++)
          {
            System.out.println(a[i]);
          }
    }
    public static void main(String[] args)
    {
        int a[]={1,2,3,4,5,6,7,8,9,10};
        m1(a);
    }

}

Thanks
Happy programming

Java program : Array example

class Array_2
{
    public static void main(String[] args)
    {
        int[] a={10,20,30,40,50};
        for(int i=0; i<a.length;i++)
        {
            System.out.println(a[i]);
        }
       
        Emp[] e=new Emp[5];
        Emp e1= new Emp(111,"ashutosh");
        Emp e2= new Emp(222,"kumar");
        Emp e3= new Emp(333,"singh");
        Emp e4= new Emp(444,"lagatar haso");
        Emp e5= new Emp(444,"naya ghar");
        Emp e6= new Emp(444,"purana");
        Emp e7= new Emp(444,"aaj");
        e[0]=e1;
        //e[1]=e2;
        e[2]=e3;
        //e[3]=e4;
        e[4]=e5;
        //e[5]=e6;  RTE ArrayIndexOutOfBoundsException
        for(Object O:e)
        {   
            if(O instanceof Emp)
            { Emp ee= (Emp)O;  //DOWN CASTING HAS TO BE DOWN EXPLICITLY   
            System.out.println(ee.id+"-----"+ee.name);
            }
            if(O==null)
            { System.out.println(O);
            }
        }   
        for(int i=0;i<e.length;i++)
        {
            if(e[i]==null)
            {System.out.println(i);}
        }
        Array_1 a1=new Array_1();
        a1.m1();
    }

}

Thanks
Happy programming!

java program : Arrays

class Array_1
{
    public static void main(String[] args)
    {
        int[] a={10,20,30,40,50};
        for(int i=0; i<a.length;i++)
        {
            System.out.println(a[i]);
        }
        m1();
    }  
        static void m1()
        {
        Emp[] e=new Emp[5];
        Emp e1= new Emp(111,"ashutosh");
        Emp e2= new Emp(222,"kumar");
        Emp e3= new Emp(333,"singh");
        Emp e4= new Emp(444,"lagatar");
        Emp e5= new Emp(444,"naya");
        Emp e6= new Emp(444,"purana");
        Emp e7= new Emp(444,"aaj");
        e[0]=e1;
        e[1]=e2;
        e[2]=e3;
        e[3]=e4;
        e[4]=e5;
               
        for(Emp ee: e)
        {   
            System.out.println(ee.id+"-----"+ee.name);
        }   
        }

}

Thanks
Happy Programming!

Java Program : Enumerators example

class Enums1
{
    enum Months{jan,feb,mar,apr,may}
   
    public static void main(String[] args)
    {    Months m=Months.feb;
        System.out.println(m);
    }
}

---------------------------------------------------------

command to compile the program

D:\javaprograms>javac  Enums1.java   <ENTER>

command to run the compiled program

D:\javaprograms>java Emuns1  <ENTER>

You need to save and compile your program each time you make a change in it.
Thanks
Happy programming!

Python program : To find the longest Palindrome

As we all know, a palindrome is a word that equals its reverse. Here are some examples of palindromes: malayalam, gag, appa, amma.
We consider any sequence consisting of the letters of the English alphabet to be a word. So axxb,abbba and bbbccddx are words for our purpose. And aaabbaaa, abbba and bbb are examples of palindromes.
By a subword of a word, we mean a contiguous subsequence of the word. For example the subwords of the word abbba are a, b, ab, bb, ba, abb, bbb, bba, abbb, bbba and abbba.
In this task you will given a word and you must find the longest subword of this word that is also a palindrome.
For example if the given word is abbba then the answer is abbba. If the given word is abcbcabbacba then the answer is bcabbacb.

Solution hint

Any subword of w that is a palindrome is also a subword when w is reversed.

Input format

The first line of the input contains a single integer N indicating the length of the word. The following line contains a single word of length N, made up of the letters a,b,…, z.

Output format

The first line of the output must contain a single integer indicating the length of the longest subword of the given word that is a palindrome. The second line must contain a subword that is a palindrome and which of maximum length. If there is more than one subword palindrome of maximum length, print the one that is lexicographically smallest (i.e., smallest in dictionary order).

Test Data:

You may assume that 1 ≤ N ≤ 5000. You may further assume that in 30% of the inputs 1 ≤ N ≤ 300.

Example:

We illustrate the input and output format using the above examples:

Sample Input 1:

5
abbba

Sample Output 1:

5
abbba

Sample Input 2:

12
abcbcabbacba

Sample Output 2:

8
bcabbacb 
 
 
 
n=input()
w=input()
def longestPalSubstr(string):
    maxLength = 1
    k=0
    start = 0
    length = len(string)
 
    low = 0
    high = 0
 
    # One by one consider every character as center point of 
    # even and length palindromes
    for i in range(1, length):
        # Find the longest even length palindrome with center
    # points as i-1 and i.
        low = i - 1
        high = i
        while low >= 0 and high < length and string[low] == string[high]:
            if high - low + 1 > maxLength:
                start = low
                maxLength = high - low + 1
            low -= 1
            high += 1
 
        # Find the longest odd length palindrome with center 
        # point as i
        low = i - 1
        high = i + 1
        while low >= 0 and high < length and string[low] == string[high]:
            if high - low + 1 > maxLength:
                start = low
                maxLength = high - low + 1
            low -= 1
            high += 1
 
    #print "Longest palindrome substring is:",
    k=maxLength
    print(k)
    print(string[start:start + maxLength])
 
Thanks
Happy Programming ! 

Python program : String manipulations

The possible grades are A, AB, B, BC, C, CD, D with corresponding grade points 10, 9, 8, 7, 6, 5 and 4. The grade point average of a student is the sum of his/her grade points divided by the number of courses. For instance, if a student has taken two courses with grades A and C, the grade point average is 8 = (10+6)÷2. If a student has not completed any courses, the grade point average is defined to be 0.
You may assume that the data is internally consistent. For every grade, there is a corresponding course code and roll number in the input data.
Each section of the input starts with a line containing a single keyword. The first section begins with a line containing Courses. The second section begins with a line containing Students. The third section begins with a line containing Grades. The end of the input is marked by a line containing EndOfInput.
Write a Python program to read the data as described above and print out a line listing the grade point average for each student in the following format:
Roll Number~Full Name~Grade Point Average
Your output should be sorted by Roll Number. The grade point average should be rounded off to 2 digits after the decimal point. Use the built-in function round().
Here is a sample input and its corresponding output.
Sample Input
Courses
TRAN~Transfiguration~1~2011-2012~Minerva McGonagall
CHAR~Charms~1~2011-2012~Filius Flitwick
Students
SLY2301~Hannah Abbott
SLY2302~Euan Abercrombie
SLY2303~Stewart Ackerley
SLY2304~Bertram Aubrey
SLY2305~Avery
SLY2306~Malcolm Baddock
SLY2307~Marcus Belby
SLY2308~Katie Bell
SLY2309~Sirius Orion Black
Grades
TRAN~1~2011-2012~SLY2301~AB
TRAN~1~2011-2012~SLY2302~B
TRAN~1~2011-2012~SLY2303~B
TRAN~1~2011-2012~SLY2305~A
TRAN~1~2011-2012~SLY2306~BC
TRAN~1~2011-2012~SLY2308~A
TRAN~1~2011-2012~SLY2309~AB
CHAR~1~2011-2012~SLY2301~A
CHAR~1~2011-2012~SLY2302~BC
CHAR~1~2011-2012~SLY2303~B
CHAR~1~2011-2012~SLY2305~BC
CHAR~1~2011-2012~SLY2306~C
CHAR~1~2011-2012~SLY2307~B
CHAR~1~2011-2012~SLY2308~AB
EndOfInput
Sample Output
SLY2301~Hannah Abbott~9.5
SLY2302~Euan Abercrombie~7.5
SLY2303~Stewart Ackerley~8.0
SLY2304~Bertram Aubrey~0
SLY2305~Avery~8.5
SLY2306~Malcolm Baddock~6.5
SLY2307~Marcus Belby~8.0
SLY2308~Katie Bell~9.5
SLY2309~Sirius Orion Black~9.0
 
def gpa(l):
  n=len(l)
  m=0
  M=0
  for i in range(0,n):
    if l[i]=='A':
      m=10
    elif l[i]=='AB':
      m=9
    elif l[i]=='B':
      m=8
    elif l[i]=='BC':
      m=7
    elif l[i]=='C':
      m=6
    elif l[i]=='CD':
      m=5
    elif l[i]=='D':
      m=4
    elif l[i]=='E':
      return(0)
    M += m
    #M_round=round(M ,2)
  gpa = (M/n)
  return(round(gpa,2))


n=None
c=''
s=''
g=''
gl=''
while(n!='EndOfInput'):      
  n=input()
  c += n +'\n'
  if (n=='Students'):
    while(n!='Grades'):
      n=input()
      s += n +'~'+'\n'
  if (n=='Grades'):
    while(n!='EndOfInput'):
      n=input()
      g += n + '\n'
      gl += n
      

#print(c)
#print(s)
#print(g)
G=g[ :-12]
#print(gl)
#print(G)
S=s[ :-8]
gs=G.split('\n')
#print(G,end='')
#print(gs)
#print(S,end='')
stu=S.split('\n')
#print(stu)
stud=stu[ : -1]
#print(stud)
stut=[]
for a in range(0,len(stud)):
  stut += [stud[a].split('~')]
#print(stut)

sorted_stut= sorted(stut)
#print(sorted_stut)


for p in range(0,len(stut)):
  if gl.find(stut[p][0])== -1:
    gs += ['t~t~t~' + str(stut[p][0])+'~E']

#print(gs)

gsl=[]
for i in range(0,len(gs)):
  gsl += [gs[i].split('~')]
  
#print(gsl)
gslm=[]
for j in range(0,len(gsl)):
  gslm += [{gsl[j][3]:gsl[j][4]}]
#print(gslm)

r={}
for d in gslm:
  for k,v in d.items():
    r.setdefault(k,[]).append(v)

#print(r)
R={}
R=sorted(r.items())
#print(R)
grades=[]
for z in range(0,len(R)):
  grades += [R[z][1]]

#print(grades)


glist=[]
for x in range(0,len(grades)):
  glist += [gpa(grades[x])]
#print(glist)

outputlist=[]
for x in range(0,len(R)):
  outputlist += [[sorted_stut[x][0]] +['~']+[sorted_stut[x][1]]+['~']+ [str(glist[x])]+['\n']]
#print(outputlist)
for x in range(0,len(outputlist)):
    print(outputlist[x][0]+outputlist[x][1]+outputlist[x][2]+ outputlist[x][3]+outputlist[x][4])
 
Thanks
Happy Programming ! 
 
 

Python program : Sorting of lists

An airline has assigned each city that it serves a unique numeric code. It has collected information about all the direct flights it operates, represented as a list of pairs of the form (i,j), where i is the code of the starting city and j is the code of the destination.
It now wants to compute all pairs of cities connected by one intermediate hope --- city i is connected to city j by one intermediate hop if there are direct flights of the form (i,k) and (k,j) for some other city k. The airline is only interested in one hop flights between different cities --- pairs of the form (i,i) are not useful.
Write a Python function onehop(l) that takes as input a list of pairs representing direct flights, as described above, and returns a list of all pairs (i,j), where i != j, such that i and j are connected by one hop. Note that it may already be the case that there is a direct flight from i to j. So long as there is an intermediate k with a flight from i to k and from k to j, the list returned by the function should include (i,j). The input list may be in any order. The pairs in the output list should be in lexicographic (dictionary) order. Each pair should be listed exactly once.
For instance
>>> onehop([(2,3),(1,2)])
[(1, 3)]

>>> onehop([(2,3),(1,2),(3,1),(1,3),(3,2),(2,4),(4,1)])
[(1, 2), (1, 3), (1, 4), (2, 1), (3, 2), (3, 4), (4, 2), (4, 3)]

>>> onehop([(1,2),(3,4),(5,6)])
[] 
 
 def onehop(l):
  n=len(l)
  oh=[]
  for i in range(0,n):
    for j in range(0,n):
      if ((l[i][1]==l[j][0]) and (l[i][0]!=l[j][1])):
       oh += [(l[i][0], l[j][1])]
  myset=set(oh)
  return(sorted(myset))
 
Thanks
Happy programming ! 

Python program : Lists

Write a Python function frequency(l) that takes as input a list of integers and returns a pair of the form (minfreqlist,maxfreqlist) where
  • minfreqlist is a list of numbers with minimum frequency in l, sorted in ascending order
  • maxfreqlist is a list of numbers with maximum frequency in l, sorted in ascending
For instance
>>> frequency([13,12,11,13,14,13,7,11,13,14,12])
([7], [13])

>>> frequency([13,12,11,13,14,13,7,11,13,14,12,14,14])
([7], [13, 14])

>>> frequency([13,12,11,13,14,13,7,11,13,14,12,14,14,7])
([7, 11, 12], [13, 14]) 
 
def frequency(l):
  m=sorted(l)
  d={x:m.count(x) for x in m}
  hfelindex=[]
  lfelindex=[]
  hfel=[]
  lfel=[]
  k=list(d.keys())
  v=list(d.values())
  h=max(v)
  g=min(v)
  for i in range(0,len(v)):
    if v[i] == h:
	    hfelindex += [i]
  for j in hfelindex:
    hfel += [k[j]]
  p=sorted(hfel)
  for a in range(0,len(v)):
    if v[a] == g:
	    lfelindex += [a]
  for b in lfelindex:
    lfel += [k[b]]
  q=sorted(lfel)
  return((q,p))
 
Thanks
Happy programming ! 
 
 
 

Python program : To transpose a two dimensional matrix

A two dimensional matrix can be represented in Python row-wise, as a list of lists: each inner list represents one row of the matrix. For instance, the matrix
1  2  3
4  5  6 
would be represented as [[1,2,3],[4,5,6]].

The transpose of a matrix makes each row into a column. For instance, the transpose of the matrix above is
1  4  
2  5
3  6
Write a Python function transpose(m) that takes as input a two dimensional matrix using this row-wise representation and returns the transpose of the matrix using the same representation.

Here are some examples to show how your function should work. You may assume that the input to the function is always a non-empty matrix.

>>> transpose([[1,4,9]])
[[1], [4], [9]]

>>> transpose([[1,3,5],[2,4,6]])
[[1,2], [3,4], [5,6]]
0 
>>> transpose([[1,1,1],[2,2,2],[3,3,3]])
[[1,2,3], [1,2,3], [1,2,3]] 
 
 
 def transpose(m):
  
  result = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
  t=[]
  for r in result:
    t+= [r]
  return(t)
  

Python program : To check if given list of integers is a valley

A list of integers is said to be a valley if it consists of a sequence of strictly decreasing values followed by a sequence of strictly increasing values. The decreasing and increasing sequences must be of length at least 2. The last value of the decreasing sequence is the first value of the increasing sequence.

Write a Python function valley(l) that takes a list of integers and returns True if l is a valley and False otherwise.

Here are some examples to show how your function should work.


>>> valley([3,2,1,2,3])
True
>>> valley([3,2,1])
False
>>> valley([3,3,2,1,2])
False 
 
def valley(l): 
  n=len(l)
  downhill=0
  uphill=0
 
  
  for i in range(0,n-1):
      
    if(l[i]>l[i+1]):
       downhill +=1
    else:
      if i==(n-1):
        break
      elif(l[i]<l[i+1]):
        uphill +=1
      else:
          return(False)
  return(True)
 
 
Thanks
Happy Programming ! 
 

Python program :That returns True if each element in its input list is at least as big as the one before it.

Define a Python function ascending(l) that returns True if each element in its input list is at least as big as the one before it.

Here are some examples to show how your function should work.


>>> ascending([])
True
>>> ascending([3,3,4])
True
>>> ascending([7,18,17,19])
False 
 
def ascending(l):
  n=len(l)
  status=False
  if n<=1:
    return(True)
  for i in range(0,n-1):
    if(l[i]<=l[i+1]):
      status=True
    else:
      status=False
      break
  return(status)
      
      Thanks
Happy Programming ! 
 

Python program : Sum of all the perfect squares in a List

Write a function sumsquares(l) that takes as input a list of integers and retuns the sum of all the perfect squares in l.

Here are some examples to show how your function should work.


>>> sumsquares([1,4,9])
14
>>> sumsquares([10,11,12,15])
0
>>> sumsquares([16,20,25,30,625])
666 
 
from math import * 
def sumsquares(l):
  sum=0
  
  for i in l:
    sqr=sqrt(float(i))
    if ((sqr-int(sqr))==0.0) :
      sum=sum + i
  return(int(sum))
 

Python program : To calculate the depth of nesting

For an expression with parentheses, we can define the nesting depth as the maximum number of parentheses that are open when reading the expression from left to right. For instance, the nesting depth of "(33+77)(44-12)" is 1, while the nesting depth of "(a(b+c)-d)(e+f)" is 2.

Write a Python function depth(s) that takes a string containing an expression with parentheses and returns an integer, the nesting depth of s. You can assume that s is well-parenthesized: that is, that is, every "(" has a matching ")" after it and every ")" has a matching "(" before it.

Here are some examples to show how your function should work.


>>> depth("22")
0
>>> depth("(a+b)(a-b)")
1
>>> depth("(a(b+c)-d)(e+f)")
2
 
 
ef depth(S):
    current_max = 0
    max = 0
    n = len(S)
 
    # Traverse the input string
    for i in range(0,n):
        if S[i] == '(':
            current_max += 1
 
            if current_max > max:
                max = current_max
        elif S[i] == ')':
            if current_max > 0:
                current_max -= 1
            else:
                return -1
 
    # finally check for unbalanced string
    if current_max != 0:
        return -1
 
    return max
 
Thanks
Happy Programming ! 

Python Program : To check for perfect integer

A positive integer n is said to be perfect if the sum of the factors of n, other than n itself, add up to n. For instance 6 is perfect since the factors of 6 are {1,2,3,6} and 1+2+3=6. Likewise, 28 is perfect because the factors of 28 are {1,2,4,7,14,28} and 1+2+4+7+14=28.

Write a Python function perfect(n) that takes a positive integer argument and returns True if the integer is perfect, and False otherwise.

Here are some examples to show how your function should work.


>>> perfect(6)
True
>>> perfect(12)
False
 
 
def perfect(n):
  factors_of_n=[]
  sum=0
  for i in range(1,n+1):
    if n%i==0:
      factors_of_n = factors_of_n + [i]
  for j in factors_of_n[0:-1]:
    sum=sum + j
  return(sum==n)
 
Thanks
Happy Programming ! 

C++ program : Template Class

#include <iostream>
#include <string>
using namespace std;
void Swap(int& a,int& b  ){
int temp;
temp=a;
a=b;
b=temp;

}
void Swap(double& a,double& b  ){
double temp;
temp=a;
a=b;
b=temp;

}
void Swap(string& a,string& b  ){
string temp;
temp=a;
a=b;
b=temp;
}
int main() {
    int a, b;
    double s, t;
    string mr, ms;
    cin >> a >> b;
    cin >> s >> t;
    cin >> mr >> ms;
    Swap(a, b);
    Swap(s, t);
    Swap(mr, ms);
    cout << a << " " << b << " ";
    cout << s << " " << t << " ";
    cout << mr << " " << ms;
    return 0;
}

Thanks
Happy programming !


C++ program : Exception handling

#include <iostream>
#include <exception>
using namespace std;
class myexception:public exception{
                                  
                                  
 virtual const char *what() const throw(){std::cout<<"DivideByZero";return 0;}
};



class DivideByZero {
public:
    int numerator, denominator;
    DivideByZero(int a = 0, int b = 0) : numerator(a), denominator(b) {}
    int divide(int numerator, int denominator){
        if (denominator == 0) {
            throw myexception();
        }
        return numerator / denominator;
    }
};

int main() {
    DivideByZero d;
    int a, b;
    cin >> a >> b;

    try {
        d.divide(a, b);
    }

    catch (exception& e){
        cout << e.what() ;
    }
    return 0;
}

Thanks
Happy Programming !


C++ program : Template Function

#include<iostream>
using namespace std;
class Person {
    public: Person(int x) { cout << x << ":"; }
        Person() {}
};
class Instructor : virtual public Person {
    public: Instructor(int x) :Person(x) { }
};
class Student : virtual public Person {
    public: Student(int x) :Person(x) { }
};
class TA :  public Instructor,  public Student {
    public: TA(int x) :Student(x), Instructor(x) { cout << x * 3 ; }
};
int main() {
    int no;
    cin >> no;
    TA ta(no);
    return 0;
}

Thanks
Happy Computing !

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows