Snippets Collections
import React, { useEffect, useRef, useState } from 'react';
import { fetchExpenses } from "../../../../APIs/ExpensesApi";

const Expenses = () => {
  const [expensesData, setexpensesData] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(0);
  const elements = useRef(null);

  function onIntersection(entries) {
    const firstEntry = entries[0];
    if (firstEntry.isIntersecting && hasMore) {
      fetchMoreItems();
    }
  }

  useEffect(() => {
    const observer = new IntersectionObserver(onIntersection);
    if (elements.current) {
      observer.observe(elements.current);
    }
    return () => {
      observer.disconnect();
    };
  }, [expensesData, hasMore]);

  async function fetchMoreItems() {
    try {
      const response = await fetchExpenses();
      const data = await response.results;
      if (data.length === 0) {
        setHasMore(false);
      } else {
        setexpensesData(prevProducts => [...prevProducts, ...data]);
        setPage(prevPage => prevPage + 1);
      }
    } catch (error) {
      console.error('Error fetching more items:', error);
    }
  }

  return (
    <div>
      {expensesData.map(item => (
        <div key={item.id}>
          <p>{item.id}</p>
        </div>
      ))}

      {hasMore && (
        <div ref={elements}>
          Load More
        </div>
      )}
    </div>
  );
};

export default Expenses;
      const allGroups = await contactService.getAllGroups(req);
      const allAccounts = await contactService.getAllAccounts(req);
function About() {
  return (
    <section className="px-6 lg:px-10 py-6  flex flex-col gap-6 lg:gap-10  ">
      <h2 className="font-bold text-xl max-md:text-xl">About this project</h2>
      <div className="flex flex-col gap-6 lg:gap-10 text-dark-gray text-lg max-md:text-sm">
        <p>
          The Mastercraft Bamboo Monitor Riser is a sturdy and stylish platform
          that elevates your screen to a more comfortable viewing height.
          Placing your monitor at eye level has the potential to improve your
          posture and make you more comfortable while at work, helping you stay
          focused on the task at hand.
        </p>
        <p>
          Featuring artisan craftsmanship, the simplicity of design creates
          extra desk space below your computer to allow notepads, pens, and USB
          sticks to be stored under the stand.
        </p>
      </div>
    </section>
  );
}

export default About;
import React from "react";
import { backers } from "../constants";

function Backed() {
  return (
    <>
      <section className="flex flex-col lg:flex-row items-center lg:px-8 lg:items-start justify-center lg:justify-start gap-4 lg:gap-12 mt-10">
        {backers.map((item, index) => (
          <div
            key={index}
            className={`flex flex-col gap-2 lg:border-r-2 lg:pr-12 items-center lg:items-start  
            ${!item.line && "border-none"}
            ${index == 1 && "lg:pr-20"}
            `}
          >
            <h2 className="font-bold text-3xl">{item.value}</h2>
            <p className="text-dark-gray">{item.label}</p>
            <hr
              className={` border-1 text-black w-[100px] mt-5 lg:hidden ${
                !item.line && "hidden"
              }`}
            />
          </div>
        ))}
      </section>
      <div className="flex justify-center lg:px-8 lg:pb-8">
        <div className="relative z-10 mt-10 w-10/12 lg:w-full flex  lg:justify-start">
          <div className="absolute w-full bg-gray-200 py-1.5 rounded-full" />
          <div className="absolute w-4/5 bg-moderate-cyan py-1.5 rounded-full" />
        </div>
      </div>
    </>
  );
}

export default Backed;
import React from "react";
import { feature } from "../constants";
import Button from "../components/Button";

function Features() {
  return (
    <section className="max-md:px-2 lg:mt-10 py-4">
      <div className="flex flex-col gap-8 lg:px-10 px-2 md:px-8">
        {feature.map((item) => (
          <div
            key={item.title}
            className={`border-solid border-2 border-gray-300 p-6 
            flex flex-col gap-6 rounded-xl 
            ${item.disabled ? "opacity-50" : "opacity-100"}
            `}
          >
            <div className="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-2">
              <h2 className="text-lg font-bold">{item.title}</h2>
              <p className="text-moderate-cyan ">{item.subtitle}</p>
            </div>
            <p className="text-dark-gray max-md:text-sm">{item.description}</p>
            <div className="flex flex-col gap-4 lg:flex-row lg:justify-between">
              <p className="flex flex-row items-center gap-2 text-dark-gray ">
                <span className="text-3xl font-bold text-black">
                  {item.stock}
                </span>
                left
              </p>
              <div>
                {item.disabled ? (
                  <Button
                    label="Out of Stock"
                    backgroundColor={"!bg-dark-gray cursor-default"}
                    textColor={"text-white"}
                  />
                ) : (
                  <Button label="Select Reward" />
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

export default Features;
import { useEffect, useState } from "react";
import { heroMobile, heroDesktop } from "../assets/images";

function Hero() {
  const [isMobile, setIsMobile] = useState(false);

  //check mobile or not
  const checkMobile = () => {
    if (window.innerWidth <= 768) {
      setIsMobile(true);
    } else {
      setIsMobile(false);
    }
  };
  useEffect(() => {
    checkMobile();
    window.addEventListener("resize", checkMobile);

    return () => {
      window.removeEventListener("resize", checkMobile);
    };
  }, []);

  return (
    <section className={`md:w-full relative`}>
      <img
        src={isMobile ? heroMobile : heroDesktop}
        alt={isMobile ? "hero mobile" : "hero desktop"}
        className="object-cover w-full contrast-[85%]"
      />
    </section>
  );
}

export default Hero;
import Button from "../components/Button";
import { backers } from "../constants";
import { logoMastercraft } from "../assets/images";
import { IconBookmark } from "../assets/images/icon-bookmark";
import { useState } from "react";
function Product({ openModal }) {
  const [bookmark, setBookmark] = useState(true);

  return (
    <section className="flex flex-col items-center gap-6 xl:gap-10 relative -translate-y-12">
      <img src={logoMastercraft} alt="" width={56} className="" />
      <div className="flex flex-col gap-4 items-center">
        <h1 className="font-bold text-xl xl:text-2xl max-w-[250px] lg:max-w-full text-center">
          Mastercraft Bamboo Monitor Riser
        </h1>
        <p className="max-w-[300px] lg:max-w-full text-center text-base  text-dark-gray ">
          A beautiful & handcrafted monitor stand to reduce neck and eye strain.
        </p>
      </div>
      <div className="flex gap-2 items-center lg:justify-between justify-center w-full">
        <Button label={"Back this project"} onClick={openModal} />
        <div className="flex gap-4 items-center lg:bg-slate-100 lg:rounded-full lg:pr-8">
          <div
            onClick={() => {
              setBookmark(!bookmark);
            }}
          >
            <IconBookmark
              bgFill={bookmark ? "fill-black" : "fill-dark-cyan"}
              iconFill={bookmark ? "fill-gray-400" : "fill-white"}
              className={""}
            />
          </div>
          <p
            className={`
            ${
              bookmark ? "text-dark-gray" : "text-dark-cyan"
            } text-lg max-lg:hidden lg:block font-bold
             
            `}
          >
            {bookmark ? "Bookmark" : "Bookmarked"}
          </p>
        </div>
      </div>
    </section>
  );
}

export default Product;
import React, { useState } from "react";
import { navlink } from "../constants";
import { ic_close_menu, ic_humburger, logo } from "../assets/images";

const Nav = () => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

  const handleToggleMobileMenu = () => {
    setIsMobileMenuOpen(!isMobileMenuOpen);
  };

  return (
    <header className="p-8 lg:pl-40 lg:pr-[9rem] lg:py-10 absolute z-10 w-full max-container">
      <nav className="flex justify-between items-center max-container">
        <a href="/">
          <img
            src={logo}
            alt="logo"
            className={`${
              isMobileMenuOpen ? "relative z-50 w-[130px]" : "w-[100px] "
            }`}
          />
        </a>
        <ul className="flex-1 flex justify-end items-center gap-6 max-lg:hidden">
          {navlink.map((item) => (
            <li key={item.label}>
              <a href={item.href} className="text-white text-lg">
                {item.label}
              </a>
            </li>
          ))}
        </ul>
        <div className="hidden max-lg:block">
          {isMobileMenuOpen ? (
            <img
              src={ic_close_menu}
              alt="close"
              width={16}
              onClick={handleToggleMobileMenu}
              className="relative z-50"
            />
          ) : (
            <img
              src={ic_humburger}
              alt="hamburger"
              width={16}
              onClick={handleToggleMobileMenu}
            />
          )}
        </div>
      </nav>
      {isMobileMenuOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-40 z-20"
          onClick={handleToggleMobileMenu}
        >
          <div className="flex items-center justify-center">
            <ul
              id="mobileMenu"
              className=" mt-20 w-[80%] bg-white px-4 py-4 flex flex-col gap-6 rounded-lg shadow-md"
            >
              {navlink.map((item) => (
                <li key={item.label}>
                  <a
                    href={item.href}
                    className="text-black text-sm font-medium"
                  >
                    {item.label}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        </div>
      )}
    </header>
  );
};

export default Nav;
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
import React from "react";
import { ic_check } from "../assets/images";
import Button from "./Button";

function DialogBox({ isOpen, onClose }) {
  if (!isOpen) return null;
  return (
    <section className="modal-section">
      <div className="modal-box  translate-y-1.5 lg:w-[30%]">
        <div className="flex flex-col items-center gap-6">
          <img src={ic_check} alt="Icon check" width={80} />
          <h1 className="font-bold text-xl">Thanks for your support!</h1>
          <p className="text-dark-gray text-center">
            Your pledge brings us one step closer to sharing Mastercraft Bamboo
            Monitor Riser worldwide. You will get an email once our campaign is
            completed.
          </p>
          <Button 
            label={"Got it!"}
            onClick={onClose}
        />
        </div>
      </div>
    </section>
  );
}

export default DialogBox;
import React, { useEffect, useState } from "react";
import { project } from "../constants";
import Button from "../components/Button";
import IconCloseModal from "../assets/images/icon-close-modal";

function Modal({ isOpen, onClose, openDialog }) {
  const [selectedItem, setSelectedItem] = useState("");
  const [isMobile, setIsMobile] = useState(false);

  //check mobile or not
  const checkMobile = () => {
    if (window.innerWidth <= 768) {
      setIsMobile(true);
    } else {
      setIsMobile(false);
    }
  };
  useEffect(() => {
    checkMobile();
    window.addEventListener("resize", checkMobile);

    return () => {
      window.removeEventListener("resize", checkMobile);
    };
  }, []);

  const handleRadioChange = (title) => {
    setSelectedItem(title);
  };
  if (!isOpen) return null;
  return (
    <section className="modal-section">
      <div className="modal-box">
        <div className="flex flex-row items-center justify-between">
          <h1 className="text-lg font-bold">Back this project</h1>
          <div
            className="cursor-pointer"
            onClick={() => {
              onClose();
              setSelectedItem("");
            }}
          >
            <IconCloseModal className=" fill-dark-gray hover:fill-black" />
          </div>
        </div>
        <p className="text-base text-dark-gray">
          Want to support us in bringing Mastercraft Bamboo Monitor Riser out in
          the world?
        </p>

        {project.map((item, index) => (
          <div
            key={index}
            className={`flex flex-col p-4 lg:p-8 gap-8 border-2 border-solid rounded-xl 
                ${item.disabled ? "opacity-50" : "opacity-100"}
                ${
                  selectedItem === item.title
                    ? "border-moderate-cyan"
                    : "border-gray-100"
                }
            `}
          >
            <div className="flex flex-row gap-4 items-center ">
              <input
                type="radio"
                name="project"
                id={`project-${index}`}
                className={`
                  bg-transparent  border border-gray-200 rounded-full 
                
                `}
                checked={selectedItem === item.title}
                onChange={() => handleRadioChange(item.title)}
              />
              <div className="flex flex-col lg:flex-row lg:justify-between  lg:gap-4 lg:w-full">
                <div className="flex flex-col lg:flex-row lg:gap-4">
                  <label
                    htmlFor={`project-${index}`}
                    className="cursor-pointer text-lg font-bold .form-control hover:text-dark-cyan"
                  >
                    {item.title}
                  </label>

                  {item.subtitle && (
                    <p className="text-moderate-cyan font-medium lg:text-lg">
                      {item.subtitle}
                    </p>
                  )}
                </div>

                <div>
                  {!isMobile && item.stock >= 0 && (
                    <p className="flex flex-row items-center gap-2 text-dark-gray">
                      <span className="text-xl font-bold text-black">
                        {item.stock}
                      </span>
                      left
                    </p>
                  )}
                </div>
              </div>
            </div>

            <div className="lg:pl-8 flex flex-col gap-8">
              <p className="text-dark-gray font-medium">{item.description}</p>
              {isMobile && item.stock >= 0 && (
                <p className="flex flex-row items-center gap-2 text-dark-gray">
                  <span className="text-xl font-bold text-black">
                    {item.stock}
                  </span>
                  left
                </p>
              )}
            </div>

            {selectedItem === item.title &&
              item.stock != 0 && (
                <div className="flex flex-col lg:flex-row lg:justify-between items-center gap-4 justify-center border-t-2 py-4">
                  <h3 className="text-dark-gray ">Enter your pledge</h3>
                  <div className="flex flex-row gap-6 max-sm:gap-2 items-center justify-center">
                    <Button
                      label={item.button1}
                      borderColor={
                        "border-gray-300 hover:border-moderate-cyan  border-2"
                      }
                      textColor={"text-black"}
                      optionalIcon={"$"}
                      backgroundColor={"bg-white"}
                    />
                    <Button label={item.button2} onClick={openDialog} />
                  </div>
                </div>
              )}
          </div>
        ))}
      </div>
    </section>
  );
}

export default Modal;
import { useState } from "react";
import Modal from "./components/Modal";
import About from "./sections/About";
import Features from "./sections/Features";
import Hero from "./sections/Hero";
import Nav from "./sections/Nav";
import Product from "./sections/Product";
import DialogBox from "./components/DialogBox";
import Backed from "./sections/Backed";

function App() {
  const [isModalOpen, setModalOpen] = useState(false);
  const [isDialogOpen, setDialogOpen] = useState(false);

  const handleOpenModal = () => {
    setModalOpen(true);
    document.body.classList.add("modal-open");
  };
  const handleCloseModal = () => {
    setModalOpen(false);
    document.body.classList.remove("modal-open");
  };
  const handleOpenDialog = () => {
    setModalOpen(false);
    setDialogOpen(true);
    document.body.classList.add("modal-open");
  };
  const handleCloseDialog = () => {
    setDialogOpen(false);
    document.body.classList.remove("modal-open");
  };
  return (
    <>
      <main className={` bg-gray-50 max-container`}>
        <Modal
          isOpen={isModalOpen}
          onClose={handleCloseModal}
          openDialog={handleOpenDialog}
        />
        <DialogBox isOpen={isDialogOpen} onClose={handleCloseDialog} />
        <Nav />
        <Hero />

        <div className="flex flex-col gap-6 relative -translate-y-[92px]">
          <div className=" bg-white w-[90%] lg:w-1/2 lg:px-8 px-2  max-container rounded-lg pt-4  ">
            <Product openModal={handleOpenModal} />
          </div>
          <div className=" bg-white w-[90%] lg:w-1/2 max-container rounded-lg pb-10 ">
            <Backed />
          </div>

          <div className=" bg-white w-[90%] lg:w-1/2 m-auto max-container rounded-lg py-4 ">
            <About />
            <Features openDialog={handleOpenDialog} />
          </div>
        </div>
      </main>
    </>
  );
}

export default App;
#include "SSD1306Wire.h"
#include "ESP8266WiFi.h"
// Initialize the OLED display using Arduino Wire:
SSD1306Wire display(0x3c, SCL, SDA); // reversed!

void setup() {
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  
  // Initialising the UI will init the display too.
  display.init();

  //display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.drawString(0, 0, "Starting.." );
  display.display();
}


void loop() {
  // clear the display
  display.clear();
  int height = 10;
  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  if (n == 0) {
    display.drawString(0, 0, "no networks found");
  } else {
    for (int i = 0; i < n; ++i) {
      int y = i * height;
      String ssid = WiFi.SSID(i);
      String rssi = String(WiFi.RSSI(i));
      String encryption = "Unknown";
      switch(WiFi.encryptionType(i)) {
        case ENC_TYPE_WEP:
          encryption = "WEP";
          break;
        case ENC_TYPE_TKIP:
          encryption = "WPA";
          break;
        case ENC_TYPE_CCMP:
          encryption = "WPA2";
          break;
        case ENC_TYPE_NONE:
          encryption = "Open";
          break;
        case ENC_TYPE_AUTO:
          encryption = "Auto";
          break;
        default:
          encryption = "Unknown";
          break;
      }
      String line = ssid + ": " + rssi + " " + encryption;
      display.drawString(0, y, line);
      display.display();
      delay(10);
    }
  }

  // Wait a bit before scanning again
  delay(5000);
}

const tweetId = location.pathname.match(/status\/([0-9]+)/)[1];
const imgElements = document.querySelectorAll(`a[href*="${tweetId}"] img`);
let imgArray = new Array();
for (const imgElement of imgElements) {
  let imgSrc = imgElement
    .getAttribute("src")
    .replace(/\?format=/, ".")
    .replace(/&.+/, "");
  imgArray.push(imgSrc);
}
import math
import os
import random
import re
import sys


# Complete the 'diagonalDifference' function below.

# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.


def diagonalDifference(arr):
    diagonal1_sum = 0
    diagonal2_sum = 0
    
    for i in range(len(arr)):
        diagonal1_sum += arr[i][i]
        diagonal2_sum += arr[i][len(arr)-(i+1)]
        
    absolute_sum = abs(diagonal1_sum - diagonal2_sum)
    
    return absolute_sum

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    arr = []

    for _ in range(n):
        arr.append(list(map(int, input().rstrip().split())))

    result = diagonalDifference(arr)

    fptr.write(str(result) + '\n')

    fptr.close()
package pl.pp;

import java.util.Scanner;

public class AgeInSeconds {
        public static void main(String[] args) {
                // Create a Scanner object to read input
                Scanner scanner = new Scanner(System.in);

                // Ask the user for their age in years
                System.out.print("Enter your age in years: ");
                int ageInYears = scanner.nextInt();

                // Close the scanner to prevent resource leak
                scanner.close();

                // Calculate the age in seconds
                long ageInSeconds = (long) ageInYears * 365 * 24 * 60 * 60;

                // Display the age in seconds with proper description
                System.out.println("My age in seconds: " + ageInSeconds);
        }
}
#include <iostream>
#include <algorithm>
using namespace std;
long long w, h, s, g, x1, y1, x2, y2, sum1, sum2, y, tot, n;
int main()
{
    cin>>w>>h>>s>>g>>x1>>y1>>x2>>y2;
    y=(y2-y1)*(g+1);
    s=min(s, w-s);
    if(s<x1)
    {
        sum2=x2-x1;
    }
    else if(x2>s)
    {
        sum1=2*(s-x1);
        sum2=x2-s;
    }
    else
    {
        sum1=2*(x2-x1);
    }
    tot=w*h-y*(sum1+sum2);
    cout<<tot;
}
export const navlink = [
  { href: "#about", label: "About" },
  { href: "#discover", label: "Discover" },
  { href: "#getStarted", label: "Get Started" },
];

export const backers = [
  { value: "$89,914", label: "of $100,000 backed", line:"true" },
  { value: "5,007", label: "total backers", line:"true" },
  { value: "56", label: "days left", line:false },
];

export const feature = [
  {
    title: "Bamboo Stand",
    subtitle: "Pledge $25 or more",
    description:
      "You get a Black Special Edition computer stand and a personal thank you. You’ll be added to our Backer member list. Shipping is included.",
    stock: 101,
    button: "Select Reward",
    disabled: false,
  },
  {
    title: "Black Edition Stand",
    subtitle: "Pledge $75 or more",
    description:
      "You get an ergonomic stand made of natural bamboo. You've helped us launch our promotional campaign, and you’ll be added to a special Backer member list.",
    stock: 64,
    button: "Select Reward",
    disabled: false,
  },
  {
    title: "Mahogany Special Edition",
    subtitle: "Pledge $200 or more",
    description:
      "You get two Special Edition Mahogany stands, a Backer T-Shirt, and a personal thank you. You’ll be added to our Backer member list. Shipping is included.",
    stock: 0,
    button: "Out of Stock",
    disabled: true,
  },
];

export const project = [
  {
    title: "Pledge with no reward",
    subtitle: "",
    description:
      "Choose to support us without a reward if you simply believe in our project. As a backer, you will be signed up to receive product updates via email.",

    selectedTitle: "",
    button1: 0,
    button2: "Continue",
    disabled: false,
  },
  {
    title: "Bamboo Stand",
    subtitle: "Pledge $25 or more",
    description:
      "You get an ergonomic stand made of natural bamboo. You've helped us launch our promotional campaign, and you’ll be added to a special Backer member list.",
    stock: 101,

    selectedTitle: "Enter your pledge",
    button1: 25,
    button2: "Continue",
    disabled: false,
  },
  {
    title: "Black Edition Stand",
    subtitle: "Pledge $75 or more",
    description:
      "You get a Black Special Edition computer stand and a personal thank you. You’ll be added to our Backer member list. Shipping is included.",
    stock: 64,

    selectedTitle: "Enter your pledge",
    button1: 75,
    button2: "Continue",
    disabled: false,
  },
  {
    title: "Mahogany Special Edition",
    subtitle: "Pledge $200 or more",
    description:
      "You get two Special Edition Mahogany stands, a Backer T-Shirt, and a personal thank you. You’ll be added to our Backer member list. Shipping is included.",
    stock: 0,

    selectedTitle: "Enter your pledge",
    button1: 200,
    button2: "Continue",
    disabled: true,
  },
];
import React from "react";

function Button({ 
  optionalIcon,
  label,
  disabled, 
  onClick,
  backgroundColor,
  borderColor,
  textColor,
 }) {
  return (
    <button
    onClick={onClick}
    className={`
    ${optionalIcon ? `${backgroundColor} hover:bg-white` : "bg-moderate-cyan hover:bg-dark-cyan" }
    ${
      backgroundColor
        ? `${backgroundColor} ${textColor} ${borderColor} ${optionalIcon}`
        : "bg-moderate-cyan hover:bg-dark-cyan text-white"
    }
    py-4 px-12 max-sm:py-4 max-sm:px-8
    font-bold text-base max-sm:text-sm rounded-full duration-300`}
    >
      {optionalIcon && (
        <span className="text-dark-gray">{optionalIcon} </span>
      )}
      {label}
    </button>
  );
}

export default Button;
# Basics
import os
import pandas as pd
import matplotlib.pyplot as plt
from dotenv import load_dotenv

# LangChain Training
# LLM
from langchain.llms import OpenAI

# Document Loader
from langchain.document_loaders import PyPDFLoader 

# Splitter
from langchain.text_splitter import RecursiveCharacterTextSplitter 

# Tokenizer
from transformers import GPT2TokenizerFast  

# Embedding
from langchain.embeddings import OpenAIEmbeddings 

# Vector DataBase
from langchain.vectorstores import FAISS, Pinecone # for the vector database part -- FAISS is local and temporal, Pinecone is cloud-based and permanent. 

# Chains
#from langchain.chains.question_answering import load_qa_chain
#from langchain.chains import ConversationalRetrievalChain
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
from transformers import AutoModelForCausalLM, AutoTokenizer
import time
import torch

class Chatbot:
    def __init__(self, model_name):
        self.tokenizer = AutoTokenizer.from_pretrained(model_name, padding_side='left')
        self.model = AutoModelForCausalLM.from_pretrained(model_name, load_in_4bit=True, torch_dtype=torch.bfloat16)
        if self.tokenizer.pad_token_id is None:
            self.tokenizer.pad_token_id = self.tokenizer.eos_token_id

    def get_response(self, prompt):
        inputs = self.tokenizer.encode_plus(prompt, return_tensors="pt", padding='max_length', max_length=100)
        if next(self.model.parameters()).is_cuda:
            inputs = {name: tensor.to('cuda') for name, tensor in inputs.items()}
        start_time = time.time()
        tokens = self.model.generate(input_ids=inputs['input_ids'], 
                                    attention_mask=inputs['attention_mask'],
                                    pad_token_id=self.tokenizer.pad_token_id,
                                    max_new_tokens=400)
        end_time = time.time()
        output_tokens = tokens[0][inputs['input_ids'].shape[-1]:]
        output = self.tokenizer.decode(output_tokens, skip_special_tokens=True)
        time_taken = end_time - start_time
        return output, time_taken

def main():
    chatbot = Chatbot("LoupGarou/Starcoderplus-Guanaco-GPT4-15B-V1.0")
    while True:
        user_input = input("Enter your prompt: ")
        if user_input.lower() == 'quit':
            break
        output, time_taken = chatbot.get_response(user_input)
        print("\033[33m" + output + "\033[0m")
        print("Time taken to process: ", time_taken, "seconds")
    print("Exited the program.")

if __name__ == "__main__":
    main()
var links = document.links;
for (let i = 0, linksLength = links.length ; i < linksLength ; i++) {
  if (links[i].hostname !== window.location.hostname) {
    links[i].target = '_blank';
    links[i].rel = 'noreferrer noopener';
  }
}             
<script>
  let items = document.querySelector(".header__inline-menu").querySelectorAll("details");
  console.log(items)
  items.forEach(item => {
    item.addEventListener("mouseover", () => {
      item.setAttribute("open", true);
      item.querySelector("ul").addEventListener("mouseleave", () => {
        item.removeAttribute("open");
      });
    item.addEventListener("mouseleave", () => {
      item.removeAttribute("open");
    });
  });
  
  });
</script>                                   
javascript: (function () {
  const query = prompt("Search App Store", document.getSelection().toString());
  if (query) {
    window.open(
      `itms-apps://search.itunes.apple.com/WebObjects/MZSearch.woa/wa/search?media=software&term=${encodeURIComponent(query)}`,
    );
  }
})();
package pl.pp;

import java.util.Scanner;
public class mySecondApp {
    public static void main(String[] args) {

        //this is a line comment
        Scanner scanner = new Scanner(System.in);

            /*
             This is a block comment
             it can have multiple lines
             just like here
             */

        double x = 10; // creating a double type variable and assigning it a value of 10
        double y = 2;
        scanner = new Scanner(System.in);

        var result = x + y;
        System.out.println("x + y = " + result);

        result = x - y;
        System.out.println("x - y = " + result);

        result = x * y;
        System.out.println("x * y = " + result);

        result = x / y;
        System.out.println("x / y = " + result);

        result = x % y;
        System.out.println("x % y = " + result);

        System.out.println("Enter two numbers separated by the Enter key:");
        double first = scanner.nextDouble(); //reguest to enter a double value
        double second = scanner.nextDouble();

        System.out.println("x + y = " + (first + second));

        System.out.println("Please enter your name:");
        String forename = scanner.nextLine();
        System.out.println("Please enter your surname:");
        String surname = scanner.nextLine();

        scanner.close();
        System.out.println("Welcome " + forename + " " + surname);
    }
}
@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Выбирай что хочешь узнать', reply_markup=keyboard1)

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Привет. Вводи город или страну для того, чтобы узнать погоду')





weath = ['На улице пипец, лучше сиди дома','Ну, и куда ты намылился в такую погоду?''','Доставай валенки, мы идём гулять']
weath2 = ['На улице норм, можешь выходить и особо не утепляться','Прохладно, надевай что-нибудь от ветра','Полёт нормальный, косуха в самый раз']
weath3 = ['На улице очень жарко, можешь выходить в трусах','Жарево, выходи в футболке', 'Солненчо и душно, как в Египте']





@bot.message_handler(content_types=['text'])
def send_text(message):
    observation = owm_ru.weather_at_place(message.text)
    w = observation.get_weather()
    temp = w.get_temperature('celsius')["temp"]
    answer = ' В городе / стране ' + message.text + ' сейчас ' + w.get_detailed_status() + "\n"
    answer += 'Температура составляет ' + str(temp) + "\n-------------------------------------------\n"
    if temp < 10:
        answer +=random.choice(weath)
    elif message.text == 'Привет':
        bot.send_message(message.chat.id, 'Привет. Хочешь узнать погоду? Введи страну или город. ')
    elif temp < 20:
        answer+=random.choice(weath2)
    else:
        answer+=random.choice(weath3)
    bot.send_message(message.chat.id, answer)

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text == 'Привет':
        bot.send_message(message.chat.id, 'Привет. Хочешь узнать погоду? Введи страну или город. ')
    elif message.text == 'Пока':
        bot.send_message(message.chat.id, 'До скорого!')





keyboard1 = telebot.types.ReplyKeyboardMarkup()
keyboard1.row('Привет','Пока')
@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text == 'Привет':
        bot.send_message(message.chat.id, 'Привет. Хочешь узнать погоду? Введи страну или город. ')
    elif message.text == 'Пока':
        bot.send_message(message.chat.id, 'До скорого!')




bot.polling( none_stop = True )
#!venv/bin/python
import logging
from aiogram import Bot, Dispatcher, executor, types

# Объект бота
bot = Bot(token="12345678:AaBbCcDdEeFfGgHh")
# Диспетчер для бота
dp = Dispatcher(bot)
# Включаем логирование, чтобы не пропустить важные сообщения
logging.basicConfig(level=logging.INFO)


# Хэндлер на команду /test1
@dp.message_handler(commands="test1")
async def cmd_test1(message: types.Message):
    await message.reply("Test 1")


if __name__ == "__main__":
    # Запуск бота
    executor.start_polling(dp, skip_updates=True)
import math
import os
import random
import re
import sys

# Complete the 'timeConversion' function below.

# The function is expected to return a STRING.
# The function accepts STRING s as parameter.


def timeConversion(s):
    TS = s[-2:]
    if TS == "PM" and s[:2] != "12":
        s = str(12 + int(s[:2])) + s[2:]
    if TS == "AM" and s[:2] == "12":
        s = "00" + s[2:]
    return s[:-2]

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = timeConversion(s)

    fptr.write(result + '\n')

    fptr.close()
import math
import os
import random
import re
import sys

# Complete the 'miniMaxSum' function below.
# The function accepts INTEGER_ARRAY arr as parameter.

def miniMaxSum(arr):
    min_sum = sum(arr[1:])
    max_sum = sum(arr[1:])
    len_of_arr = len(arr)

    
    for i in range(len_of_arr):
        temp = 0
        for j in range(len_of_arr):
            if j==i:
                continue
            else:
                temp += arr[j]
        
        if temp < min_sum:
            min_sum = temp
        if temp > max_sum:
            max_sum = temp
            
    print(min_sum, max_sum)
            

if __name__ == '__main__':

    arr = list(map(int, input().rstrip().split()))

    miniMaxSum(arr)
char[] task = new char[]{'a', 'b', 'c', 'c', 'd', 'e'};
        Map<Character, Long> map = IntStream.range(0, task.length)
                .mapToObj(idx -> task[idx]).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
int minimumBoxes(int* apple, int appleSize, int* capacity, int capacitySize) {

    

}
import { useState } from "react";

function useGeolocation() {
  const [isLoading, setIsLoading] = useState(false);
  const [position, setPosition] = useState({});
  const [error, setError] = useState(null);

  function getPosition() {
    if (!navigator.geolocation)
      return setError("Your browser does not support geolocation");

    setIsLoading(true);
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        setPosition({
          lat: pos.coords.latitude,
          lng: pos.coords.longitude
        });
        setIsLoading(false);
      },
      (error) => {
        setError(error.message);
        setIsLoading(false);
      }
    );
  }

  return { isLoading, position, error, getPosition };
}

export default function App() {
  const {
    isLoading,
    position: { lat, lng },
    error,
    getPosition
  } = useGeolocation();

  const [countClicks, setCountClicks] = useState(0);

  function handleClick() {
    setCountClicks((count) => count + 1);
    getPosition();
  }

  return (
    <div>
      <button onClick={handleClick} disabled={isLoading}>
        Get my position
      </button>

      {isLoading && <p>Loading position...</p>}
      {error && <p>{error}</p>}
      {!isLoading && !error && lat && lng && (
        <p>
          Your GPS position:{" "}
          <a
            target="_blank"
            rel="noreferrer"
            href={`https://www.openstreetmap.org/#map=16/${lat}/${lng}`}
          >
            {lat}, {lng}
          </a>
        </p>
      )}

      <p>You requested position {countClicks} times</p>
    </div>
  );
}
#include <stdio.h>
int main (void) {
    double AmountOfCement;
    int iTotalCost, NumberOfBags;
    scanf ("%lf", &AmountOfCement);
    NumberOfBags = (int) (AmountOfCement/120 + 1);
    iTotalCost = NumberOfBags * 45;
    printf ("%d", iTotalCost);
    return 0;
}
Add Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package to the project

Add the following in Startup.cs/Program.cs:

services.AddControllersWithViews().AddRazorRuntimeCompilation();
List<Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
 
Integer[] arr = new Integer[al.size()];
arr = al.toArray(arr);
 
for (Integer x : arr)
   System.out.print(x + " ");
# import the module
import python_weather

import asyncio
import os

async def getweather():
  # declare the client. the measuring unit used defaults to the metric system (celcius, km/h, etc.)
  async with python_weather.Client(unit=python_weather.IMPERIAL) as client:
    # fetch a weather forecast from a city
    weather = await client.get('New York')
    
    # returns the current day's forecast temperature (int)
    print(weather.current.temperature)
    
    # get the weather forecast for a few days
    for forecast in weather.forecasts:
      print(forecast)
      
      # hourly forecasts
      for hourly in forecast.hourly:
        print(f' --> {hourly!r}')

if __name__ == '__main__':
  # see https://stackoverflow.com/questions/45600579/asyncio-event-loop-is-closed-when-getting-loop
  # for more details
  if os.name == 'nt':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  
  asyncio.run(getweather())
$ pip install python-weather
# import the module
import python_weather

import asyncio
import os

async def getweather():
  # declare the client. the measuring unit used defaults to the metric system (celcius, km/h, etc.)
  async with python_weather.Client(unit=python_weather.IMPERIAL) as client:
    # fetch a weather forecast from a city
    weather = await client.get('New York')
    
    # returns the current day's forecast temperature (int)
    print(weather.current.temperature)
    
    # get the weather forecast for a few days
    for forecast in weather.forecasts:
      print(forecast)
      
      # hourly forecasts
      for hourly in forecast.hourly:
        print(f' --> {hourly!r}')

if __name__ == '__main__':
  # see https://stackoverflow.com/questions/45600579/asyncio-event-loop-is-closed-when-getting-loop
  # for more details
  if os.name == 'nt':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  
  asyncio.run(getweather())
const genDTO = (className, id) => {
  var fields = [
    'package com.voltcash.integrations.opencp.common.dto; ',
    '\n',
    'import com.voltcash.integrations.common.dto.BaseJsonEntity; ',
    'import lombok.Data;',
     '\n',
    '@Data ',
    'public class '+ className +' extends BaseJsonEntity{ ' 
  ];
 var declarations = $('#' + id).parentNode.querySelectorAll('td:first-child strong').forEach(e => fields.push('private String ' + e.innerHTML + ';'));
  
  fields.push('}');
  
  console.log(fields.join('\n'));
}
star

Tue Mar 12 2024 06:57:44 GMT+0000 (Coordinated Universal Time)

@Raj0250

star

Tue Mar 12 2024 06:50:59 GMT+0000 (Coordinated Universal Time)

@ltam

star

Tue Mar 12 2024 06:49:46 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Tue Mar 12 2024 06:48:04 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Tue Mar 12 2024 06:46:48 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Tue Mar 12 2024 06:44:42 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Tue Mar 12 2024 06:40:33 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Tue Mar 12 2024 06:32:52 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Tue Mar 12 2024 06:30:51 GMT+0000 (Coordinated Universal Time)

@topthonder

star

Tue Mar 12 2024 06:25:23 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Tue Mar 12 2024 03:52:33 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Tue Mar 12 2024 03:38:03 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Tue Mar 12 2024 02:08:54 GMT+0000 (Coordinated Universal Time) https://blog.marxy.org/2019/06/arduino-esp8266-with-on-board-oled.html

@Raf12066

star

Tue Mar 12 2024 02:06:53 GMT+0000 (Coordinated Universal Time)

@agedofujpn #javascript

star

Tue Mar 12 2024 01:15:40 GMT+0000 (Coordinated Universal Time) https://spycit.notion.site/S2-IT-Notes-Web-Development-9db5e9b2ac2d4a32aa8660c0c6f0e0b6

@sadasadsas

star

Tue Mar 12 2024 00:54:21 GMT+0000 (Coordinated Universal Time) https://codeium.com/vscode_tutorial?extensionName

@tony5

star

Mon Mar 11 2024 22:16:05 GMT+0000 (Coordinated Universal Time) https://www.darkhackerworld.com/2020/06/best-hacking-tools-for-termux.html

@Saveallkids

star

Mon Mar 11 2024 18:23:47 GMT+0000 (Coordinated Universal Time) https://github.com/karthiksalapu/python_code

@karthiksalapu

star

Mon Mar 11 2024 18:10:14 GMT+0000 (Coordinated Universal Time)

@brhm_lifter

star

Mon Mar 11 2024 11:46:02 GMT+0000 (Coordinated Universal Time) https://www.acmicpc.net/submit/1117/74789328

@hajinjang0714

star

Mon Mar 11 2024 08:23:56 GMT+0000 (Coordinated Universal Time) https://bito.ai/resources/javascript-calculate-total-price-javascript-explained/

@vishpriya412

star

Mon Mar 11 2024 07:09:54 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Mon Mar 11 2024 06:52:41 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Mon Mar 11 2024 04:06:25 GMT+0000 (Coordinated Universal Time)

@vaibhavupadhyay

star

Mon Mar 11 2024 02:12:25 GMT+0000 (Coordinated Universal Time)

@manhmd

star

Sun Mar 10 2024 21:37:53 GMT+0000 (Coordinated Universal Time) https://huggingface.co/LoupGarou/Starcoderplus-Guanaco-GPT4-15B-V1.0

@acarp3422

star

Sun Mar 10 2024 20:43:08 GMT+0000 (Coordinated Universal Time)

@VinMinichiello #javascript

star

Sun Mar 10 2024 20:42:11 GMT+0000 (Coordinated Universal Time)

@VinMinichiello #html

star

Sun Mar 10 2024 20:37:40 GMT+0000 (Coordinated Universal Time)

@VinMinichiello

star

Sun Mar 10 2024 17:04:23 GMT+0000 (Coordinated Universal Time) https://darkwebmarketbuyer.com/product/oxycodone-80-mg/

@darkwebmarket

star

Sun Mar 10 2024 17:03:48 GMT+0000 (Coordinated Universal Time) https://darkwebmarketbuyer.com/product/fake-e10-euro-banknotes-x-50/

@darkwebmarket

star

Sun Mar 10 2024 16:41:26 GMT+0000 (Coordinated Universal Time)

@agedofujpn #javascript

star

Sun Mar 10 2024 15:54:33 GMT+0000 (Coordinated Universal Time)

@brhm_lifter

star

Sun Mar 10 2024 14:06:22 GMT+0000 (Coordinated Universal Time) https://www.cyberforum.ru/python-api/thread2602746.html

@qwdixq

star

Sun Mar 10 2024 12:23:06 GMT+0000 (Coordinated Universal Time) https://mastergroosha.github.io/aiogram-2-guide/quickstart/

@qwdixq

star

Sun Mar 10 2024 12:20:35 GMT+0000 (Coordinated Universal Time) https://github.com/karthiksalapu/python_code/blob/main/time_conversion_basic

@karthiksalapu

star

Sun Mar 10 2024 12:10:48 GMT+0000 (Coordinated Universal Time) https://github.com/karthiksalapu/python_code/blob/main/min_max_of_4digits_in_any_array

@karthiksalapu

star

Sun Mar 10 2024 05:46:54 GMT+0000 (Coordinated Universal Time) https://legacy.reactjs.org/docs/cdn-links.html

@rahulk

star

Sun Mar 10 2024 02:54:38 GMT+0000 (Coordinated Universal Time) https://leetcode.com/contest/weekly-contest-388/problems/apple-redistribution-into-boxes/

@hepzz03 #undefined

star

Sat Mar 09 2024 22:48:13 GMT+0000 (Coordinated Universal Time)

@davidmchale #geolocation #react

star

Sat Mar 09 2024 18:51:19 GMT+0000 (Coordinated Universal Time)

@NoobAl

star

Sat Mar 09 2024 15:09:44 GMT+0000 (Coordinated Universal Time) https://ayudawp.com/omitir-cache-optimizaciones-wp-rocket/

@rstringa

star

Sat Mar 09 2024 13:41:45 GMT+0000 (Coordinated Universal Time)

@abhikash01

star

Sat Mar 09 2024 08:41:02 GMT+0000 (Coordinated Universal Time)

@hiimsa

star

Sat Mar 09 2024 07:07:00 GMT+0000 (Coordinated Universal Time) https://pypi.org/project/python-weather/

@qwdixq

star

Sat Mar 09 2024 07:06:50 GMT+0000 (Coordinated Universal Time) https://pypi.org/project/python-weather/

@qwdixq

star

Sat Mar 09 2024 07:06:34 GMT+0000 (Coordinated Universal Time) https://pypi.org/project/python-weather/

@qwdixq

star

Sat Mar 09 2024 02:43:16 GMT+0000 (Coordinated Universal Time)

@titorobe #javascript

Save snippets that work with our extensions

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