Snippets Collections
#Step-5: Calculate Accuracy,  Precision ,Recall, and F1 Score

#Calculate accuracy
accuracy=accuracy_score(y_test, y_pred)
print("Accuracy :",accuracy)

#Calculate precision
precision= precision_score(y_test, y_pred)
print("Precision :",precision)

#Calculate recall
recall= recall_score(y_test, y_pred)
print("Recall :",recall)

#calculate the f1 score
f1= f1_score(y_test, y_pred)
print("F1 Score :",f1)
                      
Fig. 1
From: Investigating the effectiveness of peer code review in distributed software development based on objective and subjective data


Overview of the Code Review Process

Back to article page
#include <bits/stdc++.h>  // Thư viện tiêu chuẩn cho C++ (bao gồm tất cả các thư viện phổ biến)
using namespace std;

void primMST(int V, vector<vector<pair<int, int>>>& adj) {  // Hàm tìm MST với V đỉnh và danh sách kề 'adj'
    vector<int> key(V, INT_MAX), parent(V, -1);  // 'key' lưu trọng số nhỏ nhất để kết nối, 'parent' lưu đỉnh cha
    vector<bool> inMST(V, false);  // Đánh dấu đỉnh nào đã được thêm vào MST
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;  // Min-heap lưu (trọng số, đỉnh)

    key[0] = 0;  // Khởi tạo đỉnh đầu tiên với trọng số 0 (bắt đầu từ đỉnh 0)
    pq.push({0, 0});  // Đẩy đỉnh 0 vào hàng đợi ưu tiên với trọng số 0

    while (!pq.empty()) {  // Vòng lặp chính: Chạy cho đến khi hàng đợi rỗng
        int u = pq.top().second;  // Lấy đỉnh 'u' có trọng số nhỏ nhất từ hàng đợi
        pq.pop();  // Loại bỏ đỉnh 'u' khỏi hàng đợi
        inMST[u] = true;  // Đánh dấu 'u' đã được thêm vào MST

        // Duyệt qua tất cả các đỉnh kề 'v' của 'u' với trọng số 'weight'
        for (auto& [v, weight] : adj[u]) {  
            // Nếu 'v' chưa thuộc MST và 'weight' nhỏ hơn trọng số hiện tại 'key[v]'
            if (!inMST[v] && weight < key[v]) {  
                key[v] = weight;  // Cập nhật 'key[v]' với trọng số mới
                pq.push({key[v], v});  // Đẩy (trọng số mới, đỉnh 'v') vào hàng đợi ưu tiên
                parent[v] = u;  // Cập nhật đỉnh cha 'u' của 'v'
            }
        }
    }

    // In ra các cạnh của cây khung nhỏ nhất (MST)
    for (int i = 1; i < V; i++)  // Duyệt qua các đỉnh từ 1 đến V-1
        cout << parent[i] << " - " << i << " (" << key[i] << ")\n";  // In cạnh (parent[i] - i) và trọng số (key[i])
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: What's on in Melbourne this week! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n Hey Melbourne, happy Monday! Please see below for what's on this week. "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Xero Café :coffee:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n :new-thing: *This week we are offering:* \n\n We have Muesli & Apple Yoghurt Cookies, Triple Chocolate Fudge Cookes (GF), and Hedgehog Slice!\n\n *Weekly Café Special*: _Vanilla Chai Latte_"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Wednesday, 4th September :calendar-date-4:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n:late-cake: *Afternoon Tea*: From *2pm* in the *L1, L2 and L3* kitchens! \n\n:massage:*Wellbeing - Yoga Flow*: Confirm your spot <https://docs.google.com/spreadsheets/d/1iKMQtSaawEdJluOmhdi_r_dAifeIg0JGCu7ZSPuwRbo/edit?gid=0#gid=0/|*here*>. Please note we have a maximum of 15 participants per class, a minimum notice period of 2 hours is required if you can no longer attend."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Thursday, 5th September :calendar-date-5:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":breakfast: *Breakfast*: Provided by *Kartel Catering* from *8:30am* in the Wominjeka Breakout Space.\n\n"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*Later this month:* We have our Grand Final Eve-Eve BBQ Social on the 26th of September! Make sure to wear your team colours (can be NRL or AFL) and come along for some fun! \n\nStay tuned to this channel for more details, and make sure you're subscribed to the <https://calendar.google.com/calendar/u/0?cid=Y19xczkyMjk5ZGlsODJzMjA4aGt1b3RnM2t1MEBncm91cC5jYWxlbmRhci5nb29nbGUuY29t|*Melbourne Social Calendar*> :party-wx:"
			}
		}
	]
}
<link rel="stylesheet" href="2bit-ui.css" />
// Footer
.ari-section.footer{
  	@media (max-width: 991px){
    	padding: 0;
  	}
  	.ari-layout.internal &, .ari-layout.contact-pg &{
    	margin-top: 50px;
  	}
}
.footer{
    &-top{
        font-size: _res-m(36);
        text-align: center;
        @include screen-sm-min{
            font-size: _res(16);
            text-align: left;
            padding: _res(88) 0;
            @include _flex($halign: space-between, $valign: flex-start);
            &::before, &::after{ display: none; }
        }
        @include section-padding;
        a{
            color: #fff;
            transition: all .3s ease-in-out;
            &:hover{
                color: $brand-primary;
                text-decoration: none;
            }
        }
        >div{
            @include screen-xs{
                padding: _res-m(130) 0;
                &:not(:last-child){
                    border-bottom: 2px solid #9B9DA0;
                }
            }
            @include screen-sm-min{
                width: auto;
            }
        }
    }
    &-title{
        @include screen-sm-min{}
    }
    &-logo{
        width: _res-m(382);
        margin: 0 auto;
        @include screen-sm-min{
            width: _res(254);
        }
        img{ width: 100%; }
    }
    &-phone{
        @include screen-sm-min{}
    }
    &-address{
        @include screen-sm-min{}
    }
    &-phone, &-address{
        @include screen-sm-min{}
    }
    &-quick-links{
        ul{
            margin: 0;
            padding: 0;
            list-style: none;
            li{
                padding-bottom: _res-m(20);
                @include screen-sm-min{
                    padding-bottom: _res(20);
                }
            }
        }
    }
    &-smedia{
        .social-media{
            .fa-circle{ display: none; }
            .fa-stack{
                width: 1em; height: 1em;
                line-height: 1em;
                font-size: _res-m(50);
                @include screen-sm-min{
                    font-size: _res(30);
                }
            }
            @include screen-sm-min{
                &:hover{}
            }
        }
    }
    &-hours{
        .hours{
            display: inline-block;
            text-align: left;
            >div{
                padding-bottom: _res-m(20);
                @include screen-sm-min{
                    padding-bottom: _res(10);
                }
            }
        }
        .day{
            display: inline-block;
            width: _res-m(300);
            @include screen-sm-min{
                width: _res(90,168);
            }
        }
    }
    &-map{
        iframe{
            width: _res-m(923);
            height: _res-m(609);
            @include screen-sm-min{
                width: _res(180,250);
                height: _res(110,165);
            }
        }
        .map{ display: flex; }
    }
    &-cta{
        display: inline-block;
        .btn-cta{
            font-size: _res-m(36);
            @include screen-sm-min{
                font-size: _res(16);
            }
        }
    }
    &-bottom{
        background: #000;
        border-top: _res-m(5,10) solid $brand-primary;
        padding: _res-m(15,30) 0;
        @include screen-sm-min{
            padding: 15px 0;
            border-top-width: _res(2,5);
            .bottom-row{
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
        }
        @include section-padding;
        a, a:hover{ color: #fff; }
        .footer-nav{
            ul{
                margin: 0;
                padding: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                li{
                    list-style: none;
                    a{
                        font-size: _res-m(10,25);
                        display: inline-block;
                        padding: 0 10px;
                        line-height: 1;
                        border-right: 1px solid #fff;
                        @include screen-sm-min{
                            font-size: _res(11,14);
                        }
                    }
                    &:first-child a{
                        padding-left: 0;
                    }
                    &:last-child a{
                        padding-right: 0;
                        border-right: none;
                    }
                }
            }
        }
        .footer-copyright{
            text-align: center;
            padding: _res-m(8,15) 0;
            font-size: _res-m(10,25);
            @include screen-sm-min{
                padding: 0;
                font-size: _res(11,14);
            }
            small{ font-size: 100%; }
        }
        .footer-ds-logo{
            text-align: center;
            img{
                width: _res-m(174,284);
                @include screen-sm-min{
                  width: _res(150,284);
                }
            }
        }
    }
}
package com.example.objectdemo

import kotlin.js.ExperimentalJsExport

class Employee(var name:String,var position:String="Clerk",var dept:String="Sales",var Experience:Int=1)
{

    fun display(){
        println("Employee Details \nName:$name\nPosition:$position\nDepartment:$dept\nExperience:$Experience")
    }
    fun promote(place:String)
    {
        this.position=place
    }
    fun transfer(place:String)
    {
        this.dept=place
    }
    fun increament(inc:Int)
    {
        this.Experience+=inc
    }
}
fun main(){
    val b1=Employee("Karan","Junior Developer","sales")
    b1.display()
    b1.promote("Senior Developer")
    b1.display()
    val b2=Employee("Raju","Manager",)
    b2.display()
    b2.transfer("Marketing")
    b2.display()
    val b3=Employee("Tani", position = "Marketing", Experience = 2)
    b3.display()
    b3.increament(3)
    b3.display()
    val b4=Employee("Ashok", position = "Manager", dept = "HR")
    b4.display()
    b4.promote("Senior Manager")
    b3.display()
    val b5=Employee("Balu", position = "Analyst", dept = "Finance")
    b3.display()
    b3.transfer("Sales")
    b3.display()
    val b6=Employee("Charan", position = "Developer", Experience = 2)
    b3.display()
    b3.increament(3)
    b3.display()
}
package com.example.objectdemo

import kotlin.js.ExperimentalJsExport

class Employee(var name:String,var position:String="Clerk",var dept:String="Sales",var Experience:Int=1)
{

    fun display(){
        println("Employee Details \nName:$name\nPosition:$position\nDepartment:$dept\nExperience:$Experience")
    }
    fun promote(place:String)
    {
        this.position=place
    }
    fun transfer(place:String)
    {
        this.dept=place
    }
    fun increament(inc:Int)
    {
        this.Experience+=inc
    }
}
fun main(){
    val b1=Employee("Karan","Junior Developer","sales")
    b1.display()
    b1.promote("Senior Developer")
    b1.display()
    val b2=Employee("Raju","Manager",)
    b2.display()
    b2.transfer("Marketing")
    b2.display()
    val b3=Employee("Tani", position = "Marketing", Experience = 2)
    b3.display()
    b3.increament(3)
    b3.display()
    val b4=Employee("Ashok", position = "Manager", dept = "HR")
    b4.display()
    b4.promote("Senior Manager")
    b3.display()
    val b5=Employee("Balu", position = "Analyst", dept = "Finance")
    b3.display()
    b3.transfer("Sales")
    b3.display()
    val b6=Employee("Charan", position = "Developer", Experience = 2)
    b3.display()
    b3.increament(3)
    b3.display()
}
1. Create a 'Book' class with the following specifications:

 Properties:  title,Author,Published_year

Methods:
  displayInfo : to print Book details.

//Program
package com.example.objectoriented

class Book(val title:String, val author:String, val published_year:Int){
    fun display(){
        println("Title: $title\nAuthor: $author\nPublished Year: $published_year")
        println()
    }
}

fun main(){
    val b1 = Book("Computer Networking", "John", 2020)
    val b2 = Book("Algorithms Design And Analysis", "James", 2019)

    println("Book Details")
    println()
    b1.display()
    b2.display()
}



2. Simple class with a Primary Constructor

//Program

package com.example.objectoriented

class Emp(val ename:String, val id:Int, val age:Int){

    init {
        if(age<0){
            println("Age cannot be negative")
        }
        else{
            println("Object is created")
        }
    }
    fun showDetails(){
        println("Name: $ename \nID: $id")
    }
}

fun main(){
    val e1 = Emp("Rahul", 101, 20)
    e1.showDetails()
    println()
    val e2 = Emp("Aarav", 102, -3)
    e2.showDetails()
}


3. Implelemt a Employee Class with default constructor values

    Properties: name,position,department,experience(set it to 1 default)

  Methods: showdetails()

  a. Create a Instance with only Name specified
  b. Create a Instance with Name and Position Specified
  c. Create a Instance with All Properties Specified
  d. Instance with Name and Experience Specified
  
//Program

package com.example.objectoriented

class Employee(val name:String, val position:String = "Clerk", val department:String = "CS", val experience:Int = 1){
    fun display(){
        println("Name: $name")
        println("Poistion: $position")
        println("Department: $department")
        println("Experience: $experience")
        println()
    }
}

fun main(){
    val e1 = Employee("Rahul")
    val e2 = Employee("Aarav", "Data Analyst ", "CS")
    val e3 = Employee("James", "Manager", "IT", 20)
    val e4 = Employee("Adam", experience = 15)

    e1.display()
    e2.display()
    e3.display()
    e4.display()


}
x=0 y=0
mouse=down <y(10)>
wait(0.5)<y(-10)>
 if (window.fetch) {
            document.getElementById("submit").addEventListener("click", (e) => {
                e.preventDefault();
                fetch("https://jsonplaceholder.typicode.com/posts", {
                    method: "POST",
                    body: new FormData(document.getElementById("myForm")),
                })
                    .then((response) => response.json())
                    .then((json) => console.log(json))
                    .catch(error => console.log(error));
            });
        } else {
            document.getElementById("submit").addEventListener("click", (e) => {
                e.preventDefault();
                let xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        let result = JSON.parse(this.responseText);
                        console.log(result);
                    } else if (this.readyState == 4) {
                        console.log("can't fecth data")
                    }
                }

                xhttp.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
                const formData = new FormData(document.getElementById("myForm"));
                xhttp.send(formData);
            });
        }
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <unordered_map>
#include <algorithm>
#include <deque>
#include <set>
#include <iostream>
#include <string>
#include <algorithm>
#include <algorithm>
using namespace std;

void BFS(int startnode, const vector<vector<int> >& S){
    vector<int> visited(S.size(), 0);
    visited[startnode] = 1;
    deque<int> dq;
    dq.push_back(startnode);
    
    while(dq.empty() == false){
        int node = dq.front();
        dq.pop_front();
        
        cout << node << " ";
        
         for(int i = 0; i < S[node].size(); i++){
            int neighbor = S[node][i]; // Lấy đỉnh kề
            if(visited[neighbor] == 0){ // Nếu đỉnh kề chưa được thăm
                visited[neighbor] = 1; // Đánh dấu đỉnh kề đã được thăm
                dq.push_back(neighbor); // Thêm đỉnh kề vào deque
            }
         }
    }
}

void DFS(int node, const vector<vector<int> >& S, vector<int>& visited){
    visited[node] = 1;
    cout << node << " ";
    for(int i = 0; i < S[node].size(); i++){
        if(visited[S[node][i]] == 0){
            DFS(S[node][i], S, visited);
            }
    }
}

int main()
{
  int n,m; //số đỉnh, cạnh
  cin >> n >> m;
  vector<vector<int> > S(n);
  vector<int> visited(n,0);
  for(int i = 0; i < m; i++){
      int a,b;
      cin >> a >> b;
      S[a].push_back(b);
      S[b].push_back(a);
}

  DFS(0, S , visited);  
  return 0;  
}
import React from "react";
import ImageGallery from "react-image-gallery";
import { useImageGallery } from "../../hooks/useImageGallery";

export const FeatureImageGallery = ({
  images,
}: Record<string, any>): JSX.Element => {
  const { galleryRef, handleScreenChange, handleFullscreen } =
    useImageGallery();

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        margin: "1rem 0",
        maxWidth: "1100px",
      }}
    >
      <ImageGallery
        items={images.map(
          (image: {
            original: string | undefined;
            originalAlt: string;
            originalClass: string;
          }) => ({
            ...image,
            renderItem: () => (
              <img
                key={image.original}
                style={{ width: "auto" }}
                src={image.original}
                alt={image.originalAlt}
              />
            ),
          })
        )}
        ref={galleryRef}
        showPlayButton={false}
        showFullscreenButton={false}
        autoPlay={true}
        slideInterval={3000}
        lazyLoad={true}
        onClick={() => handleFullscreen()}
        onScreenChange={(isFullScreen) => handleScreenChange(isFullScreen)}
        showNav={false}
        showBullets={images.length > 1}
      />
    </div>
  );
};
import { useState } from 'react';

import { Badge } from '@/shadcn-ui/components/ui/badge';
import { ShadCnButton } from '@/shadcn-ui/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from '@/shadcn-ui/components/ui/dropdown-menu';
import { Separator } from '@/shadcn-ui/components/ui/separator';
import { X } from 'lucide-react';

interface BusinessesFilterProps {
  title?: string;
  icon: JSX.Element;
  options: {
    label: string | null;
    value: string;
  }[];
  onSelectedValues: (
    value: {
      label: string | null;
      value: string;
    }[],
  ) => void;
}

export function BusinessesFilter({
  icon,
  options,
  title,
}: BusinessesFilterProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedItems, setSelectedItems] = useState<
    {
      label: string | null;
      value: string;
    }[]
  >([]);

  function handleItemsSelected(clickedItem: {
    label: string | null;
    value: string;
  }) {
    const itemAlreadyExist = selectedItems.find(
      (item) => item.value === clickedItem.value,
    );

    if (itemAlreadyExist) {
      setSelectedItems((prevItems) => {
        const filteredItem = prevItems.filter(
          (prevItem) => prevItem !== itemAlreadyExist,
        );
        return filteredItem;
      });
    } else {
      setSelectedItems((prevItems) => {
        const filteredItem = [...prevItems, clickedItem];
        return filteredItem;
      });
    }
  }

  return (
    <DropdownMenu open={isOpen}>
      <DropdownMenuTrigger asChild onClick={() => setIsOpen(true)}>
        <ShadCnButton
          variant="outline"
          size="default"
          className="h-12 border-dashed flex gap-2"
        >
          {icon}
          {title}

          <Separator orientation="vertical" className="mx-2 h-4" />
          <div>
            {selectedItems && (
              <Badge
                variant="secondary"
                className="rounded-sm px-1 font-normal"
              >
                {selectedItems.length}
              </Badge>
            )}
          </div>
        </ShadCnButton>
      </DropdownMenuTrigger>
      <DropdownMenuContent className="w-[200px] p-0" align="start">
        <div className="flex justify-between items-center p-2 border-b">
          <span className="font-medium">{title}</span>
          <ShadCnButton
            variant="ghost"
            size="sm"
            className="h-8 w-8 p-0"
            onClick={() => setIsOpen(false)}
          >
            <X className="h-4 w-4" />
          </ShadCnButton>
        </div>
        <div className="flex flex-col gap-2 p-2">
          {options.map(({ label, value }) => {
            const isChecked = selectedItems.find(
              (item) => item.value === value,
            );
            return (
              <DropdownMenuCheckboxItem
                checked={!!isChecked}
                onCheckedChange={() => {
                  handleItemsSelected({ label, value });
                }}
                key={value}
              >
                {label}
              </DropdownMenuCheckboxItem>
            );
          })}
        </div>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
#include <bits/stdc++.h>
#include <algorithm>
#include <cmath>
using namespace std;


int gcd(int a, int b){
    while(b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int lcm(int a, int b){
    return (a*b) / gcd(a,b);
}
<!-- sldsValidatorIgnore -->
<template>
      <div class="related-list-style-div"></div>
      <div class="slds-card_boundary">
            <div class="slds-page-header related-list-header">
                  <div class="slds-page-header__row">
                        <div class="slds-page-header__col-title" style="margin: auto;">
                              <div class="slds-media">
                                    <div class="slds-media__figure">
                                          <lightning-icon icon-name="standard:quotes" size="small"
                                                title="large size"></lightning-icon>
                                    </div>
                                    <div class="slds-media__body">
                                          <div class="slds-page-header__name">
                                                <div class="slds-page-header__name-title">
                                                      <h1>
                                                            <span
                                                                  class="slds-page-header__title slds-truncate related-list-title">
                                                                  Grupo de Cotações ({qntQuotes})
                                                            </span>
                                                      </h1>
                                                </div>
                                          </div>
                                    </div>
                              </div>
                        </div>
                        <div class="slds-page-header__col-actions">
                              <div class="slds-page-header__controls">
                                    <!-- <div if:true={showClipWrapButton} class="slds-page-header__control">
                                          <button class="slds-button slds-button_icon slds-button_icon-more"
                                                aria-haspopup="true" aria-expanded="false" title="Clip/Wrap Text"
                                                onclick={handleClipWrap}>
                                                <lightning-icon if:true={wrapText} icon-name="utility:right_align"
                                                      alternative-text="Wrap Text" size="xx-small"></lightning-icon>
                                                <lightning-icon if:false={wrapText}
                                                      icon-name="utility:center_align_text" alternative-text="Clip Text"
                                                      size="xx-small"></lightning-icon>
                                                <span class="slds-assistive-text">Clip/Wrap Text</span>
                                          </button>
                                    </div> -->

                                    <div class="slds-page-header__control">
                                          <button class="slds-button slds-button_icon slds-button_icon-border-filled"
                                                title="Refresh List" onclick={handleRefreshList}>
                                                <lightning-icon icon-name="utility:refresh"
                                                      alternative-text="Refresh List" size="xx-small"></lightning-icon>
                                                <span class="slds-assistive-text">Refresh List</span>
                                          </button>
                                    </div>

                                    <!-- <template if:true={showNewButton}>
                                          <div class="slds-page-header__control">
                                                <ul class="slds-button-group-list">
                                                      <li>
                                                            <lightning-button variant="neutral" label="New"
                                                                  onclick={navigateToNewRecordPage}></lightning-button>
                                                      </li>
                                                </ul>
                                          </div>
                                    </template> -->

                              </div>
                        </div>
                  </div>
            </div>

            <div class="related-list-body">
                  <lightning-tree-grid columns={gridColumns} data={gridData} key-field="id" hide-checkbox-column>
                  </lightning-tree-grid>
            </div>
      </div>
</template>
#include <iostream>
#include <iomanip>
using namespace std;

struct Time {
    int hours;
    int minutes;
    int seconds;
};

// Function to calculate time difference
Time calculateTimeDifference(Time t1, Time t2) {
    Time difference;

    // Calculate total seconds for both times
    int seconds1 = t1.hours * 3600 + t1.minutes * 60 + t1.seconds;
    int seconds2 = t2.hours * 3600 + t2.minutes * 60 + t2.seconds;

    // Difference in seconds
    int diffSeconds = seconds1 - seconds2;

    // Convert difference back to hours, minutes, seconds
    difference.hours = diffSeconds / 3600;
    diffSeconds = diffSeconds % 3600;
    difference.minutes = diffSeconds / 60;
    difference.seconds = diffSeconds % 60;

    return difference;
}

int main() {
    // Input the two times
    Time t1, t2;
    char colon;
    cin >> t1.hours >> colon >> t1.minutes >> colon >> t1.seconds;
    cin >> t2.hours >> colon >> t2.minutes >> colon >> t2.seconds;

    // Calculate the difference
    Time difference = calculateTimeDifference(t1, t2);

    // Output the difference in HH:MM:SS format
    cout << setfill('0') << setw(2) << difference.hours << ":"
         << setfill('0') << setw(2) << difference.minutes << ":"
         << setfill('0') << setw(2) << difference.seconds << endl;

    return 0;
}
<!-- Squarepaste Form Logic © -->

<script src="https://storage.googleapis.com/squarepaste/base-jquery.js"></script>

<script type="text/javascript">
/* Select Field */

$(document).on('change', '#select-6ed7f446-8ef8-42ea-abf4-e72a84b41cb3-field select', function() {

        const value = $(this).val();

        if (value == 'Yes') {

           $('#section-8ce22bc1-00cb-43c0-b3ab-cccaab43ad22').fadeIn();

        }

        else {

            $('#section-8ce22bc1-00cb-43c0-b3ab-cccaab43ad22').hide();

        }

    });

/* Radio Field- Hide submit button based on radio button selection and display message */
    $(document).on('change', 'input[type="radio"]', function() {
        if ($('input[type="radio"][value="No"]:checked').length > 0) {
            $('button[type="submit"]').fadeIn();
            $('#section-26b8b3d8-8295-42a8-bae3-3f26b85de441').hide();
        } else if ($('input[type="radio"][value="No"]:checked').length === 0) {
            $('button[type="submit"]').hide();
            $('#section-26b8b3d8-8295-42a8-bae3-3f26b85de441').fadeIn();

        } else {
            $('button[type="submit"]').hide();
        }
    });

    // Trigger the change event on page load to set initial state
    $('input[type="radio"]:checked').change();

    

</script>
const CategoryCard: React.FC<CategoryCardProps> = ({ name, icon: Icon }) => {
  return (
    <div className="flex h-14 w-full items-center justify-start rounded-2xl bg-frostWhite/80 px-4 shadow-md transition-shadow duration-300 hover:shadow-lg">
      <Icon className="text-[22px] text-gray-600" />
      <span className="ml-3 text-xl font-medium text-gray-800">{name}</span>
    </div>
  );
};



import { IconType } from "react-icons";
import {
  FaBolt,
  FaPalette,
  FaStar,
  FaLaptop,
  FaFont,
  FaCamera,
  FaGraduationCap,
  FaBlog,
  FaPodcast,
  FaBook,
  FaUniversalAccess,
  FaUsers,
  FaRobot,
  FaPencilRuler,
  FaMagic,
  FaPaintBrush,
  FaClipboardCheck,
  FaCode,
} from "react-icons/fa";

interface Category {
  id: string;
  name: string;
  icon: IconType;
}

export const categories: Category[] = [
  { id: "inspiration", name: "Inspiration", icon: FaBolt },
  { id: "illustrations", name: "Illustrations", icon: FaPalette },
  { id: "icons", name: "Icons", icon: FaStar },
  { id: "mockups", name: "Mockups", icon: FaLaptop },
];


#include <iostream>
#include <string>

using namespace std;

class Person {
private:
    string name;
    int age;
    string gender;

public:
    void setDetails(string n, int a, string g) {
        name = n;
        age = a;
        gender = g;
    }

    void displayDetails() {
        string uppercaseName = "";
        string uppercaseGender = "";

        for (char c : name) {
            uppercaseName += toupper(c);
        }

        for (char c : gender) {
            uppercaseGender += toupper(c);
        }

        cout << uppercaseName << " " << age << " " << uppercaseGender << endl;
    }
};

int main() {
    Person person;
    string name;
    int age;
    string gender;


    cin >> name;
 
    cin >> age;

    cin >> gender;

    person.setDetails(name, age, gender);
    person.displayDetails();

    return 0;
}
#include <iostream>
#include <string>

using namespace std;

class dayOfWeek {
public:
    int dayNumber;
    string dayName;

    void setDay(int n) {
        dayNumber = n;
        switch (dayNumber) {
            case 1: dayName = "Sunday"; break;
            case 2: dayName = "Monday"; break;
            case 3: dayName = "Tuesday"; break;
            case 4: dayName = "Wednesday"; break;
            case 5: dayName = "Thursday"; break;
            case 6: dayName = "Friday"; break;
            case 7: dayName = "Saturday"; break;
            case 0: dayName = "Weekend"; break;
            default: dayName = "Invalid"; break;
        }
    }

    void printDay() {
        cout << dayName << endl;
    }
};

int main() {
    dayOfWeek day;
    int dayNumber;

    cin >> dayNumber;

    day.setDay(dayNumber);
    day.printDay();

    return 0;
}
#include <iostream>
#include <cmath>

using namespace std;

int main() {
    long long binaryNumber;

    cin >> binaryNumber;

    long long decimalNumber = 0;
    int power = 0;

    while (binaryNumber != 0) {
        int digit = binaryNumber % 10;
        decimalNumber += digit * pow(2, power);
        binaryNumber /= 10;
        power++;
    }

    cout << "Decimal: " << decimalNumber << endl;

    return 0;
}
<div className="card m-[0_10px] mb-10 flex flex-col items-center rounded-[24px] bg-midnightBlue p-[50px_50px_60px_50px] text-center">
      <Image
        width="300"
        height="280"
        alt=""
        src="/oneHour/image.jpg"
        className="m-[-100px_0_30px_0]
    h-[180px]
    w-full
    rounded-[inherit]
    object-cover
    shadow-[0_60px_40px_rgba(0,0,0,0.08)]"
      />
      <div>
        <h2 className="pb-6 text-2xl font-bold text-frostWhite">
          Developer Portfolios
        </h2>
        <p className="pb-10 text-base font-normal text-frostWhite">
          Empowering users through captivating interfaces, turning ideas into
          pixel-perfect realities.
        </p>
        <button className="rounded-full border bg-frostWhite px-4 py-2 text-base font-medium text-darkSlate">
          Check Collection
        </button>
      </div>
    </div>
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: Xero Boost Days- What's on! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Hey Manchester! \n\n We're excited to kickstart another great week in the office with our new Boost Day Program! :zap: \n\nPlease see below for what's on this week! "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-27: Tuesday, 27th August",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Café-style beverages with *Ditto Coffee*, located at 61, Oxford Street, M1 6EQ. (Please show your Xero ID to claim your free coffee)\n:breakfast: *Breakfast*: Provided by *Balance Kitchen* from *9:00AM* in the kitchen area."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-29: Thursday, 29th August",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Café-style beverages with *Ditto Coffee*, located at 61 Oxford Street, M1 6EQ. (Please bring your Xero ID to claim your free coffee)\n:Lunch-2: *Lunch*: Provided by *Balance Kitcheb* from *12:30PM* in the kitchen area."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Comms will be via this slack channel, get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
	]
}
/* 
 * C program to Implement the Circular Doubly Linked List
 */
 
#include<stdio.h>
#include<stdlib.h>
 
// structure of the node
struct node
{
    struct node* prev;
    int data;
    struct node* next;
};
 
// global declaration of head node
struct node* head = NULL;
 
// function prototyping
struct node* create(int);
void insert_begin(int);
void insert_end(int);
void insert_mid(int, int);
void delete_begin();
void delete_end();
void delete_mid();
int search(int);
void update(int, int);
void sort();
int list_size();
void display();
void display_reverse(struct node*);
int get_data();
int get_position();
 
int main()
{
    char user_active = 'Y';
    int user_choice;
    int data, position;
 
    while(user_active == 'Y' || user_active == 'y')
    {
        printf("\n\n------ Circular Doubly Linked List -------\n");
        printf("\n1. Insert a node at beginning");
        printf("\n2. Insert a node at end");
        printf("\n3. Insert a node at given position");
        printf("\n\n4. Delete a node from beginning");
        printf("\n5. Delete a node from end");
        printf("\n6. Delete a node from given position");
        printf("\n\n7. Print list from beginning");
        printf("\n8. Print list from end");
        printf("\n9. Search a node data");
        printf("\n10. Update a node data");
        printf("\n11. Sort the list");
        printf("\n12. Exit");
        printf("\n\n------------------------------\n");
 
        printf("\nEnter your choice: ");
        scanf("%d", &user_choice);
 
        printf("\n------------------------------\n");
        switch(user_choice)
        {
            case 1:
                printf("\nInserting a node at beginning");
                data = get_data();
                insert_begin(data);
                break;
 
            case 2:
                printf("\nInserting a node at end");
                data = get_data();
                insert_end(data);
                break;
 
            case 3: 
                printf("\nInserting a node at the given position");
                data = get_data();
                position = get_position();
                insert_mid(position, data);
                break;
 
            case 4: 
                printf("\nDeleting a node from beginning\n");
                delete_begin();
                break;
 
            case 5: 
                printf("\nDeleting a node from end\n");
                delete_end();
                break;
 
            case 6: 
                printf("\nDelete a node from given position\n");
                position = get_position();
                delete_mid(position);
                break;
 
            case 7: 
                printf("\nPrinting the list from beginning\n\n");
                display();
                break;
 
            case 8: 
                printf("\nPrinting the list from end\n\n");
                if (head == NULL)
                {
                    printf("\n\tList is Empty!\n");
                } else {
                    display_reverse(head);
                }
                break;
 
            case 9:
                printf("\nSearching the node data");
                data = get_data();
                if (search(data) == 1) {
                    printf("\n\tNode Found\n");
                } else {
                    printf("\n\tNode Not Found\n");
                }
                break;
 
            case 10:
                printf("\nUpdating the node data");
                data = get_data();
                position = get_position();
                update(position, data);
                break;
 
            case 11:
                sort();
                printf("\nList was sorted\n");
                break;
            case 12:
                printf("\nProgram was terminated\n\n");
                return 0;
 
            default:
                printf("\n\tInvalid Choice\n");
        }
 
        printf("\n...............................\n");
        printf("\nDo you want to continue? (Y/N) : ");
        fflush(stdin);
        scanf(" %c", &user_active);
    }
 
    return 0;
}
 
// creates a new node 
struct node* create(int data)
{
    struct node* new_node = (struct node*) malloc (sizeof(struct node));
 
    if (new_node == NULL)
    {
        printf("\nMemory can't be allocated\n");
        return NULL;
    }
 
    new_node->data = data;
    new_node->next = NULL;
    new_node->prev = NULL;
 
    return new_node;
}
 
// insert a new node at the beginning of the list
void insert_begin(int data)
{
    struct node* new_node = create(data);
 
    if (new_node)
    {
        // if list is empty
        if (head == NULL)
        {
            new_node->next = new_node;
            new_node->prev = new_node;
            head = new_node;
            return;
        }
        head->prev->next = new_node;
        new_node->prev = head->prev;
        new_node->next = head;
        head->prev = new_node;
        head = new_node;
    }
}
 
// inserts a new node at the end 
void insert_end(int data)
{
    struct node* new_node = create(data);
 
    if (new_node)
    {
        if (head == NULL)
        {
            new_node->next = new_node;
            new_node->prev = new_node;
            head = new_node;
            return;
        }
        head->prev->next = new_node;
        new_node->prev = head->prev;
        new_node->next = head;
        head->prev = new_node;
    }
}
 
// inserts node at the given position
void insert_mid(int position, int data)
{
    // checking if the position is valid or not
    if (position <= 0)
    {
        printf("\nInvalid Position\n");
    } else if (head == NULL && position > 1) {
        printf("\nInvalid Position\n");
    } else if (head != NULL && position > list_size()) {
        printf("\nInvalid Position\n");
    } else if (position == 1) {
        insert_begin(data);
    } else {
        struct node *new_node = create(data);
 
        if (new_node != NULL) {
            struct node *temp = head, *prev = NULL;
            int i = 1;
 
            // traverse the list to the given position
            while (++i <= position) {
                prev = temp;
                temp = temp->next;
            }
 
            // update the prev node to the new noe
            prev->next = new_node;
 
            // update the new node to the temp (position node)
            new_node->next = temp;
        }
    }
}
 
void delete_begin()
{
    if (head == NULL) {
        printf("\nList is Empty\n");
        return;
    } else  if (head->next == head) {
        free(head);
        head = NULL;
        return;
    }
 
    struct node* temp = head;
    head->prev->next = head->next;
    head->next->prev = head->prev;
    head = head->next;
 
    free(temp);
    temp = NULL;
}   
 
// deletes the node from the end of the list
void delete_end()
{
    if (head == NULL) {
        printf("\nList is Empty\n");
        return;
    } else  if (head->next == head) {
        free(head);
        head = NULL;
        return;
    }
 
    struct node* last_node = head->prev;
 
    last_node->prev->next = head;
    head->prev = last_node->prev;
 
    free(last_node);
    last_node = NULL;
}
 
// deletes the node from the given position
void delete_mid(int position)
{
    if (position <= 0) {
        printf("\n Invalid Position \n");
    }
    else if (position > list_size()) {
        printf("\n Invalid position \n");
    }
    else if (position == 1) {
        delete_begin();
    }
    else if (position == list_size()) {
        delete_end();
    }
    else {
        struct node *temp = head;
        struct node *prev = NULL;
        int i = 1;
 
        while (i < position) {
            prev = temp;
            temp = temp->next;
            i += 1;
        }
        prev->next = temp->next;
        temp->next->prev = prev;
        free(temp);
        temp = NULL;
    }
}
 
// search the node with the given key item
int search(int key)
{
    if (head == NULL) {
        printf("\n Not Found \n");
        return 0;
    }
 
    struct node* temp = head;
    do
    {
        if (temp->data == key) {
            return 1;
        }
        temp = temp->next;
    } while (temp != head);
 
    return 0;
}
 
// updates the data of the given node position
void update(int position, int new_value)
{
    if (head == NULL) {
        printf("\n  List is Empty \n");
        return;
    } else if (position <= 0 || position > list_size()) {
        printf("\nInvalid position\n");
        return;
    } 
 
    struct node* temp = head;
    int i = 0;
 
    while (++i < position) {
        temp = temp->next;
    }
    temp->data = new_value;
}
 
 
// sorts the linked list data using insertion sort
void sort()
{
    if (head == NULL) {
       printf("\nList  is Empty\n");
       return;
    }
    struct node* temp1 = head;
    struct node* temp2 = head;
    int key = 0, value;
 
    do {
        temp2 = temp1->next;
 
        while(temp2 != head)
        {
            if (temp1->data > temp2->data)
            {
                value = temp1->data;
                temp1->data = temp2->data;
                temp2->data = value;
            }
            temp2 = temp2->next;
        }
        temp1 = temp1->next;
    }while (temp1->next != head);
 
}
 
 
// display the list
void display()
{
    if (head == NULL) {
        printf("\nList is empty!\n");
        return;
    }
 
    struct node* temp = head;
    do {
        printf("%d ", temp->data);
        temp = temp->next;
    } while (temp != head);
}
 
// display the list from end to start
void display_reverse(struct node* temp)
{
    if (temp->next == head) {
        printf("%d ", temp->data);
        return;
    }
 
    display_reverse(temp->next);
    printf("%d ", temp->data);
}
 
// calculate the size of the list
int list_size()
{
    if (head == NULL) {
        return 0;
    }
 
    struct node* temp = head;
    int count = 0;
 
    do {
        count += 1;
        temp = temp->next;
    } while (temp != head);
 
    return count;
}
 
 
int get_data()
{
    int data;
    printf("\n\nEnter Data: ");
    scanf("%d", &data);
 
    return data;
}
 
int get_position()
{
    int position;
    printf("\n\nEnter Position: ");
    scanf("%d", &position);
 
    return position;
}
#include <stdio.h>
#include <stdlib.h>

// node creation
struct Node {
  int data;
  struct Node* next;
  struct Node* prev;
};

// insert node at the front
void insertFront(struct Node** head, int data) {
  // allocate memory for newNode
  struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

  // assign data to newNode
  newNode->data = data;

  // make newNode as a head
  newNode->next = (*head);

  // assign null to prev
  newNode->prev = NULL;

  // previous of head (now head is the second node) is newNode
  if ((*head) != NULL)
    (*head)->prev = newNode;

  // head points to newNode
  (*head) = newNode;
}

// insert a node after a specific node
void insertAfter(struct Node* prev_node, int data) {
  // check if previous node is null
  if (prev_node == NULL) {
    printf("previous node cannot be null");
    return;
  }

  // allocate memory for newNode
  struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

  // assign data to newNode
  newNode->data = data;

  // set next of newNode to next of prev node
  newNode->next = prev_node->next;

  // set next of prev node to newNode
  prev_node->next = newNode;

  // set prev of newNode to the previous node
  newNode->prev = prev_node;

  // set prev of newNode's next to newNode
  if (newNode->next != NULL)
    newNode->next->prev = newNode;
}

// insert a newNode at the end of the list
void insertEnd(struct Node** head, int data) {
  // allocate memory for node
  struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

  // assign data to newNode
  newNode->data = data;

  // assign null to next of newNode
  newNode->next = NULL;

  // store the head node temporarily (for later use)
  struct Node* temp = *head;

  // if the linked list is empty, make the newNode as head node
  if (*head == NULL) {
    newNode->prev = NULL;
    *head = newNode;
    return;
  }

  // if the linked list is not empty, traverse to the end of the linked list
  while (temp->next != NULL)
    temp = temp->next;

  // now, the last node of the linked list is temp

  // assign next of the last node (temp) to newNode
  temp->next = newNode;

  // assign prev of newNode to temp
  newNode->prev = temp;
}

// delete a node from the doubly linked list
void deleteNode(struct Node** head, struct Node* del_node) {
  // if head or del is null, deletion is not possible
  if (*head == NULL || del_node == NULL)
    return;

  // if del_node is the head node, point the head pointer to the next of del_node
  if (*head == del_node)
    *head = del_node->next;

  // if del_node is not at the last node, point the prev of node next to del_node to the previous of del_node
  if (del_node->next != NULL)
    del_node->next->prev = del_node->prev;

  // if del_node is not the first node, point the next of the previous node to the next node of del_node
  if (del_node->prev != NULL)
    del_node->prev->next = del_node->next;

  // free the memory of del_node
  free(del_node);
}

// print the doubly linked list
void displayList(struct Node* node) {
  struct Node* last;

  while (node != NULL) {
    printf("%d->", node->data);
    last = node;
    node = node->next;
  }
  if (node == NULL)
    printf("NULL\n");
}

int main() {
  // initialize an empty node
  struct Node* head = NULL;

  insertEnd(&head, 5);
  insertFront(&head, 1);
  insertFront(&head, 6);
  insertEnd(&head, 9);

  // insert 11 after head
  insertAfter(head, 11);

  // insert 15 after the seond node
  insertAfter(head->next, 15);

  displayList(head);

  // delete the last node
  deleteNode(&head, head->next->next->next->next->next);

  displayList(head);
}
import os
import sys
import re
import json
import logging
from pathlib import Path
from dotenv import load_dotenv
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.db import connection
from langchain_community.agent_toolkits import create_sql_agent
from langchain_community.utilities import SQLDatabase
from langchain_groq import ChatGroq
from langchain.tools import BaseTool
from langchain.chains import LLMChain
from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
from langchain.schema import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from .models import AssetData
from langchain.agents import load_tools, initialize_agent, AgentType
# Setup Django environment
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_root)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "asset_management_system.settings")
import django
django.setup()

# Setup logging
logger = logging.getLogger(__name__)

# Load environment variables and set up API keys
load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')
groq_api_key = os.getenv("GROQ_API_KEY")
os.environ["GROQ_API_KEY"] = groq_api_key

# Initialize LLM
llm = ChatOpenAI(api_key=api_key, model="gpt-4o-mini", temperature=0)

# Constants
WEBAPP_INFO = """
The Asset Management System features a login system with three roles: Master Admin, Super Admin, and Admin, each with specific permissions. The system supports various asset types, with QR codes generated for each asset for easy tracking and management. Assets can be transferred between branches, with movement history tracked for audits.
"""

offense_words = ['asdf','asdfasdf']

# Create SQLDatabase instance
db_engine = connection.settings_dict['ENGINE']
db_name = connection.settings_dict['NAME']
if isinstance(db_name, (str, Path)):
    db_name = str(db_name)
else:
    raise ValueError(f"Unexpected type for db_name: {type(db_name)}")
db_url = f"sqlite:///{db_name}" if 'sqlite' in db_engine else f"{db_engine}://{db_name}"
db = SQLDatabase.from_uri(db_url)

# Create SQL agent
sql_agent = create_sql_agent(llm, db=db, agent_type="openai-tools", verbose=True)


class GreetingTool(BaseTool):
    name = "greeting_tool"
    description = "Use this to respond to greetings or simple queries that don't require complex reasoning."

    def _run(self, query: str) -> str:
        greetings = ["hello", "hi", "hey", "greetings", "good morning", "good afternoon", "good evening"]
        if any(greeting in query.lower() for greeting in greetings):
            return "Hello! I'm the Asset Trace AI assistant. How can I help you with asset management today?"
        return "I'm here to help with asset management. What specific information or assistance do you need?"

    async def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

# Tool classes
class QueryValidationTool(BaseTool):
    name = "query_validation_tool"
    description = f"""Evaluate the given query to ensure it is appropriate, respectful, and suitable for general audiences. Check for offensive language, hate speech, explicit content, harassment, sensitive topics, and respectfulness."""

    def _run(self, query: str) -> str:
        return "VALID" if len(query) > 5 and all(word.lower() not in query.lower() for word in offense_words) else "INVALID"

    async def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

class CybersecurityTool(BaseTool):
    name = "cybersecurity_tool"
    description = """Checks if the query contains any potentially malicious content, including injection attacks, XSS, malware links, obfuscation techniques, and known vulnerabilities."""

    def _run(self, query: str) -> str:
        return "SAFE" if all(word.lower() not in query.lower() for word in ["hack", "exploit", "vulnerability", "attack", "'; DROP TABLE", "<script>"]) else "UNSAFE"

    async def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

class AssetAdditionTool(BaseTool):
    name = "asset_addition_tool"
    description = "Provides instructions on how to add an asset to the Asset Management System."

    def _run(self, query: str) -> str:
        return """
        To add an asset to the Asset Management System:
        1. Log in to the system.
        2. Navigate to 'Assets' section.
        3. Click 'Add New Asset'.
        4. Fill in asset details.
        5. Click 'Save'.
        6. A QR code will be generated for tracking.
        Contact support for further assistance.
        """

    async def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

# Create instances of specialized tools
query_validation_tool = QueryValidationTool()
cybersecurity_tool = CybersecurityTool()
asset_addition_tool = AssetAdditionTool()
greeting_tool = GreetingTool()

# Define the tools
tools = [
    Tool(name="Greeting", func=greeting_tool.run, description="Use this to handle greetings and simple queries"),
    Tool(name="Query Validation", func=query_validation_tool.run, description="Use this to validate user queries"),
    Tool(name="Cybersecurity Check", func=cybersecurity_tool.run, description="Use this to perform security checks on user queries"),
    Tool(name="Asset Addition", func=asset_addition_tool.run, description="Use this to get instructions on adding an asset"),
    Tool(name="Database Query", func=sql_agent.run, description="Use this to query the database for asset information and should not give the table details")
]

# Define the agent
prefix = """You are an AI assistant for the Asset Trace application. Your role is to provide accurate and helpful information about the application, assist users with queries, and guide them in using the app effectively.

Application Details:
{WEBAPP_INFO}

Available Tools: [Greeting, Query Validation, Cybersecurity Check, Asset Addition, Database Query]

Key Instructions:
- For simple greetings or queries, use the Greeting tool directly without further reasoning.
- For more complex queries related to asset management, use the appropriate tools.
- Respond in the same language as the user's query.
- Provide concise answers for simple questions, offering to elaborate if needed.
- Maintain a professional and friendly tone.
- If you're unsure about any information, state that clearly and suggest where the user might find accurate details.
- For complex queries, break down your response into clear, manageable steps.
- Respect user privacy and data security at all times.

Please respond to user queries based on these guidelines and the information provided about the Asset Trace application.
"""

suffix = """Begin! Remember to focus on the current query and not be overly influenced by past interactions"""

prompt = ZeroShotAgent.create_prompt(
    tools,
    prefix=prefix,
    suffix=suffix,
    input_variables=["input", "agent_scratchpad", "WEBAPP_INFO"]
)

llm_chain = LLMChain(llm=llm, prompt=prompt)

tool_names = [tool.name for tool in tools]
agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)

# Create the agent with a maximum number of iterations
agent = initialize_agent(
    tools, 
    llm, 
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, 
    verbose=True,
    max_iterations=3,  # Limit the number of iterations
    early_stopping_method="generate",
    agent_kwargs={
        "prefix": prefix,
        "format_instructions": """Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question"""
    }
)

def process_query(query: str) -> str:
    try:
        response = agent.run(input=query, WEBAPP_INFO=WEBAPP_INFO)
        return response
    except Exception as e:
        logger.error(f"Error processing query: {str(e)}", exc_info=True)
        return "I apologize, but I encountered an issue while processing your request. Could you please rephrase your question or try again later?"

@csrf_exempt
@require_http_methods(["POST"])
def chatbot_response(request):
    logger.info("Chatbot response view called")
    try:
        data = json.loads(request.body)
        user_message = data.get('message', '').strip()
        conversation_history = data.get('conversation_history', [])
        logger.info(f"Received message: {user_message}")

        system_message = f"""
        You are an AI assistant for an asset management system. Here's the current context:
        1. User's latest message: "{user_message}"
        2. System overview: {WEBAPP_INFO}
        Respond naturally and conversationally. If the user asks about an asset or the system's capabilities, provide relevant information.
        If they ask about something we don't have info on, politely explain that and offer to help with something else.
        Always stay focused on asset management and the system's capabilities.
        """

        messages = [SystemMessage(content=system_message)]
        for msg in conversation_history[-5:]:
            messages.append(HumanMessage(content=msg['user_message']))
            messages.append(SystemMessage(content=msg['ai_response']))
        messages.append(HumanMessage(content=user_message))

        response = process_query(user_message)

        conversation_history.append({
            'user_message': user_message,
            'ai_response': response
        })

        return JsonResponse({
            'response': response,
            'conversation_history': conversation_history
        })
    except json.JSONDecodeError:
        logger.error("Invalid JSON received")
        return JsonResponse({'error': 'We encountered an issue processing your request. Please try again.'}, status=400)
    except Exception as e:
        logger.error(f"An error occurred: {str(e)}", exc_info=True)
        return JsonResponse({'error': 'We apologize, but we experienced a temporary issue. Please try again later.'}, status=500)
#views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import AssetData, AssetType,AssetImage,Asset_movement_data
from .forms import AssetDataForm, AssetTypeForm,AssetMovementForm
from django.urls import reverse
from .utils import generate_qr_code
from authentication.models import Branches
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

def asset_list(request):
    
    user = request.user
    if user.is_superuser:
        assets = AssetData.objects.all()
        asset_type = AssetType.objects.all()
    elif user.is_superadmin and user.head_office:
        branches = Branches.objects.filter(head_office=user.head_office)
        assets = AssetData.objects.filter(branch__in=branches)
        asset_type = AssetType.objects.filter(assets__branch__in=branches).distinct()
    elif user.is_admin and user.branch:
        assets = AssetData.objects.filter(branch=user.branch)
        asset_type = AssetType.objects.filter(assets__branch=user.branch).distinct()
    else:
        assets = AssetData.objects.none()
        asset_type = AssetType.objects.none()
    print(assets)
    asset_data=[]

    for asset in assets:

        vessel_url = request.build_absolute_uri(reverse('asset_link', args=[asset.id]))
        qr_code_url = generate_qr_code(asset.asset_name, vessel_url)
        asset_data.append({'asset': asset, 'qr_code_url': qr_code_url})
    
    return render(request, 'asset/asset_list.html', {'assets': asset_data,'asset_type':asset_type})




def asset_create(request):
    if request.method == 'POST':
        if 'asset_type_submit' in request.POST:
            return handle_asset_type_submit(request)
        elif 'asset_submit' in request.POST:
            return handle_asset_submit(request)
    else:
        asset_type_form = AssetTypeForm(prefix='asset_type')
        asset_form = AssetDataForm(prefix='asset')

    return render(request, 'asset/asset_form.html', {
        'asset_type_form': asset_type_form,
        'asset_form': asset_form,
    })

def handle_asset_type_submit(request):
    asset_type_form = AssetTypeForm(request.POST, prefix='asset_type')
    asset_form = AssetDataForm(prefix='asset')
    
    if asset_type_form.is_valid():
        asset_type_form.save()
        return redirect('asset_create')
    
    return render(request, 'asset/asset_form.html', {
        'asset_type_form': asset_type_form,
        'asset_form': asset_form,
    })

def handle_asset_submit(request):
    asset_form = AssetDataForm(request.POST, request.FILES, prefix='asset')
    print(f"POST data: {request.POST}")
    print(f"Form errors: {asset_form.errors}")
    asset_type_form = AssetTypeForm(prefix='asset_type')
    
    if asset_form.is_valid():
        asset = asset_form.save(commit=False)
        
       
        asset.save()  
        
        
        for image in asset_form.cleaned_data['images']:
            AssetImage.objects.create(asset=asset, image=image)
    
        
        asset_url = request.build_absolute_uri(reverse('asset_link', args=[asset.id]))
        asset.qr_code_base64 = generate_qr_code(asset.asset_name, asset_url)
        asset.save()  
        return redirect('asset_list')
    
    return render(request, 'asset/asset_form.html', {
        'asset_type_form': asset_type_form,
        'asset_form': asset_form,
    })

def get_branches(request):
    office_id = request.GET.get('office_id')
    print(office_id)
    branches = Branches.objects.filter(head_office_id=office_id).values('id', 'branch_name')
    print(branches)
    return JsonResponse(list(branches), safe=False)



def asset_detail(request, pk):
    asset = get_object_or_404(AssetData, pk=pk)
    asset_url = request.build_absolute_uri(reverse('asset_link', args=[asset.id]))
    qr_code_base64 = generate_qr_code(asset.asset_name, asset_url)
    return render(request, 'asset/asset_detail.html', {'asset': asset,'qr_code_base64': qr_code_base64,})

def asset_type_edit(request, pk):
    asset = get_object_or_404(AssetType, pk=pk)

    if request.method == 'POST':
        asset_type_form = AssetTypeForm(request.POST, instance=asset, prefix='asset_type')

        if 'asset_type_submit' in request.POST and asset_type_form.is_valid():
            asset_type_form.save()
            return redirect('asset_list')
    else:
        asset_type_form = AssetTypeForm(instance=asset, prefix='asset_type')

    return render(request, 'asset/edit_assettype.html', {'asset_type_form': asset_type_form})



def asset_edit(request, pk):
    asset = get_object_or_404(AssetData, pk=pk)

    if request.method == 'POST':
        asset_form = AssetDataForm(request.POST, request.FILES, instance=asset, prefix='asset')

        if 'asset_submit' in request.POST and asset_form.is_valid():
            asset = asset_form.save(commit=False)
            asset_url = request.build_absolute_uri(reverse('asset_link', args=[asset.id]))
            asset.qr_code_base64 = generate_qr_code(asset.asset_name, asset_url)
            asset.save()

            # Clear existing images if necessary
            asset.images.all().delete()

            # Handle image uploads
            for image in asset_form.cleaned_data['images']:
                AssetImage.objects.create(asset=asset, image=image)

            return redirect('asset_list')
    else:
        asset_form = AssetDataForm(instance=asset, prefix='asset')

    return render(request, 'asset/asset_edit.html', {
        'asset_form': asset_form,
    })


def asset_delete(request, pk):
    asset = get_object_or_404(AssetData, pk=pk)
    
    asset.delete()
    return redirect('asset_list')
    




def asset_link(request, asset_id):
    
    asset = get_object_or_404(AssetData, id=asset_id)

    main_details = [
        {'key': 'Name', 'value': asset.asset_name},
        {'key': 'Asset Type', 'value': asset.asset_type},
        {'key': 'Head Office', 'value': asset.office},
        {'key': 'Branch', 'value': asset.branch.branch_name},
        {'key': 'Model', 'value': asset.model},
        {'key': 'Purchase Date', 'value': asset.purchase_date},
        {'key': 'Warranty Info', 'value': asset.warranty_info},
    
    ]
    images = asset.images.all()
    context = {
        'asset': asset,
        'main_details': main_details,
        'images': images,
    }
    return render(request, 'asset/asset_link.html', context)


from django.http import HttpResponse
from django.conf import settings

def download_qr_code(request, vessel_id):
    vessel = get_object_or_404(AssetData, id=vessel_id)

    qr_code_path = f'{settings.MEDIA_ROOT}/qr_codes/{vessel.name}.png'

    try:
        with open(qr_code_path, 'rb') as f:
            response = HttpResponse(f.read(), content_type='image/png')
            response['Content-Disposition'] = f'attachment; filename="{vessel.name}_qr.png"'
            return response
    except FileNotFoundError:
        return HttpResponse("QR code not found", status=404)
    

from django.db.models import Q

def asset_movement_page(request):
    if request.method == 'POST':
        form = AssetMovementForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('asset_movement_list')
        else:
            print(form.errors)
    else:
        form = AssetMovementForm()
    
    # movements = Asset_movement_data.objects.all().order_by('-movement_date')
    user = request.user
    if user.is_superuser:
        movements = Asset_movement_data.objects.all()
    elif user.is_superadmin and user.head_office:
        branches = Branches.objects.filter(head_office=user.head_office)
        movements = Asset_movement_data.objects.filter(
            Q(from_branch__in=branches) | Q(to_branch__in=branches)
        )
    elif user.is_admin and user.branch:
        movements = Asset_movement_data.objects.filter(
            Q(from_branch=user.branch) | Q(to_branch=user.branch)
        )
    else:
        movements = Asset_movement_data.objects.none()
    return render(request, 'asset/asset_movement_list.html', {'form': form, 'movements': movements})

def edit_asset_movement(request, movement_id):
    movement = get_object_or_404(Asset_movement_data, id=movement_id)
    if request.method == 'POST':
        form = AssetMovementForm(request.POST, instance=movement)
        if form.is_valid():
            form.save()
            return redirect('asset_movement_list')
    else:
        form = AssetMovementForm(instance=movement)
    
    return render(request, 'asset/edit_asset_movement.html', {'form': form, 'movement': movement})


def asset_movement_success(request):
    return render(request, 'asset/asset_movement_success.html')



def asset_filter_by_branches(request, branch_id):
    branch = Branches.objects.get(id=branch_id)
    
    # Assets currently in the branch, excluding those that have been moved
    moved_out_assets = Asset_movement_data.objects.filter(from_branch=branch).values_list('asset_id', flat=True)
    assets = AssetData.objects.filter(branch=branch).exclude(id__in=moved_out_assets)
    
    # Assets moved from the branch
    moved_assets = Asset_movement_data.objects.filter(from_branch=branch).order_by('-movement_date')
    
    # Assets received at the branch
    received_assets = Asset_movement_data.objects.filter(to_branch=branch).order_by('-movement_date')
    
    context = {
        'branch': branch,
        'assets': assets,
        'moved_assets': moved_assets,
        'received_assets': received_assets,
    }
    return render(request, 'asset/assets_by_branch.html', context)

@login_required
def asset_movement_list(request):
    user = request.user
    if user.is_superuser:
        movements = Asset_movement_data.objects.all()
    elif user.is_superadmin and user.head_office:
        branches = Branches.objects.filter(head_office=user.head_office)
        movements = Asset_movement_data.objects.filter(
            Q(from_branch__in=branches) | Q(to_branch__in=branches)
        )
    else:
        movements = Asset_movement_data.objects.none()
    
    form = AssetMovementForm()  # Assuming you have this form
    
    return render(request, 'authentication/asset_movement_list.html', {
        'movements': movements,
        'form': form
    })
 
#views   
#views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import AssetData, AssetType,AssetImage,Asset_movement_data
from .forms import AssetDataForm, AssetTypeForm,AssetMovementForm
from django.urls import reverse
from .utils import generate_qr_code
from authentication.models import Branches
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

def asset_list(request):
    
    user = request.user
    if user.is_superuser:
        assets = AssetData.objects.all()
        asset_type = AssetType.objects.all()
    elif user.is_superadmin and user.head_office:
        branches = Branches.objects.filter(head_office=user.head_office)
        assets = AssetData.objects.filter(branch__in=branches)
        asset_type = AssetType.objects.filter(assets__branch__in=branches).distinct()
    elif user.is_admin and user.branch:
        assets = AssetData.objects.filter(branch=user.branch)
        asset_type = AssetType.objects.filter(assets__branch=user.branch).distinct()
    else:
        assets = AssetData.objects.none()
        asset_type = AssetType.objects.none()
    print(assets)
    asset_data=[]

    for asset in assets:

        vessel_url = request.build_absolute_uri(reverse('asset_link', args=[asset.id]))
        qr_code_url = generate_qr_code(asset.asset_name, vessel_url)
        asset_data.append({'asset': asset, 'qr_code_url': qr_code_url})
    
    return render(request, 'asset/asset_list.html', {'assets': asset_data,'asset_type':asset_type})




def asset_create(request):
    if request.method == 'POST':
        if 'asset_type_submit' in request.POST:
            return handle_asset_type_submit(request)
        elif 'asset_submit' in request.POST:
            return handle_asset_submit(request)
    else:
        asset_type_form = AssetTypeForm(prefix='asset_type')
        asset_form = AssetDataForm(prefix='asset')

    return render(request, 'asset/asset_form.html', {
        'asset_type_form': asset_type_form,
        'asset_form': asset_form,
    })

def handle_asset_type_submit(request):
    asset_type_form = AssetTypeForm(request.POST, prefix='asset_type')
    asset_form = AssetDataForm(prefix='asset')
    
    if asset_type_form.is_valid():
        asset_type_form.save()
        return redirect('asset_create')
    
    return render(request, 'asset/asset_form.html', {
        'asset_type_form': asset_type_form,
        'asset_form': asset_form,
    })

def handle_asset_submit(request):
    asset_form = AssetDataForm(request.POST, request.FILES, prefix='asset')
    print(f"POST data: {request.POST}")
    print(f"Form errors: {asset_form.errors}")
    asset_type_form = AssetTypeForm(prefix='asset_type')
    
    if asset_form.is_valid():
        asset = asset_form.save(commit=False)
        
       
        asset.save()  
        
        
        for image in asset_form.cleaned_data['images']:
            AssetImage.objects.create(asset=asset, image=image)
    
        
        asset_url = request.build_absolute_uri(reverse('asset_link', args=[asset.id]))
        asset.qr_code_base64 = generate_qr_code(asset.asset_name, asset_url)
        asset.save()  
        return redirect('asset_list')
    
    return render(request, 'asset/asset_form.html', {
        'asset_type_form': asset_type_form,
        'asset_form': asset_form,
    })

def get_branches(request):
    office_id = request.GET.get('office_id')
    print(office_id)
    branches = Branches.objects.filter(head_office_id=office_id).values('id', 'branch_name')
    print(branches)
    return JsonResponse(list(branches), safe=False)



def asset_detail(request, pk):
    asset = get_object_or_404(AssetData, pk=pk)
    asset_url = request.build_absolute_uri(reverse('asset_link', args=[asset.id]))
    qr_code_base64 = generate_qr_code(asset.asset_name, asset_url)
    return render(request, 'asset/asset_detail.html', {'asset': asset,'qr_code_base64': qr_code_base64,})

def asset_type_edit(request, pk):
    asset = get_object_or_404(AssetType, pk=pk)

    if request.method == 'POST':
        asset_type_form = AssetTypeForm(request.POST, instance=asset, prefix='asset_type')

        if 'asset_type_submit' in request.POST and asset_type_form.is_valid():
            asset_type_form.save()
            return redirect('asset_list')
    else:
        asset_type_form = AssetTypeForm(instance=asset, prefix='asset_type')

    return render(request, 'asset/edit_assettype.html', {'asset_type_form': asset_type_form})



def asset_edit(request, pk):
    asset = get_object_or_404(AssetData, pk=pk)

    if request.method == 'POST':
        asset_form = AssetDataForm(request.POST, request.FILES, instance=asset, prefix='asset')

        if 'asset_submit' in request.POST and asset_form.is_valid():
            asset = asset_form.save(commit=False)
            asset_url = request.build_absolute_uri(reverse('asset_link', args=[asset.id]))
            asset.qr_code_base64 = generate_qr_code(asset.asset_name, asset_url)
            asset.save()

            # Clear existing images if necessary
            asset.images.all().delete()

            # Handle image uploads
            for image in asset_form.cleaned_data['images']:
                AssetImage.objects.create(asset=asset, image=image)

            return redirect('asset_list')
    else:
        asset_form = AssetDataForm(instance=asset, prefix='asset')

    return render(request, 'asset/asset_edit.html', {
        'asset_form': asset_form,
    })


def asset_delete(request, pk):
    asset = get_object_or_404(AssetData, pk=pk)
    
    asset.delete()
    return redirect('asset_list')

def asset_link(request, asset_id):
    
    asset = get_object_or_404(AssetData, id=asset_id)

    main_details = [
        {'key': 'Name', 'value': asset.asset_name},
        {'key': 'Asset Type', 'value': asset.asset_type},
        {'key': 'Head Office', 'value': asset.office},
        {'key': 'Branch', 'value': asset.branch.branch_name},
        {'key': 'Model', 'value': asset.model},
        {'key': 'Purchase Date', 'value': asset.purchase_date},
        {'key': 'Warranty Info', 'value': asset.warranty_info},
    
    ]
    images = asset.images.all()
    context = {
        'asset': asset,
        'main_details': main_details,
        'images': images,
    }
    return render(request, 'asset/asset_link.html', context)


from django.http import HttpResponse
from django.conf import settings

def download_qr_code(request, vessel_id):
    vessel = get_object_or_404(AssetData, id=vessel_id)

    qr_code_path = f'{settings.MEDIA_ROOT}/qr_codes/{vessel.name}.png'

    try:
        with open(qr_code_path, 'rb') as f:
            response = HttpResponse(f.read(), content_type='image/png')
            response['Content-Disposition'] = f'attachment; filename="{vessel.name}_qr.png"'
            return response
    except FileNotFoundError:
        return HttpResponse("QR code not found", status=404)
    

from django.db.models import Q

def asset_movement_page(request):
    if request.method == 'POST':
        form = AssetMovementForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('asset_movement_list')
        else:
            print(form.errors)
    else:
        form = AssetMovementForm()
    
    # movements = Asset_movement_data.objects.all().order_by('-movement_date')
    user = request.user
    if user.is_superuser:
        movements = Asset_movement_data.objects.all()
    elif user.is_superadmin and user.head_office:
        branches = Branches.objects.filter(head_office=user.head_office)
        movements = Asset_movement_data.objects.filter(
            Q(from_branch__in=branches) | Q(to_branch__in=branches)
        )
    elif user.is_admin and user.branch:
        movements = Asset_movement_data.objects.filter(
            Q(from_branch=user.branch) | Q(to_branch=user.branch)
        )
    else:
        movements = Asset_movement_data.objects.none()
    return render(request, 'asset/asset_movement_list.html', {'form': form, 'movements': movements})

def edit_asset_movement(request, movement_id):
    movement = get_object_or_404(Asset_movement_data, id=movement_id)
    if request.method == 'POST':
        form = AssetMovementForm(request.POST, instance=movement)
        if form.is_valid():
            form.save()
            return redirect('asset_movement_list')
    else:
        form = AssetMovementForm(instance=movement)
    
    return render(request, 'asset/edit_asset_movement.html', {'form': form, 'movement': movement})


def asset_movement_success(request):
    return render(request, 'asset/asset_movement_success.html')



def asset_filter_by_branches(request, branch_id):
    branch = Branches.objects.get(id=branch_id)
    
    # Assets currently in the branch, excluding those that have been moved
    moved_out_assets = Asset_movement_data.objects.filter(from_branch=branch).values_list('asset_id', flat=True)
    assets = AssetData.objects.filter(branch=branch).exclude(id__in=moved_out_assets)
    
    # Assets moved from the branch
    moved_assets = Asset_movement_data.objects.filter(from_branch=branch).order_by('-movement_date')
    
    # Assets received at the branch
    received_assets = Asset_movement_data.objects.filter(to_branch=branch).order_by('-movement_date')
    
    context = {
        'branch': branch,
        'assets': assets,
        'moved_assets': moved_assets,
        'received_assets': received_assets,
    }
    return render(request, 'asset/assets_by_branch.html', context)

@login_required
def asset_movement_list(request):
    user = request.user
    if user.is_superuser:
        movements = Asset_movement_data.objects.all()
    elif user.is_superadmin and user.head_office:
        branches = Branches.objects.filter(head_office=user.head_office)
        movements = Asset_movement_data.objects.filter(
            Q(from_branch__in=branches) | Q(to_branch__in=branches)
        )
    else:
        movements = Asset_movement_data.objects.none()
    
    form = AssetMovementForm()  # Assuming you have this form
    
    return render(request, 'authentication/asset_movement_list.html', {
        'movements': movements,
        'form': form
    })
    
#views
import os
import sys
import re
import json
import logging
from pathlib import Path
from dotenv import load_dotenv
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.db import connection
from langchain_community.agent_toolkits import create_sql_agent
from langchain_community.utilities import SQLDatabase
from langchain_groq import ChatGroq
from langchain.tools import BaseTool
from langchain.chains import LLMChain
from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
from langchain.schema import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from .models import AssetData
from langchain.agents import load_tools, initialize_agent, AgentType
# Setup Django environment
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_root)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "asset_management_system.settings")
import django
django.setup()

# Setup logging
logger = logging.getLogger(__name__)

# Load environment variables and set up API keys
load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')
groq_api_key = os.getenv("GROQ_API_KEY")
os.environ["GROQ_API_KEY"] = groq_api_key

# Initialize LLM
llm = ChatOpenAI(api_key=api_key, model="gpt-4o-mini", temperature=0)

# Constants
WEBAPP_INFO = """
The Asset Management System features a login system with three roles: Master Admin, Super Admin, and Admin, each with specific permissions. The system supports various asset types, with QR codes generated for each asset for easy tracking and management. Assets can be transferred between branches, with movement history tracked for audits.
"""

offense_words = ["Ninde ama, pati!", "Aaana kunna", "aan-vedi", "achante andi", "Achinga Kunnan", "adichu poli", "Ajoli ka Thajoli", "ammaudi pootil poocha", "Ammente Pooru", "amminhnha", "Andi pidiyan", "anna kunna", "Appi", "appikunna", "Arjun shambu", "arraykku chuttum poorruu ullaval", "avaraathi", "avarathi mone", "Beejam", "chalam nakki", "Chandi", "Chathavante andi oombiya", "Cheekoothi mon", "Cheekoothi mone", "Chokka lingam", "CHotta kunnan", "Chotta Tha", "coondi", "Da patti", "Dushtan", "eli kunna", "Ettukali Patti Pooran", "inchi mola", "johninte andi", "kaatu poori", "kallel oouuki", "kandara oli", "kandi", "kandi theeni", "Kandu", "Kanni", "Kanni mola", "kara vedi", "karim kunna", "karim pooran", "katta thayoli", "kazhappu perutha mairan", "Keepu", "Kettal", "kodam nakiii", "Kolekkeri", "Koothara", "Koothi", "Koothichi", "kotham", "kotham kalakki", "kotham nakku", "Koyimani", "kuch", "kulamavuka", "kundan", "kundaroli poori mone", "Kundi", "Kundi mon", "Kundi oota", "kundimol", "kunji kunnan", "kunna", "Kunna", "kunna chappu", "Kunna Oli", "Kunna paal", "Kunna thayoli", "kunna urunji", "kunnappal", "kushukk", "Lick Me", "malayalam", "Mandu", "Maratel ooki", "Masa", "Mattanga Poore", "matti", "Mayiradi mon", "Mlechan", "mola", "moonchikko", "Mula Adi", "mula chappu", "mula kashakku", "mula mol", "Mundachi", "Myir", "Myre", "Myrru", "Naayi meedan", "naayinte mone", "nayinte mone", "Nayinte Mone", "Nayinte Monne", "ni urru myre", "ninde andi maire", "Ninte ama koondi ishtima", "Ninte ammakku vettu nayinte mone", "Ninte ammaku vetu", "ninte ammeda tar", "Ninte Ammede Kothil.", "ninte ammede pooru", "Ninte ammede thenga mairu", "ninte appante andi", "Odu myre", "ookki", "oomban", "oombi mon", "Oooomb", "Ootan", "paara pooru", "paareel ookki", "Pacha tayolli", "Pachila Pooran", "Paik keriko myra", "paiku vetti", "pala thanthakkundaya thaoli", "pallinedayil kanthu", "pambara kutichi", "pampara thayoli", "panchavarna kunna"]

# Create SQLDatabase instance
db_engine = connection.settings_dict['ENGINE']
db_name = connection.settings_dict['NAME']
if isinstance(db_name, (str, Path)):
    db_name = str(db_name)
else:
    raise ValueError(f"Unexpected type for db_name: {type(db_name)}")
db_url = f"sqlite:///{db_name}" if 'sqlite' in db_engine else f"{db_engine}://{db_name}"
db = SQLDatabase.from_uri(db_url)

# Create SQL agent
sql_agent = create_sql_agent(llm, db=db, agent_type="openai-tools", verbose=True)


class GreetingTool(BaseTool):
    name = "greeting_tool"
    description = "Use this to respond to greetings or simple queries that don't require complex reasoning."

    def _run(self, query: str) -> str:
        greetings = ["hello", "hi", "hey", "greetings", "good morning", "good afternoon", "good evening"]
        if any(greeting in query.lower() for greeting in greetings):
            return "Hello! I'm the Asset Trace AI assistant. How can I help you with asset management today?"
        return "I'm here to help with asset management. What specific information or assistance do you need?"

    async def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

# Tool classes
class QueryValidationTool(BaseTool):
    name = "query_validation_tool"
    description = f"""Evaluate the given query to ensure it is appropriate, respectful, and suitable for general audiences. Check for offensive language, hate speech, explicit content, harassment, sensitive topics, and respectfulness."""

    def _run(self, query: str) -> str:
        return "VALID" if len(query) > 5 and all(word.lower() not in query.lower() for word in offense_words) else "INVALID"

    async def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

class CybersecurityTool(BaseTool):
    name = "cybersecurity_tool"
    description = """Checks if the query contains any potentially malicious content, including injection attacks, XSS, malware links, obfuscation techniques, and known vulnerabilities."""

    def _run(self, query: str) -> str:
        return "SAFE" if all(word.lower() not in query.lower() for word in ["hack", "exploit", "vulnerability", "attack", "'; DROP TABLE", "<script>"]) else "UNSAFE"

    async def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

class AssetAdditionTool(BaseTool):
    name = "asset_addition_tool"
    description = "Provides instructions on how to add an asset to the Asset Management System."

    def _run(self, query: str) -> str:
        return """
        To add an asset to the Asset Management System:
        1. Log in to the system.
        2. Navigate to 'Assets' section.
        3. Click 'Add New Asset'.
        4. Fill in asset details.
        5. Click 'Save'.
        6. A QR code will be generated for tracking.
        Contact support for further assistance.
        """

    async def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

# Create instances of specialized tools
query_validation_tool = QueryValidationTool()
cybersecurity_tool = CybersecurityTool()
asset_addition_tool = AssetAdditionTool()
greeting_tool = GreetingTool()

# Define the tools
tools = [
    Tool(name="Greeting", func=greeting_tool.run, description="Use this to handle greetings and simple queries"),
    Tool(name="Query Validation", func=query_validation_tool.run, description="Use this to validate user queries"),
    Tool(name="Cybersecurity Check", func=cybersecurity_tool.run, description="Use this to perform security checks on user queries"),
    Tool(name="Asset Addition", func=asset_addition_tool.run, description="Use this to get instructions on adding an asset"),
    Tool(name="Database Query", func=sql_agent.run, description="Use this to query the database for asset information and should not give the table details")
]

# Define the agent
prefix = """You are an AI assistant for the Asset Trace application. Your role is to provide accurate and helpful information about the application, assist users with queries, and guide them in using the app effectively.

Application Details:
{WEBAPP_INFO}

Available Tools: [Greeting, Query Validation, Cybersecurity Check, Asset Addition, Database Query]

Key Instructions:
- For simple greetings or queries, use the Greeting tool directly without further reasoning.
- For more complex queries related to asset management, use the appropriate tools.
- Respond in the same language as the user's query.
- Provide concise answers for simple questions, offering to elaborate if needed.
- Maintain a professional and friendly tone.
- If you're unsure about any information, state that clearly and suggest where the user might find accurate details.
- For complex queries, break down your response into clear, manageable steps.
- Respect user privacy and data security at all times.

Please respond to user queries based on these guidelines and the information provided about the Asset Trace application.
"""

suffix = """Begin! Remember to focus on the current query and not be overly influenced by past interactions"""

prompt = ZeroShotAgent.create_prompt(
    tools,
    prefix=prefix,
    suffix=suffix,
    input_variables=["input", "agent_scratchpad", "WEBAPP_INFO"]
)

llm_chain = LLMChain(llm=llm, prompt=prompt)

tool_names = [tool.name for tool in tools]
agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)

# Create the agent with a maximum number of iterations
agent = initialize_agent(
    tools, 
    llm, 
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, 
    verbose=True,
    max_iterations=3,  # Limit the number of iterations
    early_stopping_method="generate",
    agent_kwargs={
        "prefix": prefix,
        "format_instructions": """Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question"""
    }
)

def process_query(query: str) -> str:
    try:
        response = agent.run(input=query, WEBAPP_INFO=WEBAPP_INFO)
        return response
    except Exception as e:
        logger.error(f"Error processing query: {str(e)}", exc_info=True)
        return "I apologize, but I encountered an issue while processing your request. Could you please rephrase your question or try again later?"

@csrf_exempt
@require_http_methods(["POST"])
def chatbot_response(request):
    logger.info("Chatbot response view called")
    try:
        data = json.loads(request.body)
        user_message = data.get('message', '').strip()
        conversation_history = data.get('conversation_history', [])
        logger.info(f"Received message: {user_message}")

        system_message = f"""
        You are an AI assistant for an asset management system. Here's the current context:
        1. User's latest message: "{user_message}"
        2. System overview: {WEBAPP_INFO}
        Respond naturally and conversationally. If the user asks about an asset or the system's capabilities, provide relevant information.
        If they ask about something we don't have info on, politely explain that and offer to help with something else.
        Always stay focused on asset management and the system's capabilities.
        """

        messages = [SystemMessage(content=system_message)]
        for msg in conversation_history[-5:]:
            messages.append(HumanMessage(content=msg['user_message']))
            messages.append(SystemMessage(content=msg['ai_response']))
        messages.append(HumanMessage(content=user_message))

        response = process_query(user_message)

        conversation_history.append({
            'user_message': user_message,
            'ai_response': response
        })

        return JsonResponse({
            'response': response,
            'conversation_history': conversation_history
        })
    except json.JSONDecodeError:
        logger.error("Invalid JSON received")
        return JsonResponse({'error': 'We encountered an issue processing your request. Please try again.'}, status=400)
    except Exception as e:
        logger.error(f"An error occurred: {str(e)}", exc_info=True)
        return JsonResponse({'error': 'We apologize, but we experienced a temporary issue. Please try again later.'}, status=500)
 

#image_views
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
import os
import torch
from PIL import Image
from transformers import CLIPProcessor, CLIPModel
from .models import AssetData, AssetImage

# Load the CLIP model and processor
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")

def extract_features(image_path):
    image = Image.open(image_path)
    inputs = processor(images=image, return_tensors="pt", padding=True)
    with torch.no_grad():
        image_features = model.get_image_features(**inputs)
    return image_features

@csrf_exempt
def chatbot_image_response(request):
    if request.method == 'POST':
        try:
            # Get the uploaded image from the request
            image_file = request.FILES.get('image')
            
            if not image_file:
                return JsonResponse({'error': 'No image file provided'}, status=400)

            # Save the image temporarily
            temp_path = default_storage.save('temp_image.jpg', ContentFile(image_file.read()))
            full_temp_path = os.path.join(settings.MEDIA_ROOT, temp_path)

            # Extract features from the uploaded image
            uploaded_features = extract_features(full_temp_path)

            # Find the top 3 matching images in the database
            matches = []
            for asset_image in AssetImage.objects.all():
                db_image_path = os.path.join(settings.MEDIA_ROOT, str(asset_image.image))
                db_features = extract_features(db_image_path)
                similarity = torch.nn.functional.cosine_similarity(uploaded_features, db_features).item()
                matches.append((asset_image, similarity))

            # Sort matches by similarity (descending) and get top 3
            top_matches = sorted(matches, key=lambda x: x[1], reverse=True)[:3]

            if top_matches and top_matches[0][1] > 0.8:
                response = "I've identified the top 3 assets that match the uploaded image. Here's the information:\n\n"
                for i, (asset_image, similarity) in enumerate(top_matches, 1):
                    asset = asset_image.asset
                    image_url = request.build_absolute_uri(asset_image.image.url)
                    response += f"{i}. Match {i} (Similarity: {similarity:.2f})\n"
                    response += f"   • Asset Name: {asset.asset_name}\n"
                    response += f"   • Asset Type: {asset.asset_type}\n"
                    response += f"   • Model: {asset.model}\n"
                    response += f"   • Serial Number: {asset.serial_number}\n"
                    response += f"   • Purchase Date: {asset.purchase_date}\n"
                    response += f"   • Warranty Info: {asset.warranty_info}\n"
                    response += f"   • Image: [View Image]({image_url})\n\n"

                # Include the uploaded image URL in the response
                uploaded_image_url = request.build_absolute_uri(settings.MEDIA_URL + temp_path)
                response += f"Uploaded Image: [View Uploaded Image]({uploaded_image_url})\n"
            else:
                response = "I couldn't find any assets that closely match the uploaded image. Please make sure the image is clear and matches an asset in our database."

            # Clean up the temporary file
            os.remove(full_temp_path)
            
            return JsonResponse({'response': response})
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    return JsonResponse({'error': 'Invalid request method'}, status=405)
import sys
import chilkat2

# This example program loads a file (sample.csv)
# that contains this content:
# 
# year,color,country,food
# 2001,red,France,cheese
# 2005,blue,"United States",hamburger
# 2008,green,Italy,pasta
# 1998,orange,Japan,sushi
# 
# The first row contains the column names.
# This file is available at:
# http://www.chilkatsoft.com/testData/sample.csv

csv = chilkat2.Csv()

# Prior to loading the CSV file, indicate that the 1st row
# should be treated as column names:
csv.HasColumnNames = True

# Load the CSV records from the file:

success = csv.LoadFile("sample.csv")
if (success != True):
    print(csv.LastErrorText)
    sys.exit()

# Display the contents of the 3rd column (i.e. the country names)

n = csv.NumRows
for row in range(0,n):
    print(csv.GetCell(row,2))


List<OauthToken> invalidTokens = [Select id, user.name, accesstoken,AppName, DeleteToken  From OauthToken where user.IsActive = false];
Auth.OauthTokenType  deltoken = Auth.OauthTokenType.DELETE_TOKEN;
for(OauthToken invalidToken :invalidTokens){
    try{
    	Boolean result = Auth.OauthToken.revokeToken(deltoken,invalidToken.DeleteToken);
    	system.debug('Result is: '+result);
    }catch (Exception e){
        system.debug('Exception is: '+e);
    }
}
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);

    vector<int> A = {2, 4, 6, 8, 10};  // Ví dụ vector
    int n = A.size();
    
    // Tạo mảng tổng cộng dồn S
    vector<int> S(n);
    S[0] = A[0];
    for (int i = 1; i < n; ++i) {
        S[i] = S[i-1] + A[i];
    }
    
    // Ví dụ tính tổng subarray từ i đến j
    int i = 0, j = 3;  // Thay đổi i và j để kiểm tra
    
    int sum;
    if (i == 0) {
        sum = S[j];
    } else {
        sum = S[j] - S[i-1];
    }

    cout << "Tổng của subarray từ " << i << " đến " << j << " là: " << sum << endl;

    return 0;
}
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);

    int n;
    cin >> n;
    
    vector<int> a(n), b(n);
    
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    
    for (int i = 0; i < n; ++i) {
        cin >> b[i];
    }
    
    sort(a.begin(),a.end());
    sort(b.begin(),b.end());
    
    int ans = 1000000;
    int l = 0; int r = n-1;
    while(l < n && r >= 0){
        int DIFF = a[l] + b[r];
        ans = min(ans,abs(DIFF));
        if(ans == 0){
            break;
        }
        
        if(DIFF > 0){
            r--;
        }
        else{
            l++;
        }
    }
    cout << ans;
    return 0;
}
lúc nào nhớ đến nyc thì nghe Em dạo này
nhớ quá mức thì nghe Để quên còn nếu muốn cố quên thì Đốt
nếu lụy người ta quá thì nghe Chuyện dở dang còn nếu muốn ảo tưởng rằng người ta ở cạnh mình thì nghe Em trong đầu 
Lúc nào người ta bỏ mình theo người khác thì nghe Em có chắc không? sau khi nghe bài đó xong mà đau quá thì nghe tiếp Tôi đi trú đông
Còn nếu như người ta không tôn trọng tình cảm của mình thì nghe Giả vờ
Microsoft.EnterpriseManagement.GatewayApprovalTool.exe /ManagementServerName=GW01.dmz.contoso.com /GatewayName=GW02.dmz.contoso.com /Action=Create
$GatewayServer = Get-SCOMGatewayManagementServer -Name "GW01.dmz.contoso.com"
$PrimaryServer = Get-SCOMManagementServer -Name "MS02.Contoso.com"
$FailoverServer = Get-SCOMManagementServer -Name "MS01.Contoso.com","MS03.Contoso.com"
Set-SCOMParentManagementServer -GatewayServer $GatewayServer -PrimaryServer $PrimaryServer -FailoverServer $FailoverServer
$GatewayServer = Get-SCOMGatewayManagementServer -Name "GW01.dmz.contoso.com"
$FailoverServer = Get-SCOMManagementServer -Name "MS02.Contoso.com","MS03.Contoso.com"
Set-SCOMParentManagementServer -GatewayServer $GatewayServer -FailoverServer $FailoverServer
Dim rest As New ChilkatRest
Dim success As Long

'  URL: https://api.stripe.com/v1/customers/cus_CBbgVLJqv487Oq
Dim bTls As Long
bTls = 1
Dim port As Long
port = 443
Dim bAutoReconnect As Long
bAutoReconnect = 1
success = rest.Connect("api.stripe.com",port,bTls,bAutoReconnect)
If (success <> 1) Then
    Debug.Print "ConnectFailReason: " & rest.ConnectFailReason
    Debug.Print rest.LastErrorText
    Exit Sub
End If

success = rest.SetAuthBasic("STRIPE_SECRET_KEY","")

success = rest.AddQueryParam("description","Customer for isabella.williams@example.com")

Dim strResponseBody As String
strResponseBody = rest.FullRequestFormUrlEncoded("POST","/v1/customers/cus_CBbgVLJqv487Oq")
If (rest.LastMethodSuccess <> 1) Then
    Debug.Print rest.LastErrorText
    Exit Sub
End If

Dim jsonResponse As New ChilkatJsonObject
success = jsonResponse.Load(strResponseBody)

Dim id As String
Dim object As String
Dim account_balance As Long
Dim created As Long
Dim currency As String
Dim default_source As Long
Dim delinquent As Long
Dim description As String
Dim discount As Long
Dim email As Long
Dim livemode As Long
Dim shipping As Long
Dim sourcesObject As String
Dim sourcesHas_more As Long
Dim sourcesTotal_count As Long
Dim sourcesUrl As String
Dim subscriptionsObject As String
Dim subscriptionsHas_more As Long
Dim subscriptionsTotal_count As Long
Dim subscriptionsUrl As String
Dim i As Long
Dim count_i As Long

id = jsonResponse.StringOf("id")
object = jsonResponse.StringOf("object")
account_balance = jsonResponse.IntOf("account_balance")
created = jsonResponse.IntOf("created")
currency = jsonResponse.StringOf("currency")
default_source = jsonResponse.IsNullOf("default_source")
delinquent = jsonResponse.BoolOf("delinquent")
description = jsonResponse.StringOf("description")
discount = jsonResponse.IsNullOf("discount")
email = jsonResponse.IsNullOf("email")
livemode = jsonResponse.BoolOf("livemode")
shipping = jsonResponse.IsNullOf("shipping")
sourcesObject = jsonResponse.StringOf("sources.object")
sourcesHas_more = jsonResponse.BoolOf("sources.has_more")
sourcesTotal_count = jsonResponse.IntOf("sources.total_count")
sourcesUrl = jsonResponse.StringOf("sources.url")
subscriptionsObject = jsonResponse.StringOf("subscriptions.object")
subscriptionsHas_more = jsonResponse.BoolOf("subscriptions.has_more")
subscriptionsTotal_count = jsonResponse.IntOf("subscriptions.total_count")
subscriptionsUrl = jsonResponse.StringOf("subscriptions.url")
i = 0
count_i = jsonResponse.SizeOfArray("sources.data")
Do While i < count_i
    jsonResponse.I = i
    i = i + 1
Loop
i = 0
count_i = jsonResponse.SizeOfArray("subscriptions.data")
Do While i < count_i
    jsonResponse.I = i
    i = i + 1
Loop
'  It requires the Chilkat API to have been previously unlocked.
'  See Global Unlock Sample for sample code.

Dim http As New ChilkatHttp
Dim req As New ChilkatHttpRequest

'  The AddHeader method corresponds to the curl "-H" argument.
req.AddHeader "Accept","application/json"
req.AddHeader "Accept-Language","en_US"

'  The curl "-d" argument specifies the HTTP request body.  In this case,
'  we're sending an application/x-www-form-urlencoded request, and therefore
'  the body contains the URL-encoded query parameters.
req.AddParam "grant_type","client_credentials"

http.Login = "PAYPAL_REST_API_CLIENT_ID"
http.Password = "PAYPAL_REST_API_SECRET"

'  Sends a POST request where the Content-Type is application/x-www-form-urlencoded
Dim resp As ChilkatHttpResponse
Set resp = http.PostUrlEncoded("https://api.sandbox.paypal.com/v1/oauth2/token",req)
If (http.LastMethodSuccess <> 1) Then
    Debug.Print http.LastErrorText
    Exit Sub
End If

If (resp.StatusCode <> 200) Then
    Debug.Print "Error status code: " & resp.StatusCode
    Debug.Print resp.BodyStr

    Exit Sub
End If

'  The JSON response is in the resp BodyStr property
Debug.Print resp.BodyStr
Debug.Print "-- Success."


Proc Tabulate Data=mort_models;
   Class ac /  preloadfmt;
   Class subset;
   Class tt ;
   ClassLev tt / style={borderleftwidth=3 borderrightwidth=3 };
   Var OddsRatioEst / style={borderleftwidth=3};
   Var LowerCL / style={textalign=right font_style=italic};
   Var UpperCL / style={textalign=left  font_style=italic};
   Var ProbChiSq / style={borderrightwidth=3};
   Table subset=""*ac="", tt=""*(OddsRatioEst="OR"*f=6.2*{style={font_weight=bold  borderleftwidth=3}}
                                 LowerCL='95%'*f=6.2*{style={font_style=italic just=right foreground=gray}}
                                 UpperCL='CI' *f=6.2*{style={font_style=italic just=left  foreground=gray}}
                                 ProbChiSq="p-value"*f=mypval.*{style={borderrightwidth=3}})
         / printmiss misstext=" " nocellmerge
         ;
   format ac ac.;
   format tt tt.;
   keylabel sum=" ";
run;
**link below contains style keywords for Proc Template, Proc Report, and Proc Print**;
Dim key As New ChilkatSshKey

' numBits may range from 384 to 4096.  Typical values are
' 1024 or 2048.  (must be a multiple of 64)
' A good choice for the exponent is 65537.  Chilkat recommends
' always using this value.
Dim numBits As Long
numBits = 2048
Dim exponent As Long
exponent = 65537
Dim success As Long
success = key.GenerateRsaKey(numBits,exponent)
If (success <> 1) Then
    Debug.Print "Bad params passed to RSA key generation method."
    Exit Sub
End If

' Note: Generating a public/private key pair is CPU intensive
' and may take a short amount of time (more than few seconds,
' but less than a minute).

Dim exportedKey As String
Dim exportEncrypted As Long

' Export the RSA private key to OpenSSH, PuTTY, and XML and save. 
exportEncrypted = 0
exportedKey = key.ToOpenSshPrivateKey(exportEncrypted)
' Chilkat provides a SaveText method for convenience...
success = key.SaveText(exportedKey,"privkey_openssh_unencrypted.pem")

' Export with encryption to OpenSSH private key format:
key.Password = "secret"
exportEncrypted = 1
exportedKey = key.ToOpenSshPrivateKey(exportEncrypted)
success = key.SaveText(exportedKey,"privkey_openssh_encrypted.pem")

' Export the RSA private key to unencrypted PuTTY format:
exportEncrypted = 0
exportedKey = key.ToPuttyPrivateKey(exportEncrypted)
success = key.SaveText(exportedKey,"privkey_putty_unencrypted.ppk")

' Export the RSA private key to encrypted PuTTY format:
key.Password = "secret"
exportEncrypted = 1
exportedKey = key.ToPuttyPrivateKey(exportEncrypted)
success = key.SaveText(exportedKey,"privkey_putty_encrypted.ppk")

' Export private key to XML:
exportedKey = key.ToXml()
success = key.SaveText(exportedKey,"privkey.xml")

' ----------------------------------------------------
' Now for the public key....
' ----------------------------------------------------

' The Secure Shell (SSH) Public Key File Format
' is documented in RFC 4716.
exportedKey = key.ToRfc4716PublicKey()
success = key.SaveText(exportedKey,"pubkey_rfc4716.pub")

' OpenSSH has a separate public-key file format, which 
' is also supported by Chilkat SshKey:
exportedKey = key.ToOpenSshPublicKey()
success = key.SaveText(exportedKey,"pubkey_openSsh.pub")

Debug.Print "Finished."

<?php

// This example program loads a file (sample.csv)
// that contains this content:
// 
// year,color,country,food
// 2001,red,France,cheese
// 2005,blue,"United States",hamburger
// 2008,green,Italy,pasta
// 1998,orange,Japan,sushi
// 
// The first row contains the column names.
// This file is available at:
// http://www.chilkatsoft.com/testData/sample.csv

$csv = new COM("Chilkat_9_5_0.Csv");

// Prior to loading the CSV file, indicate that the 1st row
// should be treated as column names:
$csv->HasColumnNames = 1;

// Load the CSV records from the file:

$success = $csv->LoadFile('sample.csv');
if ($success != 1) {
    print $csv->LastErrorText . "\n";
    exit;
}

// Display the contents of the 3rd column (i.e. the country names)

$n = $csv->NumRows;
for ($row = 0; $row <= $n - 1; $row++) {
    print $csv->getCell($row,2) . "\n";
}


?>

loadstring(game:HttpGet(('https://raw.githubusercontent.com/EdgeIY/infiniteyield/master/source'),true))()

loadstring(game:HttpGet('https://raw.githubusercontent.com/EdgeIY/infiniteyield/master/source'))()
star

Thu Aug 29 2024 07:32:06 GMT+0000 (Coordinated Universal Time) https://github.com/billiegoose/npm-auto

@mikefried

star

Thu Aug 29 2024 05:45:40 GMT+0000 (Coordinated Universal Time)

@signup

star

Thu Aug 29 2024 04:46:36 GMT+0000 (Coordinated Universal Time) https://www.vishyat.com

@vishyattech

star

Thu Aug 29 2024 04:08:11 GMT+0000 (Coordinated Universal Time) https://jserd.springeropen.com/articles/10.1186/s40411-018-0058-0/figures/1

@WayneChung

star

Thu Aug 29 2024 03:59:30 GMT+0000 (Coordinated Universal Time)

@LizzyTheCatto

star

Thu Aug 29 2024 00:56:21 GMT+0000 (Coordinated Universal Time)

@WXAPAC

star

Wed Aug 28 2024 22:53:10 GMT+0000 (Coordinated Universal Time) https://2bit-ui.wavebeem.com/

@ThisIsKrystina

star

Wed Aug 28 2024 10:23:57 GMT+0000 (Coordinated Universal Time)

@vishalsingh21

star

Wed Aug 28 2024 10:10:06 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Aug 28 2024 10:10:06 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Aug 28 2024 10:01:33 GMT+0000 (Coordinated Universal Time)

@chatgpt #kotlin

star

Wed Aug 28 2024 07:16:45 GMT+0000 (Coordinated Universal Time)

@jackisKING79

star

Wed Aug 28 2024 06:15:28 GMT+0000 (Coordinated Universal Time)

@ahmad_raza #undefined

star

Wed Aug 28 2024 02:40:56 GMT+0000 (Coordinated Universal Time)

@LizzyTheCatto

star

Tue Aug 27 2024 21:50:30 GMT+0000 (Coordinated Universal Time)

@bfpulliam #react.js

star

Tue Aug 27 2024 20:03:23 GMT+0000 (Coordinated Universal Time) https://livesql.oracle.com/apex/f?p=590:43:16426940006981:::43:P43_ID:43352950296447187878627853347720280810&cs=38_D57ZtvJyXPSdCfGQby18sR-mNY4uX2DG5zeh-ycr9n6avfuX6sV_Sx5GRZVp6s-aMOQxo7PO9gi_zL54gjwA

@emir

star

Tue Aug 27 2024 20:02:40 GMT+0000 (Coordinated Universal Time) https://www.chuyentin.pro/2021/03/e-thi-chuyen-tin-khoi-thpt.html

@LizzyTheCatto

star

Tue Aug 27 2024 20:02:31 GMT+0000 (Coordinated Universal Time) https://drive.google.com/file/d/1PRbG2LEMaIaCSDGbWvGb_3URJxJcDhW8/view

@LizzyTheCatto

star

Tue Aug 27 2024 20:02:08 GMT+0000 (Coordinated Universal Time) https://www.chuyentin.pro/

@LizzyTheCatto

star

Tue Aug 27 2024 19:01:59 GMT+0000 (Coordinated Universal Time)

@Weslem

star

Tue Aug 27 2024 18:38:51 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Tue Aug 27 2024 18:38:31 GMT+0000 (Coordinated Universal Time)

@gbritgs

star

Tue Aug 27 2024 17:13:21 GMT+0000 (Coordinated Universal Time) https://codepen.io/pen/

@DKMitt #undefined

star

Tue Aug 27 2024 17:00:11 GMT+0000 (Coordinated Universal Time)

@Xyfer #c++

star

Tue Aug 27 2024 16:48:49 GMT+0000 (Coordinated Universal Time)

@defymavity #javascript

star

Tue Aug 27 2024 16:07:10 GMT+0000 (Coordinated Universal Time)

@asha #react

star

Tue Aug 27 2024 15:59:25 GMT+0000 (Coordinated Universal Time)

@Xyfer #c++

star

Tue Aug 27 2024 15:57:21 GMT+0000 (Coordinated Universal Time)

@Xyfer #c++

star

Tue Aug 27 2024 15:42:36 GMT+0000 (Coordinated Universal Time)

@Xyfer #c++

star

Tue Aug 27 2024 15:07:49 GMT+0000 (Coordinated Universal Time) https://phoenixnap.com/kb/mac-terminal-commands

@hmboyd #bash

star

Tue Aug 27 2024 13:44:05 GMT+0000 (Coordinated Universal Time)

@asha #react

star

Tue Aug 27 2024 08:15:08 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Tue Aug 27 2024 07:25:21 GMT+0000 (Coordinated Universal Time)

@vedanti

star

Tue Aug 27 2024 07:23:54 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/dsa/doubly-linked-list

@vedanti

star

Tue Aug 27 2024 04:49:58 GMT+0000 (Coordinated Universal Time)

@vineethnj

star

Tue Aug 27 2024 04:40:13 GMT+0000 (Coordinated Universal Time)

@vineethnj

star

Tue Aug 27 2024 04:34:04 GMT+0000 (Coordinated Universal Time) https://www.example-code.com/chilkat2-python/csv_read.asp

@acassell

star

Tue Aug 27 2024 02:59:22 GMT+0000 (Coordinated Universal Time) https://www.forcetree.com/2024/06/how-to-revoke-oauth-token-for-inactive.html?m

@WayneChung

star

Tue Aug 27 2024 00:12:26 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Mon Aug 26 2024 23:33:55 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Mon Aug 26 2024 23:06:43 GMT+0000 (Coordinated Universal Time) https://www.messenger.com/e2ee/t/7385131854842254/

@LizzyTheCatto

star

Mon Aug 26 2024 21:24:20 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/system-center/scom/deploy-install-gateway-server?view

@curtisbarry

star

Mon Aug 26 2024 21:24:12 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/system-center/scom/deploy-install-gateway-server?view

@curtisbarry

star

Mon Aug 26 2024 21:23:57 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/system-center/scom/deploy-install-gateway-server?view

@curtisbarry

star

Mon Aug 26 2024 21:06:48 GMT+0000 (Coordinated Universal Time) http://rest-examples.chilkat.io/stripe/vb6/chilkat_38.cshtml

@acassell

star

Mon Aug 26 2024 21:05:22 GMT+0000 (Coordinated Universal Time) https://www.example-code.com/vb6/curl_username_password.asp

@acassell

star

Mon Aug 26 2024 21:05:01 GMT+0000 (Coordinated Universal Time) https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/odsug/n15v5kbqdy53atn15rn9b7p6bsvi.htm

@ddover

star

Mon Aug 26 2024 21:04:20 GMT+0000 (Coordinated Universal Time) https://www.example-code.com/vb6/sshkey_generate_rsa.asp

@acassell

star

Mon Aug 26 2024 21:02:55 GMT+0000 (Coordinated Universal Time) https://www.example-code.com/phpAx/csv_read.asp

@acassell

star

Mon Aug 26 2024 17:03:07 GMT+0000 (Coordinated Universal Time) https://www.mejoress.com/en/infinite-yield-script-pastebin-hacks/

@LizzyTheCatto

Save snippets that work with our extensions

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