text
stringlengths
184
4.48M
import type { ReadyMessage, TokenRequest, TokenResponse, WorkerError, } from "./types"; /** * Check if a value is a "ready" message. * @param value The value to check. */ export function isReadyMessage(value: unknown): value is ReadyMessage { return typeof value === "object" && value !== null && (value as ReadyMessage).type === "ready"; } /** * Check if a value is a worker error message. * @param value The value to check. */ export function isWorkerError(value: unknown): value is WorkerError { return typeof value === "object" && value !== null && (value as WorkerError).error === true; } /** * Check if a value is a token request message. * @param value The value to check. */ export function isTokenRequest(value: unknown): value is TokenRequest { return typeof value === "object" && value !== null && (value as TokenRequest).type === "token-request"; } /** * Check if a value is a token response message. * @param value The value to check. */ export function isTokenResponse( value: unknown, id?: number, ): value is TokenResponse { return typeof value === "object" && value !== null && (value as TokenResponse).type === "token-response" && (id === undefined || (value as TokenResponse).payload.id === id); }
import React , {useState, useEffect} from "react"; import CommonSection from "../shared/CommonSection"; import { Col, Container, Row} from 'reactstrap'; import '../styles/tour.css'; import TourCard from './../shared/TourCard'; import SearchBar from './../shared/SearchBar'; import Newsletter from './../shared/Newsletter'; import useFetch from "../hooks/useFetch"; import { BASE_URL } from "../utils/config"; const Tours = ( ) => { const [pageCount, setPageCount] = useState(0); const [page, setPage] = useState(0); const {data:tours, loading, error} = useFetch(`${BASE_URL}/tours?page=${page}`); const {data:tourCount} = useFetch(`${BASE_URL}/tours/search/getTourCount`); useEffect(() => { const pages = Math.ceil(tourCount / 8); setPageCount(pages); window.scrollTo(0,0); },[page, tourCount, tours]) return ( <> <CommonSection title={"All Tours"} /> <section> <Container> <Row> <SearchBar /> </Row> </Container> </section> <section className="pt-0"> <Container> {loading && <h4 className="text-center pt-5">Loading.......</h4>} {error && <h4 className="text-center pt-5">{error}</h4>} { !loading && !error && <Row> {tours?.map(tour=> ( <Col lg='3' md="6" sm="6" className="mb-4" key={tour._id}> <TourCard tour={tour} /> </Col> ))} <Col lg='12'> <div className="pagination d-flex align-items-center justify-content-center mt-4 gap-3"> {[...Array(pageCount).keys()].map(number=> ( <span key={number} onClick={() => setPage(number)} className={page === number ? "active__page" : ""}> {number + 1} </span> ))} </div> </Col> </Row> } </Container> </section> <Newsletter /> </>); }; export default Tours;
import Footer from './Layout/Footer/Footer'; import Header from './Component/Header/Header'; import { BrowserRouter, Route, Routes } from 'react-router-dom'; import Homepage from './Pages/Homepage'; import Servicespage from './Pages/Servicespage'; import Solutionpage from './Pages/Solutionpage'; // Language change section start import { useTranslation } from "react-i18next"; import { useCallback, useEffect } from 'react'; //particles implement import Particles from "react-particles"; import { loadFull } from "tsparticles"; function App() { const { t } = useTranslation(); useEffect(()=>{ localStorage.setItem("language", "en") },[]) //particles implement const particlesInit = useCallback(async engine => { // console.log(engine); await loadFull(engine); }, []); const particlesLoaded = useCallback(async container => { await console.log(container); }, []); return ( <BrowserRouter> <Header/> <Routes> <Route path='/' element={<Homepage />}/> <Route path='/servicespage/:id' element={<Servicespage/>}/> <Route path='/solutionpage/:id' element={<Solutionpage />} /> </Routes> {/* particles section start here */} <div style={{ width:'100wv', hieght:'100hv', position:'absolute', zIndex:-100 }}> <Particles id="tsparticles" init={particlesInit} loaded={particlesLoaded} options={{ fpsLimit: 120, interactivity: { events: { onClick: { enable: true, mode: "push", }, onHover: { enable: true, mode: "repulse", }, resize: true, }, modes: { push: { quantity: 3, }, repulse: { distance: 200, duration: 0.5, }, }, }, particles: { color: { value: "#003333", }, links: { color: "#002633", distance: 150, enable: true, opacity: 0.3, width: 2, }, collisions: { enable: true, }, move: { directions: "none", enable: true, outModes: { default: "bounce", }, random: false, speed: 2, straight: false, }, number: { density: { enable: true, area:1500, }, value: 80, }, opacity: { value: 0.4, }, shape: { type: "circle", }, size: { value: { min: 1, max: 5 }, }, }, detectRetina: true, }} /> </div> <Footer /> </BrowserRouter> ); } export default App;
# dbsec A set of scripts to parse nmap / Nessus data and import XML data into a MySQL database. ## Required -Python 2.7 -MySQL 5.5 -mysqlclient 1.3.6 -nmap -Nessus ### (Optional) -MySQL Workbench -PHPmyadmin ## Files 1. README.md 2. dbsec_database.sql 3. batch_import.sql 4. master_parse.py ## Description The dbsec project is designed to create a foundation to better analyze vulnerability scan data. The majority of vulnerability scanners on the market produce xml and csv data exports for analysts to crawl through, which can be tedious. While some may rely on command line parsing tools, and others might depend more heavily upon a collection of specialized scripts, the dbsec project aims to pull the most relevant information from a scan report and load it into a database. Once in a database, the user can utilize SQL to analyze the information more effectively. Additionally, information in a database can easily be linked to a web framework, such as Django, for reporting purposes. ## Instructions 1. Download the required software. At a minimum, you will need to install Python 2.7 or greater and MySQL 5.5. Keep in mind that to run locally, you will need both the MySQL client and MySQL server running. Additionally, tools such as MySQL Workbench or PHPmyadmin can be handy to manage your databases. 2. Generate nmap / Nessus xml data. Both products are free (Nessus for home users). 3. Execute 'master_parse.py' with the nmap and Nessus xml files as command line arguments. By default, output is displayed in the terminal. ex. 'python master_parse.py nmap.xml data.nessus > output.xml' 4. Using either command line, or one of the GUI options listed above, connect to the database server. Create the database using the 'dbsec_database.sql' file. 5. Again, from command line or GUI, access the database server. Run the 'batch_import.sql' file, but take note of the lines that need to be replaced. Most text editors support a 'replace-all' function, which is typically ctrl+h.
<!DOCTYPE html> <html lang="uk"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css" /> <link rel="stylesheet" href="./css/styles.css" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet" /> </head> <body> <header> <div class="container-header"> <div class="container-nav"> <a class="logo" href="./index.html" ><span class="logo-text">Web</span>Studio</a > <nav> <ul class="site-nav list"> <li> <a class="nav-link" href="./index.html">Студія</a> </li> <li> <a class="nav-link" href="./portfolio.html">Портфоліо</a> </li> <li><a class="nav-link" href="#">Контакти</a></li> </ul> </nav> </div> <div class="container-contact"> <ul class="container-list list"> <li class="icon-nav"> <a class="address-mail" href="mailto:info@devstudio.com" ><svg class="addres-icon" width="16px" height="12px"> <use href="/images/sprite-icon.svg#icon-mail"></use> </svg> info@devstudio.com</a> </li> <li class="icon-nav"> <a class="address-header" href="tel:+380961111111" ></a><svg class="addres-icon" width="10px" height="16px"> <use href="/images/sprite-icon.svg#icon-phone"></use> </svg> +38 096 111 11 11</a> </li> </ul> </div> </div> </header> <main> <section class="section-portfolio"> <div class="container-portfolio"> <ul class="menu list"> <li> <button class="portfolio-button" type="button">Усі</button> </li> <li> <button class="portfolio-button" type="button">Веб-сайти</button> </li> <li> <button class="portfolio-button" type="button">Додатки</button> </li> <li> <button class="portfolio-button" type="button">Дизайн</button> </li> <li> <button class="portfolio-button" type="button">Маркетинг</button> </li> </ul> <ul class="cart list"> <li class="portfolio-carts"> <div class="cart-text"> <a href="#"><img src="/images/portfolio/img1.jpg" alt="Компьютер"> <h2 class="portfolio-title">Технокряк</h2> <p class="portfolio-text">Веб-сайт</p></a> </div> </li> <li class="portfolio-carts"> <div class="cart-text"> <a href="#"><img src="/images/portfolio/img2.jpg" alt="баскетболісти"> <h2 class="portfolio-title"> Постер New Orlean vs Golden Star </h2> <p class="portfolio-text">Дизайн</p></a> </div> </li> <li class="portfolio-carts"> <div class="cart-text"> <a href="#"><img src="/images/portfolio/img3.jpg" alt="Реклама"> <h2 class="portfolio-title">Ресторан Seafood</h2> <p class="portfolio-text">Додаток</p></a> </div> </li> <li class="portfolio-carts"> <div class="cart-text"> <a href="#"><img src="/images/portfolio/img4.jpg" alt="Наушники"></a> <h2 class="portfolio-title">Проєкт Prime</h2> <p class="portfolio-text">Маркетинг</p></a> </div> </li> <li class="portfolio-carts"> <div class="cart-text"> <a href="#"><img src="/images/portfolio/img5.jpg" alt="Дві коробки"> <h2 class="portfolio-title">Проєкт Boxes</h2> <p class="portfolio-text">Додаток</p></a> </div> </li> <li class="portfolio-carts"> <a href="#"><img src="/images/portfolio/img6.jpg" alt="Монітор"> <div class="cart-text"> <h2 class="portfolio-title">Inspiration has no Borders</h2> <p class="portfolio-text">Веб-сайт</p></a> </div> </li> <li class="portfolio-carts"> <div class="cart-text"> <a href="#"><img src="/images/portfolio/img7.jpg" alt="Книга"> <h2 class="portfolio-title">Видання Limited Edition</h2> <p class="portfolio-text">Дизайн</p></a> </div> </li> <li class="portfolio-carts"> <div class="cart-text"> <a href="#"><img src="/images/portfolio/img8.jpg" alt="Лейба"> <h2 class="portfolio-title">Проєкт LAB</h2> <p class="portfolio-text">Маркетинг</p></a> </div> </li> <li class="portfolio-carts"> <div class="cart-text"> <a href="#"><img src="/images/portfolio/img9.jpg" alt="Ноутбук"> <h2 class="portfolio-title">Growing Business</h2> <p class="portfolio-text">Додаток</p></a> </div> </li> </ul> </div> </section> </main> <footer class="page-footer"> <div class="footer-container"> <div> <a class="logo" href="/" ><span class="logo-text">Web</span ><span class="footer-text">Studio</span></a > <address class="address"> <p class="text">м. Київ, пр-т Лесі Українки, 26</p> <a class="address" href="mailto:info@devstudio.com" >info@devstudio.com</a > <a class="phone" href="tel:+380961111111">+38 096 111 11 11</a> </address> </div> <div class="icon-footer"> <h2 class="slogan">приєднуйтесь</h2> <ul class="icon-list list"> <li class="icon-item"> <a href="#" class="icon-link" ><svg width="20" height="20"> <use href="./images/sprite-icon.svg#icon-instagram"></use> </svg> </a> </li> <li class="icon-item"> <a href="#" class="icon-link" ><svg width="20" height="20"> <use href="/images/sprite-icon.svg#icon-Twitter"></use> </svg> </a> </li> <li class="icon-item"> <a href="#" class="icon-link" ><svg width="20" height="20"> <use href="/images/sprite-icon.svg#icon-facebook"></use> </svg> </a> </li> <li class="icon-item"> <a href="#" class="icon-link" ><svg width="20" height="20"> <use href="/images/sprite-icon.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </div> </footer> </body> </html>
// 1 - Arrays const numbers: number[] = [1, 2, 3]; numbers.push(5); console.log(numbers[2]); const nomes: string[] = ['Guilherme', 'Russo']; console.log(nomes[0]); // 2 - Arrays outra sintaxe const nums: Array<number> = [1, 2, 3]; nums.push(300); console.log(nums[3]); // 3 - Any (evitar ao máximo esse tipo) const arr1: any = [1, 'teste', true, [], { nome: 'Guilherme' }]; console.log(arr1); // 4 - parametros tipados function soma(a: number, b: number) { console.log(a + b); } soma(5, 10); // 5 - retornos de função function greeting(name: string): string { return `Olá ${name}`; } console.log(greeting('Guilherme')); // 6 - funções anônimas setTimeout(function () { const sallary = 1000; // console.log(parseFloat(sallary)); }, 2000); // 7 - tipos de objeto function passCoordinates(coord: { x: number; y: number }) { console.log('X coordinatas: ' + coord.x); console.log('Y coordinatas: ' + coord.y); } const objCoord = { x: 329, y: 84.5 }; passCoordinates(objCoord); // 8 - propriedades opcionais function showNumbers(a: number, b: number, c?: number) { console.log('A: ' + a); console.log('B: ' + b); if (c) console.log('C: ' + c); } showNumbers(1, 2, 3); showNumbers(4, 5); // 9 - validação de propriedades opcionais function advancedGreeting(firstName: string, lastName?: string) { if (lastName !== undefined) { return `Olá, ${firstName} ${lastName}, tudo bem?`; } return `Olá, ${firstName}, tudo bem?`; } console.log(advancedGreeting('Guilhrme', 'Russo')); console.log(advancedGreeting('Guilhrme')); // 10 - Union type function showBalance(balance: string | number) { console.log(`O saldo da conta é R$${balance}`); } showBalance(100); showBalance('500'); const arr2: Array<number | string | boolean> = [1, 'teste', false]; console.log(arr2); // 11 - Avançando em union types function showUserRole(role: boolean | string) { if (typeof role === 'boolean') { return 'Usuário não aprovado!'; } return `A função do usuário é: ${role}`; } console.log(showUserRole(false)); console.log(showUserRole('Admin')); // 12 - Type alias type ID = string | number; function showId(id: ID) { console.log(`O ID é : ${id}`); } showId(1); showId('200'); // 13 - Interfaces interface Point { x: number; y: number; z: number; } function showCoords(obj: Point) { console.log(`X: ${obj.x}`); console.log(`Y: ${obj.y}`); console.log(`Z: ${obj.z}`); } const coordObj: Point = { x: 10, y: 15, z: 30, }; showCoords(coordObj); // 14 - interface x type alias // interfaces podem ser incrementadas com a evolução do código interface Person { name: string; } interface Person { age: number; } const somePerson: Person = { name: 'Guilherme', age: 34 }; console.log(somePerson); //type alias não podem ser alterados type personType = { name: string; }; // código abaixo não funciona // type personType = { // age: number; // }; const otherPerson: personType = { name: 'Guilherme' }; console.log(otherPerson); // 15 - literal types function showDirection(direction: 'left' | 'right' | 'center') { console.log(`A direção é : ${direction}`); } showDirection('left'); // 16 - Non null assertion operator "!" // const p = document.getElementById('some-p'); // Eslint não aceita esse tipo de asserção // console.log(p!.innerText); // 17 - BigInt // eslint-disable-next-line const n: bigint = 100n; console.log(n); console.log(typeof n); // 18 - Symbol - cria uma referência única para um valor, mesmo que outra variável tenha o mesmo valor, ele considera que são diferentes // eslint-disable-next-line const symbolA:symbol = Symbol("a"); const symbolB = Symbol('a'); console.log(symbolA == symbolB); console.log(symbolA === symbolB);
import Spinner from "../Spinner/Spinner"; import useOrders from "../../api/order/user/useOrders"; export default function ProfileOrders() { const { orders, isLoading } = useOrders(); return ( <section className="relative"> {isLoading ? ( <div className="pt-64"> <Spinner /> </div> ) : !orders?.length ? ( <div className="w-full text-center py-24"> <img src="/images/order-empty.svg" className="m-auto object-contain" /> <p className="text-lg font-semibold dark:text-white-100"> You haven't placed any orders </p> </div> ) : ( orders?.map((data) => ( <div className="px-8 border-b py-8" key={data?.id}> <div className="md:flex md:justify-between grid grid-cols-2"> <div className="flex md:mb-0 mb-4 items-center"> <p className="mr-2 text-sm text-gray-800">status:</p> <p className="flex"> {data.status === "1" ? ( <img src="" className="w-6 h-6 rounded-full" /> ) : ( <img src="/images/success.png" className="w-6 h-6 rounded-full" /> )} </p> </div> <div className="flex md:mb-0 mb-4 items-center"> <p className="mr-2 text-sm text-gray-800">Date:</p> <p className="dark:text-white-100 text-black-900 text-sm lg:text-base"> {data?.createdAt?.slice(0, 10)} </p> </div> <div className="flex md:mb-0 mb-4 items-center"> <p className="mr-2 text-sm text-gray-800">price:</p> <p className="dark:text-white-100 text-black-900 text-sm lg:text-base "> {data.price}$ </p> </div> <div className="flex md:mb-0 mb-4 items-center"> <p className="mr-2 text-sm text-gray-800">code:</p> <p className="dark:text-white-100 text-black-900 text-sm lg:text-base "> {data.code} </p> </div> </div> <div className="flex py-6"> {data?.fileUrls?.map((file, index) => ( <img src={file} className="w-20 h-20 mr-12 object-cover" key={index} /> ))} </div> </div> )) )} </section> ); }
import React, { createContext, useReducer } from "react"; import { init, reducer } from "../Reducers/itemReducer"; import axios from "axios"; export const itemContext = createContext(init); export const ItemProvider = ({ children }) => { const [state, dispatch] = useReducer(reducer, init); function selectNumber(n) { dispatch({ type: "number", payload: { item: n } }); } function selectCategory(c) { dispatch({ type: "category", payload: { item: c } }); } function selectDifficulty(d) { dispatch({ type: "difficulty", payload: { item: d } }); } function selectType(t) { dispatch({ type: "choice", payload: { item: t } }); } const quizQuestion = async () => { localStorage.setItem("Loading", true); try { const response = await axios.get( `https://opentdb.com/api.php?amount=${state.questions}&category=${state.categories}&difficulty=${state.difficulty}&type=${state.choice}` ); dispatch({ type: "quizQuestion", payload: { item: response.data.results, }, }); localStorage.removeItem("Loading"); } catch (err) { console.log(err); } }; const value = { ...state, selectNumber, selectCategory, selectDifficulty, selectType, quizQuestion, }; return <itemContext.Provider value={value}>{children}</itemContext.Provider>; };
import { Container, // Logo, ButtonLogin, Conjunto, Items, MobileNav, Ruta, } from "./styled"; import Hamburger from "../../assets/images/icon-hamburger.svg"; import Close from "../../assets/images/icon-close.svg"; //import logo from "./../../assets/images/logo-bookmark.svg"; import { Link } from "react-router-dom"; import { useEffect, useState } from "react"; import { i18n } from "./../../translate/i18n"; export default function Header() { const [navToggle, setNavToggle] = useState(false); const alternar = () => { setNavToggle(!navToggle); }; useEffect(() => { if (navToggle === true) { document.body.style.overflow = "hidden"; } else { document.body.style.overflow = "auto"; } }); return ( <Container> <Link to="/"> {/* <Logo src={logo} alt="logo" /> */} </Link> <MobileNav navToggle={navToggle}> <button onClick={alternar}> {navToggle ? ( <i> <img src={Close} alt="Fechar" /> </i> ) : ( <i> <img src={Hamburger} alt="abrir" /> </i> )} </button> </MobileNav> <Conjunto navToggle={navToggle}> <Items> <Link to="/"> <Ruta>{i18n.t("rutas.home")}</Ruta> </Link> <Link to="/services"> <Ruta>{i18n.t("rutas.services")}</Ruta> </Link> <Link to="/register"> <Ruta>{i18n.t("rutas.register")}</Ruta> </Link> <ButtonLogin> {i18n.t("rutas.login")} <span></span><span></span><span></span><span></span> </ButtonLogin> </Items> </Conjunto> </Container> ); }
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>{% block title%} News from all the Globe {% endblock title%}</title> <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"/> <link href="{% static 'css/style.css' %}" rel="stylesheet"/> </head> <body> {% include 'inc/_nav.html' %} <div class="container mt-3"> <div class="row"> <div class="col-md-3"> {% load cache %} {% cache 50 sidebar %} {% block sidebar%}{% endblock sidebar %} {% endcache %} </div> <div class="col-md-9"> {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alert alert-danger" role="alert"> {{ message }} </div> {% else %} <div class="alert alert-{{ message.tags }}" role="alert"> {{ message }} </div> {% endif %} {% endfor %} {% endif %} {% block content%}{% endblock content %} {% if page_obj.has_other_pages %} <nav aria-label="..."> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item "> <a href="?page={{ page_obj.previous_page_number }}"> <span class="page-link" >Previous</span> </a> </li> {% endif %} {% for p in page_obj.paginator.page_range %} {% if page_obj.number == p %} <li class="page-item active" aria-current="page"> <a class="page-link" href="?page={{ p }}">{{ p }}</a> </li> {% elif p > page_obj.number|add:-3 and p < page_obj.number|add:3 %} <li class="page-item"> <a class="page-link" href="?page={{ p }}">{{ p }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item "> <a href="?page={{ page_obj.next_page_number }}"> <span class="page-link" >Next</span> </a> </li> {% endif %} </ul> </nav> {% endif %} </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous" ></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous" ></script> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}" integrity="sha384-mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD" crossorigin="anonymous" ></script> </body> </html>
import { styled, ToggleButton, ToggleButtonGroup } from "@mui/material"; import { PLAN_PERIOD } from "constants/gallery"; import { t } from "i18next"; const CustomToggleButton = styled(ToggleButton)(({ theme }) => ({ textTransform: "none", padding: "12px 16px", borderRadius: "4px", backgroundColor: theme.colors.fill.faint, border: `1px solid transparent`, color: theme.colors.text.faint, "&.Mui-selected": { backgroundColor: theme.colors.accent.A500, color: theme.colors.text.base, }, "&.Mui-selected:hover": { backgroundColor: theme.colors.accent.A500, color: theme.colors.text.base, }, width: "97.433px", })); export function PeriodToggler({ planPeriod, togglePeriod }) { const handleChange = (_, newPlanPeriod: PLAN_PERIOD) => { if (newPlanPeriod !== null && newPlanPeriod !== planPeriod) { togglePeriod(); } }; return ( <ToggleButtonGroup value={planPeriod} exclusive onChange={handleChange} color="primary" > <CustomToggleButton value={PLAN_PERIOD.MONTH}> {t("MONTHLY")} </CustomToggleButton> <CustomToggleButton value={PLAN_PERIOD.YEAR}> {t("YEARLY")} </CustomToggleButton> </ToggleButtonGroup> ); }
# Chatting-AppXSwing A chat application using Java Swing involves creating a graphical user interface (GUI) where users can exchange messages in real-time. Here’s an outline of how you might build a simple chat application using Swing: ### Components Required: - JFrame: Represents the main window of the application. - JTextArea: Displays the conversation history. - JTextField: Allows users to input messages. - JButton: Triggers the sending of messages. ### Server-Client Structure: - Server Side: Manages incoming connections and distributes messages among connected clients. - Client Side: Connects to the server, sends messages, and receives messages from the server. ### Steps to Implement: #### Server Side: 1. Setup the Server: - Create a `ServerSocket`. - Accept incoming connections from clients. - Create input and output streams to communicate with connected clients. 2. Handle Client Messages: - Continuously listen for incoming messages from connected clients. - Upon receiving a message, broadcast it to all connected clients. #### Client Side: 1. Connect to the Server: - Create a `Socket` to connect to the server. - Create input and output streams to communicate with the server. 2. Send and Receive Messages: - Allow the user to type messages in the `JTextField`. - Upon pressing the send button, send the message to the server using the output stream. - Continuously listen for incoming messages from the server using the input stream. ### User Interface: - Arrange the Swing components within the JFrame using layout managers like BorderLayout, GridLayout, etc. - The chat history can be displayed in a JTextArea or a JList for better formatting. - The JTextField allows users to input messages. - The JButton triggers sending the message to the server. ### Additional Considerations: - Implement a protocol to differentiate different types of messages (e.g., regular messages, system messages). - Add error handling for lost connections or server/client crashes. - Implement threading or asynchronous communication to avoid UI freezes when listening for messages. ### Example Features (Not Included in Basic Outline): - Username assignment and display. - Differentiating between users in the chat. - Private messaging between specific users. - Emoticon or file-sharing support. Building a complete chat application involves setting up a server-client structure, designing an intuitive GUI using Swing components, implementing message handling logic, and considering error handling and additional functionalities for a more robust experience.
import { hideLinkEmbed, hyperlink, inlineCode, time, TimestampStyles } from '@discordjs/builders'; import { ApplyOptions } from '@sapphire/decorators'; import { Command, CommandOptions, version as sapphireVersion } from '@sapphire/framework'; import { send } from '@sapphire/plugin-editable-commands'; import { Time } from '@sapphire/time-utilities'; import { roundNumber } from '@sapphire/utilities'; import { envParseString } from '@skyra/env-utilities'; import { PermissionFlagsBits } from 'discord-api-types/v10'; import { Message, MessageActionRow, MessageButton, MessageEmbed, Permissions, version as discordjsVersion } from 'discord.js'; import { cpus, uptime, type CpuInfo } from 'node:os'; @ApplyOptions<CommandOptions>({ aliases: ['info'], description: 'Provides information about Alestra' }) export class UserCommand extends Command { private numberFormat = new Intl.NumberFormat('en-GB', { maximumFractionDigits: 2 }); private readonly canvasConstructorServerInviteLink = 'https://discord.gg/taNgb9d'; public override messageRun(message: Message) { return send(message, { embeds: [this.embed], components: this.components }); } private get components(): MessageActionRow[] { return [ new MessageActionRow().addComponents( new MessageButton() // .setStyle('LINK') .setURL(this.inviteLink) .setLabel('Add me to your server!') .setEmoji('🎉'), new MessageButton() // .setStyle('LINK') .setURL(this.canvasConstructorServerInviteLink) .setLabel('Support server') .setEmoji('🆘') ), new MessageActionRow().addComponents( new MessageButton() .setStyle('LINK') .setURL('https://github.com/skyra-project/alestra') .setLabel('GitHub Repository') .setEmoji('<:github2:950888087188283422>'), new MessageButton() // .setStyle('LINK') .setURL('https://donate.skyra.pw/patreon') .setLabel('Donate') .setEmoji('🧡') ) ]; } private get inviteLink() { return this.container.client.generateInvite({ scopes: ['bot', 'applications.commands'], permissions: new Permissions([ PermissionFlagsBits.ViewChannel, PermissionFlagsBits.ReadMessageHistory, PermissionFlagsBits.SendMessages, PermissionFlagsBits.EmbedLinks ]) }); } private get embed(): MessageEmbed { const titles = { stats: 'Statistics', uptime: 'Uptime', serverUsage: 'Server Usage' }; const stats = this.generalStatistics; const uptime = this.uptimeStatistics; const usage = this.usageStatistics; const fields = { stats: [ // `• **Users**: ${stats.users}`, `• **Guilds**: ${stats.guilds}`, `• **Channels**: ${stats.channels}`, `• **Node.js**: ${stats.nodeJs}`, `• **Discord.js**: ${stats.discordjsVersion}`, `• **Sapphire Framework**: ${stats.sapphireVersion}` ].join('\n'), uptime: [ // `• **Host**: ${uptime.host}`, `• **Total**: ${uptime.total}`, `• **Client**: ${uptime.client}` ].join('\n'), serverUsage: [ // `• **CPU Load**: ${usage.cpuLoad}`, `• **Heap**: ${usage.ramUsed}MB (Total: ${usage.ramTotal}MB)` ].join('\n') }; const clientVersion = envParseString('CLIENT_VERSION'); const canvasConstructorPackage = hyperlink(inlineCode("canvas-constructor's"), hideLinkEmbed('https://github.com/kyranet/CanvasConstructor')); const canvasConstructorServer = hyperlink('official canvas constructor server', hideLinkEmbed(this.canvasConstructorServerInviteLink)); return new MessageEmbed() // .setColor(0xfcac42) .setDescription(`Alestra ${clientVersion} is a private Discord Bot used for ${canvasConstructorPackage} ${canvasConstructorServer}`) .setFields( { name: titles.stats, value: fields.stats, inline: true }, { name: titles.uptime, value: fields.uptime }, { name: titles.serverUsage, value: fields.serverUsage } ); } private get generalStatistics(): StatsGeneral { const { client } = this.container; return { channels: client.channels.cache.size, guilds: client.guilds.cache.size, nodeJs: process.version, users: client.guilds.cache.reduce((acc, val) => acc + (val.memberCount ?? 0), 0), discordjsVersion: `v${discordjsVersion}`, sapphireVersion: `v${sapphireVersion}` }; } private get uptimeStatistics(): StatsUptime { const now = Date.now(); const nowSeconds = roundNumber(now / 1_000); return { client: time(this.secondsFromMilliseconds(now - this.container.client.uptime!), TimestampStyles.RelativeTime), host: time(roundNumber(nowSeconds - uptime()), TimestampStyles.RelativeTime), total: time(roundNumber(nowSeconds - process.uptime()), TimestampStyles.RelativeTime) }; } private get usageStatistics(): StatsUsage { const usage = process.memoryUsage(); return { cpuLoad: cpus().slice(0, 2).map(UserCommand.formatCpuInfo.bind(null)).join(' | '), ramTotal: this.formatNumber(usage.heapTotal / 1_048_576), ramUsed: this.formatNumber(usage.heapUsed / 1_048_576) }; } private secondsFromMilliseconds(milliseconds: number): number { return roundNumber(milliseconds / Time.Second); } private formatNumber(number: number): string { return this.numberFormat.format(number); } private static formatCpuInfo({ times }: CpuInfo) { return `${roundNumber(((times.user + times.nice + times.sys + times.irq) / times.idle) * 10_000) / 100}%`; } } interface StatsGeneral { channels: number; guilds: number; nodeJs: string; users: number; discordjsVersion: string; sapphireVersion: string; } interface StatsUptime { client: string; host: string; total: string; } interface StatsUsage { cpuLoad: string; ramTotal: string; ramUsed: string; }
class ImageUploader < CarrierWave::Uploader::Base include CarrierWave::RMagick process :fix_exif_rotation def store_dir "uploads/photos/users/#{model.user.id}/#{model.id}" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end def thumbnail(width, height) manipulate! do |img| img = img.resize_to_fill(width, height) end end version :favicon do process thumbnail: [16, 16] end version :tiny do process thumbnail: [40, 40] end version :avatar do process thumbnail: [130, 130] end version :square do process thumbnail: [300, 300] end version :medium do process resize_to_limit: [500, 500] end version :large do process resize_to_limit: [1140, nil] end def extension_white_list %w(jpg jpeg gif png) end def filename if original_filename extension = original_filename.split(".").last "photo.#{extension}" end end def rotate(options) manipulate! do |img| if options.has_key? :rotate img.rotate!(options[:rotate].to_i) end if options.has_key? :flip img.flip! end if options.has_key? :flop img.flop! end img end end def fix_exif_rotation manipulate! do |img| img.auto_orient! yield(img) if block_given? img end end end
import cv2 import numpy as np import os def is_black_frame(frame): """ Check if the given frame is entirely black. """ return np.all(frame == 0) def remove_black_frames_from_folder(folder_path, save_folder): """ Remove all black frames from the specified folder. """ # Check if the provided path is a directory if not os.path.isdir(folder_path): return # List all the image frames within the folder frames = sorted( [os.path.join(folder_path, frame) for frame in os.listdir(folder_path) if frame.endswith(('.jpg', '.png'))]) for i, frame_path in enumerate(frames): frame = cv2.imread(frame_path) # If the frame is black, remove it from the directory if is_black_frame(frame): os.remove(frame_path) def compute_optical_flow(prev_frame, curr_frame): """ Compute dense optical flow using Gunner Farneback's algorithm. """ # Convert frames to grayscale for optical flow computation prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY) curr_gray = cv2.cvtColor(curr_frame, cv2.COLOR_BGR2GRAY) # Calculate dense optical flow using Farneback's method flow = cv2.calcOpticalFlowFarneback(prev_gray, curr_gray, None, 0.5, 3, 15, 3, 5, 1.2, 0) # Convert the computed flow to an RGB image for visualization magnitude, angle = cv2.cartToPolar(flow[..., 0], flow[..., 1]) flow_image = np.zeros((curr_frame.shape[0], curr_frame.shape[1], 3), dtype=np.float32) flow_image[..., 0] = angle * (180 / np.pi / 2) flow_image[..., 1] = 255 flow_image[..., 2] = cv2.normalize(magnitude, None, 0, 255, cv2.NORM_MINMAX) flow_rgb = cv2.cvtColor(flow_image.astype(np.uint8), cv2.COLOR_HSV2BGR) return flow_rgb def extract_optical_flow_from_folder(folder_path, save_folder): """ Compute optical flow for frames in the given folder and save them to the designated folder. """ # Check if the provided path is a directory if not os.path.isdir(folder_path): return [] # List all the frames in the folder frames = sorted([os.path.join(folder_path, frame) for frame in os.listdir(folder_path)]) prev_frame = None # Compute optical flow for each pair of consecutive frames for i, frame_path in enumerate(frames): curr_frame = cv2.imread(frame_path) if prev_frame is not None: flow_rgb = compute_optical_flow(prev_frame, curr_frame) save_path = os.path.join(save_folder, f"flow_{i}.png") cv2.imwrite(save_path, flow_rgb) prev_frame = curr_frame # Paths for preprocessed data and where to save optical flow data processed_path = 'Path_to_your_Preprocess_processed_path' flow_dataset_path = 'Path_to_your_output' # Create the directory for optical flow data if it doesn't exist if not os.path.exists(flow_dataset_path): os.makedirs(flow_dataset_path) # Define labels - 0 for non-fall and 1 for fall labels = [0, 1] # Loop through each label, compute and save optical flow for label in labels: label_folder_path = os.path.join(processed_path, str(label)) subfolders = [os.path.join(label_folder_path, subfolder) for subfolder in os.listdir(label_folder_path)] for subfolder in subfolders: # First, remove any black frames remove_black_frames_from_folder(subfolder, flow_dataset_path) # Then compute optical flow for the frames subfolder_name = os.path.basename(subfolder) save_folder = os.path.join(flow_dataset_path, str(label), subfolder_name) if not os.path.exists(save_folder): os.makedirs(save_folder) flow_data = extract_optical_flow_from_folder(subfolder, save_folder) print("Feature extraction for DL complete")
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; CREATE DATABASE Cotizador; use Cotizador; -- Creación de tablas CREATE TABLE `clientes` ( `id_cliente` int(10) NOT NULL, `id_cotizacion` int(10) DEFAULT NULL, `razon_social` varchar(50) DEFAULT NULL, `nombre` varchar(50) DEFAULT NULL, `apellido` varchar(50) DEFAULT NULL, `tipo_documento` varchar(50) DEFAULT NULL, `nro_documento` int(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE `cotizacion` ( `id_cotizacion` int(10) NOT NULL, `numero_cotizacion` int(10) DEFAULT NULL, `id_producto` int(10) DEFAULT NULL, `id_cliente` int(10) DEFAULT NULL, `cantidad` int(110) DEFAULT NULL, `telefono` int(10) DEFAULT NULL, `email` varchar(50) DEFAULT NULL, `modelo` varchar(100) DEFAULT NULL, `precio_venta` int(50) DEFAULT NULL, `total_venta` int(50) DEFAULT NULL, `validez` varchar(50) DEFAULT NULL, `fecha` date DEFAULT NULL, `id_usuario` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE `productos` ( `id_producto` int(10) NOT NULL, `codigo_producto` int(10) DEFAULT NULL, `nombre_producto` varchar(150) DEFAULT NULL, `modelo_producto` varchar(150) DEFAULT NULL, `id_proveedor` int(10) DEFAULT NULL, `estado_producto` int(10) DEFAULT NULL, `habilitado_producto` int(10) DEFAULT NULL, `precio_producto` int(10) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE `proveedor` ( `id_proveedor` int(10) NOT NULL, `nombre` varchar(50) DEFAULT NULL, `tipo_documento` varchar(50) DEFAULT NULL, `nro_documento` int(20) DEFAULT NULL, `telefono` int(20) DEFAULT NULL, `email` varchar(50) DEFAULT NULL, `estado` int(10) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE `usuarios` ( `id_usuario` int(10) NOT NULL, `nombre` varchar(50) DEFAULT NULL, `apellido` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `email` varchar(50) DEFAULT NULL, `telefono` int(20) DEFAULT NULL, `direccion` varchar(150) DEFAULT NULL, `habilitado` int(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- Índices y auto-incremento ALTER TABLE `clientes` ADD PRIMARY KEY (`id_cliente`); ALTER TABLE `cotizacion` ADD PRIMARY KEY (`id_cotizacion`), ADD KEY `id_producto` (`id_producto`), ADD KEY `id_cliente` (`id_cliente`), ADD KEY `id_usuario` (`id_usuario`); ALTER TABLE `productos` ADD PRIMARY KEY (`id_producto`), ADD KEY `id_proveedor` (`id_proveedor`); ALTER TABLE `proveedor` ADD PRIMARY KEY (`id_proveedor`); ALTER TABLE `usuarios` ADD PRIMARY KEY (`id_usuario`); ALTER TABLE `clientes` MODIFY `id_cliente` int(10) NOT NULL AUTO_INCREMENT; ALTER TABLE `cotizacion` MODIFY `id_cotizacion` int(10) NOT NULL AUTO_INCREMENT; ALTER TABLE `productos` MODIFY `id_producto` int(10) NOT NULL AUTO_INCREMENT; ALTER TABLE `proveedor` MODIFY `id_proveedor` int(10) NOT NULL AUTO_INCREMENT; ALTER TABLE `usuarios` MODIFY `id_usuario` int(10) NOT NULL AUTO_INCREMENT; -- Restricciones de clave foránea ALTER TABLE `cotizacion` ADD CONSTRAINT `cotizacion_ibfk_1` FOREIGN KEY (`id_producto`) REFERENCES `productos` (`id_producto`), ADD CONSTRAINT `cotizacion_ibfk_2` FOREIGN KEY (`id_cliente`) REFERENCES `clientes` (`id_cliente`), ADD CONSTRAINT `cotizacion_ibfk_3` FOREIGN KEY (`id_usuario`) REFERENCES `usuarios` (`id_usuario`); ALTER TABLE `productos` ADD CONSTRAINT `productos_ibfk_1` FOREIGN KEY (`id_proveedor`) REFERENCES `proveedor` (`id_proveedor`); -- Fin de la transacción COMMIT; SET SQL_MODE = @OLD_SQL_MODE;
'use client' import React, { useEffect, useState } from "react" import { useSession } from "next-auth/react" import { faPen, faTrash, faCircleUp, faCheck } from "@fortawesome/free-solid-svg-icons" import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import Link from "next/link" import Image from "next/image" import { useRouter } from "next/navigation" import { ToastContainer, toast } from "react-toastify"; import 'react-toastify/dist/ReactToastify.css'; import CommentForm from "@/components/CommentForm" import CommentList from "@/components/CommentList" //ctx or postId const PostDetails = (ctx) => { const [postDetails, setPostDetails] = useState('') const [isReacted, setIsReacted] = useState(false) const [postReactions, setPostReactions] = useState(0) const [commentText, setCommentText] = useState('') const [comments, setComments] = useState([]) const [formattedTime, setFormattedTime] = useState(''); const { data: session, status } = useSession() const router = useRouter() useEffect(() => { const time = new Date(postDetails.createdAt).toLocaleString(undefined, { timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone }); setFormattedTime(time); }, [postDetails.createdAt]); useEffect(() => { const displayedCommentIds = new Set() //keep track of displayed comments async function fetchComments() { const res = await fetch(`/api/comment/${ctx.params.id}`, { cache: 'no-store' }) const commentsData = await res.json() // Filter out comments that have already been displayed const newComments = commentsData.filter(comment => !displayedCommentIds.has(comment._id)); setComments((prevComments) => [...prevComments, ...newComments]) // Add new comment IDs to the displayed set newComments.forEach(comment => displayedCommentIds.add(comment._id)); } //fetch comments initially fetchComments() // Set up polling interval const pollingInterval = setInterval(fetchComments, 3000); // Poll every 3 seconds // Clean up the interval when the component unmounts or when the dependency changes return () => { clearInterval(pollingInterval); }; }, [ctx.params.id]) useEffect(() => { async function fetchPosts() { const res = await fetch(`/api/post/${ctx.params.id}`, { cache: 'no-store' }) const post = await res.json() setPostDetails(post) setIsReacted(post?.reactions?.includes(session?.user?._id)) setPostReactions(post?.reactions?.length || 0) } session && fetchPosts() }, [ctx.params.id, session]) const handleDelete = async () => { try { const confirmModal = confirm('Are you sure you want to delete this post?') if (confirmModal) { const res = await fetch(`/api/post/${ctx.params.id}`, { headers: { 'Authorization': `Bearer ${session.user.accessToken}` }, method: "DELETE" }) if (res.ok) { router.push('/feed') } } } catch (error) { console.log(error); } } const handleReaction = async () => { try { const res = await fetch(`/api/post/${ctx.params.id}/reaction`, { headers: { 'Authorization': `Bearer ${session.user.accessToken}` }, method: "PUT" }) console.log(res); if (res.ok) { if (isReacted) { setIsReacted(prev => !prev) setPostReactions(prev => prev - 1) } else { setIsReacted(prev => !prev) setPostReactions(prev => prev + 1) } } } catch (error) { console.log(error); } } const addComment = async (newComment, commentText) => { try { const body = { postId: ctx.params.id, authorId: session?.user?._id, text: commentText, } const res = await fetch('/api/comment', { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${session?.user?.accessToken}` }, method: "POST", body: JSON.stringify(body) }) if (res.ok) { const newComment = await res.json() console.log('Commenting successful'); console.log(newComment); setComments([newComment, ...comments]); // Clear the commentText after successfully adding the comment setCommentText(''); } } catch (error) { console.log(error) toast.error('An error occured. Please try again later') } } if (status === "loading") { return <div>Loading...</div> } return ( session?.user ? ( <div className="bg-bgRGBA p-4 my-4 mx-auto rounded flex flex-col flex-wrap items-center justify-center md:w-2/3"> <div className="top-bar flex flex-row my-2 items-center text-center w-full justify-between pb-2 border-b border-gray-200"> <span className="inline-block p-2 rounded bg-brandGreen text-white text-xs font-medium ">{postDetails.category}</span> <p className="text-sm text-gray-400 pr-2 ml-auto">{postDetails?.authorId?.username}</p> <p className="text-sm text-gray-400 px-2">{formattedTime}</p> { //if the post has been made by the current user postDetails?.authorId?._id.toString() === session?.user?._id.toString() ? ( <> <Link href={`/post/edit/${ctx.params.id}`} className=""> <FontAwesomeIcon icon={faPen} className="text-md mx-2 bg-transparent text-gray-300 hover:text-brandGreen" /> </Link> <FontAwesomeIcon icon={faTrash} onClick={handleDelete} className="text-md ml-2 bg-transparent text-gray-300 hover:text-red" /> </> ) : ( <> <p className="font-medium p-2">{postDetails?.authorId?.username}</p> </> ) } </div> <div className="textContent flex flex-col flex-wrap w-full items-start justify-start mb-4 px-4 bg-white rounded"> <h2 className="text-2xl font-medium my-2 tracking-wide">{postDetails.title}</h2> <p className="mb-4 mt-2 py-6 text-base leading-relaxed">{postDetails.desc}</p> </div> <div className="flex items-center flex-wrap pb-4 mb-4 border-b-2 border-gray-200 mt-auto w-full"> <span className="mr-3 inline-flex items-center ml-auto leading-none text-md"> {postReactions}{" "}{isReacted ? (<FontAwesomeIcon icon={faCircleUp} onClick={handleReaction} className="text-md ml-2 bg-transparent text-brandGreen cursor-pointer" />) : (<FontAwesomeIcon icon={faCircleUp} onClick={handleReaction} className="text-md ml-2 bg-transparent text-gray-300 cursor-pointer" />)} </span> </div> <div className="w-full flex flex-col items-start justify-start text-center"> <CommentForm postId={ctx.params.id} authorId={session?.user?._id} addComment={addComment} /> <CommentList comments={comments} setComments={setComments} /> </div> <ToastContainer hideProgressBar={true} position="top-center" /> </div> ) : ( <div className="feed"> <p className="text-base flex justify-center items-center p-4" >Please log in to access the forum.</p> </div> ) ) } export default PostDetails
<template> <div :at-u-sidebar="atAttribute" class="u-sidebar" > <div class="sidebar__section"> <div class="sidebar__section-title"> Upload image </div> <div class="sidebar__section-content"> <CFileSelectArea v-model:model-value="file" :is-uploading="isGetImagesLoading" @uploadFile="handleUploadFile" /> </div> </div> <div class="sidebar__section"> <div class="sidebar__section-title"> Assets </div> <div class="sidebar__section-sub-title"> Text </div> <div class="sidebar__section-content"> <UAddTextForm /> </div> <div class="sidebar__section-sub-title"> Images </div> <div class="sidebar__section-content"> <USidebarImagesAssets :images="images" :is-loading="false" class="sidebar__images" /> </div> </div> </div> </template> <script lang="ts"> import { ref, defineComponent } from 'vue'; import CInput from '../../../components/common/c-input'; import CButton from '../../../components/common/c-button'; import UAddTextForm from '../../../components/unique/u-add-text-form'; import CFileSelectArea from '../../../components/common/c-file-select-area'; import USidebarImagesAssets from '../../../components/unique/u-sidebar-images-assets'; import useApiImages from '../../../use/use-api-images'; export default defineComponent({ name: 'USidebar', components: { CInput, CButton, UAddTextForm, CFileSelectArea, USidebarImagesAssets }, props: { /** * AQA attribute */ atAttribute: { type: String, default: '' } }, setup() { const { uploadImage, getImages, isGetImagesLoading, isUploadImageLoading } = useApiImages(); const images = ref([]); const file = ref<File | null>(null); async function fetchImages() { try { images.value = await getImages() } catch (error) { console.log('ERROR fetchImages: ', error); } } async function handleUploadFile() { if (!file.value) return; try { await uploadImage(file.value) file.value = null; await fetchImages(); } catch (error) { console.log('ERROR handleUploadFile: ', error); } } fetchImages() return { file, images, isGetImagesLoading, isUploadImageLoading, handleUploadFile } } }); </script> <style lang="scss" src="./u-sidebar.scss" />
# 14 - Adding and Removing Nominations Via Socket Events Last time we created an authorized socket.io event and handler to remove a participant from the poll. Today, we're going to working on creating events and handlers for adding and removing nominations. A nomination is a candidate for the answer to a poll. So for example, if the poll's "topic" is "Where should we go out for dinner?" and nomination might be "The Turkish Restaurant," or the "Mexican Restaurant." (I'm not gonna lie, I would have a hard time deciding between the two). To get all of this done, we'll need to add some new repository methods to add nominations to our poll, along with some service methods. If I recall, the service methods should be rather straight-forward for nominations. But we'll see! *Github reminder* ## Defining Types for Nominations Before creating repository methods to add and remove nominations, I want to define the necessary types for this. Let's first define the payload we'll use in an `addNomination` method in [types.ts](../server/src/polls/types.ts). Recall that we add a `Data` suffix to our payload types for the repository layer methods. ```ts export type AddNominationData = { pollID: string; nominationID: string; nomination: Nomination; }; ``` We'll end up extracting the `pollID` from the client's token. The `nominationID` will be created in the service methods using a little helper we have for creating ids in [ids.ts](//server/src/ids.ts). But we have yet to define a nomination. Recall that we're defining our `Poll` and associated types in a [shared](../shared) package using npm workspaces. So let's add the Nomination type to [poll-types.ts](../shared/poll-types.ts)! And while we are add it, I want to update all of the `interfaces` to `types`, since we're using `types` and not `interfaces` elsewhere in our project. ```ts export type Participants = { [participantID: string]: string; } export type Nomination = { userID: string; text: string; } export type Nominations = { [nominationID: string]: Nomination; } export type Poll = { id: string; topic: string; votesPerVoter: number; participants: Participants; nominations: Nominations; // rankings: Rankings; // results: Results; adminID: string; hasStarted: boolean; } ``` A single `Nomination` contains the id of the user submitting the nomination along with the text of the nomination. Then we'll store all nominations in an object which maps the `nominationID` we'll soon create to the nomination. Finally, make sure to import `Nomination` into [types.ts](../server/src/polls/types.ts). ```ts // ... import { Nomination } from 'shared/poll-types'; ``` ## Repository methods With our Poll types updated and our addNomination argument type defined, let's create our `addNomination` method in [polls.repository.ts](../server/src/polls/polls.repository.ts). Upon opening the file, you'll see that we now have an error. This is because we have no initialized our poll with nominations. This is an easy fix. ```ts const initialPoll = { id: pollID, topic, votesPerVoter, participants: {}, nominations: {}, adminID: userID, hasStarted: false, }; ``` And our method is as follows: ```ts async addNomination({ pollID, nominationID, nomination, }: AddNominationData): Promise<Poll> { this.logger.log( `Attempting to add a nomination with nominationID/nomination: ${nominationID}/${nomination.text} to pollID: ${pollID}`, ); const key = `polls:${pollID}`; const nominationPath = `.nominations.${nominationID}`; try { await this.redisClient.send_command( 'JSON.SET', key, nominationPath, JSON.stringify(nomination), ); return this.getPoll(pollID); } catch (e) { this.logger.error( `Failed to add a nomination with nominationID/text: ${nominationID}/${nomination.text} to pollID: ${pollID}`, e, ); throw new InternalServerErrorException( `Failed to add a nomination with nominationID/text: ${nominationID}/${nomination.text} to pollID: ${pollID}`, ); } } ``` Even though we haven't done too much repository work in a while, I hope this is straightforward. We essentially access our polls key, and then set the nested nominations object's key, which is the `nominationID` which is passed to this method. We then return the updated poll, and throw an `InternalServerErrorException` if anything goes wrong. Let's add a similar method to remove a nomination. ```ts async removeNomination(pollID: string, nominationID: string): Promise<Poll> { this.logger.log( `removing nominationID: ${nominationID} from poll: ${pollID}`, ); const key = `polls:${pollID}`; const nominationPath = `.nominations.${nominationID}`; try { await this.redisClient.send_command('JSON.DEL', key, nominationPath); return this.getPoll(pollID); } catch (e) { this.logger.error( `Failed to remove nominationID: ${nominationID} from poll: ${pollID}`, e, ); throw new InternalServerErrorException( `Failed to remove nominationID: ${nominationID} from poll: ${pollID}`, ); } } ``` This is pretty similar to the last method, except we'll use the Redis JSON command to delete the value at a particular path, `JSON.DEL`.first-letter: That's basically it. The only thing I want to update is to use an `InternalServerErrorException` for `addParticipant` and `getPoll`. I merely want to do this for consistency, and to control precisely what information a client might see. ```ts // ... throw new InternalServerErrorException(`Failed to get pollID ${pollID}`); //... throw new InternalServerErrorException( `Failed to add a participant with userID/name: ${userID}/${name} to pollID: ${pollID}`, ); ``` ## Adding Service Methods for Nominations We'll need to update some types here as well. Let's update [types.ts](../server/src/polls/types.ts). I'm also going to delete an unused `RemoveParticipantData` type that is unused. I think I decided to just pass the pollID and userID directly as method arguments since there were only 2 arguments. ```ts export type AddNominationFields = { pollID: string; userID: string; text: string; }; // remove interface below // export interface RemoveParticipantData { // pollID: string; // userID: string; // } ``` Let's now create a service `addNomination` method to the [PollsService](../server/src/polls/polls.service.ts). ```ts import { createUserID, createPollID, createNominationID } from 'src/ids'; async addNomination({ pollID, userID, text, }: AddNominationFields): Promise<Poll> { return this.pollsRepository.addNomination({ pollID, nominationID: createNominationID(), nomination: { userID, text, }, }); } ``` Recall that we had a little id-creation file to create id's for our polls. Each poll nomination will have 8 characters. Next, let's add `removeNomination`. ```ts async removeNomination(pollID: string, nominationID: string): Promise<Poll> { return this.pollsRepository.removeNomination(pollID, nominationID); } ``` Like I said, there's not a lot to this. ## Gateway Socket.io Event Handlers We're going to accept a nomination event that will allow nominations from any authorized user, which is any user who connected and joined our poll's room. However, we're going to restrict removing nominations to the admin via the guard we created in our last tutorial. Let's add the first method to our [PollsGateway](../server/src/polls/polls.gateway.ts). ```ts @SubscribeMessage('nominate') async nominate( @MessageBody() nomination: NominationDto, @ConnectedSocket() client: SocketWithAuth, ): Promise<void> { this.logger.debug( `Attempting to add nomination for user ${client.userID} to poll ${client.pollID}\n${nomination.text}`, ); const updatedPoll = await this.pollsService.addNomination({ pollID: client.pollID, userID: client.userID, text: nomination.text, }); this.io.to(client.pollID).emit('poll_updated', updatedPoll); } ``` So we'll listen to an event called `nominate`, perform a little logging, then call our service method. If all goes well, we'll send out updated poll via the `poll_updated` event we've been using. But, we also need to define the shape of our `NominationDto`. Recall that we create these details with a class decorated with decorators from the class-validator library. We also previously handled converting validation errors from the class-validator library into socket.io errors, which we'll see when we demo this. That was a lot of words to add a DTO with one field to [dtos.ts](../server/src/polls/dtos.ts). ```ts export class NominationDto { @IsString() @Length(1, 100) text: string; } ``` we merely want to make sure the nomination text does not exceed 100 characters. *Remember to import this into polls.gateway.ts to eliminate errors*. Let's now add our admin-only event handler for removing nominations. ```ts @UseGuards(GatewayAdminGuard) @SubscribeMessage('remove_nomination') async removeNomination( @MessageBody('id') nominationID: string, @ConnectedSocket() client: SocketWithAuth, ): Promise<void> { this.logger.debug( `Attempting to remove nomination ${nominationID} from poll ${client.pollID}`, ); const updatedPoll = await this.pollsService.removeNomination( client.pollID, nominationID, ); this.io.to(client.pollID).emit('poll_updated', updatedPoll); } ``` First, note that we use the auth guard from last time. Then we reach out to our service layer, and send the updated poll back to clients connected to the same room, or `pollID`. ## Testing in Postman 1. Create Poll - "Where should we go out to eat?" 2. Join poll with second player 3. Connect Socket client 1 and socket client 2 4. Show addition of `nominate` and `removeNomination` 5. Try to nominate with empty `text` to show validation error. Example of our exception filter working! 6. Submit valid nominations form each participant 7. Try to remove a nomination with Participant or socket client 2 - show authorization error
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; interface IQueue { /*** Inserts an item at the queue front.*/ public void enqueue(Object item); /*** Removes the object at the queue rear and returnsit.*/ public Object dequeue(); /*** Tests if this queue is empty.*/ public boolean isEmpty(); /*** Returns the number of elements in the queue*/ public int size(); } class Object{ int val; Object next; } public class LinkedListQueue implements IQueue { Object head=null; Object tail=null; int size; public void enqueue(Object item) { item.next=head; head=item; size++; } public Object dequeue() { if(size==0) { return null; } else if (size==1) { Object d=head; head=null; tail=null; size--; return d; } else { Object h=head; Object d; for(int i=0;i<size-2;i++) h=h.next; d=h.next; h.next=null; tail=h; size--; return d; } } public boolean isEmpty() { if(size==0) return true; else return false; } public int size() { return size; } public void print() { if(size==0) { System.out.print("[]"); } else { Object h=head; System.out.print("["); System.out.print(h.val); for(int i=0;i<size-1;i++) { h=h.next; System.out.print(", "); System.out.print(h.val); } System.out.print("]"); } } public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc = new Scanner(System.in); String sin = sc.nextLine().replaceAll("\\[|\\]", ""); String[] s = sin.split(", "); int[] arr = new int[s.length]; if (s.length == 1 && s[0].isEmpty()) arr = new int[]{}; else { for(int i = 0; i < s.length; ++i) arr[i] = Integer.parseInt(s[i]); } LinkedListQueue lq = new LinkedListQueue (); int[] arr2= new int[arr.length]; int j=0; for(int i=arr.length-1;i>-1;i--) { arr2[j++]=arr[i]; } if(!s[0].isEmpty()) { for(int i = 0; i < s.length;i++){ Object h = new Object(); h.val = arr2[i]; lq.enqueue(h); } } String op; op=sc.nextLine(); int x; Object element=new Object(); //law m3mltsh new hy2oli enha might not be declared b3d kda leh m3rfsh awi switch(op) { case"enqueue": x= sc.nextInt(); element.val=x; lq.enqueue(element); lq.print(); break; case"dequeue": if(lq.dequeue()==null) System.out.print("Error"); else lq.print(); break; case"isEmpty": if(lq.isEmpty()) System.out.print("True"); else System.out.print("False"); break; case"size": System.out.print(lq.size()); break; } } }
<template> <div class="container" style="height:100%"> <v-card> <v-card-title> <v-icon large left > supervisor_account </v-icon> <v-spacer></v-spacer> <v-text-field v-model="search" append-icon="search" label="Search" single-line hide-details ></v-text-field> </v-card-title> <v-data-table v-model="selected" :headers="headers" :items="users" :search="search" :loading="true" :pagination.sync="pagination" select-all item-key="id" class="elevation-1" > <template slot="headers" slot-scope="props"> <tr> <th v-for="header in props.headers" :key="header.text" :class="['column sortable', pagination.descending ? 'desc' : 'asc', header.value === pagination.sortBy ? 'active' : '','text-xs-left']" @click="changeSort(header.value)" > {{ header.text }} <v-icon small>arrow_upward</v-icon> </th> </tr> </template> <v-progress-linear v-show="showProgress" slot="progress" color="blue" indeterminate></v-progress-linear> <template slot="items" slot-scope="props"> <tr> <td>{{ props.item.fullName }}</td> <td class="text-xs-left">{{ props.item.username }}</td> <td class="text-xs-left">{{ props.item.type }}</td> <td class="justify-center"> <v-icon small class="mr-2" @click="editItem(props.item)" > edit </v-icon> <v-icon small class="mr-2" @click="showDocuments(props.item)"> folder </v-icon> </td> </tr> </template> </v-data-table> </v-card> <br> <v-btn @click="showAdd" color="primary" dark>{{ $t('btnNew')}} <v-icon dark right>add_circle</v-icon> </v-btn> <v-snackbar v-model="showTopMessage" :timeout="4000" :top="true" :color="topMessageColor" > {{ topMessage }} </v-snackbar> <v-dialog v-model="editDialog" persistent max-width="900px"> <edit-user :user="selectedUser" @save="onUserSaved" @cancel="editDialog = false"> </edit-user> </v-dialog> <v-dialog v-model="documentDialog" persistent max-width="900px"> <user-document :user="selectedUser" @document-saved="onDocumentSaved" @cancel="documentDialog = false"> </user-document> </v-dialog> </div> </template> <script> import axios from 'axios' import moment from "moment"; import bus from "../../bus"; import UserDocument from './UserDocument' import EditUser from './EditUser' let self export default { data () { self = this return { pagination: { sortBy: 'fullName', rowsPerPage: 10 }, search: '', headers: [ { text: this.$t('userMainHeaders[0]'), align: 'left', value: 'fullName' }, { text: this.$t('userMainHeaders[1]'), value: 'username' }, { text: this.$t('userMainHeaders[2]'), value: 'status' }, { text: this.$t('userMainHeaders[3]'), value: '', sortable: false }, ], users: [], selected: [], showProgress:true, valid: false, selectedUser: {}, showTopMessage: false, topMessage: '', topMessageColor: 'info', editDialog: false, documentDialog: false, assignDialog: false, editing:false } }, components: { 'UserDocument': UserDocument, 'EditUser': EditUser }, methods: { getUsers() { this.editing = false this.showProgress = true axios .get('/api/users') .then(response => { this.users = response.data this.showProgress = false }) .catch(function (error) { console.log(error); }); }, changeSort (column) { if (this.pagination.sortBy === column) { this.pagination.descending = !this.pagination.descending } else { this.pagination.sortBy = column this.pagination.descending = false } }, showDocuments(item){ this.selectedUser = Object.assign({}, item) this.documentDialog = true }, showAdd() { this.selectedUser = { id: '', fullName: '', username: '', password: '' } this.editDialog = true }, editItem (item) { this.selectedUser = Object.assign({}, item) this.editDialog = true; }, onDocumentSaved() { this.topMessageColor = 'success' this.topMessage = "El documento fue guardado." this.showTopMessage = true }, onUserSaved() { this.topMessageColor = 'success' this.topMessage = "Los cambios al usuario fueron guardados." this.showTopMessage = true this.editDialog = false this.getUsers() } }, mounted: function () { this.$nextTick(function () { this.getUsers() }) } } </script> <style> </style>
import { isEqual, pull } from 'lodash-es' import { PreferenceParser } from '../classes/preference-parser' type GamepadButtonMap = Map<string, string> const buttonsMaps = new Map<string, GamepadButtonMap>() function updateButtonsMaps() { const gamepadMappings = PreferenceParser.get('gamepadMappings') for (const gamepadMapping of gamepadMappings) { const gamepadButtonMap = new Map(Object.entries(gamepadMapping.mapping)) buttonsMaps.set(gamepadMapping.name, gamepadButtonMap) } } PreferenceParser.onUpdated(({ name }) => { if (name === 'gamepadMappings') { updateButtonsMaps() } }) updateButtonsMaps() type GamepadButtonStatus = { -readonly [key in keyof GamepadButton]: GamepadButton[key] } const gamepadsStatus: GamepadButtonStatus[][] = [] function updateGamepadStatus({ gamepad, gamepadStatus }) { const { buttons } = gamepad const gamepadButtonsEntries = [...buttons.entries()] // run callback functions if certain buttons are pressed / touched // pressed in this loop const pressedButtonIndicies: number[] = [] // pressed before or in this loop, includes `pressedButtonIndicies` const pressedForTimesButtonIndicies: number[] = [] for (const [buttonIndex, button] of gamepadButtonsEntries) { const prevbuttonStatus = gamepadStatus[buttonIndex] if (button.pressed) { pressedForTimesButtonIndicies.push(buttonIndex) if (!prevbuttonStatus?.pressed) { pressedButtonIndicies.push(buttonIndex) } } } if (pressedForTimesButtonIndicies.length > 0) { pressButtonsCallback({ gamepad, pressedForTimesButtonIndicies, pressedButtonIndicies }) } // update button status record for using in next loop for (const [buttonIndex, button] of gamepadButtonsEntries) { const buttonStatus = gamepadStatus[buttonIndex] ?? { pressed: false, touched: false, value: 0 } buttonStatus.pressed = button.pressed buttonStatus.touched = button.touched buttonStatus.value = button.value gamepadStatus[buttonIndex] = buttonStatus } } function updateGamepadsStatus({ index, gamepad }) { const gamepadStatus = gamepadsStatus[index] ?? [] updateGamepadStatus({ gamepad, gamepadStatus }) gamepadsStatus[index] = gamepadStatus } export function gamepadPollLoop() { if (document.hasFocus()) { const gamepads = navigator.getGamepads() for (const [index, gamepad] of gamepads.entries()) { if (gamepad) { updateGamepadsStatus({ index, gamepad }) } } } requestAnimationFrame(gamepadPollLoop) } interface PressButtonListenerFunctionParam { gamepad?: Gamepad pressedForTimesButtonNames?: string[] pressedButtonNames?: string[] pressedForTimesButtonIndicies?: number[] pressedButtonIndicies?: number[] } export type PressButtonListenerFunction = (param: PressButtonListenerFunctionParam) => void interface PressButtonListener { buttonNames: string[] originalCallback: any listener: PressButtonListenerFunction } const pressButtonListeners: PressButtonListener[] = [] interface pressButtonsCallbackParams { gamepad: Gamepad pressedForTimesButtonIndicies: number[] pressedButtonIndicies: number[] } function pressButtonsCallback({ gamepad, pressedButtonIndicies, pressedForTimesButtonIndicies, }: pressButtonsCallbackParams) { const buttonsMap = buttonsMaps.get(gamepad.id) ?? buttonsMaps.get('') if (!buttonsMap) { return } const pressedForTimesButtonNames = pressedForTimesButtonIndicies.map((i) => buttonsMap.get(`${i}`) as string) const pressedButtonNames = pressedButtonIndicies.map((i) => buttonsMap.get(`${i}`) as string) if (pressedForTimesButtonNames.length > 0) { for (const { listener } of pressButtonListeners) { listener({ gamepad, pressedForTimesButtonNames, pressedButtonNames, pressedForTimesButtonIndicies, pressedButtonIndicies, }) } } } export function onPressAnyButton(callback: PressButtonListenerFunction) { if (typeof callback === 'function') { pressButtonListeners.push({ buttonNames: [], originalCallback: callback, listener(params) { const { pressedForTimesButtonIndicies, pressedButtonIndicies } = params if (pressedForTimesButtonIndicies && pressedButtonIndicies) { callback(params) } }, }) } } export function offPressAnyButton(callback: PressButtonListenerFunction) { for (const pressButtonListener of pressButtonListeners) { if (callback === pressButtonListener.originalCallback) { pull(pressButtonListeners, pressButtonListener) } } } export function onPressButtons(buttonNames: string[], callback) { if (typeof callback === 'function') { pressButtonListeners.push({ buttonNames, originalCallback: callback, listener({ pressedForTimesButtonNames, pressedButtonNames }) { if ( buttonNames.every((buttonName) => pressedForTimesButtonNames?.includes(buttonName)) && buttonNames.some((buttonName) => pressedButtonNames?.includes(buttonName)) ) { callback() } }, }) } } export function onPressButton(buttonName: string, callback) { onPressButtons([buttonName], callback) } export function offPressButtons(buttonNames: string[], callback) { for (const pressButtonListener of pressButtonListeners) { if (isEqual(buttonNames, pressButtonListener.buttonNames) && callback === pressButtonListener.originalCallback) { pull(pressButtonListeners, pressButtonListener) } } } export function offPressButton(buttonName: string, callback) { offPressButtons([buttonName], callback) } function startGamepadPollLoop() { const gamepads = navigator.getGamepads?.() if (gamepads?.some(Boolean)) { gamepadPollLoop() } } window.addEventListener('gamepadconnected', () => { startGamepadPollLoop() }) startGamepadPollLoop()
import React from 'react'; import {useState, useEffect} from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { getDogs,filterByOrigin, orderByName, orderByWeight, getTemperaments, filterByTemperament } from '../actions'; import { Link } from 'react-router-dom'; import Card from './Card'; import Pages from './Pages'; import SearchBar from './SearchBar'; import puppy1 from '../images/all4.png'; import puppy2 from '../images/all3.png'; export default function Home (){ const dispatch = useDispatch(); const allDogs = useSelector(state => state.dogs); const [render, setRender] = useState(''); const [currentPage, setCurrentPage] = useState(1); const [dogsPerPage] = useState(8); const indexOfLastDog = currentPage * dogsPerPage; // 8 * 1 = 8 const indexOfFirstDog = indexOfLastDog - dogsPerPage; // 8 - 8 = 0 const currentDogs = allDogs.slice(indexOfFirstDog, indexOfLastDog); const temperaments = useSelector(state => state.temperaments); const pages = (pageNumber=>( setCurrentPage(pageNumber) )) useEffect(() => { dispatch(getDogs()) },[dispatch]) useEffect(() => { dispatch(getTemperaments()) } ,[dispatch]) function handleClick(e){ e.preventDefault(); dispatch(getDogs()); } function handleFilterOrigin(e){ e.preventDefault(); setCurrentPage(1) dispatch(filterByOrigin(e.target.value)); } function handleFilterTemperament(e){ e.preventDefault(); setCurrentPage(1) dispatch(filterByTemperament(e.target.value)); } function handleSortByName(e){ e.preventDefault(); dispatch(orderByName(e.target.value)); setRender(`Ordenado ${e.target.value}`); setCurrentPage(1); } function handleSortByWeight(e){ e.preventDefault(); dispatch(orderByWeight(e.target.value)); setCurrentPage(1); setRender(`Ordenado ${e.target.value}`); } return( <div className='main'> <header> <img className="imgbk"src={puppy1} alt="puppies" /> <div className='main'> <h1>Dog breed database</h1> <p>get information about dog breeds</p> </div> <img className="imgbk"src={puppy2} alt="puppies" /> </header> {/* <Link className='link_to' to='/create'>new Breed</Link> */} <div className='back-head'> <div className='filters'> <button className='button' onClick={e=>{handleClick(e)}}>Reset</button> <Link className='link_to' to='/create'><button className='button'>new breed</button></Link> <div className='filter-item sel'> <div>Sort by breed name</div> <select onChange={e => handleSortByName(e)}> <option value='x'> Select</option> <option value='asc'> A-Z</option> <option value='desc'>Z-A</option> </select> </div> <div className='filter-item sel'> <div>Sort by weight </div> <select onChange={e=> handleSortByWeight(e)}> <option value='x'> Select</option> <option value='asc'> Min-Max</option> <option value='desc'>Max-Min</option> </select> </div> <div className='filter-item sel'> <div>Filter by origin</div> <select onChange={e => handleFilterOrigin(e)} > <option value='all'>All breeds</option> <option value='api'>Registered breeds</option> <option value='created'>Created breeds</option> </select> </div> <div className='filter-item sel'> <div>Filter by temperament</div> <select onChange={e => handleFilterTemperament(e)} > <option key={0} value='all'>All temperaments</option> {temperaments?.sort(function (a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }).map(el => { return ( <option key={el.id} value={el.name}>{el.name}</option> ) })} </select> </div> </div> <div className='filter-item sbp'> <SearchBar page1={setCurrentPage}/> <Pages dogsPerPage={dogsPerPage} allDogs={allDogs.length} pages={pages} current ={currentPage}/> </div> </div> <div className='cards'> {allDogs.length===0?<div className='landing'>Loading...</div>:''} {currentDogs?.map((dog) => { return ( <div className='card' key={dog.id} > <Link to= {"/home/"+dog.id}> <Card name={dog.name} img={dog.image} temperaments={dog.temperaments} wMin={dog.weightMin} wMax={dog.weightMax} created={dog.createdInDb}/> </Link> </div> ); })} </div> </div> )}
import 'package:chatkuy/constants/app_constant.dart'; import 'package:chatkuy/presentation/home/page/home_page.dart'; import 'package:chatkuy/presentation/profile/profile_page.dart'; import 'package:chatkuy/widgets/snackbar_widget.dart'; import 'package:flutter/material.dart'; class BasePageArg { final BasePageRoute route; const BasePageArg({required this.route}); } enum BasePageRoute { chat, profile, } class BasePage extends StatefulWidget { final BasePageArg argument; const BasePage({super.key, required this.argument}); @override State<BasePage> createState() => _BasePageState(); } class _BasePageState extends State<BasePage> { final List<IconData> _icon = [Icons.group, Icons.settings]; int _selectedIndex = 0; final List<String> _titleMenu = ['Chat', 'Profil']; DateTime preBackPress = DateTime.now(); void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override void initState() { _selectedIndex = _convertToIndex(); super.initState(); } int _convertToIndex() { switch (widget.argument.route) { case BasePageRoute.profile: return _selectedIndex = 1; default: return _selectedIndex = 0; } } // BasePageRoute _convertToIndex(int index) { // switch (widget.argument.route) { // case BasePageRoute.profile: // _selectedIndex = 1; // break; // default: // _selectedIndex = 0; // break; // } // } Widget _buildNavigator() { return BottomNavigationBar( selectedItemColor: AppColor.primaryColor, currentIndex: _selectedIndex, onTap: _onItemTapped, items: List.generate( _titleMenu.length, (index) => BottomNavigationBarItem( label: _titleMenu[index], icon: Icon(_icon[index]), ), ), ); // return Container( // child: Row( // children: List.generate( // _titleMenu.length, // (index) => BottomNavigationBarItem( // label: _titleMenu[index], // icon: Icon(_icon[index]), // ), // ), // ), // ); } Future<bool> _onWillPop() async { final timegap = DateTime.now().difference(preBackPress); final cantExit = timegap >= const Duration(seconds: 3); preBackPress = DateTime.now(); if (cantExit) { showSnackbar( context, Colors.green, 'Tekan sekali lagi untuk menutup aplikasi'); return false; } else { return true; } } Widget _buildPages() { final List<Widget> pages = <Widget>[ const HomePage(), const ProfilePage(), ]; return pages[_selectedIndex]; } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: _onWillPop, child: Scaffold( body: _buildPages(), bottomNavigationBar: _buildNavigator(), ), ); } }
package com.hendisantika.springbootvirtualthreads.controller; import com.hendisantika.springbootvirtualthreads.domain.Book; import com.hendisantika.springbootvirtualthreads.domain.Order; import com.hendisantika.springbootvirtualthreads.domain.User; import com.hendisantika.springbootvirtualthreads.dto.OrderDTO; import com.hendisantika.springbootvirtualthreads.repository.BookRepository; import com.hendisantika.springbootvirtualthreads.repository.OrderRepository; import com.hendisantika.springbootvirtualthreads.repository.UserRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.UUID; /** * Created by IntelliJ IDEA. * Project : spring-boot-virtual-threads * User: hendisantika * Email: hendisantika@gmail.com * Telegram : @hendisantika34 * Date: 11/25/23 * Time: 11:25 * To change this template use File | Settings | File Templates. */ @RestController @RequestMapping("/orders") @RequiredArgsConstructor @Slf4j public class OrderController { private final UserRepository userRepository; private final BookRepository bookRepository; private final OrderRepository orderRepository; @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @Transactional public ResponseEntity<OrderDTO> addOrder(@RequestParam("bookIsbn") String bookIsbn, @RequestParam("firstName") String firstName) { UUID uuid = UUID.randomUUID(); log.info("addOrder() {} running", uuid); User user = userRepository.findByFirstName(firstName); Book book = bookRepository.findByIsbn(bookIsbn); log.info("addOrder() {} I've got user and book", uuid); Order order = new Order(); order.setUser(user); order.setQuantity(1); order.setBook(book); order = orderRepository.save(order); OrderDTO orderDTO = new OrderDTO(order.getOrderId(), order.getQuantity(), book.getBookId(), user.getUserId()); log.info("addOrder() {} executed", uuid); return ResponseEntity.ok(orderDTO); } }
package com.library.library; import com.fasterxml.jackson.core.JsonProcessingException; import com.library.library.controller.CategoryController; import com.library.library.entity.Category; import com.library.library.service.CategoryService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RunWith(SpringRunner.class) public class CategoryControllerTest { @InjectMocks private CategoryController categoryController; @Mock private RequestAttributes requestAttributes; @Mock private CategoryService categoryService; private MockMvc mockMvc; @Before public void setup(){ RequestContextHolder.setRequestAttributes(requestAttributes); this.mockMvc = MockMvcBuilders.standaloneSetup(categoryController).build(); } @Test public void getCategoryList() throws Exception { String categoryName = "category 1"; Long id = 3L; List<Category> categoryList = new ArrayList<>(); Mockito.when(categoryService.getAllCategories()).thenReturn(categoryList); Assert.assertNotNull(categoryController.getCategoryList()); Assert.assertNotNull(categoryList); Assert.assertNotNull(categoryName); Assert.assertNotNull(id); } @Test public void getCategoryById(){ String categoryName = "category 1"; Long id = 3L; Category category = new Category(1L,"category 1"); Mockito.when(categoryService.getCategoryById(id)).thenReturn(category); Assert.assertNotNull(categoryController.getCategoryById(id)); Assert.assertNotNull(categoryName); Assert.assertNotNull(id); Assert.assertNotNull(category); } @Test public void deleteCategoryById() throws JsonProcessingException { String categoryName = "Category 1"; Long id = 3L; Mockito.when(categoryService.deleteCategory(id)).thenReturn(String.valueOf(Optional.empty())); Assert.assertNotNull(categoryController.deleteCategory(id)); Assert.assertNotNull(categoryName); Assert.assertNotNull(id); } @Test public void addCategory() throws JsonProcessingException { String categoryName = "category 2"; Long idCategory = 3L; Category category = new Category(1L,"category test"); Mockito.when(categoryService.addCategory(category)).thenReturn("Category added successfully"); Assert.assertNotNull(categoryController.addCategory(category)); Assert.assertNotNull(categoryName); Assert.assertNotNull(idCategory); Assert.assertNotNull(category); } @Test public void updateCategory() throws JsonProcessingException { String categoryName = "category 2"; Category category = new Category(1L,"category test"); Mockito.when(categoryService.updateCategory(1L,category)).thenReturn("The Category with id 1 is updated successfully"); Assert.assertNotNull(categoryController.updateCategory(1L,category)); Assert.assertNotNull(categoryName); Assert.assertNotNull(category); } }
import signal import sys import threading from termcolor import colored import network_utils # Основное меню def main_menu(): while True: print(colored("\n=== Меню захвата хэндшейка ===", "yellow")) print(colored("1. Автоматическое определение сетевой карты", "cyan")) print(colored("2. Включить режим монитора", "cyan")) print(colored("3. Выключить режим монитора", "cyan")) print(colored("4. Обновить интерфейсы и их названия", "cyan")) print(colored("5. Поиск сетей", "cyan")) print(colored("6. Захват хэндшейка", "cyan")) print(colored("0. Выход", "cyan")) choice = input(colored("Введите ваш выбор: ", "green")) if choice == "1": interface = network_utils.auto_detect_network_card() if interface: print(colored(f"Сетевая карта {interface} обнаружена.", "green")) elif choice == "2": interface = network_utils.choose_network_card() if interface: network_utils.enable_monitor_mode(interface) elif choice == "3": interface = network_utils.choose_network_card() if interface: network_utils.disable_monitor_mode(interface) elif choice == "4": network_utils.update_interfaces() elif choice == "5": interface = network_utils.choose_network_card() if interface: network_utils.search_networks(interface) elif choice == "6": interface = network_utils.choose_network_card() if interface: bssid = input(colored("Введите BSSID выбранной сети: ", "green")) channel = input(colored("Введите требуемый канал: ", "green")) path = input(colored("Введите путь для сохранения хэндшейка: ", "green")) filename = input(colored("Введите имя файла для сохранения хэндшейка: ", "green")) # Создаем объект события capture_event = threading.Event() # Создаем поток для захвата хэндшейка capture_thread = threading.Thread(target=network_utils.capture_handshake, args=(interface, bssid, channel, path, filename, capture_event)) # Создаем поток для функции deauthenticate_clients deauth_thread = threading.Thread(target=network_utils.deauthenticate_clients, args=(interface, bssid, capture_event)) # Запускаем потоки параллельно capture_thread.start() deauth_thread.start() # Ждем завершения захвата хэндшейка capture_thread.join() # Останавливаем отключение пользователей после завершения захвата хэндшейка capture_event.clear() deauth_thread.join() elif choice == "0": sys.exit(colored("Выход из программы.", "yellow")) else: print(colored("Неверный выбор. Пожалуйста, попробуйте снова.", "red")) if __name__ == "__main__": signal.signal(signal.SIGINT, signal.SIG_IGN) # Игнорируем сигнал SIGINT (Ctrl+C) в основном цикле программы while True: main_menu()
import { useState } from 'react' // import './App.css' import './componentscss/Header.css' import '@chatscope/chat-ui-kit-styles/dist/default/styles.min.css'; import { MainContainer, ChatContainer, MessageList, Message, MessageInput, TypingIndicator } from '@chatscope/chat-ui-kit-react'; const API_KEY=process.env.REACT_APP_GPT_KEY // const API_KEY="" // use your own OpenAI api-key here const systemMessage = { "role": "system", "content": "Explain things like you are a cutomer service representative at an electornics cervice center, if asked about how time taken for a paticular part to be rapaired answer it as approximately between 3 to 6 days, if asked about price use genereal avialable price of that part in indian rupee" } function Chatmodel() { const [messages, setMessages] = useState([ { message: "Hello dear! Ask me anything!", sentTime: "just now", sender: "ChatGPT" } ]); const [isTyping, setIsTyping] = useState(false); // const additionalmessage='Generate all related keywords from the given propts to match to our e commerce database'; const handleSend = async (message) => { const newMessage = { message: message, direction: 'outgoing', sender: "user" }; const newMessages = [...messages, newMessage]; setMessages(newMessages); // Initial system message to determine ChatGPT functionality // How it responds, how it talks, etc. setIsTyping(true); console.log(process.env); await processMessageToChatGPT(newMessages); }; async function processMessageToChatGPT(chatMessages) { // messages is an array of messages // Format messages for chatGPT API // API is expecting objects in format of { role: "user" or "assistant", "content": "message here"} // So we need to reformat let apiMessages = chatMessages.map((messageObject) => { let role = ""; if (messageObject.sender === "ChatGPT") { role = "assistant"; } else { role = "user"; } return { role: role, content: messageObject.message} }); const apiRequestBody = { "model": "gpt-3.5-turbo", "messages": [ systemMessage, ...apiMessages ] } await fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Authorization": "Bearer " + API_KEY, "Content-Type": "application/json" }, body: JSON.stringify(apiRequestBody) }).then((data) => { return data.json(); }).then((data) => { console.log(data); setMessages([...chatMessages, { message: data.choices[0].message.content, sender: "ChatGPT" }]); setIsTyping(false); }); } return ( <div className="App"> <div className="rounded-md" style={{ position:"relative", height: "650px", width: "700px",padding:'0px 20px',bordeRadius:'8px' }}> <MainContainer> <ChatContainer> <MessageList scrollBehavior="smooth" typingIndicator={isTyping ? <TypingIndicator content="Loading...." /> : null} > {messages.map((message, i) => { console.log(message) return <Message key={i} model={message} /> })} </MessageList> <MessageInput placeholder="Type message here" onSend={handleSend} /> </ChatContainer> </MainContainer> </div> </div> ) } export default Chatmodel
import React from "react"; import styles from "./Potfolios.module.css"; import { useRecoilState } from "recoil"; import { categoryState } from "../../atoms"; // Recoil에서 정의한 상태 import Resume from "./Resume"; import { useNavigate } from "react-router-dom"; // useNavigate 임포트 function Portfolios({ resumes }) { const [categoryNum, setCategoryNum] = useRecoilState(categoryState); // Recoil 상태와 setter 함수 불러오기 const navigate = useNavigate(); // useNavigate를 호출하여 navigate 함수를 생성 const localStorageUserId = localStorage.getItem("userId"); // localStorage에서 userId 가져옴 const writePortfoliohandler = () => { navigate(`/user/${localStorageUserId}/mypage/resumeMaking`); // localStorageUserId 사용 }; const handleDoubleClick = (resumeId) => { navigate(`/user/${localStorageUserId}/mypage/resumes/${resumeId}`); ///user/:userId/resume/:resumeId }; return ( <div className={styles.mainContainer}> <div className={styles.titleButton}> <h2> 이력서 목록 </h2> <button onClick={writePortfoliohandler}>이력서 작성</button> </div> <div className={styles.resumeContainer}> {resumes.map((resume, index) => ( <Resume key={index} onDoubleClcik={() => handleDoubleClick(resume.id)} resume={resume} /> ))} </div> </div> ); } export default Portfolios;
import './App.css'; import React, { Component } from 'react' import { Routes , Route, Navigate, useNavigate } from 'react-router-dom'; import { useState ,useEffect} from 'react'; import Navbar from './Navbar'; import Notfound from './Notfound'; import Movies from './Movies'; import People from './People' import Home from './Home'; import Tv from './Tv' import Footer from './Footer' import Login from './Login' import Register from './Register' import jwtDecode from 'jwt-decode' import TvDetails from'./TvDetails'; import MovieDetails from './MovieDetails'; import PeopleDetails from './PeopleDetails'; function App() { let navigate=useNavigate() const [userData, setuserData] = useState(null) function saveUserData(){ let encodedToken=localStorage.getItem("userToken") let decodedToken=jwtDecode(encodedToken) setuserData(decodedToken) console.log(decodedToken) } function logout(){ setuserData(null) localStorage.removeItem("userToken") navigate('/login') } useEffect(() => { if(localStorage.getItem("userToken")){ saveUserData() } }, []) function ProtectedRoute(props){ if(localStorage.getItem("userToken")===null){ return <Navigate to='/login'/> } else{ return props.children; } } return ( <div> <Navbar logout={logout} userData={userData}/> <div className="container"> <Routes> <Route path="" element={<ProtectedRoute><Home/></ProtectedRoute> }/> <Route path="home" element={<ProtectedRoute><Home/></ProtectedRoute> }/> <Route path="movies" element={<ProtectedRoute><Movies/></ProtectedRoute>}/> <Route path="people" element={<ProtectedRoute><People/></ProtectedRoute>}/> <Route path="tv" element={<ProtectedRoute><Tv/></ProtectedRoute>}/> <Route path="movieDetails" element={<ProtectedRoute><MovieDetails/></ProtectedRoute>}> <Route path=":id" element={<ProtectedRoute><MovieDetails/></ProtectedRoute>}/> </Route> <Route path="tvDetails" element={<ProtectedRoute><TvDetails/></ProtectedRoute>}> <Route path=":id" element={<ProtectedRoute><TvDetails/></ProtectedRoute>}/> </Route> <Route path="personDetails" element={<ProtectedRoute><PeopleDetails/></ProtectedRoute>}> <Route path=":id" element={<ProtectedRoute><PeopleDetails/></ProtectedRoute>}/> </Route> <Route path="login" element={<Login saveUserData={saveUserData}/>}/> <Route path="register" element={<Register/>}/> <Route path="*" element={<Notfound/>}/> </Routes> </div> <Footer/> </div> ) } export default App;
export type NTPVersion = 3 | 4; export interface NTPData { /** * 2-bit integer warning of an impending leap second to be inserted or deleted * in the last minute of the current month with values defined in Figure 9. */ leapIndicator: number; /** * 3-bit integer representing the NTP version number */ version: number; /** * 3-bit integer representing the mode, with values defined in Figure 10. */ mode: number; /** * 8-bit integer representing the stratum, with values defined in Figure 11. */ stratum: number; /** * 8-bit signed integer representing the maximum interval between * successive messages, in log2 seconds. */ pollInterval: number; /** * 8-bit signed integer representing the precision of the system clock, in log2 seconds. */ precision: number; /** * Total round-trip delay to the reference clock, in NTP short format. */ rootDelay: Buffer; /** * Total dispersion to the reference clock, in NTP short format. */ rootDispersion: Buffer; /** * 32-bit code identifying the particular server or reference clock. */ referenceIdentifier: Buffer; /** * Time when the system clock was last set or corrected, in NTP timestamp format. */ referenceTimestamp: Date; /** * Time at the client when the request departed for the server, in NTP timestamp format. */ originTimestamp: Date; /** * Time at the server when the request arrived from the client, in NTP timestamp format. */ receiveTimestamp: Date; /** * Time at the server when the response left for the client, in NTP timestamp format. */ transmitTimestamp: Date; /** * The extension fields are used to add optional capabilities */ extensionField1: Buffer; extensionField2: Buffer; /** * 32-bit unsigned integer used by the client and server to designate a secret 128-bit MD5 key. */ keyIdentifier: Buffer; /** * 128-bit MD5 hash computed over the key followed by the NTP packet header and extensions fields * (but not the Key Identifier or Message Digest fields). */ digest: Buffer; }
# © Copyright Databand.ai, an IBM Company 2022 import contextlib import logging import typing from abc import ABCMeta, abstractmethod from itertools import chain import six from dbnd._core.current import get_databand_run from dbnd._core.errors.errors_utils import log_exception from dbnd._core.log.logging_utils import TaskContextFilter from dbnd._core.task_build.task_context import task_context from dbnd._core.utils.basics.nested_context import nested if typing.TYPE_CHECKING: from typing import Any, Dict, Optional from dbnd._core.context.databand_context import DatabandContext from dbnd._core.parameter.parameter_value import Parameters from dbnd._core.settings import DatabandSettings from dbnd._core.task.base_task import _BaseTask from dbnd._core.task_ctrl.task_dag import _TaskDagNode from dbnd._core.task_run.task_run import TaskRun logger = logging.getLogger(__name__) class TaskSubCtrl(object): def __init__(self, task): super(TaskSubCtrl, self).__init__() self.task = task # type: _BaseTask @property def dbnd_context(self): # type: (TaskSubCtrl) -> DatabandContext return self.task.dbnd_context @property def ctrl(self): # type: (TaskSubCtrl) -> _BaseTaskCtrl return self.task.ctrl @property def task_id(self): # type: (TaskSubCtrl) -> str return self.task.task_id @property def task_dag(self): # type: (TaskSubCtrl) -> _TaskDagNode return self.ctrl._task_dag @property def params(self): # type: () -> Parameters return self.task._params @property def settings(self): # type: ()-> DatabandSettings return self.task.settings def get_task_by_task_id(self, task_id): return self.dbnd_context.task_instance_cache.get_task_by_id(task_id) def __repr__(self): return "%s.%s" % (self.task.task_id, self.__class__.__name__) @six.add_metaclass(ABCMeta) class _BaseTaskCtrl(TaskSubCtrl): """ task.ctrl Main dispatcher for task sub-actions 1. used by Tracking via TrackingTaskCtrl """ def __init__(self, task): super(_BaseTaskCtrl, self).__init__(task) from dbnd._core.task_ctrl.task_dag import _TaskDagNode # noqa: F811 from dbnd._core.task_ctrl.task_descendant import ( TaskDescendants as _TaskDescendants, ) self._task_dag = _TaskDagNode(task) self.descendants = _TaskDescendants(task) # will be assigned by the latest Run self.last_task_run = None # type: Optional[TaskRun] self.force_task_run_uid = None # force task run uid def _initialize_task(self): return @property def task_run(self): # type: ()-> TaskRun run = get_databand_run() return run.get_task_run(self.task.task_id) @contextlib.contextmanager def task_context(self, phase): # we don't want logs/user wrappers at this stage with nested( task_context(self.task, phase), TaskContextFilter.task_context(self.task.task_id), ): yield @abstractmethod def should_run(self): pass def io_params(self): return chain(self.task_outputs.values(), self.task_inputs.values()) @property @abstractmethod def task_inputs(self): # type: () -> Dict[str, Dict[str][Any]] raise NotImplementedError() @property @abstractmethod def task_outputs(self): # type: () -> Dict[str, Dict[str][Any]] raise NotImplementedError() class TrackingTaskCtrl(_BaseTaskCtrl): def __init__(self, task): from dbnd._core.task.tracking_task import TrackingTask assert isinstance(task, TrackingTask) super(TrackingTaskCtrl, self).__init__(task) @property def task_inputs(self): return dict(dict()) @property def task_outputs(self): return dict(dict()) def should_run(self): return True def banner(self, msg, color=None, task_run=None): try: from dbnd._core.task_ctrl.task_visualiser import _TaskBannerBuilder builder = _TaskBannerBuilder(task=self.task, msg=msg, color=color) return builder.build_tracking_banner(task_run=task_run) except Exception as ex: log_exception( "Failed to calculate banner for '%s'" % self.task_id, ex, non_critical=True, ) return msg + (" ( task_id=%s)" % self.task_id)
"use client" import Link from "next/link" import { usePathname } from "next/navigation" interface NavLink { path: string name: string } const Navigation = ({ navLinks }: { navLinks: NavLink[] }) => { const path = usePathname() return ( <nav className="flex w-full gap-3 text-white px-5 py-3 z-50 text-xl bg-black"> <div className="flex w-1/4" /> <div className="flex w-2/4 gap-10 justify-center"> {navLinks?.map((link, index) => ( <Link href={link.path} key={index} className={path === link.path ? "underline underline-offset-8" : ""} > {link.name} </Link> ))} </div> <div className="flex w-1/4 gap-10 justify-end"> <Link href="/cart"> <i className="fas fa-shopping-cart" /> </Link> <Link href="/login"> <i className="fa-solid fa-user" /> </Link> </div> </nav> ) } export default Navigation
import React from 'react'; import Button from '../../../components/reusable/button'; const MailDetails = ({user,mail,mailUser,handleMainClick,receptionFromListMails}) => { const createdDate = new Date(mail.created_at); const date = createdDate.toLocaleDateString(); const time = createdDate.toLocaleTimeString(); return ( <div className="w-full flex justify-center mx-auto -mt-16 bg-gray-100" style={{height : '88vh'}}> {/* MailSideBar */} <div className="w-1/4 flex flex-col bg-gray-100 pt-6"> <div className="w-full flex justify-center"> <Button buttonText={user.lang=="eng" ? "New mail" : (user.lang=="fr" ? "Nouveau message" : "رسالة جديدة")} variableClassName="w-2/3 py-3 flex items-center justify-start"/> </div> <ul className="flex flex-col items-start w-full mx-12 mt-6"> <li className={`flex items-center ${user.lang=="عربي" ? "justify-end" : "justify-start"} w-48 gap-4 cursor-pointer py-3 px-4 rounded-lg hover:bg-slate-300 ${receptionFromListMails ? "bg-slate-300" : ""} `} onClick={()=>{handleMainClick("ListMails",true)}}> <a className={`text-sm text-slate-800 ${receptionFromListMails ? "font-medium" : ""}`} > {user.lang=="eng" ? "Reception box" : (user.lang=="fr" ? "Boite de reception" : "صندوق الاستقبال")} </a> </li> <li className={`flex items-center ${user.lang=="عربي" ? "justify-end" : "justify-start"} w-48 gap-4 cursor-pointer py-3 px-4 rounded-lg hover:bg-slate-300 ${!receptionFromListMails ? "bg-slate-300" : ""}`} onClick={()=>{handleMainClick("ListMails",false)}}> <a className={`text-sm text-slate-800 ${!receptionFromListMails ? "font-medium" : ""}`}> {user.lang=="eng" ? "Mails sent" : (user.lang=="fr" ? "Messages envoyés" : "رسالة مرسلة")} </a> </li> </ul> </div> {/* MailBox */} <div className="w-3/4 flex justify-center"> <div className="flex flex-col w-4/5 p-6 bg-main-bg border-gray-100 rounded-xl" style={{height:"80vh"}}> <div className="mx-14 mt-14"> <h2 className="text-lg">{mail.subject}</h2> </div> <div className="mt-6 flex items-center justify-between w-full"> <div className="flex items-center"> {!receptionFromListMails && ( <span className="font-semibold text-sm mr-4 mx-14">To </span> )} <img className='w-10 bg-slate-700 rounded-full mr-4' src={`http://localhost:8000/storage/${mailUser.userProfil}`}/> <span className="font-semibold text-sm mr-1">{mailUser.lastName} {mailUser.firstName} </span> <span className='text-xsm text-gray-600'>{"<"+mailUser.email+">"}</span> </div> <div> <span className='text-xsm text-gray-600'>{date + " " + time}</span> </div> </div> <p className='mt-6 mx-14 text-sm'>{mail.content}</p> <div className='w-full mt-6 mx-6'> {receptionFromListMails && ( <button type="submit" className="text-white bg-slate-800 hover:bg-gray-700 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-4 py-2 text-center m-8" onClick={()=>{handleMainClick("NewMail",mailUser)}}>Respond</button> )} </div> </div> </div> </div> ); }; export default MailDetails;
import { createContext , useState } from "react"; export const CartContext = createContext({}) const {Provider} = CartContext export const CartProvider = ({defaultValue = [], children }) => { const [cart, setCart] = useState(defaultValue); const clearCart = () =>{ setCart([]) } const addToCart = (item, cantidad) =>{ console.log('item:' + item) console.log('cantidad:' + cantidad) if (isInCart(item.id)){ const newCart = [...cart] for (const elemento of newCart){ if(elemento.item.id === item.id){ elemento.cantidad = elemento.cantidad + cantidad } } setCart(newCart) }else{ setCart( [ ...cart,{ item: item, cantidad: cantidad } ] ) } } const isInCart = (id) =>{ return cart.find((elemento)=> elemento.item.id === id) } const getTotal=()=>{ let total = 0 cart.forEach((element)=>{ total = total + (element.cantidad * element.item.precio) }) return total; } const totalCantidad =()=>{ let cantidad = 0 cart.forEach((element)=>{ cantidad += element.cantidad }) return cantidad; } const removeFromCart = (id) =>{ const newCart = [...cart].filter(elemento=> elemento.item.id !== id) setCart(newCart) } const context = { cart, clearCart, addToCart, removeFromCart, getTotal, totalCantidad, } return ( <Provider value={context}> {children} </Provider> ) }
package gr.hua.dit.ds.projectDSBackend.entity; import jakarta.persistence.*; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "products") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @NotBlank @Size(max = 50) private String name; private double price; @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}) @JoinTable(name = "farmer_products", joinColumns = @JoinColumn(name = "farmer_id"), inverseJoinColumns = @JoinColumn(name = "product_id")) private Set<Farmer> farmers = new HashSet<>(); @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}) @JoinTable(name = "region_products", joinColumns = @JoinColumn(name = "region_id"), inverseJoinColumns = @JoinColumn(name = "product_id")) private Set<Region> regions = new HashSet<>(); public Product() { } public Product(String name, double price) { this.name = name; this.price = price; } public Product(String name, double price, Set<Farmer> farmers, Set<Region> regions) { this.name = name; this.price = price; this.farmers = farmers; this.regions = regions; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Set<Farmer> getFarmers() { return farmers; } public void setFarmers(Set<Farmer> farmers) { this.farmers = farmers; } public Set<Region> getRegions() { return regions; } public void setRegions(Set<Region> regions) { this.regions = regions; } public Integer getId() { return id; } @Override public String toString() { return "Product{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + ", farmers=" + farmers + ", regions=" + regions + '}'; } }
package org.apache.commons.lang3.time; public class DurationFormatUtils { public DurationFormatUtils() { super(); } public static final java.lang.String ISO_EXTENDED_FORMAT_PATTERN = "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.S'S'"; public static java.lang.String formatDurationHMS(final long durationMillis) { return org.apache.commons.lang3.time.DurationFormatUtils.formatDuration(durationMillis, "H:mm:ss.SSS"); } public static java.lang.String formatDurationISO(final long durationMillis) { return org.apache.commons.lang3.time.DurationFormatUtils.formatDuration(durationMillis, org.apache.commons.lang3.time.DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN, false); } public static java.lang.String formatDuration(final long durationMillis, final java.lang.String format) { return org.apache.commons.lang3.time.DurationFormatUtils.formatDuration(durationMillis, format, true); } public static java.lang.String formatDuration(long durationMillis, final java.lang.String format, final boolean padWithZeros) { final org.apache.commons.lang3.time.DurationFormatUtils.Token[] tokens = org.apache.commons.lang3.time.DurationFormatUtils.lexx(format); int days = 0; int hours = 0; int minutes = 0; int seconds = 0; int milliseconds = 0; if (org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.d)) { days = ((int)(durationMillis / (org.apache.commons.lang3.time.DateUtils.MILLIS_PER_DAY))); durationMillis = durationMillis - (days * (org.apache.commons.lang3.time.DateUtils.MILLIS_PER_DAY)); } if (org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.H)) { hours = ((int)(durationMillis / (org.apache.commons.lang3.time.DateUtils.MILLIS_PER_HOUR))); durationMillis = durationMillis - (hours * (org.apache.commons.lang3.time.DateUtils.MILLIS_PER_HOUR)); } if (org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.m)) { minutes = ((int)(durationMillis / (org.apache.commons.lang3.time.DateUtils.MILLIS_PER_MINUTE))); durationMillis = durationMillis - (minutes * (org.apache.commons.lang3.time.DateUtils.MILLIS_PER_MINUTE)); } if (org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.s)) { seconds = ((int)(durationMillis / (org.apache.commons.lang3.time.DateUtils.MILLIS_PER_SECOND))); durationMillis = durationMillis - (seconds * (org.apache.commons.lang3.time.DateUtils.MILLIS_PER_SECOND)); } if (org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.S)) { milliseconds = ((int)(durationMillis)); } return org.apache.commons.lang3.time.DurationFormatUtils.format(tokens, 0, 0, days, hours, minutes, seconds, milliseconds, padWithZeros); } public static java.lang.String formatDurationWords(final long durationMillis, final boolean suppressLeadingZeroElements, final boolean suppressTrailingZeroElements) { java.lang.String duration = org.apache.commons.lang3.time.DurationFormatUtils.formatDuration(durationMillis, "d' days 'H' hours 'm' minutes 's' seconds'"); if (suppressLeadingZeroElements) { duration = " " + duration; java.lang.String tmp = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 0 days", ""); if ((tmp.length()) != (duration.length())) { duration = tmp; tmp = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 0 hours", ""); if ((tmp.length()) != (duration.length())) { duration = tmp; tmp = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 0 minutes", ""); duration = tmp; if ((tmp.length()) != (duration.length())) { duration = org.apache.commons.lang3.StringUtils.replaceOnce(tmp, " 0 seconds", ""); } } } if ((duration.length()) != 0) { duration = duration.substring(1); } } if (suppressTrailingZeroElements) { java.lang.String tmp = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 0 seconds", ""); if ((tmp.length()) != (duration.length())) { duration = tmp; tmp = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 0 minutes", ""); if ((tmp.length()) != (duration.length())) { duration = tmp; tmp = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 0 hours", ""); if ((tmp.length()) != (duration.length())) { duration = org.apache.commons.lang3.StringUtils.replaceOnce(tmp, " 0 days", ""); } } } } duration = " " + duration; duration = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 1 seconds", " 1 second"); duration = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 1 minutes", " 1 minute"); duration = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 1 hours", " 1 hour"); duration = org.apache.commons.lang3.StringUtils.replaceOnce(duration, " 1 days", " 1 day"); return duration.trim(); } public static java.lang.String formatPeriodISO(final long startMillis, final long endMillis) { return org.apache.commons.lang3.time.DurationFormatUtils.formatPeriod(startMillis, endMillis, org.apache.commons.lang3.time.DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN, false, java.util.TimeZone.getDefault()); } public static java.lang.String formatPeriod(final long startMillis, final long endMillis, final java.lang.String format) { return org.apache.commons.lang3.time.DurationFormatUtils.formatPeriod(startMillis, endMillis, format, true, java.util.TimeZone.getDefault()); } public static java.lang.String formatPeriod(final long startMillis, final long endMillis, final java.lang.String format, final boolean padWithZeros, final java.util.TimeZone timezone) { final org.apache.commons.lang3.time.DurationFormatUtils.Token[] tokens = org.apache.commons.lang3.time.DurationFormatUtils.lexx(format); final java.util.Calendar start = java.util.Calendar.getInstance(timezone); start.setTime(new java.util.Date(startMillis)); final java.util.Calendar end = java.util.Calendar.getInstance(timezone); end.setTime(new java.util.Date(endMillis)); int milliseconds = (end.get(java.util.Calendar.MILLISECOND)) - (start.get(java.util.Calendar.MILLISECOND)); int seconds = (end.get(java.util.Calendar.SECOND)) - (start.get(java.util.Calendar.SECOND)); int minutes = (end.get(java.util.Calendar.MINUTE)) - (start.get(java.util.Calendar.MINUTE)); int hours = (end.get(java.util.Calendar.HOUR_OF_DAY)) - (start.get(java.util.Calendar.HOUR_OF_DAY)); int days = (end.get(java.util.Calendar.DAY_OF_MONTH)) - (start.get(java.util.Calendar.DAY_OF_MONTH)); int months = (end.get(java.util.Calendar.MONTH)) - (start.get(java.util.Calendar.MONTH)); int years = (end.get(java.util.Calendar.YEAR)) - (start.get(java.util.Calendar.YEAR)); while (milliseconds < 0) { milliseconds += 1000; seconds -= 1; } while (seconds < 0) { seconds += 60; minutes -= 1; } while (minutes < 0) { minutes += 60; hours -= 1; } while (hours < 0) { hours += 24; days -= 1; } if (org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.M)) { while (days < 0) { days += start.getActualMaximum(java.util.Calendar.DAY_OF_MONTH); months -= 1; start.add(java.util.Calendar.MONTH, 1); } while (months < 0) { months += 12; years -= 1; } if ((!(org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.y))) && (years != 0)) { while (years != 0) { months += 12 * years; years = 0; } } } else { if (!(org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.y))) { int target = end.get(java.util.Calendar.YEAR); if (months < 0) { target -= 1; } while ((start.get(java.util.Calendar.YEAR)) != target) { days += (start.getActualMaximum(java.util.Calendar.DAY_OF_YEAR)) - (start.get(java.util.Calendar.DAY_OF_YEAR)); if (((start instanceof java.util.GregorianCalendar) && ((start.get(java.util.Calendar.MONTH)) == (java.util.Calendar.FEBRUARY))) && ((start.get(java.util.Calendar.DAY_OF_MONTH)) == 29)) { days += 1; } start.add(java.util.Calendar.YEAR, 1); days += start.get(java.util.Calendar.DAY_OF_YEAR); } years = 0; } while ((start.get(java.util.Calendar.MONTH)) != (end.get(java.util.Calendar.MONTH))) { days += start.getActualMaximum(java.util.Calendar.DAY_OF_MONTH); start.add(java.util.Calendar.MONTH, 1); } months = 0; while (days < 0) { days += start.getActualMaximum(java.util.Calendar.DAY_OF_MONTH); months -= 1; start.add(java.util.Calendar.MONTH, 1); } } if (!(org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.d))) { hours += 24 * days; days = 0; } if (!(org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.H))) { minutes += 60 * hours; hours = 0; } if (!(org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.m))) { seconds += 60 * minutes; minutes = 0; } if (!(org.apache.commons.lang3.time.DurationFormatUtils.Token.containsTokenWithValue(tokens, org.apache.commons.lang3.time.DurationFormatUtils.s))) { milliseconds += 1000 * seconds; seconds = 0; } return org.apache.commons.lang3.time.DurationFormatUtils.format(tokens, years, months, days, hours, minutes, seconds, milliseconds, padWithZeros); } static java.lang.String format(final org.apache.commons.lang3.time.DurationFormatUtils.Token[] tokens, final int years, final int months, final int days, final int hours, final int minutes, final int seconds, int milliseconds, final boolean padWithZeros) { final java.lang.StringBuilder buffer = new java.lang.StringBuilder(); boolean lastOutputSeconds = false; final int sz = tokens.length; for (int i = 0 ; i < sz ; i++) { final org.apache.commons.lang3.time.DurationFormatUtils.Token token = tokens[i]; final java.lang.Object value = token.getValue(); final int count = token.getCount(); if (value instanceof java.lang.StringBuilder) { buffer.append(value.toString()); } else { if (value == (org.apache.commons.lang3.time.DurationFormatUtils.y)) { buffer.append((padWithZeros ? org.apache.commons.lang3.StringUtils.leftPad(java.lang.Integer.toString(years), count, '0') : java.lang.Integer.toString(years))); lastOutputSeconds = false; } else if (value == (org.apache.commons.lang3.time.DurationFormatUtils.M)) { buffer.append((padWithZeros ? org.apache.commons.lang3.StringUtils.leftPad(java.lang.Integer.toString(months), count, '0') : java.lang.Integer.toString(months))); lastOutputSeconds = false; } else if (value == (org.apache.commons.lang3.time.DurationFormatUtils.d)) { buffer.append((padWithZeros ? org.apache.commons.lang3.StringUtils.leftPad(java.lang.Integer.toString(days), count, '0') : java.lang.Integer.toString(days))); lastOutputSeconds = false; } else if (value == (org.apache.commons.lang3.time.DurationFormatUtils.H)) { buffer.append((padWithZeros ? org.apache.commons.lang3.StringUtils.leftPad(java.lang.Integer.toString(hours), count, '0') : java.lang.Integer.toString(hours))); lastOutputSeconds = false; } else if (value == (org.apache.commons.lang3.time.DurationFormatUtils.m)) { buffer.append((padWithZeros ? org.apache.commons.lang3.StringUtils.leftPad(java.lang.Integer.toString(minutes), count, '0') : java.lang.Integer.toString(minutes))); lastOutputSeconds = false; } else if (value == (org.apache.commons.lang3.time.DurationFormatUtils.s)) { buffer.append((padWithZeros ? org.apache.commons.lang3.StringUtils.leftPad(java.lang.Integer.toString(seconds), count, '0') : java.lang.Integer.toString(seconds))); lastOutputSeconds = true; } else if (value == (org.apache.commons.lang3.time.DurationFormatUtils.S)) { if (lastOutputSeconds) { milliseconds += 1000; final java.lang.String str = padWithZeros ? org.apache.commons.lang3.StringUtils.leftPad(java.lang.Integer.toString(milliseconds), count, '0') : java.lang.Integer.toString(milliseconds); buffer.append(str.substring(1)); } else { buffer.append((padWithZeros ? org.apache.commons.lang3.StringUtils.leftPad(java.lang.Integer.toString(milliseconds), count, '0') : java.lang.Integer.toString(milliseconds))); } lastOutputSeconds = false; } } } return buffer.toString(); } static final java.lang.Object y = "y"; static final java.lang.Object M = "M"; static final java.lang.Object d = "d"; static final java.lang.Object H = "H"; static final java.lang.Object m = "m"; static final java.lang.Object s = "s"; static final java.lang.Object S = "S"; static org.apache.commons.lang3.time.DurationFormatUtils.Token[] lexx(final java.lang.String format) { final char[] array = format.toCharArray(); final java.util.ArrayList<org.apache.commons.lang3.time.DurationFormatUtils.Token> list = new java.util.ArrayList<org.apache.commons.lang3.time.DurationFormatUtils.Token>(array.length); boolean inLiteral = false; java.lang.StringBuilder buffer = null; org.apache.commons.lang3.time.DurationFormatUtils.Token previous = null; final int sz = array.length; for (int i = 0 ; i < sz ; i++) { final char ch = array[i]; if (inLiteral && (ch != '\'')) { buffer.append(ch); continue; } java.lang.Object value = null; switch (ch) { case '\'' : if (inLiteral) { buffer = null; inLiteral = false; } else { buffer = new java.lang.StringBuilder(); list.add(new org.apache.commons.lang3.time.DurationFormatUtils.Token(buffer)); inLiteral = true; } break; case 'y' : value = org.apache.commons.lang3.time.DurationFormatUtils.y; break; case 'M' : value = org.apache.commons.lang3.time.DurationFormatUtils.M; break; case 'd' : value = org.apache.commons.lang3.time.DurationFormatUtils.d; break; case 'H' : value = org.apache.commons.lang3.time.DurationFormatUtils.H; break; case 'm' : value = org.apache.commons.lang3.time.DurationFormatUtils.m; break; case 's' : value = org.apache.commons.lang3.time.DurationFormatUtils.s; break; case 'S' : value = org.apache.commons.lang3.time.DurationFormatUtils.S; break; default : if (buffer == null) { buffer = new java.lang.StringBuilder(); list.add(new org.apache.commons.lang3.time.DurationFormatUtils.Token(buffer)); } buffer.append(ch); } if (value != null) { if ((previous != null) && ((previous.getValue()) == value)) { previous.increment(); } else { final org.apache.commons.lang3.time.DurationFormatUtils.Token token = new org.apache.commons.lang3.time.DurationFormatUtils.Token(value); list.add(token); previous = token; } buffer = null; } } return list.toArray(new org.apache.commons.lang3.time.DurationFormatUtils.Token[list.size()]); } static class Token { static boolean containsTokenWithValue(final org.apache.commons.lang3.time.DurationFormatUtils.Token[] tokens, final java.lang.Object value) { final int sz = tokens.length; for (int i = 0 ; i < sz ; i++) { if ((tokens[i].getValue()) == value) { return true; } } return false; } private final java.lang.Object value; private int count; Token(final java.lang.Object value) { this.value = value; org.apache.commons.lang3.time.DurationFormatUtils.Token.this.count = 1; } Token(final java.lang.Object value ,final int count) { this.value = value; org.apache.commons.lang3.time.DurationFormatUtils.Token.this.count = count; } void increment() { (count)++; } int getCount() { return count; } java.lang.Object getValue() { return value; } @java.lang.Override public boolean equals(final java.lang.Object obj2) { if (obj2 instanceof org.apache.commons.lang3.time.DurationFormatUtils.Token) { final org.apache.commons.lang3.time.DurationFormatUtils.Token tok2 = ((org.apache.commons.lang3.time.DurationFormatUtils.Token)(obj2)); if ((org.apache.commons.lang3.time.DurationFormatUtils.Token.this.value.getClass()) != (tok2.value.getClass())) { return false; } if ((org.apache.commons.lang3.time.DurationFormatUtils.Token.this.count) != (tok2.count)) { return false; } if ((org.apache.commons.lang3.time.DurationFormatUtils.Token.this.value) instanceof java.lang.StringBuilder) { return org.apache.commons.lang3.time.DurationFormatUtils.Token.this.value.toString().equals(tok2.value.toString()); } else if ((org.apache.commons.lang3.time.DurationFormatUtils.Token.this.value) instanceof java.lang.Number) { return org.apache.commons.lang3.time.DurationFormatUtils.Token.this.value.equals(tok2.value); } else { return (org.apache.commons.lang3.time.DurationFormatUtils.Token.this.value) == (tok2.value); } } return false; } @java.lang.Override public int hashCode() { return org.apache.commons.lang3.time.DurationFormatUtils.Token.this.value.hashCode(); } @java.lang.Override public java.lang.String toString() { return org.apache.commons.lang3.StringUtils.repeat(org.apache.commons.lang3.time.DurationFormatUtils.Token.this.value.toString(), org.apache.commons.lang3.time.DurationFormatUtils.Token.this.count); } } }
/* * --------------------------------------------------- * ESTRUCTURAS DE DATOS * --------------------------------------------------- * Facultad de Informática * Universidad Complutense de Madrid * --------------------------------------------------- */ /* Introduce aquí los nombres de los componentes del grupo: Componente 1: Steven Mallqui Aguilar Componente 2: */ #include <iostream> #include <cassert> #include <fstream> #include <vector> #include <string> using namespace std; const int MAX_ELEMS = 2000; class Multiconjunto { public: Multiconjunto():num_elems(0){} void anyadir(int elem); void eliminar(int elem); bool pertenece(int elem) const; // Implementa las operaciones necesarias. // No olvides el coste! private: struct Elem { int valor; int multiplicidad; }; Elem elems[MAX_ELEMS]; int num_elems; int binarySearch(int target) const; }; //Coste logarítmico int Multiconjunto::binarySearch(int target) const{ int low = 0; int high = num_elems - 1; while(low <= high){ int middle = (low + high) / 2; if(elems[middle].valor == target) return middle; else if ( elems[middle].valor < target) low = middle + 1; else high = middle - 1; } return low; } //Coste lineal con respecto a num_elems void Multiconjunto::anyadir(int elem){ int i = binarySearch(elem); if(elems[i].valor != elem || i == num_elems){ for(int j = num_elems; j > i; j--){ elems[j] = elems[j-1]; } elems[i].valor = elem; elems[i].multiplicidad = 1; num_elems++; }else if(elems[i].valor == elem ){ elems[i].multiplicidad++; } } //Coste logarítmico con respecto a num_elems void Multiconjunto::eliminar(int elem){ int i = binarySearch(elem); if(elems[i].valor == elem && i < num_elems){ elems[i].multiplicidad--; if(elems[i].multiplicidad == 0){ for(int j = i; j < num_elems; j++){ elems[j] = elems[j + 1]; } num_elems--; } } } //Coste logarítmico con respecto a num_elems bool Multiconjunto::pertenece(int elem) const{ int i = binarySearch(elem); return i < num_elems && elems[i].valor == elem && elems[i].multiplicidad != 0; } // Función que trata un caso de prueba. // Devuelve false si se ha leído el 0 que marca el fin de la entrada, // o true en caso contrario. void resuelve_caso(const vector<int> secuencia,const vector<int> intento, Multiconjunto mc, const int M){ string resultado; for(int i = 0; i < M; i++){ if(intento[i] == secuencia[i]){ resultado.push_back('#'); mc.eliminar(intento[i]); } else resultado.push_back('.'); } for(int i = 0; i < M; i++){ if(mc.pertenece(intento[i]) && resultado[i] != '#'){ resultado[i] = 'O'; mc.eliminar(intento[i]); } } cout << resultado << endl; } //Coste lineal con respecto a M bool tratar_caso() { int M; cin >> M; if(M == 0) return false; vector<int> secuencia(M), intento(M); Multiconjunto mc; for(int i = 0; i < M; i++){ cin >> secuencia[i]; mc.anyadir(secuencia[i]); } for(int i = 0; i < M; i++){ cin >> intento[i]; } resuelve_caso(secuencia, intento, mc, M); return true; } int main() { #ifndef DOMJUDGE std::ifstream in("sample.in"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); #endif while (tratar_caso()) { } #ifndef DOMJUDGE std::cin.rdbuf(cinbuf); // Descomentar en Windows si la consola se cierra inmediatamente // system("PAUSE"); #endif return 0; }
/* * Copyright (C) 2018-2024 Garden Technologies, Inc. <info@garden.io> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import type { DeepPrimitiveMap } from "../../../config/common.js" import { createSchema, joi, joiIdentifier, joiPrimitive, joiSparseArray } from "../../../config/common.js" import type { KubernetesCommonRunSpec, KubernetesTargetResourceSpec, PortForwardSpec } from "../config.js" import { kubernetesCommonRunSchemaKeys, namespaceNameSchema, portForwardsSchema, runPodResourceSchema, targetResourceSpecSchema, } from "../config.js" import type { KubernetesDeploySyncSpec } from "../sync.js" import { kubernetesDeploySyncSchema } from "../sync.js" import type { DeployAction, DeployActionConfig } from "../../../actions/deploy.js" import { dedent, deline } from "../../../util/string.js" import type { KubernetesLocalModeSpec } from "../local-mode.js" import { kubernetesLocalModeSchema } from "../local-mode.js" import type { RunAction, RunActionConfig } from "../../../actions/run.js" import type { TestAction, TestActionConfig } from "../../../actions/test.js" import type { ObjectSchema } from "@hapi/joi" import type { KubernetesRunOutputs } from "../kubernetes-type/config.js" // DEPLOY // export const defaultHelmTimeout = 300 export const defaultHelmRepo = "https://charts.helm.sh/stable" interface HelmChartSpec { name?: string // Formerly `chart` on Helm modules path?: string // Formerly `chartPath` repo?: string url?: string version?: string } interface HelmDeployActionSpec { atomic: boolean chart?: HelmChartSpec defaultTarget?: KubernetesTargetResourceSpec sync?: KubernetesDeploySyncSpec localMode?: KubernetesLocalModeSpec namespace?: string portForwards?: PortForwardSpec[] releaseName?: string values: DeepPrimitiveMap valueFiles: string[] } const parameterValueSchema = () => joi .alternatives( joiPrimitive(), joi.array().items(joi.link("#parameterValue")), joi.object().pattern(/.+/, joi.link("#parameterValue")) ) .id("parameterValue") const helmReleaseNameSchema = () => joiIdentifier().description( "Optionally override the release name used when installing (defaults to the Deploy name)." ) const helmValuesSchema = () => joi .object() .pattern(/.+/, parameterValueSchema()) .default(() => ({})).description(deline` Map of values to pass to Helm when rendering the templates. May include arrays and nested objects. When specified, these take precedence over the values in the \`values.yaml\` file (or the files specified in \`valueFiles\`). `) const helmValueFilesSchema = () => joiSparseArray(joi.posixPath()).description(dedent` Specify value files to use when rendering the Helm chart. These will take precedence over the \`values.yaml\` file bundled in the Helm chart, and should be specified in ascending order of precedence. Meaning, the last file in this list will have the highest precedence. If you _also_ specify keys under the \`values\` field, those will effectively be added as another file at the end of this list, so they will take precedence over other files listed here. Note that the paths here should be relative to the _config_ root, and the files should be contained in this action config's directory. `) export const helmCommonSchemaKeys = () => ({ namespace: namespaceNameSchema(), portForwards: portForwardsSchema(), releaseName: helmReleaseNameSchema(), timeout: joi .number() .integer() .default(defaultHelmTimeout) .description( "Time in seconds to wait for Helm to complete any individual Kubernetes operation (like Jobs for hooks)." ), values: helmValuesSchema(), valueFiles: helmValueFilesSchema(), }) export const helmChartNameSchema = () => joi .string() .description( "A valid Helm chart name or URI (same as you'd input to `helm install`) Required if the action doesn't contain the Helm chart itself." ) .example("ingress-nginx") export const helmChartRepoSchema = () => joi .string() .description(`The repository URL to fetch the chart from. Defaults to the "stable" helm repo (${defaultHelmRepo}).`) export const helmChartVersionSchema = () => joi.string().description("The chart version to deploy.") export const defaultTargetSchema = () => targetResourceSpecSchema().description( dedent` Specify a default resource in the deployment to use for syncs, local mode, and for the \`garden exec\` command. Specify either \`kind\` and \`name\`, or a \`podSelector\`. The resource should be one of the resources deployed by this action (otherwise the target is not guaranteed to be deployed with adjustments required for syncing or local mode). Set \`containerName\` to specify a container to connect to in the remote Pod. By default the first container in the Pod is used. Note that if you specify \`podSelector\` here, it is not validated to be a selector matching one of the resources deployed by the action. ` ) const helmChartSpecSchema = () => joi .object() .keys({ name: helmChartNameSchema(), path: joi .posixPath() .subPathOnly() .description( "The path, relative to the action path, to the chart sources (i.e. where the Chart.yaml file is, if any)." ), repo: helmChartRepoSchema(), url: joi.string().uri().description("URL to OCI repository, or a URL to a packaged Helm chart archive."), version: helmChartVersionSchema(), }) .without("path", ["name", "repo", "version", "url"]) .without("url", ["name", "repo", "path"]) .xor("name", "path", "url") .description( dedent` Specify the Helm chart to use. If the chart is defined in the same directory as the action, you can skip this, and the chart sources will be detected. If the chart is in the source tree but in a sub-directory, you should set \`chart.path\` to the directory path, relative to the action directory. For remote charts, there are multiple options: - **[Helm Chart repository](https://helm.sh/docs/topics/chart_repository/)**: specify \`chart.name\` and \`chart.version\, and optionally \`chart.repo\` (if the chart is not in the default "stable" repo). - **[OCI-Based Registry](https://helm.sh/docs/topics/registries/)**: specify \`chart.url\` with the \`oci://\` URL and optionally \`chart.version\`. - **Absolute URL to a packaged chart**: specify \`chart.url\`. One of \`chart.name\`, \`chart.path\` or \`chart.url\` must be specified. ` ) export const defaultHelmAtomicFlag = false export const defaultHelmAtomicFlagDesc = `Whether to set the --atomic flag during installs and upgrades. Set to true if you'd like the changes applied to be reverted on failure. Set to false if e.g. you want to see more information about failures and then manually roll back, instead of having Helm do it automatically on failure.` export const helmDeploySchema = () => joi .object() .keys({ ...helmCommonSchemaKeys(), atomic: joi.boolean().default(defaultHelmAtomicFlag).description(defaultHelmAtomicFlagDesc), chart: helmChartSpecSchema(), defaultTarget: defaultTargetSchema(), sync: kubernetesDeploySyncSchema(), localMode: kubernetesLocalModeSchema(), }) .rename("devMode", "sync") export type HelmDeployConfig = DeployActionConfig<"helm", HelmDeployActionSpec> export type HelmDeployAction = DeployAction<HelmDeployConfig, {}> // RUN & TEST // export interface HelmPodRunActionSpec extends KubernetesCommonRunSpec { chart?: HelmChartSpec namespace?: string releaseName?: string values: DeepPrimitiveMap valueFiles: string[] resource?: KubernetesTargetResourceSpec } // Maintaining this cache to avoid errors when `kubernetesRunPodSchema` is called more than once with the same `kind`. const runSchemas: { [name: string]: ObjectSchema } = {} export const helmPodRunSchema = (kind: string) => { const name = `${kind}:helm-pod` if (runSchemas[name]) { return runSchemas[name] } const schema = createSchema({ name: `${kind}:helm-pod`, keys: () => ({ ...kubernetesCommonRunSchemaKeys(), releaseName: helmReleaseNameSchema().description( `Optionally override the release name used when rendering the templates (defaults to the ${kind} name).` ), chart: helmChartSpecSchema(), values: helmValuesSchema(), valueFiles: helmValueFilesSchema(), resource: runPodResourceSchema("Run"), timeout: joi .number() .integer() .default(defaultHelmTimeout) .description("Time in seconds to wait for Helm to render templates."), }), xor: [["resource", "podSpec"]], })() runSchemas[name] = schema return schema } export type HelmPodRunConfig = RunActionConfig<"helm-pod", HelmPodRunActionSpec> export type HelmPodRunAction = RunAction<HelmPodRunConfig, KubernetesRunOutputs> export type HelmPodTestActionSpec = HelmPodRunActionSpec export type HelmPodTestConfig = TestActionConfig<"helm-pod", HelmPodTestActionSpec> export type HelmPodTestAction = TestAction<HelmPodTestConfig, KubernetesRunOutputs> export type HelmActionConfig = HelmDeployConfig | HelmPodRunConfig | HelmPodTestConfig
%% [V,B,tripdist,tripdistkm,relodist,relodistkm,queue]=tripassignmentsaev(Vin,Bin,Par) % Trip assignment for SAEV simulation with active rebalancing % % input % Vin: vehicles information in the form: % [station delay soc connected] % Bin: passengers info in the form: % [O , D , waiting , tariff , utility_alternative] % Par: parameters: % Tr, D, Epsilon, consumption, battery, minsoc, maxwait, modechoice, % chargepenalty, LimitFCR, traveltimecost, VOT % % output % V: vehicle movements in the form [station delay used] % B: passengers status in the form: % [chosenmode waiting dropped waitingestimated] % tripdist: total distance with passengers % relodist: total distance for relocation to pickup % queue: queued passengers (IDs) % % See also: main function [V,B,tripdist,tripdistkm,relodist,relodistkm,queue]=tripassignmentsaev(Vin,Bin,Par) tripdist=0; tripdistkm=0; relodist=0; relodistkm=0; queue=zeros(100,1); ql=0; % limit of assignments per minute (only for simulations without mode choice) if Par.modechoice AssignmentLimit=inf; else AssignmentLimit=round(size(Vin,1)/2); end ad=Par.consumption/Par.battery*Par.Epsilon; % discharge rate per time step (normalized) % if there are trips if ~isempty(Bin) m=size(Bin,1); waiting=Bin(:,3); chosenmode=(waiting>0); waitingestimated=zeros(m,1); modeutilities=zeros(m,2); dropped=zeros(m,1); queueextended=[]; if size(Bin,1)>AssignmentLimit Deferred=AssignmentLimit:m; queueextended=Deferred'; waiting(Deferred)=waiting(Deferred)+Par.Epsilon; % if waiting exceeds maximum, reject directly and remove from queue ToReject=(waiting(Deferred)>=Par.maxwait); queueextended=queueextended.*(1-ToReject); dropped(ToReject)=1; Bin=Bin(1:AssignmentLimit,:); end %n=size(Par.Tr,1); ui=Vin(:,1); di=Vin(:,2); Used=zeros(length(ui),1); Connected=logical(Vin(:,4)); m=size(Bin,1); distancepickup=Par.Tr(ui,Bin(:,1))'; distancetomove=Par.Tr(sub2ind(size(Par.Tr),Bin(:,1),Bin(:,2))); distancetomovekm=Par.D(sub2ind(size(Par.D),Bin(:,1),Bin(:,2))); EnergyReq=(distancepickup+(distancetomove+di'))*ad+Par.minsoc; % create matrix X X=(distancepickup + ... distance from passenger ones(m,1)*( di' + ... current delay 0.1 + ... indicate the vehicle is available Vin(:,4)'*0.25*Par.chargepenalty + ... penalty for currently charging vehicles (1-Vin(:,3)')*0.25) ... penalty for low soc vehicles )... .*(EnergyReq<ones(m,1)*Vin(:,3)'); % requirement for enough SOC X(X==0)=NaN; if sum(Connected)<=Par.LimitFCR X(:,Connected)=NaN; end for tripID=1:m %if sum(~isnan(X(tripID,:))) % best vehicle [Delay,uids]=min(X(tripID,:)); % if there is a possible vehicle if ~isnan(Delay) WaitingTime=floor(Delay)*Par.Epsilon; else WaitingTime=NaN; end % avoid changing chosen mode after deciding if chosenmode(tripID)==0 if Par.modechoice if isnan(WaitingTime) AcceptProbability=0; UtilitySAEV=nan; else Tariff=Bin(tripID,4); UtilitySAEV=-Tariff-(WaitingTime+Par.traveltimecost*distancetomove(tripID))*Par.VOT/60; AcceptProbability=exp(UtilitySAEV)/(exp(UtilitySAEV)+Bin(tripID,5)); end modeutilities(tripID,:)=[UtilitySAEV , log(Bin(tripID,5))]; else AcceptProbability=1; end chosenmode(tripID)=(rand()<AcceptProbability); waitingestimated(tripID)=WaitingTime; end if chosenmode(tripID)==1 % if the best vehicle is at the station if (waiting(tripID)<=Par.maxwait && isnan(WaitingTime)) || (waiting(tripID)+WaitingTime<Par.maxwait) % if (waiting(tripID)+WaitingTime)<=Par.maxwait if ~isnan(WaitingTime) waiting(tripID)=waiting(tripID)+WaitingTime; % update travelled distance tripdist=tripdist+distancetomove(tripID); tripdistkm=tripdistkm+distancetomovekm(tripID); % update additional travel distance to pickup pickupdist=Par.Tr(ui(uids),Bin(tripID,1)); pickupdistkm=Par.D(ui(uids),Bin(tripID,1)); relodist=relodist+pickupdist; relodistkm=relodistkm+pickupdistkm; % accept request and update vehicle position ui(uids)=Bin(tripID,2); % position di(uids)=di(uids)+pickupdist+distancetomove(tripID); % delay % update X X(:,uids)=(Par.Tr(Bin(:,1),ui(uids))+ ... di(uids)+... updated delay 0.1 + ... indicate the vehicle is available (1-Vin(uids,3))*0.25).* ... penalty for low soc vehicles (EnergyReq(:,uids)+(ad*(pickupdist+distancetomove(tripID)))<Vin(uids,3)'); X(X(:,uids)==0,uids)=NaN; % remove vehicles that are needed for FCR Connected(uids)=0; if sum(Connected)<=Par.LimitFCR X(:,Connected)=NaN; end Used(uids)=1; else % increase waiting time (minutes) for this trip waiting(tripID)=waiting(tripID)+Par.Epsilon; % add this trip to the queue ql=ql+1; % current trip queue(ql)=tripID; end else % TODO: fix pooling % if max waiting exceeded, request dropped % if pooling(tripID)>0 % tripsdropped=find(pooling==pooling(tripID)); % else tripsdropped=tripID; % end % register this as a dropped request dropped(tripsdropped)=1; end end end queue=[queue(queue>0);queueextended(queueextended>0)]; %% report results V=[ui , di , Used]; B=[chosenmode , waiting , dropped , waitingestimated , modeutilities]; else V=Vin(:,1:2); B=[]; end
import React, { useEffect, useState } from "react"; import { Navigation } from "swiper/modules"; import axios from "axios"; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, } from "chart.js"; import { Line } from "react-chartjs-2"; ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend ); function SearchModels() { const [searchQuery, setSearchQuery] = useState(""); const [searchResults, setSearchResults] = useState([]); const [activeModelName, setActiveModelName] = useState(""); const [activeModelType, setActiveModelType] = useState(""); const [activeModelVis, setActiveModelVis] = useState(""); const [activeTrainingData, setActiveTrainingData] = useState({}); const [activeValidationData, setActiveValidationData] = useState({}); const handleSearch = async () => { if (searchQuery.length !== 0) { try { const response = await axios.get("http://localhost:3000/search", { params: { q: searchQuery }, }); if (response.data.length > 0) { setSearchResults(response.data); console.log(searchQuery); setActiveModelName(response.data[0].model_name); setActiveModelType(response.data[0].model_type); //setActiveModelVis(response.data[0].model_vis); //console.log(response.data[0].training_loss) //console.log(response.data[0].training_accuracy) /* Set training loss data */ const training_data = { labels: Array.from(Array(100).keys()), datasets: [ { label: "Training Loss", data: response.data[0].training_loss, borderColor: "rgb(255, 99, 132)", backgroundColor: "rgba(255, 99, 132, 0.5)", }, { label: "Training Accuracy", data: response.data[0].training_accuracy, borderColor: "rgb(0, 204, 102)", backgroundColor: "rgba(0, 204, 102, 0.5)", }, ], }; /* Set validation loss data */ const validation_data = { labels: Array.from(Array(100).keys()), datasets: [ { label: "Validation Loss", data: response.data[0].validation_loss, borderColor: "rgb(255, 99, 132)", backgroundColor: "rgba(255, 99, 132, 0.5)", }, { label: "Validation Accuracy", data: response.data[0].validation_accuracy, borderColor: "rgb(0, 204, 102)", backgroundColor: "rgba(0, 204, 102, 0.5)", }, ], }; setActiveTrainingData(training_data); setActiveValidationData(validation_data); } else { setSearchResults([]); } console.log(response.data); } catch (error) { console.error(error); setSearchResults([]); } } }; let info = () => { if (searchResults.length === 0) { return <p>No Models Were Found</p>; } return searchResults.map((element, index) => { return ( <tr class="odd:bg-white odd:dark:bg-gray-900 even:bg-gray-50 even:dark:bg-gray-800 border-b dark:border-gray-700"> <th scope="row" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white" > {element.model_name} </th> <td class="px-6 py-4">{element.model_type}</td> <td class="px-6 py-4">{element.validation_accuracy[element.validation_accuracy.length - 1]}</td> <td class="px-6 py-4"> <a href="#" class="font-medium text-blue-600 dark:text-blue-500 hover:underline" > View </a> </td> </tr> ); }); }; return ( <div class="min-h-screen bg-bg-grey"> <div class="bg-contain bg-bg-grey"> <div class="max-w-md mx-auto "> <label for="default-search" class="mb-2 text-sm font-medium text-gray-900 sr-only dark:text-white" > Search </label> <div class="relative "> <div class="absolute inset-y-0 start-0 flex items-center ps-3 pointer-events-none"> <svg class="w-4 h-4 text-gray-500 dark:text-gray-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20" > <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z" /> </svg> </div> <input type="text" id="default-search" class="block w-full p-4 ps-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" onChange={(e) => setSearchQuery(e.target.value)} placeholder="Search Models" required /> <button onClick={handleSearch} class="text-white absolute end-2.5 bottom-2.5 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-4 py-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" > Search </button> </div> </div> <div class="relative overflow-x-auto shadow-md sm:rounded-lg "> <table class="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400"> <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400"> <tr> <th scope="col" class="px-6 py-3"> Model name </th> <th scope="col" class="px-6 py-3"> Model Type </th> <th scope="col" class="px-6 py-3"> Accuracy </th> <th scope="col" class="px-6 py-3"> View Model </th> </tr> </thead> <tbody>{info()}</tbody> </table> </div> </div> <div class="h-full bg-bg-grey"> </div> </div> ); } export default SearchModels;
<!doctype html> <html lang="en"> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootsrap CSS Offline --> <link rel="stylesheet" href="style.css"> <!-- Bootsrap css online --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <!-- navbar awal--> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="https://UMPIT.github.io">YULIASTORE</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-end" id="navbarNavDropdown"> <ul class="navbar-nav"> <!-- Beranda --> <li class="nav-item active"> <a class="nav-link" href="#">Beranda <span class="sr-only">(current)</span></a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-expanded="false"> Blog </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="#">Bootstrap Layout</a> <a class="dropdown-item" href="#">Bootstrap Components</a> <a class="dropdown-item" href="#">Bootstrap Content</a> </div> </li> <!-- Portofolio --> <li class="nav-item"> <a class="nav-link" href="portofolioYulia.html">Portofolio <span class="sr-only">(current)</span></a> </li> <!-- Blog --> <li class="nav-item"> <a class="nav-link" href="#">Produk</a> </li> <li class="nav-item"> <a class="nav-link" href="kontakwa.html">Kontak</a> </li> </ul> </div> </nav> <!-- AKHIR : Navigasi Bar --> <!-- AWAL : Jumbotron --> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="img/Slide-1.jpg" class="d-block w-100" alt=""> </div> <div class="carousel-item"> <img src="img/Slide-2.jpg" class="d-block w-100" alt=""> </div> <div class="carousel-item"> <img src="img/Slide-3.jpg" class="d-block w-100" alt=""> </div> <div class="carousel-item"> <img src="img/Slide-4.jpg" class="d-block w-100" alt=""> </div> </div> <button class="carousel-control-prev" type="button" data-target="#carouselExampleControls" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </button> <button class="carousel-control-next" type="button" data-target="#carouselExampleControls" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </button> </div> <!-- AKHIR : Jumbotron --> <!-- AWAL : Produk Terbaru --> <div class="container" id="produkTerbaru"> <h1 class="display-5">Produk Terbaru</h1> <br> </div> <!-- baris pertama --> <div class="row"> <!-- Produk Satu --> <div class="col-md-3 mb-3"> <img src="img/produk1.jpg" class="card-img-top" alt="Produk Satu"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> <!-- Produk Dua --> <div class="col-md-3 mb-3 mb-3"> <div class="card"> <img src="img/produk2.png" class="card-img-top" alt="Produk Dua"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> <!-- Produk Tiga --> <div class="col-md-3 mb-3"> <div class="card"> <img src="img/produk3.png" class="card-img-top" alt="Produk Tiga"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> <!-- Produk Empat --> <div class="col-md-3 mb-3"> <div class="card"> <img src="img/produk4.jpg" class="card-img-top" alt="Produk Tiga"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> </div> <!-- baris kedua --> </div> <!-- AKHIR : Produk Terbaru --> <!-- Bootstrap js Offline --> <!-- <script src="js/bootstrap.bundle.min.js"></script> --> <!-- <script src="js/jquery.slim.min.js"></script> --> <!-- Bootsrap JS Online --> <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script> </body> </html>
# Stock Price Prediction Using FB Prophet and yfinance with Taipy Charts ## 📈 Project Overview Welcome to the **Stock Price Prediction** project! This innovative tool leverages the power of FB Prophet for robust time series forecasting and yfinance for fetching historical stock data. The results are presented through beautiful, interactive visualizations created with Taipy Charts, making data analysis a breeze. ## 🌟 Features - **Data Collection**: Seamlessly fetch historical stock data with yfinance. - **Data Preprocessing**: Efficiently clean and prepare data for precise modeling. - **Time Series Forecasting**: Harness the predictive power of FB Prophet to forecast future stock prices. - **Visualization**: Experience data through dynamic and interactive Taipy Charts. - **User Interface**: Enjoy a simple, intuitive interface to input stock symbols and visualize predictions. ## 🚀 Getting Started Follow these steps to get the project up and running: ### Prerequisites Ensure you have Python installed, along with the following libraries: ```bash pip install yfinance pip install fbprophet pip install taipy ``` ## 📂 Project Structure - `stock_price_prediction.py`: The core script to execute stock price predictions and generate visualizations. - `data/`: Directory for storing downloaded stock data. - `models/`: Directory for saving trained prediction models. - `charts/`: Directory for storing generated charts. ## 🎥 Demo Video Watch our demo video to see the project in action: ![Demo](Demo.mp4) ## 🤝 Contributing We are thrilled to welcome contributions! Feel free to fork the repository, implement your changes, and create a pull request. Please ensure you follow the contribution guidelines outlined in the repository. ## 🙏 Acknowledgments A special thanks to: - **yfinance**: For providing an effortless interface to download historical stock data. - **FB Prophet**: For its powerful and user-friendly time series forecasting capabilities. - **Taipy Charts**: For enabling stunning, interactive visualizations. - **The Open Source Community**: For their invaluable support and contributions. ## 📬 Contact Have questions or suggestions? Open an issue or reach out to us at shubhamsingla259@example.com. vi
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateEmployeesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('employees', function (Blueprint $table) { $table->id(); $table->string('lastName'); $table->string('firstName'); $table->unsignedBigInteger('work_org_id')->nullable(); $table->foreign("work_org_id")->references("id")->on("work_organizations")->onUpdate('cascade')->onDelete('cascade'); $table->unsignedBigInteger('sec_id')->nullable(); $table->foreign("sec_id")->references("id")->on("users")->onUpdate('cascade')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('employees'); } }
/* Copyright (c) 2024 Joshua White * SPDX-License-Identifier: Apache-2.0 */ #include <pub_sub/delayable_msg.h> static void add_to_wait_list(struct pub_sub_delayable_msg *msg_to_add, struct pub_sub_delayable_msg *next_msg); static void timer_timeout(struct k_timer *timer); static sys_dlist_t g_wait_list = SYS_DLIST_STATIC_INIT(&g_wait_list); static sys_dlist_t g_expired_list = SYS_DLIST_STATIC_INIT(&g_expired_list); static K_TIMER_DEFINE(g_msg_timer, timer_timeout, NULL); static struct k_spinlock g_spin_lock; static k_timepoint_t g_current_end_time; void pub_sub_delayable_msg_init(struct pub_sub_delayable_msg *delayable_msg, struct pub_sub_subscriber *subscriber, uint16_t msg_id) { __ASSERT(delayable_msg != NULL, ""); sys_dnode_init(&delayable_msg->header.node); delayable_msg->header.subscriber = subscriber; delayable_msg->header.aborted = false; pub_sub_msg_init(&delayable_msg->msg, msg_id, PUB_SUB_ALLOC_ID_DELAYABLE_MSG); } void pub_sub_delayable_msg_start(struct pub_sub_delayable_msg *delayable_msg, k_timeout_t timeout) { __ASSERT(delayable_msg != NULL, ""); delayable_msg->header.aborted = pub_sub_msg_get_ref_cnt(&delayable_msg->msg) != 0; k_timepoint_t new_end_time = sys_timepoint_calc(timeout); K_SPINLOCK(&g_spin_lock) { // Assume we are going to insert at the head of the list struct pub_sub_delayable_msg *insert_msg = SYS_DLIST_PEEK_HEAD_CONTAINER(&g_wait_list, insert_msg, header.node); // If the message is linked then we need to remove it if (sys_dnode_is_linked(&delayable_msg->header.node)) { // If the new end time is further away than the current end time then move // the insert_msg to the next message in the queue rather than the head // message. Make sure the current end time isn't expired though, otherwise // we will be peeking into the expired list rather than the wait list if (!sys_timepoint_expired(delayable_msg->header.end_time) && (sys_timepoint_cmp(new_end_time, delayable_msg->header.end_time) > 0)) { insert_msg = SYS_DLIST_PEEK_NEXT_CONTAINER( &g_wait_list, delayable_msg, header.node); sys_dlist_remove(&delayable_msg->header.node); } else { sys_dlist_remove(&delayable_msg->header.node); // Update the head of the list pointer in case it was the message // being updated insert_msg = SYS_DLIST_PEEK_HEAD_CONTAINER(&g_wait_list, insert_msg, header.node); } } delayable_msg->header.end_time = new_end_time; add_to_wait_list(delayable_msg, insert_msg); // Update the timer timeout if needed struct pub_sub_delayable_msg *head_msg = SYS_DLIST_PEEK_HEAD_CONTAINER(&g_wait_list, insert_msg, header.node); // head_msg can't be null because we just added a message. // Update the msg_timer timeout if the updated message is the at the head of // the wait list or the current end time doesn't equal the head message's // end time if ((head_msg == delayable_msg) || (sys_timepoint_cmp(head_msg->header.end_time, g_current_end_time) != 0)) { g_current_end_time = head_msg->header.end_time; k_timer_start(&g_msg_timer, sys_timepoint_timeout(head_msg->header.end_time), K_NO_WAIT); } } } void pub_sub_delayable_msg_abort(struct pub_sub_delayable_msg *delayable_msg) { __ASSERT(delayable_msg != NULL, ""); delayable_msg->header.aborted = pub_sub_msg_get_ref_cnt(&delayable_msg->msg) != 0; K_SPINLOCK(&g_spin_lock) { if (sys_dnode_is_linked(&delayable_msg->header.node)) { sys_dlist_remove(&delayable_msg->header.node); struct pub_sub_delayable_msg *head_msg = SYS_DLIST_PEEK_HEAD_CONTAINER(&g_wait_list, head_msg, header.node); if (head_msg == NULL) { // wait list is empty stop the timer k_timer_stop(&g_msg_timer); } else if ((sys_timepoint_cmp(head_msg->header.end_time, g_current_end_time) > 0)) { // If the head message in the wait list is further away than the // current timeout then update the timeout to the head message's // timeout g_current_end_time = head_msg->header.end_time; k_timer_start(&g_msg_timer, sys_timepoint_timeout(head_msg->header.end_time), K_NO_WAIT); } } } } void pub_sub_free_delayable_msg(const void *msg) { __ASSERT(msg != NULL, ""); struct pub_sub_delayable_msg *delayable_msg = CONTAINER_OF(msg, struct pub_sub_delayable_msg, msg); // Clear the aborted flag delayable_msg->header.aborted = false; // If the expired list is not empty then check if any messages can be published if (!sys_dlist_is_empty(&g_expired_list)) { K_SPINLOCK(&g_spin_lock) { delayable_msg = SYS_DLIST_PEEK_HEAD_CONTAINER(&g_expired_list, delayable_msg, header.node); while (delayable_msg != NULL) { void *msg = delayable_msg->msg; struct pub_sub_delayable_msg *next_msg = SYS_DLIST_PEEK_NEXT_CONTAINER(&g_expired_list, delayable_msg, header.node); if (pub_sub_msg_get_ref_cnt(msg) == 0) { sys_dlist_remove(&delayable_msg->header.node); pub_sub_acquire_msg(msg); pub_sub_publish_to_subscriber( delayable_msg->header.subscriber, msg); } delayable_msg = next_msg; } } } } // Must be called with the g_spin_lock held static void add_to_wait_list(struct pub_sub_delayable_msg *msg_to_add, struct pub_sub_delayable_msg *next_msg) { // Search through the wait list from next_msg until we find a message with an end_time that // is further away. Then insert the msg_to_add before next_msg so that wait_list is always // sorted by message end_time. while ((next_msg != NULL) && (sys_timepoint_cmp(next_msg->header.end_time, msg_to_add->header.end_time) <= 0)) { next_msg = SYS_DLIST_PEEK_NEXT_CONTAINER(&g_wait_list, next_msg, header.node); } if (next_msg == NULL) { sys_dlist_append(&g_wait_list, &msg_to_add->header.node); } else { sys_dlist_insert(&next_msg->header.node, &msg_to_add->header.node); } } static void timer_timeout(struct k_timer *timer) { K_SPINLOCK(&g_spin_lock) { // Publish all expired messages in the wait list struct pub_sub_delayable_msg *delayable_msg = SYS_DLIST_PEEK_HEAD_CONTAINER(&g_wait_list, delayable_msg, header.node); while ((delayable_msg != NULL) && sys_timepoint_expired(delayable_msg->header.end_time)) { struct pub_sub_delayable_msg *tmp_msg = delayable_msg; void *msg = tmp_msg->msg; delayable_msg = SYS_DLIST_PEEK_NEXT_CONTAINER(&g_wait_list, tmp_msg, header.node); sys_dlist_remove(&tmp_msg->header.node); // If the reference counter is zero then the message is not queued with the // subscriber and we can publish it, otherwise we need to move the message // to the expired list so it can be handled when the message is freed. if (pub_sub_msg_get_ref_cnt(msg) == 0) { pub_sub_acquire_msg(msg); pub_sub_publish_to_subscriber(tmp_msg->header.subscriber, msg); } else { sys_dlist_append(&g_expired_list, &tmp_msg->header.node); } } // delayable_msg is pointing to the new head of wait_list and it is the next message // to be published so restart the timer with its timeout if (delayable_msg != NULL) { g_current_end_time = delayable_msg->header.end_time; k_timer_start(timer, sys_timepoint_timeout(delayable_msg->header.end_time), K_NO_WAIT); } } }
import { useParams } from "react-router-dom"; import "./City.css"; import { useIcons } from "../../contexts/IconsContext"; import { useEffect, useState } from "react"; import Spinner from "../Spinner/Spinner"; import BackButton from "../Button/BackButton"; const formatDate = (date) => new Intl.DateTimeFormat("en", { day: "numeric", month: "long", year: "numeric", weekday: "long", }).format(new Date(date)); function City() { const { id } = useParams(); const { getIcon, currentIcon, isLoading, icons } = useIcons(); const { iconName, emoji, area, notes, distance, condition } = currentIcon; console.log(distance); const [shouldRender, setShouldRender] = useState(true); // Function to toggle the condition const toggleRender = () => { if (distance === null) setShouldRender(!shouldRender); }; useEffect(() => { // This effect runs whenever shouldRender changes // You can place any additional logic here }, [shouldRender]); toggleRender(); useEffect( function () { getIcon(id); }, [id] ); if (isLoading) return <Spinner />; icons.map((icon) => { if (icon.id === currentIcon.id) { currentIcon.distance = icon.distance; } }); return ( <div className="city"> <div className="row"> <h6>name</h6> <h3> <span>{emoji}</span> {iconName} </h3> </div> <div className="row"> <h6> {"area"} : {id}{" "} </h6> <p>{area}</p> </div> <div className="row"> <h6>Approximate distance from your Location</h6> <p>{distance} km</p> </div> {condition !== null ? ( <div className="row"> <h6>Condition</h6> <p>{condition}</p> </div> ) : ( console.log("") )} {notes && ( <div className="row"> <h6>Your notes</h6> <p>{notes}</p> </div> )} {/* <div className={styles.row}> <h6>Learn more</h6> <a href={`https://en.wikipedia.org/wiki/${cityName}`} target="_blank" rel="noreferrer" > Check out {cityName} on Wikipedia &rarr; </a> </div> */} <div> <BackButton /> </div> </div> ); } export default City;
import React from "react"; import logo from "./../../../assets/Np.png"; import { Navbar, Collapse, Typography, Button, IconButton, List, ListItem, Menu, MenuHandler, MenuList, MenuItem, Chip, } from "@material-tailwind/react"; import { ChevronDownIcon, UserCircleIcon, CubeTransparentIcon, Bars3Icon, XMarkIcon, FlagIcon, ChatBubbleOvalLeftIcon, UsersIcon, FolderIcon, Square3Stack3DIcon, RocketLaunchIcon, FaceSmileIcon, PuzzlePieceIcon, GiftIcon, } from "@heroicons/react/24/outline"; import { Link } from "react-router-dom"; import useCategory from "../../../hooks/useCategory"; const colors = { blue: "bg-blue-50 text-blue-500", orange: "bg-orange-50 text-orange-500", green: "bg-green-50 text-green-500", "blue-gray": "bg-blue-gray-50 text-blue-gray-500", purple: "bg-purple-50 text-purple-500", teal: "bg-teal-50 text-teal-500", cyan: "bg-cyan-50 text-cyan-500", pink: "bg-pink-50 text-pink-500", }; function NavListMenu() { const [isMenuOpen, setIsMenuOpen] = React.useState(false); const [isMobileMenuOpen, setIsMobileMenuOpen] = React.useState(false); const [refetch, allcategory] = useCategory(); const renderItems = allcategory.map(({ categoryName, categorySlug }, key) => ( <li key={key} className="relative list-none group hover:bg-np px-4"> <Link to={`products/${categorySlug}`} className="block font-semibold font-oswald text-base px-4 py-2 text-gray-600 hover:text-white" > {categoryName} </Link> {/* <ul className={`w-64 absolute left-full top-0 mt-0 space-y-2 bg-white shadow-lg transition-transform duration-300 ease-in-out transform`} > {subCategories && subCategories.map((subsubmenuItem,index) => ( <SubSubMenu key={index} {...subsubmenuItem} /> ))} </ul> */} </li> )); return ( <React.Fragment> <Menu open={isMenuOpen} handler={setIsMenuOpen} offset={{ mainAxis: 20 }} placement="bottom" allowHover={true} > <MenuHandler> <Typography as="div" variant="small" className="font-xl font-semibold font-oswald uppercase"> <ListItem className="flex items-center gap-2 py-2 pr-4" selected={isMenuOpen || isMobileMenuOpen} onClick={() => setIsMobileMenuOpen((cur) => !cur)} > <Square3Stack3DIcon className="h-[18px] w-[18px]" /> Products <ChevronDownIcon strokeWidth={2.5} className={`hidden h-3 w-3 transition-transform lg:block ${ isMenuOpen ? "rotate-180" : "" }`} /> <ChevronDownIcon strokeWidth={2.5} className={`block h-3 w-3 transition-transform lg:hidden ${ isMobileMenuOpen ? "rotate-180" : "" }`} /> </ListItem> </Typography> </MenuHandler> <MenuList className="hidden py-2 max-w-screen-xl lg:block"> <ul className="grid grid-cols-1 gap-y-2">{renderItems}</ul> </MenuList> </Menu> <div className="block lg:hidden"> <Collapse open={isMobileMenuOpen}>{renderItems}</Collapse> </div> </React.Fragment> ); } function NavList() { return ( <List className="mt-4 mb-6 p-0 lg:mt-0 lg:mb-0 lg:flex-row lg:p-1"> <Link to={'/'} className="font-xl font-semibold font-oswald uppercase" > <ListItem className="flex items-center gap-2 py-2 pr-4"> Home </ListItem> </Link> <NavListMenu /> <Link to={'/about-us'} className="font-xl font-semibold font-oswald uppercase" > <ListItem className="flex items-center gap-2 py-2 pr-4"> About Us </ListItem> </Link> <Link to={'/contact-us'} className="font-xl font-semibold font-oswald uppercase" > <ListItem className="flex items-center gap-2 py-2 pr-4"> Contacts Us </ListItem> </Link> </List> ); } export function NewMenubar() { const [openNav, setOpenNav] = React.useState(false); const [refetch, allcategory] = useCategory(); React.useEffect(() => { window.addEventListener( "resize", () => window.innerWidth >= 960 && setOpenNav(false) ); }, []); return ( <Navbar className="mx-auto md:mx-16 max-w-screen-xl shadow-none px-4 py-0"> <div className="flex items-center justify-between text-blue-gray-900"> <div className="w-16 p-2 md:p-0 "> <Link to={"/"}> {" "} <img className="w-full" src={logo} alt="" />{" "} </Link> </div> <div className="hidden lg:block"> <NavList /> </div> <IconButton variant="text" color="blue-gray" className="lg:hidden" onClick={() => setOpenNav(!openNav)} > {openNav ? ( <XMarkIcon className="h-6 w-6" strokeWidth={2} /> ) : ( <Bars3Icon className="h-6 w-6" strokeWidth={2} /> )} </IconButton> </div> <Collapse open={openNav}> <NavList /> </Collapse> </Navbar> ); }
import csv ALL_PLAYERS = [] class Player: def __init__(self, _id, known_as, fullname, avg, age, potential, value, position, secondary_positions, club, nationality, image_link, wage, release_clause, contract_until, joined_on, national_team_name): self._id = _id self.known_as = known_as self.fullname = fullname self.avg = avg self.age = age self.potential = potential self.value = value self.position = position self.secondary_positions = secondary_positions self.club = club self.nationality = nationality self.image_link = image_link self.wage = wage self.release_clause = release_clause self.contract_until = contract_until self.joined_on = joined_on self.national_team_name = national_team_name self.P = 0 self.G = 0 self.A = 0 self.form = 0 # add playe to list of players ALL_PLAYERS.append(self) FINAL_DATA = [] ALL_FIELDNAMES = [] UNWANTED_FIELDNAMES = [] HEADERS = ['Known As', 'Full Name', 'Overall', 'Age', 'Potential', 'Value(in Euro)', 'Positions Played', 'Best Position', 'Nationality', 'Image Link', 'Club Name', 'Wage(in Euro)', 'Release Clause', 'Contract Until', 'Joined On', 'National Team Name'] def generate_players_csv_data(ALL_CLUBS): # read csv and get all fieldnames with open("players.csv") as csvfile: csv_reader = csv.DictReader(csvfile) ALL_FIELDNAMES = [key for key in csv_reader.fieldnames] # add all players with corresponding clubs to final data for line in csv_reader: if line['Club Name'] in [club.name for club in ALL_CLUBS]: FINAL_DATA.append(line) # open the new csv file and write the headers with open("new_players.csv", "w") as outfile: csv_writer = csv.DictWriter(outfile, fieldnames=HEADERS) csv_writer.writeheader() # check for all other fields that were not inclided in headers and remove them.. unwanted_fields = [field for field in ALL_FIELDNAMES if field not in HEADERS] for line in FINAL_DATA: for field in unwanted_fields: del line[field] csv_writer.writerows(FINAL_DATA) generate_players() # add player to their respective clubs for player in ALL_PLAYERS: for club in ALL_CLUBS: if player.club == club.name: club.add_player(player) # calculate club avarage for each club for club in ALL_CLUBS: club.set_avarage() def generate_players(): for _id, player in enumerate(FINAL_DATA, start=1): player_obj = Player(_id=int(_id), known_as=player['Known As'], fullname=player['Full Name'], avg=int(player['Overall']), age=int(player['Age']), potential=int(player['Potential']), value=player['Value(in Euro)'], secondary_positions=player['Positions Played'], position=player['Best Position'], nationality=player['Nationality'], image_link=player['Image Link'], club=player['Club Name'], wage=player['Wage(in Euro)'], release_clause=player['Release Clause'], contract_until=player['Contract Until'], joined_on=player['Joined On'], national_team_name=player['National Team Name']) ALL_PLAYERS.append(player_obj)
# VITE A vite é uma ferramenta de desenvolvimento front-end que surgiu em 2020, criado pelo Evan You - mesmo criador do Vue. Ele surgiu para resolver o problema de empacotamento que o javascript possuia, já que para importar um pacote no seu projeto, como, por exemplo, o `import react from react` era preciso utilizar um terceiro serviço: Os blunders. Serviços como Webpack, Rollup e Parcel, que são exemplo de bundlers, eram necessários para viabilizar a importação de pacotes externos para dentro da aplicação. Todavia, os projetos mais robustos, que necessitavam de maiores taxas de processamento de dados, acabavam tendo um carregamento extremamente longo por conta da quantidade massiva de pacotes que o bundler estava encarregado de importar. Com o surgimento do VITE, o tempo de carregamento diminuiu expressivamente, já que ela possui algumas dependências pré-empacotadas utilizando o esbuild, que, por ser escrito em GO, pré-empacota as dependências de 10x a 100x mais rápido que os empacotadores baseados em Javascript utilizados anteriormente. A VITE também possui outros benefícios que você pode conferir acessando a documentação deles: \ https://pt.vitejs.dev/guide/why.html ## COMO USAR Essa é a base da linha de comando que devemos utilizar para criar um projeto usando o VITE:\ ```npm create vite@latest``` Mas podemos incrementar colocando em que pasta queremos criar a aplicação:\ ```# cria um projeto na pasta chamada "projeto-react"```\ ``` npm create vite@latest projeto-react``` ```# cria o projeto na pasta local```\ ```npm create vite@latest .``` Nós também podemos especificar o modelo (template) que desejamos utilizar:\ ```# cria uma aplicação dentro da pasta "projeto react" usando o template do react.js```\ ``` npm create vite@latest projeto-react --template react``` Atualmente, o VITE possui vários tipos de modelos que podem ser utilizados. Você pode conferir isso no link abaixo: https://github.com/vitejs/vite/tree/main/packages/create-vite ### INICIANDO UM SERVIDOR ``` npm install npm run dev ```
<template> <div id="delCouponModal" ref="modal" class="modal fade" tabindex="-1" aria-labelledby="delCouponModalLabel" aria-hidden="true" > <div class="modal-dialog modal-dialog-centered"> <div class="modal-content border-0"> <div class="modal-header bg-danger text-white"> <h3 id="delCouponModalLabel" class="modal-title"> <span>刪除優惠券</span> </h3> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body"> 是否刪除 <strong class="text-danger">{{ propsCoupon.title }}</strong> 優惠券(刪除後將無法恢復)。 </div> <div class="modal-footer"> <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal" > 取消 </button> <button @click="$emit('delete-coupon', propsCoupon)" type="button" class="btn btn-danger" > 確認刪除 </button> </div> </div> </div> </div> </template> <script> import modalMixin from "@/assets/js/mixins/modalMixin"; export default { emits: ["delete-coupon"], props: { propsCoupon: { type: Object, default() { return {}; }, }, }, data() { return { modal: "", }; }, mixins: [modalMixin], }; </script>
# %% ## Ben's pipeline library("AnnotationDbi") library("org.Hs.eg.db") library(RUVSeq) library('openxlsx') source("downstreamAnalysis_RNAseqFunctions.R") # %% # %% # Read in data cts = as.matrix(read.csv("../../data/processed_data/data_c_all_raw.csv", sep=',', row.names='gene')) coldata = read.csv('../../data/metadata/coldata_all_c.csv', sep=',', row.names='sample') #remove sample PNIBD26_C from cts and coldata (eventually dx'd with indeterminate IBD years after study biopsy) cts = cts[,-which(colnames(cts) == 'PNIBD26_C')] coldata = coldata[-which(rownames(coldata) == 'PNIBD26_C'),] dim(coldata) dim(cts) # %% # %% #create a new column for the sample name coldata$sample = rownames(coldata) sample = rownames(coldata) #set columns as factor coldata$status = as.factor(coldata$status) coldata$batch = as.factor(coldata$batch) coldata$sex = as.factor(coldata$sex) #make variables based on co-variates for use in removebatcheffect status = coldata$status batch = coldata$batch sexBin = coldata$sex tin = coldata$TIN #round counts to integers cts <- round(cts); #check if row names of coldata match colnames of cts all(rownames(coldata) == colnames(cts)) #adjust for batch and sex design <- as.formula(~ batch + sex) #create the dds object dds = DESeqDataSetFromMatrix(countData = cts, colData = coldata, design = design) #variance stabilizing transform vsd = vst(dds) mat= assay(vsd) # %% # %% #PCA of raw data pcaData <- plotPCA(vsd, intgroup=c("status"), ntop = 500, returnData=TRUE) percentVar <- round(100 * attr(pcaData, "percentVar")) #save the plot png("results/c/cd/pca_raw.png", width=1024, height=1024) ggplot(pcaData, aes(PC1, PC2, color=tin, shape=status)) + geom_point(size=5) + #geom_text(aes(label=sample),hjust=0, vjust=0) + xlab(paste0("PC1: ",percentVar[1],"% variance")) + ylab(paste0("PC2: ",percentVar[2],"% variance")) + coord_fixed() + theme(text = element_text(size = 24)) dev.off() # %% #remove batch effect assay(vsd) <- removeBatchEffect(assay(vsd), batch=batch, batch2 = sexBin, covariates=cbind(tin)) # %% #PCA of batch effect removed data pcaData <- plotPCA(vsd, intgroup=c("status"), ntop = 500, returnData=TRUE) percentVar <- round(100 * attr(pcaData, "percentVar")) #save the plot png("results/c/cd/pca_tin_corrected.png", width=1024, height=1024) ggplot(pcaData, aes(PC1, PC2, color=tin, shape=status)) + geom_point(size=5) + #geom_text(aes(label=sample),hjust=0, vjust=0) + xlab(paste0("PC1: ",percentVar[1],"% variance")) + ylab(paste0("PC2: ",percentVar[2],"% variance")) + coord_fixed() + theme(text = element_text(size = 24)) dev.off() # %% #RUVseq # Calculate the average gene expression of each genes and take the top 5000 highest expressed nc <- as.data.frame(assay(vsd)) nc$avg_exp <- rowSums(nc,na.rm=TRUE) / ncol(nc) # x should be your normalized matrix nc <- arrange(nc, -avg_exp)%>%dplyr::select(-avg_exp) nc <- nc[1:5000,] # Calculate the variance of each genes, and choose the lowest 1000 genes as the negative control gene nc$row_stv <- rowSds(as.matrix(nc))/(rowSums(nc,na.rm=TRUE) / ncol(nc)) nc <- arrange(nc, row_stv) %>% dplyr::select(-row_stv) nc <- nc[1:1000,] ##The newSeqExpressionSet is given the raw count matrix, phenotypic data, and then the names of the samples # Create a new Expression Set and perform an upper quartile normalization nc <- round(nc*1000) set <- newSeqExpressionSet(as.matrix(nc),phenoData = data.frame(colData(dds),row.names=colnames(nc))) ##Run RUV ##k refers to the number of "unwanted factors of variation", set as 1 based on correlation with outcome and deseq results set_ruv<- RUVg(set, rownames(nc), k=1) # %% #RLE plot png("results/c/cd/RUV_rle_plot_1.png") plotRLE(set_ruv, outline=FALSE, ylim=c(-0.1, 0.1), col=as.numeric(as.factor(coldata$status))) dev.off() # %% # Creates a PCA plot based on negative control genes. Should not see much of a pattern. png("results/c/cd/RUV_pca_1.png") plotPCA(set, col=as.numeric(as.factor(coldata$status)), k=2, cex=1.2) dev.off() # %% #save the coldata + RUV factor ruv_data<-pData(set_ruv) # write.xlsx(ruv_data, file="results/c/cd/ruv_data_1.xlsx") # %% #redo data-prep steps with the ruv_data dataframe #set columns as factor ruv_data$status = as.factor(ruv_data$status) ruv_data$batch = as.factor(ruv_data$batch) ruv_data$sex = as.factor(ruv_data$sex) status = ruv_data$status batch = ruv_data$batch sexBin = ruv_data$sex tin = ruv_data$TIN w_1 = ruv_data$W_1 # %% # Set up new DESeq object to perform differential analyses dds1 <- DESeqDataSetFromMatrix(countData=cts, colData=ruv_data, design = ~batch + sex + TIN + W_1 + status) # %% vsd = vst(dds) mat= assay(vsd) assay(vsd) <- removeBatchEffect(assay(vsd), batch=batch, batch2=sexBin, covariates=cbind(tin + w_1)) #save the PCA, accounting for batch effect, sex, tin score, and the RUV factor (W_1) pcaData <- plotPCA(vsd, intgroup=c("status"), ntop = 500, returnData=TRUE) percentVar <- round(100 * attr(pcaData, "percentVar")) png("results/c/cd/pca_cd_tin_w1_new.png", width=1024, height=1024) ggplot(pcaData, aes(PC1, PC2, color=status)) + geom_point(size=5) + # geom_text(aes(label=sample),hjust=0, vjust=0) + xlab(paste0("PC1: ",percentVar[1],"% variance")) + ylab(paste0("PC2: ",percentVar[2],"% variance")) + coord_fixed() + scale_color_manual(values = c("nonIBD" = "#0066cc", "CD" = "#990000")) + theme(text = element_text(size = 24)) dev.off() # %% #now the DESeq analysis dds1 <- DESeqDataSetFromMatrix(countData=cts,colData=ruv_data,design = ~batch + sex + TIN + W_1 + status) #filter out lowly expressed genes y <- DGEList(counts=counts(dds1), group=coldata$status) keep <- filterByExpr(y) table(keep) y <- y[keep,] dds1 <- dds1[keep,] #run DESeq dds1 <- DESeq(dds1) #get the results, with nonIBD as the reference res <- results(dds1, contrast=c('status', 'CD', 'nonIBD')) #order the results by adjusted p-value resOrdered <- res[order(res$padj),] #create a column named gene which is the gene name resOrdered$gene = rownames(resOrdered) #set gene as the first column by making the last column the first column resOrdered = resOrdered[,c(7, 1, 2, 3, 4, 5, 6)] #plot a histogram of the p-values png("results/c/cd/pvals_hist.png", width=512, height=512) hist(resOrdered$pvalue, breaks=20, col="grey", main="p-value distribution", xlab="p-value") dev.off() #save the results write.csv(resOrdered, file = "results/c/cd/results_deseq.csv", sep = ",", row.names = FALSE, col.names = TRUE) #save the number of genes that are significant deg_counts <- data.frame('colon' = c(sum(resOrdered$padj < 0.05))) write.xlsx(deg_counts, file = "results/c/cd/deg_counts.xlsx", sheetName='DEGs', row.names = TRUE, col.names = TRUE) # %% # %% #same thing for the ileum data # Read in data cts = as.matrix(read.csv("../../data/processed_data/data_i_all_raw.csv", sep=',', row.names='gene')) coldata = read.csv('../../data/metadata/coldata_all_i.csv', sep=',', row.names='sample') dim(coldata) dim(cts) coldata$sample = rownames(coldata) sample = rownames(coldata) #set columns as factor coldata$status = as.factor(coldata$status) coldata$batch = as.factor(coldata$batch) coldata$sex = as.factor(coldata$sex) status = coldata$status batch = coldata$batch sexBin = coldata$sex tin = coldata$TIN #round counts to integers cts <- round(cts); #check if row names of coldata match colnames of cts all(rownames(coldata) == colnames(cts)) #adjust for batch and sexBin design <- as.formula(~ batch + sex) #create the dds object dds = DESeqDataSetFromMatrix(countData = cts, colData = coldata, design = design) vsd = vst(dds) mat= assay(vsd) design0 <- model.matrix(~coldata$status, data=data.frame(assay(vsd))) pcaData <- plotPCA(vsd, intgroup=c("status"), ntop = 500, returnData=TRUE) percentVar <- round(100 * attr(pcaData, "percentVar")) #save the plot png("results/i/cd/pca_raw.png", width=1024, height=1024) ggplot(pcaData, aes(PC1, PC2, color=tin, shape=status)) + geom_point(size=5) + #geom_text(aes(label=sample),hjust=0, vjust=0) + xlab(paste0("PC1: ",percentVar[1],"% variance")) + ylab(paste0("PC2: ",percentVar[2],"% variance")) + coord_fixed() + theme(text = element_text(size = 24)) dev.off() assay(vsd) <- removeBatchEffect(assay(vsd), batch=batch, batch2 = sexBin, covariates=cbind(tin)) pcaData <- plotPCA(vsd, intgroup=c("status"), ntop = 500, returnData=TRUE) percentVar <- round(100 * attr(pcaData, "percentVar")) #save the plot png("results/i/cd/pca_tin_corrected.png", width=1024, height=1024) ggplot(pcaData, aes(PC1, PC2, color=tin, shape=status)) + geom_point(size=5) + #geom_text(aes(label=sample),hjust=0, vjust=0) + xlab(paste0("PC1: ",percentVar[1],"% variance")) + ylab(paste0("PC2: ",percentVar[2],"% variance")) + coord_fixed() + theme(text = element_text(size = 24)) dev.off() # Calculate the average gene expression of each genes and take the top 5000 highest expressed nc <- as.data.frame(assay(vsd)) nc$avg_exp <- rowSums(nc,na.rm=TRUE) / ncol(nc) # x should be your normalized matrix nc <- arrange(nc, -avg_exp)%>%dplyr::select(-avg_exp) nc <- nc[1:5000,] # Calculate the variance of each genes, and choose the lowest 1000 genes as the negative control gene nc$row_stv <- rowSds(as.matrix(nc))/(rowSums(nc,na.rm=TRUE) / ncol(nc)) nc <- arrange(nc, row_stv) %>% dplyr::select(-row_stv) nc <- nc[1:1000,] ##The newSeqExpressionSet is given the raw count matrix, phenotypic data, and then the names of the samples # Create a new Expression Set and perform an upper quartile normalization nc <- round(nc*1000) set <- newSeqExpressionSet(as.matrix(nc),phenoData = data.frame(colData(dds),row.names=colnames(nc))) #set <- betweenLaneNormalization(set, which="upper") ##Run RUV ##k refers to the number of "unwanted factors of variation" (kinda like PCs in PCA), with rows referring to the samples ##and columns to the factors. You can play around with k, but 5 is a good starting number. set_ruv<- RUVg(set, rownames(nc), k=1) png("results/i/cd/RUV_rle_plot_1.png") plotRLE(set_ruv, outline=FALSE, ylim=c(-0.1, 0.1), col=as.numeric(as.factor(coldata$status))) dev.off() # Creates a PCA plot of the negative control genes. Should not see much of a pattern. Write out learned RUVseq factors png("results/i/cd/RUV_pca_1.png") plotPCA(set, col=as.numeric(as.factor(coldata$status)), k=2, cex=1.2) dev.off() ruv_data<-pData(set_ruv) # write.csv(ruv_data, file="results/i/cd/ruv_data_1.csv") #set columns as factor ruv_data$status = as.factor(ruv_data$status) ruv_data$batch = as.factor(ruv_data$batch) ruv_data$sex = as.factor(ruv_data$sex) status = ruv_data$status batch = ruv_data$batch sexBin = ruv_data$sex tin = ruv_data$TIN w_1 = ruv_data$W_1 # Set up new DESeq object to perform differential analyses dds1 <- DESeqDataSetFromMatrix(countData=cts,colData=ruv_data,design = ~batch + sex + TIN + W_1 + status) vsd = vst(dds) mat= assay(vsd) assay(vsd) <- removeBatchEffect(assay(vsd), batch=batch, batch2=sexBin, covariates=cbind(tin + w_1)) pcaData <- plotPCA(vsd, intgroup=c("status"), ntop = 500, returnData=TRUE) percentVar <- round(100 * attr(pcaData, "percentVar")) #save the plot png("results/i/cd/pca_cd_tin_w1.png", width=1024, height=1024) ggplot(pcaData, aes(PC1, PC2, color=status)) + geom_point(size=5) + #geom_text(aes(label=sample),hjust=0, vjust=0) + xlab(paste0("PC1: ",percentVar[1],"% variance")) + ylab(paste0("PC2: ",percentVar[2],"% variance")) + coord_fixed() + scale_color_manual(values = c("nonIBD" = "#0066cc", "CD" = "#990000")) + theme(text = element_text(size = 24)) dev.off() # Set up new DESeq object to perform differential analyses dds1 <- DESeqDataSetFromMatrix(countData=cts,colData=ruv_data,design = ~batch + sex + TIN + W_1 + status) y <- DGEList(counts=counts(dds1), group=coldata$status) keep <- filterByExpr(y) table(keep) y <- y[keep,] dds1 <- dds1[keep,] dds1 <- DESeq(dds1) res <- results(dds1, contrast=c('status', 'CD', 'nonIBD')) resOrdered <- res[order(res$padj),] #create a column named gene which is the gene name resOrdered$gene = rownames(resOrdered) #set gene as the first column by making the last column the first column resOrdered = resOrdered[,c(7, 1, 2, 3, 4, 5, 6)] #plot a histogram of the p-values png("results/i/cd/pvals_hist.png", width=512, height=512) hist(resOrdered$pvalue, breaks=20, col="grey", main="p-value distribution", xlab="p-value") dev.off() write.csv(resOrdered, file = "results/i/cd/results_deseq.csv", sep = ",", row.names = FALSE, col.names = TRUE) deg_counts = data.frame(matrix(ncol=2, nrow=0)) col_names = c('tissue', 'n_DEGs') colnames(deg_counts) = col_names sum(resOrdered$padj < 0.05) deg_counts[nrow(deg_counts)+1,] <- c('ileum', sum(resOrdered$padj < 0.05)) write.xlsx(deg_counts, file = "results/i/cd/deg_counts.xlsx", sheetName='DEGs', row.names = TRUE, col.names = TRUE) # %%
#ifndef PROCESS_H #define PROCESS_H #include "../include/kernel/config.h" #include "task.h" #include <stdbool.h> #include <stdint.h> #define PROCESS_FILE_TYPE_ELF 0 #define PROCESS_FILE_TYPE_BIN 1 typedef unsigned char PROCESS_FILE_TYPE; struct process_allocation { void* ptr; size_t size; }; struct cmd_arg { char arg[512]; struct cmd_arg* next; }; struct process_args { int argc; char** argv; }; struct process { uint16_t id; char file_name[ENKI_MAX_PATH]; PROCESS_FILE_TYPE file_type; struct task* task; struct process_allocation allocations[ENKI_MAX_PGM_ALLOCATIONS]; union { void* addr; // process memory (code and data segments) struct elf_file* elf_file; }; void* stack; // stack memory uint32_t size; // size of process memory struct keyboard_buffer { char buffer[ENKI_KEYBOARD_BUFFER_SIZE]; int tail; int head; } keyboard; struct process_args args; }; // fetch current process struct process* process_get_current(); // fetch process by id struct process* process_get(int id); // switch current process int process_switch(struct process* proc); // load a process into an open slot int process_load(const char* file_name, struct process** proc); // load process and set it to current process int process_load_switch(const char* file_name, struct process** proc); // load file as process into slot int process_load_slot(const char* file_name, struct process** proc, int proc_slot); // allocate memory for given process void* process_malloc(struct process* proc, size_t size); // free memory in given process void process_free(struct process* proc, void* to_free); // get argc and argv of process void process_get_args(struct process* proc, int* argc, char*** argv); // inject command arguments into process int process_inject_args(struct process* proc, struct cmd_arg* root_arg); // load another shell instance struct process* process_new_shell(); // terminate a given process and free its memory int process_terminate(struct process* proc); #endif
from transformers import RobertaForSequenceClassification import torch import torch.nn as nn import torch.nn.functional as F # CUSTOM MODULES class CustomClassifier(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.out_proj = nn.Linear(config.hidden_size, config.num_labels) def forward(self, features, **kwargs): '''Build a custom classifier head for ChemBERTa''' x = features[:, 0, :] x = self.dropout(F.relu(self.dense(x))) x = self.dropout(F.relu(self.dense(x))) x = self.dropout(F.relu(self.dense(x))) x = self.out_proj(x) x = torch.tanh(x) return x class VerboseExecution(nn.Module): def __init__(self, model): super().__init__() self.model = model for name, layer in self.model.named_modules(): if 'roberta.encoder.layer.2.output' in name: layer.__name__ = name layer.register_forward_hook( lambda layer, _, output: print(f'{layer.__name__}: {output.shape}') ) def forward(self, *args): return self.model(*args) class ActivationHook(nn.Module): def __init__(self, model, layers) -> None: super().__init__() self.model = model self.layers = layers self._activations = {layer: torch.empty(0) for layer in layers} for layer_name in layers: layer = dict([*self.model.named_modules()])[layer_name] layer.register_forward_hook(self.getActivation(layer_name)) def getActivation(self, layer_name: str): def fn(_, __, output): self._activations[layer_name] = output return fn def forward(self, *args): return self.model(*args) # MODELS class Model_Base(): def __init__(self, model_link): self.model = RobertaForSequenceClassification.from_pretrained(model_link, num_labels = 1, output_attentions=True) class Model_CustomClassifier(Model_Base): def __init__(self, model_link): super().__init__(model_link) self.model.classifier = CustomClassifier(config=self.model.config)
import React, { Component } from 'react'; import {render} from 'react-dom'; import CheckList from './CheckList'; import marked from 'marked' class Card extends Component { constructor() { super(...arguments); this.state = { showDetails: false } }; toggleDetails(){ this.setState({showDetails: !this.state.showDetails}) } render() { let cardDetails; if (this.state.showDetails) { cardDetails = ( <div className="card__details"> <span dangerouslySetInnerHTML={{__html:marked(this.props.description)}} /> <CheckList cardId={this.props.id} tasks={this.props.tasks} /> </div> ); }; let sideColor = { backgroundColor:this.props.color, position:'absolute', zIndex : -1, top: 0, bottom:0, left : 0, width : 7 } return ( <div className="card"> <div style={sideColor} /> <div className={ this.state.showDetails ? "card__title card__title--is-open" : "card__title" } onClick={this.toggleDetails.bind(this)}>{this.props.title}</div> {cardDetails} </div> ); } } export default Card;
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="css/style-for-login.css"> </head> <body> <?php include ('dbconnect.php'); ?> <div class="main"> <?php $displayLoginForm = true; if (isset($_POST['signup'])) { // Handle signup form submission $displayLoginForm = false; // include 'signup.php'; } elseif (isset($_POST['login'])) { // Handle login form submission $displayLoginForm = true; // include 'login.php'; } $checkboxState = $displayLoginForm ? 'checked="true"' : ''; ?> <input type="checkbox" id="chk" aria-hidden="true" <?php echo $checkboxState; ?>> <div class="signup"> <form action="" method="post" onsubmit="return validateSignupForm()"> <label for="chk" aria-hidden="true">Sign up</label> <input type="email" id="signup-email" name="email" placeholder="Email" required=""> <span id="signup-email-error" class="error"> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_POST['signup'])) { $user = $_POST['email']; $password = $_POST['pswd']; $encpassword = md5($password); $check_query = "SELECT * FROM user WHERE email = '$user'"; $check_result = mysqli_query($conn, $check_query); if (mysqli_num_rows($check_result) > 0) { echo "Email already exists. Please choose a different Email."; } else { // Insert new user if username doesn't exist $insert_query = "INSERT INTO user (email, password) VALUES ('$user', '$encpassword')"; $insert_result = mysqli_query($conn, $insert_query); if ($insert_result) { echo "<script>"; echo "sessionStorage.setItem('email', '$user');"; echo "sessionStorage.setItem('bool', 'true');"; echo "window.location.href = 'flightchoose.php';"; echo "</script>"; exit; } else { echo "The record was not inserted successfully because of this error: " . mysqli_error($conn); } } } } ?> </span> <input type="password" id="signup-password" name="pswd" placeholder="Enter Password" required=""> <span id="signup-password-error" class="error"></span> <input type="password" id="signup-confirm-password" name="confirm-pswd" placeholder="Enter Confirm Password" required=""> <span id="signup-confirm-password-error" class="error"></span> <button type="submit" name="signup">Sign up</button> </form> </div> <div class="login"> <form action="" method="post" onsubmit="return validateLoginForm()"> <label for="chk" aria-hidden="true">Login</label> <input type="email" id="login-email" name="email" placeholder="Email" required=""> <span id="login-email-error" class="error"> </span> <input type="password" id="login-password" name="pswd" placeholder="Password" required=""> <span id="login-password-error" class="error"> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_POST['login'])) { $user = $_POST['email']; $password = $_POST['pswd']; $encpassword = md5($password); $sql = "SELECT * FROM user WHERE email='$user' and password='$encpassword';"; $result = mysqli_query($conn, $sql); $num = mysqli_num_rows($result); if ($num > 0) { echo "<script>"; echo "sessionStorage.setItem('email', '$user');"; echo "sessionStorage.setItem('bool', 'true');"; echo "window.location.href = 'flightchoose.php';"; echo "</script>"; exit; } else { echo "<b>Login UnSuccessful</b>"; } } } ?> </span> <button type="submit" name="login">Login</button> </form> </div> </div> <script> function validateEmail(email) { // Regular expression for basic email validation const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); } function validateSignupForm() { const email = document.getElementById('signup-email').value; const password = document.getElementById('signup-password').value; const confirmPassword = document.getElementById('signup-confirm-password').value; let isValid = true; // Clear previous errors document.getElementById('signup-email-error').textContent = ''; document.getElementById('signup-password-error').textContent = ''; document.getElementById('signup-confirm-password-error').textContent = ''; // Validate email if (!validateEmail(email)) { document.getElementById('signup-email-error').textContent = 'Invalid email format'; isValid = false; } // Validate password length if (password.length < 8) { document.getElementById('signup-password-error').textContent = 'Password must be at least 8 characters long'; isValid = false; } // Validate password match if (password !== confirmPassword) { document.getElementById('signup-confirm-password-error').textContent = 'Passwords do not match'; isValid = false; } return isValid; } function validateLoginForm() { const email = document.getElementById('login-email').value; const password = document.getElementById('login-password').value; let isValid = true; // Clear previous errors document.getElementById('login-email-error').textContent = ''; // Validate email if (!validateEmail(email)) { document.getElementById('login-email-error').textContent = 'Invalid email format'; isValid = false; } return isValid; } </script> </body> </html>
package com.scaler.core.java_3_advance_3.dsa_26_linked_list_3; import com.scaler.core.java_3_advance_3.dsa_26_linked_list_3.model.Node; /** * @author Deepak Kumar Rai * @created 20/10/23 * @project scaler_course_code */ public class Q1_Delete_a_node_in_DDL { /** * Delete a node in Doubly LinkedList * Note 1: Node reference/address is given in Doubly LinkedList * Note 2: Given Node is not a head/tail node * <></> * <></> * Observation: To delete a node in Doubly LinkedList, the current node address is sufficient! * **/ private static void deleteNode(Node deleteNode /* Can't be head or tail */) { deleteNode.prev.next = deleteNode.next; deleteNode.next.prev = deleteNode.prev; deleteNode.next = null; // isolating the node, deallocating the memory for language like C/C++, can skip for java deleteNode.prev = null; } public static void main(String[] args) { Node node1 = new Node(11); Node node2 = new Node(12); Node node3 = new Node(13); Node node4 = new Node(14); Node node5 = new Node(15); node1.next = node2; node2.prev = node1; node2.next = node3; node3.prev = node2; node3.next = node4; node4.prev = node3; node4.next = node5; node5.prev = node4; deleteNode(node3); printDLL(node1); } private static void printDLL(Node head) { while (head != null) { System.out.print(head.data); if (head.next != null) System.out.print(" -> "); head = head.next; } } }
<?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class VehicleTypeResources extends JsonResource { /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return [ 'id' => $this->id, 'service_locations' => new ServiceLocationsResources($this->service_location), 'name' => $this->name, 'icon' => $this->icon, 'capacity' => $this->capacity, 'is_accept_share_ride' => $this->is_accept_share_ride(), 'status' => $this->status(), 'create_dates' => [ 'created_at_human' => $this->created_at->diffForHumans(), 'created_at' => $this->created_at ], 'update_dates' => [ 'updated_at_human' => $this->updated_at->diffForHumans(), 'updated_at' => $this->updated_at ], ]; } }
import React from 'react'; import { connect } from 'react-redux'; import { colorsByStages } from '../colors'; import { Head, Body, BodyPlaceholder } from './styled/Modal'; import Seat from './SeatSummary'; import { useTranslation } from '@dinify/common/src/lib/i18n'; const ModalTable = ({ shown, payload: { tableId }, tableMap, seatList }) => { if (!shown) return (<div />); const { t } = useTranslation(); const table = tableMap[tableId] || {}; const seats = seatList.filter((seat) => seat.tableId === tableId); return ( <div> <Head bg='rgba(0,0,0,0.3)'> {t('table-number')} {table.number} </Head> <Body> {seats.length < 1 ? <BodyPlaceholder>{t('no-guests-at-this-table')}</BodyPlaceholder> : <div> {seats.map((seat) => <Seat seat={seat} key={seat.id} /> )} </div> } </Body> </div> ); } export default connect( state => ({ tableMap: state.table.all }) )(ModalTable);
import { CartContext } from "@/contexts/CartContext"; import Link from "next/link"; import { useContext, useEffect } from "react"; import Buttton from "../utils/Button"; export default function Cart({ orderPage = false, modalCloser }) { const { cartItems, removeItem, clearCart, increaseItemQuantity, decreaseItemQuantity, } = useContext(CartContext); const handleRemoveItem = (index) => { removeItem(index); }; const handleClearCart = () => { clearCart(); }; const handleIncrease = (index) => { increaseItemQuantity(index); }; const handleDecrease = (index) => { decreaseItemQuantity(index); }; const orderHandler = () => {}; const getTotalPrice = () => { let total = 0; cartItems.forEach((item) => { total += item.offer_price ? item.offer_price * item.quantity : item.price * item.quantity; }); return total; }; useEffect(() => { if (!orderPage) { if (cartItems < 1) modalCloser(); } }, [cartItems]); return ( <div className="flex flex-col gap-3 mt-4"> {cartItems?.length > 0 && cartItems?.map((item, i) => { const name = item?.name; const offer_price = item?.offer_price; const price = item?.price; const quantity = item?.quantity; return ( <div key={item.id} className="flex justify-between border-b"> <div> <h4>{name}</h4> <div className="text-golden text-md font-semibold"> {offer_price ? ( <> <del className="text-sm text-gray-500">{price}</del> <span className="ml-2">{offer_price} ৳</span> </> ) : ( <span>{price} ৳</span> )} </div> </div> <div className="text-lg text-golden font-semibold"> <div className="div"> <span className="text-gray-700 font-normal">x</span> ( {quantity}) <span className="text-gray-700">=</span>{" "} {offer_price ? offer_price * quantity : price * quantity} ৳ </div> {!orderPage && ( <div className="flex gap-3 py-1"> {/* decrese */} <button onClick={() => handleDecrease(i)}> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5" > <path strokeLinecap="round" strokeLinejoin="round" d="M15 12H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> </button> {/* increse */} <button onClick={() => handleIncrease(i)}> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5" > <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> </button> <button onClick={() => handleRemoveItem(i)}> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5" > <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" /> </svg> </button> </div> )} </div> </div> ); })} <div className="flex justify-between"> <div className="font-semibold text-xl">Total</div> <div className="font-semibold text-xl"> {parseFloat(getTotalPrice()).toFixed(2)} ৳ </div> </div> {!orderPage && ( <div className="flex flex-col md:flex-row justify-between mt-4 gap-2"> <button onClick={handleClearCart} className="py-3 px-3 text-red-500 border border-red-500 hover:text-white bg-white hover:bg-red-500 rounded hover:duration-300" > Clear Tray </button> <Link href={"/orders"}> <Buttton onClickHandler={orderHandler} text="Continue Order" width={`w-full`} /> </Link> </div> )} </div> ); }
use std::sync::{mpsc, Arc, Mutex}; use std::thread; use crate::Opts; type Job = Box<dyn FnOnce(Arc<Opts>) + Send + 'static>; struct NewJob { job: Job, opts: Arc<Opts> } enum Message { NewJob(NewJob), Terminate, } pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Message>, opts: Arc<Opts> } impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize, opts: Arc<Opts>) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))) } ThreadPool { workers, sender, opts } } /// Creates an execution job for the provided closure. /// /// The closure will be executed on the first thread to accept the job. pub fn execute<F>(&self, f: F) where F: FnOnce(Arc<Opts>) + Send + 'static, { let closure = Box::new(f); let job = NewJob{ job: closure, opts: self.opts.clone()}; self.sender.send(Message::NewJob(job)).unwrap(); } } impl Drop for ThreadPool { /// Cleanly shuts down all threads fn drop(&mut self) { println!("Sending terminate message to all workers."); for _ in &self.workers { self.sender.send(Message::Terminate).unwrap(); } println!("Shutting down all workers."); for worker in &mut self.workers { println!("Shutting down worker {}", worker.id); if let Some(thread) = worker.thread.take() { thread.join().unwrap(); } } } } struct Worker { id: usize, thread: Option<thread::JoinHandle<()>>, } impl Worker { /// Listens for jobs and executes upon receiving. fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker { let thread = thread::spawn(move || loop { let message = receiver.lock().unwrap().recv().unwrap(); match message { Message::NewJob(job) => { (job.job)(job.opts); } Message::Terminate => { println!("Worker {} was told to terminate.", id); break; } } }); Worker { id, thread: Some(thread), } } }
from selenium import webdriver from selenium.webdriver.common.by import By import time username = 'standard_user' password = 'secret_sauce' driver = webdriver.Chrome() # write a selenium script to open https://www.saucedemo.com/ and wait for 3 sec # open the window in maximized mode driver.maximize_window() driver.get('https://www.saucedemo.com/') time.sleep(3) # declare a new variable which represent the element div form the html website # using the css selector and call the var - swag_label swag_label = driver.find_element(By.CSS_SELECTOR, '#root > div > div.login_logo') # print the text from the website print(swag_label.text) # declare a new variable which represent the input element by css selector username_input = driver.find_element(By.CSS_SELECTOR, '#user-name') # this function takes str and send it to the website as input username_input.send_keys(username) # enter the password for the user 'secret_sauce' password_input = driver.find_element(By.CSS_SELECTOR, '#password') password_input.send_keys(password) login_btn = driver.find_element(By.CSS_SELECTOR, '#login-button') login_btn.click() time.sleep(5) if driver.current_url == 'https://www.saucedemo.com/inventory.html': print('login test pass') else: print('login test fail') driver.close()
<?php namespace AcMarche\Edr\Enfant\Repository; use AcMarche\Edr\Doctrine\OrmCrudTrait; use AcMarche\Edr\Entity\Animateur; use AcMarche\Edr\Entity\Enfant; use AcMarche\Edr\Entity\Jour; use AcMarche\Edr\Entity\Scolaire\AnneeScolaire; use AcMarche\Edr\Entity\Scolaire\Ecole; use AcMarche\Edr\Jour\Repository\JourRepository; use AcMarche\Edr\Presence\Repository\PresenceRepository; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\ORM\QueryBuilder; use Doctrine\Persistence\ManagerRegistry; /** * @method Enfant|null find($id, $lockMode = null, $lockVersion = null) * @method Enfant|null findOneBy(array $criteria, array $orderBy = null) * @method Enfant[] findAll() * @method Enfant[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ final class EnfantRepository extends ServiceEntityRepository { use OrmCrudTrait; public function __construct( ManagerRegistry $managerRegistry, private readonly JourRepository $jourRepository, private readonly PresenceRepository $presenceRepository ) { parent::__construct($managerRegistry, Enfant::class); } /** * @return Enfant[] */ public function findAllActif(): array { return $this->getNotArchivedQueryBuilder()->getQuery()->getResult(); } /** * @param $keyword * * @return Enfant[] */ public function findByName(string $keyword, bool $actif = true, int $max = 50): array { $queryBuilder = $this->getOrCreateQueryBuilder() ->andWhere('enfant.nom LIKE :keyword OR enfant.prenom LIKE :keyword') ->setParameter('keyword', '%' . $keyword . '%'); if ($actif) { $queryBuilder->andWhere('enfant.archived = 0'); } $queryBuilder->setMaxResults($max); return $queryBuilder->getQuery()->getResult(); } /** * @param array $ecoles * * @return Enfant[] */ public function findByEcoles(iterable $ecoles): array { return $this->getNotArchivedQueryBuilder() ->andWhere('enfant.ecole IN (:ecoles)') ->setParameter('ecoles', $ecoles) ->getQuery()->getResult(); } /** * @param array $ecoles * * @return Enfant[] */ public function findByEcolesForEcole(iterable $ecoles): array { return $this->getNotArchivedQueryBuilder() ->andWhere('enfant.ecole IN (:ecoles)') ->setParameter('ecoles', $ecoles)->andWhere('enfant.accueil_ecole = 1') ->getQuery()->getResult(); } /** * J'exclus les enfants sans tuteur ! * * @return Enfant[] */ public function findByEcolesForInscription(Ecole $ecole): array { return $this->getNotArchivedQueryBuilder() ->andWhere('enfant.ecole = :ecole') ->setParameter('ecole', $ecole) ->andWhere('relations IS NOT NULL')->andWhere('enfant.accueil_ecole = 1') ->getQuery()->getResult(); } /** * @return Enfant[] */ public function findOrphelins(): array { return $this->getOrCreateQueryBuilder() ->andWhere('enfant.relations IS EMPTY') ->getQuery()->getResult(); } /** * @return Enfant[] */ public function search(?string $nom, ?Ecole $ecole, ?AnneeScolaire $anneeScolaire, ?bool $archived): array { $queryBuilder = $this->getOrCreateQueryBuilder(); if ($nom) { $queryBuilder->andWhere('enfant.nom LIKE :keyword OR enfant.prenom LIKE :keyword') ->setParameter('keyword', '%' . $nom . '%'); } if ($ecole instanceof Ecole) { $queryBuilder->andWhere('ecole = :ecole') ->setParameter('ecole', $ecole); } if ($anneeScolaire instanceof AnneeScolaire) { $queryBuilder->andWhere('enfant.annee_scolaire = :annee') ->setParameter('annee', $anneeScolaire); } match ($archived) { true | false => $queryBuilder->andwhere('enfant.archived = :archive') ->setParameter('archive', $archived), default => $queryBuilder->andwhere('enfant.archived = :archive') ->setParameter('archive', 0), }; return $queryBuilder->getQuery()->getResult(); } public function searchForEcole(iterable $ecoles, ?string $nom, bool $strict = true) { $queryBuilder = $this->getNotArchivedQueryBuilder(); if ($nom) { $queryBuilder->andWhere('enfant.nom LIKE :keyword OR enfant.prenom LIKE :keyword') ->setParameter('keyword', '%' . $nom . '%'); } $queryBuilder->andWhere('enfant.ecole IN (:ecoles)') ->setParameter('ecoles', $ecoles); if ($strict) { $queryBuilder->andWhere('enfant.accueil_ecole = 1'); } return $queryBuilder->getQuery()->getResult(); } /** * @return array|Enfant[] */ public function findAllForAnimateur(Animateur $animateur): array { $queryBuilder = $this->getNotArchivedQueryBuilder(); $jours = $this->jourRepository->findByAnimateur($animateur); if ([] === $jours) { return []; } $presences = $this->presenceRepository->findPresencesByJours($jours); return $queryBuilder ->andWhere('presences IN (:presences)') ->setParameter('presences', $presences)->getQuery()->getResult(); } /** * @return array|Enfant[] */ public function searchForAnimateur(Animateur $animateur, ?string $nom = null, ?Jour $jour = null): array { $queryBuilder = $this->getNotArchivedQueryBuilder(); $jours = $jour instanceof Jour ? [$jour] : $this->jourRepository->findByAnimateur($animateur); if ([] === $jours) { return []; } $presences = $this->presenceRepository->findPresencesByJours($jours); if ($nom) { $queryBuilder->andWhere('enfant.nom LIKE :keyword OR enfant.prenom LIKE :keyword') ->setParameter('keyword', '%' . $nom . '%'); } return $queryBuilder ->andWhere('presences IN (:presences)') ->setParameter('presences', $presences)->getQuery()->getResult(); } public function findDoublon(): array { return $this->createQueryBuilder('enfant') ->select('count(enfant.nom) as lignes, enfant.nom, enfant.prenom') ->addGroupBy('enfant.nom') ->addGroupBy('enfant.prenom') ->getQuery()->getResult(); } private function getOrCreateQueryBuilder(): QueryBuilder { return $this->createQueryBuilder('enfant') ->leftJoin('enfant.ecole', 'ecole', 'WITH') ->leftJoin('enfant.annee_scolaire', 'annee_scolaire', 'WITH') ->leftJoin('enfant.sante_fiche', 'sante_fiche', 'WITH') ->leftJoin('enfant.relations', 'relations', 'WITH') ->leftJoin('enfant.presences', 'presences', 'WITH') ->addSelect('ecole', 'relations', 'sante_fiche', 'annee_scolaire', 'presences') ->addOrderBy('enfant.nom', 'ASC'); } private function getNotArchivedQueryBuilder(): QueryBuilder { return $this->getOrCreateQueryBuilder() ->andWhere('enfant.archived = 0'); } }
import 'package:flutter/foundation.dart'; import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; class UtilsSQLite { static Future<Database?> connect(String filePath) async { Database? database; // Initialitzar com a null try { database = await openDatabase( join(await getDatabasesPath(), filePath), onCreate: (db, version) { // En cas que la Base de Dades no existeixi, es crea aquí. // En cas de necessitar-ho, es poden executar declaracions d'SQL per crear taules. }, version: 1, ); } catch (e) { if (kDebugMode) { print("Error opening database: $e"); } } return database; } static Future<void> disconnect(Database database) async { await database.close(); if (kDebugMode) { print("Database disconnected"); } } static Future<List<String>> listTables(Database database) async { List<String> tables = []; try { List<Map<String, dynamic>> result = await database.rawQuery( "SELECT name FROM sqlite_master WHERE type='table'"); for (Map<String, dynamic> row in result) { tables.add(row['name'] as String); } } catch (e) { if (kDebugMode) { print("Error listing tables: $e"); } } return tables; } static Future<int> queryUpdate(Database database, String sql) async { int result = 0; try { result = await database.rawUpdate(sql); } catch (e) { if (kDebugMode) { print("Error updating database: $e"); } } return result; } static Future<List<Map<String, dynamic>>> querySelect( Database database, String sql) async { List<Map<String, dynamic>> result = []; try { result = await database.rawQuery(sql); } catch (e) { if (kDebugMode) { print("Error selecting from database: $e"); } } return result; } }
{% extends "base.html" %} {% block title %} Clientes {% endblock %} {% block content %} <div class="container bg-body-tertiary col-10"> <div class="row"> <div class="col-12 d-flex justify-content-around d-flex align-items-end"> <h2 class="mt-5">Clientes</h2> <a href="{% url 'client_form' %}" class="btn btn-success mb-2">Añadir Cliente</a> </div> <div class="shadow-sm card p-3"> <table id="myTable" class="table table-striped" style="width: 100%;"> <thead> <tr> <th scope="col">id</th> <th scope="col">Nombre</th> <th scope="col">Apellido</th> <th scope="col">Numero</th> <th scope="col">Correo</th> <th scope="col">Documento</th> <th scope="col">Dirección</th> <th scope="col">Acciones</th> </tr> </thead> <tbody> {% for customer in all_customers %} <tr> <td>{{ customer.id }}</td> <td>{{ customer.first_name }}</td> <td>{{ customer.last_name }}</td> <td>{{ customer.phone_number }}</td> <td>{{ customer.email }}</td> <td>{{ customer.document }}</td> <td>{{ customer.address }}</td> <td> <a class="btn btn-warning btn-sm" href="{% url 'customer_edit_form' id=customer.id%}" title="edit link"> <i class="bi bi-pencil-fill"></i> </a> <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#delete{{customer.id}}"> <i class="bi bi-trash3-fill"></i> </button> <div class="modal fade" id="delete{{customer.id}}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Eliminar usuario numero: {{customer.id}} </h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ¿Estas seguro de eliminar al cliente: {{customer.first_name}} {{customer.last_name}}? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <a class="btn btn-danger" href="{% url 'delete_customer' id=customer.id %}">Eliminar</a> </div> </div> </div> </div> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> {% endblock %}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="overflow-hidden" onload="init()"> <h1 class="font-semibold text-center text-2xl py-6 md:py-10 text-purple-600">Detectando Encomendas</h1> <section class="flex items-center justify-center w-screen md:gap-8 flex-col h-screen md:flex-row box-border "> <section class="w-100 md:w-3/5 flex items-center justify-start flex-col md:h-screen lg:w-full max-w-screen-md box-border"> <section class="box-border p-3 md:p-5 bg-purple-100 rounded-3xl w-100 mx-5 lg:w-full lg:max-w-screen-lg"> <h2 class="mb-4 font-semibold text-purple-600 text-center">Câmera ao vivo</h2> <div id="webcam-container" class="rounded-3xl w-100 lg:w-full"> </div> <!-- <img src="\img.png" alt="" class="rounded-3xl w-100 lg:w-full"> --> </section> </section> <section class="flex items-center justify-start text-justify flex-col w-100 md:w-2/5 h-2/3 md:h-screen mt-7 md:mt-0"> <h2 class="mb-4 text-xl font-semibold text-purple-600 text-center w-100">Log de Previsões</h2> <section class="overflow-auto w-full text-center h-4/5 rounded-3xl" id="log-container"> <!-- Log container content will be dynamically added here --> </section> </section> </section> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@teachablemachine/image@latest/dist/teachablemachine-image.min.js"></script> <script type="text/javascript"> // the link to your model provided by Teachable Machine export panel const URL = "./my_model/"; let model, webcam, logContainer, maxPredictions; // Load the image model and setup the webcam async function init() { const modelURL = URL + "model.json"; const metadataURL = URL + "metadata.json"; // load the model and metadata model = await tmImage.load(modelURL, metadataURL); maxPredictions = model.getTotalClasses(); // Convenience function to setup a webcam const flip = true; // whether to flip the webcam webcam = new tmImage.Webcam(200, 200, flip); // width, height, flip await webcam.setup(); // request access to the webcam await webcam.play(); window.requestAnimationFrame(loop); // append elements to the DOM document.getElementById("webcam-container").appendChild(webcam.canvas); logContainer = document.getElementById("log-container"); // Start the prediction loop predictLoop(); } // Run the prediction loop recursively every 5 seconds async function predictLoop() { await predict(); // Predict setTimeout(predictLoop, 5000); // Schedule next prediction after 5 seconds } // Run the webcam image through the image model async function predict() { webcam.update(); // Update the webcam frame // predict can take in an image, video, or canvas HTML element const prediction = await model.predict(webcam.canvas); // Check if the prediction is for "Pessoas_e_Pacotes" with a probability above 60% const classPrediction = prediction.find(pred => pred.className === 'Pessoas_e_Pacotes' && pred.probability > 0.6); if (classPrediction) { // Show message if "Pessoas_e_Pacotes" with probability above 60% is detected const logMessage = `Possível encomenda detectada em ${getCurrentDateTime()}`; const imgDataUrl = webcam.canvas.toDataURL(); // Convert current webcam image to base64 addToLog(logMessage, imgDataUrl); // Add log with image } } // Function to get current date and time function getCurrentDateTime() { const now = new Date(); const date = now.toLocaleDateString(); const time = now.toLocaleTimeString(); return `${date} ${time}`; } // Function to add a message and image to the log function addToLog(message, imageDataUrl) { const logEntry = document.createElement("div"); logEntry.className = "flex items-center"; // Create image element const img = document.createElement("img"); img.src = imageDataUrl; img.width = 100; // Adjust image width as needed img.height = 100; // Adjust image height as needed logEntry.appendChild(img); // Add image to log entry // Create paragraph element for log message const logMessage = document.createElement("p"); logMessage.textContent = message; logEntry.appendChild(logMessage); // Add log message to log entry // Add the new log entry to the top of the log container logContainer.insertBefore(logEntry, logContainer.firstChild); } </script> </body> </html>
// import 'package:flutter/material.dart'; // import 'package:flutter_bloc/flutter_bloc.dart'; // import 'package:shoppy/core/utils/app_colors.dart'; // import 'package:shoppy/core/utils/app_typography.dart'; // import 'package:shoppy/core/utils/gap_constants.dart'; // import 'package:shoppy/presentation/bloc/cart_bloc/cart_bloc.dart'; // import 'package:shoppy/widgets/custom_button.dart'; // class CheckoutBar extends StatelessWidget { // const CheckoutBar({super.key}); // @override // Widget build(BuildContext context) { // return BlocBuilder<CartBloc, CartState>( // builder: (context, state) { // if (context.read<CartBloc>().cart.cartItems.isNotEmpty) { // return Positioned( // bottom: 10, // right: 0, // left: 0, // child: Container( // alignment: Alignment.center, // padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), // height: 80, // width: MediaQuery.of(context).size.width, // decoration: BoxDecoration( // color: AppColorPallete.lightGreen.withOpacity(0.9), // borderRadius: BorderRadius.circular(20), // ), // child: Row( // crossAxisAlignment: CrossAxisAlignment.center, // children: [ // Column( // crossAxisAlignment: CrossAxisAlignment.start, // mainAxisAlignment: MainAxisAlignment.center, // children: [ // Text( // "Subtotal", // style: AppTypoGraphy.labelLarge // .copyWith(color: AppColorPallete.white), // ), // Text( // "\$${context.read<CartBloc>().totalAmount.toStringAsFixed(0)}", // style: AppTypoGraphy.titleLarge // .copyWith(color: AppColorPallete.white), // overflow: TextOverflow.ellipsis, // ) // ], // ), // GapConstant.w28, // Expanded( // child: CustomButton( // label: "Checkout now", // borderRadius: 20, // onTap: () => navigateToCustomerScreen(context), // )) // ], // ), // ), // ); // } // return const SizedBox(); // }, // ); // } // navigateToCustomerScreen(context) {} // }
import { Flex, FormControl, FormLabel, InputGroup, InputLeftAddon, NumberInput, NumberInputField, NumberInputProps, Text } from '@chakra-ui/react' import { useField } from 'formik' import * as React from 'react' type ConnectedNumberInputProps = NumberInputProps & { label?: string name: string unit?: string } const ConnectedNumberInput: React.FC<ConnectedNumberInputProps> = ({ label, precision, unit, ...rest }) => { const [field, meta] = useField(rest.name) return ( <Flex flexDirection="column" width="100%" mr={rest.mr} ml={rest.ml} mt={rest.mt} mb={rest.mb}> <FormControl> {label && ( <FormLabel fontSize="xs" htmlFor={field.name}> {label} </FormLabel> )} <InputGroup width="100%"> {!!unit && <InputLeftAddon>{unit}</InputLeftAddon>} <NumberInput {...rest} precision={precision} step={0.01} width="100%"> <NumberInputField {...field} id={field.name} roundedLeft={!!unit ? 0 : 4} focusBorderColor="accent.500" /> </NumberInput> </InputGroup> {meta.touched && meta.error ? ( <Text color="red.500" textAlign="right"> {meta.error} </Text> ) : null} </FormControl> </Flex> ) } export default ConnectedNumberInput ConnectedNumberInput.defaultProps = { mb: 2, fontWeight: 'lighter', precision: 0 }
package org.geekbang.dependency.injection.aware; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * @author mao 2021/4/22 15:14 */ @Component public class UserService implements BeanFactoryAware, ApplicationContextAware { private BeanFactory beanFactory; private ApplicationContext applicationContext; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public BeanFactory getBeanFactory() { return beanFactory; } public ApplicationContext getApplicationContext() { return applicationContext; } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <GL/glut.h> #define WINDOW_X (500) #define WINDOW_Y (500) #define WINDOW_NAME "test3" void init_GL(int argc, char *argv[]); void init(); void set_callback_functions(); void glut_display(); void glut_keyboard(unsigned char key, int x, int y); void glut_mouse(int button, int state, int x, int y); void glut_motion(int x, int y); void draw_pyramid(); void draw_cube(); // グローバル変数 double g_angle1 = 0.0; double g_angle2 = 0.0; double g_distance = 20.0; bool g_isLeftButtonOn = false; bool g_isRightButtonOn = false; int main(int argc, char *argv[]){ /* OpenGLの初期化 */ init_GL(argc,argv); /* このプログラム特有の初期化 */ init(); /* コールバック関数の登録 */ set_callback_functions(); /* メインループ */ glutMainLoop(); return 0; } void init_GL(int argc, char *argv[]){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(WINDOW_X,WINDOW_Y); glutCreateWindow(WINDOW_NAME); } void init(){ glClearColor(0.0, 0.0, 0.0, 0.0); // 背景の塗りつぶし色を指定 } void set_callback_functions(){ glutDisplayFunc(glut_display); glutKeyboardFunc(glut_keyboard); glutMouseFunc(glut_mouse); glutMotionFunc(glut_motion); glutPassiveMotionFunc(glut_motion); } void glut_keyboard(unsigned char key, int x, int y){ switch(key){ case 'q': case 'Q': case '\033': exit(0); } glutPostRedisplay(); } void glut_mouse(int button, int state, int x, int y){ if(button == GLUT_LEFT_BUTTON){ if(state == GLUT_UP){ g_isLeftButtonOn = false; }else if(state == GLUT_DOWN){ g_isLeftButtonOn = true; } } if(button == GLUT_RIGHT_BUTTON){ if(state == GLUT_UP){ g_isRightButtonOn = false; }else if(state == GLUT_DOWN){ g_isRightButtonOn = true; } } } void glut_motion(int x, int y){ static int px = -1, py = -1; if(g_isLeftButtonOn == true){ if(px >= 0 && py >= 0){ g_angle1 += (double)-(x - px)/20; g_angle2 += (double)(y - py)/20; } px = x; py = y; }else if(g_isRightButtonOn == true){ if(px >= 0 && py >= 0){ g_distance += (double)(y - py)/20; } px = x; py = y; }else{ px = -1; py = -1; } glutPostRedisplay(); } void glut_display(){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(30.0, 1.0, 0.1, 100); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if (cos(g_angle2)>0){ gluLookAt(g_distance * cos(g_angle2) * sin(g_angle1), g_distance * sin(g_angle2), g_distance * cos(g_angle2) * cos(g_angle1), 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);} else{ gluLookAt(g_distance * cos(g_angle2) * sin(g_angle1), g_distance * sin(g_angle2), g_distance * cos(g_angle2) * cos(g_angle1), 0.0, 0.0, 0.0, 0.0, -1.0, 0.0);} glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glPushMatrix(); glTranslated(0.0, 0.5, 0.0); glScaled(2.0, 1.5, 2.0); draw_cube(); glPopMatrix(); glPushMatrix(); glTranslatef(0.0, 2.0, 0.0); glScaled(1.0, 0.8, 1.0); draw_pyramid(); glPopMatrix(); glFlush(); glDisable(GL_DEPTH_TEST); glutSwapBuffers(); } void draw_cube(){ GLdouble point0[] = {0.5, 0.5, 0.5}; GLdouble point1[] = {-0.5, 0.5, 0.5}; GLdouble point2[] = {-0.5, -0.5, 0.5}; GLdouble point3[] = {0.5, -0.5, 0.5}; GLdouble point4[] = {0.5, 0.5, -0.5}; GLdouble point5[] = {-0.5, 0.5, -0.5}; GLdouble point6[] = {-0.5, -0.5, -0.5}; GLdouble point7[] = {0.5, -0.5, -0.5}; glColor3d(1.0, 1.0, 1.0); glBegin(GL_POLYGON); glVertex3dv(point0); glVertex3dv(point1); glVertex3dv(point2); glVertex3dv(point3); glEnd(); glBegin(GL_POLYGON); glVertex3dv(point0); glVertex3dv(point1); glVertex3dv(point5); glVertex3dv(point4); glEnd(); glBegin(GL_POLYGON); glVertex3dv(point0); glVertex3dv(point3); glVertex3dv(point7); glVertex3dv(point4); glEnd(); glBegin(GL_POLYGON); glVertex3dv(point6); glVertex3dv(point7); glVertex3dv(point4); glVertex3dv(point5); glEnd(); glBegin(GL_POLYGON); glVertex3dv(point6); glVertex3dv(point7); glVertex3dv(point3); glVertex3dv(point2); glEnd(); glBegin(GL_POLYGON); glVertex3dv(point6); glVertex3dv(point2); glVertex3dv(point1); glVertex3dv(point5); glEnd(); } void draw_pyramid(){ GLdouble pointO[] = {0.0, 1.0, 0.0}; GLdouble pointA[] = {1.5, -1.0, 1.5}; GLdouble pointB[] = {-1.5, -1.0, 1.5}; GLdouble pointC[] = {-1.5, -1.0, -1.5}; GLdouble pointD[] = {1.5, -1.0, -1.5}; glColor3d(1.0, 0.0, 0.0); glBegin(GL_TRIANGLES); glVertex3dv(pointO); glVertex3dv(pointA); glVertex3dv(pointB); glEnd(); glBegin(GL_TRIANGLES); glVertex3dv(pointO); glVertex3dv(pointB); glVertex3dv(pointC); glEnd(); glBegin(GL_TRIANGLES); glVertex3dv(pointO); glVertex3dv(pointC); glVertex3dv(pointD); glEnd(); glBegin(GL_TRIANGLES); glVertex3dv(pointO); glVertex3dv(pointD); glVertex3dv(pointA); glEnd(); glBegin(GL_POLYGON); glVertex3dv(pointA); glVertex3dv(pointB); glVertex3dv(pointC); glVertex3dv(pointD); glEnd(); }
import React from 'react'; import Header from './headerComponents/Header'; import Footer from './footerComponent/Footer'; import AboutMe from './pages/AboutMe'; import Portfolio from './pages/Portfolio'; import Contact from './pages/Contact'; import Resume from './pages/Resume'; import { BrowserRouter as Router, Route, Routes } from "react-router-dom"; const PortfolioContainer = () => { return ( <Router> <div className="PortfolioContainer"> <Header /> <Routes> <Route path='/' element={<AboutMe />} /> <Route path='/portfolio' element={<Portfolio />} /> <Route path='/contact' element={<Contact />} /> <Route path='/resume' element={<Resume />} /> </Routes> <Footer /> </div> </Router> ) } export default PortfolioContainer;
import { initializeApp } from "firebase/app"; import { getAuth, signInWithRedirect, signInWithPopup, GoogleAuthProvider, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, onAuthStateChanged, User, NextOrObserver, } from "firebase/auth"; import { getFirestore, doc, getDoc, setDoc, collection, writeBatch, query, getDocs, QueryDocumentSnapshot, } from "firebase/firestore"; import { Category } from "../../store/categories/category.types"; const firebaseConfig = { apiKey: "AIzaSyCpRg1A1ICS5qcpzXjKAfxOBJwstYWcj3o", authDomain: "shopsystem-1ef19.firebaseapp.com", projectId: "shopsystem-1ef19", storageBucket: "shopsystem-1ef19.appspot.com", messagingSenderId: "691215778844", appId: "1:691215778844:web:3c5f4b14c62fede13f4bd9", }; // Initialize Firebase const firebaseApp = initializeApp(firebaseConfig); const googleProvider = new GoogleAuthProvider(); googleProvider.setCustomParameters({ prompt: "select_account", }); export const auth = getAuth(); export const signInWithGooglePopup = () => signInWithPopup(auth, googleProvider); export const signInWithGoogleRedirect = () => signInWithRedirect(auth, googleProvider); export const db = getFirestore(firebaseApp); export type ObjectToAdd = { title: string; }; //importing data export const addCollectionAndDocuments = async <T extends ObjectToAdd>( collectionKey: string, objectsToAdd: T[] ): Promise<void> => { const collectionRef = collection(db, collectionKey); const batch = writeBatch(db); objectsToAdd.forEach((object) => { const docRef = doc(collectionRef, object.title.toLowerCase()); batch.set(docRef, object); }); await batch.commit(); }; //getting products export const getCategoriesAndDocuments = async (): Promise<Category[]> => { const collectionRef = collection(db, "categories"); const q = query(collectionRef); const querySnapshot = await getDocs(q); return querySnapshot.docs.map( (docSnapshot) => docSnapshot.data() as Category ); }; export type AdditionalInformation = { displayName?: string; }; export type UserData = { createdAt: Date; displayName: string; email: string; }; export const createUserDocumentFromAuth = async ( userAuth: User, additionalInformation = {} as AdditionalInformation ): Promise<void | QueryDocumentSnapshot<UserData>> => { if (!userAuth) return; const userDocRef = doc(db, "users", userAuth.uid); const userSnapshot = await getDoc(userDocRef); if (!userSnapshot.exists()) { const { displayName, email } = userAuth; const createdAt = new Date(); try { await setDoc(userDocRef, { displayName, email, createdAt, ...additionalInformation, }); } catch (error) { console.log("error creating the user", error); } } return userSnapshot as QueryDocumentSnapshot<UserData>; }; export const createAuthUserWithEmailAndPassword = async ( email: string, password: string ) => { if (!email || !password) return; return await createUserWithEmailAndPassword(auth, email, password); }; export const signInAuthUserWithEmailAndPassword = async ( email: string, password: string ) => { if (!email || !password) return; return await signInWithEmailAndPassword(auth, email, password); }; export const signOutUser = async () => await signOut(auth); export const onAuthStateChangedListener = (callback: NextOrObserver<User>) => onAuthStateChanged(auth, callback); export const getCurrentUser = (): Promise<User | null> => { return new Promise((resolve, reject) => { const unsubscribe = onAuthStateChanged( auth, (userAuth) => { unsubscribe(); resolve(userAuth); }, reject ); }); };
import React from "react"; import { useRouter } from "next/router"; import { exportToBlob } from "../../packages/utils"; import { useImagine } from "@/context/ImagineContext"; import { getFileFromBlob } from "@/utils/images"; import { useApp, useExcalidrawAppState, useExcalidrawElements } from "../App"; import ButtonPrimary from "@/components/buttons/ButtonPrimary/ButtonPrimary"; import styles from "./SendToImagine.module.scss"; export const SendImageToImagine = () => { const router = useRouter(); const app = useApp(); const elements = useExcalidrawElements(); const appState = useExcalidrawAppState(); const { setImg2imgFile } = useImagine(); const handleSendTo = () => { const props = { elements, appState, files: app.files, exportPadding: 10, maxWidthOrHeight: 512, mimeType: "image/png", }; exportToBlob(props).then((blob) => { setImg2imgFile(getFileFromBlob(blob, "excalidraw.png")); router.back(); }); }; const handleCancel = () => { router.back(); }; return ( <div className={styles.container}> <ButtonPrimary loading={false} text={"Cancel"} onClick={handleCancel} /> <ButtonPrimary loading={false} text={"Use on imagine"} onClick={handleSendTo} /> </div> ); }; SendImageToImagine.displayName = "SendImageToImagine";
# Copyright 2021 Collate # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Base class for ingesting messaging services """ from abc import ABC, abstractmethod from typing import Any, Iterable, List, Optional, Set from pydantic import BaseModel from metadata.generated.schema.api.data.createTopic import CreateTopicRequest from metadata.generated.schema.entity.data.topic import Topic, TopicSampleData from metadata.generated.schema.entity.services.messagingService import ( MessagingConnection, MessagingService, ) from metadata.generated.schema.metadataIngestion.messagingServiceMetadataPipeline import ( MessagingServiceMetadataPipeline, ) from metadata.generated.schema.metadataIngestion.workflow import ( Source as WorkflowSource, ) from metadata.ingestion.api.delete import delete_entity_from_source from metadata.ingestion.api.models import Either from metadata.ingestion.api.steps import Source from metadata.ingestion.api.topology_runner import TopologyRunnerMixin from metadata.ingestion.models.delete_entity import DeleteEntity from metadata.ingestion.models.topology import ( NodeStage, ServiceTopology, TopologyContext, TopologyNode, ) from metadata.ingestion.ometa.ometa_api import OpenMetadata from metadata.ingestion.source.connections import get_connection, get_test_connection_fn from metadata.utils import fqn from metadata.utils.filters import filter_by_topic from metadata.utils.logger import ingestion_logger logger = ingestion_logger() class BrokerTopicDetails(BaseModel): """ Wrapper Class to combine the topic_name with topic_metadata """ topic_name: str topic_metadata: Any class MessagingServiceTopology(ServiceTopology): """ Defines the hierarchy in Messaging Services. service -> messaging -> topics. We could have a topology validator. We can only consume data that has been produced by any parent node. """ root = TopologyNode( producer="get_services", stages=[ NodeStage( type_=MessagingService, context="messaging_service", processor="yield_create_request_messaging_service", overwrite=False, must_return=True, cache_entities=True, ) ], children=["topic"], post_process=["mark_topics_as_deleted"], ) topic = TopologyNode( producer="get_topic", stages=[ NodeStage( type_=Topic, context="topic", processor="yield_topic", consumer=["messaging_service"], use_cache=True, ), NodeStage( type_=TopicSampleData, processor="yield_topic_sample_data", consumer=["messaging_service"], nullable=True, ), ], ) class MessagingServiceSource(TopologyRunnerMixin, Source, ABC): """ Base class for Messaging Services. It implements the topology and context. """ source_config: MessagingServiceMetadataPipeline config: WorkflowSource # Big union of types we want to fetch dynamically service_connection: MessagingConnection.__fields__["config"].type_ topology = MessagingServiceTopology() context = TopologyContext.create(topology) topic_source_state: Set = set() def __init__( self, config: WorkflowSource, metadata: OpenMetadata, ): super().__init__() self.config = config self.metadata = metadata self.source_config: MessagingServiceMetadataPipeline = ( self.config.sourceConfig.config ) self.service_connection = self.config.serviceConnection.__root__.config self.connection = get_connection(self.service_connection) # Flag the connection for the test connection self.connection_obj = self.connection self.test_connection() @property def name(self) -> str: return self.service_connection.type.name @abstractmethod def yield_topic(self, topic_details: Any) -> Iterable[Either[CreateTopicRequest]]: """ Method to Get Messaging Entity """ def yield_topic_sample_data( self, topic_details: Any ) -> Iterable[Either[TopicSampleData]]: """ Method to Get Sample Data of Messaging Entity """ @abstractmethod def get_topic_list(self) -> Optional[List[Any]]: """ Get List of all topics """ @abstractmethod def get_topic_name(self, topic_details: Any) -> str: """ Get Topic Name """ def get_topic(self) -> Any: for topic_details in self.get_topic_list(): topic_name = self.get_topic_name(topic_details) if filter_by_topic( self.source_config.topicFilterPattern, topic_name, ): self.status.filter( topic_name, "Topic Filtered Out", ) continue yield topic_details def yield_create_request_messaging_service(self, config: WorkflowSource): yield Either( right=self.metadata.get_create_service_from_source( entity=MessagingService, config=config ) ) def get_services(self) -> Iterable[WorkflowSource]: yield self.config def prepare(self): """By default, nothing to prepare""" def test_connection(self) -> None: test_connection_fn = get_test_connection_fn(self.service_connection) test_connection_fn(self.metadata, self.connection_obj, self.service_connection) def mark_topics_as_deleted(self) -> Iterable[Either[DeleteEntity]]: """Method to mark the topics as deleted""" if self.source_config.markDeletedTopics: yield from delete_entity_from_source( metadata=self.metadata, entity_type=Topic, entity_source_state=self.topic_source_state, mark_deleted_entity=self.source_config.markDeletedTopics, params={"service": self.context.messaging_service}, ) def register_record(self, topic_request: CreateTopicRequest) -> None: """ Mark the topic record as scanned and update the topic_source_state """ topic_fqn = fqn.build( self.metadata, entity_type=Topic, service_name=topic_request.service.__root__, topic_name=topic_request.name.__root__, ) self.topic_source_state.add(topic_fqn) def close(self): """By default, nothing to close"""
/** * 인터페이스의 확장 * 중복된 property 비효율 */ // 비효율 예시 interface Animal { name: string; age: number; } // interface Dog { // name: string; // age: number; // isBark: boolean; // } // // interface Cat { // name: string; // age: number; // isScratch: boolean; // } // // interface Chicken { // name: string; // age: number; // isFly: boolean; // } /** * java와는 다르게 interface 상속 extends 사용 * 동일한 property 재정의 가능 -> 원본타입의 서브타입만 가능 */ interface Dog extends Animal { isBark: boolean; } interface Cat extends Animal { isScratch: boolean; } interface Chicken extends Animal { isFly: boolean; } interface DogCat extends Dog, Cat { } const dogCat: DogCat = { name: '', age: 0, isBark: true, isScratch: true } const dog: Dog = { name: 'hello', age: 2, isBark: true }; const animal: Animal = { name: 'yy', age: 1 }
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:pawsomcommunity/Auth_screen/signupscreen.dart'; import 'package:pawsomcommunity/Home_screen/home_screen.dart'; import 'package:pawsomcommunity/Splesh_screen/skip1.dart'; import 'package:pawsomcommunity/Splesh_screen/skip2.dart'; import 'package:pawsomcommunity/consts/styles.dart'; import 'package:pawsomcommunity/controller/home_controller.dart'; class Home extends StatelessWidget { const Home({Key? key}) : super(key: key); @override Widget build(BuildContext context) { //init Home controller var Controller = Get.put(HomeContainer()); var navbarItem = [ const BottomNavigationBarItem( icon: SizedBox( child: Icon( Icons.home_outlined, size: 30.0, ), ), label: '', ), const BottomNavigationBarItem( icon: SizedBox( child: Icon( Icons.favorite, size: 30.0, ), ), label: '', ), const BottomNavigationBarItem( icon: SizedBox( child: Icon( Icons.add_circle_outline_outlined, size: 30.0, ), ), label: '', ), const BottomNavigationBarItem( icon: SizedBox( child: Icon( Icons.message_rounded, size: 30.0, ), ), label: '', ), const BottomNavigationBarItem( icon: SizedBox( child: Icon( Icons.account_circle_outlined, size: 30.0, ), ), label: '', ), ]; var navBody = [ const HomeScreen(), Skip1(), // const LoginScreen(), const SignupScreen(), const Skip1(), const Skip2() ]; return Scaffold( body: Column( children: [ Obx( () => Expanded( child: navBody.elementAt(Controller.CurrentNavIndex.value), ), ), ], ), bottomNavigationBar: Obx( () => ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0), ), child: BottomNavigationBar( currentIndex: Controller.CurrentNavIndex.value, selectedItemColor: const Color.fromARGB(255, 143, 53, 35), selectedLabelStyle: const TextStyle(fontFamily: semibold), type: BottomNavigationBarType.fixed, backgroundColor: const Color.fromARGB(255, 245, 208, 201), items: navbarItem, onTap: (value) { Controller.CurrentNavIndex.value = value; }, ), ), ), ); } }
import React from "react"; import { Routes, Route } from "react-router-dom"; import { LoginView } from "./views/LoginView"; import { Header } from "./components/Header"; import { HomeView } from "./views/HomeView"; import { Logout } from "./components/Logout"; import { isEmpty } from "lodash"; import { useEffect, useState } from "react"; import { UserContext } from "./state/UserContext"; import { SpotifyUsers } from "./api/SpotifyUsers"; import { User } from "./api/types"; import "./App.css"; const token = localStorage.getItem("accessToken") ?? ""; const App = () => { const [me, setMe] = useState<User>(); useEffect(() => { if (!isEmpty(token)) { const api = new SpotifyUsers(token); api.getMe().then(setMe).catch(api.defaultErrorHandler); return () => api.abortAll(); } }, []); return ( <React.StrictMode> <div className="App"> <UserContext.Provider value={{ user: me, token: localStorage.getItem("accessToken") }} > <Header /> <Routes> {!isEmpty(token) && <Route path="/" element={<HomeView />} />} <Route path="/login" element={<LoginView />} /> <Route path="/logout" element={<Logout />} /> </Routes> </UserContext.Provider> </div> </React.StrictMode> ); }; export default App;
import React from 'react'; import { Jumbotron, Container, CardColumns, Card, Button } from 'react-bootstrap'; import { useQuery, useMutation } from '@apollo/client'; import { QUERY_ME } from '../utils/queries'; import { DELETE_BOOK } from '../utils/mutations'; import Auth from '../utils/auth'; import { removeBookId } from '../utils/localStorage'; const SavedBooks = () => { const { loading, data } = useQuery(QUERY_ME); const userData = data?.me || {}; // const refreshPage = ()=>{ // window.location.reload(); // } const [deletedBook] = useMutation(DELETE_BOOK); const handleDeleteBook = async (removedBook) => { const token = Auth.loggedIn() ? Auth.getToken() : null; if (!token) { return false; } const decodedToken = Auth.getProfile(token).data._id; try { await deletedBook({ variables: { bookId: removedBook }, _id: decodedToken }); removeBookId(removedBook); // window.location.reload(); } catch (err) { console.error(err); } // refreshPage() } if (loading) { return <h2>LOADING...</h2>; } return ( <> <Jumbotron fluid className='text-light bg-dark'> <Container> <h1>Viewing saved books!</h1> </Container> </Jumbotron> <Container> <h2> {userData.savedBooks.length ? `Viewing ${userData.savedBooks.length} saved ${userData.savedBooks.length === 1 ? 'book' : 'books'}:` : 'You have no saved books!'} </h2> <CardColumns> {userData.savedBooks.map((book) => { return ( <Card key={book.bookId} border='dark'> {book.image ? <Card.Img src={book.image} alt={`The cover for ${book.title}`} variant='top' /> : null} <Card.Body> <Card.Title>{book.title}</Card.Title> <p className='small'>Authors: {book.authors}</p> <Card.Text>{book.description}</Card.Text> <Button className='btn-block btn-danger' onClick={() => handleDeleteBook(book.bookId)}> Delete this Book! </Button> <Card.Link rel="noreferrer" target="_blank" href={book.link}>{book.title} - More Info</Card.Link> </Card.Body> </Card> ); })} </CardColumns> </Container> </> ); }; export default SavedBooks;
package com.freyr.apollo18.commands.image; import com.freyr.apollo18.Apollo18; import com.freyr.apollo18.commands.Category; import com.freyr.apollo18.commands.Command; import com.freyr.apollo18.util.embeds.EmbedUtils; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; import okhttp3.*; import org.json.JSONObject; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.Objects; public class GenerateCommand extends Command { public GenerateCommand(Apollo18 bot) { super(bot); this.name = "generate"; this.description = "Uses the DALL-E to generate AI art"; this.category = Category.IMAGE; this.args.add(new OptionData(OptionType.STRING, "prompt", "The description of the image", true)); this.cooldown = 5 * 1000; } @Override public void execute(SlashCommandInteractionEvent event) { event.deferReply().queue(); OkHttpClient client = new OkHttpClient(); // OpenAI API endpoint String url = "https://api.openai.com/v1/images/generations"; // OpenAI API request payload String requestBody = "{\"prompt\":\"" + Objects.requireNonNull(event.getOption("prompt")).getAsString() + "\", \"n\": 1, \"size\": \"256x256\"}"; // Create the request Request request = new Request.Builder() .url(url) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer sk-" + bot.getConfig().get("OPENAI_KEY", System.getenv("OPENAI_KEY"))) .post(RequestBody.create(requestBody, MediaType.parse("application/json"))) .build(); // Send the request try (Response response = client.newCall(request).execute()) { // Handle the response JSONObject responseBody = new JSONObject(response.body().string()); System.out.println(responseBody); event.getHook().sendMessage(responseBody.getJSONArray("data").getJSONObject(0).getString("url")).queue(); } catch (SocketTimeoutException e) { event.getHook().sendMessageEmbeds(EmbedUtils.createError("It took too long to generate your image...")).queue(); } catch (IOException e) { System.err.println(e); event.getHook().sendMessageEmbeds(EmbedUtils.createError("Something went wrong while generating your image")).queue(); } } }
package com.wiprojobsearch.joblisting.model; import org.springframework.data.annotation.Id; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; public class User { @Id private String id; @NotEmpty(message="Fullname is required") private String fullName; @Email(message="Invalid email format") @NotEmpty(message="email is required") private String email; @NotEmpty(message="Password is required") private String password; @NotEmpty(message="Mobile number is required") private String mobileNumber; @NotEmpty(message="workStatus is required") private String workStatus; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getMobileNumber() { return mobileNumber; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String getWorkStatus() { return workStatus; } public void setWorkStatus(String workStatus) { this.workStatus = workStatus; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", fullName='" + fullName + '\'' + ", email='" + email + '\'' + ", password='" + password + '\'' + ", mobileNumber='" + mobileNumber + '\'' + ", workStatus='" + workStatus + '\'' + '}'; } }
# 49. 字母异位词分组 ### Question [https://leetcode.cn/problems/group-anagrams/description/](https://leetcode.cn/problems/group-anagrams/description/) 给你一个字符串数组,请你将 **字母异位词** 组合在一起。可以按任意顺序返回结果列表。 **字母异位词** 是由重新排列源单词的所有字母得到的一个新单词。 &#x20; **示例 1:** <pre><code><strong>输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] </strong><strong>输出: [["bat"],["nat","tan"],["ate","eat","tea"]] </strong></code></pre> **示例 2:** <pre><code><strong>输入: strs = [""] </strong><strong>输出: [[""]] </strong></code></pre> **示例 3:** <pre><code><strong>输入: strs = ["a"] </strong><strong>输出: [["a"]] </strong></code></pre> &#x20; **提示:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` 仅包含小写字母 ### Solution #### 哈希表 **字母异位词**意味着组成该串的字符以及对应的字符数量完全相同。相同的**字母异位词**需要放到一个List中,因此可以使用哈希表进行分组,因此我们主要关注hashkey的构造即可,保证**字母异位词**的key都是相同的。 在这里我推荐计数的方式,具体算法如下: 1. 声明$$counts$$数组,下标存储字符,值是对应的数量,当然,也可以使用哈希表计数,但是性能比较差。 2. 遍历待计算的字符串$$s$$,给当前字符计数 3. 声明`StringBuilder`&#x20; 4. 重新遍历$$a - z$$(**重点,此处相当于做了排序**),如果当前字符有计数,则将字符和数量加入key,最后返回`toString()` ```java class Solution { // 遍历每个单词,构造key,同key放入同一个List // 构造key过程: 统计字母数量,再按字母顺序和对应的数量拼接 public List<List<String>> groupAnagrams(String[] strs) { var result = new HashMap<String, List<String>>(); for(var str: strs) { var key = buildKey(str); result.putIfAbsent(key, new ArrayList<>()); result.get(key).add(str); } return new ArrayList<>(result.values()); } // 构造Key private String buildKey(String s) { var counts = new int[26]; for(int i = 0; i < s.length(); i++) { counts[s.charAt(i)-'a']++; } var sb = new StringBuilder(); for(int i = 0; i < 26; i++) { if(counts[i] > 0) { sb.append(i).append('-').append(counts[i]); } } return sb.toString(); } } ``` **时间复杂度** $$O(m*n)$$, $$m$$是字符串数组长度,$$n$$是字符串平均长度,我们需要遍历所有字符串,需要$$m$$的时间复杂度,对于每个字符串,我们遍历所有字符,需要$$n$$的时间复杂度;哈希表的操作视为$$O(1)$$。 **空间复杂度** $$O(m*n)$$, $$m$$是字符串数组长度,$$n$$是字符串平均长度,所有字符都需要存储在哈希表。
<template> <div style="margin-top: 16px"> <el-form-item label="脚本格式"> <el-input v-model="scriptTaskForm.scriptFormat" clearable @input="updateElementTask()" @change="updateElementTask()" /> </el-form-item> <el-form-item label="脚本类型"> <el-select v-model="scriptTaskForm.scriptType" class="ui-w-100"> <el-option label="内联脚本" value="inline" /> <el-option label="外部资源" value="external" /> </el-select> </el-form-item> <el-form-item label="脚本" v-show="scriptTaskForm.scriptType === 'inline'"> <el-input v-model="scriptTaskForm.script" type="textarea" resize="vertical" :autosize="{ minRows: 2, maxRows: 4 }" clearable @input="updateElementTask()" @change="updateElementTask()" /> </el-form-item> <el-form-item label="资源地址" v-show="scriptTaskForm.scriptType === 'external'"> <el-input v-model="scriptTaskForm.resource" clearable @input="updateElementTask()" @change="updateElementTask()" /> </el-form-item> <el-form-item label="结果变量"> <el-input v-model="scriptTaskForm.resultVariable" clearable @input="updateElementTask()" @change="updateElementTask()" /> </el-form-item> </div> </template> <script lang="ts" setup> import { onUnmounted, ref, toRaw } from "vue"; import { nextTick, reactive, watch } from "vue"; const props = defineProps<{ id: string; type: string }>(); const defaultTaskForm = reactive({ scriptFormat: "", script: "", resource: "", resultVariable: "" }); const scriptTaskForm = reactive({ scriptFormat: "", scriptType: "", script: "", resource: "", resultVariable: "" }); const bpmnElement = ref(); watch( props, (val) => { bpmnElement.value = window.bpmnInstances.bpmnElement; nextTick(() => resetTaskForm()); }, { immediate: true } ); onUnmounted(() => { bpmnElement.value = null; }); const resetTaskForm = () => { for (const key in defaultTaskForm) { const value = bpmnElement.value?.businessObject[key] || defaultTaskForm[key]; scriptTaskForm[key] = value; } scriptTaskForm.scriptType = scriptTaskForm.script ? "inline" : "external"; }; const updateElementTask = () => { const taskAttr = Object.create(null); taskAttr.scriptFormat = scriptTaskForm.scriptFormat || null; taskAttr.resultVariable = scriptTaskForm.resultVariable || null; if (scriptTaskForm.scriptType === "inline") { taskAttr.script = scriptTaskForm.script || null; taskAttr.resource = null; } else { taskAttr.resource = scriptTaskForm.resource || null; taskAttr.script = null; } window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), taskAttr); }; </script>
# -*- coding: utf-8 -*- """ Created on Fri Mar 19 10:43:48 2021 @author: yuwen """ #### Word Bag import nltk from nltk.corpus import wordnet from collections import defaultdict from nltk.corpus import stopwords from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score defaultStopwords = stopwords.words('english') dum_train = open('d_train', 'r') snp_train = open('s_train', 'r') trainPos = [] dum_line = dum_train.readline() while dum_line: trainPos.append(dum_line) dum_line = dum_train.readline() trainNeg = [] snp_line = snp_train.readline() while snp_line: trainNeg.append(snp_line) snp_line = snp_train.readline() dum_train.close() snp_train.close() from nltk.tokenize import RegexpTokenizer newTrainPos = [] for s in trainPos: new = '' tokenizer = RegexpTokenizer(r'\w+') # use NOT alphanumeric as token separator noPunct = tokenizer.tokenize( s ) for word in noPunct: if word.lower() not in defaultStopwords: new += word.lower() new += ' ' newTrainPos.append(new) #print(newTrainPos) #print() newTrainNeg = [] for s in trainNeg: new = '' tokenizer = RegexpTokenizer(r'\w+') # use NOT alphanumeric as token separator noPunct = tokenizer.tokenize( s ) for word in noPunct: if word.lower() not in defaultStopwords: new += word.lower() new += ' ' newTrainNeg.append(new) #print(newTrainNeg) V = set() bagPos = [] # bagPos: words in "positive" class for pos in newTrainPos: tokenList = nltk.word_tokenize(pos) for w in tokenList: bagPos.append(w) V.add(w) bagNeg = [] # bagNeg: words in "negative" class for neg in newTrainNeg: tokenList = nltk.word_tokenize(neg) for w in tokenList: bagNeg.append(w) V.add(w) ######## LR Model test import nltk from nltk.corpus import wordnet import math # pos_word = set(bagPos) neg_word = set(bagNeg) # def zValue(fv,w,b): return b + sum([fv[i]*w[i] for i in range(len(fv))]) def sigmoid(N): return 1/ ( 1 + math.exp(-N)) # import csv d_result = open ('./Dumbledore_LR_Result.csv', 'w', newline = '') s_result = open ('./Snape_LR_Result.csv', 'w', newline = '') headList = ['content', 'p1', 'whether the character'] writer1 = csv.DictWriter(d_result, fieldnames = headList) writer2 = csv.DictWriter(s_result, fieldnames = headList) writer1.writeheader() writer2.writeheader() print('TEST START') d_test = open('d_test', 'r') s_test = open('s_test','r') testPos = [] testNeg = [] d_line = d_test.readline() s_line = s_test.readline() while d_line: testPos.append(d_line) d_line = d_test.readline() while s_line: testNeg.append(s_line) s_line = s_test.readline() d_test.close() s_test.close() print('DUMBLEDORE') for fullString in testPos: print("-"*30) fv = [0]*2 for w in nltk.word_tokenize(fullString): if w in pos_word: fv[0] += 1 if w in neg_word: fv[1] += 1 z = zValue(fv = fv,w = [3, -1], b = 0) p1 = sigmoid(z) print(f'Test string = "{fullString}"') print(f"fv = {fv}") print(f'z = {z}') print(f'p1 = {p1}') if p1> 0.5: print("Classified as postive") writer1.writerow({headList[0]:fullString, headList[1]:p1, headList[2]:'1'}) else: print("Classified as negative") writer1.writerow({headList[0]:fullString, headList[1]:p1, headList[2]:'0'}) d_result.close() print('\n\nSNAPE') for fullString in testNeg: print("-"*30) fv = [0]*2 for w in nltk.word_tokenize(fullString): if w in pos_word: fv[0] += 1 if w in neg_word: fv[1] += 1 z = zValue(fv = fv,w = [1, -2], b = 0) p1 = sigmoid(z) print(f'Test string = "{fullString}"') print(f"fv = {fv}") print(f'z = {z}') print(f'p1 = {p1}') if p1> 0.5: print("Classified as postive") writer2.writerow({headList[0]:fullString, headList[1]:p1, headList[2]:'0'}) else: print("Classified as negative") writer2.writerow({headList[0]:fullString, headList[1]:p1, headList[2]:'1'}) s_result.close() # Part 2 ######## from sklearn import tree from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from scipy.sparse import csr_matrix # def prediction_measure(y_test, y_predicted): CM = confusion_matrix(y_test, y_predicted) TN = CM[0][0] FN = CM[1][0] TP = CM[1][1] FP = CM[0][1] # print(CM) print("Accuracy = ", accuracy_score(y_test, y_predicted)) print("Precision = ", precision_score(y_test, y_predicted)) print("Recall = ", recall_score(y_test, y_predicted)) posDocs = [] negDocs = [] docsToClassify = [] fp = open('d_train', 'r') for line in fp: posDocs.append(line.strip()) fp = open('s_train', 'r') for line in fp: negDocs.append(line.strip()) theDocs = posDocs + negDocs ; labelsPosDocs = [1 for i in posDocs] labelsNegDocs = [0 for i in negDocs] labels = labelsPosDocs + labelsNegDocs # Original Approach cv = CountVectorizer(binary=False,max_df=0.95) cv.fit_transform(theDocs) counts = cv.transform(theDocs) x_train, x_test, y_train, y_test = train_test_split( counts, labels, test_size=0.2, random_state=1) # LR print("-"*20) print("LR Evaluation") model_logisticReg = LogisticRegression(random_state=0,max_iter=10000000).fit(x_train,y_train) y_predicted_LR = model_logisticReg.predict(x_test) prediction_measure(y_test, y_predicted_LR)
<mat-toolbar color="primary"> <h2 mat-dialog-title>Seleccionar Curso</h2> </mat-toolbar> <mat-dialog-content class="mat-typography"> <mat-form-field class="full-width"> <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Buscar..."> </mat-form-field> <div class="mat-elevation-z8"> <table mat-table [dataSource]="dataSource" matSort> <!-- Actions Column --> <ng-container matColumnDef="actions"> <th mat-header-cell *matHeaderCellDef> </th> <td mat-cell *matCellDef="let row"> <button mat-mini-fab color="primary" [mat-dialog-close]="row"> <mat-icon> check</mat-icon> </button> </td> </ng-container> <!-- Id Column --> <ng-container matColumnDef="TipCurId"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Curso </th> <td mat-cell *matCellDef="let row"> {{row.TipCurId}} </td> </ng-container> <!-- Nombre Column --> <ng-container matColumnDef="TipCurNom"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Nombre </th> <td mat-cell *matCellDef="let row"> {{row.TipCurNom}} </td> </ng-container> <!-- Estado Column --> <ng-container matColumnDef="TipCurEst"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Estado </th> <td mat-cell *matCellDef="let row"> {{getEstado(row.TipCurEst)}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"> </tr> </table> <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator> </div> </mat-dialog-content> <mat-dialog-actions align="end"> <button mat-button mat-dialog-close (click)="onNoClick()">Cancelar</button> </mat-dialog-actions>
package com.dmtryii.usersystem.service; import com.dmtryii.usersystem.exception.UserAgeException; import com.dmtryii.usersystem.exception.UserNotFountException; import com.dmtryii.usersystem.model.User; import com.dmtryii.usersystem.repository.UserRepository; import com.dmtryii.usersystem.service.impl.UserServiceImpl; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.util.ReflectionUtils; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; @SpringBootTest public class UserServiceTest { @Mock private UserRepository userRepository; @InjectMocks private UserServiceImpl userService; @Value("${service.user.ageLimit}") private int ageLimitTest; @Test public void testGetById_ForExistingUser_UserFound() { Long id = 1L; User user = User.builder() .id(id) .build(); when(userRepository.findById(id)).thenReturn(Optional.of(user)); User result = userService.getById(id); assertNotNull(result); } @Test public void testGetById_ForNotExistingUser_UserNotFoundThrows() { Long userId = 1L; when(userRepository.findById(userId)).thenThrow(UserNotFountException.class); assertThrows(UserNotFountException.class, () -> userService.getById(userId)); } @Test public void testSave_ValidAge_UserNotNull() throws NoSuchFieldException { LocalDate validBirthDate = LocalDate.now().minusYears(ageLimitTest); User user = User.builder() .id(1L) .birthDate(validBirthDate) .build(); setAgeLimitUserService(); when(userRepository.save(user)).thenReturn(user); User savedUser = userService.save(user); assertNotNull(savedUser); } @Test public void testSave_InvalidAge_UserAgeException() throws NoSuchFieldException { LocalDate invalidBirthDate = LocalDate.now().minusYears(ageLimitTest-1); User user = User.builder() .id(1L) .birthDate(invalidBirthDate) .build(); setAgeLimitUserService(); assertThrows(UserAgeException.class, () -> userService.save(user)); } @Test public void updateAllFields_ValidUserAndId_UpdatedUser() throws NoSuchFieldException { Long id = 1L; User existingUser = User.builder() .id(id) .email("old@gmail.com") .firstName("John") .lastName("Doe") .birthDate(LocalDate.of(2000,1,1)) .build(); when(userRepository.findById(id)).thenReturn(Optional.of(existingUser)); User newUser = User.builder() .email("new@gmail.com") .firstName("Jane") .lastName("Smith") .birthDate(LocalDate.of(2000,1,1)) .build(); setAgeLimitUserService(); when(userRepository.save(existingUser)).thenReturn(existingUser); User updatedResult = userService.updateAllFields(id, newUser); assertEquals(updatedResult.getEmail(), newUser.getEmail()); assertEquals(updatedResult.getFirstName(), newUser.getFirstName()); assertEquals(updatedResult.getLastName(), newUser.getLastName()); } @Test public void updateFields_ValidUserAndId_UpdatedUser() throws NoSuchFieldException { Long id = 1L; User existingUser = User.builder() .id(id) .email("doe@gmail.com") .firstName("John") .lastName("Doe") .birthDate(LocalDate.of(2000,1,1)) .build(); when(userRepository.findById(id)).thenReturn(Optional.of(existingUser)); User newUser = User.builder() .firstName("Jane") .lastName("Smith") .phone("+380989788456") .birthDate(LocalDate.of(2001,10,1)) .build(); setAgeLimitUserService(); when(userRepository.save(existingUser)).thenReturn(existingUser); User updatedResult = userService.updateFields(id, newUser); assertEquals(updatedResult.getEmail(), existingUser.getEmail()); assertEquals(updatedResult.getFirstName(), newUser.getFirstName()); assertEquals(updatedResult.getLastName(), newUser.getLastName()); assertEquals(updatedResult.getPhone(), newUser.getPhone()); assertEquals(updatedResult.getBirthDate(), newUser.getBirthDate()); } @Test public void GetAllByDataRange_ForThreeUsers_ReturnsTwoUsers() { LocalDate fromDate = LocalDate.of(1990, 1, 1); LocalDate toDate = LocalDate.of(2000, 12, 31); User user1 = User.builder() .id(1L) .birthDate(LocalDate.of(1995, 5, 10)) .build(); User user2 = User.builder() .id(2L) .birthDate(LocalDate.of(1990, 2, 15)) .build(); User user3 = User.builder() .id(3L) .birthDate(LocalDate.of(2005, 8, 20)) .build(); List<User> usersInRange = Arrays.asList(user1, user2); when(userRepository.findByBirthDateBetween(fromDate, toDate)).thenReturn(usersInRange); List<User> result = userService.getAllByDataRange(fromDate, toDate); verify(userRepository).findByBirthDateBetween(fromDate, toDate); assertEquals(usersInRange.size(), result.size()); assertTrue(result.contains(user1)); assertTrue(result.contains(user2)); assertFalse(result.contains(user3)); } @Test public void testDelete_ForExistingUser_Delete() { Long id = 1L; User user = User.builder() .id(id) .build(); when(userRepository.findById(id)).thenReturn(Optional.of(user)); userService.delete(id); verify(userRepository, times(1)).delete(user); } private void setAgeLimitUserService() throws NoSuchFieldException { ReflectionUtils.setField( userService.getClass().getDeclaredField("ageLimit"), userService, ageLimitTest ); } }
import pandas as pd import numpy as np import plotly.express as px from openpyxl import Workbook from openpyxl.drawing.image import Image import dash from dash import dcc, Input, Output import plotly.graph_objs as go from dash import html import webbrowser # Import the webbrowser module # Load the CSV file into a DataFrame df = pd.read_csv('pricehistory.csv') # Convert the "Scraped Date" column to datetime df['Scraped Date'] = pd.to_datetime(df['Scraped Date']) # Find the rows with the latest scraped date for each product latest_prices = df.groupby('Product Name').apply(lambda x: x[x['Scraped Date'] == x['Scraped Date'].max()]) # Create a new DataFrame with the latest prices and stock price_list = latest_prices[['Product Name', 'Price', 'Stock', 'Brand', 'Category']] # Initialize the Dash app app = dash.Dash(__name__) # Define app layout with external CSS app.layout = html.Div([ html.H1("Product Price History", id='app-title'), # Dropdown menu to select a product dcc.Dropdown( id='product-dropdown', options=[{'label': product, 'value': product} for product in price_list['Product Name']], value=price_list['Product Name'].iloc[0], # Initial selected value ), # Interactive line chart dcc.Graph(id='price-history-chart'), dcc.Location(id='url', refresh=False) # Location component to capture browser tab close event ]) # Define callback to update the chart based on product selection @app.callback( Output('price-history-chart', 'figure'), [Input('product-dropdown', 'value')] ) def update_chart(selected_product): filtered_df = df[df['Product Name'] == selected_product] # Convert datetime to Python datetime objects using np.array scraped_dates = np.array(filtered_df['Scraped Date']) # Create the line chart with markers fig = go.Figure() fig.add_trace(go.Scatter(x=scraped_dates, y=filtered_df['Price'], mode='lines+markers')) fig.update_layout( title=f'Price Change Over Time for {selected_product}', xaxis_title='Scraped Date', yaxis_title='Price', ) return fig # Define callback to stop the server when the tab is closed @app.callback(Output('url', 'pathname'), Input('url', 'href')) def close_tab(href): if href is None: raise dash.exceptions.PreventUpdate return href if __name__ == '__main__': # Open the app in the default web browser webbrowser.open('http://127.0.0.1:8050/') # Run the Dash app app.run_server(debug=True)
package org.go.together.service; import org.go.together.context.RepositoryContext; import org.go.together.dto.NotificationDto; import org.go.together.dto.NotificationMessageDto; import org.go.together.dto.NotificationReceiverDto; import org.go.together.enums.CrudOperation; import org.go.together.model.Notification; import org.go.together.model.NotificationReceiver; import org.go.together.model.NotificationReceiverMessage; import org.go.together.repository.interfaces.NotificationMessageRepository; import org.go.together.repository.interfaces.NotificationReceiverMessageRepository; import org.go.together.repository.interfaces.NotificationRepository; import org.go.together.service.interfaces.NotificationMessageService; import org.go.together.service.interfaces.NotificationService; import org.go.together.tests.CrudServiceCommonTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.test.context.EmbeddedKafka; import org.springframework.test.context.ContextConfiguration; import java.util.Collection; import java.util.Date; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @ContextConfiguration(classes = RepositoryContext.class) @EmbeddedKafka(partitions = 1, brokerProperties = {"listeners=PLAINTEXT://localhost:9807", "port=9807"}) public class NotificationReceiverServiceTest extends CrudServiceCommonTest<NotificationReceiver, NotificationReceiverDto> { private static final String CREATED = "Created"; @Autowired private NotificationService notificationService; @Autowired private NotificationRepository notificationRepository; @Autowired private NotificationMessageService notificationMessageService; @Autowired private NotificationMessageRepository notificationMessageRepository; @Autowired private NotificationReceiverMessageRepository notificationReceiverMessageRepository; @Override public void clean() { super.clean(); notificationReceiverMessageRepository.findAll() .forEach(notificationReceiverMessageRepository::delete); notificationMessageRepository.findAll() .forEach(notificationMessageRepository::delete); notificationRepository.findAll() .forEach(notificationRepository::delete); } @Test public void removeReceiver() { getCreatedEntityId(dto); createNotificationMessage(dto); crudService.delete(dto.getId()); Collection<NotificationReceiverMessage> notificationReceiverMessages = notificationReceiverMessageRepository.findAll(); assertEquals(0, notificationReceiverMessages.size()); } @Test public void addReceiver() { getCreatedEntityId(dto); createNotificationMessage(dto); Collection<NotificationReceiverMessage> notificationReceiverMessages = notificationReceiverMessageRepository.findAll(); int receiverMessagesSize = notificationReceiverMessageRepository.findByReceiverId(dto.getUserId()).size(); assertEquals(1, notificationReceiverMessages.size()); assertEquals(1, receiverMessagesSize); createNotificationMessage(dto); int receiverAddMessagesSize = notificationReceiverMessageRepository.findByReceiverId(dto.getUserId()).size(); Collection<NotificationReceiverMessage> notificationReceiverNewMessages = notificationReceiverMessageRepository.findAll(); assertEquals(2, receiverAddMessagesSize); assertEquals(2, notificationReceiverNewMessages.size()); assertFalse(notificationReceiverNewMessages.iterator().next().getIsRead()); assertEquals(CREATED, notificationReceiverMessages.iterator().next().getNotificationMessage().getMessage()); } @Override protected NotificationReceiverDto createDto() { NotificationReceiverDto notificationReceiverDto = factory.manufacturePojo(NotificationReceiverDto.class); NotificationDto notificationDto = new NotificationDto(); notificationDto.setProducerId(UUID.randomUUID()); notificationReceiverDto.setNotification(notificationDto); return notificationReceiverDto; } private void createNotificationMessage(NotificationReceiverDto dto) { NotificationMessageDto notificationMessageDto = new NotificationMessageDto(); notificationMessageDto.setMessage(CREATED); Notification notification = notificationRepository.findByProducerId(dto.getNotification().getProducerId()).orElse(null); notificationMessageDto.setNotification(notificationService.read(notification.getId())); notificationMessageDto.setDate(new Date()); notificationMessageService.create(notificationMessageDto); } @Override protected void checkDtos(NotificationReceiverDto dto, NotificationReceiverDto savedObject, CrudOperation operation) { assertEquals(dto.getId(), savedObject.getId()); assertEquals(dto.getUserId(), savedObject.getUserId()); assertEquals(dto.getNotification().getProducerId(), savedObject.getNotification().getProducerId()); } }
import AxeBuilder from '@axe-core/playwright' import { expect, test } from '@playwright/test' test.describe('landing page', () => { test('page should be rendered with correct title', async ({ page, isMobile }) => { await page.goto('/') expect(await page.title()).toEqual('Next Starter') await expect( page.getByRole('navigation', { name: /global/i }) ).toBeVisible() await expect( page.getByRole('link', { name: /next starter/i }) ).toBeVisible() await expect( page.getByRole('link', { name: /next starter/i }) ).toHaveAttribute('href', '/') if (isMobile) { await expect( page.getByRole('button', { name: /open main menu/i }) ).toBeVisible() } else { await expect(page.getByRole('link', { name: /product/i })).toBeVisible() await expect( page.getByRole('link', { name: /product/i }) ).toHaveAttribute('href', '/product') await expect(page.getByRole('link', { name: /features/i })).toBeVisible() await expect( page.getByRole('link', { name: /features/i }) ).toHaveAttribute('href', '/features') await expect( page.getByRole('link', { name: /marketplace/i }) ).toBeVisible() await expect( page.getByRole('link', { name: /marketplace/i }) ).toHaveAttribute('href', '/marketplace') await expect(page.getByRole('link', { name: /company/i })).toBeVisible() await expect( page.getByRole('link', { name: /company/i }) ).toHaveAttribute('href', '/company') await expect(page.getByRole('link', { name: /log in/i })).toBeVisible() await expect(page.getByRole('link', { name: /log in/i })).toHaveAttribute( 'href', '/login' ) } await expect(page.getByRole('main', { name: /content/i })).toBeVisible() await expect( page.getByRole('heading', { name: /data to enrich your online business/i }) ).toBeVisible() await expect(page.getByRole('link', { name: /get started/i })).toBeVisible() await expect( page.getByRole('link', { name: /get started/i }) ).toHaveAttribute('href', '/get-started') await expect(page.getByRole('link', { name: /live demo/i })).toBeVisible() await expect( page.getByRole('link', { name: /live demo/i }) ).toHaveAttribute('href', '/demo') }) test('page should not have any automatically detectable accessibility issues', async ({ page }) => { await page.goto(`/`) const accessibilityScanResults = await new AxeBuilder({ page }).analyze() expect(accessibilityScanResults.violations).toEqual([]) await page.close() }) })
import 'package:coolmovies/core/error/error.dart'; import 'package:coolmovies/data/datasources/datasources.dart'; import 'package:coolmovies/data/models/models.dart'; import 'package:coolmovies/data/repositories/repositories.dart'; import 'package:dartz/dartz.dart'; import 'package:mocktail/mocktail.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../../mocks/movies_mock.dart'; class MockMovieDatasource extends Mock implements MovieDatasource {} void main() { late MovieRepositoryImpl repository; late MovieDatasource datasource; MoviesModel movie = MoviesMock.moviesModel; List<MoviesModel> moviesList = [movie]; setUp(() { datasource = MockMovieDatasource(); repository = MovieRepositoryImpl(movieDatasource: datasource); }); group('getAllMoviesList', () { test('success - should return all the movies list', () async { // arrange when(() => datasource.getAllMoviesList()) .thenAnswer((_) async => Future.value(moviesList)); // act final result = await repository.getAllMoviesList(); // assert expect(result, isA<Right>()); verify(() => datasource.getAllMoviesList()).called(1); }); test('failure - should return all movies failure', () async { // arrange when(() => datasource.getAllMoviesList()) .thenThrow(const Left(AllMoviesListFailure())); // act final result = await repository.getAllMoviesList(); //assert expect( result, const Left(AllMoviesListFailure()), ); }); }); }
import { GoogleGeolocationAdapter } from './google-geolocation-adapter' import { mockGeolocation, throwError } from '@/domain/test' import axios from 'axios' jest.mock('axios', () => ({ async get (): Promise<any> { return await Promise.resolve({ data: { status: 'OK', results: [ { geometry: { location: mockGeolocation() } } ] } }) } })) const apiUrl = 'aaaaaaa' const apiToken = 'aaaaaaa' const makeSut = (): GoogleGeolocationAdapter => { return new GoogleGeolocationAdapter(apiUrl, apiToken) } describe('Google Geolocation Adapter', () => { describe('locate()', () => { test('Should return a valid geolocation on locate on success', async () => { const sut = makeSut() const location = await sut.locate('any_value') expect(location).toStrictEqual(mockGeolocation()) }) test('Should throws if axios throws', async () => { const sut = makeSut() jest.spyOn(axios, 'get').mockImplementationOnce(throwError) const promise = sut.locate('any_value') await expect(promise).rejects.toThrow() }) }) })
package ATP.Project.EziCall.service; import ATP.Project.EziCall.DTO.CallHistoryDTO; import ATP.Project.EziCall.DTO.CallHistoryDetailsDTO; import ATP.Project.EziCall.DTO.CustomerDTO; import ATP.Project.EziCall.DTO.CustomerDetailDTO; import ATP.Project.EziCall.exception.*; import ATP.Project.EziCall.models.*; import ATP.Project.EziCall.repository.CustomerRepository; import ATP.Project.EziCall.requests.CustomerRequest; import ATP.Project.EziCall.requests.UpdateCustomerRequest; import ATP.Project.EziCall.util.AppConstants; import ATP.Project.EziCall.util.DataValidation; import ATP.Project.EziCall.util.Validatable; import jakarta.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.List; @Service public class CustomerService { private final CustomerRepository customerRepository; private final DataValidation dataValidation; private final TicketService ticketService; private final UserService userService; private final NoteService noteService; @Autowired public CustomerService(CustomerRepository customerRepository, DataValidation dataValidation, TicketService ticketService, UserService userService, NoteService noteService) { this.customerRepository = customerRepository; this.dataValidation = dataValidation; this.ticketService = ticketService; this.userService = userService; this.noteService = noteService; } public List<CustomerDTO> findCustomer(String phonenumber, String name) { return customerRepository.findCustomer(phonenumber,name); } public List<CustomerDTO> findCustomer(String phonenumber, String name, String id, String gender) { Gender gendr = null; if (gender != null && !gender.isEmpty()) { try { gendr = Gender.valueOf(gender); } catch (IllegalArgumentException e) { // Giới tính không hợp lệ sẽ bị bỏ qua và không gán giá trị cho gendr } } return customerRepository.findCustomer(phonenumber,name, id, gendr); } public List<CustomerDTO> getCustomers() { if(customerRepository.findAll().isEmpty()) { throw new EmptyListException(AppConstants.NO_DATA_LIST); } List<CustomerDTO> customerDTOS = customerRepository.getAll(); for (CustomerDTO customerDTO:customerDTOS) { if(customerDTO.getNumberCall() == null) { customerDTO.setNumberCall(0L); } } return customerRepository.getAll(); } public CustomerDetailDTO getCustomerById(String id) { return customerRepository.getCustomerById(id) .orElseThrow(() -> new ObjectNotFoundException(AppConstants.CUS_IS_NOT_EXIST)); } private void validateCustomerData(Validatable data) throws InvalidFormatException, RegistrationFailedException { if (!dataValidation.isValidDataCustomer(data.getEmail(), data.getPhonenumber())) { throw new InvalidFormatException("Email không hợp lệ"); } customerRepository.findCustomerByPhoneNumber(data.getPhonenumber()) .ifPresent(s -> { throw new FieldAlreadyExistException("SĐT đã có trong hệ thống"); }); } @Transactional public CustomerDetailDTO insertNewCustomerAndTicket(CustomerRequest customerRequest, String value) { validateCustomerData(customerRequest); Customer customer = Customer.builder() .fullname(customerRequest.getFullname()) .email(customerRequest.getEmail()) .phoneNumber(customerRequest.getPhonenumber()) .address(customerRequest.getAddress()) .tickets(new HashSet<>()) .gender(Gender.valueOf(customerRequest.getGender())).build(); customerRepository.save(customer); if(value.equalsIgnoreCase("true")) { if(customerRequest.getTitle().equals("")) { throw new InvalidFormatException("Tiêu đề không được để trống"); }else { User user = userService.getUserByUsername(); Ticket ticket = ticketService.createNewTicket(customer, customerRequest.getTitle(), user); Note note = noteService.createNewNote(ticket, customerRequest.getNote()); ticket.getNotes().add(note); customer.getTickets().add(ticket); } } return customerRepository.getCustomerById(customer.getCustomerId()).get(); } public Customer updateCustomer(String id, UpdateCustomerRequest customerRequest) { validateCustomerData(customerRequest); Customer customer = customerRepository.findById(id) .orElseThrow(() -> new ObjectNotFoundException(AppConstants.CUS_IS_NOT_EXIST)); customer.setFullname(customerRequest.getFullname()); customer.setEmail(customerRequest.getEmail()); customer.setPhoneNumber(customerRequest.getPhonenumber()); customer.setAddress(customerRequest.getAddress()); customer.setGender(Gender.valueOf(customerRequest.getGender())); return customerRepository.save(customer); } public void removeCustomer(String id) { Customer customer = customerRepository.findById(id) .orElseThrow(() -> new ObjectNotFoundException(AppConstants.CUS_IS_NOT_EXIST)); customerRepository.delete(customer); } public List<CallHistoryDTO> getCallHistory() { return customerRepository.getCallHistory(); } public CallHistoryDetailsDTO getCallHistoryDetails(String id) { CallHistoryDetailsDTO callHistoryDetailsDTO = customerRepository.getCallHistoryDetails(id) .orElseThrow(() -> new ObjectNotFoundException(AppConstants.CUS_IS_NOT_EXIST)); if(ticketService.getTicketsByCustomerId(id).isEmpty()) { throw new EmptyListException(AppConstants.NO_DATA_LIST); } callHistoryDetailsDTO.setTicketOverviewDTOS(ticketService.getTicketsByCustomerId(id)); return callHistoryDetailsDTO; } }
package com.example.rest; import com.example.entity.Customer; import com.example.service.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RequestMapping("/api") @RestController public class CustomerRestController { @Autowired private CustomerService customerService; @GetMapping("/customers") public List<Customer> getCustomers(){ return customerService.getCustomers(); } @GetMapping("/customers/{customerId}") public Customer getCustomer(@PathVariable int customerId) { Customer theCustomer = customerService.getCustomer(customerId); if (theCustomer == null) { throw new CustomerNotFoundException("Customer id not found - " + customerId); } return theCustomer; } @PostMapping("/customers") // @RequestBody will automatically convert the json code to Java POJO public Customer addCustomer(@RequestBody Customer customer){ // also just in case the pass an id in JSON ... set id to 0 // this is force a save of new item ... instead of update customer.setId(0); customerService.saveCustomer(customer); return customer; } @PutMapping("/customers") public Customer updateCustomer(@RequestBody Customer customer){ customerService.saveCustomer(customer); return customer; } @DeleteMapping("/customers/{customerId}") public String deleteCustomer(@PathVariable int customerId) { Customer customer = customerService.getCustomer(customerId); if (customer == null) { throw new CustomerNotFoundException("Customer id not found - " + customerId); } customerService.deleteCustomer(customerId); return "Deleted customer id - " + customerId; } }
<div>{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}</div> <p><span class="seoSummary">{{domxref("SourceBuffer")}} インターフェイスの <strong><code>mode</code></strong> プロパティは、メディアセグメントを <code>SourceBuffer</code> に任意の順序で追加できるか、厳密な順序で追加できるかを制御します。</span></p> <p>使用可能な2つの値は次のとおりです。</p> <ul> <li><code>segments</code>: メディアセグメントのタイムスタンプが、セグメントの再生順序を決定します。 セグメントは、任意の順序で <code>SourceBuffer</code> に追加できます。</li> <li><code>sequence</code>: セグメントが <code>SourceBuffer</code> に追加される順序により、セグメントの再生順序を決定します。 セグメントのタイムスタンプは、この順序に従ってセグメントに対して自動的に生成されます。</li> </ul> <p><code>mode</code> 値は、<code>MediaSource.addSourceBuffer()</code> を使用して <code>SourceBuffer</code> が作成されるときに最初に設定されます。 メディアセグメントにタイムスタンプが既に存在する場合、値は <code>segments</code> に設定されます。 そうでない場合、値は <code>sequence</code> に設定されます。</p> <p>初期値が <code>sequence</code> のときに <code>mode</code> プロパティ値を <code>segments</code> に設定しようとすると、例外がスローされます。 <code>sequence</code> モードでは、既存のセグメントの順序を維持する必要があります。 ただし、値を <code>segments</code> から <code>sequence</code> に変更することはできます。 これは、再生順序が固定され、これを反映するために新しいタイムスタンプが生成されることを意味します。</p> <p>このプロパティは、<code>SourceBuffer</code> が {{domxref("SourceBuffer.appendBuffer","appendBuffer()")}} または {{domxref("SourceBuffer.remove","remove()")}} の呼び出しを処理している間は変更できません。</p> <h2 id="Syntax" name="Syntax">構文</h2> <pre class="syntaxbox">var <em>myMode</em> = <em>sourceBuffer</em>.mode; <em>sourceBuffer</em>.mode = 'sequence'; </pre> <h3 id="Value" name="Value">値</h3> <p>{{domxref("DOMString")}}。</p> <h3 id="Exceptions" name="Exceptions">例外</h3> <p>このプロパティに新しい値を設定すると、次の例外がスローされる場合があります。</p> <table class="standard-table"> <thead> <tr> <th scope="col">例外</th> <th scope="col">説明</th> </tr> </thead> <tbody> <tr> <td><code>InvalidAccessError</code></td> <td>初期値が <code>sequence</code> の場合に、値を <code>segments</code> に設定しようとしました。</td> </tr> <tr> <td><code>InvalidStateError</code></td> <td>{{domxref("SourceBuffer")}} オブジェクトが更新中(つまり、その {{domxref("SourceBuffer.updating")}} プロパティが現在 <code>true</code>)、この <code>SourceBuffer</code> に追加された最後のメディアセグメントが不完全、またはこの <code>SourceBuffer</code> が {{domxref("MediaSource")}} から取り除かれています。</td> </tr> </tbody> </table> <h2 id="Example" name="Example">例</h2> <p>このスニペットは、<code>sourceBuffer</code> のモードが、 現在 <code>'segments'</code> に設定されている場合、<code>'sequence'</code> に設定します。 したがって、再生順序は、メディアセグメントを追加した順に設定されます。</p> <pre class="brush: js">var curMode = sourceBuffer.mode; if (curMode == 'segments') { sourceBuffer.mode = 'sequence'; }</pre> <h2 id="Specifications" name="Specifications">仕様</h2> <table class="standard-table"> <tbody> <tr> <th scope="col">仕様</th> <th scope="col">状態</th> <th scope="col">コメント</th> </tr> <tr> <td>{{SpecName('Media Source Extensions', '#idl-def-sourcebuffer-mode', 'mode')}}</td> <td>{{Spec2('Media Source Extensions')}}</td> <td>初期定義</td> </tr> </tbody> </table> <h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> <div> <div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> <p>{{Compat("api.SourceBuffer.mode")}}</p> </div> <h2 id="See_also" name="See_also">関連情報</h2> <ul> <li>{{domxref("MediaSource")}}</li> <li>{{domxref("SourceBufferList")}}</li> </ul>
# leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def __init__(self): # 搞一个全局遍历进行计数 self.total_n_queens = 0 def totalNQueens(self, n): """ :type n: int :rtype: int """ # 和N皇后[51]基本一毛一样 # 回溯法 # 初始化棋盘,二位数组 board = [['.' for _ in range(n)] for _ in range(n)] # 列表是使用引用方式 # total_n_queens = [0] def is_valid(board, row, col): # 在棋盘board中的row行col列放置皇后,是否合法 # 只需要判断,上、左上(对角线)、右上(对角线)是否存在皇后 # col列上面是否存在Q for i in range(row): if board[i][col] == 'Q': return False # 左上方对角线是否存在 for i, j in zip(range(row-1, -1, -1), range(col-1, -1, -1)): if board[i][j] == 'Q': return False # 右上方对角线是否存在Q for i, j in zip(range(row-1, -1, -1), range(col+1, n)): if board[i][j] == 'Q': return False return True def backtrack(board, row): # 在第row行放置皇后 if row == n: #total_n_queens[0] += 1 self.total_n_queens += 1 return for col in range(n): # 遍历该行的每个位置 if is_valid(board, row, col): # 如果当前行是vaild的,放置皇后,进行下一一列判断 board[row][col] = 'Q' backtrack(board, row+1) board[row][col] = '.' backtrack(board, 0) #return total_n_queens[0] return self.total_n_queens # leetcode submit region end(Prohibit modification and deletion)
// // Str + Extension.swift // Vstore // // Created by Ghoost on 12/31/19. // Copyright © 2019 Khalij. All rights reserved. // import Foundation extension String { var urlFromString: String { return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" } var localized: String { return NSLocalizedString(self, comment: "") } var replacedArabicDigitsWithEnglish: String { var str = self let map = ["٠": "0", "١": "1", "٢": "2", "٣": "3", "٤": "4", "٥": "5", "٦": "6", "٧": "7", "٨": "8", "٩": "9"] map.forEach { str = str.replacingOccurrences(of: $0, with: $1) } return str } var replacedWhitespaceWithUnderscore: String { return self.replacingOccurrences(of: " ", with: "_") } var html2AttributedString: NSAttributedString? { return Data(utf8).html2AttributedString } var html2String: String { return html2AttributedString?.string ?? "" } var isValidEmail: Bool { let regularExpressionForEmail = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let testEmail = NSPredicate(format:"SELF MATCHES %@", regularExpressionForEmail) return testEmail.evaluate(with: self) } var isValidPhone: Bool { let regularExpressionForPhone = "^\\d{3}-\\d{3}-\\d{4}$" let testPhone = NSPredicate(format:"SELF MATCHES %@", regularExpressionForPhone) return testPhone.evaluate(with: self) } } extension Data { var html2AttributedString: NSAttributedString? { do { return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) } catch { print("error:", error) return nil }}}
/* * Copyright 2010-2020 OpenXcom Developers. * * This file is part of OpenXcom. * * OpenXcom is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenXcom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenXcom. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPENXCOM_MAPDATASET_H #define OPENXCOM_MAPDATASET_H //#include <string> //#include <vector> #include <SDL/SDL_stdinc.h> #include <yaml-cpp/yaml.h> namespace OpenXcom { class Game; class MapData; class SurfaceSet; /** * Represents the MapControlData of an MCD & PCK/TAB fileset. * @note Popularly known as a tileset. The list of datafiles is stored in * RuleSet but referenced in RuleTerrain. * @sa http://www.ufopaedia.org/index.php?title=MCD */ class MapDataSet { private: bool _loaded; std::string _type; static MapData * _floorBlank, // not used directly. Although RuleTerrain::getTerrainPart() uses BLANKS entry #0 to 'fix' broken tile-parts. * _floorScorch; const Game* _game; SurfaceSet* _surfaceSet; std::vector<MapData*> _records; public: /// Constructs a MapDataSet. MapDataSet( const std::string& type, const Game* const game); /// Destructs the MapDataSet. ~MapDataSet(); /// Loads the MapDataSet from YAML. void load(const YAML::Node& node); /// Gets the dataset-type used for MAP generation. std::string getType() const; /// Gets the quantity of records in the MapDataSet. size_t getRecordsQty() const; /// Gets the parts/entries in the MapDataSet. std::vector<MapData*>* getRecords(); /// Gets the Surfaces in the MapDataSet. SurfaceSet* getSurfaceset() const; /// Loads the MCD-file. void loadData(); /// Unloads the MapDataSet to free-up RAM. void unloadData(); /// Loads LoFT-voxel data from a DAT file. static void loadLoft( const std::string& file, std::vector<Uint16>* const voxelData); /// Gets the universal blank-floor part. // static MapData* getBlankFloor(); // not used. /// Gets the universal scorched-earth part. static MapData* getScorchedEarth(); }; } #endif
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:gap/gap.dart'; import 'package:mobil_proje/ekranlar/ara%C3%A7lar/app_layout.dart'; import 'package:mobil_proje/ekranlar/ara%C3%A7lar/app_style.dart'; class HotelScreen extends StatelessWidget { final Map<String, dynamic> hotel; const HotelScreen({Key? key,required this.hotel}) : super(key: key); @override Widget build(BuildContext context) { print('Hotel price is ${hotel ['price']}'); final size = AppLayOut.getSize(context); return Container( width: size.width*0.6, height: AppLayOut.getHeight(350), padding: const EdgeInsets.symmetric(horizontal: 15,vertical: 17), margin: const EdgeInsets.only(right: 17,top: 5), decoration: BoxDecoration( color: Styles.primarycolor, borderRadius: BorderRadius.circular(24), boxShadow: [ BoxShadow( color: Colors.grey.shade200, blurRadius: 20, spreadRadius: 5, ), ], ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: AppLayOut.getWidth(180), decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), color: Styles.primarycolor, image: DecorationImage( fit: BoxFit.cover, image: AssetImage( "assets/images/${hotel ['image']}" ), ), ), ), const Gap(10), Text( hotel['place'], style: Styles.headLineStyle2.copyWith(color: Styles.kakiColor), ), const Gap(5), Text( hotel['destination'], style: Styles.headLineStyle3.copyWith(color: Colors.white), ), const Gap(8), Text( '\₺${hotel['price']}/Gece', style: Styles.headLineStyle1.copyWith(color: Styles.kakiColor), ), ], ), ); } }
import React from "react"; import GuessInput from "../GuessInput"; import PreviousGuesses from "../PreviousGuesses"; import { sample } from "../../utils"; import { WORDS } from "../../data"; import ResultBanner from "../ResultBanner"; // Pick a random word on every pageload. const answer = sample(WORDS); // To make debugging easier, we'll log the solution in the console. console.info({ answer }); function Game() { const [guesses, setGuesses] = React.useState([]); const [isWon, setIsWon] = React.useState(null); function handleGuessSubmit(newGuess) { if (newGuess === answer) { setIsWon(true); } // when submitting a guess, guesses has not been updated yet. Therefore comparing guesses.length === 5 and not 6 if (guesses.length === 5 && newGuess !== answer) { setIsWon(false); } const nextGuesses = [ ...guesses, { id: crypto.randomUUID(), guess: newGuess, }, ]; setGuesses(nextGuesses); } return ( <> <PreviousGuesses guesses={guesses} answer={answer} /> <GuessInput handleGuessSubmit={handleGuessSubmit} isWon={isWon} /> <ResultBanner isWon={isWon} numOfTries={guesses.length} answer={answer} /> </> ); } export default Game;
import { app } from '../main'; import { IUser, Role,} from '@workspace/interfaces'; import { IUserDocument, User } from '../app/resources/user/model/user.model'; import * as request from "supertest"; import { connect, clearDatabase, closeDatabase } from "../test-db-setup"; import * as path from "path"; describe("users API",()=>{ let someAdminValidUser:IUser; let someInventoryValidUser: IUser; let someCheckoutValidUser: IUser; let someCheckoutValidUserDocument: IUserDocument; let someAdminValidUserDocument: IUserDocument; let someInventoryValidUserDocument: IUserDocument; let someUsers: IUser[]; let someUsersDocument: IUserDocument[]; let adminToken; let inventoryToken; let checkoutToken; const uri = '/users'; beforeAll(()=>{ return connect(); }); beforeEach(()=>{ return clearDatabase(); }); afterAll(()=>{ return closeDatabase(); }) beforeEach(async ()=>{ someAdminValidUser = { firstName:"someFirstName", lastName:"someLastName", role:Role.ADMIN, username:"username3", password:"somepassword" }; someInventoryValidUser = { firstName:"someFirstName", lastName:"someLastName", role:Role.INVENTORY, username:"username2", password:"somepassword" }; someCheckoutValidUser = { firstName:"someFirstName", lastName:"someLastName", role:Role.CHECKOUT, username:"username1", password:"somepassword" }; someAdminValidUserDocument = await User.create(someAdminValidUser); someInventoryValidUserDocument = await User.create(someInventoryValidUser); someCheckoutValidUserDocument = await User.create(someCheckoutValidUser); }); beforeEach(async ()=>{ someUsers = [ { firstName:"somefirstname", lastName:"somelastname", role:Role.INVENTORY, username:"username9", password:"somepasswrod" }, { firstName:"somefirstname", lastName:"somelastname", role:Role.INVENTORY, username:"username10", password:"somepasswrod" }, ]; someUsersDocument = await User.create(someUsers); }); beforeEach(async ()=>{ let loginRes = await request(app).post("/sign-in").send({data:{username:someAdminValidUser.username,password:someAdminValidUser.password}}); adminToken = loginRes.body.data.token; loginRes = await request(app).post("/sign-in").send({data:{username:someInventoryValidUser.username,password:someInventoryValidUser.password}}); inventoryToken = loginRes.body.data.token; loginRes = await request(app).post("/sign-in").send({data:{username:someCheckoutValidUser.username,password:someCheckoutValidUser.password}}); checkoutToken = loginRes.body.data.token; }); describe("GET /",()=>{ it("should require authentication",async ()=>{ const response = await request(app).get(uri); expect(response.status).toBe(401); }); it("should return users when authenticated",async(done)=>{ const response = await request(app).get(uri).set('Authorization',"Bearer "+adminToken); expect(response.status).toBe(200); done(); }); }); describe("GET /:id",()=>{ it("should require authentication",async ()=>{ const response = await request(app).get(path.join(uri,someUsersDocument[0]._id.toHexString())); expect(response.status).toBe(401); }); it("should return the user when authenticated",async()=>{ const response = await request(app).get(path.join(uri,someUsersDocument[0]._id.toHexString())).set('Authorization',"Bearer "+adminToken); expect(response.status).toBe(200); expect(JSON.stringify(response.body.data)).toEqual(JSON.stringify(someUsersDocument[0])); }); }); describe("POST /",()=>{ it("should require authentication",async ()=>{ const response = await request(app).post(uri).send({data:someUsers[0]}); expect(response.status).toBe(401); }); it("should require Admin role Auth",async ()=>{ const someNewUser = { firstName:"somefirstname", lastName:"somelastname", role:Role.INVENTORY, username:"username8", password:"somepasswrod", }; let response = await request(app).post(uri).send({data:someNewUser}).set('Authorization',"Bearer "+checkoutToken); expect(response.status).toBe(403); expect(response.body).toHaveProperty('error') response = await request(app).post(uri).send({data:someNewUser}).set('Authorization',"Bearer "+adminToken); expect(response.status).not.toBe(403); expect(response.body).toHaveProperty('data') response = await request(app).post(uri).send({data:someNewUser}).set('Authorization',"Bearer "+inventoryToken); expect(response.status).toBe(403); expect(response.body).toHaveProperty('error') }); it("should return 201 with the new user as data when successful",async ()=>{ const someNewUser: IUser = { firstName:"somefirstname", lastName:"somelastname", role:Role.INVENTORY, username:"username8", password:"somepasswrod" }; const response = await request(app).post(uri).send({data:someNewUser}).set("Authorization","Bearer "+adminToken); expect(response.status).toBe(201); expect(response.body).toHaveProperty("data"); }); }); describe("PUT /:id",()=>{ it("should require authentication",async ()=>{ const response = await request(app).put(uri).send({data:someUsers[0]}); expect(response.status).toBe(401); }); it("should require Inventory or Admin role Auth",async ()=>{ let response = await request(app).put(path.join(uri,someUsersDocument[0]._id.toHexString())).send({data:someUsers[0]}).set('Authorization',"Bearer "+checkoutToken); expect(response.status).toBe(403); expect(response.body).toHaveProperty('error') response = await request(app).put(path.join(uri,someUsersDocument[0]._id.toHexString())).send({data:someUsers[0]}).set('Authorization',"Bearer "+adminToken); expect(response.status).not.toBe(403); expect(response.body).toHaveProperty('data') response = await request(app).put(path.join(uri,someUsersDocument[1]._id.toHexString())).send({data:someUsers[1]}).set('Authorization',"Bearer "+inventoryToken); expect(response.status).toBe(403); expect(response.body).toHaveProperty('error') }); it("should return 200 with the new user as data when successful",async ()=>{ const someNewUser: IUser = { firstName:"somefirstname", lastName:"somelastname", role:Role.INVENTORY, username:"newusername", password:"somepasswrod" }; const response = await request(app).put(path.join(uri,someUsersDocument[0]._id.toHexString())).send({data:someNewUser}).set("Authorization","Bearer "+adminToken); expect(response.status).toBe(200); expect(response.body.data.username).toBe(someNewUser.username) expect(response.body.data._id).toBe(someUsersDocument[0]._id.toHexString()); }); }); describe("DELETE /:id",()=>{ it("should require authentication",async ()=>{ const response = await request(app).del(uri).send({data:someUsers[0]}); expect(response.status).toBe(401); }); it("should require Inventory or Admin role Auth",async ()=>{ let response = await request(app).del(path.join(uri,someUsersDocument[0]._id.toHexString())).set('Authorization',"Bearer "+checkoutToken); expect(response.status).toBe(403); expect(response.body).toHaveProperty('error') response = await request(app).del(path.join(uri,someUsersDocument[0]._id.toHexString())).set('Authorization',"Bearer "+adminToken); expect(response.status).not.toBe(403); expect(response.body).toHaveProperty('data') response = await request(app).del(path.join(uri,someUsersDocument[1]._id.toHexString())).set('Authorization',"Bearer "+inventoryToken); expect(response.status).toBe(403); expect(response.body).toHaveProperty('error') }); it("should return 200 with the deleted user as data when successful",async ()=>{ const response = await request(app).del(path.join(uri,someUsersDocument[1]._id.toHexString())).set("Authorization","Bearer "+adminToken); expect(response.status).toBe(200); expect(response.body.data._id).toBe(someUsersDocument[1]._id.toHexString()); }); }); });
import 'dart:async'; import 'package:country_currency_pickers/country_pickers.dart'; import 'package:country_picker/country_picker.dart'; import 'package:flag/flag.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:huzz/core/widgets/button/button.dart'; import 'package:huzz/data/repository/auth_respository.dart'; import 'package:pin_code_fields/pin_code_fields.dart'; import 'package:huzz/core/constants/app_themes.dart'; class ForgotPIN extends StatefulWidget { const ForgotPIN({super.key}); @override State<ForgotPIN> createState() => _ForgotPINState(); } class _ForgotPINState extends State<ForgotPIN> { final _authController = Get.find<AuthRepository>(); StreamController<ErrorAnimationType>? errorController; String countryFlag = "NG"; String countryCode = "234"; @override void initState() { errorController = StreamController<ErrorAnimationType>(); super.initState(); } @override void dispose() { errorController!.close(); _authController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Obx(() { if (_authController.Otpverifystatus == OtpVerifyStatus.Error) { errorController!.add(ErrorAnimationType.shake); } return Scaffold( body: SizedBox( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 100, width: MediaQuery.of(context).size.width, child: Stack( children: [ Positioned( top: 20, child: SvgPicture.asset('assets/images/Vector.svg')), Positioned( top: 50, left: 20, child: GestureDetector( onTap: () { Get.back(); }, child: const Icon( Icons.arrow_back, color: AppColors.backgroundColor, ), ), ), ], ), ), Center( child: Text('Forgot Pin', style: GoogleFonts.inter( color: AppColors.orangeBorderColor, fontSize: 28, fontWeight: FontWeight.w500)), ), const SizedBox( height: 10, ), Container( margin: const EdgeInsets.only(left: 50, right: 50), child: Text( 'To make sure it’s really you, we’ll send a secret code to your phone number via SMS', textAlign: TextAlign.center, style: GoogleFonts.inter( fontSize: 12, fontWeight: FontWeight.w400), ), ), const SizedBox( height: 10 ), SizedBox(height: MediaQuery.of(context).size.height * 0.1), Container( margin: const EdgeInsets.only( left: 20, ), child: Text( "Phone Number", style: GoogleFonts.inter( color: Colors.black, fontSize: 12, fontWeight: FontWeight.w400, ), )), const SizedBox( height: 10, ), Container( margin: const EdgeInsets.only(left: 20, right: 20), width: MediaQuery.of(context).size.width, height: 50, decoration: BoxDecoration( color: Colors.white, border: Border.all( color: AppColors.backgroundColor, width: 2.0), borderRadius: const BorderRadius.all(Radius.circular(10)), ), child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ GestureDetector( onTap: () { showCountryCode(context); }, child: Container( decoration: const BoxDecoration( border: Border( right: BorderSide( color: AppColors.backgroundColor, width: 2)), ), height: 50, width: 80, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const SizedBox(width: 10), Flag.fromString(countryFlag, height: 30, width: 30), const SizedBox( width: 5, ), Icon( Icons.arrow_drop_down, size: 24, color: AppColors.backgroundColor.withOpacity(0.5), ) ], ), ), ), const SizedBox( width: 10, ), Expanded( child: TextFormField( controller: _authController.forgotPhoneNumberController, decoration: InputDecoration( border: InputBorder.none, enabledBorder: InputBorder.none, disabledBorder: InputBorder.none, focusedBorder: InputBorder.none, hintText: "8123456789", hintStyle: GoogleFonts.inter( color: Colors.black.withOpacity(0.5), fontSize: 14, fontWeight: FontWeight.w500), prefixText: "+$countryCode ", prefixStyle: GoogleFonts.inter( fontSize: 14, fontWeight: FontWeight.w500, color: Colors.black)), ), ), const SizedBox( width: 10, ), ], ), ), const Expanded(child: SizedBox()), Padding( padding: const EdgeInsets.all(Insets.lg), child: Button( action: () { if (_authController.Otpauthstatus != OtpAuthStatus.Loading) { _authController.sendForgetOtp(); } }, label: "Continue", children: true), ), const SizedBox( height: 40, ) ]), ), ); }); } Future showCountryCode(BuildContext context) async { showCountryPicker( context: context, showPhoneCode: true, // optional. Shows phone code before the country name. onSelect: (Country country) { countryCode = country.toJson()['e164_cc']; countryFlag = country.toJson()['iso2_cc']; country.toJson(); final currency = CountryPickerUtils.getCountryByIsoCode(countryFlag) .currencyCode .toString(); setState(() {}); }, ); } }
// // PlayerDetailInfoSelectionView.swift // player-demo // // Created by edwin wilson on 22/07/2023. // import SwiftUI enum PlayerDetailType: String, CaseIterable { case info = "Info" case statistics = "Statistics" case event = "Event" case media = "Media" var icon: Image { switch self { case .info: return Image("inbox") case .statistics: return Image("statistic-board") case .event: return Image("date") case .media: return Image("play") } } } struct PlayerDetailInfoSelectionView: View { @Binding var type: PlayerDetailType var body: some View { ScrollView(.horizontal, showsIndicators: false) { LazyHStack(alignment: .top, spacing: 8) { ForEach( PlayerDetailType.allCases, id: \.self) { detailType in PlayerDetailInfoSelectionCell(type: detailType, isSelected: detailType == type) .onTapGesture { type = detailType } } .padding(.leading, 11) } .padding(.init(top: 2, leading: 0, bottom: 2, trailing: 11)) .frame(alignment: .topLeading) } } } struct PlayerDetailInfoSelectionCell: View { var type: PlayerDetailType var isSelected: Bool var body: some View { HStack(alignment: .center, spacing: 4) { type.icon .frame(width: 20, height: 20) Text(type.rawValue) .FontSFPro(15, .semibold, isSelected ? Color("Primary Light") : Color("Grey Dark") ) } .foregroundColor(isSelected ? Color("Primary Light") : Color("Grey Dark")) .padding(.horizontal, 16) .padding(.vertical, 0) .frame(height: 40, alignment: .leading) .background(isSelected ? Color("Primery") : Color("Grey0")) .cornerRadius(8) .shadow(color: .black.opacity(0.15), radius: 5, x: 2, y: 2) .overlay( RoundedRectangle(cornerRadius: 8) .inset(by: 0.5) .stroke(Color(red: 0.92, green: 0.92, blue: 0.92), lineWidth: 1) ) } } struct PlayerDetailInfoSelectionView_Previews: PreviewProvider { static var previews: some View { @State var type: PlayerDetailType = .info PlayerDetailInfoSelectionView(type: $type) } }