text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="ko"> <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"> <!-- 1. 타이틀 변경 --> <title>훈련생이름 포트폴리오</title> <!-- 2. 파비콘 적용 --> <!-- 파비콘(favicon.ico)은 프로젝트 폴더의 최상위(Root) 경로에 포함시키면 자동 적용 최상위 경로에 없거나, ico가 아닌 별도 파일을 가진 경우에는 <link>로 적용 (참고) 파비콘 만들기: https://iconifier.net --> <link rel="icon" href="favicon.ico"> <!-- 3. reset.css 적용 --> <!-- 스타일 초기화: 브라우저 별로 다른 기본스타일이 적용되는 것을 초기화 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reset-css@5.0.2/reset.min.css"> <!-- 4. 구글 웹폰트 연결 --> <!-- 구글 웹폰트: 경량화된 오픈 라이선스 폰트, 한글 지원하는지 확인 및 필요한 굵기 선택 후 연결 --> <!-- 한글: Noto Sans Korean, 영문: Open Sans --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100..900&family=Open+Sans:ital,wght@0,300..800;1,300..800&display=swap" rel="stylesheet"> <!-- 5. 구글 머티리얼 아이콘 연결 --> <!-- 구글 머티리얼 아이콘: 구글에서 제공하는 머티리얼 스타일의 아이콘, 글자처럼 취급 가능한 장점 --> <!-- 그 외 fontawesome, bootstrap icon 등 --> <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet" /> <!-- <link href="https://fonts.googleapis.com/css2?family=Material+Icons" rel="stylesheet"> --> <!-- Filled 외 다른 테마 사용하고 싶으면 --> <!-- <link href="https://fonts.googleapis.com/css2?family=Material+Icons+Outlined" rel="stylesheet" /> --> <!-- 6. main.css 파일 만들고 폰트 및 아이콘 테스트 --> <link rel="stylesheet" href="css/main.css"> <!-- 8. ScrollMagic --> <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/ScrollMagic.min.js" integrity="sha512-8E3KZoPoZCD+1dgfqhPbejQBnQfBXe8FuwL4z/c8sTrgeDMFEnoyTlH3obB4/fV+6Sg0a0XF+L/6xS4Xx1fUEg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <!-- 7. main.js 미리 연결 --> <script defer src="js/main.js"></script> </head> <body> <!-- 폰트 테스트 --> <!-- <span>헬로 월드!</span> <span class="font-en">Hello world!</span> --> <!-- 아이콘 테스트 --> <!-- <span class="material-symbols-outlined"> search </span> --> <!-- <span class="material-icons-outlined"> search </span> <span class="material-icons"> search </span> --> <div style="overflow-x: hidden;"> <!-- HEADER --> <header> <div class="inner"> <!-- 로고 --> <a href="index.html" class="logo"> <!-- 본인의 로고를 이미지로 제작 시 logo.png로 만들어서 기존 파일과 교체, 만약 텍스트로 넣을거면 img 요소를 제거하고 텍스트 입력 --> <img src="images/logo.png" alt="로고"> </a> <!-- 메뉴 --> <nav class="font-en"> <ul> <!-- 본인의 메뉴 구조에 맞게 변경 --> <li><a href="#about">ABOUT</a></li> <li><a href="#skill">SKILL</a></li> <li><a href="#work">WORK</a></li> <li><a href="#contact">CONTACT</a></li> </ul> </nav> <!-- (추가1) 햄버거 버튼 --> <a href="javascript:void(0)" class="btn-hamburger"> <span class="material-symbols-outlined">menu</span> </a> </div> </header> <!-- VISUAL --> <!-- 배경 비디오 적용(슬라이드로 만들고 싶으면 swiper 참고) --> <section class="visual"> <video autoplay muted loop> <source src="videos/movie2.mp4" type="video/mp4"> </video> </section> <!-- ABOUT --> <section id="about" class="about"> <div class="inner"> <h2 class="title font-en">ABOUT</h2> <div class="about__wrapper"> <div class="about__img"> <!-- 본인 프로필 이미지로 변경 --> <img src="images/profile.jpg" alt="프로필"> </div> <div class="about__text"> <!-- 본인 슬로건, 이름(생년월), 교육 사항 등 작성 --> <strong class="slogan font-en">Best or Nothing</strong> <h3 class="font-en">Kim Jae Hyun (1986. 10)</h3> <div> <h4 class="font-en">EDUCATION</h4> <ul> <li>10.03 ~ 12.02 OO학교 OO과 졸업</li> <li>23.12 ~ 24.05 (멀티미디어)영상편집&amp;모션그래픽 과정 수료</li> </ul> </div> </div> </div> <!-- 연락처 버튼 --> <div class="about__btn font-en"> <a href="#contact"> <img src="images/icon/icon_contact.png" alt="전화">CONTACT </a> </div> </div> </section> <!-- SKILL --> <section id="skill" class="skill scroll-spy"> <div class="inner"> <h2 class="title font-en">SKILL</h2> <!-- 스킬 추가하려면 li 요소 복사 붙여넣기. 삭제하려면 해당 li 요소만 삭제 --> <ul class="skill__list"> <li> <div class="font-en"> <p>Ps</p> </div> <h3 class="font-en">PHOTOSHOP</h3> <ul> <li>이미지 편집</li> <li>타이포 그래피</li> <li>아트 워크 제작</li> <li>썸네일 제작</li> </ul> </li> <li> <div class="font-en"> <p>Ai</p> </div> <h3 class="font-en">ILLUSTRATOR</h3> <ul> <li>CI·BI 제작</li> <li>캐릭터 디자인</li> <li>타이포 그래피</li> <li>레터링</li> </ul> </li> <!-- <li> <div class="font-en"> <p>Html</p> </div> <h3 class="font-en">HTML5</h3> <ul> <li>웹페이지 구성, 편집</li> <li>페이지 디자인</li> </ul> </li> --> <!-- <li> <div class="font-en"> <p>Css</p> </div> <h3 class="font-en">CSS3</h3> <ul> <li>홈페이지 디자인, 편집</li> <li>반응형 제작</li> </ul> </li> --> <li> <div class="font-en"> <p>Pr</p> </div> <h3 class="font-en">PREMIERE PRO</h3> <ul> <li>영상 편집</li> <li>자막 삽입</li> <li>사운드 디자인</li> </ul> </li> <li> <div class="font-en"> <p>Af</p> </div> <h3 class="font-en">AFTER EFFECT</h3> <ul> <li>디지털 모션 그래픽</li> <li>모션 합성</li> <li>모션 타이포 그래피</li> </ul> </li> <li> <div class="font-en"> <p>3d</p> </div> <h3 class="font-en">3D MAX<br>CINEMA 4D</h3> <ul> <li>모델링</li> <li>렌더링</li> <li>텍스처 삽입</li> </ul> </li> </ul> </div> </section> <!-- WORK --> <!-- 구글에서 굿 디자인 웹 검색 후 왼쪽 메뉴에서 'WEB 부분' 클릭하면 타겟층, 표현방법, 콘셉트, 컬러 등 참고 가능 (예: 20~30대 여성, 모션그래픽, 서정적인, 베이지컬러) --> <section id="work" class="work font-en"> <div class="inner"> <h2 class="title">WORK</h2> <div class="port"> <div class="port__img"> <img src="images/work_1.jpg" alt="포트폴리오1 썸네일"> </div> <div class="port__text"> <h3>Kinetic Typography</h3> <ul> <li><span>CONCEPT : </span>해당 영상의 콘셉트 설명</li> <li><span>KEYWORD : </span>해당 영상의 주요 키워드</li> <li><span>PROGRAM : </span>Adobe After effect, illustrator, photoshop</li> <li><span>COHERENCE : </span>100%</li> </ul> <div class="btn-group"> <a href="서버상의 pdf 주소" class="btn">VIEW PLAN</a> <a href="javascript:void(0)" class="btn btn-play">VIEW VIDEO</a> </div> </div> </div> <div class="port"> <div class="port__img"> <img src="images/work_2.jpg" alt="포트폴리오2 썸네일"> </div> <div class="port__text"> <h3>Movie Trailer</h3> <ul> <li><span>CONCEPT : </span>해당 영상의 콘셉트 설명</li> <li><span>KEYWORD : </span>해당 영상의 주요 키워드(예: 20~30대 여성, 모션그래픽, 서정적인, 베이지컬러)</li> <li><span>PROGRAM : </span>Adobe After effect, illustrator, photoshop</li> <li><span>COHERENCE : </span>100%</li> </ul> <div class="btn-group"> <a href="서버상의 pdf 주소" class="btn">VIEW PLAN</a> <a href="javascript:void(0)" class="btn btn-play">VIEW VIDEO</a> </div> </div> </div> <div class="port"> <div class="port__img"> <img src="images/work_3.jpg" alt="포트폴리오3 썸네일"> </div> <div class="port__text"> <h3>Album Cover Redesign</h3> <ul> <li><span>CONCEPT : </span>해당 영상의 콘셉트 설명</li> <li><span>KEYWORD : </span>해당 영상의 주요 키워드(예: 20~30대 여성, 모션그래픽, 서정적인, 베이지컬러)</li> <li><span>PROGRAM : </span>Adobe After effect, illustrator, photoshop</li> <li><span>COHERENCE : </span>100%</li> </ul> <div class="btn-group"> <a href="서버상의 pdf 주소" class="btn">VIEW PLAN</a> <a href="javascript:void(0)" class="btn btn-play">VIEW VIDEO</a> </div> </div> </div> <div class="port"> <div class="port__img"> <img src="images/work_4.jpg" alt="포트폴리오4 썸네일"> </div> <div class="port__text"> <h3>Detail Page Design I</h3> <ul> <li><span>CONCEPT : </span>해당 영상의 콘셉트 설명</li> <li><span>KEYWORD : </span>해당 영상의 주요 키워드(예: 20~30대 여성, 모션그래픽, 서정적인, 베이지컬러)</li> <li><span>PROGRAM : </span>Adobe After effect, illustrator, photoshop</li> <li><span>COHERENCE : </span>100%</li> </ul> <div class="btn-group"> <a href="서버상의 pdf 주소" class="btn">VIEW PLAN</a> <a href="javascript:void(0)" class="btn btn-play">VIEW VIDEO</a> </div> </div> </div> </div> </section> <!-- CONTACT --> <section id="contact" class="contact font-en scroll-spy"> <div class="inner"> <h2 class="title">CONTACT</h2> <div class="contact__info"> <ul> <li><a href="#사이트주소">XXXX.dothome.co.kr</a></li> <li>010-1234-5678</li> <li>XXXX@naver.com</li> </ul> </div> <div class="contact__sns"> <ul> <li> <a href="인스트그램 주소" target="_blank"> <img src="images/icon/icon_insta.png" alt="인스타그램"> </a> </li> <li> <a href="유튜브 주소" target="_blank"> <img src="images/icon/icon_youtube.png" alt="유튜브"> </a> </li> </ul> </div> </div> </section> <!-- FOOTER --> <footer> <div class="inner"> <p class="copyright"> &copy; <span class="this-year"></span> 훈련생이름. <span class="font_en">All Rights Reserved.</span> </p> </div> </footer> </div> <!-- MODAL --> <div id="modal"> <div class="modal__inner"> <video controls></video> <span class="material-symbols-outlined btn-close">close</span> </div> </div> <!-- SCROLL TO TOP --> <div id="to-top"> <a href="#"> <span class="material-symbols-outlined">arrow_upward</span> </a> </div> </body> </html>
// import React, { useEffect, useState } from "react"; // import { motion, useAnimation } from "framer-motion"; // import { useInView } from "react-intersection-observer"; // import styles from "./Contact.module.scss"; // const Contact = () => { // const [sent, setSent] = useState(false); // const { ref, inView } = useInView({ // threshold: 0, // }); // const animation = useAnimation(); // useEffect(() => { // if (inView) { // animation.start({ // scale: 1, // opacity: 1, // y: 0, // transition: { // }, // }); // } // if (!inView) { // animation.start({ // scale: 0.8, // opacity: 0, // y: -50, // }); // } // }, [inView, animation]); // async function handleSubmit(e) { // e.preventDefault(); // const formData = {}; // Array.from(e.currentTarget.elements).forEach((field) => { // if (!field.name) return; // formData[field.name] = field.value; // }); // console.log(formData); // fetch("/api/mail", { // method: "post", // body: JSON.stringify(formData), // }); // var form = document.getElementById("contactForm"); // form.reset(); // setSent(true); // setTimeout(() => { // setSent(false); // }, 3000); // } // return ( // <section id="5" className={styles.wrapper}> // {/* Contact */} // <motion.div className={styles.headlineWrap} ref={ref} animate={animation}> // <h5>have any questions?</h5> // <h2>Get in touch with us!</h2> // </motion.div> // <motion.div className={styles.grid} ref={ref} animate={animation}> // <div className={styles.formWrap}> // <form method="post" id="contactForm" onSubmit={handleSubmit}> // <div className={styles.double}> // <div className={styles.single}> // <label htmlFor="name" className={styles.formLabel}> // Name <span>*</span> // </label> // <input // required // type="text" // name="name" // className={styles.formInput} // /> // </div> // <div className={styles.single}> // <label htmlFor="email" className={styles.formLabel}> // Email <span>*</span> // </label> // <input // required // type="text" // name="email" // className={styles.formInput} // /> // </div> // </div> // <div className={styles.double}> // <div className={styles.single}> // <label htmlFor="company" className={styles.formLabel}> // Company // </label> // <input // type="text" // name="company" // className={styles.formInput} // /> // </div> // <div className={styles.single}> // <label htmlFor="phone" className={styles.formLabel}> // Contact number // </label> // <input type="text" name="phone" className={styles.formInput} /> // </div> // </div> // <label htmlFor="name" className={styles.formLabel}> // Message <span>*</span> // </label> // <textarea required name="message" className={styles.formInput} /> // {sent ? ( // <> // <div className={styles.actionMessage}> // <p>Your message has been sent!</p> // </div> // <br /> // </> // ) : null} // <button>Submit</button> // </form> // </div> // </motion.div> // </section> // ); // }; // export default Contact;
import React from 'react'; import { useState, useEffect } from 'react'; import { Typography, Grid, Button, OutlinedInput, InputAdornment, IconButton, FormHelperText } from '@mui/material'; import PageContainer from 'src/components/container/PageContainer'; import DashboardCard from '../../components/shared/DashboardCard'; import CustomTextField from '../../components/forms/theme-elements/CustomTextField'; import { useNavigate, Link, useParams } from 'react-router-dom'; import Stack from '@mui/material/Stack'; import Alert from '@mui/material/Alert'; import Cookie from 'js.cookie'; import { Visibility, VisibilityOff } from '@mui/icons-material'; import { UserService } from '../../api/UserService'; export const CreateOsPage = () => { const userLogin = Cookie.get('email'); const expires = Cookie.get('expires'); var now = new Date(); const [disableButton, setDisableButton] = useState(true); const [alertIsError, setAlertIsError] = useState(false); const [openAlert, setOpenAlert] = useState(false); const history = useNavigate(); const [email, setEmail] = useState(userLogin); const [password, setPassword] = useState(''); const [showErrorPassword, setShowErrorPassword] = useState(false); const [showErrorEmail, setShowErrorEmail] = useState(false); const [errorEmail, setErrorEmail] = useState(''); const [showPassword, setShowPassword] = useState(false); useEffect(() => { if (!userLogin || now.toUTCString() >= expires) { history('/'); } }, []); useEffect(() => { if (password !== "") { setDisableButton(false); } }, ); const validateEmail = () => { const emailIsValid = /^[\w+.]+@\w+\.\w{2,}(?:\.\w{2})?$/.test(email); if (email === '') { setShowErrorEmail(true); setDisableButton(true); setErrorEmail('Campo de preenchimento obrigatório'); } else if (!emailIsValid) { setShowErrorEmail(true); setDisableButton(true); setErrorEmail('O Email está incorreto, por favor digite um email valído'); } else { setShowErrorEmail(false); } }; const validatePassword = () => { if (password === '') { setShowErrorPassword(true); setDisableButton(true); } else { setShowErrorPassword(false); } }; const handleClickShowPassword = () => setShowPassword((show) => !show); const editUser = async () => { const newLogin = email === userLogin ? "" : email await UserService.editUser(userLogin,newLogin, password) .then(function (response) { history('/dashboard'); }) .catch(function (error) { setOpenAlert(true); }); }; return ( <PageContainer title="Typography" description="this is Typography"> <Grid container spacing={3}> <Grid item sm={12}> <DashboardCard title="Meu Perfil"> <Grid container spacing={3}> <Grid item sm={12}> <Stack spacing={2}> <Typography variant="subtitle1" fontWeight={600} component="label" htmlFor="name" mb="5px" > Email </Typography> <CustomTextField error={showErrorEmail} helperText={showErrorEmail ? errorEmail : ''} id="email" variant="outlined" fullWidth value={email} onBlur={() => validateEmail()} onChange={(e) => { setEmail(e.target.value); }} /> <Typography variant="subtitle1" fontWeight={600} component="label" htmlFor="name" mb="5px" > Senha </Typography> <OutlinedInput id="filled-adornment-password" variant="outlined" type={showPassword ? 'text' : 'password'} error={showErrorPassword} value={password} onBlur={() => validatePassword()} onChange={(e) => { setPassword(e.target.value); }} endAdornment={ <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleClickShowPassword} edge="end" > {showPassword ? <Visibility /> : <VisibilityOff />} </IconButton> </InputAdornment> } /> <FormHelperText error={showErrorPassword} id="component-error-text"> {showErrorPassword ? 'Campo de preenchimento obrigatório' : ''} </FormHelperText> <Button color="primary" variant="contained" size="large" fullWidth component={Link} onClick={editUser} disabled={disableButton} > Confirmar </Button> {openAlert && ( <Stack sx={{ width: '100%' }} spacing={2}> <Alert variant="filled" severity={alertIsError ? 'error' : 'success'}> {' '} {alertIsError ? 'Houve um erro com o sua OS, revise seus dados e tente novamente' : 'Ordem de serviço regristada com sucesso'} </Alert> </Stack> )} </Stack> </Grid> </Grid> </DashboardCard> </Grid> </Grid> </PageContainer> ); }; export default CreateOsPage;
import { memo, useState } from "react"; import { Stack } from "@mui/material"; import { Button, Text } from "components/shared"; import CircleTickIcon from "icons/CircleTickIcon"; import useToggle from "hooks/useToggle"; type PackageItemProps = {}; const PackageItem = (props: PackageItemProps) => { const [isHovered, onHovered, onHoveredFalse] = useToggle(false); return ( <Stack sx={sxConfig.root} width={220} alignItems="center" spacing={2}> <Text variant="h4">Starter 1 month</Text> <Stack direction="row" alignItems="center" spacing={0.5}> <Text variant="h3">$</Text> <Text variant="h1">9.99</Text> </Stack> <Button variant={isHovered ? "primary" : "secondary"} fullWidth size="small" onMouseMove={onHovered} onMouseLeave={onHoveredFalse} > Get start </Button> <Stack flex={1} spacing={1.25}> <Stack direction="row" spacing={1}> <CircleTickIcon fontSize="medium" color="success" /> <Text variant="body2"> Nemo enim ipsam volup tatem quia volu ptas sit aspernatur </Text> </Stack> <Stack direction="row" spacing={1}> <CircleTickIcon fontSize="medium" color="success" /> <Text variant="body2"> Nemo enim ipsam volup tatem quia volu ptas sit aspernatur </Text> </Stack> <Stack direction="row" spacing={1}> <CircleTickIcon fontSize="medium" color="success" /> <Text variant="body2"> Nemo enim ipsam volup tatem quia volu ptas sit aspernatur </Text> </Stack> </Stack> </Stack> ); }; export default memo(PackageItem); const sxConfig = { root: { border: "1px solid", borderColor: "grey.200", borderRadius: 4, py: 2, px: 1.25, height: "auto", minHeight: 400, "&:hover": { backgroundColor: "grey.50", boxShadow: "0px 10px 15px rgba(33, 33, 33, 0.1)", // px: 3.125, // py: 4.5, }, }, };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="Assets/Css/all.min.css"> <link rel="stylesheet" href="Assets/Css/style.css"> <link rel="stylesheet" href="Assets/Css/bootstrap.css"> <title>Document</title> </head> <body> <header class="py-2"> <nav class="nav-container"> <div class="d-flex flex-wrap justify-content-between align-items-center"> <div class="logo col-lg-2 col-md-2"> <img src="Assets/img/Logo.png"> </div> <div class="mobile-menu col-md-8 col-lg-4"> <i class="fa-solid fa-bars fx-2"></i> <div class="navigation-bar"> <ul class="nav-links"> <li><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#service">Services</a></li> <li><a href="#projects">Projects</a></li> <li><a href="#contact">Contact</a></li> </ul> </div> </div> </div> </nav> </header> <main> <div class="banner"> <div class="d-flex flex-wrap align-items-center justify-content-between"> <div class="banner-content mb-md-5 col-sm-12 col-lg-6"> <h1>Hi.</h1> <h2>I am Eslam Hesham</h2> <h4>I am a frontend web developer. I can provide clean code and pixel perfect design. I also make website more & more interactive with web animations.</h4> <a href="#">HIRE ME!</a> </div> <div class="banner-img col-sm-12 col-lg-5"> <img src="Assets/img/avatar.png" style="width: 100%;"> </div> </div> </div> <div class="section" id="service"> <div class="section-title"> <h5>SERVICES</h5> <h1 class="col-md-12 col-lg-6">I am <span>Web Developer</span> with year experience & <span>Network Engineering</span></h1> </div> <div class="container"> <div class="service-section d-flex flex-wrap align-items-center"> <div class="serv-card d-flex flex-column align-items-center col-sm-12 col-md-6 col-lg-3"> <div class="text-center"> <h2>Web Development</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum assumenda eum tenetur molestiae.</p> </div> <div class="serv-img col-sm-4"> <img src="Assets/img/front-development.png" style="width: 100%;"> </div> <div class="right-arrow"> <a href="#"><i class="fa-solid fa-arrow-right"></i></a> </div> </div> <div class="serv-card d-flex flex-column align-items-center col-sm-12 col-md-6 col-lg-3"> <div class="text-center"> <h2>UI/UX Design</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum assumenda eum tenetur molestiae.</p> </div> <div class="serv-img col-sm-4"> <img src="Assets/img/ui-design.png" style="width: 100%;"> </div> <div class="right-arrow"> <a href="#"><i class="fa-solid fa-arrow-right"></i></a> </div> </div> <div class="serv-card d-flex flex-column align-items-center col-sm-12 col-md-6 col-lg-3"> <div class="text-center"> <h2>Network Engineering</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum assumenda eum tenetur molestiae.</p> </div> <div class="serv-img col-sm-4"> <img src="Assets/img/dns.png" style="width: 100%;"> </div> <div class="right-arrow"> <a href="#"><i class="fa-solid fa-arrow-right"></i></a> </div> </div> <div class="serv-card d-flex flex-column align-items-center col-sm-12 col-md-6 col-lg-3"> <div class="text-center"> <h2>SEO</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum assumenda eum tenetur molestiae.</p> </div> <div class="serv-img col-sm-4"> <img src="Assets/img/seo.png" style="width: 100%;"> </div> <div class="right-arrow"> <a href="#"><i class="fa-solid fa-arrow-right"></i></a> </div> </div> </div> </div> </div> <div class="section" id="about"> <div class="about-container"> <div class="d-flex flex-wrap align-items-center justify-content-evenly"> <div class="avatar mb-sm-2 col-sm-12 col-lg-4"> <img src="Assets/img/avatar.png" style="width: 100%;"> </div> <div class="brief col-sm-12 col-md-12 col-lg-5"> <h2>About Me</h2> <p>I am a Web Devoloper with a strong focus on digital branding. Web design seeks to attract, inspire, create desires and motivate people to respond to messages, with a view to making a favorable impact. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptatem deserunt illum totam eos architecto atque! Maxime perspiciatis obcaecati dolor hic voluptates animi? Temporibus aliquid perferendis dicta ratione, sapiente voluptatem possimus porro asperiores laboriosam quis itaque qui quasi illum explicabo quidem repudiandae laborum eos facere at saepe. Facere corporis accusantium libero!</p> <a href="#">DOWNLOAD CV</a> </div> </div> <div class="d-flex flex-wrap align-items-center justify-content-evenly"> <div class="profile-info col-sm-12 col-lg-5"> <h2>What I Do?</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum, rerum esse! Hic sequi nulla similique repudiandae exercitationem commodi laborum consequuntur amet, in iusto deleniti eos, dolor ad error eum voluptate? Porro perferendis, quis vel adipisci itaque ullam repudiandae voluptates cupiditate, consectetur error molestias consequuntur esse.</p> </div> <div class="expert-tool col-sm-12 col-lg-6 column"> <div class="skill-main"> <div class="skill-item"> <h4>Web Design</h4> <div class="progress_bar" data-count="85%"> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100" style="width: 85%;"> </div> </div> </div> </div> </div> <div class="skill-main"> <div class="skill-item"> <h4>Adobe XD</h4> <div class="progress_bar" data-count="65%"> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100" style="width: 65%;"> </div> </div> </div> </div> </div> <div class="skill-main"> <div class="skill-item"> <h4>Network Engineering</h4> <div class="progress_bar" data-count="45%"> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 45%;"> </div> </div> </div> </div> </div> <div class="skill-main"> <div class="skill-item"> <h4>SEO</h4> <div class="progress_bar" data-count="85%"> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width: 50%;"> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="section" id="projects"> <div class="container"> <div class="title d-flex flex-wrap align-items-center justify-content-between"> <h1 class="col-sm-12 mb-sm-2 col-lg-4">Latest Projects</h1> <div class="view-btn col-sm-12 col-lg-2"><a href="#">See All Projects</a></div> </div> <div class="gallery d-flex flex-wrap"> <div class="project-field col-sm-12 col-lg-3"> <img src="Assets/img/Learning System.png" style="width: 100%;"> <a href="#" class="project-info" target="_blank"> <p>Web Design</p> <h5>Learning System</h5> </a> </div> <div class="project-field col-sm-12 col-lg-3"> <img src="Assets/img/Hourse Club.png" style="width: 100%;"> <a href="#" class="project-info" target="_blank"> <p>Web Design</p> <h5>Hourse Club</h5> </a> </div> <div class="project-field col-sm-12 col-lg-3"> <img src="Assets/img/Bank.png" style="width: 100%;"> <a href="#" class="project-info" target="_blank"> <p>Web Design</p> <h5>Bank WEbSite</h5> </a> </div> <div class="project-field col-sm-12 col-lg-3"> <img src="Assets/img/UI App.png" style="width: 100%;"> <a href="#" class="project-info" target="_blank"> <p >Mobile App Design</p> <h5>Booking App</h5> </a> </div> </div> </div> </div> <div class="section" id="contact"> <div class="container"> <div class="title"> <h1>Get In Touch.</h1> <p>I bring rapid solutions to make the life of my cients easier.Have any questions?Reach out to me from this contact form and i will get back to you shortly.</p> </div> <div class="contact-form"> <form class="flex-column" action="#"> <div class="input-grp d-flex flex-wrap"> <div class="input-field col-sm-12 col-lg-6 pr-lg-1 mb-sm-1 pe-sm-0 mb-md-2"> <input type="text" placeholder="Name" required /> </div> <div class="input-field col-sm-12 col-lg-6 ps-lg-1 ps-sm-0"> <input type="text" placeholder="example@mail.com" required /> </div> </div> <textarea class="d-flex col-sm-12" name="" id="" cols="30" rows="5"></textarea> <a class="d-flex col-sm-12">Send message</a> </form> </div> </div> </div> </main> <footer> <div class="container"> <div class="d-flex flex-column align-items-center"> <div class="footer-logo col-lg-2"> <img src="Assets/img/Logo.png" style="width: 100%;"> </div> <div class="social-icons"> <a href="#"><i class="fa-brands fa-facebook-f"></i></a> <a href="#"><i class="fa-brands fa-twitter"></i></a> <a href="#"><i class="fa-brands fa-linkedin"></i></a> <a href="#"><i class="fa-brands fa-instagram"></i></a> </div> </div> </div> </footer> <!-- jQuery --> <script src="Assets/javascript/jquery.min.js"></script> <!-- Bootstrap Core JS --> <script src="Assets/javascript/popper.min.js"></script> <script src="Assets/javascript/bootstrap.min.js"></script> </body> </html>
## Description: Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: ![alt text](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) ## Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] ## Example 2: Input: numRows = 1 Output: [[1]] ## Constraints: 1 <= numRows <= 30 ## Source: https://leetcode.com/problems/pascals-triangle/
import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App.tsx"; import "./index.css"; import { Auth0Provider } from "@auth0/auth0-react"; import * as Sentry from "@sentry/react"; import "./logger"; import { RecoilRoot } from "recoil"; if (import.meta.env.VITE_SENTRY_DSN) { Sentry.init({ dsn: import.meta.env.VITE_SENTRY_DSN, integrations: [Sentry.browserTracingIntegration(), Sentry.replayIntegration()], // Performance Monitoring tracesSampleRate: 1.0, // Capture 100% of the transactions // Set 'tracePropagationTargets' to control for which URLs distributed tracing should be enabled tracePropagationTargets: ["localhost", /^https:\/\/yourserver\.io\/api/], // Session Replay replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production. replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur. }); } ReactDOM.createRoot(document.getElementById("root")!).render( <React.StrictMode> <RecoilRoot> <Auth0Provider domain="pob-web.us.auth0.com" clientId="o8TOT9gDHzztbdIIIV54HxlfaSMFYTeH" legacySameSiteCookie={false} useRefreshTokens={true} cacheLocation={"localstorage"} authorizationParams={{ redirect_uri: window.location.origin, audience: "https://pob.cool/api", scope: "openid profile email offline_access", }} > <App /> </Auth0Provider> </RecoilRoot> </React.StrictMode>, );
import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; import { Exercise } from '../exercise.model'; import { TrainingService } from '../training.service'; import { MatSort } from '@angular/material/sort'; import { MatPaginator } from '@angular/material/paginator'; import { Store } from '@ngrx/store'; import * as fromTraining from '../training.reducer'; @Component({ selector: 'app-past-trainings', templateUrl: './past-trainings.component.html', styleUrls: ['./past-trainings.component.css'] }) export class PastTrainingsComponent implements OnInit, AfterViewInit { displayedColumns = ['date', 'name', 'duration', 'calories', 'state']; dataSource = new MatTableDataSource<Exercise>(); @ViewChild(MatSort, { static: false }) sort: MatSort; @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator; constructor(private trainingService: TrainingService, private store: Store<fromTraining.State>) {} ngOnInit() { this.store.select(fromTraining.getFinishedExercises).subscribe((exercises: Exercise[]) =>{ this.dataSource.data=exercises; }); this.trainingService.fetchCompletedOrCancelledExercises(); } ngAfterViewInit(){ this.dataSource.sort=this.sort; this.dataSource.paginator=this.paginator; } doFilter(filterValue:string){ this.dataSource.filter=filterValue.trim().toLowerCase(); } }
--- title: "Tarea 6" author: "Curso Big Data TEC" output: html_document editor_options: chunk_output_type: console --- ## Tarea sesión 6 ### Descripción tarea En la clase hablamos sobre como aplicar los metodos de estadistica a escala. Uno de los conceptos más dificiles para bajar a tierra fué "datos en movimiento" (**streaming data**). El [vignette del paquete stream](https://cran.r-project.org/web/packages/stream/vignettes/stream.pdf) da una introducción a fondo e incluye ejemplos. ## Tarea Como tarea, lee el vignette del paquete stream mencionado arriba. Y sique los ejemplos para validar que ejecutan. Si tienes tiempo puedes incluir algunos ejemplos mas que estan descritos por los autores. ```{r} library(stream) set.seed(1000) stream <- DSD_Gaussians(k = 3, d = 3, noise = .5, p = c(.5, .3, .1)) stream p <- get_points(stream, n = 50) p ``` > Pregunta: que significan los parametros k, d, noise, y p arriba? Para que los > puedes usar? Ahora miramos los datos moviendose ```{r} library(animation) set.seed(1000) stream <- DSD_Benchmark(1) stream # abre la pestaña "Plots" a mano si no vez nada al correr las siguientes lineas for(i in 1:4) { plot(stream, 250, xlim = c(0, 1), ylim = c(0, 1)) tmp <- get_points(stream, n = 1400) } reset_stream(stream) animate_data(stream, n = 10000, horizon = 100, xlim = c(0, 1), ylim = c(0, 1)) animation::ani.options(interval = .1) ani.replay() ``` > Pregunta: Si piensas en cual es el promedio de X2 la respuesta va ser "depende > de cuando miras, y de cuanta historia incluyes". Discute como esto impacta tu > analisis y cuales soluciones le propondrias a un cliente.
#!/usr/bin/python3 """ create a class studen with some argument""" class Student: """ defin public instance attribute""" def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """ self .__dict arguments == None otherwise only key in the list""" dic = {} if attrs is not None: for key, value in self.__dict__.items(): if key in attrs: dic[key] = value else: dic = self.__dict__ return dic def reload_from_json(self, json): """ that replaces all attributes of the Student instance: """ for key, value in json.items(): if key in self.__dict__: self.__dict__[key] = value
--- {"dg-publish":true,"permalink":"/zettel-kasten/conjuntos/"} --- # Conjuntos Creado: 2024-03-01 11:11 Tema General:[[ZettelKasten/Libros/Matematicas\|Matematicas]] Tag: #Topic ___ ## Que son? *Def*: Un conjunto es una coleccion de objetos *Def. (Conjunto vacio)*: $\emptyset$ es el conjunto que no tiene objetos $\emptyset = \{ \}$ *Def.*: Decimos que x es un elemento del conjunto A si y solo si x es un objeto de A y lo denotamos como $x \in A$ ## Propiedades de los conjuntos El conjunto $\{ a,a \} = \{ a \}$ El conjunto $\{ a,b \} = \{ b,a \}$ ## Contentencia *Def*: $A\subseteq B$ Decimos que A es un subconjunto de B si y solo si para cada $x \in A$ se tiene que $x \in B$ >[!example] > Si $B = \mathbb{Z}$ entonces $A = \{ x=2k: k \in \mathbb{Z} \}$ es un subconjunto de B > $A \subseteq B$ *Def* Si $A \subseteq B \text{{ y }} B \subseteq A \text{ entonces } A = B$ ___ ## References 1.
import { DataSetType } from "../types/type.dataset"; import { getDataset, getItemBasedOnYear } from "./utils.dataset"; export interface VaccinationPerPopulation { population: number; location: string; newVaccinations: number; newVaccinationsPerPopulation: number; } export interface PositiveRate { location: string; positiveRate: number; } /** * * @param data * @param year */ function getNewVaccinationsPerPopulation( data: DataSetType[], year: number ): VaccinationPerPopulation[] { return data .map((d) => { const newVaccinationsArr = getItemBasedOnYear<number>( d, year, "new_vaccinations" ).filter((v) => v); if (!newVaccinationsArr.length) { return null; } const newVaccinations = newVaccinationsArr.reduce((a, b) => a + b, 0) / newVaccinationsArr.length; if (!newVaccinations || !d.location) return null; return { location: d.location, newVaccinations, population: d.population, newVaccinationsPerPopulation: newVaccinations / d.population, }; }) .filter( (d) => d !== null && !isNaN(d.newVaccinationsPerPopulation) ) as VaccinationPerPopulation[]; } /** * * @param data * @param year */ function getPositiveRateData( data: DataSetType[], year: number ): PositiveRate[] { return data .map((d) => { const positiveRateArr = getItemBasedOnYear<number>( d, year, "positive_rate" ).filter((d) => d); if (!positiveRateArr.length) { return null; } const positiveRate = positiveRateArr.reduce((a, b) => a + b, 0) / positiveRateArr.length; if (!positiveRate || !d.location) return null; return { location: d.location, positiveRate, }; }) .filter((d) => d !== null) as PositiveRate[]; } /** * * @param data * @param year */ export function getVaccinationScatterPlotData( data: DataSetType[], year: number ) { const newVaccinationsPerPopulation = getNewVaccinationsPerPopulation( data, year ); const positiveRateData = getPositiveRateData(data, year); const scatterPlotData = positiveRateData .map((d) => { const newVaccinationsPerPopulationData = newVaccinationsPerPopulation.find((d2) => d2.location === d.location); if (!newVaccinationsPerPopulationData) return null; return { location: d.location, positiveRate: d.positiveRate, newVaccinationsPerPopulation: newVaccinationsPerPopulationData.newVaccinationsPerPopulation, }; }) .filter((d) => d !== null && !isNaN(d.newVaccinationsPerPopulation)); return { scatterPlotData, newVaccinationsPerPopulation, positiveRateData, }; }
import { render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Input } from './Input'; test('should render an input with a label', () => { const { getByLabelText } = render(<Input label='Test Label' />); expect(getByLabelText('Test Label')).toBeInTheDocument(); }); test('should render an input without a label', () => { const { getByLabelText } = render(<Input />); expect(getByLabelText('Input field')).toBeInTheDocument(); }); test('should update the value when the user types in the input', () => { const { getByLabelText } = render(<Input label='Test Label' />); const inputElement = getByLabelText('Test Label') as HTMLInputElement; expect(inputElement.value).toBe(''); userEvent.type(inputElement, 'test value'); expect(inputElement.value).toBe('test value'); });
// // BookDetailsReducer.swift // headwayTestApp // // Created by Radomyr Sidenko on 13.10.2023. // import ComposableArchitecture import StoreKit enum BaseError: Error { case somethingWentWrong } //struct BuyOption { // let price: Double // Change to Currency or Decimal // let description: String // let inAppId: String //} struct BookDetailsReducer: ReducerProtocol { private let skManager = StoreKitManager() struct State: Equatable { var bookId: Int = 0 var book: Book? var shouldOpenPlayer = false var product: Product? var subscription: Product? var isPurchased = false var shouldOpenBuyAlert: Bool = false } enum Action: Equatable { case fetchBook case productLoaded(TaskResult<Product>) case subscriptionLoaded(TaskResult<Product>) case openPlayer(isPresented: Bool) case openBuyAlert(isPresented: Bool) case listenButtonTaped case readButtonTaped case buyButtonTaped case buySubscriptionTaped case isPurchased(Bool) } private func fetchBook(state: inout State) -> EffectTask<Action> { let allBooks = Book.allBook let currentBook = allBooks.first { $0.id == state.bookId } state.book = currentBook return .run { [inAppId = state.book?.inAppId] send in guard let inAppId = inAppId, let product = await skManager.fetchOneProduct(id: inAppId), let subscription = await skManager.fetchOneProduct(id: MockStoreKit.subscriptionsIds[0]) else { return await send(.productLoaded(.failure(BaseError.somethingWentWrong)))} await send(.productLoaded(.success(product))) await send(.subscriptionLoaded(.success(subscription))) } } private func buySubscriptionTaped(state: inout State) -> EffectTask<Action> { return .run { send in guard let product = await skManager.fetchOneProduct(id: MockStoreKit.subscriptionsIds[0]) //TODO: Edit else { return await send(.productLoaded(.failure(BaseError.somethingWentWrong)))} guard await skManager.purchase(product: product) != nil else { return await send(.isPurchased(false)) } await send(.isPurchased(true)) await send(.openBuyAlert(isPresented: false)) } } private func buyButtonTaped(state: inout State) -> EffectTask<Action> { return .run { [product = state.product] send in guard let product = product, await skManager.purchase(product: product) != nil else { return await send(.isPurchased(false)) } await send(.isPurchased(true)) await send(.openBuyAlert(isPresented: false)) } } func reduce(into state: inout State, action: Action) -> EffectTask<Action> { switch action { case .fetchBook: return fetchBook(state: &state) case .buyButtonTaped: return buyButtonTaped(state: &state) case .buySubscriptionTaped: return buySubscriptionTaped(state: &state) case let .productLoaded(.success(product)): state.product = product return .run { [inAppId = state.book?.inAppId] send in let product = await skManager.isPurchased(productID: inAppId ?? "") await send(.isPurchased(product)) } case let .subscriptionLoaded(result): switch result { case .success(let subscription): state.subscription = subscription case .failure(_): state.subscription = nil } return .run { send in let product = await skManager.isPurchased(productID: MockStoreKit.subscriptionsIds[0]) await send(.isPurchased(product)) } case .productLoaded(.failure(_)): return .none case .isPurchased(let isPurchased): if !state.isPurchased {//TODO: Edit race condition state.isPurchased = isPurchased } case .listenButtonTaped, .readButtonTaped: if state.isPurchased { return .run { send in await send(.openPlayer(isPresented: true)) } } else { return .run { send in await send(.openBuyAlert(isPresented: true)) } } case .openPlayer(let isPresented): state.shouldOpenPlayer = isPresented case .openBuyAlert(isPresented: let isPresented): state.shouldOpenBuyAlert = isPresented } return .none } }
CREATE DATABASE ast; use ast; CREATE TABLE users ( `u_id` INT NOT NULL UNIQUE AUTO_INCREMENT COMMENT '用户id', `u_name` VARCHAR(20) NOT NULL UNIQUE COMMENT '用户名', `u_password` VARCHAR(20) NOT NULL COMMENT '用户密码', PRIMARY KEY (u_id) ) ENGINE=InnoDB; INSERT INTO users (u_name, u_password) VALUE ('rogepi','118384'); CREATE TABLE contacts ( `id` INT NOT NULL UNIQUE AUTO_INCREMENT COMMENT '通讯录id', `name` VARCHAR(20) NOT NULL UNIQUE COMMENT '姓名', `phone` VARCHAR(20) NoT NULL COMMENT '电话', `class` VARCHAR(50) NULL COMMENT '班级', `birth_m` INT NULL COMMENT '生日月', `birth_d` INT NULL COMMENT '生日天', `u_id` INT NOT NULL COMMENT '所属用户id', PRIMARY KEY (`id`) ) ENGINE=InnoDB; CREATE TABLE courses ( `id` INT NOT NULL UNIQUE AUTO_INCREMENT COMMENT '课程id', `name` VARCHAR(30) NOT NULL COMMENT '课程名', `week` VARCHAR(20) NOT NULL COMMENT '星期', `num` INT NOT NULL COMMENT '课序', `u_id` INT NOT NULL COMMENT '所属用户id', PRIMARY KEY (`id`) ) ENGINE=InnoDB; INSERT INTO courses (name, week, num, u_id) VALUE ('高等数学', '1', '1', '1'), ('Linux操作系统', '1', '2', '1'), ('数据结构', '1', '3', '1'), ('数据库原理与应用', '1', '4', '1'), ('企业职素', '2', '1', '1'), ('离散数学', '2', '2', '1'), ('数据结构', '2', '3', '1'), ('数据结构', '2', '4', '1'), ('高等数学', '3', '1', '1'), ('大学英语', '3', '2', '1'), ('数据结构', '3', '3', '1'), ('Linux操作系统', '3', '4', '1'), ('中国近现代史', '4', '1', '1'), ('数据库原理与应用', '4', '2', '1'), ('高等数学', '4', '3', '1'), ('数据库原理与应用', '4', '4', '1'), ('离散数学', '5', '1', '1'), ('大学英语', '5', '2', '1'), ('大学体育', '5', '3', '1'), ('C++程序设计', '5', '4', '1'); CREATE TABLE todos ( `id` INT NOT NULL UNIQUE AUTO_INCREMENT COMMENT '便签id', `matter` VARCHAR(50) NOT NULL UNIQUE COMMENT '便签', `finsh` INT NOT NULL COMMENT '完成情况', `u_id` INT NOT NULL COMMENT '所属用户id', PRIMARY KEY (`id`) ) ENGINE=InnoDB; INSERT INTO contacts(name,phone,class,birth_m,birth_d,u_id) VALUE ('小智','13344557788','计本3班',12,4,1), ('小明','15877663344','计本2班',10,24,1), ('小红','17899005566','计本4班',4,5,1), ('小蓝','13466887700','计本3班',5,25,1), ('小刚','15977558866','计本1班',4,15,1), ('小西','13588667722','计本6班',2,24,1); INSERT INTO todos(matter,finsh,u_id) VALUE ('健康卡打卡',0,1), ('数据库课程设计',0,1), ('高数大作业',0,1), ('linux实验报告',0,1), ('数据结构课程设计',1,1);
library(rstan) library(dplyr) library(tidyr) library(bayesplot) library(ggplot2) library(gridExtra) # Load data diabetes_data <- read.csv("diabetes.csv") #Create histograms for each variable by outcome Glucose_ggplot <- ggplot(diabetes_data, aes(x = Glucose, fill = factor(Outcome))) + geom_histogram(binwidth = 5, alpha = 0.5, position = "identity") + labs(x = "Glucose", y = "Count", title = "Histogram of Glucose by Outcome") BloodPressure_ggplot <- ggplot(diabetes_data, aes(x = BloodPressure, fill = factor(Outcome))) + geom_histogram(binwidth = 5, alpha = 0.5, position = "identity") + labs(x = "Blood Pressure", y = "Count", title = "Histogram of Blood Pressure by Outcome") SkinThickness_ggplot <- ggplot(diabetes_data, aes(x = SkinThickness, fill = factor(Outcome))) + geom_histogram(binwidth = 5, alpha = 0.5, position = "identity") + labs(x = "Skin Thickness", y = "Count", title = "Histogram of Skin Thickness by Outcome") Insulin_ggplot<- ggplot(diabetes_data, aes(x = Insulin, fill = factor(Outcome))) + geom_histogram(binwidth = 5, alpha = 0.5, position = "identity") + labs(x = "Insulin", y = "Count", title = "Histogram of Insulin by Outcome") BMI_ggplot<- ggplot(diabetes_data, aes(x = BMI, fill = factor(Outcome))) + geom_histogram(binwidth = 1, alpha = 0.5, position = "identity") + labs(x = "BMI", y = "Count", title = "Histogram of BMI by Outcome") DiabetesPedigreeFunction_ggplot <-ggplot(diabetes_data, aes(x = DiabetesPedigreeFunction, fill = factor(Outcome))) + geom_histogram(binwidth = 0.05, alpha = 0.5, position = "identity") + labs(x = "Diabetes Pedigree Function", y = "Count", title = "Histogram of Diabetes Pedigree Function by Outcome") Age_ggplot<- ggplot(diabetes_data, aes(x = Age, fill = factor(Outcome))) + geom_histogram(binwidth = 2, alpha = 0.5, position = "identity") + labs(x = "Age", y = "Count", title = "Histogram of Age by Outcome") grid.arrange(Glucose_ggplot, BloodPressure_ggplot, SkinThickness_ggplot, Insulin_ggplot, BMI_ggplot, DiabetesPedigreeFunction_ggplot,Age_ggplot,nrow=4,ncol=2) pairs(diabetes_data) # Split data into training and testing sets set.seed(123) train_idx <- sample(seq_len(nrow(diabetes_data)), size = 0.7 * nrow(diabetes_data)) train_data <- diabetes_data[train_idx, ] test_data <- diabetes_data[-train_idx, ] # Compile and fit the model try({ stan_fit <- stan( file = "bayesian.stan", data = list( N = nrow(train_data), K = ncol(train_data) - 1, X = as.matrix(train_data[, -1]), y = as.integer(train_data$Outcome) ), chains = 4, iter = 1000, warmup = 500, seed = 123 ) }, silent = TRUE) print(summary(stan_fit)) # Check for errors in the model fit if (is(stan_fit, "try-error")) { cat("Stan model failed with error message:\n") cat(attr(stan_fit, "condition"), "\n") } else if (is(stan_fit, "stanfit")) { # Extract posterior samples posterior_samples <- rstan::extract(stan_fit) # Generate posterior predictive distribution y_ppc <- posterior_samples$y_rep # Calculate posterior predictive checks ppc_data <- test_data %>% mutate(y = as.integer(test_data$Outcome)) %>% select(-Outcome) %>% as.matrix() ppc_stats <- sapply(seq_len(nrow(ppc_data)), function(i) { mean(y_ppc[, i] == ppc_data[i, ]) }) ##Plot posterior predictive checks plot(ppc_stats, type = "l", ylim = c(0, 1), xlab = "Observation", ylab = "Posterior predictive p-value", main = "Posterior predictive checks for logistic regression model") %>% abline(h = 0.05, lty = 2, col = "red") print(traceplot(stan_fit)) print(stan_dens(stan_fit)) print(stan_hist(stan_fit)) }
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.gateways.ndelius import io.kotest.core.spec.style.DescribeSpec import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import org.mockito.Mockito import org.mockito.internal.verification.VerificationModeFactory import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.http.HttpStatus import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import uk.gov.justice.digital.hmpps.hmppsintegrationapi.gateways.HmppsAuthGateway import uk.gov.justice.digital.hmpps.hmppsintegrationapi.gateways.NDeliusGateway import uk.gov.justice.digital.hmpps.hmppsintegrationapi.helpers.generateTestOffence import uk.gov.justice.digital.hmpps.hmppsintegrationapi.mockservers.HmppsAuthMockServer import uk.gov.justice.digital.hmpps.hmppsintegrationapi.mockservers.NDeliusApiMockServer import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.UpstreamApi import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.UpstreamApiError import java.io.File import java.time.LocalDate @ActiveProfiles("test") @ContextConfiguration( initializers = [ConfigDataApplicationContextInitializer::class], classes = [NDeliusGateway::class], ) class GetOffencesForPersonTest( @MockBean val hmppsAuthGateway: HmppsAuthGateway, val nDeliusGateway: NDeliusGateway, ) : DescribeSpec( { val nDeliusApiMockServer = NDeliusApiMockServer() val deliusCrn = "X777776" beforeEach { nDeliusApiMockServer.start() nDeliusApiMockServer.stubGetSupervisionsForPerson( deliusCrn, File("src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationapi/gateways/ndelius/fixtures/GetSupervisionsResponse.json").readText(), ) Mockito.reset(hmppsAuthGateway) whenever(hmppsAuthGateway.getClientToken("nDelius")).thenReturn(HmppsAuthMockServer.TOKEN) } afterTest { nDeliusApiMockServer.stop() } it("authenticates using HMPPS Auth with credentials") { nDeliusGateway.getOffencesForPerson(deliusCrn) verify(hmppsAuthGateway, VerificationModeFactory.times(1)).getClientToken("nDelius") } it("returns offences for the matching CRN") { val response = nDeliusGateway.getOffencesForPerson(deliusCrn) response.data.shouldBe( listOf( generateTestOffence( cjsCode = null, hoCode = "10501", courtDates = listOf( LocalDate.parse("2009-07-07"), LocalDate.parse("2009-07-07"), ), description = "Common assault and battery - 10501", endDate = null, startDate = LocalDate.parse("2009-03-31"), statuteCode = null, ), generateTestOffence( cjsCode = null, hoCode = "05800", courtDates = listOf( LocalDate.parse("2009-07-07"), LocalDate.parse("2009-07-07"), ), description = "Other Criminal Damage (including causing explosion) - 05800", endDate = null, startDate = LocalDate.parse("2009-03-31"), statuteCode = null, ), generateTestOffence( cjsCode = null, hoCode = "12511", courtDates = listOf( LocalDate.parse("2009-09-01"), LocalDate.parse("2009-08-11"), ), description = "Threatening behaviour, fear or provocation of violence (Public Order Act 1986) - 12511", endDate = null, startDate = LocalDate.parse("2009-07-31"), statuteCode = null, ), generateTestOffence( cjsCode = null, hoCode = "03900", courtDates = listOf( LocalDate.parse("2009-09-01"), LocalDate.parse("2009-08-11"), ), description = "Stealing from the person of another - 03900", endDate = null, startDate = LocalDate.parse("2009-08-14"), statuteCode = null, ), generateTestOffence( cjsCode = null, hoCode = "99902", courtDates = listOf( LocalDate.parse("2009-09-01"), LocalDate.parse("2009-08-11"), ), description = "Migrated Breach Offences", endDate = null, startDate = LocalDate.parse("1900-01-01"), statuteCode = null, ), ), ) } it("returns an empty list if no offences are found") { nDeliusApiMockServer.stubGetSupervisionsForPerson( deliusCrn, """ { "supervisions": [] } """, ) val response = nDeliusGateway.getOffencesForPerson(deliusCrn) response.data.shouldBeEmpty() } it("returns an error when 404 Not Found is returned because no person is found") { nDeliusApiMockServer.stubGetSupervisionsForPerson(deliusCrn, "", HttpStatus.NOT_FOUND) val response = nDeliusGateway.getOffencesForPerson(deliusCrn) response.errors.shouldHaveSize(1) response.errors.first().causedBy.shouldBe(UpstreamApi.NDELIUS) response.errors.first().type.shouldBe(UpstreamApiError.Type.ENTITY_NOT_FOUND) } }, )
<div class="mt-[10%] mx-[30%] w-[30%] border-2 border-gray-500 p-3 rounded-lg bg-slate-100"> <div class="mb-4 text-sm text-gray-600"> <div class="text-center flex justify-center gap-2 mb-2"> <img src="{{ asset('images/logo.png') }}" alt="UserKey" class="w-[17%] h-[20%] p-1.5"> <h2 class="text-2xl font-semibold">Verify OTP</h2> </div> <hr class="border-gray-300 mb-4"> <!-- <div class="mb-4 grid grid-cols-4 gap-2"> --> <div class="mb-4 col-span-3 flex space-x-4"> <input type="text" name="verify_otp" id="verify_otp" maxlength="1" class="bg-gray-50 border border-gray-300 text-center font-semibold text-gray-900 w-full p-2 rounded-lg" value=""> <input type="text" name="verify_otp" id="verify_otp" maxlength="1" class="bg-gray-50 border border-gray-300 text-center font-semibold text-gray-900 w-full p-2 rounded-lg" value=""> <input type="text" name="verify_otp" id="verify_otp" maxlength="1" class="bg-gray-50 border border-gray-300 text-center font-semibold text-gray-900 w-full p-2 rounded-lg" value=""> <input type="text" name="verify_otp" id="verify_otp" maxlength="1" class="bg-gray-50 border border-gray-300 text-center font-semibold text-gray-900 w-full p-2 rounded-lg" value=""> <input type="text" name="verify_otp" id="verify_otp" maxlength="1" class="bg-gray-50 border border-gray-300 text-center font-semibold text-gray-900 w-full p-2 rounded-lg" value=""> <input type="text" name="verify_otp" id="verify_otp" maxlength="1" class="bg-gray-50 border border-gray-300 text-center font-semibold text-gray-900 w-full p-2 rounded-lg" value=""> </div> <div class="col-span-1"> <button onclick="getOTP()" class="btn-submit w-full bg-blue-600 text-white font-semibold p-2 rounded-lg">Verify OTP</button> </div> <!-- </div> --> </div> </div> <script> const otpInputs = document.querySelectorAll('input[type="text"]'); otpInputs.forEach((input, index) => { input.addEventListener('input', (e) => { if (e.target.value.length === 1) { // otpInputs[index + 1].focus(); if (index < otpInputs.length - 1) { otpInputs[index + 1].focus(); } else { // Last digit entered, you can trigger verification process here console.log("OTP Entered:", getOTP()); } } else if (e.target.value.length === 0) { if (index > 0) { otpInputs[index - 1].focus(); } } }); input.addEventListener('keydown', (e) => { if (e.key === 'Backspace' && e.target.value.length === 0) { if (index > 0) { otpInputs[index - 1].focus(); } } }); }); async function getOTP() { let otp = ""; otpInputs.forEach((input) => { otp += input.value; }); // return otp; // Send OTP to server if(otp.length !== 6){ errorToast('Please enter valid OTP'); }else{ showLoader(); let res = await axios.post('/verify-otp', { otp: otp, email: sessionStorage.getItem('email'), }); hideLoader(); if(res.status === 200 && res.data['status'] === 'success'){ successToast(res.data['message']); sessionStorage.clear(); setTimeout(() => { window.location.href = '/reset-password'; }, 2000); }else{ errorToast(res.data['message']); } } } </script>
<p-card header="Users Table" responsiveLayout="scroll" class="table-container"> <p-table [value]="users" class="card-table m-2 "> <ng-template pTemplate="header"> <tr> <th>Username</th> <th>Email</th> <th>Subscribed</th> <th>Country</th> <th>City</th> <th>Actions</th> </tr> </ng-template> <ng-template pTemplate="body" let-user> <tr> <td>{{ user.username }}</td> <td>{{ user.email }}</td> <td> <div *ngIf="user.subscribed; then Check; else Ban"></div> <ng-template #Check> <i class="pi pi-check"></i> </ng-template> <ng-template #Ban> <i class="pi pi-ban"></i> </ng-template> </td> <td>{{ user.country }}</td> <td>{{ user.countryCity }}</td> <td> <button class="p-button-secondary mr-3" pButton type="button" label="Edit" icon="pi pi-user-edit" iconPos="right" (click)="editUserInfo(user)" ></button> <button class="p-button-danger" pButton type="button" label="Delete" icon="pi pi-trash" iconPos="right" (click)="deleteUser(user.id)" ></button> </td> </tr> </ng-template> </p-table> </p-card> <!-- <pre> {{ users | json }} </pre> -->
''' In this file, write the code to segment an unseen image If there is a new model you would like to try, don't delete what's here; just add a new function in this file and change which function is called in main.py ''' import matplotlib.pyplot as plt import numpy as np import cv2 as cv import os import csv def model_segmentation_by_sift(frame): ''' Segments the image frame into left and right tools Parameters: frame: a dimensional nxmx3 uint8 numpy array, where the third dimension is RBG color in the range 0-255 Returns: left_guess: a nxmx1 binary numpy array. True values represent the pixel locations of the left (or only) tool in the image. If there is no tool, all values are False right_guess: a nxmx1 binary numpy array. True values represent the pixel locations of the right tool, if any. If there is no second tool, all values will be False. ''' # Note - probably DON'T resize the image # Unless you upscale it again at the end # Because the output needs to be the same size as the input # Blur only red hsv_image = cv.cvtColor(frame, cv.COLOR_BGR2HSV) low_H = 215/2 high_H = 330/2 low_S = 0*2.55 high_S = 90*2.55 low_V = 0*2.55 high_V = 90*2.55 lower_bound = np.array([215/2, 0*2.55, 0*2.55]) # Lower bound for green in HSV upper_bound = np.array([330/2, 90*2.55, 90*2.55]) # Upper bound for green in HSV #lower_bound = np.array([100, 50, 50]) # Lower bound for blue in HSV #upper_bound = np.array([130, 255, 255]) # Create a mask based on the color threshold mask = cv.inRange(hsv_image, lower_bound, upper_bound) # Apply the mask to the original image masked_image = cv.bitwise_and(frame, frame, mask=mask) # Apply a blur operation to the masked image blurred_image = cv.GaussianBlur(masked_image, (51, 51), 0) # Invert the mask mask = cv.bitwise_not(mask) # Apply the inverted mask to the original image masked_background = cv.bitwise_and(frame, frame, mask=mask) # Combine the original image and the blurred image frame = cv.add(masked_background, blurred_image) # Sharpen image tool points kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]) frame = cv.filter2D(frame, -1, kernel) gamma=0.9 frame1=np.power(frame,gamma) if frame1.dtype != 'uint8': frame1 = cv.convertScaleAbs(frame1) frame1 = cv.Canny(frame1, 600, 870) kernel_size = 21 frame = cv.GaussianBlur(frame,(kernel_size,kernel_size),0) # Edges are weird. Get them out frame[0:15,:] = 0 frame[-15:-1,:] = 0 frame[:,0:15] = 0 frame[:,-15:-1] = 0 # Dilate and erode kernel = np.ones((3, 3), np.uint8) frame = cv.erode(frame, kernel, iterations=1) kernel = np.ones((5, 5), np.uint8) frame = cv.dilate(frame, kernel, iterations=2) gray_frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # Initialize the SIFT detector sift = cv.SIFT_create() # Detect keypoints and descriptors keypoints, descriptors = sift.detectAndCompute(gray_frame, None) # Create a mask to store the segmented regions mask = np.zeros_like(gray_frame) # Draw keypoints on the mask (regions of interest) for kp in keypoints: x, y = np.int32(kp.pt) size = np.int32(kp.size) cv.circle(mask, (x, y), 19, 255, -1) kernel = np.ones((5, 5), np.uint8) mask = cv.morphologyEx(mask, cv.MORPH_CLOSE, kernel) segmented_img = cv.bitwise_and(frame, frame, mask=mask) frame_with_keypoints = cv.drawKeypoints(frame, keypoints, None) # cv.imshow('Video with SIFT Keypoints', frame_with_keypoints) # TODO uncomment frame = gray_frame # Keep the two biggest curves gray_seg = cv.cvtColor(segmented_img, cv.COLOR_BGR2GRAY) contours, hierarchy = cv.findContours(gray_seg,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_NONE ) min_contour = 2000 maxContour = 0 secondContour = 0 maxContourData = None secondContourData = None for contour in contours: contourSize = cv.contourArea(contour) if contourSize > secondContour and contourSize > min_contour: if contourSize > maxContour: secondContour = maxContour secondContourData = maxContourData maxContour = contourSize maxContourData = contour else: secondContour = contourSize secondContourData = contour # Create a mask from the largest contours left_guess = np.zeros(frame.shape, np.uint8) right_guess = np.zeros(frame.shape, np.uint8) if secondContour > 0: # Find which is right and left M_first = cv.moments(maxContourData) cX_first = int(M_first["m10"] / M_first["m00"]) M_second = cv.moments(secondContourData) cX_second = int(M_second["m10"] / M_second["m00"]) if cX_second > cX_first: # first is left cv.drawContours(left_guess, [maxContourData], -1, 255, cv.FILLED) cv.drawContours(right_guess, [secondContourData], -1, 255, cv.FILLED) else: # first is right cv.drawContours(left_guess, [secondContourData], -1, 255, cv.FILLED) cv.drawContours(right_guess, [maxContourData], -1, 255, cv.FILLED) elif maxContour > 0: cv.drawContours(left_guess, [maxContourData], -1, 255, cv.FILLED) return left_guess, right_guess def match_features(descriptors1, descriptors2): bf = cv.BFMatcher() matches = bf.knnMatch(descriptors1, descriptors2, k=2) good_matches = [] for m, n in matches: if m.distance < 0.75 * n.distance: good_matches.append(m) return good_matches def segment_instrument(img, keypoints): mask = np.zeros_like(img) pts = np.array([kp.pt for kp in keypoints], dtype=np.int32) cv.fillPoly(mask, [pts], (255, 255, 255)) segmented = cv.bitwise_and(img, mask) return segmented
import React, { useEffect, useState } from "react"; import { FaUserSecret } from "react-icons/fa"; import { BiArrowBack } from "react-icons/bi"; import appwriteService from "../Appwrite/config"; import { useNavigate, useParams } from "react-router-dom"; import { Container, PostCard, ProfileToast, AuthorPost, LikeBtn, } from "../components/index"; import parse from "html-react-parser"; import { useSelector } from "react-redux"; import toast from "react-hot-toast"; const Post = () => { const [post, setPost] = useState(null); const [isLiked, setIsLiked] = useState(false); const [likeCount, setLikeCount] = useState(post && post.likes.length); const [more, setMore] = useState([]); const { slug } = useParams(); const navigate = useNavigate(); const userData = useSelector((state) => state.auth.userData); const isAuthor = post && userData ? post.userId === userData.$id : false; const findId = (arr, str) => { return arr.includes(str); }; useEffect(() => { if (userData) { appwriteService.getPosts([]).then((recs) => { if (recs) { setMore( recs.documents.filter( (rec) => rec.status != "Post Anonymous" && rec?.userId === post?.userId && rec.$id !== post.$id ) ); } }); } }, [userData, post]); useEffect(() => { window.scrollTo(0, 0); if (slug) { appwriteService.getPost(slug).then((post) => { if (post) { setPost(post); const find = findId(post.likes, userData.$id); setLikeCount(post.likes.length); setIsLiked(find); } else navigate("/"); }); } else { navigate("/"); } }, [, slug, navigate]); const profile = () => { toast.custom((t) => ( <ProfileToast t={t} status={post.status} username={post.username} email={post.email} /> )); }; const handleLikes = async () => { if (post) { const updatedLikes = isLiked ? post.likes.filter((id) => id !== userData.$id) : [...post.likes, userData.$id]; setIsLiked((prev) => !prev); setLikeCount(!isLiked ? post.likes.length + 1 : post.likes.length - 1); const dbPost = await appwriteService.updatePost(post.$id, { ...post, likes: updatedLikes, }); } }; return post ? ( <section className="text-gray-600 w-full body-font"> <BiArrowBack className="cursor-pointer absolute text-3xl sm:text-4xl m-4 sm:m-8" onClick={() => navigate(-1)} /> <div className="container mx-auto flex px-5 pt-2 pb-12 items-center justify-center flex-col"> <img className="lg:w-4/6 border w-5/6 mb-6 sm:mb-10 object-contain max-h-96 object-center rounded-lg" src={appwriteService.getFilePreview(post.featuredImage)} alt={post.title} /> <div className="text-center lg:w-2/3 w-full"> <h1 className="title-font sm:text-4xl text-3xl mb-4 font-medium text-gray-900"> {post.title} </h1> <p className="mb-8 text-gray-900 text-lg whitespace-break-spaces custom-content"> {parse(post.content)} </p> <div className="flex justify-between items-center"> <div className=" text-left flex gap-2"> <span onClick={profile} className="bg-gray-600 cursor-pointer text-white text-center uppercase w-10 h-10 aspect-square text-2xl font-semibold rounded-full flex items-center justify-center" > {post.status == "Post Anonymous" ? ( <FaUserSecret /> ) : ( post.username[0] )} </span> <div> <h2 className="font-semibold"> {isAuthor ? "You" : post.username} </h2> <h2 className="text-gray-500 leading-4">{post.time}</h2> </div> </div> <LikeBtn isLiked={isLiked} likeCount={likeCount} handleLikes={handleLikes} /> </div> <br /> {isAuthor && <AuthorPost id={post.$id} image={post.featuredImage} />} </div> </div> <div className={`w-full ${post.status != "Post Anonymous" && "pb-10"}`}> <Container> {more.length > 0 && post.status != "Post Anonymous" && ( <h2 className="text-2xl font-semibold flex flex-wrap justify-center"> More from {post.username}: </h2> )} <br /> <div className="flex flex-wrap gap-2 gap-y-4 duration-500 justify-center"> {more.length > 0 && post.status != "Post Anonymous" && more .slice() .reverse() .map( (rec, index) => index < 3 && ( <div key={rec.$id} className="p-4 sm:p-2 w-full border-2 border-slate-900 duration-200 cursor-pointer hover:border-gray-300 rounded-md min-w-64 sm:w-72 md:w-1/4 lg:w-1/5" > <PostCard {...rec} /> </div> ) )} </div> </Container> </div> </section> ) : null; }; export default Post;
import Foundation public enum Errors: Error, LocalizedError { case errorWithLogInfo(String, underlyingError: Error) case openingLogError(Error, underlyingError: Error) public var errorDescription: String? { description } public var description: String { switch self { case .errorWithLogInfo(let logInfo, underlyingError: let underlyingError): return """ An error occurred: \(underlyingError.localizedDescription). Here is the contents of the log file: """ + logInfo case .openingLogError(let error, underlyingError: let underlyingError): return """ An error occurred: \(underlyingError.localizedDescription) Also, an error occurred while attempting to open the log file: \(error.localizedDescription) """ } } }
import { ChangeEvent, FC, useCallback, useEffect, useState, useRef } from 'react'; import './Range.scss'; import React from 'react'; interface MultiRangeSliderProps { min: number; max: number; onChange: ({ min, max }: { min: number; max: number }) => void; } const containerClass = 'slider-range__container'; const resultBoxClass = 'slider-range__result'; const viewRangeClass = 'slider-range'; const rangeTrackClass = 'slider-range__track'; const rangeClass = 'slider-range__range'; export const Range: FC<MultiRangeSliderProps> = ({ min, max, onChange }) => { const [minVal, setMinVal] = useState(min); const [maxVal, setMaxVal] = useState(max); const minValRef = useRef<HTMLInputElement>(null); const maxValRef = useRef<HTMLInputElement>(null); const range = useRef<HTMLDivElement>(null); const getPercent = useCallback( (value: number) => Math.round(((value - min) / (max - min)) * 100), [min, max] ); useEffect(() => { if (maxValRef.current) { const minPercent = getPercent(minVal); const maxPercent = getPercent(+maxValRef.current.value); if (range.current) { range.current.style.left = `${minPercent}%`; range.current.style.width = `${maxPercent - minPercent}%`; } } }, [minVal, getPercent]); useEffect(() => { if (minValRef.current) { const minPercent = getPercent(+minValRef.current.value); const maxPercent = getPercent(maxVal); if (range.current) { range.current.style.width = `${maxPercent - minPercent}%`; } } }, [maxVal, getPercent]); useEffect(() => { onChange({ min: minVal, max: maxVal }); }, [minVal, maxVal, onChange]); return ( <div className={containerClass}> <input type="range" min={min} max={max} value={minVal} ref={minValRef} onChange={(event: ChangeEvent<HTMLInputElement>) => { const value = Math.min(+event.target.value, maxVal - 1); setMinVal(value); event.target.value = value.toString(); }} className={`${'thumb thumb__zindex-3'} ${ minVal > max - 100 ? 'thumb__zindex-5' : '' }`} /> <input type="range" min={min} max={max} value={maxVal} ref={maxValRef} onChange={(event: ChangeEvent<HTMLInputElement>) => { const value = Math.max(+event.target.value, minVal + 1); setMaxVal(value); event.target.value = value.toString(); }} className="thumb thumb__zindex-4" /> <div className={viewRangeClass}> <div className={rangeTrackClass}></div> <div ref={range} className={rangeClass}></div> </div> <div className={resultBoxClass}> <div>{minVal + ' $'}</div> <div>{maxVal + ' $'}</div> </div> </div> ); };
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ import React from "react"; import { StyleSheet } from "react-native"; import { SafeAreaProvider } from "react-native-safe-area-context"; import { NavigationContainer } from "@react-navigation/native"; import { Colors } from "react-native/Libraries/NewAppScreen"; import { LogBox } from "react-native"; import AppNavigator from "./src/navigation/appNavigator"; import AppProvider from "./appProvider"; LogBox.ignoreLogs([ "Animated: `useNativeDriver` was not specified", "Sending `onAnimatedValueUpdate` with no listeners registered", "Warning: componentWillReceiveProps has been renamed, and is not recommended for use", ]); const App = () => { return ( <AppProvider> <SafeAreaProvider> <NavigationContainer> <AppNavigator /> </NavigationContainer> </SafeAreaProvider> </AppProvider> ); }; //change const styles = StyleSheet.create({ scrollView: { backgroundColor: Colors.lighter, }, engine: { position: "absolute", right: 0, }, body: { backgroundColor: Colors.white, fontFamily: "Poppins-Black", }, sectionContainer: { marginTop: 32, paddingHorizontal: 24, }, sectionTitle: { fontSize: 24, fontWeight: "600", color: Colors.black, }, sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: "400", color: Colors.dark, }, highlight: { fontWeight: "700", }, footer: { color: Colors.dark, fontSize: 12, fontWeight: "600", padding: 4, paddingRight: 12, textAlign: "right", }, }); export default App;
<div class="card"> <div class="card-body"> <form [formGroup]="formulario" (ngSubmit)="onSubmit(formulario)" novalidate> <table class="table"> <thead> <tr> <th scope="col">Día</th> <th scope="col">Horario</th> <th scope="col">Especialidad</th> <th scope="col">Duración</th> </tr> </thead> <tbody> <tr *ngFor="let dia of dias; index as i" id="{{dia}}" [formGroupName]="dia" class="formGroup"> <th scope="row"><label class="form-check-label me-3" for="{{dia}}">{{dia}}</label></th> <td> <select class="form-select form-select-sm" formControlName="rango" [compareWith]='compare'> <option [ngValue]="valoresHorario[0]" class="dropdown-item">De {{valoresHorario[0].horaInicio}} a {{valoresHorario[0].horaFin}}</option> <ng-container *ngIf="dia != 'Sabado'"> <option [ngValue]="valoresHorario[1]" class="dropdown-item">De {{valoresHorario[1].horaInicio}} a {{valoresHorario[1].horaFin}}</option> <option [ngValue]="valoresHorario[2]" class="dropdown-item">De {{valoresHorario[2].horaInicio}} a {{valoresHorario[2].horaFin}}</option> </ng-container> <option [ngValue]="valoresHorario[3]" class="dropdown-item">No brindar atención</option> </select> </td> <ng-container *ngIf="formulario.controls[dia].value.rango.horaInicio != 0"> <td> <select class="form-select form-select-sm" formControlName="especialidadDelDia"> <option [ngValue]="esp" class="dropdown-item" *ngFor="let esp of especialidadesDelEspecialista">{{esp}}</option> </select> </td> <td> <select class="form-select form-select-sm" formControlName="duracionDelDia"> <option [ngValue]="dur" class="dropdown-item" *ngFor="let dur of valoresDuracion">{{dur}} minutos</option> </select> </td> </ng-container> </tr> </tbody> </table> <button *ngIf="!modificacionHabilitada" (click)="habilitarModificacion()" class="btn btn-primary me-1">Modificar</button> <button *ngIf="modificacionHabilitada" [disabled]="formulario.invalid" class="btn btn-success me-1" type="submit">Guardar</button> <button *ngIf="modificacionHabilitada" (click)="cancelarModificacion()" class="btn btn-danger me-1">Cancelar</button> </form> </div> </div> <!-- Así se accede a campos anidados en un formgroup {{formulario.controls['Lunes'].value.rango.horaInicio | json}} <div class="card"> <div class="card-body"> <form [formGroup]="formulario" (ngSubmit)="onSubmit(formulario)" novalidate> <div *ngFor="let dia of dias; index as i" id="{{dia}}" [formGroupName]="dia" class="formGroup"> <div class="input-group mt-3"> <label class="form-check-label me-3" for="{{dia}}">{{dia}}</label> <div> <select class="form-select form-select-sm" formControlName="rango" [compareWith]='compare'> <option [ngValue]="valoresHorario[0]" class="dropdown-item">De {{valoresHorario[0].horaInicio}} a {{valoresHorario[0].horaFin}}</option> <option [ngValue]="valoresHorario[1]" class="dropdown-item">De {{valoresHorario[1].horaInicio}} a {{valoresHorario[1].horaFin}}</option> <option [ngValue]="valoresHorario[2]" class="dropdown-item">De {{valoresHorario[2].horaInicio}} a {{valoresHorario[2].horaFin}}</option> <option [ngValue]="valoresHorario[3]" class="dropdown-item">No brindar atención</option> </select> </div> <ng-container *ngIf="formulario.controls[dia].value.rango.horaInicio != 0"> <div class="ms-2"> <select class="form-select form-select-sm" formControlName="especialidadDelDia"> <option [ngValue]="esp" class="dropdown-item" *ngFor="let esp of especialidadesDelEspecialista">{{esp}} </option> </select> </div> <div class="ms-2"> <select class="form-select form-select-sm" formControlName="duracionDelDia"> <option [ngValue]="dur" class="dropdown-item" *ngFor="let dur of valoresDuracion">{{dur}} minutos </option> </select> </div> </ng-container> </div> <p></p> </div> <button [disabled]="formulario.invalid" class="btn btn-primary" type="submit">Guardar</button> </form> </div> </div> -->
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Models\User; class UserProfileController extends Controller { public function show() { $user = auth()->user(); return view('profile.show', compact('user')); } public function edit() { $user = Auth::user(); return view('profile.edit', compact('user')); } public function update(Request $request) { $user = Auth::user(); $request->validate([ 'name' => 'required', 'email' => 'required|email|unique:users,email,' . auth()->user()->id . ',user_id', 'password' => 'required|min:6', 'user_room' => 'required|numeric', 'user_pic' => 'image|mimes:jpeg,png,jpg|max:2048', 'admin_id' => 'required|numeric', ]); $user->name = $request->input('name'); $user->email = $request->input('email'); $user->password = bcrypt($request->input('password')); $user->user_room = $request->input('user_room'); $user->admin_id = $request->input('admin_id'); if ($request->hasFile('user_pic')) { $imagePath = $request->file('user_pic')->store('public'); $user->user_pic = basename($imagePath); } $user->save(); return redirect()->route('profile.show'); } }
// // PurgeOperation.swift // Kinvey // // Created by Victor Barros on 2016-02-18. // Copyright © 2016 Kinvey. All rights reserved. // import Foundation import PromiseKit internal class PurgeOperation<T: Persistable>: SyncOperation<T, Int, Swift.Error> where T: NSObject { typealias ResultType = Swift.Result<Int, Swift.Error> internal override init( sync: AnySync?, cache: AnyCache<T>?, options: Options? ) { super.init( sync: sync, cache: cache, options: options ) } func execute(timeout: TimeInterval? = nil, completionHandler: CompletionHandler?) -> AnyRequest<ResultType> { let requests = MultiRequest<ResultType>() var promises: [Promise<Void>] = [] if let sync = sync { for pendingOperation in sync.pendingOperations() { var urlRequest = pendingOperation.buildRequest() if let timeout = timeout { urlRequest.timeoutInterval = timeout } switch HttpMethod.parse(urlRequest.httpMethod ?? "GET").requestType { case .update: if let promise = updatePromise(pendingOperation: pendingOperation, requests: requests) { promises.append(promise) } else { sync.remove(pendingOperation: pendingOperation) } case .delete: promises.append(deletePromise(pendingOperation: pendingOperation, sync: sync)) case .create: promises.append(createPromise(pendingOperation: pendingOperation, sync: sync)) default: break } } } when(fulfilled: promises).done { (results: [Void]) -> Void in let result: ResultType = .success(results.count) requests.result = result completionHandler?(result) }.catch { error in let result: ResultType = .failure(error) requests.result = result completionHandler?(result) } return AnyRequest(requests) } private func createPromise(pendingOperation: PendingOperation, sync: AnySync) -> Promise<Void> { return Promise<Void> { resolver in if let objectId = pendingOperation.objectId { let query = Query(format: "\(try T.entityIdProperty()) == %@", objectId) cache?.remove(byQuery: query) } sync.remove(pendingOperation: pendingOperation) resolver.fulfill(()) } } private func deletePromise(pendingOperation: PendingOperation, sync: AnySync) -> Promise<Void> { return Promise<Void> { resolver in sync.remove(pendingOperation: pendingOperation) resolver.fulfill(()) } } private func updatePromise(pendingOperation: PendingOperation, requests: MultiRequest<ResultType>) -> Promise<Void>? { guard let objectId = pendingOperation.objectId else { return nil } return Promise<Void> { resolver in let client = options?.client ?? self.client let request = client.networkRequestFactory.appData.buildAppDataGetById( collectionName: try T.collectionName(), id: objectId, options: options, resultType: ResultType.self ) requests.addRequest(request) request.execute() { data, response, error in if let response = response, response.isOK, let data = data, let persistable = try? client.jsonParser.parseObject(T.self, from: data) { self.cache?.save(entity: persistable) self.sync?.remove(pendingOperation: pendingOperation) resolver.fulfill(()) } else { resolver.reject(buildError(data, response, error, self.client)) } } } } }
import asyncio import json import logging from datetime import datetime from logging.handlers import RotatingFileHandler from time import sleep import aiohttp import certifi from pymongo import MongoClient, UpdateOne from pymongo.errors import BulkWriteError, ConnectionFailure import modules.preferences.preferences as pref from cards import reminder_card as rc # pylint: disable=logging-fstring-interpolation, undefined-variable Mongo_Connection_URI: MongoClient = MongoClient( f"{pref.MONGO_URI}?retryWrites=true&w=majority", tlsCAFile=certifi.where(), serverSelectionTimeoutMS=500, ) console_formatter = logging.Formatter( "%(asctime)s - %(filename)s:%(lineno)d - %(name)s - %(levelname)s - %(message)s" ) # Create a stream handler with the formatter console_handler = logging.StreamHandler() console_handler.setFormatter(console_formatter) console_handler.setLevel(logging.INFO) # Create a file handler for file logging file_handler = RotatingFileHandler( "./logs/reminders.log", maxBytes=10 * 1024 * 1024, backupCount=5 ) # 10 MB file_handler.setFormatter(console_formatter) file_handler.setLevel(logging.INFO) # Logging to Flask console logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(console_handler) logger.addHandler(file_handler) # Add file handler to the logger logger.propagate = False message_counter = { "accepted": 0, "tentative": 0, "no_response": 0, } message_sets: dict[str, set] = {} headers = { "Authorization": pref.fusebot_help_bearer, "Content-Type": "application/json", } reminders_collection = Mongo_Connection_URI["fuse-test"]["cwa_reminders"] async def send_message(session, email, payload, message_type): max_retries = 3 too_many_requests_counter = 0 too_many_requests_limit = 1 for i in range(max_retries): try: async with session.post( pref.WEBEX_MSG_URL, json=payload, headers=headers ) as response: if response.status == 429: # Use the Retry-After header to determine how long to wait retry_after = int( response.headers.get("Retry-After", 5) ) # Default to 5 seconds if Retry-After header is not provided if too_many_requests_counter < too_many_requests_limit: print( f" Too many requests, retrying in {retry_after} seconds..." ) too_many_requests_counter += 1 await asyncio.sleep( retry_after ) # Pause execution for 'retry_after' seconds continue if response.status == 200: logger.info( f" Sent {message_type} message to {email} ({response.status})" ) response_text = await response.text() message_id = json.loads(response_text)["id"] # Increment the counter for the message type message_counter[message_type] += 1 return [message_id, email, 200] logger.warning( f" Unexpected status ({response.status}) sending to {email}" ) return None except Exception as e: logger.error( f" Failed to send {message_type} message to {email} due to {str(e)}" ) async def main(fuse_date): async with aiohttp.ClientSession() as session: tasks = [] markdown_msg = ( "Adaptive card response. Open the message on a supported client to respond." ) for message_type, message_set in message_sets.items(): if message_set: # Create the attachment inside the loop attachment = rc.reminder_card(fuse_date, message_type) for person in message_set: email = f"{person}@cisco.com" # < --- change to p.test_email for test. person in prod mode payload = { "toPersonEmail": email, "markdown": markdown_msg, "attachments": attachment, } tasks.append(send_message(session, email, payload, message_type)) results = await asyncio.gather(*tasks) # Update the reminders database with the message status and message id if results: logger.info(f"Processing {len(results)} results") operations = [] for result in results: if result is not None: logger.info(f"Processing result: {result}") # Assuming that result[1] is the email alias = ( result[1].replace("@cisco.com", "") if len(result) > 1 else None ) try: # Attempt to unpack the tuple message_id, email, status = result logger.info(f"Adding {email} message to reminders database") # Create timestamp for Mountain Time Zone ts = datetime.now() # Add the UpdateOne operation to the list operations.append( UpdateOne( {"date": fuse_date, "alias": alias}, { "$set": { "message_id": message_id, "email": email, "status": status, "timestamp": ts, } }, upsert=True, ) ) except (TypeError, ValueError) as te: # Log an error message if unpacking fails logger.error( f"Error unpacking result for record {alias}: {te} - skipping record" ) if operations: logger.info(f"Operations to execute: {len(operations)}") else: logger.info("No operations to execute") # Only perform the bulk write if there are operations to execute if operations: logger.info(f"Operations to execute: {len(operations)}") logger.info("Updating reminders database") for attempt in range(5): try: reminder_updates = reminders_collection.bulk_write(operations) if reminder_updates.upserted_ids: logger.info( f"MongoDB upserted {len(reminder_updates.upserted_ids)} records." ) break # Exit the retry loop if successful except BulkWriteError as bwe: print("Bulk Write Error: ", bwe.details) sleep_duration = pow(2, attempt) logger.warning( f"*** Sleeping for {sleep_duration} seconds and trying again ***" ) sleep(sleep_duration) # Exponential backoff except Exception as e: logger.error(f"An unexpected error occurred: {e}") logger.error(f"operations: {operations}") break # Exit the retry loop if an unexpected exception occurs else: logger.info("No operations to execute") # Print the message counter at the end logger.info(f"Sent message count by type: {message_counter}") logger.info(f"Total messages sent: {sum(message_counter.values())}") class Reminders: """ Class to process attachments """ def __init__(self, inside_fuse_date, mongo_connect_uri): """ Constructor """ self.fuse_date = inside_fuse_date self.mongo_connect_uri = mongo_connect_uri self.logger = logging.getLogger(__name__) def send_reminders(self): """ Process reminders """ try: # Retrieve the attendees record from the database self.logger.info("Retrieving attendees record") attendees = self.mongo_connect_uri[pref.MONGODB]["cwa_prematch"].find_one( {"date": self.fuse_date} ) if attendees is None: self.logger.info("No attendees record found") return (None, set(), set(), set(), set()) self.logger.info(attendees) accepted_set = set(attendees["accepted"]) declined_set = set(attendees["declined"]) tentative_set = set(attendees["tentative"]) no_response_set = set(attendees["no_response"]) self.logger.info("Retrieved attendees record") # make message_sets a global variable global message_sets # pylint: disable=global-statement message_sets = { "accepted": accepted_set, "tentative": tentative_set, "no_response": no_response_set, } logger.info(f" **** MESSAGE SETS: {message_sets}") asyncio.run(main(self.fuse_date)) self.logger.info("Main function finished") return True, accepted_set, declined_set, tentative_set, no_response_set except ConnectionFailure as cf: self.logger.error(f" Connection Failure looking up attendees record: {cf}") self.logger.warning( " *** Sleeping for {pow(2, _)} seconds and trying again ***" ) sleep(pow(2, _)) # noqa: F821 # type: ignore return False, 0, 0, 0, 0 except KeyError: self.logger.error(" *** No attendees record found ***") if __name__ == "__main__": pass
import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { handleBuyProduct } from "../../hooks/BuyProduct"; import { TProduct } from "../../components/type/Types"; interface ProductCartProps { datas: TProduct[]; } const ProductCart: React.FC<ProductCartProps> = ({ datas }) => { const navigate = useNavigate(); const [hoverStates, setHoverStates] = useState<boolean[]>( new Array(datas.length).fill(false) ); const [imageIndexes, setImageIndexes] = useState<number[]>( new Array(datas.length).fill(0) ); useEffect(() => { const intervals = datas.map((_, index) => { if (hoverStates[index]) { return setInterval(() => { setImageIndexes((prevIndexes) => { const newIndexes = [...prevIndexes]; newIndexes[index] = (newIndexes[index] + 1) % datas[index].images.length; return newIndexes; }); }, 3000); } return null; }); return () => { intervals.forEach((interval) => { if (interval) clearInterval(interval); }); }; }, [hoverStates, datas]); const handleProductClick = async (id: string) => { try { const productData = await handleBuyProduct(id); console.log("Product Data:", productData); navigate(`/product/${id}`); } catch (error) { console.error("Error during product purchase and navigation:", error); } }; const handleMouseEnter = (index: number) => { setHoverStates((prevStates) => { const newStates = [...prevStates]; newStates[index] = true; return newStates; }); }; const handleMouseLeave = (index: number) => { setHoverStates((prevStates) => { const newStates = [...prevStates]; newStates[index] = false; return newStates; }); setImageIndexes((prevIndexes) => { const newIndexes = [...prevIndexes]; newIndexes[index] = 0; return newIndexes; }); }; return ( <div className="grid w-11/12 mx-auto grid-cols-1 md:grid-cols-4 md:gap-10 text-[#3c3633]"> {datas?.length > 0 ? ( datas.map((data, index) => ( <div key={data._id} onClick={() => handleProductClick(data._id)} className="cursor-pointer border md:mb-0 mb-12 " > <div className="overflow-hidden shadow-md transition-shadow ease-out relative hover:shadow-lg " onMouseEnter={() => handleMouseEnter(index)} onMouseLeave={() => handleMouseLeave(index)} > <div className="relative"> <img src={data.images[imageIndexes[index]]} alt={`Image ${data.title}`} className="w-full mx-auto md:w-[256px] h-[372px] transition-opacity duration-100 ease-out" /> </div> </div> <div> <p className="text-[22px] py-1 text-center font-semibold"> {data.title} </p> <p className="text-center font-medium text-xl tracking-wide"> ${data.price} </p> </div> </div> )) ) : ( <p>No products available</p> )} </div> ); }; export default ProductCart;
package lazyInitialization; // Thread-Safe Singleton (Lazy Initialization with Double Checked Locking) public class Singleton { // Double Checked Locking (volatile since Java5) private static volatile Singleton instance = null; private Singleton() { System.out.println("Thread-Safe Singleton (Lazy Initialization with Double Checked Locking) constructor"); } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) instance = new Singleton(); } } return instance; } public void print() { System.out.println("Thread-Safe Singleton (Lazy Initialization with Double Checked Locking) instance hashCode=" + instance.hashCode()); } }
import { access, mkdir, readFile, writeFile } from "fs/promises"; import { dirname, join } from "path"; import { METICULOUS_LOGGER_NAME } from "@alwaysmeticulous/common"; import log from "loglevel"; import { Duration } from "luxon"; import { lock, LockOptions } from "proper-lockfile"; export const sanitizeFilename: (filename: string) => string = (filename) => { return filename.replace(/[^a-zA-Z0-9]/g, "_"); }; type ReleaseLock = () => Promise<void>; export interface LoadOrDownloadJsonFileOptions<T> { filePath: string; downloadJson: () => Promise<T | null>; /** * For debug messages e.g. 'session' or 'session data' */ dataDescription: string; } /** * Returns the JSON.parse'd contents of the file at the given path. If the file * doesn't exist yet then it downloads the object, writes it to the file, and returns it. * * Handles concurrent processes trying to download to the same file at the same time. */ export const getOrDownloadJsonFile = async <T>({ filePath, downloadJson, dataDescription, }: LoadOrDownloadJsonFileOptions<T>): Promise<T | null> => { const logger = log.getLogger(METICULOUS_LOGGER_NAME); await mkdir(dirname(filePath), { recursive: true }); // We create a lock file so that if multiple processes try downloading at the same // time they don't interfere with each other. The second process to run will // wait for the first process to complete, and then return straight away because // it'll notice the file already exists. const releaseLock = await waitToAcquireLockOnFile(filePath); try { const existingData = await readFile(filePath) .then((data) => JSON.parse(data.toString("utf-8"))) .catch(() => null); if (existingData) { logger.debug(`Reading ${dataDescription} from local copy in ${filePath}`); return existingData; } const downloadedData = await downloadJson(); if (downloadedData) { await writeFile(filePath, JSON.stringify(downloadedData, null, 2)); logger.debug(`Wrote ${dataDescription} to ${filePath}`); } return downloadedData; } finally { await releaseLock(); } }; export const waitToAcquireLockOnFile = async ( filePath: string ): Promise<ReleaseLock> => { // In many cases the file doesn't exist yet, and can't exist yet (need to download the data, and creating an // empty file beforehand is risky if the process crashes, and a second process tries reading the empty file). // However proper-lockfile requires us to pass a file or directory as the first arg. This path is just used // to detect if the same process tries taking out multiple locks on the same file. It just needs to be calculated // as something that's unique to the file, and gives the same path for a given file everytime. So we create our // own lock-target directory for this purpose (directory not file since mkdir is guaranteed to be synchronous). // The path needs to actually exist, since proper-lockfile resolves symlinks on it. // // Note: we don't delete the lock directory afterwards because doing so without creating race-conditions is tricky const lockDirectory = `${filePath}.lock-target`; await mkdir(lockDirectory, { recursive: true }); const releaseLock = await lock(lockDirectory, { retries: LOCK_RETRY_OPTIONS, lockfilePath: `${filePath}.lock`, }); return async () => { await releaseLock(); }; }; export const fileExists = (filePath: string) => access(filePath) .then(() => true) .catch(() => false); export const waitToAcquireLockOnDirectory = ( directoryPath: string ): Promise<ReleaseLock> => { return lock(directoryPath, { retries: LOCK_RETRY_OPTIONS, lockfilePath: join(directoryPath, "dir.lock"), }); }; const LOCK_RETRY_OPTIONS: LockOptions["retries"] = { // We want to keep on retrying till we get the maxRetryTime, so we set retries, which is a maximum, to a high value retries: 1000, factor: 1.05, minTimeout: 500, maxTimeout: 2000, // Wait a maximum of 120s for the other process to finish downloading and/or extracting maxRetryTime: Duration.fromObject({ minutes: 2 }).as("milliseconds"), // Randomize so processes are less likely to clash on their retries randomize: true, };
/* * SPDX-FileCopyrightText: 2013 (c) Business Operation Systems GmbH <info@top-logic.com> * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-BOS-TopLogic-1.0 */ package com.top_logic.basic.col.search; import static com.top_logic.basic.StringServices.*; import static com.top_logic.basic.col.factory.CollectionFactory.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Convenience class for search implementations. * <p> * Has convenience methods for checking the search result size. * </p> * <p> * Use {@link #addCandidate(Object)} to get the list of all candidates in error messages. The * candidates can have a different type than the results. Example: Objects are searched by labels. * In this case, adding the labels as candidates can lead to a better error message than adding the * objects themselves. * </p> * * @author <a href=mailto:jst@top-logic.com>Jan Stolzenburg</a> */ public class SearchResult<T> { private static final String ERROR_MESSAGE_LIST_ENTRY_SEPARATOR = ", "; private List<T> _results = Collections.emptyList(); private Collection<Object> _candidates = list(); /** * Adds the given result. * * @param entry * Is allowed to be <code>null</code>. */ public void add(T entry) { if (_results.isEmpty()) { // Many searches return exactly one result, // therefore this implementation is (memory) optimized for that case. _results = Collections.singletonList(entry); return; } if (_results.size() == 1) { ArrayList<T> multiResultList = new ArrayList<>(4); multiResultList.add(_results.get(0)); _results = multiResultList; } _results.add(entry); } /** Calls {@link #add(Object)} if the condition is <code>true</code>. */ public void addIf(boolean condition, T entry) { if (condition) { add(entry); } } /** * Candidates are used for error messages: * <p> * If the object is not found, all the candidates are written into the error message. * </p> */ public void addCandidate(Object candidate) { _candidates.add(candidate); } /** * Returns the {@link List} of search results. * <p> * The internal list is returned, which <b>might be unmodifiable, but might also change</b> if * further search results are added via {@link #add(Object)}. * </p> * * @return Never <code>null</code>, but might contain <code>null</code>, if {@link #add(Object)} * is called with <code>null</code> as parameter. */ public List<T> getResults() { return _results; } /** * Convenience short-cut for {@link #getResult(Object, String)} with <code>null</code> as * default value. */ public T getResultNullable(String errorPrefix) { return getResult(null, errorPrefix); } /** * Convenience short-cut that calls {@link #checkAtMostOneResult(String)} before returning the * first result, or the default value, if there is no result. */ public T getResult(T defaultValue, String errorPrefix) { checkAtMostOneResult(errorPrefix); if (_results.isEmpty()) { return defaultValue; } return _results.get(0); } /** * Convenience short-cut that calls {@link #checkSingleResult(String)} before returning the * single result. */ public T getSingleResult(String errorPrefix) { checkSingleResult(errorPrefix); return _results.get(0); } /** Throws an {@link IllegalStateException} if at least one result has been found. */ public void checkEmpty(String errorPrefix) { if (!_results.isEmpty()) { fail(true, errorPrefix, " Expected to find nothing but found ", _results.size(), " results: "); } } /** Throws an {@link IllegalStateException} if no result has been found. */ public void checkNonEmpty(String errorPrefix) { if (_results.isEmpty()) { fail(false, errorPrefix, "Expected at least one result but found nothing."); } } /** Throws an {@link IllegalStateException} if no or multiple results have been found. */ public void checkSingleResult(String errorPrefix) { if (_results.isEmpty()) { fail(false, errorPrefix, " Expected to find exactly one result but found nothing."); } if (_results.size() > 1) { fail(true, errorPrefix, " Expected to find exactly one result but found ", _results.size(), " results: "); } } /** Throws an {@link IllegalStateException} if multiple results have been found. */ public void checkAtMostOneResult(String errorPrefix) { if (_results.size() > 1) { fail(true, errorPrefix, " Expected to find at most one result but found ", _results.size(), " results: "); } } private void fail(boolean appendResults, Object... messageParts) { StringBuilder errorMessage = new StringBuilder(); for (Object messagePart : messageParts) { errorMessage.append(messagePart); } if (appendResults) { appendResults(errorMessage); } errorMessage.append(" Candidates: '"); errorMessage.append(join(_candidates, "', '")); errorMessage.append("'"); throw new IllegalStateException(errorMessage.toString()); } private void appendResults(StringBuilder resultDetail) { for (T result : _results) { resultDetail.append(debug(result)); resultDetail.append(ERROR_MESSAGE_LIST_ENTRY_SEPARATOR); } if (!_results.isEmpty()) { resultDetail.delete( resultDetail.length() - ERROR_MESSAGE_LIST_ENTRY_SEPARATOR.length(), resultDetail.length()); } resultDetail.append("."); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Companies; use App\Models\Employees; use Illuminate\Support\Facades\Storage; class EmployeesController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $employees = Employees::with(['company'])->latest()->paginate(10); return view('employees/list', ['employees' => $employees]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('employees/create', ['companies' => Companies::all()]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validation = $request->validate([ 'first_name' => 'required', 'last_name' => 'required', ]); $employee = new Employees; $employee->first_name = $request->first_name; $employee->last_name = $request->last_name; $employee->company_id = $request->company_id; $employee->email = $request->email; $employee->phone = $request->phone; $employee->save(); return redirect()->route('employees')->with('message', 'Record created successfully!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $employee = Employees::where('id', $id)->first(); return view('employees/edit', ['employee' => $employee, 'companies' => Companies::all()]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request) { $validation = $request->validate([ 'first_name' => 'required', 'last_name' => 'required', ]); $employee = Employees::find($request->id); $employee->first_name = $request->first_name; $employee->last_name = $request->last_name; $employee->company_id = $request->company_id; $employee->email = $request->email; $employee->phone = $request->phone; $employee->save(); return redirect()->route('employees')->with('message', 'Record updated successfully!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $employee = Employees::find($id); $employee->delete(); return redirect()->route('employees')->with('message', 'Record deleted successfully!'); } }
<!doctype html> <!--[if lt IE 7]><html <?php language_attributes(); ?> class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]--> <!--[if (IE 7)&!(IEMobile)]><html <?php language_attributes(); ?> class="no-js lt-ie9 lt-ie8"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html <?php language_attributes(); ?> class="no-js lt-ie9"><![endif]--> <!--[if gt IE 8]><!--> <html <?php language_attributes(); ?> class="no-js"><!--<![endif]--> <head> <meta charset="utf-8"> <?php // force Internet Explorer to use the latest rendering engine available ?> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title><?php wp_title(''); ?></title> <?php // mobile meta (hooray!) ?> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1"/> <?php // icons & favicons (for more: http://www.jonathantneal.com/blog/understand-the-favicon/) ?> <link rel="apple-touch-icon" href="<?php echo get_template_directory_uri(); ?>/library/images/apple-touch-icon.png"> <link rel="icon" href="<?php echo get_template_directory_uri(); ?>/favicon.png"> <!--[if IE]> <link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/favicon.ico"> <![endif]--> <?php // or, set /favicon.ico for IE10 win ?> <meta name="msapplication-TileColor" content="#f01d4f"> <meta name="msapplication-TileImage" content="<?php echo get_template_directory_uri(); ?>/library/images/win8-tile-icon.png"> <meta name="theme-color" content="#121212"> <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>"> <?php // wordpress head functions ?> <?php wp_head(); ?> <?php // end of wordpress head ?> <?php // drop Google Analytics Here ?> <!-- Google tag (gtag.js) --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-12EKQM14SH"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-12EKQM14SH'); </script> <?php // end analytics ?> <script type="application/ld+json" id="jsonld"> { "@context": [ "https://schema.org/" ], "@type": [ "Service", "Organization", "ResearchProject" ], "@id": "https://arcticdata.io", "name": "Arctic Data Center", "legalName": "Arctic Data Center", "alternateName": "ADC", "logo": "https://arcticdata.io/wp-content/themes/aurora/library/images/logo_.png", "url": "https://arcticdata.io", "description": "The Arctic Data Center is the primary data and software repository for the Arctic section of NSF Polar Programs.", "identifier": [ { "@type": "PropertyValue", "name": "ROR:055hrh286", "propertyID": "https://registry.identifiers.org/registry/ror", "value": "ror:055hrh286", "url": "https://ror.org/055hrh286" }, { "@type": "PropertyValue", "name": "Re3data DOI: 10.17616/R37P98", "propertyID": "https://registry.identifiers.org/registry/doi", "value": "doi:10.17616/R37P98", "url": "https://doi.org/10.17616/R37P98" }, { "@type": "PropertyValue", "name": "wikidata:Q77285095", "propertyID": "https://registry.identifiers.org/registry/wikidata", "value": "wikidata:Q77285095", "url": "https://www.wikidata.org/wiki/Q77285095" }, { "@type": "PropertyValue", "name": "grid:grid.507882.0", "propertyID": "https://registry.identifiers.org/registry/grid", "value": "grid:grid.507882.0", "url": "https://www.grid.ac/institutes/grid.507882.0" } ], "sameAs": [ "https://ror.org/055hrh286", "https://www.grid.ac/institutes/grid.507882.0", "https://www.wikidata.org/wiki/Q77285095", "https://www.re3data.org/repository/r3d100011973", "http://doi.org/10.17616/R37P98", "urn:node:ARCTIC" ], "category": [ "Arctic Research" ], "provider": { "@id": "https://arcticdata.io" }, "contactPoint": { "@type": "ContactPoint", "name": "Support", "email": "support@arcticdata.io", "url": "https://arcticdata.io/support/", "contactType": "customer support" }, "foundingDate": "2016-02-01", "funder": { "@type": "Organization", "@id": "https://doi.org/10.13039/100000087", "legalName": "Office of Polar Programs", "alternateName": "OPP", "url": "https://www.nsf.gov/div/index.jsp?div=OPP", "identifier": { "@type": "PropertyValue", "propertyID": "https://registry.identifiers.org/registry/doi", "value": "doi:10.13039/100000087", "url": "https://doi.org/10.13039/100000087" }, "parentOrganization": { "@type": "Organization", "@id": "https://doi.org/10.13039/100000085", "legalName": "Directorate for Geosciences", "alternateName": "NSF-GEO", "url": "http://www.nsf.gov", "identifier": { "@type": "PropertyValue", "propertyID": "https://registry.identifiers.org/registry/doi", "value": "10.13039/100000085", "url": "https://doi.org/10.13039/100000085" }, "parentOrganization": { "@type": "Organization", "@id": "https://doi.org/10.13039/100000001", "legalName": "National Science Foundation", "alternateName": "NSF", "url": "http://www.nsf.gov", "identifier": { "@type": "PropertyValue", "propertyID": "https://registry.identifiers.org/registry/doi", "value": "10.13039/100000001", "url": "https://doi.org/10.13039/100000001" } } } }, "hasOfferCatalog": { "@type": "OfferCatalog", "name": "Arctic Data Center Data Catalog", "itemListElement": [ { "@type": "DataCatalog", "@id": "https://arcticdata.io/catalog/data", "name": "Arctic Data Center Catalog", "audience": { "@type": "Audience", "audienceType": "public", "name": "General Public" } } ] }, "address": { "@type": "PostalAddress", "streetAddress": "1021 Anacapa Street", "addressLocality": "Santa Barbara", "addressRegion": "CA", "postalCode": "93101", "addressCountry": "US" }, "parentOrganization": { "@type": "Organization", "@id": "https://ror.org/0146z4r19", "legalName": "National Center for Ecological Analysis and Synthesis", "alternateName": "NCEAS", "url": "http://nceas.ucsb.edu", "identifier": { "@type": "PropertyValue", "propertyID": "https://registry.identifiers.org/registry/ror", "value": "ror:0146z4r19", "url": "https://ror.org/0146z4r19" }, "parentOrganization": { "@type": "Organization", "@id": "https://ror.org/02t274463", "legalName": "University of California, Santa Barbara", "alternateName": "UCSB", "url": "http://ucsb.edu", "identifier": { "@type": "PropertyValue", "propertyID": "https://registry.identifiers.org/registry/ror", "value": "ror:02t274463", "url": "https://ror.org/02t274463" } } }, "inLanguage": "en-US", "addressCountry": "US", "license": [ "http://spdx.org/licenses/CC0-1.0", "https://spdx.org/licenses/CC-BY-4.0" ], "credentialCategory": "CoreTrustSeal", "termsOfService": [ "http://spdx.org/licenses/CC0-1.0", "https://spdx.org/licenses/CC-BY-4.0" ], "ex:persistentIdentifiers": [ "https://registry.identifiers.org/registry/doi", "https://registry.identifiers.org/registry/orcid", "https://registry.identifiers.org/registry/ror", "https://registry.identifiers.org/registry/rrid", "https://registry.identifiers.org/registry/d1id", "https://registry.identifiers.org/registry/ark" ], "ex:machineInteroperability": [ "DataONE", "OAI-PMH", "DataCite", "REST", "SPARQL" ], "ex:metadata": [ "EML", "ISO-19115", "DDI", "Dublin Core", "FGDC CSDGM", "METS", "DataCite", "OAI-ORE", "other" ], "ex:curation": "https://arcticdata.io/submit/", "ex:preservationPolicy": "https://arcticdata.io/preservation/", "ex:termsOfAccess": [ "http://spdx.org/licenses/CC0-1.0", "https://spdx.org/licenses/CC-BY-4.0" ] } </script> </head> <body <?php body_class(); ?> itemscope itemtype="http://schema.org/WebPage"> <div id="container"> <header class="header" role="banner" itemscope itemtype="http://schema.org/WPHeader"> <?php if ( is_active_sidebar( 'top_banner' ) ) : ?> <?php dynamic_sidebar( 'top_banner' ); ?> <?php endif; ?> <?php if ( is_active_sidebar( 'top_banner_warning' ) ) : ?> <?php dynamic_sidebar( 'top_banner_warning' ); ?> <?php endif; ?> <div class="border-image" role="img"></div> <div id="inner-header" class="wrap cf"> <a href="<?php echo home_url(); ?>" rel="nofollow" id="logo" class="h1 brand" itemscope itemtype="http://schema.org/Organization"> <img src="<?php bloginfo( 'template_url' ); ?>/library/images/logo_.png" alt="Arctic Data Center" title="Arctic Data Center"/> </a> <a id="nav-trigger"><i class="fa fa-bars icon"></i><i class="fa fa-close icon hidden"></i></a> <nav role="navigation" itemscope itemtype="http://schema.org/SiteNavigationElement" id="main-nav"> <?php wp_nav_menu(array( 'container' => false, // remove nav container 'container_class' => 'menu cf', // class of container (should you choose to use it) 'menu' => __( 'The Main Menu', 'auroratheme' ), // nav name 'menu_class' => 'nav top-nav cf', // adding custom nav class 'theme_location' => 'main-nav', // where it's located in the theme 'before' => '', // before the menu 'after' => '', // after the menu 'link_before' => '', // before each link 'link_after' => '', // after each link 'depth' => 0, // limit the depth of the nav 'fallback_cb' => '' // fallback function (if there is one) )); ?> </nav> </div> </header>
package io.flutter.plugins.googlemobileads; import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.ads.nativetemplates.TemplateView; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.admanager.AdManagerAdRequest; import com.google.android.gms.ads.nativead.NativeAd; import com.google.android.gms.ads.nativead.NativeAd.OnNativeAdLoadedListener; import com.google.android.gms.ads.nativead.NativeAdOptions; import com.google.android.gms.ads.nativead.NativeAdView; import com.google.errorprone.annotations.CanIgnoreReturnValue; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory; import io.flutter.plugins.googlemobileads.nativetemplates.FlutterNativeTemplateStyle; import java.util.Map; public class FlutterPreloadNativeAd extends FlutterAd { private static final String TAG = "FlutterPreloadNativeAd"; @NonNull private final AdInstanceManager manager; @NonNull private final String adUnitId; @Nullable private final NativeAdFactory adFactory; @NonNull private final FlutterAdLoader flutterAdLoader; @Nullable private FlutterAdRequest request; @Nullable private FlutterAdManagerAdRequest adManagerRequest; @Nullable private Map<String, Object> customOptions; @Nullable private NativeAdView nativeAdView; @Nullable private final FlutterNativeAdOptions nativeAdOptions; @Nullable private final FlutterNativeTemplateStyle nativeTemplateStyle; @Nullable private TemplateView templateView; @NonNull private final Context context; @Nullable private NativeAd nativeAd; static class Builder { @Nullable private AdInstanceManager manager; @Nullable private String adUnitId; @Nullable private NativeAdFactory adFactory; @Nullable private FlutterAdRequest request; @Nullable private FlutterAdManagerAdRequest adManagerRequest; @Nullable private Map<String, Object> customOptions; @Nullable private Integer id; @Nullable private FlutterNativeAdOptions nativeAdOptions; @Nullable private FlutterAdLoader flutterAdLoader; @Nullable private FlutterNativeTemplateStyle nativeTemplateStyle; @NonNull private final Context context; Builder(Context context) { this.context = context; } @CanIgnoreReturnValue public Builder setAdFactory(@NonNull NativeAdFactory adFactory) { this.adFactory = adFactory; return this; } @CanIgnoreReturnValue public Builder setId(int id) { this.id = id; return this; } @CanIgnoreReturnValue public Builder setCustomOptions( @Nullable Map<String, Object> customOptions ) { this.customOptions = customOptions; return this; } @CanIgnoreReturnValue public Builder setManager(@NonNull AdInstanceManager manager) { this.manager = manager; return this; } @CanIgnoreReturnValue public Builder setAdUnitId(@NonNull String adUnitId) { this.adUnitId = adUnitId; return this; } @CanIgnoreReturnValue public Builder setRequest(@NonNull FlutterAdRequest request) { this.request = request; return this; } @CanIgnoreReturnValue public Builder setAdManagerRequest( @NonNull FlutterAdManagerAdRequest request ) { this.adManagerRequest = request; return this; } @CanIgnoreReturnValue public Builder setNativeAdOptions( @Nullable FlutterNativeAdOptions nativeAdOptions ) { this.nativeAdOptions = nativeAdOptions; return this; } @CanIgnoreReturnValue public Builder setFlutterAdLoader( @NonNull FlutterAdLoader flutterAdLoader ) { this.flutterAdLoader = flutterAdLoader; return this; } @CanIgnoreReturnValue public Builder setNativeTemplateStyle( @Nullable FlutterNativeTemplateStyle nativeTemplateStyle ) { this.nativeTemplateStyle = nativeTemplateStyle; return this; } FlutterPreloadNativeAd build() { if (manager == null) { throw new IllegalStateException("AdInstanceManager cannot be null."); } else if (adUnitId == null) { throw new IllegalStateException("AdUnitId cannot be null."); } else if (request == null && adManagerRequest == null) { throw new IllegalStateException( "adRequest or addManagerRequest must be non-null." ); } final FlutterPreloadNativeAd nativeAd; if (request == null) { nativeAd = new FlutterPreloadNativeAd( context, id, manager, adUnitId, adFactory, adManagerRequest, flutterAdLoader, customOptions, nativeAdOptions, nativeTemplateStyle ); } else { nativeAd = new FlutterPreloadNativeAd( context, id, manager, adUnitId, adFactory, request, flutterAdLoader, customOptions, nativeAdOptions, nativeTemplateStyle ); } return nativeAd; } } protected FlutterPreloadNativeAd( @NonNull Context context, int adId, @NonNull AdInstanceManager manager, @NonNull String adUnitId, @Nullable NativeAdFactory adFactory, @NonNull FlutterAdRequest request, @NonNull FlutterAdLoader flutterAdLoader, @Nullable Map<String, Object> customOptions, @Nullable FlutterNativeAdOptions nativeAdOptions, @Nullable FlutterNativeTemplateStyle nativeTemplateStyle ) { super(adId); this.context = context; this.manager = manager; this.adUnitId = adUnitId; this.adFactory = adFactory; this.request = request; this.flutterAdLoader = flutterAdLoader; this.customOptions = customOptions; this.nativeAdOptions = nativeAdOptions; this.nativeTemplateStyle = nativeTemplateStyle; } protected FlutterPreloadNativeAd( @NonNull Context context, int adId, @NonNull AdInstanceManager manager, @NonNull String adUnitId, @Nullable NativeAdFactory adFactory, @NonNull FlutterAdManagerAdRequest adManagerRequest, @NonNull FlutterAdLoader flutterAdLoader, @Nullable Map<String, Object> customOptions, @Nullable FlutterNativeAdOptions nativeAdOptions, @Nullable FlutterNativeTemplateStyle nativeTemplateStyle ) { super(adId); this.context = context; this.manager = manager; this.adUnitId = adUnitId; this.adFactory = adFactory; this.adManagerRequest = adManagerRequest; this.flutterAdLoader = flutterAdLoader; this.customOptions = customOptions; this.nativeAdOptions = nativeAdOptions; this.nativeTemplateStyle = nativeTemplateStyle; } @Override void load() { final OnNativeAdLoadedListener loadedListener = new FlutterPreloadNativeAdLoadedListener( this ); final AdListener adListener = new FlutterNativeAdListener(adId, manager); // Note we delegate loading the ad to FlutterAdLoader mainly for testing purposes. // As of 20.0.0 of GMA, mockito is unable to mock AdLoader. final NativeAdOptions options = this.nativeAdOptions == null ? new NativeAdOptions.Builder().build() : nativeAdOptions.asNativeAdOptions(); if (request != null) { flutterAdLoader.loadNativeAd( adUnitId, loadedListener, options, adListener, request.asAdRequest(adUnitId) ); } else if (adManagerRequest != null) { AdManagerAdRequest adManagerAdRequest = adManagerRequest.asAdManagerAdRequest( adUnitId ); flutterAdLoader.loadAdManagerNativeAd( adUnitId, loadedListener, options, adListener, adManagerAdRequest ); } else { Log.e(TAG, "A null or invalid ad request was provided."); } } @Override @Nullable public PlatformView getPlatformView() { if (nativeAdView != null) { return new FlutterPlatformView(nativeAdView); } else if (templateView != null) { return new FlutterPlatformView(templateView); } return null; } void setPlatformView( @Nullable NativeAdFactory adFactory, @Nullable FlutterNativeTemplateStyle nativeTemplateStyle ) { if (adFactory == null && nativeTemplateStyle == null) { throw new IllegalStateException( "NativeAdFactory and nativeTemplateStyle cannot be null." ); } if (nativeTemplateStyle != null) { templateView = nativeTemplateStyle.asTemplateView(context); templateView.setNativeAd(nativeAd); } else { nativeAdView = adFactory.createNativeAd(nativeAd, customOptions); } } void onNativeAdLoaded(@NonNull NativeAd nativeAd) { this.nativeAd = nativeAd; nativeAd.setOnPaidEventListener( new FlutterPaidEventListener(manager, this) ); manager.onAdLoaded(adId, nativeAd.getResponseInfo()); } @Override void dispose() { if (nativeAdView != null) { nativeAdView.destroy(); nativeAdView = null; } if (templateView != null) { templateView.destroyNativeAd(); templateView = null; } } }
# Table of contents * [Overview](README.md) ## Basics * [Architecture](basics/introduction.md) ## Key Concepts * [EVM Ledger](key-concepts/evm-smart-chain.md) * [UTXO Chain](key-concepts/utxo-native-chain/README.md) * [Confidential transfers](key-concepts/utxo-native-chain/confidential-transfers/README.md) * [Overview](key-concepts/utxo-native-chain/confidential-transfers/overview.md) * [Concepts](key-concepts/utxo-native-chain/confidential-transfers/concepts.md) * [Technical Specifications](key-concepts/utxo-native-chain/confidential-transfers/technical-specifications.md) * [Prism++ Transfer](key-concepts/prism-transfer.md) * [Triple Masking](key-concepts/triple-masking/README.md) * [Overview](key-concepts/triple-masking/overview.md) * [SDK Installation](key-concepts/triple-masking/sdk-installation.md) * [Bar to Abar](key-concepts/triple-masking/bar-to-abar.md) * [Abar to Bar](key-concepts/triple-masking/abar-to-bar.md) * [Abar Transfer](key-concepts/triple-masking/abar-transfer.md) * [Staking](key-concepts/staking/README.md) * [Overview](key-concepts/staking/overview.md) * [EVM Staking](key-concepts/staking/evm-staking/README.md) * [UTXO Staking and EVM Staking](key-concepts/staking/evm-staking/utxo-staking-and-evm-staking.md) * [EVM Staking Portal User Guide](key-concepts/staking/evm-staking/evm-staking-portal-user-guide.md) * [Consensus](key-concepts/staking/consensus.md) * [Rewards](key-concepts/staking/rewards.md) * [Penalties](key-concepts/staking/penalties.md) ## Developers * [Acquire Testnet FRA](developers/request-fra-testnet.md) * [EVM Tools & Tutorials](developers/evm-tools-and-tutorials/README.md) * [Contract Deployment](developers/evm-tools-and-tutorials/contract-deployment/README.md) * [Ganache](developers/evm-tools-and-tutorials/contract-deployment/ganache.md) * [Hardhat](developers/evm-tools-and-tutorials/contract-deployment/hardhat.md) * [Remix](developers/evm-tools-and-tutorials/contract-deployment/remix.md) * [Truffle](developers/evm-tools-and-tutorials/contract-deployment/truffle.md) * [Waffle](developers/evm-tools-and-tutorials/contract-deployment/waffle.md) * [The Graph](developers/evm-tools-and-tutorials/the-graph/README.md) * [Band Protocol](developers/evm-tools-and-tutorials/band-protocol.md) * [Mint NFTs](developers/evm-tools-and-tutorials/mint-nfts/README.md) * [Deploy NFT Contract (1 of 3)](developers/evm-tools-and-tutorials/mint-nfts/deploy-nft-contract-1-of-3.md) * [Mint NFT (2 of 3)](developers/evm-tools-and-tutorials/mint-nfts/mint-nft-2-of-3.md) * [View NFT (3 of 3)](developers/evm-tools-and-tutorials/mint-nfts/view-nft-3-of-3.md) * [Developer SDKs](developers/developer-sdks/README.md) * [UTXO Native Chain SDK](developers/developer-sdks/utxo-native-chain-sdk/README.md) * [UTXO Native Chain SDK Installation](developers/developer-sdks/utxo-native-chain-sdk/utxo-native-chain-sdk-installation.md) * [Developer Tools](developers/developer-sdks/utxo-native-chain-sdk/developer-tools/README.md) * [Findora CLI Tool](developers/developer-sdks/utxo-native-chain-sdk/developer-tools/findora-cli-tool.md) * [UTXO API Reference](developers/developer-sdks/utxo-native-chain-sdk/utxo-api-reference/README.md) * [Account](developers/developer-sdks/utxo-native-chain-sdk/utxo-api-reference/account.md) * [Keypair](developers/developer-sdks/utxo-native-chain-sdk/utxo-api-reference/keypair.md) * [Network](developers/developer-sdks/utxo-native-chain-sdk/utxo-api-reference/network.md) * [Asset](developers/developer-sdks/utxo-native-chain-sdk/utxo-api-reference/asset.md) * [Staking](developers/developer-sdks/utxo-native-chain-sdk/utxo-api-reference/staking.md) * [Transaction](developers/developer-sdks/utxo-native-chain-sdk/utxo-api-reference/transaction.md) * [Helpers](developers/developer-sdks/utxo-native-chain-sdk/utxo-api-reference/helpers.md) * [ZkRouting SDK](developers/developer-sdks/privacy-routing-sdk.md) * [zkDID SDK](developers/developer-sdks/zkdid-sdk/README.md) * [zkDID SDK Installation](developers/developer-sdks/zkdid-sdk/zkdid-sdk-installation.md) * [zkDID API Reference](developers/developer-sdks/zkdid-sdk/zkdid-api-reference.md) * [zkDID Example Code](developers/developer-sdks/zkdid-sdk/zkdid-example-code.md) * [Prism++ SDK](developers/developer-sdks/prism++-sdk.md) * [EVM References](developers/evm-references/README.md) * [Metamask](developers/evm-references/metamask.md) * [Local Development Network Setup](developers/evm-references/local-development-network-setup.md) * [EVM API Reference](developers/evm-references/evm-api-reference.md) * [Precompiled Contracts](developers/evm-references/precompiled-contracts.md) * [Resources](developers/resources/README.md) * [Bug Bounties](developers/resources/bug-bounties.md) * [Events](developers/resources/events/README.md) * [🏗 ETH San Francisco 2022](developers/resources/events/eth-san-francisco-2022.md) * [zkDID and Credentials](key-concepts/zkdid-and-credentials.md) * [🏗 ETH Denver 2023](developers/resources/events/eth-denver-2023.md) * [Game-Specific Chains](developers/game-specific-chains/README.md) * [GSC Highlights](developers/game-specific-chains/gsc-highlights.md) * [User Guide](developers/game-specific-chains/user-guide.md) * [Developer Tools](developers/game-specific-chains/developer-tools.md) ## Network Settings * [Contract Addresses](network-contract-settings/contract-addresses.md) * [Network Settings](network-settings/network-settings.md) ## General User Materials * [Acquire FRA](general-user-materials/acquire-fra.md) * [Acquire FRA (Testnet)](general-user-materials/request-fra-testnet.md) * [Stake FRA](general-user-materials/stake-fra.md) * [Use Wallets](general-user-materials/use-wallets/README.md) * [MetaMask](general-user-materials/use-wallets/metamask/README.md) * [Download](general-user-materials/use-wallets/metamask/download.md) * [Configure (Auto)](general-user-materials/use-wallets/metamask/configure-auto.md) * [Configure (Manual)](general-user-materials/use-wallets/metamask/configure-manual.md) * [Findora Wallet](general-user-materials/use-wallets/findora-wallet/README.md) * [Download](general-user-materials/use-wallets/findora-wallet/download.md) * [New Wallet](general-user-materials/use-wallets/findora-wallet/new-wallet.md) * [Transfer](general-user-materials/use-wallets/findora-wallet/transfer.md) * [Prism++](general-user-materials/use-wallets/findora-wallet/prism.md) * [Adding Assets to the Findora Wallet](general-user-materials/use-wallets/findora-wallet/adding-assets-to-the-findora-wallet.md) * [Manage Assets](general-user-materials/use-wallets/findora-wallet/manage-assets.md) * [Ledger Hardware Wallet](general-user-materials/use-wallets/ledger-hardware-wallet.md) * [Bridging Tokens to Findora](general-user-materials/bridge-tokens-to-findora.md) * [Use Block Explorers](general-user-materials/use-block-explorers.md) * [Explore Testnet](general-user-materials/testnet/README.md) * [Triple Masking](general-user-materials/testnet/triple-masking/README.md) * [Triple Masking Demo](general-user-materials/testnet/triple-masking/triple-masking-demo.md) * [EVM Staking](general-user-materials/testnet/evm-staking.md) * [Prism++](general-user-materials/testnet/prism-++/README.md) * [Prism++ Testing Campaign](general-user-materials/testnet/prism-++/prism++-testing-campaign/README.md) * [💰 Testnet Wallet Setup/Funding](general-user-materials/testnet/prism-++/prism++-testing-campaign/testnet-wallet-setup-funding.md) * [👨🌾 👨🌾 Peasant: Prism++ Campaign Signup](general-user-materials/testnet/prism-++/prism++-testing-campaign/peasant-prism++-campaign-signup.md) * [🧒 Pupil: FRC20 Token Transfers](general-user-materials/testnet/prism-++/prism++-testing-campaign/frc20-token-transfers.md) * [🧑🎨 🧑🎨 Pilgrim: FRC 721 Token Transfers](general-user-materials/testnet/prism-++/prism++-testing-campaign/pilgrim-frc-721-token-transfers.md) * [🧑🎓 🧑🎓 Prodigy: FRC1155 Token Transfers](general-user-materials/testnet/prism-++/prism++-testing-campaign/prodigy-frc1155-token-transfers.md) * [🧑🚀 🧑🚀 Pioneer: Mainnet Transfers](general-user-materials/testnet/prism-++/prism++-testing-campaign/pioneer-mainnet-transfers.md) * [Prism++ Testnet Campaign FAQs](general-user-materials/explore-testnet/prism++/prism++-testing-campaign/prism++-testnet-campaign-faqs.md) * [Gaxle Events](general-user-materials/gaxle-events/README.md) * [Game Chain Challenges](general-user-materials/gaxle-events/game-chain-challenges/README.md) * [Getting Started](general-user-materials/gaxle-events/game-chain-challenges/getting-started.md) * [The Campaigns](general-user-materials/gaxle-events/game-chain-challenges/the-campaigns.md) * [The Reward Raffles](general-user-materials/gaxle-events/game-chain-challenges/the-reward-raffles.md) ## Validator Materials * [Findora's University Program](validator-materials/findoras-university-program.md) * [Validator Setup Guides](validator-materials/node-setup-guides/README.md) * [System Requirements](validator-materials/node-setup-guides/system-requirements.md) * [Acquire a Server](validator-materials/node-setup-guides/acquire-a-server.md) * [Validator Toolbox Setup](validator-materials/node-setup-guides/validator-toolbox-setup/README.md) * [New Build](validator-materials/node-setup-guides/validator-toolbox-setup/new-build.md) * [Existing Build](validator-materials/node-setup-guides/validator-toolbox-setup/existing-build.md) * [Additional Info](validator-materials/node-setup-guides/validator-toolbox-setup/additional-info.md) * [Manual Setup](validator-materials/node-setup-guides/manual-setup.md) * [Automated Setup (Deprecated)](validator-materials/node-setup-guides/automated-setup.md) * [Upgrade Guides](validator-materials/upgrade-guides/README.md) * [Node Upgrade (Toolbox)](validator-materials/upgrade-guides/node-upgrades.md) * [Node Upgrade (Manual)](validator-materials/upgrade-guides/node-upgrades-1.md) * [fn CLI Upgrade (Wallet)](validator-materials/operational-guides/fn-cli-upgrade-wallet.md) * [Operational Guides](validator-materials/operational-guides/README.md) * [Emergency Recovery](validator-materials/operational-guides/emergency-recovery.md) * [Data Backup](validator-materials/operational-guides/data-backup.md) * [CLI Staking](validator-materials/operational-guides/cli-staking.md)
/* RMIT University Vietnam Course: EEET2482/COSC2082 Semester: 2023-2 Lab Assessment: 2 Author: Huynh Bao Cuong ID: 3978719 Compiler used: 8.1.0 Created date: (e.g. 09/09/2023) Acknowledgement: List the resources that you use to complete this assessment (write 'None' if you don't use any). */ #include <iostream> #include <vector> #include <iomanip> #define START 0 class Fruits{ private: std::string name; double price; public: Fruits(std::string name = "", double price = 0) : name(name), price(price){}; std::string returnName(){ return name; } int returnPrice(){ return price; } friend class Shop; friend class Bill; }; class Shop { private: std::string shopName; std::vector<Fruits> ShopListFruits; public: Shop(std::string nameInput = "", std::vector<Fruits> ShopListFruits = {}) : shopName(nameInput) , ShopListFruits(ShopListFruits){}; void addFruits(Fruits FruitsExample){ ShopListFruits.push_back(FruitsExample); } void showList(){ for(int i = 0; i < ShopListFruits.size(); i++){ std::cout << ShopListFruits[i].name << ", $" << std::fixed << std::setprecision(2) << ShopListFruits[i].price << std::endl; } } int findFruitPositionInShopList(std::string userInput){ int position = 0; for(int i = 0; i < ShopListFruits.size(); i++){ if(userInput.compare(ShopListFruits[i].name) == 0){ position == i; break; } } return position; } Fruits ReturnFruits(int position){ return ShopListFruits[position]; } std::string getName(){ return shopName; } }; class Bill{ private: int billID; Fruits fruitBought; int quantity; public: Bill(){}; Bill(int billIDInput, Fruits fruits){ this->billID = billIDInput; this->fruitBought = fruits; } void setQuantity(int num){ this->quantity = num; } int returnQuantity(){ return quantity; } int returnBillID(){ return billID; } Fruits returnFruitsBought(){ return fruitBought; } }; int main(int argc, char* argv[]){ Fruits* allFruitsList = new Fruits[3]; std::vector<Bill> theBill; allFruitsList[0] = {"Banana", 1.80}; allFruitsList[1] = {"Apple", 0.90}; allFruitsList[2] = {"Avocado", 3.00}; Shop shop1("Fruit Store 1", {}); shop1.addFruits(allFruitsList[0]); shop1.addFruits(allFruitsList[1]); shop1.addFruits(allFruitsList[2]); system("cls"); std::cout << "Welcome to " << shop1.getName() << "\n" << "\n"; std::cout << "List of all fruits available\n"; shop1.showList(); int startingpointID = 1; while(1){ std::string userInput; std::cout << "Enter item ('Q' to quit) :"; std::cin >> userInput; if(userInput == "Q"){ double totalAmountPrice = 0; int totalAmountofFruits = 0; for(int i = 0; i < theBill.size(); i++){ // std::cout << "Receipt ID: " << theBill[i].returnBillID() << std::endl; std::cout << "Bought fruits" << std::endl; std::cout << theBill[i].returnBillID() << ". Fruits: " << theBill[i].returnFruitsBought().returnName() << std::endl; std::cout << "Quantity: " << theBill[i].returnQuantity() << std::endl; totalAmountPrice += theBill[i].returnFruitsBought().returnPrice() * theBill[i].returnQuantity(); totalAmountofFruits += theBill[i].returnQuantity(); } std::cout << "Total number of item : " << totalAmountofFruits << std::endl; std::cout << "Total amount to be paid: $" << std::fixed << std::setprecision(2) << totalAmountPrice << std::endl; break; } else{ int position = shop1.findFruitPositionInShopList(userInput); Fruits temp = shop1.ReturnFruits(position); Bill tempBill = {startingpointID, temp}; startingpointID++; std::cout << "Enter quantity: "; int userquantityInput; std::cin.ignore(1,'\n'); std::cin >> userquantityInput; tempBill.setQuantity(userquantityInput); theBill.push_back(tempBill); std::cout << std::endl; userInput.clear(); } } }
import { NgModule, Optional, SkipSelf, ErrorHandler } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { NgxMaterialModule } from '../lib/modules/ngx-material/ngx-material.module'; import { NgxTranslocoModule } from '../lib/modules/ngx-transloco/ngx-transloco.module'; import { throwIfAlreadyLoaded } from '@core/module-import-guard'; import { ErrorHandlerService } from '@core/services/error-handler.service'; import { ErrorHandlerInterceptor } from '@core/interceptors/error-handler.interceptor'; @NgModule({ imports: [ BrowserAnimationsModule, HttpClientModule, NgxMaterialModule ], providers: [ { provide: ErrorHandler, useClass: ErrorHandlerService }, { provide: HTTP_INTERCEPTORS, useClass: ErrorHandlerInterceptor, multi: true } ], exports: [ BrowserModule, NgxTranslocoModule ] }) export class CoreModule { public constructor(@Optional() @SkipSelf() parentModule: CoreModule) { throwIfAlreadyLoaded(parentModule, 'CoreModule'); } }
// Homework 2 // Implement Dijkstra algorithm to compute single-source shortest paths. #include "dijkstra.h" #include <assert.h> #include <iostream> #include <unordered_set> using namespace std; // PriorityQueue // Change priority of the given vertex within the priority queue. For // the purpose of Dijkstra algorithm, only the reduction of priority is // supported. void PriorityQueue::change_priority(int vertex, double priority) { assert(contains(vertex)); int position = vertex_map_[vertex]; QueueElement& this_element = priority_queue_[position]; assert(this_element.get_priority() > priority); // Change priority and percolate upward. this_element.set_priority(priority); percolate_up(position); } // Insert the vertex and priority into the priority queue. Check if the // given vertex already exists in the queue and if its existing priority // needs to be updated. void PriorityQueue::insert(int vertex, double priority) { if(contains(vertex)) { int position = vertex_map_[vertex]; QueueElement& this_element = priority_queue_[position]; // Check if the priority for this vertex needs to be updated. if(this_element.get_priority() > priority) change_priority(vertex, priority); return; } // Push this new vertex onto the priority queue. push(vertex, priority); } // For a given position, return the position of the child with // the minimum priority. int PriorityQueue::min_child(int position) { int left_child_position = left_child(position); assert(valid_position(left_child_position)); int right_child_position = right_child(position); // There is no right child, return the left one. if(!valid_position(right_child_position)) return left_child_position; // Compare priorities and return the position for the min. child. QueueElement left_element = priority_queue_[left_child_position]; QueueElement right_element = priority_queue_[right_child_position]; if(left_element.get_priority() < right_element.get_priority()) return left_child_position; return right_child_position; } // Recursively move the queue element downward to its rightful // position. void PriorityQueue::percolate_down(int position) { assert(valid_position(position)); QueueElement this_element = priority_queue_[position]; int min_child_position; // Base case. Stop if there is no children. if(!valid_position(left_child(position))) return; min_child_position = min_child(position); QueueElement min_child_element = priority_queue_[min_child_position]; // Check if this element is in its rightful position. if(this_element.get_priority() < min_child_element.get_priority()) return; // Swap positions and continue percolation. swap(position, min_child_position); percolate_down(min_child_position); } // Recursively move the queue element upward to its rightful // position. void PriorityQueue::percolate_up(int position) { assert(valid_position(position)); QueueElement this_element = priority_queue_[position]; int parent_position; // Base case. if(position == 0) return; // Get parent of this element. parent_position = parent(position); QueueElement parent_element = priority_queue_[parent_position]; // Check if this element is in its rightful position. if(parent_element.get_priority() <= this_element.get_priority()) return; // Swap positions and continue percolation. swap(parent_position, position); percolate_up(parent_position); } // Push the vertex and priority into the priority queue. void PriorityQueue::push(int vertex, double priority) { assert(!contains(vertex)); int position; // Insert the vertex to the tail of priority queue first. position = priority_queue_.size(); priority_queue_.push_back(QueueElement(vertex, priority)); // Update the queue position and percolate upward. vertex_map_.emplace(vertex, position); percolate_up(position); } // Pop and return the queue element at the top of the priority queue. QueueElement PriorityQueue::top() { assert(!priority_queue_.empty()); QueueElement top_element = priority_queue_[0]; // Remove the vertex from the vertex_map. vertex_map_.erase(top_element.get_vertex()); QueueElement last_element = priority_queue_.back(); priority_queue_.pop_back(); // Just return if there is no element in the queue. if(size() == 0) return top_element; // Move the last element in the queue to the top and percolate // downward. priority_queue_[0] = last_element; vertex_map_[last_element.get_vertex()] = 0; percolate_down(0); return top_element; } // Swap queue elements for the given pair of queue positions. void PriorityQueue::swap(int position1, int position2) { QueueElement e1 = priority_queue_[position1]; QueueElement e2 = priority_queue_[position2]; priority_queue_[position1] = e2; vertex_map_[e2.get_vertex()] = position1; priority_queue_[position2] = e1; vertex_map_[e1.get_vertex()] = position2; } // ======= // Graph // ======= // Add an edge to the graph. Edge from a vertex to itself is not supported. void Graph::add_edge(int vertex1, int vertex2, double distance) { int temp; unordered_map<int, double>& neighbor_info1 = vertex_edge_map_[vertex1]; unordered_map<int, double>& neighbor_info2 = vertex_edge_map_[vertex2]; // Don't add an edge from a vertex to itself. if(vertex1 == vertex2) return; neighbor_info1.emplace(vertex2, distance); neighbor_info2.emplace(vertex1, distance); } // ========== // Dijkstra // ========== // Get the queue element with the next closest vertex and update the // closest set and shortest path vector. QueueElement Dijkstra::get_closest_element(unordered_set<int>& closest_set, unordered_map<int, double>& spaths) { QueueElement element = priority_queue_.top(); int vertex = element.get_vertex(); // Some implementation may choose to push vertex with reduced priority onto // the priority queue even though it is already in the queue. The use of // .emplace() in the following code should handle this without changing the // shortest-path distances. closest_set.emplace(vertex); spaths.emplace(vertex, element.get_priority()); return element; } // Explore all edges from the given vertex. void Dijkstra::explore_edges_from(int vertex, double distance, const unordered_set<int>& closest_set) { int neighbor; double priority; for(auto& info: graph_.get_neighbor_info(vertex)) { neighbor = info.first; // Skip this neighbor if it is already a closest one. if(closest_set.count(neighbor)) continue; priority = distance + info.second; // The algorithm requires us to compare this priority/distance with any // existing one. This will require some table for look-up. Since the // priority queue already has such info, we let it handle this on our // behalf. priority_queue_.insert(neighbor, priority); } } // Compute shortest paths from the given source. unordered_map<int, double> Dijkstra::shortest_paths(int source) { unordered_set<int> closest_set = {}; // Contains closest vertices. unordered_map<int, double> spaths = {}; // Map of shortest paths. // Initialize the priority queue. priority_queue_.insert(source, 0); while(priority_queue_.size()) { QueueElement element = get_closest_element(closest_set, spaths); explore_edges_from(element.get_vertex(), element.get_priority(), closest_set); } return spaths; }
<?php namespace App\Controllers; use App\Models\ModelLogin; class Home extends BaseController { public function __construct() { $this->ModelLogin = new ModelLogin(); } public function index(): string { $data = [ 'judul' => 'Login' ]; return view('v_login', $data); } public function CekLogin() { //validasi input if ($this->validate([ 'username' => [ 'label' => 'Username', 'rules' => 'required', 'errors' => [ 'required' => 'Username harus diisi!' ] ], 'password' => [ 'label' => 'Password', 'rules' => 'required', 'errors' => [ 'required' => 'Password Kosong' ] ] ])) { $username = $this->request->getPost('username'); $password = $this->request->getPost('password'); $cek_login = $this->ModelLogin->LoginUser($username, $password); if ($cek_login) { session()->set('id_user', $cek_login['id_user']); session()->set('nama_kandidat', $cek_login['namakandidat']); session()->set('jabatan', $cek_login['jabatan']); return redirect()->to(base_url('Admin')); } else { session()->setFlashdata('gagal', 'Username Atau Password Salah!'); return redirect()->to(base_url('Home')); } } else { session()->setFlashdata('errors', \Config\Services::validation()->getErrors()); return redirect()->to('Home')->withInput('validation', \Config\Services::validation()->getErrors()); } } public function Logout() { session()->remove('id_user'); session()->remove('nama_kandidat'); session()->remove('jabatan'); session()->setFlashdata('pesan', 'Anda Berhasil Logout'); return redirect()->to(base_url('Home')); } }
import React from 'react'; import PropTypes from 'prop-types'; import '../mixins/typography.scss'; class ColorCycler extends React.PureComponent { static propTypes = { className: PropTypes.string, fullText: PropTypes.string, choices: PropTypes.arrayOf(PropTypes.string), interval: PropTypes.number, delay: PropTypes.number, isActive: PropTypes.bool, }; static defaultProps = { className: '', fullText: '', choices: [], interval: 2000, delay: 0, isActive: false, }; state = { isActive: this.props.isActive, index: 0, }; componentDidMount() { if (this.state.isActive) { this.onColorCycle(); } } componentWillReceiveProps(nextProps) { if (nextProps.isActive !== this.props.isActive) { this.setState({ isActive: nextProps.isActive }); } } componentWillUnmount() { clearInterval(this.timer); } onColorCycle = () => { const { choices, interval, delay } = this.props; setTimeout(() => { this.timer = setInterval(() => { const { index } = this.state; const nextIndex = (index + 1) % choices.length; this.setState({ index: nextIndex }); }, interval); }, delay); }; render() { const { className, fullText, choices } = this.props; const { index } = this.state; return ( <p styleName={`text-${choices[index]}`} className={className}> <span dangerouslySetInnerHTML={{ __html: fullText }} /> </p> ); } } export default ColorCycler;
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; import "forge-std/Test.sol"; import "../src/AppAccount.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; contract SignerTest is Test { AppAccount public account; address constant ENTRY_POINT_ADDRESSS = address(0); address executor; uint256 constant pk = 1; address alice; GHO token; uint72 lateDate; function setUp() public { alice = vm.addr(pk); account = new AppAccount( IEntryPoint(ENTRY_POINT_ADDRESSS), executor, alice ); token = new GHO(1e18); lateDate = uint72(block.timestamp + 1 days); } function testSignArbitraryData() public { bytes32 hash = keccak256("Signed by Alice"); (uint8 v, bytes32 r, bytes32 s) = vm.sign(pk, hash); address signer = ECDSA.recover(hash, v, r, s); assertEq(alice, signer); // [PASS] } function testSignatureWithApproval() public { AppSpenderSigner.ApproveArgs memory args = AppSpenderSigner.ApproveArgs(1e18, token, 0, 0); bytes32 hash = account.getApproveHash(args); (uint8 v, bytes32 r, bytes32 s) = vm.sign(pk, hash); address signer = ECDSA.recover(hash, v, r, s); assertEq(alice, signer); // [PASS] } function testSignApprovalBySignature() public { AppSpenderSigner.ApproveArgs memory args = AppSpenderSigner.ApproveArgs(1e18, token, 0, 0); bytes32 hash = account.getApproveHash(args); (uint8 v, bytes32 r, bytes32 s) = vm.sign(pk, hash); address signer = ECDSA.recover(hash, v, r, s); console.log("signer: %s", signer); console.log("alice: %s", alice); assertEq(alice, signer); // [PASS] account.approveBySignature(args, v, r, s); AppSpenderSigner.Allowance memory allowanceApproved = account.getAllowanceById(0); assertEq(allowanceApproved.amount, args.amount); assertEq(allowanceApproved.resetTimeMin, args.resetTimeMin); assertEq(address(allowanceApproved.token), address(args.token)); assertEq(allowanceApproved.nonce, account.allowanceNonce() - 1); assertEq(account.isSpendable(0), false); } }
<div class="login-section bg-mint-black"> <div style="padding-top: 15%"> <div class="card col-md-4 p-4 bg-mint-black text-light text-center"> <span class="h4 pb-4 text-center"> <img src="../../assets/img/mint.png" alt="" width="200px"> </span> <form #loginForm="ngForm" *ngIf="auditInProgress; else showNotification"> <div class="mb-2 small text-danger ">{{message}}</div> <div class="form-group"> <div class="input-group"> <!-- <span class="input-group-prepend"> <span class="input-group-text" ><i class="fa fa-fw fa-user"></i></span> </span>--> <input type="text" class="form-control" placeholder="Username" name="username" ngModel required onkeyup="this.value = this.value.toLowerCase();" autocomplete="off"> </div> </div> <div class="form-group"> <div class="input-group"> <!--<span class="input-group-prepend"> <span class="input-group-text" ><i class="fa fa-fw fa-lock"></i></span> </span>--> <input type="password" class="form-control" placeholder="Password" name="password" ngModel required autocomplete="off"> </div> </div> <div class="form-group text-center"> <button *ngIf="!loading" type="submit" class="btn bg-mint-red text-light" [disabled]="loginForm.invalid" (click)="login(loginForm.value)" style="cursor: pointer;"> I'm ready! Sign In :) </button> <div *ngIf="loading"> <span class="fa fa-fw fa-spin fa-circle-o-notch text-danger fa-lg"></span> </div> </div> <div class="small mt-4" (click)="open()" style="cursor: pointer;">Forgot Your Password?</div> </form> <ng-template #showNotification> <div class="row"> <span class="h3">Miracle's Quarterly Audit is currently not in session.</span> <span class="mt-2">If you would like to use the MINT App, please head over to Apple App Store or Google Play Store to get the application.</span> </div> <div class="row mt-4"> <div class="col-md-6 btn"> <a href="https://itunes.apple.com/us/app/miracles-inventory-tracker/id1354459188?mt=8"><img src="../../assets/icons/app-store.png" alt="Apple App Store" style="width: 7em !important; height: 2.5em !important;"></a> </div> <div class="col-md-6 btn"> <a href="https://play.google.com/store/apps/details?id=com.mss.mint"><img src="../../assets/icons/play-store.png" alt="Google Play Store" style="width: 7em !important; height: 2.5em !important;"></a> </div> </div> </ng-template> </div> </div> </div>
import React from "react"; import { IField, RecordEditorValues } from "./types"; import { List, ListInput, Button, Icon } from "framework7-react"; import { useScreenSize } from "../../../hooks/useScreenSize"; import { getInputType, parseValueTypeOnInput, getInputParsedValue, } from "./helpers"; import SmartSelect from "../SmartSelect"; export const RenderField = ({ field, values, setValues, indexIdentifier, fieldRefs, loading, error, }: { field: IField; values: RecordEditorValues; setValues: (values: RecordEditorValues) => void; indexIdentifier: number; fieldRefs: { [key: string]: any }; loading: boolean; error?: string; }): JSX.Element => { const keyIdentifier = `record-editor-field-${field.key}-${indexIdentifier}`; const { size } = useScreenSize(); if (field.type === "custom" && field.customRenderer) { return ( <> {field.customRenderer({ field, ref: fieldRefs.current[field.key], value: getInputParsedValue(values, field), onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => { let value = parseValueTypeOnInput(e.target.value, field); if (field.onChange) field.onChange(value, values, setValues); else { setValues({ ...values, [field.key]: value }); } }, setValues, errorMessage: error, })} </> ); } if (field.type === "smartselect") { if (field.options) { return ( <SmartSelect title={field.label} options={field.options} listProps={{ style: { margin: 0 } }} inputRef={fieldRefs.current[field.key]} value={getInputParsedValue(values, field)} onChange={(value) => { if (field.onChange) field.onChange(value, values, setValues); else { setValues({ ...values, [field.key]: value }); } }} /> ); } } if (field.type === "textarea") { return ( <List inset style={{ margin: 0 }} key={keyIdentifier} className="record-editor-list-container" > <ListInput type="textarea" ref={fieldRefs.current[field.key]} label={field.label} outline inputId={field.key} // input={false} // disabled={field.readonly || loading} floatingLabel={ true || size === "small" || size === "xsmall" ? true : false } readonly={field.readonly || loading} value={getInputParsedValue(values, field)} onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => { let value = parseValueTypeOnInput(e.target.value, field); if (field.onChange) field.onChange(value, values, setValues); else { setValues({ ...values, [field.key]: value }); } }} errorMessage={error} errorMessageForce={error ? true : false} > {/* <textarea className={field.readonly ? "disabled" : ""} slot="input" ref={fieldRefs.current[field.key]} id={field.key} placeholder={field?.placeholder || ""} readOnly={field.readonly || loading} disabled={field.readonly || loading} onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => { let value = parseValueTypeOnInput(e.target.value, field); if (field.onChange) field.onChange(value, values, setValues); else { setValues({ ...values, [field.key]: value }); } }} value={getInputParsedValue(values, field)} /> */} </ListInput> </List> ); } return ( <List inset style={{ margin: 0 }} key={keyIdentifier} className="record-editor-list-container" > <ListInput label={field.label} outline inputId={field.key} input={false} // disabled={field.readonly || loading} floatingLabel={ true || size === "small" || size === "xsmall" ? true : false } readonly={field.readonly || loading} value={getInputParsedValue(values, field)} errorMessage={error} errorMessageForce={error ? true : false} > <input className={field.readonly ? "disabled" : ""} slot="input" ref={fieldRefs.current[field.key]} id={field.key} placeholder={field?.placeholder || ""} type={getInputType(field.type)} readOnly={field.readonly || loading} disabled={field.readonly || loading} onChange={(e: React.ChangeEvent<HTMLInputElement>) => { let value = parseValueTypeOnInput(e.target.value, field); if (field.onChange) field.onChange(value, values, setValues); else { setValues({ ...values, [field.key]: value }); } }} value={getInputParsedValue(values, field)} /> {field.rightButton && ( <Button fill slot="content-end" onClick={() => { field.rightButton?.onClick( values?.[field.key], values, setValues ); }} style={{ marginTop: "var(--f7-list-item-padding-vertical)", marginLeft: "0.5rem", // marginRight: // "calc(var(--f7-list-item-padding-horizontal) + var(--f7-safe-area-right) - var(--menu-list-offset))", }} disabled={ field.rightButton?.isDisabled ? field.rightButton?.isDisabled(values) : false } > <Icon material={field.rightButton.icon} /> </Button> )} </ListInput> </List> ); };
package com.power; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author : xuyunfeng * @date : 2019/8/21 9:03 */ @Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // 自行修改为自己的包路径 .apis(RequestHandlerSelectors.basePackage("com.power.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("工作流接口") .description("基于flowable的工作流部分接口") //服务条款网址 //.termsOfServiceUrl("") .version("1.0") //.contact(new Contact("hello", "url", "email")) .build(); } }
import { inject, injectable } from 'tsyringe' import { Either, right, left } from 'common/seedword/core/Either' import { AppError } from 'common/seedword/errors/AppError' import { InvalidParameterError } from 'common/errors/InvalidParameterError' import { ResourceNotFound } from 'common/errors/ResourceNotFoundError' import { IUserRepository } from '../domain/user/IUserRepository' import { Password } from '../domain/user/Password' import { ITokenProvider } from 'common/providers/token/ITokenProvider' type Input = { token: string password: string } type Output = Either<AppError, null> @injectable() export class ResetPasswordService { constructor( @inject('UserRepository') private readonly userRepository: IUserRepository, @inject('TokenProvider') private readonly tokenProvider: ITokenProvider ) {} async execute(input: Input): Promise<Output> { const password = Password.create(input.password, false) if (password.isLeft()) { return left(new InvalidParameterError([password.value])) } const result = this.tokenProvider.decodeResetToken(input.token) if (result.isLeft()) { return left(result.value) } const user = await this.userRepository.findById(result.value.subject) if (!user) { return left(new ResourceNotFound()) } user.resetPassword(password.value) await this.userRepository.updatePassword(user) return right(null) } }
import { Schema, model, Document, Types } from 'mongoose' import md5 from 'md5' import { IBroker } from '@models/Broker' export enum UserType { Broker = 1, Agent = 2, } export enum UserLoginType { email = 1, facebook = 2, google = 3, } export interface IUser extends Document { email: string name: string type: UserType login_type: UserLoginType password?: string phone?: string email_activated: boolean broker?: IBroker['_id'] validPassword: (password: string) => boolean } const UserSchema: Schema = new Schema<IUser>( { // Main fields email: { type: String, required: true }, name: { type: String, required: true }, type: { type: Number, enum: Object.values(UserType).filter( (value) => typeof value === 'number' ), required: true, }, // Login fields login_type: { type: Number, enum: Object.values(UserLoginType).filter( (value) => typeof value === 'number' ), required: true, }, password: { type: String }, // Other fields phone: { type: String }, email_activated: { type: Boolean, required: true, default: false }, broker: { type: Types.ObjectId, ref: 'Broker' }, }, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, collection: 'User', } ) // Middlewares UserSchema.pre('save', function (next) { if (this.isModified('password')) { this.password = md5(this.password) } next() }) // Methods UserSchema.methods.validPassword = function (password) { return this.password === md5(password) } // Indexes UserSchema.index({ email: 1 }) UserSchema.index({ email: 1, type: 1 }) UserSchema.index({ email: 1, login_type: 1 }, { unique: true }) export default model<IUser>('User', UserSchema)
import "./TableTennisWebComponent.css"; import "./scoreboardCounter.js" import React, { useEffect, useContext, useState, useRef } from 'react'; import { TechnologyContext } from "../../providers/TechnologyProvider"; import { useParams } from 'react-router-dom'; import axios from "axios"; import { ScoreBoard } from "./scoreboardCounter.js"; // * TableTennisWebComponent component export default function TableTennisWebComponent({ handleFinishMatch }) { // Get the loggedIn and accessToken state const { loggedIn, accessToken } = useContext(TechnologyContext); // Set state const [player1, setPlayer1] = useState(""); const [player2, setPlayer2] = useState(""); const [idPlayer1, setIdPlayer1] = useState(null); const [idPlayer2, setIdPlayer2] = useState(null); const [finishedLoading, setFinishedLoading] = useState(false) const [gameOver, setGameOver] = useState(false); const [startTime, setStartTime] = useState() // Get the match Id from the URL const { id } = useParams(); console.log("Match id:", id); // Listen on startTime useEffect(() => { if (startTime) return setStartTime(new Date()) }, []) // Calculate duration const getDuration = (start, end) => { const duration = end - start // Convert milliseconds to human-readable format const durationInSeconds = Math.floor(duration / 1000); const minutes = Math.floor((durationInSeconds % 3600) / 60); const seconds = durationInSeconds % 60; return `${minutes}:${seconds}` } // * Fetch players data from the created match useEffect(() => { if (!loggedIn) { return; } axios .get(`http://localhost:5005/api/matches/${id}`, { headers: { authToken: `Bearer ${accessToken}` }, }) .then((res) => { // Set players name and players id setPlayer1(res.data[0].players.player1.firstname); setPlayer2(res.data[0].players.player2.firstname); setIdPlayer1(res.data[0].players.player1._id); // console.log(res.data[0].players.player1._id); setIdPlayer2(res.data[0].players.player2._id); // Dont render before its finished loading setFinishedLoading(true) }) .catch((error) => { setFinishedLoading(true) console.log(error) }); }, [loggedIn, accessToken]); // Initialize new ref const scoreBoardRef = useRef(null); // Helper function to handle the showResults event const handleShowResults = (e) => { console.log('custom event listened to', e); if (!loggedIn) { return; } // Set endTime const endTime = new Date(); // Set timestamps const timestamps = { startTime: startTime, endTime: endTime, }; // Get the details from the finished match const { detail: { dateAndTime, player1_name, player2_name, player_score, player_winner } } = e; // Set the players based on id const players = { player1: idPlayer1, player2: idPlayer2, }; // Set the sets results from the match const setResults = player_score; console.log("OVERALL SCORE", setResults); // Set the final results from the match. let player1Sets = 0; let player2Sets = 0; // For each set result, increment the overall score. setResults.forEach((set) => { const [player1Score, player2Score] = set[0].split(' - '); if (parseInt(player1Score) > parseInt(player2Score)) { player1Sets++; } else { player2Sets++; } }); console.log("PLAYER1 SETS", player1Sets); console.log("PLAYER2 SETS", player2Sets); // Calculate the overall points const overallPoints = `${player1Sets}-${player2Sets}`; // Extract the winner's name from player_winner const winnerName = player_winner; console.log(); // Set the winning player, and then get the winning player's id let winner; if (winnerName === player1_name) { winner = idPlayer1; } if (winnerName === player2_name) { winner = idPlayer2; } // Make the API call to update the match updateMatch({ players: players, timestamps: timestamps, duration: getDuration(startTime, endTime), player1Sets: player1Sets, player2Sets: player2Sets, setResults: setResults, overallPoints: overallPoints, winner: winner, finished: true, }); setGameOver(true); }; // Helper function to update the match const updateMatch = (data) => { axios .put(`http://localhost:5005/api/matches/${id}`, data, { headers: { authToken: `Bearer ${accessToken}` }, }) .then((res) => { console.log(res.data); }) .catch((error) => { console.log(error); }); }; // Helper function to set attributes to the web components const setScoreboardAttributes = (scoreboard) => { scoreboard.setAttribute("showplayers", "true"); scoreboard.setAttribute("showsets", "true"); scoreboard.setAttribute("showprevioussets", "true"); scoreboard.setAttribute("player1_name", player1); scoreboard.setAttribute("player2_name", player2); }; // useEffect to handle the rendering and event listener useEffect(() => { if (!scoreBoardRef.current) { return; } const scoreboard = new ScoreBoard(); scoreBoardRef.current.addEventListener('showResults', handleShowResults); setScoreboardAttributes(scoreboard); scoreBoardRef.current.appendChild(scoreboard); return () => { if (scoreBoardRef.current) { scoreBoardRef.current.removeEventListener('showResults', handleShowResults); scoreBoardRef.current.removeChild(scoreboard); } }; }, [finishedLoading, scoreBoardRef]); return ( <div className="tabletennis-container"> <h1>Let's play!</h1> <section className="scoreboard-container"> <div ref={scoreBoardRef}></div> </section> {gameOver && ( <button className="finishMatchBtn" onClick={handleFinishMatch}>Finish match</button> )} </div> ); }
<?php use App\Http\Controllers\ReservationController; use App\Http\Controllers\CourtController; use App\Http\Controllers\ProfileController; use App\Http\Controllers\DashboardController; use App\Http\Controllers\EquipmentController; use App\Http\Controllers\UserController; use App\Http\Controllers\WelcomeController; use Illuminate\Foundation\Application; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; use Inertia\Inertia; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return redirect('/welcome'); }); Route::get('/welcome', function () { if (Auth::check()) { return redirect('/dashboard'); } return app(WelcomeController::class)->show(); })->name('welcome'); // Routing used only by admin Route::middleware('can:isAdmin')->group(function () { // Users Route::get('/users', [UserController::class, 'index']) ->name('users.index'); Route::get('/users/{user}/edit', [UserController::class, 'edit']) ->name('users.edit'); Route::put('/users/{user}', [UserController::class, 'update']) ->name('users.update'); // Reservations Route::get('/reservations', [ReservationController::class, 'index']) ->name('admin.reservations.index'); Route::get('/reservations/{reservation}/edit', [ReservationController::class, 'edit']) ->name('reservations.edit'); // Courts Route::get('/courts', [CourtController::class, 'index']) ->name('courts.index'); Route::get('/courts/create', [CourtController::class, 'create']) ->name('courts.create'); Route::post('/courts', [CourtController::class, 'store']) ->name('courts.store'); Route::get('/courts/{court}', [CourtController::class, 'show']) ->name('courts.show'); Route::get('/courts/{court}/edit', [CourtController::class, 'edit']) ->name('courts.edit'); Route::put('/courts/{court}', [CourtController::class, 'update']) ->name('courts.update'); Route::delete('/courts/{court}', [CourtController::class, 'destroy']) ->name('courts.destroy'); // Equipments Route::get('/equipments', [EquipmentController::class, 'index']) ->name('equipments.index'); Route::get('/equipments/create', [EquipmentController::class, 'create']) ->name('equipments.create'); Route::post('/equipments', [EquipmentController::class, 'store']) ->name('equipments.store'); }); Route::middleware('can:isUser')->group(function () { // Reservations Route::get('/reservations/index', [ReservationController::class, 'index']) ->name('user.reservations.index'); Route::get('/my-reservations', [ReservationController::class, 'myReservations']) ->name('my.reservations'); Route::get('/reserve/{court}', [ReservationController::class, 'create']) ->name('reservations.create'); Route::get('/reservation/confirm/{court}/{start}/{end}/{total_price}', [ReservationController::class, 'confirm']) ->name('reservation.confirm'); Route::post('/reservations', [ReservationController::class, 'store']) ->name('reservations.store'); Route::delete('/reservations/{reservation}', [ReservationController::class, 'destroy']) ->name('reservations.destroy'); Route::post('/reservations/{id}/cancel', [ReservationController::class, 'cancel']) ->name('reservations.cancel'); Route::get('/add-equipment', [ReservationController::class, 'showEquipment']) ->name('show.equipment'); Route::get('/select-reservation', [ReservationController::class, 'selectReservation']) ->name('select.reservation'); Route::get('/reservations/{id}/add-equipment', [ReservationController::class, 'showEquipmentForm']) ->name('reservations.showEquipmentForm'); // Route to handle the form submission Route::post('/reservations/{id}/add-equipment', [ReservationController::class, 'storeEquipment']) ->name('reservations.addEquipment'); // Courts Route::get('/courts/{court}/availability', [CourtController::class, 'generateAvailableSlots']) ->name('court.availability'); Route::get('/courts/{court}/slots', [CourtController::class, 'slots']) ->name('courts.slots'); }); Route::middleware('auth')->group(function () { Route::get('/dashboard', [DashboardController::class, 'index']) ->name('dashboard'); Route::get('/profile', [ProfileController::class, 'edit']) ->name('profile.edit'); Route::patch('/profile', [ProfileController::class, 'update']) ->name('profile.update'); Route::delete('/profile', [ProfileController::class, 'destroy']) ->name('profile.destroy'); }); require __DIR__.'/auth.php';
import { ExternalBank } from "@/domain/entities/external-bank" import { ExternalBanksRepository } from "@/domain/repositories/external-banks-repository" export class InMemoryExternalBankRepository implements ExternalBanksRepository { public items: ExternalBank[] = [] async create(externalBank: ExternalBank) { this.items.push(externalBank) } async delete(externalBank: ExternalBank) { const externalBankIndex = this.items.findIndex( (item) => item.id === externalBank.id, ) this.items.splice(externalBankIndex, 1) } async findById(externalBankId: string) { const externalBank = this.items.find( (item) => item.id.toString() === externalBankId, ) if (!externalBank) { return null } return externalBank } }
<!DOCTYPE html> <html> <head> <title>註冊帳號</title> <style> body { font-family: Arial, sans-serif; } * { box-sizing: border-box; } .container { display: flex; justify-content: center; align-items: center; height: 100vh; width: 100vw; } .login-area { position: relative; box-sizing: border-box; max-width: 400px; width: 100%; margin: 0 auto; padding: 20px; border: 1px solid #ccc; border-radius: 16px; } h1 { text-align: center; } .form-group { margin-bottom: 16px; } .form-group label { display: block; margin-bottom: 8px; font-weight: bold; } .form-group input { width: 100%; padding: 8px 16px; border: 1px solid #ccc; border-radius: 8px; height: 42px; font-size: 16px; } .form-group button { width: 100%; padding: 12px 16px; font-size: 16px; background-color: #4078c2; color: #fff; border: none; border-radius: 8px; cursor: pointer; margin-top: 8px; } .form-group button:hover { background-color: #2e5d99; transition: 0.4s; } .signup-area { display: flex; justify-content: center; align-items: center; } .signup-area p { font-size: 14px; } .signup-area a { font-size: 14px; } </style> </head> <body> <div class="container"> <div class="login-area"> <h1>註冊</h1> <form id="loginForm" action="/auth/login" method="POST"> <div class="form-group"> <label for="username">暱稱</label> <input type="text" id="username" name="username" required /> </div> <div class="form-group"> <label for="account">帳號</label> <input type="text" id="account" name="account" required /> </div> <div class="form-group"> <label for="password">密碼</label> <input type="password" id="password" name="password" required /> </div> <div class="signup-area"> <p>已經有帳號了嗎?</p> <a href="/login">前往登入</a> </div> <div class="form-group"> <button type="submit">註冊</button> </div> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script> <script> var key = 'mollymoooo'; async function postData(jsonString) { try { const response = await fetch('/members', { method: 'POST', headers: { 'Content-Type': 'application/json', // 或 'application/x-www-form-urlencoded' }, body: jsonString, }); const data = await response.json(); // 根據登入請求的回應進行判斷 if (data?.account) { alert('註冊成功,請登入!'); // 登入成功 window.location.href = `/login`; // 跳轉到 /dashboard 頁面 } else { alert('註冊失敗!'); } } catch (error) { console.error('註冊請求失敗', error); alert('註冊請求失敗'); } } document .getElementById('loginForm') .addEventListener('submit', function (event) { event.preventDefault(); // 阻止表單的預設提交行為 var passwordEncrypted = CryptoJS.AES.encrypt( document.getElementById('password').value, key, ); // var decrypted = CryptoJS.AES.decrypt(encrypted, key); // console.log('Encrypted: ' + encrypted); // console.log('Decrypted: ' + decrypted); // console.log(decrypted.toString(CryptoJS.enc.Utf8)); const formData = { account: document.getElementById('account').value, password: `${passwordEncrypted}`, username: document.getElementById('username').value, }; // 轉換為 JSON 字串 const jsonString = JSON.stringify(formData); postData(jsonString); }); </script> </div> </div> </body> </html>
import random import pygame from plane_sprites import * class PlaneGame(object): """飞机大战主游戏""" def __init__(self): print("游戏初始化") #1.创建游戏窗口 self.screen=pygame.display.set_mode(SCREEN_RECT.size) #2.创建游戏时钟 self.clock=pygame.time.Clock() #3.调用私有方法,精灵和精灵组的创建 self.__create_sprites() #4.设置定时器事件 ---创建敌机 1s pygame.time.set_timer(CREATE_ENEMY_EVENT,1000) #设置子弹事件定时器 pygame.time.set_timer(HERO_FIRE_EVENT,500) #创建精灵方法 def __create_sprites(self): #创建背景精灵和精灵组 bg1 = Background() bg2 = Background(True) self.back_group = pygame.sprite.Group(bg1,bg2) #创建敌机的精灵组 self.enemy_group = pygame.sprite.Group() #创建英雄的精灵和精灵组 self.hero=Hero() self.hero_group=pygame.sprite.Group(self.hero) def start_game(self): print("游戏开始...") while True: #1.设置刷新频率 self.clock.tick(FRAME_PER_SEC) #2.事件监听 self.__event_handler() #3.碰撞检测 self.__check_collide() #4.更新/绘制精灵组 self.__updata_sprites() #5.更新显示 pygame.display.update() #事件监听的方法 def __event_handler(self): for event in pygame.event.get(): #判断是否退出游戏 if event.type == pygame.QUIT: PlaneGame.__game_over() elif event.type == CREATE_ENEMY_EVENT: print("敌机出场....") #创建敌机精灵 enemy=Enemy() #将敌机精灵组添加到敌机精灵组 self.enemy_group.add(enemy) elif event.type == HERO_FIRE_EVENT: self.hero.fire() #使用键盘控制的方法获取键盘按键 -按键元组 keys_pressed = pygame.key.get_pressed() #判断元组中对应的按键索引值 if keys_pressed[pygame.K_RIGHT]: self.hero.speed = 2 elif keys_pressed[pygame.K_LEFT]: self.hero.speed = -2 else: self.hero.speed=0 #碰撞检测的方法 def __check_collide(self): #1.子弹摧毁敌机 pygame.sprite.groupcollide(self.hero.bullets,self.enemy_group,True,True) #2.敌机摧毁英雄 enemies=pygame.sprite.spritecollide(self.hero,self.enemy_group,True) #判断列表是否有内容 if len(enemies)>0: #让英雄牺牲 self.hero.kill() #结束游戏 PlaneGame.__game_over() #更新精灵组的方法 def __updata_sprites(self): self.back_group.update() self.back_group.draw(self.screen) self.enemy_group.update() self.enemy_group.draw(self.screen) self.hero_group.update() self.hero_group.draw(self.screen) self.hero.bullets.update() self.hero.bullets.draw(self.screen) #游戏结束的方法,静态方法 @staticmethod def __game_over(): print("游戏结束") pygame.quit() #卸载所有的模块 exit() #结束当前正在运行的程序 if __name__ == '__main__': #创建游戏对象 game = PlaneGame() #启动游戏 game.start_game()
<template> <RouterLink :to="`/movie/${movie.imdbID}`" :style="{ backgroundImage: `url(${movie.Poster})` }" class="movie"> <Loader v-if="imageLoading" :size="1.5" absolute /> <div class="info"> <div class="year"> {{ movie.Year }} </div> <div class="title"> {{ movie.Title }} </div> </div> </RouterLink> </template> <script> import Loader from '~/components/Loader' export default { components: { Loader }, props: { movie: { type: Object, // 배열이나 객체 데이터는 데이터가 가변할 수 있음 // 함수를 만들어서 객체(배열)데이터를 반환하도록 해야함 default: () => ({}) } }, data() { return{ imageLoading: true } }, mounted() { // created 에서는 HTML구조가 연결된 상태가 아니기 때문에 mounted 에서 init 호출 this.init() }, methods: { async init() { const poster = this.movie.Poster if (!poster || poster === 'N/A') { this.imageLoading = false } else { await this.$loadImage(poster) this.imageLoading = false } } } } </script> <style lang="scss" scoped> @import "../scss/main.scss"; .movie { $width: 200px; width: $width; height: calc($width * 3/2); margin: 10px; border-radius: 4px; background-color: $gray-400; background-size: cover; overflow: hidden; position: relative; &:hover::after { content: ""; position: absolute; top: 0; bottom: 0; left: 0; right: 0; border: 6px solid $primary } .info { background-color: rgba($black, .3); width: 100%; padding: 14px; font-size: 14px; text-align: center; position: absolute; left: 0; bottom: 0; backdrop-filter: blur(10px); .year { color: $primary; } .title { color: $white; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } } } </style>
<!DOCTYPE html> <html lang="no"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Steg for steg</title> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="stylesheet" href="style.css"> </head> <body> <header> <a class="logo" href="index.html"><span>Grønn kode</span></a> <nav> <a class="navElement" href="impact.html">Effekt</a> <a class="navElement" href="step-by-step.html">Steg-for-steg</a> <a class="navElement" href="resources.html">Ressurser</a> <a class="navElement" href="about.html">Om siden</a> </nav> </header> <main> <h1>Hvordan koder man grønt?</h1> <h2>En steg-for-steg quide</h2> <div class="steps-container"> <div class="step"> <h2 class="step-header">1. Vær bevisst på bildebruk</h2> <i>Bilder er en av de største bidragsyterne til karbonutslipp på de fleste nettsider </i><br> <b>Hva du burde gjøre:</b> <ul> <li>Bruk kun bilder der det er nødvendig</li> <li>Bruk effektive filformater som WEBP, AVIF eller PNG for enkle bilder</li> <li>Komprimer bildene med verktøy som Shortpixel eller TinyPNG</li> <li>Vurder å bytte det ut med vektorgrafikk</li> </ul> </div> <div class="step"> <h2 class="step-header">2. Noen kodespråk er mer miljøvennlige enn andre</h2> <i>Det er stor forskjell på energibruken til ulike kodespråk </i><br> <b>Hva du burde gjøre:</b> <ul> <li>Bruk de tre minst energikrevende kodespråkene, C, Rust og C++</li> <li>Unngå om mulig Perl, Python og Ruby</li> <li>Ha energieffektivitet som et krav når du skal velge språk til et prosjekt</li> </ul> </div> <div class="step"> <h2 class="step-header">3. Bruk kun JavaScript der det er nødvendig</h2> <i>I forhold til ren HTML og CSS krever det mye mer energi å benytte JS </i><br> <b>Hva du burde gjøre:</b> <ul> <li>Bruk kun JS om det ikke kan løses med HTML og CSS</li> <li>Tenk en ekstra gang på om funksjonaliteten er viktig å ha med</li> <li>Bruk CSS til å animere elementer istedenfor JS</li> </ul> </div> <div class="step"> <h2 class="step-header">4. Gjør siden enkel å navigere</h2> <i>Å laste inn en ny side krever en del energi</i><br> <b>Hva du burde gjøre:</b> <ul> <li>Finn ut hva det er mest vanlig å gjøre på siden og gjør slik at det kan bli gjort ved å besøke få sider</li> <li>Lag god og intuitiv navigasjon</li> </ul> </div> <div class="step"> <h2 class="step-header">5. Grønn fargebruk</h2> <i>De fleste skjermer i dag bruker OLED-teknologi som lyser opp hvert piksel individuelt, noe som betyr at ulike farger krever ulike mengder energi</i><br> <b>Hva du burde gjøre:</b> <ul> <li>Å bruke mørkere farger utgjør en markant forskjell</li> <li>Unngå for mye hvitt</li> <li>Blå piksler krever 25% mer energi enn grønn og rød</li> </ul> </div> <div class="step"> <h2 class="step-header">6. Alt med bevegelser krever mer energi</h2> <i>Videoer krever utrolig mye energi og er kun lenger ned på lista enn bilder fordi det ikke er like vanlig</i><br> <b>Hva du burde gjøre:</b> <ul> <li>Erstatt videoen med bilder der det er mulig</li> <li>Unngå autoplay. Gi brukeren en start-knapp</li> <li>Optimaliser videofilen med komprimering</li> <li>Hvert sekund teller, hold videoen så kort som mulig</li> <li>Vær varsom med bruk av GIFs</li> <li>Unngå for stor bruk av animerte interaksjoner, loadingeffekter og hover- og scrollingeffektiver</li> </ul> </div> <div class="step"> <h2 class="step-header">7. Fontvalg har betydning</h2> <i>Fontfiler kan i skjul gjøre nettsiden din mye tyngre enn nødvendig</i><br> <b>Hva du burde gjøre:</b> <ul> <li>Det mest energieffektive valget er systemfonter som kommer ferdig installert, som eksempelvis Arial og Times New Roman, eller Helvetica på Apple-enheter og Roboto på Android</li> <li>Skal du bruke nedlastede fonter så pass på at du kun inkluderer fontfilene som faktisk er i bruk</li> </ul> </div> </div> </main> <footer> <i>Innholdet på denne siden er basert på boken “Sustainable Web Design” av Tom Greenwood</i> </footer> </body> </html>
Imports System ' ' * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. ' * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' Namespace javax.print.attribute.standard ''' <summary> ''' Class JobName is a printing attribute class, a text attribute, that specifies ''' the name of a print job. A job's name is an arbitrary string defined by the ''' client. It does not need to be unique between different jobs. A Print Job's ''' JobName attribute is set to the value supplied by the client in the Print ''' Request's attribute set. If, however, the client does not supply a JobName ''' attribute in the Print Request, the printer, when it creates the Print Job, ''' must generate a JobName. The printer should generate the value of the Print ''' Job's JobName attribute from the first of the following sources that produces ''' a value: (1) the <seealso cref="DocumentName DocumentName"/> attribute of the first (or ''' only) doc in the job, (2) the URL of the first (or only) doc in the job, if ''' the doc's print data representation object is a URL, or (3) any other piece ''' of Print Job specific and/or document content information. ''' <P> ''' <B>IPP Compatibility:</B> The string value gives the IPP name value. The ''' locale gives the IPP natural language. The category name returned by ''' <CODE>getName()</CODE> gives the IPP attribute name. ''' <P> ''' ''' @author Alan Kaminsky ''' </summary> Public NotInheritable Class JobName Inherits javax.print.attribute.TextSyntax Implements javax.print.attribute.PrintRequestAttribute, javax.print.attribute.PrintJobAttribute Private Const serialVersionUID As Long = 4660359192078689545L ''' <summary> ''' Constructs a new job name attribute with the given job name and locale. ''' </summary> ''' <param name="jobName"> Job name. </param> ''' <param name="locale"> Natural language of the text string. null ''' is interpreted to mean the default locale as returned ''' by <code>Locale.getDefault()</code> ''' </param> ''' <exception cref="NullPointerException"> ''' (unchecked exception) Thrown if <CODE>jobName</CODE> is null. </exception> Public Sub New(ByVal jobName As String, ByVal locale As java.util.Locale) MyBase.New(jobName, locale) End Sub ''' <summary> ''' Returns whether this job name attribute is equivalent to the passed in ''' object. To be equivalent, all of the following conditions must be true: ''' <OL TYPE=1> ''' <LI> ''' <CODE>object</CODE> is not null. ''' <LI> ''' <CODE>object</CODE> is an instance of class JobName. ''' <LI> ''' This job name attribute's underlying string and <CODE>object</CODE>'s ''' underlying string are equal. ''' <LI> ''' This job name attribute's locale and <CODE>object</CODE>'s locale are ''' equal. ''' </OL> ''' </summary> ''' <param name="object"> Object to compare to. ''' </param> ''' <returns> True if <CODE>object</CODE> is equivalent to this job name ''' attribute, false otherwise. </returns> Public Overrides Function Equals(ByVal [object] As Object) As Boolean Return (MyBase.Equals([object]) AndAlso TypeOf [object] Is JobName) End Function ''' <summary> ''' Get the printing attribute class which is to be used as the "category" ''' for this printing attribute value. ''' <P> ''' For class JobName, the category is class JobName itself. ''' </summary> ''' <returns> Printing attribute class (category), an instance of class ''' <seealso cref="java.lang.Class java.lang.Class"/>. </returns> Public Property category As Type Get Return GetType(JobName) End Get End Property ''' <summary> ''' Get the name of the category of which this attribute value is an ''' instance. ''' <P> ''' For class JobName, the category name is <CODE>"job-name"</CODE>. ''' </summary> ''' <returns> Attribute category name. </returns> Public Property name As String Get Return "job-name" End Get End Property End Class End Namespace
'use client'; import React, { useRef, useState } from 'react'; import emailjs from '@emailjs/browser'; import Image from 'next/image'; import Link from 'next/link'; import { AiOutlineMail } from 'react-icons/ai'; import { FaLinkedinIn, FaGithub, FaTelegram } from 'react-icons/fa'; export default function Contacts() { const form = useRef(null); const [done, setDone] = useState(false); const sendEmail = (e: React.SyntheticEvent) => { e.preventDefault(); emailjs .sendForm('service_uzrsqfu', 'template_ct2goqa', form.current!, 'Oq34YLTxk_3IpCbJo') .then( (result) => { console.log(result.text); setDone(true); }, (error) => { console.log(error.text); }, ); }; return ( <> <h2 className="uppercase text-center text-3xl font-bold tracking-widest text-[#5d31b6] mt-4 dark:text-violet-400"> Get in Touch <hr className="w-10 h-1 mx-auto my-4 bg-violet-500 border-0 rounded"></hr> </h2> <div id="contact" className="w-full"> <div className="max-w-[1000px] m-auto md:px-8 lg:px-8 py-12"> <div className="grid lg:grid-cols-5 gap-8"> <div className="col-span-2 lg:col-span-2 w-full h-full p-4 shadow-xl shadow-gray-400 dark:shadow-sm dark:shadow-gray-200 rounded-xl"> <div className="lg:p-4 h-full"> <div> <Image src="/assets/contact.svg" alt="contact" width={400} height={300} /> </div> <div> <p className="py-4 text-violet-800 text-2xl tracking-wide text-center font-semibold dark:text-violet-400"> Frontend Developer </p> <p className="py-2 text-gray-600 text-xl dark:text-gray-500"> Let&#39;s build something interesting together. </p> <p className="py-2 text-gray-600 text-xl dark:text-gray-500"> Contact me and let&#39;s talk. </p> </div> <div> <div className="flex items-center justify-between py-4"> <Link href="https://www.linkedin.com/in/cholpon-damirbekova-a879b022b/" target="_blank" className="rounded-full shadow-lg shadow-gray-400 dark:shadow-sm dark:shadow-gray-200 p-3 cursor-pointer hover:bg-[#5d31b6] hover:text-white hover:scale-105 ease-in duration-300" > <FaLinkedinIn size={20} /> </Link> <Link href="https://github.com/Cholpon-dd" target="_blank" className="rounded-full shadow-lg shadow-gray-400 dark:shadow-sm dark:shadow-gray-200 p-3 cursor-pointer hover:bg-[#5d31b6] hover:text-white hover:scale-105 ease-in duration-300" > <FaGithub size={20} /> </Link> <Link href="https://t.me/cholpon_dd" target="_blank" className="rounded-full shadow-lg shadow-gray-400 dark:shadow-sm dark:shadow-gray-200 p-3 cursor-pointer hover:bg-[#5d31b6] hover:text-white hover:scale-105 ease-in duration-150" > <FaTelegram size={20} /> </Link> <Link href="https://cholpon.damirbekova@gmail.com" target="_blank" className="rounded-full shadow-lg shadow-gray-400 dark:shadow-sm dark:shadow-gray-200 p-3 cursor-pointer hover:bg-[#5d31b6] hover:text-white hover:scale-105 ease-in duration-300" > <AiOutlineMail size={20} /> </Link> </div> </div> </div> </div> <div className="col-span-3 w-full shadow-xl shadow-gray-400 rounded-xl lg:p-4 dark:shadow-sm dark:shadow-gray-200"> <div className="p-4"> <form ref={form} onSubmit={sendEmail}> <div className="grid md:grid-cols-2 gap-4 py-2"> <div className="flex flex-col "> <label className="uppercase text-sm py-2 text-violet-800">Name</label> <input className="border-2 rounded-lg p-2 flex border-violet-400 focus:outline-none focus:border-violet-800" type="text" placeholder="Name" name="user_name" required /> </div> <div className="flex flex-col"> <label className="uppercase text-sm py-2 text-violet-800">Subject</label> <input className="border-2 rounded-lg p-2 flex border-violet-400 focus:outline-none focus:border-violet-800" type="text" placeholder="Subject" required /> </div> </div> <div className="flex flex-col py-2"> <label className="uppercase text-sm py-2 text-violet-800">Email</label> <input className="border-2 rounded-lg p-3 flex border-violet-400 focus:outline-none focus:border-violet-800" type="email" placeholder="Your email" name="user_email" required /> </div> <div className="flex flex-col py-2"> <label className="uppercase text-sm py-2 text-violet-800">Message</label> <textarea className="border-2 rounded-lg p-3 border-violet-400 focus:outline-none focus:border-violet-800" rows={4} placeholder="Message" name="message" required ></textarea> </div> <button className="w-full p-4 text-bold capitalize text-2xl bg-[#5d31b6] text-white rounded-lg mt-4"> Send message </button> {done && ( <p className="text-center text-bold text-xl ">Thank you for your message</p> )} </form> </div> </div> </div> </div> </div> </> ); }
package hust.soict.hedspi.aims.media; import java.util.Comparator; import java.util.Objects; public abstract class Media { protected int id; protected String title; protected String category; protected float cost; protected static int idCount = 0; public int getId() { return id; } public String getTitle() { return title; } public String getCategory() { return category; } public float getCost() { return cost; } public Media(String title) { this.title = title; id = ++idCount; } public Media(String title, String category) { this.title = title; this.category = category; id = ++idCount; } public Media(String title, String category, float cost) { this.title = title; this.category = category; this.cost = cost; id = ++idCount; } public boolean equals(Object obj) throws ClassCastException, NullPointerException { if (obj == null) { throw new NullPointerException("ERROR: Null object!"); } if (!(obj instanceof Media media)) { throw new ClassCastException("ERROR: Not a media!"); } return (Objects.equals(this.title, media.title) && (this.cost == media.cost)); } public boolean isMatch(String keyword) { String keywordLowerCase = keyword.toLowerCase(); String titleLowerCase = title.toLowerCase(); String[] words = keywordLowerCase.split(" "); for (String word : words) { if (!titleLowerCase.contains(word)) { return true; } } return false; } public static final Comparator<Media> COMPARE_BY_TITLE_COST = new MediaComparatorByTitleCost(); public static final Comparator<Media> COMPARE_BY_COST_TITLE = new MediaComparatorByCostTitle(); }
import { transliterate } from "transliteration"; import { v4 as uuidv4 } from "uuid"; export const createSlug = (cyrillicText) => { // Transliterate Cyrillic text to Latin characters const latinText = transliterate(cyrillicText); // Generate a unique ID const id = uuidv4(); // Replace spaces and special characters to create a slug const slug = latinText .toLowerCase() .replace(/\s+/g, "-") // Replace spaces with hyphens .replace(/[^a-z0-9-]/g, ""); // Remove special characters // Add the ID to the end of the slug const slugWithId = `${slug}-${id}`; return slugWithId; };
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import { kubernetesApi } from "../api/api"; import { toast } from "sonner"; import { IgetNamespace, IgetNamespaces, } from "../interfaces/useFunctionsInterfaces"; export const createFederatedFleet = createAsyncThunk( "fleet/createFederatedFleet", async (values: { organizationId: string; roboticsCloudName: string; instanceId: string; region: string; robolaunchFederatedFleetsName: string; }) => { const response = await kubernetesApi.createFederatedFleet({ name: "fleet/createFederatedFleet", organizationId: values?.organizationId, roboticsClouds: [ { name: values?.roboticsCloudName, cloudInstances: [ { instanceId: values?.instanceId, region: values?.region, robolaunchFederatedFleets: [ { name: values?.robolaunchFederatedFleetsName }, ], }, ], }, ], }); return response.data; }, ); export const getFederatedFleets = createAsyncThunk( "fleet/getFederatedFleets", async (values: { organizationId: string; roboticsCloudName: string; region: string; instanceId: string; }) => { const response = await kubernetesApi.getFederatedFleets({ name: "fleet/getFederatedFleets", organizationId: values?.organizationId, roboticsClouds: [ { name: values?.roboticsCloudName, cloudInstances: [ { instanceId: values?.instanceId, region: values?.region }, ], }, ], }); return response.data; }, ); export const deleteFederatedFleet = createAsyncThunk( "fleet/deleteFederatedFleet", async (values: any) => { const response = await kubernetesApi.deleteFederatedFleet({ name: "fleet/deleteFederatedFleet", organizationId: values?.organizationId, roboticsClouds: [ { name: values?.roboticsCloudName, cloudInstances: [ { instanceId: values?.instanceId, region: values?.region, robolaunchFederatedFleets: [ { name: values?.robolaunchFederatedFleetsName }, ], }, ], }, ], }); return response.data; }, ); export const createNamespace = createAsyncThunk( "fleet/createNamespace", async (values: IgetNamespace) => { const response = await kubernetesApi.createNamespace({ name: "fleet/createNamespace", organizationId: values?.organizationId, roboticsClouds: [ { name: values?.roboticsCloudName, cloudInstances: [ { instanceId: values?.instanceId, region: values?.region, robolaunchNamespaces: [{ name: values?.namespaceName }], }, ], }, ], }); return response.data; }, ); export const getNamespaces = createAsyncThunk( "fleet/getNamespaces", async (values: IgetNamespaces) => { const response = await kubernetesApi.getNamespaces({ name: "fleet/getNamespaces", organizationId: values?.organizationId, roboticsClouds: [ { name: values?.roboticsCloudName, cloudInstances: [ { instanceId: values?.instanceId, region: values?.region }, ], }, ], }); return response.data; }, ); export const deleteNamespace = createAsyncThunk( "fleet/deleteNamespace", async (values: IgetNamespace) => { const response = await kubernetesApi.deleteNamespace({ name: "fleet/deleteNamespace", organizationId: values?.organizationId, roboticsClouds: [ { name: values?.roboticsCloudName, cloudInstances: [ { instanceId: values?.instanceId, region: values?.region, robolaunchNamespaces: [{ name: values?.namespaceName }], }, ], }, ], }); return response.data; }, ); export const FleetSlice = createSlice({ name: "fleet", initialState: {}, reducers: {}, extraReducers: (builder) => { builder .addCase(createFederatedFleet.fulfilled, (_, action: any) => { if (!action?.payload?.success) { toast.error(action?.payload?.message); } else { toast.success(action?.payload?.message); } }) .addCase(createFederatedFleet.rejected, () => { toast.error("Something went wrong of creating fleet"); }) .addCase(getFederatedFleets.fulfilled, (_, action: any) => { if (!action?.payload?.success) { toast.error(action?.payload?.message); } }) .addCase(getFederatedFleets.rejected, () => { toast.error(`Something went wrong of getting fleets`); }) .addCase(deleteFederatedFleet.fulfilled, (_, action: any) => { if (!action?.payload?.success) { toast.error(action?.payload?.message); } else { toast.success(action?.payload?.message); } }) .addCase(deleteFederatedFleet.rejected, () => { toast.error("Something went wrong of deleting fleet"); }) .addCase(createNamespace.fulfilled, (_, action: any) => { if (!action?.payload?.success) { toast.error(action?.payload?.message); } else { toast.success(action?.payload?.message); } }) .addCase(createNamespace.rejected, () => { toast.error("Something went wrong of creating namespace"); }); }, }); export default FleetSlice.reducer;
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/style.css"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"> <title>Country App</title> </head> <body> {{> navbar }} <div class="container-fluid"> <div class="container"> <div class="row"> {{!-- <h1 class="text-center">County Seach</h1> --}} <div class="col mt-1 text-center"> <div class="country-box col-md-8 offset-md-2 py-5 pt-3"> <div class="search-bar"> <input type="text" name="" id="serch_input" placeholder="Search County..." onKeyUp="showCountry(this.value)"> <small class="text-white d-block">Type 3 character of a country</small> <ul id="auto_City"> </ul> </div> <div class="result-box mt-5"> <div class="country-image"> <img src="images/india.jpg" alt="" style="width: 80%; height: 250px!important"> </div> <div class="country-caption"> <h2 class="text-white">India</h2> </div> <div class="extra-info d-flex justify-content-between mx-5" > <span class="text-white">Capital: <strong id="capital"></strong></span> <span class="text-white">Population: <strong id="population"></strong></span> </div> </div> </div> </div> </div> </div> </div> {{> footer}} <script> // searching city let countryArr = [ 'Afghanistan', 'Åland Islands', 'Albania', 'Algeria', 'American Samoa', 'AndorrA', 'Angola', 'Anguilla', 'Antarctica', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Bouvet Island', 'Brazil', 'British Indian Ocean Territory', 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Cayman Islands', 'Central African Republic', 'Chad', 'Chile', 'China', 'Christmas Island', 'Cocos (Keeling) Islands', 'Colombia', 'Comoros', 'Congo', 'Congo, The Democratic Republic of the', 'Cook Islands', 'Costa Rica', 'Cote D\'Ivoire', 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Falkland Islands (Malvinas)', 'Faroe Islands', 'Fiji', 'Finland', 'France', 'French Guiana', 'French Polynesia', 'French Southern Territories', 'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guadeloupe', 'Guam', 'Guatemala', 'Guernsey', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Heard Island and Mcdonald Islands', 'Holy See (Vatican City State)', 'Honduras', 'Hong Kong', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran, Islamic Republic Of', 'Iraq', 'Ireland', 'Isle of Man', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jersey', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea, Democratic People\'S Republic of', 'Korea, Republic of', 'Kuwait', 'Kyrgyzstan', 'Lao People\'S Democratic Republic', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libyan Arab Jamahiriya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macao', 'Macedonia, The Former Yugoslav Republic of', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Martinique', 'Mauritania', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia, Federated States of', 'Moldova, Republic of', 'Monaco', 'Mongolia', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'Netherlands Antilles', 'New Caledonia', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Norfolk Island', 'Northern Mariana Islands', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestinian Territory, Occupied', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Pitcairn', 'Poland', 'Portugal', 'Puerto Rico', 'Qatar', 'Reunion', 'Romania', 'Russian Federation', 'RWANDA', 'Saint Helena', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Pierre and Miquelon', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia and Montenegro', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia and the South Sandwich Islands', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Svalbard and Jan Mayen', 'Swaziland', 'Sweden', 'Switzerland', 'Syrian Arab Republic', 'Taiwan, Province of China', 'Tajikistan', 'Tanzania, United Republic of', 'Thailand', 'Timor-Leste', 'Togo', 'Tokelau', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks and Caicos Islands', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'United States Minor Outlying Islands', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Viet Nam', 'Virgin Islands, British', 'Virgin Islands, U.S.', 'Wallis and Futuna', 'Western Sahara', 'Yemen', 'Zambia', 'Zimbabwe' ] let res; let city_serch; function autocompleteMatch(input) { if (input == '') { return []; } if(input.length < 3) { return []; } var reg = new RegExp(input.toLowerCase()) return countryArr.filter(function(term) { let terms = term.toLowerCase(); if (terms.match(reg)) { return terms; } }); } function showCountry(val) { res = document.getElementById("auto_City"); res.innerHTML = ''; let list = ''; let terms = autocompleteMatch(val); for (i = 0; i < terms.length; i++) { list += '<li>' + terms[i] + '</li>'; } res.innerHTML = list; const searchLI = document.querySelectorAll("#auto_City li"); searchLI.forEach((data) => { data.addEventListener("click", function() { city_serch = document.getElementById("serch_input"); city_serch.value = this.innerHTML; res.innerHTML = ''; let serachTerms = city_serch.value; const countryImage = document.querySelector(".country-image img"); const countryName = document.querySelector(".country-caption h2"); const capital = document.querySelector("#capital"); const population = document.querySelector("#population"); fetch("/oneCountry",{ method:"POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify({serachTerms}) }).then(res => res.text()).then(data =>{ let countryInfo = JSON.parse(data); countryImage.src = countryInfo.countryInfo[1]; countryName.innerHTML = countryInfo.countryInfo[0]; capital.innerHTML = countryInfo.countryInfo[2]; population.innerHTML = countryInfo.countryInfo[3] }) }); }) } </script> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>
//---------------------------------------------------------------------------- // ObjectWindows // Copyright (c) 1993, 1995 by Borland International, All Rights Reserved // // This program has example code that uses the Common Dialog classes // in OWL // // The main window will have menu selections for opening a file, changing // the font and changing the color used for the selected font. When a file // is selected the name will be displayed on the client area of the window. // //---------------------------------------------------------------------------- #include <owl/pch.h> #include <owl/applicat.h> #include <owl/framewin.h> #include <owl/dialog.h> #include <owl/dc.h> #include <owl/chooseco.h> #include <owl/choosefo.h> #include <owl/opensave.h> #include <stdio.h> #include <string.h> #include "commdlgx.rh" // // class TCommDlgWnd // ~~~~~ ~~~~~~~~~~~ class TCommDlgWnd : public TFrameWindow { public: TCommDlgWnd(TWindow*, const char*); ~TCommDlgWnd(); void Paint(TDC&, bool, TRect&); void CmFileOpen(); void CmColor(); void CmFont(); void CmHelpAbout(); TColor Color; TFont* Font; TOpenSaveDialog::TData FilenameData; TChooseFontDialog::TData FontData; void EvSize(uint sizeType, TSize& size); DECLARE_RESPONSE_TABLE(TCommDlgWnd); }; DEFINE_RESPONSE_TABLE1(TCommDlgWnd, TFrameWindow) EV_WM_SIZE, EV_COMMAND(CM_FILEOPEN, CmFileOpen), EV_COMMAND(CM_COLOR, CmColor), EV_COMMAND(CM_FONT, CmFont), EV_COMMAND(CM_HELPABOUT, CmHelpAbout), END_RESPONSE_TABLE; // // Note the initialization method of the filter string. The TOpenSave::TData // class expects to find a filter string that has a '|' terminator between // strings and an extra '|' that terminates the entire filter data set. // The '|' characters are translated to 0's within TData's copy of the string. // Using '|'s allows the filter to be loaded from a resource & copied using // strcpy. // TCommDlgWnd::TCommDlgWnd(TWindow* parent, const char* title) : TFrameWindow(parent, title), FilenameData(OFN_FILEMUSTEXIST|OFN_HIDEREADONLY|OFN_PATHMUSTEXIST, "All Files (*.*)|*.*|Text Files (*.txt)|*.txt|", 0, "", "*") { AssignMenu("CMDLGAPMENU"); // Set up the menu Color = TColor::Black; // Use black as the default color Font = 0; // Empty the handle to the font // Take advantage of each OS' enhancements to the FileOpen Dialog // #if defined(BI_PLAT_WIN32) if (TSystem::IsNT() || TSystem::IsWin95()) FilenameData.Flags |= OFN_LONGNAMES; if (TSystem::IsWin95()) FilenameData.Flags |= OFN_EXPLORER; #endif } TCommDlgWnd::~TCommDlgWnd() { delete Font; } // // We need to invalidate the entire area, not just the clip area so that // paint gets called correctly // void TCommDlgWnd::EvSize(uint sizeType, TSize& size) { Invalidate(); TFrameWindow::EvSize(sizeType,size); } // // Display the file name using the selected font in the selected color. // void TCommDlgWnd::Paint(TDC& paintDC, bool, TRect&) { paintDC.SetTextColor(Color); paintDC.SetBkColor(TColor::SysWindow); if (Font) paintDC.SelectObject(*Font); paintDC.DrawText(FilenameData.FileName, strlen(FilenameData.FileName), GetClientRect(), DT_CENTER | DT_WORDBREAK); } // // // void TCommDlgWnd::CmFileOpen() { // If the call to Execute fails you can examine the Error member // of FilenameData to determine the type of error that occured. // if (TFileOpenDialog(this, FilenameData).Execute() != IDOK) { if (FilenameData.Error != 0) { // 0 value means user selected Cancel char msg[50]; sprintf(msg, "GetOpenFileName returned Error #%ld", FilenameData.Error); MessageBox(msg, "WARNING", MB_OK|MB_ICONSTOP); } } Invalidate(); // Repaint to display the new name } // // void TCommDlgWnd::CmColor() { TChooseColorDialog::TData choose; static TColor custColors[16] = { 0x010101L, 0x101010L, 0x202020L, 0x303030L, 0x404040L, 0x505050L, 0x606060L, 0x707070L, 0x808080L, 0x909090L, 0xA0A0A0L, 0xB0B0B0L, 0xC0C0C0L, 0xD0D0D0L, 0xE0E0E0L, 0xF0F0F0L }; choose.Flags = CC_RGBINIT; choose.Color = Color; choose.CustColors = custColors; if (TChooseColorDialog(this, choose).Execute() == IDOK) { Color = choose.Color; } Invalidate(); } // // // void TCommDlgWnd::CmFont() { if (Font) { // FontData contains previous selections FontData.Flags |= CF_INITTOLOGFONTSTRUCT; FontData.Color = Color; } else { FontData.DC = 0; FontData.Flags = CF_EFFECTS | CF_FORCEFONTEXIST | CF_SCREENFONTS; FontData.Color = Color; // Color and font dialogs use the same color FontData.Style = 0; FontData.FontType = SCREEN_FONTTYPE; FontData.SizeMin = 0; FontData.SizeMax = 0; } if (TChooseFontDialog(this, FontData).Execute() == IDOK) { delete Font; Color = FontData.Color; Font = new TFont(&FontData.LogFont); } Invalidate(); } void TCommDlgWnd::CmHelpAbout() { MessageBox("Common Dialog Example\nWritten using ObjectWindows\n" "Copyright (c) 1993, 1995 Borland", "About Common Dialog Example", MB_OK); } // // class TCommDlgApp // ~~~~~ ~~~~~~~~~~~ class TCommDlgApp : public TApplication { public: TCommDlgApp() : TApplication() {} void InitMainWindow() { MainWindow = new TCommDlgWnd(0, "Common Dialog Example"); EnableCtl3d(); } }; int OwlMain(int /*argc*/, char* /*argv*/ []) { return TCommDlgApp().Run(); }
'use strict'; import 'mocha'; import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; import chaiSubset from 'chai-subset'; import { default as Endpoint } from '../../../src/api/paths/users'; import { TestHarness } from '../testUtils'; // Configure Chai chai.use(chaiSubset); chai.use(chaiAsPromised); const expect = chai.expect; describe('Test src/api/paths/index.ts endpoint', () => { const baseOptions = { instanced: false, endpoint: Endpoint, uri: '/', }; describe('GET', () => { const getOptions = { ...baseOptions, req: {}, method: 'GET', }; it('Returns success heartbeat', async () => { const options = { ...getOptions, }; // test const res = await TestHarness.makeRequest(options); // validate const expectedStatusCode = 200; const expectedBody = { success: true }; expect(res.statusCode).to.deep.equal(expectedStatusCode); expect(res.body).to.deep.equal(expectedBody); }); }); });
package practice_41.album.dao; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import practice_41.album.model.Photo; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.*; class AlbumImplTest { AlbumImpl albums; Photo[] photos = new Photo[6]; LocalDateTime now = LocalDateTime.now(); @BeforeEach void setUp() { albums = new AlbumImpl(7); photos[0] = new Photo(1, 1, "title-1", "url1", now.minusDays(10)); photos[1] = new Photo(1, 2, "title-2", "url2", now.minusDays(10)); photos[2] = new Photo(1, 3, "title-3", "url3", now.minusDays(5)); photos[3] = new Photo(2, 1, "title-1", "url1", now.minusDays(10)); photos[4] = new Photo(2, 4, "title-4", "url4", LocalDateTime.of(now.minusDays(2).toLocalDate(), LocalTime.MAX)); photos[5] = new Photo(1, 4, "title-4", "url1", LocalDateTime.of(now.minusDays(2).toLocalDate(), LocalTime.MAX)); for (int i = 0; i < photos.length; i++) { albums.addPhoto(photos[i]); } } @Test void addPhotoTest() { assertFalse(albums.addPhoto(null));//добавление пустого фото assertFalse(albums.addPhoto(photos[1]));//добавление имеющегося Photo photo = new Photo(1, 5, "title-5", "url5", now.minusDays(3)); assertTrue(albums.addPhoto(photo));//проверяем добавился ли фото assertEquals(7, albums.size());//проверка размера size photo = new Photo(1, 6, "title-6", "url6", now.minusDays(3)); assertFalse(albums.addPhoto(photo));//добавление сверх capacity } @Test void removePhotoTest() { assertFalse(albums.removePhoto(5,1));//не можем удалить несуществующего фото assertTrue(albums.removePhoto(1,1)); assertEquals(5, albums.size());//проверка размера size assertNull(albums.getPhotoFromAlbum(1,1)); } @Test void updatePhotoTest() { assertTrue(albums.updatePhoto(1,1,"newUrl")); assertEquals("newUrl",albums.getPhotoFromAlbum(1,1).getUrl()); } @Test void getPhotoFromAlbumTest() { assertEquals(photos[0], albums.getPhotoFromAlbum(1,1)); assertNull(albums.getPhotoFromAlbum(3,3)); } @Test void getAllPhotoFromAlbumTest() { Photo[] actual = albums.getAllPhotoFromAlbum(1); Arrays.sort(actual);//сортировали Photo[] expected = {photos[0], photos[1], photos[2], photos[5]}; assertArrayEquals(expected, actual); } @Test void getBetweenDateTest() { LocalDate ld = now.toLocalDate();//сколько прошло времени от сейчас до LocalDate System.out.println(ld); Photo[] actual = albums.getBetweenDate(ld.minusDays(5), ld.minusDays(2)); Arrays.sort(actual); Photo[] expected = { photos[2], photos[5], photos[4]}; assertArrayEquals(expected, actual); } @Test void sizeTest() { assertEquals(6, albums.size()); } }
d3.csv("https://10matcho27.github.io/InfoVis2022/W04/w04_task1.csv") .then(data => { data.forEach(d => { d.x = +d.x; d.y = +d.y; d.c = d.c; d.r = +d.r; }) var config = { parent: '#drawing_region', width: 256, height: 256, margin: { top: 20, right: 20, bottom: 20, left: 20 }, }; const scatter_plot = new ScatterPlot(config, data); scatter_plot.update(); }) .catch(error => { console.log(error); }); class ScatterPlot { constructor(config, data) { this.config = { parent: config.parent, width: config.width || 256, height: config.height || 256, margin: config.margin || { top: 10, right: 10, bottom: 10, left: 10 }, } this.data = data; this.init(); } init() { let self = this; self.svg = d3.select(self.config.parent) .attr('width', self.config.width) .attr('height', self.config.height); self.chart = self.svg.append('g') .attr('transform', `translate(${self.config.margin.left }, ${self.config.margin.top })`); self.inner_width = self.config.width - self.config.margin.left - self.config.margin.right; self.inner_height = self.config.height - self.config.margin.top - self.config.margin.bottom; self.xscale = d3.scaleLinear() .range([self.config.margin.left, self.inner_width]); self.yscale = d3.scaleLinear() .range([0, self.inner_height]); self.xaxis = d3.axisBottom(self.xscale) .ticks(8) .tickSize(4) .tickPadding(8); self.yaxis = d3.axisLeft(self.yscale) .ticks(8) .tickSize(4) .tickPadding(8); self.xaxis_group = self.chart.append('g') .attr('transform', `translate(0, ${self.inner_height})`); self.yaxis_group = self.chart.append('g') .attr('transform', `translate(${self.config.margin.left}, 0)`); } update() { let self = this; const xmin = d3.min(self.data, d => d.x); const xmax = d3.max(self.data, d => d.x); const ymin = d3.min(self.data, d => d.y); const ymax = d3.max(self.data, d => d.y); self.xscale.domain([xmin - self.config.margin.left, xmax + self.config.margin.right]); self.yscale.domain([ymin - self.config.margin.top, ymax + self.config.margin.bottom]); self.render(); } render() { let self = this; self.chart.selectAll("circle") .data(self.data) .enter() .append("circle") .attr("cx", d => self.xscale(d.x)) .attr("cy", d => self.yscale(d.y)) .attr("r", d => d.r) .attr("fill", d => d.c) .attr("stroke", "black") .attr("stroke-width", 1); self.xaxis_group.call(self.xaxis); self.yaxis_group.call(self.yaxis); } }
<header> <nav class="navbar navbar-expand-lg navbar-light bg-light nav"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div> </div> <div class=" collapse navbar-collapse nav1" id="navbarSupportedContent"> <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse" [ngClass]="{ show: isExpanded }"> <ul class="navbar-nav flex-grow"> <li class="nav-item" [routerLinkActive]="['link-active']" [routerLinkActiveOptions]="{ exact: true }"> <a class="nav-link text-dark" [routerLink]="['/']">Home</a> </li> <li *ngIf="isAdmin === true && isLoggedIn == true" class="nav-item" [routerLinkActive]="['link-active']"> <a class="nav-link text-dark" [routerLink]="['/game-create']">Create game</a> </li> <li *ngIf="isAdmin === true && isLoggedIn == true" class="nav-item" [routerLinkActive]="['link-active']"> <a class="nav-link text-dark" [routerLink]="['/admin-panel']">Admin panel</a> </li> <li *ngIf="isLoggedIn === true && isAdmin == false" class="nav-item" [routerLinkActive]="['link-active']"> <a class="nav-link text-dark" [routerLink]="['/user-profile']">Profile</a> </li> <li *ngIf="isLoggedIn === false" class="nav-item" [routerLinkActive]="['link-active']"> <a class="nav-link text-dark" [routerLink]="['/register']">Register</a> </li> <li *ngIf="isLoggedIn === false" class="nav-item" [routerLinkActive]="['link-active']"> <a class="nav-link text-dark" [routerLink]="['/login']">Login</a> </li> <li *ngIf="isLoggedIn === true" class="nav-item"> <a class="nav-link text-dark" [routerLink]="['/']" (click)="Logout()">Logout</a> </li> </ul> </div> <form class="form-inline my-2 my-lg-0 "> <input class="form-control mr-sm-2 search" type="search" placeholder="Search" aria-label="Search"> <!-- <button class="btn btn-outline-success my-2 my-sm-0 " type="submit"><i class="material-icons">search</i></button> --> <img class="img-logo2" src="../../assets/background — копия/logo2.png" style="width: 70px;"> </form> </div> </nav> </header>
# File name: ListQueue.py # Author: Aadhawan Maadheshwaran # Date created: 11/15/2023 # Date last modified: 12/03/2023 # Python Version: 3.12.0 class ListQueue: def __init__(self): self.stack = [] def enqueue(self, value): self.stack.append(value) def dequeue(self): dequeued = self.stack.pop(0) return dequeued def seek(self): return self.stack[0] def __str__(self): return str(self.stack) def clear(self): self.stack = [] customStack = ListQueue() customStack.enqueue(1) customStack.enqueue(2) customStack.enqueue(3) customStack.enqueue(4) #access print("\n---------------------") print("- Access Operations -") print("---------------------") print("Accessing value by seek: " +str(customStack.seek())) #insert print("\n---------------------") print("- Insert Operations -") print("---------------------") customStack.enqueue(5) print("enqueueing a number: ", customStack) #delete print("\n---------------------") print("- Delete Operations -") print("---------------------") dequeueped = customStack.dequeue() #index can be given optionally else it fetches the last element print("Deleting by dequeue method: ", customStack) print("dequeued number from list:", dequeueped) customStack.clear() print("clearing entire stack :", customStack) # -- Result -- # --------------------- # - Access Operations - # --------------------- # Accessing value by seek: 1 # --------------------- # - Insert Operations - # --------------------- # enqueueing a number: [1, 2, 3, 4, 5] # --------------------- # - Delete Operations - # --------------------- # Deleting by dequeue method: [2, 3, 4, 5] # dequeued number from list: 1 # clearing entire stack : []
import React, {useEffect, useState} from 'react'; import {Card, Container, TableBody, TableCell, TableContainer, TableHead, TableRow, Typography} from "@mui/material"; import {Footer} from "../component/Footer"; import MyHeader from '../component/MyHeader'; import {Product} from "../../model/Product"; import ProductService from "../../services/ProductService"; import Button from "@mui/material/Button"; import {Link} from "react-router-dom"; import {Table} from "semantic-ui-react"; const ProductsUpdatePage = () => { const [products, setProducts] = useState<Array<Product>>([]); useEffect(() => { ProductService.findAllProducts() .then(response => setProducts(response)); }, []); return ( <div> <MyHeader/> <Container > <Typography component="h1" variant="h5"> <h1>All products</h1> </Typography> <Card style={{width: 1000}}> <TableContainer> <Table celled padded> <TableHead> <Table.Row> <Table.HeaderCell>Id product</Table.HeaderCell> <Table.HeaderCell>Name product</Table.HeaderCell> <Table.HeaderCell>Price</Table.HeaderCell> <Table.HeaderCell>Type product</Table.HeaderCell> <Table.HeaderCell>Count in stock</Table.HeaderCell> <Table.HeaderCell>Description</Table.HeaderCell> </Table.Row> </TableHead> <TableBody> {products.map((product) => ( <TableRow key={product.productId} sx={{'&:last-child td, &:last-child th': {border: 0}}} > <TableCell component="th" scope="row"> {product.productId} </TableCell> <TableCell component="th" scope="row"> {product.productName} </TableCell> <TableCell component="th" scope="row"> {product.price} </TableCell> <TableCell component="th" scope="row"> {product.idType} </TableCell> <TableCell component="th" scope="row"> {product.countInStock} </TableCell> <TableCell component="th" scope="row"> {product.description} </TableCell> <TableCell> <Button component={Link} type="submit" fullWidth variant="contained" sx={{mt: 1, mb: 1}} to={'/admin/products/'+product.productId} > Update </Button> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </Card> <Footer/> </Container> </div> ); }; export default ProductsUpdatePage;
import os import django # Set the DJANGO_SETTINGS_MODULE environment variable os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AnimeReviewHub.settings') # Initialize Django django.setup() from django.shortcuts import render, redirect from django.http import JsonResponse from bs4 import BeautifulSoup from Sources.models import ExternalAnimeTitle, ExternalReview, ExternalSource, ExternalUser import requests # Define the URL and User-Agent header url = "https://myanimelist.net/reviews.php?t=anime" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } # Make the request with headers response = requests.get(url, headers=headers) # Check if the request was successful if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') # Find all review elements review_elements = soup.find_all('div', class_='review-element js-review-element') # Process or store the results for review_element in review_elements: # Extract data from each review element anime_title = review_element.find('div', class_='titleblock mb4').find('a').text created_at = review_element.find('div', class_='thumbbody mt8').find('div', class_='update_at').text username = review_element.find('div', class_='thumbbody mt8').find('div', class_='username').find('a').text content = review_element.find('div', class_='thumbbody mt8').find('div', class_='text').text.strip() # Create or get ExternalSource instance source, _ = ExternalSource.objects.get_or_create(name='MyAnimeList', website=url) # Create or get ExternalAnimeTitle instance anime_title_instance, _ = ExternalAnimeTitle.objects.get_or_create(title=anime_title) # Create or get ExternalUser instance user, _ = ExternalUser.objects.get_or_create(username=username) # Create ExternalReview instance and save to database review = ExternalReview.objects.create( source=source, external_title=anime_title_instance, review_text=content, external_user=user, created_at=created_at # use the time from the external source ) else: print("Failed to retrieve data. Status code:", response.status_code)
import React, { useState } from "react"; import { AppBar, Typography, Toolbar, Box, Button, Tabs, Tab, useMediaQuery, useTheme, Drawer, } from "@mui/material"; import { Link } from "react-router-dom"; import { useDispatch, useSelector } from "react-redux"; import { useStyles } from "./utils"; import { authActions } from "../store"; import DrawerComp from "./women/Drawer"; const Header = () => { const [value1, setvalue1] = useState() const classes = useStyles(); const dispath = useDispatch(); const isLoggedIn = useSelector((state) => state.isLoggedIn); const [value, setValue] = useState(); const theam = useTheme() const isMatch = useMediaQuery(theam.breakpoints.down("md")) return ( <AppBar position="sticky" sx={{ background: " radial-gradient(circle, rgba(234,234,234,1) 0%, rgba(26,246,255,1) 36%, rgba(147,204,236,1) 56%, rgba(224,224,224,1) 73%, rgba(217,255,251,1) 84%)", }} > <Toolbar> <Typography> </Typography> { isMatch ? <> {isLoggedIn && <Box display="flex" marginLeft={2} marginRight={2}> <Tabs textColor="secondary" value={value} onChange={(e, val) => setValue(val)} > <Tab className={classes.font} LinkComponent={Link} to="/blogs" label="All Complaints" /> <Tab className={classes.font} LinkComponent={Link} to="/myBlogs" label="My Complaints" /> <Tab className={classes.font} LinkComponent={Link} to="/blogs/add" label="Add Complaints" /> </Tabs> </Box> } <DrawerComp /> </> : ( <> { (!isLoggedIn) && <Box display="flex" marginLeft={'auto'}> <Tabs value={value1} onChange={(e, val) => setvalue1(val)}> <Tab label="Home" to="/home" component={Link} /> <Tab label="Laws" to="/laws" component={Link} /> <Tab label="Helpline" to="/Helpline" component={Link} /> <Tab label="SaftyTips" to="/Saftytips" component={Link} /> <Tab label="AboutUs" to="/Aboutus" component={Link} /> <Tab label="News_and_Notifications" to="/news" component={Link} /> </Tabs> </Box> } {isLoggedIn && <Box display="flex" marginLeft={"auto"} marginRight="auto"> <Tabs textColor="primary" value={value} onChange={(e, val) => setValue(val)} > { <Tab className={classes.font} LinkComponent={Link} to="/Complaints" label="All Complaints" /> } <Tab className={classes.font} LinkComponent={Link} to="/myBlogs" label="My Complaints" /> <Tab className={classes.font} LinkComponent={Link} to="/blogs/add" label="Add Complaints" /> </Tabs> </Box> } <Box display="flex" marginLeft="auto"> {!isLoggedIn && ( <> {" "} <Button LinkComponent={Link} to="/auth" variant="contained" sx={{ margin: 1, borderRadius: 10 }} color="warning" > Login </Button> <Button LinkComponent={Link} to="/DoDoComplaint" variant="contained" sx={{ margin: 1 }} color="primary">Add-Complaint</Button> </> )} {isLoggedIn && ( <Button onClick={() => dispath(authActions.logout())} LinkComponent={Link} to="/auth" variant="contained" sx={{ margin: 1, borderRadius: 10 }} color="warning" > Logout </Button> )} </Box> </> ) } </Toolbar> </AppBar> ); }; export default Header;
import utils from '../../support/utils.js'; const config = require('../../../config.json'); const pageControllers = require('../../pages/pageControllers.js'); Cypress.on('uncaught:exception', (err, runnable) => { return false; }); // Iterate over each viewport configuration Object.entries(config.viewPorts).forEach(([viewportName, viewportSetting]) => { // Run Cypress tests with the current viewport settings describe(`Validate pricing and performance page - ${viewportName}`, () => { beforeEach(() => { cy.visit(config.environments.baseURL + "/" + config.environments.prospectusesFundDocumentsPage); if (viewportSetting.includes(':')) { // Custom viewport size specified const [width, height] = viewportSetting.split(',').map(value => parseInt(value.split(':')[1].trim())); cy.viewport(width, height); } else { // Predefined device name cy.viewport(viewportSetting); } }); describe('Validate prospectuses Fund and Documents page', () => { it('Validate all prospectuses Fund and Documents links ', () => { // Find all rows in the table cy.xpath('//table/tbody/tr').each(($row) => { // Find the first link in the current row const link = $row.find('td:first-of-type a'); // Check if the link exists in the row if (link.length > 0) { // Capture the text of the link const linkText = link.text(); cy.xpath(`//a[text() = "${linkText}"]`).click(); cy.wait(2000); cy.xpath('//h1').invoke('text').then(headerText => { // Check if any link text contains '*' const containsAsterisk = headerText.includes('*'); // If no link text contains '*', assert that it's not present if (!containsAsterisk) { cy.xpath('//h1').invoke('text').should('eq', link.text()); cy.log("No link text contains '*'"); } else { // If at least one link text contains '*', assert its presence cy.log("At least one link text contains '*'"); cy.xpath('//h1').invoke('text').should('eq', link.text() + '*'); } }); //cy.go('back'); cy.window().then((win) => { win.history.back(); }); } }); }); }); }); });
/* * Copyright 2022 AERIS IT Solutions GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.qalipsis.api.events import assertk.all import assertk.assertThat import assertk.assertions.hasSize import assertk.assertions.index import assertk.assertions.isEqualTo import assertk.assertions.prop import io.qalipsis.test.coroutines.TestDispatcherProvider import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.extension.RegisterExtension import java.time.Duration import java.time.Instant import java.util.LinkedList import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicInteger @Timeout(30) internal class AbstractBufferedEventsPublisherTest { @JvmField @RegisterExtension val testCoroutineDispatcher = TestDispatcherProvider() @Test fun `should not log when logger level is OFF`() = testCoroutineDispatcher.runTest { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.OFF, Duration.ofMillis(500), batchSize = 1000) publisher.publish(Event(EVENT_NAME, EventLevel.TRACE)) publisher.publish(Event(EVENT_NAME, EventLevel.DEBUG)) publisher.publish(Event(EVENT_NAME, EventLevel.INFO)) publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) publisher.publish(Event(EVENT_NAME, EventLevel.ERROR)) Assertions.assertTrue(publisher.bufferedData.isEmpty()) } @Test fun `should log all when logger level is TRACE`() = testCoroutineDispatcher.runTest { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.TRACE, Duration.ofMillis(500), batchSize = 1000) publisher.publish(Event(EVENT_NAME, EventLevel.TRACE)) publisher.publish(Event(EVENT_NAME, EventLevel.DEBUG)) publisher.publish(Event(EVENT_NAME, EventLevel.INFO)) publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) publisher.publish(Event(EVENT_NAME, EventLevel.ERROR)) assertThat(publisher.bufferedData).all { hasSize(5) index(0).prop(Event::level).isEqualTo(EventLevel.TRACE) index(1).prop(Event::level).isEqualTo(EventLevel.DEBUG) index(2).prop(Event::level).isEqualTo(EventLevel.INFO) index(3).prop(Event::level).isEqualTo(EventLevel.WARN) index(4).prop(Event::level).isEqualTo(EventLevel.ERROR) } } @Test fun `should log from DEBUG when logger level is DEBUG`() = testCoroutineDispatcher.runTest { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.DEBUG, Duration.ofMillis(500), batchSize = 1000) publisher.publish(Event(EVENT_NAME, EventLevel.TRACE)) publisher.publish(Event(EVENT_NAME, EventLevel.DEBUG)) publisher.publish(Event(EVENT_NAME, EventLevel.INFO)) publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) publisher.publish(Event(EVENT_NAME, EventLevel.ERROR)) assertThat(publisher.bufferedData).all { hasSize(4) index(0).prop(Event::level).isEqualTo(EventLevel.DEBUG) index(1).prop(Event::level).isEqualTo(EventLevel.INFO) index(2).prop(Event::level).isEqualTo(EventLevel.WARN) index(3).prop(Event::level).isEqualTo(EventLevel.ERROR) } } @Test fun `should log from INFO when logger level is INFO`() = testCoroutineDispatcher.runTest { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.INFO, Duration.ofMillis(500), batchSize = 1000) publisher.publish(Event(EVENT_NAME, EventLevel.TRACE)) publisher.publish(Event(EVENT_NAME, EventLevel.DEBUG)) publisher.publish(Event(EVENT_NAME, EventLevel.INFO)) publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) publisher.publish(Event(EVENT_NAME, EventLevel.ERROR)) assertThat(publisher.bufferedData).all { hasSize(3) index(0).prop(Event::level).isEqualTo(EventLevel.INFO) index(1).prop(Event::level).isEqualTo(EventLevel.WARN) index(2).prop(Event::level).isEqualTo(EventLevel.ERROR) } } @Test fun `should log from WARN when logger level is WARN`() = testCoroutineDispatcher.runTest { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.WARN, Duration.ofMillis(500), batchSize = 1000) publisher.publish(Event(EVENT_NAME, EventLevel.TRACE)) publisher.publish(Event(EVENT_NAME, EventLevel.DEBUG)) publisher.publish(Event(EVENT_NAME, EventLevel.INFO)) publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) publisher.publish(Event(EVENT_NAME, EventLevel.ERROR)) assertThat(publisher.bufferedData).all { hasSize(2) index(0).prop(Event::level).isEqualTo(EventLevel.WARN) index(1).prop(Event::level).isEqualTo(EventLevel.ERROR) } } @Test fun `should log only ERROR when logger level is ERROR`() = testCoroutineDispatcher.runTest { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.ERROR, Duration.ofMillis(500), batchSize = 1000) publisher.publish(Event(EVENT_NAME, EventLevel.TRACE)) publisher.publish(Event(EVENT_NAME, EventLevel.DEBUG)) publisher.publish(Event(EVENT_NAME, EventLevel.INFO)) publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) publisher.publish(Event(EVENT_NAME, EventLevel.ERROR)) assertThat(publisher.bufferedData).all { hasSize(1) index(0).prop(Event::level).isEqualTo(EventLevel.ERROR) } } @Test @Timeout(5) fun `should publish when buffer is full`() = testCoroutineDispatcher.run { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.INFO, Duration.ofMinutes(10), 10, 2) publisher.start() repeat(25) { publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) } publisher.publicationCountDownLatch.await() assertEquals(2, publisher.executionTimes.size) assertEquals(20, publisher.publishedCount.get()) } @Test @Timeout(5) fun `should publish when linger time is over`() = testCoroutineDispatcher.run { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.INFO, Duration.ofMillis(400), 100, 2) publisher.start() repeat(3) { delay(300) publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) } publisher.publicationCountDownLatch.await() assertEquals(2, publisher.executionTimes.size) assertEquals(2, publisher.publishedCount.get()) } @Test @Timeout(5) fun `should log even when logs are faster than publish`() = testCoroutineDispatcher.run { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.INFO, Duration.ofMinutes(1), 1, 30) { Thread.sleep(30) } publisher.start() repeat(30) { publisher.publish(Event(EVENT_NAME, EventLevel.ERROR)) } publisher.publicationCountDownLatch.await() assertEquals(30, publisher.executionTimes.size) assertEquals(30, publisher.publishedCount.get()) } @Test @Timeout(1) fun `should support concurrent logs`() = testCoroutineDispatcher.run { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.INFO, Duration.ofMinutes(1), 1000) publisher.start() val job1 = launch { repeat(300) { publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) } } val job2 = launch { repeat(300) { publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) } } repeat(300) { publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) } job1.join() job2.join() assertEquals(900, publisher.bufferedData.size) } @Test @Timeout(5) fun `stopping the logger should force publish`() = testCoroutineDispatcher.runTest { val publisher = TestAbstractBufferedEventsPublisher(this, EventLevel.INFO, Duration.ofMinutes(1), 100, 1) publisher.start() publisher.publish(Event(EVENT_NAME, EventLevel.WARN)) publisher.stop() publisher.publicationCountDownLatch.await() assertEquals(1, publisher.executionTimes.size) assertEquals(1, publisher.publishedCount.get()) } companion object { const val EVENT_NAME = "event-name" } class TestAbstractBufferedEventsPublisher( coroutineScope: CoroutineScope, loggableLevel: EventLevel, lingerDuration: Duration, batchSize: Int, expectedPublications: Int = Int.MAX_VALUE, private val doOnPublish: (() -> Unit) = {} ) : AbstractBufferedEventsPublisher(loggableLevel, lingerDuration, batchSize, coroutineScope) { val executionTimes = mutableListOf<Instant>() val publicationCountDownLatch = CountDownLatch(expectedPublications) val bufferedData: LinkedList<Event> get() = LinkedList(buffer) val publishedCount = AtomicInteger() override suspend fun publish(values: List<Event>) { doOnPublish() publishedCount.addAndGet(values.size) executionTimes.add(Instant.now()) publicationCountDownLatch.countDown() } } }
import 'package:flutter/material.dart'; import 'package:todoapp/quiz_app/constants.dart'; import 'package:todoapp/quiz_app/model/questions_model.dart'; import 'package:todoapp/quiz_app/quiz_res.dart'; class QuizQuestionScreen extends StatefulWidget { const QuizQuestionScreen({super.key}); @override State<QuizQuestionScreen> createState() => _QuizQuestionScreenState(); } class _QuizQuestionScreenState extends State<QuizQuestionScreen> { var pageController = PageController(initialPage: 0); bool isPressed = false; Color trueAns = Colors.green; Color wrongAns = Colors.red; Color btnColor = secondColor; int score = 0; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: mainColor, appBar: AppBar( backgroundColor: const Color.fromARGB(255, 41, 44, 81), elevation: 40, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50)), ), bottom: PreferredSize( preferredSize: const Size.fromHeight(60), child: Padding( padding: const EdgeInsets.only(bottom: 28.0), child: Text( 'QUIZ QUESTIONS', style: Theme.of(context).textTheme.headline5!.copyWith( color: Colors.white, ), ), ), ), ), body: Padding( padding: const EdgeInsets.all(15), child: PageView.builder( controller: pageController, onPageChanged: (page) { setState(() { isPressed = false; btnColor = secondColor; }); }, itemCount: ques1.length, itemBuilder: (context, index) => Column( children: [ Text( 'Question ${index + 1} / ${ques1.length}', style: Theme.of(context).textTheme.headline4!.copyWith( color: Colors.white, ), ), const Divider( color: Colors.white, height: 10, thickness: 1, ), const SizedBox( height: 20, ), Text( ques1[index].question, style: Theme.of(context).textTheme.headline4!.copyWith( color: Colors.white, ), ), const SizedBox( height: 20, ), for (int i = 0; i < 4; i++) Container( width: double.infinity, margin: const EdgeInsets.only(bottom: 20), padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: //btnColor, isPressed ? ques1[index].answers.entries.toList()[i].value ? trueAns : wrongAns : secondColor, borderRadius: BorderRadius.circular(20)), child: MaterialButton( onPressed: () { setState(() { isPressed = true; if (ques1[index].answers.entries.toList()[i].value) { btnColor = trueAns; score += 10; } else { btnColor = wrongAns; } }); }, shape: const StadiumBorder(), child: Text( ques1[index].answers.keys.toList()[i], style: Theme.of(context).textTheme.bodyText1!.copyWith( color: Colors.white, fontWeight: FontWeight.w500, fontSize: 20, ), ), ), ), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ OutlinedButton( style: OutlinedButton.styleFrom( shape: const StadiumBorder(), side: const BorderSide(color: Colors.orange)), onPressed: () { if (index + 1 != ques1.length) { pageController.nextPage( duration: const Duration(microseconds: 500), curve: Curves.linear, ); setState(() { isPressed = false; }); } else { Navigator.pushReplacement( context, MaterialPageRoute( builder: (_) => QuizResult(score: score), ), ); } }, child: Text( index + 1 == ques1.length ? 'See Result' : 'Next Question', style: Theme.of(context).textTheme.headline5!.copyWith( color: Colors.white, ), ), ), ], ) ], ), ), ), ); } }
const express = require("express"); const expressAsyncHandler = require("express-async-handler"); const statusRouter = express.Router(); const statusServices = require("../services/statusServices"); const projectServices = require("../services/projectServices"); statusRouter.post( "/", expressAsyncHandler(async (req, res) => { const { status } = req.body; if (!status) { res.status(400).send({ msg: "Field Missing", }); }else{ const result = await statusServices.addNew(status); if (result) { res.status(200).send({ msg: "status Added", data: result, }); } else { res.status(400).send({ msg: "status Not Added", }); } } }) ); statusRouter.put( "/", expressAsyncHandler(async (req, res) => { const { statusId,status } = req.body; if (!status||!statusId) { res.status(400).send({ msg: "Field Missing", }); } else { const result = await statusServices.update(statusId, status); if (result) { res.status(200).send({ msg: "status updated", data: result, }); } else { res.status(400).send({ msg: "status Not updated", }); } } }) ); statusRouter.get( "/all", expressAsyncHandler(async (req, res) => { const result = await statusServices.get(); if (result.length != 0) { res.status(200).send({ msg: "status List", data: result, }); } else { res.status(400).send({ msg: "status Not Found", }); } }) ); statusRouter.get( "/getOne", expressAsyncHandler(async (req, res) => { const {statusId}=req.query const result = await statusServices.getOne(statusId); if (result) { res.status(200).send({ msg: "status Details", data: result, }); } else { res.status(400).send({ msg: "status Not Found", }); } }) ); statusRouter.delete( "/", expressAsyncHandler(async (req, res) => { const { statusId } = req.query; const isUse=await projectServices.isUse(statusId); if(isUse){ return res.status(400).send({ msg:"This status use for a project!" }) } const result = await statusServices.delete(statusId); if(result.deletedCount===0){ res.status(404).send({ msg: "Not Found!", }); } if (result) { res.status(200).send({ msg: "status deleted", }); return; } else { res.status(400).send({ msg: "status Not deleted", }); return; } }) ); module.exports = statusRouter;
// This file is part of Moonfire NVR, a security camera network video recorder. // Copyright (C) 2021 The Moonfire NVR Authors; see AUTHORS and LICENSE.txt. // SPDX-License-Identifier: GPL-v3.0-or-later WITH GPL-3.0-linking-exception import Avatar from "@mui/material/Avatar"; import Container from "@mui/material/Container"; import BugReportIcon from "@mui/icons-material/BugReport"; import React from "react"; interface State { error: any; } interface Props { children: React.ReactNode; } /** * A simple <a href="https://reactjs.org/docs/error-boundaries.html">error * boundary</a> meant to go at the top level. * * The assumption is that any error here is a bug in the UI layer. Components * shouldn't throw errors upward even if there are network or server problems. * * Limitations: as described in the React docs, error boundaries don't catch * errors in async code / rejected Promises. */ class MoonfireErrorBoundary extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { error: null }; } static getDerivedStateFromError(error: any) { return { error }; } componentDidCatch(error: any, errorInfo: React.ErrorInfo) { console.error("Uncaught error:", error, errorInfo); } render() { const { children } = this.props; if (this.state.error !== null) { var error; if (this.state.error.stack !== undefined) { error = <pre>{this.state.error.stack}</pre>; } else if (this.state.error instanceof Error) { error = ( <> <pre>{this.state.error.name}</pre> <pre>{this.state.error.message}</pre> </> ); } else { error = <pre>{this.state.error}</pre>; } return ( <Container> <Avatar sx={{ float: "left", bgcolor: "secondary.main", marginRight: "1em", }} > <BugReportIcon color="primary" /> </Avatar> <h1>Error</h1> <p> Sorry! You've found a bug in Moonfire NVR. We need a good bug report to get it fixed. Can you help? </p> <h2>How to report a bug</h2> <p> Please open{" "} <a href="https://github.com/scottlamb/moonfire-nvr/issues"> Moonfire NVR's issue tracker </a>{" "} and see if this problem has already been reported. </p> <h3>Can't find anything?</h3> <p>Open a new issue with as much detail as you can:</p> <ul> <li>the version of Moonfire NVR you're using</li> <li> your environment, including: <ul> <li>web browser: Chrome, Firefox, Safari, etc.</li> <li>platform: macOS, Windows, Linux, Android, iOS, etc.</li> <li>browser extensions</li> <li>anything special about your Moonfire NVR setup</li> </ul> </li> <li>all the errors you see in your browser's Javascript console</li> <li>steps to reproduce, if possible</li> </ul> <h3>Already reported?</h3> <ul> <li>+1 the issue so we know more people are affected.</li> <li>add any new details you've noticed.</li> </ul> <h2>The error</h2> {error} </Container> ); } return children; } } export default MoonfireErrorBoundary;
import swr from 'hooks/swr' import Head from 'next/head' import Image from 'next/image' import { Transition, Dialog } from '@headlessui/react' import { Fragment, useEffect } from 'react' import config from '../../site.config.js' import { useRouter } from 'next/router' import Link from 'next/link' import { useState } from 'react' import { motion, MotionConfigContext } from "framer-motion" export default function Home() { const router = useRouter() const statsArray = [ { label: "Total Bots Created", value: "80+", icon: "fas fa-server" }, { label: "Total Nodes", value: "1+", icon: "fas fa-users" }, { label: "Users", value: "100+", icon: "fas fa-comments" }, ] const chooseArray = [ { number: "1.", label: "Free Source Codes", value: "We Provide Free Source Codes of Discord bots(open source)." }, { number: "2.", label: "Free Bots", value: "We Provide Free Bots with many commands Hosted Manually on our Private Hosting Panel!" }, { number: "3.", label: "Good Bots Ping ", value: "We are Actually Providing Hosted with good Pings (20-30-40 ms)" }, ] const chooseArray2 = [ { number: "4.", label: "Support Team", value: "We have a great support team that will help you with any problem you have!" }, { number: "5.", label: "Paid Bots too", value: "We Also Provide Paid Cheap Bots" }, { number: "6.", label: "Fast Support", value: "We have a very fast support team that will help you with any problem you have!" }, ] return ( <> <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.5 }} > <div className="flex flex-col items-center"> <Head> <title>{config.siteMetadata.title}</title> <link rel="icon" href={config.siteMetadata.favicon} type="image/x-icon" /> </Head> <main className="flex flex-col items-center justify-center text-center"> <div className="h-[33rem] flex flex-col justify-center items-center mb-72"> <h1 className="relative text-4xl lg:text-5xl text-black dark:text-white pb-2 leading-20 font-semibold">Welcome To <span class="text-primary">Custom Bot Hub Studios</span></h1> <p className="text-lg text-gray-500 font-bold">Join Custom Bot Hub Studios For Free and Paid Bots</p> <div className="flex justify-center w-full mt-6"> <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} className="mt-4" > <Link href={`/services`} locale="en"> <a className="w-auto flex items-center justify-center shadow-2xl gap-x-2 shadow-primary/20 rounded-xl py-3.5 font-bold px-8 bg-gradient-to-tl from-primary/50 to-primary text-white hover:opacity-80 transition duration-200"> <span className="text-1xl font-bold button button-text">Our Services</span> </a> </Link> </motion.div> <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} className="mr-4 ml-4 mt-4" > <Link href={`/pricing`} locale="en"> <a className="w-auto flex items-center justify-center shadow-2xl gap-x-2 shadow-primary/20 rounded-xl py-3.5 font-bold px-8 bg-gradient-to-tl from-primary/50 to-primary text-white hover:opacity-80 transition duration-200"> <span className="text-1xl font-bold button button-text">Pricing</span> </a> </Link> </motion.div> </div> </div> <div className="mb-40 max-w-3xl mx-auto"> <div className="flex flex-col justify-center items-center w-full"> <h1 className="text-4xl font-bold text-black dark:text-white">Why <span className="text-primary">Choose Us?</span></h1> <p className="text-lg text-gray-500 font-bold">We deliver high quality Discord Bots for FREE and Paid with a great support team!</p> <div className="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-60 mt-5 py-6"> {chooseArray.map((stat, index) => ( <div className="flex flex-col items-center"> <motion.div whileHover={{ scale: 1.05 }} > <div className="lg:h-30 w-80 bg-gradient-to-br from-primary/10 to-primary-dark rounded-lg p-6 shadow-lg"> <h1 className="text-4xl font-bold text-black dark:text-white absolute">{stat.number}</h1> <div className="mt-16"> <h2 className="text-2xl font-bold text-black dark:text-white mt-4">{stat.label}</h2> <p className="text-lg text-gray-500 font-bold mt-4">{stat.value}</p> </div> </div> </motion.div> </div> ))} </div> <div className="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-60 py-6"> {chooseArray2.map((stat, index) => ( <div className="flex flex-col items-center"> <motion.div whileHover={{ scale: 1.05 }} > <div className="lg:h-30 w-80 bg-gradient-to-br from-primary/10 to-primary-dark rounded-lg p-6 shadow-lg"> <h1 className="text-4xl font-bold text-black dark:text-white absolute">{stat.number}</h1> <div className="mt-16"> <h2 className="text-2xl font-bold text-black dark:text-white mt-4">{stat.label}</h2> <p className="text-lg text-gray-500 font-bold mt-4">{stat.value}</p> </div> </div> </motion.div> </div> ))} </div> </div> </div> <div className="py-20 max-w-3xl mx-auto"> <div className="flex flex-col justify-center items-center w-full"> <h1 className="text-4xl text-black dark:text-white pb-2 font-semibold">Some of our <span className="text-primary">Stats</span></h1> <p className="text-lg text-gray-500 font-bold">Here you can see some of our stats!</p> <div className="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-60 mt-5 py-6"> {statsArray.map((stat, index) => ( <div className="flex flex-col items-center"> <motion.div whileHover={{ scale: 1.05 }} > <div className="lg:h-30 w-80 bg-gradient-to-br from-primary/10 to-primary-dark rounded-lg p-6 shadow-lg"> <i className={`${stat.icon} text-4xl text-primary`}></i> <h1 className="text-2xl font-bold text-black dark:text-white mt-4">{stat.value}</h1> <p className="text-lg text-gray-500 font-bold">{stat.label}</p> </div> </motion.div> </div> ))} </div> </div> </div> </main> </div> </motion.div> </> ) }
import React, { useState } from "react"; import Image from "next/image"; interface Props { src?: string; alt?: string; title?: string; className?: string; maxWidth?: number; maxHeight?: number; layout?: "fixed" | "fill" | "intrinsic" | "responsive"; objectFit?: "contain" | "cover" | "fill" | "none" | "scale-down"; objectPosition?: string; priority?: false | true; loading?: "lazy" | "eager"; quality?: number; style?: any; sizes?: string; fill?: any; } const SImage = (props: Props) => { const { src = "", alt = "", title = "", maxWidth = 0, maxHeight = 0, className = "", layout = undefined, objectFit = undefined, objectPosition = undefined, priority = false, loading = "lazy", quality = 75, } = props; const [imgSrc, setImgSrc] = useState(src); const fallbackImage = `https://via.placeholder.com/${maxWidth}x${maxHeight}`; return layout ? ( <Image src={imgSrc || fallbackImage} alt={alt} title={title} layout={layout} width={layout !== "fill" ? maxWidth : undefined} height={layout !== "fill" ? maxHeight : undefined} objectFit={objectFit} objectPosition={objectPosition} priority={priority} loading={loading} quality={quality} onError={() => { setImgSrc(fallbackImage); }} /> ) : ( <img src={src || fallbackImage} alt={alt} title={title} className={className} /> ); }; export default SImage;
using Garage_HomeWork_16.DAL; using Garage_HomeWork_16.Helpers; using Garage_HomeWork_16.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace Garage_HomeWork_16.Areas.Admin.Controllers { [Area("Admin")] public class TeamController : Controller { private readonly AppDbContext _dbContext; private readonly IWebHostEnvironment _hostEnvironment; private readonly IFileService _fileService; public TeamController(AppDbContext dbContext, IWebHostEnvironment hostEnvironment, IFileService fileService) { _dbContext = dbContext; _hostEnvironment = hostEnvironment; _fileService = fileService; } public async Task<IActionResult> Index() { var members = await _dbContext.TeamMembers.ToListAsync(); return View(members); } #region Create [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public async Task<IActionResult> Create(TeamMember member) { if (!ModelState.IsValid) return View(member); if (!_fileService.IsImage(member.Photo)) { ModelState.AddModelError("Photo", "File Image Formatinda olmalidir"); return View(member); } int maxSize = 60; if (!_fileService.CheckSize(member.Photo,maxSize)) { ModelState.AddModelError("Photo", $"Image Size {maxSize} kb dan coxdur"); return View(member); } member.PhotoName = await _fileService.UploadAsync(member.Photo); await _dbContext.AddAsync(member); await _dbContext.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } #endregion #region Delete [HttpPost] public async Task<IActionResult> Delete(int id) { var deletedMember = await _dbContext.TeamMembers.FirstOrDefaultAsync(c => c.Id == id); var imagePath = Path.Combine(_hostEnvironment.WebRootPath, "assets/img", deletedMember?.PhotoName!); _dbContext.TeamMembers.Remove(deletedMember!); await _dbContext.SaveChangesAsync(); _fileService.DeleteFile(imagePath); return RedirectToAction(nameof(Index)); } #endregion #region Edit [HttpGet] public async Task<IActionResult> Edit(int id) { var updatedMember = await _dbContext.TeamMembers.FirstOrDefaultAsync(c => c.Id == id); if (updatedMember == null) return NotFound(); return View(updatedMember); } [HttpPost] public async Task<IActionResult> Edit(TeamMember member) { if (member.Photo == null) { ModelState.Remove("Photo"); } if (!ModelState.IsValid) { return View(member); } if (member.Photo != null) { if (!_fileService.IsImage(member.Photo)) { ModelState.AddModelError("Photo", "File Image Formatinda olmalidir"); return View(member); } int maxsize = 60; if (!_fileService.CheckSize(member.Photo,maxsize)) { ModelState.AddModelError("Photo", $"Image Size {maxsize} kb dan coxdur"); return View(member); } string filePath = Path.Combine(_hostEnvironment.WebRootPath, "assets/img", member.PhotoName); _fileService.DeleteFile(filePath); member.PhotoName= await _fileService.UploadAsync(member.Photo); } _dbContext.TeamMembers.Update(member); await _dbContext.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } #endregion } }
import React, { useState } from 'react'; import { Flex, Box, Image, Text } from '@chakra-ui/react'; import { AddIcon, CheckIcon } from '@chakra-ui/icons'; const UserCard = ({ name, email, profilePic, addNewFriend, }) => { const [isInvited, setIsInvited] = useState(false); const handleAdd = () => { if (!isInvited) { // add friend's email to current user's friend array addNewFriend(email); } }; return ( <Flex borderWidth="1px" alignItems="center" p="1rem" borderRadius="12px" mb=".5rem" > <Image src={profilePic || 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'} alt="" borderRadius="full" w="64px" h="64px" mr="0.5rem" border="1px solid" borderColor="gray.300" /> <Flex pos="relative" flexDir="column" width="100%"> <Text pos="absolute" bottom="0px" right="12px"> ... </Text> <Flex pos="absolute" top="10%" right="6px" h="24px" w="24px" borderRadius="full" border="black 2px solid" alignContent="center" _hover={{ cursor: 'pointer', transform: 'scale(1.1)'}} onClick={handleAdd} > {isInvited ? <CheckIcon m="auto" /> : <AddIcon m="auto" />} </Flex> <Text as="b" alignSelf="start"> {name} </Text> <Text alignSelf="start">{`@${email}`}</Text> </Flex> </Flex> ); }; export default UserCard;
<!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Fonts --> <link rel="dns-prefetch" href="//fonts.gstatic.com"> <link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link href='https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css' rel='stylesheet'> <!-- Scripts --> @vite(['resources/sass/app.scss', 'resources/js/app.js']) @vite(['resources/css/app.css']) </head> <body> <!-- Menu --> <nav class="sidebar close"> <header> <div class="image-text"> <span class="image"> <img src="https://upload.wikimedia.org/wikipedia/fr/2/2c/Grappler_Baki_anime_logo_ja.png" alt=""> </span> <div class="text logo-text"> <span class="name">Ani Day</span> <span class="surum">Beta 1.2</span> </div> </div> </header> <div class="menu-bar"> <div class="menu"> <li class="search-box"> <i class='bx bx-search icon'></i> <input type="text" placeholder="Search..."> </li> <ul class="menu-links"> <li class="nav-link"> <a href="/"> <i class='bx bx-home-alt icon' ></i> <span class="text nav-text">Home</span> </a> </li> <li class="nav-link"> <a href="/episode"> <i class='bx bx-tv icon'></i> <span class="text nav-text">Series</span> </a> </li> <li class="nav-link"> <a href="/dashboard"> <i class='bx bx-group icon' ></i> <span class="text nav-text">Teams</span> </a> </li> <li class="nav-link"> <a href="#"> <i class='bx bx-help-circle icon' ></i> <span class="text nav-text">About-us</span> </a> </li> <li class="nav-link"> <a href="#"> <i class='bx bxl-discord-alt icon' ></i> <span class="text nav-text">Discord</span> </a> </li> </ul> </div> @if (session('logged_in')) <div class="bottom-content"> <li class=""> <a href="{{ route('signout')}}"> <i class='bx bx-log-out icon' ></i> <span class="text nav-text">Log-out</span> </a> </li> @else <div class="bottom-content"> <li class=""> <a href="/login"> <i class='bx bx-log-in icon' ></i> <span class="text nav-text">Log-out</span> </a> </li> @endif @if (session('logged_in')) <li class=""> <a href="#"> <i class='bx bxl-flickr icon'></i> <span class="text nav-text">Setting</span> </a> </li> @endif </div> </div> </nav> <section class="home"> <div class="content"> @yield('content') </div> </section> </div> <script> $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); function Watched(anime_id, user_id) { $.ajax({ type: "POST", url: '/anime/watched', data: { anime_id: anime_id, user_id: user_id }, success: function(response) { console.log(response); $('.watched-button[data-anime-id="'+anime_id+'"] img').attr('src', 'storage/images/ok.png'); $('.watched-button[data-anime-id="'+anime_id+'"]').attr('onclick', 'RemoveWatch(' + anime_id + ',' + user_id + ')'); }, error: function(error) { console.log(error); } })}; function changeImageNotLogin(event) { var button = event.target; if (button.src.match("plus")) { button.src = "storage/images/ok.png"; } else { button.src = "storage/images/plus.png"; } } function RemoveWatch(anime_id, user_id) { $.ajax({ type: "DELETE", url: '/anime/watched/delete/' + anime_id, data: { anime_id: anime_id, user_id: user_id }, success: function(response) { console.log(response); // En enleve dans le dom $('.watched-button[data-anime-id="'+anime_id+'"] img').attr('src', 'storage/images/plus.png'); $('.watched-button[data-anime-id="'+anime_id+'"]').attr('onclick', 'changeImage(' + anime_id + ',' + user_id + ')'); }, error: function(error) { console.log(error); } }); } function RemoveWatchFromDashboard(anime_id) { $.ajax({ type: "DELETE", url: '/anime/watched/delete/' + anime_id, data: { _token: '{{ csrf_token() }}' }, success: function(response) { console.log(response); // $("figure").remove('.snip1578[data-anime-id="'+anime_id+'"]'); }, error: function(error) { console.log(error); } }); } </script> </body> </html>
### 解题思路 暴力+剪枝,开5个[N+2][N+2]大的数组。 一个用来初始化数组。 另外四个用来统计该点上下左右1的大小 left[i][j]=board[i][j]==1?(1+left[i][j-1]):0; // 左 right[i][N-j+1]=board[i][N-j+1]==1?(1+right[i][N-j+2]):0;// 右 top[j][i]=board[j][i]==1?(1+top[j-1][i]):0; // 上 bottom[N-j+1][i]=board[N-j+1][i]==1?(1+bottom[N-j+2][i]):0; // 右 具体见代码 思路并不难 ### 代码 ```java class Solution { // 764. 最大加号标志 public int orderOfLargestPlusSign(int N, int[][] mines) { int[][] board = new int[N+2][N+2]; for(int i = 1 ; i <= N ; i++){ Arrays.fill(board[i], 1); } int[][] left = new int[N+2][N+2]; // 记录 left[i][j]为从i,j开始左面连续1的个数 int[][] right = new int[N+2][N+2]; // 记录right[i][j]为从i,j开始右面连续1的个数 int[][] top = new int[N+2][N+2]; int[][] bottom = new int[N+2][N+2]; for(int i = 0 ; i < mines.length;i++){ board[mines[i][0]+1][mines[i][1]+1]=0; } for(int i = 0 ; i < N+2 ; i++){ board[i][0]=board[i][N+1]=0; } // for(int i = 0 ; i < board.length ; i++){ // for(int j = 0 ; j < board[0].length ; j++) // System.out.print(board[i][j]+" "); // System.out.println(); // } for(int i = 1 ; i <= N ; i++){ for(int j = 1 ; j <= N ; j++){ left[i][j]=board[i][j]==1?(1+left[i][j-1]):0; // 左 right[i][N-j+1]=board[i][N-j+1]==1?(1+right[i][N-j+2]):0;// 右 top[j][i]=board[j][i]==1?(1+top[j-1][i]):0; // 上 bottom[N-j+1][i]=board[N-j+1][i]==1?(1+bottom[N-j+2][i]):0; // 右 } } int res = 0; for(int i = 1; i <= N ; i++){ for(int j = 1 ; j <=N ; j++){ if(left[i][j]>res && right[i][j]>res && top[i][j]>res && bottom[i][j]>res){ res=Math.min(Math.min(left[i][j], right[i][j]),Math.min(top[i][j], bottom[i][j]) ); } } } return res; } } ```
package com.rutsubosuki.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.servlet.PathRequest; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.UserDetailsManager; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserDetailsManager userDetailsManager; @Autowired PasswordEncoder passwordEncoder; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // UserDetailServiceとPasswordEncorderを指定 auth.userDetailsService(userDetailsManager).passwordEncoder(passwordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { // Configure a new SecurityChainFilter. http.authorizeRequests() .antMatchers("/").permitAll()//permitAll ->loginなしでアクセス可 .antMatchers("/*").permitAll() .antMatchers("/login*").permitAll() .antMatchers("/logout").permitAll() .antMatchers("/signup").permitAll() .antMatchers("/register").permitAll() .antMatchers("/article").permitAll() //記事一覧用 .antMatchers("/article/*").permitAll() .antMatchers("/tag").permitAll() .antMatchers("/tag/*").permitAll() .antMatchers("/image").permitAll() .antMatchers("/image/*").permitAll() .antMatchers("/upload").permitAll() .antMatchers("/upload/*").permitAll() .antMatchers("/index").permitAll() .antMatchers("/imageupload").permitAll() .anyRequest().authenticated(); http.formLogin() .loginPage("/login") .usernameParameter("username") .passwordParameter("password") .successForwardUrl("/") .failureForwardUrl("/login-fail?error") .permitAll(); http.logout() .logoutSuccessUrl("/") .permitAll(); //4.認証設定の追加 } @Override public void configure(WebSecurity web) throws Exception { // Configure a new SecurityChainFilter web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations()); } }
import React, { useCallback, useRef } from "react"; import { tooltip } from "./index"; import { TooltipProps } from "@react-elf-types/tooltip"; export function FixedTooltip({ children, message, ...tooltipProps }: TooltipProps) { const tooltipRef = useRef(null); const onMouseEnter = useCallback( (e) => { const target = e.target; const labelRect = target.getBoundingClientRect(); const { left, top, width, height, right, bottom } = labelRect; tooltipRef.current = tooltip({ placement: "top", message, ...tooltipProps, style: { left, top, width, height, right, bottom, }, }); }, [message] ); const onMouseLeave = useCallback(() => { tooltipRef.current.close(); tooltipRef.current.remove(); tooltipRef.current = null; }, [message]); return ( <div className="elf--fixed-tooltip" style={{ display: "inline-block", width: "fit-content", height: "fit-content", }} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} > {children} </div> ); }
const pool = require('../config/connection'); const Bus = require('./busSchema'); const Route = require('./routeSchema'); const User = require('./userSchema'); const Reservation = require('./reservationSchema'); const BusUser = require('./busUserSchema'); class DatabaseInitializer { constructor(pool) { this.pool = pool; this.bus = new Bus(pool); this.route = new Route(pool); this.user = new User(pool); this.reservation = new Reservation(pool); this.busUser = new BusUser(pool); } async createTables() { // await this.busUser.deleteBuseUserRelationTable(); // await this.reservation.deleteReservationSchema(); // await this.bus.deleteBusTable(); // await this.route.deleteRoutesTable(); // await this.user.deleteUserTable(); await this.route.createRoutesTable(); await this.bus.createBusTable(); await this.user.createUserTable(); await this.reservation.createReservationSchema(); await this.busUser.createBusUserRelationTable(); } async initialise() { try { await this.createTables(); console.log('Database initialized successfully'); } catch (error) { console.error('Error initializing database:', error); } } } const dbInitializer = new DatabaseInitializer(pool); dbInitializer.initialise();
var util = require('../../utils/util'); var wxRequest = require('../../utils/wxRequest'); var app = getApp(); Page({ data:{ filePath:'', sourceType:['camera'], image_photo:[], load:false }, //图片选择 showAction:function(){ var that=this; wx.showActionSheet({ itemList: ['拍照', '从手机相册选择'], success: function(res) { console.log(res); if(res.tapIndex == 0){ that.setData({ sourceType:['camera'] }) }else if(res.tapIndex == 1){ that.setData({ sourceType:['album'] }) } that.choice(); }, fail: function(res) { } }) }, choice: function () { var that = this; var sourceType=this.data.sourceType; wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType:sourceType, // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths; that.setData({ image_photo: tempFilePaths }); that.uploadPhoto(); }, fail:function(res){ } }) }, parsePlace:function (str){ var strArr =str.split('/'); return strArr[0]; }, //上传图片 uploadPhoto: function () { var that = this; that.setData({ load:true }); wx.uploadFile({ url: app.globalData.huoLiBase+'upLoadJpg', filePath: that.data.image_photo[0], header: {"Content-Type": "multipart/form-data"}, name: 'passport', // formData: { // // }, success: function (res) { console.log(res); if(res.statusCode !== 200) { that.setData({ load:false }); wx.showModal({ title:'解析出错,请上传符合规格的图片', showCancel:false }); return; } var data = JSON.parse(res.data); if(data.code === 200){ data.object.huIssueplace=that.parsePlace(data.object.huIssueplace); wx.redirectTo({ url:'../addpassport/addpassport?isScanning=true&passport='+JSON.stringify(data.object) }); }else{ wx.showModal({ title:'解析出错,请上传符合规格的图片', showCancel:false }) } }, fail:function(err){ }, complete:function(){ that.setData({ load:false }); } }) } });
import { Injectable } from '@angular/core'; import Web3 from 'web3'; import SayHelloTo from '../../artifacts/contracts/SayHelloTo.sol/SayHelloTo.json' import Addresses from '../../adresses.json' import { Observable, Subject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class Web3conService { web3!: Web3 error$: Subject<Error> = new Subject<Error>() contract?: any accounts?: string[] Contract currentAbi?: any currentAddress?: any constructor() { this.initWeb3() this.Contract = this.web3.eth.Contract } initWeb3() { //@ts-ignore this.web3 = new Web3(window.ethereum) this.web3.eth.requestAccounts((error, accs) => { if(error) { this.error$.next(error) return } this.accounts = accs }) } setContract(abi: any, address: string) { if(abi != this.currentAbi && address != this.currentAddress) { this.contract = new this.Contract(abi, address) this.currentAbi = abi this.currentAddress = address } } async callSayHello() { this.setContract(SayHelloTo.abi, Addresses.sayHelloTo) return this.contract.methods.sayHello().call() } async sendChangeTo(to: string, clbk: Function) { if(!this.accounts?.length) return this.setContract(SayHelloTo.abi, Addresses.sayHelloTo) this.contract.methods.changeTo(to).send({ from: this.accounts[0] }).on('receipt', clbk) } subscribeToChangeToEvent(dataClbk: (data:any) => any) { this.setContract(SayHelloTo.abi, Addresses.sayHelloTo) this.contract.events.ToChange({ //fromBlock: 0 }, (error: Error, data: any) => { dataClbk(data) }) } getError(): Observable<Error | undefined> { return this.error$.asObservable() } }
#' Prepares the needed files to run the PBF OM model in SS in bootstrap mode and runs the model #' This produces data files with error for input into EM #' #' @param pdir the parent directory path #' @param sdir path to directory of OM (initial) #' @param hs the harvest strategy being run #' @param hcr the hcr being run #' @param scn the scenario being run #' @param hsw the harves tstrategy being run in Windows notation #' @param hcrw the hcr being run in Winodws notation #' @param scnw the scenario being run in Windows notation #' @param pwin he parent directory path in Windows notation #' @param itr iteration number #' @param tstep time step of the OM #' @param tasmt frequency of assessments #' @param new_cdat new catch data obtained from TAC and catch ratios #' @param rec_devsn new recruitment deviations #' @author Desiree Tommasi OMBoot_fun_tvry <- function(pdir, sdir, hs, hcr, scn, hsw, hcrw, scnw, pwin, itr, tstep, tasmt, new_cdat, rec_devs){ #create directory for the Bootstrap routine setwd(paste(pdir, hs, hcr, scn, itr,"/",tstep, sep = "")) cmddir = "mkdir Boot" shell(cmd = cmddir) #*****************************CHANGE FORECAST FILE******************************************* #Specify inputs to the change_for function if (tstep == 1){ file_in = paste(pdir, hs, hcr, "forecast.ss", sep="") } else { file_in = paste(pdir, hs, hcr, scn, itr,"/",(tstep-1),"/Boot/forecast.ss",sep="") } file_out= paste(pdir, hs, hcr, scn, itr,"/", tstep,"/Boot",sep="") change_for(ss_file_in = file_in, ss_file_out = file_out, t_asmt = tasmt) #*****************************CHANGE PAR FILE********************************************** #include recruitment and selectivity deviations for future time steps #Specify inputs to change_rec_devs_alb function if (tstep == 1){ pfile_in = paste(sdir,scn, "ss.PAR",sep="") } else { pfile_in = paste(pdir, hs, hcr, scn, itr,"/",(tstep-1),"/Boot/ss.PAR", sep = "") } pfile_out = paste(pdir, hs, hcr, scn, itr, "/",tstep,"/Boot/ss.PAR", sep="") #Modify par file to include the recruitment deviations for the next assessment cycle rec_devsn = rec_devs[asmt_t[tstep]:((asmt_t[tstep])+(tasmt-1))] change_rec_devs(recdevs_new = rec_devsn, par_file_in = pfile_in, par_file_out = pfile_out) #*****************************CHANGE DAT FILE******************************************* # Enter new catch data given the TAC and put dummy values for CPUE and size compositions #Specify inputs to the change_dat function if (tstep == 1){ file_in = paste(sdir,scn,"dat_PBF_nonum.ss",sep="") } else { file_in = paste(pdir, hs, hcr, scn, itr,"/",(tstep-1),"/Boot/Bootdat.txt",sep="")# file in for catch, as it should be the true one up to the time of the assessment } file_out= paste(pdir, hs, hcr, scn, itr,"/", tstep,"/Boot/Bootdat.txt",sep="") #if the TAC is 0, then no CPUE or size comps possible as no fish were caught, use the change catch only code, if not also add dummy values for CPUE and size comps if (sum(new_cdat$catch)==0){ #Insert new catch data into .dat file change_dat_boot(ss_file_in = file_in, ss_file_out = file_out, t_asmt = tasmt, nrep = tasmt, cdat_new = new_cdat) } else { change_dat_cpue_boot_adj(ss_file_in = file_in, ss_file_out = file_out, t_asmt = tasmt, nrep = tasmt, cdat_new = new_cdat) } #***************************CHANGE CTL FILE************************************* #Modify end of blocks, end of main recruitment deviations, and set rec devs as fixed in control file blk_in = paste(sdir, scn, "control_simple_1719_2021.ss", sep = "") blk_out = paste(pdir, hs, hcr, scn, itr, "/",tstep,"/Boot/Boot.ctl", sep="") blk_end = 2020 + asmt_t[tstep] + (tasmt-1) #change control file change_ctl(blk_in, blk_out, blk_end, vadj = 2) #*************************CHANGE STARTER FILE**************************************** #Modify starter file to run OM with new catch data without estimating parameters #read into R the ss starter file using the r4ss SS_readstarter function starter_dat=SS_readstarter(paste(pdir, hs, "starter.ss", sep="")) #specify the new dat file name starter_dat$datfile = "Bootdat.txt" #specify the new ctl file name starter_dat$ctlfile = "Boot.ctl" #specify to use the ss.par as parameters starter_dat$init_values_src = 1 #turn off estimation of parameters starter_dat$last_estimation_phase = 0 #add 1 data bootstrap file starter_dat$N_bootstraps = 3 #change last year with uncertainty to end year starter_dat$maxyr_sdreport= blk_end #write new starter file path_start = paste(pdir, hs, hcr, scn, itr,"/",tstep,"/Boot/",sep="") SS_writestarter(starter_dat, path_start) #*************************RUN THE BOOTSTRAP MODEL************************************* #generate the .bat file to run the model Path = paste(pdir, hs, hcr, scn, itr, "/", tstep,"/Boot/", sep="") filename_om <-paste(Path,"ssnohess.bat",sep="") batchtext_om = paste(pwin,"SS_model\\ss -maxfn 0 -phase 50 -nohess",sep="") writeLines(batchtext_om,filename_om) setwd(Path) command_run_om="ssnohess.bat" shell(cmd= command_run_om) }
import container from '@app/dependency-injection'; import { Logger } from 'winston'; import { KafkaConnection } from './KafkaConnection'; import { KafkaMessage } from 'kafkajs'; import { DomainEventDeserializer } from '../DomainEventDeserializer'; import { DomainEventSubscriber } from '@context/shared/domain/event/DomainEventSubscriber'; import { DomainEvent } from '@context/shared/domain/DomainEvent'; export class KafkaConsumer { private logger: Logger = container.get('Shared.Logger'); constructor(private subscriber: DomainEventSubscriber<DomainEvent>, private deserializer: DomainEventDeserializer, private connection: KafkaConnection) { } async onMessage(topic: string, message: KafkaMessage) { if (!message.value) return; const content = message.value.toString(); const domainEvent = this.deserializer.deserialize(content); try { await this.subscriber.on(domainEvent); } catch (error: any) { this.logger.error(`[EVENT NAME]: ${domainEvent.eventName}, [EVENT ID]: ${domainEvent.eventId}, [ERROR STACK]: ${error.stack}`); this.handleError(topic, message, domainEvent); } } private async handleError(topic: string, message: KafkaMessage, domainEvent: DomainEvent) { if (this.hasBeenRedeliveredTooMuch(message, domainEvent.maxRetries)) { await this.deadLetter(message, domainEvent) } else { await this.retry(topic, message); } } private async retry(topic: string, message: KafkaMessage) { await this.connection.retry(topic, message) } private async deadLetter(message: KafkaMessage, domainEvent: DomainEvent) { this.logger.error(`[NEW DEAD LETTER] - [EVENT]: ${domainEvent.eventName}, [MESSAGE]: ${JSON.stringify(domainEvent)}`); await this.connection.deadLetter(message) } private hasBeenRedeliveredTooMuch(message: KafkaMessage, maxRetries: number) { if (this.hasBeenRedelivered(message)) { const count = parseInt(message!.headers!['redelivery_count'] as string); return count >= maxRetries; } return false; } private hasBeenRedelivered(message: KafkaMessage) { return message.headers !== undefined && message.headers['redelivery_count'] !== undefined; } }
/* * SPDX-FileCopyrightText: 2013 (c) Business Operation Systems GmbH <info@top-logic.com> * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-BOS-TopLogic-1.0 */ package com.top_logic.basic.config.internal; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import com.top_logic.basic.annotation.FrameworkInternal; import com.top_logic.basic.col.ObservableMapProxy; import com.top_logic.basic.config.PropertyDescriptor; import com.top_logic.basic.config.PropertyDescriptorImpl; import com.top_logic.basic.tools.NameBuilder; /** * Observable {@link Map} implementation that sends notifications through its owning * {@link ItemChangeHandler}. * * @author <a href="mailto:bhu@top-logic.com">Bernhard Haumacher</a> */ @FrameworkInternal public class ItemMap<K, V> extends ObservableMapProxy<K, V> { private static final int NO_INDEX = -1; private LinkedHashMap<K, V> _impl; private final ItemChangeHandler _handler; private final PropertyDescriptor _property; private boolean _modified; /** * Creates a {@link ItemMap}. * * @param handler * The container that handles notification. * @param property * The property for which this {@link ItemMap} holds elements. */ public ItemMap(ItemChangeHandler handler, PropertyDescriptor property) { _impl = new LinkedHashMap<>(); _handler = handler; _property = property; } @Override protected Map<K, V> impl() { return _impl; } @Override public V put(K key, V value) { checkLegalValue(Collections.singletonMap(key, value)); return super.put(key, value); } @Override public void putAll(Map<? extends K, ? extends V> m) { if (m.isEmpty()) { return; } checkLegalValue(m); super.putAll(m); } @Override protected void afterPut(K key, V value) { receiver().__notifyAdd(_property, NO_INDEX, value); markModified(); } @Override protected void afterRemove(Object key, V oldValue) { receiver().__notifyRemove(_property, NO_INDEX, oldValue); markModified(); } /** * Whether this map has been modified after construction (either creating the containing * configuration item or reading it from XML). */ public boolean isModified() { return _modified; } @FrameworkInternal private void markModified() { setModified(true); } /** * Sets the modified state of this map. * * @see #isModified() */ @FrameworkInternal public void setModified(boolean value) { _modified = value; } /** * Updates this map to the new state. * * @param value * The new contents. * @param isSet * The new {@link #isModified()} marker. */ @FrameworkInternal public void set(Map<? extends K, ? extends V> value, boolean isSet) { clear(); putAll(value); setModified(isSet); } /** * Resets the modification marker. * * @see #isModified() */ @FrameworkInternal public void markUnmodified() { _modified = false; } ItemChangeHandler receiver() { return _handler; } private void checkLegalValue(Map<? extends K, ? extends V> m) { PropertyDescriptorImpl.checkCorrectMapValues(_property, m); } @Override public String toString() { return new NameBuilder(this) .add("property", _property) .add("map", _impl) .build(); } }
package org.soa.entity; import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; import java.util.LinkedHashSet; import java.util.Set; @Entity @Table(name = "customer") @NamedQueries({ @NamedQuery(name = "Customer.findByEmail", query = "SELECT c FROM Customer c WHERE c.email = :email") }) @Getter @Setter public class Customer { @Id @Basic(optional = false) @Column(name = "customer_id") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_SEQ") private Long customerId; @Column(name = "name", nullable = false) private String name; @Column(name = "email", nullable = false) private String email; @Column(name = "phone", length = 15) private String phone; @Column(name = "password", nullable = false) private String password; @Column(name = "roles", length = 100) private String roles; @OneToMany(mappedBy = "customer") private Set<Purchase> purchases = new LinkedHashSet<>(); }
import { createRoot, onMount, createEffect } from "solid-js"; import { createStore } from "solid-js/store"; import { getDefaultFontSize } from "@app/utils/functions"; interface FontSizes { sm: number; md: number; lg: number; xl: number; } interface Store { valid: boolean; activeSize: number; sizes: FontSizes; } const GROW_FACTOR = 2; const FONT_SIZE_KEY = "FONT_SIZE_KEY"; const fontSizeStore = () => { const [fontStore, setFontStore] = createStore<Store>({ valid: false, activeSize: 0, sizes: { sm: 0, md: 0, lg: 0, xl: 0, }, }); const htmlEl = document.querySelector("html"); createEffect(() => { if (fontStore.activeSize > 0 && fontStore.valid && htmlEl !== null) { localStorage.setItem(FONT_SIZE_KEY, fontStore.activeSize.toString()); htmlEl.style.fontSize = `${fontStore.activeSize}px`; } }); onMount(() => { if (htmlEl === null) return; const baseSize = getDefaultFontSize(); // if can't get default size, don't provide change font option if (baseSize === 0) return; setFontStore({ valid: true, sizes: { sm: baseSize - GROW_FACTOR, md: baseSize, lg: baseSize + GROW_FACTOR, xl: baseSize + 2 * GROW_FACTOR, }, }); const savedSizeStr = localStorage.getItem(FONT_SIZE_KEY); if (savedSizeStr === null) { setFontStore("activeSize", baseSize); return; } const savedSize = parseInt(savedSizeStr); const isValidSize = Object.values(fontStore.sizes).some( (size) => size === savedSize, ); if (isValidSize) { setFontStore("activeSize", savedSize); } else { setFontStore("activeSize", baseSize); } }); const setSm = () => setFontStore("activeSize", fontStore.sizes.sm); const setMd = () => setFontStore("activeSize", fontStore.sizes.md); const setLg = () => setFontStore("activeSize", fontStore.sizes.lg); const setXl = () => setFontStore("activeSize", fontStore.sizes.xl); const setFontSize = (n: number) => setFontStore("activeSize", n); return { fontStore, setSm, setMd, setLg, setXl, setFontSize }; }; export default createRoot(fontSizeStore);
import React, { useState } from "react"; import { useHistory } from "react-router-dom"; import { Container, Menu } from "semantic-ui-react"; import CartSummary from "./CartSummary"; import SignedIn from "./SignedIn"; import SignedOut from "./SignedOut"; import { useSelector } from 'react-redux'; export default function Navi() { //baştaki state yanındaki state değiştiren method //destructed yapıyık const {cartItems} = useSelector(state => state.cart) //setis state değiştircez isauthenticated değişsin const [isAuthenticated, setIsAuthenticated] = useState(true); const history=useHistory() //handle çıkış yap oluyor burda //state navide kullan ama altcomponentden çağırmak lazum fonk ile function handleSignOut() { setIsAuthenticated(false) history.push("/") } //handle giriş yap oluyor burda //state navide kullan ama altcomponentden çağırmak lazum fonk ile function handleSignIn() { setIsAuthenticated(true) } return ( <div> <Menu inverted fixed="top"> <Container> <Menu.Item name="home" active /> <Menu.Item name="messages" /> <Menu.Menu position="right"> {cartItems.length>0&&<CartSummary /> } {isAuthenticated ? <SignedIn signedOut={handleSignOut} bisey="1" /> : <SignedOut signedIn={handleSignIn} ikincibisey="2" />} </Menu.Menu> </Container> </Menu> </div> ); }
<h1 align="center"> Filcker photo </h1> <br> ## Table of Contents - [Introduction](#introduction) - [Features](#features) - [Architecture](#architecture) - [Roadmap (Features to be added )](#roadmap) - [Download](#download) - [Getting started](#getting-started) ## Introduction <!-- [![Build Status](https://img.shields.io/travis/gitpoint/git-point.svg?style=flat-square)](https://travis-ci.org/gitpoint/git-point)--> [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) An Android Application written purely in Kotlin utilizing all the latest tech in Android. The project uses Material Design guidelines, Clean + MVI architecture, Dependency Injection and uses Room. The data is fetched from <a href='https://www.flickr.com/services/api/'>Flickr API</a> ## Features A few of the things you can do with app: - Search - Bookmark - Search History - FullScreen Image <p align="center"> <img src = https://github.com/hamedsilver/Filcker-Photo/blob/main/screenshots/history.jpg width=240 height=420> <img src = https://github.com/hamedsilver/Filcker-Photo/blob/main/screenshots/search.jpg width=240 height=420> <img src = https://github.com/hamedsilver/Filcker-Photo/blob/main/screenshots/detail.jpg width=240 height=420> </p> ## Architecture This application implements the following concepts : - [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) - MVI + View binding - Navigation Component - ViewModel - Repository - Unit Test - [Kotlin](https://kotlinlang.org/) - [Coroutines](https://github.com/Kotlin/kotlinx.coroutines) - [Flow](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/) - [Retrofit2 & OkHttp3](https://github.com/square/retrofit) - construct the REST APIs and paging network data. - [Gson](https://github.com/google/gson) - Gson is a Java library that can be used to convert Java Objects into their JSON representation. - [Room](https://developer.android.com/topic/libraries/architecture/room) - For storing Database. - [Glide](https://github.com/bumptech/glide) - Glide supports fetching, decoding, and displaying video stills, images, and animated GIFs. ## Roadmap (Features to be added 🛠️ ) - Using Jetpack compose - Animations using Jetpack compose - Pagination for search list - Modularize Project ## Download [Download apk file](/app/release/app-release.apk) ## Getting started - Clone this repository - Import the repository to Android Studio - Build
********************************************************************* * z390 - Mainframe assembler emulator and run-time engine * Copyright (C) 2021 z390 Assembler LLC * * This file is part of z390. * * z390 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. * z390 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 https://www.gnu.org/licenses. * Author - Don Higgins * * Date - 11/28/05 * ********************************************************************* * * RUN DEMOGUI1 WITH GUI OPTION TO DEMO WTO/WTOR/WAIT GUI MCS CONSOLE * * DEMOGUI1 CAN BE RUN IN 4 DIFFERENT MODES: * 1. Windows command line interface * a. Enter command: ez390 demo\demogui1 * b. Enter replies when prompted and terminal with END. * c. When a WTOR reply is pending with GUI option off, * ez390 monitors the system standard input for keyboard input * and when ready, stores reply and posts ecb complete. * * 2. Windows z390 GUI system window interface * a. Enter command: ez390 demo\demogui1 * b. Enter replies when prompted and terminal with END. * c. When a WTOR reply is pending GUI option off, * ez390 monitors the system standard input for keyboard input * and when ready, stores reply and posts ecb complete. Note * this case the standard input is supplied to ez390 process * started from the z390 GUI system window and the wto message * and reply messages are routed back to the z390 GUI system * window scrolling log display. * * 3. Windows command line interface * a. Enter command: ez390 demo\demogui1 gui * b. Enter replies when prompted and terminal with END. * c. When a WTOR reply is pending with GUI option on, * ez390 monitors the GUI application window for command input * and when ready, stores reply and posts ecb complete. WTO * and reply messages are routed to the GUI application window * for display on MCS console view panel and are also logged * on the z390 system log file. * * 4. Windows z390 GUI system window interface * a. Enter command: ez390 demo\demogui1 gui * b. Enter replies when prompted and terminal with END. * c. When a WTOR reply is pending with GUI option on, * ez390 monitors the GUI application window for command input * and when ready, stores reply and posts ecb complete. WTO * and reply messages are routed to the GUI application window * for display on MCS console view panel. Note in this case * wto messages and reply messages are also routed to the * separate z390 GUI system window scrolling log display and * system log file. * * See DEMOGUI2 for simllar demo but with counter being incremented * in loop until WTOR ECB is posted indicationg reply is read. The * time and AP instructions since last reply is displayed. * ********************************************************************* DEMOGUI1 SUBENTRY WTO 'DEMOGUI1 DEMO WTO AND WTOR WAIT LOOP' LOOP EQU * WTOR 'ENTER TEXT TO DISPLAY OR END',REPLY,,WAITECB WAIT ECB=WAITECB CLC REPLY(3),=C'END' BE EOF WTO MF=(E,WTOMSG1) B LOOP EOF WTO 'DEMOGUI1 ENDING OK' SUBEXIT WAITECB DC F'0' WTOMSG1 DC AL2(WTOEND1-*,0),C'TEXT ENTERED = ' REPLY DC CL40' ' WTOEND1 EQU * END
<template> <div class="wrap-post"> <el-dialog title="Choose property for post" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="set_false" :close-on-press-escape="set_false" :show-close="set_false" > <el-form :model="property_post" :rules="rules" ref="property_post"> <el-row> <el-col :span="12"> <el-form-item label="Type" prop="idType"> <el-select @change="changeSelect($event, `type`)" v-model="property_post.idType" filterable allow-create default-first-option placeholder="Activity Type" > <el-option v-for="item in data.types" :key="item.id" :label="item.name" :value="item.id" > </el-option> </el-select> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="Category" prop="idCategory"> <el-select v-model="property_post.idCategory" filterable allow-create default-first-option @change="changeSelect($event, `category`)" placeholder="Activity Category" > <el-option v-for="item in data.categories" :key="item.id" :label="item.name" :value="item.id" > </el-option> </el-select> </el-form-item> </el-col> </el-row> <el-row> <el-col :span="12"> <el-form-item label="Status" prop="idStatus"> <el-select v-model="property_post.idStatus" filterable allow-create default-first-option placeholder="Activity Status" @change="changeSelect($event, `status`)" > <el-option v-for="item in data.statuses" :key="item.id" :label="item.name" :value="item.id" > </el-option> </el-select> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="Exam" prop="idExam"> <el-select v-model="property_post.idExam" filterable allow-create default-first-option placeholder="Activity Exam" @change="changeSelect($event, `exam`)" > <el-option v-for="item in data.exams" :key="item.id" :label="item.dateExam" :value="item.id" > </el-option> </el-select> </el-form-item> </el-col> </el-row> </el-form> <span slot="footer" class="dialog-footer"> <el-button type="primary" @click="submitForm('property_post')" >Confirm</el-button > </span> </el-dialog> <div> <el-row> <el-col :span="6" >Type : <el-tag effect="dark" type="success" size="medium"> {{ showData.type }}</el-tag > </el-col> <el-col :span="6" >Category : <el-tag effect="dark" type="success" size="medium">{{ showData.category }}</el-tag> </el-col> <el-col :span="6" >Status : <el-tag effect="dark" type="success" size="medium"> {{ showData.status }}</el-tag > </el-col> <el-col :span="6" >Exam : <el-tag effect="dark" type="success" size="medium"> {{ showData.exam }}</el-tag > </el-col> </el-row> </div> <vue-editor v-model="property_post.content"></vue-editor> <el-row> <el-col :span="24" ><div class="grid-content bg-purple-dark"></div ></el-col> </el-row ><el-button type="primary" @click="storePost">Submit</el-button> </div> </template> <script> import axios from "axios"; import { VueEditor } from "vue2-editor"; export default { components: { VueEditor, }, data() { return { dialogVisible: true, set_false: false, property_post: { idType: "", idCategory: "", idStatus: "", idExam: "", idStudent: this.$store.getters.id, content: "", }, rules: { idType: [ { required: true, message: "Please select", trigger: "change", }, ], idExam: [ { required: true, message: "Please select", trigger: "change", }, ], idCategory: [ { required: true, message: "Please select", trigger: "change", }, ], idStatus: [ { required: true, message: "Please select", trigger: "change", }, ], }, data: { types: [], categories: [], statuses: [], exams: [], }, showData: { type: "", category: "", status: "", exam: "", }, }; }, methods: { getAllProp() { axios .get(`type`) .then((result) => { this.data.types = result.data.data; }) .catch((err) => { console.log(err); }); axios .get(`category`) .then((result) => { this.data.categories = result.data.data; }) .catch((err) => { console.log(err); }); axios .get(`status`) .then((result) => { this.data.statuses = result.data.data; }) .catch((err) => { console.log(err); }); axios .get(`exam/student/${this.property_post.idStudent}`) .then((result) => { this.data.exams = result.data.data; }) .catch((err) => { console.log(err); }); }, submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { this.dialogVisible = false; } else { console.log("error submit!!"); return false; } }); }, changeSelect(e, list) { if (list == "type") { this.showData.type = this.data.types.find((x) => x.id === e).name; } else if (list == "status") { this.showData.status = this.data.statuses.find((x) => x.id === e).name; } else if (list == "category") { this.showData.category = this.data.categories.find( (x) => x.id === e ).name; } else { this.showData.exam = this.data.exams.find((x) => x.id === e).dateExam; } }, storePost() { axios .post("post", this.property_post) .then((result) => { console.log(result); }) .catch((err) => { console.log(err); }); }, }, created() { this.getAllProp(); }, }; </script> <style scoped> .wrap-post { background: #ffff; height: 500px; } </style>
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { UserLoginRequest } from '@contracts/auth/user/requests/user-login.request'; import { LocalStorageService } from '@helpers/services/local-storage.service'; import { ToastService } from '@services/_common/toast.service'; import { UserService } from '@services/auth/user/user.service'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit, OnDestroy { loginForm: FormGroup | undefined = undefined; private subscribers: Subscription[] = []; constructor( private router: Router, private formBuilder: FormBuilder, private userService: UserService, private toastService: ToastService, private localStorageService: LocalStorageService ) { } initForm() { this.loginForm = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]], password: ['', [Validators.required, Validators.minLength(6)]], }); } submitForm() { if (!this.loginForm) return; if (this.loginForm.invalid) { this.toastService.warning('Invalid form data'); return; } const request: UserLoginRequest = new UserLoginRequest(this.loginForm.value.email, this.loginForm.value.password); const subscriber = this.userService.login(request).subscribe(response => { if (!response || !response.isSuccess || !response.data) { this.localStorageService.clear(); return; } this.localStorageService.setAndDoStringfy('auth', response.data); this.router.navigateByUrl('/'); }); this.subscribers.push(subscriber); } ngOnInit(): void { this.initForm(); } ngOnDestroy(): void { this.subscribers.forEach(subscriber => subscriber.unsubscribe()); } }
import React from 'react'; import { Card } from 'react-bootstrap'; import _ from 'lodash'; import music from '../images/music.jpeg'; const ArtistsList = ({ artists }) => { return ( <React.Fragment className="content"> {Object.keys(artists).length > 0 && ( <div className="artists container"> {artists.items.map((artist, index) => { return ( <React.Fragment key={index}> <Card className="disc"> <a target="_blank" href={artist.external_urls.spotify} rel="noopener noreferrer" className="card-image-link" > {!_.isEmpty(artist.images) ? ( <Card.Img variant="top" src={artist.images[0].url} alt="" /> ) : ( <img src={music} alt="" /> )} </a> <Card.Body> <Card.Title className="artist">{artist.name}</Card.Title> </Card.Body> </Card> </React.Fragment> ); })} </div> )} </React.Fragment> ); }; export default ArtistsList;
import TransactionsRepository from '../repositories/TransactionsRepository'; import Transaction from '../models/Transaction'; interface Request { title: string; type: 'income' | 'outcome'; value: number; } class CreateTransactionService { private transactionsRepository: TransactionsRepository; constructor(transactionsRepository: TransactionsRepository) { this.transactionsRepository = transactionsRepository; } public execute({ title, value, type }: Request): Transaction { const transaction = new Transaction({ title, value, type }); const balance = this.transactionsRepository.getBalance(); if (type === 'outcome' && value > balance.total) { throw Error('Transaction rejected! Insufficient funds.'); } this.transactionsRepository.create({ title, value, type }); return transaction; } } export default CreateTransactionService;
import { Router, AjaxRequest } from "webuilder"; import "webuilder/formAjax"; import "bootstrap-inputmsg"; import "bootstrap"; import Main from "../events/main"; interface IDescription { id: number; likes: number; text: string; isLike: boolean, user: { id: number; name: string; }; sent_at: { relative: string; date: string; }, } export class viewLyric{ public static init():void { viewLyric.song = parseInt($("#like").data("song") as string, 10); viewLyric.runLikelistener(); $(".tooltips").tooltip(); if($(".translations select.selectpicker").length){ $(".translations select.selectpicker").val($("section.text").data("lang")); viewLyric.runChangeLangListener(); } viewLyric.addCommentsubmitFormListener(); viewLyric.runLyricsDescription(); viewLyric.setCommentsReplyEvents(); $("#filtering-modal").modal({ show: true, backdrop: "static" }); } protected static song: number; public static runLikelistener():void{ $("#like").on("click", function(e){ e.preventDefault(); $.ajax({ url: Router.url("songs/like/" + viewLyric.song), dataType: "json", data: { ajax: 1 }, success: function( data:{status?:boolean, liked:boolean} ) { if(data.hasOwnProperty("status")){ if(data.status){ let likes:number = parseInt($(".like-number").text()); if(data.liked){ $(".like-icon").attr("class", "fa fa-heart like-icon"); $(".like-number").text(++likes); }else{ $(".like-icon").attr("class", "fa fa-heart-o like-icon"); $(".like-number").text(--likes); } } } } }); }); } private static runChangeLangListener():void{ $(".translations select.selectpicker option").on("click", function(){ if($(this).hasClass("ltr")){ $(this).parents(".selectpicker").addClass("ltr"); }else{ $(this).parents(".selectpicker").removeClass("ltr"); } const lang = $("section.text").data("lang"); if(lang != $(this).val()){ window.location.href = $(this).data("link"); } }); } protected static addCommentsubmitFormListener() { $(".comments-section .panel-comments form").on("submit", function(e) { e.preventDefault(); const reset = () => { (this as HTMLFormElement).reset(); $(".has-error", this).removeClass("has-error"); $(".help-block", this).remove(); $(".reply-section", this).slideUp(); }; ($(this) as any).formAjax({ url: `songs/${viewLyric.song}/addComment?ajax=1`, dataType: "json", success: (data: any) => { $.growl.notice({ title:"موفق", message:"نظر شما بعد از تایید ما به نمایش در خواهد آمد." }); reset(); }, error: function(error: any) { if(error.error == "data_duplicate" || error.error == "data_validation"){ let $input = $(`[name="${error.input}"]`); let $params = { title: "خطا", message:"" }; if (error.error == "data_validation") { $params.message = "داده وارد شده معتبر نیست"; } if (error.error == "data_duplicate") { $params.message = "داده وارد شده تکراری میباشد"; } if ($input.length) { $input.inputMsg($params); } else { $.growl.error($params); } } else if (error.hasOwnProperty("message")) { const $error = `<div class="alert alert-block alert-danger "> <button data-dismiss="alert" class="close" type="button">×</button> <h4 class="alert-heading"><i class="fa fa-times-circle"></i> خطا</h4> <p>${error.message}</p> </div>`; $(".container .errors").html($error); } else { $.growl.error({ title:"خطا", message:"درخواست شما توسط سرور قبول نشد" }); } } }); }); } protected static runLyricsDescription() { let activePopover: JQuery; const $container = $(".lyric section.text"); const $decs = $("span", $container); $decs.popover({ placement: "bottom", html: true, content: `<div class="text-center"><i class="fa fa-spinner fa-pulse fa-2x fa-fw text-muted"></i><span>در حال دریافت</span></div>`, }); $decs.on("show.bs.popover", function() { $(".popover .popover-content", $(this)).html(`<div class="text-center"><i class="fa fa-spinner fa-pulse fa-2x fa-fw text-muted"></i><span>در حال دریافت</span></div>`); $(".popover .popover-title", $(this)).html("توضیحات"); }); $decs.on("shown.bs.popover", function() { if (activePopover !== undefined && !activePopover.is($(this))) { activePopover.popover("hide"); } activePopover = $(this); $(this).data("prevent-close", true); const parent = $(this).parent(); const $clone = $(this).clone(); $(".popover", $clone).remove(); const lyric = parseInt($(this).data("lyric") as string, 10); const $popoverContainer = $(".popover .popover-content", parent); $popoverContainer.css("height", ""); let html = ""; if (Main.isLogin) { html = `<div class="text-center form-group"><button type="button" class="btn btn-sm btn-success btn-add-description">افزودن توضیح<i class="fa fa-pluse"></i></button></div>`; } else { html = `<p class="text-center form-group"><small>برای افزودن توضیحات <a href="${Router.url("userpanel/register")}">ثبت نام </a> کنید و یا <a href="${Router.url("userpanel/login")}">وارد</a> شوید</small></p>`; } AjaxRequest({ url: `songs/lyric/${lyric}/description?ajax=1`, dataType: "json", method: "POST", success: function(data) { if (!data.items.length) { return; } for (const description of data.items as IDescription[]) { html += `<div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-xs-8"><span class="username">${description.user.name}</span></div> <div class="col-xs-4"><time class="tooltips" title="${description.sent_at.date}">${description.sent_at.relative}</time></div> </div> </div> <div class="panel-body">${description.text}</div> <div class="panel-footer"> <div class="row"> <div class="col-xs-4 pull-left"> <button type="button" class="btn btn-sm ${description.isLike ? "btn-success" : "btn-default"} btn-like" data-description="${description.id}"><i class="fa fa-thumbs-o-up"></i> <span>${description.likes}</span> </button> </div> </div> </div> </div>`; } $popoverContainer.html(html); viewLyric.setDescriptionEvetns($(".popover", parent)); viewLyric.setLyricPopoverEvents($(".popover", parent), $clone.text(), $clone.hasClass("ltr"), lyric); }, error: function() { $popoverContainer.html(`${html}<div class="alert alert-info">توضیحی ثبت نشده است</div>`); $popoverContainer.css("height", "auto"); viewLyric.setLyricPopoverEvents($(".popover", parent), $clone.text(), $clone.hasClass("ltr"), lyric); } }); }); $decs.on("hidden.bs.popover", function() { $("body").removeClass("modal-open"); }); } protected static setLyricPopoverEvents($popover: JQuery, text: string, isLtr: boolean, lyric: number) { if (!Main.isLogin) { return; } const $container = $(".popover-content", $popover); const song = $("header > .title h1").html(); const singer = $("header > .title h2").html(); $(".btn-add-description", $popover).on("click", () => { $(".popover-title", $popover).html("افزودن توضیح"); if (Main.windowWidth < 768) { $popover.css({ position: "fixed", top: 0, bottom: 0, margin: 0, }); $("body").addClass("modal-open"); } $container.html(`<form id="addLyricDescriptionForm" method="post"> <p>با افزودن توضیحات میتوانید امتیاز کسب کنید</p> <p><strong>نام آهنگ:</strong> ${song}</p> <p><strong>اثر:</strong> ${singer}</p> <p><strong>متن عبارت:</strong></p> <p class="${isLtr ? "ltr text-left" : ""}">${text}</p> <div class="form-group"> <label class="control-label">توضیح</label> <textarea rows="8" name="content" class="form-control"></textarea> </div> </form> <div class="popover-footer"> <div class="row"> <div class="col-xs-6"> <button type="submit" class="btn btn-sm btn-block btn-success btn-submit" form="addLyricDescriptionForm"><i class="fa fa-check-square-o"></i> افزودن</button> </div> <div class="col-xs-6"> <button type="button" class="btn btn-sm btn-block btn-default btn-close"><i class="fa fa-times"></i> بستن</button> </div> </div> </div> `); if (Main.windowWidth < 768) { $container.css("height", Main.windowHeight - ($(".popover-title", $popover).height() + $(".popover-footer").height() + 40)); } else { $container.css("height", "auto"); } $(".btn-close", $container).one("click", () => { $popover.popover("hide"); }); $("form", $popover).on("submit", function(e) { e.preventDefault(); const $btn = $(".btn-submit", $popover); $btn.prop("disabled", true); $("i", $btn).removeClass("fa-check-square-o").addClass("fa-spinner fa-pulse fa-fw"); ($(this) as any).formAjax({ url: `songs/lyric/${lyric}/description/add?ajax=1`, dataType: "json", success: () => { $.growl.notice({ title: "متشکریم", message: "توضیح شما بعد از تایید ما به نمایش در خواهد آمد." }); $popover.popover("hide"); }, error: function(error: any) { if(error.error == "data_duplicate" || error.error == "data_validation"){ let $input = $(`[name="${error.input}"]`, $popover); let $params = { title: "خطا", message:"" }; if (error.error == "data_validation") { $params.message = "داده وارد شده معتبر نیست"; } if (error.error == "data_duplicate") { $params.message = "داده وارد شده تکراری میباشد"; } if ($input.length) { $input.inputMsg($params); } else { $.growl.error($params); } } else { $.growl.error({ title:"خطا", message:"درخواست شما توسط سرور قبول نشد" }); } $btn.prop("disabled", false); $("i", $btn).removeClass("fa-spinner fa-pulse fa-fw").addClass("fa-check-square-o"); } }); }); }); } protected static setDescriptionEvetns($popover: JQuery) { $(".tooltips", $popover).tooltip(); $(".btn-like", $popover).on("click", function(e) { e.preventDefault(); $(this).prop("disabled", true); $("i", this).removeClass("thumbs-o-up").addClass("fa-spinner fa-pulse fa-fw"); const that = this; const description = parseInt($(this).data("description"), 10); AjaxRequest({ url: `songs/lyric/descriptions/${description}/like?ajax=1`, dataType: "json", method: "POST", success: function(data) { $.growl.notice({ title: "موفق", message: "" }); $(that).prop("disabled", false); $("i", that).removeClass("fa-spinner fa-pulse fa-fw").addClass("thumbs-o-up"); $("span", that).html(data.likes); if (data.isLiked) { $(that).removeClass("btn-default").addClass("btn-success"); } else { $(that).removeClass("btn-success").addClass("btn-default"); } }, error: function() { $.growl.error({ title:"خطا", message:"درخواست شما توسط سرور قبول نشد" }); $(that).prop("disabled", false); $("i", that).removeClass("fa-spinner fa-pulse fa-fw").addClass("thumbs-o-up"); } }); }); } protected static setCommentsReplyEvents() { const $container = $(".lyric .comments-section"); const $replyContainer = $(".lyric .reply-section"); $(".comment .btn-reply", $container).on("click", function(e) { e.preventDefault(); const comment = $(this).data("comment"); $(".comment-reply-sender-name", $replyContainer).html($(this).data("sender-name")); $replyContainer.slideDown(); $("input[name=reply]", $replyContainer).val(comment); $("html, body").animate({ scrollTop: $(".panel-comments", $container).offset().top }, 700); }); $(".bnt-cancel-reply", $replyContainer).on("click", (e) => { e.preventDefault(); $replyContainer.slideUp(); $("input[name=reply]", $replyContainer).val(""); }); } }
import {useCallback, useContext, useMemo} from 'react'; import TIcon from '~/icon/TIcon'; import TButton from '~/button/button/TButton'; import themeToken from '~style/designToken/ThemeToken.module.scss'; import datePickerConText from '~/input/date-picker/TDatePickerContext'; import {TDateValue} from '~/input/date-picker'; const TYearSelector = () => { // region [Hooks] const { dateValue, onChangeValue, displayDateObject, setDisplayDateObject, changeViewMode, validDateRange, nowDate, viewMode, } = useContext(datePickerConText); const displayYearRange = useMemo(() => { const startYear = Math.floor(displayDateObject.year / 10) * 10; return Array.from({length: 10}, (_, index) => startYear + index); }, [displayDateObject]); // endregion // region [Privates] const selectedDateObject = useMemo((): TDateValue => { if (dateValue === '') { return {year: null, month: null, day: null}; } const year = Number(dateValue.substring(0, 4)); return {year, month: null, day: null}; }, [dateValue]); // endregion // region [Styles] const dateLabelClass = useCallback( (year: number): string => { const clazz = []; if (year === selectedDateObject.year) { clazz.push('t-year-selector__content__year-container__item__year--selected'); } if (year === nowDate().year) { clazz.push('t-year-selector__content__year-container__item__year--today'); } if (!validDateRange(`${year}`)) { clazz.push('t-year-selector__content__year-container__item__year--disabled'); } return clazz.join(' '); }, [selectedDateObject, nowDate, validDateRange], ); const iconClass = useMemo(() => { if (viewMode.original !== viewMode.current) { return 't-year-selector__header__current-display-date__icon--open'; } return ''; }, [viewMode]); // endregion // region [Events] const onClickDate = useCallback((clickedYear: number) => { if (viewMode.current !== viewMode.original) { setDisplayDateObject((prev) => ({...prev, year: clickedYear})); changeViewMode(viewMode.original); return; } if (validDateRange(clickedYear?.toString())) { onChangeValue(clickedYear?.toString()); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [onChangeValue]); const onMoveYear = useCallback((move: 'next' | 'prev') => { if (move === 'next' || move === 'prev') { setDisplayDateObject((prev) => { const moveValue = move === 'next' ? 10 : -10; const newYear = prev.year + moveValue; if (newYear >= 1000 && newYear <= 9999) { return {...prev, year: newYear}; } return prev; }); } else { throw new Error('Invalid move value'); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const onClickToggleViewMode = useCallback(() => { if (viewMode.original !== viewMode.current) { changeViewMode(viewMode.original); } }, [viewMode, changeViewMode]); // endregion // region [Effects] // endregion // region [Templates] return ( <div className={'t-year-selector'} data-testid={'t-year-selector'}> <div className={'t-year-selector__header'}> <div className={'t-year-selector__header__current-display-date'}> <div onClick={() => { changeViewMode('year'); }}> {`${displayYearRange[0]}년 - ${displayYearRange[displayYearRange.length - 1]}년`} </div> <TIcon xsmall onClick={onClickToggleViewMode} className={`t-year-selector__header__current-display-date__icon ${iconClass}`}> arrow_drop_down </TIcon> </div> <div className={'t-year-selector__header__control'}> <TButton onClick={() => { onMoveYear('prev'); }} xsmall className={'t-year-selector__header__control__icon-button'}> <TIcon xsmall color={themeToken.tGrayColor5}>arrow_left</TIcon> </TButton> <TButton onClick={() => { onMoveYear('next'); }} xsmall className={'t-year-selector__header__control__icon-button'}> <TIcon xsmall color={themeToken.tGrayColor5}>arrow_right</TIcon> </TButton> </div> </div> <div className={'t-year-selector__content'} data-testid={'t-day-selector-control'}> <div className={'t-year-selector__content__year-container'}> {displayYearRange.map((year) => ( <span className={`t-year-selector__content__year-container__item ${dateLabelClass(year)}`} onClick={() => { onClickDate(year); }} key={year}> {year} </span> ))} </div> </div> </div> ); // endregion }; TYearSelector.defaultProps = {}; TYearSelector.displayName = 'TYearSelector'; export default TYearSelector;
import Card from 'react-bootstrap/Card' import Button from 'react-bootstrap/Button' import React from "react" import './card.css' import Spinner from 'react-spinkit' class ProjectEmbedCard extends React.Component { constructor(props) { super(props); this.state = { loading: true }; } hideSpinner = () => { this.setState({ loading: false }); }; render() { let button; if (this.props.newTab == "1") { button = <Button variant="primary" onClick={()=>window.open(this.props.newURL)}>{this.props.buttonText}</Button>; } else { button = <Button variant="primary" onClick={()=>window.location.href = this.props.newURL}>{this.props.buttonText}</Button>; } return ( <div className = "card2"> <Card style={{ }}> <Card.Img variant="top" src= {this.props.imgURL} /> <Card.Body> <Card.Title>{this.props.title}</Card.Title> <Card.Text> {this.props.text} </Card.Text> <div className="buffer"> <div className="minHeight"> <div className="container rsvp-wrapper"> {this.state.loading ? ( <Spinner className="loading text-center" name="three-bounce" color="Black" fadeIn="none" /> ) : null} {this.props.embedCode} </div> </div> </div> <Card.Title>{this.props.title2}</Card.Title> <Card.Text className="technologies"> {this.props.CHTML} </Card.Text> {button} </Card.Body> </Card> </div> ) } } export default ProjectEmbedCard