text
stringlengths
184
4.48M
import axios from "axios"; import { useCallback, useEffect, useState } from "react"; import toast from "react-hot-toast"; import { useAuth } from "../context/auth"; import { useGetById } from "./_commons"; import { useNavigate } from "react-router-dom"; const initValues = { title: "", content: null, categories: [], }; export const useCreateBlog = (url, dataFromEditPage) => { const [values, setValues] = useState(initValues); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const submit = async () => { setLoading(true); try { const { data } = await axios.post(url, values); if (data.error) { setError(data.error); return; } } catch (error) { // 500 console.log(error, "from create post"); return toast.error("Something went wrong"); } finally { setLoading(false); } }; useEffect(() => { if (dataFromEditPage) { setValues(dataFromEditPage); } }, []); return { setValues, values, loading, error, submit, }; }; export const useEditBlog = (slug) => { const navigate = useNavigate(); const [values, setValues] = useState(initValues); const [loading, setLoading] = useState(false); const { data } = useGetById(`/post/${slug}`); useEffect(() => { let arr = []; data?.categories?.map((x) => arr.push(x.name)); setValues({ ...values, content: data.content, title: data.title, categories: arr }); }, [data]); const EditBlog = async () => { setLoading(true); try { const res = await axios.put(`/edit-post/${data._id}`, values); if (res.data.error) { return toast.error(res.data.error); } else { navigate("/blogs"); toast.success("Edit"); } } catch (error) { console.log(error); return toast.error("Something went wrong"); } finally { setLoading(false); } }; return { values, setValues, loading, EditBlog }; };
function Player(name, symbol) { return { name, symbol, }; } function Cell() { let value = ""; const addToken = (token) => { value = token; }; const getToken = () => { return value; }; return { addToken, getToken, }; } function Gameboard() { let board = []; for (let i = 0; i < 3; i++) { board[i] = []; for (let j = 0; j < 3; j++) { board[i].push(Cell()); } } const getBoard = () => board; const dropToken = (token, idx1, idx2) => { // if (idx1 <= 0 || idx2 <= 0 || idx1 > 3 || idx2 > 3) { // console.log("Invalid gameboard idx"); // return; // } let currentCell = board[idx1][idx2]; if (currentCell.getToken() == "") { currentCell.addToken(token); } else { console.log("Already used by a player " + currentCell.getToken()); } }; const printBoard = () => { for (let i = 0; i < board.length; i++) { let str = ""; for (let j = 0; j < board[i].length; j++) { str += board[i][j].getToken() + " | "; } console.log(str); } }; return { getBoard, dropToken, printBoard, }; } function GameController(playerOne = "Player One", playerTwo = "Player Two") { const board = Gameboard(); let turns = 0; const players = [Player(playerOne, "X"), Player(playerTwo, "O")]; let currentPlayer = players[0]; let winner = ""; const switchPlayer = () => { currentPlayer = currentPlayer == players[0] ? players[1] : players[0]; }; const getCurrentPlayer = () => currentPlayer; const printNewRound = () => { board.printBoard(); console.log(currentPlayer.name + "'s turn"); }; const playRound = (idx1, idx2) => { if (winner) { board.printBoard(); console.log( `${currentPlayer.name} already won!! please start a new game.` ); return; } board.dropToken(currentPlayer.symbol, idx1, idx2); turns++; console.log( currentPlayer.name + ` marking ${idx1}, ${idx2} with ${currentPlayer.symbol}` ); printNewRound(); if (turns > 4) { if (checkWinner(board.getBoard(), currentPlayer.symbol)) { console.log("-----------------------"); console.log(`${currentPlayer.name} wins`); winner = currentPlayer.name; return; } } switchPlayer(); }; const checkWinner = (currentBoard, symbol) => { for (let i = 0; i < 3; i++) { if ( (currentBoard[i][0].getToken() == symbol && currentBoard[i][1].getToken() == symbol && currentBoard[i][2].getToken() == symbol) || (currentBoard[0][i].getToken() == symbol && currentBoard[1][i].getToken() == symbol && currentBoard[2][i].getToken() == symbol) ) { return true; } if ( (currentBoard[0][0].getToken() == symbol && currentBoard[1][1].getToken() == symbol && currentBoard[2][2].getToken() == symbol) || (currentBoard[0][2].getToken() == symbol && currentBoard[1][1].getToken() == symbol && currentBoard[2][0].getToken() == symbol) ) { return true; } return false; } }; printNewRound(); return { playRound, getCurrentPlayer, getBoard: board.getBoard, }; } // let game = GameController(); // game.playRound(1, 1); // game.playRound(1, 3); // game.playRound(3, 1); // game.playRound(2, 1); // game.playRound(3, 3); // game.playRound(3, 2); // game.playRound(2, 2); function ScreenController() { let game = GameController(); const boardDiv = document.querySelector('.board'); const updateScreen = () => { boardDiv.textContent = ""; const board = game.getBoard(); board.forEach((row, rowIndex) => { row.forEach((cell, columnIndex) => { const cellButton = document.createElement("button"); cellButton.classList.add("cell"); cellButton.dataset.column = columnIndex; cellButton.dataset.row = rowIndex; cellButton.textContent = cell.getToken(); boardDiv.appendChild(cellButton); }) }) } function clickHandler(e) { const row = e.target.dataset.row; const column = e.target.dataset.column; if(!row || !column) { return; } console.log(row, column, "-------------------------------") game.playRound(row, column); updateScreen(); } boardDiv.addEventListener("click", clickHandler); updateScreen(); // game.playRound(1, 1); // game.playRound(1, 3); // game.playRound(3, 1); // game.playRound(2, 1); // game.playRound(3, 3); // game.playRound(3, 2); // game.playRound(2, 2); } ScreenController();
use crate::prelude::*; use std::sync::Arc; #[derive(Clone)] pub struct AsyncSubject<'a, Item> where Item: Clone + Send + Sync, { subject: Arc<subject::Subject<'a, Item>>, } impl<'a, Item> AsyncSubject<'a, Item> where Item: Clone + Send + Sync, { pub fn new() -> AsyncSubject<'a, Item> { AsyncSubject { subject: Arc::new(subjects::Subject::new()), } } pub fn next(&self, item: Item) { self.subject.next(item); } pub fn error(&self, err: RxError) { self.subject.error(err); } pub fn complete(&self) { self.subject.complete(); } pub fn observable(&self) -> Observable<'a, Item> { self.subject.observable().take_last(1).clone() } } #[cfg(test)] mod tset { use crate::prelude::*; #[test] fn basic() { let sbj = subjects::AsyncSubject::new(); sbj.observable().subscribe( print_next_fmt!("{}"), print_error!(), print_complete!(), ); sbj.next(1); sbj.next(2); sbj.next(3); sbj.complete(); } #[test] fn error() { let sbj = subjects::AsyncSubject::new(); sbj.observable().subscribe( print_next_fmt!("{}"), print_error_as!(&str), print_complete!(), ); sbj.next(1); sbj.next(2); sbj.error(RxError::from_error("ERR!")); } }
/** * ***************************************************************************** Turnstone Biologics * Confidential * * <p>2018 Turnstone Biologics All Rights Reserved. * * <p>This file is subject to the terms and conditions defined in file 'license.txt', which is part * of this source code package. * * <p>Contributors : Turnstone Biologics - General Release * **************************************************************************** */ package com.occulue.europeanstandards.commongridmodelexchangestandard.equipmentprofile.loadmodel.controller.command; import com.occulue.api.*; import com.occulue.command.*; import com.occulue.controller.*; import com.occulue.delegate.*; import com.occulue.entity.*; import com.occulue.exception.*; import java.util.*; import java.util.concurrent.*; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.web.bind.annotation.*; /** * Implements Spring Controller command CQRS processing for entity ConformLoad. * * @author your_name_here */ @CrossOrigin @RestController @RequestMapping("/ConformLoad") public class ConformLoadCommandRestController extends BaseSpringRestController { /** * Handles create a ConformLoad. if not key provided, calls create, otherwise calls save * * @param ConformLoad conformLoad * @return CompletableFuture<UUID> */ @PostMapping("/create") public CompletableFuture<UUID> create( @RequestBody(required = true) CreateConformLoadCommand command) { CompletableFuture<UUID> completableFuture = null; try { completableFuture = ConformLoadBusinessDelegate.getConformLoadInstance().createConformLoad(command); } catch (Throwable exc) { LOGGER.log(Level.WARNING, exc.getMessage(), exc); } return completableFuture; } /** * Handles updating a ConformLoad. if no key provided, calls create, otherwise calls save * * @param ConformLoad conformLoad * @return CompletableFuture<Void> */ @PutMapping("/update") public CompletableFuture<Void> update( @RequestBody(required = true) UpdateConformLoadCommand command) { CompletableFuture<Void> completableFuture = null; try { // ----------------------------------------------- // delegate the UpdateConformLoadCommand // ----------------------------------------------- completableFuture = ConformLoadBusinessDelegate.getConformLoadInstance().updateConformLoad(command); ; } catch (Throwable exc) { LOGGER.log( Level.WARNING, "ConformLoadController:update() - successfully update ConformLoad - " + exc.getMessage()); } return completableFuture; } /** * Handles deleting a ConformLoad entity * * @param command ${class.getDeleteCommandAlias()} * @return CompletableFuture<Void> */ @DeleteMapping("/delete") public CompletableFuture<Void> delete(@RequestParam(required = true) UUID conformLoadId) { CompletableFuture<Void> completableFuture = null; DeleteConformLoadCommand command = new DeleteConformLoadCommand(conformLoadId); try { ConformLoadBusinessDelegate delegate = ConformLoadBusinessDelegate.getConformLoadInstance(); completableFuture = delegate.delete(command); LOGGER.log( Level.WARNING, "Successfully deleted ConformLoad with key " + command.getConformLoadId()); } catch (Throwable exc) { LOGGER.log(Level.WARNING, exc.getMessage()); } return completableFuture; } /** * save EnergyConsumers on ConformLoad * * @param command AssignEnergyConsumersToConformLoadCommand */ @PutMapping("/addToEnergyConsumers") public void addToEnergyConsumers( @RequestBody(required = true) AssignEnergyConsumersToConformLoadCommand command) { try { ConformLoadBusinessDelegate.getConformLoadInstance().addToEnergyConsumers(command); } catch (Exception exc) { LOGGER.log(Level.WARNING, "Failed to add to Set EnergyConsumers", exc); } } /** * remove EnergyConsumers on ConformLoad * * @param command RemoveEnergyConsumersFromConformLoadCommand */ @PutMapping("/removeFromEnergyConsumers") public void removeFromEnergyConsumers( @RequestBody(required = true) RemoveEnergyConsumersFromConformLoadCommand command) { try { ConformLoadBusinessDelegate.getConformLoadInstance().removeFromEnergyConsumers(command); } catch (Exception exc) { LOGGER.log(Level.WARNING, "Failed to remove from Set EnergyConsumers", exc); } } // ************************************************************************ // Attributes // ************************************************************************ protected ConformLoad conformLoad = null; private static final Logger LOGGER = Logger.getLogger(ConformLoadCommandRestController.class.getName()); }
<script setup> import {ref, onMounted, computed, watch } from 'vue' const todos = ref([]) const name = ref('') const input_content = ref('') const input_category = ref(null) const todos_asc = computed(() => todos.value.sort((a, b) =>{ return b.createdAt - a.createdAt })) const addTodo = () => { if (input_content.value.trim() === '' || input_category.value === null) { return } todos.value.push({ content: input_content.value, category: input_category.value, done: false, createdAt: new Date().getTime() }) input_content.value = '' input_category.value = null } const removeTodo = (todo) => { todos.value = todos.value.filter(t => t !== todo) } watch(todos, (newVal) => { localStorage.setItem('todos', JSON.stringify(newVal)) }, {deep: true}) watch(name, (newVal) => { localStorage.setItem('name', newVal) }) onMounted(()=> { name.value = localStorage.getItem('name') || '' todos.value = JSON.parse(localStorage.getItem('todos')) || [] }) </script> <template> <main class="app"> <section class="greeting"> <h2 class="title"> What's Up, <input type="text" placeholder="Name Here" v-model="name"/> </h2> </section> <section class="create-todo"> <h3>CREATE A TODO</h3> <form @submit.prevent="addTodo"> <h4>What's on your to-do list?</h4> <input type="text" placeholder=" e.g. Learn Javascript" v-model="input_content" /> <h4>Pick a Category</h4> <div class="options"> <label> <input type="radio" name="category" value="work" v-model="input_category" /> <span class="bubble business"></span> <div>Work</div> </label> <label> <input type="radio" name="category" value="personal" v-model="input_category" /> <span class="bubble personal"></span> <div>Personal</div> </label> </div> <input type="submit" value="Add Task"> </form> </section> <section class="todo-list"> <h3>TODO LIST</h3> <div class="list"> <div v-for="todo in todos_asc" :class="`todo-item ${todo.done && 'done'}`"> <label> <input type="checkbox" v-model="todo.done"> <span :class="`bubble ${todo.category == 'work' ? 'work' : 'personal'}`"></span> </label> <div class="todo-content"> <input type="text" name="" id="" v-model="todo.content"> </div> <div class="actions"> <button class="delete" @click="removeTodo(todo)">Delete</button> </div> </div> </div> </section> </main> </template>
import { Grid, Accordion, AccordionSummary, Typography, AccordionDetails, Divider, Box } from "@mui/material"; import { FC } from "react"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import { ReservationDtoWithError } from "./fileImport.types"; interface ImportErrorsProps { errors: ReservationDtoWithError[]; } const ImportErrors: FC<ImportErrorsProps> = ({ errors }) => { return ( <Grid container sx={{ py: 4, maxWidth: "75vw" }} spacing={2} justifyContent="center"> {errors.map((reservation) => ( <Grid item xs={12} key={reservation.rowNumber}> <Accordion> <AccordionSummary expandIcon={<ExpandMoreIcon />} sx={{ alignContent: "center" }}> <Box display="flex" alignItems="center"> <Typography textAlign="center" pr={4}> Línea {reservation.rowNumber} </Typography> </Box> <Divider orientation="vertical" flexItem /> <Typography sx={{ wordWrap: "break-word", pl: 4 }}>{reservation.error}</Typography> </AccordionSummary> <AccordionDetails> <Typography sx={{ wordWrap: "break-word" }} variant="body2"> {JSON.stringify(reservation.dto)} </Typography> </AccordionDetails> </Accordion> </Grid> ))} </Grid> ); }; export default ImportErrors;
let pokemon = [ {name: 'Bulbasaur', types: ['grass', 'poison'], attacks: ['tackle', 'vine whip']}, {name: 'Ivysaur', types: ['grass', 'poison'], attacks: ['razor leaf', 'vine whip']}, {name: 'Venusaur', types: ['grass', 'poison'], attacks: ['razor leaf', 'vine whip']}, {name: 'Charmander', types: ['fire'], attacks: ['scratch', 'ember']}, {name: 'Charmeleon', types: ['fire'], attacks: ['ember', 'fire fang']}, {name: 'Charizard', types: ['fire', 'flying'], attacks: ['fire spin', 'air slash']}, {name: 'Squirtle', types: ['water'], attacks: ['tackle', 'bubble']}, {name: 'Wartortle', types: ['water'], attacks: ['bite', 'water gun']}, {name: 'Blastoise', types: ['water'], attacks: ['bite', 'water gun']}, {name: 'Caterpie', types: ['bug'], attacks: ['bug bite', 'tackle']}, {name: 'Metapod', types: ['bug'], attacks: ['tackle', 'bug bite']}, {name: 'Butterfree', types: ['bug', 'flying'], attacks: ['struggle bug', 'confusion']}, {name: 'Weedle', types: ['bug', 'poison'], attacks: ['bug bite', 'poison sting']}, {name: 'Kakuna', types: ['bug', 'poison'], attacks: ['bug bite', 'poison sting']}, {name: 'Beedrill', types: ['bug', 'poison'], attacks: ['infestation', 'poison jab']}, {name: 'Pidgey', types: ['normal', 'flying'], attacks: ['quick attack', 'tackle']} ]; let results = []; // look at last element // results = pokemon[0]; // results = pokemon[pokemon.length - 1]; // results = pokemon.at(-1); // get and remove last element // pokemon.pop(); // get and rmove first element // pokemon.shift(); // get names of pokemon /* results = pokemon.map((pok, index) => { return pok.name; }); */ // retrieve only elements with 1 type /* results = pokemon.filter((pok) => { return pok.types.length === 1; }); */ // retrieve only elements with multiple types /* results = pokemon.filter((pok) => { return pok.types.length > 1; }); */ // retrieve only pokemon with multiple types WHERE one of those types is flying /* results = pokemon.filter((pok) => { return (pok.types.length > 1) && (pok.types.includes("flying")); }); */ // retrieve the NAMES of all pokemon with multiple types WHERE one of those types is flying /* results = pokemon.filter((pok) => { return (pok.types.length > 1) && (pok.types.includes("flying")); }).map((pok) => { return pok.name; }); */ // retrieve the NON-FLYING type of all pokemon with multiple types WHERE one of those types is flying results = pokemon.filter((pok) => { return (pok.types.length > 1) && (pok.types.includes("flying")); }).map((pok) => { return pok.types.filter((type) => { return type != "flying"; })[0]; }); console.log(results);
import React, { Component } from 'react'; import Link from 'next/link' import { Transition } from 'react-transition-group'; import { disableBodyScroll, enableBodyScroll, clearAllBodyScrollLocks } from 'body-scroll-lock'; import CartItem from '../cart/CartItem'; import { connect } from 'react-redux'; // Cart redux action creators import { retrieveCart as dispatchRetreiveCart } from '../../store/actions/cartActions'; const duration = 300; const defaultStyle = { transition: `transform ${duration}ms ease-in-out` }; const transitionStyles = { entering: { transform: 'translateX(100%)' }, entered: { transform: 'translateX(0)' }, exiting: { transform: 'translateX(100%)' }, exited: { transform: 'translateX(100%)' } }; const backdropTransitionStyles = { entering: { opacity: '0' }, entered: { opacity: '0.56' }, exiting: { opacity: '0' }, exited: { opacity: '0' } }; class Cart extends Component { constructor(props) { super(props); this.cartScroll = React.createRef(); this.onEntering = this.onEntering.bind(this); this.onExiting = this.onExiting.bind(this); } /** * Retrieve cart and contents client-side to dispatch to store */ componentDidMount() { this.props.dispatchRetreiveCart() } componentWillUnmount() { clearAllBodyScrollLocks(); } onEntering() { disableBodyScroll(this.cartScroll.current); } onExiting() { enableBodyScroll(this.cartScroll.current); } render() { const { isOpen, toggle } = this.props; const { cart } = this.props; return ( <Transition in={isOpen} timeout={duration} unmountOnExit onEntering={this.onEntering} onExiting={this.onExiting} > {state => ( <div className="cart-modal font-weight-regular"> <div className="backdrop" style={{ transition: `opacity ${duration}ms ease-in-out`, ...backdropTransitionStyles[state] }} onClick={() => toggle(false)} /> {/* Cart Main Content */} <div className="main-cart-content d-flex flex-column" style={{ ...defaultStyle, ...transitionStyles[state] }} > {/* Cart Header */} <div className="px-4 px-md-5"> <div className="pt-4 pb-3 borderbottom border-color-black d-flex justify-content-between align-items-center"> <p className="font-family-secondary font-size-subheader"> Shopping Cart </p> <button className="bg-transparent p-0" onClick={() => toggle(false)} > <img src="/icon/cross.svg" title="Times icon" alt="" /> </button> </div> </div> {cart.total_unique_items > 0 ? ( <> <div className="flex-grow-1 overflow-auto pt-4" ref={this.cartScroll} > {cart.line_items.map(item => ( <CartItem key={item.id} item={item} /> ))} </div> {/* Cart Footer */} <div className="cart-footer"> <div className="mb-3 d-flex"> <p className="font-color-light mr-2 font-weight-regular"> Subtotal: </p> <p>{cart.subtotal.formatted_with_symbol}</p> </div> <div className="row"> <div className="col-6 d-none d-md-block"> <Link href="/collection"> <a className="h-56 d-flex align-items-center justify-content-center border border-color-black bg-white w-100 flex-grow-1 font-weight-medium font-color-black px-3"> Continue Shopping </a> </Link> </div> <div className="col-12 col-md-6"> <Link href="/checkout"> <a className="h-56 d-flex align-items-center justify-content-center bg-black w-100 flex-grow-1 font-weight-medium font-color-white px-3"> Checkout </a> </Link> </div> </div> </div> </> ) : ( <div className="d-flex align-items-center justify-content-center bg-brand300 flex-grow-1 p-4 p-md-5 flex-column"> <div className="position-relative cursor-pointer mb-3"> <img src="/icon/cart.svg" title="Cart icon" alt="" className="w-32" /> <div className="position-absolute font-size-tiny font-weight-bold" style={{ right: '-4px', top: '-4px' }} > 0 </div> </div> <p className="text-center font-weight-medium"> Your cart is empty </p> </div> )} </div> </div> )} </Transition> ); } } export default connect(state => state, { dispatchRetreiveCart, })(Cart);
import { MdFlashOn } from "react-icons/md" import styles from "./styles.module.scss" import CountDown from "../../countDown/CountDown" import { useRef, useState } from "react"; // Import Swiper React components import { Swiper, SwiperSlide } from "swiper/react"; import { Pagination } from 'swiper/modules'; // Import Swiper styles import "swiper/css"; import "swiper/css/pagination"; import { flashDealsArray } from "@/data/home"; import FlashCard from "./card/FlashCard"; const FlashDeals = () => { return ( <div className={styles.flashDeals}> <div className={styles.flashDeals__header}> <h1> FLASH DEALS <MdFlashOn /> </h1> <CountDown date={new Date(2023, 9, 17)} /> </div> <Swiper slidesPerView={1} spaceBetween={50} pagination={{ clickable: true, }} breakpoints={{ 450: { slidesPerView: 2, }, 630: { slidesPerView: 3, }, 920: { slidesPerView: 4, }, 1232: { slidesPerView: 5, }, 1520: { slidesPerView: 6, }, }} modules={[Pagination]} className="flashDeals__swiper" > <div className={styles.flashDeals__list}> {flashDealsArray.map((product, i) => ( <SwiperSlide key={i}> <FlashCard product={product} /> </SwiperSlide> ))} </div> </Swiper> </div> ) } export default FlashDeals
import React, { useRef } from "react"; import Link from "next/link"; import SectionHeading from "@components/custom/SectionHeading"; import { clients_list } from "@data/data"; import styles from "@styles/home/Client.module.scss"; import { motion, useInView } from "framer-motion"; import { staggerChildrenVariants } from "@animations/preloader"; const Clients: React.FC = () => { const inViewRef = useRef<HTMLElement>(null); const isInView = useInView(inViewRef); return ( <motion.section className={styles.clients} id="#section" variants={staggerChildrenVariants} initial="hidden" animate={isInView && "visible"} ref={inViewRef} > <div className="container"> <SectionHeading title1="Selected Clients" /> </div> <div className={styles.clients_wrapper}> {clients_list.map(({ name, href, image }) => ( <Link href={href} passHref key={name}> <a title={name}> <img src={image} alt={name} /> </a> </Link> ))} </div> </motion.section> ); }; export default Clients;
// Define a type Product that has the properties id (number), name (string), description (string), and price (number). // Write a function that takes an array of Product and returns the most expensive product. type Product = { id: number; name: string; description: string; price: number; }; function mostExpensiveProduct(products: Product[]): Product { // The `reduce` function iterates over each product in the array, comparing their prices. // It returns the product with the highest price by comparing the current product's price with the highest found so far. return products.reduce((highest, product) => { if (product.price > highest.price) { return product; } return highest }) } 1 // Input: const products: Product[] = [ { id: 1, name: "Product 1", description: "This is product 1", price: 10 }, { id: 2, name: "Product 2", description: "This is product 2", price: 20 }, { id: 3, name: "Product 3", description: "This is product 3", price: 30 }, ]; // Expected Output: { id: 3, name: "Product 3", description: "This is product 3", price: 30 } console.log(mostExpensiveProduct(products)); const products2: Product[] = [ {id: 1, name: "Teclado", description: "Mechanical keyboard", price: 1_000}, {id: 2, name: "Monitor 34 inch", description: "ultrawide monitor curved", price: 25_000}, {id: 2, name: "Mouse X", description: "super light and precise mouse pro", price: 3_500}, ] console.log(mostExpensiveProduct(products2))
/* eslint-disable prettier/prettier */ import { useEffect, useState } from "react"; import axios from "axios"; import { Link } from "react-router-dom"; import MDButton from "components/MDButton"; import Icon from "@mui/material/Icon"; import Swal from "sweetalert2"; export default function PermissionsTable() { const [roles, setPermissions] = useState([]); async function getPermissions() { const response = await axios.get("http://127.0.0.1:8000/api/permissions"); return response.data; } async function deletePermission(id) { try { await axios.delete(`http://127.0.0.1:8000/api/permissions/${id}`); const newPermissions = users.filter((user) => user.id !== id); setPermissions(newPermissions); Swal.fire({ icon: "success", title: "Success!", text: "Utilisateur supprimé", }); } catch (error) { Swal.fire({ icon: "error", title: "Oops...", text: "Erreur utilisateur non supprimé", }); } } useEffect(() => { async function fetchData() { const data = await getPermissions(); setPermissions(data); } fetchData(); }, []); return { columns: [ { Header: "Role", accessor: "Role", width: "45%", align: "left" }, { Header: "Description", accessor: "Description", align: "left" }, { Header: "Action", accessor: "Action", align: "center" }, ], rows: roles.map((role) => ({ Role: role.name, Description: role.description, Action: [ <Link key="edit" to={`/permissions/edit/${role.id}`} component={Link}> <MDButton variant="text" color="dark"> <Icon>edit</Icon>&nbsp;edit </MDButton> </Link>, <MDButton key="delete" variant="text" color="primary" onClick={() => { Swal.fire({ title: "Voulez vous confirmer la suppression?", text: "Vous ne pourrez pas revenir en arrière !", icon: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", confirmButtonText: "Supprimer", cancelButtonText: "Annuler", }).then((result) => { if (result.isConfirmed) { deletePermission(user.id); } }); }} > <Icon>delete</Icon>&nbsp;delete </MDButton>, ], })), }; }
![notice1.png](img/notice1.png) ## 🧑🏻‍💻<a href="https://webduck.info">Webduck 방문하기</a> --- ## 📚웹툰 덕후들을 위한 사이트 --- 플랫폼 별 리뷰가 달라 당황스러우셨나요? 요일마다 보시던 웹툰을 잊으셨나요? --- ## 🥸WebdDuck에서 웹툰관리하고 리뷰를 찾아보세요! 웹툰 리뷰평을 보고 보고싶은 웹툰을 <a href="https://webduck.info">WebDuck</a>에서 찾아봐요 나만의 보관함을 만들어 보던 웹툰을 기록하세요! --- ## 📝목차 - [기술스택](#기술스택) - [아키텍처](#아키텍쳐) - [ERD](#erd) - [빌드](#빌드) - [API 문서](#api-문서) - [관리자 페이지](#관리자-페이지) - [트러블슈팅](#트러블슈팅) --- ## 🔧기술스택 | **BackEnd** | |:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:| | ![Spring boot](https://img.shields.io/badge/SpringBoot-6DB33F?style=flat-square&logo=SpringBoot&logoColor=white) ![RestDocs](https://img.shields.io/badge/RestDocs-ff?style=flat-square&logo=SpringBoot&logoColor=white) ![Spring Security](https://img.shields.io/badge/SpringSecurity-6DB33F?style=flat-square&logo=SpringSecurity&logoColor=white) ![Gradle](https://img.shields.io/badge/Gradle-white?style=flat-square&logo=gradle&color=02303A) ![Java](https://img.shields.io/badge/Java-ED8B00?style=flat-square&logo=java&logoColor=white) | **FrontEnd** | ![Vue](https://img.shields.io/badge/Vue.js-35495E?style=flat-the-badge&logo=vuedotjs&logoColor=4FC08D) | **DataBase** | ![MariaDB](https://img.shields.io/badge/MariaDB-003545?style=flat-the-badge&logo=mariadb&logoColor=white) | **Infra** | | ![AWS](https://img.shields.io/badge/AWS-232F3E?style=flat-square&logo=AmazonAWS&logoColor=white) ![Git Action](https://img.shields.io/badge/GitAction-2088FF?style=flat-square&logo=GithubActions&logoColor=white) ![S3](https://img.shields.io/badge/S3-569A31?style=flat-square&logo=AmazonS3&logoColor=white) ![EC2](https://img.shields.io/badge/EC2-orange?style=flat-square&logo=AmazonAWS&logoColor=white) ![RDS](https://img.shields.io/badge/RDS-1E90FF?style=flat-square&logo=AmazonAWS&logoColor=white) ![Nginx](https://img.shields.io/badge/Nginx-009639?style=flat-square&logo=Nginx&logoColor=white) --- ## 아키텍쳐 ![architecture.png](img/architecture.png) --- ## ERD --- ![db.png](img/db.png) --- ## 빌드 | **도커 사용 시** | |:-----------:| ``` docker compose up ``` ### 접속 - 프론트엔드 http://localhost:80 - 백엔드 http://localhost:8090 <br/> | **수동 빌드 시** | |:-----------:| ### Vue #### webduck/frontend ```java vue run dev // 개발환경 vue run build // 배포환경 ``` ### SpringBoot #### webduck/backend #### 환경 설정 ```yaml # webduck/backend/src/main/resources/application.yml spring: profiles: active: dev // prod,test,docker ``` #### gradle ```java ./gradlew build ``` #### jar ```java java -jar webduck/backend/build/libs/*.jar ``` ### 접속 - 프론트엔드 http://localhost:5173 - 백엔드 http://localhost:8090 --- ## API 문서 http://localhost:8090/docs/index.html --- ## 관리자 페이지 | **도커 환경** | **http://localhost:80/login** | |:------------:|:-------------------------------:| | **수동 배포 환경** | **http://localhost:5173/login** | 1. 관리자 로그인 ![admin1.png](img/admin1.png) <br/> 2. 상단 메뉴바 관리자 페이지 접속 ![admin2.png](img/admin2.png) <br/> 3. 메뉴 목록 ![admin3.png](img/admin3.png) --- ## 📌트러블슈팅 & 성능 개선 - [외부 API 여러건 요청 성능 개선](https://velog.io/@minu1117/%EC%86%8D%EB%8F%84%EA%B0%80-%EB%8A%90%EB%A6%B0-%EC%99%B8%EB%B6%80-API-%EA%B0%9C%EC%84%A0%EA%B8%B0-1-Multi-Thread) - [자주 조회되는 API 성능 개선](https://velog.io/@minu1117/Ehcache-%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EC%84%B1%EB%8A%A5-%EA%B0%9C%EC%84%A0ngrinder-%EB%AA%A8%EB%8B%88%ED%84%B0%EB%A7%81) - [만능과 같은 서비스 레이어](backend/troubleshooting%20/서비스_레이어.md) - [웹툰 데이터 통합 처리](backend/troubleshooting%20/웹툰_데이터_통합처리.md) - [방대해지는 연관 관계](backend/troubleshooting%20/연관관계.md)
import apiArticle from '@/api/article'; const state = { isSubmitting: false, validatesError: null, isLoading: false, article: null, }; export const mutationsType = { updateArticleStart: '[editArticle] updateArticleStart', updateArticleSuccess: '[editArticle] updateArticleSuccess', updateArticleFailure: '[editArticle] updateArticleFailure', getArticleStart: '[editArticle] getArticleStart', getArticleSuccess: '[editArticle] getArticleSuccess', getArticleFailure: '[editArticle] getArticleFailure', }; export const actionTypes = { updateArticle: '[editArticle] updateArticle', getArticle: '[editArticle] getArticle', }; const mutations = { [mutationsType.updateArticleStart](state) { state.isSubmitting = true; }, [mutationsType.updateArticleSuccess](state) { state.isSubmitting = false; }, [mutationsType.updateArticleFailure](state, payload) { state.isSubmitting = false; state.validatesError = payload; }, [mutationsType.getArticleStart](state) { state.isLoading = true; state.article = null; }, [mutationsType.getArticleSuccess](state, payload) { state.isLoading = false; state.article = payload; }, [mutationsType.getArticleFailure](state) { state.isLoading = false; }, }; const actions = { [actionTypes.updateArticle](context, { slug, articleInput }) { return new Promise((resolve) => { context.commit(mutationsType.updateArticleStart); apiArticle .updateArticle(slug, articleInput) .then((article) => { context.commit(mutationsType.updateArticleSuccess, article); resolve(article); }) .catch((result) => { context.commit( mutationsType.updateArticleFailure, result.response.data.errors ); }); }); }, [actionTypes.getArticle](context, { slug }) { return new Promise((resolve) => { context.commit(mutationsType.getArticleStart); apiArticle .getArticle(slug) .then((article) => { context.commit(mutationsType.getArticleSuccess, article); resolve(article); }) .catch(() => { context.commit(mutationsType.getArticleFailure); }); }); }, }; export default { state, actions, mutations, };
import React, { useState } from "react"; import { Dropdown, Space, Menu } from "antd"; import { useTranslation } from "react-i18next"; import { DownOutlined } from "@ant-design/icons"; const Navbar: React.FC = () => { const [menuOpen, setMenuOpen] = useState(false); const { t } = useTranslation(); const [dropdownOpen] = useState(false); const [arrowRotation, setArrowRotation] = useState(false); const [dropdownActive, setDropdownActive] = useState<string | null>(null); const toggleMenu = () => { setMenuOpen(!menuOpen); }; const toggleDropdown = (dropdown: string) => { setDropdownActive(dropdownActive === dropdown ? null : dropdown); }; const closeDropdown = () => { setDropdownActive(null); }; const handleDropdownClick = (dropdown: string) => { if (dropdownActive === dropdown) { setDropdownActive(null); setArrowRotation(false); // Đặt trạng thái ban đầu khi đóng dropdown } else { setDropdownActive(dropdown); setArrowRotation(true); // Đặt trạng thái xoay khi mở dropdown } setMenuOpen(false); // Đóng menu khi chọn dropdown item }; const exploreMenu = [ { key: "0", label: ( <a target="_blank" rel="noopener noreferrer" href="https://docs.hyperaschain.com/technology/architecture" > Hyperaschain Layer 1 </a> ), onClick: () => setMenuOpen(false), // Đóng menu khi mục được nhấp }, { key: "1", label: ( <a target="_blank" rel="noopener noreferrer" href="https://docs.hyperaschain.com/general/ecosystem" > Hyperaschain Ecosystem </a> ), onClick: () => setMenuOpen(false), // Đóng menu khi mục được nhấp }, { key: "2", label: ( <a target="_blank" rel="noopener noreferrer" href="https://docs.hyperaschain.com/general/presskit" > Presskit </a> ), onClick: () => setMenuOpen(false), // Đóng menu khi mục được nhấp }, { key: "divider", type: "divider", }, ]; const applicationsMenu = [ { label: ( <a target="_blank" rel="noopener noreferrer" href="https://salala.io/"> Salala </a> ), key: "0", onClick: () => setMenuOpen(false), }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://egabid.com/"> Egabid </a> ), key: "1", onClick: () => setMenuOpen(false), }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://pindias.com/" > Pindias </a> ), key: "2", onClick: () => setMenuOpen(false), }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://www.hyperaschain.com/stake" > Staking </a> ), key: "3", onClick: () => setMenuOpen(false), }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://testnet.hyrascan.com/" > Scan </a> ), key: "4", onClick: () => setMenuOpen(false), }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://www.hyperaschain.com/swap" > Swap </a> ), key: "5", onClick: () => setMenuOpen(false), }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://www.hyperaschain.com/bridge" > Bridge </a> ), key: "6", onClick: () => setMenuOpen(false), }, { key: "divider", type: "divider", }, ]; const foundationMenu = [ { label: ( <a target="_blank" rel="noopener noreferrer" href="https://docs.hyperaschain.com/developers" > Hyperas Program </a> ), key: "0", }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://www.youtube.com/@Hyperaschain" > Video Tutorials </a> ), key: "1", }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://www.hyperaschain.com/news" > Blog </a> ), key: "2", }, { type: "divider", }, ]; const communityMenu = [ { label: ( <a target="_blank" rel="noopener noreferrer" href="https://t.me/hyperaschaingroup" > Hyperas Global Group </a> ), key: "0", }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://t.me/hyperaschaingroup" > Hyperas Vietnam group </a> ), key: "1", }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://www.facebook.com/hyperaschain" > Hyperaschain Facebook </a> ), key: "2", }, { label: ( <a target="_blank" rel="noopener noreferrer" href="https://twitter.com/hyperaschain" > Hyperaschain X </a> ), key: "3", }, { label: <span>Salala community</span>, key: "4", }, { label: <span>Egabid community</span>, key: "5", }, { type: "divider", }, ]; return ( <section className="animate-fadeInDown manrope"> <nav className="container mx-auto py-[16px] px-4 flex justify-between items-center animate-fadeInDown"> <a href="/"> <img className="" src="./Img/Logo.png" alt="Logo" /> </a> <div className="hidden lg:block"> <ul className="flex text-[#270017] text-[14px] justify-between items-center gap-8"> <Dropdown className={`text-[16px] font-bold ${ dropdownActive === "explore" ? "dropdown-active" : "" }`} overlay={ <Menu onClick={closeDropdown}> {exploreMenu.map((item) => ( <Menu.Item key={item.key} onClick={item.onClick}> {item.label} </Menu.Item> ))} </Menu> } trigger={["click"]} onVisibleChange={() => toggleDropdown("explore")} > <Space onClick={() => handleDropdownClick("explore")}> {t("explore")} <DownOutlined className={`transform ${ arrowRotation && dropdownActive === "explore" ? "rotate-180" : "" }`} style={{ fontSize: "14px" }} /> </Space> </Dropdown> {/* Dropdown Applications */} <Dropdown className={`text-[16px] font-bold ${ dropdownActive === "applications" ? "dropdown-active" : "" }`} overlay={ <Menu onClick={closeDropdown}> {applicationsMenu.map((item) => ( <Menu.Item key={item.key} onClick={item.onClick}> {item.label} </Menu.Item> ))} </Menu> } trigger={["click"]} onVisibleChange={() => toggleDropdown("applications")} > <Space onClick={() => handleDropdownClick("applications")}> {t("applications")} <DownOutlined className={`transform ${ arrowRotation && dropdownActive === "applications" ? "rotate-180" : "" }`} style={{ fontSize: "14px" }} /> </Space> </Dropdown> {/* Dropdown Foundation */} <Dropdown className={`text-[16px] font-bold ${ dropdownActive === "foundation" ? "dropdown-active" : "" }`} overlay={ <Menu onClick={closeDropdown}> {foundationMenu.map((item) => ( <Menu.Item key={item.key}>{item.label}</Menu.Item> ))} </Menu> } trigger={["click"]} onVisibleChange={() => toggleDropdown("foundation")} > <Space onClick={() => handleDropdownClick("foundation")}> {t("Foundation")} <DownOutlined className={`transform ${ arrowRotation && dropdownActive === "foundation" ? "rotate-180" : "" }`} style={{ fontSize: "14px" }} /> </Space> </Dropdown> {/* Dropdown Community */} <Dropdown className={`text-[16px] font-bold ${ dropdownActive === "community" ? "dropdown-active" : "" }`} overlay={ <Menu onClick={closeDropdown}> {communityMenu.map((item) => ( <Menu.Item key={item.key}>{item.label}</Menu.Item> ))} </Menu> } trigger={["click"]} onVisibleChange={() => toggleDropdown("community")} > <Space onClick={() => handleDropdownClick("community")}> {t("Community")} <DownOutlined className={`transform ${ arrowRotation && dropdownActive === "community" ? "rotate-180" : "" }`} style={{ fontSize: "14px" }} /> </Space> </Dropdown> </ul> </div> <a target="_blank" rel="noopener noreferrer" href="https://linktr.ee/hyperaschain" className="custom-link w-32 hidden lg:block font-medium h-10 px-5 py-2 gap-2 rounded-[4px] border border-solid border-[#EC008C] text-[14px]" > {t("Get")} </a> <div className={`lg:hidden ${menuOpen ? "hidden" : ""}`}> <button className="navbar-burger flex items-center text-white p-3" onClick={toggleMenu} > <img src="../Img/Frame 3072.png" alt="Menu" /> </button> </div> <div className={`navbar-menu ${menuOpen ? "" : "hidden"}`} style={{ zIndex: 1000 }} > <div className="navbar-backdrop fixed inset-0 bg-neutral-950 opacity-25" onClick={toggleMenu} ></div> <nav className="fixed top-0 right-0 bottom-0 flex flex-col w-5/6 max-w-sm py-6 px-6 bg-blue-50 border-r overflow-y-auto"> <div className="flex justify-between items-center mb-4"> <img src="../svg/Group 1.svg" alt="" /> <button className="navbar-close" onClick={toggleMenu}> <svg className="h-6 w-6 text-gray-400 cursor-pointer hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" ></path> </svg> </button> </div> {/* Menu Items */} <ul className="flex flex-col text-[#270017] text-[14px] justify-center items-center gap-7"> <Dropdown className={`text-[16px] font-bold ${ dropdownActive === "explore" ? "dropdown-active" : "" }`} overlay={ <Menu onClick={toggleMenu}> {exploreMenu.map((item) => ( <Menu.Item key={item.key}>{item.label}</Menu.Item> ))} </Menu> } trigger={["click"]} onVisibleChange={() => toggleDropdown("explore")} > <Space> {t("explore")} <DownOutlined className={`transform ${ arrowRotation && dropdownActive === "explore" ? "rotate-180" : "" }`} style={{ fontSize: "14px" }} /> </Space> </Dropdown> <Dropdown className={`text-[16px] font-bold ${ dropdownActive === "applications" ? "dropdown-active" : "" }`} overlay={ <Menu onClick={toggleMenu}> {applicationsMenu.map((item) => ( <Menu.Item key={item.key}>{item.label}</Menu.Item> ))} </Menu> } trigger={["click"]} onVisibleChange={() => toggleDropdown("applications")} > <Space> {t("applications")} <DownOutlined className={`transform ${ arrowRotation && dropdownActive === "applications" ? "rotate-180" : "" }`} style={{ fontSize: "14px" }} /> </Space> </Dropdown> <Dropdown className={`text-[16px] font-bold ${ dropdownActive === "foundation" ? "dropdown-active" : "" }`} overlay={ <Menu onClick={toggleMenu}> {foundationMenu.map((item) => ( <Menu.Item key={item.key}>{item.label}</Menu.Item> ))} </Menu> } trigger={["click"]} onVisibleChange={() => toggleDropdown("foundation")} > <Space> {t("Foundation")} <DownOutlined className={`transform ${ arrowRotation && dropdownActive === "foundation" ? "rotate-180" : "" }`} style={{ fontSize: "14px" }} /> </Space> </Dropdown> <Dropdown className={`text-[16px] font-bold ${ dropdownActive === "community" ? "dropdown-active" : "" }`} overlay={ <Menu onClick={toggleMenu}> {communityMenu.map((item) => ( <Menu.Item key={item.key}>{item.label}</Menu.Item> ))} </Menu> } trigger={["click"]} onVisibleChange={() => toggleDropdown("community")} > <Space> {t("Community")} <DownOutlined className={`transform ${ arrowRotation && dropdownActive === "community" ? "rotate-180" : "" }`} style={{ fontSize: "14px" }} /> </Space> </Dropdown> <a target="_blank" rel="noopener noreferrer" href="https://linktr.ee/hyperaschain" className="w-32 custom-link font-medium h-10 px-5 py-2 gap-2 rounded-[4px] border border-solid border-[#EC008C] text-[#EC008C] text-[14px]" > {t("Get")} </a> </ul> </nav> </div> </nav> </section> ); }; export default Navbar;
import React from "react"; import { Formik, Field, ErrorMessage } from "formik"; import * as Yup from "yup"; import { MdLocationDisabled } from "react-icons/md"; import { GoTrash } from "react-icons/go"; import PhoneInput from "react-phone-input-2"; import "./index.css"; import { Col, Row, Form } from "react-bootstrap"; const DistributorInformation = () => { const validationSchema = Yup.object().shape({ distributorName: Yup.string().required("Distributor Name is required"), formBasicStreet: Yup.string().required("Street is required"), country: Yup.string().required("Country is required"), postalCode: Yup.string().required("Postal Code is required"), superAdmin: Yup.string().required("Super Admin is required"), businessEmail: Yup.string() .email("Invalid email") .required("Email is required"), phoneNumber: Yup.string().required("Phone Number is required"), alternativeDistributor: Yup.string(), }); return ( <div className="distributorinfo"> <h3 className="text-center border-bottom pb-4 pt-2"> Distributor Information </h3> <div className="infoformdata pt-4 pb-2"> <Formik initialValues={{ distributorName: "", street: "", country: "", postalCode: "", superAdmin: "", businessEmail: "", phoneNumber: "", alternativeDistributor: "", }} validationSchema={validationSchema} onSubmit={(values, { setSubmitting }) => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); setSubmitting(false); }, 400); }} > {({ isSubmitting }) => ( <Form> <div className="row"> <div className="col-md-5 "> <div className="companylogodata"> <h6>Company Logo</h6> <div className="companylogo"> <p> Recommanended logo <br /> specifications: <br />{" "} 500px*300px <br /> transparent PNG </p> </div> <div className="text-center pt-2">Edit</div> </div> <div className="companylogodata"> <h6>Company White Logo</h6> <div className="companylogo"> <p> Recommanended logo <br /> specifications: <br />{" "} 500px*300px <br /> transparent PNG </p> </div> <div className="text-center pt-2">Edit</div> </div> </div> <div className="col-md-7"> <Row> <Col> <Form.Group className="mb-3" controlId="distributorName"> <Field type="text" name="distributorName" placeholder="Distributor Name" as={Form.Control} /> <ErrorMessage name="distributorName" component="div" className="error-message" /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicStreet"> <Field type="text" name="formBasicStreet" placeholder="Street" as={Form.Control} /> <ErrorMessage name="formBasicStreet" component="div" className="error-message" /> </Form.Group> </Col> </Row> <Row> <Col> <Form.Group className="mb-3" controlId="formBasicCountry"> <Field type="text" name="country" placeholder="Country" as={Form.Control} /> <ErrorMessage name="country" component="div" className="error-message" />{" "} </Form.Group> </Col> <Col> <Form.Group className="mb-3" controlId="formBasicPostal"> <Field type="text" name="postalCode" placeholder="Postal Code" as={Form.Control} /> <ErrorMessage name="postalCode" component="div" className="error-message" />{" "} </Form.Group> </Col> </Row> <hr /> <Row> <Col> <Form.Group className="mb-3" controlId="formBasicSuperAdmin" > <Field type="text" name="superAdmin" placeholder="Super Admin" as={Form.Control} /> <ErrorMessage name="superAdmin" component="div" className="error-message" />{" "} </Form.Group> <Form.Group className="mb-3" controlId="formBasicBusinessEmail" > <Field type="text" name="businessEmail" placeholder="BusinessEmail" as={Form.Control} /> <ErrorMessage name="businessEmail" component="div" className="error-message" />{" "} <Form.Control type="text" /> </Form.Group> </Col> </Row> <Row> <Col xs lg="2"> <div className="phoneinput"> <Field name="phoneNumber"> {({ field, meta }) => ( <PhoneInput {...field} country={"us"} placeholder="Phone Number" inputProps={{ name: field.name }} onChange={(value) => field.onChange(field.name)(value) } /> )} </Field> <ErrorMessage name="phoneNumber" component="div" className="error-message" /> </div> </Col> <Col> <Form.Group className="mb-3" controlId="formBasicNumber"> <Form.Control type="text" placeholder="Number" /> </Form.Group> </Col> </Row> </div> </div> <hr /> <div className="d-flex align-items-center"> <h6 className="w-25">Alternative Distributor</h6> <Form.Control type="text" className="w-75" placeholder="Distribution Name" /> </div> <hr /> <div className="row"> <div className="col-md-6"> <div className="d-flex"> <div className="me-5"> <MdLocationDisabled size={20} /> <span className="ms-1">Disable</span> </div> <div> <GoTrash size={20} /> <span> Delete</span> </div> </div> </div> <div className="col-md-6 text-end"> <button className="btn btn-dark"> Cancel</button> <button className="btn btn-primary ms-4 w-50"> Save Changes </button> </div> </div>{" "} </Form> )} </Formik> </div> </div> ); }; export default DistributorInformation;
import React, { useState } from 'react'; import { Input, Form, Tabs, Button, Radio, Checkbox } from 'antd'; import { Select } from 'antd'; import 'antd/dist/antd.css'; type RequiredMark = boolean | 'optional'; function Properties() { const [form] = Form.useForm(); const [requiredMark, setRequiredMarkType] = useState<RequiredMark>('optional'); const onRequiredTypeChange = ({ requiredMarkValue, }: { requiredMarkValue: RequiredMark; }) => { setRequiredMarkType(requiredMarkValue); }; const onFinish = (values: any) => { console.log('Success:', values); fetch('/propertiesAdd', { method: 'POST', body: JSON.stringify(values), headers: { 'Content-Type': 'application/json' }, }) .then((res) => res.json()) .then((json) => console.log(json)); }; const onFinishFailed = (errorInfo: any) => { console.log('Failed:', errorInfo); }; return ( <Form layout='vertical' name='basic' labelCol={{ span: 8 }} wrapperCol={{ span: 6 }} initialValues={{ remember: true }} onFinish={onFinish} onFinishFailed={onFinishFailed} autoComplete='off'> <Form.Item label='Cihaz Özellik Adı' name='name' rules={[{ required: true, message: 'Lütfen Özellik adı girin' }]}> <Input /> </Form.Item> <Form.Item> <Button type='primary' htmlType='submit'> Submit </Button> </Form.Item> </Form> ); } export default Properties;
/** * Synchronously resolve array of Promise executor functions. * * ```js * import promiseSynchronous from "@elricb/functions/promise/synchronous"; * * const a = [ * (resolve, reject) => setTimeout(resolve.bind(null, 1), 600), * (resolve, reject) => setTimeout(resolve.bind(null, 2), 500), * (resolve, reject) => setTimeout(resolve.bind(null, 3), 200) * ]; * * promiseSynchronous(a, (i) => console.log(`Promise ${i} done.`)).then(() => * console.log("All done") * ); * ``` */ export default async function ( iterator: FunctionExecutor[], callback: Function = () => {} ): Promise<any> { /** * Requires minimum target es2015 * for (const executor of iterator) { * callback(await new Promise(executor)); * } */ for (let i = 0; i < iterator.length; i++) { callback(await new Promise(iterator[i])); } }
<?php /** * Simple product add to cart * * This template can be overridden by copying it to yourtheme/woocommerce/single-product/add-to-cart/simple.php. * * HOWEVER, on occasion WooCommerce will need to update template files and you * (the theme developer) will need to copy the new files to your theme to * maintain compatibility. We try to do this as little as possible, but it does * happen. When this occurs the version of the template file will be bumped and * the readme will list any important changes. * * @see https://docs.woocommerce.com/document/template-structure/ * @package WooCommerce/Templates * @version 3.4.0 */ defined( 'ABSPATH' ) || exit; global $product; if ( ! $product->is_purchasable() ) { return; } echo wc_get_stock_html( $product ); // WPCS: XSS ok. // if ( $product->is_in_stock() ) : ?> <?php do_action( 'woocommerce_before_add_to_cart_form' ); ?> <?php $stop_selling = get_field('stop_selling', $product->get_id()); ?> <?php if( !$stop_selling ): $check_stock = true; if( function_exists( 'get_stock_nhanhvn_inventories' ) ) { $stock = get_stock_nhanhvn_inventories( get_field('product_nhanhvn_id', $product->get_id()) ); if( $stock > 0 ) $check_stock = true; else $check_stock = false; } else { $check_stock = false; } ?> <?php if( $check_stock ) : ?> <p class="pd-stock-status"><strong>CÒN HÀNG</strong></p> <?php else : ?> <p class="pd-stock-status pre-order"><strong style="color: orange">TẠM HẾT HÀNG - CẦN ĐẶT TRƯỚC</strong></p> <?php endif; ?> <?php endif; ?> <form id="cart-top" class="cart" action="<?php echo esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product->get_permalink() ) ); ?>" method="post" enctype='multipart/form-data'> <?php do_action( 'woocommerce_before_add_to_cart_button' ); ?> <?php do_action( 'woocommerce_before_add_to_cart_quantity' ); woocommerce_quantity_input( array( 'min_value' => apply_filters( 'woocommerce_quantity_input_min', $product->get_min_purchase_quantity(), $product ), 'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ), 'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( wp_unslash( $_POST['quantity'] ) ) : $product->get_min_purchase_quantity(), // WPCS: CSRF ok, input var ok. ) ); do_action( 'woocommerce_after_add_to_cart_quantity' ); ?> <button <?php if ( $product->is_type('simple') ) echo 'id="simple-product-add-to-cart"' ?> type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt"> <b><?php echo esc_html( $product->single_add_to_cart_text() ); ?></b><br/> </button> <?php do_action( 'woocommerce_after_add_to_cart_button' ); ?> </form> <?php do_action( 'woocommerce_after_add_to_cart_form' ); ?> <?php //endif; ?>
# Ellama [![License GPL 3](https://img.shields.io/badge/license-GPL_3-green.svg)](http://www.gnu.org/licenses/gpl-3.0.txt) [![MELPA](https://melpa.org/packages/ellama-badge.svg)](https://melpa.org/#/ellama) [![MELPA Stable](https://stable.melpa.org/packages/ellama-badge.svg)](https://stable.melpa.org/#/ellama) [![GNU ELPA](https://elpa.gnu.org/packages/ellama.svg)](https://elpa.gnu.org/packages/ellama.html) Ellama is a tool for interacting with large language models from Emacs. It allows you to ask questions and receive responses from the LLMs. Ellama can perform various tasks such as translation, code review, summarization, enhancing grammar/spelling or wording and more through the Emacs interface. Ellama natively supports streaming output, making it effortless to use with your preferred text editor. ## Installation Install the package `ellama` from [MELPA](https://melpa.org/#/getting-started). Just `M-x` `package-install`<kbd>Enter</kbd> `ellama` <kbd>Enter</kbd>. By default it uses [ollama](https://github.com/jmorganca/ollama) provider and [zephyr](https://ollama.ai/library/zephyr) model. If you ok with it, you need to install [ollama](https://github.com/jmorganca/ollama) and pull [zephyr](https://ollama.ai/library/zephyr). You can use `ellama` with other model or other llm provider. In that case you should customize ellama configuration like this: ``` emacs-lisp (use-package ellama :init (setopt ellama-language "German") (require 'llm-ollama) (setopt ellama-provider (make-llm-ollama :chat-model "zephyr:7b-beta-q6_K" :embedding-model "zephyr:7b-beta-q6_K")) ;; Predefined llm providers for interactive switching. ;; You shouldn't add ollama providers here - it can be selected interactively ;; without it. It is just example. (setopt ellama-providers '(("zephyr" . (make-llm-ollama :chat-model "zephyr:7b-beta-q6_K" :embedding-model "zephyr:7b-beta-q6_K")) ("mistral" . (make-llm-ollama :chat-model "mistral:7b-instruct-v0.2-q6_K" :embedding-model "mistral:7b-instruct-v0.2-q6_K")) ("mixtral" . (make-llm-ollama :chat-model "mixtral:8x7b-instruct-v0.1-q3_K_M-4k" :embedding-model "mixtral:8x7b-instruct-v0.1-q3_K_M-4k"))))) ``` ## Commands ### ellama-chat Ask Ellama about something by entering a prompt in an interactive buffer and continue conversation. ### ellama-ask Alias for `ellama-chat`. ![ellama-ask](imgs/ellama-ask.gif) ### ellama-ask-about Ask Ellama about a selected region or the current buffer. ![ellama-ask-about](imgs/ellama-ask-about.gif) ### ellama-ask-selection Send selected region or current buffer to ellama chat. ### ellama-ask-line Send current line to ellama chat. ### ellama-complete Complete text in current buffer with ellama. ### ellama-translate Ask Ellama to translate a selected region or word at the point. ![ellama-translate](imgs/ellama-translate.gif) ### ellama-define-word Find the definition of the current word using Ellama. ![ellama-define-word](imgs/ellama-define-word.gif) ### ellama-summarize Summarize a selected region or the current buffer using Ellama. ![ellama-summarize](imgs/ellama-summarize.gif) ### ellama-code-review Review code in a selected region or the current buffer using Ellama. ![ellama-code-review](imgs/ellama-code-review.gif) ### ellama-change Change text in a selected region or the current buffer according to a provided change. ### ellama-enhance-grammar-spelling Enhance the grammar and spelling in the currently selected region or buffer using Ellama. ![ellama-enhance-grammar-spelling](imgs/ellama-enhance-grammar-spelling.gif) ### ellama-enhance-wording Enhance the wording in the currently selected region or buffer using Ellama. ### ellama-make-concise Make the text of the currently selected region or buffer concise and simple using Ellama. ### ellama-change-code Change selected code or code in the current buffer according to a provided change using Ellama. ### ellama-enhance-code Change selected code or code in the current buffer according to a provided change using Ellama. ### ellama-complete-code Complete selected code or code in the current buffer according to a provided change using Ellama. ### ellama-add-code Add new code according to a description, generating it with a provided context from the selected region or the current buffer using Ellama. ### ellama-render Render the currently selected text or the text in the current buffer as a specified format using Ellama. ### ellama-make-list Create a markdown list from the active region or the current buffer using Ellama. ### ellama-make-table Create a markdown table from the active region or the current buffer using Ellama. ### ellama-summarize-webpage Summarize a webpage fetched from a URL using Ellama. ### ellama-provider-select Select ellama provider. ### ellama-code-complete Alias to the `ellama-complete-code` function. ### ellama-code-add Alias to the `ellama-add-code` function. ### ellama-code-edit Alias to the `ellama-change-code` function. ### ellama-code-improve Alias to the `ellama-enhance-code` function. ### ellama-improve-wording Alias to the `ellama-enhance-wording` function. ### ellama-improve-grammar Alias to the `ellama-enhance-grammar-spelling` function. ### ellama-improve-conciseness Alias to the `ellama-make-concise` function. ### ellama-make-format Alias to the `ellama-render` function. ### ellama-ask-interactive Alias to the `ellama-ask` function. ## Keymap Here is a table of keybindings and their associated functions in Ellama, using the `C-c e` prefix: | Keymap | Function | Description | |--------|----------------------------|------------------------------------| | "c c" | ellama-code-complete | Code complete | | "c a" | ellama-code-add | Code add | | "c e" | ellama-code-edit | Code edit | | "c i" | ellama-code-improve | Code improve | | "c r" | ellama-code-review | Code review | | "s s" | ellama-summarize | Summarize | | "s w" | ellama-summarize-webpage | Summarize webpage | | "i w" | ellama-improve-wording | Improve wording | | "i g" | ellama-improve-grammar | Improve grammar and spelling | | "i c" | ellama-improve-conciseness | Improve conciseness | | "m l" | ellama-make-list | Make list | | "m t" | ellama-make-table | Make table | | "m f" | ellama-make-format | Make format | | "a a" | ellama-ask-about | Ask about | | "a i" | ellama-ask-interactive | Chat with ellama (Interactive) | | "a l" | ellama-ask-line | Ask about current line | | "a s" | ellama-ask-selection | Ask about selection | | "t t" | ellama-translate | Text translate | | "t c" | ellama-complete | Text complete | | "d w" | ellama-define-word | Define word | | "p s" | ellama-provider-select | Provider select | ## Configuration The following variables can be customized for the Ellama client: - `ellama-buffer`: The default Ellama buffer name. - `ellama-enable-keymap`: Enable the Ellama keymap. - `ellama-keymap-prefix`: The keymap prefix for Ellama. - `ellama-user-nick`: The user nick in logs. - `ellama-assistant-nick`: The assistant nick in logs. - `ellama-buffer-mode`: The major mode for the Ellama logs buffer. Default mode is `markdown-mode`. - `ellama-language`: The language for Ollama translation. Default language is english. - `ellama-provider`: llm provider for ellama. Default provider is `ollama` with [zephyr](https://ollama.ai/library/zephyr) model. There are many supported providers: `ollama`, `open ai`, `vertex`, `GPT4All`. For more information see [llm documentation](https://elpa.gnu.org/packages/llm.html) - `ellama-providers`: association list of model llm providers with name as key. - `ellama-spinner-type`: Spinner type for ellama. Default type is `progress-bar`. - `ellama-ollama-binary`: Path to ollama binary. - `ellama-auto-scroll`: If enabled ellama buffer will scroll automatically during generation. Disabled by default. ## Acknowledgments Thanks [Jeffrey Morgan](https://github.com/jmorganca) for excellent project [ollama](https://github.com/jmorganca/ollama). This project cannot exist without it. Thanks [zweifisch](https://github.com/zweifisch) - I got some ideas from [ollama.el](https://github.com/zweifisch/ollama) what ollama client in Emacs can do. Thanks [Dr. David A. Kunz](https://github.com/David-Kunz) - I got more ideas from [gen.nvim](https://github.com/David-Kunz/gen.nvim). Thanks [Andrew Hyatt](https://github.com/ahyatt) for `llm` library. Without it only `ollama` would be supported. # Contributions If you are interested in creating a provider, please send a pull request, or open a bug. This library is part of GNU ELPA, so any major provider that we include in this module needs to be written by someone with FSF papers. However, you can always write a module and put it on a different package archive, such as MELPA.
DISco's Skiptree implementation release notes S. Martin (2011-2012), funding from Belgian FNRS Ph. Clerinx (2010-2011), funding from EU ResumeNet FP7 The skiptree node is implemted in Python and run with the command: python3 src/__main__.py <local address> <local port> <nameid> <numid> <local address>:<local port> is how other systems will contact your skiptree node. Make sure your local firewall allows TCP connections to be established towards this endpoint. Each node on the skiptree is identified with a NameID (any readable string). This should either be picked randomly or adjusted so that it will be able to assist an overloaded node. Additionally, nodes should receive a random 'numerical ID' that is used during the join process to define the favourite neighbours of the new node at the "skipnet" (L1-overlay) level. The above command starts the node in "interactive" mode, where you will use program's standard input to pick actions in a menu: 0. Display local node information. 1. Add data to the local node 2. Send a join message (SkipTree). 3. Send a leave message. 4. Send data to the skiptree. 5. check data on the skiptree. 6. Dump data store 7. Display Current Status 8. Debug ----- Running a SEED node ----------------------------------------- Nodes can only join the skiptree if there is some data to share. This is due to the fact that new overlay "coordinates" involve the selection of equations (CPE) to split the existing dataset equally between the new nodes. If A has already some data and B has none, then B should join A, and not the other way. The tool csv2py.pl allows you to fill a node with data locally and make it a suitable "seed" for other nodes to build a network. This tool produces essentially records such as <key> SpacePart([Component(Dimension.get('Iproto'),'06'), Component(Dimension.get('Isrc'),'7d59d8fa'), Component(Dimension.get('Idst'),'00001011'), Component(Dimension.get('Tsrc'),'0bcf'), Component(Dimension.get('Tdst'),'1f40'), Component(Dimension.get('Tflags'),'02'),]) ['1',%s]</key> out of a CSV file that provides a split view of network traffic (pcap) capture: <key>45000030,05ea,4000,6f,06,7d59d8fa,00001011,TCP,0bcf,1f40,b67e3248,00000000,70,02,ffff,00000204055001010402</key> The skiptree implementation can actually tolerate any number of 'dimensions', with freely assigned names, as long as the data can be sorted with lexicographical ordering. You may need to hack csv2py script to accommodate your needs, though. csv2py.pl also generate additional control character so that it can feed the skiptree menu directly (i.e. typing "1" for "add data to the local node"). Typical use will be perl csv2py.pl <.csv.gz file> <istep> <uid0> <uidN> | <main.py invocation> 'uid' adds a 'pure data' (non-key) part to each record in the form of a serial number ranging from <uid0> to <uidN>. After the requested (<uidN>-<uid0>)/<istep> records have been converted from the gz file to skiptree menu commands, csv2py.pl will forward transparently its own STDIN to STDOUT, allowing user to take control of the initialized node. EXAMPLE: <key> perl csv2py.pl example.csv.gz 1 0 6000 | python3 src/__main__.py localhost 8080 seeed 42 </key> will launch a node on 127.0.0.1:8080 and feed it with the 6000 first entries of the example.csv.gz file. You can then launch a second instance, e.g. with <key> python3 src/__main__.py localhost 8082 tesst 64 </key> and instruct it to connect to the first one by typing the following instructions: NameID: tesst NumericID: 64 (100) <key> Which action do you want to do ? 0. Display local node information. 1. Add data to the local node 2. Send a join message (SkipTree). 3. Send a leave message. 4. Send data to the skiptree. 5. check data on the skiptree. 6. Dump data store 7. Display Current Status 8. Debug <b>2</b> Enter the bootstrap contact information Port (2000): <b>8080</b> Host (127.0.0.1): <b>localhost</b> </key> If successful, you'll see "#_# CONNECTED" as the last line of your "tesst" node. You can cross-check the success by asking each node to show their characteristic equations (<key>0</key> then <key>1</key> from the main menu) You should then see something like <equation.CPE object at 0x97128ac> (node 00001388 (Idst) (Idst) >)</equation> If the node failed to connect, then you'll simply have <equation.CPE object at 0x97128ac></equation> ---- Running the MASTER CONTROL PROGRAM ----------------------------
<?php namespace App\Http\Controllers; use App\Mail\AppointmentMail; use App\Models\Appointment; use App\Models\Service; use App\Models\User; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Validator; class AppointmentController extends Controller { /** * Display a listing of the resource. */ public function index() { $user = Auth::user(); if (!$user) { return redirect()->route('login.create'); } $user_id = $user->id; $appointments = Appointment::where('user_id', $user_id)->get(); return view('appointment.index', compact('appointments')); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $data = $request->only(['service_id', 'date_begin', 'date_end', 'firstname', 'lastname', 'email', 'tel', 'company']); $validator = Validator::make($data, [ 'service_id' => 'required|string|max:255', 'date_begin' => 'required|date|max:255', 'date_end' => 'required|date|max:255', 'firstname' => 'required|string|max:255', 'lastname' => 'required|string|max:255', 'email' => 'required|string|max:255', 'tel' => 'required|string|max:255', 'company' => 'nullable|string|max:255', ]); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } $user = User::find($data['service_id']); if (!$user) { return redirect()->back()->with('error', 'Utilisateur non trouvé.'); } $filteredServices = Service::where('user_id', $user->id)->get(); if (!$filteredServices) { return redirect()->back()->with('error', 'Service non trouvé.'); } $serviceUser = $filteredServices[0]; try { Appointment::create([ 'service_id' => $serviceUser->id, 'date_begin' => $data['date_begin'], 'date_end' => $data['date_end'], 'firstname' => $data['firstname'], 'lastname' => $data['lastname'], 'email' => $data['email'], 'tel' => $data['tel'], 'company' => $data['company'], 'user_id' => $user->id, ]); $informations = array_merge( $request->except('_token'), ['service_name' => $serviceUser->name] ); Mail::to($data['email'])->send( new AppointmentMail($informations)); return redirect()->back()->with('success', 'Données enregistrées avec succès!'); } catch (\Exception $e) { return redirect()->back()->with('error', 'Erreur lors de la création de l\'appointment: '); } return redirect()->back()->with('success', 'Données enregistrées avec succès!'); } /** * Show the form for creating a new resource. */ public function create() { $users = User::all(); return view('appointment.create', compact('users')); } /** * Display the specified resource. */ public function show(Appointment $appointment) { $user_id = $appointment->user_id; if (!$user_id) { return redirect()->back()->with('error', 'Utilisateur non trouvé.'); } $filteredServices = Service::where('user_id', $user_id)->get(); if (!$filteredServices) { return redirect()->back()->with('error', 'Service non trouvé.'); } $service = $filteredServices[0]; return view('appointment.show', compact('appointment', 'service')); } /** * Show the form for editing the specified resource. */ public function edit(Appointment $appointment) { // Vérifier si l'appointment existe if (!$appointment) { return redirect()->back()->with('error', 'Appointment non trouvé.'); } $user_id = $appointment->user_id; if (!$user_id) { return redirect()->back()->with('error', 'Utilisateur non trouvé.'); } $filteredServices = Service::where('user_id', $user_id)->get(); if (!$filteredServices) { return redirect()->back()->with('error', 'Service non trouvé.'); } $serviceUserId = $filteredServices[0]->id; // Passer les données à la vue d'édition return view('appointment.edit', [ 'appointment' => $appointment, 'services' => $filteredServices, ]); } /** * Update the specified resource in storage. */ public function update(Request $request, Appointment $appointment) { $data = $request->only(['service_id', 'date_begin', 'date_end', 'firstname', 'lastname', 'email', 'tel', 'company']); $validator = Validator::make($data, [ 'service_id' => 'required|string|max:255', 'date_begin' => 'required|date|max:255', 'date_end' => 'required|date|max:255', 'firstname' => 'required|string|max:255', 'lastname' => 'required|string|max:255', 'email' => 'required|string|max:255', 'tel' => 'required|string|max:255', 'company' => 'nullable|string|max:255', ]); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } try { $appointment->update([ 'service_id' => $data['service_id'], 'date_begin' => $data['date_begin'], 'date_end' => $data['date_end'], 'firstname' => $data['firstname'], 'lastname' => $data['lastname'], 'email' => $data['email'], 'tel' => $data['tel'], 'company' => $data['company'], ]); // TODO: Ajoutez ici d'autres actions nécessaires après la mise à jour, par exemple, l'envoi d'un email. return redirect()->back()->with('success', 'Rendez-vous mis à jour avec succès!'); } catch (\Exception $e) { return redirect()->back()->with('error', 'Erreur lors de la mise à jour du rendez-vous: ' . $e->getMessage()); } } /** * Remove the specified resource from storage. */ public function destroy(Appointment $appointment) { $appointment->delete(); return redirect()->route('appointment.index') ->with('success', 'appointment supprimé avec succès'); } }
from src.__init__ import * session_state = Session() session_objects = [Session() for _ in range(4)] base_session_data = { "user_email": "[email protected]", "password": "password123", } session_objects[0].reset(base_session_data) def sign_in_grammar(): return Sequence({ 'endpoint': Uint8(0), "email": String(session_state.get('user_email')), "password": String(session_state.get('password')), }) sign_in_response_grammar = Sequence({ "token": Blob(num_bits=256), }) def sign_in_check(parsing_results, fuzziness): if len(parsing_results) != 1 or len(parsing_results[0].stream) != 0: if fuzziness == Fuzziness.correct: print('we should log this event for sure') return False, None path = "token" session_data = {path: parsing_results[0].data_model.get_value(path)} # TODO: implement feature vector creation and fancy logging of results... return True, session_data get_handle_grammar = Sequence({ 'endpoint': Uint8(1), "token": Blob(session_state.get('token')), "file_path": String('/mnt/a/b/c/file') }) get_handle_response_grammar = Sequence({ "handle": Blob(num_bits=256), }) def get_handle_check(parsing_results, fuzziness): if len(parsing_results) != 1 or len(parsing_results[0].stream) != 0: if fuzziness == Fuzziness.correct: print('we should log this event for sure') return False, None path = "handle" session_data = {path: parsing_results[0].data_model.get_value(path)} # TODO: implement feature vector creation and fancy logging of results... return True, session_data get_data_grammar = Sequence({ 'endpoint': Uint8(2), 'handle': Blob(session_state('handle')), # hopefully this gets mutated to point somewhere that doesn't make sense or at /etc/shadow :) }) get_data_response_grammar = Sequence({ 'length': Byte(), 'data': DynamicBlob(get_num_bits=lambda this: this.parent.children['length']), }) def get_data_check(parsing_results, fuzziness): return True, base_session_data sign_out_grammar = Sequence({ 'endpoint': Uint8(3), "email": String(session_state.get('user_email')) }) sign_out_response_grammar = Sequence({ "status": Byte(), # TODO: make a sub-class that gives meaning to values }) def sign_out_check(parsing_results, fuzziness): return True, base_session_data send_grammars = [ sign_in_grammar, get_handle_grammar, get_data_grammar, sign_out_grammar, ] response_grammars = [ sign_in_response_grammar, get_handle_response_grammar, get_data_response_grammar, sign_out_response_grammar, ] response_check_functions = [ sign_in_check, get_handle_check, get_data_check, sign_out_check, ] from bitarray.util import ba2int from secrets import randbits class SUT: def __init__(self): self.memory = { 'auth': base_session_data.copy(), 'tokens': [], 'handles': [], } def interact_function(self, input_data): try: endpoint = ba2int(input_data[:8]) input_data = input_data[8:] if endpoint == 0: # sign in user_email = '' while True: char_data = input_data[:8] if char_data != bitarray('0' * 8): char = char_data.tobytes().decode('ascii') user_email += char else: break password = '' while True: char_data = input_data[:8] if char_data != bitarray('0' * 8): char = char_data.tobytes().decode('ascii') password += char else: break if user_email not in self.memory['auth'] or self.memory['auth'][user_email] != password: return bitarray('') token = randbits(256) self.memory['tokens'].append(token) return bitarray(format(token, '0256b')) elif endpoint == 1: # get handle token = ba2int(input_data[:256]) input_data = input_data[256:] if token not in self.memory['tokens']: return bitarray('') file_path = '' while True: char_data = input_data[:8] if char_data != bitarray('0' * 8): char = char_data.tobytes().decode('ascii') file_path += char else: break handle = randbits(256) self.memory['handles'].append((handle, file_path)) return bitarray(format(handle, '0256b')) elif endpoint == 2: # get data handle = ba2int(input_data[:256]) input_data = input_data[256:] if handle not in [x for x, _ in self.memory['tokens']]: return bitarray('') return bitarray(''.join([format(ord(x), '08b') for x in 'This is the data!'])) elif endpoint == 3: # sign out return bitarray('0' * 8) else: return bitarray('') # error except: return bitarray('') # error sut = SUT() fuzzer = Fuzzer(session_objects, send_grammars, response_grammars, response_check_functions, sut.interact_function)
class Hall: def __init__(self, rows, cols, hall_no): self._seats = {} self.show_list = [] self._rows = rows self._cols = cols self._hall_no = hall_no def entry_show(self, show_id, movie_name, time): show_info = (show_id, movie_name, time) self.show_list.append(show_info) # Allocate seats with rows and cols using nested loops show_seats = [] for i in range(self._rows): row = [] for x in range(self._cols): row.append('free') show_seats.append(row) self._seats[show_id] = show_seats def book_seats(self, show_id, seat_list): if show_id not in self._seats: print(f"Error: Invalid show ID {show_id}") return for seat in seat_list: row, col = seat if row < 0 or row >= self._rows or col < 0 or col >= self._cols: print(f"Error: Invalid seat ({row}, {col}) for show {show_id}") continue if self._seats[show_id][row][col] == 'free': self._seats[show_id][row][col] = 'booked' print(f"Seat ({row}, {col}) booked for show {show_id}") else: print(f"Error: Seat ({row}, {col}) is already booked for show {show_id}") def view_show_list(self): print("Shows Today:") for show in self.show_list: show_id, movie_name, show_datetime = show print(f"Movie: {movie_name} (ID: {show_id}) - Time: {show_datetime}") def view_available_seats(self, show_id): if show_id not in self._seats: # print(f"Error: Invalid show ID {show_id}") return print(f"Available Seats for Show {show_id} (array index Format):") for row in range(self._rows): for col in range(self._cols): if self._seats[show_id][row][col] == 'free': print(f"({row}, {col})", end=' ') print() print() # Move to the next line def display_seats_2d_matrix(self, show_id): if show_id not in self._seats: print(f"Error: Wrong ID {show_id}") return print("Seating Arrangement (2D Matrix Format):") for row in range(self._rows): for col in range(self._cols): if self._seats[show_id][row][col] == 'free': print("O", end=' ') else: print("X", end=' ') print() # Move to the next line class StarCinema: hall_list = [] @classmethod def entry_hall(cls, hall): cls.hall_list.append(hall) # Example Usage hall1 = Hall(rows=10, cols=10, hall_no=1) hall1.entry_show(show_id="111", movie_name="Animal", time="25/10/2023 11:00 AM") hall1.entry_show(show_id="333", movie_name="Dubung", time="25/10/2023 2:00 PM") StarCinema.entry_hall(hall1) while True: print("\n1. VIEW ALL SHOW TODAY\n2. VIEW AVAILABLE SEATS\n3. BOOK TICKET\n4. Exit") option = input("ENTER OPTION: ") if option == '1': hall1.view_show_list() elif option == '2': show_id = input("Enter Show ID: ") hall1.display_seats_2d_matrix(show_id) hall1.view_available_seats(show_id) elif option == '3': show_id = input("Enter Show ID: ") show_ids = [show[0] for show in hall1.show_list] if show_id in show_ids: num_tickets = int(input("Number of Tickets?: ")) seat_list = [] for _ in range(num_tickets): row = int(input("Enter Seat Row: ")) col = int(input("Enter Seat Col: ")) seat_list.append((row, col)) hall1.book_seats(show_id, seat_list) else: print(f"Error: Invalid show ID {show_id}") elif option == '4': break else: print("Invalid option. Please choose again.")
import { useReducer } from 'react'; import { TodoContext } from './TodoContext'; import { TodoStateI } from '../interfaces/interfaces'; import { todoReducer } from './todoReducer'; // recibe los hijos que serán renderizados adentro // Permitimos 1 o varios "|" de esta manera el <TodoProvider> de <Todo /> no se quejará al tener varios elementos "h1 + ul" interface TodoProviderProps { children: JSX.Element | JSX.Element[]; } // si aplicamos la interface no tenemos el contenido, podemos posicionarnos sobre INITIAL_STATE CTRL + . y podemos autocompletarlas. const INITIAL_STATE: TodoStateI = { todoCount: 2, todos: [ { id: '1', desc:'Recolectar las piedras', completed: false }, { id: '2', desc:'Piedra del alma', completed: false } ], completed: 0, pending: 2 } export const TodoProvider = ({children} : TodoProviderProps) => { const [state, dispatch] = useReducer(todoReducer, INITIAL_STATE); const toggleTodo = (id: string) => { dispatch({ type: 'toggleTodo', payload:{id: id}}) } return ( <TodoContext.Provider value={{state, toggleTodo}}> {children} </TodoContext.Provider> ) }
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import helmet from 'helmet'; import * as compression from 'compression'; import * as responseTime from 'response-time'; import { ValidationPipe, VersioningType } from '@nestjs/common'; import { PackageService } from './common/package/package.service'; import { Logger } from 'nestjs-pino'; async function bootstrap() { const app = await NestFactory.create(AppModule, { cors: true, bufferLogs: true }); app.useLogger(app.get(Logger)); const packageService = app.get(PackageService); //app.setGlobalPrefix(process.env.API_PREFIX); const options = new DocumentBuilder() .setTitle('TabT Rest') .setDescription(`This api is a bridge to the TabT SOAP API. It contacts TabT and cache results in order to reduce latency for some requests. More documentation will come.<br> The data present in the api such as player names, club names, tournaments or match results are not managed by us. This information is made freely available by the Aile Francophone de Tennis de Table and the Vlaamse Tafeltennisliga. We therefore cannot be held responsible for the publication of this information. If changes need to be made, you should contact the responsible entity. If you build an application on top of the BePing's api, be sure to do at least one of the following things: <ul><li>If possible, set a X-Application-For header string. Include the name of your application, and a way to contact you in case something would go wrong.<br> An example user agent string format is, which could result in the following string: beping/2.0.0 (floca.be; [email protected]). The use of a header like this isn’t obligated or enforced, but allows for better communication.</li></ul> `) .setContact('Florent Cardoen', 'http://floca.be/', '[email protected]') .setVersion(packageService.version) .setLicense('GNU General Public License v3.0', 'https://github.com/Fllorent0D/TabT-Rest/blob/main/LICENSE') .addTag('Seasons') .addTag('Clubs') .addTag('Members') .addTag('Matches') .addTag('Divisions') .addTag('Tournaments') .addServer('http://localhost:3004', 'development') .addServer('https://api.beping.be', 'production') .build(); app.enableVersioning({ type: VersioningType.URI, }); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('doc', app, document); app.use(compression()); app.use(helmet()); app.use(responseTime()); app.useGlobalPipes(new ValidationPipe()); await app.listen(process.env.PORT); } bootstrap();
import random from django.contrib.auth.models import User from django.db import IntegrityError from ..models import Product, Cart from ..serializers import PasswordSerializer, RegisterSerializer from rest_framework import authentication, permissions, status from django.contrib.auth import authenticate, login from django.http import HttpResponse, JsonResponse from rest_framework.response import Response from django.views import View from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.tokens import RefreshToken class UserController(View): def __init__(self) -> None: # Might be generalised and moved further down the line self.METHOD_MAP = { 'register': self.register, 'populate': self.populate, 'logout': self.logout, 'password': self.password, } def __call__(self, method, request, id=None): # Select the correct method according to the request response = self.METHOD_MAP[method](request=request) return response def populate(self, request): # clearing the DB User.objects.all().delete() Product.objects.all().delete() Cart.objects.all().delete() #populating with no_u and no_p products each # no_u number of users # no_p number of products total_no_u = 6 no_u_with_p = 3 no_p = 10 try: description_list = ['Big and round', 'Great for all ages!', 'Amazing shape', 'Lightly used', 'The color has slightly faded', 'A great addition to your arsenal'] product_list = ['White toyota', 'Flower vase', 'Coffee machine', 'Head of lettuce', 'Mountain bike', 'Jeans', 'Cardigan', 'Sheet of paper', 'Map', 'Book about monsters', 'Apple'] for n in range(total_no_u): user = User.objects.create_user("testuser{}".format(n), "testuser{}@shop.aa".format(n), "pass{}".format(n)) user.save() instance_copy = product_list.copy() if(n >= no_u_with_p): for i in range(no_p): random_product = random.choice(instance_copy) random_product_description = "A sample description of {}. {}.".format(random_product, random.choice(description_list)) price = random.randint(1,150) item = Product(name=random_product, description=random_product_description, owner=user, price=price) item.save() instance_copy.remove(random_product) message = "populated with {} users and gave {} users {} products each".format(total_no_u, no_u_with_p, no_p) # Re-create a super user as well User.objects.create_superuser(username='admin', email='[email protected]', password='masterkey') except Exception as e: message = "Populate failed: " + str(e) return JsonResponse({"message": message}) def register(self, request, format=None): serializer = RegisterSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=400) try: user = User.objects.create_user( username=serializer.data["username"], email=serializer.data["email"], password=serializer.data["password"], ) except IntegrityError: return Response(f"same user name", status=400) if user is not None: return Response(f"new user is: {user.get_username()}") return Response("no new user") def logout(self, request): try: refresh_token = request.data["refresh_token"] token = RefreshToken(refresh_token) token.blacklist() return Response(status=status.HTTP_200_OK) except Exception as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST) def password(self, request): serializer = PasswordSerializer(data=request.data) serializer.is_valid() new_password = request.data['newPassword'] try: user = User.objects.get(username=serializer.data['username']) correct = user.check_password(serializer.data['password']) if(correct): user.set_password(new_password) user.save() return Response(status=status.HTTP_200_OK) return Response('Incorrect password given!',status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST)
import {createAsyncThunk} from '@reduxjs/toolkit'; import { ADD_EXPENSE, CANCEL_EDIT_DATA_EXPENSE, EDIT_EXPENSE, FETCH_EXPENSES, REMOVE_EXPENSE, SET_EDIT_DATA_EXPENSE, } from '../const/expenseConst'; import {typeExpense} from './../../../component/const'; interface Expense { id: string; description: string; amount: number; type: typeof typeExpense; date: string; } export const fetchExpenses = createAsyncThunk<Expense[]>( FETCH_EXPENSES, async () => { return []; }, ); export const addExpense = createAsyncThunk<Expense, Omit<Expense, 'id'>>( ADD_EXPENSE, async expense => { const newExpense = {...expense, id: String(Date.now())}; return newExpense; }, ); export const editExpense = createAsyncThunk<Expense, Expense>( EDIT_EXPENSE, async expense => { return expense; }, ); export const setEditDataExpense = createAsyncThunk<Expense, Expense>( SET_EDIT_DATA_EXPENSE, async expense => { return expense; }, ); export const cancelEditDataExpense = createAsyncThunk<null, null>( CANCEL_EDIT_DATA_EXPENSE, async expense => { return expense; }, ); export const removeExpense = createAsyncThunk<void, string>( REMOVE_EXPENSE, async expenseId => { return; }, );
$(document).ready(function () { $('#cancelarRcliente').click(function (e) { // Evita que el navegador se redireccione automáticamente e.preventDefault(e); location.href = url_base; }); // Example starter JavaScript for disabling form submissions if there are invalid fields (function () { 'use strict' // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.querySelectorAll('.needs-validation') // Loop over them and prevent submission Array.prototype.slice.call(forms) .forEach(function (form) { form.addEventListener('submit', function (event) { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } form.classList.add('was-validated') }, false) }) })() // Evita el evento submit default $("#frm-registroCliente").submit(function (event) { event.preventDefault(); // Valida las contraseñas var passwd = $("#password").val(); var confirmPasswd = $("#confirmPasswd").val(); if (passwd !== confirmPasswd) { // Muestra un error de validación $('.needs-validation').removeClass('was-validated') $("#password").addClass("is-invalid"); $("#confirmPasswd").addClass("is-invalid"); $("#feedback-confirmPasswd").html("Las contraseñas no coinciden"); $("#feedback-password").html("Las contraseñas no coinciden"); return false; } else { $("#password").removeClass("is-invalid"); $("#confirmPasswd").removeClass("is-invalid"); var nombre = $('#nombre').val(); var dni = $('#dni').val(); var email = $('#email').val(); var persona = { nombre: nombre, dni: dni, email: email, password: passwd }; $.ajax({ type: "POST", url: url_base + "cliente/register", data: { "cliente": persona }, success: function (data) { if (data === 'false') { console.log('falso'); data = "el correo del cliente ya esta registrado"; alertify.success(data); } if (data === '1') { //TODO: falta arreglar que muestre los mensajes y redirection console.log(data); alertify.success('Los datos se Guardaron exitosamente'); Location.href = url_base; } }, error: function (data) { alertify.error(data); }, }); } }); // ########################################### cuenta del cliente ####################################### // funciones para que cuando se modifiquen o presionen una tecla en los campos se habiliten los botones $('#nombre').on('keyup', function (event) { $('#submitDatos').prop("disabled", false); $('#submitDatos').removeClass('btn-disabled'); $('#submitDatos').addClass('btn-success'); $('#cancelarUcliente').prop("disabled", false); $('#cancelarUcliente').removeClass('btn-disabled'); $('#cancelarUcliente').addClass('btn-danger'); }); $('#email').on('keyup', function (event) { $('#submitDatos').prop("disabled", false); $('#submitDatos').removeClass('btn-disabled'); $('#submitDatos').addClass('btn-success'); $('#cancelarUcliente').prop("disabled", false); $('#cancelarUcliente').removeClass('btn-disabled'); $('#cancelarUcliente').addClass('btn-danger'); }); // codigo para cancelar la actualizacion de datos CLiente $('#cancelarUcliente').click(function (e) { // Evita que el navegador se redireccione automáticamente e.preventDefault(e); location.href = url_base + "/cliente/perfil/" + cliente; }); // habilita los campos para editarlos luego de de que se carga el documento $('#nombre').prop("disabled", false); $('#email').prop("disabled", false); // ########## Capturamos el evento submit del formulario updateCliente ################# $('#frm-updateCliente').on('submit', function (event) { // Evitamos que el formulario se envíe por defecto event.preventDefault(); // Obtenemos los datos del formulario var datos = $(this).serialize(); // Hacemos la petición Ajax $.ajax({ type: 'POST', url: url_base + "cliente/updateDatos", data: datos, success: function (respuesta) { $('#submitDatos').prop("disabled", true); $('#submitDatos').removeClass('btn-success'); $('#submitDatos').addClass('btn-disabled'); $('#cancelarUcliente').prop("disabled", true); $('#cancelarUcliente').removeClass('btn-danger'); $('#cancelarUcliente').addClass('btn-disabled'); // mensaje de éxito alertify.success(respuesta); }, error: function (respuesta) { // Mensaje de error alertify.error(respuesta); } }); }); // ############################# updatePassword ################################## $('#password').on('keyup', function (event) { $('#submitPassword').prop("disabled", false); $('#submitPassword').removeClass('btn-disabled'); $('#submitPassword').addClass('btn-success'); $('#cancelarUpasswrod').prop("disabled", false); $('#cancelarUpasswrod').removeClass('btn-disabled'); $('#cancelarUpasswrod').addClass('btn-danger'); }); $('#confirmPasswd').on('keyup', function (event) { $('#submitPassword').prop("disabled", false); $('#submitPassword').removeClass('btn-disabled'); $('#submitPassword').addClass('btn-success'); $('#cancelarUpasswrod').prop("disabled", false); $('#cancelarUpasswrod').removeClass('btn-disabled'); $('#cancelarUpasswrod').addClass('btn-danger'); }); // codigo para cancelar la actualizacion de clave CLiente $('#cancelarUpasswrod').click(function (e) { // Evita que el navegador se redireccione automáticamente e.preventDefault(e); location.href = url_base + "/cliente/perfil/" + cliente; }); $('#frm-updatePassword').on('submit', function (event) { // Evitamos que el formulario se envíe por defecto event.preventDefault(); // Valida las contraseñas var passwd = $("#password").val(); var confirmPasswd = $("#confirmPasswd").val(); if (passwd !== confirmPasswd) { // Muestra un error de validación $('.needs-validation').removeClass('was-validated') $("#password").addClass("is-invalid"); $("#confirmPasswd").addClass("is-invalid"); $("#feedback-confirmPasswd").html("Las contraseñas no coinciden"); $("#feedback-password").html("Las contraseñas no coinciden"); return false; } else { $("#password").removeClass("is-invalid"); $("#confirmPasswd").removeClass("is-invalid"); // Obtenemos los datos del formulario var datos = $(this).serialize(); }; // Hacemos la petición Ajax $.ajax({ type: 'POST', url: url_base + "cliente/updatePassword", data: datos, success: function (respuesta) { $('#submitPassword').prop("disabled", true); $('#submitPassword').removeClass('btn-success'); $('#submitPassword').addClass('btn-disabled'); $('#cancelarUpasswrod').prop("disabled", true); $('#cancelarUpasswrod').removeClass('btn-danger'); $('#cancelarUpasswrod').addClass('btn-disabled'); // mensaje de éxito alertify.success(respuesta); }, error: function (respuesta) { // Mensaje de error alertify.error(respuesta); } }); }); // código para mostrar u ocultar el valor del campo password en el form registrar cliente const togglePassword = document.querySelector('#togglePassword'); const password = document.querySelector('#password'); if (togglePassword !== null) { togglePassword.addEventListener('click', function (e) { // toggle the type attribute const type = password.getAttribute('type') === 'password' ? 'text' : 'password'; password.setAttribute('type', type); // toggle the eye slash icon this.classList.toggle('fa-eye-slash'); }); } // ################################# facturas ############################################ // inicio datatable facturas // new DataTable('#facturas'); let table = new DataTable('#facturas'); // modal pago facturas var pagar = $('.pagar'); pagar.click(function () { var factura = $(this).data('id'); var monto = $(this).data('total'); $('#id_factura').val(factura); $('#totalFactura').val(monto); }); // Al cambiar el valor del select, mostrar el input $(document).on('change', '#tipo_pago', function () { // Obtener el valor del select const tipo_pago = $(this).val(); // Si el tipo de pago es efectivo, mostrar el input if (tipo_pago === '1') { $('#referencia-group').hide(); } else { $('#referencia-group').show(); } }); $('#frm-registrarPago').on('submit', function (e) { e.preventDefault(); // Obtenemos los datos del formulario var datos = $(this).serialize(); // Hacemos la petición Ajax $.ajax({ type: 'POST', url: url_base + "cliente/registrarPago", data: datos, success: function (r) { // mensaje de éxito alertify.success(r); location.href = url_base + "/cliente/facturas/" + cliente; }, error: function (r) { // Mensaje de error alertify.error(r); } }); }); // fin del document ready });
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Multianswer question definition class. * * @package qtype * @subpackage multianswer * @copyright 2010 Pierre Pichet * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once($CFG->dirroot . '/question/type/questionbase.php'); require_once($CFG->dirroot . '/question/type/shortanswer/question.php'); require_once($CFG->dirroot . '/question/type/numerical/question.php'); require_once($CFG->dirroot . '/question/type/multichoice/question.php'); /** * Represents a multianswer question. * * A multi-answer question is made of of several subquestions of various types. * You can think of it as an application of the composite pattern to qusetion * types. * * @copyright 2010 Pierre Pichet * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class qtype_multianswer_question extends question_graded_automatically_with_countback { /** @var array of question_graded_automatically. */ public $subquestions = array(); /** * @var array place number => insex in the $subquestions array. Places are * numbered from 1. */ public $places; /** * @var array of strings, one longer than $places, which is achieved by * indexing from 0. The bits of question text that go between the subquestions. */ public $textfragments; /** * Get a question_attempt_step_subquestion_adapter * @param question_attempt_step $step the step to adapt. * @param int $i the subquestion index. * @return question_attempt_step_subquestion_adapter. */ protected function get_substep($step, $i) { return new question_attempt_step_subquestion_adapter($step, 'sub' . $i . '_'); } public function start_attempt(question_attempt_step $step, $variant) { foreach ($this->subquestions as $i => $subq) { $subq->start_attempt($this->get_substep($step, $i), $variant); } } public function apply_attempt_state(question_attempt_step $step) { foreach ($this->subquestions as $i => $subq) { $subq->apply_attempt_state($this->get_substep($step, $i)); } } public function get_question_summary() { $summary = $this->html_to_text($this->questiontext, $this->questiontextformat); foreach ($this->subquestions as $i => $subq) { switch ($subq->qtype->name()) { case 'multichoice': $choices = array(); $dummyqa = new question_attempt($subq, $this->contextid); foreach ($subq->get_order($dummyqa) as $ansid) { $choices[] = $this->html_to_text($subq->answers[$ansid]->answer, $subq->answers[$ansid]->answerformat); } $answerbit = '{' . implode('; ', $choices) . '}'; break; case 'numerical': case 'shortanswer': $answerbit = '_____'; break; default: $answerbit = '{ERR unknown sub-question type}'; } $summary = str_replace('{#' . $i . '}', $answerbit, $summary); } return $summary; } public function get_min_fraction() { $fractionsum = 0; $fractionmax = 0; foreach ($this->subquestions as $i => $subq) { $fractionmax += $subq->defaultmark; $fractionsum += $subq->defaultmark * $subq->get_min_fraction(); } return $fractionsum / $fractionmax; } public function get_max_fraction() { $fractionsum = 0; $fractionmax = 0; foreach ($this->subquestions as $i => $subq) { $fractionmax += $subq->defaultmark; $fractionsum += $subq->defaultmark * $subq->get_max_fraction(); } return $fractionsum / $fractionmax; } public function get_expected_data() { $expected = array(); foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); foreach ($subq->get_expected_data() as $name => $type) { if ($subq->qtype->name() == 'multichoice' && $subq->layout == qtype_multichoice_base::LAYOUT_DROPDOWN) { // Hack or MC inline does not work. $expected[$substep->add_prefix($name)] = PARAM_RAW; } else { $expected[$substep->add_prefix($name)] = $type; } } } return $expected; } public function get_correct_response() { $right = array(); foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); foreach ($subq->get_correct_response() as $name => $type) { $right[$substep->add_prefix($name)] = $type; } } return $right; } public function prepare_simulated_post_data($simulatedresponse) { $postdata = array(); foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); foreach ($subq->prepare_simulated_post_data($simulatedresponse[$i]) as $name => $value) { $postdata[$substep->add_prefix($name)] = $value; } } return $postdata; } public function get_student_response_values_for_simulation($postdata) { $simulatedresponse = array(); foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); $subqpostdata = $substep->filter_array($postdata); $subqsimulatedresponse = $subq->get_student_response_values_for_simulation($subqpostdata); foreach ($subqsimulatedresponse as $subresponsekey => $responsevalue) { $simulatedresponse[$i.'.'.$subresponsekey] = $responsevalue; } } ksort($simulatedresponse); return $simulatedresponse; } public function is_complete_response(array $response) { foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); if (!$subq->is_complete_response($substep->filter_array($response))) { return false; } } return true; } public function is_gradable_response(array $response) { foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); if ($subq->is_gradable_response($substep->filter_array($response))) { return true; } } return false; } public function is_same_response(array $prevresponse, array $newresponse) { foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); if (!$subq->is_same_response($substep->filter_array($prevresponse), $substep->filter_array($newresponse))) { return false; } } return true; } public function get_validation_error(array $response) { if ($this->is_complete_response($response)) { return ''; } return get_string('pleaseananswerallparts', 'qtype_multianswer'); } /** * Used by grade_response to combine the states of the subquestions. * The combined state is accumulates in $overallstate. That will be right * if all the separate states are right; and wrong if all the separate states * are wrong, otherwise, it will be partially right. * @param question_state $overallstate the result so far. * @param question_state $newstate the new state to add to the combination. * @return question_state the new combined state. */ protected function combine_states($overallstate, $newstate) { if (is_null($overallstate)) { return $newstate; } else if ($overallstate == question_state::$gaveup && $newstate == question_state::$gaveup) { return question_state::$gaveup; } else if ($overallstate == question_state::$gaveup && $newstate == question_state::$gradedwrong) { return question_state::$gradedwrong; } else if ($overallstate == question_state::$gradedwrong && $newstate == question_state::$gaveup) { return question_state::$gradedwrong; } else if ($overallstate == question_state::$gradedwrong && $newstate == question_state::$gradedwrong) { return question_state::$gradedwrong; } else if ($overallstate == question_state::$gradedright && $newstate == question_state::$gradedright) { return question_state::$gradedright; } else { return question_state::$gradedpartial; } } public function grade_response(array $response) { $overallstate = null; $fractionsum = 0; $fractionmax = 0; foreach ($this->subquestions as $i => $subq) { $fractionmax += $subq->defaultmark; $substep = $this->get_substep(null, $i); $subresp = $substep->filter_array($response); if (!$subq->is_gradable_response($subresp)) { $overallstate = $this->combine_states($overallstate, question_state::$gaveup); } else { list($subfraction, $newstate) = $subq->grade_response($subresp); $fractionsum += $subfraction * $subq->defaultmark; $overallstate = $this->combine_states($overallstate, $newstate); } } return array($fractionsum / $fractionmax, $overallstate); } public function clear_wrong_from_response(array $response) { foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); $subresp = $substep->filter_array($response); list($subfraction, $newstate) = $subq->grade_response($subresp); if ($newstate != question_state::$gradedright) { foreach ($subresp as $ind => $resp) { if ($subq->qtype == 'multichoice' && ($subq->layout == qtype_multichoice_base::LAYOUT_VERTICAL || $subq->layout == qtype_multichoice_base::LAYOUT_HORIZONTAL)) { $response[$substep->add_prefix($ind)] = '-1'; } else { $response[$substep->add_prefix($ind)] = ''; } } } } return $response; } public function get_num_parts_right(array $response) { $numright = 0; foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); $subresp = $substep->filter_array($response); list($subfraction, $newstate) = $subq->grade_response($subresp); if ($newstate == question_state::$gradedright) { $numright += 1; } } return array($numright, count($this->subquestions)); } public function compute_final_grade($responses, $totaltries) { $fractionsum = 0; $fractionmax = 0; foreach ($this->subquestions as $i => $subq) { $fractionmax += $subq->defaultmark; $lastresponse = array(); $lastchange = 0; $subfraction = 0; foreach ($responses as $responseindex => $response) { $substep = $this->get_substep(null, $i); $subresp = $substep->filter_array($response); if ($subq->is_same_response($lastresponse, $subresp)) { continue; } $lastresponse = $subresp; $lastchange = $responseindex; list($subfraction, $newstate) = $subq->grade_response($subresp); } $fractionsum += $subq->defaultmark * max(0, $subfraction - $lastchange * $this->penalty); } return $fractionsum / $fractionmax; } public function summarise_response(array $response) { $summary = array(); foreach ($this->subquestions as $i => $subq) { $substep = $this->get_substep(null, $i); $a = new stdClass(); $a->i = $i; $a->response = $subq->summarise_response($substep->filter_array($response)); $summary[] = get_string('subqresponse', 'qtype_multianswer', $a); } return implode('; ', $summary); } public function check_file_access($qa, $options, $component, $filearea, $args, $forcedownload) { if ($component == 'question' && $filearea == 'answer') { return true; } else if ($component == 'question' && $filearea == 'answerfeedback') { // Full logic to control which feedbacks a student can see is too complex. // Just allow access to all images. There is a theoretical chance the // students could see files they are not meant to see by guessing URLs, // but it is remote. return $options->feedback; } else if ($component == 'question' && $filearea == 'hint') { return $this->check_hint_file_access($qa, $options, $args); } else { return parent::check_file_access($qa, $options, $component, $filearea, $args, $forcedownload); } } /** * Return the question settings that define this question as structured data. * * @param question_attempt $qa the current attempt for which we are exporting the settings. * @param question_display_options $options the question display options which say which aspects of the question * should be visible. * @return mixed structure representing the question settings. In web services, this will be JSON-encoded. */ public function get_question_definition_for_external_rendering(question_attempt $qa, question_display_options $options) { // Empty implementation for now in order to avoid debugging in core questions (generated in the parent class), // ideally, we should return as much as settings as possible (depending on the state and display options). return null; } }
"use strict"; function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } var videoContainer = document.getElementById("videoContainer"); var commentForm = document.getElementById("commentForm"); var commentDeleteBtn = document.querySelectorAll("#commentDeleteBtn"); var commentCount = document.getElementById("commentCount"); var addComment = function addComment(text, id, avatar, name) { var commentList = document.querySelector(".video__comments ul"); var newComment = document.createElement("li"); newComment.className = "video__comment"; newComment.dataset.id = id; var avatarDiv = document.createElement("div"); avatarDiv.className = "video__comment-avatar"; if (!avatar) { var avatarBase = document.createElement("div"); var firstLetter = document.createElement("span"); firstLetter.innerText = name[0]; avatarBase.appendChild(firstLetter); avatarBase.className = "avatar-base avatar--small"; avatarDiv.appendChild(avatarBase); } else { var avatarImg = document.createElement("img"); avatarImg.src = "/".concat(avatar); avatarImg.className = "avatar--small"; avatarDiv.appendChild(avatarImg); } var contentDiv = document.createElement("div"); contentDiv.className = "video__comment-content"; var commentOwner = document.createElement("span"); commentOwner.className = "video__comment-owner"; commentOwner.innerText = name; var commentText = document.createElement("span"); commentText.className = "video__comment-text"; commentText.innerText = text; contentDiv.appendChild(commentOwner); contentDiv.appendChild(commentText); var commentDelete = document.createElement("div"); commentDelete.className = "video__comment-delete"; var commentDeleteIcon = document.createElement("span"); commentDeleteIcon.innerText = "❌"; commentDeleteIcon.id = "commentDeleteBtn"; commentDelete.appendChild(commentDeleteIcon); newComment.appendChild(avatarDiv); newComment.appendChild(contentDiv); newComment.appendChild(commentDelete); commentList.prepend(newComment); }; var handleCommentSubmit = /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(event) { var textArea, text, videoId, response, _yield$response$json, newCommentId, avatar, name, count; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: event.preventDefault(); textArea = commentForm.querySelector("textarea"); text = textArea.value; videoId = videoContainer.dataset.id; if (!(text === "")) { _context.next = 6; break; } return _context.abrupt("return"); case 6: _context.next = 8; return fetch("/api/videos/".concat(videoId, "/comment"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: text }) }); case 8: response = _context.sent; if (!(response.status === 201)) { _context.next = 20; break; } textArea.value = ""; _context.next = 13; return response.json(); case 13: _yield$response$json = _context.sent; newCommentId = _yield$response$json.newCommentId; avatar = _yield$response$json.avatar; name = _yield$response$json.name; addComment(text, newCommentId, avatar, name); count = parseInt(commentCount.textContent.split(" ")[0]); if (count === 0) { commentCount.innerText = "1 Comment"; } else { count = count + 1; commentCount.innerText = "".concat(count, " Comments"); } case 20: case "end": return _context.stop(); } } }, _callee); })); return function handleCommentSubmit(_x) { return _ref.apply(this, arguments); }; }(); var handleCommentDelete = /*#__PURE__*/function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(event) { var commentList, id, response, count; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: commentList = event.srcElement.parentNode.parentNode; id = commentList.dataset.id; _context2.next = 4; return fetch("/api/comments/".concat(id, "/delete"), { method: "DELETE" }); case 4: response = _context2.sent; if (response.status === 200) { commentList.remove(); count = parseInt(commentCount.textContent.split(" ")[0]); if (count === 2) { commentCount.innerText = "1 Comment"; } else { count = count - 1; commentCount.innerText = "".concat(count, " Comments"); } } case 6: case "end": return _context2.stop(); } } }, _callee2); })); return function handleCommentDelete(_x2) { return _ref2.apply(this, arguments); }; }(); if (commentForm) { commentForm.addEventListener("submit", handleCommentSubmit); } if (commentDeleteBtn.length !== 0) { for (var i = 0; i < commentDeleteBtn.length; i++) { commentDeleteBtn[i].addEventListener("click", handleCommentDelete); } }
/* * Copyright (c) 1998-2015 Caucho Technology -- all rights reserved * * This file is part of Baratine(TM)(TM) * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Baratine 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 2 of the License, or * (at your option) any later version. * * Baratine 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Baratine; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.v5.log.impl; import java.util.ArrayList; import java.util.logging.Filter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import com.caucho.v5.config.ConfigException; /** * Environment-specific java.util.logging.Logger configuration. */ public class LoggerConfig { private Logger _logger; private ArrayList<String> _names = new ArrayList<>(); private Level _level = null; private Boolean _useParentHandlers; private Filter _filter; private ArrayList<Handler> _handlerList = new ArrayList<Handler>(); private boolean _isSkipInit; public LoggerConfig() { } public LoggerConfig(boolean isSkipInit) { this(); _isSkipInit = isSkipInit; } /** * Sets the name of the logger to configure. */ //@ConfigRest public void addName(String name) { _names.add(name); } /** * Sets the use-parent-handlers */ public void setUseParentHandlers(boolean useParentHandlers) { _useParentHandlers = new Boolean(useParentHandlers); } /** * Sets the output level. */ //@ConfigArg(0) public void setLevel(Level level) throws ConfigException { _level = level; } void clearLevel() { _level = null; } public void add(Handler handler) { _handlerList.add(handler); } public void add(Filter filter) { _filter = filter; } /** * Initialize the logger */ @PostConstruct public void init() { if (! _isSkipInit) { initImpl(); } } /** * Should be run with system classloader */ public void initImpl() { if (_level == null) { return; } if (_names.size() == 0) { _names.add(""); } for (String name : _names) { _logger = Logger.getLogger(name); if (_level != null) { _logger.setLevel(_level); } if (_useParentHandlers != null) { _logger.setUseParentHandlers(_useParentHandlers.booleanValue()); } for (Handler handler : _handlerList) { _logger.addHandler(handler); } if (_filter != null) { _logger.setFilter(_filter); } } } }
#ifndef __PM_BOB_H__ #define __PM_BOB_H__ /*! \file pm_bob.h * \n * \brief This header file contains enums and API definitions for PMIC BOB * power rail driver. * \n * \n &copy; Copyright 2016-2017 QUALCOMM Technologies Incorporated, All Rights Reserved */ Edit History This section contains comments describing changes made to this file. Notice that changes are listed in reverse chronological order. $Header: //components/rel/boot.xf/2.1/QcomPkg/Include/api/pmic/pm/pm_bob.h#2 $ when who what, where, why -------- --- ---------------------------------------------------------- 10/20/17 czq Add pm_bob_ocp_latched_status_clear() 06/22/17 al Get BOB volt level status 12/22/15 al Created HEADER FILE INCLUDE #include "pm_err_flags.h" #include "pm_resources_and_types.h" #include "com_dtypes.h" TYPE DEFINITIONS /*! * \brief * BOB peripheral index. This enum type contains all bob regulators that you may need. */ enum { PM_BOB_1, PM_BOB_INVALID }; enum { PM_BOB_EXT_PIN_RESERVED = 0, PM_BOB_EXT_PIN_CTRL1 = 1, PM_BOB_EXT_PIN_CTRL2 = 2, PM_BOB_EXT_PIN_CTRL3 = 3, PM_BOB_EXT_PIN_MAX, }; typedef enum { PM_BOB_MODE_PASS, PM_BOB_MODE_PFM, PM_BOB_MODE_AUTO, PM_BOB_MODE_PWM, PM_BOB_MODE_INVALID, }pm_bob_mode_type; API PROTOTYPE /** * Gets the status of the modes of BOB. * * @param[in] pmic_chip Primary PMIC: 0, Secondary PMIC: 1. * * @param[in] peripheral_index LDOperipheral index. Starts from 0 * * @param[out] sw_mode Pointer to the mode of a bob, e.g., * HPM, LPM, BYPASS. See #pm_bob_mode_type. * * @return * SUCCESS or Error -- See #pm_err_flag_type. */ pm_err_flag_type pm_bob_sw_mode_status(uint8 pmic_chip, uint8 peripheral_index, pm_bob_mode_type* mode); /** * Gets the voltage level status for BOB PIN. * * @param[in] pmic_chip Primary PMIC: 0, Secondary PMIC: 1. * * @param[in] peripheral_index peripheral index. Starts from * 0 * * @param[out] volt_level Pointer to the voltage level. * * @return * SUCCESS or Error -- See pm_err_flag_type. */ pm_err_flag_type pm_bob_pin_volt_level_status(uint8 pmic_chip, uint8 peripheral_index, uint8 pin_number, pm_volt_level_type* volt_level); /** * Gets the BOB voltage level status. * * @param[in] pmic_chip Primary PMIC: 0, Secondary PMIC: 1. * * @param[in] peripheral_index peripheral index. Starts from 0 * * * @param[out] volt_level Pointer to the voltage level. * * @return * SUCCESS or Error -- See pm_err_flag_type. */ pm_err_flag_type pm_bob_volt_level_status(uint8 pmic_chip, uint8 peripheral_index, pm_volt_level_type *volt_level); /** Configures to clear VREG_OCP status of the BOB . @param[in] pmic_chip Primary PMIC: 0, Secondary PMIC: 1. @param[in] peripheral_index BOB peripheral index. Starts at 0 (for the first BOB peripheral). See @xnameref{hdr:ldoPeripheralIndex}. @param[in] *ocp_occured 1=OCP status bit was set 0=OCP status bit was NOT set @return Error flag type -- See #pm_err_flag_type. */ pm_err_flag_type pm_bob_ocp_latched_status_clear(uint8 pmic_chip, uint8 peripheral_index, boolean *ocp_occured); #endif /* __PM_BOB_H__ */
import React, { Component } from 'react' import ExcCZService from '../services/ExcCZService' class ListExcCZComponent extends Component { constructor(props) { super(props) this.state = { excCZs: [] } this.addExcCZ = this.addExcCZ.bind(this); this.editExcCZ = this.editExcCZ.bind(this); this.deleteExcCZ = this.deleteExcCZ.bind(this); } deleteExcCZ(id){ ExcCZService.deleteExcCZ(id).then( res => { this.setState({excCZs: this.state.excCZs.filter(excCZ => excCZ.excCZId !== id)}); }); } viewExcCZ(id){ this.props.history.push(`/view-excCZ/${id}`); } editExcCZ(id){ this.props.history.push(`/add-excCZ/${id}`); } componentDidMount(){ ExcCZService.getExcCZs().then((res) => { this.setState({ excCZs: res.data}); }); } addExcCZ(){ this.props.history.push('/add-excCZ/_add'); } render() { return ( <div> <h2 className="text-center">ExcCZ List</h2> <div className = "row"> <button className="btn btn-primary btn-sm" onClick={this.addExcCZ}> Add ExcCZ</button> </div> <br></br> <div className = "row"> <table className = "table table-striped table-bordered"> <thead> <tr> <th> Actions</th> </tr> </thead> <tbody> { this.state.excCZs.map( excCZ => <tr key = {excCZ.excCZId}> <td> <button onClick={ () => this.editExcCZ(excCZ.excCZId)} className="btn btn-info btn-sm">Update </button> <button style={{marginLeft: "10px"}} onClick={ () => this.deleteExcCZ(excCZ.excCZId)} className="btn btn-danger btn-sm">Delete </button> <button style={{marginLeft: "10px"}} onClick={ () => this.viewExcCZ(excCZ.excCZId)} className="btn btn-info btn-sm">View </button> </td> </tr> ) } </tbody> </table> </div> </div> ) } } export default ListExcCZComponent
import fs from "fs" import { ethers, network } from "hardhat" import { frontEndContractsFile, frontEndAbiFile, developmentChains } from "../helper-hardhat-config" const func = async () => { if (!developmentChains.includes(network.name) && process.env.UPDATE_FRONT_END) { console.log("Writing to front end...") await updateContractAddresses() await updateAbi() console.log("Front end written!") } } async function updateAbi() { const contract = await ethers.getContract("SacPayments") fs.writeFileSync(frontEndAbiFile, (contract.interface.format(ethers.utils.FormatTypes.json) as string)) } async function updateContractAddresses() { const contract = await ethers.getContract("SacPayments") const contractAddresses = JSON.parse(fs.readFileSync(frontEndContractsFile, "utf8")) if (network.config.chainId!.toString() in contractAddresses) { if (!contractAddresses[network.config.chainId!.toString()].includes(contract.address)) { contractAddresses[network.config.chainId!.toString()].push(contract.address) } } else { contractAddresses[network.config.chainId!.toString()] = [contract.address] } fs.writeFileSync(frontEndContractsFile, JSON.stringify(contractAddresses)) } export default func; func.id = "update_frontend"; func.tags = ["all", 'frontend'];
<?php use App\Http\Controllers\admin\PedidoController; use App\Http\Controllers\cliente\PerfilController; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\cliente\vistaCategoriaController; use App\Http\Controllers\cliente\PedidosCController; use App\Http\Controllers\pagofacil\CallBackAdminController; use App\Http\Controllers\pagofacil\ConsumirServicioController; use App\Models\Categoria; use App\Models\ContadorPage; use App\Models\Marca; use App\Models\Pedido; use App\Models\Producto; use Illuminate\Support\Facades\DB; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('auth.login'); }); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); Auth::routes(); //RUTAS DEL CLIENTE Route::get('Categoria/{id}', [vistaCategoriaController::class, 'index'])->name('cliente.categoria.index'); Route::get('perfil', [vistaCategoriaController::class, 'perfil'])->name('cliente.perfil'); Route::get('Editarperfil', [vistaCategoriaController::class, 'EditPerfil'])->name('cliente.editperfil'); Route::resource('datos', PerfilController::class)->names('cliente.datos'); Route::get('changePassword', [PerfilController::class, 'changePassword'])->name('cliente.changePassword'); Route::post('updatePassword', [PerfilController::class, 'updatePassword'])->name('cliente.updatePassword'); Route::resource('Pedidos', PedidosCController::class)->names('cliente.pedidos'); // Route::get('MiPedido/{id}/Productos', [PedidosCController::class, 'indexP'])->name('cliente.pedidos.indexP'); //Route::get('MiPedido', [PedidosCController::class, 'indexP'])->name('cliente.pedidos.indexP'); ///agregar desde el carrito Route::get('MiPedidoC', [PedidosCController::class, 'indexC'])->name('cliente.pedidos.indexC'); Route::post('MiPedido/Guardar_Productos/{id}', [PedidosCController::class, 'storeC'])->name('cliente.pedidos.storeC'); /////ahora con el inicial, agregar desde el pedido //Route::get('MiPedidoP', [PedidosCController::class, 'indexP'])->name('cliente.pedidos.indexP'); Route::get('MiPedido/{id}/Productos', [PedidosCController::class, 'indexP'])->name('cliente.pedidos.indexP'); Route::post('MiPedido/Guardar_ProductosP/{id}', [PedidosCController::class, 'storeP'])->name('cliente.pedidos.storeP'); Route::post('MiPedido/Guardar_ProductosD/{id}', [PedidosCController::class, 'storeD'])->name('cliente.pedidos.storeD'); Route::post('Deseo/createC',[PedidosCController::class, 'createC'])->name('cliente.pedidos.createC'); Route::post('Deseo/createCID/{id}',[PedidosCController::class, 'createCID'])->name('cliente.pedidos.createCID'); Route::get('Carrito', [PedidosCController::class, 'showC'])->name('cliente.carrito.showC'); ///deseo Route::get('MiPedidoD', [PedidosCController::class, 'indexD'])->name('cliente.pedidos.indexD'); Route::get('Deseo', [PedidosCController::class, 'showD'])->name('cliente.deseo.showD'); Route::get('VistaCategoria/{idcategoria}', function ($idcategoria) { $productos = Producto::where('categoria_id', $idcategoria)->paginate(3); //$pedido = Pedido::where('id', $idpedido)->first(); $pedidos = Pedido::where('cliente_id', Auth::user()->id)->get(); $nombrepagina = "Categoria" . $idcategoria; DB::beginTransaction(); $cantidad = ContadorPage::SumarContador($nombrepagina); DB::commit(); $categorias = Categoria::all(); $marcas = Marca::all(); return view('cliente.Pedidos.productos', compact('productos', 'marcas', 'categorias','cantidad')); })->name('cliente.pedidos.indexCategoria'); Route::delete('Eliminar/detalle/{id}', [PedidosCController::class, 'DetalleDestroy'])->name('cliente.pedidos.DetalleDestroy'); Route::delete('Eliminar/detalleC/{id}', [PedidosCController::class, 'DetalleDestroyC'])->name('cliente.pedidos.DetalleDestroyC'); Route::post('pedidos/create_factura/{id}', [PedidosCController::class, 'CreateFactura'])->name('cliente.pedidos.CreateFactura'); Route::get('/pdf/Cliente/Factura/{id}', 'App\Http\Controllers\admin\PDFController@PDFFacturaCliente')->name('cliente.PDF.FacturaCliente'); Route::get('/pagofacil', function () { return view('pagofacil.index'); }); Route::post('/consumirServicio', [ConsumirServicioController::class, 'RecolectarDatos']); Route::post('/generarQr', [ConsumirServicioController::class, 'generarQr'])->name('admin.generarQr'); Route::post('/consultar', [ConsumirServicioController::class, 'ConsultarEstado']); Route::post('/venta/pagos/callback', CallBackAdminController::class)->name('admin.pagos.callback'); //Route::get('/venta/pagos/consultar/{venta_id}', ConsultarAdminController::class)->name('admin.pagos.consultar');
///* // * // * * Copyright (C) 2015 Eason.Lai ([email protected]) // * * // * * 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. // * // */ // //package com.loosoo100.campus100.imagepicker.ui; // //import android.app.Activity; //import android.graphics.Bitmap; //import android.graphics.Rect; //import android.graphics.RectF; //import android.graphics.drawable.BitmapDrawable; //import android.os.Bundle; //import android.support.v4.app.Fragment; //import android.text.TextUtils; //import android.util.DisplayMetrics; //import android.view.LayoutInflater; //import android.view.View; //import android.view.ViewGroup; //import android.widget.FrameLayout; //import android.widget.RelativeLayout; // //import com.loosoo100.campus100.R; //import com.loosoo100.campus100.imagepicker.AndroidImagePicker; //import com.loosoo100.campus100.imagepicker.ImgLoader; //import com.loosoo100.campus100.imagepicker.UilImgLoader; //import com.loosoo100.campus100.imagepicker.Util; //import com.loosoo100.campus100.imagepicker.widget.AvatarRectView; //import com.loosoo100.campus100.imagepicker.widget.SuperImageView; // ///** // * <b>Image crop Fragment for avatar</b><br/> // * Created by Eason.Lai on 2015/11/1 10:42 <br/> // * contact:[email protected] <br/> // */ //public class AvatarCropFragment extends Fragment{ // // Activity mContext; // // SuperImageView superImageView; // AvatarRectView mRectView; // // private int screenWidth; // private final int margin = 30;//the left and right margins of the center circular shape // // private FrameLayout rootView; // // private String picPath;//the local image path in sdcard // // ImgLoader mImagePresenter;//interface to load image,you can implement it with your own code // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mContext = getActivity(); // // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View contentView = inflater.inflate(R.layout.fragment_avatar_crop,null); // // DisplayMetrics dm = new DisplayMetrics(); // mContext.getWindowManager().getDefaultDisplay().getMetrics(dm); // screenWidth = dm.widthPixels; // // initView(contentView); // // //get the image path from Arguments // picPath = getArguments().getString(AndroidImagePicker.KEY_PIC_PATH); // // mImagePresenter = new UilImgLoader(); // // if(TextUtils.isEmpty(picPath)){ // throw new RuntimeException("AndroidImagePicker:you have to give me an image path from sdcard"); // }else{ // mImagePresenter.onPresentImage(superImageView,picPath,screenWidth); // } // // return contentView; // // } // // /** // * init all views // * @param contentView // */ // void initView(View contentView){ // superImageView = (SuperImageView) contentView.findViewById(R.id.iv_pic); // rootView = (FrameLayout) contentView.findViewById(R.id.container); // // RelativeLayout.LayoutParams rlLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); // //rlLayoutParams.addRule(RelativeLayout.ABOVE, R.id.photo_preview_dock); // mRectView = new AvatarRectView(mContext, screenWidth - margin*2); // rootView.addView(mRectView, 1, rlLayoutParams); // } // // // /** // * public method to get the crop bitmap // * @return // */ // public Bitmap getCropBitmap(int expectSize){ // if(expectSize <= 0){ // return null; // } // Bitmap srcBitmap = ((BitmapDrawable)superImageView.getDrawable()).getBitmap(); // double rotation = superImageView.getImageRotation(); // int level = (int) Math.floor((rotation + Math.PI / 4) / (Math.PI / 2)); // if (level != 0){ // srcBitmap = Util.rotate(srcBitmap,90 * level); // } // Rect centerRect = mRectView.getCropRect(); // RectF matrixRect = superImageView.getMatrixRect(); // // Bitmap bmp = AndroidImagePicker.makeCropBitmap(srcBitmap, centerRect, matrixRect, expectSize); // return bmp; // } // // //}
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.client = void 0; const express_1 = __importDefault(require("express")); const mongodb_1 = require("mongodb"); const router = express_1.default.Router(); let client = new mongodb_1.MongoClient("mongodb://localhost:27017", { useNewUrlParser: true, useUnifiedTopology: true, }); exports.client = client; let db = client.db("ReindeerLichens"); router.post("/", (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { console.log("POST request to /setInProgress"); if (!req.body.fileName || !req.body.status) { return res.status(400).json({ message: "Please provide a file name and status" }); } let name = req.body.fileName; let status = req.body.status == "true"; if (name.includes("_mask")) { return res.status(400).json({ message: "Masks are not meant to be used on this API" }); } console.log(`Updating ${name} to inProgress: ${status}`); let result = yield db.collection("images.files").updateOne({ filename: name }, { $set: { inProgress: status } }); if (!result.acknowledged) { return res.status(500).json({ message: "Something went wrong" }); } if (result.modifiedCount === 1) { return res.status(200).json({ message: `Updated inProgress to ${status}` }); } return res.status(400).json({ message: "The update does not change information" }); })); router.get("/:fileName", (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { console.log("GET request to /setInProgress"); let name = req.params.fileName; if (name.includes("_mask")) { return res.status(400).json({ message: "Masks are not meant to be used on this API" }); } let result = yield db.collection("images.files").findOne({ filename: name }); if (!result) { return res.status(400).json({ message: "File not found" }); } return res.status(200).json({ inProgress: result.inProgress }); })); exports.default = router;
import 'package:chatapp/components/my_textfield.dart'; import 'package:chatapp/services/auth/auth_service.dart'; import 'package:chatapp/services/chat/chat_service.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import '../components/chat_bubble.dart'; class ChatPage extends StatefulWidget { final String receiverEmail; final String receiverID; ChatPage({ super.key, required this.receiverEmail, required this.receiverID, }); @override State<ChatPage> createState() => _ChatPageState(); } class _ChatPageState extends State<ChatPage> { // text controller final TextEditingController _messageController = TextEditingController(); // chat & auth services final ChatService _chatService = ChatService(); final AuthService _authService = AuthService(); // for textfield focus FocusNode myFocusNode = FocusNode(); @override void initState() { super.initState(); // add listener to focus mode myFocusNode.addListener(() { if (myFocusNode.hasFocus) { Future.delayed( const Duration(milliseconds: 500), () => scrollDown(), ); } }); // wait a bit for listview to be built, then scroll to bottom Future.delayed( const Duration(milliseconds: 500), () => scrollDown(), ); } @override void dispose() { myFocusNode.dispose(); _messageController.dispose(); super.dispose(); } // scroll controller final ScrollController _scrollController = ScrollController(); void scrollDown() { _scrollController.animateTo( _scrollController.position.maxScrollExtent, duration: const Duration(seconds: 1), curve: Curves.fastOutSlowIn, ); } // send messages void sendMessage() async { // if there is something inside the textfield if (_messageController.text.isNotEmpty) { // send the message await _chatService.sendMessage(widget.receiverID, _messageController.text); // clear text controller _messageController.clear(); } scrollDown(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).colorScheme.background, appBar: AppBar( title: Text(widget.receiverEmail), backgroundColor: Colors.transparent, foregroundColor: Colors.grey, elevation: 0, ), body: Column ( children: [ // display all messages Expanded( child: _buildMessageList(), ), // user input _buildUserInput(), ],) ); } // build message list Widget _buildMessageList() { String senderID = _authService.getCurrentUser()!.uid; return StreamBuilder( stream: _chatService.getMessages(widget.receiverID, senderID), builder: (context, snapshot) { // errors if (snapshot.hasError) { return const Text("Error"); } // loading if (snapshot.connectionState == ConnectionState.waiting) { return const Text("Loading..."); } // return list view return ListView( controller: _scrollController, children: snapshot.data!.docs.map((doc) => _buildMessageItem(doc)).toList(), ); }, ); } // build message item Widget _buildMessageItem(DocumentSnapshot doc) { Map <String, dynamic> data = doc.data() as Map<String, dynamic>; // is current user bool isCurrentUser = data['senderID'] == _authService.getCurrentUser()!.uid; // align message to the right if sender is the current user, otherwise left var alignment = isCurrentUser ? Alignment.centerRight : Alignment.centerLeft; return Container( alignment: alignment, child: Column( crossAxisAlignment: isCurrentUser ? CrossAxisAlignment.end : CrossAxisAlignment.start, children: [ ChatBubble( message: data["message"], isCurrentUser: isCurrentUser, ) ], ), ); } // build message input Widget _buildUserInput() { return Padding( padding: const EdgeInsets.only(bottom: 50.0), child: Row( children: [ // textfield should take up most of the space Expanded( child: MyTextField( controller: _messageController, hintText: "Ecrire un message...", obscureText: false, focusNode: myFocusNode, ), ), // send button Container( decoration: const BoxDecoration( color: Colors.green, shape: BoxShape.circle, ), margin: const EdgeInsets.only(right: 25), child: IconButton( onPressed: sendMessage, icon: const Icon( Icons.arrow_upward, color: Colors.white, ), ), ), ], ), ); } }
import React, { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { useQuery } from "@tanstack/react-query"; import { API_URL } from "../../config/index"; import Layout from "../../hocs/Layout"; import axios from "axios"; import { useRouter } from "next/router"; export const getStaticPaths = async (req, res) => { const apiRes = await fetch(`${API_URL}/api/account/users`, { method: "GET", headers: { Accept: "application/json", }, }); const data = await apiRes.json(); const paths = data.users.map((user) => { return { params: { user_id: user.id.toString() }, }; }); return { paths: paths, fallback: false, }; }; export const getStaticProps = async (context) => { const id = context.params.user_id; const apiRes = await fetch(`${API_URL}/api/account/users/${id}`, { method: "GET", headers: { Accept: "application/json", }, }); const data = await apiRes.json(); return { props: { userData: data.user }, }; }; const UserPage = ({ userData }) => { const isAuthenticated = useSelector((state) => state.auth.isAuthenticated); const loading = useSelector((state) => state.auth.loading); const router = useRouter(); async function fetchUserData() { const { data } = await axios.get("/api/kanbanapp/getUserData", { method: "GET", headers: { Accept: "application/json", }, }); return data; } const { data, error, isError, isLoading } = useQuery(["user"], () => fetchUserData() ); if (isError) { return <div>Error! {error.message}</div>; } if (typeof window !== "undefined" && !loading && !isAuthenticated) router.push("/login"); return ( <div> <Layout title="Kanban App | User Page"> {isLoading ? <div>Loading...</div> : <div>{data.user.first_name}</div>} </Layout> </div> ); }; export default UserPage;
import 'package:flutter/material.dart'; import 'package:projectPet/login/dogClass.dart'; class Review extends StatefulWidget { const Review({Key? key, required this.title}) : super(key: key); final String title; @override State<Review> createState() => _MyHomePageState(); } class _MyHomePageState extends State<Review> { List<Post> PostInfo = [ Post('Kai-Kow', 'assets/images/catkaikow.png', ['บ้านแมวไข่ขาว'], ['หลงรักทุกตัว']), Post('JubJub', 'assets/images/catorange.png', ['บ้านแก๊งจั๊บ'], ['น่ารักฉุดๆ']), Post('Sweet', 'assets/images/agns.png', ['Jeda'], ['so cute']), ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( '🐾 PET WORLD 🐾', style: TextStyle( fontFamily: 'PawWow', // แทน 'YourFontFamily' ด้วยชื่อฟอนต์ที่คุณต้องการใช้ fontSize: 75.0, // ปรับขนาดตามที่ต้องการ fontWeight: FontWeight.bold, // ปรับความหนาตามที่ต้องการ color: Colors.black, // ปรับสีตัวอักษรตามที่ต้องการ ), ), centerTitle: true, toolbarHeight: 100.0, // Center the title ), body: SingleChildScrollView( child: Column( children: [ for (int i = 0; i < PostInfo.length; i++) buildPost(position: i), ], ), ), ); } Widget buildPost({int? position}) { var post = PostInfo[position!]; return Padding( padding: const EdgeInsets.all(20.0), child: Container( color: Colors.grey.shade200, child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Padding( padding: const EdgeInsets.all(20.0), child: CircleAvatar( radius: 30.0, backgroundImage: AssetImage(post.userImages), ), ), Text( post.user, style: TextStyle(fontSize: 35.0), ), ], ), Padding( padding: const EdgeInsets.all(50.0), child: IconButton( onPressed: () {}, icon: Image.asset('assets/images/paw.png'), ) ) ], ), SizedBox( height: 20.0, ), for (int i = 0; i < post.commmentUser.length; i++) Row( children: [ SizedBox( width: 20.0, ), Text( post.commmentUser[i] + ' : ', style: TextStyle(fontSize: 20.0, color: Colors.teal), ), Text( post.commentUserMessage[i], style: TextStyle(fontSize: 20.0, color: Colors.black), ), ], ), Row( children: [ buildThumpUp(position: position), buildField(position: position), SizedBox( width: 40.0, ), ], ), ], ), ), ); } Widget buildThumpUp({int? position}) { var postlike = PostInfo[position!]; return Padding( padding: const EdgeInsets.all(10.0), child: IconButton( onPressed: () { setState(() { postlike.like = !postlike.like; }); }, icon: Icon((postlike.like)? Icons.thumb_up : Icons.thumb_up_alt_outlined, size: 25.0,), ), ); } Widget buildField({int? position}){ var post = PostInfo[position!]; var controller = post.controller; return Flexible( child: Container( height: 25.0, child: TextField( decoration: InputDecoration(hintText: 'Add message'), controller: controller, onSubmitted: (String comment){ setState(() { post.commmentUser.add("sunny"); post.commentUserMessage.add(comment); controller.clear(); }); } ), ), ); } }
import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Slide, } from "@mui/material"; import { TransitionProps } from "@mui/material/transitions"; import React from "react"; interface Props { onSure: Function; onCancel: Function; open: boolean; handleClose: | ((event: {}, reason: "backdropClick" | "escapeKeyDown") => void) | undefined; title: string; description: string; } const Transition = React.forwardRef(function Transition( props: TransitionProps & { children: React.ReactElement<any, any>; }, ref: React.Ref<unknown> ) { return <Slide direction="up" ref={ref} {...props} />; }); const ConfirmAlert: React.FC<Props> = ({ onSure, onCancel, open, title, handleClose, description, }) => { return ( <Dialog open={open} TransitionComponent={Transition} keepMounted onClose={handleClose} aria-describedby="alert-dialog-slide-description" > <DialogTitle>{title}</DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-slide-description"> {description} </DialogContentText> </DialogContent> <DialogActions> <Button variant="outlined" color="info" onClick={() => onCancel()}> Cancel </Button> <Button variant="contained" color="error" onClick={() => onSure()}> Confirm </Button> </DialogActions> </Dialog> ); }; export default ConfirmAlert;
import { program } from 'commander' import readline from 'readline' import { Writable } from 'stream' import { isUserPasswordValid } from '@server/helpers/custom-validators/users.js' import { initDatabaseModels } from '@server/initializers/database.js' import { UserModel } from '@server/models/user/user.js' program .option('-u, --user [user]', 'User') .parse(process.argv) const options = program.opts() if (options.user === undefined) { console.error('All parameters are mandatory.') process.exit(-1) } initDatabaseModels(true) .then(() => { return UserModel.loadByUsername(options.user) }) .then(user => { if (!user) { console.error('Unknown user.') process.exit(-1) } const mutableStdout = new Writable({ write: function (_chunk, _encoding, callback) { callback() } }) const rl = readline.createInterface({ input: process.stdin, output: mutableStdout, terminal: true }) console.log('New password?') rl.on('line', function (password) { if (!isUserPasswordValid(password)) { console.error('New password is invalid.') process.exit(-1) } user.password = password user.save() .then(() => console.log('User password updated.')) .catch(err => console.error(err)) .finally(() => process.exit(0)) }) }) .catch(err => { console.error(err) process.exit(-1) })
<?php namespace Nobir\MiniWizard\Services; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use Nobir\MiniWizard\Services\BaseCreation; class MigrationCreation extends BaseCreation { public function generate() { //get table name $table_name = \Illuminate\Support\Str::snake(\Illuminate\Support\Str::plural($this->model_name)); // Derive table name from model name //ge file name $migrationFileName = date('Y_m_d_His') . '_create_' . $table_name . '_table.php'; //prepare file path $migration_file_path = self::getModulePath(self::MIGRATION, $migrationFileName); if (self::fileOverwriteOrNot($migration_file_path)) { //file creation FileModifier::getContent(self::getStubFilePath(self::MIGRATION)) ->searchingText('{{table_name}}')->replace()->insertingText($table_name) ->searchingText('{{table_name}}')->replace()->insertingText($table_name) ->searchingText('{{slot}}')->replace()->insertingText($this->generateMigrationFields()) ->save($migration_file_path); $this->info('Migration created successfully'); try { Artisan::call('migrate'); echo Artisan::output(); } catch (\Exception $e) { echo $this->info('migration fail'); } /** * if the migrations are under any folder then this folder have to register to appservice provider */ $this->loadMigration(); return true; } $this->info('Skiped migration creation') ; return true; } protected function generateMigrationFields() { $migrationFields = ''; foreach ($this->fields as $fieldName => $fieldFunctions) { $fieldLine = "\$table"; foreach ($fieldFunctions as $functinORNumeric => $functionORValue) { if (in_array($functinORNumeric, ['enum', 'set'])) { $fieldLine .= "->{$functinORNumeric}('{$fieldName}', '{$functionORValue}')"; } elseif (in_array($functinORNumeric, ['default', 'length', 'total', 'places'])) { $fieldLine .= "->{$functinORNumeric}('{$functionORValue}')"; } else { if (in_array($functionORValue, ['foreignIdFor'])) { $model_name = self::foreignKeyToModelName($fieldName); $name_space = self::getModuleNamespace(self::MODEL); if (!file_exists(self::getModulePath(self::MODEL) . '/' . self::foreignKeyToModelName($fieldName) . '.php')) { $name_space = 'App\Models'; } $fieldLine .= "->{$functionORValue}(\\$name_space\\" . $model_name . "::class)"; } elseif (in_array($functionORValue, ['unsigned', 'constrained', 'cascadeOnDelete', 'cascadeOnUpdate', 'nullable', 'primary', 'unique', 'autoIncrement', 'index', 'restrictOnDelete', 'restrictOnUpdate'])) { $fieldLine .= "->{$functionORValue}()"; } else { $fieldLine .= "->{$functionORValue}('{$fieldName}')"; } } } $fieldLine .= ';'; $migrationFields .= "\n\t\t\t" . $fieldLine; } return $migrationFields; } public function loadMigration(){ //derived app service provider path from pathmanager $app_service_provider_path = self::appServiceProviderPath(); //migration path from pathmanager $migration_seffix = self::getModuleSuffix(self::MIGRATION); if ($migration_seffix) { (new FileModifier($app_service_provider_path))->searchingText('{', 3)->insertAfter()->insertingText("\n\t\t\$this->loadMigrationsFrom([\n\t\t\tdatabase_path('migrations'),\n\t\t\tdatabase_path('migrations/$migration_seffix'),\n\t\t]);") ->save(); } } }
<?php class ActiveCampaign_Subscriptions_Block_Adminhtml_Subscriptions_Edit_Tab_Connection extends Mage_Adminhtml_Block_Widget_Form { protected function _prepareForm() { $form = new Varien_Data_Form(); $this->setForm($form); $fieldset = $form->addFieldset('subscriptions_form', array('legend'=>Mage::helper('subscriptions')->__('Add Connection Details'))); $fieldset->addField('title', 'text', array( 'label' => Mage::helper('subscriptions')->__('Title'), 'class' => 'required-entry', 'required' => true, 'name' => 'title', )); /* $fieldset->addField('filename', 'file', array( 'label' => Mage::helper('subscriptions')->__('File'), 'required' => false, 'name' => 'filename', )); */ $fieldset->addField('status', 'select', array( 'label' => Mage::helper('subscriptions')->__('Status'), 'name' => 'status', 'values' => array( array( 'value' => 1, 'label' => Mage::helper('subscriptions')->__('Enabled'), ), array( 'value' => 2, 'label' => Mage::helper('subscriptions')->__('Disabled'), ), ), )); $fieldset->addField('api_url', 'text', array( 'label' => Mage::helper('subscriptions')->__('API URL'), 'class' => 'required-entry', 'required' => true, 'name' => 'api_url', )); $fieldset->addField('api_key', 'text', array( 'label' => Mage::helper('subscriptions')->__('API Key'), 'class' => 'required-entry', 'required' => true, 'name' => 'api_key', )); /* $fieldset->addField('content', 'editor', array( 'name' => 'content', 'label' => Mage::helper('subscriptions')->__('Content'), 'title' => Mage::helper('subscriptions')->__('Content'), 'style' => 'width:700px; height:500px;', 'wysiwyg' => false, 'required' => true, )); */ if ( Mage::getSingleton('adminhtml/session')->getSubscriptionsData() ) { $form->setValues(Mage::getSingleton('adminhtml/session')->getSubscriptionsData()); Mage::getSingleton('adminhtml/session')->setSubscriptionsData(null); } elseif ( Mage::registry('subscriptions_data') ) { $form->setValues(Mage::registry('subscriptions_data')->getData()); } return parent::_prepareForm(); } }
import { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import { courseImgUrl } from "../../Utils/constants"; import "./coursedetail.css"; import Button from "react-bootstrap/Button"; import { useCart } from "../../Context/CartContext"; const CourseDetails = () => { const { id } = useParams(); const [courseData, setCourseData] = useState({}); const [loading, setLoading] = useState(true); const { addToCart } = useCart(); useEffect(() => { const fetchCourseDetail = async () => { try { const response = await fetch(`http://localhost:3000/courses?id=${id}`); if (!response.ok) { throw new Error("Network response was not ok"); } const jsonData = await response.json(); setCourseData(jsonData[0]); setLoading(false); } catch (error) { console.error("There was a problem with the fetch operation:", error); setLoading(false); } }; fetchCourseDetail(); }, [id]); return ( <> {loading ? ( <p>Loading...</p> ) : ( <> {courseData.length === 0 ? ( <> <h2>No Data Found</h2> </> ) : ( <> <div> <img className="imgcourse" src={`${courseImgUrl}/${courseData.img}`} alt={courseData.img} /> </div> <div> <p> {" "} <span className="title">Title </span>: {courseData.title} </p> <p> <span className="title">Instructor </span>:{" "} {courseData.instructor} </p> <p> <span className="title">Description </span>:{" "} {courseData.description} </p> <p> <span className="title">Pricing </span>:{" "} {`₹ ${courseData.pricing}`}{" "} <span> <Button variant="success" onClick={() => addToCart(courseData)} > Add to Cart </Button> </span> </p> </div> </> )} </> )} </> ); }; export default CourseDetails;
library(shiny) library(shinydashboard) library(rhandsontable) library(plyr) library(dplyr) library(ggplot2) dashboardPage( dashboardHeader(title = "ZW graphs"), dashboardSidebar( sidebarMenu( menuItem("File upload", tabName = "fileUpload", icon = icon("file")), menuItem("Sample grouping", tabName = "sampleGroups", icon = icon("object-group")), menuItem("Distribution graphs", tabName = "distribution", icon = icon("signal")), menuItem("Cumulative graphs", tabName = "cumulative", icon = icon("signal")) ) ), dashboardBody( tabItems( ### File upload / download tabItem( tabName = "fileUpload", h1("1) Upload files"), br(), helpText(p("Select and upload the raw data files containing size porfile and zeta potential (ZP) measurements.", "All uploaded files and the corresponding characteristics will appear in the table below.", "The table allows for a quick overview of the files that have been uploaded and enables to verify ", "the matching of size and ZP profile files belonging to the same sample."), p("After the files have been uploaded, the merged data sets can be downloaded using the download tool."), p("Note that size profile files can be analyzed independently, however, ZP files require matching size ", "profile files to be uploaded as well, since they do not contain total particle number or dilution ", "factor data")), fluidRow( column(5, fileInput("files", h3("File input"), multiple = TRUE) ), column(5, uiOutput("downloadPanelHeader"), uiOutput("downloadPanelDropdown"), uiOutput("downloadPanelButton") ) ), h3("Uploaded files"), helpText(p("The table below displays the characteristics and statuses of the uploaded files."), p("Columns ", strong("sampleName"), " and ", strong("dilutionFactor"), "can be amended.", "So, if the automatically generated sample names are not acceptable or do not allow ", "size and ZP profiles to be matched automatically, they can be changed. It is advised to ", "keep the sample names minimalistic and unique. Also, make sure that size profile and ", "ZP data files match if both are present for the given sample.", "Dilution factors can be changed as well."), p("All changes made will aslo take affect when the merged data sets are downloaded.")), br(), rHandsontableOutput("inputFilesTable"), br(), h4("Table options"), actionButton("clear", "Clear"), actionButton("undo", "Undo manual changes"), br() ), ### Sample grouping tabItem( tabName = "sampleGroups", h1("2) Sample grouping"), br(), helpText(p("The following two table enable sample assignment to experimental groups."), p("The ", strong("first set of experimental groups"), " is mandatory for data visualization ", "in the following panels. By default, all samples are assigned to one experimental ", "group labeled 'Group1'."), p("The ", strong("second set of experimental groups"), " is optional. By default, no samples are assgined ", "to any groups. The second set can be used to further improve data visualization."), p("Experimental groups can be added and removed by inserting rows into the tables (right click on the table)"), p("Group names can be changed by clicking on the corresponding cell"), p("Samples are added and removed to groups by ticking the corresponding boxes in group rows in the table. ", "One sample can be assigned to multiple groups") ), uiOutput("sampleGroupsBox1"), br(), br(), uiOutput("sampleGroupsBox2") ), ### Distribution plots tabItem( tabName = "distribution", h1("3) Distribution graphs"), br(), helpText("Various size and ZP distribution graphs can be generated using the options listed below the grap"), br(), plotOutput("plot1", height = 600), br(), box( title = strong("Main options"), fluidRow( column(2, actionButton("plot1_refresh", "Refresh"), helpText("If changes are made to uploaded files or sample groupings, refresh the graph for changes to take effect.") ), column(2, radioButtons("plot1_dataSetType", h4("Data set"), choices = list("Size profile data" = 1, "ZP profile data" = 2), selected = 1), helpText("If ZP files are not uploaded, the ZP data is unavailable.") ), column(2, radioButtons("plot1_dataSetFormat", h4("Data format"), choices = list("Absolute numbers" = 1, "Relative numbers" = 2), selected = 1), helpText("If 'Relative numbers' is selected, frequency of particles is displayed instead of total numbers.") ), column(6, conditionalPanel( condition = "input.plot1_dataSetType == 1", sliderInput("plot1_range_size", "Range of nm displayed", min = 15, max = 5985, step = 30, value = c(15, 495)) ), conditionalPanel( condition = "input.plot1_dataSetType == 2", sliderInput("plot1_range_zp", "Range of mV displayed", min = -135, max = 130, step = 5, value = c(-135, 130)) ) ) ), width = NULL ), br(), box(title = strong("Customisation options"), fluidRow( column(2, radioButtons("plot1_groupSettings", h4("Experimental groups"), choices = list("Primary" = 1, "Secondary" = 2, "Both" = 3, "None" = 4), selected = 1), helpText("Sets the grouping data used for graphs.", "Selection of secondary experimental groups is ignored if it has not been assigned.") ), conditionalPanel( condition = "input.plot1_groupSettings != 4", column(2, radioButtons("plot1_sampleSettings", h4("Sample grouping settings"), choices = list("Grouped samples" = 1, "Individual samples" = 2), selected = 2), helpText("Determines whether each sample is displayed separately or merged into a group.") ), column(2, radioButtons("plot1_facetSettings", h4("Plot faceting settings"), choices = list("Facet primary experimental groups" = 1, "Facet secondary experimental groups" = 2, "Facet experimental groups" = 3, "No faceting" = 4), selected = 4), helpText("Faceting enables groups to be separated unto sub-graphs.", "Faceting of secondary experimental groups is ignored if it has not been assigned.") ), column(2, radioButtons("plot1_colorSettings", h4("Plot coloring settings"), choices = list("Color primary experimental groups" = 1, "Color secondary experimental groups" = 2, "Color samples separately" = 3), selected = 3), helpText("Coloring enables groups to be separated by color", "Coloring of secondary experimental groups is ignored if it has not been assigned.", "Samples can only be colored separately if samples are displayed individually ", "(Sample grouping settings).") ), column(2, radioButtons("plot1_styleSettings", h4("Plot style settings"), choices = list("Lineplot" = 1, "Barplot" = 2, "Scatterplot" = 3), selected = 1) ), column(2, conditionalPanel( condition = "input.plot_1sampleSettings == 1", radioButtons("plot1_errorBarSettings", h4("Error bar settings"), choices = list("Standard deviation (SD)" = 1, "Standard error of the mean (SEM)" = 2, "None" = 3), selected = 1), helpText("If samples are aggregated into groups, error bars can be added to the means.") ) ) ) ), width = NULL ) ), ### Cumulative plots tabItem( tabName = "cumulative", h1("3) Cumulative graphs"), br(), helpText("Various size and ZP cumulative graphs can be generated using the options listed below the grap"), br(), plotOutput("plot2", height = 600), br(), box( title = strong("Main options"), fluidRow( column(2, actionButton("plot2_refresh", "Refresh"), helpText("If changes are made to uploaded files or sample groupings, refresh the graph for changes to take effect.") ), column(2, radioButtons("plot2_dataSetType", h4("Data set"), choices = list("Size profile data" = 1, "ZP profile data" = 2), selected = 1), helpText("If ZP files are not uploaded, the ZP data is unavailable.") ), column(6, conditionalPanel( condition = "input.plot2_dataSetType == 1", sliderInput("plot2_range_size", "Range of nm displayed", min = 15, max = 5985, step = 30, value = c(15, 495)) ), conditionalPanel( condition = "input.plot2_dataSetType == 2", sliderInput("plot2_range_zp", "Range of mV displayed", min = -135, max = 130, step = 5, value = c(-135, 130)) ) ) ), width = NULL ), br(), box(title = strong("Customisation options"), fluidRow( column(2, radioButtons("plot2_groupSettings", h4("Experimental groups"), choices = list("Primary" = 1, "Secondary" = 2, "Both" = 3, "None" = 4), selected = 1), helpText("Sets the grouping data used for graphs.", "Selection of secondary experimental groups is ignored if it has not been assigned.") ), conditionalPanel( condition = "input.plot2_groupSettings != 4", column(2, radioButtons("plot2_sampleSettings", h4("Sample grouping settings"), choices = list("Grouped samples" = 1, "Individual samples" = 2), selected = 2), helpText("Determines whether each sample is displayed separately or merged into a group.") ), column(2, radioButtons("plot2_facetSettings", h4("Plot faceting settings"), choices = list("Facet primary experimental groups" = 1, "Facet secondary experimental groups" = 2, "Facet experimental groups" = 3, "No faceting" = 4), selected = 4), helpText("Faceting enables groups to be separated unto sub-graphs.", "Faceting of secondary experimental groups is ignored if it has not been assigned.") ), column(2, radioButtons("plot2_colorSettings", h4("Plot coloring settings"), choices = list("Color primary experimental groups" = 1, "Color secondary experimental groups" = 2, "Color samples separately" = 3), selected = 3), helpText("Coloring enables groups to be separated by color", "Coloring of secondary experimental groups is ignored if it has not been assigned.", "Samples can only be colored separately if samples are displayed individually ", "(Sample grouping settings).") ), column(2, conditionalPanel( condition = "input.plot2_sampleSettings == 1", radioButtons("plot2_errorBarSettings", h4("'Error hue' settings"), choices = list("Standard deviation (SD)" = 1, "Standard error of the mean (SEM)" = 2, "None" = 3), selected = 1), helpText("If samples are aggregated into groups, 'error' hues can be added to the means.") ) ) ) ), width = NULL ) ) ) ) )
import 'package:aura_wallet_example/src/core/utils/dart_core_extension.dart'; class AuraWalletBalanceData { final List<AuraWalletBalance> balances; const AuraWalletBalanceData({required this.balances}); } class AuraWalletBalance { final String id; final String deNom; final String amount; const AuraWalletBalance({ required this.id, required this.amount, required this.deNom, }); String get toAura { double amount = double.tryParse(this.amount) ?? 0; switch (deNom.toUpperCase()) { case 'AURA': return '${amount.truncateToDecimalPlaces(2)} AURA'; case 'UEAURA': return '${(amount / 1000000).truncateToDecimalPlaces(2)} EAURA'; case 'UAURA': return '${(amount / 1000000).truncateToDecimalPlaces(2)} AURA'; default: return '${amount.truncateToDecimalPlaces(2)} AURA'; } } }
--- title: 'Next 13 blog post' date: '2023-25-05' tags: [nextjs, routes] --- # Searching and Routing Dynamically We can route programmatically and dynamically in next js when we handle a form: ```typescript const handleSubmit = async (e: FormEvent<HTMLFormElement>) => { e.preventDefault() setSearch('') //Routing dynamically router.push(`/${search}/`) } ``` now to handle it we should create a dynamic route, for example: **[searchTerm]** and _page.tsx_ inside it. # Generating Dynamic metaData ```typescript //It accepts what dynamic routes accept and next will deduplicate the request export async function generateMetadata({ params: { searchTerm } }: Params) { const wikiData: Promise<SearchResult> = getWikiResults(searchTerm) const data = await wikiData const displayTerm = searchTerm.replaceAll('%20', ' ') //If not found if (!data?.query?.pages) { return { title: `${displayTerm} Not Found`, } } //results return { title: displayTerm, description: `Search results for ${displayTerm}`, } } ``` # Tailwind _prose_ **@tailwindcss/typography** first install it: _npm install -D @tailwindcss/typography_ then add it to _tailwind.config.js_ ```typescript module.exports = { theme: { // ... }, plugins: [ require('@tailwindcss/typography'), // ... ], } ``` > The official Tailwind CSS Typography plugin provides a set of prose classes you can use to add beautiful typographic defaults to any vanilla HTML you don’t control, like HTML rendered from Markdown, or pulled from a CMS.
#include <Wire.h> #include <Adafruit_PWMServoDriver.h> #include <ArduinoBLE.h> // Objetos Adafruit_PWMServoDriver brazo = Adafruit_PWMServoDriver(); BLEService ledService("180A"); BLEByteCharacteristic switchCharacteristic("2A57", BLEWrite); // Dependiendo de la marca de tus servos, pueden variar el pulso mínimo y máximo. // Consulta sus especificaciones. #define SERVOMIN 150 // Pulso mínimo (fuera de 4096) #define SERVOMAX 600 // Pulso máximo (fuera de 4096) int flu = 15; // Primer servo # de contador uint8_t servonum = 0; void setup() { Serial.begin(9600); brazo.begin(); brazo.setPWMFreq(60); // Servos analógicos funcionan a ~60 Hz actualizado. if (!BLE.begin()) { Serial.println("No funcionó el Bt"); while (1); } //yield(); // set advertised local name and service UUID: BLE.setLocalName("BrazoRobotico"); BLE.setAdvertisedService(ledService); // add the characteristic to the service ledService.addCharacteristic(switchCharacteristic); // add service BLE.addService(ledService); // set the initial value for the characteristic: switchCharacteristic.writeValue(0); // start advertising BLE.advertise(); Serial.println("Ya estoy por aquí...disponible, como si no tuviera nada que hacer... "); } void loop() { /* * Coreografía automática ... descomente todo este bloque si lo que desea es que se mueva autónomamente setear la coreografía Se mueve a la derecha Baja el cuerpo baja el griper Cierra el griper Sube el griper sube el cuerpo Se mueve a la izquierda Baja el cuerpo baja el griper abre el griper girarDerecha(); bajarCuerpo(); bajarGriper(); abrirGriper(); cerrarGriper(); subirGriper(); subirCuerpo(); girarIzquierda(); bajarCuerpo(); bajarGriper(); abrirGriper(); cerrarGriper(); subirCuerpo(); subirGriper(); Fin del bloque automático... elimine el comentario siguiente para habilitar el movimiento autónomo */ // Movimiento vía Ble BLEDevice central = BLE.central(); if (central) { while (central.connected()) { if (switchCharacteristic.written()) { switch (switchCharacteristic.value()) { Serial.print("Valor recibido: "); Serial.println(switchCharacteristic.value()); // Si se envía un 0 o 1, gira a la derecha o a la izquierda los grados preprogramados case 0: // Gira a la derecha girarDerecha(); break; case 1: // Gira a la izquierda girarIzquierda(); break; // Si se envía un 2 o 3 sube o baja el cuerpo principal del brazo case 2: // Baja el brazo bajarCuerpo(); break; case 3: // Sube el brazo subirCuerpo(); break; // Si se envía un 4 o 5, sube o baja la inclinación del griper case 4: // Baja el griper bajarGriper(); break; case 5: // Sube el griper subirGriper(); break; // Si se envía un 6 o 7, abre y cierra el griper case 6: // Abre el griper abrirGriper(); break; case 7: // Cierra el griper cerrarGriper(); break; // Si se manda algo que no sea nada de lo anterior, va a una posición de inicio default: break; } } } Serial.print(F("Se desconectó de ")); Serial.println(central.address()); } } //------------------------------------------------ // Funciones que convierte angulos a Pulsos //------------------------------------------------ int anguloApulsar(int ang){ int pulso = map(ang,0, 180, SERVOMIN,SERVOMAX); return pulso; } //------------------------------------------------ // Funciones que hacen que rote la base //------------------------------------------------ void girarDerecha(){ Serial.println("Girando a la derecha"); for( int angulo =130; angulo>=50; angulo -=1){ brazo.setPWM(0, 0, anguloApulsar(angulo) ); delay(flu); } delay(3000); } void girarIzquierda(){ Serial.println("Girando a la izquierda"); for( int angulo = 50; angulo<130; angulo +=1){ delay(flu); brazo.setPWM(0, 0, anguloApulsar(angulo) ); } delay(3000); } //------------------------------------------------ // Funciones que hacen que se incline el brazo entero //------------------------------------------------ void bajarCuerpo(){ Serial.println("Bajando el cuerpo"); for( int angulo =110; angulo>=70; angulo -=1){ brazo.setPWM(1, 0, anguloApulsar(angulo) ); delay(flu); } delay(3000); } void subirCuerpo(){ Serial.println("Subiendo el cuerpo"); for( int angulo = 70; angulo< 110; angulo +=1){ brazo.setPWM(1, 0, anguloApulsar(angulo) ); delay(flu); } delay(3000); } //------------------------------------------------ // Servo que inclina la muñeca //------------------------------------------------ void bajarGriper(){ Serial.println("Bajando el griper"); for( int angulo =120; angulo<150; angulo +=1){ brazo.setPWM(2, 0, anguloApulsar(angulo) ); delay(flu); } delay(3000); } void subirGriper(){ Serial.println("Subiendo el griper"); for( int angulo =150; angulo>=120; angulo -=1){ brazo.setPWM(2, 0, anguloApulsar(angulo) ); delay(flu); } delay(3000); } //------------------------------------------------ // servo que controla el gripper //------------------------------------------------ void abrirGriper(){ Serial.println("Abriendo Griper"); for( int angulo =90; angulo>=0; angulo -=1){ brazo.setPWM(3, 0, anguloApulsar(angulo) ); delay(flu); } delay(2000); } void cerrarGriper(){ Serial.println("Cerrando Griper"); for( int angulo =0; angulo<90; angulo +=1){ brazo.setPWM(3, 0, anguloApulsar(0) ); Serial.println(angulo); delay(flu); } delay(2000); }
<div class="col-12 col-lg-12"> <div class="card flex-fill"> <div class="card-header"> <h5 class="card-title mb-0">Registrar Citas</h5> </div> <div class="container"> <form [formGroup]="formularioCitas" (ngSubmit)="registrarCita()"> <div class="row"> <div class="col-lg-4"> <div class="form-group "> <label for="nombreClub">Hora Cita</label> <select class="form-select" aria-label="Default select example" formControlName="Hora" [class.is-invalid]="HoraNovalido"> <option selected value="">Seleccione Hora Cita</option> <option [value]="hora.id" *ngFor="let hora of horas">{{hora.hora}}</option> </select> <small *ngIf="HoraNovalido" class="text-danger">Escoja una hora</small> </div> </div> <div class="col-lg-4"> <div class="form-group"> <label for="direccionClub">Fecha Cita</label> <input type="date" class="form-control has-danger" placeholder="30/12/2022" formControlName="Fecha" [class.is-invalid]="FechaNovalido"> <small *ngIf="FechaNovalido" class="text-danger">Escoja una opcion</small> </div> </div> <div class="col-lg-4"> <div class="form-group"> <label for="direccionClub">Sede</label> <select class="form-select" aria-label="Default select example" formControlName="Sede" [class.is-invalid]="SedeNovalido"> <option selected value="">Seleccione Sede</option> <option [value]="sede.direccion" *ngFor="let sede of sedes">{{sede.nombre}}</option> </select> <small *ngIf="SedeNovalido" class="text-danger">Escoja una opcion</small> </div> </div> <div class="col-lg-4"> <div class="form-group"> <label for="direccionClub">Cliente</label> <select class="form-select" aria-label="Default select example" formControlName="IdUsuarioAgenda" [class.is-invalid]="IdUsuarioAgendaNovalido"> <option selected value="">Seleccione Cliente</option> <option [value]="cliente.id" *ngFor="let cliente of clientes">{{ cliente.nombre + " " + cliente.apellido }}</option> </select> <small *ngIf="IdUsuarioAgendaNovalido" class="text-danger">Escoja una opcion</small> </div> </div> <div class="col-lg-4"> <div class="form-group"> <label for="direccionClub">Barbero</label> <select class="form-select" aria-label="Default select example" formControlName="IdUsuarioAtiende" [class.is-invalid]="IdUsuarioAtiendeNovalido"> <option selected value="">Seleccione Barbero</option> <option [value]="barbero.id" *ngFor="let barbero of barberos">{{ barbero.nombre + " " + barbero.apellido }}</option> </select> <small *ngIf="IdUsuarioAtiendeNovalido" class="text-danger">Escoja una opcion</small> </div> </div> <div class="col-lg-4"> <div class="form-group"> <label for="direccionClub">Estado</label> <select class="form-select" aria-label="Default select example" formControlName="IdEstado" [class.is-invalid]="IdEstadoNovalido"> <option selected value="">Seleccione Estado</option> <option [value]="estado.id" *ngFor="let estado of estados">{{ estado.nombre }}</option> </select> <small *ngIf="IdEstadoNovalido" class="text-danger">Escoja una opcion</small> </div> </div> </div> <br> <div class="row"> <div class="col-lg-3"> <button type="submit" [disabled]="formularioCitas.invalid" class="btn waves-effect waves-light btn-block btn-info pull-right">{{idCitaActualizar === null ?'Registrar':'Actualizar'}}</button> </div> <div class="col-lg-3"> <button type="button" class="btn waves-effect waves-light btn-block btn-info pull-left" (click)="volver()">Volver </button> </div> </div> </form> </div> </div> </div> <!-- <hr> <pre> estado del formu:{{formularioServicio.valid}} <br> Status:{{formularioServicio.status}} </pre> <pre> {{formularioServicio.value |json}} </pre> -->
import PropTypes from "prop-types"; import { Box, FormControl, FormLabel, Input, InputGroup, InputRightAddon, Skeleton, Tooltip, useClipboard, } from "@chakra-ui/react"; import { IoCopy } from "react-icons/io5"; interface PubkeyBoxProps { pubkey: string; loading: boolean; } const PubKeyBox = ({ loading, pubkey }: PubkeyBoxProps) => { const { hasCopied, onCopy } = useClipboard(""); if (loading) { return ( <Box mb={10}> <Skeleton h="20px" /> </Box> ); } return ( <FormControl mb={"30px"}> <FormLabel>Your Public Key:</FormLabel> <InputGroup> <Input value={pubkey} readOnly /> <Tooltip label={hasCopied ? "Copied" : "Copy to clipboard"}> <InputRightAddon cursor={"pointer"} as="button" type="button" bg="blue.500" onClick={onCopy} > <IoCopy fontSize="18px" color="#fff" /> </InputRightAddon> </Tooltip> </InputGroup> </FormControl> ); }; PubKeyBox.propTypes = { pubkey: PropTypes.string.isRequired, loading: PropTypes.bool.isRequired, }; export default PubKeyBox;
package org.solutions.leetcode; import java.util.*; public class MathProblems { int countArrangement = 0; /** * Q. 9 Palindrome Number * <p> * Given an integer x, return true if x is palindrome integer. * An integer is a palindrome when it reads the same backward as forward. * For example, 121 is palindrome while 123 is not. * <p> * tags::math, reverse, palindrome */ public boolean isPalindrome(int x) { if (x < 0) return false; int reversed = 0, remainder, original = x; while (x != 0) { remainder = x % 10; reversed = reversed * 10 + remainder; x /= 10; } return original == reversed; } /** * Q. 50 Pow(x, n) * <p> * Implement pow(x, n), which calculates x raised to the power n (i.e., x^n). * <p> * tags:: math */ public double myPow(double x, int n) { if (n == 0) return 1; double temp = myPow(x, n / 2); double factor = 1; if (n % 2 != 0) { factor = (n > 0) ? x : (1 / x); } return temp * temp * factor; } /** * Q. 70 Climbing Stairs * <p> * You are climbing a staircase. It takes n steps to reach the top. * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? * <p> * tags:: math, fibonacci */ public int climbStairs(int n) { if (n <= 2) return n; int n1 = 1, n2 = 2; for (int i = 3; i <= n; i++) { int temp = n2; n2 = n1 + n2; n1 = temp; } return n2; } /** * Q. 137 Single Number II * <p> * Given an integer array nums where every element appears three times except for one, which appears exactly once. * Find the single element and return it. * <p> * You must implement a solution with a linear runtime complexity and use only constant extra space. * <p> * tags:: math, bitManipulation */ public int singleNumberII(int[] nums) { int seenOnce = 0, seenTwice = 0; for (int num : nums) { seenOnce = ~seenTwice & (seenOnce ^ num); seenTwice = ~seenOnce & (seenTwice ^ num); } return seenOnce; } /** * Q. 191 Number of 1 bits * <p> * Write a function that takes an unsigned integer and returns the number of '1' bits it has * (also known as the Hamming weight). * <p> * Tags:: math */ public int numberOf1Bits(long n) { int count = 0; while (n != 0) { count++; n &= (n - 1); } return count; } /** * Q. 204 Count primes * <p> * Count the number of prime numbers less than a non-negative number, n. */ public int countPrimes(int n) { if (n <= 2) return 0; boolean[] primes = new boolean[n]; Arrays.fill(primes, true); int count = n - 2; for (int i = 2; i <= (int) Math.sqrt(n); i++) { if (primes[i]) { for (int j = i * i; j < n; j += i) { if (primes[j]) { primes[j] = false; count--; } } } } return count; } /** * Q. 227 Basic Calculator II * <p> * Given a string s which represents an expression, evaluate this expression and return its value. * The integer division should truncate toward zero. * You may assume that the given expression is always valid. * All intermediate results will be in the range of [-2^31, 2^31 - 1]. * <p> * Note: You are not allowed to use any built-in function which evaluates strings * as mathematical expressions, such as eval(). * <p> * tags::math, calculator */ public int basicCalculatorII(String s) { Stack<Integer> stack = new Stack<>(); int currNumber = 0, answer = 0; char op = '+'; s = s.replaceAll(" ", ""); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (Character.isDigit(ch)) { currNumber = currNumber * 10 + (ch - '0'); } if (!Character.isDigit(ch) || i == s.length() - 1) { if (op == '-') stack.push(-currNumber); else if (op == '+') stack.push(currNumber); else if (op == '*') stack.push(stack.pop() * currNumber); else if (op == '/') stack.push(stack.pop() / currNumber); op = ch; currNumber = 0; } } while (!stack.isEmpty()) { answer += stack.pop(); } return answer; } /** * Q. 268 Missing Number * <p> * Given an array nums containing n distinct numbers in the range [0, n], * return the only number in the range that is missing from the array. * <p> * Tags:: math */ public int missingNumber(int[] nums) { if (nums == null || nums.length == 0) return -1; int n = nums.length, sum = 0; for (int num : nums) sum += num; return (n * (n + 1) / 2 - sum); } /** * Q. 319 Bulb Switcher * <p> * There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. * On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). * For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.Return the number of * bulbs that are on after n rounds. * <p> * tags:: math */ public int bulbSwitcher(int n) { return (int) Math.sqrt(n); } /** * Q. 326 Power of Three * <p> * Given an integer n, return true if it is a power of three. Otherwise, return false. * An integer n is a power of three, if there exists an integer x such that n == 3^x. * <p> * tags:: math */ public boolean isPowerOfThree(int n) { if (n <= 0) return false; // check decimal part is zero, by taking mod 1 return (Math.log10(n) / Math.log10(3)) % 1 == 0; } /** * Q. 526 Beautiful Arrangement * Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered * a beautiful arrangement if for every i (1 <= i <= n), either of the following is true: * perm[i] is divisible by i. * i is divisible by perm[i]. * Given an integer n, return the number of the beautiful arrangements that you can construct. * <p> * tags::backtracking */ public int countArrangement(int n) { backtrackCountArrangement(new boolean[n + 1], n, 1); return countArrangement; } /** * Q. 575 Distribute Candies * <p> * Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, * so she visited a doctor.The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). * Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while * still following the doctor's advice. * <p> * Given the integer array candyType of length n, * return the maximum number of different types of candies she can eat if she only eats n / 2 of them. * <p> * Tags:: math */ public int distributeCandies(int[] candyType) { if (candyType == null || candyType.length == 0) return 0; Set<Integer> set = new HashSet<>(); for (int c : candyType) { set.add(c); if (set.size() == candyType.length / 2) return candyType.length / 2; } return set.size(); } /** * Q. 645 Set Mismatch * <p> * You have a set of integers s, which originally contains all the numbers from 1 to n. * Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, * which results in repetition of one number and loss of another number. * <p> * You are given an integer array nums representing the data status of this set after the error. * Find the number that occurs twice and the number that is missing and return them in the form of an array. * <p> * Tags:: math */ public int[] findErrorNums(int[] nums) { if (nums == null || nums.length < 2) return new int[]{}; int diff = 0, sqDiff = 0, sum; for (int i = 0; i < nums.length; i++) { diff += i + 1 - nums[i]; sqDiff += (i + 1) * (i + 1) - nums[i] * nums[i]; } sum = sqDiff / diff; return new int[]{(sum - diff) / 2, (sum + diff) / 2}; } /** * Q. 670 Maximum Swap * You are given an integer num. You can swap two digits at most once to get the maximum valued number. * Return the maximum valued number you can get. * <p> * tags::array, math, greedy */ public int maximumSwap(int num) { char[] numArray = Integer.toString(num).toCharArray(); int[] buckets = new int[10]; for (int i = 0; i < numArray.length; i++) buckets[numArray[i] - '0'] = i; for (int i = 0; i < numArray.length; i++) { for (int j = 9; j > numArray[i] - '0'; j--) { if (buckets[j] > i) { char temp = numArray[i]; numArray[i] = numArray[buckets[j]]; numArray[buckets[j]] = temp; return Integer.parseInt(new String(numArray)); } } } return num; } /** * Q. 869 Reordered Power of 2 * <p> * Starting with a positive integer N, we reorder the digits in any order (including the original order) * such that the leading digit is not zero. * Return true if and only if we can do this in a way such that the resulting number is a power of 2. * <p> * tags:: math */ public boolean reorderedPowerOf2(int N) { int[] expectedCount = getCount(N); for (int i = 0; i < 31; i++) if (Arrays.equals(expectedCount, getCount(1 << i))) return true; return false; } /** * Q. 970 Powerful Integers * <p> * Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or * equal to bound. An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0. * You may return the answer in any order. In your answer, each value should occur at most once. * <p> * tags:: math, array */ public List<Integer> powerfulIntegers(int x, int y, int bound) { Set<Integer> ans = new HashSet<>(); int a = (x == 1) ? bound : (int) (Math.log10(bound) / Math.log10(x)); int b = (y == 1) ? bound : (int) (Math.log10(bound) / Math.log10(y)); for (int i = 0; i <= a; i++) { for (int j = 0; j <= b; j++) { int sum = (int) (Math.pow(x, i) + Math.pow(y, j)); if (sum <= bound) ans.add(sum); if (y == 1) break; } if (x == 1) break; } return new ArrayList<>(ans); } /** * Q. 973 K Closest Points to Origin * <p> * Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, * return the k closest points to the origin (0, 0). * The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). * You may return the answer in any order. * The answer is guaranteed to be unique (except for the order that it is in). * <p> * tags:: math, euclidean distance */ public int[][] kClosest(int[][] points, int k) { int[][] answer = new int[k][2]; PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] * b[0] + b[1] * b[1] - a[0] * a[0] - a[1] * a[1]); for (int[] point : points) { pq.add(point); if (pq.size() > k) pq.poll(); } for (int i = 0; i < k; i++) { answer[i] = pq.poll(); } return answer; } /** * Q. 1342 Number of steps to reduce a number to zero * <p> * Given a non-negative integer num, return the number of steps to reduce it to zero. * If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. * <p> * Tags:: math */ public int numberOfSteps(int num) { if (num == 0) return 0; int count = 0; while (num > 1) { count += (num % 2) + 1; num = num >> 1; } return ++count; } /** * Q. 1551 Minimum Operations to Make Array Equal * <p> * You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n). * In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 * to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. * It is guaranteed that all the elements of the array can be made equal using some operations. Given an integer n, * the length of the array. Return the minimum number of operations needed to make all the elements of arr equal. * <p> * tags:: array, Math */ public int minOperations(int n) { return (n * n) >> 2; } /** * Q. 2139 Minimum Moves to Reach Target Score * <p> * You are playing a game with integers. You start with the integer 1 and you want to reach the integer target. * In one move, you can either: * Increment the current integer by one (i.e., x = x + 1). * Double the current integer (i.e., x = 2 * x). * You can use the increment operation any number of times, however, you can only use the double operation at most * maxDoubles times. Given the two integers target and maxDoubles, return the minimum number of moves needed to * reach target starting with 1. * <p> * tags::math */ public int minMoves(int target, int maxDoubles) { int count = 0; while (target > 1 && maxDoubles-- > 0) { count += 1 + (target % 2); target >>= 1; } return count + target - 1; } private void backtrackCountArrangement(boolean[] used, int n, int pos) { if (pos > n) { countArrangement++; return; } for (int i = 1; i <= n; i++) { if (!used[i] && (i % pos == 0 || pos % i == 0)) { used[i] = true; backtrackCountArrangement(used, n, pos + 1); used[i] = false; } } } /** * Given a number, return an array, with occurrence of each digit */ private int[] getCount(int num) { int[] count = new int[10]; while (num > 0) { count[num % 10]++; num /= 10; } return count; } }
const PatientRepository = require('../repositories/PatientRepository'); const patientQueryParser = require('../helpers/patientQueryParser'); class PatientController { async index(request, response) { const patients = await PatientRepository.find(); const patientsParsed = patientQueryParser(patients); response.json(patientsParsed); } async show(request, response) { const { id } = request.params; const patient = await PatientRepository.findById(id); if (!patient) { return response.status(404).json({ error: 'Patient not find' }); } const [patientParsed] = patientQueryParser([patient]); response.json(patientParsed); } async store(request, response) { const { name, email, sex, phone } = request.body; if (!name || !email) { return response.status(400).json({ error: `'name' and 'email' is required` }); } const emailExists = await PatientRepository.findByEmail(email); if (emailExists) { return response.status(400).json({ error: 'Email is alread in use' }); } await PatientRepository.create({ name, email, sex, phone }); response.json(request.body) } async update(request, response) { const { id } = request.params; const { name, email, sex, phone } = request.body; const patientExists = await PatientRepository.findById(id); if (!patientExists) { return response.status(404).json({ error: 'Patient not find' }); } if (!name || !email) { return response.status(400).json({ error: `'name' and 'email' is required` }); } const patientByEmail = await PatientRepository.findByEmail(email); if (patientByEmail && patientByEmail.id !== id) { return response.status(400).json({ error: 'Email is already in use' }); } await PatientRepository.update(id, { name, email, sex , phone }); response.json(request.body) } async delete(request, response) { const { id } = request.params; await PatientRepository.delete(id); response.sendStatus(204); } } module.exports = new PatientController()
import React, { useState, useEffect } from "react"; import { NavLink, useNavigate } from "react-router-dom"; import { FaBars, FaTimes } from "react-icons/fa"; import "../../assets/styles/components/NavBar/NavBarStyle.css"; import { UserAuth } from "../../context/AuthContext"; import { getUserProfileDocument } from "../../firebase/getUserProfileDocument"; import defaultAvatar from "../../assets/images/defaultAvatar.png"; import {useOutsideClick} from "../../hooks/useOutsideClick"; const NavBar = () => { const [menuOpen, setMenuOpen] = useState(false); const { user, logout } = UserAuth(); const [profileImage, setProfileImage] = useState(null); const [firstName, setFirstName] = useState(""); const [lastName, setLastName] = useState(""); const [email, setEmail] = useState(""); const [gender, setGender] = useState(""); const [city, setCity] = useState(""); const [country, setCountry] = useState(""); const [registrationTime, setRegistrationTime] = useState(""); const navigate = useNavigate(); const avatarURL = defaultAvatar; const menuRef = useOutsideClick(() => { setMenuOpen(false); }); const handleMenuToggle = () => { setMenuOpen(!menuOpen); }; const handleProfile = () => { navigate("/profile"); setMenuOpen(false); }; useEffect(() => { const fetchData = async () => { if (user && user.uid) { try { const userProfile = await getUserProfileDocument(user.uid); if (userProfile && userProfile.profile && userProfile.profile) { const { FirstName = "", LastName = "", email: userEmail = "", Gender = "", City = "", Country = "", ProfileImage, } = userProfile.profile; setFirstName(FirstName); setLastName(LastName); setEmail(userEmail); setGender(Gender); setCity(City); setCountry(Country); setProfileImage(ProfileImage || null); console.log(lastName, email, gender, city, country, registrationTime); // Postavite i ostale vrijednosti, npr. registrationTime setRegistrationTime(userProfile.theRest?.registrationTime || ""); } else { console.error("Profile data is missing or incomplete."); } } catch (error) { console.error("Error fetching user profile:", error); } } }; fetchData(); }, [user ]); return ( <div className="component-navbar" > <div className="navbar" ref={menuRef}> <div className="logo"> <h1>Spendy</h1> </div> <div className="menu-icon" onClick={handleMenuToggle}> {menuOpen ? <FaTimes /> : <FaBars />} </div> <ul className={`nav-links ${menuOpen ? "active" : ""}`} > <li> <NavLink to="/">Home</NavLink> </li> {user ? ( <> <li> <NavLink to="/dashboard">Dashboard</NavLink> </li> <li> <NavLink to="/profile">Profile</NavLink> </li> <li onClick={logout}> <NavLink to="/">Logout</NavLink> </li> </> ) : ( <> <li> <NavLink to="/signin">Sign In</NavLink> </li> <li> <NavLink to="/signup">Sign Up</NavLink> </li> </> )} <li> <NavLink to="/about">About</NavLink> </li> <li> <NavLink to="/contact">Contact</NavLink> </li> <li> <NavLink to="/privacyandterms">Privacy & Terms</NavLink> </li> {user && ( <div className="profile-info" onClick={handleProfile}> <div className="profile-picture" > {profileImage ? ( <img src={profileImage} alt="Profile" style={{maxHeight: "100px", maxWidth: "100px"}} /> ) : ( <img src={avatarURL} alt="Avatar" style={{maxHeight: "100px", maxWidth: "100px"}} /> )} </div> <div className="name-profile"> <p>welcome, </p> <p>{firstName || user.email}</p> </div> </div> )} </ul> </div> </div> ); }; export default NavBar;
# Hand note ### @SpringBootApplication Spring cần biết nơi để khởi chạy ngay trên hàm gọi > SpringApplication.run(App.class, args); spring đặt tên cho container chứa các bean (dependance) là ```ApplicationContext``` ``` @SpringBootApplication public class App { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(App.class, args); // Khi chạy xong, lúc này context sẽ chứa các Bean có đánh // dấu @Component. // Lấy Bean ra bằng cách Outfit outfit = context.getBean(Outfit.class); // In ra để xem thử nó là gì System.out.println("Out Instance: " + outfit); // xài hàm wear() outfit.wear(); Girl girl = context.getBean(Girl.class); System.out.println("Girl Instance: " + girl); System.out.println("Girl Outfit: " + girl.outfit); girl.outfit.wear(); } } ``` ### @Autowired Thuộc tính Outfit của Girl bởi Annotation @Autowired. Spring Boot tự động inject một instance của Outfit vào thuộc tính này khi khởi tạo Girl. ``` @Component public class Girl { @Autowired Outfit outfit; public Girl(Outfit outfit) { this.outfit = outfit; } // GET // SET } ``` > Tất cả những Bean được quản lý trong ApplicationContext đều chỉ được tạo ra một lần duy nhất và khi có Class yêu cầu @Autowired thì nó sẽ lấy đối tượng có sẵn trong ApplicationContext để inject vào. Trong trường hợp bạn muốn mỗi lần sử dụng là một instance hoàn toàn mới. Thì hãy đánh dấu @Component đó bằng @Scope("prototype") ``` @Component @Scope("prototype") public class Bikini implements Outfit { @Override public void wear() { System.out.println("Mặc bikini"); } } ``` Sau khi tìm thấy một class đánh dấu @Component. thì quá trình inject Bean xảy ra theo cách như sau: 1. Nếu Class không có hàm Constructor hay Setter. Thì sẽ sử dụng Java Reflection để đưa đối tượng vào thuộc tính có đánh dấu @Autowired. 2. Nếu có hàm Constructor thì sẽ inject Bean vào bởi tham số của hàm 3. Nếu có hàm Setter thì sẽ inject Bean vào bởi tham số của hàm ``` @Component public class Girl { // Đánh dấu để Spring inject một đối tượng Outfit vào đây @Autowired Outfit outfit; // Spring sẽ inject outfit thông qua Constructor trước public Girl() { } // Nếu không tìm thấy Constructor thoả mãn, nó sẽ thông qua setter public void setOutfit(Outfit outfit) { this.outfit = outfit; } // GET // SET } @Component public class Girl { // Đánh dấu để Spring inject một đối tượng Outfit vào đây Outfit outfit; // Spring sẽ inject outfit thông qua Constructor trước public Girl() { } @Autowired // Nếu không tìm thấy Constructor thoả mãn, nó sẽ thông qua setter public void setOutfit(Outfit outfit) { this.outfit = outfit; } // GET // SET } ``` Khi có nhiều hơn 1 dữ liệu có thể autowired thì cần gán cho 1 cái là ```@Primary``` lúc này sẽ gán auto là primary class, nhưng nếu ở component gọi autowired gán ```@Qualifier()``` thì sẽ chọn cái được gán
package com.tsystems.tm.acc.ta.team.upiter.ontcommissioning; import com.tsystems.tm.acc.data.upiter.models.accessline.AccessLineCase; import com.tsystems.tm.acc.data.upiter.models.ont.OntCase; import com.tsystems.tm.acc.ta.data.osr.models.AccessLine; import com.tsystems.tm.acc.ta.data.osr.models.Ont; import com.tsystems.tm.acc.ta.robot.osr.AccessLineRiRobot; import com.tsystems.tm.acc.ta.robot.osr.HomeIdManagementRobot; import com.tsystems.tm.acc.ta.robot.osr.OntOltOrchestratorRobot; import com.tsystems.tm.acc.ta.team.upiter.UpiterTestContext; import com.tsystems.tm.acc.ta.testng.GigabitTest; import com.tsystems.tm.acc.tests.osr.access.line.resource.inventory.v5_38_1.client.model.AccessLineStatus; import com.tsystems.tm.acc.tests.osr.access.line.resource.inventory.v5_38_1.client.model.OntState; import com.tsystems.tm.acc.tests.osr.access.line.resource.inventory.v5_38_1.client.model.ProfileState; import com.tsystems.tm.acc.tests.osr.access.line.resource.inventory.v5_38_1.client.model.SubscriberNeProfileDto; import com.tsystems.tm.acc.tests.osr.ont.olt.orchestrator.v2_16_0.client.model.*; import de.telekom.it.t3a.kotlin.log.annotations.ServiceLog; import io.qameta.allure.Description; import io.qameta.allure.Epic; import io.qameta.allure.TmsLink; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.tsystems.tm.acc.ta.data.upiter.UpiterConstants.*; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; @ServiceLog({ ONT_OLT_ORCHESTRATOR_MS, ACCESS_LINE_RESOURCE_INVENTORY_MS, DECOUPLING_MS, APIGW_MS }) @Epic("ONT Processes on Adtran") public class AdtranOntCommissioning extends GigabitTest { private final AccessLineRiRobot accessLineRiRobot = new AccessLineRiRobot(); private final OntOltOrchestratorRobot ontOltOrchestratorRobot = new OntOltOrchestratorRobot(); private final HomeIdManagementRobot homeIdManagementRobot = new HomeIdManagementRobot(); private final UpiterTestContext context = UpiterTestContext.get(); private AccessLine accessLine; private Ont ontSerialNumber; @BeforeClass public void loadContext() throws InterruptedException { accessLineRiRobot.clearDatabase(); Thread.sleep(1000); accessLineRiRobot.fillDatabaseForAdtranOltCommissioning(); accessLine = context.getData().getAccessLineDataProvider().get(AccessLineCase.adtranOntAccessLine); ontSerialNumber = context.getData().getOntDataProvider().get(OntCase.adtranOntSerialNumber); } @Test @TmsLink("DIGIHUB-91170") @Description("Adtran Reservation ONT resource") public void adtranOntReservation() { //Get 1 Free HomeId from pool accessLine.setHomeId(homeIdManagementRobot.generateHomeid().getHomeId()); //Start access line registration PortAndHomeIdDto portAndHomeIdDto = new PortAndHomeIdDto() .vpSz(accessLine.getOltDevice().getVpsz()) .fachSz(accessLine.getOltDevice().getFsz()) .portNumber(accessLine.getPortNumber()) .homeId(accessLine.getHomeId()); OperationResultLineIdDto callback = ontOltOrchestratorRobot.reserveAccessLineByPortAndHomeId(portAndHomeIdDto); // check callback assertNull("Callback returned an error", callback.getError()); assertTrue(callback.getSuccess(), "Callback returned an error"); assertNotNull(callback.getResponse().getLineId(), "Callback didn't return a LineId"); assertEquals("HomeId returned in the callback is incorrect", callback.getResponse().getHomeId(), accessLine.getHomeId()); // check alri accessLine.setLineId(callback.getResponse().getLineId()); assertEquals("AccessLine state is incorrect", AccessLineStatus.ASSIGNED, accessLineRiRobot.getAccessLineStateByLineId(accessLine.getLineId())); } @Test(dependsOnMethods = "adtranOntReservation") @TmsLink("DIGIHUB-91173") @Description("Adtran Registeration ONT resource") public void adtranOntRegistration() { OperationResultLineIdSerialNumberDto callback = ontOltOrchestratorRobot.registerOnt(accessLine, ontSerialNumber); // check callback assertNull("Callback returned an error", callback.getError()); assertTrue(callback.getSuccess(), "Callback returned an error"); assertEquals("LineId returned in the callback is incorrect", accessLine.getLineId(), callback.getResponse().getLineId()); assertEquals("ONT S/N returned in the callback is incorrect", ontSerialNumber.getSerialNumber(), callback.getResponse().getSerialNumber()); // check alri SubscriberNeProfileDto subscriberNEProfile = accessLineRiRobot.getSubscriberNEProfile(accessLine.getLineId()); assertNotNull(subscriberNEProfile, ""); assertEquals("ONT S/N on the AccessLine is incorrect", subscriberNEProfile.getOntSerialNumber(), ontSerialNumber.getSerialNumber()); assertEquals("SubscriberNeProfile state is incorrect", subscriberNEProfile.getState(), ProfileState.ACTIVE); assertEquals("SubscriberNeProfile ONT state is incorrect", subscriberNEProfile.getOntState(), OntState.UNKNOWN); } @Test(dependsOnMethods = {"adtranOntReservation", "adtranOntRegistration"}) @TmsLink("DIGIHUB-91174") @Description("Adtran ONT Connectivity test") public void adtranOntTest() { //test Ont OperationResultOntTestDto callback = ontOltOrchestratorRobot.testOnt(accessLine.getLineId()); // check callback assertNull("Callback returned an error", callback.getError()); assertTrue(callback.getSuccess(), "Callback returned an error"); assertNotNull(callback.getResponse().getLastDownCause(), "Callback didn't return LastDownCause"); assertNotNull(callback.getResponse().getLastDownTime(), "Callback didn't return LastDownTime"); assertNotNull(callback.getResponse().getLastUpTime(), "Callback didn't return LastUpTime"); assertEquals("ActualRunState returned in the callback is incorrect", com.tsystems.tm.acc.tests.osr.ont.olt.orchestrator.v2_16_0.client.model.OntState.ONLINE, callback.getResponse().getActualRunState()); //todo add check for onuid ontOltOrchestratorRobot.updateOntState(accessLine); // check alri SubscriberNeProfileDto subscriberNEProfile = accessLineRiRobot.getSubscriberNEProfile(accessLine.getLineId()); assertNotNull(subscriberNEProfile, "SubscriberNeProfile is not present"); assertEquals("Ont State on the AccessLine is incorrect", subscriberNEProfile.getOntState(), OntState.ONLINE); } @Test(dependsOnMethods = {"adtranOntReservation", "adtranOntRegistration", "adtranOntTest"}) @TmsLink("DIGIHUB-91178") @Description("Adtran Change ONT serial number") public void adtranOntChange() { //check SN assertEquals("ONT S/N on the AccessLine is incorrect", ontSerialNumber.getSerialNumber(), accessLineRiRobot.getSubscriberNEProfile(accessLine.getLineId()).getOntSerialNumber()); OperationResultLineIdSerialNumberDto callback = ontOltOrchestratorRobot.changeOntSerialNumber(accessLine.getLineId(), ontSerialNumber.getNewSerialNumber()); // check callback assertNull("Callback returned an error", callback.getError()); assertTrue(callback.getSuccess(), "Callback returned an error"); assertEquals("LineId returned in the callback is incorrect", accessLine.getLineId(), callback.getResponse().getLineId()); assertEquals("ONT S/N returned in the callback is incorrect", ontSerialNumber.getNewSerialNumber(), callback.getResponse().getSerialNumber()); // check alri assertEquals("New ONT S/N on the AccessLine is incorrect", ontSerialNumber.getNewSerialNumber(), accessLineRiRobot.getSubscriberNEProfile(accessLine.getLineId()).getOntSerialNumber()); } @Test(dependsOnMethods = {"adtranOntReservation", "adtranOntRegistration", "adtranOntTest", "adtranOntChange"}) @TmsLink("DIGIHUB-91179") @Description("Adtran ONT Termination rollback to reservation = false") public void adtranOntTermination() { OperationResultVoid callback = ontOltOrchestratorRobot.decommissionOnt(accessLine); // check callback assertTrue(callback.getSuccess(), "Callback returned an error"); assertNull("Callback returned an error", callback.getError()); // check alri assertEquals("AccessLine state in incorrect", accessLineRiRobot.getAccessLineStateByLineId(accessLine.getLineId()), AccessLineStatus.WALLED_GARDEN); assertEquals("HomeId on the AccessLine is incorrect", accessLineRiRobot.getAccessLinesByLineId(accessLine.getLineId()).get(0).getHomeId(), accessLine.getHomeId()); assertEquals("DefaultNeProfile state is incorrect", accessLineRiRobot.getAccessLinesByLineId(accessLine.getLineId()).get(0).getDefaultNeProfile().getState(), ProfileState.ACTIVE); SubscriberNeProfileDto subscriberNEProfile = accessLineRiRobot.getSubscriberNEProfile(accessLine.getLineId()); assertNull("SubscriberNeProfile was not deleted", subscriberNEProfile); } }
package net.vowed.core.storage; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.UUID; /** * Store meta-data in an ItemStack as attributes. * * @author Kristian */ public class AttributeStorage { public static final UUID storageUUID = UUID.fromString("92bd6fd9-0b5c-4bd1-988c-8afa6a063822"); private ItemStack target; private final UUID uniqueKey; private AttributeStorage(ItemStack target, UUID uniqueKey) { this.target = Preconditions.checkNotNull(target, "target cannot be NULL"); this.uniqueKey = Preconditions.checkNotNull(uniqueKey, "uniqueKey cannot be NULL"); } /** * Construct a new attribute storage system. * <p/> * The key must be the same in order to retrieve the same data. * * @param target - the getItem stack where the data will be stored. * @param uniqueKey - the unique key used to retrieve the correct data. */ public static AttributeStorage newTarget(ItemStack target, UUID uniqueKey) { return new AttributeStorage(target, uniqueKey); } /** * Retrieve the data stored in the getItem's attribute. * * @param returnValue - the default value to return if no data can be found. * @return The stored data, or defaultValue if not found. */ public String getData(String returnValue) { Attributes.Attribute current = getAttribute(new Attributes(target), uniqueKey); if (current != null) { return current.getName(); } else { return returnValue; } } /** * Determine if we are storing any data. * * @return TRUE if we are, FALSE otherwise. */ public boolean hasData() { return getAttribute(new Attributes(target), uniqueKey) != null; } /** * Set the data stored in the attributes. * * @param data - the data. */ public void setData(String data) { Attributes attributes = new Attributes(target); Attributes.Attribute current = getAttribute(attributes, uniqueKey); if (current == null) { attributes.add( Attributes.Attribute.newBuilder(). name(data). amount(getBaseDamage(target)). uuid(uniqueKey). operation(Attributes.Operation.ADD_NUMBER). type(Attributes.AttributeType.GENERIC_ATTACK_DAMAGE). build() ); } else { current.setName(data); } ItemStack item = attributes.getStack(); ItemMeta meta = item.getItemMeta(); meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); item.setItemMeta(meta); this.target = item; } /** * Retrieve the base damage of the given getItem. * * @param stack - the stack. * @return The base damage. */ private int getBaseDamage(ItemStack stack) { // Yes - we have to hard code these values. Cannot use Operation.ADD_PERCENTAGE either. switch (stack.getType()) { case WOOD_SWORD: return 4; case GOLD_SWORD: return 4; case STONE_SWORD: return 5; case IRON_SWORD: return 6; case DIAMOND_SWORD: return 7; case WOOD_AXE: return 3; case GOLD_AXE: return 3; case STONE_AXE: return 4; case IRON_AXE: return 5; case DIAMOND_AXE: return 6; default: return 0; } } /** * Retrieve the target stack. May have been changed. * * @return The target stack. */ public ItemStack getTarget() { return target; } /** * Retrieve an attribute by UUID. * * @param attributes - the attribute. * @param id - the UUID to search for. * @return The first attribute associated with this UUID, or NULL. */ private Attributes.Attribute getAttribute(Attributes attributes, UUID id) { for (Attributes.Attribute attribute : attributes.values()) { if (Objects.equal(attribute.getUUID(), id)) { return attribute; } } return null; } }
#importing the library we need to use library(RMySQL) library(sqldf) library(dplyr) library(ggplot2) library(recommenderlab) #connecting to mysql database connect <- dbConnect(MySQL(), user='simha', password='Sbdf2021!', dbname='nextbook4u', host='localhost') #importing the tables with sqldf library #books <- sqldf("SELECT * FROM `bx-books`", con=connect) #users <- sqldf("SELECT * FROM `bx-users`", con=connect) #ratings <- sqldf("SELECT * FROM `bx-book-ratings`", con=connect) #importing the tables with dbSendQuery library books <- dbSendQuery(connect, "SELECT * FROM `bx-books`") books <- fetch(books, n=-1) users <- dbSendQuery(connect, "SELECT * FROM `bx-users`") users <- fetch(users, n=-1) ratings <- dbSendQuery(connect, "SELECT * FROM `bx-book-ratings`") ratings <- fetch(ratings, n=-1) #removing duplicates ratings <- unique(ratings) books <- unique(books) users <- unique(users) # removing all the ratings that not exist in users or books book <- books[which(books$'ISBN' %in% ratings$'ISBN'),] user <-users[which(users$'User-ID' %in% ratings$'User-ID'),] rating <- ratings[which(ratings$'User-ID' %in% users$'User-ID'),] rating <- ratings[which(ratings$'ISBN' %in% books$'ISBN'),] #book <- books[which(ratings$'ISBN' %in% books$'ISBN'),] #ratings$"User-ID" <- as.factor(ratings$"User-ID") #ratings$'ISBN' <- as.factor(ratings$'ISBN') #removing users or books outliers rating.hist <- table(rating$'User-ID') rating.hist <- as.data.frame(rating.hist) head(rating.hist) correct.users.index <- which(rating.hist$Freq > 7) rating.afer.ouliers <- rating.hist[correct.users.index,] rating.afer.ouliers.3.vars <- rating[which(rating$'User-ID' %in% rating.afer.ouliers$Var1),]#s rating.afer.ouliers.3.vars <- rating.afer.ouliers.3.vars[which(rating.afer.ouliers.3.vars$'Book-Rating'>0),] head(rating.afer.ouliers.3.vars) ### books clearings rating.hist2 <- table(rating$'ISBN') #s rating.hist2 <- as.data.frame(rating.hist2) head(rating.hist2) correct.users.index2 <- which(rating.hist2$Freq > 7 & rating.hist2$Freq< 100) rating.afer.ouliers2 <- rating.hist2[correct.users.index2,] rating.afer.ouliers.3.vars2 <- rating.afer.ouliers.3.vars[which(rating.afer.ouliers.3.vars$ISBN %in% rating.afer.ouliers2$Var1),] #rating.afer.ouliers.3.vars2 <- rating.afer.ouliers.3.vars2[which(rating.afer.ouliers.3.vars2$'ISBN'>0),] head(rating.afer.ouliers.3.vars2) # Few checking before running the CF dim(rating.afer.ouliers.3.vars2) ratings.df <- rating.afer.ouliers.3.vars2 paste("Number of users", length(unique(ratings.df$'User-ID'))) paste("Number of users", length(unique(ratings.df$ISBN))) # converting to real rating matrix type ratings.matrix <- as(ratings.df, "realRatingMatrix") str(ratings.matrix) ################################################## # _ # | | # | | ___ __ _ __ # | |/ / '_ \| '_ \ # | <| | | | | | | # |_|\_\_| |_|_| |_| # ################################################## # knn function .knn <- function(sim, k) lapply(1:nrow(sim), FUN = function(i) head(order(sim[i,], decreasing = TRUE, na.last = NA), k)) # splitting the data into train 80% and test 20% eval_sets <- evaluationScheme( data = ratings.matrix, method = "split", train = 0.8, given = -1, goodRating = 6, k = 5 ) str(eval_sets) # Running the recommender system eval_recommender.UB <- Recommender( data = getData(eval_sets, "train"), method = "UBCF", parameter = list(method = "Euclidean", normalize="Z-score") ) str(eval_recommender.UB) eval_recommender.UB@model$weighted <- FALSE ###################################################### # _ _ _ # | (_) | | # _ __ _ __ ___ __| |_ ___| |_ # | '_ \| '__/ _ \/ _` | |/ __| __| # | |_) | | | __/ (_| | | (__| |_ # | .__/|_| \___|\__,_|_|\___|\__| # | | # |_| # ###################################################### ########## top 10 #################################### R.UB <- predict(eval_recommender.UB, newdata = getData(eval_sets, "known"), n = 10, type = "ratings" ) eval_accuracy <- calcPredictionAccuracy(x = R.UB, data = getData(eval_sets, "unknown"), byUser = TRUE) eval_accuracy R.UB.RECOMMEND <- my.predict(eval_recommender.UB@model, newdata = getData(eval_sets, "known"), n = 10, type = "topNList" ) library(data.table) h<-R.UB.RECOMMEND@items[1:50] R.UB.RECOMMEND.top10 <- as.data.frame(h) h ################## ### my predict ### ################## my.predict <- function (model, newdata, n = 10, data = NULL, type = c("topNList", "ratings", "ratingMatrix"), ...) { print(newdata) type <- match.arg(type) newdata_id <- NULL if (is.numeric(newdata)) { if (model$sample) stop("(EE) User id in newdata does not work when sampling is used!") newdata_id <- newdata newdata <- model$data[newdata, ] } else { if (ncol(newdata) != ncol(model$data)) stop("(EE) number of items in newdata does not match model.") if (!is.null(model$normalize)) newdata <- normalize(newdata, method = model$normalize) } cat('(II) running similarity() calculation\n') sim <- similarity(newdata, model$data, method = model$method, min_matching = model$min_matching_items, min_predictive = model$min_predictive_items) cat('(II) similarity() done\n') if (!is.null(newdata_id)) sim[cbind(seq(length(newdata_id)), newdata_id)] <- NA cat(paste('(II) creating knn with', model$nn ,'neighbors\n')) neighbors <- .knn(sim, model$nn) cat('(II) knn done\n') if (model$weighted) { cat ('(II) weigh the ratings by similarities\n') s_uk <- sapply(1:nrow(sim), FUN = function(i) sim[i, neighbors[[i]]]) if (!is.matrix(s_uk)) s_uk <- as.matrix(t(s_uk)) ratings <- t(sapply(1:nrow(newdata), FUN = function(i) { r_neighbors <- as(model$data[neighbors[[i]]], "dgCMatrix") Cols.1 <- drop(as(crossprod(r_neighbors, s_uk[, i]), "matrix")) Cols.2 <- drop(as(crossprod(!dropNAis.na(r_neighbors), s_uk[, i]), "matrix")) Cols.1 / Cols.2 })) ratings[!is.finite(ratings)] <- NA cat ('(II) done weigh the ratings\n') } else { cat ("(II) copy the ratings across the user's knn\n") ratings <- t(sapply(1:nrow(newdata), FUN = function(i) { r_neighbors <- as(model$data[neighbors[[i]]], "dgCMatrix") Cols.1 <- colSums(r_neighbors) Cols.2 <- colSums(!dropNAis.na(r_neighbors)) Cols.1 / Cols.2 })) ratings[!is.finite(ratings)] <- NA cat ("(II) copy the ratings ... done\n") } rownames(ratings) <- rownames(newdata) ratings <- new("realRatingMatrix", data = dropNA(ratings), normalize = getNormalize(newdata)) cat ('(II) de-normalize the ratings (back to rating scale)\n') ratings <- denormalize(ratings) cat ('(II) de-normalize done\n') returnRatings(ratings, newdata, type, n) } # running the prediction model my.predict.model <- my.predict(eval_recommender.UB@model, newdata = getData(eval_sets, "known"), n = 10, type = "ratings") # RMSE table output from the prediction model eval_accuracy_ubcf <- calcPredictionAccuracy(x = my.predict.model, data = getData(eval_sets, "unknown"), byUser = TRUE) View(eval_accuracy_ubcf[,'RMSE']) v <- as.data.frame(eval_accuracy_ubcf[,'RMSE']) v1 <- as.data.frame(eval_accuracy[,'RMSE']) v1 <- na.omit(v1) # IBCF eval_sets <- subsetData(eval_sets) eval_sets@data@data <- eval_sets@data@data[1:100,1:100] eval_sets@knownData@data <- eval_sets@knownData@data[1:100,1:100] eval_sets@unknownData@data <- eval_sets@unknownData@data[1:100,1:100] eval_recommender.IB <- Recommender( data = getData(eval_sets, "train"), method = "IBCF", parameter = list(method = "Cosine", normalize="Z-score") ) str(eval_recommender.IB) eval_recommender.IB@model$weighted <- FALSE eval_prediction_ibcf <- my.predict(eval_recommender.IB@model, newdata = getData(eval_sets, "known"), n = 10, type = "ratings") eval_accuracy_ibcf <- calcPredictionAccuracy(x = eval_prediction_ibcf, data = getData(eval_sets, "unknown"), byUser = FALSE) ##### saving #### save(eval_recommender.UB, file = "model.Rdata")
import { Component, Inject, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { EditCrop, NewCrop } from 'src/app/models/crop'; import { CropsService } from 'src/app/services/crops.service'; import { LoginService } from 'src/app/services/login.service'; @Component({ selector: 'app-add-crop', templateUrl: './add-crop.component.html', styleUrls: ['./add-crop.component.css'] }) export class AddCropComponent implements OnInit { public title: string = "Nuevo Cultivo"; public btnTxt: String = "Agregar"; public addCropForm!: FormGroup; userID: number = 0; constructor(private formBuider: FormBuilder, private cropsService: CropsService, private loginService: LoginService, @Inject(MAT_DIALOG_DATA) public editData: any, private dialogRef: MatDialogRef<AddCropComponent>) { } ngOnInit(): void { this.addCropForm = this.initForm(); if(this.editData){ this.title = "Editar Cultivo" this.btnTxt = "Actualizar" this.addCropForm.controls['id'].setValue(this.editData.id) this.addCropForm.controls['name'].setValue(this.editData.name); this.addCropForm.controls['description'].setValue(this.editData.description); } } action(){ console.log(this.btnTxt + " - " + this.editData) if(this.btnTxt === 'Actualizar'){ this.editCrop(); }else{ this.addCrop(); } } editCrop(){ const editCrop: EditCrop = { id: this.addCropForm.value.id, name: this.addCropForm.value.name, description: this.addCropForm.value.description } this.cropsService.editCrop(editCrop).subscribe({ next: (res) =>{ this.dialogRef.close('updateCrop') }, error: (err) =>{ this.dialogRef.close('updateCrop') console.log(err) } }) } addCrop(){ this.loginService.actualUserInfo$.subscribe(userInfo => this.userID = userInfo.userID) const newCrop: NewCrop = { userID: this.userID, name: this.addCropForm.value.name, description: this.addCropForm.value.description } this.cropsService.addCrop(newCrop).subscribe(data =>{ this.dialogRef.close('save') }); } initForm(): FormGroup{ return this.formBuider.group({ id:[], name: ['', Validators.required], description: ['', Validators.required] }) } }
import React, { Component } from "react"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import logo from "../img/spotfinder_logo_inverse_color_drk_lt.jpg"; import { VscGithubInverted } from "react-icons/vsc"; class Header extends Component { renderContent() { switch (this.props.auth) { case null: return; case false: return ( <li className="nav-top"> <a className="nav-link-top" href="/auth/github"> <VscGithubInverted className="github-icon" /> Login with GitHub </a> </li> ); default: return [ <li className="nav-top d-flex align-items-center" key="1"> <img src={this.props.auth.avatarImgUrl} alt={this.props.auth.username} className="user-profile-image" /> <Link to="/profile" className="nav-link-top"> {this.props.auth.username} </Link> </li>, <li className="nav-top" key="2"> <a className="nav-link-log" href="/api/logout" style={{ fontSize: "12px", marginTop: "4px" }} > Logout </a> </li> ]; } } renderSubNavbar() { return ( <nav className="navbar navbar-expand-lg navbar-light"> <div className="container"> <ul className="navbar-nav ml-auto"> <li> <Link to="/search-page" className="nav-link"> Search Projects </Link> </li> <li> <Link to="/help-page" className="nav-link"> Help </Link> </li> {/* Add more links as needed */} </ul> </div> </nav> ); } render() { return ( <div> <nav className="navbar custom-navbar navbar-expand-lg navbar-light"> <div className="container"> {" "}{/* Added container for center alignment */} <Link to={this.props.auth ? "/" : "/"} className="navbar-brand"> <img src={logo} alt="SpotFinder Logo" className="spotfinder-logo" /> <span>SpotFinder</span> </Link> <ul className="navbar-nav ml-auto "> {" "}{/* ml-auto to push content to the right */} {this.renderContent()} </ul> </div> </nav> {this.renderSubNavbar()} </div> ); } } // handle authorization state data function mapStateToProps({ auth }) { return { auth }; } export default connect(mapStateToProps)(Header);
import React, { useState } from 'react'; import { useLoaderData, useNavigation } from 'react-router-dom'; import LoadingSppiner from './LoadingSppiner'; const BookDetails = () => { const book = useLoaderData(); // console.log(book) const { title, image, price, authors, desc, language, pages, publisher, rating, year, url } = book; // read less and more btn handler const[ fold, setFold] = useState(true); // loading spinner handler const navigation = useNavigation() console.log(navigation.state); if(navigation.state ==='loading'){ return <LoadingSppiner/>} // main function return return ( <div> <div className='my-container'> {/* Container Box */} <div className='flex flex-col max-w-screen-lg overflow-hidden bg-white border rounded shadow-sm lg:flex-row sm:mx-auto'> {/* Image Container */} <div className=' lg:w-1/2 h-full'> <img src={image} alt='book cover' className='object-cover w-full lg:h-full' /> </div> {/* Details Container */} <div className=' p-8 bg-white lg:p-16 lg:pl-10 lg:w-1/2'> <div> <p className='badge'>Brand new</p> </div> <h5 className='mb-3 text-3xl font-extrabold leading-none sm:text-4xl'> {title} </h5> <p className=' text-gray-900'>Authors: {authors.substring(0, 50)}</p> <p className=' text-gray-900'>Publisher: {publisher}</p> <p className=' text-gray-900'>Year: {year}</p> <p className='mb-5 text-gray-900'>Rating: {rating}</p> <div className='flex gap-5 mt-8 items-center mb-5'> <a href={url} target='_blank' className='btn'> Buy Now </a> <p className='items-center font-extrabold text-gray-600 '> Price: {price} </p> </div> { fold ? ( <> <p className=' text-gray-900'> {desc.substring(0, 100)} ... <span onClick={ ()=>setFold(!fold)} className=' px-3 py-1 rounded cursor-pointer m-2 text-blue-800 font-bold'> Read More</span> </p> </>) : (<> <p className=' text-gray-600'> {desc} <span onClick={ ()=>setFold(!fold)} className=' px-2 py-1 rounded cursor-pointer m-2 text-blue-800 font-bold' >Read Less</span></p> </> ) } </div> </div> </div> </div> ); }; export default BookDetails;
from scipy.optimize import fmin import pandas as pd import numpy as np import matplotlib.pyplot as plt dd = pd.read_csv('fred_table.csv') df = dd.copy() df.style.format({'Maturity': '{:,.0f}'.format,'Yield': '{:,.2%}'}) sf = df.copy() sf = sf.dropna() sf1 = sf.copy() sf1['Y'] = round(sf['Yield']*1,4) sf = sf.style.format({'Maturity': '{:,.2f}'.format,'Yield': '{:,.4%}'}) print(sf1) import matplotlib.pyplot as plt import matplotlib.markers as mk import matplotlib.ticker as mtick fontsize=15 fig = plt.figure(figsize=(13,7)) plt.title("Nelson-Siegel Model - Unfitted Yield Curve",fontsize=fontsize) ax = plt.axes() ax.set_facecolor("black") fig.patch.set_facecolor('white') X = sf1["Maturity"] Y = sf1["Y"] plt.scatter(X, Y, marker="o", c="blue") plt.xlabel('Time (Months)',fontsize=fontsize) plt.ylabel('Yield',fontsize=fontsize) ax.yaxis.set_major_formatter(mtick.PercentFormatter()) ax.xaxis.set_ticks(np.arange(0, 360, 12)) ax.yaxis.set_ticks(np.arange(0, 4, 0.5)) ax.legend(loc="lower right", title="Yield") plt.grid() plt.show β0 = 0.01 β1 = 0.01 β2 = 0.01 λ = 1.00 df['NS'] =(β0)+(β1*((1-np.exp(-df['Maturity']/λ))/(df['Maturity']/λ)))+(β2*((((1-np.exp(-df['Maturity']/λ))/(df['Maturity']/λ)))-(np.exp(-df['Maturity']/λ)))) df.style.format({'Maturity': '{:,.0f}'.format,'Yield': '{:,.2%}','NS': '{:,.2%}'}) df1 = df.copy() df['Y'] = round(df['Yield']*100,4) df['NS'] =(β0)+(β1*((1-np.exp(-df['Maturity']/λ))/(df['Maturity']/λ)))+(β2*((((1-np.exp(-df['Maturity']/λ))/(df['Maturity']/λ)))-(np.exp(-df['Maturity']/λ)))) df['N'] = round(df['NS']*100,4) df2 = df.copy() df2 = df2.style.format({'Maturity': '{:,.2f}'.format,'Y': '{:,.2%}', 'N': '{:,.2%}'}) import matplotlib.pyplot as plt import matplotlib.markers as mk import matplotlib.ticker as mtick fontsize=15 fig = plt.figure(figsize=(13,7)) plt.title("Nelson-Siegel Model - Unfitted Yield Curve",fontsize=fontsize) ax = plt.axes() ax.set_facecolor("black") fig.patch.set_facecolor('white') X = df["Maturity"] Y = df["Y"] x = df["Maturity"] y = df["N"] ax.plot(x, y, color="orange", label="NS") plt.scatter(x, y, marker="o", c="orange") plt.scatter(X, Y, marker="o", c="blue") plt.xlabel('Period',fontsize=fontsize) plt.ylabel('Interest',fontsize=fontsize) ax.yaxis.set_major_formatter(mtick.PercentFormatter()) ax.xaxis.set_ticks(np.arange(0, 30, 5)) ax.yaxis.set_ticks(np.arange(0, 4, 0.5)) ax.legend(loc="lower right", title="Yield") plt.grid() plt.show() df['Residual'] = (df['Yield'] - df['NS'])**2 df22 = df[['Maturity','Yield','NS','Residual']] df22.style.format({'Maturity': '{:,.0f}'.format,'Yield': '{:,.2%}','NS': '{:,.2%}','Residual': '{:,.9f}'}) np.sum(df['Residual']) def myval(c): df = dd.copy() df['NS'] =(c[0])+(c[1]*((1-np.exp(-df['Maturity']/c[3]))/(df['Maturity']/c[3])))+(c[2]*((((1-np.exp(-df['Maturity']/c[3]))/(df['Maturity']/c[3])))-(np.exp(-df['Maturity']/c[3])))) df['Residual'] = (df['Yield'] - df['NS'])**2 val = np.sum(df['Residual']) print("[β0, β1, β2, λ]=",c,", SUM:", val) return(val) c = fmin(myval, [0.01, 0.00, -0.01, 1.0]) β0 = c[0] β1 = c[1] β2 = c[2] λ = c[3] print("[β0, β1, β2, λ]=", [c[0].round(4), c[1].round(4), c[2].round(4), c[3].round(4)]) df = df1.copy() df['NS'] =(β0)+(β1*((1-np.exp(-df['Maturity']/λ))/(df['Maturity']/λ)))+(β2*((((1-np.exp(-df['Maturity']/λ))/(df['Maturity']/λ)))-(np.exp(-df['Maturity']/λ)))) sf4 = df.copy() sf5 = sf4.copy() sf5['Y'] = round(sf4['Yield']*100,4) sf5['N'] = round(sf4['NS']*100,4) sf4 = sf4.style.format({'Maturity': '{:,.2f}'.format,'Yield': '{:,.2%}', 'NS': '{:,.2%}'}) M0 = 0.00 M1 = 3.50 import matplotlib.pyplot as plt import matplotlib.markers as mk import matplotlib.ticker as mtick fontsize=15 fig = plt.figure(figsize=(13,7)) plt.title("Nelson-Siegel Model - Fitted Yield Curve",fontsize=fontsize) ax = plt.axes() ax.set_facecolor("black") fig.patch.set_facecolor('white') X = sf5["Maturity"] Y = sf5["Y"] x = sf5["Maturity"] y = sf5["N"] ax.plot(x, y, color="orange", label="NS") plt.scatter(x, y, marker="o", c="orange") plt.scatter(X, Y, marker="o", c="blue") plt.xlabel('Time (Months)',fontsize=fontsize) plt.ylabel('Yield',fontsize=fontsize) ax.yaxis.set_major_formatter(mtick.PercentFormatter()) ax.xaxis.set_ticks(np.arange(0, 372, 12)) ax.yaxis.set_ticks(np.arange(3, 7, 0.5)) ax.legend(loc="lower right", title="Yield") plt.grid() plt.show() df.style.format({'Maturity': '{:,.0f}'.format,'Yield': '{:,.2%}','NS': '{:,.2%}'})
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Drivetrain; import edu.wpi.first.wpilibj.XboxController; public class ArcadeDrive extends CommandBase { /** Creates a new ArcadeDrive. */ private final Drivetrain m_drivetrain; private final XboxController m_xboxController; public ArcadeDrive(Drivetrain drivetrain, XboxController xboxController) { // Use addRequirements() here to declare subsystem dependencies. m_drivetrain = drivetrain; m_xboxController = xboxController; addRequirements(m_drivetrain); } // Called when the command is initially scheduled. @Override public void initialize() {} // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { m_drivetrain.arcadeDrive(m_xboxController.getRightY(), m_xboxController.getLeftX()); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { m_drivetrain.arcadeDrive(0, 0); } // Returns true when the command should end. @Override public boolean isFinished() { return false; } }
/* * backoffAlgorithm v1.0.1 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * @file backoff_algorithm.c * @brief Implementation of the backoff algorithm API for a "Full Jitter" * exponential backoff with jitter strategy. */ /* Standard includes. */ #include <assert.h> #include <stddef.h> /* Include API header. */ #include "backoff_algorithm.h" /*-----------------------------------------------------------*/ BackoffAlgorithmStatus_t BackoffAlgorithm_GetNextBackoff( BackoffAlgorithmContext_t* pRetryContext, uint32_t randomValue, uint16_t* pNextBackOff) { BackoffAlgorithmStatus_t status = BackoffAlgorithmSuccess; assert(pRetryContext != NULL); assert(pNextBackOff != NULL); /* If BACKOFF_ALGORITHM_RETRY_FOREVER is set to 0, try forever. */ if ((pRetryContext->attemptsDone < pRetryContext->maxRetryAttempts) || (pRetryContext->maxRetryAttempts == BACKOFF_ALGORITHM_RETRY_FOREVER)) { /* The next backoff value is a random value between 0 and the maximum jitter * value for the retry attempt. */ /* Choose a random value for back-off time between 0 and the max jitter * value. */ *pNextBackOff = (uint16_t)(randomValue % (pRetryContext->nextJitterMax + (uint32_t)1U)); /* Increment the retry attempt. */ pRetryContext->attemptsDone++; /* Double the max jitter value for the next retry attempt, only * if the new value will be less than the max backoff time value. */ if (pRetryContext->nextJitterMax < (pRetryContext->maxBackoffDelay / 2U)) { pRetryContext->nextJitterMax += pRetryContext->nextJitterMax; } else { pRetryContext->nextJitterMax = pRetryContext->maxBackoffDelay; } } else { /* When max retry attempts are exhausted, let application know by * returning BackoffAlgorithmRetriesExhausted. Application may choose to * restart the retry process after calling * BackoffAlgorithm_InitializeParams(). */ status = BackoffAlgorithmRetriesExhausted; } return status; } /*-----------------------------------------------------------*/ void BackoffAlgorithm_InitializeParams(BackoffAlgorithmContext_t* pContext, uint16_t backOffBase, uint16_t maxBackOff, uint32_t maxAttempts) { assert(pContext != NULL); /* Initialize the context with parameters used in calculating the backoff * value for the next retry attempt. */ pContext->nextJitterMax = backOffBase; pContext->maxBackoffDelay = maxBackOff; pContext->maxRetryAttempts = maxAttempts; /* The total number of retry attempts is zero at initialization. */ pContext->attemptsDone = 0; } /*-----------------------------------------------------------*/
package com.bs.dbperformancemetrics.service.databse.oracle.jpa; import com.bs.dbperformancemetrics.model.OracleUser; import com.bs.dbperformancemetrics.repository.oracle.jpa.OracleUserJPARepository; import com.bs.dbperformancemetrics.service.IUserService; import com.bs.dbperformancemetrics.utils.UserValidation; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class OracleUserJPAServiceImp implements IUserService<OracleUser, Long> { private final OracleUserJPARepository repository; @PersistenceContext private final EntityManager entityManager; public OracleUserJPAServiceImp(OracleUserJPARepository repository, EntityManager entityManager) { this.repository = repository; this.entityManager = entityManager; } // CREATE @Override @Transactional public void insert(OracleUser user) { UserValidation.validateUserCreation(user); entityManager.persist(createCopyOfUser(user)); } @Override @Transactional public void insertAll(List<OracleUser> users) { UserValidation.validateUsersCreation(users); int batchSize = 1000; int i = 0; for (OracleUser user : users) { entityManager.persist(createCopyOfUser(user)); i++; if (i % batchSize == 0) { entityManager.flush(); entityManager.clear(); } } if (i % batchSize != 0) { entityManager.flush(); entityManager.clear(); } } @Override @Transactional public void save(OracleUser user) { UserValidation.validateUserCreation(user); repository.save(createCopyOfUser(user)); } @Override @Transactional public void saveAll(List<OracleUser> users) { UserValidation.validateUsersCreation(users); repository.saveAll(createCopyOfUserList(users)); entityManager.clear(); } // READ @Override public OracleUser findById(Long id) { if (id == null || id <= 0) { throw new IllegalArgumentException("User ID cannot be null or less than or equal to zero"); } return repository.findById(id).orElse(null); } @Override public List<OracleUser> findAll() { return repository.findAll(Sort.by(Sort.Direction.ASC, "id")); } @Override public OracleUser findByUsername(String username) { if (username == null || username.isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } return repository.findByUsername(username).orElse(null); } @Override public List<OracleUser> findByName(String name) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } List<OracleUser> users = repository.findByName(name); return users.isEmpty() ? null : users; } @Override public String findPasswordByUsername(String username) { if (username == null || username.isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } return repository.findPasswordByUsername(username).orElseThrow(() -> new IllegalArgumentException("User with username " + username + " not found")); } // UPDATE @Override @Transactional public void updateAll(List<OracleUser> users) { UserValidation.validateUsers(users); saveAll(createCopyOfUserList(users)); } @Override @Transactional public void update(OracleUser user) { UserValidation.validateUser(user); repository.findById(user.getId()) .orElseThrow(() -> new IllegalArgumentException("User with ID " + user.getId() + " not found")); save(user); } @Override @Transactional public void updatePasswordByUsername(String username, String newPassword) { if (username == null || username.isEmpty()) { throw new IllegalArgumentException("User username cannot be null or empty"); } if (newPassword == null || newPassword.isEmpty()) { throw new IllegalArgumentException("New password cannot be null or empty"); } OracleUser user = repository.findByUsername(username) .orElseThrow(() -> new IllegalArgumentException("User with username " + username + " not found")); user.setPassword(newPassword); UserValidation.validateUser(user); repository.save(user); } @Override @Transactional public void updatePasswordByName(String name, String newPassword) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("User name cannot be null or empty"); } if (newPassword == null || newPassword.isEmpty()) { throw new IllegalArgumentException("New password cannot be null or empty"); } List<OracleUser> users = repository.findByName(name); if (users.isEmpty()) { throw new IllegalArgumentException("User with name " + name + " not found"); } users.forEach(user -> user.setPassword(newPassword)); UserValidation.validateUsers(users); repository.saveAll(users); } @Override @Transactional public void addFriend(Long userId, Long friendId) { if (userId == null || userId <= 0) { throw new IllegalArgumentException("User ID cannot be null or less than or equal to zero"); } if (friendId == null || friendId <= 0) { throw new IllegalArgumentException("Friend ID cannot be null or less than or equal to zero"); } if (userId.equals(friendId)) { throw new IllegalArgumentException("User ID and friend ID cannot be the same"); } OracleUser user = repository.findById(userId) .orElseThrow(() -> new IllegalArgumentException("User with id " + userId + " not found")); user.addFriendId(friendId); repository.save(user); } @Override @Transactional public void removeFriend(Long userId, Long friendId) { OracleUser user = repository.findById(userId) .orElseThrow(() -> new IllegalArgumentException("User with id " + userId + " not found")); user.removeFriendId(friendId); repository.save(user); } // DELETE @Override @Transactional public void deleteAll() { repository.deleteAllInBatch(); } @Override @Transactional public void deleteById(Long id) { if (id == null || id <= 0) { throw new IllegalArgumentException("User ID cannot be null or less than or equal to zero"); } repository.deleteById(id); } @Override @Transactional public void deleteByUsername(String username) { if (username == null || username.isEmpty()) { throw new IllegalArgumentException("User username cannot be null or empty"); } repository.deleteByUsername(username); } @Override @Transactional public void deleteByName(String name) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("User name cannot be null or empty"); } repository.deleteByName(name); } @Override public OracleUser createCopyOfUser(OracleUser originalUser) { return new OracleUser(originalUser); } @Override public List<OracleUser> createCopyOfUserList(List<OracleUser> originalList) { return originalList.parallelStream() .map(OracleUser::new) .toList(); } }
created: 20160423233507631 creator: guillefix modified: 20161218153236650 modifier: cosmos tags: [[Complex systems]] [[Automata theory]] title: Cellular automata tmap.id: 141171ee-17d6-4899-8543-4d3ee60c41c4 type: text/vnd.tiddlywiki [[Complex systems]], artificial life in [[Bio-inspired computing]]. See [[Dynamical systems on networks]], [[Discrete dynamical systems]] [[Cellular automaton|https://en.wikipedia.org/wiki/Cellular_automaton]] [[Exploring Cellular Automata|https://www.fourmilab.ch/cellab/manual/cellab.html#contents]] [[Theory of Cellular Automata|https://theory.org/complexity/cdpt/html/node4.html]] [[Classsification of Cellular Automata|http://www.cs.cmu.edu/~sutner/papers/ecss.pdf]] [[Computer simulations of cellular automata|http://iopscience.iop.org/article/10.1088/0305-4470/24/5/007/meta]] [[Automata theory]] !!__Statistical mechanics of cellular automata__ [[Equivalence of Cellular Automata to Ising Models and Directed Percolation|http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.53.311]] [[Phase Transitions of Cellular Automata|http://download.springer.com/static/pdf/383/art%253A10.1007%252FBF01309255.pdf?originUrl=http%3A%2F%2Flink.springer.com%2Farticle%2F10.1007%2FBF01309255&token2=exp=1466080666~acl=%2Fstatic%2Fpdf%2F383%2Fart%25253A10.1007%25252FBF01309255.pdf%3ForiginUrl%3Dhttp%253A%252F%252Flink.springer.com%252Farticle%252F10.1007%252FBF01309255*~hmac=03be81353c981a73c9671ca9fbfc4e687fa7c3964255a560d0b111f5c8879f11]] See [[Directed percolation]] [[Statistical Mechanics of Probabilistic Cellular Automata|http://journals.aps.org/prl/abstract/10.1103/PhysRevLett.55.2527]] [[Universality in Elementary Cellular Automata|http://www.complex-systems.com/pdf/15-1-1.pdf]] proves a conjecture made by Stephen Wolfram in 1985, that an elementary one dimensional cellular automaton known as “Rule 110” is capable of universal computation, i.e. it is a [[Turing machine]] (see [[Theory of computation]]) [[Statistical mechanics of cellular automata|http://www.stephenwolfram.com/publications/academic/statistical-mechanics-cellular-automata.pdf]] !!![[Computation theory of cellular automata|http://www.stephenwolfram.com/publications/academic/computation-theory-cellular-automata.pdf]] //A new kind of science// - Stephen Wolfram [[http://www.paradise.caltech.edu/~cook/papers/index.html]] [[Game of Life Cellular Automata|http://www.springer.com/gp/book/9781849962162]] !!!__Elementary cellular automaton__ [[(wiki)|https://en.wikipedia.org/wiki/Elementary_cellular_automaton]] [[Rule 90|https://en.wikipedia.org/wiki/Rule_90]] [img width=400 [https://upload.wikimedia.org/wikipedia/commons/5/5b/R090_rand_0.png]] [[Rule 30|https://en.wikipedia.org/wiki/Rule_30]] [img width=500 [https://upload.wikimedia.org/wikipedia/commons/d/d9/Rule30-first-500-rows.png]] !!__Examples__ [[Von Neumann cellular automata|https://en.wikipedia.org/wiki/Von_Neumann_cellular_automaton]] are the original expression of cellular automata, the development of which were prompted by suggestions made to John von Neumann by his close friend and fellow mathematician Stanislaw Ulam. Their original purpose was to provide insight into the logical requirements for machine self-replication and were used in von Neumann's universal constructor. [img[https://upload.wikimedia.org/wikipedia/commons/5/50/VonNeumann_CA_demo.gif]] [[Codd's cellular automaton|https://en.wikipedia.org/wiki/Codd%27s_cellular_automaton]] designed to recreate the computation- and construction-universality of von Neumann's CA but with fewer states: 8 instead of 29. [img[https://upload.wikimedia.org/wikipedia/commons/6/69/Codd_CA_RepeaterEmitter.gif]] [[Conway's Game of Life|https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life]] [img[https://upload.wikimedia.org/wikipedia/commons/e/e5/Gospers_glider_gun.gif]] [[Langton's loops|https://en.wikipedia.org/wiki/Langton%27s_loops]] consist of a loop of cells containing genetic information, which flows continuously around the loop and out along an "arm" (or pseudopod), which will become the daughter loop [img widh=500 [https://upload.wikimedia.org/wikipedia/commons/2/28/Langtons_Loop_Colony.png]] [[Nobili cellular automata|https://en.wikipedia.org/wiki/Nobili_cellular_automata]] are a variation of von Neumann cellular automata (vNCA), in which additional states provide means of memory and the interference-free crossing of signal. [img widh=500 [https://upload.wikimedia.org/wikipedia/en/9/98/Lambda-G.png]] [[Brian's Brain|https://en.wikipedia.org/wiki/Brian%27s_Brain]] [img[https://upload.wikimedia.org/wikipedia/commons/a/a7/Brian%27s_brain.gif]] [[Langton's ant|https://en.wikipedia.org/wiki/Langton%27s_ant]] [img[https://upload.wikimedia.org/wikipedia/commons/f/f9/LangtonsAnt-nColor_LLRRRLRLRLLR_36437.png]] [img[http://i.imgur.com/YBBk3fl.gif]] [[Wireworld|https://en.wikipedia.org/wiki/Wireworld]] [img[https://upload.wikimedia.org/wikipedia/commons/5/5d/Animated_display.gif]] --------- See also [[Discrete dynamical systems]] [img[http://www.ddlab.com/gdca_cropped_front_cover.jpg]] [[http://out.coy.cat/?n=1001010010]] [[http://out.coy.cat/?n=topkek]] [[http://out.coy.cat/?n=nicememe]] http://out.coy.cat/?n=welp http://out.coy.cat/?n=culo http://out.coy.cat/?n=bra http://out.coy.cat/?n=megabra http://out.coy.cat/?n=asdas http://out.coy.cat/?n=cate wooow sierpinski http://out.coy.cat/?n=liborio http://out.coy.cat/?n=cognio http://out.coy.cat/?n=black http://out.coy.cat/?n=extropy http://out.coy.cat/?n=entropy http://out.coy.cat/?n=XOXO http://out.coy.cat/?n=doitforthelulz http://out.coy.cat/?n=rebroff http://out.coy.cat/?n=topcate http://cells.coy.cat/ http://cellularautomata.coy.cat/ http://out.coy.cat/?n=1269489990&s=0 http://out.coy.cat/?n=1269489997&s=0 http://out.coy.cat/?n=1269490006&s=0 http://out.coy.cat/?n=1269490035&s=0 http://out.coy.cat/?n=1269490071&s=0 like the matrix: http://out.coy.cat/rndpat.php?n=1269490075&s=0 http://out.coy.cat/?n=1269490127&s=0 http://psoup.math.wisc.edu/mcell/ca_gallery.html http://www.sciencedirect.com/science/article/pii/S0304397515005344
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('forms', function (Blueprint $table) { $table->id(); $table->text('namalengkap'); $table->text('universitas'); $table->text('nim')->unique(); $table->text('email')->unique(); $table->text('medsos')->unique(); $table->text('bukti'); $table->text('instagram')->unique()->nullable(); $table->text('linkkaryaig')->nullable(); $table->text('pathfilehasilkarya')->nullable(); $table->enum('type', ['Mobile Journalism', 'Long-Form Article', 'News Infographic']); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('forms'); } };
package com.elksa.sample.buscador.mercadolibre.domain.interactors import com.elksa.sample.buscador.mercadolibre.domain.entities.ItemDescriptionEntity import com.elksa.sample.buscador.mercadolibre.domain.interfaces.IItemRepository import com.elksa.sample.buscador.mercadolibre.domain.utils.EMPTY_STRING import io.reactivex.Single import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.anyString import org.mockito.Mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class FetchItemDescriptionUseCaseTest { private lateinit var sut: FetchItemDescriptionUseCase @Mock private lateinit var repositoryMock: IItemRepository @Before fun setUp() { sut = FetchItemDescriptionUseCase(repositoryMock) } @Test fun fetchItemDescription_onSuccess_returnsItemDescription() { // given val itemDescription = ItemDescriptionEntity("text", "plaintext") `when`(repositoryMock.getItemDescription(anyString())) .thenReturn(Single.just(itemDescription)) // when val result = sut.fetchItemDescription(EMPTY_STRING) // then assertEquals(itemDescription, result.blockingGet()) } @Test fun fetchItemDescription_onFailure_returnsError() { // given val error = Throwable("error fetching item description") `when`(repositoryMock.getItemDescription(anyString())) .thenReturn(Single.error(error)) // when val result = sut.fetchItemDescription(EMPTY_STRING) // then result.test().assertError(error) } @Test fun fetchItemDescription_invocation_apiGetItemDescriptionInvokedWithItemId() { // given val itemId = "itemId" `when`(repositoryMock.getItemDescription(anyString())) .thenReturn(Single.error(Throwable())) // when sut.fetchItemDescription(itemId) // then verify(repositoryMock).getItemDescription(itemId) } }
import { useParams } from "react-router-dom"; import { useApi } from "../hooks/useApi"; export default function Meeting() { const { id } = useParams(); const { success, error, loading, response } = useApi({ method: "get", endpoint: `/class/${id}`, }); if (loading) return <>Loading...</>; if (success && response.status === 200) { const { classDetails, meetDetails } = response.data; return ( <div className="meeting-details-container"> <div className="section"> <h2>Class Details</h2> <ul> <li> <strong>Teacher:</strong> {classDetails.teacher} </li> <li> <strong>Students:</strong> {classDetails.students.join(", ")} </li> <li> <strong>Meeting ID:</strong> {classDetails.meeting_id} </li> </ul> </div> <div className="section"> <h2>Meeting Details</h2> <ul> <li> <strong>Topic:</strong> {meetDetails.topic} </li> <li> <strong>Status:</strong> {meetDetails.status} </li> <li> <strong>Start Time:</strong>{" "} {new Date(meetDetails.start_time).toLocaleString()} </li> </ul> </div> <div className="section"> <div className="buttons"> <a href={classDetails.meeting_join_url} target="_blank" rel="noopener noreferrer" > Join Meeting </a> <a href={classDetails.meeting_start_url} target="_blank" rel="noopener noreferrer" > Start Meeting </a> </div> </div> </div> ); } if (error) return <>Something Went Wrong</>; return <>Meeting id {id}</>; }
import React, {FormEvent, useState} from 'react' import './Auth.css' import { useTypedDispatch } from '../../Redux/Hooks' import { authStart, loginSuccess, registerSuccess, authFailure } from '../../Redux/userSlice' import ArrowCircleLeftIcon from '@mui/icons-material/ArrowCircleLeft'; import { useNavigate } from 'react-router-dom'; import { axiosInstance } from '../../axiosInstance'; import {Link} from 'react-router-dom' import { GoogleLogin } from 'react-google-login'; import { UserType} from '../../Redux/userSlice' import {gapi} from "gapi-script" if(process.env.NODE_ENV === 'production') { gapi.load("client:auth2", () => { gapi.client.init({ clientId: process.env.REACT_APP_PROD_CLIENT_ID, plugin_name: "chat", }); }); } const Login : React.FC = () => { const dispatch = useTypedDispatch() const navigate = useNavigate() const [email, setEmail] = useState<string>(""); const [password, setPassword] = useState<string>(""); const handleLogin = async (e: FormEvent) => { e.preventDefault(); dispatch(authStart()) try { const res = await axiosInstance.post(`/api/auth/login`, {email, password}) console.log('activation url',res.data.url) console.log('[port]', res.data.port) dispatch(loginSuccess(res.data)) navigate(`/`); } catch (error: any) { const errors = error?.response?.data?.errors; const msg = error?.response?.data?.msg; if (Array.isArray(errors)) { errors.forEach((err) => alert(err.msg)); } if (msg) { alert(msg); } dispatch(authFailure()) } setEmail('') setPassword('') } const googleLoginSuccess = async (result: any) => { dispatch(authStart()) try { const form: UserType = { firstName: result?.profileObj.givenName , lastName: result?.profileObj.familyName, email: result?.profileObj.email, password: result?.profileObj.googleId, }; const response = await axiosInstance.get(`/api/users`) const User = response.data?.find((u: any) => u?.email === form?.email) if (!User) { const res = await axiosInstance.post(`/api/auth/register`, form) dispatch(registerSuccess(res.data)); } else { const res = await axiosInstance.post(`/api/auth/login`, {email: User?.email, password: User?.password}) dispatch(loginSuccess(res.data)); } navigate('/') } catch (error) { console.log(error); dispatch(authFailure()) } }; return ( <div> <div className='back' style={{position: 'absolute'}} onClick={() => navigate(-1)}><ArrowCircleLeftIcon/></div> <div className='login-container'> <h1>Sign In</h1> <div className='login-wrapper'> <div className="mb-3"> <label className="form-label">Email address <span className='required'>*</span></label> <input type="email" className="form-control" placeholder="[email protected]" required value={email} onChange={e => setEmail(e.target.value)} /> </div> <div className="mb-3"> <label className="form-label">Password <span className='required'>*</span></label> <input type="password" className="form-control" placeholder="Password.." required value={password} onChange={e => setPassword(e.target.value)} /> </div> <button className='login-btn' onClick={e => handleLogin(e)}>Login</button> <div className='login-links'> <Link to="/register"><p className='login-link'>New Account</p></Link> <Link to="/forgot-password"><p className='login-link'>Forgot Password ?</p></Link> </div> <div className='or'>OR</div> <div className='google-login'> { process.env.REACT_APP_DEV_CLIENT_ID && process.env.REACT_APP_PROD_CLIENT_ID && <GoogleLogin clientId={ process.env.NODE_ENV === 'development' ? process.env.REACT_APP_DEV_CLIENT_ID : process.env.REACT_APP_PROD_CLIENT_ID } buttonText="Login with Google" onSuccess={googleLoginSuccess} onFailure={(err) => console.log('Google Sign In Unsuccessful. Try Again Later', err)} cookiePolicy={'single_host_origin'} theme='dark' /> } </div> </div> </div> </div> )} export default Login
package com.example.electroapp.presenation.fragments import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.Toast import androidx.lifecycle.ViewModelProvider import com.example.electroapp.R import com.example.electroapp.data.models.Advertisement import com.example.electroapp.data.util.DATA_ADS import com.example.electroapp.data.util.DATA_AD_USER_ID import com.example.electroapp.databinding.FragmentHomeBinding import com.example.electroapp.presenation.adapters.AdvertisementsAdapter import com.example.electroapp.presenation.listeners.AdListenerImpl import com.example.electroapp.presenation.viewmodels.AdvertisementViewModel import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.storage.FirebaseStorage class HomeFragment : ElectroFragment() { private lateinit var binding: FragmentHomeBinding private val firebaseDB = FirebaseFirestore.getInstance() private val userId = FirebaseAuth.getInstance().currentUser?.uid private var adapter: AdvertisementsAdapter?=null private lateinit var viewModel: AdvertisementViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(requireActivity())[AdvertisementViewModel::class.java] adapter = AdvertisementsAdapter(arrayListOf(),userId!!) listener = AdListenerImpl(binding.rvAdvertisements,this@HomeFragment, adapter!!) adapter!!.setListener(listener!!) binding.rvAdvertisements.adapter = adapter updateList() binding.etSearch.setOnEditorActionListener { textView, actionId, keyEvent -> if(actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEARCH){ requireActivity().supportFragmentManager.beginTransaction() .replace(R.id.main_container, SearchFragment.newInstance(binding.etSearch.text.toString())) .addToBackStack("search").commit() binding.etSearch.setText("") binding.etSearch.clearFocus() } true } } override fun onResume() { super.onResume() updateList() } override fun onStart() { super.onStart() updateList() } private fun updateList() { val ads = arrayListOf<Advertisement>() firebaseDB.collection(DATA_ADS).get() .addOnSuccessListener { list -> for (document in list.documents) { val ad = document.toObject(Advertisement::class.java) ad?.let { ads.add(ad)} } adapter?.updateAds(ads) } .addOnFailureListener { Toast.makeText( requireContext(), "Something went wrong... :(", Toast.LENGTH_SHORT ).show() } } companion object { @JvmStatic fun newInstance() = HomeFragment() } }
# BOOSTED TREE # create spec boost_model <- boost_tree() %>% set_engine("xgboost") %>% set_mode("regression") # create workflow boost_wkflow <- workflow() %>% add_model(boost_model %>% set_args(trees = tune(), mtry = tune())) %>% add_recipe(movies_recipe) # grid for different values boost_param_grid <- grid_regular( mtry(range=c(1,7)), trees(range=c(1,500)), levels=10) # results for different models boost_param_res <- tune_grid(rf_wkflow, resamples = movies_fold, grid = rf_param_grid) # visual autoplot(boost_param_res) # select best model best_boost_res <- select_best(boost_param_res, metric = "rmse") boost_final <- finalize_workflow( boost_wkflow, best_boost_res) boost_final_fit <- fit( boost_final, data = movies_train) # check performance augment(boost_final_fit, new_data = movies_train) %>% rmse(truth = score, estimate = .pred) # plot the true versus the predicted values augment(boost_final_fit, new_data = movies_train) %>% ggplot(aes(score, .pred)) + geom_abline() + geom_point(alpha = 0.5) save(boost_param_res, boost_wkflow, file = "boosted_runs.rda") load(file = "boosted_runs.rda")
1. It is time to create the actual index.html template. 2. Create a new directory called templates in the /src/main/_resources folder, and in it an index.html file. Remember, this is the path you configured your templateResolver in your ApplicationConfiguration to use, in the last lesson. ## Unix/Linux/MacOS cd /src/main mkdir -p resources/templates cd resources/templates touch index.html 3. Give the HTML file the following contents: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>First Thymeleaf Template</title> </head> <body> <h1>This is it!</h1> <p>Your very first Thymleaf template.</p> </body> </html> • The template, for now, does not contain any variables or any other dynamic data. It is just a static HTML page. Enough, to see if things are set-up correctly. 4. Checkpoint: Adding Thymeleaf Restart your application and go to http://localhost:8080. You should see this: *This is it!* Your very first Thymleaf template. Congratulations! Let’s now build a slightly more sophisticated page.
import React, { useEffect, useState } from "react" import { useNavigate, useParams } from "react-router-dom" import * as RemixIcons from "react-icons/ri" import toast from "react-hot-toast" import dateFormat from 'dateformat' import HeaderMain from "../../../components/HeaderMain" import { Survey } from "../../../services/surveyService" import { Account } from "../../../services/accountService" import CustomDataTable from "../../../components/CustomDataTable" import SelectOption from "../../../components/SelectOption" import { sortOption, StatusOption } from "../../../data/optionFilter" import SearchInput from "../../../components/SearchInput" import Access from "../../../utils/utilsAccess" import { Average } from "../../../services/average" import { QuestionAnswer } from "../../../services/questionAnswerService" import useHandleError from "../../../hooks/useHandleError" const ListNote = () => { const Navigate = useNavigate() const access = Access const statusOption = StatusOption() const { id } = useParams() const [data, setData] = useState([]) const [oneData, setOneData] = useState([]) const [loading, setLoading] = useState(true) const [order, setOrder] = useState('asc') const [filter, setFilter] = useState('name') const [status, setStatus] = useState('') const [search, setSearch] = useState('') const [limit, setLimit] = useState(10) const [page, setPage] = useState(0) const [refresh, setRefresh] = useState(0) const [allCount, setAllCount] = useState(0) // GET ORDER VALUE const handleOrderChange = (e) => { setOrder(e.target.value) } // GET FILTER VALUE const handleFilterChange = (e) => { setFilter(e.target.value) } // GET RESEARCH VALUE const handleSearchChange = (e) => { setSearch(e.target.value) } // GET ALL DATA API useEffect(() => { const loadData = async () => { try { setLoading(true) // RETRIEVE ALL Note const res = await QuestionAnswer.getByQuestion(id) setData(res.data.content.data) } catch (err) { useHandleError(err, Navigate) } finally { setLoading(false) } } loadData() }, [order, filter, search, id]) // SYSTEM PAGINATION // const handlePageChange = (newPage) => { // setPage(newPage) // } // const handleLimitChange = (newLimit) => { // setLimit(newLimit) // } // FORMATTING JSON DATA TO MAKE IT MORE READABLE const ExpandedComponent = ({ data }) => <pre>{JSON.stringify(data, null, 2)}</pre> // HEADING AND DISPLAY PRINCIPLE OF THE TABLE const columns = [ { name: 'Note', selector: row => row.Answer.note, sortable: true, wrap: true, }, { name: 'Suggestion', selector: row => row.Answer.suggestion, sortable: true, wrap: true, }, { name: 'Date créat.', selector: row => dateFormat(new Date(row.createdAt), 'dd-mm-yyyy HH:MM:ss'), sortable: true, wrap: true, } ] // FILTER SELECT TAG DATA const filterOptions = [ { value: 'name', label: 'nom' }, { value: 'createdAt', label: 'date de créat.' }, ] return ( <> <HeaderMain total={allCount} /> <div className="OptionFilter"> <SelectOption label="Trier par" id="sort" name={order} value={order} onChange={handleOrderChange} options={sortOption} /> <SelectOption label="Filtrer par" id="filter" name={filter} value={filter} onChange={handleFilterChange} options={filterOptions} /> <SearchInput filter={filter} placeholder="Tapez ici.." ariaLabel="Search" value={search} onChange={handleSearchChange} /> </div> <CustomDataTable loading={loading} columns={columns} data={data} ExpandedComponent={ExpandedComponent} /> </> ) } export default ListNote
import React, { useState, useEffect } from "react"; import { AllTimeScore, AllTimScoreHeader, Button, GlobalStyle, Input, InputWrapper, Label, LabelWrapper, LastScore, LastScoreHeader, UserListItem, UserListWraper, Username, UserNameHeader, Wrapper, } from "../../App.styles"; import { createUser, getUsers } from "../../services/UserService"; import { HomeScreenProps } from "../../types/HomeScreen/HomeScreenProps"; import { UserWithScore } from "../../types/HomeScreen/UserWithScore"; import { UserObject } from "../../types/UserObject"; const HomeScreen: React.FC<HomeScreenProps> = ({ loading, username, onUsernameChange, onLoadingChange, onUserChange, }) => { const [userList, setUserList] = useState<UserWithScore[]>([]); useEffect(() => { getUsers() .then((response) => setUserList(response.data)) .catch((err) => console.log(err)); }, []); const handleClick = async () => { onLoadingChange(true); const response = await createUser(username); const newUser: UserObject = response.data; if (newUser) { onUserChange(newUser); } onLoadingChange(false); }; return ( <> <GlobalStyle /> <Wrapper> <h1>Please enter a username</h1> <InputWrapper> <LabelWrapper> <Label htmlFor="username">Username:</Label> </LabelWrapper> <Input type="text" id="username" placeholder="Please enter a username..." onChange={(e) => onUsernameChange(e.target.value)} /> <Button onClick={handleClick}>Submit</Button> {loading && <p>Loading questions...</p>} </InputWrapper> </Wrapper> <Wrapper> <h2>High scores</h2> <UserListWraper> <UserListItem> <UserNameHeader>Username:</UserNameHeader> <LastScoreHeader>Recent score:</LastScoreHeader> <AllTimScoreHeader>All time score:</AllTimScoreHeader> </UserListItem> {userList.length !== 0 ? ( userList.map((user) => ( <UserListItem key={user?.username}> <Username>{user?.username}</Username> <LastScore>{user?.recentScore}</LastScore> <AllTimeScore>{user?.allTimeScore}</AllTimeScore> </UserListItem> )) ) : ( <p>No user available</p> )} </UserListWraper> </Wrapper> </> ); }; export default HomeScreen;
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @TestOn('browser') // Uses package:web library; import 'dart:async'; import 'dart:js_interop'; import 'package:google_identity_services_web/loader.dart'; import 'package:google_identity_services_web/src/js_loader.dart'; import 'package:test/test.dart'; import 'package:web/web.dart' as web; // NOTE: This file needs to be separated from the others because Content // Security Policies can never be *relaxed* once set. // // In order to not introduce a dependency in the order of the tests, we split // them in different files, depending on the strictness of their CSP: // // * js_loader_test.dart : default TT configuration (not enforced) // * js_loader_tt_custom_test.dart : TT are customized, but allowed // * js_loader_tt_forbidden_test.dart: TT are completely disallowed void main() { group('loadWebSdk (no TrustedTypes)', () { final web.HTMLDivElement target = web.document.createElement('div') as web.HTMLDivElement; test('Injects script into desired target', () async { // This test doesn't simulate the callback that completes the future, and // the code being tested runs synchronously. unawaited(loadWebSdk(target: target)); // Target now should have a child that is a script element final web.Node? injected = target.firstChild; expect(injected, isNotNull); expect(injected, isA<web.HTMLScriptElement>()); final web.HTMLScriptElement script = injected! as web.HTMLScriptElement; expect(script.defer, isTrue); expect(script.async, isTrue); expect(script.src, 'https://accounts.google.com/gsi/client'); }); test('Completes when the script loads', () async { final Future<void> loadFuture = loadWebSdk(target: target); Future<void>.delayed(const Duration(milliseconds: 100), () { // Simulate the library calling `window.onGoogleLibraryLoad`. web.window.onGoogleLibraryLoad(); }); await expectLater(loadFuture, completes); }); }); } extension on web.Window { void onGoogleLibraryLoad() => _onGoogleLibraryLoad(); @JS('onGoogleLibraryLoad') external JSFunction? _onGoogleLibraryLoad(); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactoryMethod { internal class Program { static void Main(string[] args) { CustomerManager customerManager = new CustomerManager(); customerManager.Save(); Console.ReadLine(); } } public class LoggerFactory:ILoggerFactory { public ILogger CreateLogger() { return new MyLogger(); } } public interface ILoggerFactory { } public interface ILogger { void Log(); } public class MyLogger : ILogger { public void Log() { Console.WriteLine("Logged with MyLogger"); } } public class CustomerManager { public void Save() { Console.WriteLine("Saved"); ILogger logger = new LoggerFactory().CreateLogger(); logger.Log(); } } }
```cpp #include <bits/stdc++.h> using namespace std; struct Node { int value, lazy; Node() : value(0), lazy(0) {} }; class SegmentTree { vector<Node> tree; int n; void push(int node, int start, int end) { if (tree[node].lazy != 0) { tree[node].value = (end - start + 1) * tree[node].lazy; if (start != end) { tree[2*node].lazy = tree[node].lazy; tree[2*node+1].lazy = tree[node].lazy; } tree[node].lazy = 0; } } void update(int node, int start, int end, int l, int r, int val) { push(node, start, end); if (r < start || end < l) return; if (l <= start && end <= r) { tree[node].lazy = val; push(node, start, end); return; } int mid = (start + end) / 2; update(2*node, start, mid, l, r, val); update(2*node+1, mid+1, end, l, r, val); tree[node].value = tree[2*node].value + tree[2*node+1].value; } int query(int node, int start, int end, int l, int r) { push(node, start, end); if (r < start || end < l) return 0; if (l <= start && end <= r) return tree[node].value; int mid = (start + end) / 2; return query(2*node, start, mid, l, r) + query(2*node+1, mid+1, end, l, r); } public: SegmentTree(int n) : tree(4*n), n(n) {} void update(int l, int r, int val) { update(1, 0, n-1, l, r, val); } int query(int l, int r) { return query(1, 0, n-1, l, r); } }; int m, n, k, t; int a[200000]; int l[200000]; int r[200000]; int d[200000]; bool is_possible(int mid) { SegmentTree stree(n+1); int min_agility = a[mid]; for (int i = 0; i < k; i++) { if (d[i] > min_agility) { stree.update(l[i]-1, r[i]-1, 1); } } int req_time = n+1 + stree.query(0, n); return req_time <= t; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> m >> n >> k >> t; for (int i = 0; i < m; i++) { cin >> a[i]; } for (int i = 0; i < k; i++) { cin >> l[i] >> r[i] >> d[i]; } sort(a, a+m, greater<int>()); int left = 0; int right = m; while (left < right) { int mid = left + (right - left) / 2; if (is_possible(mid)) { right = mid; } else { left = mid + 1; } } cout << left << endl; } ```
<!-- Start Content --> <div class="container py-5"> <div class="row"> <div class="col-lg-3"> <h1 class="h2 pb-4">Hãng Sản Xuất</h1> <ul class="list-unstyled templatemo-accordion"> <li *ngFor="let item of manufacturer" class="pb-3"> <a (click)="findProductByManufacturerId(item.id)" [queryParams]="{manufacturer: item.id}" [routerLink]="['/zayShopping/category']" class="collapsed d-flex justify-content-between h3 text-decoration-none"> {{item.name}} <!-- <i class="fa fa-fw fa-chevron-circle-down mt-1"></i>--> </a> </li> </ul> </div> <div class="col-lg-9"> <div class="row"> <div class="col-md-6"> <ul class="list-inline shop-top-menu pb-3 pt-1"> <li class="list-inline-item"> <a (click)="getAllProducts()" [routerLink]="['/zayShopping/category']" class="h3 text-dark text-decoration-none mr-3">All</a> </li> <li class="list-inline-item"> <a class="h3 text-dark text-decoration-none mr-3" href="#">Mới</a> </li> <li class="list-inline-item"> <a class="h3 text-dark text-decoration-none" href="#">Bán Chạy</a> </li> </ul> </div> <div class="col-md-6 pb-4"> <div class="d-flex"> <select class="form-control"> <option>Mặc Định</option> <option>A đến Z</option> <option>Giá</option> </select> </div> </div> </div> <div class="row"> <div *ngFor="let item of products | paginate: {itemsPerPage: 6, currentPage: page}" class="col-md-4"> <div class="card mb-4 product-wap rounded-0"> <div class="card rounded-0"> <img alt="img" class="card-img rounded-0 img-fluid" src="{{item.imageMain}}"> <div class="card-img-overlay rounded-0 product-overlay d-flex align-items-center justify-content-center"> <ul class="list-unstyled"> <li><a class="btn btn-success text-white" href="shop-single.html"><i class="far fa-heart"></i></a></li> <li><a class="btn btn-success text-white mt-2" href="shop-single.html"><i class="far fa-eye"></i></a></li> <li><a (click)="addCart(item.pid)" class="btn btn-success text-white mt-2"><i class="fas fa-cart-plus"></i></a></li> </ul> </div> </div> <a (click)="openProductDetail(item.pid)" [queryParams]="{productID: item.pid}" [routerLink]="['/zayShopping/detail']" class="h3 text-decoration-none overflow-text" style="color:#198754; cursor: pointer; font-weight: 400 !important;">{{item.name}}</a> <div (click)="openProductDetail(item.pid)" class="card-body" style="padding-top: 0; cursor: pointer"> <ul class="w-100 list-unstyled d-flex justify-content-between mb-0"> <li style="padding-bottom: 10px;"> <small style="background-color: #e8e8e8;padding: 2px 10px; border-radius: 2px;border: 1px solid #59ab6e; margin-right: 10px;"> {{item.ramdisk | chain: 1}} GB </small> <small style="background-color: #e8e8e8;padding: 2px 10px; border-radius: 2px;border: 1px solid #59ab6e;"> {{item.hardDiskDrive | chain: 2}} </small> </li> <li class="pt-2"> <span class="product-color-dot color-dot-red float-left rounded-circle ml-1"></span> <span class="product-color-dot color-dot-blue float-left rounded-circle ml-1"></span> <span class="product-color-dot color-dot-black float-left rounded-circle ml-1"></span> <span class="product-color-dot color-dot-light float-left rounded-circle ml-1"></span> <span class="product-color-dot color-dot-green float-left rounded-circle ml-1"></span> </li> </ul> <ul class="list-unstyled d-flex justify-content-center mb-1"> <li> <i class="text-warning fa fa-star"></i> <i class="text-warning fa fa-star"></i> <i class="text-warning fa fa-star"></i> <i class="text-muted fa fa-star"></i> <i class="text-muted fa fa-star"></i> </li> </ul> <p class="text-center mb-0" style="color: #dc3545; font-weight: bold; font-size: 1.3rem"> {{item.price.toLocaleString('vn', {style: undefined, currency: 'VND'})}} VND</p> </div> </div> </div> </div> <!-- <div div="row">--> <!-- <ul class="pagination pagination-lg justify-content-end">--> <!-- <li class="page-item disabled">--> <!-- <a class="page-link active rounded-0 mr-3 shadow-sm border-top-0 border-left-0" href="#"--> <!-- tabindex="-1">1</a>--> <!-- </li>--> <!-- <li class="page-item">--> <!-- <a class="page-link rounded-0 mr-3 shadow-sm border-top-0 border-left-0 text-dark"--> <!-- href="#">2</a>--> <!-- </li>--> <!-- <li class="page-item">--> <!-- <a class="page-link rounded-0 shadow-sm border-top-0 border-left-0 text-dark" href="#">3</a>--> <!-- </li>--> <!-- </ul>--> <!-- </div>--> <ng-container *ngIf="products.length > 6"> <pagination-controls (pageChange)="onPage($event)"></pagination-controls> </ng-container> </div> </div> </div> <!-- End Content -->
function sphere_grid_test01 ( ) %*****************************************************************************80 % %% sphere_grid_test01() tests sphere_icos_point_num(). % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 11 October 2012 % % Author: % % John Burkardt % fprintf ( 1, '\n' ); fprintf ( 1, 'sphere_grid_test01():\n' ); fprintf ( 1, ' SPHERE_ICOS_POINT_NUM determines the size\n' ); fprintf ( 1, ' (number of vertices, edges and faces) in a grid\n' ); fprintf ( 1, ' on a sphere, made by subdividing an initial\n' ); fprintf ( 1, ' projected icosahedron.\n' ); fprintf ( 1, '\n' ); fprintf ( 1, ' N determines the number of subdivisions of each\n' ); fprintf ( 1, ' edge of the icosahedral faces.\n' ); fprintf ( 1, '\n' ); fprintf ( 1, ' N V E F\n' ); fprintf ( 1, ' -------- -------- -------- --------\n' ); fprintf ( 1, '\n' ); for factor = 1 : 20 point_num = sphere_icos_point_num ( factor ); edge_num = sphere_icos_edge_num ( factor ); face_num = sphere_icos_face_num ( factor ); fprintf ( 1, ' %8d %8d %8d %8d\n', ... factor, point_num, edge_num, face_num ); end fprintf ( 1, '\n' ); fprintf ( 1, ' Repeat, but using N constrained by doubling:\n' ); fprintf ( 1, '\n' ); fprintf ( 1, ' N V E F\n' ); fprintf ( 1, ' -------- -------- -------- --------\n' ); fprintf ( 1, '\n' ); factor = 1; for factor_log = 0 : 10 point_num = sphere_icos_point_num ( factor ); edge_num = sphere_icos_edge_num ( factor ); face_num = sphere_icos_face_num ( factor ); fprintf ( 1, ' %8d %8d %8d %8d\n', ... factor, point_num, edge_num, face_num ); factor = factor * 2; end return end
const express = require ('express') const app = express() const multer = require("multer") const Contenedor1 = require("../desafio_2") const file = new Contenedor1("productos.txt") // app.use("/static", express.static(__dirname + "/public")) // app.use(express.urlencoded({extended:false})) // app.use(express.json()) app.set("views", "./views") app.set("view engine", "pug") let storage = multer.diskStorage({ //almacenamiento destination: function (req, file, cb) { // Va a setear la carpeta donde se van a guardar mis archivs que vamos a subir por multer cb(null, "upload") // recibe un valor nulo y el nombre de la carpeta donde se van a guardar }, filename: function (req, file, cb) { // como va a ir guardandolos cb(null, file.originalname) // recibe un valor nulo y el nombre del archivo o el parametro file } }) let upload = multer({ storage }) app.get("/", (req, res) => { res.render("index") }) app.post('/', upload.single("foto"), async (req, res) => { const Contenedor1 = require("../desafio_2") const file = new Contenedor1("productos.txt") // const arr = await file.getAll() const objNew = { "title": req.body.nombre, "price": req.body.precio, "thumbnail": req.file.originalname } // arr.push(objNew) file.save(objNew) res.render("landing") }) app.get('/productos', async (req, res) => { const productos = await file.getAll() console.log() res.render("productos",{data:JSON.parse(productos)}) }) app.listen(8080, ()=>{ console.log("Listen Port 8080") })
<script lang="ts" setup> import { ref } from 'vue' const emit = defineEmits({ 'files-dropped': (files: File[]) => true, }) const field = ref<HTMLInputElement>() var isDragging = ref(false) var files = ref<File[]>([]) function onChange() { const fileList = field.value?.files if (fileList) { const newFiles = [...fileList].filter( (file) => !files.value.some( (oldFile) => `${oldFile.name}-${oldFile.size}-${oldFile.lastModified}-${oldFile.type}` === `${file.name}-${file.size}-${file.lastModified}-${file.type}` ) ) files.value.push(...newFiles) emit('files-dropped', files.value) } } function generateThumbnail(file: File) { let fileSrc = URL.createObjectURL(file) setTimeout(() => { URL.revokeObjectURL(fileSrc) }, 1000) return fileSrc } function makeName(name: string) { return ( name.split('.')[0].substring(0, 3) + '...' + name.split('.')[name.split('.').length - 1] ) } function remove(i: number) { files.value.splice(i, 1) } function dragover() { isDragging.value = true } function dragleave() { isDragging.value = false } function drop(e: DragEvent) { const newFiles = e.dataTransfer?.files if (newFiles) { field.value!.files = newFiles } onChange() isDragging.value = false } </script> <template> <div class="main-container"> <v-sheet class="pa-2 ml-10 w-100" style="height: 180px" border rounded="lg" @dragover.prevent="dragover" @dragleave.prevent="dragleave" @drop.prevent="drop" > <input type="file" multiple name="file" id="fileInput" class="hidden-input" @change="onChange" ref="field" accept=".pdf,.jpg,.jpeg,.png" /> <label for="fileInput" class="file-label"> <div v-if="isDragging">Lepasin buat nyimpen berkasnya disini.</div> <div v-else> Lempar berkasnya sini atau <u>klik disini</u> buat upload. </div> </label> <div class="preview-container mt-4" v-if="files.length"> <v-sheet v-for="file in files" :key="`${file.name}-${file.size}-${file.lastModified}-${file.type}`" class="preview-card" rounded="lg" > <div> <img v-if="file.type.split('/')[0] === 'image'" class="preview-img" :src="generateThumbnail(file)" /> <v-icon v-else size="50"> mdi-file </v-icon> <p :title="file.name"> {{ makeName(file.name) }} </p> </div> <div> <button class="ml-2" type="button" @click="remove(files.indexOf(file))" title="Remove file" > <b>&times;</b> </button> </div> </v-sheet> </div> </v-sheet> </div> </template> <style scoped> .main-container { display: flex; flex-grow: 1; align-items: center; justify-content: center; text-align: center; vertical-align: middle; } .hidden-input { opacity: 0; overflow: hidden; position: absolute; width: 1px; height: 1px; } .file-label { font-size: 20px; display: block; cursor: pointer; } .preview-container { display: flex; margin-top: 2rem; } .preview-card { display: flex; border: 1px solid #a2a2a2; padding: 5px; margin-left: 5px; } .preview-img { width: 50px; height: 50px; border-radius: 5px; border: 1px solid #a2a2a2; background-color: #a2a2a2; } </style>
<div class="d-flex justify-content-between"> <h1>List des produits</h1> <button type="button" class="btn btn-outline-dark" [routerLink]="['/admin/product/new']" > <i class="bi bi-plus-lg"></i> Ajouter </button> </div> <!-- Bouton (+) ajouter produit --> <table class="table table-hover mt-5"> <thead> <tr> <!-- Pastille dispo / indispo ? --> <th scope="col">#</th> <th scope="col">Nom</th> <th scope="col">Catégorie</th> <th scope="col">Stock</th> <th scope="col">Prix</th> <th scope="col">Action</th> </tr> </thead> <tbody> <tr *ngFor="let product of products"> <th scope="row">{{ product.id }}</th> <td>{{ product.name }}</td> <td>{{ product.category | titlecase }}</td> <td [ngClass]="{ 'text-danger': !product.stock }">{{ product.stock }}</td> <td>{{ product.price | currency: 'EUR' }}</td> <td> <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editProductModal" (click)="selectProduct(product)" > <i class="bi bi-pencil"></i> </button> <span class="p-1"></span> <button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteProductModal" (click)="selectProduct(product)" > <i class="bi bi-trash"></i> </button> </td> </tr> </tbody> </table> <!-- Edit Modal --> <div class="modal fade" id="editProductModal" tabindex="-1" aria-labelledby="editProductModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content modal-body" *ngIf="selectedProduct"> <app-new-product-form [method]="'edit'" [product]="selectedProduct"></app-new-product-form> </div> </div> </div> <!-- Delete Modal --> <div class="modal fade" id="deleteProductModal" tabindex="-1" aria-labelledby="deleteProductModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="deleteProductModalLabel"> Supprimer un produit </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body"> <span class="text-danger" >Vous êtes sur le point de supprimer définitivement le produit {{ selectedProduct?.name }}</span > <br /> <span>Confirmer la suppression ?</span> </div> <div class="modal-footer" *ngIf="selectedProduct"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> Annuler </button> <button type="button" class="btn btn-danger" (click)="deleteProduct(selectedProduct.id)" > Supprimer </button> </div> </div> </div> </div> <!-- pagination -->
import { OpenAPIHono } from "@hono/zod-openapi"; import { swaggerUI } from "@hono/swagger-ui"; import { userSwaggerRoute } from "./userSwagger"; import { postSwaggerRoute } from "./postSwagger"; import { authSwaggerRoute } from "./authSwagger"; const swaggerRoute = new OpenAPIHono(); swaggerRoute.route("/", userSwaggerRoute); swaggerRoute.route("/", postSwaggerRoute); swaggerRoute.route("/", authSwaggerRoute); swaggerRoute.get( "/ui", swaggerUI({ url: "/doc", }) ); swaggerRoute.openAPIRegistry.registerComponent("securitySchemes", "jwt", { type: "http", scheme: "bearer", }); swaggerRoute.doc("/doc", { info: { title: "NodeJS API", version: "v1", description: "This is a sample NodeJs Server based on the OpenAPI 3.0 specification", }, openapi: "3.1.0", tags: [ { name: "users", description: " Everything about users", }, { name: "post", description: " Everything about posts", }, { name: "auth", description: " Everything about authorization", }, ], }); export default swaggerRoute;
= 상속(Inheritance) * 상속은 "is a kind of" 관계를 지정 * 상속은 클래스 사이의 관계 * 파생된 클래스는 존재하는 클래스에서 전문화됨 image:./images/image09.png[] --- 상속은 클래스 수준에서 지정되는 관계입니다. 새 클래스는 기존 클래스에서 파생될 수 있습니다. 그림에서, `ViolinPlayer` 클래스는 `Musician` 클래스에서 파생됩니다. 이 경우 `Musician` 클래스는 `ViolinPlayer` 클래스의 슈퍼 클래스(Super class) - 기본 클래스(Base class), 부모 클래스(Parent class) 라고 불리기도 합니다 - 라고 불리며, `ViolinPlayer` 클래스는 서브 클래스(Subclass) - 파생된 클래스(Derived class), 자식 클래스(Child class)라고 불리기도 합니다 - 라고 불립니다. 상속은 UML(Unified Modeling Language) 표기법을 사용하여 표시됩니다. 서브 클래스는 슈퍼 클래스에서 모든 것을 상속합니다. 예를 들어 슈퍼 클래스 `Musician` 에 `TuneYourInstrument` 라는 메소드가 포함되어 있으면 이 메소드는 자동으로 서브 클래스 `ViolinPlayer` 클래스의 멤버가 됩니다. 슈퍼 클래스에는 여러 서브 클래스가 있을 수 있습니다. 예를 들어 `FlutePlayer` 나 `GuitarPlayer` 는 모두 `Musician` 클래스에서 파생될 수 있습니다. 이런 파생된 클래스는 슈퍼 클래스의 메소드를 자동으로 상속합니다. == 객체지향 프로그램의 상속 이해 성인 남자와 여자, 여자 아이가 있는 그림을 생각해 봅시다. 남자와 여자가 그 아이의 생물학적 부모라면 여자 아이는 남자로부터 절반의 유전자를, 여자로부터 절반의 유전자를 물려받습니다. 이것은 클래스 상속의 예가 아닙니다. 성인 남자와 여자, 여자 아이가 있는 그림을 객체지향적으로 생각한다면, `Man` 과 `Woman` 클래스가 있고, `Woman` 클래스의 인스턴스가 두 개, `Man` 클래스의 인스턴스가 하나 있는 것입니다. 이 예에서는 클래스간의 상속 관계가 없습니다. 상속관계를 꼭 만들어야 한다면 `Man` 와 `Woman` 두 클래스가 공유하는 행위와 속성들을 가지는 `Person` 클래스를 생성하고 `Person` 클래스가 `Man`, `Woman` 두 클래스의 슈퍼 클래스가 되는 것입니다. `Man`, `Woman` 은 `Person` 에서 전문화되어 각각의 `Person` 클래스의 동작과 속성에서 추가된 동작과 속성을 가지도록 모델링 되어야 합니다. link:./20_oo_system.adoc[이전: 객체지향 시스템 정의] + link:./22_hier.adoc[다음: 클래스 계층구조]
package ServiceLayerTest; import Model.Course; import DAO.CourseDAO; import Exception.ItemAlreadyExistsException; import Exception.ItemDoesNotExistException; import Service.CourseService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static org.mockito.Mockito.times; import java.util.ArrayList; import java.util.List; public class CourseServiceTest { CourseService courseService; CourseDAO mockCourseDAO; /** * Set up the test environment before each test case. * * It creates a Mockito mock for the `CourseDAO` class and initializes the * `courseService` instance with this mock, allowing the testing of the * `CourseService` class in isolation from its actual dependencies. */ @Before public void setUp() { mockCourseDAO = Mockito.mock(CourseDAO.class); courseService = new CourseService(mockCourseDAO); } /** * This test is testing the getAllCourses() method in a CourseService class. * The method gets empty ArrayList from DAO level. * * @Test verifies: * ...that method invoked appropriate method in DAO level precisely one time and * transferred an empty ArrayList from DAO level. */ @Test public void getAllCoursesEmptyArrayTest() { List<Course> courses = new ArrayList<>(); Mockito.when(mockCourseDAO.getAllCourses()).thenReturn(courses); List<Course> actual = courseService.getAllCourses(); Mockito.verify(mockCourseDAO, Mockito.times(1)).getAllCourses(); Assert.assertTrue(actual.isEmpty()); } /** * Tests the behavior of the getAllCourses() method in the CourseService class. * * This test case verifies that the getAllCourses method returns the expected list of courses * by using Mockito to mock the behavior of the CourseDAO dependency. It sets up a mock response * for getAllCourses, calls the method, and then compares the expected and actual results. */ @Test public void getAllCoursesTest() { List<Course> expected = new ArrayList<>(); expected.add(new Course(1, "MATH", 15000, "Number Systems", 4.000, 1)); expected.add(new Course(2, "BIOL", 12300, "Biology 101", 4.000, 1)); Mockito.when(this.mockCourseDAO.getAllCourses()).thenReturn(expected); List<Course> actual = this.courseService.getAllCourses(); Mockito.verify(this.mockCourseDAO, times(1)).getAllCourses(); Assert.assertEquals(expected, actual); } /** * This test is testing the getCourseById() method in a CourseService class. * The method gets instance of a Course class from DAO level. * * @Test verifies: * ...that method invoked appropriate method in DAO level precisely one time and * transferred an instance of a Course class from DAO level. * * @throws ItemDoesNotExistException */ @Test public void getCourseByIdTest() throws ItemDoesNotExistException { int courseId = 1; int teacherId = 1; Course expected = new Course(courseId, "MATH", 15000, "Number Systems", 4.000, teacherId); Mockito.when(this.mockCourseDAO.getCourseById(courseId)).thenReturn(expected); Course actual = this.courseService.getCourseById(courseId); Mockito.verify(this.mockCourseDAO, times(1)).getCourseById(courseId); Assert.assertEquals(expected, actual); } /** * Tests the behavior of the getCoursesByTeacherId() method in the CourseService class. * * This test case verifies that the getCoursesByTeacherId method returns the expected list of courses * when provided with a valid teacher ID. It uses Mockito to mock the behavior of the CourseDAO dependency, * sets up a mock response for getCoursesByTeacherId, calls the method, and compares the expected and actual results. */ @Test public void getCoursesByTeacherIdTest() { int teacherId = 3; List<Course> expected = new ArrayList<>(); expected.add(new Course(4, "ENG", 20200, "Literary Interpretation", 3.0, teacherId)); expected.add(new Course(5, "ENG", 20400, "Introduction to Fiction", 3.0, teacherId)); Mockito.when(this.mockCourseDAO.getCoursesByTeacherId(teacherId)).thenReturn(expected); List<Course> actual = this.courseService.getCoursesByTeacherId(teacherId); Mockito.verify(this.mockCourseDAO, times(1)).getCoursesByTeacherId(teacherId); Assert.assertEquals(expected, actual); } /** * Tests the behavior of the addCourse() method in the CourseService class. * * This test case verifies that the addCourse method successfully adds a new course when provided * with valid course data. It uses Mockito to mock the behavior of the CourseDAO dependency, sets up * the mock response for addCourse to do nothing, calls the method, and verifies that addCourse is * called once with the expected course data. * * @throws ItemAlreadyExistsException If the course being added already exists. * @throws ItemDoesNotExistException If any referenced item (e.g., teacherId) does not exist. */ @Test public void addCourseTest() throws ItemAlreadyExistsException, ItemDoesNotExistException { Course course = new Course(3, "HIST", 30100, "World History", 3.0, 2); Mockito.doNothing().when(this.mockCourseDAO).addCourse(course); this.courseService.addCourse(course); Mockito.verify(this.mockCourseDAO, times(1)).addCourse(course); } /** * Tests the behavior of the deleteCourse() method in the CourseService class. * * This test case verifies that the deleteCourse method successfully deletes a course when provided * with a valid course ID. It uses Mockito to mock the behavior of the CourseDAO dependency, sets up * the mock response for deleteCourse to do nothing, calls the method, and verifies that deleteCourse is * called once with the expected course ID. * * @throws ItemDoesNotExistException If the course being deleted does not exist. */ @Test public void deleteCourseTest() throws ItemDoesNotExistException { int courseId = 2; Mockito.doNothing().when(this.mockCourseDAO).deleteCourse(courseId); this.courseService.deleteCourse(courseId); Mockito.verify(this.mockCourseDAO, times(1)).deleteCourse(courseId); } /** * Tests the behavior of the updateCourse() method in the CourseService class. * * This test case verifies that the updateCourse method successfully updates a course when provided * with valid updated course data. It uses Mockito to mock the behavior of the CourseDAO dependency, sets up * the mock response for updateCourse to do nothing, calls the method, and verifies that updateCourse is * called once with the expected updated course data. * * @throws ItemDoesNotExistException If the course being updated does not exist. */ @Test public void updateCourseTest() throws ItemDoesNotExistException { Course course = new Course(1, "MATH", 10100, "Advanced Algebra", 4.0, 1); Mockito.doNothing().when(this.mockCourseDAO).updateCourse(course); this.courseService.updateCourse(course); Mockito.verify(this.mockCourseDAO, times(1)).updateCourse(course); } }
import { faLocationDot, faCheck, faTrashAlt, } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useContext, useEffect, useRef, useState } from "react"; import { AuthContext } from "../../context/AuthContext"; import { formatDaysLeft, formatDaysToStart, formatNumber, revertTimeStamp, } from "../../components/longFunctions"; import axios from "axios"; import CashOnDelivery from "../../images/cash-on-delivery-icon.png"; import WalletBanking from "../../images/wallet-banking-icon.png"; import WarningIcon from "../../images/warning-icon.png"; import ConfirmCheckout from "../../images/confirm-checkout.png"; import BreadCrumb from "../../components/Customer/BreadCrumb/BreadCrumb"; import "./checkout.css"; import { useToast } from "@chakra-ui/react"; import { useHistory } from "react-router-dom"; import Footer from "../../components/Customer/Footer/Footer"; import BazaarBayIcon from "../../images/bazaarbay-icon.ico"; import { faClock } from "@fortawesome/free-regular-svg-icons"; import CustomerPopup from "../../components/Customer/CustomerPopup/CustomerPopup"; const Checkout = () => { const { BACKEND_URL, config, currentUser, setCurrentUser } = useContext(AuthContext); const [storeProducts, setStoreProducts] = useState([]); const [deliveryPartners, setDeliveryPartners] = useState([]); const [address, setAddress] = useState( currentUser.addresses[currentUser.addresses.length - 1] ); const [vouchers, setVouchers] = useState([]); const [selectedPaymentMethod, setSelectedPaymentMethod] = useState("CASH_ON_DELIVERY"); const [loading, setLoading] = useState(false); const [selectedAddress, setSelectedAddress] = useState(address); const [selectedVouchers, setSelectedVouchers] = useState([]); const [chosenVouchers, setChosenVouchers] = useState([]); const [voucherIds, setVoucherIds] = useState([]); const [creditCards, setCreditCards] = useState([]); const [selectedDeliveryPartnerId, setSelectedDeliveryPartnerId] = useState(0); const [shippingFee, setShippingFee] = useState(0); const [voucherDiscount, setVoucherDiscount] = useState(0); const [couponDiscount, setCouponDiscount] = useState(0); const [openProvideInfo, setOpenProvideInfo] = useState(false); const [openChooseAddress, setOpenChooseAddress] = useState(false); const [openConfirmCheckout, setOpenConfirmCheckout] = useState(false); const [openChooseVoucher, setOpenChooseVoucher] = useState(false); const [openPopup, setOpenPopup] = useState(false); const [popupType, setPopupType] = useState(""); const [openChooseDeliveryPartner, setOpenChooseDeliveryPartner] = useState(false); const provideInfo = useRef(); const chooseAddressRef = useRef(); const chooseDeliveryPartnerRef = useRef(); const chooseVoucherRef = useRef(); const toast = useToast(); const history = useHistory(); const subTotalPrice = storeProducts.reduce((accumulator, currentValue) => { const itemTotal = currentValue.items.reduce((itemAccumulator, item) => { return itemAccumulator + item.product.price * item.quantity; }, 0); return accumulator + itemTotal; }, 0); const fetchCart = async () => { try { const { data } = await axios.get( `${BACKEND_URL}/api/customer/cart`, config ); setStoreProducts(data.data); } catch (error) { if ( error.response.data.message === "Your account is locked! Please contact admin to unlock your account!" ) { setOpenPopup(true); setPopupType("account-locked"); return; } toast({ title: "An error occurred adding product to cart", status: "error", duration: 3000, isClosable: true, position: "bottom", }); } }; const fetchVoucher = async () => { try { const { data } = await axios.get( `${BACKEND_URL}/api/customer/vouchers-coupons-to-add-to-cart`, config ); setVouchers(data.data.usable); } catch (error) {} }; const fetchDeliveryPartners = async () => { try { const { data } = await axios.get(`${BACKEND_URL}/api/delivery-partners`); setDeliveryPartners(data.data.content); setSelectedDeliveryPartnerId(8); } catch (error) {} }; const handleChooseVoucher = (voucher) => { if (chosenVouchers.some((v) => v.id === voucher.id)) { setChosenVouchers(chosenVouchers.filter((v) => v.id !== voucher.id)); } else { setChosenVouchers([...chosenVouchers, voucher]); } }; const handleAddVoucherToCart = async () => { if ( chosenVouchers.filter((v) => v.type === "voucher").length > 1 || chosenVouchers.filter((v) => v.type === "coupon").length > 1 ) { return toast({ title: "You may choose only one voucher and/or one coupon!", status: "warning", duration: 3000, isClosable: true, position: "bottom", }); } setSelectedVouchers(chosenVouchers); setOpenChooseVoucher(false); }; const handleRemoveVoucherFromCart = async (voucher) => { setSelectedVouchers(chosenVouchers.filter((v) => v.id !== voucher.id)); setChosenVouchers(chosenVouchers.filter((v) => v.id !== voucher.id)); }; const fetchCreditCard = async () => { try { const { data } = await axios.get( `${BACKEND_URL}/api/customer/payment-information`, config ); setCreditCards(data.data); } catch (error) {} }; const handleClickOnlinePayment = () => { if (creditCards.length > 0) { setSelectedPaymentMethod("ONLINE_PAYMENT"); } else { setOpenPopup(true); setPopupType("nav-credit-card"); } }; const handleCheckout = async () => { if (currentUser.addresses.length === 0 || !currentUser.phoneNumber) { setOpenProvideInfo(true); return; } else { setLoading(true); try { voucherIds.length > 0 && (await axios.put( `${BACKEND_URL}/api/customer/add-voucher-coupon-to-cart`, { promotionIds: voucherIds, }, config )); await axios.post( `${BACKEND_URL}/api/customer/checkout`, { deliveryPartnerId: selectedDeliveryPartnerId, destinationAddress: selectedAddress, paymentMethod: selectedPaymentMethod, }, config ); toast({ title: "Checkout successful", status: "success", duration: 3000, isClosable: true, position: "bottom", }); setLoading(false); setOpenConfirmCheckout(true); await axios.put( `${BACKEND_URL}/api/customer/remove-all-voucher-coupon-from-cart`, {}, config ); const { data } = await axios.get( `${BACKEND_URL}/api/customer/account`, config ); setCurrentUser(data.data); } catch (error) { if ( error.response.data.message === "Your account is locked! Please contact admin to unlock your account!" ) { setLoading(false); setPopupType("account-locked"); setOpenPopup(true); return; } if (error.response.data.message === "Not enough balance to checkout") { setLoading(false); return toast({ title: "Not enough balance to checkout!", status: "error", duration: 3000, isClosable: true, position: "bottom", }); } toast({ title: "An error occurred checking out", status: "error", duration: 3000, isClosable: true, position: "bottom", }); setLoading(false); } } }; window.addEventListener("beforeunload", async function (event) { await axios.put( `${BACKEND_URL}/api/customer/remove-all-voucher-coupon-from-cart`, {}, config ); }); useEffect(() => { fetchCart(); fetchVoucher(); fetchDeliveryPartners(); fetchCreditCard(); document.title = "Checkout | BazaarBay"; }, []); useEffect(() => { setCouponDiscount( selectedVouchers.filter((item) => item.type === "coupon")[0]?.percent || 0 ); setVoucherDiscount( selectedVouchers.filter((item) => item.type === "voucher")[0]?.percent || 0 ); setVoucherIds(selectedVouchers.map((voucher) => voucher.id)); }, [selectedVouchers]); useEffect(() => { if (deliveryPartners.length > 0) { setShippingFee( deliveryPartners.filter( (deliveryPartner) => deliveryPartner.id === selectedDeliveryPartnerId )[0].shippingFee ); } }, [selectedDeliveryPartnerId]); useEffect(() => { function handleClickOutside(event) { if ( chooseAddressRef.current && !chooseAddressRef.current.contains(event.target) ) { setOpenChooseAddress(false); } if ( chooseDeliveryPartnerRef.current && !chooseDeliveryPartnerRef.current.contains(event.target) ) { setOpenChooseDeliveryPartner(false); } if (provideInfo.current && !provideInfo.current.contains(event.target)) { setOpenProvideInfo(false); } if ( chooseVoucherRef.current && !chooseVoucherRef.current.contains(event.target) ) { setOpenChooseVoucher(false); } } document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [ chooseAddressRef, chooseDeliveryPartnerRef, provideInfo, chooseVoucherRef, ]); return ( <div className="checkout" style={{ overflow: openChooseAddress ? "hidden" : "scroll" }} > <BreadCrumb title="Cart / Checkout" /> <div className="checkoutContainer"> <div className="deliveryLocation"> <div className="deliveryTitle"> <FontAwesomeIcon icon={faLocationDot} className="locationIcon" /> <h2>Delivery Location</h2> </div> <div className="customerLocationInfo"> <span className="customerName">{currentUser.name}</span> <span className="customerPhone">{currentUser.phoneNumber}</span> <span className="customerLocation">{address}</span> <button className="button" onClick={() => setOpenChooseAddress(true)} > Change </button> </div> </div> {storeProducts.map((product) => ( <div className="checkoutProducts" key={product.id}> <div className="shopInfo"> <img src={product.store.avatar} alt="" className="shopAvatar" /> <span className="shopName">{product.store.name}</span> </div> <table> <thead> <tr style={{ display: "flex", paddingBottom: "15px" }}> <th style={{ flex: "6", color: "#222", fontSize: "18px", fontWeight: "600", paddingRight: "15px", }} > Product </th> <th style={{ flex: "1.5" }}>Price</th> <th style={{ flex: "1.5", textAlign: "center" }}>Quantity</th> <th style={{ flex: "2.5", textAlign: "right" }}>Subtotal</th> </tr> </thead> <tbody> {product.items.map((item) => ( <tr style={{ display: "flex" }}> <td style={{ flex: "6", display: "flex", alignItems: "center", gap: "15px", paddingRight: "15px", }} > <img src={item.product.images[0]} alt="" /> <span>{item.product.name}</span> </td> <td style={{ flex: "1.5" }}> <span className="price-symbol">₫</span> {formatNumber(item.product.price)} </td> <td style={{ flex: "1.5", justifyContent: "center" }}> {item.quantity} </td> <td style={{ flex: "2.5", justifyContent: "flex-end" }}> <span className="price-symbol">₫</span> {formatNumber(item.product.price * item.quantity)} </td> </tr> ))} </tbody> </table> <div className="totalProductPrice"> <span>{`Total price (${product.items.reduce( (accumulator, item) => { return accumulator + item.quantity; }, 0 )} product${ product.items.reduce((accumulator, item) => { return accumulator + item.quantity; }, 0) > 1 ? "s" : "" }): `}</span> <span> <span className="price-symbol">₫</span> {formatNumber( product.items.reduce((accumulator, item) => { return accumulator + item.product.price * item.quantity; }, 0) )} </span> </div> </div> ))} <div className="deliveryOption"> <div className="deliveryPartner"> <span className="deliveryHeading">Delivery Partner: </span> <span className="deliveryPartnerName"> {deliveryPartners.length > 0 && deliveryPartners.filter( (deliveryPartner) => deliveryPartner.id === selectedDeliveryPartnerId )[0].name} </span> <button className="button" onClick={() => setOpenChooseDeliveryPartner(true)} > Change </button> </div> </div> <div className="voucherOption"> <div className="voucherOptionContainer"> <h2>Voucher / Coupon</h2> <div className="chosenVouchers"> {selectedVouchers.map((voucher) => ( <div className="voucher" key={voucher.id}> <div className="voucherLeft"> {voucher.store && ( <div className="voucherOptionImage voucherStore"> <img src={voucher.store.avatar} alt="" /> <span>{voucher.store.name}</span> </div> )} {!voucher.store && ( <div className="voucherOptionImage"> <img src={BazaarBayIcon} alt="" /> <span>BazaarBay</span> </div> )} <div className="voucherInfo"> <div className="voucherBasicInfo"> <h2 className="voucherPercent">{`Discount ${voucher.percent}%`}</h2> </div> </div> </div> <div className="voucherRemove" onClick={() => handleRemoveVoucherFromCart(voucher)} > <FontAwesomeIcon icon={faTrashAlt} /> </div> </div> ))} </div> <button className="button" onClick={() => { setOpenChooseVoucher(true); setChosenVouchers(selectedVouchers); }} > Choose </button> </div> </div> <div className="cartTotal"> <div className="cartTotalContainer"> <div className="paymentMethod"> <span>Payment method</span> <div className={ selectedPaymentMethod === "CASH_ON_DELIVERY" ? "paymentItem selectedPaymentMethod" : "paymentItem" } onClick={() => setSelectedPaymentMethod("CASH_ON_DELIVERY")} > <img src={CashOnDelivery} alt="" /> <span>Cash On Delivery</span> </div> <div className={ selectedPaymentMethod === "ONLINE_PAYMENT" ? "paymentItem selectedPaymentMethod" : "paymentItem" } onClick={() => handleClickOnlinePayment()} > <img src={WalletBanking} alt="" /> <span>Bazaar Wallet</span> </div> </div> <div className="cartTotalPrice"> <div className="cartTotalPriceContainer"> <table> <tbody> <tr> <td className="priceHeading">Product Price:</td> <td className="price"> <span className="price-symbol">₫</span> {formatNumber(subTotalPrice)} </td> </tr> {couponDiscount > 0 && ( <tr> <td className="priceHeading">Coupon Discount:</td> <td className="price"> <span className="price-symbol"></span> {`${couponDiscount}%`} </td> </tr> )} {voucherDiscount > 0 && ( <tr> <td className="priceHeading">Voucher Discount:</td> <td className="price"> <span className="price-symbol"></span> {`${voucherDiscount}%`} </td> </tr> )} <tr> <td className="priceHeading">Shipment Fee:</td> <td className="price"> <span className="price-symbol">₫</span> {formatNumber(shippingFee)} </td> </tr> <tr style={{ paddingTop: "20px" }}> <td className="priceHeading">Total Price:</td> <td className="priceTotalContainer"> {(couponDiscount > 0 || voucherDiscount > 0) && ( <div className="price initialPrice"> <span className="price-symbol"></span> {"₫" + formatNumber(subTotalPrice + shippingFee)} </div> )} <div className="price totalPrice"> {"₫" + formatNumber( ( subTotalPrice * ((100 - couponDiscount) / 100) * ((100 - voucherDiscount) / 100) + shippingFee ).toFixed(0) )} </div> </td> </tr> </tbody> </table> <button className="checkoutButton" onClick={handleCheckout} style={{ padding: loading ? "15px 55px 15px 63px" : "15px 40px", }} > {loading ? ( <div className="loginLoading"> <div class="lds-ring"> <div></div> <div></div> <div></div> <div></div> </div> </div> ) : ( "Checkout" )} </button> </div> </div> </div> </div> </div> <div className={ openChooseAddress ? "chooseAddress open" : "chooseAddress close" } > <div className="chooseAddressContainer" ref={chooseAddressRef}> <h2>My Address</h2> <ul> {currentUser.addresses.map((a, i) => ( <li key={i} className={a === selectedAddress ? "selected" : ""} onClick={() => setSelectedAddress(a)} > {a} </li> ))} </ul> <div className="chooseAddressButtons"> <button className="button" onClick={() => setOpenChooseAddress(false)} > Cancel </button> <button className="button" onClick={() => { setAddress(selectedAddress); setOpenChooseAddress(false); }} > Confirm </button> </div> </div> </div> <div className={ openChooseDeliveryPartner ? "chooseDeliveryPartner open" : "chooseDeliveryPartner close" } > <div className="chooseDeliveryPartnerContainer" ref={chooseDeliveryPartnerRef} > <h2 className="chooseDeliveryPartnerHeading"> Choose Delivery Partner </h2> <ul> {deliveryPartners.map((deliveryPartner) => ( <li key={deliveryPartner.id} onClick={() => { setSelectedDeliveryPartnerId(deliveryPartner.id); setOpenChooseDeliveryPartner(false); }} > <div className="deliveryPartnerLeft"> <div className="deliveryPartnerAvatar"> <img src={deliveryPartner.avatar} alt="" /> </div> <div className="deliveryPartnerInfo"> <h2>{deliveryPartner.name}</h2> <span>{deliveryPartner.description}</span> </div> </div> <div className="deliveryPartnerRight"> <span> <span className="price-symbol">₫</span> {formatNumber(deliveryPartner.shippingFee)} </span> </div> </li> ))} </ul> </div> </div> <div className={openProvideInfo ? "provideInfo open" : "provideInfo close"} > <div className="provideInfoContainer" ref={provideInfo}> <img src={WarningIcon} alt="" /> <h2>Your account does not have phone number or address!</h2> <span>Please provide phone number and address</span> <button className="button" onClick={() => { if (!currentUser.phoneNumber) history.push("/account/profile"); else if (currentUser.addresses.length === 0) history.push("/account/address"); }} > OK </button> </div> </div> <div className={ openConfirmCheckout ? "confirmCheckout open" : "confirmCheckout close" } > <div className="confirmCheckoutContainer"> <h2 className="confirmTitle">Your order has been received</h2> <div className="confirmImage"> <img src={ConfirmCheckout} alt="" /> <div className="confirmText"> <h2>{`Hey ${currentUser.name},`}</h2> <span className="thankText">Thanks for your purchase!</span> </div> </div> <button className="confirmButton" onClick={() => history.push("/")}> Continue Shopping </button> </div> </div> <div className={ openChooseVoucher ? "chooseVoucher open" : "chooseVoucher close" } > <div className="chooseVoucherContainer" ref={chooseVoucherRef}> <h2>Choose your voucher/coupon</h2> <div className="vouchersToAdd"> {vouchers.map((voucher) => ( <div className="voucher" style={{ textAlign: "left" }} onClick={() => handleChooseVoucher(voucher)} > <div className="voucherLeft"> {voucher.store && ( <div className="voucherImage storeCoupon"> <img src={voucher.store.avatar} alt="" /> <span>{voucher.store.name}</span> </div> )} {!voucher.store && ( <div className="voucherImage"> <img src={BazaarBayIcon} alt="" /> <span>BazaarBay</span> </div> )} <div className="voucherInfo"> <div className="voucherBasicInfo"> <h2 className="voucherPercent"> {`Discount ${voucher.percent}%`} </h2> <span className="voucherDescription"> {`${voucher.description.substring(0, 60)}${ voucher.description.length > 60 ? "..." : "" }`} </span> </div> {revertTimeStamp(voucher.startAt) >= revertTimeStamp(new Date()) && ( <span className="voucherExpired"> <FontAwesomeIcon icon={faClock} /> <span>{formatDaysToStart(voucher.startAt)}</span> </span> )} {revertTimeStamp(voucher.startAt) < revertTimeStamp(new Date()) && ( <span className="voucherExpired"> <FontAwesomeIcon icon={faClock} /> <span>{formatDaysLeft(voucher.expiredAt)}</span> </span> )} </div> </div> <div className="voucherCheck"> <div className="voucherCheckContainer"> {chosenVouchers.some((v) => v.id === voucher.id) && ( <FontAwesomeIcon icon={faCheck} /> )} </div> </div> </div> ))} </div> <div className="chooseVoucherButtons"> <button className="button" onClick={() => handleAddVoucherToCart()}> OK </button> <button className="button cancel" onClick={() => { setOpenChooseVoucher(false); }} > Cancel </button> </div> </div> </div> <CustomerPopup open={openPopup} setOpen={setOpenPopup} popupType={popupType} /> <Footer /> </div> ); }; export default Checkout;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Exercise 11</title> <script> function fun() { // synchronous if (Math.random() <= 0.5) throw "Something is wrong!"; return 42; } function gun() { // asynchronous return new Promise((resolve, reject) => { if (Math.random() <= 0.5) reject("Something is wrong!"); resolve(42); }); } try{ console.log(fun()); }catch (e) { console.error(e); } gun().then(console.log).catch(console.error) async function sun() { // asynchronous if (Math.random() <= 0.5) throw "Something is wrong!"; return 42; } sun().then(console.log).catch(console.error) let result = await sun(); </script> </head> <body> </body> </html>
const express = require("express"); const bcrypt = require("bcrypt"); const User = require("../models/User"); const Category = require("../models/Category"); const Article = require("../models/Article"); const router = express.Router(); function checkAuthenticated(req, res, next) { if (req.session.user) { return next(); } res.redirect("/login"); } function checkAdmin(req, res, next) { if (req.session.adminAuthenticated) { return next(); } res.redirect("/admin-login"); } router.get("/", checkAuthenticated, async (req, res) => { let page = parseInt(req.query.page) || 1; let limit = 10; try { let articles = await Article.find() .sort({ createdAt: -1 }) .skip((page - 1) * limit) .limit(limit) .populate("category"); let totalArticles = await Article.countDocuments(); res.render("index", { username: req.session.user.username, articles, currentPage: page, totalPages: Math.ceil(totalArticles / limit), }); } catch (error) { console.log(error); res.redirect("/"); } }); router.get("/register", (req, res) => { res.render("register"); }); router.post("/register", async (req, res) => { try { if (req.body.password !== req.body.passwordConfirm) { throw new Error("Les mots de passe ne correspondent pas"); } const user = new User(req.body); await user.save(); req.session.user = user; res.redirect("/"); } catch (error) { res.redirect("/register"); } }); router.get("/login", (req, res) => { res.render("login"); }); router.post("/login", async (req, res) => { const user = await User.findOne({ email: req.body.email }); if (user && (await bcrypt.compare(req.body.password, user.password))) { req.session.user = user; res.redirect("/"); } else { res.redirect("/login"); } }); router.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/login"); }); router.get("/admin-login", (req, res) => { res.render("admin-login"); }); router.post("/admin-login", (req, res) => { const adminPassword = process.env.ADMIN_PASSWORD; if (req.body.password === adminPassword) { req.session.adminAuthenticated = true; res.redirect("/admin"); } else { res.redirect("/admin-login"); } }); module.exports = router;
import assert from 'assert'; import { app } from 'egg-mock/bootstrap'; import { TestUtil } from '../../../../test/TestUtil'; describe('test/port/controller/PackageBlockController/unblockPackage.test.ts', () => { let adminUser: any; beforeEach(async () => { adminUser = await TestUtil.createAdmin(); }); describe('[DELETE /-/package/:fullname/blocks] unblockPackage()', () => { it('should 200 when admin request', async () => { const { pkg } = await TestUtil.createPackage({ isPrivate: false }); let res = await app.httpRequest() .delete(`/-/package/${pkg.name}/blocks`) .set('authorization', adminUser.authorization); assert(res.status === 200); assert(res.body.ok === true); res = await app.httpRequest() .put(`/-/package/${pkg.name}/blocks`) .set('authorization', adminUser.authorization) .send({ reason: 'only for tests', }); assert(res.status === 201); assert(res.body.ok === true); assert(res.body.id); res = await app.httpRequest() .delete(`/-/package/${pkg.name}/blocks`) .set('authorization', adminUser.authorization); assert(res.status === 200); assert(res.body.ok === true); // get blocks res = await app.httpRequest() .get(`/-/package/${pkg.name}/blocks`); assert(res.status === 200); assert(res.body.data.length === 0); // block again res = await app.httpRequest() .put(`/-/package/${pkg.name}/blocks`) .set('authorization', adminUser.authorization) .send({ reason: 'only for tests', }); assert(res.status === 201); assert(res.body.ok === true); res = await app.httpRequest() .get(`/-/package/${pkg.name}/blocks`); assert(res.status === 200); assert(res.body.data.length === 1); // unblock gain res = await app.httpRequest() .delete(`/-/package/${pkg.name}/blocks`) .set('authorization', adminUser.authorization); assert(res.status === 200); assert(res.body.ok === true); res = await app.httpRequest() .get(`/-/package/${pkg.name}/blocks`); assert(res.status === 200); assert(res.body.data.length === 0); }); it('should 403 block private package', async () => { const { pkg } = await TestUtil.createPackage({ isPrivate: true }); const res = await app.httpRequest() .delete(`/-/package/${pkg.name}/blocks`) .set('authorization', adminUser.authorization); assert(res.status === 403); assert(res.body.error === '[FORBIDDEN] Can\'t unblock private package "@cnpm/testmodule"'); }); it('should 403 when user is not admin', async () => { const user = await TestUtil.createUser(); const { pkg } = await TestUtil.createPackage({ isPrivate: true }); let res = await app.httpRequest() .delete(`/-/package/${pkg.name}/blocks`) .set('authorization', user.authorization); assert(res.status === 403); assert(res.body.error === '[FORBIDDEN] Not allow to access'); res = await app.httpRequest() .delete(`/-/package/${pkg.name}/blocks`); assert(res.status === 403); assert(res.body.error === '[FORBIDDEN] Not allow to access'); }); }); });
import React, { useEffect, useState } from "react"; import Avatar from "@mui/material/Avatar"; import Button from "@mui/material/Button"; import CssBaseline from "@mui/material/CssBaseline"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomplete"; import Link from "@mui/material/Link"; import Grid from "@mui/material/Grid"; import { useFormik } from "formik"; import * as yup from "yup"; import { toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import Box from "@mui/material/Box"; import Typography from "@mui/material/Typography"; import Container from "@mui/material/Container"; import { createTheme, ThemeProvider } from "@mui/material/styles"; import { useNavigate } from "react-router-dom"; import { Stack } from "@mui/material"; import { Address } from "./Address"; import Cookies from "js-cookie"; const cityAddress = Address; const validationSchema = yup.object({ name: yup .string("Enter your name") .trim("Invalid name") .min(3, "Minimum 3 Letter Name") .max(10) .required("Name is required"), email: yup .string("Enter your email") .trim("Invalid Email") .email("Enter a valid email") .required("Email is required"), password: yup .string("Enter your password") .trim("Invalid Password") .min(6, "Password should be of minimum 6 characters length") .required("Password is required"), addressLine1: yup .string("Enter Address Line 1") .trim() .min(3) .required("Address Line 1 is required"), addressLine2: yup .string("Enter Address Line 2") .trim() .min(3) .required("Address Line 2 is required"), city: yup .string("City is required") .trim() .min(3, "city name is too short") .required("City is required"), state: yup .string("state is required") .trim() .min(3, "state name is too short") .required("State is required"), postalcode: yup .string("Postal Code is required") .trim() .min(3, "postal code is too short") .required("Postal code is required"), country: yup .string("country is required") .trim() .min(3, "country name is too short") .required("Country is required"), }); function Copyright(props) { return ( <Typography variant="body2" color="text.secondary" align="center" {...props} > {"Copyright © "} <Link color="inherit">Food App</Link> {new Date().getFullYear()} {"."} </Typography> ); } const theme = createTheme(); export function Register() { const navigate = useNavigate(); const formik = useFormik({ initialValues: { name: "", email: "", password: "", addressLine1: "", addressLine2: "", city: "", state: "", postalcode: "", country: "", }, validationSchema: validationSchema, onSubmit: (value) => { let userData = JSON.parse(localStorage.getItem("UserData")) || []; const existingUser = userData.find((user) => user.email === value.email); if (existingUser) { toast.error("User Exists,Try New Email", { position: "top-right", autoClose: 4000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); return; } localStorage.setItem("UserData", JSON.stringify([...userData, value])); navigate("/login"); }, }); useEffect(() => { let cookie = Cookies.get("foo"); if (cookie) { navigate("/"); } }, []); return ( <ThemeProvider theme={theme}> <Container component="main" maxWidth="md"> <CssBaseline /> <Box sx={{ marginTop: 8, display: "flex", flexDirection: "column", alignItems: "center", }} > <Avatar sx={{ m: 1, bgcolor: "secondary.main" }}></Avatar> <Typography component="h1" variant="h5"> Register </Typography> <Box component="form" onSubmit={formik.handleSubmit} noValidate sx={{ mt: 1 }} > <Grid container direction="row" justifyContent="start" alignItems="center" spacing={2} mt={3} sx={{ width: "100%", margin: "auto" }} > <Grid item md={6}> <TextField margin="normal" required fullWidth id="name" type="name" value={formik.values.name} onChange={formik.handleChange} error={formik.touched.name && Boolean(formik.errors.name)} helperText={formik.touched.name && formik.errors.name} label="Name" name="name" autoComplete="name" /> </Grid> <Grid item md={6}> <TextField margin="normal" required fullWidth id="email" type="email" value={formik.values.email} onChange={formik.handleChange} error={formik.touched.email && Boolean(formik.errors.email)} helperText={formik.touched.email && formik.errors.email} label="Email Address" name="email" autoComplete="email" /> </Grid> <Grid item md={6}> <TextField margin="normal" required fullWidth id="password" type="password" value={formik.values.password} onChange={formik.handleChange} error={ formik.touched.password && Boolean(formik.errors.password) } helperText={formik.touched.password && formik.errors.password} label="Password" name="password" autoComplete="password" /> </Grid> </Grid> <Stack direction="column" spacing={2} justifyContent="center" alignItems="center" sx={{ padding: "15px" }} > <TextField margin="normal" required fullWidth id="addressLine1" type="text" value={formik.values.addressLine1} onChange={formik.handleChange} error={ formik.touched.addressLine1 && Boolean(formik.errors.addressLine1) } helperText={ formik.touched.addressLine1 && formik.errors.addressLine1 } label="Address Line 1" name="addressLine1" autoComplete="addressLine1" /> <TextField margin="normal" required fullWidth id="addressLine2" type="text" value={formik.values.addressLine2} onChange={formik.handleChange} error={ formik.touched.addressLine2 && Boolean(formik.errors.addressLine2) } helperText={ formik.touched.addressLine2 && formik.errors.addressLine2 } label="Address Line 2 " name="addressLine2" autoComplete="addressLine2" /> </Stack> <Grid container direction="row" justifyContent="start" alignItems="center" spacing={2} mt={3} sx={{ width: "100%", margin: "auto" }} > <Grid item> {/* <TextField margin="normal" required fullWidth id="city" list="cityList" type="city" value={formik.values.city} onChange={formik.handleChange} onBlur={()=>{ }} error={formik.touched.city && Boolean(formik.errors.city)} helperText={formik.touched.city && formik.errors.city} label="City" name="city" autoComplete="city" /> */} <Autocomplete freeSolo id="combo-box-demo" options={cityAddress} sx={{ width: 300 }} renderInput={(params) => ( <TextField {...params} required fullWidth id="city" list="cityList" type="city" value={formik.values.city} onChange={formik.handleChange} onBlur={(e) => { let city = e.target.value; if (city.length > 2) { let cityExist = cityAddress.find( (eachCity) => eachCity.label === city ); if (cityExist) { formik.setFieldValue("city", cityExist.label); formik.setFieldValue("country", cityExist.country); formik.setFieldValue( "postalcode", cityExist.pincode ); formik.setFieldValue("state", cityExist.state); } } }} error={formik.touched.city && Boolean(formik.errors.city)} helperText={formik.touched.city && formik.errors.city} label="City" name="city" autoComplete="city" /> )} /> <datalist id="cityList"> <option value="HSR Layout">HSR Layout</option> <option value="Kormangala">Kormnagala</option> <option value="Madiwala">Madiwala</option> <option value="BTM Layout">BTM Layout</option> </datalist> </Grid> <Grid item> <TextField margin="normal" required fullWidth id="state" type="text" value={formik.values.state} onChange={formik.handleChange} error={formik.touched.state && Boolean(formik.errors.state)} helperText={formik.touched.state && formik.errors.state} label="State/Region" name="state" autoComplete="state" /> </Grid> <Grid item> <TextField margin="normal" required fullWidth id="postalcode" type="text" value={formik.values.postalcode} onChange={formik.handleChange} error={ formik.touched.postalcode && Boolean(formik.errors.postalcode) } helperText={ formik.touched.postalcode && formik.errors.postalcode } label="Postal Code" name="postalcode" autoComplete="postalcode" /> </Grid> <Grid item> <TextField margin="normal" required fullWidth id="country" type="text" value={formik.values.country} onChange={formik.handleChange} error={ formik.touched.country && Boolean(formik.errors.country) } helperText={formik.touched.country && formik.errors.country} label="Country" name="country" autoComplete="country" /> </Grid> </Grid> <Box sx={{ textAlign: "center" }}> <Button type="submit" variant="contained" sx={{ mt: 3, mb: 2 }}> Sign Up </Button> </Box> <Grid container> <Grid item> <Link onClick={() => { navigate("/login"); }} variant="body2" > {"Have an account? Login"} </Link> </Grid> </Grid> </Box> </Box> <Copyright sx={{ mt: 8, mb: 4 }} /> </Container> </ThemeProvider> ); }
import { Request, Response } from 'express'; import { ICardSchema } from '../models/card'; const Card = require('../models/card'); const Category = require('../models/category'); const { cloudinary } = require('../utils/cloudinary'); export interface IWordRes { word: string; translation: string; image: string; audioSrc: string; category: string; } class CardController { async getCard(req:Request, res:Response) { try { const number = <string>req.query.number; const category = <string>req.query.category; const cardArr:ICardSchema[] = await Card.find({ category }); cardArr.splice(parseInt(number, 10), cardArr.length); const result: IWordRes[] = []; cardArr.forEach((element) => result.push({ word: element.word, translation: element.translation, image: element.image, audioSrc: element.audioSrc, category: element.category, })); return res.send(result); } catch (e) { console.log(e); return res.status(500).json({ message: `Can not get cards${e}` }); } } async createCard(req:Request, res:Response) { try { const { word, category, translation, number, } = req.body; const files = req.files! as { [fieldname: string]: Express.Multer.File[] }; const uploadImg = await cloudinary.uploader.upload(files.img[0].path, { resource_type: 'image' }); const uploadAudio = await cloudinary.uploader.upload(files.audio[0].path, { resource_type: 'video' }); const newDBCard = new Card({ word, translation, image: uploadImg.url, audioSrc: uploadAudio.url, category, image_Id: uploadImg.public_id, audioSrc_Id: uploadAudio.public_id, }); const cardCategory = await Category.findOne({ category }); const newWordsNumber = cardCategory.wordsNumber + 1; await Category.findOneAndUpdate({ category }, { wordsNumber: newWordsNumber }); await newDBCard.save(); const cardArr:ICardSchema[] = await Card.find({ category }); cardArr.splice(parseInt(number, 10), cardArr.length); const result: IWordRes[] = []; cardArr.forEach((element) => result.push({ word: element.word, translation: element.translation, image: element.image, audioSrc: element.audioSrc, category: element.category, })); return res.send(result); } catch (e) { console.log(e); return res.status(500).json({ message: e }); } } async deleteCard(req:Request, res:Response) { try { const number = <string>req.query.number; const category = <string>req.query.category; const word = <string>req.query.word; const card = await Card.findOne({ word, category }); if (!card) { throw new Error('Card not found to delite'); } await cloudinary.uploader.destroy(card.image_Id, { invalidate: true, resource_type: 'image' }); await cloudinary.uploader.destroy(card.audioSrc_Id, { invalidate: true, resource_type: 'video' }); const categoryUpdate = await Category.findOne( { category }, ); await Category.findOneAndUpdate( { category }, { wordsNumber: categoryUpdate.wordsNumber - 1 }, ); await card.remove(); const cardArr:ICardSchema[] = await Card.find({ category }); cardArr.splice(parseInt(number, 10), cardArr.length); const result: IWordRes[] = []; cardArr.forEach((element) => result.push({ word: element.word, translation: element.translation, image: element.image, audioSrc: element.audioSrc, category: element.category, })); return res.send(result); } catch (e) { console.log(e); return res.status(400).json({ message: `Cannot delete card${e}` }); } } async updateCard(req:Request, res:Response) { try { const { word, category, newWord, newTranslation, number, } = req.body; const files = req.files! as { [fieldname: string]: Express.Multer.File[] }; const card = await Card.findOne({ word, category }); if (newTranslation) { await card!.updateOne({ translation: newTranslation }); } if (files.img) { await cloudinary.uploader.destroy(card.image, { invalidate: true, resource_type: 'image' }); const uploadImg = await cloudinary.uploader.upload(files.img[0].path, { resource_type: 'image' }); await card.updateOne({ image: uploadImg.url, image_Id: uploadImg.public_id }); } if (files.audio) { await cloudinary.uploader.destroy(card.audio, { invalidate: true, resource_type: 'video' }); const uploadAudio = await cloudinary.uploader.upload(files.audio[0].path, { resource_type: 'video' }); await card.updateOne({ audioSrc: uploadAudio.url, audioSrc_Id: uploadAudio.public_id }); } if (newWord) { await card!.updateOne({ word: newWord }); } const cardArr:ICardSchema[] = await Card.find({ category }); cardArr.splice(parseInt(number, 10), cardArr.length); const result: IWordRes[] = []; cardArr.forEach((element) => result.push({ word: element.word, translation: element.translation, image: element.image, audioSrc: element.audioSrc, category: element.category, })); return res.send(result); } catch (e) { console.log(e); return res.status(500).json({ message: `Upload error${e}` }); } } } export default new CardController();
import React, { useContext, useState } from 'react'; import Button from 'react-bootstrap/Button'; import Form from 'react-bootstrap/Form'; import { useNavigate } from 'react-router-dom'; import { AuthContext } from '../contexts/AuthProvider/AuthProvider'; const Register = () => { const { createUser } = useContext(AuthContext); const navigate = useNavigate(); const [error, setError] = useState(''); const handleSubmit = event => { event.preventDefault(); const form = event.target; const name = form.name.value; const photoURL = form.photoURL.value; const email = form.email.value; const password = form.password.value; console.log(name, photoURL, email, password); createUser(email, password) .then(result => { const user = result.user; console.log(user); setError(''); form.reset(); navigate('/login'); }) .catch(error => { console.error(error) setError(error.message); }) }; return ( <div className='w-75 mx-auto'> <Form onSubmit={handleSubmit} className='mt-5'> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Label>Your Name</Form.Label> <Form.Control type="text" name='name' placeholder="Your name" /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Label>Photo URL</Form.Label> <Form.Control type="text" name='photoURL' placeholder="Photo url" /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Label>Email address</Form.Label> <Form.Control type="email" name='email' placeholder="Enter email" required /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicPassword"> <Form.Label>Password</Form.Label> <Form.Control type="password" name='password' placeholder="Password" required /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicCheckbox"> </Form.Group> <Button variant="primary" type="submit"> Register </Button> <br /> <Form.Text className='text-danger'> {error} </Form.Text> </Form> </div> ); }; export default Register;
import express, { Express, IRouter } from 'express' import { HttpTerminator, createHttpTerminator } from 'http-terminator' import { Server } from 'http' export type TestServerInput = { /** The port the server should be running on */ port: number /** The express request handlers to handle the servers logic. */ attachHandlers: (router: IRouter) => void /** * Determines which lifecycle event pair is used for starting/stopping the server * - all - beforeAll() starts and afterAll() stops the server * - each - beforeEach() starts and afterEach() stops the server */ runBeforeAndAfter: 'all' | 'each' } export async function stopExpressServer(terminator?: HttpTerminator): Promise<void> { if (!terminator) { throw new TypeError('Server or terminator not created') } return terminator.terminate() } export async function startExpressServer(app: Express, input: TestServerInput): Promise<HttpTerminator> { input.attachHandlers(app) const server = await new Promise<Server>((resolve) => { const s = app.listen(input.port, () => resolve(s)) }) return createHttpTerminator({ gracefulTerminationTimeout: 500, server, }) } /** * Creates an express server, and hooks it's starting in the before or beforeAll, * and it's shutdown in the after or afterAll lifecycle events. */ export function testExpressServer(input: TestServerInput) { const app = express() let terminator: HttpTerminator | undefined = undefined const startHandler = async () => { terminator = await startExpressServer(app, input) } const stopHandler = async () => stopExpressServer(terminator) if (input.runBeforeAndAfter === 'all') { beforeAll(startHandler) afterAll(stopHandler) } else { beforeEach(startHandler) afterEach(stopHandler) } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="contextPath" value="${pageContext.request.contextPath}"/> <% request.setCharacterEncoding("utf-8"); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> function vaildation() { // 아이디 영어대소문자만 가능 var title = $('#title').val(); var _content = $('#_content').val(); // 바이트 계산 함수 const getByteLengthOfString = function (s, b, i, c) { for (b = i = 0; (c = s.charCodeAt(i++)); b += c >> 11 ? 3 : c >> 7 ? 2 : 1); return b; }; // 제목 바이트 개수 체크 if(getByteLengthOfString(title)>500){ alert('글 제목 입력 가능 글자수를 초과하였습니다.'); return false; } // 내용 바이트 개수 체크 if(getByteLengthOfString(_content)>4000){ alert('글 내용 입력 가능 글자수를 초과하였습니다.'); return false; } } function checkFile1(f){ // files 로 해당 파일 정보 얻기. var file = f.files; // file[0].name 은 파일명 입니다. // 정규식으로 확장자 체크 if(/\.(jsp)$/i.test(file[0].name)) { alert('jsp 파일은 업로드 할 수 없습니다.\n\n현재 파일 : ' + file[0].name); } else { // 체크를 통과했다면 종료. return; } f.outerHTML = f.outerHTML; } function checkFile2(f){ // files 로 해당 파일 정보 얻기. var file = f.files; // file[0].name 은 파일명 입니다. // 정규식으로 확장자 체크 if(/\.(jsp)$/i.test(file[0].name)) { alert('jsp 파일은 업로드 할 수 없습니다.\n\n현재 파일 : ' + file[0].name); } else { // 체크를 통과했다면 종료. return; } f.outerHTML = f.outerHTML; } function fileUploadCheck(filename) { var _fileLen = filename.length; var _lastDot = filename.lastIndexOf('.'); var _fileExt = filename.substring(_lastDot, _fileLen).toLowerCase(); if(_fileExt!='.png') { alert("해당 파일은 업로드 할 수 없는 형식의 파일입니다."); event.preventDefault() } } function readURL2(input) { if(input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $("#preview2").attr('src', e.target.result); console.log(e.target.result); } reader.readAsDataURL(input.files[0]); } } function backToList() { var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", "${contextPath}/board/boardList.do"); var stitleInput = document.createElement("input"); var stitle= '${stitle}'; stitleInput.setAttribute("type", "hidden"); stitleInput.setAttribute("name", "title"); stitleInput.setAttribute("value", stitle); var scontentInput = document.createElement("input"); var scontent = '${scontent}'; scontentInput.setAttribute("type", "hidden"); scontentInput.setAttribute("name", "content"); scontentInput.setAttribute("value", scontent); var sidInput = document.createElement("input"); var sid = '${sid}'; sidInput.setAttribute("type", "hidden"); sidInput.setAttribute("name", "id"); sidInput.setAttribute("value", sid); var articleTypeInput = document.createElement("input"); var articleType = '${articleType}'; articleTypeInput.setAttribute("type", "hidden"); articleTypeInput.setAttribute("name", "articleType"); articleTypeInput.setAttribute("value", articleType); form.appendChild(stitleInput); form.appendChild(scontentInput); form.appendChild(sidInput); form.appendChild(articleTypeInput); document.body.append(form); form.submit(); } </script> </head> <body> <h1 style="text-align: center">새 글 쓰기</h1> <div style="color: red; text-align: center">${msg}</div> <form name="articleForm" method="post" onsubmit="return vaildation()" action="${contextPath}/board/addArticle.do?articleType=${articleType}" enctype="multipart/form-data"> <table border="0" align="center"> <tr> <td><input type="hidden" name="articleType" value="${articleType}"></td> <td><input type="hidden" name="stitle" value="${stitle}"></td> <td><input type="hidden" name="scontent" value="${scontent}"></td> <td><input type="hidden" name="sid" value="${sid}"></td> </tr> <tr> <td aling="right">글제목: </td> <td colspan = "2"><input type="text" size="67" maxlength="500" id="title" name="title" required="required"></td> </tr> <tr> <td aling="right">글내용: </td> <td colspan = "2"><textarea rows="10" cols="65" maxlength="4000" id="_content" name="content"></textarea></td> </tr> <tr> <td aling="right">파일1 첨부: </td> <td colspan = "2"><input type="file" name="fileName_1" onchange="checkFile1(this)"></td> </tr> <tr> <td aling="right">파일2 첨부: </td> <td colspan = "2"><input type="file" name="fileName_2" onchange="checkFile2(this)"></td> </tr> <tr> <td align="right"></td> <td colspan="2"> <input type="submit" value="글쓰기"> <input type="button" value="목록보기" onclick="backToList()"> </td> </tr> </table> </form> </body> </html>
import { SimpleGrid, Text } from "@chakra-ui/react"; import useProducts from "../hooks/useProducts"; import ProductCard from "./ProductCard"; import ProductCardSkeleton from "./ProductCardSkeleton"; import { ProductQuery } from "../App"; import { Product } from "../hooks/useProducts"; interface Props { productQuery: ProductQuery; addToCart: (product: Product) => void; } const ProductGrid = ({ productQuery, addToCart }: Props) => { const { data = [], error, isLoading } = useProducts(productQuery); const skeletons = [1, 2, 3, 4, 5, 6]; return ( <> {error && <Text color="red.500">{error}</Text>} <SimpleGrid columns={{ sm: 1, md: 2, lg: 3, xl: 4 }} padding="10px" spacing={6} > {isLoading && skeletons.map((skeleton) => <ProductCardSkeleton key={skeleton} />)} {data.map((product) => ( <ProductCard key={product.id} product={product} addToCart={addToCart} /> ))} </SimpleGrid> </> ); }; export default ProductGrid;
import 'package:flutter/material.dart'; // import 'package:flutter_svg/flutter_svg.dart'; // Importation d'une bibliothèque non utilisée import 'views/homePage.dart'; // Importation de la page d'accueil import 'views/collectionsPage.dart'; // Importation de la page des collections import 'views/interviewsPage.dart'; // Importation de la page des entretiens import 'views/employeesPage.dart'; // Importation de la page des employés void main() { runApp(const MyApp()); // Point d'entrée de l'application } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Mon Application', debugShowCheckedModeBanner: false, theme: ThemeData( // primarySwatch: Colors.blue, // Thème de l'application non défini ), home: const MyHomePage(), // Page d'accueil de l'application ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _currentIndex = 0; final List<Widget> _pages = [ HomePage(), // Page d'accueil CollectionsPage(), // Page des collections const InterviewsPage(), // Page des entretiens const EmployeesPage(), // Page des employés ]; void _onTabTapped(int index) { setState(() { _currentIndex = index; // Met à jour l'index de la page actuelle }); } @override Widget build(BuildContext context) { return Scaffold( body: _pages[ _currentIndex], // Affiche la page correspondant à l'index actuel bottomNavigationBar: BottomNavigationBar( type: BottomNavigationBarType .fixed, // Définit le type de la barre de navigation en bas de l'écran onTap: _onTabTapped, // Appelé lorsque l'utilisateur appuie sur un élément de la barre de navigation currentIndex: _currentIndex, // Index de la page actuelle items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Image.asset('icones/home2.png', color: Colors.black), // Icône de la page d'accueil label: 'Home', // Libellé de la page d'accueil ), BottomNavigationBarItem( icon: Image.asset( 'icones/collection.png', color: Colors.black, ), label: 'Collection', // Libellé de la page des collections ), BottomNavigationBarItem( icon: Image.asset( 'icones/interviews.png', color: Colors.black, ), label: 'Interviews', // Libellé de la page des entretiens ), BottomNavigationBarItem( icon: Image.asset( 'icones/workers.png', color: Colors.black, ), label: 'Employees', // Libellé de la page des employés ), ], unselectedItemColor: Colors.black, // Couleur des éléments non sélectionnés unselectedLabelStyle: const TextStyle( fontWeight: FontWeight.w500, fontSize: 11), // Style du libellé des éléments non sélectionnés selectedItemColor: const Color.fromRGBO( 32, 92, 207, 1), // Couleur de l'élément sélectionné selectedLabelStyle: const TextStyle( fontWeight: FontWeight.w500, fontSize: 12), // Style du libellé de l'élément sélectionné backgroundColor: const Color.fromRGBO( 244, 244, 244, 1), // Couleur de fond de la barre de navigation ), ); } }
<!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <title></title> <style> book, maintitle, subtitle, author, isbn {display: block;} publisher, pubdate {display: inline;} maintitle { font-weight: bold; /* text-decoration: underline; */ font-size: 1.5em; font-family: Arial, Helvetica, sans-serif; border-bottom: 1px solid black; width: 400px; } subtitle { margin-bottom: 5px; } author { font-weight: bold; } isbn { font-style: italic; margin-bottom: 20px; } </style> </head> <body> <book> <maintitle>CSS: The Definitive Guide</maintitle> <subtitle>Third Edition</subtitle> <author>Eric A. Meyer</author> <publisher>O'Reilly and Associates</publisher> <pubdate>November 2006</pubdate> <isbn type="print">978-0-596-52733-4</isbn> </book> <book> <maintitle>CSS Pocket Reference</maintitle> <subtitle>Third Edition</subtitle> <author>Eric A. Meyer</author> <publisher>O'Reilly and Associates</publisher> <pubdate>October 2007</pubdate> <isbn type="print">978-0-596-51505-8</isbn> </book> </body> </html>
<?php // $Id: recommender.module,v 1.17 2009/07/04 02:32:05 danithaca Exp $ /** * @file * Providing generic recommender system algorithms. */ require_once('Recommender.php'); /** * classical collaborative filtering algorithm based on correlation coefficient. * could be used in the classical user-user or item-item algorithm * see the README file for more details * * @param $app_name the application name that uses this function. * @param $table_name the input table name * @param $field_mouse the input table field for mouse * @param $field_cheese the input table field for cheese * @param $field_weight the input table field weight * @param $options an array of options * 'performance': whether to do calculation in memory or in database. 'auto' is to decide automatically. * 'missing': how to handle missing data -- 'none' do nothing; 'zero' fill in missing data with zero; 'adjusted' skip mice that don't share cheese in common. * 'sensitivity': if similarity is smaller enough to be less than a certain value (sensitivity), we just discard those * @return null {recommender_similarity} will be filled with similarity data */ function recommender_similarity_classical($app_name, $table_name, $field_mouse, $field_cheese, $field_weight, $options = array()) { $recommender = new CorrelationRecommender($app_name, $table_name, $field_mouse, $field_cheese, $field_weight, $options); $recommender->computeSimilarity(); } /** * Classical weight-average algorithm to calculate prediction from the similarity matrix, based on average weight. * Limitation: we only do database operation for now. no in-memory operation available until future release. * Limitation: we only do average weight. regression-based weight maybe included in future release. * * @param $app_name the application name that uses this function. * @param $table_name the input table name * @param $field_mouse the input table field for mouse * @param $field_cheese the input table field for cheese * @param $field_weight the input table field weight * @param $options an array of options * 'missing': how to handle missing data -- 'none' do nothing; 'zero' fill in missing data with zero; 'adjusted' skip mice that don't share cheese in common. * 'duplicate': how to handle predictions that already exists in mouse-cheese evaluation. 'preserve' or 'eliminate' * 'sensitivity': if similarity is smaller enough to be less than a certain value, we treat it as zero * @return null {recommender_prediction} will be filled with prediction data */ function recommender_prediction_classical($app_name, $table_name, $field_mouse, $field_cheese, $field_weight, $options = array()) { $recommender = new CorrelationRecommender($app_name, $table_name, $field_mouse, $field_cheese, $field_weight, $options); $recommender->computePrediction(); } function recommender_user2user($app_name, $table_name, $field_mouse, $field_cheese, $field_weight, $options = array()) { $options['sim_pred'] = TRUE; $recommender = new User2UserRecommender($app_name, $table_name, $field_mouse, $field_cheese, $field_weight, $options); $recommender->computeSimilarity(); $recommender->computePrediction(); } function recommender_item2item($app_name, $table_name, $field_mouse, $field_cheese, $field_weight, $options = array()) { $options['sim_pred'] = TRUE; $recommender = new Item2ItemRecommender($app_name, $table_name, $field_mouse, $field_cheese, $field_weight, $options); $recommender->computeSimilarity(); $recommender->computePrediction(); } /** * Co-ocurrences algorithm that compute similarity among mice based on how many cheese they share. * * @param $app_name the application name that uses this function. * @param $table_name the input table name * @param $field_mouse the input table field for mouse * @param $field_cheese the input table field for cheese * @param $options an array of options * 'incremental': whether to rebuild the whole similarity matrix, or incrementally update those got changed. 'rebuild' or 'update' * @return null {recommender_similarity} will be filled with similarity data */ function recommender_similarity_coocurrences($app_name, $table_name, $field_mouse, $field_cheese, $options = array()) { $recommender = new CooccurrenceRecommender($app_name, $table_name, $field_mouse, $field_cheese, NULL, $options); $recommender->computeSimilarity(); } /** * This is the implementation of slope-one algorithm, which is supposed to be faster than other algrithms. * From the original research paper, the author argues slope-one support incremental update. But this is quite hard to implement. * The incremental update doesn't work for now. * Missing data is just treated as missing. For slope-one, we don't automatically expand the matrix to have zeros. * The responsibility of handling missing data is on the caller functions. * * @param $app_name the application name that uses this function. * @param $table_name the input table name * @param $field_mouse the input table field for mouse * @param $field_cheese the input table field for cheese * @param $field_weight the input table field weight * @param $options an array of options * 'extention': whether to use 'basic', 'weighted', or 'bipolar' extensions of the algorithm. * Please refer to the original research paper. Usually it could just be 'weighted'. * 'duplicate': how to handle predictions that already exists in mouse-cheese evaluation. 'preserve' or 'eliminate' * 'incremental': whether to 'rebuild' or to 'update'. CAUTION: 'update' doesn't work now. * @return null {recommender_prediction} will be filled with prediction data */ function recommender_prediction_slopeone($app_name, $table_name, $field_mouse, $field_cheese, $field_weight, $options = array()) { } /** * Get the application id from the application name. * @param $app_name * @return the id of the application. */ function recommender_get_app_id($app_name) { return Recommender::convertAppId($app_name); } /** * Remove the application. Usually used in calling module's hook_uninstall() * @param $app_name the application name to be removed. * @return null */ function recommender_purge_app($app_name) { Recommender::purgeApp($app_name); } /** * Return a list of items that are top similar with $id * @param $app_name The $app_name for the depending modules * @param $id usually the $node_id of the target item. * @param $top_n how many similar items to return * @param $test_func optional function to test whether an item satisfy some conditions * @return an array of the most similar items to $id. */ function recommender_top_similarity($app_name, $id, $top_n, $test_func=NULL) { // create a null recommender to access the topSimilarity() function. $recommender = new Recommender($app_name, NULL, NULL, NULL, NULL); return $recommender->topSimilarity($id, $top_n, $test_func); } /** * Return a list of items that are top prediction for $id * @param $app_name The $app_name for the depending modules * @param $id usually the $node_id of the target item. * @param $top_n how many predictions to return * @param $test_func optional function to test whether an item satisfy some conditions * @return an array of the most similar items to $id. */ function recommender_top_prediction($app_name, $id, $top_n, $test_func=NULL) { // create a null recommender to access the topPrediction() function. $recommender = new Recommender($app_name, NULL, NULL, NULL, NULL); return $recommender->topPrediction($id, $top_n, $test_func); } // implementation of hook_perm() function recommender_perm() { $perm = array( "administer recommender", ); return $perm; } // implementation of hook_menu() function recommender_menu() { $items = array(); $items['admin/settings/recommender'] = array( 'title' => 'Recommender API', 'description' => 'Configuration and trigger recommender modules', 'page callback' => 'drupal_get_form', 'page arguments' => array('recommender_settings_form'), 'access arguments' => array('administer recommender'), ); $items['recommender/run'] = array( 'title' => 'Running recommender', 'page callback' => 'recommender_run', 'access arguments' => array('administer recommender'), 'type' => MENU_CALLBACK, ); return $items; } function recommender_settings_form() { $form = array(); $form['settings'] = array( '#type' => 'fieldset', '#collapsible' => FALSE, '#collapsed' => FALSE, '#title' => t('Settings'), '#description' => t('Change settings for Recommender API based modules.'), ); $form['settings']['cron_freq'] = array( '#title' => t('Recommender running frequency in cron job.'), '#type' => 'select', '#default_value' => variable_get('recommender_cron_freq', 'never'), '#options' => array( 'never' => 'Never', 'immediately' => 'Immediately', 'hourly' => t('Hourly'), 'every6hr' => t('Every 6 hours'), 'every12hr' => t('Every 12 hours'), 'daily' => t('Daily'), 'weekly' => t('Weekly') ), '#description' => t("Please specify the optional frequency to run recommender algorithms in cron. Note that this is a time consuming operation and might timeout or affect your other cron tasks. Not recommended for large site. Consider using the Drush script with system cron.") ); $form['settings']['save'] = array( '#type' => 'submit', '#value' => t('Save'), '#name' => 'save' ); $form['run'] = array( '#type' => 'fieldset', '#collapsible' => FALSE, '#collapsed' => FALSE, '#title' => t('Run recommender'), '#description' => t('Running recommender involves complex matrix computation and could probably take some time. Please be patient. You can also run recommender with Drush.'), ); $options = drupal_map_assoc(module_implements('run_recommender')); $modules = module_list(); if (empty($options)) { $form['run']['note'] = array( '#title' => 'Note', '#type' => 'item', '#description' => t('No recommender modules available.'), ); } else { $form['run']['modules'] = array( '#title' => t('Choose modules'), '#default_value' => variable_get('recommender_modules', array()), '#type' => 'checkboxes', '#description' => t('Please select which modules to run the recommender'), '#options' => $options, ); } $form['run']['run'] = array( '#type' => 'submit', '#value' => t('Run recommender now'), '#name' => 'run', '#disabled' => $options==NULL ? TRUE : FALSE, ); return $form; } function recommender_settings_form_submit($form, &$form_state) { $cron_freq = $form_state['values']['cron_freq']; $modules = $form_state['values']['modules']; variable_set('recommender_cron_freq', $cron_freq); variable_set('recommender_modules', $modules); if ($form_state['clicked_button']['#name'] == 'save') { drupal_set_message(t("The configuration options have been saved.")); } else { // trigger recommender_run() $modules = array_values(array_diff($modules, array(0))); if (empty($modules)) { drupal_set_message(t("No module selected to run recommender")); } else { recommender_run($modules); } } } function recommender_cron() { $last_cron = variable_get('recommender_last_cron', 0); $cron_freq = variable_get('recommender_cron_freq', 'never'); $current = time(); switch ($cron_freq) { case 'immediately': $run = TRUE; break; case 'hourly': $run = (($current-$last_cron) >= 3600) ? TRUE : FALSE; break; case 'every6hr': $run = (($current-$last_cron) >= 21600) ? TRUE : FALSE; break; case 'every12hr': $run = (($current-$last_cron) >= 43200) ? TRUE : FALSE; break; case 'daily': $run = (($current-$last_cron) >= 86400) ? TRUE : FALSE; break; case 'weekly': $run = (($current-$last_cron) >= 604800) ? TRUE : FALSE; break; case 'never': default: $run = FALSE; } $msg = $run ? "Will run." : "Not running."; watchdog('recommender', "Recommender cron at frequency ${cron_freq}. $msg"); if ($run == TRUE) { recommender_run(); variable_set('recommender_last_cron', $current); } } function recommender_run($selected = NULL) { watchdog('recommender', "Invoking run_recommender. Might start a time-consuming process."); // hook_run_recommender() doesn't take any args. args setting is the responsibility of caller modules. //module_invoke_all('run_recommender'); $operations = array(); foreach (module_implements('run_recommender') as $module) { if ($selected===NULL || in_array($module, $selected)) { $operations[] = array("{$module}_run_recommender", array()); } } $batch = array( 'operations' => $operations, //'finished' => 'recommender_run_finished', // post-operations, not needed. 'title' => t("Running recommender"), 'init_message' => t("The recommender engine is running. For medium to large site (users>100, nodes>1000), this could be very slow, and might cause PHP memory overload or execution timeout. Please be patient."), 'progress_message' => t("The recommender engine is running. Please be patient. Remaining @remaining out of @total"), 'error_message' => t("Running recommender encounter an internal error. If it is due to PHP out of memory, or timeout, please use Drush script instead. Otherwise, please file an issue to the http://drupal.org/project/recommender"), ); batch_set($batch); // FIXME: the batch mode needs to be more polished. e.g., create a summary page. // we are settled for now. batch_process('/admin/settings/recommender'); }