text
stringlengths
184
4.48M
import { HttpClient} from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { NgxFuseSearchOptions } from 'ngx-fuse-search'; import {map} from 'rxjs/operators'; type Country = { name: string; prefix: string; code: string; flag?: string; phoneLength: number; } @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { title = 'demo'; searchTerm: string = ""; countries: Country[] = []; trackByCode = (index: number, item: any) => item.code; searchOptions: NgxFuseSearchOptions = { isCaseSensitive: false, keys: ['name'], shouldSort: true }; constructor(private readonly http: HttpClient) { } ngOnInit() { this.getCountries().pipe( map(values => { const newValues = values.map(country => ({ name: country.name, prefix: `+${country.callingCodes[0]}`, flag: country.flag || country.flags.svg, code: country.alpha2Code } as Country) ); return newValues; }) ).subscribe((values ) => { console.info(values); this.countries = values; }); } getCountries() { return this.http.get<any[]>("https://restcountries.com/v2/all"); } }
import { JuegoDeCasino } from "./juegoDeCasino"; export class Slots extends JuegoDeCasino { private typeAnimation : string; private jackpot : number; private lines : number; constructor(name : string, type : string, maxBet : number, minBet : number, typeMoney : string, typeAnimation : string, jackpot : number, lines : number) { super(name, type, maxBet, minBet, typeMoney) this.typeAnimation = typeAnimation; this.jackpot = jackpot; this.lines = lines; } public setTypeAnimation(typeAnimation : string) : void{ this.typeAnimation = typeAnimation; } public getTypeAnimation() : string { return this.typeAnimation; } public setJackpot(jackpot : number) : void { this.jackpot = jackpot; } public getJackpot() : number { return this.jackpot; } public setLines(lines : number) : void { this.lines = lines; } public getLines() : number { return this.lines; } }
<?php /** * The main template file. * * This is the most generic template file in a WordPress theme * and one of the two required files for a theme (the other being style.css). * It is used to display a page when nothing more specific matches a query. * E.g., it puts together the home page when no home.php file exists. * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package ThemeGrill * @subpackage ColorNews * @since ColorNews 1.0 */ get_header(); ?> <?php do_action( 'colornews_before_body_content' ); ?> <div id="main" class="clearfix"> <div class="tg-container"> <div class="tg-inner-wrap clearfix"> <div id="main-content-section clearfix"> <div id="primary"> <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /* * Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'template-parts/content', get_post_format() ); ?> <?php endwhile; ?> <?php colornews_posts_navigation(); ?> <?php else : ?> <?php get_template_part( 'template-parts/content', 'none' ); ?> <?php endif; ?> </div><!-- #primary end --> <?php colornews_sidebar_select(); ?> </div><!-- #main-content-section end --> </div><!-- .tg-inner-wrap --> </div><!-- .tg-container --> </div><!-- #main --> <?php do_action( 'colornews_after_body_content' ); ?> <?php get_footer(); ?>
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; @Entity('awb_detail', { schema: 'public' }) export class AwbDetail extends BaseEntity { @PrimaryGeneratedColumn({ type: 'bigint', name: 'awb_detail_id', }) awbDetailId: string; @Column('bigint', { nullable: false, name: 'awb_id', }) awbId: string; @Column('bigint', { nullable: false, name: 'attachment_id', }) attachmentId: string; @Column('numeric', { nullable: true, precision: 10, scale: 5, }) width: string | null; @Column('numeric', { nullable: true, precision: 10, scale: 5, }) length: string | null; @Column('numeric', { nullable: true, precision: 10, scale: 5, }) height: string | null; @Column('numeric', { nullable: true, precision: 10, scale: 5, }) volume: string | null; @Column('numeric', { nullable: true, precision: 10, scale: 5, name: 'divider_volume', }) dividerVolume: string | null; @Column('numeric', { nullable: true, precision: 20, scale: 5, name: 'weight_volume', }) weightVolume: string | null; @Column('numeric', { nullable: true, precision: 20, scale: 5, name: 'weight_volume_rounded', }) weightVolumeRounded: string | null; @Column('numeric', { nullable: true, precision: 20, scale: 5, }) weight: string | null; @Column('numeric', { nullable: true, precision: 20, scale: 5, name: 'weight_rounded', }) weightRounded: string | null; @Column('numeric', { nullable: true, precision: 20, scale: 5, name: 'weight_final', }) weightFinal: string | null; @Column('numeric', { nullable: true, precision: 10, scale: 5, name: 'item_price', }) itemPrice: string | null; @Column('numeric', { nullable: true, precision: 10, scale: 5, }) insurance: string | null; @Column('bigint', { nullable: false, name: 'users_id_created', }) usersIdCreated: string; @Column('timestamp without time zone', { nullable: false, name: 'created_time', }) createdTime: Date; @Column('bigint', { nullable: false, name: 'users_id_updated', }) usersIdUpdated: string; @Column('timestamp without time zone', { nullable: true, name: 'updated_time', }) updatedTime: Date | null; @Column('boolean', { nullable: false, default: () => 'false', name: 'is_deleted', }) isDeleted: boolean; @Column('bigint', { nullable: true, name: 'bag_item_id_latest', }) bagItemIdLatest: string | null; }
import React from "react"; import { Wrapper } from "../ui"; import { StarCounter } from "../products"; import { Link, useNavigate } from "react-router-dom"; const ProductDetailCard = ({ id, title, price, image, category, rating: { rate, count }, description, }) => { const nav = useNavigate(); const handleClick = () => { nav(-1); }; return ( <Wrapper> <Link onClick={handleClick} className=" inline-flex px-4 py-2 select-none active:scale-95 mb-3 gap-2 bg-neutral-600 text-neutral-200 " > Go Back <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6" > <path strokeLinecap="round" strokeLinejoin="round" d="M9 15 3 9m0 0 6-6M3 9h12a6 6 0 0 1 0 12h-3" /> </svg> </Link> <div className=" border border-neutral-400 p-5 grid grid-cols-1 items-center gap-3 md:grid-cols-3"> <div className=" flex justify-center items-center md:justify-start col-span-1"> <img alt="ecommerce" className="rounded md:w-80 h-40 w-40 md:h-80 object-contain" src={image} /> </div> <div className=" md:col-span-2 md:border-l md:ps-5 space-y-5"> <h2 className="text-sm title-font text-neutral-500 tracking-widest"> {category} </h2> <h1 className="text-neutral-900 text-3xl title-font font-medium mb-1"> {title} </h1> <div className="flex gap-3"> <div className="rating-stars flex gap-1"> <StarCounter rating={rate} /> </div> <p className=" text-neutral-400">{count} reviews</p> </div> <p className="leading-relaxed">{description}</p> <div className="flex gap-8"> <span className="title-font font-medium text-2xl text-neutral-900"> ${price} </span> </div> <button className="disabled:hover:bg-transparent disabled:hover:text-gray-600 disabled:opacity-65 bg-transparent border block w-full py-2 text-neutral-600 border-neutral-600 hover:bg-neutral-600 hover:text-white duration-500"> <div className=" flex justify-center gap-3 items-center"> <p>Add to cart</p> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-cart-plus" viewBox="0 0 16 16" > <path d="M9 5.5a.5.5 0 0 0-1 0V7H6.5a.5.5 0 0 0 0 1H8v1.5a.5.5 0 0 0 1 0V8h1.5a.5.5 0 0 0 0-1H9z" /> <path d="M.5 1a.5.5 0 0 0 0 1h1.11l.401 1.607 1.498 7.985A.5.5 0 0 0 4 12h1a2 2 0 1 0 0 4 2 2 0 0 0 0-4h7a2 2 0 1 0 0 4 2 2 0 0 0 0-4h1a.5.5 0 0 0 .491-.408l1.5-8A.5.5 0 0 0 14.5 3H2.89l-.405-1.621A.5.5 0 0 0 2 1zm3.915 10L3.102 4h10.796l-1.313 7zM6 14a1 1 0 1 1-2 0 1 1 0 0 1 2 0m7 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0" /> </svg> </div> </button> </div> </div> </Wrapper> ); }; export default ProductDetailCard;
import React from 'react'; import Typography from '@mui/material/Typography'; import NumberTextField from "../NumberTextField"; import { TextField } from "@mui/material"; import {BlackAlignedItem, CenterItem, languageDirection, LeftItem, mathJaxConfig} from "../LanguageAndButtonUtility"; import Box from "@mui/material/Box"; import { MathJax, MathJaxContext } from "better-react-mathjax"; import Grid from "@mui/material/Grid"; import { LogisticRegressionModule, math } from "./LogisticRegressionCore"; import QuestionTable from "../QuestionTable"; import { getLogisticRegressionDataColumnNames, getLogisticRegressionModuleColumns, getLogisticRegressionModuleInfoColumns, } from "../QuestionTableDefinitions"; import {useTranslation} from "react-i18next"; const TOTAL_ITERATIONS = 2 const DIGITS = 4 function getDataAnswers(xs: number[][], cs: number[], algo: LogisticRegressionModule): { [id: string]: string }[] { let moduleInfo = algo.getModuleInfo() let answers: { [id: string]: string }[] = [] let step = 0 for (let epoch = 1; epoch < TOTAL_ITERATIONS + 1; epoch++) { // eslint-disable-next-line no-loop-func xs.forEach((xi, id) => { let yi = Number(Number(moduleInfo.ys[epoch - 1].subset(math.index(id))).toFixed(DIGITS)) // // console.log("moduleInfo.ys = \n", moduleInfo.ys) // // console.log("typeOf moduleInfo.ys = \n", (typeof moduleInfo.ys)) // // console.log("moduleInfo.ys[epoch - 1] = \n", moduleInfo.ys[epoch - 1]) // // console.log("typeOf moduleInfo.ys[epoch - 1] = \n", (typeof moduleInfo.ys[epoch - 1])) // // console.log("moduleInfo.ys[epoch - 1].subset(math.index(id)) = \n", moduleInfo.ys[epoch - 1].subset(math.index(id))) // // console.log("typeOf moduleInfo.ys[epoch - 1].subset(math.index(id)) = \n", (typeof moduleInfo.ys[epoch - 1].subset(math.index(id)))) // // console.log("yi = \n", yi) // // console.log("typeOf yi = \n", (typeof yi)) // // console.log("Number(yi) = \n", Number(yi)) let tmp = { "step": (step % 3).toString(), "xOne": xi[0].toFixed(DIGITS).toString(), "xTwo": xi[1].toFixed(DIGITS).toString(), "yi": yi.toFixed(DIGITS).toString(), "dbi": (yi - cs[id]).toFixed(DIGITS).toString() } // // console.log("tmp = \n", tmp) answers.push(tmp) step++ }) } // console.log("Data Answers = \n", answers) return answers // return [] } function getModuleAnswers(alpha: number, algo: LogisticRegressionModule): { [id: string]: string }[] { let moduleInfo = algo.getModuleInfo() let answers: { [id: string]: string }[] = [] let step = 0 let ws = moduleInfo.ws let bs = moduleInfo.bs let bPrev = 0 let w1Prev = 0 let w2Prev = 0 for (let epoch = 0; epoch < TOTAL_ITERATIONS; epoch++) { let bNew = bs[epoch] let w1New = Number(ws[epoch].subset(math.index(0))) let w2New = Number(ws[epoch].subset(math.index(1))) // // console.log("bNew ", bNew) // // console.log("w2New ", w2New) // // console.log("w2New ", w2New) answers.push({ "step": (step % 1).toString(), "wOne": w1Prev.toFixed(DIGITS).toString(), "wTwo": w2Prev.toFixed(DIGITS).toString(), "b": bPrev.toFixed(DIGITS).toString(), "dwOne": ((w1Prev - w1New) / alpha).toFixed(DIGITS).toString(), "dwTwo": ((w2Prev - w2New) / alpha).toFixed(DIGITS).toString(), "dB": ((bPrev - bNew) / alpha).toFixed(DIGITS).toString(), "wOneNew": w1New.toFixed(DIGITS).toString(), "wTwoNew": w2New.toFixed(DIGITS).toString(), "bNew": bNew.toFixed(DIGITS).toString() }) step++ } // console.log("Module Answers = \n", answers) return answers // return [] } function getModuleFinalAnswers(algo: LogisticRegressionModule): { [id: string]: string }[] { let module = algo.getModule() let moduleFinalAnswers = [{ 'step': "0", 'wOneFinal': Number(module.W.subset(math.index(0))).toFixed(DIGITS).toString(), 'wTwoFinal': Number(module.W.subset(math.index(1))).toFixed(DIGITS).toString(), 'bFinal': Number(module.B).toFixed(DIGITS).toString() }] // console.log("Module Final Answers = \n", moduleFinalAnswers) return moduleFinalAnswers } const translation_path = "logreg.pages.sbs." export default function LogisticRegressionStepByStep() { const headers_style = { fontFamily: 'Arial, Helvetica, sans-serif' } const [alpha, setAlpha] = React.useState(0.001) // XS (vector of features) = [[x1_1, x1_2], [x2_1, x2_2], ...] const [xs, setXS] = React.useState([[0, 0], [0, 0], [0, 0]]) // CS (vector of classifications) = [c1, c2, c3, c4] const [cs, setCS] = React.useState([0, 0, 0]) // Logistic Regression model const [algo, setAlgo] = React.useState(new LogisticRegressionModule(xs, cs, alpha, TOTAL_ITERATIONS)) // Translate const [t] = useTranslation('translation'); function handleXS(sampleId: number, feature1: number, feature2: number) { let tmp = xs tmp[sampleId] = [feature1, feature2] setXS(tmp) setAlgo(new LogisticRegressionModule(xs, cs, alpha, TOTAL_ITERATIONS)) } function handleCS(sampleId: number, classification: number) { let tmp = cs tmp[sampleId] = classification setCS(tmp) setAlgo(new LogisticRegressionModule(xs, cs, alpha, TOTAL_ITERATIONS)) } function handleAlpha(newAlpha: number) { setAlpha(newAlpha) setAlgo(new LogisticRegressionModule(xs, cs, alpha, TOTAL_ITERATIONS)) } return ( <div> <Box sx={{ width: "100%" }}> <MathJaxContext version={3} config={mathJaxConfig}> <Grid container rowSpacing={1} columnSpacing={{ xs: 1, }}> <Grid item xs={12}> <LeftItem> <Grid container rowSpacing={1} columnSpacing={{ xs: 1, }} alignItems={"center"} alignContent={"center"}> <Grid item xs={4}> <Typography style={{ width: '100%', color: 'black' }}> <MathJax style={{ fontSize: "20px" }} inline> {`$$ \\alpha = $$`} </MathJax> </Typography> </Grid> <Grid item xs={2}> <NumberTextField InputProps={{"data-testid":"alphaInput"}} value={alpha} onChange={event => handleAlpha(Number(event.target.value))} /> </Grid> <Grid item xs={6} /> </Grid> </LeftItem> <LeftItem> <Grid container rowSpacing={1} columnSpacing={{ xs: 1, }} alignItems={"center"} alignContent={"center"}> <Grid item xs={4}> <Typography style={{ width: '100%', color: 'black' }}> <MathJax style={{ fontSize: "20px" }} inline> {`$$ X_{3x2} = \\begin{bmatrix} x_{11} & x_{12} \\\\ x_{21} & x_{22} \\\\ x_{31} & x_{32} \\\\ \\end{bmatrix} = $$`} </MathJax> </Typography> </Grid> <Grid item xs={2}> <Grid item xs={12}> <TextField data-testid="x11Input" value={xs[0][0]} label="x11" type="number" size="small" onChange={event => handleXS(0, Number(event.target.value), xs[0][1])} sx={{ width: "100%" }} /> </Grid> <Grid item xs={12}> <TextField data-testid="x21Input" value={xs[1][0]} label="x21" type="number" size="small" onChange={event => handleXS(1, Number(event.target.value), xs[1][1])} sx={{ width: "100%" }} /> </Grid> <Grid item xs={12}> <TextField data-testid="x31Input" value={xs[2][0]} label="x31" type="number" size="small" onChange={event => handleXS(2, Number(event.target.value), xs[2][1])} sx={{ width: "100%" }} /> </Grid> </Grid> <Grid item xs={2}> <Grid item xs={12}> <TextField data-testid="x12Input" value={xs[0][1]} label="x12" type="number" size="small" onChange={event => handleXS(0, xs[0][0], Number(event.target.value))} sx={{ width: "100%" }} /> </Grid> <Grid item xs={12}> <TextField data-testid="x22Input" value={xs[1][1]} label="x22" type="number" size="small" onChange={event => handleXS(1, xs[1][0], Number(event.target.value))} sx={{ width: "100%" }} /> </Grid> <Grid item xs={12}> <TextField data-testid="x32Input" value={xs[2][1]} label="x32" type="number" size="small" onChange={event => handleXS(2, xs[2][0], Number(event.target.value))} sx={{ width: "100%" }} /> </Grid> </Grid> <Grid item xs={4} /> </Grid> </LeftItem> <LeftItem> <Grid container rowSpacing={1} columnSpacing={{ xs: 1, }} alignItems={"center"} alignContent={"center"}> <Grid item xs={4}> <Typography style={{ width: '100%', color: 'black' }}> <MathJax style={{ fontSize: "20px" }} inline> {`$$ C_{1x3} = \\begin{bmatrix} c_{11} & c_{12} & c_{13} \\\\ \\end{bmatrix} = $$`} </MathJax> </Typography> </Grid> <Grid item xs={2}> <TextField data-testid="c1Input" value={cs[0]} label="1st Classification" type="number" size="small" onChange={event => handleCS(0, Number(event.target.value))} /> </Grid> <Grid item xs={2}> <TextField data-testid="c2Input" value={cs[1]} label="2nd Classification" type="number" size="small" onChange={event => handleCS(1, Number(event.target.value))} /> </Grid> <Grid item xs={2}> <TextField data-testid="c3Input" value={cs[2]} label="3rd Classification" type="number" size="small" onChange={event => handleCS(2, Number(event.target.value))} /> </Grid> <Grid item xs={2} /> </Grid> </LeftItem> </Grid> </Grid> <br /> <Grid container rowSpacing={1} columnSpacing={{ xs: 1, }}> <Grid item xs={12}> <BlackAlignedItem> <h4 style={headers_style} dir={languageDirection()}> {t(translation_path.concat("itr_num"))} 1:<br /> <br /> </h4> <h5 style={headers_style} dir={languageDirection()}> {t(translation_path.concat("res"))}:<br /> </h5> <CenterItem> <Box sx={{ width: "100%", textAlign: 'center', direction: 'ltr' }}> <QuestionTable headers={getLogisticRegressionModuleInfoColumns()} exampleEnabled={false} correctAnswers={getModuleAnswers(alpha, algo).slice(0, 1)} comparator={(res, ans) => Number(ans) === Number(res)} /> </Box> </CenterItem> <br /> <h5 style={headers_style} dir={languageDirection()}> {t(translation_path.concat("calc"))}:<br /> </h5> <CenterItem> <Box sx={{ width: "100%", textAlign: 'center', direction: 'ltr' }}> <QuestionTable headers={getLogisticRegressionDataColumnNames()} exampleEnabled={false} correctAnswers={getDataAnswers(xs, cs, algo).slice(0, 3)} comparator={(res, ans) => Number(ans) === Number(res)} /> </Box> </CenterItem> <br /> </BlackAlignedItem> </Grid> </Grid> <br /> <Grid container rowSpacing={1} columnSpacing={{ xs: 1, }}> <Grid item xs={12}> <BlackAlignedItem> <h4 style={headers_style} dir={languageDirection()}> {t(translation_path.concat("itr_num"))} 2:<br /> </h4> <h5 style={headers_style} dir={languageDirection()}> {t(translation_path.concat("res"))}:<br /> </h5> <CenterItem> <Box sx={{ width: "100%", textAlign: 'center', direction: 'ltr' }}> <QuestionTable headers={getLogisticRegressionModuleInfoColumns()} exampleEnabled={false} correctAnswers={getModuleAnswers(alpha, algo).slice(1, 2)} comparator={(res, ans) => Number(ans) === Number(res)} /> </Box> </CenterItem> <br /> <h5 style={headers_style} dir={languageDirection()}> {t(translation_path.concat("calc"))}:<br /> </h5> <CenterItem> <Box sx={{ width: "100%", textAlign: 'center', direction: 'ltr' }}> <QuestionTable headers={getLogisticRegressionDataColumnNames()} exampleEnabled={false} correctAnswers={getDataAnswers(xs, cs, algo).slice(3, 6)} comparator={(res, ans) => Number(ans) === Number(res)} /> </Box> </CenterItem> <br /> </BlackAlignedItem> </Grid> </Grid> <br /> <Grid container rowSpacing={1} columnSpacing={{ xs: 1, }}> <Grid item xs={12}> <BlackAlignedItem> <h4 style={headers_style} dir={languageDirection()}> {t(translation_path.concat("final_res"))}:<br /> </h4> <CenterItem> <Box sx={{ width: "100%", textAlign: 'center', direction: 'ltr' }}> <QuestionTable headers={getLogisticRegressionModuleColumns()} exampleEnabled={false} correctAnswers={getModuleFinalAnswers(algo)} comparator={(res, ans) => Number(ans) === Number(res)} /> </Box> </CenterItem> </BlackAlignedItem> </Grid> </Grid> </MathJaxContext> </Box> </div> ); }
<?php class UserModel extends CI_Model { /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * UserModel constructor. * * @param array $data Optional data to initialize the model. */ public function __construct(array $data = null) { $session = $this->session->userdata(config_item('auth')['LOGGED_USER']); $this->container['id'] = isset($session['id']) ? $session['id'] : null; $this->container['username'] = isset($session['username']) ? $session['username'] : null; $this->container['first_name'] = isset($session['first_name']) ? $session['first_name'] : null; $this->container['last_name'] = isset($session['last_name']) ? $session['last_name'] : null; $this->container['email'] = isset($session['email']) ? $session['email'] : null; $this->container['password'] = isset($session['password']) ? $session['password'] : null; $this->container['phone'] = isset($session['phone']) ? $session['phone'] : null; $this->container['birth_date'] = isset($session['birth_date']) ? $session['birth_date'] : null; $this->container['profile_image'] = isset($session['profile_image']) ? $session['profile_image'] : null; $this->container['isAdmin'] = isset($session['isAdmin']) ? $session['isAdmin'] : null; parent::__construct(); } /** * Registers a new user in the database. * * @param array $data An associative array containing the user's data. * The array should include the following keys: * - 'username' (string) - The user's concatenated first name and last name. * - 'email' (string) - The user's email address. * - 'password' (string) - The user's password, hashed before insertion. * - 'first_name' (string) - The user's first name. * - 'last_name' (string) - The user's last name. * - 'phone' (string) - The user's phone number. * - 'birth_date' (string) - The user's birth date in Y-m-d format. * - 'profile_image' (string) - The user's profile image URL. * * @return bool|int True on success, false on failure, or the ID of the inserted user if using auto-increment IDs. */ public function register_user($data) { $this->db->insert('user_system', $data); $user_id = $this->db->insert_id(); $this->db->select('id, username, first_name, last_name, email, phone, birth_date, profile_image, isAdmin'); $this->db->where('id', $user_id); $query = $this->db->get('user_system'); $was_created = $query->num_rows() > 0; if (!$was_created) { return false; } return $query->row_array(); } /** * Logs the user into the system. * * @param string $email The user's email address. * @param string $password The user's password. * * @return array|bool The user's data if the login is successful, false otherwise. */ public function login(string $email, string $password) { $this->db->select( 'id, username, first_name, last_name, email, phone, birth_date, profile_image, isAdmin' ); $this->db->where('email', $email); $this->db->where('password', md5($password)); $user = $this->db->get('user_system')->row_array(); return $user; } /** * Gets the user's data. * * @return array The user's data. */ public function getData() { $user_data = array( 'id' => $this->container['id'], 'username' => $this->container['username'], 'first_name' => $this->container['first_name'], 'last_name' => $this->container['last_name'], 'email' => $this->container['email'], 'phone' => $this->container['phone'], 'birth_date' => $this->container['birth_date'], 'profile_image' => $this->container['profile_image'], 'isAdmin' => $this->container['isAdmin'], ); return $user_data; } /** * Gets the user's ID. * * @return int The user's ID. */ public function getId() { return $this->container['id']; } /** * Sets id * * @param int $id id * * @return $this */ public function setId($id) { $this->container['id'] = $id; return $this; } /** * Gets username * * @return string */ public function getUsername() { return $this->container['username']; } /** * Sets username * * @param string $username username * * @return $this */ public function setUsername($username) { $this->container['username'] = $username; return $this; } /** * Gets first_name * * @return string */ public function getFirstName() { return $this->container['first_name']; } /** * Sets first_name * * @param string $first_name first_name * * @return $this */ public function setFirstName($first_name) { $this->container['first_name'] = $first_name; return $this; } /** * Gets last_name * * @return string */ public function getLastName() { return $this->container['last_name']; } /** * Sets last_name * * @param string $last_name last_name * * @return $this */ public function setLastName($last_name) { $this->container['last_name'] = $last_name; return $this; } /** * Gets email * * @return string */ public function getEmail() { return $this->container['email']; } /** * Sets email * * @param string $email email * * @return $this */ public function setEmail($email) { $this->container['email'] = $email; return $this; } /** * Gets password * * @return string */ public function getPassword() { return $this->container['password']; } /** * Sets password * * @param string $password password * * @return $this */ public function setPassword($password) { $this->container['password'] = $password; return $this; } /** * Gets phone * * @return string */ public function getPhone() { return $this->container['phone']; } /** * Sets phone * * @param string $phone phone * * @return $this */ public function setPhone($phone) { $this->container['phone'] = $phone; return $this; } /** * Gets birth_date * * @return string */ public function getBirthDate() { return $this->container['birth_date']; } /** * Sets birth_date * * @param string $birth_date birth_date * * @return $this */ public function setBirthDate($birth_date) { $this->container['birth_date'] = $birth_date; return $this; } /** * Gets profile_image * * @return string */ public function getProfilePic() { return $this->container['profile_image']; } /** * Sets profile_image * * @param string $profile_image profile_image * * @return $this */ public function setProfileImage($profile_image) { $this->container['profile_image'] = $profile_image; return $this; } /** * Gets isAdmin * * @return array */ public function getIsAdmin() { return $this->container['isAdmin']; } /** * Sets isAdmin * * @param array $isAdmin isAdmin * * @return $this */ public function setIsAdmin($isAdmin) { $this->container['isAdmin'] = $isAdmin; return $this; } }
interface Stack<T> { readonly size: number; push(value: T): void; pop(): T; } type StackNode<T> = { readonly value: T; readonly next?: StackNode<T>; }; class StackImpl<T> implements Stack<T> { private _size: number = 0; private head?: StackNode<T>; constructor(private capacity: number) {} get size(): number { return this._size; } push(value: T): void { if (this.size >= this.capacity) { throw new Error("Stack is full!"); } const node = { value, next: this.head, }; this.head = node; this._size++; } pop(): T { if (!this.head) { throw new Error("Stack is empty!"); } const node = this.head; this.head = node.next; this._size--; return node.value; } } const stringStack = new StackImpl<string>(10); for (let i = 0; i < 10; i++) { stringStack.push(`String ${i}`); } while (stringStack.size) { console.log(stringStack.pop()); } const numberStack = new StackImpl<number>(10); for (let i = 0; i < 10; i++) { numberStack.push(i); } while (numberStack.size) { console.log(numberStack.pop()); } const boolStack = new StackImpl<boolean>(10); for (let i = 0; i < 10; i++) { boolStack.push(!!i); } while (boolStack.size) { console.log(boolStack.pop()); } console.log(boolStack.pop());
package com.example.authenticationservice.infrastructure; import java.nio.charset.StandardCharsets; import java.security.Key; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.stream.Collectors; import com.example.authenticationservice.dto.TokenRequest; import com.example.authenticationservice.exceptions.TokenNotValidException; import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.UnsupportedJwtException; import io.jsonwebtoken.security.Keys; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; @Slf4j @Component public class TokenProvider { private static final String AUTHORITIES_KEY = "auth"; private static final String BEARER_TYPE = "bearer"; private static final long ACCESS_TOKEN_EXPIRE_TIME = 1000 * 60 * 30; // 30 minutes private static final long REFRESH_TOKEN_EXPIRE_TIME = 1000 * 60 * 60 * 24 * 7; // 7 days private final Key key; public TokenProvider(@Value("${jwt.secret}") String secretKey) { this.key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8)); } public TokenRequest generateTokenDto(Authentication authentication) { String roles = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date accessTokenExpiresIn = new Date(now + ACCESS_TOKEN_EXPIRE_TIME); String accessToken = Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, roles) .setExpiration(accessTokenExpiresIn) .signWith(key, SignatureAlgorithm.HS512) .compact(); String refreshToken = Jwts.builder() .setExpiration(new Date(now + REFRESH_TOKEN_EXPIRE_TIME)) .signWith(key, SignatureAlgorithm.HS512) .compact(); return TokenRequest.builder() .grantType(BEARER_TYPE) .accessToken(accessToken) .accessTokenExpiresIn(accessTokenExpiresIn.getTime()) .refreshToken(refreshToken) .build(); } public Authentication getAuthentication(String accessToken) { Claims claims = parseClaims(accessToken); if (claims.get(AUTHORITIES_KEY) == null) { throw new RuntimeException("There's no authority info."); } Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); UserDetails principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, "", authorities); } public String validateToken(String token) throws TokenNotValidException{ try { Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody(); String role = (String) claims.get("auth"); return role; } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) { log.info("Wrong JWT signature."); } catch (ExpiredJwtException e) { log.info("It is an expired JWT token."); } catch (UnsupportedJwtException e) { log.info("It is an unsupported JWT token."); } catch (IllegalArgumentException e) { log.info("There's something wrong with JWT token."); } throw new TokenNotValidException("Token is not valid."); } private Claims parseClaims(String accessToken) { try { return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(accessToken).getBody(); } catch (ExpiredJwtException e) { return e.getClaims(); } } }
import React, { useState } from 'react' import { fetchFromApi } from '../assets/fetchFromApi' import { useEffect } from 'react' import { FaThumbsUp } from 'react-icons/fa6' function CommentSection({ commentId, commentCount }) { const [comments, setComments] = useState([]) const [error, setError] = useState('') useEffect(() => { fetchFromApi(`commentThreads?part=snippet&videoId=${commentId}`) .then((data) => { return data.json() }) .then((commentsData) => { setComments(commentsData.items) }) .catch((err) => { setError(err.message) }) }, []) return ( <div> <h1 className='text-xl font-semibold my-5 flex gap-2 text-gray-600'>{commentCount}<span className='text-red-500'>Comments</span></h1> { comments.map(comment => { const commentSnippet = comment.snippet.topLevelComment.snippet return <section className='bg-slate-100 my-2 p-2' key={comment.id}> {/* commentor details */} <div className='flex items-center gap-3'> <img src={commentSnippet.authorProfileImageUrl} alt="img" className='rounded-full'/> <p className='font-semibold text-gray-700'>{commentSnippet?.authorDisplayName}</p> </div> {/* comment */} <div className='text-sm my-2'> <p dangerouslySetInnerHTML={{__html:commentSnippet?.textDisplay}}></p> </div> {/* comment statistics */} <div className='flex items-center text-[12px] gap-5'> <p>Published on: {commentSnippet?.publishedAt.slice(0,10)}</p> {/* comment likes */} <section className='flex items-center gap-1'> <FaThumbsUp/> <p>{commentSnippet?.likeCount}</p> </section> </div> </section> }) } </div> ) } export default CommentSection
import {User} from "../model/User.js"; import { catchAsyncError } from "../middlewares/catchAsyncError.js"; import ErrorHandler from "../utils/errorHandler.js"; import {sendToken} from "../utils/sendToken.js"; import { Course } from "../model/Course.js"; import crypto from "crypto"; import { sendEmail } from "../utils/sendEmail.js" import getDataUri from "../utils/dataUri.js"; import cloudinary from "cloudinary"; import { Stats } from "../model/Stats.js"; export const register = catchAsyncError(async (req,res, next)=>{ const {name ,email , password } = req.body; const file = req.file; if(!name || !email || !password || !file) { return next(new ErrorHandler("Please enter all field", 400)); } let user = await User.findOne({ email }); if (user) { return next (new ErrorHandler("User Already Exists", 409)); } const fileUri = getDataUri(file); const mycloud = await cloudinary.v2.uploader.upload(fileUri.content); user = await User.create({ name, email, password, avatar: { public_id: mycloud.public_id, url: mycloud.secure_url, }, }); sendToken(res, user, "Registered Successfully", 201); }) export const login = catchAsyncError( async(req,res,next)=>{ const {email ,password } = req.body; if (!email || !password) { return next(new ErrorHandler(" Please enter all Field ",400)); } const user = await User.findOne({email}).select("+password"); if (!user) { return next(new ErrorHandler("Incorrect Email And Password", 400)); } const isMatched = await user.comparePassword(password); if (!isMatched) { return next(new ErrorHandler("Please Enter Correct password",401)); } sendToken(res , user , `Welcome to ${user.name}` , 200); }) export const logOut = catchAsyncError(async(req,res,next)=>{ return res.status(200).cookie("token",null ,{ expires:new Date(Date.now()), httpOnly: true, secure: true, sameSite:"none", }).json({ success:true, message:"User Logged Out Successfully" }); }); export const getMyProfile = catchAsyncError(async (req, res, next) => { const user = await User.findById(req.user._id); res.status(200).json({ success: true, user, }); }); export const changePassword = catchAsyncError(async(req,res,next)=>{ const {oldPassword , newPassword } = req.body; if (!oldPassword || !newPassword) { return next(new ErrorHandler("Please Enter All Fields",400)); } const user = await User.findById(req.user._id).select("+password"); const isMatch = await user.comparePassword(oldPassword); if (!isMatch) { return next(new ErrorHandler("Incorrect Old Password ",400)); } user.password = newPassword; await user.save(); res.status(200).json({ success: true, user, message:"Password Changed Successfully" }); }) export const updateProfile = catchAsyncError(async(req,res,next)=>{ const {name ,email } = req.body; const user = await User.findById(req.user._id); if (name) user.name = name; if (email) user.email = email; await user.save(); res.status(200).json({ success:true, user, message:"User Profile Updated Successfully" }); }) export const updateProfilePicture = catchAsyncError(async(req,res,next)=>{ const file = req.file; const user = await User.findById(req.user._id); const fileUri = getDataUri(file); const mycloud = await cloudinary.v2.uploader.upload(fileUri.content); await cloudinary.v2.uploader.destroy(user.avatar.public_id); user.avatar={ public_id:mycloud.public_id, url:mycloud.secure_url } await user.save(); res.status(200).json({ success:true, user, message:"User Profile Picture Updated Successfully" }); }) export const forgotPassword = catchAsyncError(async(req,res,next)=>{ const { email } = req.body; const user = await User.findOne({email}); if (!user ) return next (new ErrorHandler("User Does not Exists",400)); const resetToken = user.getResetPasswordToken(); await user.save(); const url = `${process.env.FRONTEND_URL}/resetpassword/${resetToken}`; const message = `Click on the link to reset your password. ${url}. If you have not request then please ignore.`; // Send token via email await sendEmail(user.email, "CourseBundler Reset Password", message); res.status(200).json({ success: true, message: `Reset Token has been sent to ${user.email}`, }); }) export const resetPassword = catchAsyncError( async(req,res,next)=>{ const { token } = req.params; const resetPasswordToken = crypto .createHash("sha256") .update(token) .digest("hex"); const user = await User.findOne({ resetPasswordToken, resetPasswordExpire:{ $gt:Date.now() }, }); if (!user ) return next (new ErrorHandler("Reset Token is Invalid has been Expired ",400)); user.password = req.body.password; user.resetPasswordToken = undefined; user.resetPasswordExpire = undefined; await user.save(); res.status(201).json({ success:true, message:" Password Changed Successfully" }); }) export const addToPlaylist = catchAsyncError( async(req,res,next)=>{ const user = await User.findById(req.user._id); const course = await Course.findById(req.body.id); if (!course) return next(new ErrorHandler("Invalid Course Id", 404)); const itemExist = user.playlist.find((item)=>{ if (item.course.toString() === course._id.toString()) return true; }); if (itemExist) return next(new ErrorHandler("Item Already Exist", 409)); user.playlist.push({ course: course._id, poster: course.poster.url, }); await user.save(); res.status(201).json({ success:true, message: "Course Added to playlist", }); }) export const removeFromPlaylist = catchAsyncError( async(req,res,next)=>{ const user = await User.findById(req.user._id); const course = await Course.findById(req.query.id); if (!course) return next(new ErrorHandler("Invalid Course Id", 404)); const newPlayList = user.playlist.filter(item => { if (item.course.toString() !== course._id.toString()) return item; }); user.playlist = newPlayList; await user.save(); res.status(201).json({ success:true, message: "Course Remove From User playlist", }); }) export const getAllUsers = catchAsyncError( async(req,res,next)=>{ const users = await User.find({}); res.status(201).json({ success:true, users, }); }) export const updateUserRole = catchAsyncError( async(req,res,next)=>{ const user = await User.findById(req.params.id); if (!user ) return next (new ErrorHandler("User Does not Exists",400)); if (user.role === "user") user.role= "admin"; else user.role = "user"; await user.save(); res.status(201).json({ success:true, message:"User Role Updated Successfully", user, }); }) export const deleteUser = catchAsyncError( async(req,res,next)=>{ const user = await User.findById(req.params.id); if (!user ) return next (new ErrorHandler("User Does not Exists",400)); await cloudinary.v2.uploader.destroy(user.avatar.public_id); // cancel subscribe await user.deleteOne(); res.status(201).json({ success:true, message:"User Deleted Successfully", user, }); }) export const deleteMyProfile = catchAsyncError( async(req,res,next)=>{ const user = await User.findById(req.user._id); if (!user ) return next (new ErrorHandler("User Does not Exists",400)); await cloudinary.v2.uploader.destroy(user.avatar.public_id); // cancel subscribe await user.deleteOne(); res.status(201).cookie("token", null, { expires: new Date(Date.now()), }).json({ success:true, message:"User Profile Deleted Successfully", user, }); }) User.watch().on("change",async()=>{ const stats = await Stats.find({}).sort({createdAt:"desc"}).limit(1); const subscription = await User.find({"subscription.status":"active" }); stats[0].users = await User.countDocuments(); stats[0].subscription = subscription.length; stats[0].createdAt = new Date(Date.now()); await stats[0].save(); })
#include "ds1339.h" static uint8_t ConvertDataToSet(const T_DS1339TIME *time, uint8_t regType); static void ConvertDataToGet(uint8_t rData, T_DS1339TIME *time, uint8_t regType); /* * @brief 初始化ds1339 */ void ds1339_init(void) { Wire.setPins(2,0); Wire.begin(); } /* * @brief ds1339写寄存器 * * @param[address] 寄存器地址 * * @param[txdata] 需要写入的数据 */ static uint8_t ds1339_write_byte(uint8_t address,uint8_t txdata) { Wire.beginTransmission(0x68); /* 启动传输 */ Wire.write(address); Wire.write(txdata); return Wire.endTransmission(); /* 结束传输 */ } /* * @brief ds1339读寄存器 * * @param[address] 寄存器地址 * * @param[rxdata] 读取数据的存储地址 */ static uint8_t ds1339_read_byte(uint8_t address,uint8_t *rxdata) { uint8_t ret=0; uint8_t t=200; Wire.beginTransmission(0x68); /* 启动传输 */ Wire.write(address); ret = Wire.endTransmission(false); /* 结束传输 */ Wire.requestFrom(0x68,1); /* 请求数据 */ while(!Wire.available()) { t--; delay(1); if(t==0) { return 1; } } *rxdata = Wire.read(); return ret; } /* * @brief 把时间写到ds1339 * * @param[time] 存储时间信息的地址 */ uint8_t ds1339_write_time(const T_DS1339TIME *time) { uint8_t ret=0,i; for(i=0;i<7;i++) { if(ds1339_write_byte(REGADDR_SECONDS+i,ConvertDataToSet(time,REGADDR_SECONDS+i))) { ret = 1; return ret; } } return ret; } /* * @brief 从ds1339读取时间 * * @param[time] 存储时间信息的地址 */ uint8_t ds1339_read_time(T_DS1339TIME *time) { uint8_t ret=0,i,rx_data=0; for(i=0;i<7;i++) { if(ds1339_read_byte(REGADDR_SECONDS+i,&rx_data)) { ret = 1; return ret; }else{ ConvertDataToGet(rx_data,time,REGADDR_SECONDS+i); } } return ret; } /* * @brief 格式转换 用户->寄存器 * * @param[time] 存储时间信息的地址 * * @param[regType] 寄存器宏 */ static uint8_t ConvertDataToSet(const T_DS1339TIME *time, uint8_t regType) { uint8_t sendData = 0; switch(regType) { case REGADDR_SECONDS: if(time->second > 10) { sendData = ((time->second / 10) << 4) & 0x7F; sendData |= time->second % 10; } else { sendData = time->second; } break; case REGADDR_MINUTES: if(time->minute > 10) { sendData = ((time->minute / 10) << 4) & 0x7F; sendData |= time->minute % 10; } else { sendData = time->minute; } break; case REGADDR_HOURS: if(time->hour > 10) { // sendData = ((time->hour / 10) << 4) & 0x1F; sendData = ((time->hour / 10) << 4) & 0x30; sendData |= time->hour % 10; } else { sendData = time->hour; } break; case REGADDR_DAY: sendData = time->weekday & 0x0E; break; case REGADDR_DATA: if(time->day > 10) { sendData = ((time->day / 10) << 4) & 0x3F; sendData |= time->day % 10; } else { sendData = time->day; } break; case REGADDR_MONTH_CENTURY: if(time->month > 10) { sendData = ((time->month / 10) << 4) & 0x1F; sendData |= time->month % 10; } else { sendData = time->month; } break; case REGADDR_YEAR: if(time->year > 10) { sendData = ((time->year / 10) << 4) & 0xF0; sendData |= time->year % 10; } else { sendData = time->year; } break; default: ; } return sendData; } /* * @brief 格式转换 寄存器->用户 * * @param[rData] 寄存器读到的数据 * * @param[time] 存储时间信息的地址 * * @param[regType] 寄存器宏 */ static void ConvertDataToGet(uint8_t rData, T_DS1339TIME *time, uint8_t regType) { switch(regType) { case REGADDR_SECONDS: time->second = (rData >> 4 & 0x07) * 10 + (rData & 0x0F); break; case REGADDR_MINUTES: time->minute = (rData >> 4 & 0x07) * 10 + (rData & 0x0F); break; case REGADDR_HOURS: time->hour = (rData >> 4 & 0x03) * 10 + (rData & 0x0F); break; case REGADDR_DAY: time->weekday = rData & 0x07; break; case REGADDR_DATA: time->day = (rData >> 4 & 0x03) * 10 + (rData & 0x0F); break; case REGADDR_MONTH_CENTURY: time->month = (rData >> 4 & 0x01) * 10 + (rData & 0x0F); break; case REGADDR_YEAR: time->year = (rData >> 4 & 0x0F) * 10 + (rData & 0x0F); break; default: ; } } void ds1339_set_time_by_serial(void) { T_DS1339TIME time; if(Serial.available()==2) { time.year = 23; time.month = 9; time.day = 10; time.weekday = 7; time.hour = 9; time.minute = Serial.read(); time.second = Serial.read(); ds1339_write_time(&time); Serial.println("OK\r\n"); } }
<template> <div class="mx-6 md:mx-10 mb-6 md:mb-10 mt-6 md:mt-8" v-if="loginStore.getLoggedIn && !loader" > <NuxtLink aria-label="Return to account page" class="goBack flex items-center text-base gap-0 mb-8" to="/account" > <Icon :icon="backIcon" class="w-7" /> Go Back </NuxtLink> <div v-if="likedVideos.length > 0"> <VideoListItem v-for="video in likedVideos" :key="video.id" class="mb-8" :video="video" /> </div> <div v-else class="text-base flex justify-center items-center w-full h-full" > No videos liked </div> </div> <div v-else class="flex justify-center items-center w-full h-screen"> <Loader /> </div> </template> <script setup lang="ts"> import { mdiChevronLeft as backIcon } from '@mdi/js' import { useLoginStore } from '~~/stores/login' useHead({ title: `Liked Videos - Vox TV`, }) definePageMeta({ middleware: 'auth', }) const loginStore = useLoginStore() const client = useStrapiClient() const loader = ref(true) const router = useRouter() const likedVideos = ref<Array<Video>>([]) const likedVideoIds = ref<Array<Number>>([]) try { const resp: any = await client(`/users-permissions/liked-videos`, { headers: { Authorization: `Bearer ${loginStore.getJwt}`, }, }) likedVideoIds.value = resp // loginStore.likedVideos = resp } catch (err) { console.log(err) } onMounted(async () => { // Fetch user likes if (likedVideoIds.value.length > 0) { try { const resp: any = await client(`/videos`, { params: { filters: { id: { $in: likedVideoIds.value, }, }, populate: ['coverImage'], }, }) likedVideos.value = resp.data loader.value = false } catch (err) { console.log(err) // router.push('/account') } } else { loader.value = false likedVideos.value = [] } }) </script> <style lang="scss" scoped> .goBack { transition: 0.2s all ease-in-out; color: $accent; svg { transition: 0.2s all ease-in-out; fill: $accent; } &:hover { color: $secondary; svg { fill: $secondary; } } } .dark .goBack { color: $accent; svg { fill: $accent; } &:hover { color: white; svg { fill: white; } } } </style>
import React, { useState, useEffect } from 'react'; import { getPost, getPosts } from '@store/post'; import { useAppDispatch } from '@utils/hooksUtil'; import { twitterAPI } from '@utils/axios.wrapper'; import router from 'next/router'; import { ComposeContainer } from '../post/ComposeContainer'; export const Compose = () => { const dispatch = useAppDispatch(); const [value, setValue] = useState(''); const [postID, setPostID] = useState(null); const [imageURL, setImageURL] = useState(''); const handleTempPost = async () => { const { data } = await twitterAPI.post('/api/posts'); setPostID(data.id); dispatch(getPost(data.id)); }; const onSubmit = async () => { await twitterAPI.put(`/api/posts/${postID}`, { content: value, status: 'PUBLISHED', }); dispatch(getPosts()); router.push('/'); }; const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => { e.preventDefault(); if (!e.target.files) return undefined; // const file = Array.from(e.target.files); const file = e.target.files[0]; const formData = new FormData(); formData.append('file', file); const { data } = await twitterAPI.post( `/api/posts/${postID}/image`, formData, { headers: { 'content-type': 'multipart/form-data', }, }, ); return setImageURL(data.url); }; useEffect(() => { handleTempPost(); dispatch(getPosts()); }, []); return ( <ComposeContainer onChange={setValue} value={value} onSubmit={onSubmit} onFileChange={handleFileChange} previewImageURL={imageURL} /> ); };
<template> <v-app> <v-main> <v-app-bar> <v-app-bar-title>글보기</v-app-bar-title> </v-app-bar> <v-container> <v-sheet max-width="800" class="mx-auto mt-16"> <v-form> <v-row> <v-col cols="12"> <v-text-field name="" label="제목" id="" v-model="article.title" ></v-text-field> <v-textarea label="내용" rows="22" no-resize auto-grow="" v-model="article.content" ></v-textarea> </v-col> </v-row> </v-form> <v-sheet> <v-row> <v-col cols="6"> <v-btn color="indigo" @click="btnList">목록</v-btn> </v-col> <v-col cols="6" class="text-end"> <v-btn color="warning" class="mr-5" @click="btnModify" >수정</v-btn > <v-btn color="error" @click="btnDelete()">삭제</v-btn> </v-col> </v-row> </v-sheet> </v-sheet> </v-container> </v-main> <v-footer class="bg-indigo-lighten-1"> copyright &copy;Voard v1.0</v-footer> </v-app> </template> <script setup> import { useAppStore } from "@/store/app"; import axios from "axios"; import { reactive } from "vue"; import { onBeforeMount } from "vue"; import { useRouter } from "vue-router"; const userStore = useAppStore(); const router = useRouter(); const btnList = () => { router.push("/list"); }; const btnModify = () => { router.push("/modify"); }; const btnDelete = (no) => { axios .delete("http://localhost:8184/" + no) .then((res) => { console.log(res); router.push("/list"); }) .catch((err) => { alert(err.message); }); }; const article = reactive({ title: "", content: "", }); onBeforeMount(() => { console.log(userStore.getArticle); if (userStore.getArticle == null) { const no = localStorage.getItem("no"); const loadArticle = userStore.setArticle(no); article.title = loadArticle.title; article.content = loadArticle.content; } }); </script> <style scoped></style>
char *ft_strlowcase(char *str) { unsigned int i; i = 0; while (str[i] != '\0') { if (str[i] >= 'A' && str[i] <= 'Z') str[i] = str[i] + 32; i++; } return (str); } /* main for it : int main(void) { char str1[] = "HeLLo, WoRLd!"; char str2[] = "!(CODING is FUN)"; write(1, "Original String 1: ", 20); ft_putstr(str1); write(1, "\n", 1); write(1, "Uppercase String 1: ", 21); ft_putstr(ft_strupcase(str1)); write(1, "\n", 1); write(1, "Original String 2: ", 20); ft_putstr(str2); write(1, "\n", 1); write(1, "Uppercase String 2: ", 21); ft_putstr(ft_strupcase(str2)); write(1, "\n", 1); } expected output : Original String 1: HeLLo, WoRLd! Uppercase String 1: hello, world! Original String 2: !(CODING is FUN) Uppercase String 2: !(coding is fun) */
import 'package:dio/dio.dart'; import 'package:video2/constants.dart'; import 'package:video2/core/strings.dart'; class DioHelperSearch { static Dio? dio; static init() { dio = Dio( BaseOptions( baseUrl: "https://google.serper.dev/", receiveDataWhenStatusError: true, ), ); } static Future<Response> getData({ required String url, required Map<String, dynamic> query, }) async { return await dio!.get( url, queryParameters: query, options: Options( headers: {}, ), ); } static Future<Response> postData({ required String url, Map<String, dynamic>? query, required Map<String, dynamic> body, }) async { dio!.options.headers = query; return await dio!.post( url, data: body, ); } }
-- auto install packer if not installed local ensure_packer = function() local fn = vim.fn local install_path = fn.stdpath("data") .. "/site/pack/packer/start/packer.nvim" if fn.empty(fn.glob(install_path)) > 0 then fn.system({ "git", "clone", "--depth", "1", "https://github.com/wbthomason/packer.nvim", install_path }) vim.cmd([[packadd packer.nvim]]) return true end return false end local packer_bootstrap = ensure_packer() -- true if packer was just installed -- autocommand that reloads neovim and installs/updates/removes plugins -- when file is saved vim.cmd([[ augroup packer_user_config autocmd! autocmd BufWritePost plugins-setup.lua source <afile> | PackerSync augroup end ]]) -- import packer safely local status, packer = pcall(require, "packer") if not status then return end -- add list of plugins to install return packer.startup(function(use) -- packer can manage itself use("wbthomason/packer.nvim") use("bluz71/vim-nightfly-guicolors") -- preferred colorscheme -- essential plugins -- use("tpope/vim-surround") -- add, delete, change surroundings (it's awesome) -- file explorer use("nvim-tree/nvim-tree.lua") -- vs-code like icons use("kyazdani42/nvim-web-devicons") -- statusline use("nvim-lualine/lualine.nvim") use { 'nvim-telescope/telescope.nvim', tag = '0.1.0', requires = { {'nvim-lua/plenary.nvim'}, {'nvim-lua/popup.nvim'}, {'nvim-telescope/telescope-fzf-native.nvim', run = 'make' }, } } -- {'nvim-telescope/telescope-fzy-native.nvim'}, -- fuzzy finding w/ telescope -- autocompletion use("hrsh7th/nvim-cmp") -- completion plugin use("hrsh7th/cmp-buffer") -- source for text in buffer use("hrsh7th/cmp-path") -- source for file system paths -- snippets use("L3MON4D3/LuaSnip") -- snippet engine use("saadparwaiz1/cmp_luasnip") -- for autocompletion use("rafamadriz/friendly-snippets") -- useful snippets -- managing & installing lsp servers, linters & formatters use("williamboman/mason.nvim") -- in charge of managing lsp servers, linters & formatters use("williamboman/mason-lspconfig.nvim") -- bridges gap b/w mason & lspconfig -- configuring lsp servers use("neovim/nvim-lspconfig") -- easily configure language servers use("hrsh7th/cmp-nvim-lsp") -- for autocompletion use({ "glepnir/lspsaga.nvim", branch = "main" }) -- enhanced lsp uis use("onsails/lspkind.nvim") -- vs-code like icons for autocompletion -- -- formatting & linting use("jose-elias-alvarez/null-ls.nvim") -- configure formatters & linters use("jayp0521/mason-null-ls.nvim") -- bridges gap b/w mason & null-ls -- treesitter configuration use({ "nvim-treesitter/nvim-treesitter", run = function() require("nvim-treesitter.install").update({ with_sync = true }) end, }) use 'simrat39/rust-tools.nvim' -- -- auto closing -- use("windwp/nvim-autopairs") -- autoclose parens, brackets, quotes, etc... -- use({ "windwp/nvim-ts-autotag", after = "nvim-treesitter" }) -- autoclose tags -- git integration use("lewis6991/gitsigns.nvim") -- show line modifications on left hand side use 'numToStr/Comment.nvim' use {'hkupty/iron.nvim'} use {"akinsho/toggleterm.nvim", tag = '*'} use { 'CRAG666/code_runner.nvim', requires = 'nvim-lua/plenary.nvim' } use 'ggandor/leap.nvim' use 'karb94/neoscroll.nvim' -- use { -- 'declancm/cinnamon.nvim', -- config = function() require('cinnamon').setup() end -- } if packer_bootstrap then require("packer").sync() end end)
import { useMutation } from '@tanstack/react-query'; import type { GetStaticProps, NextPage } from 'next'; import { useRouter } from 'next/router'; import { serverSideTranslations } from 'next-i18next/serverSideTranslations'; import { useReducer, useState } from 'react'; import signUpCaller from 'api-callers/sign-up'; import type { SignUpFormValues } from 'backend/dtos/signUp.dto'; import type { AccountWithPopulatedSide } from 'backend/types/auth'; import SEO from 'components/abstract/SEO'; import InfoDialog from 'components/dialog/info-dialog'; import { infoDialogReducer, initInfoDialogState, } from 'components/dialog/info-dialog/reducer'; import { FlexRowCenter } from 'components/flex-box'; import { SIGN_IN_ROUTE } from 'constants/routes.ui.constant'; import type { AxiosErrorWithMessages } from 'helpers/error.helper'; import { useCustomTranslation } from 'hooks/useCustomTranslation'; import { useServerSideErrorDialog } from 'hooks/useServerErrorDialog'; import SignUp from 'pages-sections/auth/SignUp'; const SignUpPage: NextPage = () => { const [state, dispatch] = useReducer(infoDialogReducer, initInfoDialogState); const [isRedirecting, setIsRedirecting] = useState(false); const [hasError, setHasError] = useState(false); const router = useRouter(); const { t } = useCustomTranslation(['customer', 'account']); const { ErrorDialog, dispatchErrorDialog } = useServerSideErrorDialog({ t, operationName: 'Đăng ký', onStart: () => setHasError(true), onClose: () => { if (!hasError) { setIsRedirecting(true); router.push('/'); } }, }); const { mutate: signUp, isLoading } = useMutation< AccountWithPopulatedSide<'customer'>, AxiosErrorWithMessages, SignUpFormValues >({ mutationFn: (values: SignUpFormValues) => signUpCaller.signUp(values), onSuccess: () => { setHasError(false); dispatch({ type: 'open_dialog', payload: { variant: 'info', title: 'Đăng ký thành công', content: t('Account.SignUp.Success'), }, }); }, onError: dispatchErrorDialog, }); const handleFormSubmit = async (values: SignUpFormValues) => { signUp(values); }; return ( <> <FlexRowCenter flexDirection='column' minHeight='100vh'> <SEO title='Đăng ký' /> <SignUp loading={isLoading} disabled={isRedirecting} handleFormSubmit={handleFormSubmit} /> </FlexRowCenter> <InfoDialog variant={state.variant} open={state.open} handleClose={() => { dispatch({ type: 'close_dialog' }); setIsRedirecting(true); router.push(SIGN_IN_ROUTE); }} title={state.title} content={state.content} /> <ErrorDialog /> </> ); }; export const getStaticProps: GetStaticProps = async ({ locale }) => { const locales = await serverSideTranslations(locale ?? 'vn', [ 'customer', 'account', 'common', ]); return { props: { ...locales } }; }; export default SignUpPage;
package org.example.newsmanager.controller; import lombok.RequiredArgsConstructor; import org.example.newsmanager.models.bean.UserRegistrationDataBean; import org.example.newsmanager.service.UserService; import org.example.newsmanager.service.exception.ServiceException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid; @Controller @RequestMapping("/user") @RequiredArgsConstructor public class UserController { private final UserService userService; @GetMapping("/goToRegistrationPage") public String showRegistrationPage(Model model) { UserRegistrationDataBean user = new UserRegistrationDataBean(); model.addAttribute("user", user); model.addAttribute("action", "registrationPage"); return "baseLayout/baseLayout"; } @PostMapping("/doRegistrationUser") public String doRegistration(@ModelAttribute("user") @Valid UserRegistrationDataBean user, BindingResult bindingResult, Model model) { try { if(bindingResult.hasErrors()){ model.addAttribute("action", "registrationPage"); return "baseLayout/baseLayout"; } userService.registration(user); return "redirect:/news"; } catch (ServiceException e) { return "redirect:/news/errorPage"; } } @GetMapping("/authentication") public String goToNewsList(){ return "redirect:/news/goToNewsList"; } @GetMapping("/access-denied") public String getAccessDeniedPage(){ return "accessDenied"; } }
import './App.css'; import * as THREE from 'three'; import { Canvas, extend, useFrame, useLoader, useThree } from '@react-three/fiber'; import {OrbitControls} from "@react-three/drei" import circleImg from './circle.png'; import { Suspense, useCallback, useMemo, useRef } from 'react'; import { FontLoader } from 'three/examples/jsm/loaders/FontLoader' import myFont from '../../public/Vtks Revolt_Regular.json' import { TextGeometry } from 'three/examples/jsm/geometries/TextGeometry'; import MeshMaterial from "../Pages/MeshBasicMaterial" import Text from "./Text" import React from "react" function CameraControls(){ const { camera, gl: {domElement} } = useThree(); const controlsRef = useRef(); useFrame(() => controlsRef.current.update()) return ( <OrbitControls ref={controlsRef} args={[camera, domElement]} autoRotate autoRotateSpeed={-0.2} enableZoom={false} /> ); } function AnimationCanvas() { const imgTex = useLoader(THREE.TextureLoader, circleImg); const bufferRef = useRef(); let t = 0; let f = 0.002; let a = 3; const graph = useCallback((x, z) => { return Math.sin(f * (x ** 2 + z ** 2 + t)) * a; }, [t, f, a]) const count = 100 const sep = 3 let positions = useMemo(() => { let positions = [] for (let xi = 0; xi < count; xi++) { for (let zi = 0; zi < count; zi++) { let x = sep * (xi - count / 2); let z = sep * (zi - count / 2); let y = graph(x, z); positions.push(x, y, z); } } return new Float32Array(positions); }, [count, sep, graph]) useFrame(() => { t += 15 const positions = bufferRef.current.array; let i = 0; for (let xi = 0; xi < count; xi++) { for (let zi = 0; zi < count; zi++) { let x = sep * (xi - count / 2); let z = sep * (zi - count / 2); positions[i + 1] = graph(x, z); i += 3; } } bufferRef.current.needsUpdate = true; }) return ( <Suspense fallback={null}> {/* <Points /> */} <points> <bufferGeometry attach="geometry"> <bufferAttribute ref={bufferRef} attach="attributes-position" array={positions} count={positions.length / 3} itemSize={3} /> </bufferGeometry> <pointsMaterial attach="material" map={imgTex} color={"red"} size={0.5} sizeAttenuation transparent={false} alphaTest={0.5} opacity={1.0} /> </points> </Suspense> ); } function Jumbo() { const ref = useRef() useFrame(({ clock }) => (ref.current.rotation.x = ref.current.rotation.y = ref.current.rotation.z = Math.sin(clock.getElapsedTime()) * 0.3)) return ( <group ref={ref}> <Text hAlign="right" position={[-10, 16.5, 0]} children="REHAN" /> <Text hAlign="right" position={[-10, 10, 0]} children="GORAYA" /> <Text hAlign="right" position={[-10, 4.5, 0]} children="MOSYALA" /> </group> ) } function Jumbo1() { return ( <group> <Text hAlign="right" position={[-10, 16.5, 0]} children="CLICK" /> </group> ) } function App() { extend({ TextGeometry }) const [visible,setVisible] = React.useState(false); return ( <div className="anim"> <Suspense fallback={<div>Loading...</div>}> <Canvas colormanagement={"false"} camera={{ position: [100, 10, 0], fov: 75 }} > {!visible&&<MeshMaterial setVisible={setVisible} />} {!visible&&<Jumbo1 />} <AnimationCanvas /> {visible&&<Jumbo />} <ambientLight args={["#ffffff", 0.25]} /> <CameraControls /> </Canvas> </Suspense> </div> ); } export default App;
import numpy as np from tensorflow.keras.preprocessing.image import ImageDataGenerator # 1. 데이터 train_datagen = ImageDataGenerator( rescale=1./255, horizontal_flip=True, vertical_flip=True, width_shift_range=0.1, height_shift_range=0.1, rotation_range=5, zoom_range=1.2, shear_range=0.7, fill_mode='nearest', ) test_datagen = ImageDataGenerator(rescale=1./255) xy_train = train_datagen.flow_from_directory( './_data/brain01_data/train', target_size=(150, 150), batch_size=5, class_mode='binary', shuffle=False, ) # Found 160 images belonging to 2 classes. xy_test = test_datagen.flow_from_directory( './_data/brain01_data/test', target_size=(150, 150), batch_size=5, class_mode='binary', shuffle=False, ) # Found 120 images belonging to 2 classes. # print(xy_train) # # <tensorflow.python.keras.preprocessing.image.DirectoryIterator object at 0x0000028D21338550> # # print(xy_train[0]) # print(xy_train[0][0]) # x값 # print(xy_train[0][1]) # y값 # # print(xy_train[0][2]) # 없음 # print(xy_train[0][0].shape, xy_train[0][1].shape) # # (5, 150, 150, 3) (5,) # print(xy_train[31][1]) # 마지막 배치 y # print(xy_train[32][1]) # 없음 # print(type(xy_train)) # <class 'tensorflow.python.keras.preprocessing.image.DirectoryIterator'> # print(type(xy_train[0])) # <class 'tuple'> # print(type(xy_train[0][0])) # <class 'numpy.ndarray'> # print(type(xy_train[0][1])) # <class 'numpy.ndarray'> # 2. 모델 구성 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv2D, Flatten model = Sequential() model.add(Conv2D(32, (2,2), input_shape=(150, 150, 3))) model.add(Flatten()) model.add(Dense(1, activation='sigmoid')) # 3. 컴파일, 훈련 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc']) # model.fit(x_train, y_train) hist = model.fit_generator(xy_train, epochs=50, steps_per_epoch=32, # validation_data=xy_test, validation_steps=4 ) # 160/5 = 32 acc = hist.history['acc'] val_acc = hist.history['val_acc'] loss = hist.history['loss'] val_loss = hist.history['val_loss'] # 위에거로 시각화 할 것 print('acc :', acc[-1]) print('val_acc :', val_acc[:-1])
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { library } from '@fortawesome/fontawesome-svg-core' import { faArrowsRotate } from '@fortawesome/free-solid-svg-icons' import { useEffect, useState } from 'react'; library.add(faArrowsRotate) export default function RefreshButton({setMinutes, setSeconds, minutes, seconds}) { const [canRefresh, setCanRefresh] = useState(false); const handleRefresh = () => { setMinutes(0); setSeconds(0); } useEffect(() => { setCanRefresh(minutes === 0 && seconds === 0) }, [minutes, seconds]) return ( <button className={"refresh " + (canRefresh ? "d-none" : "")} onClick={handleRefresh}> <FontAwesomeIcon icon={faArrowsRotate} /> </button> ) }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProjectsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('projects', function (Blueprint $table) { $table->bigIncrements('id'); $table->text('english_title'); $table->text('marathi_title'); $table->text('english_description'); $table->text('marathi_description'); $table->string('english_link'); $table->string('marathi_link'); $table->string('english_pdf'); $table->string('marathi_pdf'); $table->enum('status', ['completed', 'ongoing','future']); $table->string('is_deleted')->default(false); $table->boolean('is_active')->default(true); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('projects'); } }
import SearchIcon from '@mui/icons-material/Search' import { Box, CircularProgress, Grid, LinearProgress, ListItemButton, Select, Stack, useTheme, } from '@mui/material' import Avatar from '@mui/material/Avatar' import Divider from '@mui/material/Divider' import IconButton from '@mui/material/IconButton' import List from '@mui/material/List' import ListItem from '@mui/material/ListItem' import ListItemAvatar from '@mui/material/ListItemAvatar' import ListItemText from '@mui/material/ListItemText' import MenuItem from '@mui/material/MenuItem' import Paper from '@mui/material/Paper' import TextField from '@mui/material/TextField' import Typography from '@mui/material/Typography' import { motion } from 'framer-motion' import React, { useEffect, useRef, useState } from 'react' import { useQuery } from 'react-query' import { useNavigate } from 'react-router' import useAuth from '../../Hooks/useAuth' import { searchStudentRequest } from '../../Services/API/searchStudentsRequest' const options = [ { value: 'name', label: 'Name', }, { value: 'rollNo', label: 'Roll no', }, ] export default function SearchStudent() { const fieldRef = useRef('') const [query, setQuery] = useState('') const [type, setType] = useState('name') const [studentHistory, setStudentHistory] = useState([]) const [isLoadingHistory, setIsLoadingHistory] = useState(false) const { token } = useAuth() const navigate = useNavigate() const theme = useTheme() const handleSearch = e => { e.preventDefault() setQuery(fieldRef.current.value) } let displayType if (type === 'rollNo') displayType = 'roll no' else if (type === 'name') displayType = 'name' const { isError, isLoading, data } = useQuery( ['students', query, type], () => searchStudentRequest(token, { type, query }), { staleTime: 1000 * 60 * 60 * 24, enabled: !!token && query !== '', }, ) const handleClick = (studentId, name, rollNo, avatar) => { const history = localStorage.getItem('admin_search_history') let newHistory = [] if (history) newHistory = [...JSON.parse(history)] if (newHistory.filter(student => student._id === studentId).length <= 0) { newHistory.unshift({ _id: studentId, name, rollNo, avatar }) localStorage.setItem('admin_search_history', JSON.stringify(newHistory)) } navigate(`/head/search/${studentId}`) } useEffect(() => { setIsLoadingHistory(prev => true) const history = localStorage.getItem('admin_search_history') if (!history) { setIsLoadingHistory(prev => false) return } let parsedHistory = JSON.parse(history) if (parsedHistory.length > 5) { parsedHistory = parsedHistory.slice(0, 5) localStorage.setItem( 'admin_search_history', JSON.stringify(parsedHistory.slice(0, 5)), ) } setStudentHistory(parsedHistory) setIsLoadingHistory(prev => false) }, []) return ( <Grid container> <Grid item xs={12} md={8}> <Stack width='100%'> <Box component='form' onSubmit={handleSearch} sx={{ width: '100%' }}> <Stack direction='row'> <Select id='outlined-select-currency' value={type} onChange={e => setType(e.target.value)} > {options.map(option => ( <MenuItem key={option.value} value={option.value}> {option.label} </MenuItem> ))} </Select> <TextField fullWidth placeholder='Name or Roll no' inputRef={fieldRef} /> <IconButton type='submit' sx={{ p: '10px' }} aria-label='search'> <SearchIcon /> </IconButton> </Stack> </Box> <List sx={{ width: '100%', bgcolor: 'background.paper' }}> {isLoading && ( <Stack width='100%' alignItems='center' margin='2em 0'> <CircularProgress /> </Stack> )} {data?.length > 0 && !isLoading ? ( !isLoading && !isError && data?.map((student, i) => ( <motion.div key={student._id} initial={{ filter: 'blur(20px)' }} animate={{ filter: 'blur(0px)' }} transition={{ delay: 0.1 * i }} > <ListItem alignItems='flex-start'> <ListItemButton onClick={() => handleClick( student?._id, student?.name, student?.rollNo, student?.avatar, ) } > <ListItemAvatar> <Avatar alt={student?.name} src={student?.avatar} /> </ListItemAvatar> <ListItemText primary={student?.name} secondary={ <> <Typography sx={{ display: 'inline' }} component='span' variant='body2' color='text.primary' > {student?.rollNo} </Typography> </> } /> </ListItemButton> </ListItem> </motion.div> )) ) : query === '' ? ( <Typography color='error' align='center'> Enter the {displayType} of student </Typography> ) : ( <Typography color='error' align='center'> Could not find student by that {displayType} </Typography> )} </List> </Stack> </Grid> <Grid item xs={12} md={4}> <Paper sx={{ position: 'relative' }}> {isLoadingHistory && ( <LinearProgress sx={{ position: 'absolute', width: '100%', top: 0, left: 0, }} /> )} <Typography align='center' sx={{ paddingTop: '1em', }} > History </Typography> {!isLoadingHistory && ( <List sx={{ width: '100%', bgcolor: 'background.paper' }}> {studentHistory.length > 0 ? ( studentHistory?.map((student, i) => ( <motion.div key={student._id} initial={{ filter: 'blur(20px)' }} animate={{ filter: 'blur(0px)' }} transition={{ delay: 0.1 * i }} > <ListItem alignItems='flex-start'> <ListItemButton onClick={() => handleClick( student?._id, student?.name, student?.rollNo, student?.avatar, ) } > <ListItemAvatar> <Avatar alt={student?.name} src={student?.avatar} /> </ListItemAvatar> <ListItemText primary={student?.name} secondary={ <> <Typography sx={{ display: 'inline' }} component='span' variant='body2' color='text.primary' > {student?.rollNo} </Typography> </> } /> </ListItemButton> </ListItem> <Divider variant='inset' component='li' /> </motion.div> )) ) : ( <Typography color={theme.palette.warning.main} align='center'> No history present </Typography> )} </List> )} </Paper> </Grid> </Grid> ) }
import React from "react"; import { MDBRow, MDBCol, MDBInput } from "mdbreact"; import { Philippines } from "../../services/fakeDb"; export default function AddressSelect({ handleChange = () => {}, address = {}, size = "3", label = "Address Information", view = false, }) { const handleAddress = (key, value) => { const _address = { ...address }; switch (key) { case "region": _address.region = value; _address.province = Philippines.initialProvince(value); _address.city = Philippines.initialCity(_address.province); break; case "province": _address.province = value; const cityCode = Philippines.initialCity(value); _address.city = cityCode; break; default: _address[key] = value; break; } handleChange("address", _address); }; const { region = "REGION III (CENTRAL LUZON)", province = "NUEVA ECIJA", city = "CABANATUAN CITY", barangay = "", zip = "", street = "", } = address; return ( <> <h6> <b>{label}</b> </h6> <MDBRow className={`${view && "pt-2"}`}> <MDBCol md={size} className="px-1"> {view ? ( <> <h6 className="mb-0">Region:</h6> <h5 className="font-weight-bold">{region}</h5> </> ) : ( <> <label className="mb-0">Region</label> <select value={region} onChange={(e) => handleAddress("region", e.target.value)} className="form-control" > {Philippines.Regions.map(({ name, code }) => ( <option key={code} value={name}> {name} </option> ))} </select> </> )} </MDBCol> <MDBCol md={size} className="px-1"> {view ? ( <> <h6 className="mb-0">Province:</h6> <h5 className="font-weight-bold">{province}</h5> </> ) : ( <> <label className="mb-0">Province</label> <select value={province} onChange={(e) => handleAddress("province", e.target.value)} className="form-control" > {Philippines.Provinces(region).map(({ name, code }) => ( <option key={code} value={name}> {name} </option> ))} </select> </> )} </MDBCol> <MDBCol md={size} className="px-1"> {view ? ( <> <h6 className="mb-0">City/Municipality:</h6> <h5 className="font-weight-bold">{city}</h5> </> ) : ( <> <label className="mb-0">City/Municipality</label> <select value={city} onChange={(e) => handleAddress("city", e.target.value)} className="form-control" > {Philippines.Cities(province).map(({ name, code }) => ( <option key={code} value={name}> {name} </option> ))} </select> </> )} </MDBCol> <MDBCol md={size} className="px-1"> {view ? ( <> <h6 className="mb-0">Barangay:</h6> <h5 className="font-weight-bold">{barangay || <i>N/A</i>}</h5> </> ) : ( <> <label className="mb-0">City/Municipality</label> <select value={barangay} onChange={(e) => handleAddress("barangay", e.target.value)} className="form-control" > <option>???</option> {Philippines.Barangays(city).map(({ name }) => ( <option key={name} value={name}> {name} </option> ))} </select> </> )} </MDBCol> </MDBRow> <MDBRow className={`${view && "pt-2"}`}> <MDBCol md="8" className="px-1"> {view ? ( <> <h6 className="mb-0">Street:</h6> <h5 className="font-weight-bold">{street || <i>N/A</i>}</h5> </> ) : ( <MDBInput type="text" label="Street Name" value={street} outline onChange={(e) => handleAddress("street", e.target.value)} /> )} </MDBCol> <MDBCol md="4" className="px-1"> {view ? ( <> <h6 className="mb-0">Zip Code:</h6> <h5 className="font-weight-bold">{zip || <i>N/A</i>}</h5> </> ) : ( <MDBInput type="number" label="Zip Code" value={String(zip)} outline onChange={(e) => handleAddress("zip", Number(e.target.value))} /> )} </MDBCol> </MDBRow> </> ); }
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { MatDialog } from "@angular/material"; import { throwError } from "rxjs"; import { catchError } from "rxjs/operators"; import { ErrorComponent } from "./error/error.component"; @Injectable() export class ErrorInterceptor implements HttpInterceptor{ constructor (private dialog: MatDialog){} intercept(req: HttpRequest<any>, next: HttpHandler) { return next.handle(req).pipe( catchError((error:HttpErrorResponse) =>{ let errorMessage = "An unknown error ocurred"; if(error.error.message){ errorMessage = error.error.message; } this.dialog.open(ErrorComponent,{data: {message:errorMessage}}); return throwError(error); }) ); } }
package org.example.serverproject.serviceImpl; import org.example.serverproject.models.Category; import org.example.serverproject.repositories.CategoryRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional(readOnly = true) public class CategoryServiceImpl { private final CategoryRepo categoryRepo; @Autowired public CategoryServiceImpl(CategoryRepo categoryRepo) { this.categoryRepo = categoryRepo; } public List<Category> findAll() { return categoryRepo.findAll(); } public Category findOne(int id) { return categoryRepo.findById(id).orElse(null); } @Transactional public void save(Category category) { categoryRepo.save(category); } @Transactional public void deleteById(int id) { categoryRepo.deleteById(id); } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strmapi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: majacque <majacque@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/24 12:06:15 by majacque #+# #+# */ /* Updated: 2021/10/21 21:06:17 by majacque ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_strmapi(char const *s, char (*f)(unsigned int, char)) { char *ret; unsigned int i; if (!s || !f) return (NULL); ret = ft_calloc(sizeof(char), ft_strlen(s) + 1); if (!ret) return (NULL); i = 0; while (s[i]) { ret[i] = f(i, s[i]); i++; } return (ret); }
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Estudos de IFrames</title> </head> <body> <!-- O IFRAME cria uma janela dentro do página html para exibir um site externo a ela. Essa tag é do tipo display inline, isto é, um quadrado numa linha. O tamanho padrão de um IFRAME é 300x150 (lagura e altura) e o seu fundo é trasparente. Essas dimensões podem ser mudadas tanto no html (com parâmetros width e height) como no CSS (que sempre prevalecerá sobre o html). O IFRAME usa o parâmetro "frameborder" para indicar se o quadrado terá ou não cotorno, com o valor "0" para zero contorno e "1" para contorno. Isso também pode ser mudado no CSS com a propriedade "border". Ainda há o parâmetro "scrolling" (com os valores "auto", "yes" e "no") para indicar se haverá ou não uma barra rolagem lateral quando a página exceder o tamanho do iframe. Por padrão, sempre que exceder, haverá barra de rolagem. Hoje em dia, por questões de segurança, o IFRAME é um recurso pouco utilizado. Sites como Google não permitem que sua página seja exibida em iframe.--> <h1>Testando o uso de um iframe</h1> <p>Acessando o site do <iframe src="https://www.cursoemvideo.com" frameborder="0" height="500" width="500"></iframe> para aprender a programar.</p> <!-- No espaço entre o frameborder e o fechamento normalmente é usado para colocar um texto avisando que o dispositivo não conseguiu ler o iframe. Porém pode ser usado como um link para a página que estaria no iframe.--> <p>O repositório do <iframe src="https://gustavoguanabara.github.io" frameborder="0"> <a href="https://gustavoguanabara.github.io">Gustavo Guanabara</a></iframe> também é legal.</p> </body> </html>
<?php namespace Tests\Feature; use App\Models\City; use App\Models\User; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; class CityTest extends TestCase { use DatabaseTransactions, WithFaker; public function get_authenticated_user() { $admin_phone_number = config('app.admin_phone_number'); $admin = User::select('users.*')->where('phone_number',$admin_phone_number)->first(); $this->actingAs($admin); return $admin; } /** * A basic feature test example. */ public function test_city_web(): void { $out = "test_city_web"; var_dump($out); $admin = $this->get_authenticated_user(); $response = $this->get('/cities'); $response->assertStatus(200); $dt_url = "/ajax-get-city-data?_=1680244096377&columns%5B0%5D%5Bdata%5D=DT_RowIndex&columns%5B0%5D%5Bname%5D=id&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=name&columns%5B1%5D%5Bname%5D=name&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=action&columns%5B2%5D%5Bname%5D=action&columns%5B2%5D%5Bsearchable%5D=false&columns%5B2%5D%5Borderable%5D=false&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&draw=1&length=10&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&search=&start=0"; $response = $this->getJson($dt_url); $response->assertStatus(200)->assertJsonStructure([ 'draw', 'recordsTotal', 'recordsFiltered', 'data' => [ '*' => [ 'id', 'name', 'created_at', 'updated_at', 'deleted_at', 'action', 'DT_RowIndex' ] ] ]); } public function test_get_create_city_web(): void { $out = "test_get_create_city_web"; var_dump($out); $admin = $this->get_authenticated_user(); $response = $this->get('/cities/create'); $response->assertStatus(200); } public function test_store_create_city(): void { $out = "test_store_create_city"; var_dump($out); $admin = $this->get_authenticated_user(); $response = $this->post('/cities', [ 'name' => $this->faker->name, ]); $response->assertStatus(302) ->assertRedirect('/cities'); } public function test_city_detail_web(): void { $out = "test_city_detail_web"; var_dump($out); $admin = $this->get_authenticated_user(); $city_id = City::all()->random()->id; $response = $this->get('/cities/' . $city_id); $response->assertStatus(200); } public function test_update_city(): void { $out = "test_update_city"; var_dump($out); $admin = $this->get_authenticated_user(); $rand_city_id = City::all()->random()->id; $response = $this->put('/cities/' . $rand_city_id, [ 'name' => $this->faker->name, ]); $response->assertStatus(302) ->assertRedirect('/cities/' . $rand_city_id); } public function test_delete_city(): void { $out = "test_delete_city"; var_dump($out); $admin = $this->get_authenticated_user(); $city_id = City::all()->random()->id; $response = $this->delete('/cities/' . $city_id); $response->assertStatus(302) ->assertRedirect('/cities'); } }
package com.ohgiraffers.section02.set.run; import java.util.*; public class Application1 { public static void main(String[] args) { /* * Set 인터페이스를 구현한 Set 컬렉션 클래스의 특징 * 1. 요소의 저장 순서를 유지하지 않는다. * 2. 같은 요소의 중복 저장을 허용하지 않는다. (null 값도 중복되지 않게 하나의 null만 저장) * */ /* * HashSet 클래스 * Set 컬렉션 클래스에서 가장 많이 사용되는 클래스 중 하나이다. * Hash-> 해시 알고리즘을 사용해서 검색 속도가 빠르다는 장점이 있다. * */ HashSet<String> hSet = new HashSet<>(); // Set hset2 = new HashSet(); // Collection hset3 = new HashSet(); hSet.add(new String("java")); hSet.add("oracle"); hSet.add("jdbc"); hSet.add("html"); hSet.add("css"); // 저장 순서는 유지되지 않는다. System.out.println("hset : " + hSet); hSet.add("java"); // 중복을 허용하지 않는다. System.out.println("hset : " + hSet); System.out.println("저장된 객체수 : " + hSet.size()); System.out.println("포함확인 : " + hSet.contains("oracle")); /* * 저장된 객체를 한개씩 꺼내는 기능이 없다. * 반복문을 이용해서 연속처리하는 방법 * */ // 1. toArray()배열로 바꾸고 for문 사용 Object[] arr = hSet.toArray(); for (int i = 0; i < arr.length; i++){ System.out.println(i + " : " + arr[i]); } // 2. iterator()로 목록을 만들어서 연속 처리 Iterator<String> iter = hSet.iterator(); while (iter.hasNext()){ System.out.println("Iterator로 목록을 만들어 출력 = " + iter.next()); } Boolean result = hSet.remove("oracle"); System.out.println("지운 결과 : " + result); System.out.println("hset = " + hSet); hSet.clear(); System.out.println("isEmpty : " + hSet.isEmpty()); System.out.println("hSet = " + hSet); } }
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class ButtonWidget extends StatelessWidget { final String text; final VoidCallback onClicked; const ButtonWidget({ Key? key, required this.text, required this.onClicked, }) : super(key: key); @override Widget build(BuildContext context) => ElevatedButton( style: ElevatedButton.styleFrom( minimumSize: Size.fromHeight(50), shape: StadiumBorder(), backgroundColor: Color.fromARGB(135, 139, 75, 148), ), onPressed: onClicked, child: FittedBox( child: Text(text, style: TextStyle(fontSize: 18, color: Colors.white)), ), ); }
package co.com.sofka.questions.model; import javax.validation.constraints.NotBlank; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; /** * QuestionDTO class. * DTO para la colección Question */ public class QuestionDTO { private String id; @NotBlank private String userId; @NotBlank(message = "Debe existir el userName para este objeto") private String userName; @NotBlank private String question; @NotBlank private String description; @NotBlank private String category; private List<AnswerDTO> answers; public QuestionDTO() { } public QuestionDTO(String userId, String userName, String question, String description, String category) { this.userId = userId; this.userName = userName; this.question = question; this.description = description; this.category = category; } public QuestionDTO(String id, String userId, String userName, String question, String description, String category) { this.id = id; this.userId = userId; this.userName = userName; this.question = question; this.description = description; this.category = category; } public List<AnswerDTO> getAnswers() { this.answers = Optional.ofNullable(answers).orElse(new ArrayList<>()); return answers; } public void setAnswers(List<AnswerDTO> answers) { this.answers = answers; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public String toString() { return "QuestionDTO{" + "id='" + id + '\'' + ", userId='" + userId + '\'' + ", userName='" + userName + '\'' + ", question='" + question + '\'' + ", description='" + description + '\'' + ", category='" + category + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QuestionDTO that = (QuestionDTO) o; return Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(id); } }
"use client" import { useThemeStore } from "@/store"; import { useTheme } from "next-themes"; import { themes } from "@/config/thems"; import { ResponsiveContainer, PieChart, Pie, Cell } from 'recharts'; const PieChartWithPaddingAngle = ({ height = 300 }) => { const { theme: config, setTheme: setConfig } = useThemeStore(); const { theme: mode } = useTheme(); const theme = themes.find((theme) => theme.name === config); const data = [ { name: 'Group A', value: 400 }, { name: 'Group B', value: 300 }, { name: 'Group C', value: 300 }, { name: 'Group D', value: 200 }, ]; const COLORS = [ `hsl(${theme?.cssVars[mode === "dark" ? "dark" : "light"].primary})`, `hsl(${theme?.cssVars[mode === "dark" ? "dark" : "light"].info})`, `hsl(${theme?.cssVars[mode === "dark" ? "dark" : "light"].warning})`, `hsl(${theme?.cssVars[mode === "dark" ? "dark" : "light"].success})` ]; return ( <ResponsiveContainer width="100%" height={height}> <PieChart width={"100%"} height={height}> <Pie data={data} cx={120} cy={150} innerRadius={80} outerRadius={120} fill={`hsl(${theme?.cssVars[mode === "dark" ? "dark" : "light"].primary})`} paddingAngle={5} dataKey="value" > {data.map((entry, index) => ( <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} /> ))} </Pie> <Pie data={data} cx={420} cy={120} startAngle={180} endAngle={0} innerRadius={80} outerRadius={100} fill={`hsl(${theme?.cssVars[mode === "dark" ? "dark" : "light"].info})`} paddingAngle={5} dataKey="value" > {data.map((entry, index) => ( <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} /> ))} </Pie> </PieChart> </ResponsiveContainer> ); }; export default PieChartWithPaddingAngle;
import sys import os # Add the parent directory to the sys.path parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(parent_dir) from solvers import Solver from rich import print import random import csv import concurrent.futures def run_thread(solver, user_choice_algorithm, initial_state, goal_state): try: solution, steps, cost_of_path, nodes_expanded, search_depth, running_time = solver.solve(user_choice_algorithm, initial_state, goal_state) solutions[user_choice_algorithm][initial_state] = [solution, cost_of_path, nodes_expanded, search_depth, running_time] if solution: print(f'Solution found for {initial_state}.') else: print(f'No solution found for {initial_state}.') except Exception as err: print(f'Error occurred while solving {initial_state}.') print(err) quit() if __name__ == '__main__': sample_size = int(input('Enter sample size: ')) solutions = {'1': {},'2': {},'3': {},'4': {}} solver = Solver() test_cases = [x.strip() for x in open('tests.txt', 'r')] sample = random.sample(test_cases, sample_size) goal_state = '0123456780' executor = concurrent.futures.ThreadPoolExecutor(max_workers=5000) for i, initial_state in enumerate(sample): executor.submit(run_thread, solver, '1', initial_state, goal_state) executor.submit(run_thread, solver, '2', initial_state, goal_state) executor.submit(run_thread, solver, '3', initial_state, goal_state) executor.submit(run_thread, solver, '4', initial_state, goal_state) print(i) executor.shutdown(wait=True) with open('results.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['Initial State'] + ['Solution', 'Steps', 'Nodes Expanded', 'Search Depth', 'Running Time'] * 4) for initial_state in solutions['1']: row = [] row.append(initial_state) for algorithm in solutions: row.extend(solutions[algorithm][initial_state]) writer.writerow(row)
## Usage **Want to suggest a new feature or chat with us?** [Join our Discord](https://deno.re/discord) ### Minify Files When you request a `*.min.js`, `*.min.mjs` or `*.min.jsx` file and the release does not contain such a file, deno.re will automatically minify the file. ```ts // Since deno-esbuild only comes with a mod.js file, deno.re will minify it for you. import { build } from 'https://deno.re/esbuild/deno-esbuild@v0.20.0/mod.min.js' ``` ### Import Latest Tag ```ts import { encodeHex } from 'https://deno.re/denoland/deno_std/encoding/hex.ts' ``` ### Import Specific Commit ```ts import { encodeHex } from 'https://deno.re/denoland/deno_std@6cc097b6212eaba083634b0e826c0916a49a3148/encoding/hex.ts' ``` ### Import Specific Tag ```ts import { encodeHex } from 'https://deno.re/denoland/deno_std@0.220.0/encoding/hex.ts' ``` ### Omit Entry Point ```ts import { crypto } from 'https://deno.re/denoland/deno_std@0.221.0/crypto' // ↓ import { crypto } from 'https://deno.re/denoland/deno_std@0.221.0/crypto/mod.ts' ``` The order of priority for file extensions can be found [here](https://github.com/boywithkeyboard/deno.re/blob/main/registry/get_entry_point.ts#L6). ## Self-Hosting There are two approaches you can take to deploy your custom instance of deno.re. You can either 1. use our [Docker image](https://github.com/boywithkeyboard/deno.re/pkgs/container/deno.re) 2. or clone the repository and run `npm ci && npm run build` to build the server Either way, you need to set the below environment variables in order for the server to work: - `BASE_URL` *(The base URL for your custom instance, e.g. `https://foo.com`)* - `S3_HOSTNAME` *(The public hostname of your bucket, e.g. `bar.foo.com`)* - `S3_ACCESS_KEY_ID` - `S3_SECRET_ACCESS_KEY` - `S3_BUCKET` *(The name of your S3 bucket, e.g. `foo`)* - `S3_ENDPOINT` *(e.g. `https://<id>.eu.r2.cloudflarestorage.com` for Cloudflare R2)* ## Terms of Use deno.re is designed to be a permanent caching layer for Deno modules stored on GitHub. If you decide to abuse our service in whatever way, we reserve the right to blacklist your GitHub account. No guarantee of availability is assumed for this service.
import { Component, OnInit } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { SidebarService } from '../shared/sidebar/sidebar.service' import { FormBuilder, Validators, FormGroup } from '@angular/forms'; import { ValidatorsService } from '../shared/services/validators.service'; import { AuthServiceService } from '../auth/services/auth-service.service'; import Swal from 'sweetalert2'; import { ProfileService } from './services/profile.service'; @Component({ selector: 'app-user-profile', templateUrl: './user-profile.component.html', styleUrls: ['./user-profile.component.scss'] }) export class UserProfileComponent implements OnInit { FormReactive: FormGroup = this.fb.group({ name: ['', [Validators.required, Validators.pattern(this.validatorsService.patternName), this.validatorsService.nameVacio]], lastName: ['', [Validators.required, Validators.pattern(this.validatorsService.patternName), this.validatorsService.nameVacio]], city: ['', [Validators.required, this.validatorsService.nameVacio]], phone: ['', [Validators.required, Validators.minLength(10), Validators.pattern(this.validatorsService.phonePattern), Validators.maxLength(10)]] }); FormReactiveAgregar: FormGroup = this.fb.group({ type: ['', [Validators.required, this.validatorsService.nameVacio]], city: ['', [Validators.required, this.validatorsService.nameVacio]], address: ['', [Validators.required, this.validatorsService.nameVacio]], price: ['', [Validators.required, ]], desc: ['', [Validators.required, this.validatorsService.nameVacio]], images: [[], [Validators.required]] }); user:any; FormReactivePassword: FormGroup = this.fb.group({ uid: [''], passwordA: ['', [Validators.required]], password: ['', [Validators.required, Validators.minLength(8)]], passwordv: ['', [Validators.required]] }, { validators: [this.validatorsService.passwordActual('passwordA', 'uid'), this.validatorsService.passwordIguales('password', 'passwordv')] }); hide = true; public imagenes: any; products: any; get nameMsg(): string { const errors = this.FormReactive.get('name').errors; if (errors['required'] || errors['vacio']){ return 'El nombre es obligatorio.'; }else if (errors['pattern']){ return 'El nombre no peude contener caracteres numericos o especiales.'; } return ''; } get lastNameMsg(): string { const errors = this.FormReactive.get('lastName').errors; if (errors['required'] || errors['vacio']){ return 'El apellido es obligatorio.'; }else if (errors['pattern']){ return 'El apellido no peude contener caracteres numericos o especiales.'; } return ''; } constructor(public sidebarservice: SidebarService, private router: Router, private fb: FormBuilder, private validatorsService: ValidatorsService, private authService: AuthServiceService, private profileService: ProfileService) { } toggleSidebar() { this.sidebarservice.setSidebarState(!this.sidebarservice.getSidebarState()); } getSideBarState() { return this.sidebarservice.getSidebarState(); } hideSidebar() { this.sidebarservice.setSidebarState(true); } ngOnInit() { this.router.events.subscribe((evt) => { if (!(evt instanceof NavigationEnd)) { return; } window.scrollTo(0, 0) }); this.user = this.authService.user; console.log(this.user); this.FormReactive.get('name').setValue(this.user.name); this.FormReactive.get('phone').setValue(this.user.phone); this.FormReactive.get('city').setValue(this.user.city); this.FormReactive.get('lastName').setValue(this.user.lastName); this.FormReactivePassword.get('uid').setValue(this.user.uid); this.profileService.obtenerProductosDeUsuario(this.user.uid) .subscribe((resp)=>{ this.products = resp.produts; }); $.getScript('./assets/plugins/fancy-file-uploader/jquery.ui.widget.js'); $.getScript('./assets/plugins/fancy-file-uploader/jquery.fileupload.js'); $.getScript('./assets/plugins/fancy-file-uploader/jquery.iframe-transport.js'); $.getScript('./assets/plugins/fancy-file-uploader/jquery.fancy-fileupload.js'); $.getScript('./assets/plugins/Drag-And-Drop/imageuploadify.min.js'); $.getScript('./assets/js/custom-file-upload.js'); } onProductos(){ this.router.navigateByUrl('profile/productos'); } campoValid(campo:string){ return (this.FormReactive.get(campo).invalid && this.FormReactive.get(campo).touched); } campoValidP(campo:string){ return (this.FormReactivePassword.get(campo).invalid && this.FormReactivePassword.get(campo).touched); } campoValidA(campo:string){ return (this.FormReactiveAgregar.get(campo).invalid && this.FormReactiveAgregar.get(campo).touched); } updateInfo(){ const {name, lastName, city, phone} = this.FormReactive.value; const body ={ name, lastName, city, phone } this.authService.updateUser(body, this.user.uid) .subscribe( ok =>{ if(ok === true){ console.log(ok); this.router.navigateByUrl('profile'); window.location.reload(); }else{ Swal.fire('Error', ok, 'error'); } }); } onUpdatePassword(){ const {password} = this.FormReactivePassword.value; const body = { password } this.authService.updateUser(body, this.user.uid) .subscribe( ok=>{ if(ok === true){ window.location.reload(); }else{ Swal.fire('Error', ok, 'error'); } }); } agregarHab(){ const {type, city, address, price, desc} = this.FormReactiveAgregar.value; const body = new FormData(); body.append('image', this.imagenes.file, this.imagenes.name); body.append('type', type); body.append('city', city); body.append('address', address); body.append('price', price); body.append('desc', desc); this.profileService.insertProduct(body) .subscribe(resp =>{ if(resp.ok === true){ window.location.reload(); }else{ Swal.fire('Error', resp, 'error'); } }) } capturarFile(event){ const [file] = event.target.files; this.imagenes = { file: file, name: file.name } } deleteProduct(uid){ this.profileService.deleteProduct(uid) .subscribe((resp)=>{ if(resp.ok === true){ console.log(resp); window.location.reload(); }else{ Swal.fire('Error', resp, 'error'); } }); } }
import React, {useRef, useState} from 'react'; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; import Avatar from "@material-ui/core/Avatar"; import IconButton from "@material-ui/core/IconButton"; import {useHistory} from 'react-router-dom' import {makeStyles} from "@material-ui/core"; import {useFirebase, useFirebaseConnect} from "react-redux-firebase"; import { v4 as uuidv4 } from 'uuid'; import {useForm} from "react-hook-form"; import FormLoader from "./FormLoader"; import {useSelector} from "react-redux"; const DEFAULT_AVATAR = "https://www.w3schools.com/howto/img_avatar.png" const useStyles = makeStyles(theme => ({ textField: { marginTop: theme.spacing(1), marginBottom: theme.spacing(1), }, avatarPicker: { alignSelf: 'center', justifyContent: "center", alignItems: "center", display: 'flex', '& > *': { margin: theme.spacing(1), }, }, inputFile: { display: "none", }, avatarLarge: { width: theme.spacing(15), height: theme.spacing(15), borderColor: 'black', borderWidth: theme.spacing(1) }, })) const Form = () => { const classes = useStyles() const history = useHistory() useFirebaseConnect('users') const firebase = useFirebase() const users = useSelector((state) => state.firebase.ordered.users ? state.firebase.ordered.users : []) const form = useRef(null) const fileInput = useRef(null) const { register, handleSubmit, errors } = useForm({ mode: 'onChange', reValidateMode: 'onChange', defaultValues: { email: '', name: '', phone: '', }, }); const [avatar, setAvatar] = useState(null) const [loading, setLoading] = useState(false) const onSubmit =async (data) => { setLoading(true) const formData = new FormData(form.current) let file = formData.get('avatar') let fileName = null; data.phone = parseInt(data.phone) if(file.size > 0){ fileName = uuidv4() + '.' + file.name.split('.').pop() await firebase.uploadFile('/',file,null,{name: fileName} ) } if(fileName) data.image = fileName firebase.ref('users').push(data, () => { setLoading(false) history.goBack() }) } const onFileInputChange = () => { if(fileInput.current.files.length > 0){ let file = fileInput.current.files[0] let reader = new FileReader() reader.onload = () => setAvatar(reader.result) reader.readAsDataURL(file) } } return ( <form autoComplete="off" ref={form} noValidate onSubmit={handleSubmit(onSubmit)}> <div className={classes.avatarPicker}> <input accept="image/*" ref={fileInput} onChange={onFileInputChange} className={classes.inputFile} id="icon-button-file" type="file" name="avatar" /> <label htmlFor="icon-button-file"> <IconButton color="primary" aria-label="upload picture" component="span"> <Avatar src={avatar ? avatar : DEFAULT_AVATAR} className={classes.avatarLarge} /> </IconButton> </label> </div> <TextField fullWidth className={classes.textField} error={!!errors.name} id="name" name="name" label="Nombre" defaultValue={''} helperText={errors.name ? (errors.name.message || 'Este nombre ya esta registrado.') : ''} required inputRef={register({ required: 'Este campo es obligatorio.', validate: value => { let existUser = users.find( user => user.value.name === value) return !existUser } })} /> <TextField fullWidth className={classes.textField} error={!!errors.phone} id="phone" name="phone" label="Telefono" type="tel" defaultValue={''} helperText={errors.phone ? errors.phone.message : ''} inputRef={register({ required: 'Debes registrar un numero de telefono.', pattern: { value: /^\d+$/, message: 'Este campo solo permite numeros enteros.', }, })} /> <TextField fullWidth className={classes.textField} error={!!errors.email} id="email" name="email" type="email" label="Correo" defaultValue={''} helperText={errors.email ? errors.email.message : ''} inputRef={register({ required: 'Debes registrar una direccion email.', pattern: { value: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, message: 'Debes registrar una direccion email valida.', }, })} /> { loading && <FormLoader/> } <Button variant="contained" type="submit" color="primary"> Registrar </Button> <Button variant="contained" color="secondary" onClick={() => history.goBack()}> Volver </Button> </form> ); }; export default Form;
import 'package:audioplayers/audioplayers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:frontend/service/utils/sp_provider.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:markdown/markdown.dart' as md; /// /// Custom chat message display [markdown] style /// - [CustomMarkdown] /// - [CustomAudioTagSyntax] /// - [CustomAudioBuilder] /// - [CustomSyntaxHighlighter] /// class CustomMarkdown extends StatelessWidget { CustomMarkdown(this.displayMsg, {super.key}); final String displayMsg; final AudioPlayer player = AudioPlayer(); @override Widget build(BuildContext context) { return MarkdownBody( data: displayMsg, selectable: true, fitContent: true, syntaxHighlighter: CustomSyntaxHighlighter(), styleSheet: MarkdownStyleSheet( codeblockDecoration: BoxDecoration( color: Colors.white70, borderRadius: BorderRadius.circular(8))), onTapLink: (String text, String? href, String title) { if (href == null || href.isEmpty) return; launchUrl(Uri.parse(href)); }, imageBuilder: (Uri uri, String? title, String? alt) { var header = {'Authorization': SpProvider().getString('token')}; return Container( alignment: Alignment.topLeft, width: 128, height: 128, child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(8)), child: Image.network(uri.toString(), headers: header))); }, extensionSet: md.ExtensionSet(md.ExtensionSet.gitHubWeb.blockSyntaxes, [ ...md.ExtensionSet.gitHubWeb.inlineSyntaxes, CustomAudioTagSyntax() ]), builders: {'audio': CustomAudioBuilder(player)}, ); } } /// /// Custom audio tag syntax, /// to parse <audio>https://localhost:8000/static/audio/xxxx.wav</audio> /// class CustomAudioTagSyntax extends md.InlineSyntax { CustomAudioTagSyntax() : super(r'\s*<audio>(.*?)<\/audio>\s*'); @override bool onMatch(md.InlineParser parser, Match match) { var el = md.Element.withTag('audio'); el.attributes['src'] = match[1]!.trim(); parser.addNode(el); return true; } } /// /// Custom audio widget, /// to show audio name and click play it /// class CustomAudioBuilder extends MarkdownElementBuilder { CustomAudioBuilder(this.player) : super(); final AudioPlayer player; @override Widget visitElementAfter(md.Element element, TextStyle? preferredStyle) { var src = element.attributes['src']; if (src == null) return const SizedBox(); return TextButton.icon( onPressed: () { player.play( UrlSource("$src?Authorization=${SpProvider().getString('token')}")); }, icon: const Icon(Icons.play_circle_outline_rounded), label: Text( src.split("audio/")[1], style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500), ), ); } } /// /// Custom syntax high light keywords,you can add others(key and style) /// const Map<String, TextStyle> _keywordsStyle = { 'class': TextStyle(color: Colors.blue), 'Widget': TextStyle(color: Colors.blue), 'BuildContext': TextStyle(color: Colors.blue), 'void': TextStyle(color: Colors.blueAccent), 'build': TextStyle(color: Colors.blueAccent), 'var': TextStyle(color: Colors.green), 'int': TextStyle(color: Colors.green), 'String': TextStyle(color: Colors.green), 'bool': TextStyle(color: Colors.green), 'Future': TextStyle(color: Colors.purple), 'Stream': TextStyle(color: Colors.purple), 'if': TextStyle(color: Colors.orange), 'else': TextStyle(color: Colors.orange), 'return': TextStyle(color: Colors.orange), // ... Other keywords }; /// /// TextSpan regExp,you can add others /// final RegExp _regExp = RegExp( r'\b(class|Widget|BuildContext|build|void|var|int|String|bool|Future|Stream|if|else|return)\b', multiLine: true, ); /// /// Custom syntax high light /// class CustomSyntaxHighlighter extends SyntaxHighlighter { @override TextSpan format(String source) { List<TextSpan> spans = []; int lastMatchEnd = 0; for (final match in _regExp.allMatches(source)) { final String beforeMatch = source.substring(lastMatchEnd, match.start); final String matchString = match[0]!; spans.add(TextSpan(text: beforeMatch)); spans .add(TextSpan(text: matchString, style: _keywordsStyle[matchString])); lastMatchEnd = match.end; } if (lastMatchEnd < source.length) { spans.add(TextSpan(text: source.substring(lastMatchEnd))); } return TextSpan(children: spans); } }
import React from "react"; import { Link } from "react-router-dom"; import { FaHome } from "react-icons/fa"; import { IoMdSend } from "react-icons/io"; import Translation from "../languages.json"; import styles from "./feedback.module.css"; const Feedback = () => { return ( <div className={styles.feedbackContainer}> <Link to="/ASL4All" className="absolute top-0 right-0 p-8"> <FaHome size={64} className="text-white" /> </Link> <form> <div className={styles.feedbackForm}> <input placeholder={Translation[Translation.current].name} /> <select name="feedback-type" id="feedback-type"> <option value="problem">{Translation[Translation.current].problem}</option> <option value="suggestion">{Translation[Translation.current].suggestion}</option> <option value="praise">{Translation[Translation.current].praise}</option> <option value="other">{Translation[Translation.current].other}</option> </select> <input placeholder={Translation[Translation.current].email} /> <textarea placeholder={Translation[Translation.current].message} required /> <button type="submit">{Translation[Translation.current].send} <IoMdSend /></button> </div> </form> </div> ); }; export default Feedback;
import { IEmployee } from './employee'; import { Component, OnInit } from '@angular/core'; import { EmployeeService } from './employee.service' @Component({ selector: 'list-employee', templateUrl: './employeeList.component.html', styleUrls: ['./employeeList.component.scss'], // Register EmployeeService in this component by // declaring it in the providers array providers: [EmployeeService] }) export class EmployeeListComponent implements OnInit { employees: IEmployee[]; articles: any; indiaTopHeadings: any; JSObject: any[] = []; // This property keeps track of which radio button is selected // We have set the default value to All, so all the employees // are displayed in the table by default selectedEmployeeCountRadioButton: string = 'All'; // Inject EmployeeService using the constructor // The private variable _employeeService which points to // EmployeeService singelton instance is then available // throughout this class constructor(private _employeeService: EmployeeService) { this.employees = this._employeeService.getEmployees(); } ngOnInit(): void { //this.employees = this._employeeService.getEmployees(); this._employeeService.getNews().subscribe((data) => { console.log(data); this.articles = data['articles']; }); this._employeeService.getIndiaTopHeadings().subscribe((indiaNews: any) => { console.log(indiaNews); this.indiaTopHeadings = indiaNews['articles']; for (let property in indiaNews) { this.JSObject = this.JSObject.concat(`Property: ${property} and Value: ${indiaNews[property]}`); } }); this._employeeService.getRhreporting().subscribe(rhreportingData => { console.log(rhreportingData); }); } getEmployees() { this.employees = this.employees.concat({ code: 'emp107', name: 'Nancy', gender: 'Female', annualSalary: 9800.481, dateOfBirth: '10/28/1979' }); } trackByEmpCode(index: number, employee: any): string { return employee.code; } getTotalEmployeesCount(): number { return this.employees.length; } getMaleEmployeesCount(): number { return this.employees.filter(e => e.gender.toLowerCase() === 'male').length; } getFemaleEmployeesCount(): number { return this.employees.filter(e => e.gender.toLowerCase() === 'female').length; } // Depending on which radio button is selected, this method updates // selectedEmployeeCountRadioButton property declared above // This method is called when the child component (EmployeeCountComponent) // raises the custom event - countRadioButtonSelectionChanged // The event binding is specified in employeeList.component.html onEmployeeCountRadioButtonChange(selectedRadioButtonValue: string): void { this.selectedEmployeeCountRadioButton = selectedRadioButtonValue; } }
"use strict"; // Class definition var KTSigninGeneral = function() { // Elements var form; var submitButton; var validator; // Handle form var handleForm = function(e) { // Init form validation rules. For more info check the FormValidation plugin's official documentation:https://formvalidation.io/ validator = FormValidation.formValidation( form, { fields: { 'email': { validators: { notEmpty: { message: 'Email tidak boleh kosong' }, emailAddress: { message: 'Email tidak valid' } } }, // 'password': { // validators: { // notEmpty: { // message: 'Password tidak boleh kosong' // } // } // } }, plugins: { trigger: new FormValidation.plugins.Trigger(), bootstrap: new FormValidation.plugins.Bootstrap5({ rowSelector: '.fv-row' }) } } ); // Handle form submit submitButton.addEventListener('click', function (e) { // Prevent button default action e.preventDefault(); // Validate form validator.validate().then(function (status) { if (status == 'Valid') { // Show loading indication submitButton.setAttribute('data-kt-indicator', 'on'); // Disable button to avoid multiple click submitButton.disabled = true; // Simulate ajax request setTimeout(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': CSRF_TOKEN } }); var formLogin = $('#kt_sign_in_form').serialize(); var emailSubmit = $('#email').val(); $.ajax({ type: "POST", url: urlLogin, data: formLogin, success: function (data) { var temp = []; $.each(data, function (key, value) { temp.push({ v: value, k: key }); }); if(temp[0].v == 'email_not_exist'){ submitButton.removeAttribute('data-kt-indicator'); submitButton.disabled = false; Swal.fire({ text: "Mohon maaf email tidak ditemukan, Cek lagi!", icon: "error", buttonsStyling: false, confirmButtonText: "Ok, siap!", customClass: { confirmButton: "btn btn-primary" } }); } if(temp[0].v == 'overload'){ submitButton.removeAttribute('data-kt-indicator'); submitButton.disabled = false; Swal.fire({ text: "Mohon maaf email kamu sudah melakukan 3 kali permintaan forgot password, coba lagi besok!", icon: "error", buttonsStyling: false, confirmButtonText: "Ok, siap!", customClass: { confirmButton: "btn btn-primary" } }); } if(temp[0].v == 'error'){ submitButton.removeAttribute('data-kt-indicator'); submitButton.disabled = false; Swal.fire({ text: "Mohon maaf terjadi kesalahan saat pengiriman link!", icon: "error", buttonsStyling: false, confirmButtonText: "Ok, siap!", customClass: { confirmButton: "btn btn-primary" } }); } if(temp[0].v == 'success'){ submitButton.removeAttribute('data-kt-indicator'); submitButton.disabled = false; Swal.fire({ text: "Kami telah mengirim link reset password ke email kamu silahkan cek inbox atau spam email kamu dan ikuti langkah selanjutnya!", icon: "success", buttonsStyling: false, confirmButtonText: "Oke siap!", customClass: { confirmButton: "btn btn-primary" } }).then(function (result) { if (result.isConfirmed) { form.querySelector('[name="email"]').value= ""; //form.querySelector('[name="password"]').value= ""; window.setTimeout(function(){location.href=urlHome},500); } }); } }, error: function (data) { } }); }, 1000); } else { // Show error popup. For more info check the plugin's official documentation: https://sweetalert2.github.io/ Swal.fire({ text: "Sorry, looks like there are some errors detected, please try again.", icon: "error", buttonsStyling: false, confirmButtonText: "Ok, siap!", customClass: { confirmButton: "btn btn-primary" } }); } }); }); } // Public functions return { // Initialization init: function() { form = document.querySelector('#kt_sign_in_form'); submitButton = document.querySelector('#kt_sign_in_submit'); handleForm(); } }; }(); // On document ready KTUtil.onDOMContentLoaded(function() { KTSigninGeneral.init(); });
package com.example.Authentication.configuration; import com.example.Authentication.helper.JwtUtil; import com.example.Authentication.service.CustomUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class JwtAuthentificationFilter extends OncePerRequestFilter { @Autowired private CustomUserDetailsService customUserDetailsService; @Autowired private JwtUtil jwtUtil; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //get jwt //bearer //validate String requestTokenHeader=request.getHeader("Authorization"); String username=null; String jwtToken=null; //null and format if(requestTokenHeader!=null && requestTokenHeader.startsWith("Bearer ")){ jwtToken=requestTokenHeader.substring(7); try{ username=this.jwtUtil.getUsernameFromToken(jwtToken); } catch(Exception e){ e.printStackTrace(); } // UserDetails userDetails = this.customUserDetailsService.loadUserByUsername(username); //security if(username!=null && SecurityContextHolder.getContext().getAuthentication()==null) { UserDetails userDetails = this.customUserDetailsService.loadUserByUsername(username); if (jwtUtil.validatetoken(jwtToken, userDetails)) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } } else{ System.out.println("Token is not validated.."); } } filterChain.doFilter(request,response); } }
import { storage } from "near-sdk-core" import { u128, logging, PersistentSet, Context, ContractPromiseBatch } from 'near-sdk-as'; import { AccountId, ONE_NEAR, MIN_ACCOUNT_BALANCE, asNEAR } from '../../utils'; import { Campaign } from './models'; export const ownerIds = new PersistentSet<AccountId>("ci"); /* RULES: 1 Campaign per account. Campaign can be overwritten (edit) if it's unlocked. Campaign locks on first contributrion from backer. Campaign un-locks once its state is SUCCESS or FAIL. Once campaign goal is reached, the owner can call closeCampaign. */ /* initCampaign() Args - goal: 1500 (N) - description: Help us create the new portable flamethrower! - name: Portable flamethrower - lifetime: timestamp integer */ export function initCampaign(goal: u128, description: String, name: String, lifetime: u128): AccountId { const c = createOrEdit(goal, description, name, u128.from(lifetime)); return c.creator; } /* backCampaign() Args - cid: The campaign you want to back. */ export function backCampaign(cid: AccountId): void { const c = getCampaign(cid); c.back(); storage.set(c.creator, c); } /* Closes a campaign. Pays out funds to c.creator if SUCCESS Returns contributions to c.backers if FAIL */ export function closeCampaign(): void { const c = getCampaign(Context.sender); assert(Context.sender == c.creator, "This method can be called only by the Campaign creator!") c.close(); storage.set(c.creator, c); } /* Logs campaigns. */ export function getCampaigns(): void { const ids = ownerIds.values(); for (let i = 0; i < ids.length; i++) { logging.log(getCampaign(ids[i])); } } /* Decides wether to return campaign in storage || overwrite with new campaign Based on locked and payed campaign params. */ function createOrEdit(goal: u128, description: String, name: String, lifetime: u128): Campaign { if (storage.hasKey(Context.sender)) { let c: Campaign = getCampaign(Context.sender); assert(!c.isLocked(), "Campaign is Locked!"); if(!c.isPayed()) { return c; } } let c = new Campaign(goal, description, name, lifetime); if(!ownerIds.has(c.creator)) { ownerIds.add(c.creator); } storage.set(Context.sender, c); return c; } /* Returns a campaign based on its id. */ export function getCampaign(cid: AccountId): Campaign { return storage.getSome<Campaign>(cid); } /* Gather scattered testing funds. Place your accountId in ContractPromiseBatch.create(); */ export function returnBalance(): u128 { assert(getCampaign(Context.sender), "You can not withdraw funds. No campaigns in your name!"); const payout = u128.sub(u128.from(Context.accountBalance), u128.mul(u128.from(3),ONE_NEAR)); // E.g ContractPromiseBatch.create("test.testnet"); ContractPromiseBatch.create(Context.sender).transfer(payout); return payout; }
// // AuthenticationEndpoint.swift // Layers // // Created by Michael Sevy on 5/8/17. // Copyright © 2017 Michael Sevy. All rights reserved. // import Foundation import Alamofire /** An enum that conforms to `BaseEndpoint`. It defines endpoints that would be used for authentication. */ enum AuthenticationEndpoint: Int { case login // case loginFacebook(facebookAccessToken: String) // case signupFacebook(facebookInfo: FacebookUserInfo) // case signUp(signUpInfo: SignUpInfo) // case update(updateInfo: UpdateInfo, userId: Int) case currentUser // case oauth2(oauth2Info: OAuth2Info) // case oauth1Step1(oauth1Step1Info: OAuth1Step1Info) // case oauth1Step2(oauth1Step2Info: OAuth1Step2Info) // case forgotPasswordRequest(email: String) // case forgotPasswordReset(token: String, newPassword: String) // case changeEmailRequest(newEmail: String) // case changeEmailConfirm(token: String, userId: Int) // case changeEmailVerify(token: String, userId: Int) // case changePassword(currentPassword: String, newPassword: String) // case confirmEmail(token: String, userId: Int) var endpointInfo: Int { // let path: String // let requestMethod: Alamofire.HTTPMethod // let parameters: Alamofire.Parameters? // let parameterEncoding: Alamofire.ParameterEncoding? // let requiresAuthorization: Bool switch self { case .login: //do something : insert a URL for alamfire? // path = "login" // requestMethod = .post // parameters = ["email": email, "password": password] // parameterEncoding = JSONEncoding() // requiresAuthorization = false break // case let .loginFacebook(facebookAccessToken): // path = "PicksUsers/login-facebook" // requestMethod = .post // parameters = ["facebookAccessToken": facebookAccessToken]; // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .signupFacebook(facebookInfo): // path = "PicksUsers/signup-facebook" // requestMethod = .post // parameters = facebookInfo.parameters // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .signUp(signUpInfo): // path = "register" // requestMethod = .post // parameters = signUpInfo.parameters // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .update(updateInfo, userId): // path = "users/\(userId)" // requestMethod = .patch // parameters = updateInfo.parameters // parameterEncoding = JSONEncoding() // requiresAuthorization = true // break case .currentUser: // path = "PicksUsers/me" // requestMethod = .get // parameters = nil // parameterEncoding = nil // requiresAuthorization = true break // case let .oauth2(oauth2Info): // path = "social-auth" // requestMethod = .post // parameters = oauth2Info.parameters // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .oauth1Step1(oauth1Step1Info): // path = "social-auth" // requestMethod = .post // parameters = oauth1Step1Info.parameters // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .oauth1Step2(oauth1Step2Info): // path = "social-auth" // requestMethod = .post // parameters = oauth1Step2Info.parameters // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .forgotPasswordRequest(email): // path = "forgot-password" // requestMethod = .post // parameters = ["email": email] // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .forgotPasswordReset(token, newPassword): // path = "forgot-password/reset" // requestMethod = .post // parameters = ["token": token, "new_password": newPassword] // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .changeEmailRequest(newEmail): // path = "change-email" // requestMethod = .post // parameters = ["new_email": newEmail] // parameterEncoding = JSONEncoding() // requiresAuthorization = true // break // case let .changeEmailConfirm(token, userId): // path = "change-email/\(userId)/confirm" // requestMethod = .post // parameters = ["token": token] // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .changeEmailVerify(token, userId): // path = "change-email/\(userId)/verify" // requestMethod = .post // parameters = ["token": token] // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break // case let .changePassword(currentPassword, newPassword): // path = "users/change-password" // requestMethod = .post // parameters = ["current_password": currentPassword, "new_password": newPassword] // parameterEncoding = JSONEncoding() // requiresAuthorization = true // break // case let .confirmEmail(token, userId): // path = "users/\(userId)/confirm-email" // requestMethod = .post // parameters = ["token": token] // parameterEncoding = JSONEncoding() // requiresAuthorization = false // break } // return BaseEndpointInfo(path: path, requestMethod: requestMethod, parameters: parameters, parameterEncoding: parameterEncoding, requiresAuthorization: requiresAuthorization) return 1 } } /** A struct encapsulating what information is needed when registering a user. */ struct SignUpInfo { // MARK: - Public Instance Attributes let email: String let password: String let referralCodeOfReferrer: String? // MARK: - Getters & Setters var parameters: Alamofire.Parameters { var params: Parameters = [ "email": email, "password": password ] if let referralCode = referralCodeOfReferrer { params["referral_code"] = referralCode } return params } // MARK: - Initializers /** Initializes an instance of `SignUpInfo`. - Parameters: - email: A `String` representing the email of the user. - password: A `String` representing the password that the user would enter when logging in. - referralCodeOfReferrer: A `String` representing the referral code of another user that referred the current user to the application. `nil` can be passed if referral code isn't being used. */ init(email: String, password: String, referralCodeOfReferrer: String?) { self.email = email self.password = password self.referralCodeOfReferrer = referralCodeOfReferrer } } /** A struct encapsulating what information is needed when logging in a user via Facebook login. */ struct FacebookUserInfo { // MARK: - Public Instance Attributes let email: String let facebookAccessToken: String let firstName: String let lastName: String let avatarURL: String? // MARK: - Getters & Setters var parameters: Alamofire.Parameters { var params: Parameters = [ "email": email, "facebookAccessToken": facebookAccessToken, "firstName": firstName, "lastName": lastName ] if let avatarURLForUser = avatarURL { params["source"] = avatarURLForUser } return params } // MARK: - Initializers /** Initializes an instance of `LoginFBUserInfo`. - Parameters: - email: A `String` representing the email of the user, which represents their FB username/email. - password: A `String` representing the authToken received from a successfull FB login. - firstName: A `String` representing the first name of ther user from their FB public profile. - lastName: A `String` representing the last name of the user from their FB public profile. - avatarURL: A `String` representing the url of the user's avatar from their FB public profile. */ init(email: String, facebookAccessToken: String, firstName: String, lastName: String, avatarURL: String?) { self.email = email self.facebookAccessToken = facebookAccessToken self.firstName = firstName self.lastName = lastName self.avatarURL = avatarURL } } /** A struct encapsulating what information is needed when updating a user. */ struct UpdateInfo { // MARK: - Public Instance Attributes let referralCodeOfReferrer: String? let avatarBaseString: String? let firstName: String let lastName: String // MARK: - Getters & Setters var parameters: Alamofire.Parameters { var params: Parameters = [ "first_name": firstName, "last_name": lastName ] if let baseString = avatarBaseString { params["avatar"] = baseString } if let referralCode = referralCodeOfReferrer { params["referral_code"] = referralCode } return params } // MARK: - Initializers /** Initializes an instance of `UpdateInfo`. - Parameters: - referralCodeOfReferrer: A `String` representing the referral code of another user that referred the current user to the application. This is used when the user signs up through social authentication. In regular email signup, `nil` would be passed. - avatarBaseString: A `String` representing the base sixty four representation of an image. `nil` can be passed if no imaged was selected or changed. - firstName: A `String` representing the first name of the user. - lastName: A `String` representing the last name of the user. */ init(referralCodeOfReferrer: String?, avatarBaseString: String?, firstName: String, lastName: String) { self.referralCodeOfReferrer = referralCodeOfReferrer self.avatarBaseString = avatarBaseString self.firstName = firstName self.lastName = lastName } } /** A struct encapsulating what information is needed when doing OAuth2 Authentication. */ struct OAuth2Info { // MARK: - Public Instance Methods let provider: String let oauthCode: String let redirectUri: String let email: String? let referralCodeOfReferrer: String? // MARK: - Getters & Setters var parameters: Alamofire.Parameters { var params: Parameters = [ "provider": provider, "code": oauthCode, "redirect_uri": redirectUri ] if let userEmail = email { params["email"] = userEmail } if let referralCode = referralCodeOfReferrer { params["referral_code"] = referralCode } return params } // MARK: - Initializers /** Initializes an instance of `OAuth2Info`. - Parameters: - provider: An `OAuth2Provider` representing the type of OAuth provider used. - oauthCode: A `String` representing the OAuth authorization code that is received from an OAuth2 provider. - redirectUri: A `String` representing the redirect used for the provider. - email: A `String` representing the email of the user used for logining in to the provider. This value would be filled if an error occured due to an email not being used for login. `nil` can be passed as a parameter. - referralCodeOfReferrer: A `String` representing the referral code of another user that the referred the current user to the application. In some situations, if the referral code can't be supplied due to the `oauthCode` expiring, the `UpdateInfo` can be used to pass the referral code. This only avaliable for twenty four hours after the user logged in. `nil` can be passed as a parameter. */ init(provider: OAuth2Provider, oauthCode: String, redirectUri: String, email: String?, referralCodeOfReferrer: String?) { self.provider = provider.rawValue self.oauthCode = oauthCode self.redirectUri = redirectUri self.email = email self.referralCodeOfReferrer = referralCodeOfReferrer } } /** A struct encapsulating what information is needed for completing step one of OAuth1 Authentication. - SeeAlso: https://developers.baseapp.tsl.io/users/social-auth/ */ struct OAuth1Step1Info { // MARK: - Public Instance Attributes let provider: String let redirectUri: String // MARK: - Getters & Setters var parameters: Alamofire.Parameters { let params: Parameters = [ "provider": provider, "redirect_uri": redirectUri ] return params } // MARK: - Initializers /** Initiailizes an instance of `OAuth1Step1Info`. - Parameters: - provider: A `OAuth1Provider` representing the type of OAuth provider used. - redirectUri: A `String` representing the redirect used for the provider. */ init(provider: OAuth1Provider, redirectUri: String) { self.provider = provider.rawValue self.redirectUri = redirectUri } } /** A struct encapsulating what information is needed for completing step two of OAuth1 Authentication. - SeeAlso: https://developers.baseapp.tsl.io/users/social-auth/ */ struct OAuth1Step2Info { // MARK: - Public Instance Attributes let provider: String let oauthToken: String let oauthTokenSecret: String let oauthVerifier: String let email: String? let referralCodeOfReferrer: String? // MARK: - Getters & Setters var parameters: Alamofire.Parameters { var params = [ "provider": provider, "oauth_token": oauthToken, "oauth_token_secret": oauthTokenSecret, "oauth_verifier": oauthVerifier ] if let userEmail = email { params["email"] = userEmail } if let referralCode = referralCodeOfReferrer { params["referral_code"] = referralCode } return params } // MARK: - Initializers /** Initializes an instance of `OAuth1Step2Info`. - Parameters: - provider: A `OAuth1Provider` representing the type of OAuth provider used. - oauthToken: A `String` representing the OAuth token recieved from the provider. - oauthTokenSecret: A `String` representing the secret used for the provider. - oauthVerifier: A `String` representing the verifier recieved from the provider. - email: A `String` representing the email of the user used for logining in to the provider. This value would be filled if an error occured due to an email not being used for login. `nil` can be passed as a parameter. - referralCodeOfReferrer: A `String` representing the referral code of another user that the referred the current user to the application. In some situations, if the referral code can't be supplied due to the `oauthToken` expiring, the `UpdateInfo` can be used to pass the referral code. This only avaliable for twenty four hours after the user logged in. `nil` can be passed as a parameter. */ init(provider: OAuth1Provider, oauthToken: String, oauthTokenSecret: String, oauthVerifier: String, email: String?, referralCodeOfReferrer: String?) { self.provider = provider.rawValue self.oauthToken = oauthToken self.oauthTokenSecret = oauthTokenSecret self.oauthVerifier = oauthVerifier self.email = email self.referralCodeOfReferrer = referralCodeOfReferrer } } /** An enum that specifies the type of OAuth2 provider. */ enum OAuth2Provider: String { case facebook = "facebook" case linkedIn = "linkedin-oauth2" } /** An enum that specifies the type of OAuth1 provider. */ enum OAuth1Provider: String { case twitter = "twitter" }
<!DOCTYPE html> <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> <link id="import1" rel="import" href="resources/attribute-upgrade.html"> <script> 'use strict'; let reactions = []; customElements.define('a-a', class extends HTMLElement { static get observedAttributes() { return ['attr']; } attributeChangedCallback() { reactions.push(this); } }); </script> <link id="import2" rel="import" href="resources/attribute-parsercreate.html"> <script> 'use strict'; test(() => { let importDoc1 = import1.import; let importDoc2 = import2.import; let a = importDoc1.querySelector('#a'); let b = importDoc1.querySelector('#b'); let c = importDoc2.querySelector('#c'); let d = importDoc2.querySelector('#d'); assert_array_equals(reactions, [b, d], 'attributeChangedCallback should be called for both upgrade and create.'); reactions = []; a.setAttribute('attr', 'a'); b.setAttribute('attr', 'b'); c.setAttribute('attr', 'c'); d.setAttribute('attr', 'd'); assert_array_equals(reactions, [a, b, c, d], 'attributeChangedCallback should be called for setAttribute().'); reactions = []; d.removeAttribute('attr', 'd'); c.removeAttribute('attr', 'c'); b.removeAttribute('attr', 'b'); a.removeAttribute('attr', 'a'); assert_array_equals(reactions, [d, c, b, a], 'attributeChangedCallback should be called for removeAttribute().'); }, 'attributeChangedCallback should be invoked for elements in import'); </script>
<?php namespace App\Http\Controllers\Backend\Setup; use App\Http\Controllers\Controller; use App\Models\StudentYear; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class StudentYearController extends Controller { /** * Display a listing of the resource. */ public function index() { $data=StudentYear::all(); return view('Backend.Setup.Year.year_view',compact('data')); } /** * Show the form for creating a new resource. */ public function create() { return view('Backend.Setup.Year.year_add'); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|unique:student_years,name', ]); if ($validator->fails()) { return redirect() ->back() ->withErrors($validator); } StudentYear::create([ 'name' => $request->name, ]); $notification = array( 'message'=> 'Year Inserted Successfully', 'alert-type' => 'success' ); return redirect()->route('year.index')->with($notification); } /** * Display the specified resource. */ public function show(string $id) { // } /** * Show the form for editing the specified resource. */ public function edit(string $id) { $data = StudentYear::find($id); return view('Backend.Setup.Year.year_edit',compact('data')); } /** * Update the specified resource in storage. */ public function update(Request $request, string $id) { $validator = Validator::make($request->all(), [ 'name' => 'required|unique:student_groups,name', ]); if ($validator->fails()) { return redirect() ->back() ->withErrors($validator); } StudentYear::findorFail($id)->update([ 'name' => $request->name, ]); $notification = array( 'message'=> 'Year Updated Successfully', 'alert-type' => 'info' ); return redirect()->route('year.index')->with($notification); } /** * Remove the specified resource from storage. */ public function destroy(string $id) { StudentYear::findorFail($id)->delete(); $notification = array( 'message'=> 'Year Deleted Successfully', 'alert-type' => 'info' ); return back()->with($notification); } }
Java Persistence API Mapping & Configuring Relationships Question: Which of the following statements are true about the @JoinTable annotation? [ ] This sets up a foreign key reference from the entity on the one side of the relationship to the many side of the relationship [x] The inverseJoinColumns property specifies the foreign key relationship of the owned entity [ ] This avoids using an additional table to hold the mapping [x] The joinColumns property specifies the foreign key relationship of the owning entity Question: Which of the following is true in a one-to-many and many-to-one bidirectional mapping relationship? [x] The entity on the many side can be the owning side [x] The entity on the one side can be the owning side [ ] This cannot be expressed using an additional mapping table [ ] There is no owning side of the relationship Question: In one to many unidirectional mapping, how do you specify the owning side of the relationship? [ ] The owning side and inverse side are both picked at random when the entities are persisted [x] The entity which holds a reference to the other entity and has the @OneToMany annotation is the owning side [ ] There is no clear owning side and inverse side [ ] The entity which is held as a reference and does not have the @OneToMany annotation is the owning side Question: What is the annotation that you need to specify to have two entities in a one-to-one relationship share a primary key? [ ] @OneToOne [ ] @GeneratedValue [ ] @SharedKey [x] @MapsId Question: What is the default mechanism for representing one-to-many unidirectional relationships in JPA? [ ] A foreign key reference from the entity on the one side to the entity on the many side of the relationship [ ] A foreign key reference from the entity on the many side to the entity on the one side of the relationship [x] A mapping table which holds the primary keys of both entities in the relationship [ ] A shared primary key between the entities on the one and many side of the relationship Question: Many Variants exist for a single Product list on an e-commerce site. I use a @ManyToOne annotation in the following manner: @Entity public class Variant { … @ManyToOne private Product product; } How will this relationship be modelled by default in the underlying tables? [ ] A separate mapping table will be set up to hold the variant-product mapping [ ] Every record in the Product table will hold a foreign key reference to the Variants’ primary key [x] Every record in the Variant table will hold a foreign key reference to the Product’s primary key [ ] Product and Variant will share the same primary key Question: Every vote in a voting application must be associated with exactly one phone number. What kind of mapping would you specify between a Vote entity and Phone entity in JPA? [ ] OneToMany [ ] ManyToMany [x] OneToOne [ ] ManyToOne Question: Which of the following representations are possible in order to model a one-to-many mapping relationship? [ ] By having entities linked by name [x] Using a separate mapping table to model entity associations [ ] By having the entities share a primary key [ ] By having entities live in the same table [x] Using a foreign key reference to associated entities Question: What annotation would you use on the entities on the many side of a one-to-many relationship so that the entities are persisted in a certain order in the underlying database? [ ] @OrderBy [ ] @RetrieveOrder [x] @OrderColumn [ ] @ReadOrder Question: Which of the following use cases will need a many-to-many relationship to model? [x] Customers and Bank Accounts [ ] People and Drivers Licenses [ ] People and Social Security Numbers [x] Customers and Products Question: By default, how does the @OneToOne mapping annotation express the relationship between two entities in the underlying tables? [x] Entries in one table are set up to have a foreign key reference to entries in the other table [ ] Entries in one table are set up to have a primary key reference to entries in the other table [ ] The position of the rows in each table express the relationship [ ] A separate mapping table is set up to hold the mapping Question: What annotation would you use if you want to retrieve a list of entities on the many side of a relationship such that the entities are ordered by some attribute? [ ] @OrderColumn [ ] @RetrieveOrder [x] @OrderBy [ ] @ReadOrder Question: I want to express a many-to-one relationship using multiple join columns to join the two tables in the underlying database. Which of the following annotations will I use? [x] @JoinColumn [x] @JoinColumns [ ] MapsId [ ] @JoinTable Question: What does it mean to eagerly load entities on the many side of a one-to-many relationship? [ ] The entities on the many side of the relationship will be loaded as soon as the application is run [ ] The entities on the many side of the relationship will be loaded when they are referenced [ ] The entities on the many side of the relationship will not be loaded at all [x] The entities on the many side of the relationship will be loaded when the entity on the one side is loaded Question: What does it mean to lazily load entities on the many side of a one-to-many relationship? [ ] The entities on the many side of the relationship will not be loaded at all [x] The entities on the many side of the relationship will be loaded when they are referenced [ ] The entities on the many side of the relationship will be loaded when the entity on the one side is loaded [ ] The entities on the many side of the relationship will be loaded as soon as the application is run Question: Which of the following representations are possible in order to model a one-to-one mapping relationship? [x] Using a foreign key reference to associated entities [ ] By having entities live in the same table [x] By having the entities share a primary key [x] Using a separate mapping table to model entity associations [ ] By having entities linked by name Question: In a voting application a single phone number can cast a single vote. When would you need a bidirectional relationship between the Vote entity and the Phone entity? [ ] In order to get access to all phone numbers associated with a vote [x] In order to be able to reference the vote cast from a phone number and the phone number associated with each vote [ ] In order to get access to all votes cast by a phone number [ ] All one-to-one relationships in JPA are necessarily bidirectional Question: Which of the following is true about retrieving entities in a one-to-many bidirectional relationship? [ ] Entities on the many side are eagerly loaded by default [x] Can reference one entity from another i.e. many side to one side and one side to many side [ ] Retrieving entities always includes a join operation on the underlying tables [x] Entities on the many side are lazily loaded by default Question: Which annotations will you use to specify a one-to-many bidirectional relationship? [x] @OneToMany [ ] @OneToOne [ ] @ManyToMany [x] @ManyToOne
<script> import { reactive, computed, watch, watchEffect } from "vue" export default { setup() { // 创建一个响应式对象 reactive() 内部采用是new Proxy(target) const state = reactive({ sup: 5, opp: 5, per: 0 }) // const { sup, opp } = state; // 如果用老的写法,所有的变量都需要返回,才能在模板中使用。 最终放到了组件的实例上 // 计算属性只有使用才执行,而且多次取值如果依赖的值没有变化,不会重新的执行 const total = computed({ // 写对象的格式我们可以修改计算属性的值,修改后在set方法可以操作其他属性 get: () => { return state.sup + state.opp // 10 进行包装(装包) 底层采用的事getter和setter的方式来实现的 }, set: (newVal) => {} }) const change = (type) => { if (type === "sup") { state.sup++ } else { state.opp++ } } // 什么时候用watch 什么时候用computed? // watch 监控某个值的变化,更新其他值, 发送一些请求 // 计算属性 根据已经有的属性 衍生一个新的属性, 衍生的结果可以用在模板上 (同步返回的) // const per = computed(() => { // return ((state.sup / total.value) * 100).toFixed(2) + "%" // }) // vue2中不能直接监控一个响应式数据, watch可以watch一个 计算属性或者 reactive也可以 // watch(total, (newVal,oldVal) => { // state.per = ((state.sup / newVal) * 100).toFixed(2) + "%" // },{immediate:true}) // 这种写法浪费性能 不建议使用 // watch(state, (newVal,oldVal) => { // console.log('watch') // state.per = ((state.sup / newVal) * 100).toFixed(2) + "%" // },{immediate:true,deep:true}) // 监控力度比较小 // watch([() => state.sup, () => state.opp], function () { // state.per = ((state.sup / total.value) * 100).toFixed(2) + "%" // }) // 此方法默认会执行一次,如果函数中依赖的变量,发生变化则会重新再执行一次 watchEffect(() => { state.per = ((state.sup / total.value) * 100).toFixed(2) + "%" }) // 能用计算属性解决的我们一般不用watch // watch监控一个响应式的数据 computed, reactive watch一个函数返回一个值 watch一个数组 // watchEffect 被动追踪依赖,如果值发生变化会重新执行 // 分页 onMounted 掉一个接口获取数据 // 5页 -》 调用一个接口来获取数 return { state, total, change } }, mounted() { console.log(this) } } </script> <template> <div class="box"> <header> <div class="title">标题</div> <div class="title">{{ total }}</div> </header> <div class="main"> <div> <van-button @click="change('sup')">支持</van-button> <span>人数 {{ state.sup }}</span> </div> <div> <van-button @click="change('opp')">反对</van-button> <span>人数 {{ state.opp }}</span> </div> </div> <footer> <span>支持率 {{ state.per }}</span> </footer> </div> </template> <style scoped> .box { width: 300px; margin: 100px auto 0; border: 1px solid #ccc; } header { display: flex; background: rgb(9, 189, 195); justify-content: space-between; padding: 5px; font-size: 25px; } .main { display: flex; flex-direction: column; padding: 5px; } .main .van-button { margin-right: 10px; } footer { font-size: 16px; } </style>
<div class="class-wrapper"> <form class="form-wrapper" (ngSubmit)="onSubmit()"> <mat-form-field class="nice-field" appearance="fill"> <mat-label>Nick</mat-label> <input type="text" #message matInput [formControl]="nickFormControl" [errorStateMatcher]="matcher" placeholder="Ex. Arnold87"> <mat-hint align="start"><strong>Nick jest wymagany.</strong> </mat-hint> <mat-error *ngIf="nickFormControl.hasError('required')"> Nick is <strong>required</strong> </mat-error> </mat-form-field> <mat-form-field class="nice-field" appearance="fill"> <mat-label>Nazwa</mat-label> <input type="text" #message matInput [formControl]="nameFormControl" [errorStateMatcher]="matcher" placeholder="Ex. pyszny deser Tiramisu"> <mat-hint align="start"><strong>Nazwa jest wymagana.</strong> </mat-hint> <mat-error *ngIf="nameFormControl.hasError('required')"> Review name is <strong>required</strong> </mat-error> </mat-form-field> <mat-form-field class="nice-field" appearance="fill"> <mat-label>Twoja recenzja</mat-label> <input type="text" #message matInput [formControl]="reviewBodyFormControl" [errorStateMatcher]="matcher" placeholder="Ex. Pyszny deser Tiramisu. Dość słodki, ale to dobrze..."> <mat-hint align="start"><strong>Minimalnie 50, maksymalnie 500 znaków.</strong> </mat-hint> <mat-hint align="end">{{message.value.length}} / 500</mat-hint> <mat-error *ngIf="reviewBodyFormControl.hasError('minlength') && !reviewBodyFormControl.hasError('required')"> Please enter minimally 50 characters. </mat-error> <mat-error *ngIf="reviewBodyFormControl.hasError('maxlength') && !reviewBodyFormControl.hasError('required')"> Please enter maximally 500 characters. </mat-error> <mat-error *ngIf="reviewBodyFormControl.hasError('required')"> Review body text is <strong>required</strong> </mat-error> </mat-form-field> <mat-form-field appearance="fill"> <mat-label>Wybierz datę dokonania zakupu</mat-label> <input matInput [matDatepicker]="picker" [formControl]="dateFormControl"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> <button type="submit" [disabled]="!reviewForm.valid" class="submit-button">Submit</button> <div class="form-status "> <p>Status wypełnienia formularza: {{ reviewForm.status }}</p> Niepoprawnie wypełnione pola: <span *ngFor="let i of invalidFormControls()">{{i}}, </span> </div> </form> </div>
import Button from '@/components/Button/Button'; import Navbar from '@/components/Navbar'; import Name from '@/components/UserProfile/Name'; import ProfilePic from '@/components/UserProfile/ProfilePic'; import Statistics from '@/components/UserProfile/Statistics'; import Match from '@/components/UserProfile/Match'; import { useCookies } from 'react-cookie'; import type { UserInfos, MatchInfos } from 'global'; import styles from '@/styles/userProfile/userProfile.module.scss'; import { SocketContext } from '@/utils/contexts/SocketContext'; import jwtDecode from 'jwt-decode'; import Head from 'next/head'; import { useRouter } from 'next/router'; import { useContext, useEffect, useState } from 'react'; import { AiOutlineUserAdd } from 'react-icons/ai'; import { BiBlock, BiCheck, BiEdit, BiMessageAltDetail } from 'react-icons/bi'; type jwtType = { userId: number; email: string; username: string; displayName: string; iat: number; exp: number; } export default function Profile() { const router = useRouter(); const [userInfo, setUserInfo] = useState<UserInfos | undefined>(undefined); const [cookies] = useCookies(); const [matches, setMatches] = useState<Array<MatchInfos>>([]); const [buttonText, setButtonText] = useState<string>(''); const [status, setStatus] = useState<string>(''); const [isBlocked, setIsBlocked] = useState(false); const username = router.query.username as string; const socketContext = useContext(SocketContext); const socket = socketContext?.socket; function updateButtonState(response: string) { if (response === 'ACCEPTED') setButtonText('Friend'); else if (response === 'PENDING') setButtonText('Pending request ...'); else if (response === 'BLOCKED') setButtonText('Blocked'); else if (response === 'RECEIVED') setButtonText('Accept request'); else if (response === 'EDIT') setButtonText('Edit profile'); else setButtonText('Add friend'); setStatus(response); } function toggleBlockStatus() { setIsBlocked(!isBlocked); updateButtonState(status); } useEffect(() => { if (!router.isReady) return; const user_matches = async () => { try { const statusResponse = await fetch( `http://${process.env.NEXT_PUBLIC_IP_ADDRESS}:4000/users/${router.query.username}/matches`, { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + cookies['jwt'], }, } ) .then((response) => { if (!response.ok) { if (response.status === 404) { router.push('/404'); return null; } throw new Error('Failed to fetch match info'); } else return response.json(); }) .then((response: MatchInfos[]) => { setMatches(response); }); } catch (error) { console.error(error); } }; user_matches(); }, [router]); // This useEffect is used to update the button text when the user changes as blocked or unblocked useEffect(() => { if (!router.isReady) return; const jwtPayload: jwtType = jwtDecode<jwtType>(cookies['jwt']); const updateBlockStatus = async () => { try { const statusResponse = await fetch( `http://${process.env.NEXT_PUBLIC_IP_ADDRESS}:4000/friendship/getRelationship?requesterName=${encodeURIComponent( jwtPayload.username )}&addresseeName=${router.query.username}`, { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + cookies['jwt'], }, } ); const status = await statusResponse.text(); if (status === 'BLOCKED') setIsBlocked(true); else setIsBlocked(false); } catch (error) { console.error(error); } }; updateBlockStatus(); }, [router.query.username]); function redirectToEdit() { router.push('/user/edit'); } const startDm = () => { const jwtPayload: jwtType = jwtDecode<jwtType>(cookies['jwt']); router.push({ pathname: '/chat', query: { addresseeName: `${router.query.username}`, requesterName: encodeURIComponent(jwtPayload.username), } }); }; async function relationshipUpdate() { let route = 'add'; if (status === 'ACCEPTED') route = 'remove'; else if (status === 'PENDING') route = 'decline'; else if (status === 'BLOCKED') { route = 'unblock'; toggleBlockStatus(); } const jwtPayload: jwtType = jwtDecode<jwtType>(cookies['jwt']); const response = await fetch( `http://${process.env.NEXT_PUBLIC_IP_ADDRESS}:4000/friendship/${route}?requesterName=${encodeURIComponent( jwtPayload.username )}&addresseeName=${router.query.username}`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + cookies['jwt'], }, }); let responseText = await response.text(); if (encodeURIComponent(jwtPayload.username) === router.query.username) responseText = 'EDIT'; setStatus(responseText); } // Verify if the user exists and setUserInfo. Fetch the relationship status between the user and the profile owner and set the button text useEffect(() => { if (!router.isReady) return; const jwtPayload: jwtType = jwtDecode<jwtType>(cookies['jwt']); const fetchUserInfo = async () => { try { await fetch( `http://${process.env.NEXT_PUBLIC_IP_ADDRESS}:4000/users/${router.query.username}`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + cookies['jwt'], }, }) .then((response) => { if (!response.ok) { if (response.status === 404) { router.push('/404'); return null; } throw new Error('Failed to fetch user info'); } else return response.json(); }) .then((response: UserInfos) => { setUserInfo(response); }); const statusResponse = await fetch(`http://${process.env.NEXT_PUBLIC_IP_ADDRESS}:4000/friendship/getRelationship?requesterName=${encodeURIComponent( jwtPayload.username )}&addresseeName=${router.query.username}`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + cookies['jwt'], }, }); let status = await statusResponse.text(); let buttonText = 'Add friend'; if (status === 'ACCEPTED') buttonText = 'Friend'; else if (status === 'PENDING') buttonText = 'Pending request ...'; else if (status === 'BLOCKED') buttonText = 'Blocked'; else if (status === 'RECEIVED') buttonText = 'Accept request'; else if (encodeURIComponent(jwtPayload.username) === router.query.username) { status = 'EDIT'; buttonText = 'Edit profile'; } setStatus(status); } catch (error) { console.error(error); } }; updateButtonState(status); fetchUserInfo(); }, [router.isReady, router.query.username, router, cookies, status]); return ( <> <Head> <title>Profile - {userInfo?.displayName}</title> </Head> <Navbar /> <main className={styles.main}> { userInfo ? ( <> <div className={styles.header}> <div className={styles.user_id_container}> <ProfilePic path={userInfo.profilePicPath} size={90} stroke currentUser={username} /> <Name Username={userInfo.displayName} FirstName={userInfo.firstName} LastName={userInfo.lastName} initialIsBlocked={isBlocked} toggleBlockStatus={toggleBlockStatus} updateButtonState={updateButtonState} /> </div> <div className={styles.header_buttons_container}> <Button text='Message' theme='light' boxShadow icon={<BiMessageAltDetail />} onClick={startDm} /> <Button text={buttonText} boxShadow={buttonText === 'Add friend' || buttonText === 'Edit profile' ? true : false} onClick={buttonText === 'Edit profile' ? redirectToEdit : relationshipUpdate} theme={buttonText === 'Add friend' || buttonText === 'Edit profile' ? 'light' : 'dark'} icon={buttonText === ('Add friend') ? <AiOutlineUserAdd /> : buttonText === 'Edit profile' ? <BiEdit /> : buttonText === 'Blocked' ? <BiBlock /> : buttonText === 'Friend' ? <BiCheck /> : null} /> </div> </div> <div className={styles.content_container}> <section className={styles.content_section}> <h2 className={styles.title2}>Statistics</h2> <Statistics level={userInfo.level} wins={userInfo.wins} losses={userInfo.losses} winRate={userInfo.wins && userInfo.losses ? userInfo.wins / userInfo.losses: 'N/A'} /> </section> <section className={styles.content_section}> <h2 className={styles.title2}>Match history</h2> { matches.map((match, i) => ( <Match key={i} player1Name = {match.userIdLeft} player2Name = {match.userIdRight} player1Score = {match.scorePlayerOne} player2Score = {match.scorePlayerTwo} matchDuration = {match.duration} winnerId= {match.winnerId} /> )) } </section> </div> </> ) : ( <p>Loading...</p> ) } </main> </> ); }
package datapark.SimHashSample3; import datapark.test.FNVHash; import datapark.utils.HashUtils; import datapark.utils.RedisUtils; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import redis.clients.jedis.Jedis; import java.math.BigInteger; import java.util.*; /** * Created by dpliyuan on 2016/2/29. */ public class SimHashJudge implements DuplicateJudge { private static Logger log = Logger.getLogger(SimHashJudge.class); private static RedisUtils redisUtils = new RedisUtils(); private int HASH_LENGTH = 64; /** * In this method, use int(32 bits) to store hashcode. * use 1 as all words weight for simple reason. * use Hamming distance as hashcode distance. * * @author dpliyuan */ public String duplicate(JSONObject requestDataObj) { //get words from request String words = (String) requestDataObj.get("words"); //todo:weight calculate String weightStr = (String) requestDataObj.get("weight"); String url = requestDataObj.get("url").toString(); if (words == null) { log.info("no keywords"); return null; } List weightList = getWeightList(weightStr); //get simhash of words String simhash = getHashCode(words, weightList); JSONObject responseObj = getResponseObj(simhash, url); return responseObj.toString(); } /** * @param simhash * @return */ private synchronized JSONObject getResponseObj(String simhash, String url) { JSONObject responseObj = new JSONObject(); /*//todo:cut simhash into 4 segment if (redisUtils == null) { redisUtils = new RedisUtils(); } Jedis jedis = redisUtils.getJedisFromPool(); Map map = jedis.hgetAll("simhash"); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String finger = (String) entry.getValue(); int hammingDistance = getDistance(finger, simhash); if (hammingDistance <= 3) { responseObj.put("url", entry.getKey()); responseObj.put("finger", finger); responseObj.put("status", "EXIST"); log.info("find similar target : "+entry.getKey() +" current : "+url +"simhash code is : "+simhash); break; } } //todo:if there is no finger which hammingDistance less then 3 in redis,then we put the request finger into redis if (responseObj.length() == 0) { jedis.hset("simhash", url, simhash); responseObj.put("url", url); responseObj.put("finger", simhash); responseObj.put("status", "INSERT"); log.info("insert current : " + url + "simhash code is : " + simhash); } redisUtils.returnJedisToPool(jedis);*/ // simhash cut into 4 segment String[] hashs=new String[4]; // String hash_1 = simhash.substring(0, 16); // String hash_2 = simhash.substring(16, 32); // String hash_3 = simhash.substring(32, 48); // String hash_4 = simhash.substring(48, 64); hashs[0]=simhash.substring(0, 16); hashs[1] = simhash.substring(16, 32); hashs[2] = simhash.substring(32, 48); hashs[3] = simhash.substring(48, 64); if (redisUtils == null) { redisUtils = new RedisUtils(); } Jedis jedis = redisUtils.getJedisFromPool(); // 选择redis的db jedis.select(1); boolean isFindSimliari = false; long ins1 = System.currentTimeMillis(); for (int i= 0; i<hashs.length ;i++){ Map<String, String> hashSets = jedis.hgetAll(hashs[i]); long start = System.currentTimeMillis(); for (Map.Entry<String,String> hashValue :hashSets.entrySet()){ String finger = hashValue.getKey(); int hammingDistance = getDistance(finger, simhash); if (hammingDistance <=3){ long end = System.currentTimeMillis(); responseObj.put("url", hashValue.getValue()); responseObj.put("finger", finger); responseObj.put("status", "EXIST"); log.info("find similar url : "+hashValue.getValue() +" current : "+url +" simhash code is : "+ simhash +" hammingDistance is : " +hammingDistance +"compareTime need : " + (end -start)); isFindSimliari =true; break; } } if (isFindSimliari){ break; } } if (!isFindSimliari) { long ins2 = System.currentTimeMillis(); log.info("insert current : " + url + "simhash code is : " + simhash + " all time is : " + (ins2 - ins1)); responseObj.put("url", url); responseObj.put("finger", simhash); responseObj.put("status", "INSERT"); } for (int j = 0; j < hashs.length ; j++) { jedis.hset(hashs[j],simhash, url); } redisUtils.returnJedisToPool(jedis); return responseObj; } /** * contert "0" and "1" string to int * * @param str01 * @return */ private BigInteger string01ToInt(String str01) { BigInteger num; num = new BigInteger(str01); return num; } /** * maybe in the future,we neet to cut simhash into four parts * * @param simhash * @return */ private List cutSimHash(int simhash) { List simhashSegmentsList = new ArrayList(); String simhashStr = Integer.toBinaryString(simhash); String patch = ""; if (simhashStr.length() < 32) { for (int i = 0; i < 32 - simhashStr.length(); i++) { patch = patch + "0"; } } simhashStr = patch + simhashStr; int gap = simhashStr.length() / 4; for (int i = 0; i < simhashStr.length(); i += gap) { simhashSegmentsList.add(simhashStr.substring(i, i + gap)); } return simhashSegmentsList; } // public int compareString(String str1, String str2) { // System.out.println("SimHash compare string of: \"" + str1 + "\" AND \"" + str2 + "\""); // int hash1 = getHashCode(str1,null); // int hash2 = getHashCode(str2,null); // // int distance = getDistance(hash1, hash2); // System.out.println("SimHash string distance of: \"" + str1 + "\" AND \"" + str2 + "\" is:" + distance); // return distance; // } /** * Use hamming distance in this method. * Can change to other distance like Euclid distance or p-distance, etc. * * @return */ public static int getDistance(String finger, String simhash) { int distance = 0; // System.out.println("finger :" + finger + "\nsimhash:" + simhash); for (int i = 0; i < finger.length(); i++) { if (finger.charAt(i) != simhash.charAt(i)) { distance++; } } // System.out.println("distance:" + distance); return distance; } private List getWeightList(String weightStr) { List weightList = new ArrayList(); String[] weightArray = weightStr.split(","); for (int i = 0; i < weightArray.length; i++) { double weight = Double.valueOf(weightArray[i]); weightList.add(weight); } return weightList; } /** * get simhashValue according to words * * @param words * @return */ private String getHashCode(String words, List weightList) { // TODO Auto-generated method stub StringBuffer simhash = new StringBuffer(); try { String[] wordsArray = words.split(","); double[] hashBits = new double[HASH_LENGTH]; for (int i = 0; i < wordsArray.length; i++) { // BigInteger hash = HashUtils.hashZHOU(wordsArray[i]); BigInteger hash = HashUtils.fnv1aHash64(wordsArray[i]); // long val = HashUtils.BKDRHash(wordsArray[i]); // BigInteger hash = fromLong2BigInt(val); // System.out.println("MINE:"+hash); for (int j = 0; j < HASH_LENGTH ; j++) { BigInteger bit = BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - j - 1); //Different keyword may have different weight. add or minus their weight here. //For simple reason, all weight are assigned as 1 in this method. if (hash.and(bit).signum() != 0) { hashBits[j] += Double.valueOf(weightList.get(i).toString()); } else { hashBits[j] -= Double.valueOf(weightList.get(i).toString()); } } } for (int i = 0; i < HASH_LENGTH; i++) { String bit = hashBits[i] > 0 ? "1" : "0"; simhash.append(bit); } } catch (Exception e) { e.printStackTrace(); } return simhash.toString(); } private BigInteger fromLong2BigInt(long val){ BigInteger hash = null; String valStr = String.valueOf(val); if(valStr.split(".").length==2){ hash = new BigInteger(valStr.split(".")[0]); }else{ hash = new BigInteger(valStr); } return hash; } }
//2095. Delete the Middle Node of a Linked List class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; this.next = null; } } public class Day18_Q2 { public ListNode deleteMiddle(ListNode head) { if (head == null || head.next == null) return null; int count = 0; ListNode p1 = head, p2 = head; while (p1 != null) { count += 1; p1 = p1.next; } int middleIndex = count / 2; for (int i = 0; i < middleIndex - 1; ++i) p2 = p2.next; p2.next = p2.next.next; return head; } public static void main(String[] args) { // Create a linked list and test the deleteMiddle method here ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); head.next.next.next.next = new ListNode(5); Day18_Q2 solution = new Day18_Q2(); ListNode newHead = solution.deleteMiddle(head); // Print the updated linked list to verify ListNode current = newHead; while (current != null) { System.out.print(current.val + " "); current = current.next; } } }
/* PSPP - a program for statistical analysis. Copyright (C) 2009, 2011 Free Software Foundation, Inc. This program 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. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OUTPUT_ITEM_H #define OUTPUT_ITEM_H 1 /* Output items. An output item is a self-contained chunk of output. */ #include <cairo.h> #include <stdbool.h> #include "libpspp/cast.h" #include "libpspp/string-array.h" enum output_item_type { OUTPUT_ITEM_CHART, OUTPUT_ITEM_GROUP, OUTPUT_ITEM_IMAGE, OUTPUT_ITEM_MESSAGE, OUTPUT_ITEM_PAGE_BREAK, OUTPUT_ITEM_TABLE, OUTPUT_ITEM_TEXT, }; const char *output_item_type_to_string (enum output_item_type); /* A single output item. */ struct output_item { /* Reference count. An output item may be shared between multiple owners, indicated by a reference count greater than 1. When this is the case, the output item must not be modified. */ int ref_cnt; /* The localized label for the item that appears in the outline pane in the PSPPIRE output viewer and in PDF outlines. This is NULL if no label has been explicitly set. Use output_item_get_label() to read an item's label. */ char *label; /* A locale-invariant identifier for the command that produced the output, which may be NULL if unknown or if a command did not produce this output. */ char *command_name; /* For OUTPUT_ITEM_GROUP, this is true if the group's subtree should be expanded in an outline view, false otherwise. For other kinds of output items, this is true to show the item's content, false to hide it. The item's label is always shown in an outline view. */ bool show; /* Information about the SPV file this output_item was read from. May be NULL. */ struct spv_info *spv_info; enum output_item_type type; union { struct chart *chart; cairo_surface_t *image; struct { struct output_item **children; size_t n_children; size_t allocated_children; } group; struct msg *message; struct pivot_table *table; struct { enum text_item_subtype { TEXT_ITEM_PAGE_TITLE, /* TITLE and SUBTITLE commands. */ TEXT_ITEM_TITLE, /* Title. */ TEXT_ITEM_SYNTAX, /* Syntax printback logging. */ TEXT_ITEM_LOG, /* Other logging. */ } subtype; struct pivot_value *content; } text; }; char *cached_label; }; struct output_item *output_item_ref (const struct output_item *) WARN_UNUSED_RESULT; void output_item_unref (struct output_item *); bool output_item_is_shared (const struct output_item *); struct output_item *output_item_unshare (struct output_item *); void output_item_submit (struct output_item *); void output_item_submit_children (struct output_item *); const char *output_item_get_label (const struct output_item *); void output_item_set_label (struct output_item *, const char *); void output_item_set_label_nocopy (struct output_item *, char *); void output_item_set_command_name (struct output_item *, const char *); void output_item_set_command_name_nocopy (struct output_item *, char *); char *output_item_get_subtype (const struct output_item *); void output_item_add_spv_info (struct output_item *); void output_item_dump (const struct output_item *, int indentation); /* In-order traversal of a tree of output items. */ struct output_iterator_node { const struct output_item *group; size_t idx; }; struct output_iterator { const struct output_item *cur; struct output_iterator_node *nodes; size_t n, allocated; }; #define OUTPUT_ITERATOR_INIT(ITEM) { .cur = ITEM } /* Iteration functions. */ void output_iterator_init (struct output_iterator *, const struct output_item *); void output_iterator_destroy (struct output_iterator *); void output_iterator_next (struct output_iterator *); /* Iteration helper macros. */ #define OUTPUT_ITEM_FOR_EACH(ITER, ROOT) \ for (output_iterator_init (ITER, ROOT); (ITER)->cur; \ output_iterator_next (ITER)) #define OUTPUT_ITEM_FOR_EACH_SKIP_ROOT(ITER, ROOT) \ for (output_iterator_init (ITER, ROOT), output_iterator_next (ITER); \ (ITER)->cur; output_iterator_next (ITER)) /* OUTPUT_ITEM_CHART. */ struct output_item *chart_item_create (struct chart *); /* OUTPUT_ITEM_GROUP. */ struct output_item *group_item_create (const char *command_name, const char *label); struct output_item *group_item_create_nocopy (char *command_name, char *label); void group_item_add_child (struct output_item *parent, struct output_item *child); struct output_item *root_item_create (void); struct output_item *group_item_clone_empty (const struct output_item *); /* OUTPUT_ITEM_IMAGE. */ struct output_item *image_item_create (cairo_surface_t *); /* OUTPUT_ITEM_MESSAGE. */ struct output_item *message_item_create (const struct msg *); const struct msg *message_item_get_msg (const struct output_item *); struct output_item *message_item_to_text_item (struct output_item *); /* OUTPUT_ITEM_PAGE_BREAK. */ struct output_item *page_break_item_create (void); /* OUTPUT_ITEM_TABLE. */ struct output_item *table_item_create (struct pivot_table *); /* OUTPUT_ITEM_TEXT. */ struct output_item *text_item_create (enum text_item_subtype, const char *text, const char *label); struct output_item *text_item_create_nocopy (enum text_item_subtype, char *text, char *label); struct output_item *text_item_create_value (enum text_item_subtype, struct pivot_value *value, char *label); enum text_item_subtype text_item_get_subtype (const struct output_item *); char *text_item_get_plain_text (const struct output_item *); bool text_item_append (struct output_item *dst, const struct output_item *src); struct output_item *text_item_to_table_item (struct output_item *); const char *text_item_subtype_to_string (enum text_item_subtype); /* An informational node for output items that were read from an .spv file. This is mostly for debugging and troubleshooting purposes with the pspp-output program. */ struct spv_info { /* The .spv file. */ struct zip_reader *zip_reader; /* True if there was an error reading the output item (e.g. because of corruption or because PSPP doesn't understand the format.) */ bool error; /* Zip member names. All may be NULL. */ char *structure_member; char *xml_member; char *bin_member; char *png_member; }; void spv_info_destroy (struct spv_info *); struct spv_info *spv_info_clone (const struct spv_info *); size_t spv_info_get_members (const struct spv_info *, const char **members, size_t allocated_members); #endif /* output/output-item.h */
package com.atz.service; import java.lang.reflect.InvocationTargetException; import java.sql.Timestamp; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import com.atz.dao.ClienteDAO; import com.atz.dao.EmpresaDAO; import com.atz.dao.EstadoDAO; import com.atz.dao.FacturaDAO; import com.atz.dao.FacturaLineaDAO; import com.atz.fb.ContratosBuscarFb; import com.atz.fb.ContratosFb; import com.atz.fb.PartesFb; import com.atz.persistencia.TFactura; import com.atz.persistencia.TFacturaLinea; import com.atz.persistencia.TMatrimonio; @Service public class FacturaService { @Autowired private FacturaDAO fdao; @Autowired private ClienteDAO kdao; @Autowired private FacturaLineaDAO ldao; @Autowired private EmpresaDAO edao; @Autowired private EstadoDAO stdao; @Transactional(readOnly=true) public List<TFactura> leerTodos() { return this.fdao.readAll(); } @Transactional(readOnly=true) public TFactura leer(int oid) { return this.fdao.read(oid); } @Transactional(readOnly=true) public List<TFactura> leerFacturasCliente(ContratosBuscarFb fb) { return this.fdao.readFacturasCliente( fb.getOidcliente() ); } @Transactional(readOnly=true) public List<TFactura> leerFacturasFechas(Date fini, Date ffin, Integer oidempresa, Integer oidcliente, Integer oid) { return this.fdao.readFacturasFechas(fini, ffin, oidempresa, oidcliente, oid); } @Transactional(readOnly=true) public List<TFactura> leerFacturas(ContratosBuscarFb fb) { return this.fdao.readFacturas ( fb.getFini() , fb.getFfin(), fb.getOidempresa(), fb.getOidcliente(), fb.getNumero() ); } @Transactional(readOnly=true) public Map<String, Boolean> leerFacturasEstado(List<TMatrimonio> lm) { List<String> ln2 = lm.stream().map( t -> t.getNumero2() ).filter( t -> t != null ).collect( Collectors.toList() ); List<TFactura> lf = this.fdao.readFacturasNumero2(ln2); Map<String, Boolean> pagadas = new HashMap<>(); lf.forEach( t -> pagadas.put( t.getNumero2(), t.getTEstado().getOid() == 2 ) ); return pagadas; } @Transactional(readOnly=false, isolation=Isolation.DEFAULT) public synchronized TFactura crear(ContratosFb fb) throws IllegalAccessException, InvocationTargetException { TFactura tc = new TFactura(); this.copy(fb, tc); tc.setAuditoria1( new Date() ); tc.setAuditoria2( new Date() ); tc.setNumero2( this.getNumero2(tc) ); return this.fdao.create(tc); } private String getNumero2(TFactura tc) { Calendar cal = Calendar.getInstance(); DecimalFormat fmt = new DecimalFormat("0000"); StringBuffer n2 = new StringBuffer(); cal.setTime( tc.getFecha() ); n2.append( tc.getTEmpresa().getOid() ); n2.append( cal.get( Calendar.YEAR ) ); n2.append( fmt.format( tc.getNumero() ) ); return n2.toString(); } @Transactional(readOnly=false, isolation=Isolation.DEFAULT) public TFactura crearSl(PartesFb fb) throws IllegalAccessException, InvocationTargetException { int oidempresa = 8; double iva = 21D; return this.crearFactura(fb, oidempresa, iva); } @Transactional(readOnly=false, isolation=Isolation.DEFAULT) public TFactura crearCarpinteria(PartesFb fb) throws IllegalAccessException, InvocationTargetException { int oidempresa = 7; double iva = 0D; return this.crearFactura(fb, oidempresa, iva); } public TFactura crearFactura(PartesFb fb, int oidempresa, double iva) throws IllegalAccessException, InvocationTargetException { String descr = "TRABAJO REALIZADO CON PARTE " + fb.getNumero() + " BASÁNDOSE EN EL RD 513/2017."; TFactura tc = new TFactura(); TFacturaLinea tlc = new TFacturaLinea(); double t1 = this.totalParte( fb.getPrecio() ); double t2 = this.totalParte( fb.getPrecioCentral() ); double t3 = this.totalParte( fb.getPrecioDetectores() ); double t4 = this.totalParte( fb.getPrecioEquipoAuxiliar() ); double t5 = this.totalParte( fb.getPrecioFuente() ); double t6 = this.totalParte( fb.getPrecioPuertas() ); double t7 = this.totalParte( fb.getPrecioPulsadores() ); double t8 = this.totalParte( fb.getPrecioRetenedor() ); double t9 = this.totalParte( fb.getPrecioSirenas() ); tc.setTCliente( this.kdao.read( fb.getOidcliente() ) ); tc.setTCliente2( tc.getTCliente() ); tc.setFecha( new Date() ); tc.setTEmpresa( this.edao.read(oidempresa) ); tc.setNumero( this.maxNumero(oidempresa) ); tc.setIva(iva); tlc.setPrecio( t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8 + t9 ); tlc.setCantidad( 1 ); tlc.setDescripcion( descr ); tlc.setTFactura(tc); tc.getTFacturaLineas().add(tlc); tc.setAuditoria1( new Date() ); tc.setAuditoria2( new Date() ); tc.setNumero2( this.getNumero2(tc) ); tc.setTEstado( this.stdao.get(1) ); // Sin pagar return this.fdao.create(tc); } private double totalParte(Double[] arr) { return arr == null ? 0D : Arrays.stream( arr ).filter( t -> t != null ).mapToDouble( t -> t.doubleValue() ).sum(); } @Transactional(readOnly=false, isolation=Isolation.DEFAULT) public void borrar(int u) throws IllegalAccessException, InvocationTargetException { this.fdao.delete(u); } @Transactional(readOnly=false, isolation=Isolation.DEFAULT) public TFactura actualizar(ContratosFb fb) throws IllegalAccessException, InvocationTargetException { TFactura tc = this.fdao.read( fb.getOid() ); for( TFacturaLinea lc : tc.getTFacturaLineas() ) { this.ldao.delete(lc); } tc.getTFacturaLineas().clear(); this.copy(fb, tc); tc.setAuditoria2(new Date()); this.fdao.update(tc); return tc; } @Transactional(readOnly=true, isolation=Isolation.DEFAULT) public Integer maxNumero(int oidempresa) { return this.fdao.readSiguienteNumero(oidempresa); } @Transactional(readOnly=false, isolation=Isolation.DEFAULT) public void actualizarFechaEnvio(Integer oid) { TFactura f = this.fdao.read(oid); f.setEnvio(new Timestamp(new Date().getTime())); this.fdao.update(f); } private void copy(ContratosFb fb, TFactura tc) { tc.setTCliente( this.kdao.read( fb.getOidcliente() ) ); tc.setTCliente2( this.kdao.read( fb.getOidcliente2() ) ); tc.setTEstado( this.stdao.get( fb.getOidestado() ) ); tc.setFecha( fb.getFecha() ); tc.setNumero( fb.getNumero() ); tc.setIva( fb.getIva() ); tc.setTEmpresa( this.edao.read( fb.getOidempresa() ) ); tc.setCcEmail( fb.getCcemail() ); for(int i=0; i<fb.getCantidadExt().length; i++) { TFacturaLinea tlc = new TFacturaLinea(); tlc.setPrecio( fb.getPrecioExt()[i] ); tlc.setCantidad( fb.getCantidadExt()[i] ); tlc.setDescripcion( fb.getDescrExt()[i] ); tlc.setDescuento( fb.getDescuentoExt()[i] ); tlc.setTFactura(tc); tc.getTFacturaLineas().add(tlc); } } }
class ImagesController < ApplicationController before_action :set_image, only: %i[ show edit update destroy ] # GET /images def index if params[:id] @imagelines = Imageline.where(image_id: params[:id]) session[:imagefile] = params[:id] upload = Upload.find(params[:id]) @images = Image.where(upload: upload.id).page(params[:page]).per(1) else redirect_to games_path end end # GET /images/1 def show session[:image] = params[:id] @imagelines = Imageline.where(image_id: params[:id]) end # GET /images/new def new @image = Image.new end # GET /images/1/edit def edit @imagelines = Imageline.where(image_id: params[:id]) end # POST /images def create upload = Upload.find(session[:imagefile]) @image = Image.new(image_params) @image.user_id = current_user.id @image.upload_id = session[:imagefile].to_i @image.game_id = Game.find(upload.game_id).id if @image.save redirect_to images_path(id: session[:imagefile]), info: "Image was successfully created." else render :new, status: :unprocessable_entity end end # PATCH/PUT /images/1 def update if @image.update(image_params) redirect_to @image, notice: "Image was successfully updated.", status: :see_other else render :edit, status: :unprocessable_entity end end def imageline #("content LIKE ?", "%#{params[:query]}%") p session[:image] @line = Imageline.create() @line.image_id = session[:image].to_i @line.line_id = params[:line_id] @line.user_id = current_user.id @line.done = false @line.active = true respond_to do |format| if @line.save format.html { render plain: @line.id } # Sikeres művelet esetén "OK" válasz HTML formátumban else format.html { render plain: @line.errors.full_messages.join(", ") } # Hiba esetén hibaüzenet HTML formátumban end end end def imagelineremove Imageline.find(params[:line]).destroy end # DELETE /images/1 def destroy @image.destroy redirect_to images_url, notice: "Image was successfully destroyed.", status: :see_other end def search @line = Line.where("content ILIKE ?", "%#{params[:query]}%") respond_to do |format| format.json { render json: @line } end end private # Use callbacks to share common setup or constraints between actions. def set_image @image = Image.find(params[:id]) end # Only allow a list of trusted parameters through. def image_params params.require(:image).permit(:title, :desc, :active, :done, :image) end end
// import 'package:lost_found/features/components/found/domain/entities/found_item.dart'; // class FoundItemModel extends FoundItem { // FoundItemModel({ // required super.id, // required super.updatedAt, // required super.userId, // required super.title, // required super.description, // required super.foundLocation, // required super.foundItemImageUrl, // required super.itemCollectionLocation, // required super.itemCategory, // required super.claimed, // super.posterName, // }); // Map<String, dynamic> toJson() { // return <String, dynamic>{ // 'id': id, // 'updated_at': updatedAt.toIso8601String(), // 'user_id': userId, // 'title': title, // 'description': description, // 'found_location': foundLocation, // 'found_item_image_url': foundItemImageUrl, // 'found_item_collection_location': itemCollectionLocation, // 'found_item_category': itemCategory, // 'claimed': claimed, // }; // } // factory FoundItemModel.fromJson(Map<String, dynamic> map) { // return FoundItemModel( // id: map['id'] as String, // updatedAt: map['updated_at'] == null // ? DateTime.now() // : DateTime.parse(map['updated_at'] as String), // userId: map['user_id'] as String, // title: map['title'] as String, // description: map['description'] as String, // foundLocation: map['found_location'] as String, // foundItemImageUrl: map['found_item_image_url'] as String, // itemCollectionLocation: map['found_item_collection_location'] as String, // itemCategory: map['found_item_category'] as String, // claimed: map['claimed'] as bool, // ); // } // FoundItemModel copyWith({ // String? id, // DateTime? updatedAt, // String? userId, // String? title, // String? description, // String? foundLocation, // String? foundItemImageUrl, // String? itemCollectionLocation, // String? itemCategory, // bool? claimed, // String? posterName, // }) { // return FoundItemModel( // id: id ?? this.id, // updatedAt: updatedAt ?? this.updatedAt, // userId: userId ?? this.userId, // title: title ?? this.title, // description: description ?? this.description, // foundLocation: foundLocation ?? this.foundLocation, // foundItemImageUrl: foundItemImageUrl ?? this.foundItemImageUrl, // itemCollectionLocation: // itemCollectionLocation ?? this.itemCollectionLocation, // itemCategory: itemCategory ?? this.itemCategory, // claimed: claimed ?? this.claimed, // posterName: posterName ?? this.posterName, // ); // } // }
<!DOCTYPE html> <html> <head> <title> Simple web Development Template </title> <link rel="stylesheet" type="text/css" href="style.css"> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css"> </head> <body> <!-- header section --> <nav class="navbar background"> <ul class="nav-list"> <div class="logo"> <img src="images/logo.png"> </div> <li><a href="#web">Home</a></li> <li><a href="#program">About</a></li> <li><a href="#course">Daily_BSE_News</a></li> <li><a href="#course">My_Daily_Study</a></li> <li><a href="#course">My Investments</a></li> <li><a href="#course">Reports</a></li> </ul> <div class="rightNav"> <input type="text" name="search" id="search"> <button class="btn btn-sm">Search</button> </div> </nav> <!-- middle carousel section of homepage --> <!-- <section class="firstsection"> <div class="box-main"> <div class="firstHalf"> <h1 class="text-big" id="web"> Web Technology </h1> <p class="text-small"> HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages. HTML is a markup language that is used by the browser to manipulate text, images, and other content to display it in the required format. </p> </div> </div> </section> --> <section id="image-carousel" class="splide" aria-label="Beautiful Images" > <div class="splide__track"> <ul class="splide__list"> <li class="splide__slide"> <img src="images/HomepageCarousel/img1.png" alt=""> </li> <li class="splide__slide"> <img src="images/HomepageCarousel/img2.png" alt=""> </li> <li class="splide__slide"> <img src="images/HomepageCarousel/img3.png" alt=""> </li> </ul> </div> </section> <!-- footer section --> <footer class="bg-dark-1"> <section id="footer" class="py-5"> <div class="container text-center"> <a href="https://www.google.com"> <img src="images/footer/linkedin_icon.png" width="40" height="40"></a> <a href="https://www.google.com"> <img src="images/footer/instagram_icon.png" width="40" height="40"></a> <a href="https://www.google.com"> <img src="images/footer/twitter_icon.png" width="40" height="40"></a> </div> </section> </footer> <!-- splide JS cdn --> <script src="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js"></script> <script> new Splide( '#image-carousel', {heightRatio: 0.365,} ).mount(); </script> </body> </html>
import React from 'react' import { Link } from 'react-router-dom' import ProductSkeleton from '../loading/ProductSkeleton' import ProductCardDetails from '../product/ProductCardDetails' const ProductCard = ({caption,page,products,link,isFetching}) => { return ( <div className='my-4 flex flex-col gap-4'> <div className='flex items-center justify-between'> <div className='flex'> <h6 className='font-semibold cap text-2xl text-gray-900'>{caption}</h6> </div> {page !== "category" && <div> <Link to={`${link}`} className='button-green !w-[90px]'>See All</Link> </div>} </div> <div className='my-2 w-full grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 gap-4'> { isFetching ? <> <ProductSkeleton/> <ProductSkeleton/> <ProductSkeleton/> <ProductSkeleton/> </> : products?.length > 0 ? products?.map((product,i) => { let descriptionForSmallScreen = product.description.slice(0,15).concat("...") let descriptionForLargeScreen = product.description.slice(0,30).concat("...") return( <ProductCardDetails key={i} product={product} descriptionForLargeScreen={descriptionForLargeScreen} descriptionForSmallScreen={descriptionForSmallScreen}/> )}) : "NO PRODUCTS" } </div> </div> ) } export default ProductCard
import React , { useState, useEffect} from 'react'; import { useParams } from 'react-router-dom'; import parse from 'html-react-parser'; import DOMPurify from 'dompurify'; import { DotPulse } from '@uiball/loaders'; import ShareButton from '../components/Share'; import '../styles/Article.css'; const Article = ({ getArticleById }) => { const { id } = useParams(); const article = getArticleById(id); const [timeLoader, setTimeLoader] = useState(true); useEffect(() => { const artcleErr = () => { setTimeout(() => { setTimeLoader(false); }, 1600); }; artcleErr(); }, []); if (!article) { return ( timeLoader ? <div style={{ color: 'white', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', }} > <DotPulse size={75} color="white"></DotPulse> </div> : ( <div className='ErrorContainer' style={{ color: 'white', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', }} > <h2>Erro 404: Artigo não encontrado</h2> <h3>Ops, esse artigo não existe ou não foi encontrado!</h3> </div> ) ); } window.scrollTo(0, 0); return ( <div className='ExpandedArticleContainer'> <div className='ExpandedArticle'> <div className='titleExp'> <h2>{parse(DOMPurify.sanitize(article.title, { USE_PROFILES: { html: true } }))}</h2> </div> <div className='contentExp'> {parse(DOMPurify.sanitize(article.content, { USE_PROFILES: { html: true } }))} </div> </div> <div className='shareOn' style={{ height: '140px', display: 'flex', alignItems: 'center', justifyContent: 'center', }} > <div> <h4 style={{ color: 'white', display: 'inline', marginRight: '25px', }} >COMPARTILHE:</h4> <ShareButton type="facebook" url={window.location.href} /> <ShareButton type="whatsapp" url={window.location.href} /> <ShareButton type="twitter" url={window.location.href} text={article.title} /> <ShareButton type="linkedin" url={window.location.href} /> <ShareButton type="reddit" url={window.location.href} text={article.title} /> <ShareButton type="copy" url={window.location.href} /> </div> </div> </div> ); }; export default Article;
import path from 'path' import type IPFS from 'ipfs' import { rmrf, connectIpfsNodes } from '../utils' import { createIPFSInstance } from '../../src/ipfs' import { PaperOrbitDB } from '../../src/orbit-db' import type LogStore from 'src/orbit-db/logstore' const dir0 = path.join(path.dirname(__dirname), 'orbitdb-test-0') const dir1 = path.join(path.dirname(__dirname), 'orbitdb-test-1') describe('PaperOrbitDB', () => { let ipfs0: IPFS let ipfs1: IPFS let db0: PaperOrbitDB let db1: PaperOrbitDB beforeAll(async () => { await rmrf(dir0) await rmrf(dir1) ipfs0 = await createIPFSInstance({ directory: dir0 }) db0 = await PaperOrbitDB.createInstance(ipfs0, { directory: dir0 }) ipfs1 = await createIPFSInstance({ directory: dir1 }) db1 = await PaperOrbitDB.createInstance(ipfs1, { directory: dir1 }) await connectIpfsNodes(ipfs0, ipfs1) }, 60 * 1000) describe('create & open', () => { let addr0: string let addr1: string test('create datastores', async () => { const store0 = await db0.createDataStore('test0', { 'test': 0 }) const store1 = await db1.createDataStore('test1', { 'test': 1 }) addr0 = store0.address.toString() addr1 = store1.address.toString() await store0.close() await store1.close() }) test('reopen datastores in different peers, have the same metadata', async () => { const store1 = await db0.openDataStore(addr1) const store0 = await db1.openDataStore(addr0) expect(store0.metaData).toStrictEqual({ 'test': 0 }) expect(store1.metaData).toStrictEqual({ 'test': 1 }) await store0.close() await store1.close() }) }) describe('replicate', () => { test('', async () => { const store0 = await db0.createDataStore('abc123') const store1 = await db1.openDataStore(store0.address.toString()) const obj0 = { name: 'obj0', i: db0.identity.toJSON() } const obj1 = { name: 'obj1', i: db1.identity.toJSON() } const hash0 = await store0.add(obj0) await new Promise((resolve) => { store1.events.on('replicated', resolve) }) const hash1 = await store1.add(obj1) await new Promise((resolve) => { store0.events.on('replicated', resolve) }) expect(store1.get(hash0).payload).toStrictEqual(obj0) expect(store0.get(hash1).payload).toStrictEqual(obj1) const entries0 = store0.iterator({ limit: -1 }).collect() const entries1 = store1.iterator({ limit: -1 }).collect() expect(entries0).toHaveLength(2) expect(entries1).toHaveLength(2) expect(entries0).toStrictEqual(entries1) expect(entries0[0].payload).toStrictEqual(obj0) expect(entries0[1].payload).toStrictEqual(obj1) await store0.close() await store1.close() }, 60 * 1000) }) describe('datastore access-controller', () => { let store0: LogStore<any, any> let store1: LogStore<any, any> beforeAll(async () => { // disable error logging // eslint-disable-next-line @typescript-eslint/no-empty-function console.error = (): void => { } store0 = await db0.createDataStore('access-controller-test') store1 = await db1.openDataStore(store0.address.toString(), (entry) => { if (entry.payload === 'a') throw new Error() return entry.identity.publicKey === db0.identity.publicKey }) }) test('client controls the access-controller', async () => { await expect(store0.add('1')).resolves.toBeTruthy() await expect(store1.add('2')).rejects.toThrowError() }) test('Allow Write if the access-controller callback throws an error, ignore anything else', async () => { await expect(store1.add('a')).resolves.toBeTruthy() }) }) afterAll(async () => { await db0.stop() await db1.stop() await ipfs0.stop() await ipfs1.stop() await rmrf(dir0) await rmrf(dir1) }) })
package reserva; import basededados.GestorDeBaseDeDados; import java.security.InvalidParameterException; import java.time.LocalDate; import java.util.*; public class GestorDeReserva { public GestorDeReserva(){ } /** * Esta função é para procurar todas as reservas pelo NIF do cliente * @param nifCliente: NIF do cliente que fez a reserva * @param gestorDeBaseDeDados: conexão há base de dados * @return retorna as reservas por NIF do cliente pesquisadas pelo utilizador */ public List<Reserva> getTodasReservasPorClienteNIF(int nifCliente, GestorDeBaseDeDados gestorDeBaseDeDados) { if(gestorDeBaseDeDados == null) throw new InvalidParameterException("Gestor de Base de Dados nulo."); String queryVerificarClienteNIFValido = "SELECT * from PTDA_BD_03.cliente where nif = %d"; List<String> resultadosClienteNIF = gestorDeBaseDeDados.tryQueryDatabase(String.format(queryVerificarClienteNIFValido, nifCliente)); if (resultadosClienteNIF.isEmpty()) throw new InvalidParameterException("Não existe cliente associado ao NIF fornecido"); HashMap<Integer, Reserva> reservasEncontradas = new HashMap<>(); String query = String.format("SELECT reserva.id, reserva.cliente_nif, reserva.empregado_id, reserva.estado_pagamento, " + " reserva.fatura_id, fatura.montante_total, " + " dia_reserva.quarto_id, quarto.layout_id, layout.preco_base" + " from reserva left join fatura on fatura.id = reserva.fatura_id" + " left join dia_reserva on dia_reserva.reserva_id = reserva.id" + " left join quarto on quarto.id = dia_reserva.quarto_id" + " left join layout on layout.id = quarto.layout_id" + " where reserva.cliente_nif = %d " + "order by reserva.id asc", nifCliente); List<String> linhasReserva = gestorDeBaseDeDados.tryQueryDatabase(query); if(linhasReserva.isEmpty()) throw new InvalidParameterException("Não existe reservas associadas ao NIF fornecido"); for( String linha : linhasReserva){ String[] colunas = linha.split(","); int reservaID = Integer.parseInt(colunas[0]); int clienteNIF = Integer.parseInt(colunas[1]); int empregadoID = Integer.parseInt(colunas[2]); boolean estadoPagamento = colunas[3].equals("1"); int faturaID; float faturaMontante; int quartoID = Integer.parseInt(colunas[6]); int quartoLayoutID = Integer.parseInt(colunas[7]); float quartoLayoutPrecoBase = Float.parseFloat(colunas[8]); Fatura fatura = null; if (estadoPagamento){ faturaID = Integer.parseInt(colunas[4]); faturaMontante = Float.parseFloat(colunas[5]); fatura = new Fatura(faturaID, faturaMontante); } if(!reservasEncontradas.containsKey(reservaID)){ Reserva reserva = new Reserva(reservaID, clienteNIF, empregadoID, quartoLayoutPrecoBase,estadoPagamento, fatura); reservasEncontradas.put(reservaID, reserva); continue; } reservasEncontradas.get(reservaID).adicionarQuarto(quartoID); reservasEncontradas.get(reservaID).somarAoPrecoAtual(quartoLayoutPrecoBase); } return new ArrayList<>(reservasEncontradas.values()); } /** * Esta função é para procurar todas as as reservas por faturar pelo NIF do cliente * @param nifCliente: NIF do cliente que fez a reserva * @param gestorDeBaseDeDados: conexão há base de dados * @return retorna as reservas por faturar por NIF do cliente pesquisadas pelo utilizador */ public List<Reserva> getReservasPorFaturarPorClienteNif(int nifCliente, GestorDeBaseDeDados gestorDeBaseDeDados){ if(gestorDeBaseDeDados == null) throw new InvalidParameterException("Gestor de Base de Dados nulo."); String queryVerificarClienteNIFValido = "SELECT * from PTDA_BD_03.cliente where nif = %d"; List<String> resultadosClienteNIF = gestorDeBaseDeDados.tryQueryDatabase(String.format(queryVerificarClienteNIFValido, nifCliente)); if (resultadosClienteNIF.isEmpty()) throw new InvalidParameterException("Não existe cliente associado ao NIF fornecido"); HashMap<Integer, Reserva> reservasEncontradas = new HashMap<>(); String query = String.format("SELECT reserva.id, reserva.cliente_nif, reserva.empregado_id," + " dia_reserva.quarto_id, layout.preco_base" + " from reserva left join fatura on fatura.id = reserva.id" + " left join dia_reserva on dia_reserva.reserva_id = reserva.id" + " left join quarto on quarto.id = dia_reserva.quarto_id" + " left join layout on layout.id = quarto.layout_id" + " where reserva.cliente_nif = %d and reserva.fatura_id is null", nifCliente); List<String> linhasReserva = gestorDeBaseDeDados.tryQueryDatabase(query); if(linhasReserva.isEmpty()) throw new InvalidParameterException("Não existem reservas por faturar para o NIF dado"); for( String linha : linhasReserva){ String[] colunas = linha.split(","); int reservaID = Integer.parseInt(colunas[0]); int clienteNIF = Integer.parseInt(colunas[1]); int empregadoID = Integer.parseInt(colunas[2]); int quartoID = Integer.parseInt(colunas[3]); float quartoLayoutPrecoBase = Float.parseFloat(colunas[4]); if(!reservasEncontradas.containsKey(reservaID)){ Reserva reserva = new Reserva(reservaID, clienteNIF, empregadoID, quartoLayoutPrecoBase,false, null); reservasEncontradas.put(reservaID, reserva); continue; } reservasEncontradas.get(reservaID).adicionarQuarto(quartoID); reservasEncontradas.get(reservaID).somarAoPrecoAtual(quartoLayoutPrecoBase); } return new ArrayList<>(reservasEncontradas.values()); } /** * Esta função serve para Adicionar uma Reserva na base de dados * @param clienteNIF: NIF do cliente que fez a reserva * @param empregadoID: ID do Empregado que irá efetuar a reserva * @param datas: Intervalo de Datas da reserva * @param quartos: Quartos que prentende reservar * @param gestorDeBaseDeDados conexão há base de dados */ public void adicionarReserva(int clienteNIF, int empregadoID, HashSet<LocalDate> datas, HashSet<Integer> quartos, GestorDeBaseDeDados gestorDeBaseDeDados){ if(gestorDeBaseDeDados == null) throw new InvalidParameterException("Gestor de Base de Dados nulo."); if(datas == null) throw new InvalidParameterException("Lista de datas nula"); if(datas.isEmpty()) throw new InvalidParameterException("Lista de datas vazia"); if(datas.contains(null)) throw new InvalidParameterException("Lista de datas com elemento nulo"); LocalDate[] datasOrdenadas = datas.toArray(new LocalDate[datas.size()]); if(datas.size() > 1){ Arrays.sort(datasOrdenadas); for( int i = 1; i < datasOrdenadas.length; i++){ LocalDate dataAtual = datasOrdenadas[i]; LocalDate dataAnterior = datasOrdenadas[i-1]; if(dataAtual.isAfter(dataAnterior.plusDays(1))) throw new InvalidParameterException("Lista de datas inclui datas não consecutivas"); } } if(quartos == null) throw new InvalidParameterException("Lista de quarto é nula"); if(quartos.isEmpty()) throw new InvalidParameterException("Lista de quartos vazia"); if(quartos.contains(null)) throw new InvalidParameterException("Lista de quartos com elemento nulo"); LocalDate dataInicial = datasOrdenadas[0]; LocalDate dataFinal = datasOrdenadas[ datasOrdenadas.length - 1 ]; if(verificarSeQuartosIndisponiveisParaDatas(quartos, dataInicial, dataFinal, gestorDeBaseDeDados)) throw new InvalidParameterException("Lista de quartos inclui quartos indisponíveis para as datas fornecidas"); String queryVerificaEmpregadoIdValido = "SELECT * FROM PTDA_BD_03.empregado where id = %d and cargo_id = 1"; List<String> resultadosEmpregadoID = gestorDeBaseDeDados.tryQueryDatabase(String.format(queryVerificaEmpregadoIdValido, empregadoID)); if(resultadosEmpregadoID.isEmpty()) throw new InvalidParameterException("Não existe empregado associado ao ID fornecido ou empregado não tem acesso a registar novas reservas"); String queryVerificarClienteNIFValido = "SELECT * from PTDA_BD_03.cliente where nif = %d"; List<String> resultadosClienteNIF = gestorDeBaseDeDados.tryQueryDatabase(String.format(queryVerificarClienteNIFValido, clienteNIF)); if (resultadosClienteNIF.isEmpty()) throw new InvalidParameterException("Não existe cliente associado ao NIF fornecido"); String baseQueryInsertReserva = "INSERT INTO reserva(cliente_nif, empregado_id, estado_pagamento, fatura_id) VALUES "; String baseQueryInsertDiasReserva = "INSERT INTO dia_reserva(data_reserva, quarto_id, reserva_id) VALUES "; StringBuilder stringBuilderInsertReserva = new StringBuilder(); StringBuilder stringBuilderInsertDiasReserva = new StringBuilder(baseQueryInsertDiasReserva); String dadosReserva = String.format("('%d', '%d', '0', NULL)", clienteNIF, empregadoID); stringBuilderInsertReserva.append(baseQueryInsertReserva); stringBuilderInsertReserva.append(dadosReserva); String finalInsertReservaQuery = stringBuilderInsertReserva.toString(); gestorDeBaseDeDados.tryUpdateDatabase(finalInsertReservaQuery); List<String> resultados = gestorDeBaseDeDados.tryQueryDatabase("select last_insert_id()"); int reservaID = Integer.parseInt(resultados.get(0)); Iterator<Integer> iteratorQuarto = quartos.iterator(); while(iteratorQuarto.hasNext()){ Integer quarto = iteratorQuarto.next(); Iterator<LocalDate> iteratorData = datas.iterator(); while (iteratorData.hasNext()){ LocalDate data = iteratorData.next(); String linhaDeValores = String.format("('%s', %s, %s)", data, quarto, reservaID); stringBuilderInsertDiasReserva.append(linhaDeValores); if(!iteratorQuarto.hasNext() && !iteratorData.hasNext()) continue; stringBuilderInsertDiasReserva.append(","); } } String finalInsertDiaReservaQuery = stringBuilderInsertDiasReserva.toString(); gestorDeBaseDeDados.tryUpdateDatabase(finalInsertDiaReservaQuery); } /** * Esta função serve para gerar Faturas para uma determinada Reserva * @param reserva: Número da reserva * @param gestorDeBaseDeDados: conexão há base de dados * @return retorna a fatura gerada para a reserva pedida */ public Fatura gerarFaturaParaReserva(Reserva reserva, GestorDeBaseDeDados gestorDeBaseDeDados){ if(gestorDeBaseDeDados == null) throw new InvalidParameterException("Gestor de Base de Dados nulo."); if (reserva == null) throw new InvalidParameterException("Reserva nula."); if (reserva.getFatura() != null) throw new InvalidParameterException("Não é possível gerar um fatura para a reserva fornecido, reserva já se encontra faturada"); float faturaMontante = reserva.getPrecoAtual(); String sqlAdicionarFatura = "insert into fatura(montante_total) values (" + faturaMontante + ")"; gestorDeBaseDeDados.tryUpdateDatabase(sqlAdicionarFatura); List<String> resultado = gestorDeBaseDeDados.tryQueryDatabase("select last_insert_id()"); int faturaID = Integer.parseInt(resultado.get(0)); String sqlAtualizarFaturaIDEmReserva = String.format("UPDATE reserva SET reserva.fatura_id = %d, reserva.estado_pagamento='1' WHERE reserva.id = %d", faturaID, reserva.getReservaID()); gestorDeBaseDeDados.tryUpdateDatabase(sqlAtualizarFaturaIDEmReserva); Fatura fatura = new Fatura(faturaID, faturaMontante); reserva.setFatura(fatura); reserva.setReservaPaga(true); return fatura; } /** * Esta função serve para verificar se os quartos estão disponíveis para as datas pretendidas pelo cliente * @param quartos: Número do Quarto * @param dataInicial: Data Inicial (Data de Check-In) * @param dataFinal: Data Final (Data de Check-Out) * @param gestorDeBaseDeDados: conexão há base de dados * @return retorna se está disponível nas datas pretendidas */ protected static boolean verificarSeQuartosIndisponiveisParaDatas(HashSet<Integer> quartos, LocalDate dataInicial, LocalDate dataFinal, GestorDeBaseDeDados gestorDeBaseDeDados){ if(gestorDeBaseDeDados == null) throw new InvalidParameterException("Gestor de Base de Dados nulo."); if(quartos == null) throw new InvalidParameterException("Lista de quartos nula"); if(quartos.isEmpty()) throw new InvalidParameterException("Lista de quartos vazia"); if(quartos.contains(null)) throw new InvalidParameterException("Lista de quarto contem elemento nulo"); if(dataFinal.isBefore(dataInicial)) throw new InvalidParameterException("Data final vem antes da data inicial"); if(contemQuartoInexistentes(quartos, gestorDeBaseDeDados)) throw new InvalidParameterException("Lista de quarto contêm quartos inexistentes"); String baseQueryQuartosIndisponiveis = "SELECT quarto_id FROM PTDA_BD_03.dia_reserva " + "where quarto_id in %s and " + "data_reserva between '%s' and '%s' " + "order by quarto_id asc"; String finalQueryQuartosIndisponiveis = String.format( baseQueryQuartosIndisponiveis, quartos.toString().replace("[", "(").replace("]",")"), dataInicial, dataFinal); List<String> resultadoQuartosIndisponiveis = gestorDeBaseDeDados.tryQueryDatabase(finalQueryQuartosIndisponiveis); return !resultadoQuartosIndisponiveis.isEmpty(); } /** * Esta função serve para verificar se existe o quarto pretendido pelo Cliente * @param quartos: Número do Quarto * @param gestorDeBaseDeDados conexão há base de dados * @return retorna se existe o quarto pedido pelo utilizador */ protected static boolean contemQuartoInexistentes(HashSet<Integer> quartos, GestorDeBaseDeDados gestorDeBaseDeDados){ if (gestorDeBaseDeDados == null) throw new InvalidParameterException("Gestor de Base de Dados nulo."); if (quartos == null) throw new InvalidParameterException("Lista de quartos nula"); if (quartos.isEmpty()) throw new InvalidParameterException("Lista de quartos vazia"); if (quartos.contains(null)) throw new InvalidParameterException("Lista de quartos com elementos nulos"); String baseQueryQuartosValidos = "SELECT count(*) FROM PTDA_BD_03.quarto where id in %s"; String finalQueryQuartosValidos = String.format( baseQueryQuartosValidos, quartos.toString().replace("[", "(").replace("]",")")); List<String> resultado = gestorDeBaseDeDados.tryQueryDatabase(finalQueryQuartosValidos); int quartosComID = Integer.parseInt(resultado.get(0)); return quartosComID < quartos.size(); } }
-- ------------------------------------------------------- -- Crear base de datos -- ------------------------------------------------------- create database Sales; use Sales; -- ------------------------------------------------------- -- Crear base de tabla Brand -- ------------------------------------------------------- create table Brand ( cod_brand char(5) not null primary key, brand varchar(30) not null ); -- ------------------------------------------------------- -- Crear base de tabla Product -- ------------------------------------------------------- create table Product ( cod_product char(5) not null primary key, product varchar(40) not null, stock int, price float, mesure char(1), cod_brand char(5) not null, foreign key (cod_brand) references Brand (cod_brand) ); -- ------------------------------------------------------- -- Insertar datos a la tabla Customer -- ------------------------------------------------------- create table Customer ( cod_customer char(5) not null primary key, last_name varchar(40) not null, first_name varchar(40) not null, email varchar(40) not null, age int ); -- ------------------------------------------------------- -- Insertar datos a la tabla Supplier -- ------------------------------------------------------- create table Supplier ( cod_supplier char(5) not null primary key, bussines_name varchar(40) not null, contact_phone varchar(10) not null, email varchar(40) not null, bussines_category int ); -- ------------------------------------------------------- -- Insertar datos a la tabla Employee -- ------------------------------------------------------- create table Employee ( cod_employee char(5) not null primary key, last_name varchar(40) not null, first_name varchar(40) not null, email varchar(60) not null, salary float ); -- ------------------------------------------------------- -- Insertar datos a la tabla Store -- ------------------------------------------------------- create table Store ( cod_store char(5) not null primary key, name_store varchar(40) not null, district varchar(40) not null, province varchar(60) not null, quantity_employees float ); -- ******************************************************* -- ------------------------------------------------------- -- Insertar datos a la tabla Brand -- ------------------------------------------------------- insert into Brand values ("M0001", "Costeño"), ("M0002", "Gloria"), ("M0003", "Del Valle"), ("M0004", "Coca Cola"); -- ------------------------------------------------------- -- Insertar datos a la tabla Product -- ------------------------------------------------------- insert into Product values ("P0001", "Aceite", 150, 9.8, "L", "M0001"), ("P0002", "Gaseosa", 200, 6, "L", "M0004"), ("P0003", "Lentejas", 120, 7.3, "K", "M0003"); -- ------------------------------------------------------- -- Insertar datos a la tabla Customer -- ------------------------------------------------------- insert into Customer values ("C0001", "Torres","Maria","tmaria@gmail.com", 25), ("C0002", "Alvarez","Rita","arita@gmail.com", 43), ("C0003", "Perez","Pedro","ppedro@gmail.com", 56); -- ------------------------------------------------------- -- Insertar datos a la tabla Supplier -- ------------------------------------------------------- insert into Supplier values ("S0001", "Provider1","987561247","pr1@company.com", 1), ("S0002", "Provider2","365478513","pr2@company.com", 2), ("S0003", "Provider3","874562147","pr3@company.com", 3); -- ------------------------------------------------------- -- Insertar datos a la tabla Employee -- ------------------------------------------------------- insert into Employee values ("E0001", "Hernandez","Roberto","hroberto@empresa.com", 930), ("E0002", "Fernadez","Olga","folga@empresa.com", 2500), ("E0003", "Rodriguez","Teresa","rteresa@empresa.com", 1500); -- ------------------------------------------------------- -- Insertar datos a la tabla Store -- ------------------------------------------------------- insert into Store values ("ST001", "SedePrincipal","Independencia","Lima", 120), ("ST002", "Sede1","Rimac","Lima", 42), ("ST003", "Sede2","Callao","Callao", 26); -- ------------------------------------------------------- -- Procedimiento almacenado -- ------------------------------------------------------- delimiter $$ create procedure BrandList() begin select * from Brand order by Brand; end; $$
import { Request } from 'express'; import { config, createLogger, format, transports } from 'winston'; import { AuthConstants } from '../auth/constants'; import { objectPropertyRegex } from './regex'; const formatOptionConsole = format.combine( format.cli(), format.splat(), format.timestamp(), format.printf((info) => { return `${info.timestamp} [${info.level}]: ${info.message}`; }), ); const formatOptionFile = format.combine( format.cli(), format.splat(), format.uncolorize(), format.timestamp(), format.printf((info) => { return `${info.timestamp} [${info.level}]: ${info.message}`; }), ); export const instance = createLogger({ levels: config.npm.levels, transports: [ new transports.DailyRotateFile({ filename: `logs/%DATE%/error.log`, level: 'error', format: formatOptionFile, datePattern: 'YYYY-MM-DD', zippedArchive: false, maxFiles: '30d', }), new transports.DailyRotateFile({ filename: `logs/%DATE%/info.log`, level: 'info', format: formatOptionFile, datePattern: 'YYYY-MM-DD', zippedArchive: false, maxFiles: '30d', }), new transports.DailyRotateFile({ filename: `logs/%DATE%/warning.log`, level: 'warning', format: formatOptionFile, datePattern: 'YYYY-MM-DD', zippedArchive: false, maxFiles: '30d', }), new transports.DailyRotateFile({ filename: `logs/%DATE%/debug.log`, level: 'debug', format: formatOptionFile, datePattern: 'YYYY-MM-DD', zippedArchive: false, maxFiles: '30d', }), new transports.DailyRotateFile({ filename: `logs/%DATE%/silly.log`, level: 'silly', format: formatOptionFile, datePattern: 'YYYY-MM-DD', zippedArchive: false, maxFiles: '30d', }), new transports.Console({ level: 'debug', format: formatOptionConsole, }), ], }); export function formatRequest(req: Request): object { const copy = JSON.parse(JSON.stringify(req.body)); const sensitiveCredentials: string[] = [ AuthConstants.Email, AuthConstants.Password, ]; sensitiveCredentials.forEach((credential) => { // if credentials are provided as inline arguments in query, then replace by regex const regex = objectPropertyRegex(credential); const replace = `${credential}: "secret"`; copy.query = copy.query.replace(regex, replace); // if passed as objects, replace their values if (copy.variables?.input && credential in copy.variables.input) { copy.variables.input[credential] = 'secret'; } }); return copy; }
import React, {useEffect, useState} from "react"; import {useHistory} from "react-router-dom"; import {fetchAllAccounts, fetchAllBookings} from "../../services/service"; import { Button, Spin, Form, Select, Input, DatePicker, Typography } from "antd"; const formItemLayout = { labelCol: { xs: { span: 24, }, sm: { span: 8, }, }, wrapperCol: { xs: { span: 24, }, sm: { span: 16, }, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; export default function BookingCreate() { const [booking, setBooking] = useState({}) const [accounts, setAccounts] = useState({}) const [buchungTextState, setBuchungTextState] = useState("") useEffect(() => { fetchAllBookings() .then(res => setBooking(res)) fetchAllAccounts().then(res => setAccounts(res)) }, []) useEffect(() => { }, [buchungTextState]) const [form] = Form.useForm(); const history = useHistory() const onFinish = (values) => { const datum = values.date.format('DD.MM.YYYY') const myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); const id = Object.keys(booking).length + 1 const raw = JSON.stringify({ [id]: { "Buchungsdatum": datum, "Buchungsnummer": id, "Beschreibung": values.Beschreibung, "Buchungsschluessel": values.Buchungschluessel, "Buchungstext": values.Buchungstext, "Steuerkonto": values.Steuerkonto, "Betrag": values.Betrag, "SollBetragMitSteuer": values.Betrag, "HabenBetragMitSteuer": values.Betrag, "HabenKonto": values.HabenKonto, "SollKonto": values.SollKonto, "SollSteuerKonto": "", "HabenSteuerKonto": "", "SollSteuerBetrag": 0, "HabenSteuerBetrag": 0, } }); const requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; fetch("http://127.0.0.1:5000/api/buchungen/add", requestOptions) .then(response => { if (response.ok) { history.push("/booking/overview") } return response.json() }) .catch(error => console.log('error', error)); }; const onReset = () => { form.resetFields() } const onBookingChange = (value) => { switch (value) { case 'Rechnungsausgang': setBuchungTextState('Rechnungsausgang') form.setFieldsValue({ Buchungschluessel: 'RA', }); return; case 'Zahlungseingang': setBuchungTextState('Zahlungseingang') form.setFieldsValue({ Buchungschluessel: 'ZE', }); return; case 'Rechnungseingang': setBuchungTextState('Rechnungseingang') form.setFieldsValue({ Buchungschluessel: 'RE', }); return; case 'Zahlungsausgang': setBuchungTextState('Zahlungsausgang') form.setFieldsValue({ Buchungschluessel: 'ZA', }); return; case 'Buchung': setBuchungTextState('Buchung') form.setFieldsValue({ Buchungschluessel: 'UM', }); return; case 'Sachkonten': setBuchungTextState('Sachkonten') form.setFieldsValue({ Buchungschluessel: 'SA', }); return; case 'Eroeffnungsbuchung': setBuchungTextState('Eroeffnungsbilanz') form.setFieldsValue({ Buchungschluessel: 'ER', }); } } let accountsWithName = [] for (const accountId in accounts) { let acc = { "Kontonummer": accountId, "Kontoname": accounts[accountId]["Kontoname"] } accountsWithName.push(acc) } //TODO: SHOULD KONTO 1400 1600 9000 9008 9009 BE EXCLUDED? const nurKreditoren = accountsWithName.filter(acc => acc["Kontonummer"] >= 70000 && acc["Kontonummer"] < 100000) const alleKontenExcludeSteuerKonto = accountsWithName.filter(acc => acc["Kontonummer"] !== "1571" && acc["Kontonummer"] !== "1576" && acc["Kontonummer"] !== "1771" && acc["Kontonummer"] !== "1776" ) const nurDebitoren = accountsWithName.filter(acc => acc["Kontonummer"] >= 10000 && acc["Kontonummer"] < 70000) const nurSachkonten = accountsWithName.filter(acc => acc["Kontonummer"] >= 1 && acc["Kontonummer"] < 10000 && acc["Kontonummer"] !== "1571" && acc["Kontonummer"] !== "1576" && acc["Kontonummer"] !== "1771" && acc["Kontonummer"] !== "1776" ) const bankKonto = accountsWithName.filter(acc => acc["Kontonummer"] >= 1000 && acc["Kontonummer"] < 1201) const erloeseKonto = accountsWithName.filter(acc => acc["Kontonummer"] >= 8000 && acc["Kontonummer"] < 9000) const mWStKonto = accountsWithName.filter(acc => acc["Kontonummer"] === "1771" || acc["Kontonummer"] === "1776") const vorSteuerKonto = accountsWithName.filter(acc => acc["Kontonummer"] === "1571" || acc["Kontonummer"] === "1576") const allSteuerKonto = accountsWithName.filter(acc => acc["Kontonummer"] === "1571" || acc["Kontonummer"] === "1576" || acc["Kontonummer"] === "1771" || acc["Kontonummer"] === "1776" ) return ( <> {!!booking ? ( <div> <> <Typography.Title level={3}>Neue Buchung erstellen</Typography.Title> <Form {...formItemLayout} form={form} name="register" onFinish={onFinish} scrollToFirstError > <Form.Item name="date" label="Buchungsdatum" rules={[{ required: true, message: 'Waehlen Sie ein Datum aus!', },]}> <DatePicker placeholder="Datum" style={{ width: 150, }} /> </Form.Item> <Form.Item name="Buchungstext" label="Buchungstext" rules={[ { required: true } ]} > <Select placeholder="W&auml;hlen Sie eine Buchung aus" onChange={onBookingChange} allowClear style={{ width: 500, }} > <Select.Option value="Rechnungsausgang">Rechnungsausgang</Select.Option> <Select.Option value="Zahlungseingang">Zahlungseingang </Select.Option> <Select.Option value="Rechnungseingang">Rechnungseingang</Select.Option> <Select.Option value="Zahlungsausgang">Zahlungsausgang</Select.Option> <Select.Option value="Buchung">Buchung</Select.Option> <Select.Option value="Sachkonten">Sachkonten</Select.Option> <Select.Option value="Eroeffnungsbuchung">Er&ouml;ffnungsbuchung 01.01.</Select.Option> </Select> </Form.Item> <Form.Item name="Buchungschluessel" label="Buchungsschl&uuml;ssel" rules={[ { required: true, }, ]} > <Input disabled style={{ width: 50, }} /> </Form.Item> <Form.Item name="Beschreibung" label="Beschreibung" rules={[ { required: true, }, ]} > <Input.TextArea style={{ width: 500, }}/> </Form.Item> <Form.Item name="Betrag" label="Betrag" rules={[ { required: true, message: 'Betrag eingeben', }, ]} > <Input min={0} style={{ width: 100 }} /> </Form.Item> <Form.Item name="Steuerkonto" label="Steuerkonto" rules={[ { required: true, message: 'Steuerkonto eingeben', }, ]} > <Select placeholder="W&auml;hlen Sie ein Steuerkonto aus" allowClear style={{ width: 500, }} > <Select.Option value=" ">Kein Steuer</Select.Option> {buchungTextState === 'Rechnungsausgang' ? mWStKonto.map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) : buchungTextState === 'Rechnungseingang' ? vorSteuerKonto.map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) : allSteuerKonto.map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } </Select> </Form.Item> <Form.Item name="SollKonto" label="Soll-Konto" rules={[ { required: true, message: 'Please select Soll-Konto!', }, ]} shouldUpdate={(prevValues, currentValues) => prevValues.Buchungstext !== currentValues.Buchungstext} > <Select placeholder="W&auml;hlen Sie ein Konto aus" allowClear style={{ width: 500, }} > {buchungTextState === '' && accountsWithName.map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Rechnungseingang' && nurSachkonten.map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Zahlungseingang' && bankKonto .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Rechnungsausgang' && nurDebitoren .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Zahlungsausgang' && nurKreditoren .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Buchung' && nurSachkonten .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Sachkonten' && nurSachkonten.map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Eroeffnungsbilanz' && alleKontenExcludeSteuerKonto.map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } </Select> </Form.Item> <Form.Item name="HabenKonto" label="Haben-Konto" rules={[ { required: true, message: 'Please select Haben-Konto!', }, ]} shouldUpdate={(prevValues, currentValues) => prevValues.Buchungstext !== currentValues.Buchungstext} > <Select placeholder="W&auml;hlen Sie ein Konto aus" allowClear style={{ width: 500, }} > {buchungTextState === '' && accountsWithName.map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Zahlungsausgang' && bankKonto .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Zahlungseingang' && nurDebitoren .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Rechnungseingang' && nurKreditoren .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Rechnungsausgang' && erloeseKonto .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Buchung' && nurSachkonten .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Sachkonten' && nurSachkonten .map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } {buchungTextState === 'Eroeffnungsbilanz' && alleKontenExcludeSteuerKonto.map((acc) => ( <Select.Option value={acc["Kontonummer"]}>{acc["Kontonummer"]} - {acc["Kontoname"]}</Select.Option> )) } </Select> </Form.Item> <Form.Item {...tailFormItemLayout}> <Button type="primary" htmlType="submit"> Buchen </Button> <Button htmlType="button" onClick={onReset}> Reset </Button> </Form.Item> </Form> </> </div> ) : ( <Spin/> ) } </> ) }
import React, {createContext, useContext, useEffect, useState} from 'react'; import {useAuth} from './Auth'; import dayjs, {Dayjs} from 'dayjs'; import Config from 'react-native-config'; type BalanceContextData = { balance: number; loading: boolean; time_since_updated_string: string; refresh(): void; }; const BalanceContext = createContext<BalanceContextData>( {} as BalanceContextData, ); const useBalance = () => { const context = useContext(BalanceContext); if (!context) { throw new Error('useBalance must be used within BalanceProvider'); } return context; }; const BalanceProvider = ({children}: {children: React.ReactNode}) => { const [balance, setBalance] = useState(0.0); const [loading, setLoading] = useState(false); const [time_updated, setTimeUpdated] = useState(dayjs()); const [time_since_updated_string, setTimeSinceUpdatedString] = useState(''); const auth = useAuth(); useEffect(() => { refresh(); // setInterval(() => { // setTimeSinceUpdatedString(getTimeSinceUpdated(time_updated)); // }, 1000); // Update the time since, every second }, []); const getTimeSinceUpdated = (time_since: Dayjs) => { const secs = Math.floor(dayjs().diff(time_since) / 1000); if (secs < 60) { // Seconds return secs == 1 ? secs.toString() + ' second ago' : secs.toString() + ' seconds ago'; } let mins = Math.floor(secs / 60); if (mins < 60) { // Minutes return mins == 1 ? mins.toString() + ' minute ago' : mins.toString() + ' minutes ago'; } const hrs = Math.floor(mins / 60); if (hrs < 24) { // Hours return hrs == 1 ? hrs.toString() + ' hour ago' : hrs.toString() + ' hours ago'; } const days = Math.floor(hrs / 24); // Days return days == 1 ? days.toString() + ' day ago' : days.toString() + ' days ago'; }; const refresh = async () => { if (auth.authData?.token) { setLoading(true); fetch(`${Config.API_URL}/api/get_token_balance`, { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${auth.authData?.token}`, }, }) .then(res => res.json()) .then(data => { setBalance(data['token_balance']); setLoading(false); // (async () => await setTimeUpdated(dayjs()))(); }) .catch(error => { console.log(error); }); } }; return ( <BalanceContext.Provider value={{balance, loading, time_since_updated_string, refresh}}> {children} </BalanceContext.Provider> ); }; export {BalanceContext, useBalance, BalanceProvider};
<template> <div class="main-container"> <span class="extra-message"> <template v-if="user"> 只展示用户 <span class="user-info">{{ user.nickname }}({{ user.username }})</span> 最近登录的 {{ historyCount }} 条历史记录 </template> <template v-else> 只展示最近登录的 {{ historyCount }} 条历史记录 </template> </span> <!-- 加载中 --> <a-skeleton v-if="loading" style="width: 70%;" :animation="true"> <a-skeleton-line :rows="4" /> </a-skeleton> <!-- 登录历史时间线 --> <a-timeline v-else-if="list.length"> <a-timeline-item v-for="item in list" :key="item.id"> <!-- 图标 --> <template #dot> <div class="icon-container"> <icon-mobile v-if="isMobile(item.userAgent)" /> <icon-desktop v-else /> </div> </template> <!-- 日志行 --> <div class="log-line"> <!-- 地址行 --> <a-space class="address-line"> <span class="mr8">{{ item.address }}</span> <span>{{ item.location }}</span> </a-space> <!-- 错误信息行 --> <span class="error-line" v-if="item.result === ResultStatus.FAILED"> 登录失败: {{ item.errorMessage }} </span> <!-- 时间行 --> <span class="time-line"> {{ dateFormat(new Date(item.createTime)) }} </span> <!-- ua --> <span class="ua-line"> {{ item.userAgent }} </span> </div> </a-timeline-item> </a-timeline> <!-- 空 --> <a-empty v-else /> </div> </template> <script lang="ts"> export default { name: 'loginHistory' }; </script> <script lang="ts" setup> import type { UserQueryResponse, LoginHistoryQueryResponse } from '@/api/user/user'; import { ref, onBeforeMount } from 'vue'; import useLoading from '@/hooks/loading'; import { historyCount, ResultStatus } from '../types/const'; import { getCurrentLoginHistory } from '@/api/user/mine'; import { getLoginHistory } from '@/api/user/user'; import { dateFormat } from '@/utils'; import { isMobile } from '@/utils/is'; const props = defineProps<{ user?: UserQueryResponse; }>(); const list = ref<LoginHistoryQueryResponse[]>([]); const { loading, setLoading } = useLoading(); // 查询操作日志 onBeforeMount(async () => { try { setLoading(true); if (props.user) { // 查询其他用户 const { data } = await getLoginHistory(props.user.username, historyCount); list.value = data; } else { // 查询当前用户 const { data } = await getCurrentLoginHistory(historyCount); list.value = data; } } catch (e) { } finally { setLoading(false); } }); </script> <style lang="less" scoped> .main-container { width: 100%; min-height: 200px; padding-left: 48px; } .extra-message { margin-bottom: 42px; margin-left: -24px; display: block; color: var(--color-text-3); user-select: none; .user-info { color: rgb(var(--primary-6)); font-weight: 600; } } .icon-container { border-radius: 50%; width: 56px; height: 56px; color: var(--color-white); background: var(--color-fill-4); font-size: 28px; display: flex; align-items: center; justify-content: center; } :deep(.arco-timeline-item-content-wrapper) { position: relative; margin-left: 44px; margin-top: -22px; } :deep(.arco-timeline-item) { padding-bottom: 36px; .arco-timeline-item-dot-custom { background: unset; } } .log-line { display: flex; flex-direction: column; .address-line { color: var(--color-text-1); font-size: 15px; font-weight: 600; margin-bottom: 2px; } .time-line, .ua-line, .error-line { color: var(--color-text-3); font-size: 14px; margin-top: 2px; } .error-line { color: rgb(var(--danger-6)); font-weight: 600; } } </style>
import { AnimateSharedLayout, motion } from "framer-motion"; import { useRouter } from "next/router"; import { isActiveLink } from "lib/utils"; import Link from "./NoScrollLink"; const links: { name: string; href: string }[] = [ { name: "Home", href: "/", }, { name: "About", href: "/about", }, { name: "Portfolio", href: "/portfolio", }, ]; const Navigation = (): JSX.Element => { const router = useRouter(); return ( <AnimateSharedLayout> <nav className="flex"> {links.map(({ name, href }) => ( <Link key={name} href={href}> <a className="relative mr-6 flex flex-col sm:mr-8"> {name} {isActiveLink(href, router.pathname) && ( <motion.div layoutId="navigation-underline" className="navigation-underline" animate /> )} </a> </Link> ))} </nav> </AnimateSharedLayout> ); }; export default Navigation;
import {Subject} from './observation/Subject'; import {Observer} from "./observation/Observer"; import {Observatory} from "./observation/Observatory"; import {A, A_CLASS_ID} from "./A"; class B{ static readonly CLASS_ID = new B(0); constructor(public value: number) {} } const B_CLASS_ID = new B(0); class A_Observer extends Observer<A> { constructor(class_id: A) { super(class_id); } signal(subject: Subject<A>): void { console.log(`A_Observer: ${subject.state.value}`) } } class B_Observer extends Observer<B> { constructor(class_id: B, public observer_id: number) { super(class_id); } signal(subject: Subject<B>): void { console.log(`B_Observer (#${this.observer_id}): ${subject.state.value}`) } } let observatory = new Observatory(); let a_subject = new Subject<A>(A_CLASS_ID); let a2_subject = new Subject<A>(A_CLASS_ID); let b_subject = new Subject<B>(B_CLASS_ID); let a_observer = new A_Observer(A_CLASS_ID); let b_observer = new B_Observer(B_CLASS_ID, 1); let b2_observer = new B_Observer(B_CLASS_ID, 2);; observatory.provide(a_subject); observatory.provide(a2_subject); observatory.provide(b_subject); observatory.subscribe(a_observer); observatory.subscribe(b_observer); observatory.subscribe(b2_observer); let a = new A("hallo"); let a2 = new A("welt"); let b = new B(42); a_subject.state = a; b_subject.state = b; a2_subject.state = a2; a2_subject.state = new A("foo"); b_subject.state = new B(21);
:author: Roman Kofler-Hofer :listing-caption: Code-Auszug :source-highlighter: rouge // path to the directory containing the source code :src: ../app/src/main // path to the directory containing the images :imagesdir: ./images :toc: :numbered: :toclevels: 3 :rouge-style: github :pdf-themesdir: ./theme :pdf-theme: basic :pdf-fontsdir: ./fonts // front-cover-image can be used to include the Exercise specification, for example: //:front-cover-image: = CaaS - Ausbaustufe 3 <<< == Lösungsidee Ziel dieser Ausarbeitung war es, auf Basis der zur Verfügung gestellten REST-Schnittstelle ein Frontend zu entwickeln, das zumindest die Mindestanforderungen erfüllt. Ich habe mich dazu entschieden zwei Anwendungen zu bauen. Eine für einen Shop (CaaS.Shop) und eine zweite (komplett abgekoppelte) für die Verwaltung von Shops (CaaS.Admin). CaaS.Shop kann beim Start so konfiguriert werden, dass Daten für einen anderen Shop angezeigt werden. Für die Umsetzung des UIs wurde Bootstrap 5 verwendet. Für die Authentifizierung in Caas.Admin wurde KeyCloak verwendet. .Projektstruktur image::appStructure.png[width=600] <<< == Caas.Admin === Architekur Caas.Admin besteht aus verschiedenen Komopnenten. Die Grafik Caas.Admin Struktur gibt einen schematischen Überblick über den Aufbau. Ohne Login erreichbar ist die Login-Seite (gleichzusetzen mit einer Hero-Page bzw. Startseite). Eine Redirect Komponente ist ebenfalls ohne Login zu erreichen. Der Login-Prozess wird im Anschluss im Detail beschrieben. Hinter dem Login hat der User Zugriff auf die einzelnen Bereiche des Admin-Tools und kann hier den zugeordneten Shop verwalten. Dazu werden von der Applikation Services zur Verfügung gestellt welche den Zugriff auf die API erlauben. Die models sind Abbilder der ViewModels der API. Diese dienen der typisierten Programmierung in Angular. Die Services verwenden die Models und retournieren auch bestimmte Models an die aufrufenden Komponenten. Auf der Home-Komponente werden dem User die Shop-Infos angezeigt. Diese können auch direkt dort verändert werden. Dazu bindet die Home-Komponente eine Kind-Komponente namens shop-form ein. Discounts werden in einer Liste angezeigt (discount-list). Von hier aus gelangt man auf die discount-form Komponente welche es erlaubt einen neuen Discount anzulegen bzw. einen bestehenden zu ändern. Die beiden chart-Komponenten (cart und order statistics) dienen zur Anzeige von Statistiken des Shops. Zur Auswahl des Auswertungszeitraums haben beide Komponenten die Kind-Komponente datepicker eingebunden. Die Komponente navbar wird in sämtlichen HTML templates der einzelnen Komponenten angezeigt und dient der Navigation zwischen den einzelnen Seiten. .Caas.Admin Struktur image::admin_structure.png[width=600] === Login Die index.html Seite leitet auf die Login-Komponente weiter. Von dort kann man den Login mittels KeyCloak triggern. In KeyCloak wurden die beiden CaaS-Admin-User angelegt. Außerdem wurde dort ein zusätzliches Attribut namens caasId gespeichert. Dieses entspricht der id des Admins aus dem Backend. Als redirectUri wurde in der authConfig die redirect-Komponente angegeben. Das Attribut caasId wird beim Login neben dem access token und id token ebenfalls in den Session Storage gespeichert. Die einzige Aufgabe der redirect-Komponente ist es, auf die home-Komponente weiterzuleiten. Vor dieser ist ein Guard, welcher überprüft, ob der User eingeloggt ist. Warum habe ich nicht direkt auf die home-Komponente geleitet (redirectUri) und mir die redirect-Komponente gespart? Das war der ursprüngliche Plan, allerdings hat KeyCloak in diesem Fall den access_token, id_token, caasId etc. nicht in den Session Storage gespeichert. Ich glaub, es lag daran, dass in diesem Fall die redirect Uri durch einen Guard geschützt war. In der Home-Komponente steht der shopService bereit. Das Backend bietet eine Möglichkeit einen Shop für eine bestimmte Admin-Id zu erhalten. In diesem Shop Element ist auch der API-Key sowie die Tenant-Id des Shops gespeichert. Diese Daten werden für sämtliche API-calls benötigt, welche Administratorenrechte benötigen. Beide Daten werden in den Session-Storage gespeichert und stehen ab nun allen Services zur Verfügung. .Ablauf Login image::login.png[width=600] <<< === Benutzerschnittstelle .Login Komponente image::admin/login.png[width=700] Die Login Komponente dient als Hero-Page. Von hier aus kann der Login gestartet werden. .Redirect Komponente image::admin/redirect.png[width=600] Bevor zur Home-Komponente geleitet wird, muss der User über die Redirect-Komponente geleitet werden (dauert 2 Sekunden). .Home Komponente image::admin/home.png[width=700] Die Home Komponente zeigt die Shopdetails an. Durch die eingebundene Komponente "Shop-Form" kann der Shop upgedatet werden .Home Komponente - editieren aktiviert image::admin/home_edit.png[width=700] Das Editieren des Shops kann gespeichert oder abgebrochen werden .Discount-list Komponente image::admin/discount_list.png[width=700] In der Discount-List werden die verschiedenen Discounts aufgelistet. Von hier aus kann der User diese bearbeiten, neu anlegen oder löschen. Die Regeln und Aktionen sind individuell. Es wurde kein dynamisches Formular verwendet. Stattdessen werden die Parameter der Regeln und Aktionen nur als JSON angezeigt. .Discount-form Komponente image::admin/edit_existing_discount.png[width=700] In dieser Komponente kann ein Discount editiert werden. Diese Komponente wird auch geöffnet, wenn der User einen neuen Discount anlegen möchte. Dann werden in das Formular jedoch nur Platzhalter eingefügt. .cart- und order-statistics Komponente image::admin/orderstatistics.png[width=700] Die Charts wurden mittels chartjs erstellt. Die beiden Komponenten für Cart und Orderstatistics sind sehr ähnlich. Das Backend unterstützt die Auswahl eines Aggregationslevels (Tag, Monat, Jahr). Außerdem können verschiedene Statistiken angezeigt werden (z.B. Anzahl an Bestellungen, summierter Wert der Bestellungen, usw.). Der User kann für die Auswertung einen Zeitraum eingeben. Es werden jedoch maximal 60 Datenpunkte dargstellt, da die Balken ansonsten zu klein werden (kein endloses Anwachsen der X-Achse). <<< == Caas.Shop === Architekur Der Shop ist eine eigenständige Applikation, hat aber natürlich einige Gemeinsamkeiten mit der Admin-App. So sind die Services natürlich ähnlich aufgebaut und auch die view-models sind Großteils ident. Die Home-Komponente soll die Startseite von einem Online-Shop simulieren. Zu finden sind darauf grafische Elemente ohne Funktionalität. Über die Komponente product-list kann man Produkte zu einem Warenkorb hinzufügen. Die Kind-Komponente search liefert zu Suchanfragen passende Ergebnisse vom Backend. Die Ergebnisse werden "paginated" dargestellt. Neue Ergebnisse werden nicht während dem Tippen geliefert, sondern erst, wenn der User "search" klickt. Das wurde gemacht, um das Backend zu entlasten. Die Komponente product-detail dient dazu, um Details eines Produktes anzuzeigen. Außerdem kann das Produkt auch zum Warenkorb hinzugefügt werden. Die Cart-Komponente beinhaltet cart-entry-Komponenten für jedes Item in einem Warenkorb. Mit einem gültigen Warenkorb (alle Items haben eine Menge von > 0) kann man zum Checkout navigieren. Im Checkout muss der User seine Daten angeben. Sofern die Zahlung erfolgreich ist (managed das Backend), wird die Bestellung erfolgreich abgeschickt und der User wird zur Startseite weitergeleitet. Mit einem Toast wird die Bestellnummer angezeigt. In der Shop-Applikation gibt es keinen User-Login. Shops werden durch den Local Storage persistiert. Wenn auf die Cart-Komponente gewechselt wird, wird zuerst im Local Storage nachgesehen, ob ein Cart existiert. Falls das der Fall ist, wird vom Server ein Update des Carts geholt. Ansonsten wird ein leerer Cart angezeigt. .Caas.Shop Struktur image::shop_structure.png[width=700] Bei allen Aktionen die den Cart betreffen wird zuerst in den LocalStorage gesehen, um zu checken, ob es bereits einen Warenkorb gibt oder nicht. Die Grafik unterhalb beschreibt den Ablauf beim Hinzufügen eines Produkts zum Cart. Wenn addToCart(productId) aufgerufen wird, muss zuerst im LocalStorage der aktuelle Cart geholt werden. Falls einer gefunden wird, wird aus dem Cart das gewählte Produkt (über die übergebene id) gesucht. Falls ein Produkt gefunden wird, wird der Count erhöht. Ansonsten wird ein neues Item zum Cart hinzugefügt. Wenn im Local Storage kein Cart gefunden wird, wird eine neuer mit dem einen hinzugefügten Item initialisiert. Mit diesem Cart ruft der CartService nun updateCart auf, was ein Update am Server auslöst. Der retournierte Cart wird bis zur Product-List weitergegeben. Diese zeigt bei erfolgreichem Hinzufügen einen Toast an und updated den im LocalStorage gespeicherten Cart (es wäre möglich, dass sich anwendbare Discounts geändert haben). .Ablauf Produkt zu Cart hinzufügen image::addToCart.png[width=600] <<< === Benutzerschnittstelle .Startseite image::shop/home.png[width=700] Die Startseite soll an eine E-Commerce Seite erinnen, hat ansonsten aber keine Funktion. .Produktsuche image::shop/product_search.png[width=700] In der product-list-Komponente kann nach Produkten gesucht werden. Die Bilder sind Platzhalter. Über den Titel des Produkts kommt man zur Detailseite. Außerdem kann ein Produkt zum Warenkorb hinzugefügt werden. Die Suchergebnisse sind auf einzelne Seiten aufgeteilt. .Detailseite image::shop/product_details.png[width=700] Auch über die Detailseite können Produkte zum Cart hinzugefügt werden .Cart image::shop/cart.png[width=700] Im Cart sieht dier User alleine seine Produkte. Außerdem können hier Gutscheine hinzugefügt werden. Die Zusammenfassung der Bestellung mit Basispreis, Abzüge und Endsumme wird dem User auch angezeigt. .Checkout image::shop/checkout.png[width=700] Auf der Checkout-Seite muss der User seine Daten eingeben. Die Felder werden natürlich validiert. Sobald alle Daten eingegeben wurden, kann der Checkout abgeschlossen werden .Checkout erfolgreich image::shop/successful_order.png[width=700] Nach dem Checkout wird der User auf die Startseite zurückgeleitet. Die Bestellnummer wird mit einem Toast angezeigt. .Übersetzungen image::shop/translations.png[width=700] Für die Shopkomponente wurden Übersetzungen hinzugefügt. Allerdings nur in HTML Komponenten. Texte, die in den .ts Files definiert wurden, werden nicht übersetzt. Hier hatte ich in der Umsetzung ein Problem, das ich bis zum Schluss nicht lösen konnte. == Installation Mit ng build kann die Applikation gebaut werden. Der Output-Ordner (dist/CaaSShop bzw. dist/CaaSAdmin) kann dann auf einen Webserver geladen werden.
/* MIT License Copyright (c) 2024 Gianluca Russo 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. */ #include <iostream> #include <string> #include <unordered_map> #include <cstdint> //for the uint8_t type #include <cstdlib> //for the exit function #ifdef _WIN32 #include <windows.h> #else #endif using std::cout, std::endl; using std::string, std::to_string, std::unordered_map; using std::ostream; //Check if the user is on Windows, if true includes the library for the Windows API otherwise it doesn't namespace CLIStyle { //This namespace contains all the functions that the user shouldn't access namespace _private { //Maps style names to their corresponding ANSI escape codes. unordered_map<string, string> styles = { {"bold", "\033[1m"}, {"italic", "\033[3m"}, {"underline", "\033[4m"}, {"reverse", "\033[7m"} }; //Maps color names to their corresponding ANSI escape codes for text. unordered_map<string, string> color_text = { {"grey", "\033[30m"}, {"red", "\033[31m"}, {"green", "\033[32m"}, {"yellow", "\033[33m"}, {"blue", "\033[34m"}, {"magenta", "\033[35m"}, {"cyan", "\033[36m"}, {"white", "\033[37m"}, {"bright grey", "\033[1;30m"}, {"bright red", "\033[1;31m"}, {"bright green", "\033[1;32m"}, {"bright yellow", "\033[1;33m"}, {"bright blue", "\033[1;34m"}, {"bright magenta", "\033[1;35m"}, {"bright cyan", "\033[1;36m"}, {"bright white", "\033[1;37m"} }; //Maps color names to their corresponding ANSI escape codes for background. unordered_map<string, string> color_background = { {"grey", "\033[40m"}, {"red", "\033[41m"}, {"green", "\033[42m"}, {"yellow", "\033[43m"}, {"blue", "\033[44m"}, {"magenta", "\033[45m"}, {"cyan", "\033[46m"}, {"white", "\033[47m"}, {"bright grey", "\033[1;40m"}, {"bright red", "\033[1;41m"}, {"bright green", "\033[1;42m"}, {"bright yellow", "\033[1;43m"}, {"bright blue", "\033[1;44m"}, {"bright magenta", "\033[1;45m"}, {"bright cyan", "\033[1;46m"}, {"bright white", "\033[1;47m"} }; constexpr auto RESET_STYLE = "\033[0m"; bool handleVTSequences = false; //checks if the user terminal can access the ANSI code #ifdef _WIN32 // check if the user is on Windows /** * @brief Enables virtual terminal sequence processing for the console output. * * @param handleVTSequences A reference to a boolean flag indicating whether the user terminal can handle VT sequences. */ void enableVTSequences(bool& handleVTSequences) { HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); if (hOut == INVALID_HANDLE_VALUE) { std::cerr << "Couldn't get the console handle. Quitting.\n" << std::endl; exit(EXIT_FAILURE); } DWORD dwMode = 0; if (!GetConsoleMode(hOut, &dwMode)) { std::cerr << "Unable to enter VT processing mode. Quitting.\n" << std::endl; exit(EXIT_FAILURE); } dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; if (!SetConsoleMode(hOut, dwMode)) { std::cerr << "Unable to enter VT processing mode. Quitting.\n" << std::endl; exit(EXIT_FAILURE); } handleVTSequences = true; } #else //If not on Windows, runs a simplifed function just for code reusability void enableVTSequences(bool& handleVTSequences) { handleVTSequences = true; } #endif /** * @brief Generates an ANSI escape code for the background or for the text based on the position * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color applies. * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * @return The ANSI escape code for the specified color either for the background or for the text. */ template <uint8_t position, uint8_t red, uint8_t green, uint8_t blue> string getColor(){ if (position == 1){ // TEXT return "\033[38;2;" + to_string(red) + ";" + to_string(green) + ";" + to_string(blue) + "m"; } else { // BACKGROUND return "\033[48;2;" + to_string(red) + ";" + to_string(green) + ";" + to_string(blue) + "m"; } } /** * @brief Applies a color to the given text based on the templates parameters * * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * * @param text The text to color. * * @return The colored text followed by the reset style. */ template <uint8_t red, uint8_t green, uint8_t blue> string colorText(const string& text) { const string color = getColor<1, red, green, blue>(); return color + text + RESET_STYLE; } /** * @brief Returns a color based on the templates parameters. * * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * @return The color calculated from the temlate parameters. */ template <uint8_t red, uint8_t green, uint8_t blue> string colorText() { const string color = getColor<1, red, green, blue>(); return color; } /** * @brief Applies a color for the background based on the templates parameters * * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * * @param text The text to color. * * @return The colored background followed by the reset style. */ template <uint8_t red, uint8_t green, uint8_t blue> string colorBackground(const string& text) { const string color = getColor<0, red, green, blue>(); return color + text + RESET_STYLE; } /** * @brief Returns a color for the background based on the templates parameters. * * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * * @param text The text to color. * * @return The colored text followed by the reset style. */ template <uint8_t red, uint8_t green, uint8_t blue> string colorBackground() { const string color = getColor<0, red, green, blue>(); return color; } /** * @brief Check if a given position is equal to TEXT (1) or to BACKGROUND (0), otherwise throws an error */ void checkPosition(uint8_t position){ if (position != 1 && position != 0) throw std::runtime_error("Position must be either 0 or 1"); } } constexpr uint8_t TEXT = 1; constexpr uint8_t BACKGROUND = 0; /** * @brief Returns the stream with the a color, specified from the template params, for the background or text. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color applies. * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * * @param os The stream to apply the color to. * * @return The modified stream. */ template <uint8_t position, uint8_t red, uint8_t green, uint8_t blue> ostream& color(ostream& os){ _private::checkPosition(position); if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); os << _private::getColor<position, red, green, blue>(); return os; } /** * @brief Applies the specified color, specified from the template params, to the text or background. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color applies. * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * * @param text The text to color. * * @return The modified text with the applied color. */ template <uint8_t position, uint8_t red, uint8_t green, uint8_t blue> string color(const string& text) { _private::checkPosition(position); if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); return position == TEXT ? _private::colorText<red, green, blue>(text) : _private::colorBackground<red, green, blue>(text); } /** * @brief Applies the specified color, specified from the template params, to the text. * * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * * @param text The text to color. * * @return The modified text with the applied color. */ template<uint8_t red, uint8_t green, uint8_t blue> string color(const string& text) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); return _private::colorText<red, green, blue>(text); } /** * @brief Applies to the stream the color specified from the template params. * * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * * @param os The stream to apply the color to. * * @return The modified stream. */ template<uint8_t red, uint8_t green, uint8_t blue> ostream& color(ostream& os) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); os << _private::colorBackground<red, green, blue>(); return os; } /** * @brief Applies the specified color, specified from the template params, to the background. * * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * * @param text The text to color. * * @return The modified text with the applied background color. */ template<uint8_t red, uint8_t green, uint8_t blue> string on_color(const string& text) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); return _private::colorText<red, green, blue>(text); } /** * @brief Applies to the stream the color specified from the template params. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color applies. * @tparam red Red component of the color (0-255). * @tparam green Green component of the color (0-255). * @tparam blue Blue component of the color (0-255). * * @param os The stream to apply the color to. * * @return The modified stream. */ template<uint8_t red, uint8_t green, uint8_t blue> ostream& on_color(ostream& os) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); os << _private::colorBackground<red, green, blue>(); return os; } // Functions for grey color /** * @brief Applies the color grey either for the background or for the text, based on the position * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color applies. * * @param os The stream to apply the color to. * * @return The modified stream. */ template<uint8_t position> ostream& grey(ostream& os){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); _private::checkPosition(position); os << ((position == TEXT) ? _private::color_text["grey"] : _private::color_background["grey"]); return os; } /** * @brief Applies the color grey either for the background or for the text, based on the position * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color applies. * * @param text The text to color. * * @return The modified text with the grey color. */ template<uint8_t position> string grey(const string& text) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); _private::checkPosition(position); const string grey = (position == TEXT) ? _private::color_text["grey"] : _private::color_background["grey"]; return grey + text + _private::RESET_STYLE; } /** * @brief Applies the color grey to the text * * @param text The text to color. * * @return The modified text with the grey color. */ string grey(const string& text) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); const string grey = _private::color_text["grey"]; return grey + text + _private::RESET_STYLE; } /** * @brief Applies the color grey to the text * * @param os The stream to apply the color to. * * @return The modified stream. */ ostream& grey(ostream& os){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); os << _private::color_text["grey"]; return os; } /** * @brief Applies the color grey to the background * * @param text The text to color. * * @return The modified text with the grey color. */ string on_grey(const string& text){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); const string grey = _private::color_background["grey"]; return grey + text + _private::RESET_STYLE; } /** * @brief Applies the color grey to the background * * @param os The stream to apply the color to. * * @return The modified stream. */ ostream& on_grey(ostream& os){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); os << _private::color_background["grey"]; return os; } // Functions for bright grey color /** * @brief Applies a bright grey color to the text or background based on the position. * * This function applies the bright grey color to the specified position (either text or background). * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the bright grey color applied. */ template<uint8_t position> ostream& bright_grey(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["bright grey"] : _private::color_background["bright grey"]); return os; } /** * @brief Applies a bright grey color to the text based on the position. * * This function applies the bright grey color to the specified position (either text or background). * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the bright grey color will be applied. * @return The modified text with the bright grey color applied. */ template<uint8_t position> string bright_grey(const string& text) { _private::checkPosition(position); const string bright_grey = (position == TEXT)? _private::color_text["bright grey"] : _private::color_background["bright grey"]; return bright_grey + text + _private::RESET_STYLE; } /** * @brief Applies a bright grey color to the text. * * This function applies the bright grey color to the text. * * @param text The text to which the bright grey color will be applied. * @return The modified text with the bright grey color applied. */ string bright_grey(const string& text) { const string bright_grey = _private::color_text["bright grey"]; return bright_grey + text + _private::RESET_STYLE; } /** * @brief Applies a bright grey color to the text. * * This function applies the bright grey color to the text. * * @param os The output stream to which the bright grey color will be applied. * @return The modified output stream with the bright grey color applied. */ ostream& bright_grey(ostream& os){ os << _private::color_text["bright grey"]; return os; } /** * @brief Applies a bright grey color to the background. * * This function applies the bright grey color to the background. * * @param text The text to which the bright grey color will be applied. * @return The modified text with the bright grey color applied. */ string on_bright_grey(const string& text){ const string bright_grey = _private::color_background["bright grey"]; return bright_grey + text + _private::RESET_STYLE; } /** * @brief Applies a bright grey color to the background. * * This function applies the bright grey color to the background. * * @param os The output stream to which the bright grey color will be applied. * @return The modified output stream with the bright grey color applied. */ ostream& on_bright_grey(ostream& os){ os << _private::color_background["bright grey"]; return os; } // Functions for red color /** * @brief Applies the red color to the text or background based on the position. * * This function applies the red color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the red color applied. */ template<uint8_t position> ostream& red(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["red"] : _private::color_background["red"]); return os; } /** * @brief Applies the red color to the text based on the position. * * This function applies the red color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the red color will be applied. * @return The modified text with the red color applied. */ template<uint8_t position> string red(const string& text) { _private::checkPosition(position); const string red = (position == TEXT)? _private::color_text["red"] : _private::color_background["red"]; return red + text + _private::RESET_STYLE; } /** * @brief Applies the red color to the text. * * This function applies the red color to the text. * * @param text The text to which the red color will be applied. * @return The modified text with the red color applied. */ string red(const string& text) { const string red = _private::color_text["red"]; return red + text + _private::RESET_STYLE; } /** * @brief Applies the red color to the text. * * This function applies the red color to the text. * * @param os The output stream to which the red color will be applied. * @return The modified output stream with the red color applied. */ ostream& red(ostream& os){ os << _private::color_text["red"]; return os; } /** * @brief Applies the red color to the background. * * This function applies the red color to the background. * * @param text The text to which the red color will be applied. * @return The modified text with the red color applied. */ string on_red(const string& text){ const string red = _private::color_background["red"]; return red + text + _private::RESET_STYLE; } /** * @brief Applies the red color to the background. * * This function applies the red color to the background. * * @param os The output stream to which the red color will be applied. * @return The modified output stream with the red color applied. */ ostream& on_red(ostream& os){ os << _private::color_background["red"]; return os; } // Functions for bright red color /** * @brief Applies the bright red color to the text or background based on the position. * * This function applies the bright red color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the bright red color applied. */ template<uint8_t position> ostream& bright_red(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["bright red"] : _private::color_background["bright red"]); return os; } /** * @brief Applies the bright red color to the text based on the position. * * This function applies the bright red color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the bright red color will be applied. * @return The modified text with the bright red color applied. */ template<uint8_t position> string bright_red(const string& text) { _private::checkPosition(position); const string bright_red = (position == TEXT)? _private::color_text["bright red"] : _private::color_background["bright red"]; return bright_red + text + _private::RESET_STYLE; } /** * @brief Applies the bright red color to the text. * * This function applies the bright red color to the text. * * @param text The text to which the bright red color will be applied. * @return The modified text with the bright red color applied. */ string bright_red(const string& text) { const string bright_red = _private::color_text["bright red"]; return bright_red + text + _private::RESET_STYLE; } /** * @brief Applies the bright red color to the text. * * This function applies the bright red color to the text. * * @param os The output stream to which the bright red color will be applied. * @return The modified output stream with the bright red color applied. */ ostream& bright_red(ostream& os){ os << _private::color_text["bright red"]; return os; } /** * @brief Applies the bright red color to the background. * * This function applies the bright red color to the background. * * @param text The text to which the bright red color will be applied. * @return The modified text with the bright red color applied. */ string on_bright_red(const string& text){ const string bright_red = _private::color_background["bright red"]; return bright_red + text + _private::RESET_STYLE; } /** * @brief Applies the bright red color to the background. * * This function applies the bright red color to the background. * * @param os The output stream to which the bright red color will be applied. * @return The modified output stream with the bright red color applied. */ ostream& on_bright_red(ostream& os){ os << _private::color_background["bright red"]; return os; } //Functions for the color green /** * @brief Applies the green color to the text or background based on the position. * * This function applies the green color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the green color applied. */ template<uint8_t position> ostream& green(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["green"] : _private::color_background["green"]); return os; } /** * @brief Applies the green color to the text based on the position. * * This function applies the green color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the green color will be applied. * @return The modified text with the green color applied. */ template<uint8_t position> string green(const string& text) { _private::checkPosition(position); const string green = (position == TEXT)? _private::color_text["green"] : _private::color_background["green"]; return green + text + _private::RESET_STYLE; } /** * @brief Applies the green color to the text. * * This function applies the green color to the text. * * @param text The text to which the green color will be applied. * @return The modified text with the green color applied. */ string green(const string& text) { const string green = _private::color_text["green"]; return green + text + _private::RESET_STYLE; } /** * @brief Applies the green color to the text. * * This function applies the green color to the text. * * @param os The output stream to which the green color will be applied. * @return The modified output stream with the green color applied. */ ostream& green(ostream& os){ os << _private::color_text["green"]; return os; } /** * @brief Applies the green color to the background. * * This function applies the green color to the background. * * @param text The text to which the green color will be applied. * @return The modified text with the green color applied. */ string on_green(const string& text){ const string green = _private::color_background["green"]; return green + text + _private::RESET_STYLE; } /** * @brief Applies the green color to the background. * * This function applies the green color to the background. * * @param os The output stream to which the green color will be applied. * @return The modified output stream with the green color applied. */ ostream& on_green(ostream& os){ os << _private::color_background["green"]; return os; } // Functions for bright green color /** * @brief Applies the bright green color to the text or background based on the position. * * This function applies the bright green color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the bright green color applied. */ template<uint8_t position> ostream& bright_green(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["bright green"] : _private::color_background["bright green"]); return os; } /** * @brief Applies the bright green color to the text based on the position. * * This function applies the bright green color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the bright green color will be applied. * @return The modified text with the bright green color applied. */ template<uint8_t position> string bright_green(const string& text) { _private::checkPosition(position); const string bright_green = (position == TEXT)? _private::color_text["bright green"] : _private::color_background["bright green"]; return bright_green + text + _private::RESET_STYLE; } /** * @brief Applies the bright green color to the text. * * This function applies the bright green color to the text. * * @param text The text to which the bright green color will be applied. * @return The modified text with the bright green color applied. */ string bright_green(const string& text) { const string bright_green = _private::color_text["bright green"]; return bright_green + text + _private::RESET_STYLE; } /** * @brief Applies the bright green color to the text. * * This function applies the bright green color to the text. * * @param os The output stream to which the bright green color will be applied. * @return The modified output stream with the bright green color applied. */ ostream& bright_green(ostream& os){ os << _private::color_text["bright green"]; return os; } /** * @brief Applies the bright green color to the background. * * This function applies the bright green color to the background. * * @param text The text to which the bright green color will be applied. * @return The modified text with the bright green color applied. */ string on_bright_green(const string& text){ const string bright_green = _private::color_background["bright green"]; return bright_green + text + _private::RESET_STYLE; } /** * @brief Applies the bright green color to the background. * * This function applies the bright green color to the background. * * @param os The output stream to which the bright green color will be applied. * @return The modified output stream with the bright green color applied. */ ostream& on_bright_green(ostream& os){ os << _private::color_background["bright green"]; return os; } // Functions for yellow color /** * @brief Applies the yellow color to the text or background based on the position. * * This function applies the yellow color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the yellow color applied. */ template<uint8_t position> ostream& yellow(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["yellow"] : _private::color_background["yellow"]); return os; } /** * @brief Applies the yellow color to the text based on the position. * * This function applies the yellow color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the yellow color will be applied. * @return The modified text with the yellow color applied. */ template<uint8_t position> string yellow(const string& text) { _private::checkPosition(position); const string yellow = (position == TEXT)? _private::color_text["yellow"] : _private::color_background["yellow"]; return yellow + text + _private::RESET_STYLE; } /** * @brief Applies the yellow color to the text. * * This function applies the yellow color to the text. * * @param text The text to which the yellow color will be applied. * @return The modified text with the yellow color applied. */ string yellow(const string& text) { const string yellow = _private::color_text["yellow"]; return yellow + text + _private::RESET_STYLE; } /** * @brief Applies the yellow color to the text. * * This function applies the yellow color to the text. * * @param os The output stream to which the yellow color will be applied. * @return The modified output stream with the yellow color applied. */ ostream& yellow(ostream& os){ os << _private::color_text["yellow"]; return os; } /** * @brief Applies the yellow color to the background. * * This function applies the yellow color to the background. * * @param text The text to which the yellow color will be applied. * @return The modified text with the yellow color applied. */ string on_yellow(const string& text){ const string yellow = _private::color_background["yellow"]; return yellow + text + _private::RESET_STYLE; } /** * @brief Applies the yellow color to the background. * * This function applies the yellow color to the background. * * @param os The output stream to which the yellow color will be applied. * @return The modified output stream with the yellow color applied. */ ostream& on_yellow(ostream& os){ os << _private::color_background["yellow"]; return os; } // Functions for bright yellow color /** * @brief Applies the bright yellow color to the text or background based on the position. * * This function applies the bright yellow color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the bright yellow color applied. */ template<uint8_t position> ostream& bright_yellow(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["bright yellow"] : _private::color_background["bright yellow"]); return os; } /** * @brief Applies the bright yellow color to the text based on the position. * * This function applies the bright yellow color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the bright yellow color will be applied. * @return The modified text with the bright yellow color applied. */ template<uint8_t position> string bright_yellow(const string& text) { _private::checkPosition(position); const string bright_yellow = (position == TEXT)? _private::color_text["bright yellow"] : _private::color_background["bright yellow"]; return bright_yellow + text + _private::RESET_STYLE; } /** * @brief Applies the bright yellow color to the text. * * This function applies the bright yellow color to the text. * * @param text The text to which the bright yellow color will be applied. * @return The modified text with the bright yellow color applied. */ string bright_yellow(const string& text) { const string bright_yellow = _private::color_text["bright yellow"]; return bright_yellow + text + _private::RESET_STYLE; } /** * @brief Applies the bright yellow color to the text. * * This function applies the bright yellow color to the text. * * @param os The output stream to which the bright yellow color will be applied. * @return The modified output stream with the bright yellow color applied. */ ostream& bright_yellow(ostream& os){ os << _private::color_text["bright yellow"]; return os; } /** * @brief Applies the bright yellow color to the background. * * This function applies the bright yellow color to the background. * * @param text The text to which the bright yellow color will be applied. * @return The modified text with the bright yellow color applied. */ string on_bright_yellow(const string& text){ const string bright_yellow = _private::color_background["bright yellow"]; return bright_yellow + text + _private::RESET_STYLE; } /** * @brief Applies the bright yellow color to the background. * * This function applies the bright yellow color to the background. * * @param os The output stream to which the bright yellow color will be applied. * @return The modified output stream with the bright yellow color applied. */ ostream& on_bright_yellow(ostream& os){ os << _private::color_background["bright yellow"]; return os; } // Functions for blue color /** * @brief Applies the blue color to the text or background based on the position. * * This function applies the blue color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the blue color applied. */ template<uint8_t position> ostream& blue(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["blue"] : _private::color_background["blue"]); return os; } /** * @brief Applies the blue color to the text based on the position. * * This function applies the blue color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the blue color will be applied. * @return The modified text with the blue color applied. */ template<uint8_t position> string blue(const string& text) { _private::checkPosition(position); const string blue = (position == TEXT)? _private::color_text["blue"] : _private::color_background["blue"]; return blue + text + _private::RESET_STYLE; } /** * @brief Applies the blue color to the text. * * This function applies the blue color to the text. * * @param text The text to which the blue color will be applied. * @return The modified text with the blue color applied. */ string blue(const string& text) { const string blue = _private::color_text["blue"]; return blue + text + _private::RESET_STYLE; } /** * @brief Applies the blue color to the text. * * This function applies the blue color to the text. * * @param os The output stream to which the blue color will be applied. * @return The modified output stream with the blue color applied. */ ostream& blue(ostream& os){ os << _private::color_text["blue"]; return os; } /** * @brief Applies the blue color to the background. * * This function applies the blue color to the background. * * @param text The text to which the blue color will be applied. * @return The modified text with the blue color applied. */ string on_blue(const string& text){ const string blue = _private::color_background["blue"]; return blue + text + _private::RESET_STYLE; } /** * @brief Applies the blue color to the background. * * This function applies the blue color to the background. * * @param os The output stream to which the blue color will be applied. * @return The modified output stream with the blue color applied. */ ostream& on_blue(ostream& os){ os << _private::color_background["blue"]; return os; } // Functions for bright blue color /** * @brief Applies the bright blue color to the text or background based on the position. * * This function applies the bright blue color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the bright blue color applied. */ template<uint8_t position> ostream& bright_blue(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["bright blue"] : _private::color_background["bright blue"]); return os; } /** * @brief Applies the bright blue color to the text based on the position. * * This function applies the bright blue color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the bright blue color will be applied. * @return The modified text with the bright blue color applied. */ template<uint8_t position> string bright_blue(const string& text) { _private::checkPosition(position); const string bright_blue = (position == TEXT)? _private::color_text["bright blue"] : _private::color_background["bright blue"]; return bright_blue + text + _private::RESET_STYLE; } /** * @brief Applies the bright blue color to the text. * * This function applies the bright blue color to the text. * * @param text The text to which the bright blue color will be applied. * @return The modified text with the bright blue color applied. */ string bright_blue(const string& text) { const string bright_blue = _private::color_text["bright blue"]; return bright_blue + text + _private::RESET_STYLE; } /** * @brief Applies the bright blue color to the text. * * This function applies the bright blue color to the text. * * @param os The output stream to which the bright blue color will be applied. * @return The modified output stream with the bright blue color applied. */ ostream& bright_blue(ostream& os){ os << _private::color_text["bright blue"]; return os; } /** * @brief Applies the bright blue color to the background. * * This function applies the bright blue color to the background. * * @param text The text to which the bright blue color will be applied. * @return The modified text with the bright blue color applied. */ string on_bright_blue(const string& text){ const string bright_blue = _private::color_background["bright blue"]; return bright_blue + text + _private::RESET_STYLE; } /** * @brief Applies the bright blue color to the background. * * This function applies the bright blue color to the background. * * @param os The output stream to which the bright blue color will be applied. * @return The modified output stream with the bright blue color applied. */ ostream& on_bright_blue(ostream& os){ os << _private::color_background["bright blue"]; return os; } // Functions for magenta color /** * @brief Applies the magenta color to the text or background based on the position. * * This function applies the magenta color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the magenta color applied. */ template<uint8_t position> ostream& magenta(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["magenta"] : _private::color_background["magenta"]); return os; } /** * @brief Applies the magenta color to the text based on the position. * * This function applies the magenta color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the magenta color will be applied. * @return The modified text with the magenta color applied. */ template<uint8_t position> string magenta(const string& text) { _private::checkPosition(position); const string magenta = (position == TEXT)? _private::color_text["magenta"] : _private::color_background["magenta"]; return magenta + text + _private::RESET_STYLE; } /** * @brief Applies the magenta color to the text. * * This function applies the magenta color to the text. * * @param text The text to which the magenta color will be applied. * @return The modified text with the magenta color applied. */ string magenta(const string& text) { const string magenta = _private::color_text["magenta"]; return magenta + text + _private::RESET_STYLE; } /** * @brief Applies the magenta color to the text. * * This function applies the magenta color to the text. * * @param os The output stream to which the magenta color will be applied. * @return The modified output stream with the magenta color applied. */ ostream& magenta(ostream& os){ os << _private::color_text["magenta"]; return os; } /** * @brief Applies the magenta color to the background. * * This function applies the magenta color to the background. * * @param text The text to which the magenta color will be applied. * @return The modified text with the magenta color applied. */ string on_magenta(const string& text){ const string magenta = _private::color_background["magenta"]; return magenta + text + _private::RESET_STYLE; } /** * @brief Applies the magenta color to the background. * * This function applies the magenta color to the background. * * @param os The output stream to which the magenta color will be applied. * @return The modified output stream with the magenta color applied. */ ostream& on_magenta(ostream& os){ os << _private::color_background["magenta"]; return os; } // Functions for bright magenta color /** * @brief Applies the bright magenta color to the text or background based on the position. * * This function applies the bright magenta color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the bright magenta color applied. */ template<uint8_t position> ostream& bright_magenta(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["bright magenta"] : _private::color_background["bright magenta"]); return os; } /** * @brief Applies the bright magenta color to the text based on the position. * * This function applies the bright magenta color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the bright magenta color will be applied. * @return The modified text with the bright magenta color applied. */ template<uint8_t position> string bright_magenta(const string& text) { _private::checkPosition(position); const string bright_magenta = (position == TEXT)? _private::color_text["bright magenta"] : _private::color_background["bright magenta"]; return bright_magenta + text + _private::RESET_STYLE; } /** * @brief Applies the bright magenta color to the text. * * This function applies the bright magenta color to the text. * * @param text The text to which the bright magenta color will be applied. * @return The modified text with the bright magenta color applied. */ string bright_magenta(const string& text) { const string bright_magenta = _private::color_text["bright magenta"]; return bright_magenta + text + _private::RESET_STYLE; } /** * @brief Applies the bright magenta color to the text. * * This function applies the bright magenta color to the text. * * @param os The output stream to which the bright magenta color will be applied. * @return The modified output stream with the bright magenta color applied. */ ostream& bright_magenta(ostream& os){ os << _private::color_text["bright magenta"]; return os; } /** * @brief Applies the bright magenta color to the background. * * This function applies the bright magenta color to the background. * * @param text The text to which the bright magenta color will be applied. * @return The modified text with the bright magenta color applied. */ string on_bright_magenta(const string& text){ const string bright_magenta = _private::color_background["bright magenta"]; return bright_magenta + text + _private::RESET_STYLE; } /** * @brief Applies the bright magenta color to the background. * * This function applies the bright magenta color to the background. * * @param os The output stream to which the bright magenta color will be applied. * @return The modified output stream with the bright magenta color applied. */ ostream& on_bright_magenta(ostream& os){ os << _private::color_background["bright magenta"]; return os; } // Functions for cyan color /** * @brief Applies the cyan color to the text or background based on the position. * * This function applies the cyan color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the cyan color applied. */ template<uint8_t position> ostream& cyan(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["cyan"] : _private::color_background["cyan"]); return os; } /** * @brief Applies the cyan color to the text based on the position. * * This function applies the cyan color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the cyan color will be applied. * @return The modified text with the cyan color applied. */ template<uint8_t position> string cyan(const string& text) { _private::checkPosition(position); const string cyan = (position == TEXT)? _private::color_text["cyan"] : _private::color_background["cyan"]; return cyan + text + _private::RESET_STYLE; } /** * @brief Applies the cyan color to the text. * * This function applies the cyan color to the text. * * @param text The text to which the cyan color will be applied. * @return The modified text with the cyan color applied. */ string cyan(const string& text) { const string cyan = _private::color_text["cyan"]; return cyan + text + _private::RESET_STYLE; } /** * @brief Applies the cyan color to the text. * * This function applies the cyan color to the text. * * @param os The output stream to which the cyan color will be applied. * @return The modified output stream with the cyan color applied. */ ostream& cyan(ostream& os){ os << _private::color_text["cyan"]; return os; } /** * @brief Applies the cyan color to the background. * * This function applies the cyan color to the background. * * @param text The text to which the cyan color will be applied. * @return The modified text with the cyan color applied. */ string on_cyan(const string& text){ const string cyan = _private::color_background["cyan"]; return cyan + text + _private::RESET_STYLE; } /** * @brief Applies the cyan color to the background. * * This function applies the cyan color to the background. * * @param os The output stream to which the cyan color will be applied. * @return The modified output stream with the cyan color applied. */ ostream& on_cyan(ostream& os){ os << _private::color_background["cyan"]; return os; } //Functions for bright cyan color /** * @brief Applies the bright cyan color to the text or background based on the position. * * This function applies the bright cyan color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the bright cyan color applied. */ template<uint8_t position> ostream& bright_cyan(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["bright cyan"] : _private::color_background["bright cyan"]); return os; } /** * @brief Applies the bright cyan color to the text based on the position. * * This function applies the bright cyan color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the bright cyan color will be applied. * @return The modified text with the bright cyan color applied. */ template<uint8_t position> string bright_cyan(const string& text) { _private::checkPosition(position); const string bright_cyan = (position == TEXT)? _private::color_text["bright cyan"] : _private::color_background["bright cyan"]; return bright_cyan + text + _private::RESET_STYLE; } /** * @brief Applies the bright cyan color to the text. * * This function applies the bright cyan color to the text. * * @param text The text to which the bright cyan color will be applied. * @return The modified text with the bright cyan color applied. */ string bright_cyan(const string& text) { const string bright_cyan = _private::color_text["bright cyan"]; return bright_cyan + text + _private::RESET_STYLE; } /** * @brief Applies the bright cyan color to the text. * * This function applies the bright cyan color to the text. * * @param os The output stream to which the bright cyan color will be applied. * @return The modified output stream with the bright cyan color applied. */ ostream& bright_cyan(ostream& os){ os << _private::color_text["bright cyan"]; return os; } /** * @brief Applies the bright cyan color to the background. * * This function applies the bright cyan color to the background. * * @param text The text to which the bright cyan color will be applied. * @return The modified text with the bright cyan color applied. */ string on_bright_cyan(const string& text){ const string bright_cyan = _private::color_background["bright cyan"]; return bright_cyan + text + _private::RESET_STYLE; } /** * @brief Applies the bright cyan color to the background. * * This function applies the bright cyan color to the background. * * @param os The output stream to which the bright cyan color will be applied. * @return The modified output stream with the bright cyan color applied. */ ostream& on_bright_cyan(ostream& os){ os << _private::color_background["bright cyan"]; return os; } // Functions for white color /** * @brief Applies the white color to the text or background based on the position. * * This function applies the white color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the white color applied. */ template<uint8_t position> ostream& white(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["white"] : _private::color_background["white"]); return os; } /** * @brief Applies the white color to the text based on the position. * * This function applies the white color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the white color will be applied. * @return The modified text with the white color applied. */ template<uint8_t position> string white(const string& text) { _private::checkPosition(position); const string white = (position == TEXT)? _private::color_text["white"] : _private::color_background["white"]; return white + text + _private::RESET_STYLE; } /** * @brief Applies the white color to the text. * * This function applies the white color to the text. * * @param text The text to which the white color will be applied. * @return The modified text with the white color applied. */ string white(const string& text) { const string white = _private::color_text["white"]; return white + text + _private::RESET_STYLE; } /** * @brief Applies the white color to the text. * * This function applies the white color to the text. * * @param os The output stream to which the white color will be applied. * @return The modified output stream with the white color applied. */ ostream& white(ostream& os){ os << _private::color_text["white"]; return os; } /** * @brief Applies the white color to the background. * * This function applies the white color to the background. * * @param text The text to which the white color will be applied. * @return The modified text with the white color applied. */ string on_white(const string& text){ const string white = _private::color_background["white"]; return white + text + _private::RESET_STYLE; } /** * @brief Applies the white color to the background. * * This function applies the white color to the background. * * @param os The output stream to which the white color will be applied. * @return The modified output stream with the white color applied. */ ostream& on_white(ostream& os){ os << _private::color_background["white"]; return os; } //Functions for bright white color /** * @brief Applies the bright white color to the text or background based on the position. * * This function applies the bright white color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param os The output stream to which the color will be applied. * @return The modified output stream with the bright white color applied. */ template<uint8_t position> ostream& bright_white(ostream& os){ _private::checkPosition(position); os << ((position == TEXT)? _private::color_text["bright white"] : _private::color_background["bright white"]); return os; } /** * @brief Applies the bright white color to the text based on the position. * * This function applies the bright white color to the specified position (either text or background), * depending on the value of the position parameter. * * @tparam position Either TEXT (1) or BACKGROUND (0), indicating where the color should be applied. * @param text The text to which the bright white color will be applied. * @return The modified text with the bright white color applied. */ template<uint8_t position> string bright_white(const string& text) { _private::checkPosition(position); const string bright_white = (position == TEXT)? _private::color_text["bright white"] : _private::color_background["bright white"]; return bright_white + text + _private::RESET_STYLE; } /** * @brief Applies the bright white color to the text. * * This function applies the bright white color to the text. * * @param text The text to which the bright white color will be applied. * @return The modified text with the bright white color applied. */ string bright_white(const string& text) { const string bright_white = _private::color_text["bright white"]; return bright_white + text + _private::RESET_STYLE; } /** * @brief Applies the bright white color to the text. * * This function applies the bright white color to the text. * * @param os The output stream to which the bright white color will be applied. * @return The modified output stream with the bright white color applied. */ ostream& bright_white(ostream& os){ os << _private::color_text["bright white"]; return os; } /** * @brief Applies the bright white color to the background. * * This function applies the bright white color to the background. * * @param text The text to which the bright white color will be applied. * @return The modified text with the bright white color applied. */ string on_bright_white(const string& text){ const string bright_white = _private::color_background["bright white"]; return bright_white + text + _private::RESET_STYLE; } /** * @brief Applies the bright white color to the background. * * This function applies the bright white color to the background. * * @param os The output stream to which the bright white color will be applied. * @return The modified output stream with the bright white color applied. */ ostream& on_bright_white(ostream& os){ os << _private::color_background["bright white"]; return os; } //Functions for bold style /** * @brief Applies bold style to the stream. * * @param os The stream to apply the bold style to. * * @return The modified stream. */ ostream& bold(ostream& os){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); return os << "\033[1m"; } /** * @brief Applies bold style to the text. * * @param text The text to apply the bold style to. * * @return The modified text with bold style applied. */ string bold(const string& text) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); const string bold = "\033[1m"; return bold + text + _private::RESET_STYLE; } //Functions for italic style /** * @brief Applies italic style to the stream. * * @param os The stream to apply the italic style to. * * @return The modified stream. */ ostream& italic(ostream& os){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); return os << "\033[3m"; } /** * @brief Applies italic style to the text. * * @param text The text to apply the italic style to. * * @return The modified text with italic style applied. */ string italic(const string& text) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); const string italic = "\033[3m"; return italic + text + _private::RESET_STYLE; } //Functions for underline style /** * @brief Applies underline style to the stream. * * @param os The stream to apply the underline style to. * * @return The modified stream. */ ostream& underline(ostream& os){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); return os << "\033[4m"; } /** * @brief Applies underline style to the text. * * @param text The text to apply the underline style to. * * @return The modified text with underline style applied. */ string underline(const string& text) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); const string underline = "\033[4m"; return underline + text + _private::RESET_STYLE; } //Functions for reverse style /** * @brief Applies reverse style to the stream. * * @param os The stream to apply the reverse style to. * * @return The modified stream. */ ostream& reverse(ostream& os){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); return os << "\033[7m"; } /** * @brief Applies reverse style to the text. * * @param text The text to apply the reverse style to. * * @return The modified text with reverse style applied. */ string reverse(const string& text) { if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); const string reverse = "\033[7m"; return reverse + text + _private::RESET_STYLE; } //Functions for reset style /** * @brief Resets the stream to the default style. * * @param os The stream to reset. * @return The modified stream with the default style. */ ostream& reset(ostream& os){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); os << _private::RESET_STYLE; return os; } /** * @brief Resets the text to the default style. * * @param text The text to reset. * @return The modified text with the default style. */ string reset(const string& text){ if (!_private::handleVTSequences) _private::enableVTSequences(_private::handleVTSequences); return text + _private::RESET_STYLE; } } // int main() { // cout << CLIStyle::grey<1>("grey") << endl; // cout << CLIStyle::red<1>("red") << endl; // cout << CLIStyle::green<1>("green") << endl; // cout << CLIStyle::yellow<1>("yellow") << endl; // cout << CLIStyle::blue<1>("blue") << endl; // cout << CLIStyle::magenta<1>("magenta") << endl; // cout << CLIStyle::cyan<1>("cyan") << endl; // cout << CLIStyle::white<1>("white") << endl; // cout << CLIStyle::bright_red<1>("bright red") << endl; // cout << CLIStyle::bright_green<1>("bright green") << endl; // cout << CLIStyle::bright_yellow<1>("bright yellow") << endl; // cout << CLIStyle::bright_blue<1>("bright blue") << endl; // cout << CLIStyle::bright_magenta<1>("bright magenta") << endl; // cout << CLIStyle::bright_cyan<1>("bright cyan") << endl; // cout << CLIStyle::bright_white<1>("bright white") << endl; // cout << CLIStyle::grey<0>("grey") << endl; // cout << CLIStyle::red<0>("red") << endl; // cout << CLIStyle::green<0>("green") << endl; // cout << CLIStyle::yellow<0>("yellow") << endl; // cout << CLIStyle::blue<0>("blue") << endl; // cout << CLIStyle::magenta<0>("magenta") << endl; // cout << CLIStyle::cyan<0>("cyan") << endl; // cout << CLIStyle::white<0>("white") << endl; // cout << CLIStyle::bright_red<0>("bright red") << endl; // cout << CLIStyle::bright_green<0>("bright green") << endl; // cout << CLIStyle::bright_yellow<0>("bright yellow") << endl; // cout << CLIStyle::bright_blue<0>("bright blue") << endl; // cout << CLIStyle::bright_magenta<0>("bright magenta") << endl; // cout << CLIStyle::bright_cyan<0>("bright cyan") << endl; // cout << CLIStyle::bright_white<0>("bright white") << endl; // cout << CLIStyle::bold("bold") << endl; // cout << CLIStyle::underline("underline") << endl; // cout << CLIStyle::italic("italic") << endl; // cout << CLIStyle::reverse("reverse") << endl; // return 0; // } //add 256 color codes
/* eslint-disable react-hooks/exhaustive-deps */ import React, { createContext, useCallback, useContext, useEffect, useMemo, useState, } from 'react'; import useCurrentUser from '@/hooks/useCurrentUser'; import useLocalStorage from '@/hooks/useLocalStorage'; import { CartInitialValues, CartItem } from '@/interfaces/cart'; interface Props { children: React.ReactNode; } const initialState: CartInitialValues = { cartItems: [], subTotal: 0, addToCart: () => null, onUpdateItem: () => null, onDeleteItem: () => null, }; const CartContext = createContext(initialState); export default function CartProvider({ children }: Props) { const [cartItems, setCartItems] = useState<CartItem[]>([]); const [subTotal, setSubTotal] = useState(0); const { user } = useCurrentUser(); const { getItemsFromStorage, setItemsToStorage } = useLocalStorage(); const calculateSubTotal = useCallback((items: CartItem[]) => { const totalPrices = items.reduce( (acc, item) => acc + item.quantity * item.product.price, 0 ); setSubTotal(totalPrices); }, []); useEffect(() => { if (user) { const items = getItemsFromStorage().length > 0 ? getItemsFromStorage() : (user?.cart as CartItem[]); setItemsToStorage(items); setCartItems(items); calculateSubTotal(items); } else { const items = getItemsFromStorage(); setCartItems(items); calculateSubTotal(items); } }, [user]); const handleUpdateItem = useCallback( (quantity: number, productId: string) => { // TODO: find a nice and more efficient way to do this!!! const cartItem = cartItems.find((item) => item.product.id === productId); const items = cartItems.filter((item) => item.product.id !== productId); const newCartItems = [...items, { ...cartItem!, quantity }]; calculateSubTotal(newCartItems); setCartItems(newCartItems); setItemsToStorage(newCartItems); }, [cartItems] ); const handleAddToCart = useCallback( (item: CartItem) => { const foundItem = cartItems.find( ({ product }) => product.id === item.product.id ); let newCartItems: CartItem[] = []; if (!foundItem) { newCartItems = [...cartItems, item]; } else { newCartItems = cartItems.map((cartItem) => { if (cartItem.product.id === foundItem.product.id) { return { ...cartItem, quantity: cartItem.quantity + 1 }; } return cartItem; }); } calculateSubTotal(newCartItems); setCartItems(newCartItems); setItemsToStorage(newCartItems); }, [cartItems, subTotal] ); const handleDeleteItem = (productId: string) => { const newCartItems = cartItems.filter( ({ product }) => product.id !== productId ); setCartItems(newCartItems); calculateSubTotal(newCartItems); setItemsToStorage(newCartItems); }; const value = useMemo( () => ({ cartItems, subTotal, addToCart: handleAddToCart, onUpdateItem: handleUpdateItem, onDeleteItem: handleDeleteItem, }), [cartItems, subTotal] ); return <CartContext.Provider value={value}>{children}</CartContext.Provider>; } export const useCartItems = () => useContext(CartContext);
import Button from './Button'; import HomeIcon from './HomeIcon'; import PlusIcon from './PlusIcon'; function App() { return ( <div id="app"> <section> <h2>Filled Button (Default)</h2> <p> <Button>Default</Button> </p> <p> <Button mode="filled">Filled (Default)</Button> </p> </section> <section> <h2>Button with Outline</h2> <p> <Button mode="outline">Outline</Button> </p> </section> <section> <h2>Text-only Button</h2> <p> <Button mode="text">Text</Button> </p> </section> <section> <h2>Button with Icon</h2> <p> <Button Icon={HomeIcon}>Home</Button> </p> <p> <Button Icon={PlusIcon} mode="text"> Add </Button> </p> </section> <section> <h2>Buttons Should Support Any Props</h2> <p> <Button mode="filled" disabled> Disabled </Button> </p> <p> <Button onClick={() => console.log('Clicked!')}>Click me</Button> </p> </section> </div> ); } export default App; /* there are only three different types of buttons here: filled, outline, and text-only. the right strategy to choose names for the css classes is to choose the names in way that we can later on use them dynamically via string interpolation. (Button.jsx) --> string interpolation: let cssClasses = `button ${mode}-button`; and the classNames are: button filled-button, button outline-button, button text-button */
""" This makes the test configuration setup """ # pylint: disable=redefined-outer-name import os import pytest from app import create_app, User from app.db import db @pytest.fixture() def application(): """This makes the appplication itself""" os.environ['FLASK_ENV'] = 'testing' application = create_app() with application.app_context(): db.create_all() yield application db.session.remove() # Drop the database tables after the test runs, ensuring that any records made are deleted db.drop_all() return application @pytest.fixture() def add_user(application): """ Adding a user to the application's database """ with application.app_context(): # New record, username, password and not admin user = User('keith@webizly.com', 'testtest', 0) db.session.add(user) db.session.commit() @pytest.fixture() def client(application): """ This makes the http client """ return application.test_client() @pytest.fixture() def runner(application): """ This makes the task runner """ return application.test_cli_runner()
--- permalink: expansion/task_updating_lun_paths_for_new_nodes.html sidebar: sidebar keywords: cluster, configure, san, lif, add, update, path, lun, node, update lun paths for the new nodes summary: Si le cluster est configuré pour SAN, vous devez créer des LIF SAN sur les nouveaux nœuds ajoutés, puis mettre à jour les chemins. --- = Mettre à jour les chemins de LUN pour les nouveaux nœuds :allow-uri-read: :icons: font :imagesdir: ../media/ [role="lead"] Si le cluster est configuré pour SAN, vous devez créer des LIF SAN sur les nouveaux nœuds ajoutés, puis mettre à jour les chemins. .Description de la tâche Cette procédure est requise uniquement si le cluster contient des LUN. Si le cluster ne contient que des fichiers, vous pouvez ignorer cette procédure. .Étapes . Pour chaque SVM (Storage Virtual machine) du cluster, créez de nouvelles LIF sur les nouveaux nœuds : + .. Identifier les SVM qui utilisent les protocoles FC ou iSCSI à l'aide du `vserver show` commande avec `-fields allowed-protocols` paramètre et vérification de la sortie. + [listing] ---- cluster1::> vserver show -fields allowed-protocols vserver allowed-protocols ------- ----------------- vs1 cifs,ndmp vs2 fcp vs3 iscsi ... ---- .. Pour chaque SVM qui utilise FC ou iSCSI, créez au moins deux LIF de données sur chacun des nouveaux nœuds ajoutés en utilisant le `network interface create` commande avec `-role data` paramètre. + [listing] ---- cluster1::> network interface create -vserver vs1 -lif lif5 -role data -data-protocol iscsi -home-node cluster1-3 -home-port e0b -address 192.168.2.72 -netmask 255.255.255.0 ---- .. Pour chaque SVM, vérifier qu'il possède des LIF sur tous les nœuds du cluster à l'aide de `network interface show` commande avec `-vserver` paramètre. . Mettre à jour les ensembles de ports : + .. Déterminez si des ensembles de ports existent à l'aide du `lun portset show` commande. .. Si vous souhaitez que les nouvelles LIF soient visibles pour les hôtes existants, ajoutez chaque nouvelle LIF aux ensembles de ports à l'aide de la `lun portset add` Commande--une fois pour chaque LIF. . Si vous utilisez FC ou FCoE, mettez à jour la segmentation : + .. Vérifiez que la segmentation est correctement configurée pour permettre aux ports initiateurs sur l'hôte de se connecter aux nouveaux ports cibles sur les nouveaux nœuds. .. Mettez à jour la segmentation du commutateur pour connecter les nouveaux nœuds aux initiateurs existants. + La configuration de la segmentation varie en fonction du commutateur que vous utilisez. .. Si vous prévoyez de déplacer des LUN vers les nouveaux nœuds, exposez les nouveaux chemins d'accès aux hôtes à l'aide de `lun mapping add-reporting-nodes` commande. . Sur tous les systèmes d'exploitation hôtes, effectuez une nouvelle analyse pour découvrir les nouveaux chemins ajoutés. . En fonction des systèmes d'exploitation hôtes, supprimez les chemins obsolètes. . Ajoutez ou supprimez des chemins d'accès à votre configuration MPIO. *Informations connexes* https://docs.netapp.com/us-en/ontap/san-config/index.html["Configuration SAN"^] https://docs.netapp.com/us-en/ontap/san-admin/index.html["Administration SAN"^]
import React from 'react'; import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import UserSignupForm from '../components/Authentication/UserSignupForm'; import { BrowserRouter } from 'react-router-dom'; global.fetch = jest.fn(); beforeEach(() => { global.fetch.mockClear(); }); const renderUserSignupForm = () => render( <BrowserRouter> <UserSignupForm /> </BrowserRouter> ); describe('UserSignupForm', () => { test('input fields are rendered', () => { renderUserSignupForm(); expect(screen.getByLabelText(/first name/i)).toBeInTheDocument(); expect(screen.getByLabelText(/last name/i)).toBeInTheDocument(); expect(screen.getByLabelText(/email address/i)).toBeInTheDocument(); expect(screen.getByLabelText(/phone number/i)).toBeInTheDocument(); expect(screen.getByTestId('passwordInput')).toBeInTheDocument(); expect(screen.getByTestId('confirmPasswordInput')).toBeInTheDocument(); }); test('displays error for invalid email format', async () => { renderUserSignupForm(); fireEvent.change(screen.getByLabelText(/email address/i), { target: { value: 'invalidemail' } }); fireEvent.blur(screen.getByLabelText(/email address/i)); expect(await screen.findByText(/invalid email format/i)).toBeInTheDocument(); }); test('submit button is disabled when form is incomplete or invalid', () => { renderUserSignupForm(); expect(screen.getByRole('button', { name: /register/i })).toBeDisabled(); }); test('submit button is enabled when form inputs are valid', async () => { renderUserSignupForm(); fireEvent.change(screen.getByLabelText(/first name/i), { target: { value: 'John' } }); fireEvent.change(screen.getByLabelText(/last name/i), { target: { value: 'Doe' } }); fireEvent.change(screen.getByLabelText(/email address/i), { target: { value: 'test@example.com' } }); fireEvent.change(screen.getByLabelText(/phone number/i), { target: { value: '1234567890' } }); fireEvent.change(screen.getByTestId('passwordInput'), { target: { value: 'password123' } }); fireEvent.change(screen.getByTestId('confirmPasswordInput'), { target: { value: 'password123' } }); expect(screen.getByRole('button', { name: /register/i })).not.toBeDisabled(); }); test('shows success message on successful registration', async () => { global.fetch.mockResolvedValueOnce({ ok: true, json: async () => ({ String: "Signup successful! You can now login." }), }); renderUserSignupForm(); fireEvent.change(screen.getByLabelText(/first name/i), { target: { value: 'John' } }); fireEvent.change(screen.getByLabelText(/last name/i), { target: { value: 'Doe' } }); fireEvent.change(screen.getByLabelText(/email address/i), { target: { value: 'test@example.com' } }); fireEvent.change(screen.getByLabelText(/phone number/i), { target: { value: '1234567890' } }); fireEvent.change(screen.getByTestId('passwordInput'), { target: { value: 'password123' } }); fireEvent.change(screen.getByTestId('confirmPasswordInput'), { target: { value: 'password123' } }); const signupForm = screen.getByTestId('user-signup-form'); fireEvent.submit(signupForm); //fireEvent.submit(screen.getByRole('form')); await waitFor(() => { expect(screen.getByText(/signup successful!/i)).toBeInTheDocument(); }); }); test('shows failure message on failed registration', async () => { global.fetch.mockResolvedValueOnce({ ok: false, json: async () => ({ String: "An error occurred. Please try again." }), }); renderUserSignupForm(); fireEvent.change(screen.getByLabelText(/first name/i), { target: { value: 'John' } }); fireEvent.change(screen.getByLabelText(/last name/i), { target: { value: 'Doe' } }); fireEvent.change(screen.getByLabelText(/email address/i), { target: { value: 'test@example.com' } }); fireEvent.change(screen.getByLabelText(/phone number/i), { target: { value: '1234567890' } }); fireEvent.change(screen.getByTestId('passwordInput'), { target: { value: 'password123' } }); fireEvent.change(screen.getByTestId('confirmPasswordInput'), { target: { value: '123' } }); const signupForm = screen.getByTestId('user-signup-form'); fireEvent.submit(signupForm); await waitFor(() => { expect(screen.getByText(/an error occurred/i)).toBeInTheDocument(); }); }); });
export declare interface AccessAttributeNode extends BaseNode { type: 'AccessAttribute' base?: ExprNode name: string } export declare interface AccessElementNode extends BaseNode { type: 'AccessElement' base: ExprNode index: number } export declare interface AndNode extends BaseNode { type: 'And' left: ExprNode right: ExprNode } export declare type AnyStaticValue = | StringValue | NumberValue | NullValue | BooleanValue | DateTimeValue | ObjectValue | ArrayValue | PathValue export declare interface ArrayCoerceNode extends BaseNode { type: 'ArrayCoerce' base: ExprNode } export declare interface ArrayElementNode extends BaseNode { type: 'ArrayElement' value: ExprNode isSplat: boolean } export declare interface ArrayNode extends BaseNode { type: 'Array' elements: ArrayElementNode[] } /** Describes a type node for array values. */ export declare interface ArrayTypeNode<T extends TypeNode = TypeNode> { /** can be used to identify the type of the node, in this case it's always 'array' */ type: 'array' /** the type of the array elements */ of: T } export declare type ArrayValue = StaticValue<unknown[], 'array'> export declare interface AscNode extends BaseNode { type: 'Asc' base: ExprNode } /** The base interface for SyntaxNode. */ export declare interface BaseNode { type: string } /** Describes a type node for boolean values, optionally including a value. If a value is provided it will always be the given boolean value. */ export declare interface BooleanTypeNode { /** can be used to identify the type of the node, in this case it's always 'boolean' */ type: 'boolean' /** an optional value of the boolean, if provided it will always be the given boolean value */ value?: boolean } export declare type BooleanValue = StaticValue<boolean, 'boolean'> export declare interface Context { timestamp: Date identity: string before: Value | null after: Value | null sanity?: { projectId: string dataset: string } dereference?: DereferenceFunction } export declare interface ContextNode extends BaseNode { type: 'Context' key: string } /** * createReferenceTypeNode creates a ObjectTypeNode representing a reference type * it adds required attributes for a reference type. * @param name - The name of the reference type * @param inArray - Whether the reference is in an array * @returns A ObjectTypeNode representing a reference type * @internal */ export declare function createReferenceTypeNode(name: string, inArray?: boolean): ObjectTypeNode export declare class DateTime { date: Date constructor(date: Date) static parseToValue(str: string): Value equals(other: DateTime): boolean add(secs: number): DateTime difference(other: DateTime): number compareTo(other: DateTime): number toString(): string toJSON(): string } export declare type DateTimeValue = StaticValue<DateTime, 'datetime'> export declare type DereferenceFunction = (obj: { _ref: string }) => PromiseLike<Document_2 | null | undefined> export declare interface DerefNode extends BaseNode { type: 'Deref' base: ExprNode } export declare interface DescNode extends BaseNode { type: 'Desc' base: ExprNode } declare type Document_2 = { _id?: string _type?: string [T: string]: unknown } export {Document_2 as Document} /** Represents a document structure with a fixed type 'document', a name, and a collection of attributes.*/ export declare interface DocumentSchemaType { /** can be used to identify the type of the node, in this case it's always 'document' */ type: 'document' /** the name of the document */ name: string /** ttributes is defined by a key-value pair where the key is a string and the value is an ObjectAttribute. */ attributes: Record<string, ObjectAttribute> } /** * Evaluates a query. */ export declare function evaluate( tree: ExprNode, options?: EvaluateOptions, ): Value | PromiseLike<Value> export declare interface EvaluateOptions { root?: any dataset?: any params?: Record<string, unknown> timestamp?: Date identity?: string before?: any after?: any sanity?: { projectId: string dataset: string } dereference?: DereferenceFunction } export declare interface EverythingNode extends BaseNode { type: 'Everything' } export declare type Executor<N = ExprNode> = (node: N, scope: Scope) => Value | PromiseLike<Value> /** A node which can be evaluated into a value. */ export declare type ExprNode = | AccessAttributeNode | AccessElementNode | AndNode | ArrayNode | ArrayCoerceNode | AscNode | ContextNode | DerefNode | DescNode | EverythingNode | FilterNode | FlatMapNode | FuncCallNode | GroupNode | InRangeNode | MapNode | NegNode | NotNode | ObjectNode | OpCallNode | OrNode | ParameterNode | ParentNode_2 | PipeFuncCallNode | PosNode | ProjectionNode | SelectNode | SelectorNode | SliceNode | ThisNode | TupleNode | ValueNode export declare interface FilterNode extends BaseNode { type: 'Filter' base: ExprNode expr: ExprNode } export declare interface FlatMapNode extends BaseNode { type: 'FlatMap' base: ExprNode expr: ExprNode } export declare interface FuncCallNode extends BaseNode { type: 'FuncCall' func: GroqFunction namespace: string name: string args: ExprNode[] } export declare type GroqFunction = ( args: GroqFunctionArg[], scope: Scope, execute: Executor, ) => PromiseLike<Value> export declare type GroqFunctionArg = ExprNode export declare type GroqPipeFunction = ( base: Value, args: ExprNode[], scope: Scope, execute: Executor, ) => PromiseLike<Value> /** * A type of a value in GROQ. */ export declare type GroqType = | 'null' | 'boolean' | 'number' | 'string' | 'array' | 'object' | 'path' | 'datetime' export declare interface GroupNode extends BaseNode { type: 'Group' base: ExprNode } /** Describes a type node for inline values, including a name that references another type. */ export declare interface InlineTypeNode { /** can be used to identify the type of the node, in this case it's always 'inline' */ type: 'inline' /** the name of the referenced type */ name: string } export declare interface InRangeNode extends BaseNode { type: 'InRange' base: ExprNode left: ExprNode right: ExprNode isInclusive: boolean } export declare interface MapNode extends BaseNode { type: 'Map' base: ExprNode expr: ExprNode } export declare interface NegNode extends BaseNode { type: 'Neg' base: ExprNode } export declare interface NotNode extends BaseNode { type: 'Not' base: ExprNode } /** Describes a type node for null values, always being the null value. */ export declare interface NullTypeNode { /** can be used to identify the type of the node, in this case it's always 'null' */ type: 'null' } export declare type NullValue = StaticValue<null, 'null'> /** Describes a type node for number values, optionally including a value. If a value is provided it will always be the given numeric value.*/ export declare interface NumberTypeNode { /** can be used to identify the type of the node, in this case it's always 'number' */ type: 'number' /** an optional value of the number, if provided it will always be the given numeric value */ value?: number } export declare type NumberValue = StaticValue<number, 'number'> /** Describes a type node for object attributes, including a type and an optional flag for being optional. */ export declare interface ObjectAttribute<T extends TypeNode = TypeNode> { /** can be used to identify the type of the node, in this case it's always 'objectAttribute' */ type: 'objectAttribute' /** the type of the attribute */ value: T /** an optional flag if the attribute is optional set on the object */ optional?: boolean } export declare type ObjectAttributeNode = | ObjectAttributeValueNode | ObjectConditionalSplatNode | ObjectSplatNode export declare interface ObjectAttributeValueNode extends BaseNode { type: 'ObjectAttributeValue' name: string value: ExprNode } export declare interface ObjectConditionalSplatNode extends BaseNode { type: 'ObjectConditionalSplat' condition: ExprNode value: ExprNode } export declare interface ObjectNode extends BaseNode { type: 'Object' attributes: ObjectAttributeNode[] } export declare interface ObjectSplatNode extends BaseNode { type: 'ObjectSplat' value: ExprNode } /** * Describes a type node for object values, including a collection of attributes and an optional rest value. * The rest value can be another ObjectTypeNode, an UnknownTypeNode, or an InlineTypeNode. * If the rest value is an ObjectTypeNode, it means that the object can have additional attributes. * If the rest value is an UnknownTypeNode, the entire object is unknown. * If the rest value is an InlineTypeNode, it means that the object has additional attributes from the referenced type. */ export declare interface ObjectTypeNode<T extends TypeNode = TypeNode> { /** can be used to identify the type of the node, in this case it's always 'object' */ type: 'object' /** a collection of attributes */ attributes: Record<string, ObjectAttribute<T>> /** an optional rest value */ rest?: ObjectTypeNode | UnknownTypeNode | InlineTypeNode dereferencesTo?: string } export declare type ObjectValue = StaticValue<Record<string, unknown>, 'object'> export declare type OpCall = | '==' | '!=' | '>' | '>=' | '<' | '<=' | '+' | '-' | '*' | '/' | '%' | '**' | 'in' | 'match' export declare interface OpCallNode extends BaseNode { type: 'OpCall' op: OpCall left: ExprNode right: ExprNode } export declare interface OrNode extends BaseNode { type: 'Or' left: ExprNode right: ExprNode } export declare interface ParameterNode extends BaseNode { type: 'Parameter' name: string } declare interface ParentNode_2 extends BaseNode { type: 'Parent' n: number } export {ParentNode_2 as ParentNode} /** * Parses a GROQ query and returns a tree structure. */ export declare function parse(input: string, options?: ParseOptions): ExprNode export declare interface ParseOptions { params?: Record<string, unknown> mode?: 'normal' | 'delta' } export declare class Path { private pattern private patternRe constructor(pattern: string) matches(str: string): boolean toJSON(): string } export declare type PathValue = StaticValue<Path, 'path'> export declare interface PipeFuncCallNode extends BaseNode { type: 'PipeFuncCall' func: GroqPipeFunction base: ExprNode name: string args: ExprNode[] } export declare interface PosNode extends BaseNode { type: 'Pos' base: ExprNode } /** Union of any primitive type nodes. */ export declare type PrimitiveTypeNode = StringTypeNode | NumberTypeNode | BooleanTypeNode export declare interface ProjectionNode extends BaseNode { type: 'Projection' base: ExprNode expr: ExprNode } /** A schema consisting of a list of Document or TypeDeclaration items, allowing for complex type definitions. */ export declare type SchemaType = (DocumentSchemaType | TypeDeclarationSchemaType)[] export declare class Scope { params: Record<string, unknown> source: Value value: Value parent: Scope | null context: Context isHidden: boolean constructor( params: Record<string, unknown>, source: Value, value: Value, context: Context, parent: Scope | null, ) createNested(value: Value): Scope createHidden(value: Value): Scope } export declare interface SelectAlternativeNode extends BaseNode { type: 'SelectAlternative' condition: ExprNode value: ExprNode } export declare interface SelectNode extends BaseNode { type: 'Select' alternatives: SelectAlternativeNode[] fallback?: ExprNode } export declare interface SelectorNode extends BaseNode { type: 'Selector' } export declare interface SliceNode extends BaseNode { type: 'Slice' base: ExprNode left: number right: number isInclusive: boolean } export declare class StaticValue<P, T extends GroqType> { data: P type: T constructor(data: P, type: T) isArray(): boolean get(): Promise<any> [Symbol.asyncIterator](): Generator<Value, void, unknown> } export declare class StreamValue { type: 'stream' private generator private ticker private isDone private data constructor(generator: () => AsyncGenerator<Value, void, unknown>) isArray(): boolean get(): Promise<any> [Symbol.asyncIterator](): AsyncGenerator<Value, void, unknown> _nextTick(): Promise<void> } /** Describes a type node for string values, optionally including a value. If a value is provided it will always be the given string value. */ export declare interface StringTypeNode { /** can be used to identify the type of the node, in this case it's always 'string' */ type: 'string' /** an optional value of the string, if provided it will always be the given string value */ value?: string } export declare type StringValue = StaticValue<string, 'string'> /** Any sort of node which appears as syntax */ export declare type SyntaxNode = | ExprNode | ArrayElementNode | ObjectAttributeNode | SelectAlternativeNode export declare interface ThisNode extends BaseNode { type: 'This' } export declare interface TupleNode extends BaseNode { type: 'Tuple' members: Array<ExprNode> } /** Defines a type declaration with a specific name and a value that describes the structure of the type using a TypeNode. */ export declare interface TypeDeclarationSchemaType { /** can be used to identify the type of the node, in this case it's always 'type' */ type: 'type' /** the name of the type */ name: string /** the value that describes the structure of the type */ value: TypeNode } /** * Evaluates the type of a query and schema. * * @param ast - The query ast to evaluate. * @param schema - The schemas to use for type evaluation. * @returns The type of the query. * @beta */ export declare function typeEvaluate(ast: ExprNode, schema: SchemaType): TypeNode /** All possible type nodes. */ export declare type TypeNode = | ObjectTypeNode | StringTypeNode | NullTypeNode | NumberTypeNode | BooleanTypeNode | ArrayTypeNode | UnionTypeNode | InlineTypeNode | UnknownTypeNode /** Describes a type node for union values. */ export declare interface UnionTypeNode<T extends TypeNode = TypeNode> { /** can be used to identify the type of the node, in this case it's always 'union' */ type: 'union' /** a collection of types */ of: T[] } /** Describes a type node for unknown value. */ export declare type UnknownTypeNode = { /** can be used to identify the type of the node, in this case it's always 'unknown' */ type: 'unknown' } /** * The result of an expression. */ export declare type Value = AnyStaticValue | StreamValue export declare interface ValueNode<P = any> { type: 'Value' value: P } export {}
package commands import ( "context" "os" "os/signal" "syscall" "time" "github.com/keybrl/chatgpt-cli/pkg/commands/chat" "github.com/keybrl/chatgpt-cli/pkg/commands/login" "github.com/keybrl/chatgpt-cli/pkg/commands/logout" "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) var ( flagDebug bool ) // rootCmd 根命令 var rootCmd = &cobra.Command{ Use: "chartgpt-cli", Short: "CLI for OpenAI ChatGPT", PersistentPreRunE: func(cmd *cobra.Command, args []string) error { if flagDebug { logrus.SetLevel(logrus.DebugLevel) logrus.Debug("run in debug mode") } return nil }, RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, } // Execute 执行命令 func Execute() { ctx := notifyContext(context.Background()) startTime := time.Now() err := rootCmd.ExecuteContext(ctx) logrus.Debugf("duration: %s", time.Since(startTime)) if err != nil { os.Exit(1) } } func init() { rootCmd.PersistentFlags().BoolVar(&flagDebug, "debug", false, "run in debug mode") rootCmd.AddCommand( chat.Cmd, login.Cmd, logout.Cmd, ) } // notifyContext 返回一个上下文,该上下文会在进程接收到 INT 或 TERM 信号时被取消 func notifyContext(ctx context.Context) context.Context { ctx, cancel := context.WithCancel(ctx) ch := make(chan os.Signal, 1) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) go func() { defer cancel() defer close(ch) // 监听第一次事件 select { case <-ctx.Done(): return case <-ch: // 通知上下文取消 cancel() } // 接收到第二次事件时直接强行退出 <-ch os.Exit(1) }() return ctx }
package ch6; //https://fluvid.com/videos/detail/8EL-9T3X37SdvPXok#.Yhzeh-dJ0aQ.link public class InnerClasses { public static void main(String[] args) { Outer.InnerStatic ins=new Outer.InnerStatic(); ins.met(); Outer.InnerNonStatic in=new Outer().new InnerNonStatic(); in.met(); } } class Outer{ void outMet() { System.out.println("non static out met called..."); } static void staticOutMet() { System.out.println("static void out met called..."); } static class InnerStatic{ public void met() { System.out.println("static inner class method called..."); //outMet(); - non static cannot be accessed staticOutMet(); } } class InnerNonStatic{ public void met() { System.out.println("non static met called...."); outMet(); staticOutMet(); } } }
import datetime import streamlit as st import requests import os import json from pathlib import Path from elasticsearch_main import search_recipes, es import spacy nlp = spacy.load("en_core_web_sm") PROTOCOL = "https" HOST = "edbrown.mids255.com" PORT = 443 #streamlit run app.py def send_image_to_api(image_path, api_endpoint): if not os.path.exists(image_path): return {"error": "Image file does not exist."} files = {"file": open(image_path, "rb")} headers = {"accept": "application/json"} response = requests.post(api_endpoint, files=files, headers=headers) return response.json() def main(): # Check if 'tab' is in the URL query parameters if "tab" not in st.query_params: # Landing page st.markdown( """ <style> body { background-image: url('https://source.unsplash.com/featured/?food'); background-size: cover; } .stApp { color: black; } .stButton>button { background-color: #4CAF50; color: white; padding: 15px 32px; text-align: center; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 10px; } </style> """ , unsafe_allow_html=True) # Landing page content st.title("Welcome to Got Meals! 🍔📷") st.write("Our mission is unwavering – to remove the hassle from your daily culinary journey and bring joy back to your kitchen.") st.write("With a simple photo, we unlock the potential of your ingredients and deliver a personalized list of recipes tailored to your preferences.") st.write("Click the button below to get started:") # Button to navigate to Got Meals app if st.button("Go to Got Meals App"): st.write('<meta http-equiv="refresh" content="0; URL=\'?tab=got_meals\'" />', unsafe_allow_html=True) else: # Got Meals application st.title("Got Meals?🍔📷") st.header("Identify recipes based on the foods you have!") st.write("Add your food images below and select any allergies to generate a list of relevant recipes") uploaded_images = st.file_uploader(label="Upload a maximum of 5 items and a minimum of 2 items. Order the images you upload with the first image being the most important.", type=["jpg", "jpeg", "png", "heic"], accept_multiple_files=True) option = st.selectbox( 'Select from the dropdown list if any of these allergies apply to you', ('None','Peanuts', 'Tree Nuts', 'All Nuts','Milk','Eggs', 'Fish', 'Shellfish', 'Wheat', 'Soybeans')) st.write('You selected:', option) responses = [] # Initialize a list to store responses for each image correct_names = [] # Initialize a list to store the correctness of ingredient names for each image ingredient_names = [] # Initialize a list to store ingredient names in the order of image uploads # Check if a file has been uploaded if uploaded_images is not None: num_images = len(uploaded_images) st.write(f"Number of Images Uploaded: {num_images}") for i in range(num_images): # Display the uploaded image st.image(uploaded_images[i], caption = f"Uploaded Image {i+1}", use_column_width=True) # Check if the ingredient name is correct correct_name = st.radio(f"Is this the correct ingredient name for Image {i+1}?", ("Yes", "No"), key=f"radio_{i}") correct_names.append(correct_name) # Store the correctness of the ingredient name for each image # If the ingredient name is incorrect, provide a text input box to enter the correct name if correct_name == "No": corrected_name = st.text_input(f"Please enter the correct ingredient name for Image {i+1}: ", key=f"text_{i}") st.write(f"Corrected name for Image {i+1}: {corrected_name}") ingredient_names.append(corrected_name) else: #Save the uploaded image to a temp directory temp_dir = "./temp" os.makedirs(temp_dir, exist_ok=True) temp_image_path= os.path.join(temp_dir, uploaded_images[i].name) with open(temp_image_path, "wb") as f: f.write(uploaded_images[i].getvalue()) #Send the image to the RESTAPI api_endpoint = f"{PROTOCOL}://{HOST}:{PORT}/predict" response = send_image_to_api(temp_image_path, api_endpoint) responses.append(response) # Store the response for each image st.write(f"Response for Image {i+1}: {response.get('ingredient', 'No ingredient found')}") # If the ingredient name is correct, add it to the list of ingredient names ingredient_name = response.get('ingredient', 'No ingredient found') ingredient_names.append(ingredient_name) # Display the submit button submit_button = st.button("Submit") if submit_button: # Ensure that the first ingredient takes priority in the recipe if ingredient_names: #Ingredients are saved in ingredient_names #Need to get to: lemmatized_ingredient_1, lemmatized_ingredient_2, lemmatized_ingredients # ingredient1 = ingredient_names[0] # doc = nlp(ingredient1) # lemmatized_ingredient_1 = " ".join([token.lemma_ for token in doc]) # ingredient2 = ingredient_names[1] # doc = nlp(ingredient2) # lemmatized_ingredient_2 = " ".join([token.lemma_ for token in doc]) # ingredient3 = ingredient_names[2] # ingredient4 = ingredient_names[3] # ingredient5 = ingredient_names[4] lemmatized_ingredients_temp = [] for ingredient in ingredient_names: doc = nlp(ingredient) lemmatized_ingredient = " ".join([token.lemma_ for token in doc]) lemmatized_ingredients_temp.append(lemmatized_ingredient) lemmatized_ingredient_1 = lemmatized_ingredients_temp[0] lemmatized_ingredient_2 = lemmatized_ingredients_temp[1] if len(lemmatized_ingredients_temp) > 2: lemmatized_ingredients = lemmatized_ingredients_temp[2:] else: lemmatized_ingredients = [None] #Lemmatize ALLERGY if option != 'None': doc = nlp(option) option = " ".join([token.lemma_ for token in doc]) # first_ingredient = ingredient_names[0] --> OLD CODE NOT USED # nice_to_have_ingredients = ingredient_names[1:] --> OLD CODE NOT USED # Construct the list of ingredient names prioritized based on the order of image uploads # ingredient_names_prioritized = [first_ingredient] + [ingredient for ingredient in nice_to_have_ingredients if ingredient != first_ingredient] --> OLD CODE NOT USED # Perform Elasticsearch query for recipes based on all ingredient names ##UPDATE SEARCH_RECIPES WITH THE CORRECT INPUTS NEEDED recipes = search_recipes(es, lemmatized_ingredient_1, lemmatized_ingredient_2, lemmatized_ingredients) if recipes['hits']['hits']: for index, hit in enumerate(recipes['hits']['hits'], start=1): # Check if the recipe contains the selected allergy if option != 'None' and option.lower().replace(' ', '_') not in hit['_source']['ingredients'].lower(): st.write(f"--- Recipe {index} ---") st.write(f"Recipe Title: {hit['_source']['title']}") st.write(f"Recipe Ingredients: {hit['_source']['ingredients']}") st.write(f"Recipe Directions: {hit['_source']['directions']}") st.write("----------------------------") elif option == 'None': st.write(f"--- Recipe {index} ---") st.write(f"Recipe Title: {hit['_source']['title']}") st.write(f"Recipe Ingredients: {hit['_source']['ingredients']}") st.write(f"Recipe Directions: {hit['_source']['directions']}") st.write("----------------------------") else: st.write("No recipes found. Please, Try Again!") # Leave the output blank if no recipes are found else: st.write("No images uploaded. Please upload at least one image.") # Inform user if no images are uploaded else: st.write("No images uploaded. Please upload at least one image.") # Inform user if no images are uploaded if __name__ == "__main__": main()
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fontes em Css</title> <style> @import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;1,700;1,900&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Borel&family=Roboto:ital,wght@0,400;1,700;1,900&display=swap'); body{ font-family: 'Roboto'; } h1,h2{ text-decoration: underline; font-style: italic; /*short hand ordem de prioridade fontstyle, font-weight, font-size, font-family */ font:italic bolder 40pt 'borel', sans-serif; text-align: center; color:#A62B1F } p{ font:italic 1em 'roboto',sans-serif; color: #193C40; text-align: justify; } </style> </head> <body> <h1>Trabalhando com fontes</h1> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laborum obcaecati ad, magni nostrum, nobis aliquid voluptatum minima, officiis minus beatae temporibus. Voluptatibus, repudiandae necessitatibus explicabo natus autem praesentium blanditiis tempora.Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat vero saepe accusamus voluptates, culpa beatae ipsam ipsa at consequuntur, voluptatem quidem distinctio? Veniam, harum. Sapiente veritatis enim dolore ad et.</p> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat vero saepe accusamus voluptates, culpa beatae ipsam ipsa at consequuntur, voluptatem quidem distinctio? Veniam, harum. Sapiente veritatis enim dolore ad et.</p> <h2>Subtítulo do exercício</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas ea repudiandae dolores nesciunt explicabo numquam magni iusto ullam dolor eligendi, praesentium, recusandae sapiente dicta tempore et laudantium natus. Laborum, iure.</p> </body> </html>
/****************************************************************************** * * Copyright (c) 2019-2023 Fraunhofer IOSB-INA Lemgo, * eine rechtlich nicht selbstaendige Einrichtung der Fraunhofer-Gesellschaft * zur Foerderung der angewandten Forschung e.V. * *****************************************************************************/ import { CommonModule } from '@angular/common'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { NgbActiveModal, NgbModal, NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { TranslateFakeLoader, TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { AuthApiService } from '../../lib/auth/auth-api.service'; import { ERRORS } from '../../lib/types/errors'; import { INFO } from '../../lib/types/info'; import { LoginFormComponent, LoginFormResult } from '../../lib/auth/login-form/login-form.component'; import { AuthResult } from 'common'; describe('LoginFormComponent', () => { let component: LoginFormComponent; let modal: NgbActiveModal; let api: AuthApiService; let fixture: ComponentFixture<LoginFormComponent>; beforeEach(() => { TestBed.configureTestingModule({ declarations: [LoginFormComponent], providers: [ NgbModal, NgbActiveModal ], imports: [ CommonModule, FormsModule, NgbModule, HttpClientTestingModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useClass: TranslateFakeLoader } }) ] }); modal = TestBed.inject(NgbActiveModal); api = TestBed.inject(AuthApiService); fixture = TestBed.createComponent(LoginFormComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('submits a valid user', fakeAsync(async () => { const result: LoginFormResult = { token: 'a_token', stayLoggedIn: true }; spyOn(modal, 'close').and.callFake((...args) => expect(args[0]).toEqual(result)); spyOn(api, 'loginAsync').and.returnValue(new Promise<AuthResult>((result) => result({ token: 'a_token' }))); component.userId = 'john.doe@email.com'; component.password = '1234.Abcd'; component.stayLoggedIn = true; await component.submit(); expect(component.messages.length).toEqual(0); expect(modal.close).toHaveBeenCalled(); })); it('does not login a user with empty e-mail', fakeAsync(async () => { component.userId = ''; component.password = '1234.Abcd'; await component.submit(); expect(component.messages.length).toEqual(1); expect(component.messages[0].text).toEqual(ERRORS.EMAIL_REQUIRED); })); it('does not login a user with invalid e-mail', fakeAsync(async () => { component.userId = 'invalidEMail'; component.password = '1234.abcd'; await component.submit(); expect(component.messages.length).toEqual(1); expect(component.messages[0].text).toEqual(ERRORS.INVALID_EMAIL); })); it('does not login a user with empty password', fakeAsync(async () => { component.userId = 'john.doe@email.com'; component.password = ''; await component.submit(); expect(component.messages.length).toEqual(1); expect(component.messages[0].text).toEqual(ERRORS.PASSWORD_REQUIRED); })); it('does not login a user with invalid password', fakeAsync(async () => { component.userId = 'john.doe@email.com'; component.password = '123'; await component.submit(); expect(component.messages.length).toEqual(1); expect(component.messages[0].text).toEqual(ERRORS.INVALID_PASSWORD); })); it('does not login an unknown user', fakeAsync(async () => { spyOn(modal, 'close').and.returnValue(); spyOn(api, 'loginAsync').and .returnValue(new Promise<AuthResult>((_, reject) => reject(new Error('Unknown user')))); component.userId = 'unknown.user@email.com'; component.password = '1234.abcd'; await component.submit(); expect(component.messages.length).toEqual(1); expect(component.messages[0].text).toEqual('Unknown user'); })); it('supports the reset of a forgotten password', async function () { spyOn(api, 'resetPasswordAsync').and.returnValue(new Promise<void>((result) => result())); component.userId = 'john.doe@email.com'; await component.resetPassword(); expect(component.messages.length).toEqual(1); expect(component.messages[0].text).toEqual(INFO.NEW_PASSWORD_SENT); }); it('can not reset password when e-mail is empty', fakeAsync(async () => { component.userId = ''; await component.resetPassword(); expect(component.messages.length).toEqual(1); expect(component.messages[0].text).toEqual(ERRORS.EMAIL_REQUIRED); })); it('an not reset password when e-mail is invalid', fakeAsync(async () => { component.userId = 'invalidEMail'; await component.resetPassword(); expect(component.messages.length).toEqual(1); expect(component.messages[0].text).toEqual(ERRORS.INVALID_EMAIL); })); it('supports navigation to the registration', function () { spyOn(modal, 'close').and.callFake((...args) => expect(args[0]).toEqual({ action: 'register' } as LoginFormResult)); component.registerUser(); expect(modal.close).toHaveBeenCalled(); }); });
// ** React Imports import { forwardRef, ReactElement, ReactNode, Ref } from 'react' // ** MUI Imports import Dialog from '@mui/material/Dialog' import DialogTitle from '@mui/material/DialogTitle' import DialogContent from '@mui/material/DialogContent' import Slide, { SlideProps } from '@mui/material/Slide' import DialogContentText from '@mui/material/DialogContentText' import Icon from 'src/@core/components/icon' import { styled } from '@mui/material/styles' import IconButton, { IconButtonProps } from '@mui/material/IconButton' import { Typography } from '@mui/material' const Transition = forwardRef(function Transition( props: SlideProps & { children?: ReactElement<any, any> }, ref: Ref<unknown> ) { return <Slide direction='up' ref={ref} {...props} /> }) const CustomCloseButton = styled(IconButton)<IconButtonProps>(({ theme }) => ({ top: 0, right: 0, color: 'grey.500', position: 'absolute', boxShadow: theme.shadows[2], transform: 'translate(10px, -10px)', borderRadius: theme.shape.borderRadius, backgroundColor: `${theme.palette.background.paper} !important`, transition: 'transform 0.25s ease-in-out, box-shadow 0.25s ease-in-out', '&:hover': { transform: 'translate(7px, -5px)' } })) interface Props { icon?: string iconSize?: number title?: string message: ReactNode opened: boolean onClose: () => void } const AlertDialog = ({ icon, title, message, opened, iconSize = 20, onClose }: Props) => ( <Dialog open={opened} keepMounted onClose={onClose} TransitionComponent={Transition} aria-labelledby='alert-dialog-slide-title' aria-describedby='alert-dialog-slide-description' sx={{ '& .MuiDialog-paper': { overflow: 'visible' } }} > <DialogTitle id='alert-dialog-slide-title' sx={{ alignItems: 'center', alignContent: 'center', display: 'flex', marginBottom: 1 }} > {icon && icon.length > 0 ? <Icon color='primary' icon={icon} fontSize={iconSize} /> : null} {title && title.length > 0 ? <Typography sx={{ ml: 2 }}>{title}</Typography> : null} <CustomCloseButton aria-label='close' onClick={() => onClose()}> <Icon icon='tabler:x' fontSize='1.25rem' /> </CustomCloseButton> </DialogTitle> <DialogContent> <DialogContentText id='alert-dialog-slide-description'>{message}</DialogContentText> </DialogContent> </Dialog> ) export default AlertDialog
<div align="center"> <img src="https://blogs.cappriciosec.com/uploaders/CVE-2023-29489.png" alt="logo"> </div> ## Badges [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit/) ![PyPI - Version](https://img.shields.io/pypi/v/CVE-2023-29489) ![PyPI - Downloads](https://img.shields.io/pypi/dm/CVE-2023-29489) ![GitHub all releases](https://img.shields.io/github/downloads/Cappricio-Securities/CVE-2023-29489/total) <a href="https://github.com/Cappricio-Securities/CVE-2023-29489/releases/"><img src="https://img.shields.io/github/release/Cappricio-Securities/CVE-2023-29489"></a>![Profile_view](https://komarev.com/ghpvc/?username=Cappricio-Securities&label=Profile%20views&color=0e75b6&style=flat) [![Follow Twitter](https://img.shields.io/twitter/follow/cappricio_sec?style=social)](https://twitter.com/cappricio_sec) <p align="center"> <p align="center"> ## License [MIT](https://choosealicense.com/licenses/mit/) ## Installation 1. Install Python3 and pip [Instructions Here](https://www.python.org/downloads/) (If you can't figure this out, you shouldn't really be using this) - Install via pip - ```bash pip install CVE-2023-29489 ``` - Run bellow command to check - `CVE-2023-29489 -h` ## Configurations 2. We integrated with the Telegram API to receive instant notifications for vulnerability detection. - Telegram Notification - ```bash CVE-2023-29489 --chatid <YourTelegramChatID> ``` - Open your telegram and search for [`@CappricioSecuritiesTools_bot`](https://web.telegram.org/k/#@CappricioSecuritiesTools_bot) and click start ## Usages 3. This tool has multiple use cases. - To Check Single URL - ```bash CVE-2023-29489 -u http://example.com ``` - To Check List of URL - ```bash CVE-2023-29489 -i urls.txt ``` - Save output into TXT file - ```bash CVE-2023-29489 -i urls.txt -o out.txt ``` - Want to Learn about [`CVE-2023-29489`](https://blogs.cappriciosec.com/cve/137/CVE-2023-29489)? Then Type Below command - ```bash CVE-2023-29489 -b ``` <p align="center"> <b>🚨 Disclaimer</b> </p> <p align="center"> <b>This tool is created for security bug identification and assistance; Cappricio Securities is not liable for any illegal use. Use responsibly within legal and ethical boundaries. 🔐🛡️</b></p> ## Working PoC Video [![asciicast](https://blogs.cappriciosec.com/uploaders/Screenshot%202024-04-23%20at%2010.53.38%20AM.png)](https://asciinema.org/a/xB30FPnwpUJiqiyVzY20OutOD) ## Help menu #### Get all items ```bash 👋 Hey Hacker v1.0 ______ ______ ___ ___ ___ ____ ___ ___ ____ ___ ___ / ___/ | / / __/___|_ |/ _ \|_ ||_ /___|_ / _ \/ / /( _ ) _ \ / /__ | |/ / _//___/ __// // / __/_/_ <___/ __/\_, /_ _/ _ \_, / \___/ |___/___/ /____/\___/____/____/ /____/___/ /_/ \___/___/ Developed By https://cappriciosec.com CVE-2023-29489 : Bug scanner for WebPentesters and Bugbounty Hunters $ CVE-2023-29489 [option] Usage: CVE-2023-29489 [options] ``` | Argument | Type | Description | Examples | | :-------- | :------- | :------------------------- | :------------------------- | | `-u` | `--url` | URL to scan | CVE-2023-29489 -u https://target.com | | `-i` | `--input` | filename Read input from txt | CVE-2023-29489 -i target.txt | | `-o` | `--output` | filename Write output in txt file | CVE-2023-29489 -i target.txt -o output.txt | | `-c` | `--chatid` | Creating Telegram Notification | CVE-2023-29489 --chatid yourid | | `-b` | `--blog` | To Read about CVE-2023-29489 Bug | CVE-2023-29489 -b | | `-h` | `--help` | Help Menu | CVE-2023-29489 -h | ## 🔗 Links [![Website](https://img.shields.io/badge/my_portfolio-000?style=for-the-badge&logo=ko-fi&logoColor=white)](https://cappriciosec.com/) [![linkedin](https://img.shields.io/badge/linkedin-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/karthikeyan--v/) [![twitter](https://img.shields.io/badge/twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/karthithehacker) ## Author - [@karthithehacker](https://github.com/karthi-the-hacker/) ## Feedback If you have any feedback, please reach out to us at contact@karthithehacker.com
package com.microservice.currencyexchangeservice.controller; import com.microservice.currencyexchangeservice.bean.ExchangeValue; import com.microservice.currencyexchangeservice.repository.ExchangeValueRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class CurrencyExchangeController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private Environment environment; @Autowired private ExchangeValueRepository valueRepository; @GetMapping("/currency-exchange/from/{from}/to/{to}") public ExchangeValue retriveExchangeValue(@PathVariable String from, @PathVariable String to){ ExchangeValue exchangeValue = valueRepository.findByFromAndTo(from,to); exchangeValue.setPort(Integer.parseInt(environment.getProperty("local.server.port"))); logger.info("{}",exchangeValue); return exchangeValue; } }
import fs from 'fs'; import { Instance } from '@server/GameServerInstance'; import { buildCharacter, buildItem, buildPlayer, buildRoom, buildZone, initializeTestServer } from '@server/testUtils'; import { Character, CharacterFlag, ICharacterDefinition, IPlayerDefinition, matchCharacters, Player } from './character'; import { Room, RoomFlag } from './room'; import { Zone } from './zone'; import { RaceType } from './race'; import { ClassType } from './class'; import { defaultAbilities } from './abilities'; import { ItemFlag } from './item'; import { BodyPosition } from './equipment'; jest.mock('fs'); describe('core/entities/character', () => { let zone: Zone; let origin: Room; beforeEach(() => { initializeTestServer(); zone = buildZone({}, true); origin = buildRoom(zone, 'origin'); }); describe('Character', () => { describe('constructor', () => { test('initializes character largely based on definition', () => { const handler = jest.fn(); const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', admin: true, roomDescription: 'Test char room description', description: 'Test char look description', race: RaceType.ELF, class: ClassType.DRUID, abilities: { STRENGTH: { baseValue: 10, modifiers: {}, value: 10 }, }, keywords: ['keyword1', 'KEYWORD2'], workingData: { key1: 'value1', key2: 'value2', }, flags: [CharacterFlag.PACIFISM], commands: [{ name: 'testcommand', handler }], }; const char = new Character(definition, zone, origin); expect(char.definition).toEqual(definition); expect(char.id.length).toBeGreaterThan(0); expect(char.key).toEqual('testChar'); expect(char.name).toEqual('Test char'); expect(char.admin).toBeTruthy(); expect(char.npc).toBeTruthy(); expect(char.styledName).toEqual('<Y>Test char<n>'); expect(char.roomDescription).toEqual('Test char room description'); expect(char.description).toEqual('Test char look description'); expect(char.race.type).toEqual(RaceType.ELF); expect(char.class.type).toEqual(ClassType.DRUID); expect(char.abilities).toEqual({ ...defaultAbilities(), STRENGTH: { baseValue: 10, modifiers: {}, value: 10 } }); expect(char.keywords).toEqual(['keyword1', 'keyword2']); expect(char.following).toBeUndefined(); expect(char.followers).toEqual([]); expect(char.conversation).toBeUndefined(); expect(char.workingData).toEqual({ key1: 'value1', key2: 'value2' }); expect(char.flags.flags).toEqual(CharacterFlag.PACIFISM); expect(char.commandHandler?.getCommandDefinitions().length).toEqual(1); }); test('initializes character with reasonable defaults', () => { const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', }; const char = new Character(definition, zone, origin); expect(char.definition).toEqual(definition); expect(char.id.length).toBeGreaterThan(0); expect(char.key).toEqual('testChar'); expect(char.name).toEqual('Test char'); expect(char.admin).toBeFalsy(); expect(char.npc).toBeTruthy(); expect(char.styledName).toEqual('<c>Test char<n>'); expect(char.roomDescription).toEqual('<c>Test char<n> is here.'); expect(char.description).toEqual('You see <c>Test char<n>.'); expect(char.race.type).toEqual(RaceType.HUMANOID); expect(char.class.type).toEqual(ClassType.NONE); expect(char.abilities).toEqual(defaultAbilities()); expect(char.keywords).toEqual([]); expect(char.following).toBeUndefined(); expect(char.followers).toEqual([]); expect(char.conversation).toBeUndefined(); expect(char.workingData).toEqual({}); expect(char.flags.flags).toEqual(0); expect(char.commandHandler).toBeUndefined(); }); test('adds character to room', () => { const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', }; const char = new Character(definition, zone, origin); expect(char.room).toEqual(origin); expect(char.zone).toEqual(zone); expect(origin.characters).toEqual([char]); expect(zone.characters).toEqual([char]); }); }); describe('finalize', () => { test('adds items to inventory based on definition', () => { Instance.gameServer?.catalog.registerItemDefinition( { key: 'testItem', name: 'Test item', roomDescription: 'Test item room description', description: 'Test item look description', }, zone ); const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', inventory: [{ key: 'testItem' }], }; const char = new Character(definition, zone, origin); expect(char.items.length).toEqual(0); char.finalize(); expect(char.items.length).toEqual(1); expect(char.items[0].key).toEqual('testItem@testZone'); }); }); describe('changeDescription', () => { test('changes description only on actual character if not permanent', () => { const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', roomDescription: 'Original room description', description: 'Original look description', }; const char = new Character(definition, zone, origin); expect(char.roomDescription).toEqual('Original room description'); expect(char.description).toEqual('Original look description'); expect(char.definition.roomDescription).toEqual('Original room description'); expect(char.definition.description).toEqual('Original look description'); char.changeDescription({ room: 'New room description', look: 'New look description' }, false); expect(char.roomDescription).toEqual('New room description'); expect(char.description).toEqual('New look description'); expect(char.definition.roomDescription).toEqual('Original room description'); expect(char.definition.description).toEqual('Original look description'); }); test('changes description on definition as well if permanent', () => { const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', roomDescription: 'Original room description', description: 'Original look description', }; const char = new Character(definition, zone, origin); expect(char.roomDescription).toEqual('Original room description'); expect(char.description).toEqual('Original look description'); expect(char.definition.roomDescription).toEqual('Original room description'); expect(char.definition.description).toEqual('Original look description'); char.changeDescription({ room: 'New room description', look: 'New look description' }, true); expect(char.roomDescription).toEqual('New room description'); expect(char.description).toEqual('New look description'); expect(char.definition.roomDescription).toEqual('New room description'); expect(char.definition.description).toEqual('New look description'); }); }); describe('lookAt', () => { let invoker: Character; beforeEach(() => { invoker = buildCharacter(zone, 'invoker', origin); }); test('shows user name and description', () => { const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', roomDescription: 'Char room description', description: 'Char look description', }; const char = new Character(definition, zone, origin); const output = char.lookAt(invoker); expect(output).toEqual(`<c>Test char<n> Char look description Equipment: nothing Inventory: nothing`); }); test('shows inventory', () => { Instance.gameServer?.catalog.registerItemDefinition( { key: 'testItem', name: 'Test item', roomDescription: 'Test item room description', description: 'Test item look description', }, zone ); const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', roomDescription: 'Char room description', description: 'Char look description', inventory: [{ key: 'testItem' }], }; const char = new Character(definition, zone, origin); expect(char.items.length).toEqual(0); char.finalize(); const output = char.lookAt(invoker); expect(output).toEqual(`<c>Test char<n> Char look description Equipment: nothing Inventory: <y>Test item<n>`); }); test('shows equipment', () => { Instance.gameServer?.catalog.registerItemDefinition( { key: 'testItem', name: 'Test item', roomDescription: 'Test item room description', description: 'Test item look description', flags: [ItemFlag.WEARABLE], wearSpots: [BodyPosition.FEET], }, zone ); const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', roomDescription: 'Char room description', description: 'Char look description', equipment: { FEET: { key: 'testItem@testZone' } }, }; const char = new Character(definition, zone, origin); expect(char.items.length).toEqual(0); char.finalize(); const output = char.lookAt(invoker); expect(output).toEqual(`<c>Test char<n> Char look description Equipment: feet: <y>Test item<n> Inventory: nothing`); }); test('shows character key if looker is admin', () => { const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', roomDescription: 'Char room description', description: 'Char look description', }; const char = new Character(definition, zone, origin); invoker.admin = true; const output = char.lookAt(invoker); expect(output).toEqual(`<c>Test char<n> [testChar] Char look description Equipment: nothing Inventory: nothing`); }); }); describe('roomLookAt', () => { test('shows room description', () => { const invoker = buildCharacter(zone, 'invoker', origin); const definition: ICharacterDefinition = { key: 'testChar', name: 'Test char', roomDescription: 'Char room description', description: 'Char look description', }; const char = new Character(definition, zone, origin); const output = char.roomLookAt(invoker); expect(output).toEqual(`Char room description`); }); }); describe('follow', () => { test('starts following target and adds to their followers', () => { const invoker = buildCharacter(zone, 'invoker', origin); const target = buildCharacter(zone, 'target', origin); expect(invoker.following).toBeUndefined(); expect(invoker.followers).toEqual([]); expect(target.following).toBeUndefined(); expect(target.followers).toEqual([]); invoker.follow(target); expect(invoker.following).toEqual(target); expect(invoker.followers).toEqual([]); expect(target.following).toBeUndefined(); expect(target.followers).toEqual([invoker]); }); test('emits message to target and invoker', () => { const invoker = buildCharacter(zone, 'invoker', origin); const target = buildCharacter(zone, 'target', origin); jest.spyOn(invoker, 'emitTo'); jest.spyOn(target, 'emitTo'); invoker.follow(target); expect(invoker.emitTo).toBeCalledWith('You are now following <c>target name<n>.'); expect(target.emitTo).toBeCalledWith('<c>invoker name<n> is now following you.'); }); }); describe('unfollow', () => { test('stops following whoever invoker is following', () => { const invoker = buildCharacter(zone, 'invoker', origin); const target = buildCharacter(zone, 'target', origin); invoker.follow(target); expect(invoker.following).toEqual(target); expect(invoker.followers).toEqual([]); expect(target.following).toBeUndefined(); expect(target.followers).toEqual([invoker]); invoker.unfollow(); expect(invoker.following).toBeUndefined(); expect(invoker.followers).toEqual([]); expect(target.following).toBeUndefined(); expect(target.followers).toEqual([]); }); test('emits message to target and invoker', () => { const invoker = buildCharacter(zone, 'invoker', origin); const target = buildCharacter(zone, 'target', origin); jest.spyOn(invoker, 'emitTo'); jest.spyOn(target, 'emitTo'); invoker.follow(target); invoker.unfollow(); expect(invoker.emitTo).toBeCalledWith('You are no longer following <c>target name<n>.'); expect(target.emitTo).toBeCalledWith('<c>invoker name<n> is no longer following you.'); }); test('does nothing if not following anyone', () => { const invoker = buildCharacter(zone, 'invoker', origin); jest.spyOn(invoker, 'emitTo'); invoker.unfollow(); expect(invoker.emitTo).not.toBeCalled(); }); }); describe('disband', () => { test('removes all followers', () => { const invoker = buildCharacter(zone, 'invoker', origin); const follower1 = buildCharacter(zone, 'follower1', origin); const follower2 = buildCharacter(zone, 'follower2', origin); follower1.follow(invoker); follower2.follow(invoker); expect(invoker.followers).toEqual([follower1, follower2]); expect(follower1.following).toEqual(invoker); expect(follower2.following).toEqual(invoker); invoker.disband(); expect(invoker.followers).toEqual([]); expect(follower1.following).toBeUndefined(); expect(follower2.following).toBeUndefined(); }); test('emits unfollow message to everyone involved', () => { const invoker = buildCharacter(zone, 'invoker', origin); const follower1 = buildCharacter(zone, 'follower1', origin); const follower2 = buildCharacter(zone, 'follower2', origin); follower1.follow(invoker); follower2.follow(invoker); jest.spyOn(invoker, 'emitTo'); jest.spyOn(follower1, 'emitTo'); jest.spyOn(follower2, 'emitTo'); invoker.disband(); expect(follower1.emitTo).toBeCalledWith('You are no longer following <c>invoker name<n>.'); expect(follower2.emitTo).toBeCalledWith('You are no longer following <c>invoker name<n>.'); expect(invoker.emitTo).toBeCalledWith('<c>follower1 name<n> is no longer following you.'); expect(invoker.emitTo).toBeCalledWith('<c>follower2 name<n> is no longer following you.'); }); }); describe('balanced', () => { test('returns true if not unbalanced', () => { const invoker = buildCharacter(zone, 'invoker', origin); expect(invoker.balanced()).toBeTruthy(); }); test('returns true if current time greater than unbalancedUntil value', () => { const invoker = buildCharacter(zone, 'invoker', origin); invoker.unbalancedUntil = 27; expect(invoker.balanced()).toBeTruthy(); }); test('returns false if current time less than unbalancedUntil value', () => { const invoker = buildCharacter(zone, 'invoker', origin); invoker.unbalancedUntil = Date.now() + 5000; expect(invoker.balanced()).toBeFalsy(); }); }); describe('balancedIn', () => { test('returns undefined if balanced', () => { const invoker = buildCharacter(zone, 'invoker', origin); expect(invoker.balanced()).toBeTruthy(); expect(invoker.balancedIn()).toBeUndefined(); }); test('returns amount of seconds until balanced if unbalanced', () => { const invoker = buildCharacter(zone, 'invoker', origin); invoker.unbalancedUntil = Date.now() + 5400; expect(invoker.balancedIn()).toEqual(5); }); }); describe('unbalance', () => { test('unbalances character for amount of seconds passed', () => { const invoker = buildCharacter(zone, 'invoker', origin); invoker.unbalance(5); expect(invoker.balancedIn()).toEqual(5); }); test('extends unbalance if unbalanced to lesser amount', () => { const invoker = buildCharacter(zone, 'invoker', origin); invoker.unbalance(2); expect(invoker.balancedIn()).toEqual(2); invoker.unbalance(5); expect(invoker.balancedIn()).toEqual(5); }); test('does not change unbalanced amount if less than current', () => { const invoker = buildCharacter(zone, 'invoker', origin); invoker.unbalance(5); expect(invoker.balancedIn()).toEqual(5); invoker.unbalance(2); expect(invoker.balancedIn()).toEqual(5); }); }); describe('canWander', () => { test(`non npcs can't wander`, () => { const invoker = buildCharacter(zone, 'invoker', origin); invoker.npc = false; expect(invoker.canWander()).toBeFalsy(); }); test(`normal npcs can wander`, () => { const invoker = buildCharacter(zone, 'invoker', origin); expect(invoker.canWander()).toBeTruthy(); }); test(`sentinel npcs can't wander`, () => { const invoker = buildCharacter(zone, 'invoker', origin, { flags: [CharacterFlag.SENTINEL] }); expect(invoker.canWander()).toBeFalsy(); }); test(`npcs can't wander in sentinel rooms`, () => { origin.flags.addFlag(RoomFlag.SENTINEL); const invoker = buildCharacter(zone, 'invoker', origin); expect(invoker.canWander()).toBeFalsy(); }); }); describe('tick', () => { beforeEach(() => { jest.spyOn(Math, 'random').mockReturnValue(0.99); }); afterEach(() => { jest.spyOn(Math, 'random').mockRestore(); }); test('calls tick on definition if set', () => { const tick = jest.fn().mockReturnValue(true); const invoker = buildCharacter(zone, 'invoker', origin, { tick }); invoker.tick(27); expect(tick).toBeCalledWith(invoker, 27); }); test('calls tick on conversation if set', () => { const conversation = { tick: jest.fn().mockReturnValue(true) }; const invoker = buildCharacter(zone, 'invoker', origin); invoker.conversation = conversation as any; invoker.tick(27); expect(conversation.tick).toBeCalledWith(invoker, 27); }); test('prefers tick on definition to conversation', () => { const tick = jest.fn().mockReturnValue(true); const conversation = { tick: jest.fn().mockReturnValue(true) }; const invoker = buildCharacter(zone, 'invoker', origin, { tick }); invoker.conversation = conversation as any; invoker.tick(27); expect(tick).toBeCalledWith(invoker, 27); expect(conversation.tick).not.toBeCalled(); }); test('continues past definition tick if it returns false', () => { const tick = jest.fn().mockReturnValue(false); const conversation = { tick: jest.fn().mockReturnValue(true) }; const invoker = buildCharacter(zone, 'invoker', origin, { tick }); invoker.conversation = conversation as any; invoker.tick(27); expect(tick).toBeCalledWith(invoker, 27); expect(conversation.tick).toBeCalledWith(invoker, 27); }); test('wanderable mobs have 5% chance to wander', () => { jest.spyOn(Math, 'random').mockReturnValue(0.04); buildRoom(zone, 'otherRoom'); origin.definition.exits = [{ direction: 'north', destination: 'otherRoom' }]; origin.finalize(); const invoker = buildCharacter(zone, 'invoker', origin); invoker.tick(0); expect(Instance.gameServer?.handleCommand).toBeCalledWith(invoker, 'move north'); }); test('prefers tick on definition to wandering', () => { jest.spyOn(Math, 'random').mockReturnValue(0.04); buildRoom(zone, 'otherRoom'); origin.definition.exits = [{ direction: 'north', destination: 'otherRoom' }]; origin.finalize(); const tick = jest.fn().mockReturnValue(true); const invoker = buildCharacter(zone, 'invoker', origin, { tick }); invoker.tick(27); expect(tick).toBeCalledWith(invoker, 27); expect(Instance.gameServer?.handleCommand).not.toBeCalled(); }); test(`character doesn't wander if involved in conversation`, () => { jest.spyOn(Math, 'random').mockReturnValue(0.04); buildRoom(zone, 'otherRoom'); origin.definition.exits = [{ direction: 'north', destination: 'otherRoom' }]; origin.finalize(); const invoker = buildCharacter(zone, 'invoker', origin); const conversation = { tick: jest.fn().mockReturnValue(false) }; invoker.conversation = conversation as any; invoker.tick(27); expect(Instance.gameServer?.handleCommand).not.toBeCalled(); }); test(`character doesn't wander if following someone`, () => { jest.spyOn(Math, 'random').mockReturnValue(0.04); buildRoom(zone, 'otherRoom'); origin.definition.exits = [{ direction: 'north', destination: 'otherRoom' }]; origin.finalize(); const invoker = buildCharacter(zone, 'invoker', origin); const target = buildCharacter(zone, 'target', origin); invoker.follow(target); invoker.tick(27); expect(Instance.gameServer?.handleCommand).not.toBeCalled(); }); // Could use some more wander tests here test(`character doesn't wander if they can't wander`, () => { jest.spyOn(Math, 'random').mockReturnValue(0.04); buildRoom(zone, 'otherRoom'); origin.definition.exits = [{ direction: 'north', destination: 'otherRoom' }]; origin.finalize(); const invoker = buildCharacter(zone, 'invoker', origin, { flags: [CharacterFlag.SENTINEL] }); invoker.tick(27); expect(Instance.gameServer?.handleCommand).not.toBeCalled(); }); }); describe('toJson', () => { test('produces character definition based on live character', () => { const invoker = buildCharacter(zone, 'invoker', origin); const item = buildItem(zone, 'testItem'); const item2 = buildItem(zone, 'testItem2'); invoker.addItem(item); invoker.equipment.FEET = item2; invoker.workingData['testKey'] = 'testValue'; const output = invoker.toJson(); expect(output).toEqual({ key: 'invoker', name: 'invoker name', inventory: [ { key: 'testItem', name: 'testItem name', modifications: {}, workingData: {}, keywords: [], description: 'You see <y>testItem name<n>.', roomDescription: '<y>testItem name<n> is on the ground here.', }, ], equipment: { FEET: { key: 'testItem2', name: 'testItem2 name', modifications: {}, workingData: {}, keywords: [], description: 'You see <y>testItem2 name<n>.', roomDescription: '<y>testItem2 name<n> is on the ground here.', }, }, workingData: { testKey: 'testValue' }, }); }); }); describe('sendCommand', () => { test('sends command to game server for character', () => { const invoker = buildCharacter(zone, 'invoker', origin); invoker.sendCommand(`command test string`); expect(Instance.gameServer?.handleCommand).toBeCalledWith(invoker, `command test string`); }); }); describe('toString', () => { test('returns styled name', () => { const invoker = buildCharacter(zone, 'invoker', origin); expect(invoker.toString()).toEqual(`<c>invoker name<n>`); }); }); }); describe('Player', () => { describe('constructor', () => { test('initializes with extra data beyond character definition', () => { const definition: IPlayerDefinition = { accountId: 'testAccountId', room: 'origin@testZone', playerNumber: 27, key: 'testplayer', name: 'Testplayer', race: RaceType.GNOME, class: ClassType.CLERIC, abilities: defaultAbilities(), }; const player = new Player(definition); expect(player.accountId).toEqual('testAccountId'); expect(player.definition).toEqual(definition); expect(player.id.length).toBeGreaterThan(0); expect(player.key).toEqual('testplayer'); expect(player.name).toEqual('Testplayer'); expect(player.admin).toBeFalsy(); expect(player.npc).toBeFalsy(); expect(player.styledName).toEqual('<c>Testplayer<n>'); expect(player.roomDescription).toEqual('<c>Testplayer<n> is here.'); expect(player.description).toEqual('You see <c>Testplayer<n>.'); expect(player.race.type).toEqual(RaceType.GNOME); expect(player.class.type).toEqual(ClassType.CLERIC); expect(player.abilities).toEqual(defaultAbilities()); expect(player.keywords).toEqual([]); expect(player.following).toBeUndefined(); expect(player.followers).toEqual([]); expect(player.conversation).toBeUndefined(); expect(player.workingData).toEqual({}); expect(player.flags.flags).toEqual(0); expect(player.commandHandler).toBeUndefined(); expect(player.room).toEqual(origin); expect(player.zone).toEqual(origin.zone); }); }); describe('finalize', () => { test('adds items to inventory based on definition', () => { Instance.gameServer?.catalog.registerItemDefinition( { key: 'testItem', name: 'Test item', roomDescription: 'Test item room description', description: 'Test item look description', }, zone ); const definition: IPlayerDefinition = { accountId: 'testAccountId', room: 'origin@testZone', playerNumber: 27, key: 'testplayer', name: 'Testplayer', race: RaceType.GNOME, class: ClassType.CLERIC, abilities: defaultAbilities(), inventory: [{ key: 'testItem@testZone' }], }; const player = new Player(definition); expect(player.items.length).toEqual(0); player.finalize(); expect(player.items.length).toEqual(1); expect(player.items[0].key).toEqual('testItem@testZone'); }); test('shows message to user and room', () => { const definition: IPlayerDefinition = { accountId: 'testAccountId', room: 'origin@testZone', playerNumber: 27, key: 'testplayer', name: 'Testplayer', race: RaceType.GNOME, class: ClassType.CLERIC, abilities: defaultAbilities(), }; const player = new Player(definition); jest.spyOn(player.room, 'emitTo'); player.finalize(); expect(Instance.gameServer?.sendMessageToCharacter).toBeCalledWith('Testplayer', `You appear in a cloud of smoke...\n`); expect(player.room.emitTo).toBeCalledWith(`<c>Testplayer<n> appears in a cloud of smoke...`, [player]); }); test('messages can be suppressed', () => { const definition: IPlayerDefinition = { accountId: 'testAccountId', room: 'origin@testZone', playerNumber: 27, key: 'testplayer', name: 'Testplayer', race: RaceType.GNOME, class: ClassType.CLERIC, abilities: defaultAbilities(), }; const player = new Player(definition); jest.spyOn(player.room, 'emitTo'); player.finalize(true); expect(Instance.gameServer?.sendMessageToCharacter).not.toBeCalled(); expect(player.room.emitTo).not.toBeCalled(); }); }); describe('disconnect', () => { test('removes character from room', () => { const player = buildPlayer('player', origin); expect(origin.characters).toEqual([player]); player.disconnect(); expect(origin.characters).toEqual([]); }); test('shows message to room', () => { const player = buildPlayer('player', origin); jest.spyOn(player.room, 'emitTo'); player.disconnect(); expect(origin.emitTo).toBeCalledWith(`<c>playername<n> disappears in a cloud of smoke...`, [player]); }); }); describe('emitTo', () => { test('sends message to character via game server', () => { const player = buildPlayer('player', origin); player.emitTo('message to player'); expect(Instance.gameServer?.sendMessageToCharacter).toBeCalledWith(player.name, 'message to player\n'); }); }); describe('tick', () => { test('calls tick on conversation if it exists', () => { const player = buildPlayer('player', origin); const conversation = { tick: jest.fn().mockReturnValue(true) }; player.conversation = conversation as any; player.tick(27); expect(conversation.tick).toBeCalledWith(player, 27); }); test(`calls save if it hasn't happened within the save interval`, () => { const player = buildPlayer('player', origin); expect(player.lastSave).toEqual(-1); player.tick(27); expect(player.lastSave).not.toEqual(-1); }); }); describe('playerExists', () => { test('returns true if a player file exists', () => { (fs.existsSync as jest.Mock).mockReturnValue(true); expect(Player.playerExists('playername')).toBeTruthy(); expect(fs.existsSync).toBeCalledWith(`data/players/playername.json`); }); test('returns false if a player file does not exist', () => { (fs.existsSync as jest.Mock).mockReturnValue(false); expect(Player.playerExists('playername')).toBeFalsy(); expect(fs.existsSync).toBeCalledWith(`data/players/playername.json`); }); }); describe('load', () => { test('returns undefined if no player file exists', () => { (fs.existsSync as jest.Mock).mockReturnValue(false); expect(Player.load('playername')).toBeUndefined(); expect(fs.existsSync).toBeCalledWith(`data/players/playername.json`); }); test('returns player if player file exists', () => { (fs.existsSync as jest.Mock).mockReturnValue(true); (fs.readFileSync as jest.Mock).mockReturnValue( JSON.stringify({ accountId: 'testAccountId', room: 'origin@testZone', playerNumber: 27, key: 'testplayer', name: 'Testplayer', }) ); expect(Player.load('playername')?.key).toEqual('testplayer'); expect(fs.existsSync).toBeCalledWith(`data/players/playername.json`); expect(fs.readFileSync).toBeCalledWith(`data/players/playername.json`, 'utf-8'); }); }); describe('save', () => { test('writes player output to file', () => { const player = buildPlayer('player', origin); expect(player.lastSave).toEqual(-1); player.save(); // expect(player.lastSave).not.toEqual(-1); expect(fs.writeFileSync).toBeCalledWith( `data/players/playername.json`, JSON.stringify( { key: 'player', accountId: 'player', room: 'origin@testZone', playerNumber: 1, name: 'playername', race: RaceType.HUMANOID, class: ClassType.NONE, abilities: defaultAbilities(), inventory: [], equipment: {}, workingData: {}, }, null, 2 ), { encoding: 'utf-8' } ); }); }); }); describe('matchCharacters', () => { test('allows matching on character key with case insensitive matching', () => { const char1 = buildCharacter(zone, 'otherUser1', origin); let response = matchCharacters([char1], 'otherUser1'); expect(response?.[0].key).toEqual('otherUser1'); response = matchCharacters([char1], 'OTHERUSER1'); expect(response?.[0].key).toEqual('otherUser1'); }); test('allows matching on character key partial with case insensitive matching', () => { const char1 = buildCharacter(zone, 'otherUser1', origin); let response = matchCharacters([char1], 'otherUse'); expect(response?.[0].key).toEqual('otherUser1'); response = matchCharacters([char1], 'OTHERUSE'); expect(response?.[0].key).toEqual('otherUser1'); }); test('allows matching on character keywords with case insensitive matching', () => { const char1 = buildCharacter(zone, 'otherUser1', origin, { keywords: ['other-keyword'] }); let response = matchCharacters([char1], 'other-keyword'); expect(response?.[0].key).toEqual('otherUser1'); response = matchCharacters([char1], 'OTHER-KEYWORD'); expect(response?.[0].key).toEqual('otherUser1'); }); test('allows matching on character name with case insensitive matching', () => { const char1 = buildCharacter(zone, 'otherUser1', origin, { name: 'nameOfCharacter' }); let response = matchCharacters([char1], 'nameOfChar'); expect(response?.[0].key).toEqual('otherUser1'); response = matchCharacters([char1], 'NAMEOFCHAR'); expect(response?.[0].key).toEqual('otherUser1'); }); test('matching prefers full key to keywords', () => { const char1 = buildCharacter(zone, 'otherUser1', origin, { keywords: ['otherUser2'] }); const char2 = buildCharacter(zone, 'otherUser2', origin); let response = matchCharacters([char1, char2], 'otherUser2'); expect(response?.[0].key).toEqual('otherUser2'); }); test('matching prefers keywords to partial key', () => { const char1 = buildCharacter(zone, 'otherUser1', origin); const char2 = buildCharacter(zone, 'otherUser2', origin, { keywords: ['otherUser'] }); let response = matchCharacters([char1, char2], 'otherUser'); expect(response?.[0].key).toEqual('otherUser2'); }); test('matching prefers partial key to partial name', () => { const char1 = buildCharacter(zone, 'otherUser1', origin, { name: 'userKey' }); const char2 = buildCharacter(zone, 'userKey2', origin); let response = matchCharacters([char1, char2], 'userKey'); expect(response?.[0].key).toEqual('userKey2'); }); }); });
// ******************************************************************************* // Copyright (C) 2008 Sanjay Rajopadhye. All rights reserved // Author: DaeGon Kim // // This program 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. // // This program 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 this program; if not, If not, see // http://www.gnu.org/licenses/, or write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. // ******************************************************************************* package org.polymodel.polyhedralIR.polyIRCG.generator.C; import static org.polymodel.algebra.factory.IntExpressionBuilder.affine; import static org.polymodel.algebra.factory.IntExpressionBuilder.constraint; import static org.polymodel.algebra.factory.IntExpressionBuilder.term; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.polymodel.algebra.ComparisonOperator; import org.polymodel.algebra.Variable; import org.polymodel.algebra.affine.AffineExpression; import org.polymodel.algebra.factory.IntExpressionBuilder; import org.polymodel.algebra.prettyprinter.algebra.OUTPUT_FORMAT; import org.polymodel.polyhedralIR.AffineFunction; import org.polymodel.polyhedralIR.AffineSystem; import org.polymodel.polyhedralIR.Domain; import org.polymodel.polyhedralIR.ParameterDomain; import org.polymodel.polyhedralIR.StandardEquation; import org.polymodel.polyhedralIR.Type; import org.polymodel.polyhedralIR.UseEquation; import org.polymodel.polyhedralIR.VariableDeclaration; import org.polymodel.polyhedralIR.expression.ReduceExpression; import org.polymodel.polyhedralIR.factory.PolyhedralIRUserFactory; import org.polymodel.polyhedralIR.factory.PolyhedralIRUtility; import org.polymodel.polyhedralIR.impl.PolyhedralIRInheritedDepthFirstVisitorImpl; import org.polymodel.polyhedralIR.polyIRCG.Body; import org.polymodel.polyhedralIR.polyIRCG.CodeUnit; import org.polymodel.polyhedralIR.polyIRCG.Function; import org.polymodel.polyhedralIR.polyIRCG.Statement; import org.polymodel.polyhedralIR.polyIRCG.C.CLoop; import org.polymodel.polyhedralIR.polyIRCG.factory.PolyIRCGUserFactory; import org.polymodel.polyhedralIR.polyIRCG.generator.CodeGenUtility; import org.polymodel.polyhedralIR.targetMapping.SpaceTimeLevel; import org.polymodel.polyhedralIR.targetMapping.TargetMapping; import org.polymodel.polyhedralIR.util.WhileSystemUtility; public class StatementVisitorForWriteC extends PolyhedralIRInheritedDepthFirstVisitorImpl { protected static final PolyIRCGUserFactory _fact = PolyIRCGUserFactory.INSTANCE; //Input protected final CodeUnit unit; protected final TargetMapping targetMapping; private String verifyPrefix; //local protected ComputeReductionNumber reductionNumbers; /** * Constructs a CodeUnit to execute a system using demand-driven code generation. * WriteC is per system * * @param system * @param unit */ public static void construct(AffineSystem system, CodeUnit unit) { StatementVisitorForWriteC visitor = new StatementVisitorForWriteC(unit, system.getTargetMapping()); system.accept(visitor); } protected StatementVisitorForWriteC(CodeUnit unit, TargetMapping mapping) { this.unit = unit; this.targetMapping = mapping; if (unit.getSystem().getName().endsWith("_verify")) { this.verifyPrefix = "verify_"; ExpressionPrinterForWriteC.verifyPrefix = "verify_"; } else { this.verifyPrefix = ""; ExpressionPrinterForWriteC.verifyPrefix = ""; } } @Override public void inAffineSystem(AffineSystem a) { reductionNumbers = new ComputeReductionNumber(); a.accept(reductionNumbers); Function function = _fact.createFunction(a.getName(), "void"); //This is the entry point for executing this system function.setEntryPoint(true); //Register all variables for (VariableDeclaration var : a.getInputs()) { function.getInputs().add(unit.findVariable(targetMapping.getMemoryMaps().get(var).getSpace().getName())); } for (VariableDeclaration var : a.getOutputs()) { function.getOutputs().add(unit.findVariable(targetMapping.getMemoryMaps().get(var).getSpace().getName())); } for (VariableDeclaration var : a.getLocals()) { function.getLocals().add(unit.findVariable(targetMapping.getMemoryMaps().get(var).getSpace().getName())); } //Add parameter checking function.getBodies().add(_fact.createParameterCheck(a.getParameters())); //Add malloc function.getBodies().add(_fact.createVariableInitialization(function)); if (a.getWhileInfo() != null) { //If this is a while system //Add flag reset function.getBodies().add(_fact.createFlagVariableReset(function)); AffineExpression affineLowerbound = WhileSystemUtility.historyOfCondition(a); // When to start checking the termination condition function.setNumberOfTimeIterationsForFirstConditionCheck(affineLowerbound.toString()); } if (a.getWhileInfo() != null) { //in case of a while system /* * Generate loops only for the duplicates of output variables which * are added as local variables. The name ends with "__Wlocal__Main" */ for (VariableDeclaration var : a.getLocals()) { if (!var.getName().endsWith(WhileSystemUtility.WHILE_LOCAL_MAIN_VAR_POSTFIX) || var.getName().startsWith(CodeGenConstantsForC.FLAG_PREFIX)) { continue; } addLoop(a, function, var); } /* * This is added to distinguish the loops that should appear * after the time (or while) loop. */ function.getBodies().add(_fact.createBody("//Copy output")); for (VariableDeclaration varOut : a.getOutputs()) { addLoopToCopyOutput(a, function, varOut); } } else { //Create a loop that evaluate all points of the output for (VariableDeclaration var : a.getOutputs()) { addLoop(a, function, var); } } //Add free function.getBodies().add(_fact.createVariableFinalization(function)); unit.getFunctions().add(function); } private void addLoop(AffineSystem a, Function function, VariableDeclaration var) { //Create a statement that scans an output variable, and stores // the result to the memory location List<String> evalFuncParams = new LinkedList<String>(); for (Variable iv : var.getDomain().getParams()) { evalFuncParams.add(iv.toString()); }for (Variable iv : var.getDomain().getIndices()) { evalFuncParams.add(iv.toString()); } Statement stmt = _fact.createStatement( CodeGenUtility.createStatementName(unit, 0), var.getDomain().copy(), CodeGenConstantsForC.WRITEC_EVAL_PREFIX+this.verifyPrefix+var.getName()+"("+ CodeGenUtility.toStringList(evalFuncParams, ",")+")"); // Remove time domain from the statements in the loop. So that an // outer loop is not generated for time loop. We are inserting this // time loop manually when generating code. Check the BaseFunction.xtend if (unit.getSystem().getWhileInfo() != null && function.isEntryPoint()) { List<Variable> vl = new ArrayList<Variable>(stmt.getDomain().getIndices()); vl.remove(0); //(t,i,j,...->i,j,...) AffineFunction af = PolyhedralIRUtility.createProjection(stmt.getDomain(), vl); org.polymodel.polyhedralIR.Domain newDomain = stmt.getDomain().image(af); // Above newDomain has indices names starting from t, i, ... // But we do not need t as the first dimension since that is // the one we just removed and this will make issues in the // generated code. Therefore, we need to change the names of // indices. For that we create a domain {i,j,... | 0==0} and get // the intersection of this domain with newDomain. // This will change the indices to i,j,... org.polymodel.polyhedralIR.Domain trueDomain = PolyhedralIRUserFactory.eINSTANCE.createDomain(stmt.getDomain().getParams(), vl, IntExpressionBuilder.constraintSystem(constraint(affine(term(0)), affine(term(0)), ComparisonOperator.EQ))); newDomain = trueDomain.intersection(newDomain); stmt.setDomain(newDomain); } addStatementToLoop(a, function, stmt); } private void addLoopToCopyOutput(AffineSystem a, Function function, VariableDeclaration varOut) { //Create a statement that scans an output variable, and stores the result to the memory location List<String> varOutIndices = new LinkedList<String>(); for (Variable iv : varOut.getDomain().getIndices()) { varOutIndices.add(iv.toString()); } VariableDeclaration varOutLocalMain = a.getVariableDeclaration( varOut.getName()+WhileSystemUtility.WHILE_LOCAL_MAIN_VAR_POSTFIX); List<String> varOutLocalMainIndices = new LinkedList<String>(); for (Variable iv : varOutLocalMain.getDomain().getIndices()) { varOutLocalMainIndices.add(iv.toString()); } Statement stmt = _fact.createStatement( CodeGenUtility.createStatementName(unit, 0), varOut.getDomain().copy(), varOut.getName()+"("+CodeGenUtility.toStringList(varOutIndices, ",")+ ") = " + varOutLocalMain.getName()+"("+ CodeGenUtility.toStringList(varOutLocalMainIndices, ",")+")"); addStatementToLoop(a, function, stmt); } private void addStatementToLoop(AffineSystem a, Function function, Statement stmt) { CLoop loop = _fact.createCLoop(a.getParameters(), 0); loop.getStatements().add(stmt); function.getBodies().add(loop); } @Override public void outStandardEquation(StandardEquation s) { Function function = _fact.createFunction( CodeGenConstantsForC.WRITEC_EVAL_PREFIX+this.verifyPrefix+s.getVariable().getName(), s.getVariable().getType() ); //Add loop indices as function parameters for (Variable iv : s.getVariable().getDomain().getIndices()) { function.getParameters().add(_fact.createBasicVariable(iv.toString(), "int")); } SpaceTimeLevel stlevel = targetMapping.getSpaceTimeLevel(0); StringBuffer sbody = new StringBuffer(); //Get the access function AffineFunction accessFunc = stlevel.getAccessFunction(s.getVariable()); //compose it with identity of the variable domain, just so that names match accessFunc = accessFunc.compose(PolyhedralIRUtility.createIdentityFunction(s.getVariable().getDomain())); //Pretty print the access function to pass the indices List<String> access = new LinkedList<String>(); for (AffineExpression ile : accessFunc.getExpressions()) { access.add(ile.simplify().toString(OUTPUT_FORMAT.C)); } String valAccess = targetMapping.getMemoryMaps().get(s.getVariable()).getSpace().getName(); if (access.size() > 0) { valAccess += "("+CodeGenUtility.toStringList(access, ",")+")"; } String flagAccess = CodeGenConstantsForC.FLAG_PREFIX+valAccess; //Pre compute strings for self-dependence check StringBuffer iterationFormat = new StringBuffer(); for (int i = 0; i < s.getVariable().getDomain().getNIndices(); i++) { if (iterationFormat.length() > 0) { iterationFormat.append(","); } iterationFormat.append("%d"); } StringBuffer iterationParams = new StringBuffer(); for (int i = 0; i < s.getVariable().getDomain().getNIndices(); i++) { //Add "," from the beginning, to make it work in scalar variables iterationParams.append(","+s.getVariable().getDomain().getIndices().get(i).toString()); } //Generate code that checks for the flag and computes the RHS of an equation //This code is very specific to WriteC, so not even trying to make it generic and using BasicStatement sbody.append(String.format("if ( %s == 'N' ) {\n", flagAccess)); sbody.append(String.format(" %s = 'I';\n", flagAccess)); sbody.append(String.format( "//Body for %s\n", s.getVariable().getName())); sbody.append(String.format(" %s = %s;\n", valAccess, ExpressionPrinterForWriteC.print(s.getExpression()))); sbody.append(String.format(" %s = 'F';\n", flagAccess)); sbody.append(String.format("} else if ( %s == 'I' ) {\n", flagAccess)); sbody.append(String.format(" printf(\"There is a self dependence on %s at (%s) \\n\"%s);\n", s.getVariable().getName(), iterationFormat, iterationParams)); sbody.append(" exit(-1);\n"); sbody.append("}\n"); sbody.append(String.format("return %s;", valAccess)); function.getBodies().add(_fact.createBody(sbody.toString())); unit.getFunctions().add(function); } @Override public void outReduceExpression(ReduceExpression r) { if (r.getContainerEquation() instanceof UseEquation) throw new RuntimeException("TODO: implement this method for UseEquation"); Type type = r.getExpressionType(); String name = CodeGenConstantsForC.getReductionFunctionName((StandardEquation) r.getContainerEquation(), reductionNumbers.getReductionNumber(r)); Function function = _fact.createFunction(name, type); //Create domain to scan // Domain[] scanDoms = CodeGenUtility.createReductionScanningDomain(r, CodeGenConstantsForC.REDUCTION_PARAM_PREFIX); Domain[] scanDoms = CodeGenUtility.createReductionScanningDomain(r); ParameterDomain extendedParam = (ParameterDomain)scanDoms[0]; Domain scanDom = scanDoms[1]; //Add the parameters to function parameters for (int i = r.getContextDomain().getNParams(); i < extendedParam.getNParams(); i++) { function.getParameters().add(_fact.createBasicVariable(extendedParam.getParams().get(i).toString(), "int")); } //Loop to scan the constructed slice of the reduction CLoop loop = _fact.createCLoop(extendedParam, 0); //Reduction body String expr = ExpressionPrinterForWriteC.print(r.getExpr()); //Make it accumulation expr = CodeGenUtilityForC.createAccumulation(r.getOP(), r.getExpressionType(), CodeGenConstantsForC.REDUCE_VAR_NAME, expr); loop.getStatements().add(_fact.createStatement(CodeGenUtility.createStatementName(unit, 0), scanDom, expr)); //Create a body to initialize variable used during reduction Body reduceVar = _fact.createBody(r.getExpressionType() + " "+CodeGenConstantsForC.REDUCE_VAR_NAME+" = " + r.getIdentityValue()+";"); //Body for returning the result Body returnStatement = _fact.createBody("return "+CodeGenConstantsForC.REDUCE_VAR_NAME+";"); //Set all bodies to the function function.getBodies().add(reduceVar); function.getBodies().add(loop); function.getBodies().add(returnStatement); unit.getFunctions().add(function); } }
import { Request, Response } from "express"; import { RoleModel } from "../../Models/RoleModel"; import { DB } from "../../helpers/DB"; import { JWT } from "../../helpers/JWT"; import { ERROR_MESSAGES, SUCCESS_MESSAGES } from "../../../config/statusMessages/messages"; import { ROLES_PERMISSIONS_TYPE, ROLES_TYPE } from "../../../config/dataStructure/structure"; export class RoleController extends RoleModel { getRoles = async (req: Request, res: Response): Promise<Response> => { try { const AUTH = req.headers.authorization; if (!(await JWT.validatePermission(AUTH, 'ROLE-READ'))) { return res.status(401).json({ error: { message: ERROR_MESSAGES.PERMISSIONS_DENIED } }); } if (JWT.user.Roles!.rol_name === 'SUPER ADMIN') { return res.status(200).json(await this.with([{ RolesPermissions: { include: { Permissions: true } } }]).get()); } else { return res.status(200).json(await this.with([ { RolesPermissions: { where: { role_id: JWT.user.Roles!.id }, include: { Permissions: true } } } ]).whereNot('rol_name', 'SUPER ADMIN').get()); } } catch (error: any) { return res.status(409).json({ error: { message: ERROR_MESSAGES.CLIENT_SERVER_ERROR } }); } }; getRole = async (req: Request, res: Response): Promise<Response> => { try { if (!(await JWT.validatePermission(req.headers.authorization, 'ROLE-READ'))) { return res.status(401).json({ error: { message: ERROR_MESSAGES.PERMISSIONS_DENIED } }); } const id = parseInt(req.params.id); return res.json(await this.where('id', id).get()); } catch (error: any) { return res.json({ error: { message: ERROR_MESSAGES.CLIENT_SERVER_ERROR } }); } }; storeRoleAndPermissions = async (req: Request, res: Response): Promise<Response> => { try { const AUTH = req.headers.authorization; if (!(await JWT.validatePermission(AUTH, 'ROLE-CREATE'))) { return res.status(401).json({ error: { message: ERROR_MESSAGES.PERMISSIONS_DENIED } }); } const ROLE = { rol_name: req.body.rol_name }; const SAVE = await this.create(ROLE); if (SAVE.error) return res.status(409).json({ error: { message: `${SAVE.error}` } }); const PERMISSIONS: number[] = req.body.permission_id; console.log("ROL CREADO:", SAVE); PERMISSIONS.forEach(async (permission: number) => { await DB.table('RolesPermissions').create({ role_id: SAVE.id, permission_id: permission }, false); }); return res.status(201).json({ message: SUCCESS_MESSAGES.STORED }); } catch (error) { return res.status(401).json({ message: ERROR_MESSAGES.CLIENT_SERVER_ERROR }); } }; updateRoleAndPermissions = async (req: Request, res: Response): Promise<Response> => { try { if (!(await JWT.validatePermission(req.headers.authorization, 'ROLE-UPDATE'))) { return res.status(401).json({ error: { message: ERROR_MESSAGES.PERMISSIONS_DENIED } }); } /* Para actualzar rol name en caso de cambios*/ const ROLE_ID = parseInt(req.body.role_id); /* Para actualizar permisos entre rol y permisos */ const PERMISSIONS: number[] = req.body.permissions_list; const REQUEST_CURRENT_PERMISSIONS = await DB.table('Roles').with(['RolesPermissions']).where('id', ROLE_ID).get<ROLES_TYPE>(); const GET_CURRENT_PERMISSIONS: ROLES_PERMISSIONS_TYPE[] = REQUEST_CURRENT_PERMISSIONS[0].RolesPermissions!; const permissionsToAdd = PERMISSIONS.filter(permission => !GET_CURRENT_PERMISSIONS.some(p => p.permission_id === permission)); const permissionsToRemove = GET_CURRENT_PERMISSIONS.filter(permission => !PERMISSIONS.includes(permission.permission_id)); // Agregar nuevos permisos for (const permission_to_store of permissionsToAdd) { const DATA_TO_CREATE = { role_id: ROLE_ID, permission_id: permission_to_store }; const SAVE = await DB.table('RolesPermissions').create(DATA_TO_CREATE, false); if (SAVE.error) return res.status(409).json({ error: { message: `${SAVE.error}` } }); } // Eliminar permisos del rol for (const permissionToRemove of permissionsToRemove) { const TO_DELETE = { role_id: ROLE_ID, permission_id: permissionToRemove.permission_id }; const DELETE = await DB.table('RolesPermissions').deleteMany(TO_DELETE); if (DELETE.error) return res.status(409).json({ error: { message: `${DELETE.error}` } }); } return res.status(200).json({ message: SUCCESS_MESSAGES.UPDATED }); } catch (error: any) { return res.status(409).json({ error: { message: ERROR_MESSAGES.CLIENT_SERVER_ERROR } }); } }; deleteRole = async (req: Request, res: Response): Promise<Response> => { try { if (!(await JWT.validatePermission(req.headers.authorization, 'ROLE-DELETE'))) { return res.status(401).json({ error: { message: ERROR_MESSAGES.CLIENT_SERVER_ERROR } }); } const ROLE_ID: number = parseInt(req.params.id); const ROLES_PERMISSIONS: ROLES_PERMISSIONS_TYPE[] = Object.values(await DB.table('RolesPermissions').where('role_id', ROLE_ID).get()); for (const obj of ROLES_PERMISSIONS) if (obj.id) await DB.delete(obj.id); const DELETE = await this.delete(ROLE_ID); if (DELETE?.error) return res.status(409).json({ error: { message: DELETE.error } }); return res.status(204).json({ message: SUCCESS_MESSAGES.DELETED }); } catch (error: any) { return res.status(400).json({ error: { message: error } }); } }; }
package org.hyperskill.musicplayer import android.app.AlertDialog import android.widget.Button import android.widget.SeekBar import android.widget.TextView import androidx.fragment.app.FragmentContainerView import androidx.recyclerview.widget.RecyclerView import org.hyperskill.musicplayer.internals.CustomShadowAsyncDifferConfig import org.hyperskill.musicplayer.internals.CustomMediaPlayerShadow import org.hyperskill.musicplayer.internals.MusicPlayerUnitTests import org.junit.Assert.assertEquals import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows import org.robolectric.annotation.Config // version 1.4 @RunWith(RobolectricTestRunner::class) @Config(shadows = [CustomMediaPlayerShadow::class, CustomShadowAsyncDifferConfig::class]) class Stage1UnitTestB : MusicPlayerUnitTests<MainActivity>(MainActivity::class.java){ private val mainButtonSearch by lazy { val view = activity.findViewByString<Button>("mainButtonSearch") val expectedText = "search" val actualText = view.text.toString().lowercase() assertEquals("wrong text for mainButtonSearch", expectedText, actualText) view } private val mainSongList by lazy { activity.findViewByString<RecyclerView>("mainSongList") } private val mainFragmentContainer by lazy { activity.findViewByString<FragmentContainerView>("mainFragmentContainer") } val mainMenuItemIdAddPlaylist = "mainMenuAddPlaylist" val mainMenuItemIdLoadPlaylist = "mainMenuLoadPlaylist" val mainMenuItemIdDeletePlaylist = "mainMenuDeletePlaylist" @Test fun checkMainActivityComponentsExist() { testActivity { mainButtonSearch mainSongList mainFragmentContainer } } @Test fun checkPlayerControllerFragmentComponentsExist() { testActivity { mainFragmentContainer val controllerTvCurrentTime = mainFragmentContainer.findViewByString<TextView>("controllerTvCurrentTime") val actualCurrentTime = controllerTvCurrentTime.text.toString() val expectedCurrentTime = "00:00" val messageWrongInitialCurrentTime = "Wrong initial value for controllerTvCurrentTime" assertEquals(messageWrongInitialCurrentTime, expectedCurrentTime, actualCurrentTime) val controllerTvTotalTime = mainFragmentContainer.findViewByString<TextView>("controllerTvTotalTime") val actualTotalTime = controllerTvTotalTime.text.toString() val expectedTotalTime = "00:00" val messageWrongInitialTotalTime = "Wrong initial value for controllerTvTotalTime" assertEquals(messageWrongInitialTotalTime, expectedTotalTime, actualTotalTime) mainFragmentContainer.findViewByString<SeekBar>("controllerSeekBar") val controllerBtnPlayPause = mainFragmentContainer.findViewByString<Button>("controllerBtnPlayPause") val actualBtnPlayPauseText = controllerBtnPlayPause.text.toString().lowercase() val expectedBtnPlayPauseText = "play/pause" val messageWrongInitialBtnPlayPauseText = "Wrong initial value for controllerBtnPlayPause" assertEquals(messageWrongInitialBtnPlayPauseText, expectedBtnPlayPauseText, actualBtnPlayPauseText) val controllerBtnStop = mainFragmentContainer.findViewByString<Button>("controllerBtnStop") val actualBtnStopText = controllerBtnStop.text.toString().lowercase() val expectedBtnStopText = "stop" val messageWrongInitialBtnStopText = "Wrong initial value for controllerBtnStop" assertEquals(messageWrongInitialBtnStopText, expectedBtnStopText, actualBtnStopText) } } @Ignore @Test fun checkSearchButtonNoSongsFound() { testActivity { mainButtonSearch mainButtonSearch.clickAndRun() assertLastToastMessageEquals( "wrong toast message after click to mainButtonSearch", "no songs found" ) } } @Test fun checkMenuItemAddPlaylistWithNoSongs() { testActivity { activity.clickMenuItemAndRun(mainMenuItemIdAddPlaylist) assertLastToastMessageEquals( "wrong toast message after click to mainMenuItemIdAddPlaylist", "no songs loaded, click search to load songs" ) } } @Test fun checkMenuItemLoadPlaylist() { testActivity { activity.clickMenuItemAndRun(mainMenuItemIdLoadPlaylist) val (alertDialog, shadowAlertDialog) = getLastAlertDialogWithShadow( errorMessageNotFound = "No Dialog was shown after click on mainMenuLoadPlaylist." ) val actualTitle = shadowAlertDialog.title.toString().lowercase() val messageWrongTitle = "Wrong title found on dialog shown after click on mainMenuLoadPlaylist" val expectedTitle = "choose playlist to load" assertEquals(messageWrongTitle, expectedTitle, actualTitle) alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).clickAndRun() } } @Test fun checkMenuItemDeletePlaylist() { testActivity { activity.clickMenuItemAndRun(mainMenuItemIdDeletePlaylist) val (alertDialog, shadowAlertDialog) = getLastAlertDialogWithShadow( errorMessageNotFound = "No Dialog was shown after click on mainMenuDeletePlaylist." ) val actualTitle = shadowAlertDialog.title.toString().lowercase() val messageWrongTitle = "Wrong title found on dialog shown after click on mainMenuDeletePlaylist" val expectedTitle = "choose playlist to delete" assertEquals(messageWrongTitle, expectedTitle, actualTitle) alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).clickAndRun() } } @Test fun checkControllerStopButtonBeforeSearch() { testActivity { mainFragmentContainer val controllerBtnStop = mainFragmentContainer.findViewByString<Button>("controllerBtnStop") controllerBtnStop.clickAndRun() // should not throw Exception } } @Test fun checkControllerSeekBarBeforeSearch() { testActivity { mainFragmentContainer val controllerSeekBar = mainFragmentContainer.findViewByString<SeekBar>("controllerSeekBar") if(Shadows.shadowOf(controllerSeekBar).onSeekBarChangeListener != null) { controllerSeekBar.setProgressAsUser(1) //should not throw exception } else { // ok } } } @Test fun checkControllerPlayPauseButtonBeforeSearch() { testActivity { mainFragmentContainer val controllerBtnPlayPause = mainFragmentContainer.findViewByString<Button>("controllerBtnPlayPause") controllerBtnPlayPause.clickAndRun() // should not throw Exception } } }
<template> <div class="detail-shop-info"> <div class="shop-top"> <img :src="shop.logo" alt=""> <span class="shop-title">{{shop.name}}</span> </div> <div class="shop-middle"> <div class="shop-middle-item shop-middle-left"> <div class="info-sells"> <div class="sells-count">{{shop.sells | sellCountFilter}}</div> <div class="sells-text">总销量</div> </div> <div class="info-goods"> <div class="goods-count">{{shop.goodsCount}}</div> <div class="goods-text">全部宝贝</div> </div> </div> <div class="shop-middle-item shop-middle-right"> <table> <tr v-for="(item,index) in shop.score" :key="index"> <td>{{item.name}}</td> <td class="score" :class="{'score-better':item.isBetter}">{{item.score}}</td> <td class="better" :class="{'better-more':item.isBetter}"><span>{{item.isBetter ? '高' : '低'}}</span></td> </tr> </table> </div> </div> <div class="shop-bottom"> <span class="enter-shop">进店逛逛</span> </div> </div> </template> <script> export default { name:'DetailShopInfo', data() { return { } }, props: { shop:{ type: Object, default(){ return {} } } }, filters:{ sellCountFilter:function(value){ if (value < 10000) return value; return (value/10000).toFixed(2) + '万' } } } </script> <style scoped lang='less'> .detail-shop-info{ padding: 25px 8px; border-bottom: 5px solid #f2f2f8; .shop-top{ line-height: 45px; display: flex; align-items: center; img{ width: 45px; height: 45px; border-radius: 50%; border: 1px solid rgba(0, 0, 0, .1); } .shop-title{ margin-left: 10px; vertical-align: middle; } } .shop-middle{ margin-top: 15px; display: flex; align-items: center; .shop-middle-item{ flex: 1; } .shop-middle-left{ display: flex; justify-content: space-evenly; color: #333; text-align: center; border-right: 1px solid rgba(0, 0, 0, .1); .sells-count,.goods-count{ font-size: 18px; } .sells-text,.goods-text{ margin-top: 10px; font-size: 12px; } } .shop-middle-right{ font-size: 13px; color: #333; table{ width: 120px; margin-left: 30px; td{ padding: 5px 0; } .score{ color: #5ea732; } .score-better{ color: #f13e3a!important; } .better{ span{ background: #5ea732; color: #fff; text-align: center; } } .better-more{ span{ background: #f13e3a; } } } } } .shop-bottom{ font-size: 20px; text-align: center; .enter-shop{ display: inline-block; width: 40%; padding: 8px 0; text-align: center; border-radius: 7px; margin: 10px 0 0; background: #eee; } } } </style>
import express from 'express'; import session from 'express-session'; import user_routes from './routers/user.js'; import admin_product_routes from './routers/admin/products.js'; import forAdmin from './controllers/auth.js'; import User from './models/user.js'; const app = express(); const hostname = '127.0.0.1'; const port = 3001; app.use(express.json()); app.use(express.urlencoded({extended:false})); app.use(session({ secret: 'ini adalah kode secret###', resave: false, saveUninitialized: true, cookie: { maxAge: 60 * 60 * 1000 } // 1 hour })); app.use('/user',user_routes); app.use('/admin/products',forAdmin, admin_product_routes); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('index', { user:req.session.user||"" }); }) app.get('/create-db', (req, res) => { User.sync({force:true}); res.send('create db'); }) app.get('/forbidden', (req, res) => { res.render('forbidden',{ user:req.session.user||"" }); }) app.get('*', (req,res)=> { res.redirect('/') }) app.listen(port, () => { console.log(`Server running at http://${hostname}:${port}`); })
// Importation de la classe Song depuis le fichier de définition de type dans le répertoire "@/types" import { Song } from "@/types"; // Importation de la fonction `createServerComponentClient` pour créer un client Supabase côté serveur import { createServerComponentClient } from "@supabase/auth-helpers-nextjs"; // Importation de l'objet cookies pour gérer les cookies côté serveur import { cookies } from "next/headers"; // Importation de la fonction `getSongs` pour récupérer toutes les chansons import getSongs from "@/actions/getSongs"; // Définition de la fonction `getSongsByTitle` qui retourne une promesse d'un tableau de chansons (Song[]) const getSongsByTitle = async (title: string): Promise<Song[]> => { // Création d'un client Supabase spécifique au côté serveur const supabase = createServerComponentClient({ // Les cookies sont utilisés pour l'authentification et d'autres fonctionnalités côté serveur cookies: cookies }); // Vérification si un titre est fourni en paramètre if (!title) { // Si aucun titre n'est fourni, récupère toutes les chansons à l'aide de la fonction `getSongs` const allSongs = await getSongs(); // Retourne toutes les chansons return allSongs; } // Récupération des données de la table 'songs' à partir de Supabase const { data, error } = await supabase.from('songs') // Sélection de toutes les colonnes (*) .select('*') // Recherche insensible à la casse dans le titre de la chanson .ilike('title', `%${title}%`) // Tri des résultats par ordre décroissant de la colonne 'created_at' .order('created_at', { ascending: false }); // Gestion des erreurs, si une erreur survient lors de la récupération des données if (error) { // Affichage de l'erreur dans la console console.log(error); } // Retourne les données récupérées sous forme de tableau (ou un tableau vide si aucune donnée n'a été trouvée) return (data as any) || []; } // Exportation de la fonction pour utilisation ailleurs dans l'application export default getSongsByTitle;
# Split Linked List in Parts ## Problem Description Given the head of a singly linked list and an integer `k`, your task is to split the linked list into `k` consecutive linked list parts. The length of each part should be as equal as possible, with no two parts differing in size by more than one node. The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. ### Example 1: **Input:** ``` head = [1,2,3], k = 5 ``` **Output:** ``` [[1],[2],[3],[],[]] ``` ### Example 2: **Input:** ``` head = [1,2,3,4,5,6,7,8,9,10], k = 3 ``` **Output:** ``` [[1,2,3,4],[5,6,7],[8,9,10]] ``` ## Approach and Solution To solve this problem, we follow these steps: 1. Find the length of the linked list by iterating through it. 2. Calculate the average size of each part and the number of parts that should have one extra node. 3. Iterate through the linked list again, splitting it into `k` parts, and updating the `result` array. - For each part, we determine its size based on the calculated average and extra nodes. - We maintain two pointers - `current` and `temp` - to split the list. - If a part is empty, we append `None` to the `result` array. - Otherwise, we append the head of the current part to the `result`, update the `current` pointer, and sever the connection to form the next part. ### Time Complexity The time complexity of this solution is O(N), where N is the number of nodes in the linked list. We iterate through the list twice, first to find its length and second to split it into parts. ### Space Complexity The space complexity is O(k), as we store the resulting linked list parts in an array of size `k`. In the worst case, when k is equal to the length of the linked list, this would be O(N). However, in practice, it is O(k).
/* Copyright © 2011-2012 Clint Bellanger Copyright © 2012 Stefan Beller This file is part of FLARE. FLARE 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. FLARE 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 FLARE. If not, see http://www.gnu.org/licenses/ */ /** * class WidgetTooltip */ #include "FileParser.h" #include "WidgetTooltip.h" #include "Settings.h" #include "Utils.h" #include "UtilsParsing.h" using namespace std; int TOOLTIP_CONTEXT = TOOLTIP_NONE; WidgetTooltip::WidgetTooltip() { FileParser infile; // load tooltip settings from engine config file if (infile.open(mods->locate("engine/tooltips.txt").c_str())) { while (infile.next()) { if (infile.key == "tooltip_offset") offset = toInt(infile.val); else if (infile.key == "tooltip_width") width = toInt(infile.val); else if (infile.key == "tooltip_margin") margin = toInt(infile.val); } infile.close(); } else fprintf(stderr, "Unable to open engine/tooltips.txt!\n"); } /** * Knowing the total size of the text and the position of origin, * calculate the starting position of the background and text */ Point WidgetTooltip::calcPosition(int style, Point pos, Point size) { Point tip_pos; // TopLabel style is fixed and centered over the origin if (style == STYLE_TOPLABEL) { tip_pos.x = pos.x - size.x/2; tip_pos.y = pos.y - offset; } // Float style changes position based on the screen quadrant of the origin // (usually used for tooltips which are long and we don't want them to overflow // off the end of the screen) else if (style == STYLE_FLOAT) { // upper left if (pos.x < VIEW_W_HALF && pos.y < VIEW_H_HALF) { tip_pos.x = pos.x + offset; tip_pos.y = pos.y + offset; } // upper right else if (pos.x >= VIEW_W_HALF && pos.y < VIEW_H_HALF) { tip_pos.x = pos.x - offset - size.x; tip_pos.y = pos.y + offset; } // lower left else if (pos.x < VIEW_W_HALF && pos.y >= VIEW_H_HALF) { tip_pos.x = pos.x + offset; tip_pos.y = pos.y - offset - size.y; } // lower right else if (pos.x >= VIEW_W_HALF && pos.y >= VIEW_H_HALF) { tip_pos.x = pos.x - offset - size.x; tip_pos.y = pos.y - offset - size.y; } } return tip_pos; } /** * Tooltip position depends on the screen quadrant of the source. * Draw the buffered tooltip if it exists, else render the tooltip and buffer it */ void WidgetTooltip::render(TooltipData &tip, Point pos, int style, SDL_Surface *target) { if (target == NULL) { target = screen; } if (tip.tip_buffer == NULL) { createBuffer(tip); } Point size; size.x = tip.tip_buffer->w; size.y = tip.tip_buffer->h; Point tip_pos = calcPosition(style, pos, size); SDL_Rect dest; dest.x = tip_pos.x; dest.y = tip_pos.y; SDL_BlitSurface(tip.tip_buffer, NULL, target, &dest); } /** * Rendering a wordy tooltip (TTF to raster) can be expensive. * Instead of doing this each frame, do it once and cache the result. */ void WidgetTooltip::createBuffer(TooltipData &tip) { if (tip.lines.empty()) { tip.lines.resize(1); tip.colors.resize(1); } // concat multi-line tooltip, used in determining total display size string fulltext; fulltext = tip.lines[0]; for (unsigned int i=1; i<tip.lines.size(); i++) { fulltext = fulltext + "\n" + tip.lines[i]; } font->setFont("font_regular"); // calculate the full size to display a multi-line tooltip Point size = font->calc_size(fulltext, width); // WARNING: dynamic memory allocation. Be careful of memory leaks. tip.tip_buffer = createAlphaSurface(size.x + margin+margin, size.y + margin+margin); // Currently tooltips are always opaque SDL_SetAlpha(tip.tip_buffer, 0, 0); // style the tooltip background // currently this is plain black SDL_FillRect(tip.tip_buffer, NULL, 0); int cursor_y = margin; for (unsigned int i=0; i<tip.lines.size(); i++) { font->render(tip.lines[i], margin, cursor_y, JUSTIFY_LEFT, tip.tip_buffer, size.x, tip.colors[i]); cursor_y = font->cursor_y; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <!-- Шапка сайта --> <header> Header <!-- Навигация по сайту --> <nav>Navigation</nav> </header> <!-- Основное содержимое документа (уникальное) --> <main> <!-- Независимый блок (может включать другие section, header, footer) --> <section>Section 1</section> <section> Section 1 <!-- Семантически выделенный блок информации --> <article>Article1</article> </section> </main> <!-- Второстепенное содержимое документа --> <aside>Aside</aside> <!-- Подвал сайта --> <footer>Footer</footer> </body> </html> <!-- Теги расположения: header, footer, nav, aside ... Теги содержания: article, figure ... -->
import { Meta, Story } from '@storybook/react/types-6-0'; import React from 'react'; import Button, { ButtonProps } from '../components/Button'; export default { title: 'Button', component: Button, argTypes: { color: { defaultValue: 'default' }, }, } as Meta; const Template: Story<ButtonProps> = (args: ButtonProps) => ( <Button {...args}>Button</Button> ); export const DefaultText = Template.bind({}); export const PrimaryText = Template.bind({}); PrimaryText.args = { color: 'primary', }; export const DefaultContained = Template.bind({}); DefaultContained.args = { variant: 'contained', }; export const PrimaryContained = Template.bind({}); PrimaryContained.args = { color: 'primary', variant: 'contained', };
<?xml version="1.0" encoding="UTF-8"?> <chapter id="qSupp"> <title>Query Support</title> <para>To make the usage of sql queries more flexible in dbforms, you can use the query element which can be used to:</para> <itemizedlist mark="opencircle"> <listitem> <para>Create <emphasis role="italic">group by</emphasis> with flexible <emphasis role="italic">where</emphasis> part. </para> </listitem> <listitem> <para>Create joined sql with a flexible <emphasis role="italic">join</emphasis> statement </para> </listitem> <listitem> <para>Create an alias of an existing table</para> </listitem> <listitem> <para>Make dynamic changes of the query which prevents the use of a view in the database.</para> </listitem> </itemizedlist> <sect1> <title> <emphasis role="bold">Examples:</emphasis> </title> <sect2> <title>group by</title> <para>In a table with:</para> <blockquote> <screen> create table <emphasis role="bold">values</emphasis> (cno integer not null primary key, type char(20) not null, date timestamp not null, value number not null ) </screen> </blockquote> <para>You need a query with:</para> <blockquote> <screen> Select type, sum(value) as sumValue where date &lt; ? group by type having sumValue &gt; ? </screen> </blockquote> <para>Because the date should be selected by the user, you can not use a fixed view in the database. However, this is possible using the <emphasis role="bold">query</emphasis> element in dbforms_config.xml: </para> <blockquote> <screen> <emphasis role="bold">&lt;dbforms-config&gt;</emphasis> ... <emphasis role="bold">&lt;query</emphasis> name="valuesGroup" from="values" groupBy=type&gt; &lt;field="type" type="char"&gt; &lt;field="sumValue" expression=sum(value) type="number"&gt; &lt;search="date" type="timestamp"&gt; &lt;/query&gt; </screen> </blockquote> </sect2> <sect2> <title>join</title> <blockquote> <screen> <emphasis role="bold">&lt;dbforms-config&gt;</emphasis> ... <emphasis role="bold">&lt;query</emphasis> name="viewname" from="table1 left join table2 on table1.id = table2.id"&gt; &lt;field1 type=char&gt; &lt;/query&gt; </screen> </blockquote> </sect2> <sect2> <title>Simple alias</title> <blockquote> <screen> <emphasis role="bold">&lt;dbforms-config&gt;</emphasis> ... <emphasis role="bold">&lt;query</emphasis> name="aliasname" from="table" /&gt; </screen> </blockquote> <itemizedlist mark="opencircle"> <listitem> <para>can be used to have the same table more than once on a page.</para> </listitem> <listitem> <para>inherits all field definitions from the table.</para> </listitem> <listitem> <para>is updateable!</para> </listitem> <listitem> <para>may be another query.</para> </listitem> </itemizedlist> </sect2> </sect1> <sect1> <title>Use within dbforms-config.xml</title> <para>The following example is taken from <computeroutput>src\org\dbforms\resources\dbforms-config.xsd</computeroutput> It has been changed here from schema style to DTD sytle for those more familiar with the latter. However, no DTD for dbforms.xml actually exists.</para> <para> <table> <title>Excerpts in DTD style of dbforms-config.xml</title> <tgroup cols="2"> <tbody> <row> <entry> &lt;!ELEMENT query (field*, search*)&gt;</entry> <entry/> </row> <row> <entry> &lt;!ATTLIST query</entry> <entry/> </row> <row> <entry> name CDATA #REQUIRED</entry> <entry>Name of the table, same meaning as in table attribute</entry> </row> <row> <entry> from CDATA #IMPLIED</entry> <entry> Name of the parent table. This table must be defined within dbforms-config.xml. If you leave out everything else, query is used as an updatable alias for the prior defined table! If missing, </entry> </row> <row> <entry> groupBy CDATA #IMPLIED</entry> <entry>Group by clause for select</entry> </row> <row> <entry> where CDATA #IMPLIED</entry> <entry>Starting where part of select</entry> </row> <row> <entry> followAfterWhere CDATA #IMPLIED</entry> <entry> Must be OR or AND, will be appended to the starting where part if dbforms have build an own where part: Where + followAfterWhere + where_from_dbforms </entry> </row> <row> <entry> orderWithPos CDATA #IMPLIED</entry> <entry>If true, the order part will build with fieldnumber instead of fieldname</entry> </row> <row> <entry> distinct CDATA #IMPLIED</entry> <entry>If true, select will be build as select distinct</entry> </row> <row> <entry>&gt;</entry> <entry/> </row> <row> <entry/> </row> <row> <entry> &lt;!ATTLIST field</entry> <entry/> </row> <row> <entry> name CDATA #REQUIRED</entry> <entry>Name of field in table</entry> </row> <row> <entry> type CDATA #IMPLIED</entry> <entry>Type of field</entry> </row> <row> <entry> autoInc CDATA #IMPLIED</entry> <entry>stores if the field is AUTOINCremental</entry> </row> <row> <entry> key CDATA #IMPLIED</entry> <entry>=TRUE if field is key field</entry> </row> <row> <entry> sortable CDATA #IMPLIED</entry> <entry>all non-key-fields you want to be sortable should be declared &#147;sortable&#148; in the XML-config file</entry> </row> <row> <entry> expression CDATA #IMPLIED</entry> <entry> Expression of field. Results in expression + AS + name </entry> </row> <row> <entry> &gt;</entry> <entry/> </row> <row> <entry/> </row> <row> <entry> &lt;!ELEMENT search EMPTY&gt;</entry> <entry> All elements of type search can be used as normal fields in dbforms. While construction the sql statement these fields will not be included in the from part. They will only be used to generate the where part of the query. If the query has a groupBy statement, these fields will be used in the where part of the query if needed, not in the having part! </entry> </row> <row> <entry> &lt;!ATTLIST search</entry> <entry/> </row> <row> <entry> name CDATA #REQUIRED</entry> <entry>Name of field in table or alias</entry> </row> <row> <entry> expression CDATA #IMPLIED</entry> <entry> Expression of field. Results in expression + AS + name </entry> </row> <row> <entry> &gt;</entry> <entry/> </row> </tbody> </tgroup> </table> </para> <para/> </sect1> </chapter>
import Image from 'next/image' import { MouseEventHandler } from 'react' interface Props { title: string lefeIcon?: string | null rightIcon?: string | null handleClick?: MouseEventHandler isSubmitting?: boolean type?: 'button' | 'submit' bgColor?: string textColor?: string } const Button = ({ title, lefeIcon, rightIcon, handleClick, isSubmitting, type, bgColor, textColor }: Props) => { return ( <button type={type || 'button'} disabled={isSubmitting} className={`flexCenter gap-2 px-6 py-3 ${textColor || 'text-white'} ${ isSubmitting ? 'bg-black/50' : bgColor ? bgColor : 'bg-primary-purple' } rounded-xl text-sm font-medium max-md:w-full`} onClick={handleClick} > {lefeIcon && <Image src={lefeIcon} width={14} height={14} alt="left" />} {title} {rightIcon && <Image src={rightIcon} width={14} height={14} alt="right" />} </button> ) } export default Button
package com.mygdx.game.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.viewport.StretchViewport; import com.mygdx.game.Juego; import com.mygdx.game.helpers.AssetManager; import com.mygdx.game.helpers.InputHandler; import com.mygdx.game.objects.Character; import com.mygdx.game.objects.Enemy; import com.mygdx.game.objects.ScrollHandler; import com.mygdx.game.objects.Shoot; import com.mygdx.game.objects.Skull; import com.mygdx.game.utils.AppPreferences; import com.mygdx.game.utils.Settings; import java.util.ArrayList; public class GameScreen implements Screen { final Juego game; FileHandle fuente; private Stage stage; private Character character; private ScrollHandler scrollHandler; private BitmapFont font; OrthographicCamera camera; public ArrayList<Enemy> enemys; public Enemy enemy; private ShapeRenderer shapeRenderer; public TextButton returnMenuButton; // Per obtenir el batch de l'stage private Batch batch; private TextureRegion liveIcon; boolean isGameOver = false; private Skin skin; Music music; AppPreferences preferences = new AppPreferences(); boolean musicEnabled = preferences.isMusicEnabled(); float musicVolume = preferences.getMusicVolume(); boolean soundsEnabled = preferences.isSoundEffectsEnabled(); float soundsVolume = preferences.getSoundVolume(); public int vidas = 3; public int puntuacion= 0; public int mejorPuntuacion; public GameScreen(Juego game) { this.game = game; AssetManager.load(); //Reproduim la musica desde l'assets manager si esta activada i li posem el volum que tenim a les opcions if (musicEnabled) { AssetManager.GameMusic.setVolume(musicVolume); AssetManager.GameMusic.play(); } //Inizializamos la skin skin = new Skin(Gdx.files.internal("Skin/star-soldier-ui.json")); //Inizializamos la mejor puntuacion mejorPuntuacion=Gdx.app.getPreferences("data").getInteger("score"); //Inicializamos la fuente para los textos fuente = AssetManager.fuente; // Creem el ShapeRenderer shapeRenderer = new ShapeRenderer(); // Creem la càmera de les dimensions del joc camera = new OrthographicCamera(Settings.GAME_WIDTH, Settings.GAME_HEIGHT); // Posant el paràmetre a true configurem la càmera perque faci servir el sistema de coordenades Y-Down camera.setToOrtho(true); // Creem el viewport amb les mateixes dimensions que la càmera StretchViewport viewport = new StretchViewport(Settings.GAME_WIDTH, Settings.GAME_HEIGHT, camera); // Creem l'stage i assignem el viewport stage = new Stage(viewport); batch = stage.getBatch(); // Creem el character i la resta d'objectes character = new Character(Settings.CHARACTER_STARTX, Settings.CHARACTER_STARTY, Settings.CHARACTER_WIDTH, Settings.CHARACTER_HEIGHT); scrollHandler = new ScrollHandler(); // Afegim els actors a l'stage stage.addActor(scrollHandler); stage.addActor(character); // Assignem com a gestor d'entrada la classe InputHandler Gdx.input.setInputProcessor(new InputHandler(this)); } private void drawElements() { // Recollim les propietats del batch de l'stage shapeRenderer.setProjectionMatrix(batch.getProjectionMatrix()); // Pintem el fons de negre per evitar el "flickering" //Gdx.gl20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT); // Inicialitzem el shaperenderer shapeRenderer.begin(ShapeRenderer.ShapeType.Line); // Definim el color (verd) shapeRenderer.setColor(new Color(0, 1, 0, 1)); // Pintem el character shapeRenderer.rect(character.getX(), character.getY(), character.getWidth(), character.getHeight()); Skull skull = scrollHandler.getSkull(); shapeRenderer.circle(skull.getX() + skull.getWidth() / 2, skull.getY() + skull.getHeight() / 2, (skull.getWidth() / 2)+100); // Recollim tots els enemics ArrayList<Enemy> enemys = scrollHandler.getEnemys(); Enemy enemy; for (int i = 0; i < enemys.size(); i++) { enemy = enemys.get(i); switch (i) { case 0: shapeRenderer.setColor(1, 0, 0, 1); break; case 1: shapeRenderer.setColor(0, 0, 1, 1); break; case 2: shapeRenderer.setColor(1, 1, 0, 1); break; default: shapeRenderer.setColor(1, 1, 1, 1); break; } shapeRenderer.circle(enemy.getX() + enemy.getWidth() / 2, enemy.getY() + enemy.getWidth() / 2, enemy.getWidth() / 2); } shapeRenderer.end(); } private void drawLife() { liveIcon = AssetManager.liveIcon; // Itera sobre los íconos de vida en el asset manager for (int i = 0; i < AssetManager.lifeIcons.length; i++) { // Obtén el ícono correspondiente según el índice actual TextureRegion lifeIcon = AssetManager.lifeIcons[i]; // Si el ícono no es nulo, dibújalo if (lifeIcon != null) { // Calcula la posición en la pantalla para cada ícono de vida float iconX = Settings.ICON_STARTX + i * (Settings.ICON_WIDTH + Settings.ICON_PADDING_X); float iconY = Settings.ICON_STARTY; // Dibuja el ícono de vida en la posición calculada batch.begin(); batch.draw(lifeIcon, iconX, iconY, Settings.ICON_WIDTH, Settings.ICON_HEIGHT); batch.end(); } } } private void drawScore() { // Obtener la fuente de texto de la skin BitmapFont fontScore = new BitmapFont(fuente, true); fontScore.getData().scale(1f); //Asignamos la posicion del texto "BestScore" float textBestScoreY = Settings.GAME_HEIGHT-50; batch.begin(); fontScore.draw(batch, "Score: "+puntuacion, Settings.SCORE_STARTX, Settings.SCORE_STARTY); fontScore.draw(batch, "Best Score: "+mejorPuntuacion, Settings.SCORE_STARTX, textBestScoreY); batch.end(); } @Override public void show() { } @Override public void render(float delta) { stage.draw(); stage.act(delta); if (!isGameOver) { if (vidas > 0) { // Dibuixem i actualitzem tots els actors de l'stage //drawElements(); drawLife(); drawScore(); // Verificar si el el personaje esta atacando if (character.isAttack) { // Crear un disparo desde el ScrollHandler scrollHandler.createShoot(character); // Actualizar el estado de ataque del personaje character.isAttack = false; } if (scrollHandler.collides(character)) { // Si hi ha hagut col·lisió Reproduïm el so de impacte if (soundsEnabled) { Long impactSound = AssetManager.Impact.play(); AssetManager.Impact.setVolume(impactSound, soundsVolume); } character.hurt(); vidas--; // Eliminar el último ícono de vida si aún quedan vidas if (vidas >= 0 && vidas < AssetManager.lifeIcons.length) { AssetManager.lifeIcons[vidas] = null; } Gdx.app.log("VIDAS", "" + vidas); } if (scrollHandler.collidesSkull(character)) { // Si hi ha hagut col·lisió Reproduïm el so de agafar una vida if (soundsEnabled) { Long lifeSound = AssetManager.Life.play(); AssetManager.Life.setVolume(lifeSound, soundsVolume); } if(vidas<3){ vidas++; AssetManager.lifeIcons[vidas-1] = AssetManager.liveIcon; Gdx.app.log("VIDAS", "" + vidas); } else if(vidas==3){ puntuacion+=10; } } if (scrollHandler.collidesPower(character)) { // Si hi ha hagut col·lisió Reproduïm el so de agafar una vida if (soundsEnabled) { Long powerSound = AssetManager.Power.play(); AssetManager.Power.setVolume(powerSound, soundsVolume+20); } character.power(); } if (scrollHandler.collidesEnemy(character)) { if (soundsEnabled) { Long impactSound = AssetManager.ImpactShoot.play(); AssetManager.ImpactShoot.setVolume(impactSound, soundsVolume); } puntuacion+=10; Gdx.app.log("Puntuacion", "" + puntuacion); } } else { isGameOver = true; // Establecemos isGameOver como verdadero cuando el juego termina //Aturem la musica AssetManager.GameMusic.stop(); //Reproduim la animacio de cuan el caracter es mor character.death(); // Si hi ha hagut col·lisió Reproduïm el so de impacte if (soundsEnabled) { Long impactSound = AssetManager.Dead.play(); AssetManager.Dead.setVolume(impactSound, soundsVolume); } } } else { //Si la puntuacion final es superior a la mejor puntuacion la guardamos en preferences if(puntuacion>mejorPuntuacion) { //Guardem la puntuacio final a les preferences de gdx Gdx.app.getPreferences("data").putInteger("score", puntuacion).flush(); } // Obtener la fuente de texto de la skin BitmapFont font = new BitmapFont(fuente, true); font.getData().scale(3f); // Obtener la fuente de texto de la skin BitmapFont font1 = new BitmapFont(fuente, true); font1.getData().scale(2f); //Asignamos la posicion del texto "Game Over" float gameOverX = (Settings.GAME_WIDTH / 2) - 300; float gameOverY = (Settings.GAME_HEIGHT / 2) - 100; //Asignamos la posicion del texto "Score" float textScoreX = gameOverX-50; float textScoreY = gameOverY+100; batch.begin(); font.draw(batch, "Game Over", gameOverX, gameOverY); font1.draw(batch, "Final Score: "+puntuacion, textScoreX, textScoreY); batch.end(); //Asignamos la posicion del botón debajo del texto float buttonX = gameOverX + 50; // float buttonY = textScoreY + 100; // // Obtener el estilo de la skin del botón TextButton.TextButtonStyle buttonStyle = skin.get(TextButton.TextButtonStyle.class); // Cambiar la fuente del estilo del botón por el que hemos creado antes buttonStyle.font = font; //Cambiamos el control para que no lo gestione el inputhandler y no se pueda usar el personaje Gdx.input.setInputProcessor(stage); returnMenuButton = new TextButton("Menu principal", skin); returnMenuButton.getLabel().setFontScale(2f); returnMenuButton.setSize(500, 100); returnMenuButton.setPosition(buttonX, buttonY); //returnMenuButton.setDisabled(false); //returnMenuButton.debug(); returnMenuButton.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { game.setScreen(new MainMenuScreen(game)); } }); stage.addActor(returnMenuButton); } } @Override public void resize(int width, int height) { stage.getViewport().update(width, height); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } public Stage getStage() { return stage; } public Character getCharacter() { return character; } public TextButton getReturnMenuButton() { return returnMenuButton; } public Juego getGame() { return this.game; } }