Java Tutorial : CountDownLatch

CountDownLatch are used to control to flow of multiple running task. CDL delays the run time of tasks before the main thread is ran. Its simply a timer that counts down to zero and when timer hits zero the main thread is ran but during its count down it is also running other tasks .

import java.util.concurrent.CountDownLatch; 

public class countdown 
{ 
    public static void main(String args[])  
                   throws InterruptedException 
    { 

//       Creating CountDownLatch , there are 3 task being executed 
        CountDownLatch cdl = new CountDownLatch(3); 
  
//       Naming tasks and setting delay times 
//        1 second delay
        Task Task_One = new Task(1000, cdl,  "task 1"); 
//        5 second delay
        Task Task_Two = new Task(5000, cdl,  "task 2"); 
//        3 second delay 
        Task Task_Three = new Task(3000, cdl,   "task 3"); 

//       Starting tasks
        Task_One.start(); 
        Task_Two.start(); 
        Task_Three.start(); 
      
  
        // The main task waits here
        cdl.await(); 
  
        // Main thread running 
        System.out.println(Thread.currentThread().getName() + 
                           " You have hacked the main frame!"); 
        
    } 
} 
  
// What main thread does while waiting  
class Task extends Thread 
{ 
    private int dt; 
    private CountDownLatch cdl; 
  
    public Task(int dt, CountDownLatch cdl, 
                                    String name) 
    { 
        super(name); 
        this.dt = dt; 
        this.cdl = cdl; 
    } 
  
    @Override
    public void run() 
    { 
        try
        { 
//           task ran complete print finished 
            Thread.sleep(dt); 
            cdl.countDown(); 
            System.out.println(Thread.currentThread().getName() 
                            + " finished"); 
        } 
//        if not throw exception 
        catch (InterruptedException e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 
Output :
task 1 finished
task 3 finished
task 2 finished
main You have hacked the main frame!

Android Studio Loading Animation Between Activities

Progress Dialog is dialog showing a progress indicator and an optional text message or view. The methods of Progress Dialog being used in this tutorial are: ProgressDialog.setTitle() – Used to set title of dialog box ProgressDialog.setMessage() – Used to set dialog message being displayed ProgressDialog.setProgressStyle() – Choose the style of indicator ProgressDialog.dismiss() – Dismiss the…

Android Studio Tutorial SeekBar

SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch thumb and drag left or right to set the current progress level or various other task. In this example, the seekbar will be used to display a percentage. As the user moves the SeekBar left to right the percentage value…

Python Ethereum Block Chain Interaction with Web3

This tutorial will show how to interact with the Ethereum blockchain using Python. To start, the Python library Web3 will need to be installed. The Web3 library allows you to interact with a local or remote Ethereum node, using a HTTP or IPC connection. Using Web3 you will be able to create smart contracts on…

Create Website Link Qr Code with Python

First, download the library qrcode this library will be used to generate a qrcode. Here is a link to the Documentation .

import qrcode

# Website link
url_link = "https://codeit.blog/"

#Generating Empty QR code
qr = qrcode.QRCode(
        # Editing Size of Qr image
        version=5,
        box_size=10,
        border=3)
# Adding the link to Qr
qr.add_data(url_link)
qr.make(fit=True)
img = qr.make_image()

# Saving Qr code to image file
img.save('qrLink.png')
Output

Python chr()

The chr() function returns a character that represents the specified unicode. Syntax chr(i) The chr() method takes only one integer as argument.The range may vary from 0 to 1,1141,111(0x10FFFF in base 16).The chr() method returns a character whose unicode point is num, an integer.If an integer is passed that is outside the range then the method returns…

Python callable()

The callable() method checks if a object is callable. Callable objects are True if object is callable and False if object is not callable. Syntax & Parameters callable(object)  The callable() method takes one argument, an object and returns one of the two values: returns True, if the object appears to be callable.returns False, if the…

Python bytes()

bytes() returns an immutable bytes object, made up of a sequence of integers in the range 0 <=x < 256. The returned bytes sequence is immutable. A mutable bytes sequence can be used instead by calling is bytearry() . Syntax bytes(]]) bytes() takes three optional parameters: source – initialize the array of bytes. Can be String…

Java Tutorial : Distance Between two Places in Miles

This tutorial will show to to get the distance between two places using Java programming. First, to start this project we need the Longitude and Latitude from two separate locations. For this example, I used Random.org to find two different GPS coordinates.

Once the coordinates are chosen, next have to convert those coordinates into radiants. This is done by using to toRadians function that is built into the Java Math package. The Longitude and Latitude of BOTH coordinates have to be to converted before they can be placed in the formula.

The formula being used for this project is the Haversine formula. The Haversine formula is used to find the distance between to point on a sphere. Note, the Earth has a radius of 3,956 and because the we are trying to find difference in miles between two points, we must multiple the formula output by the Earths’s radius.

Haversine Formula
{\displaystyle \operatorname {hav} \left(\Theta \right)=\operatorname {hav} \left(\varphi _{2}-\varphi _{1}\right)+\cos \left(\varphi _{1}\right)\cos \left(\varphi _{2}\right)\operatorname {hav} \left(\lambda _{2}-\lambda _{1}\right)}
    public static double coordinates (double LatOne, 
                     double LatTwo, double LonOne, 
                                  double LonTwo) 
    { 

        // toRadians function converts degrees to radians. 
        LonOne = Math.toRadians(LonOne); 
        LonTwo = Math.toRadians(LonTwo); 
        LatOne = Math.toRadians(LatOne); 
        LatTwo = Math.toRadians(LatTwo); 

        // Here the Haversine formula is being created 
        double deltaLon = LonTwo - LonOne;  
        double deltaLat = LatTwo - LatOne; 
        double formula = Math.pow(Math.sin(deltaLat / 2), 2) 
                 + Math.cos(LatOne) * Math.cos(LatTwo) 
                 * Math.pow(Math.sin(deltaLon / 2),2);      
        double fOutput = 2 * Math.asin(Math.sqrt(formula));

        // Earth's Radius multiplied by OP
        double r = 3956;  
        return(fOutput * r); 

    }  
    public static void main(String[] args) 

    { 

        // Input First destination Lon & Lat
        double LatOne =  -60.25901; 
        double LonOne = -12.82658;

       // Input Second destination Lon & Lat
        double LatTwo =  -47.01424; 
        double LonTwo = -148.97184; 

        //Printing output
        System.out.println("You are " + coordinates (LatOne, LatTwo, 
                           LonOne, LonTwo)+ " Miles Away"); 
    } 
} 
Output
You are 4623.74 Miles Away

Python bytearray()

The bytearray() method returns an array of bytes. Syntax bytearray(]]) source – source to initialize the array of bytes string – Converts the string to bytes using str.encode()integer – Creates an array of provided size, all initialized to nulliterable – Creates an array of size equal to the iterable count . Iterable integers must be…

Python breakpoint()

The breakpoint() function is a debugging function that is built into Python 3.7 . Use this built in function by adding breakpoint() where you suspect the error or are wanting to check for bugs. The pdb (Python Debugger) is a interactive source code debugger for Python programs. Python Debugger Commands : Ex. Output Once code…

Python bool()

The bool() function converts a value to a Boolean expression, True or False . If no parameter is given, by default the Boolean returns False. Boolean returns True if the parameter or value is True. Syntax bool([x]) x – is the value being evaluated by standard truth testing procedures. Example Output

Python Tutorial : Create a Counter

This tutorial will be how to create a counter using Python and the library tkinter

The tkinter library allows the user to create GUIs for users to interact with. Here tkinter will be used to create a frame the will contain a label, which will show the seconds being counted, and a stop button that will stop the counter and destroy the frame.

Start by creating the counting function. Here is a quick tutorial on Functions if you are unfamiliar with python functions.

seconds = 0
def seconds_Timer(Timer):
    seconds = 0
    # Counting function
    def count():
        global seconds
        seconds += 1
        Timer.config(text=str(seconds))
        Timer.after(1000, count)
    count()

Here is the frame the will contain the button and the seconds counted

# Creating the frame
root = tk.Tk()
# Setting Label
root.title("Counter")
Timer = tk.Label(root, fg="blue")
Timer.pack()
# Calling the Timer Function
seconds_Timer(Timer)
# Stop Button
button_STP = tk.Button(root, text='Stop', fg="red" , width=40, command=root.destroy)
# Adding the button 
button_STP.pack()

root.mainloop()
Output

Python bin()

The bin() function converts an integer , both positive and negative, into binary form. Syntax bin(n) n – integer being converted Example Output

Python ascii()

ASCII – American Standard Code for Information Interchange The ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U escapes. Syntax ascii(object) object – String , List , tuple etc. Ex. Output :

Python any()

The any() function returns True if any item in an iterable are true. If no item is true then False. Syntax & Parameters any(iterable) iterable – An iterable object list, tuple, dictionary etc. Ex. Output :

Java Check-In System Tutorial

Here I am building a Check – In system that could be used for patients/ Clients to check in for there appointment. The user will interact with the program by inputting their Name, Last 4 SSN and Phone number.

For this tutorial the library Swing needs to be imported. Swing is used to create Jframes and JLables which we will be using in this project to hold the content of the program. Here are some more tutorials on Swing if you are unfamiliar with the library.

Creating the main frame and giving the program a title

// Create frame & title 
        JFrame frame= new JFrame(); 
        frame.setTitle("JFrame Check-In Demo");
         
               // Main Panel Frame
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
 
        JPanel headingPanel = new JPanel();
//Heading title
        JLabel headingLabel = new JLabel("Welcome, Please fill out form to Check-In");
        headingPanel.add(headingLabel);
         
// Panel to define the layout
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints constr = new GridBagConstraints();
        constr.insets = new Insets(5, 5, 5, 5);     
        constr.anchor = GridBagConstraints.WEST;
 
 // Set the initial grid values to 0,0
        constr.gridx=0;
        constr.gridy=0;

This portion of code will set the labels and the Edit text so the users can input their information into the program.

        // Text  
        JLabel LabelOne  = new JLabel("Enter your name :");
        JLabel LabelTwo = new JLabel("Last 4 SSN :");
        JLabel LabelThree = new JLabel("Enter Phone # :");
         
        //  Edit Text  
        JTextField ClientName = new JTextField(20);
        JPasswordField Last = new JPasswordField(20);
        JTextField Phone  = new JTextField(20);
         
        panel.add(LabelOne , constr);
        constr.gridx=1;
        panel.add(ClientName, constr);
        constr.gridx=0; constr.gridy=1;
         
        panel.add(LabelTwo, constr);
        constr.gridx=1;
        panel.add(Last, constr);
        constr.gridx=0; constr.gridy=2;
         
        panel.add(LabelThree, constr);
        constr.gridx=1;
        panel.add(Phone , constr);
        constr.gridy=3;
         
        constr.gridwidth = 2;
        constr.anchor = GridBagConstraints.CENTER;

Here the button is being set and the action listener. When the button is clicked it will prompt a pop up to confirm the Check-In

        // "Check-In Button"
        JButton button = new JButton("Check-In");
        // add ActionListener to button
        button.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent e)
          {
        	  
        	//Reset edit Text and thank client   
            headingLabel.setText("Thanks for you for Checking-In");
            ClientName.setText("");
            Last.setText("");
            Phone .setText("");
            
            //Pop up Message 
            JOptionPane.showMessageDialog(frame,"Check-In confirmed,we will notify you.");  
            
          }
        });

Last bit of code adds it all to the panel

 // Add label and button to panel
        panel.add(button, constr);
  
        mainPanel.add(headingPanel);
        mainPanel.add(panel);
 
// Add panel to frame
        frame.add(mainPanel);
        frame.pack();
                frame.setSize(400, 400);
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
Output

Python all()

The all() function returns Ture if all elements are itterable and False if elements are not. Parameters all(iterable) iterable – is an object that can be looped over such as list , string , tuple etc. Ex. Output :

Python abs( )

abs() function is used to return an absolute value Syntax abs(n)n is the required integer Example Output :

Top 10 Python Interview Questions 2021

# 1 What’s Pickling and Unpickling? Pickling –  the process of a Python object hierarchy being converted into a byte streamUnpickling – is the inverse operation, where a byte stream is converted back into an object hierarchy. Pickling is also called serialization, marshalling, or flattening. # 2 What Is the Difference Between range() and xrange() Functions in Python?…

Java Tutorial : JOptionPane

JOptionPane is a java Class used to display dialog boxes. There are three types of JOptionPanes : message dialog box, confirm dialog box and input dialog box.

Message Dialog Box
import javax.swing.*;  
public class op {  
JFrame f;  
op(){  
    f=new JFrame();  
    JOptionPane.showMessageDialog(f,"www.codeit.blog");  
}  
public static void main(String[] args) {  
    new op();  
}  
}  
Confirm Dialog Box
import javax.swing.*;  
import java.awt.event.*;  
public class op extends WindowAdapter{  
JFrame f;  
op(){  
    f=new JFrame();   
    f.addWindowListener(this);  
    f.setSize(300, 300);  
    f.setLayout(null);  
    f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);  
    f.setVisible(true);  
}  
public void windowClosing(WindowEvent e) {  
    int i=JOptionPane.showConfirmDialog(f,"Confirm Payment");  
if(i==JOptionPane.YES_OPTION){  
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
}else {
	System.out.print("Nope this is not cool");
}
}  
public static void main(String[] args) {  
    new  op();  
}     
}
Input Dialog Box
import javax.swing.*;  
public class op {  
JFrame f;  
op(){  
    f=new JFrame();   
    String Code=JOptionPane.showInputDialog(f,"Enter Verification Code");      
}  
public static void main(String[] args) {  
    new op();  
}  
}

Warning Dialog Box

import javax.swing.*;  
public class op {  
JFrame f;  
op(){  
    f=new JFrame();  
    JOptionPane.showMessageDialog(f,"Uh Oh something may be wrong","Warning",JOptionPane.WARNING_MESSAGE);     
}  
public static void main(String[] args) {  
    new op();  
}  
}  

Error Dialog Box
import javax.swing.*;  
public class op {  
JFrame f;  
op(){  
    f=new JFrame();  
    JOptionPane.showMessageDialog(f,"Something is fucked up!","Error",JOptionPane.ERROR_MESSAGE);     
}  
public static void main(String[] args) {  
    new op();  
}  
}

Java Tutorial : How to Use Swing JTables

The Swing java package is used to create GUI for user inputted data. It is a really useful library that allows you to easily create applications to handle data. Some functions include JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu…etc. However this tutorial will cover JTables.

 JTable are used to display and edit regular two-dimensional tables of cells.

This tutorial will show how to create a Jtable, input data into the table and create a button that will print out values of a column.

Here the columns are given Titles and the data is being set for the JTable. In this example, the data that is being inputted is a Land Lords Tenant list. This List is used to keep track of renters who still need to pay their rent. In this table there is the renter’s Tenant #, Name ,Rent Amount and Paid/Unpaid status.

 //Table Headers
        String[] columns = new String[] {
            "Tenant # ", "Name", "Rent Amount", "Paid/Unpaid"
        };
         
        //data for array 
        Object[][] data = new Object[][] {
            {1, "John", 600 , "Paid" },
            {2, "Jane", 1000, "Paid" },
            {3, "Mat", 725, "Unpaid" },
            {4, "Kelly", 600 , "Paid" },
            {5, "Pat", 1000, "Unpaid" },
            {6, "Kate", 725, "Unpaid" },
        };

This portion of code adds that data to the table as well as creates the button. the button will print out the last Column which shows is the tenant has paid their rent or not.

 //create table with data
        JTable table = new JTable(data, columns);
        JButton button = new JButton("Click Here..!");
                
        //add the table to the frame
        this.add(new JScrollPane(table));
        //add button
        this.add(button, BorderLayout.PAGE_END);

Controls what happens when the button is clicked

//action when button is clicked
        button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				ArrayList<Object> list = new ArrayList();
				for(int i = 3;i<table.getModel().getRowCount();i++)
				{
				list.add(table.getModel().getValueAt(i,3)); //get the all row values at column index 0
	
				//printing out list
				System.out.print(list);
				}
					

Final portion of code, this sets the title of the JFrame that hosts the JTable data

this.setTitle("Table Example");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
        this.pack();
        this.setVisible(true);
    }
     
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Table();
            }
Output :

When the button at the top is click the values of the Paid/Unpaid column should be printed out in console

Full Code
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;

public class Table extends JFrame
{
    public Table()
    {
        //Table Headers
        String[] columns = new String[] {
            "Tenant # ", "Name", "Rent Amount", "Paid/Unpaid"
        };
         
        //data for array 
        Object[][] data = new Object[][] {
            {1, "John", 600 , "Paid" },
            {2, "Jane", 1000, "Paid" },
            {3, "Mat", 725, "Unpaid" },
            {4, "Kelly", 600 , "Paid" },
            {5, "Pat", 1000, "Unpaid" },
            {6, "Kate", 725, "Unpaid" },
        };
        //create table with data
        JTable table = new JTable(data, columns);
        JButton button = new JButton("Click Here..!");
                
        //add the table to the frame
        this.add(new JScrollPane(table));
        //add button
        this.add(button, BorderLayout.PAGE_START);
        
        
        //action when button is clicked
        button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				ArrayList<Object> list = new ArrayList();
				for(int i = 3;i<table.getModel().getRowCount();i++)
				{
				list.add(table.getModel().getValueAt(i,3)); //get the all row values at column index 0
	
				//printing out list
				System.out.print(list);
				}
					
			}
				 
        });
        
        this.setTitle("Table Example");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
        this.pack();
        this.setVisible(true);
        
        
        
    }
     
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Table();
            }
        });
    }   
}

Java HashMap Tutorial

HashMaps are Maps that store objects in pairs called Keyset and Values.

Creating the hashmap, this hashmap will be a Contact List

// Create a HashMap , the objects are our Contacts 
HashMap<String, String> Contacts = new HashMap<String, String>();

Here the Keyset and Values are added. For this example , the contact’s Name and Number are being added

Note : the Values are being printed out which would reference the contact’s phone number

// Add keys and values (Name, Number)
Contacts.put("Pat", "123-321");
 Contacts.put("Jan", "321-123");
Contacts.put("Amy", "342-123");
Contacts.put("Mat", "543-123");
System.out.println(Contacts.values());

The Keyset or contact’s Name is being printed out here

 for (String i : Contacts.keySet()) {
		    		  System.out.println("Contact : " +i);
		    
		    	 }}}

remove() can be used to remove objects from map

Contacts.remove("Pat");

get() is used to select certain objects from the hashmap

Contacts.get("Mat");

clear() is used to erase all objects from hashmap

Contacts.clear()

Printing out the entire Contact List HashMap

for (String i : Contacts.keySet()) {
		        System.out.println("Name: " + i + " Number: " + Contacts.get(i));
Output
Name: Mat Number: 543-123
Name: Pat Number: 123-321
Name: Jan Number: 321-123
Name: Amy Number: 342-123
Full code
package Example;
import java.util.HashMap; 

public class example {
	
	public static void main(String[] args) {
		 
		    // Create a HashMap with object called Contacts 
		    HashMap<String, String> Contacts = new HashMap<String, String>();

		    // Add keys and values (Name, Number)
		    Contacts.put("Pat", "123-321");
		    Contacts.put("Jan", "321-123");
		    Contacts.put("Amy", "342-123");
		    Contacts.put("Mat", "543-123");
		    System.out.println(Contacts.values());
		    
	    for (String i : Contacts.keySet()) {
		        System.out.println("Name: " + i + " Number: " + Contacts.get(i));
		    	 }}}

Must Know Python Tricks

Here are some cool python tricks to play around with.

Trick # 1 : Setting Multiple Values
#Set multi values
i =  [57, 909, 8]
x, y, z = i

print(x,y,z)
Output :

57 909 8

Trick # 2 : Swap Values
#swap numbers
x=25
y=50
y, x =x, y

print (x , y )

Output :

50 25

Trick # 3 : Print X Times
#Print X number of times
x = 5
String = "Code It "

print(String * x)
Output :

Code It Code It Code It Code It Code It

Trick # 4 : Find Most Recurring Number
#Most recurring value
List = [21, 55, 21, 34, 21, 21, 76, 76, 92, 99, 65]

print(max(set(List), key = List.count))
Output :

21

Trick # 5 : Reverse Order of a List
# Reversing Numbers
list = [5,10,15,20]
print( list [::-1])

20, 15, 10, 5

How to Create a Bitcoin Brain Wallet with Python

This tutorial will show how to build a very basic Brain Wallet with Python. A Brain Wallet is a phrase that is created by the user the that user links to the seed of a crypto wallet. So in order to access the crypto wallet ,the users must type in the phrase exactly. The wallet can be used to store any type of crypto currency. The thing is, you must not for get the brain wallet phrase! If you forget or miss spell the phrase you will not be able to access the wallet. Once the phrase is forgotten the currency will be lost forever.

Before getting started with the code, the python library bitcoin must be imported. This library is really useful if you want to use python to interact or create bitcoin block chain structures.

First, we must create a Private key and choose a phrase for the brain wallet. This can be done by using the built in functions from the library. So for this example, the phrase is ” Never forget you’r Brain Wallet Phrase! ” . Note that privtopub() is used to turn the private key to a public key.

from bitcoin import *

#Creating the Phrase
Private_Key = sha256("Never forget your Brain Wallet Phrase!")

toPublic_Key = privtopub(Private_Key)

Lastly, a bitcoin address must be given to the phrase so it can interact with the block chain. Note that if you were to miss spell or leave out a character or symbol to the phrase it will Not be excepted because the hash of the Phrase will be different.

#Setting the Bitcoin Address
Create_Adress = pubtoaddr(toPublic_Key)

print("Your Brain Wallet :" ,Create_Adress)
Output :
Your Brain Wallet : 1KHtp1E9mQUG1b5DDzd2TmTLAqX7t8JZuT

There it is, the phrase has be turned in to a hash code and given a bitcoin address. So key take away would be Brain wallets are cool but kinda impractical unless your trying to flee the country and they are suspect to being hacked into so if you are gonna create a brain wallet make sure to use a randomly generated phrase because it can be cracked if it is a weak phrase. Also its probably best to create a more advanced brain wallet than the one above if you plan on using actually it . Feel free to play around with the code, the full code is posted below.

from bitcoin import *

#Creating the Phrase
Private_Key = sha256("Never forget your Brain Wallet Phrase!")
toPublic_Key = privtopub(Private_Key)
#Setting the Bitcoin Address
Create_Adress = pubtoaddr(toPublic_Key)
print("Your Brain Wallet :" ,Create_Adress)