Snippets Collections
interface Test
{ public abstract boolean check(int n);
}

public class LambdaTest
{
	public static void main(String[] args)
	{
		Test t = (n) -> (n%2)==0;  // Test t = (int n) -> (n%2)==0;
		                           // Test t = n -> (n%2)==0;
		
		java.util.Scanner scan = new java.util.Scanner(System.in);
		
		System.out.println("Enter a number: ");
		
		int x = scan.nextInt();
		System.out.println(x + " is even? " + t.check(x));
		
		x = scan.nextInt();
		System.out.println(x + " is even? " + t.check(x));
		
		t = (n) -> n >= 0;
		
		x = scan.nextInt();
		System.out.println(x + " is non-negative? " + t.check(x));
		
		x = scan.nextInt();
		System.out.println(x + " is non-negative? " + t.check(x));
	}
}
interface Capture
{ int compute(int n); }

public class CaptureDemo
{   private int a = 100;
    
	public int getA(){ return this.a; }
	
	public static void main(String[] args)
	{
		CaptureDemo c1 = new CaptureDemo();
		System.out.println("Value: "+c1.getA());
		
		int x = 200;
		Capture ob = (n)-> {
			int z = 12;
			int result = z + n + x + c1.getA();
			c1.a = 9876;
			//x++;
			return result;
		};
		
		System.out.println(ob.compute(40));
		System.out.println("Value: "+c1.getA()); 
	}

}
interface ExceptionDemo
{ String compute(String s) throws NullPointerException; }

class DemoOfLambdaException
{   public static void main(String[] args)
	{
		ExceptionDemo ed = (str) -> {
		if(str.length()==0 || str==null)
			throw new NullPointerException("No String is available");
		else
			return "The string "+str+" has "+str.length()+" characters.";
	};
	
	java.util.Scanner scan = new java.util.Scanner(System.in);
	System.out.println("Enter a String: ");
	String s = scan.nextLine();
	System.out.println(ed.compute(s));
	}
}
public interface MyNum
{ public abstract double getNum();
}
public class LambdaDemo
{
	public static void main(String[] args)
	{
		MyNum num = () -> 123.456;
		System.out.println("This is the value: " + num.getNum());
		
		num = () -> Math.random() * 100;
		System.out.println("This is the random value: " + num.getNum());
		System.out.println("This is one more random value: " + num.getNum());
	}
}
interface MyFunction<T>
{ T compute(T value); }

public class GenericLambda
{
	public static void main(String[] args)
	{
		MyFunction<String> reverse = (s) -> {
			String r = "";
			for(int i=s.length()-1; i>=0; i--)
				r += s.charAt(i);
			return r;
		};
		
		MyFunction<Integer> factorial = (n) -> {
			            int result = 1;
						for(int i=2; i<=n; i++)
							result *= i;
						return result;
		};
		
		System.out.println("Reversed string: " + reverse.compute("Lambda"));
		System.out.println("Factorial: " + factorial.compute(5));
	}
}
interface Numbers
{ public abstract boolean checkFactor(int n, int m); }

public class LambdaFactor
{
	public static void main(String[] args)
	{
		java.util.Scanner scan = new java.util.Scanner(System.in);
		
		Numbers factor = (n, m) -> (n%m)==0;
		
		System.out.println("Enter two numbers: ");
		int n = scan.nextInt(); int m = scan.nextInt();
		System.out.println(m + " is a factor of " + n + ": " + factor.checkFactor(n, m));
	}
}
interface Args
{ String compute(String s); }

public class ArgsDemo
{
	public void m(Args obj, String s)
	{ System.out.println(obj.compute(s)); 
	 }
	
	public static void main(String[] args)
	{
		ArgsDemo ad = new ArgsDemo();
		
		Args L1 = (str) -> str.toUpperCase();
		ad.m(L1, args[0]);
		
		ad.m((str)->str.toLowerCase(), args[0]);
	}
}
interface NumFunction
{ long factorial(int n); }

public class BlockLambdaDemo
{
	public static void main(String[] args)
	{
		NumFunction nf = (n) -> {
			            int result = 1;
						for(int i=2; i<=n; i++)
							result *= i;
						return result;
		};
		
		java.util.Scanner scan = new java.util.Scanner(System.in);
		
		System.out.println("Enter an integer: ");
		int n = scan.nextInt();
		System.out.println("The factorial of " + n + " is " + nf.factorial(n));
		
		System.out.println("Enter an integer: ");
		n = scan.nextInt();
		System.out.println("The factorial of " + n + " is " + nf.factorial(n));
		
	}
}
interface StringFunction
{ String reverse(String s); }

public class BlockLambdaReverse
{
	public static void main(String[] args)
	{
		java.util.Scanner scan = new java.util.Scanner(System.in);
		
		StringFunction sf = (s) -> {
			String r = "";
			for(int i=s.length()-1; i>=0; i--)
				r += s.charAt(i);
			return r;
		};
		System.out.println("Enter an input string: ");
		String s = scan.nextLine();
		System.out.println("The reverse of "+s+" is "+sf.reverse(s));
	}
}
import java.util.*;
public class TreeSetDemo
{ 
 class MyComparator implements Comparator<String>
{ public int compare(String s1, String s2)
{ if(s1.compareTo(s2)<0) 
return -1;
 if(s1.compareTo(s2)>0) 
 return +1;
 return 0;
}
}
public static void main(String[] args)
{
TreeSet<String> ts = 
 new TreeSet<>(new TreeSetDemo().new MyComparator());
ts.add("hello"); ts.add("world"); ts.add("version");
ts.add("main"); ts.add("method");
System.out.println("Contents: " + ts);
System.out.println();
System.out.println("Higher than \"main\": " + ts.higher("main"));
System.out.println("Lower than \"main\": " + ts.lower("main"));
System.out.println();
SortedSet s = ts.tailSet("method");
System.out.println("TailSet from \"method\": " + s);
s = ts.headSet("method");
System.out.println("HeadSet from \"method\": " + s);
System.out.println();
Iterator it = ts.iterator();
System.out.print("Iteration: ");
while(it.hasNext())
System.out.print(it.next()+" ");
System.out.println();
System.out.println();
Iterator it2 = ts.descendingIterator();
System.out.print("Iteration Descending: ");
while(it2.hasNext())
System.out.print(it2.next()+" ");
System.out.println();
System.out.println("First one: " + ts.pollFirst());
System.out.println("Last one: " + ts.pollLast());
System.out.println("Contents: " + ts);
}
}
import java.util.*;
public class LinkedHashSetDemo
{
public static void main(String[] args)
{
LinkedHashSet<String> hs = new LinkedHashSet<>();
hs.add("first"); hs.add("second"); hs.add("third"); 
hs.add("fourth"); hs.add("fifth"); hs.add("sixth");
System.out.println("Contents: " + hs);
System.out.println("Size: " + hs.size());
System.out.println();
Object[] arrayS = hs.toArray();
for(Object each: arrayS)
System.out.println(each);
System.out.println();
String[] arrayS2 = new String[hs.size()];
arrayS2 = hs.toArray(arrayS2);
for( String each: arrayS2)
System.out.println(each);
System.out.println();
Iterator it = hs.iterator();
while(it.hasNext())
System.out.println(it.next());
System.out.println();
System.out.println("Empty? " + hs.isEmpty());
System.out.println();
hs.remove("fourth");
System.out.println("Contents: " + hs);
System.out.println("Size: " + hs.size());
}
}
import java.util.*;
public class HashSetDemo
{
public static void main(String[] args)
{
HashSet<String> hs = new HashSet<>();
hs.add("first"); hs.add("second"); hs.add("third"); 
hs.add("fourth"); hs.add("fifth"); hs.add("sixth");
System.out.println("Contents: " + hs);
System.out.println("Size: " + hs.size());
System.out.println();
Object[] arrayS = hs.toArray();
for(Object each: arrayS)
System.out.println(each);
System.out.println();
String[] arrayS2 = new String[hs.size()];
arrayS2 = hs.toArray(arrayS2);
for( String each: arrayS2)
System.out.println(each);
System.out.println();
Iterator it = hs.iterator();
while(it.hasNext())
System.out.println(it.next());
System.out.println();
System.out.println("Empty? " + hs.isEmpty());
System.out.println();
hs.remove("fourth");
System.out.println("Contents: " + hs);
System.out.println("Size: " + hs.size());
}
}
import java.util.*;
public class TreeMapDemo
{
public static void main(String[] args)
{
TreeMap<String, Integer> tm = new TreeMap<>();
tm.put("Anand", 20);
tm.put("Mary", 20);
tm.put("Ravi", 21);
tm.put("John",19);
System.out.println("Contents: "+tm);
System.out.println();
Set<String> keys = tm.keySet();
for(String k: keys)
System.out.println(k+" -- "+tm.get(k));
System.out.println();
Set<Map.Entry<String, Integer>> entries = tm.entrySet();
for(Map.Entry<String,Integer> each: entries)
System.out.println(each.getKey()+" -- "+each.getValue());
System.out.println();
}
}
import boto3
from botocore.exceptions import ClientError
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key

    def copy(self, dest_object):
        """
        Copies the object to another bucket.

        :param dest_object: The destination object initialized with a bucket and key.
                            This is a Boto3 Object resource.
        """
        try:
            dest_object.copy_from(
                CopySource={"Bucket": self.object.bucket_name, "Key": self.object.key}
            )
            dest_object.wait_until_exists()
            logger.info(
                "Copied object from %s:%s to %s:%s.",
                self.object.bucket_name,
                self.object.key,
                dest_object.bucket_name,
                dest_object.key,
            )
        except ClientError:
            logger.exception(
                "Couldn't copy object from %s/%s to %s/%s.",
                self.object.bucket_name,
                self.object.key,
                dest_object.bucket_name,
                dest_object.key,
            )
            raise

def copy_all_objects_between_buckets(source_bucket, dest_bucket):
    """
    Copies all objects from the source bucket to the destination bucket.

    :param source_bucket: The name of the source S3 bucket.
    :param dest_bucket: The name of the destination S3 bucket.
    """
    s3_resource = boto3.resource('s3')
    source_bucket_obj = s3_resource.Bucket(source_bucket)
    
    for s3_object in source_bucket_obj.objects.all():
        source_obj = s3_resource.Object(source_bucket, s3_object.key)
        dest_obj = s3_resource.Object(dest_bucket, s3_object.key)

        wrapper = ObjectWrapper(source_obj)
        wrapper.copy(dest_obj)

if __name__ == "__main__":
    # Example usage
    source_bucket_name = 'your-source-bucket'
    dest_bucket_name = 'your-destination-bucket'

    copy_all_objects_between_buckets(source_bucket_name, dest_bucket_name)
import java.util.*;
public class LinkedHashMapDemo
{
public static void main(String[] args)
{
LinkedHashMap<String, Integer> hm = new LinkedHashMap<>();
hm.put("Anand", 20);
hm.put("Mary", 20);
hm.put("Ravi", 21);
hm.put("John",19);
System.out.println("Contents: "+hm);
System.out.println();
Set<String> keys = hm.keySet();
for(String k: keys)
System.out.println(k+" -- "+hm.get(k));
System.out.println();
Set<Map.Entry<String, Integer>> entries = hm.entrySet();
for(Map.Entry<String,Integer> each: entries)
System.out.println(each.getKey()+" -- "+each.getValue());
System.out.println();
}
}
import java.util.*;
public class HashMapDemo
{
public static void main(String[] args)
{
HashMap<String, Integer> hm = new HashMap<>();
hm.put("Anand", 20);
hm.put("Mary", 20);
hm.put("Ravi", 21);
hm.put("John",19);
System.out.println("Contents: "+hm);
System.out.println();
Set<String> keys = hm.keySet();
for(String k: keys)
System.out.println(k+" -- "+hm.get(k));
System.out.println();
Set<Map.Entry<String, Integer>> entries = hm.entrySet();
for(Map.Entry<String,Integer> each: entries)
System.out.println(each.getKey()+" -- "+each.getValue());
System.out.println();
}
}
import java.util.*;
public class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList<String> ll = new LinkedList<>();
ll.add("first"); ll.add("second"); ll.add("fourth");
System.out.println("Contents: " + ll);
System.out.println();
ll.add(2, "third"); ll.addFirst("zero");
System.out.println("Contents: " + ll);
System.out.println();
// experiment with more methods here and extend the program
}
}
import java.util.*;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<>();
al.add("one"); al.add("two"); al.add("three"); al.add("four"); 
al.add("five");
System.out.println("Contents: " + al);
System.out.println("Size: " + al.size());
System.out.println();
for(String s: al)
System.out.println(s);
System.out.println();
for(int i=0; i<al.size(); i++)
System.out.println(al.get(i));
System.out.println();
Iterator it = al.iterator();
ListIterator lit = al.listIterator();
while(it.hasNext())
System.out.println(it.next());
System.out.println();
while(lit.hasNext())
System.out.println(lit.next());
System.out.println();
while(lit.hasPrevious())
System.out.println(lit.previous());
System.out.println();
al.add(0, "zero");
System.out.println("Contents: " + al);
System.out.println("Size: " + al.size());
al.remove("one"); al.remove(0);
System.out.println("Contents: " + al);
System.out.println("Size: " + al.size())
}
}
import java.util.*;

public class SeparateChaining<T>
{	
	private static final int DEFAULT_TABLE_SIZE = 101;
	private List<T>[] theLists;
	private int currentSize;
	
	public SeparateChaining()
	{
		this(DEFAULT_TABLE_SIZE);
	}
	
	public SeparateChaining(int size)
	{
		theLists = new LinkedList[size];
		for(int i=0; i<theLists.length; i++)
			theLists[i] = new LinkedList<>();
	}
	
	public void insert(T element)
	{
		List<T> whichList = theLists[myhash(element)];
		if(!whichList.contains(element))
		{
			whichList.add(element);
			currentSize++;
		}
	}
	
	public void remove(T element)
	{
		List<T> whichList = theLists[myhash(element)];
		if(whichList.contains(element))
		{
			whichList.remove(element);
			currentSize--;
		}
	}
	
	public boolean contains(T element)
	{
		List<T> whichList = theLists[myhash(element)];
		return whichList.contains(element);
	}
	
	public void makeEmpty()
	{
		for( int i = 0; i < theLists.length; i++ )
			theLists[ i ].clear();
		currentSize = 0;
	}
	
	private int myhash(T element)
	{
		int hashValue = element.hashCode();
		hashValue %= theLists.length;
		if(hashValue < 0)
			hashValue += theLists.length;
		return hashValue;
	}
	
	public void showAll()
	{
		for(int i=0; i<theLists.length; i++)
			System.out.println("Chain "+i+" : "+theLists[i]);
	}
	
	public static void main(String[] args)
	{
		SeparateChaining<String> sc = new SeparateChaining(7);
		sc.insert("hello"); sc.insert("java"); sc.insert("world"); sc.insert("programming");
		sc.insert("separate"); sc.insert("chaining");
		System.out.println("java is present " + sc.contains("java"));
		sc.showAll();
		
	}
	
}
import java.util.*;

public class QuadraticProbing<T>
{   
	private static final int DEFAULT_TABLE_SIZE = 101;
	private HashEntry<T>[] array;
	private int currentSize;
	
	public QuadraticProbing()
	{	this(DEFAULT_TABLE_SIZE); }
	
	public QuadraticProbing(int size)
	{	array = new HashEntry[size]; 
		makeEmpty();
	}
	
	public void makeEmpty()
	{   currentSize = 0;
		for(int i=0; i<array.length; i++)
			array[i] = null;
	}
	
	public boolean contains(T element)
	{
		int currentPos = findPos(element);
		return isActive(currentPos);
	}
	
	private int findPos(T element)
	{
		int offset = 1;
		int currentPos = myhash(element);
		while(array[currentPos]!=null&&!array[currentPos].element.equals(element))
		{
			currentPos += offset;
			offset += 2;
			if(currentPos>=array.length)
				currentPos -= array.length;
		}
		return currentPos;
	}
	
	private boolean isActive(int currentPos)
	{
		return array[currentPos]!=null && array[currentPos].isActive;
	}
	
	public void insert(T element)
	{
		int currentPos = findPos(element);
		if(isActive(currentPos))
			return;
		array[currentPos] = new HashEntry<>(element, true);
	}
	
	public void remove(T element)
	{
		int currentPos = findPos(element);
		if(isActive(currentPos))
				array[currentPos].isActive = false;
	}
	
	private int myhash(T element)
	{   
		int hashValue = element.hashCode();
		hashValue %= array.length;
		if(hashValue < 0)
			hashValue += array.length;
		return hashValue;
	}
	
	private static class HashEntry<T>
	{
		public T element;
		public boolean isActive;
		
		public HashEntry(T e)
		{ this(e, true); }
		
		public HashEntry(T e, boolean i)
		{ element = e; isActive = i; }
		
		public T getElement(){ return this.element; }
	}
	
	public void showAll()
	{   for(HashEntry each: array)
			if(each != null)
				System.out.print(each.getElement()+"  ");
			else
				System.out.print("None ");
	}
	
	public static void main(String[] args)
	{
		QuadraticProbing<Integer> sc = new QuadraticProbing(10);
		sc.insert(89); sc.insert(18); sc.insert(49); sc.insert(58); sc.insert(69); 
		sc.showAll();
		
	}
}
 
# RECOMMENDED WAY
import boto3
client = boto3.client(
    s3,                         # boto3 will get the credentials either from
    region_name=us-east-1       # environment vars. or the .aws/credentials file.
)
class Superclass<T> {
    private T element;
    
    public Superclass(T element) {
        this.element = element;
    }
    
    public T getEle() {
        return this.element;
    }
}

class Subclass<T, V> extends Superclass<T> {
    private V value;
    
    public Subclass(T element, V value) {
        super(element);
        this.value = value;
    }
    
    public V getValue() {
        return this.value;
    }
}

public class Hierarchy {
    public static void main(String[] args) {
        System.out.println(" ABC");
        Subclass<String, Integer> h1 = new Subclass<>("abc", 123);
        System.out.println(h1.getEle());
        System.out.println(h1.getValue());
    }
}
public class GenericMethod {
    public static <K, R, V> boolean compare(Pack<K, R> p1, Pack<K, V> p2) {
        return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue());
    }

    public static void main(String[] args) {
        Pack<Integer, String> p1 = new Pack<>(1, "pack");
        Pack<Integer, String> p2 = new Pack<>(2, "abc");
        Pack<Integer, String> p3 = new Pack<>(1, "pack");
        
        System.out.println("p1 & p2 are same?: " + compare(p1, p2));
        System.out.println("p1 & p3 are same?: " + compare(p1, p3));
    }
}

class Pack<K, V> {
    private K key;
    private V value;

    public Pack(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return this.key;
    }

    public V getValue() {
        return this.value;
    }
}
import boto3

def read_s3_file(bucket_name, file_name):
    s3 = boto3.client('s3')
    try:
        response = s3.get_object(Bucket=bucket_name, Key=file_name)
        return response['Body'].read().decode('utf-8')
    except Exception as e:
        print(f"Error reading file from S3: {e}")
        return None
import boto3
import json

def read_ocr_from_s3(bucket_name, key_name):
    s3 = boto3.client('s3')
    response = s3.get_object(Bucket=bucket_name, Key=key_name)
    ocr_data = json.loads(response['Body'].read().decode('utf-8'))
    return ''.join([item["text"] for item in ocr_data])
@import 'jeet'

@import 'nib'

​

.large-header

   position: relative

   width: 0%

   background: #eeeeee

   overflow: hidden

   background-size: cover
10
   background-position: center center

   z-index: 1

​

.demo .large-header

   background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/4994/demo-bg.jpg')

​
16
.main-title

   position: absolute

   margin: 0

   padding: 0

   color: #ffffff

   text-align: center

   top: 50%

   left: 50%
@import 'jeet'

@import 'nib'

​

.large-header

   position: relative

   width: 0%

   background: #eeeeee

   overflow: hidden

   background-size: cover
10
   background-position: center center

   z-index: 1

​

.demo .large-header

   background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/4994/demo-bg.jpg')

​
16
.main-title

   position: absolute

   margin: 0

   padding: 0

   color: #ffffff

   text-align: center

   top: 50%

   left: 50%
<div class="container demo">

   <div class="content">

      <div id="large-header" class="large-header">

         <canvas id="demo-canvas"></canvas>

         <h1 class="main-title"><span>IMD <span class='thin'>[ Coach ]</h1>

      </div>

   </div>

</div>
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the Email address");
        String email = scanner.nextLine();

        if (isValidEmail(email)) {
            System.out.println("Valid Email address");
        } else {
            System.out.println("Invalid Email address");
        }

        scanner.close();
    }

    public static boolean isValidEmail(String email) {
        // Check if email contains '@' character
        if (!email.contains("@")) {
            return false;
        }

        // Split email address into local part and domain part
        String[] parts = email.split("@");
        String localPart = parts[0];
        String domainPart = parts[1];

        // Check if local part and domain part are not empty
        if (localPart.isEmpty() || domainPart.isEmpty()) {
            return false;
        }

        // Check if domain part contains '.' character
        if (!domainPart.contains(".")) {
            return false;
        }

        // Split domain part into domain name and domain extension
        String[] domainParts = domainPart.split("\\.");
        String domainName = domainParts[0];
        String domainExtension = domainParts[1];

        // Check if domain extension is valid
        if (!domainExtension.equals("in") && !domainExtension.equals("com")
                && !domainExtension.equals("net") && !domainExtension.equals("biz")) {
            return false;
        }

        return true;
    }
}
import java.util.*;

public class Stack<E extends Number> {
    private ArrayList<E> list;

    public Stack(ArrayList<E> list) {
        this.list = list;
    }

    public void push(E element) {
        list.add(element);
    }

    public E pop() {
        E v = list.get(list.size() - 1);
        list.remove(list.size() - 1);
        return v;
    }

    public double avg() {
        int len = list.size();
        double sum = 0.0;
        for (E item : list) {
            sum += item.doubleValue();
        }
        return sum / len;
    }

    public boolean compareAvg(Stack<E> s) {
        return this.avg() == s.avg();
    }

    public static void main(String[] args) {
        ArrayList<Integer> intList = new ArrayList<>();
        Stack<Integer> s1 = new Stack<>(intList);
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        System.out.println("Integer average: " + s1.avg());

        ArrayList<Double> doubleList = new ArrayList<>();
        Stack<Double> s2 = new Stack<>(doubleList);
        s2.push(1.1);
        s2.push(2.2);
        s2.push(3.3);
        s2.push(4.4);
        System.out.println("Double average: " + s2.avg());

        // Create another stack with the same type
        Stack<Integer> s3 = new Stack<>(new ArrayList<>());
        s3.push(5);
        s3.push(6);
        s3.push(7);
        s3.push(8);
        System.out.println("Are averages same: " + s1.compareAvg(s3));
    }
}
//Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        CountryBO countryBO = new CountryBO();
        AirportBO airportBO = new AirportBO();

        // Input for Country
        System.out.println("Enter the country count:");
        int countryCount = scanner.nextInt();
        scanner.nextLine(); // Consume newline character
        Country[] countries = new Country[countryCount];
        for (int i = 0; i < countryCount; i++) {
            System.out.println("Enter country " + (i + 1) + " details");
            String countryData = scanner.nextLine();
            countries[i] = countryBO.createCountry(countryData);
        }

        // Input for Airport
        System.out.println("Enter the airport count:");
        int airportCount = scanner.nextInt();
        scanner.nextLine(); // Consume newline character
        Airport[] airports = new Airport[airportCount];
        for (int i = 0; i < airportCount; i++) {
            System.out.println("Enter airport " + (i + 1) + " details:");
            String airportData = scanner.nextLine();
            airports[i] = airportBO.createAirport(airportData, countries);
        }

        // Find country for airport
        System.out.println("Enter the airport name for which you need to find the country name:");
        String airportName = scanner.nextLine();
        String countryName = airportBO.findCountryName(airports, airportName);
        System.out.println(airportName + " belongs to " + countryName);

        // Compare airports
        System.out.println("Enter 2 airport names:");
        String airportName1 = scanner.nextLine();
        String airportName2 = scanner.nextLine();
        boolean sameCountry = airportBO.findWhetherAirportsAreInSameCountry(airports, airportName1, airportName2);
        if (sameCountry) {
            System.out.println("The 2 airports are in the same Country");
        } else {
            System.out.println("The 2 airports are in different Country");
        }

        scanner.close();
    }
}






public class AirportBO {
    public Airport createAirport(String data, Country[] countryList) {
        String[] parts = data.split(",");
        for (Country country : countryList) {
            if (country.getCountryName().equals(parts[1])) {
                return new Airport(parts[0], country);
            }
        }
        return null;
    }

    public String findCountryName(Airport[] airportList, String airportName) {
        for (Airport airport : airportList) {
            if (airport.getAirportName().equals(airportName)) {
                return airport.getCountry().getCountryName();
            }
        }
        return null;
    }

    public boolean findWhetherAirportsAreInSameCountry(Airport[] airportList, String airportName1, String airportName2) {
        String country1 = null, country2 = null;
        for (Airport airport : airportList) {
            if (airport.getAirportName().equals(airportName1)) {
                country1 = airport.getCountry().getCountryName();
            }
            if (airport.getAirportName().equals(airportName2)) {
                country2 = airport.getCountry().getCountryName();
            }
        }
        return country1 != null && country2 != null && country1.equals(country2);
    }
}






public class Airport {
    private String airportName;
    private Country country;

    public Airport() {}

    public Airport(String airportName, Country country) {
        this.airportName = airportName;
        this.country = country;
    }

    public String getAirportName() {
        return airportName;
    }

    public void setAirportName(String airportName) {
        this.airportName = airportName;
    }

    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }
}





public class CountryBO {
    public Country createCountry(String data) {
        String[] parts = data.split(",");
        return new Country(parts[0], parts[1]);
    }
}




public class Country {
    private String iataCountryCode;
    private String countryName;

    public Country() {}

    public Country(String iataCountryCode, String countryName) {
        this.iataCountryCode = iataCountryCode;
        this.countryName = countryName;
    }

    public String getIataCountryCode() {
        return iataCountryCode;
    }

    public void setIataCountryCode(String iataCountryCode) {
        this.iataCountryCode = iataCountryCode;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}
//Country.java
class Country {
    private String iataCountryCode;
    private String countryName;

    public Country() {
    }

    public Country(String iataCountryCode, String countryName) {
        this.iataCountryCode = iataCountryCode;
        this.countryName = countryName;
    }

    public String getIataCountryCode() {
        return iataCountryCode;
    }

    public void setIataCountryCode(String iataCountryCode) {
        this.iataCountryCode = iataCountryCode;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    @Override
    public String toString() {
        return String.format("%-25s %s", iataCountryCode, countryName);
    }
}

//Client.java
class Client {
    private Integer clientId;
    private String clientName;
    private String phoneNumber;
    private String email;
    private String passport;
    private Country country;

    public Client() {
    }

    public Client(Integer clientId, String clientName, String phoneNumber, String email, String passport, Country country) {
        this.clientId = clientId;
        this.clientName = clientName;
        this.phoneNumber = phoneNumber;
        this.email = email;
        this.passport = passport;
        this.country = country;
    }

    public Integer getClientId() {
        return clientId;
    }

    public void setClientId(Integer clientId) {
        this.clientId = clientId;
    }

    public String getClientName() {
        return clientName;
    }

    public void setClientName(String clientName) {
        this.clientName = clientName;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassport() {
        return passport;
    }

    public void setPassport(String passport) {
        this.passport = passport;
    }

    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return String.format("%-25s %-25s %-25s %-25s %-25s %s", clientId, clientName, phoneNumber, email, passport, country);
    }
}


//ClientBO.java
class ClientBO {
    void viewDetails(Client[] clientList) {
        System.out.printf("%-25s %-25s %-25s %-25s %-25s %-25s %-25s\n", "ClientId", "ClientName", "PhoneNumber", "Email", "Passport", "IATACountryCode", "CountryName");
        for (Client client : clientList) {
            System.out.println(client);
        }
    }

    void printClientDetailsWithCountry(Client[] clientList, String countryName) {
        System.out.printf("%-25s %-25s %-25s %-25s %-25s %-25s %-25s\n", "ClientId", "ClientName", "PhoneNumber", "Email", "Passport", "IATACountryCode", "CountryName");
        boolean found = false;
        for (Client client : clientList) {
            if (client.getCountry().getCountryName().equalsIgnoreCase(countryName)) {
                System.out.println(client);
                found = true;
            }
        }
        if (!found) {
            System.out.println("No clients found for the specified country.");
        }
    }
}


//Main.java
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        Integer n, i, ch;
        String clientName, phoneNumber, email, passport, countryName, iataCountryCode;
        Integer clientId;

        System.out.println("Enter number of clients");
        n = Integer.parseInt(br.readLine());
        Client clientList[] = new Client[n];

        ClientBO clientBo = new ClientBO();

        Country country = new Country();

        for (i = 0; i < n; i++) {
            clientList[i] = new Client();
            System.out.println("Enter client " + (i + 1) + " details:");

            System.out.println("Enter the client id");
            clientId = Integer.parseInt(br.readLine());

            System.out.println("Enter the client name");
            clientName = br.readLine();

            System.out.println("Enter the phone number");
            phoneNumber = br.readLine();

            System.out.println("Enter the email id");
            email = br.readLine();

            System.out.println("Enter the passport number");
            passport = br.readLine();

            System.out.println("Enter the iata country code");
            iataCountryCode = br.readLine();

            System.out.println("Enter the country name");
            countryName = br.readLine();

            country = new Country(iataCountryCode, countryName);

            clientList[i] = new Client(clientId, clientName, phoneNumber, email, passport, country);

        }

        do {
            System.out.println("Menu:");
            System.out.println("1. View client details");
            System.out.println("2. Filter client with country");
            System.out.println("3. Exit");

            ch = Integer.parseInt(br.readLine());

            if (ch == 1) {
                clientBo.viewDetails(clientList);
            } else if (ch == 2) {
                System.out.println("Enter country name");
                countryName = br.readLine();
                clientBo.printClientDetailsWithCountry(clientList, countryName);
            } else
                break;

        } while (ch <= 2);

    }

}

//collections


//CallLog.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

class CallLog implements Comparable<CallLog> {
    String name;
    String dialledNumber;
    int duration;
    String dialledDate;

    public CallLog(String name, String dialledNumber, int duration, String dialledDate) {
        this.name = name;
        this.dialledNumber = dialledNumber;
        this.duration = duration;
        this.dialledDate = dialledDate;
    }

    @Override
    public int compareTo(CallLog o) {
        return this.name.compareTo(o.name);
    }

    @Override
    public String toString() {
        return String.format("%s(+91-%s) %d Seconds", name, dialledNumber, duration);
    }
}


 //Main.java//
import java.util.ArrayList;
import java.util.Collections;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException
public class Main {
    public static void main(String[] args) {
        ArrayList<CallLog> logs = readCallLogsFromFile("weeklycall.csv");

        Collections.sort(logs);
        Collections.reverse(logs); // Reverse the sorted list
        System.out.println("Call-Logs");
        System.out.println("Caller Name Duration");
        for (CallLog log : logs) {
            System.out.println(log);
        }
    }

    private static ArrayList<CallLog> readCallLogsFromFile(String filename) {
        ArrayList<CallLog> logs = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                String name = parts[0];
                String dialledNumber = parts[1];
                int duration = Integer.parseInt(parts[2]);
                String dialledDate = parts[3];
                logs.add(new CallLog(name, dialledNumber, duration, dialledDate));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return logs;
    }
}


//collection 2
import java.util.*;

class Card {
    private String symbol;
    private int number;

    public Card(String symbol, int number) {
        this.symbol = symbol;
        this.number = number;
    }

    public String getSymbol() {
        return symbol;
    }

    public int getNumber() {
        return number;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;
        Card card = (Card) obj;
        return Objects.equals(symbol, card.symbol);
    }

    @Override
    public int hashCode() {
        return Objects.hash(symbol);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Set<Card> uniqueSymbols = new HashSet<>();
        int cardsCollected = 0;

        while (uniqueSymbols.size() < 4) {
            System.out.println("Enter a card :");
            String symbol = scanner.next();
            int number = scanner.nextInt();
            Card card = new Card(symbol, number);
            uniqueSymbols.add(card);
            cardsCollected++;
        }

        System.out.println("Four symbols gathered in " + cardsCollected + " cards.");
        System.out.println("Cards in Set are :");
        for (Card card : uniqueSymbols) {
            System.out.println(card.getSymbol() + " " + card.getNumber());
    }
}
}
//collections 2 asses 2
 import java.util.*;

class Card {
    private String symbol;
    private int number;

    public Card(String symbol, int number) {
        this.symbol = symbol;
        this.number = number;
    }

    public String getSymbol() {
        return symbol;
    }

    public int getNumber() {
        return number;
    }

    @Override
    public String toString() {
        return symbol + " " + number;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Map<String, List<Card>> symbolMap = new TreeMap<>();

        System.out.println("Enter Number of Cards :");
        int N = scanner.nextInt();

        for (int i = 0; i < N; i++) {
            System.out.println("Enter card " + (i + 1) + ":");
            String symbol = scanner.next();
            int number = scanner.nextInt();
            Card card = new Card(symbol, number);

            // If the symbol is already in the map, add the card to its list, else create a new list
            symbolMap.computeIfAbsent(symbol, k -> new ArrayList<>()).add(card);
        }

        // Print distinct symbols in alphabetical order
        System.out.println("Distinct Symbols are :");
        for (String symbol : symbolMap.keySet()) {
            System.out.print(symbol + " ");
        }
        System.out.println();

        // Print details for each symbol
        for (Map.Entry<String, List<Card>> entry : symbolMap.entrySet()) {
            String symbol = entry.getKey();
            List<Card> cards = entry.getValue();

            System.out.println("Cards in " + symbol + " Symbol");
            for (Card card : cards) {
                System.out.println(card);
            }
            System.out.println("Number of cards : " + cards.size());
            int sum = cards.stream().mapToInt(Card::getNumber).sum();
            System.out.println("Sum of Numbers : " + sum);
        }
    }
}

Client.java

public class Client {
    private Integer clientId;
    private String name;
    private String email;
    private String phoneNumber;
    private String country;

    public Client(Integer clientId, String name, String email, String phoneNumber, String country) {
        this.clientId = clientId;
        this.name = name;
        this.email = email;
        this.phoneNumber = phoneNumber;
        this.country = country;
    }

    // Getters and Setters
    public Integer getClientId() {
        return clientId;
    }

    public void setClientId(Integer clientId) {
        this.clientId = clientId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    // Override toString method for CSV format
    @Override
    public String toString() {
        return clientId + "," + name + "," + email + "," + phoneNumber + "," + country;
    }
}

Main.java**

 import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
            FileUtility fileUtility = new FileUtility();
            Client[] clients = fileUtility.readFileData(br);
            Arrays.sort(clients, Comparator.comparing(Client::getClientId));
            fileUtility.writeDataToFile(clients);
            System.out.println("Output file generated successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
FileUtility.java**
  
  import java.io.*;
import java.util.*;

public class FileUtility {
    public Client[] readFileData(BufferedReader br) throws IOException {
        List<Client> clientList = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            String[] parts = line.split(",");
            Integer clientId = Integer.parseInt(parts[0].trim());
            String name = parts[1].trim();
            String email = parts[2].trim();
            String phoneNumber = parts[3].trim();
            String country = parts[4].trim();
            clientList.add(new Client(clientId, name, email, phoneNumber, country));
        }
        br.close();
        return clientList.toArray(new Client[0]);
    }

    public void writeDataToFile(Client[] clientArray) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.csv"))) {
            for (Client client : clientArray) {
                writer.write(client.toString());
                writer.newLine();
            }
        }
    }
}
public class Pair<K, V> {
    private K key;
    private V val;
    
    public Pair(K key, V val) {
        this.key = key;
        this.val = val;
    }
    
    public K getKey() {
        return this.key;
    }
    
    public V getVal() {
        return this.val;
    }
    
    public static void main(String[] args) {
        Pair<Integer, String> p1 = new Pair<>(123, "abc");
        Integer i = p1.getKey();
        System.out.println(i);
        System.out.println(p1.getVal());
    }
}
**Main.java**

import java.io.*;
import java.util.Scanner;
 public class Main {
public static void main(String[] args) {
 try {
Scanner scanner = new Scanner(System.in);
// Get airport details from the user
 System.out.println("Enter the name of the airport:");
String name = scanner.nextLine();
System.out.println("Enter the city name:");
String cityName = scanner.nextLine();
System.out.println("Enter the country code:");
 String countryCode = scanner.nextLine();
 // Write airport details to a CSV file
 FileWriter writer = new FileWriter("airport.csv");
writer.write(name + "," + cityName + "," + countryCode);
writer.close();
System.out.println("Airport details have been written to airport.csv successfully.");
 }
catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
 e.printStackTrace();
}
 }
}   
public class Container<T> {
    private T obj;

    public Container(T obj) {
        this.obj = obj;
    }

    public T getObj() {
        return this.obj;
    }

    public void showType() {
        System.out.println("Type: " + obj.getClass().getName());
    }

    public static void main(String[] args) {
        Container<String> c1 = new Container<>("generic");
        String s = c1.getObj();
        System.out.println("String is: " + s);
        c1.showType();

        Container<Integer> c2 = new Container<>(123);
        Integer i = c2.getObj();
        System.out.println("Integer is: " + i);
        c2.showType();
    }
}
//GameScreenLevel1.cpp
void GameScreenLevel1::SetLevelMap() {
	//0 blank, 1 wall, 2 win condition
	int map[MAP_HEIGHT][MAP_WIDTH] = {
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0},
		{1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1},
		{0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
		{0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
		{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
	};

	//Clear up any old map
	if (mLevelMap != NULL)
	{
		delete mLevelMap;

	}

	//Set up the new one
	mLevelMap = new LevelMap(map);
}


//Collision.cpp
bool Collision::Circle(Character* character1, Character* character2) {
	//Calculate Vector between 2 characters
	Vector2D vec = Vector2D((character1->GetPosition().x - character2->GetPosition().x), (character1->GetPosition().y - character2->GetPosition().y));

	//Calculate lenght from vector
	double distance = sqrt((vec.x * vec.x) + (vec.y * vec.y));

	//Get Collision Radius 
	double combinedDistance = (character1->GetCollisionRadius() - character2->GetCollisionRadius());

	if (distance < combinedDistance) {
		return true;
	}
	else return false;
}

bool Collision::Box(Rect2D rect1, Rect2D rect2) {
	if (rect1.x + (rect1.width / 2) > rect2.x && rect1.x + (rect1.width / 2) < rect2.x + rect2.width && rect1.y + (rect1.height / 2) > rect2.y && rect1.y + (rect1.height / 2) < rect2.y + rect2.height) {
		return true;
	}
	return false;
}
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int n_pages, size_page, n_frames, size_physical_memory, size_logical_memory;
int m, n,i,j;
int p = 0, d = 0;

int find_p(int),find_d(int);


int main()
{
    // Scanning size of Physical memory
    printf("Enter size of physical memory (power of 2)=  ");
    scanf("%d", &size_physical_memory);

    // Scanning the size of page
    // Frame size == Page size
    printf("Enter size of page/frame (power of 2)=  ");
    scanf("%d", &size_page);

    // Scanning number of pages in logical memory
    //printf("Enter no. of pages = ");
  //  scanf("%d", &n_pages);

   // size_logical_memory = size_page * n_pages;
   printf("Enter size of logical memory (power of 2)= ");
   scanf("%d",&size_logical_memory);
    n_pages=size_logical_memory/size_page;

    // Calculating the number of frames in the Physical memory
    n_frames = size_physical_memory / size_page;

    printf("\n\t\t\tLogical-Memory\t\tPhysical-Memory\n");
    printf("No. of Pages/frames\t\t%d\t\t\t%d\n", n_pages, n_frames);
    printf("Page/Frame size\t\t\t%d\t\t\t%d\n", size_page, size_page);
    printf("Size of Memory\t\t\t%d\t\t\t%d\n\n", size_logical_memory, size_physical_memory);

    // Declaring the Pages,Frames and Pagetable
    char pages[n_pages][size_page];
    int pagetable[n_pages];
    char frames[n_frames][size_page];

    n = sqrt(size_page);
    m = sqrt(size_page * n_pages);

    getchar();

    // Scanning Pages data
    printf("Enter details of the data availalbe in Logical Address Space\n");
    for (i = 0; i < n_pages; i++)
    {
        printf(" Enter the page%d data : ", (i));
        for (j = 0; j < size_page; j++)
        {
			pages[i][j] = getchar();
            getchar();
        }
    }

//Data Available in Logical Address
	printf("\nData Available in Logical Address is:\n");
	for (i = 0; i < n_pages; i++)
    {
        printf("\n Page%d: ", (i));
        for (j = 0; j < size_page; j++)
        {
			printf("%c\t",pages[i][j]);
        }
    }


    // Scanning Pagetable data
    printf("\nEnter the details of page table : \n");
for (i = 0; i < n_pages; i++) {
    printf(" Page%d stored in Frame: ", i);
    scanf("%d", &pagetable[i]);
}

	
        // Initializing all the default frames values to '0'
    for (i = 0; i < n_frames; i++){
        for (j = 0; j < size_page; j++)
        {
            frames[i][j] = '-';
        }
    }



    // Placing the data from pages to frams using page table
    for (i = 0; i < n_pages; i++)
    {
        p = i;
        int f = pagetable[p];
        for (j = 0; j < size_page; j++)
        {
            d = j;
            // Initializing Frames using (f,d)
            frames[f][d] = pages[i][j];
        }
    }

    // Displaying the Frames data
    printf("\nAccording to the given Page Table information \nFrames in the Physical Memory are loaded with following data:\n");
    for (i = 0; i < n_frames; i++)
    {
        printf(" \tFrame%d: ",i);
		for (j = 0; j < size_page; j++)
            printf("%c ", frames[i][j]);
        printf("\n");
    }
    printf("\n");

    // Finding the Physical address through Logical address
    printf("Enter any one address of Logical Memory : ");
    int n;
    scanf("%d", &n);
    p = find_p(n);
    d = find_d(n);
    int f = pagetable[p];
    printf(" Calculated Page Number is: %d\n",p);
    printf(" Calculated Displacement is: %d",d);
    printf("\nThe Physical address of %d (given Logical Address) is %d\n", n, (f * size_page) + d);
    printf("Data item \"%c\" of Logical Address %d is found at Physical Address %d i.e., at Frame Number %d with Displacement %d = \"%c\"\n", pages[n/4][n%4], n, (f * size_page) + d, f, d, frames[f][d]);


    
}

int find_p(int n)
{
    int res = n / size_page;
    return res;
}

int find_d(int n)
{
    int res = n % size_page;
    return res;
}

import {
  ButtonContent,
  DestructiveButton,
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Icon,
  Input,
  Toaster,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import React, { useState } from "react";
import { toast } from "sonner";
import wretch from "wretch";
import { useGetVesselFromIMO } from "@/hooks";

const formSchema = z.object({
  imo: z.string().max(7),
  cargo_type: z.string().optional(),
  cargo_sub_type: z.string().optional(),
  mmsi: z.string().max(9).optional(),
  vessel_name: z.string().optional(),
  year_of_build: z.string().optional(),
  flag: z.string().optional(),
  grt: z.string().optional(),
  dwt: z.string().optional(),
  overall_length: z.string().optional(),
  beam: z.string().optional(),
});

const fieldsNameHelper = {
  imo: {
    name: "IMO",
    description: "International Maritime Organization identifier",
  },
  cargo_type: {
    name: "Cargo Type",
    description: "The type of cargo the vessel carries",
  },
  cargo_sub_type: {
    name: "Cargo Sub Type",
    description: "The subtype of cargo the vessel carries",
  },
  mmsi: { name: "MMSI", description: "Maritime Mobile Service Identity" },
  vessel_name: { name: "Vessel Name", description: "The name of the vessel" },
  year_of_build: {
    name: "Year of Build",
    description: "The year the vessel was built",
  },
  flag: { name: "Flag", description: "The flag country code" },
  grt: { name: "GRT", description: "Gross Registered Tonnage" },
  dwt: { name: "DWT", description: "Dead Weight Tonnage" },
  overall_length: {
    name: "Overall Length",
    description: "The overall length of the vessel",
  },
  beam: { name: "Beam", description: "The beam of the vessel" },
};

export function VesselInfoForm() {
  const [imoChecked, setImoChecked] = useState(false);
  const [updateError, setUpdateError] = useState(null);
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {},
  });

  const imoValue = form.watch("imo");
  const {
    data: vesselData,
    isError,
    isLoading,
  } = useGetVesselFromIMO(imoValue);

  async function onSubmit(values) {
    setUpdateError(null);
    try {
      if (!imoChecked) {
        setImoChecked(true);
        if (vesselData?.length) {
          toast.error("Vessel already exists");
        }
      } else {
        const response = await wretch("/api/form/insertVessel")
          .post(values)
          .res();
        if (response.ok) {
          toast.success("Success!", {
            description: "Vessel details added.",
          });
          form.reset();
          setImoChecked(false);
        } else {
          throw new Error("Error submitting form");
        }
      }
    } catch (error) {
      setUpdateError(error);
    }
  }

  return (
    <div className={"mt-4"}>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
          <FormField
            control={form.control}
            name="imo"
            render={({ field }) => (
              <FormItem className={"flex flex-row items-center"}>
                <FormLabel className={"w-64 text-lg font-light"}>
                  {fieldsNameHelper.imo.name}
                </FormLabel>
                <div className={"mr-2"}>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                        <Icon name="unknown" style="h-5 w-5" />
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>{fieldsNameHelper.imo.description}</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </div>
                <FormControl className={"w-full"}>
                  <Input
                    {...field}
                    className={"text-md font-light"}
                    type="text"
                    value={field.value ?? ""}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          {imoChecked && vesselData && vesselData.length > 0 ? (
            <div className="vessel-info">
              <h2 className="text-lg font-semibold">Vessel Information</h2>
              <ul>
                {Object.keys(fieldsNameHelper).map(
                  (key) =>
                    vesselData[0][key] && (
                      <li key={key}>
                        <strong>{fieldsNameHelper[key].name}:</strong>{" "}
                        {vesselData[0][key]}
                      </li>
                    ),
                )}
              </ul>
            </div>
          ) : null}
          {imoChecked &&
            (!vesselData || vesselData.length === 0) &&
            Object.keys(formSchema.shape).map(
              (key, index) =>
                key !== "imo" && (
                  <FormField
                    key={key + index}
                    control={form.control}
                    name={key}
                    render={({ field }) => (
                      <FormItem className={"flex flex-row items-center"}>
                        <FormLabel className={"w-64 text-lg font-light"}>
                          {fieldsNameHelper[key].name}
                        </FormLabel>
                        <div className={"mr-2"}>
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                                <Icon name="unknown" style="h-5 w-5" />
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{fieldsNameHelper[key].description}</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        </div>
                        <FormControl className={"w-full"}>
                          <Input
                            {...field}
                            className={"text-md font-light"}
                            type="text"
                            value={field.value ?? ""}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                ),
            )}
          <div className="flex flex-row justify-end">
            <DestructiveButton type="submit" className="mt-4">
              <ButtonContent>
                {imoChecked ? "Add Vessel" : "Check IMO"}
              </ButtonContent>
            </DestructiveButton>
          </div>
          <Toaster />
        </form>
      </Form>
    </div>
  );
}
import {type NextPage} from "next";
import {Button, HeadingLink, MinimalPage, PageHeading} from "ui";
import {CommandInterface} from "@/components";
import {useRouter} from "next/router";
import {VesselButton} from "@/components/buttons/vesselButton";
import React from "react";

const ManageVessel: NextPage = () => {
  const router = useRouter();
  return (
    <MinimalPage
      pageTitle={"Manage Vessel | Email Interface"}
      pageDescription={"Spot Ship Email Interface | Manage Vessel"}
      commandPrompt
    >
      <CommandInterface/>
      <div className="w-full">
        <HeadingLink icon={"back"} text={"Home"} href={`/secure/home`}/>
      </div>
      <div>
        <PageHeading text="Manage Vessel"/>
      </div>
      <div className="grid w-full grid-flow-row auto-rows-max gap-8 p-8 pt-16 lg:w-2/3 lg:grid-cols-2">
        <Button
          text="Add Vessel"
          icon="plus-circle"
          iconRight
          action={() => {
            router.push("/secure/manager/manageVessel/addVessel");
          }}
          colour="Primary"
        />
        <Button
          text="Add Regular Vessel"
          icon="plus-circle"
          iconRight
          action={() => {
            router.push("/secure/manager/manageVessel/addRegularVessel");
          }}
          colour="Primary"
        />
        <Button
          text="Edit Vessel"
          icon="edit"
          iconRight
          action={() => {
            router.push("/secure/manager/manageVessel/editVessel");
          }}
          colour="Secondary"
        />
      </div>
      <div className="grid w-full grid-flow-row auto-rows-max gap-8 px-8 lg:w-2/3 lg:grid-cols-2">
        <VesselButton/>
      </div>
    </MinimalPage>
  );
};

export default ManageVessel;
import { NextPage } from "next";
import {
  BackHomeButton,
  CommandPalletteButton,
  MinimalPage,
  PageHeading,
} from "ui";
import { VesselInfoForm } from "@/components/forms/vesselInfoForm";
import { BugReportButton, CommandInterface, Navigation } from "@/components";

const RegularVessel: NextPage = () => {
  return (
    <MinimalPage
      pageTitle={"Regular Vessel Info | Vessel Interface"}
      pageDescription={"Vessel Interface | Regular Vessel Info"}
      commandPrompt
    >
      <div className="flex w-full flex-row justify-between pl-1 pt-1">
        <div>
          <BackHomeButton />
        </div>
        <Navigation />
        <div className="flex flex-row gap-4">
          <BugReportButton />
          <CommandPalletteButton />
          <CommandInterface />
        </div>
      </div>
      <PageHeading text="Regular Vessel Info" />
      <VesselInfoForm />
    </MinimalPage>
  );
};

export default RegularVessel;
var jwt = require('jsonwebtoken');

function auth(req, res, next) {
    // Extract the token from the Authorization header
    const authHeader = req.headers.authorization;

    if (!authHeader) {
        return res.status(401).send('Authorization header is missing');
    }

    // Ensure the token is a Bearer token
    const tokenParts = authHeader.split(' ');

    if (tokenParts.length !== 2 || tokenParts[0] !== 'Bearer') {
        return res.status(401).send('Invalid Authorization header format');
    }

    const token = tokenParts[1];

    // Verify the token
    jwt.verify(token, 'sid', function(err, decoded) {
        if (err) {
            return res.status(401).send('Failed to authenticate token');
        } else {
            // Optionally, you can attach the decoded information to the request object
            req.user = decoded;
            next();
        }
    });
}

module.exports = auth;
devtools::install_github("bioFAM/MOFA2", build_opts = c("--no-resave-data --no-build-vignettes"))
{
    "email": "harsh14@gmail.com",
    "password": "StrongPassword123!"
}
Int ledpin=2;
Void setup(){
	pinMode(ledpin,OUTPUT);
Serial.begin(9600);
}
Void loop(){
	digitalWrite(ledpin,HIGH);
	delay(1000);
	digitalWrite(ledpin,LOW);
	delay(1000);
}
#include “DHT.h”
DHT dht 2(2,DHT11);
Void setup(){
Serial.begin(9600);
}
Void loop(){
Serial.print(F(“Humidity in c: “));
Serial.print(dht.readHumidity());
Serial.print(F(“% temperature : “));
Serial.print(dht2.readTemperature());
Delay(1000);
}
int trig=D6
int echo=D5
float duration,dist_cm,dist_in
void setup(){
	pinMode(trig,OUTPUT)
	pinMode(echo,INPUT)
	Serial.begin(9600)
}
Void loop(){
	digitalWrite(trig,LOW);
	delay Microseconds(2);
	digitalWrite(trig,HIGH);
	delay Microseconds(10);
	digitalWrite(trig,LOW);
	duration=pulseIn(echo,HIGH);
	dist_cm=duration*0.0343/2.0;
	dist_in=duration*0.0135/2.0;
	Serial.print(“Distance”);
	Serial.print(dist_cm,1);
	Serial.print(“cm/ ”);
	Serial.print(dist_in,1);
	delay(300);
}
star

Wed May 29 2024 13:23:01 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:22:23 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:21:43 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:20:55 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:20:03 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:19:24 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:18:36 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:17:51 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:17:10 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:16:23 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:15:02 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:14:12 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:13:09 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:10:51 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:10:04 GMT+0000 (Coordinated Universal Time)

@krishna01 ##copy_files_from_s3 ##copy_bucket

star

Wed May 29 2024 13:09:34 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:08:42 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:07:18 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:05:38 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:01:31 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 13:00:43 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 12:18:34 GMT+0000 (Coordinated Universal Time) https://www.prplbx.com/resources/blog/aws-sdk-python-boto3-cheat-sheet/

@krishna01

star

Wed May 29 2024 10:18:09 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 10:00:58 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 09:59:37 GMT+0000 (Coordinated Universal Time)

@krishna01 ##read_s3 ##read_s3_pdf ##read_s3_files

star

Wed May 29 2024 09:53:52 GMT+0000 (Coordinated Universal Time)

@krishna01 ##read_s3 ##read_files_from_s3_json ##read_ocr_from_s3

star

Wed May 29 2024 09:51:14 GMT+0000 (Coordinated Universal Time) https://codepen.io/radeguzvic/pen/bGZorja

@radeguzvic #undefined

star

Wed May 29 2024 09:51:05 GMT+0000 (Coordinated Universal Time) https://codepen.io/radeguzvic/pen/bGZorja

@radeguzvic #undefined

star

Wed May 29 2024 09:51:00 GMT+0000 (Coordinated Universal Time) https://codepen.io/radeguzvic/pen/bGZorja

@radeguzvic #undefined

star

Wed May 29 2024 09:41:52 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:39:15 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 09:34:54 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:30:08 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:26:42 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:21:13 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:16:38 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:16:02 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 09:14:55 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:02:58 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 09:02:16 GMT+0000 (Coordinated Universal Time)

@huyrtb123 #c++

star

Wed May 29 2024 08:50:22 GMT+0000 (Coordinated Universal Time)

@Manoj1207

star

Wed May 29 2024 08:39:38 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Wed May 29 2024 08:33:30 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Wed May 29 2024 08:33:08 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Wed May 29 2024 07:45:07 GMT+0000 (Coordinated Universal Time)

@sid_balar

star

Wed May 29 2024 06:19:30 GMT+0000 (Coordinated Universal Time) https://biofam.github.io/MOFA2/installation.html

@kris96tian

star

Wed May 29 2024 06:15:34 GMT+0000 (Coordinated Universal Time)

@deepakm__

star

Wed May 29 2024 01:21:26 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:21:03 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:20:42 GMT+0000 (Coordinated Universal Time)

@login

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension