Snippets Collections
import java.util.Arrays;

class Main {
    public static void main(String[] args) {

        int [] arr1 = {54, 44, 39, 10, 12, 101};

        Arrays.sort (arr1);

        System.out.println (Arrays.toString(arr1));
    }
}
// Output: [10, 12, 39, 44, 54, 101]
class Main {
    public static void main(String[] args) {

        int[] arr1 = {54, 44, 39, 10, 12, 101};
        for (int i=0; i<arr1.length; i++) {
            if (arr1[i] == 44) {
                System.out.println ("Array has a value of 44 at index " + i);
            }
        }
    }
}
// Output: Array has a value of 44 at index 1
import java.util.Arrays;

class Main {
    public static void main(String[] args) {

        int [] arr1 = new int[10];

        for (int i = 0; i < 10; i++) {

            arr1 [i] = i;
        }
        System.out.println(Arrays.toString(arr1));
    }
}
// Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Cria o container do PostgreSQL em segundo plano
docker run -d --name api-todo -p 5432:5432 -e POSTGRES_PASSWORD=1234 postgres:13.5

# Executa o container e conecta no banco de dados
docker exec -it api-todo psql -U postgres

# Cria um usuario
create user user_todo;

# Adiciona um senha
alter user user_todo with encrypted password '1122';

# Cria o Banco de Dados 
create database api_todo;

# Adiciona privilegios
grant all privileges on database api_todo to user_todo;

# Acessa o Banco de Dados
\c api_todo

# Verifica as tabelas existentes
\dt

# Cria uma Tabela no Banco
create table todos (id serial primary key, title varchar, description text, done bool default FALSE);

# Adiciona privilegios
grant all privileges on all tables in schema public to user_todo;
grant all privileges on all sequences in schema public to user_todo;
class Main {
    public static void main(String[] args) {

        int[] arr2 = new int[10];

        arr2[0] = 1;

        System.out.println(arr2[0]);

    }
}
// Output: 1
class Main {
    public static void main(String[] args) {

        int [] arr1 = {1,2,3,4,5,6,7,8,9,10};

        arr1[1] = 22;

        System.out.println (arr1[1]);
    }
}
// Output: 22
class Main {
    public static void main(String[] args) {

        int [] arr1 = {1,2,3,4,5,6,7,8,9,10};

        System.out.println (arr1[3]);
    }
}
// Output: 4
public class Wrangler extends Car {
 
    boolean carDoors = true;
 
    public void takeOffDoors() {
        carDoors = false;
        System.out.println("Doors are taken off");
    }
 
    public void putBackDoors() {
        carDoors = true;
        System.out.println("Doors are back");
 
    }
    public String returnCarModel() {
        return "Car model is Wrangler";
    }
}
public class ModelX extends Car {

    boolean autoPilot = false;

    public void switchAutopilotOn() {
        autoPilot = true;
        System.out.println("Autopilot is switched on");
    }

    public void switchAutopilotOff() {
        autoPilot = false;
        System.out.println("Autopilot is switched off");
    }

    public String returnCarModel() {
        return "Car model is ModelX";
    }
}
public class Car {
 
    private int odometer = 0;
    private int productionYear = 0;
 
    public void setProductionYear(int year){
        productionYear = year;
    }
    
    public int getProductionYear (){
        return  productionYear;
    }
 
    public void drive( int miles) {
        System.out.println("Car drove " + miles + " miles");
        odometer = odometer + miles;
    }
 
    public String returnCarModel() {
        return "Car model is unknown";
    }
}
public class Main {
    public static void main(String[] args) {
 
        Wrangler myWranglerCar = new Wrangler();
        myWranglerCar.drive( 100);
        myWranglerCar.takeOffDoors();
        System.out.println(myWranglerCar.returnCarModel());
        myWranglerCar.setProductionYear(2022);
        System.out.println(myWranglerCar.getProductionYear());
 
        ModelX myModelXCar = new ModelX();
        myModelXCar.drive( 90);
        myModelXCar.switchAutopilotOn();
        System.out.println(myModelXCar.returnCarModel());
        myModelXCar.setProductionYear(2021);
        System.out.println(myModelXCar.getProductionYear());
 
        Car myCar = new Car();
        myCar.drive(50);
        System.out.println(myCar.returnCarModel());
    }
}
/* Output:
Car drove 100 miles
Doors are taken off
Car model is Wrangler
2022
Car drove 90 miles
Autopilot is switched on
Car model is ModelX
2021
Car drove 50 miles
Car model is unknown
*/
public class Wrangler extends Car {

    boolean carDoors = true;

    public void takeOffDoors() {
        carDoors = false;
        System.out.println("Doors are taken off");
    }

    public void putBackDoors() {
        carDoors = true;
        System.out.println("Doors are back");

    }

    public String returnCarModel() {
        return "Car model is Wrangler";
    }
}
public class Main {
    public static void main(String[] args) {

        Wrangler myWranglerCar = new Wrangler();
        myWranglerCar.drive( 100);
        System.out.println("Wrangler odometer displays " +myWranglerCar.odometer+ " miles");
        myWranglerCar.takeOffDoors();
        System.out.println(myWranglerCar.returnCarModel());

        ModelX myModelXCar = new ModelX();
        myModelXCar.drive( 90);
        System.out.println("ModelX odometer displays " +myModelXCar.odometer+ " miles");
        myModelXCar.switchAutopilotOn();
        System.out.println(myModelXCar.returnCarModel());

        Car myCar = new Car();
        myCar.drive(50);
        System.out.println(myCar.returnCarModel());
    }
}
/* Output:
Car drove 100 miles
Wrangler odometer displays 100 miles
Doors are taken off
Car model is Wrangler
Car drove 90 miles
ModelX odometer displays 90 miles
Autopilot is switched on
Car model is ModelX
Car drove 50 miles
Car model is unknown
*/
public class ModelX extends Car {

    boolean autoPilot = false;

    public void switchAutopilotOn() {
        autoPilot = true;
        System.out.println("Autopilot is switched on");
    }

    public void switchAutopilotOff() {
        autoPilot = false;
        System.out.println("Autopilot is switched off");
    }

    public String returnCarModel() {
        return "Car model is ModelX";
    }
}
public class Car {

    int odometer = 0;
    
    public void drive( int miles) {
        System.out.println("Car drove " + miles + " miles");
        odometer = odometer + miles;
    }

    public String returnCarModel() {
        return "Car model is unknown";
    }
}
public class Main {
    public static void main(String[] args) {

        Wrangler myWranglerCar = new Wrangler();
        myWranglerCar.drive( 100);
        System.out.println("Wrangler odometer displays " +myWranglerCar.odometer+ " miles");
        myWranglerCar.takeOffDoors();
        ModelX myModelXCar = new ModelX();
        myModelXCar.drive( 90);
        System.out.println("ModelX odometer displays " +myModelXCar.odometer+ " miles");
        myModelXCar.switchAutopilotOn();

        Car myCar = new Car();
        myCar.drive(50);
    }
}
/* Output:
Car drove 100 miles
Wrangler odometer displays 100 miles
Doors are taken off
Car drove 90 miles
ModelX odometer displays 90 miles
Autopilot is switched on
Car drove 50 miles
*/
public class Wrangler extends Car {
    
    boolean carDoors = true;
    
    public void takeOffDoors() {
        carDoors = false;
        System.out.println("Doors are taken off");
    }
    
    public void putBackDoors() {
        carDoors = true;
        System.out.println("Doors are back");
    }
}
public class ModelX extends Car {
 
    boolean autoPilot = false;
 
    public void switchAutopilotOn() {
        autoPilot = true;
        System.out.println("Autopilot is switched on");
    }
    
    public void switchAutopilotOff() {
        autoPilot = false;
        System.out.println("Autopilot is switched off");
    }
}
public class Car {
 
    int odometer = 0;
    
    public void drive( int miles) {
        System.out.println("Car drove " + miles + " miles");
        odometer = odometer + miles;
    }
}
public class Main {
    public static void main(String[] args) {

        Cars azatCar = new Cars("Mazda", "blue",2005);
        azatCar.brand = "Mazda" ;
        azatCar.year = 2005 ;
        azatCar.color = "blue" ;

        Cars someOtherCar = new Cars ("BMW", "black") ;
        someOtherCar.color = "black" ;
        someOtherCar.year = 2020 ;
        someOtherCar.brand = "BMW" ;

        System.out.println(someOtherCar.brand);
        azatCar.accelerate() ;
        azatCar.headlightsOn() ;
        azatCar.headlightsOff() ;
        System.out.println ("odometer is equal to " + azatCar.return0dometer(100000) + " miles");
    }
}
/* Output:
BMW
Car is accelerating
Car's headlights are on
Car's headlights are off
odometer is equal to 100000 miles
*/
public class Cars {
  
    String brand;
    String color;
    int year;
  
    public Cars (String carBrand, String carColor, int carYear) {
        brand = carBrand;
        color = carColor;
        year = carYear;
    }
  
    public Cars (String carBrand, String carColor) {
        brand = carBrand;
        color = carColor;
    }
  
    public void accelerate() {
        System.out.println("Car is accelerating");
    }
  
    public void headlightsOn() {
        System.out.println("Car's headlights are on");
    }
  
    public void headlightsOff() {
        System.out.println("Car's headlights are off");
    }
  
    public int return0dometer(int odometerValue) {
        return odometerValue;
    }
}
public class Cars {
  
    public void accelerate() {
        System.out.println("car is accelerating");
    }
    public void headlightsOn() {
        System.out.println("car's headlights are on");
    }
    public void headlightsOff() {
        System.out.println("car's headlights are off");
    }
    public int return0dometer(int odometerValue) {
        return 10000;
    }
}
class Solution {
public:
    int minimumTime(int n, vector<vector<int>>& relations, vector<int>& time) {
        vector<vector<int>> gr(n+1);
        vector<int> indegree(n+1, 0), prev_time(n+1, 0);
        for(auto& edge : relations){
            gr[edge[0]].push_back(edge[1]);
            indegree[edge[1]]++;
        }
        time.insert(time.begin(), 0);
        queue<int> q;
        for(int i =1; i <= n; i++)
            if(indegree[i] == 0)
                q.push(i);
        while(!q.empty()){
            int node = q.front();q.pop();
            for(auto adjV : gr[node]){
                prev_time[adjV] = max(prev_time[adjV] , time[node] + prev_time[node]);
                if(--indegree[adjV] == 0)
                    q.push(adjV);
            }
        }
        int ans = 0;
        for(int i =1 ; i < n + 1; ++i){
            ans = max(ans, time[i]+prev_time[i]);
        }
        return ans;
    }
};
//
//  ViewController.swift
//  PushNotifications
//
//  Created by Apple on 17/10/2023.

import UIKit
import FirebaseMessaging
import FirebaseAuth

class ViewController: UIViewController  {

    @IBOutlet weak var notificationLabel: UILabel!
    var fcmToken = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        getFcmToken()
        
    }
    
    @IBAction func sendNotificationPressed(_ sender: Any) {
        sendNotification(fcmToken)
    }
    
    func getFcmToken() {
          if let token = Messaging.messaging().fcmToken {
              print("fcm : ", token)
              fcmToken = token
              self.notificationLabel.text = "Token Found : \(token)"
          } else {
              print("no token")
              self.notificationLabel.text = "no token"
          }
      }
    
    class func instantiateVC() -> ViewController
      {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier:"ViewController") as! ViewController
        return controller
      }

    @objc func didReceivePushNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo, let message = userInfo["message"] as? String {
            // Update the UI with the received message
            notificationLabel.text = message
        }
    }

    deinit {
        // Remove the observer when the view controller is deallocated
        NotificationCenter.default.removeObserver(self)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        if let aps = userInfo["aps"] as? [String: Any], let message = aps["alert"] as? String {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PushNotificationReceived"), object: nil, userInfo: ["message": message])
        }
    }
    
    func sendNotification(_ token : String) {
        // Define the FCM server URL
        let fcmURL = URL(string: "https://fcm.googleapis.com/fcm/send")!

        // Prepare the notification payload
        let notificationBody: [String: Any] = [
            "notification": [
                "title": "New Notification",
                "body": "Notfication Received",
            ],
            "to": token, // Replace with the target device token or topic
        ]

        // Convert the payload to JSON data
        guard let jsonData = try? JSONSerialization.data(withJSONObject: notificationBody) else {
            print("Error creating JSON data")
            return
        }

        // Create an HTTP request
        var request = URLRequest(url: fcmURL)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=AAAAu-cOuBM:APA91bGgioW1_SBuSGDRVT-iDaPdvDARJCADKdJLbQIo9NmwEXmHx4wA_NcpB9fV6iZWOWrxPN3jWHIfkXYmVwRqi6xsZH_SfVphkxHU9xTrbIZM_gZDmjc9TRrz8vigBPhG5IRUjQa2", forHTTPHeaderField: "Authorization") // Replace with your FCM server key

        // Set the request body with the JSON data
        request.httpBody = jsonData

        // Perform the request
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error sending notification: \(error)")
                return
            }

            if let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) {
                print("Notification sent successfully")
            } else {
                print("Failed to send notification. Status code: \((response as? HTTPURLResponse)?.statusCode ?? -1)")
            }
        }

        task.resume()
    }
}



import UIKit
import UserNotifications
import Firebase
import FirebaseCore
import FirebaseMessaging

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    
    let gcmMessageIDKey: String = "gcm.message_id"
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
   
        FirebaseApp.configure()

        Thread.sleep(forTimeInterval: 0)
        self.registerForNotifications(application: application)
        UIApplication.shared.applicationIconBadgeNumber = 0
        let uid = Auth.auth().currentUser?.uid ?? ""
        print("user ID :" ,uid)
        
        return true
    }
    
    public static func segueViewController(viewController: UIViewController, identifier: String) {
        viewController.performSegue(withIdentifier: identifier, sender: viewController)
    }
    
    public static func newViewController(identifier: String) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let mainViewController = storyboard.instantiateViewController(withIdentifier: identifier)
        mainViewController.modalPresentationStyle = .popover
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window!.rootViewController = mainViewController
        appDelegate.window!.makeKeyAndVisible()
    }
 
    public static func embed(_ viewController: UIViewController, inParent controller: UIViewController, inView view: UIView){
        viewController.willMove(toParent: controller)
        view.addSubview(viewController.view)
        controller.addChild(viewController)
        viewController.didMove(toParent: controller)
    }

    func registerForNotifications(application: UIApplication) {
        //    application.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
        //remote Notifications
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (isGranted, err) in
                if err != nil {
                    print("Error notification : ", err!)
                }
                else {
                    print("no error in registerForNotifications")
                    UNUserNotificationCenter.current().delegate = self
                    Messaging.messaging().delegate = self
                    DispatchQueue.main.async {
                        application.registerForRemoteNotifications()
                        if let token = Messaging.messaging().fcmToken {
                            print("fcm : ", token)
                            
                            
                        } else {
                            print("no token")
                           // self.notificationLabel.text = "no token"
                        }
                    }
                }
            }
        }
        
        if #available(iOS 10, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.badge,.sound,.alert], completionHandler: { (granted, error) in
                DispatchQueue.main.async {
                    UNUserNotificationCenter.current().delegate = self
                    Messaging.messaging().delegate = self
                    application.registerForRemoteNotifications()
                }
            })
        } else {
            let notificationSettings = UIUserNotificationSettings(types: [.badge,.sound,.alert], categories: nil)
            DispatchQueue.main.async {
                UNUserNotificationCenter.current().delegate = self
                Messaging.messaging().delegate = self
                application.registerUserNotificationSettings(notificationSettings)
                application.registerForRemoteNotifications()
            }
        }
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
       let controller = ViewController.instantiateVC()
       self.window?.rootViewController = controller
       self.window?.makeKeyAndVisible()
       Messaging.messaging().appDidReceiveMessage(userInfo)
       completionHandler(.noData)
     }
    
     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
         
         print("Yay! Got a device token \(deviceToken)")
        // Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
         
       Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
       Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
       Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
     }
   }

extension AppDelegate: MessagingDelegate {
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    let dataDict:[String:String] = ["token": fcmToken ?? ""]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    print("Firebase Notification Token: \(fcmToken ?? "")")
  }
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: userInfo)
        //Messaging.messaging().shouldEstablishDirectChannel = true
        print("Notification Received")
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Firebase Notification Message yes: \(messageID)")
            print("User Info: \(userInfo)")
        }
        completionHandler([.alert, .badge, .sound])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
      //If notification is tapped
      let userInfo = response.notification.request.content.userInfo
      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
       print("Firebase Notification Message 2: \(messageID)")
      }
       //print(userInfo["title"]) //"body"
      let controller = ViewController.instantiateVC()
      self.window?.rootViewController = controller
      self.window?.makeKeyAndVisible()
      print(userInfo)
      Messaging.messaging().appDidReceiveMessage(userInfo)
      completionHandler()
     }
   }


//https://tinyurl.com/bdh8678a


include<bits/stdc++.h>
using namespace std;

vector<vector<int>>dp;
vector<vector<int>>dist; // adjacent matrix.
int n; // Number of Nodes.
int call(int S,int i){
    //All the nodes have been visited exactly once.

    if(S==((1<<n)-1)){
        return dist[i][1];
    }

    // Subtree has been calculated.
    if(dp[S][i]!=-1) return dp[S][i];

    // Go to next unvisited node.
    int res = INT_MAX;
    for(int j=0;j<n;j++){
        if((S&(1<<j))==0){ // if j'th node is unvisited.
            res = min(res , dist[i][j]+call(S|(1<<j),j)); // mark j'th node as visited.
        }
    }
    return dp[S][i] = res;
}
int main(){
    cin>>n;
    dist.resize(n,vector<int>(n));
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cin>>dist[i][j];
        }
    }
    dp.resize(1<<n,vector<int>(n,-1));
    cout<< call(1,1)<<endl;

}
/*
4
0 10 15 20
10 0 25 25
15 25 0 30
20 25 30 0
Output: 80
*/
#include <stdio.h>
int main() {
   // printf() displays the string inside quotation
   printf("Hello, World!");
   return 0;
}
  <div>
    <div id="content">
    </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollToPlugin.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/MotionPathPlugin.min.js"></script>
  <script type="module">
    gsap.registerPlugin(ScrollTrigger, MotionPathPlugin);
    smoothScroll("#content");
    function smoothScroll(content, viewport, smoothness) {
      content = gsap.utils.toArray(content)[0];

      gsap.set(viewport || content.parentNode, {
        overflow: "hidden",
        position: "fixed",
        height: "100%",
        width: "100%",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0
      });
      gsap.set(content, { overflow: "visible", width: "100%" });

      let getProp = gsap.getProperty(content),
        setProp = gsap.quickSetter(content, "y", "px"),
        removeScroll = () => (content.style.overflow = "visible"),
        needsRefreshFix =
          parseFloat(
            ScrollTrigger.version
              .split(".")
              .map((n) => ("00" + n).substr(n.length - 1, 3))
              .join("")
          ) < 3006002,
        height;

      function onResize() {
        height = content.clientHeight;
        content.style.overflow = "visible";
        document.body.style.height = height + "px";
      }
      onResize();
      ScrollTrigger.addEventListener("refreshInit", onResize);
      ScrollTrigger.addEventListener("refresh", () => {
        removeScroll();
        requestAnimationFrame(removeScroll);
      });

      ScrollTrigger.defaults({ scroller: content });

      ScrollTrigger.prototype.update = (p) => p; // works around an issue in ScrollTrigger 3.6.1 and earlier (fixed in 3.6.2, so this line could be deleted if you're using 3.6.2 or later)

      ScrollTrigger.scrollerProxy(content, {
        scrollTop(value) {
          return arguments.length ? setProp(-value) : -getProp("y");
        },
        getBoundingClientRect() {
          return {
            top: 0,
            left: 0,
            width: window.innerWidth,
            height: window.innerHeight
          };
        }
      });

      gsap.fromTo(
        content,
        { y: 0 },
        {
          y: () => document.documentElement.clientHeight - height,
          ease: "none",
          onUpdate: ScrollTrigger.update,
          scrollTrigger: {
            scroller: window,
            invalidateOnRefresh: true,
            start: 0,
            end: () => height - document.documentElement.clientHeight,
            scrub: smoothness || 3,
            onRefresh: (self) => {
              // when the screen resizes, we just want the animation to immediately go to the appropriate spot rather than animating there, so basically kill the scrub.
              gsap.killTweensOf(self.animation);
              self.animation.progress(self.progress);
              if (needsRefreshFix) {
                let all = ScrollTrigger.getAll();
                all.slice(all.indexOf(self) + 1).forEach((t) => t.refresh());
              }
            }
          }
        }
      );
    }
    
    document.addEventListener("DOMContentLoaded", function () {
      smoothScroll();
    });


  </script>
    
// Form to add a record   to display products dropdown v1.2 starts
echo '<form id="add-record-form" style="display: flex; flex-direction: row;">
<div class="main_container" style="margin-right: 20px;">
    <label for="product_name">Product Name:</label>
    <select id="product_name" name="product_name">';
    
// Retrieve product names from the database
$query = new WP_Query(array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => '-1'
));

if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
        echo '<option value="' . get_the_title() . '">' . get_the_title() . '</option>';
    endwhile;
    wp_reset_postdata();
else:
    echo '<option value="">No products found</option>';
endif;

echo '</select>
</div>';

// v1.2 stops
// Modify quantity input and add remove icon
add_filter('woocommerce_checkout_cart_item_quantity', 'bbloomer_checkout_item_quantity_input', 9999, 3);

function bbloomer_checkout_item_quantity_input($product_quantity, $cart_item, $cart_item_key) {
    $product = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key);
    $product_id = apply_filters('woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key);

    if (!$product->is_sold_individually()) {
        $product_quantity = woocommerce_quantity_input(array(
            'input_name'  => 'shipping_method_qty_' . $product_id,
            'input_value' => $cart_item['quantity'],
            'max_value'   => $product->get_max_purchase_quantity(),
            'min_value'   => '0',
        ), $product, false);

        // Add remove icon
        $product_quantity .= '<a href="#" class="remove-product" data-product-key="' . $cart_item_key . '">x</a>';

        $product_quantity .= '<input type="hidden" name="product_key_' . $product_id . '" value="' . $cart_item_key . '">';
    }

    return $product_quantity;
}

// Add JavaScript to handle product removal
add_action('wp_footer', 'add_product_removal_script');

function add_product_removal_script() {
    ?>
    <script>
        document.addEventListener('click', function (event) {
            if (event.target.classList.contains('remove-product')) {
                event.preventDefault();
                const productKey = event.target.getAttribute('data-product-key');
                const form = event.target.closest('form');

                if (form && productKey) {
                    // Remove the product from the cart via AJAX
                    jQuery.ajax({
                        type: 'POST',
                        url: wc_checkout_params.ajax_url,
                        data: {
                            action: 'remove_product_from_cart',
                            product_key: productKey
                        },
                        success: function (response) {
                            // Reload the checkout page to reflect the updated cart
                            window.location.reload();
                        }
                    });
                }
            }
        });
    </script>
    <?php
}
add_action('wp_ajax_remove_product_from_cart', 'remove_product_from_cart');

function remove_product_from_cart() {
    if (isset($_POST['product_key'])) {
        $product_key = sanitize_text_field($_POST['product_key']);
        WC()->cart->remove_cart_item($product_key);
        echo 'success';
    }

    wp_die();
}


// Detect Quantity Change and Recalculate Totals
add_action('woocommerce_checkout_update_order_review', 'bbloomer_update_item_quantity_checkout');

function bbloomer_update_item_quantity_checkout($post_data) {
    parse_str($post_data, $post_data_array);
    $updated_qty = false;
    $updated_remove = false;

    foreach ($post_data_array as $key => $value) {
        if (substr($key, 0, 20) === 'shipping_method_qty_') {
            $id = substr($key, 20);
            WC()->cart->set_quantity($post_data_array['product_key_' . $id], $post_data_array[$key], false);
            $updated_qty = true;
        } elseif (substr($key, 0, 15) === 'remove_product_') {
            $cart_item_key = substr($key, 15);
            WC()->cart->remove_cart_item($cart_item_key);
            $updated_remove = true;
        }
    }

    if ($updated_qty || $updated_remove) {
        WC()->cart->calculate_totals();
    }
}
.sp-pcp-post.left-thumb .pcp-post-thumb-wrapper {
    max-width: 38%;
    min-width: 38%;
}
var Header = document.querySelector('.atmc-header');
var body_wrp = document.querySelector('.body-wrapper');
if(Header){

  function getElHeight(){
    const elementHeight = Header.offsetHeight;
    var unit = "px"
    body_wrp.style.paddingTop = elementHeight + unit;
    console.log(elementHeight)
  }
  getElHeight();
  window.addEventListener("scroll", getElHeight);
  window.addEventListener("load", getElHeight);
  window.addEventListener("resize",getElHeight);
}
let data = [10, 42, 52];
console.log(data.length);
>> 3
//配列の最後のインデックスは 2 ですので(インデックスは 0 から始まります)、 配列の length プロパティは 3 を返します。結果として length プロパティを参照すると配列に含まれる要素の数となります。
                                                    data-popup='[{
                                                        "title":"{{ object.name }}",
                                                        "description":"{{ object.popup_des }}",
                                                        "material":"{{ object.popup_material }}",
                                                        "washable":[
                                                            {% for wash in object.popup_wash_list.value %}
                                                                ["{{ wash.icon | img_url:"master" }}","{{ wash.des }}"]{% unless forloop.last %},{% endunless %}
                                                            {% endfor %}
                                                        ],
                                                        "imgs":[
                                                            {% for img in object.popup_imgs.value %}
                                                                ["{{ img | img_url:"master" }}","{{ img.alt }}"]{% unless forloop.last %},{% endunless %}
                                                            {% endfor %}
                                                        ],
                                                        "where":"{{ object.popup_where }}",
                                                        "english":"{{ object.popup_eng }}"
                                                    }]'
//1. Write a program that reads an integer between 1 and 9 and displays the roman version (I, II, : : :, IX) of that integer.

Answer 1:

public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		System.out.println("Enter Number between 1 _ 9: ");
		int number = input.nextInt();
		
		if(number==1) {
			System.out.println("Roman Version of " + number + " is I.");
		}
		else if (number==2) {
			System.out.println("Roman Version of " + number + " is II."); }
		else if (number==3) {
			System.out.println("Roman Version of " + number + "  is III."); }
		else if (number==4) {
			System.out.println("Roman Version of " + number + "  is IV."); }
		else if (number==5) {
			System.out.println("Roman Version of " + number + "  is V. "); }
		else if (number==6) {
			System.out.println("Roman Version of " + number + " is VI."); }
		else if (number==7) {
			System.out.println("Roman Version of " + number + "  is VII."); }
		else if (number==8) {
			System.out.println("Roman Version of " + number + "  is VIII."); }
		else if (number==9) {
			System.out.println("Roman Version of " + number + "  is IX."); }
		else
			System.out.println("valid input.");
	}
}

Q 2: Write a program which displays a menu of a burger house, asks the choice of the user and displays the cost. In the implementation use switch-case.
  
  Answer 2:
  
  Scanner input = new Scanner(System.in);
		System.out.println("Menu: ");
		System.out.println("Enter C for Cheeseburger: ");
		System.out.println("Enter H for Hot dog: ");
		System.out.println("Enter L for Lemonade: ");
		System.out.println("Enter T for Iced Tea: ");
		
		System.out.println("Enter Your Choice: ");
		String choice = input.nextLine();
		
		
		switch(choice) {
			case "c": System.out.println("Price of Chesseburger is $7.49."); break;
			case "h": System.out.println("Price of Hot dog is $6.99."); break;
			case "l": System.out.println("Price of Lemonade is $2.50."); break;
			case "t": System.out.println("Price of Iced Tea is $2.75."); break;
			
			default: System.out.println("Unrecognized menu item.");
		}
	}
}

Q 3: Write a program that generates 50 random integers between 1-6 and counts the occurrence of number 4. In the implementation use while loop.
 
 Answer 3:
 int count = 0, freq4 = 0;
		while(count < 50) {
			
			int num = (int) (Math.random() * 6 +1);
			if(num==4)
				freq4 = freq4 + 1;
			count = count + 1;
		}
		System.out.println("Number 4: " + freq4 + " times generated.");
	}
}

Q 4: Write a program that prompts the user to enter the number of students and each student’s score.  Then your program displays the class average and the highest score. In the implementation use for loop.
 
Answer 4:

		Scanner input = new Scanner(System.in);
		System.out.println("Enter number of students:");
		int stuNo = input.nextInt();
		
		int i =0;
		int sum = 0; 
		int max = 0;
		for( i =0; i<stuNo; i++) {
			System.out.println("Enter the Grade of the student: " + (i+1));
			int grade = input.nextInt();
			sum = sum + grade;
			if(grade>max)
				max =grade;
		}
		double avg = (double)sum /stuNo;
		System.out.println("Class average " + avg + " & maximum grade is " + max + " at student " + i);
	}
}   //OUTPUT: 
Enter number of students:
4
Enter the Grade of the student: 1
50
Enter the Grade of the student: 2
60
Enter the Grade of the student: 3
80
Enter the Grade of the student: 4
77
Class average 66.75 & maximum grade is 80at student 4


Q 5: Write a method named maxThreeints that takes three integers as arguments and returns the the value of the largest one.

public static int maxThreeints(int a, int b, int c)
// this method calculates and returns the max value

Complete the program with main method, which asks the user to enter three numbers , invokes maxThreeints method and displays the result.
 Answer 5:
 Scanner input = new Scanner(System.in);
		System.out.println("Enter Three Numbers:");
		System.out.println("Enter Number 1: ");
		int a = input.nextInt();
		System.out.println("Enter Number 2: ");
		int b = input.nextInt();
		System.out.println("Enter Number 3: ");
		int c = input.nextInt();
		
		int max = maxThreeints(a,b,c);
		System.out.println("The Largest value is " + max);
		
	}
	public static int maxThreeints(int a, int b, int c) {
		
		if(a >= b && a >= c)
			return a;
		else if(b >= a && b >= c)
			return b;
		else 
			return c;
	}
}
//OUTPUT:
Enter Three Numbers:
Enter Number 1: 
33
Enter Number 2: 
44
Enter Number 3: 
55
The Largest value is 55
        % gpg --import KEYS
        % gpg --verify downloaded_file.asc downloaded_file
    
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    int num = 36,num2 = 6;
  for(int r=1;r<=16;r++){
      for(int s=0;s<=num;s++){
          if(r%4 == 0){num = num-6;
          cout<<' ';   }
          else if(r%4 != 0){ cout<<' ';}
      }
   for(int c=1;c<=num2;c++){
     if(r==1){cout<<'*';}
     else if(r%4==0){cout<<'*';}
     else if(r%4 != 0 && c==1 || c==num2){
         num2 = num2+6;
         cout<<'*';}
         else{cout<<'*';}
         
     }
       cout<<endl;
   }
  
    return 0;
}
const kue = require('kue');
const queue = kue.createQueue();

const addEmailJob = (email, subject, html) => {
  const job = queue.create('email', {
    email,
    subject,
    html
  })
    .save((error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(`Email job added to queue: ${email}`);
}
});
};

// Add 50,000 email jobs to the queue
const emailList = [
{ email: 'recipient1@example.com', subject: 'Test email 1', html: '<p>This is a test email 1</p>' },
{ email: 'recipient2@example.com', subject: 'Test email 2', html: '<p>This is a test email 2</p>' },
// ...
{ email: 'recipient50000@example.com', subject: 'Test email 50000', html: '<p>This is a test email 50000</p>' }
];

emailList.forEach((emailData) => {
addEmailJob(emailData.email, emailData.subject, emailData.html);
});
const kue = require('kue');
const queue = kue.createQueue();
const sendEmail = require('./send-email'); // The script from step 3

queue.process('email', (job, done) => {
sendEmail(job.data.email, job.data.subject, job.data.html);
done();
});
dont forget to add a password to it

```YML

accessories:

  redis:

    image: redis:7.0

    cmd: redis-server --requirepass <%= ENV['REDIS_PASSWORD'] %>

    host: xx.xx.xx.xx

    port: "6379:6379"

    directories:

      - dataRedis:/data

```
for (int index = 0; index < array.length; index++){
  
}
Private Sub fireOutlook()
    Dim olShellVal As Long

    On Error GoTo FIREOUTLOOK_ERR
    Set g_olApp = GetObject(, "Outlook.Application") ' If outlook is open will create obj
    ' If closed this will goto the error handler and then resume
    If g_olApp Is Nothing Then ' This checks if object was created
        olShellVal = Shell("OUTLOOK", vbNormalNoFocus) ' Opens Outlook
        Set g_olApp = CreateObject("Outlook.Application") ' Creates the Object
    End If
FIREOUTLOOK_EXIT:
    Exit Sub
FIREOUTLOOK_ERR:
    If g_olApp Is Nothing Then
        Err.Clear
        Resume Next
    Else
        MsgBox Err.Description, , "Error Number: " & Err.Number
    End If
    GoTo FIREOUTLOOK_EXIT
End Sub
According to MarketsandMarkets, the globalized crypto market size is expected to reach $1.40 Billion by 2024, at a CAGR of 6.18% during the forecast period. The crypto trading bot market is highly competitive, with many providers that render a wide range of trading bots to choose from. Some of the most popularized trading bot platforms such as Cryptohopper, HaasOnline, and 3commas and more.,

Before crypto trading bot development, you must decide whether you want to utilize a pre-developed trading bot platform or create a customized crypto trading bot. While pre-established trading bots are easy to use and need minimal programming skills, they provide limited customization and may not suit your particular crypto bot trading strategies. On the other hand, custom crypto trading bots provide more flexibility and can be tailored to your unique trading necessities. 
star

Wed Oct 18 2023 13:10:45 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 13:09:10 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 13:07:30 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 13:07:11 GMT+0000 (Coordinated Universal Time) https://docs.docker.com/engine/install/ubuntu/#install-using-the-repository

@Pedro_Neto

star

Wed Oct 18 2023 13:02:31 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 13:00:58 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:59:42 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:52:48 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:49:18 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:47:57 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:47:17 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:42:35 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:41:39 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:39:18 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:38:17 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:31:58 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:31:28 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:31:06 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:30:52 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:24:47 GMT+0000 (Coordinated Universal Time)

@banch3v

star

Wed Oct 18 2023 12:21:45 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:18:10 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 12:16:34 GMT+0000 (Coordinated Universal Time)

@testpro #java

star

Wed Oct 18 2023 10:05:41 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/1264187/css-how-do-i-create-a-gap-between-rows-in-a-table

@vishalbhan #css

star

Wed Oct 18 2023 07:44:54 GMT+0000 (Coordinated Universal Time)

@jin_mori

star

Wed Oct 18 2023 07:18:43 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/c-programming/examples/print-sentence

@raihansarker #c

star

Wed Oct 18 2023 07:18:42 GMT+0000 (Coordinated Universal Time) https://autoservis-jakovljevic.hr/wp-admin/admin.php?page

@rsiprak #undefined

star

Wed Oct 18 2023 06:42:04 GMT+0000 (Coordinated Universal Time)

@chicovirabrikin #nodejs

star

Wed Oct 18 2023 06:36:26 GMT+0000 (Coordinated Universal Time)

@Alihaan #php

star

Wed Oct 18 2023 06:34:08 GMT+0000 (Coordinated Universal Time)

@Alihaan #php

star

Wed Oct 18 2023 04:26:46 GMT+0000 (Coordinated Universal Time) https://secure.helpscout.net/conversation/2390791755/23702?folderId

@Ria

star

Wed Oct 18 2023 04:13:53 GMT+0000 (Coordinated Universal Time)

@kunal

star

Wed Oct 18 2023 02:48:06 GMT+0000 (Coordinated Universal Time) https://www.javadrive.jp/javascript/array/index6.html

@manami_13

star

Wed Oct 18 2023 02:05:54 GMT+0000 (Coordinated Universal Time) https://amaoed.app.box.com/s/g43eoh50uac77olly7auso7g37jli1c2

@bavgg

star

Tue Oct 17 2023 22:44:12 GMT+0000 (Coordinated Universal Time)

@akairo0902

star

Tue Oct 17 2023 20:25:00 GMT+0000 (Coordinated Universal Time)

@Mohamedshariif #java

star

Tue Oct 17 2023 19:56:53 GMT+0000 (Coordinated Universal Time) https://apache.org/dyn/closer.cgi/netbeans/netbeans-installers/19/Apache-NetBeans-19-bin-windows-x64.exe#verify

@AK47

star

Tue Oct 17 2023 19:44:29 GMT+0000 (Coordinated Universal Time)

@yolobotoffender

star

Tue Oct 17 2023 19:39:45 GMT+0000 (Coordinated Universal Time) https://medium.com/@techsuneel99/how-to-send-50000-emails-at-once-in-queue-node-js-b633ef9b3b30

@shimeibro #javascript

star

Tue Oct 17 2023 19:39:26 GMT+0000 (Coordinated Universal Time) https://medium.com/@techsuneel99/how-to-send-50000-emails-at-once-in-queue-node-js-b633ef9b3b30

@shimeibro #javascript

star

Tue Oct 17 2023 19:36:27 GMT+0000 (Coordinated Universal Time) https://discord.com/channels/1084848369073131531/1084848372667654248/1163905805947506748

@pedroschmitt

star

Tue Oct 17 2023 19:10:39 GMT+0000 (Coordinated Universal Time)

@csprofessorpam #react.js #javascript

star

Tue Oct 17 2023 18:10:50 GMT+0000 (Coordinated Universal Time) https://uchi.ru/payments/products

@Serkirill

star

Tue Oct 17 2023 14:43:41 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/44974735/open-outlook-using-vba-in-ms-access

@paulbarry #vb

star

Tue Oct 17 2023 12:28:17 GMT+0000 (Coordinated Universal Time) https://maticz.com/crypto-trading-bot-development

@jamielucas #drupal

Save snippets that work with our extensions

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