text
stringlengths
184
4.48M
import React, { useCallback, useEffect, useRef } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { setIsCompleted, setIsWatching, setLinkedColors } from '../../store/slicers/gameSlicer.js'; import GameStatus from './GameStatus/GameStatus.jsx'; import Engine from './Engine/Engine.jsx'; import Cell from './Cell/Cell.jsx'; import styles from './Game.module.css'; import { currCoordsSelector, gridDataSelector } from '../../store/selectors/gameSelectors.js'; import { getGameState, getGridData } from '../../utils/utils.js'; export default function Game() { const ref = useRef(); const dispatch = useDispatch(); const currCellCoords = useSelector(currCoordsSelector); const fields = useSelector(gridDataSelector); const handleMouseDown = useCallback((e) => { if ( /iPhone|iPad|iPod|Android/i.test(navigator.userAgent) && currCellCoords?.row !== null && getGridData()[currCellCoords.row][currCellCoords?.col].color !== null ) { e.preventDefault(); } dispatch(setIsWatching(true)); }, [currCellCoords]); const handleMouseUp = useCallback(() => { dispatch(setIsWatching(false)); }, []); const handleMouseLeave = () => { getGameState().isWatching && dispatch(setIsWatching(false)); } useEffect(() => { const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); if (!isMobile) { ref.current.addEventListener('mousedown', handleMouseDown); ref.current.addEventListener('mouseup', handleMouseUp); ref.current.addEventListener('mouseleave', handleMouseLeave); } else { ref.current.addEventListener('touchstart', handleMouseDown); document.addEventListener('touchend', handleMouseUp); document.addEventListener('touchcancel', handleMouseLeave); } return () => { if (!isMobile) { if (ref.current) { ref.current.removeEventListener('mousedown', handleMouseDown); ref.current.removeEventListener('mouseup', handleMouseUp); ref.current.removeEventListener('mouseleave', handleMouseLeave); } } else { ref.current && ref.current.removeEventListener('touchstart', handleMouseDown); document.removeEventListener('touchend', handleMouseUp); document.removeEventListener('touchcancel', handleMouseLeave); } } }, []); useEffect(() => { dispatch(setIsCompleted(false)); dispatch(setLinkedColors({})); return () => { dispatch(setIsCompleted(false)); dispatch(setLinkedColors({})); } }, []); return ( <section className={styles.gameSection}> {<Engine />} <ul ref={ref} className={`${[ styles.gameField, styles[`gameGrid${fields.length}`], ].join(' ')}`} > {fields.map((_, row) => { return _.map((item, col) => { return <Cell key={row + '' + col} {...{ row, col }} {...item} size={fields.length} /> }); })} </ul> {<GameStatus />} </section> ); }
import { TextField } from '@mui/material'; import { FC, useRef, useEffect } from 'react'; import { useFormContext, useWatch } from 'react-hook-form'; import { useAppDispatch } from 'redux-toolkit/hooks'; import { useDescriptionSelector, setDescription } from 'redux-toolkit/slices/currentPlaceSlice'; export const Description: FC = () => { const { control, register, formState: { errors }, setValue, } = useFormContext(); const description = useDescriptionSelector(); const dispatch = useAppDispatch(); const desc = useWatch({ control, name: 'description', }); const isFirstRender = useRef(true); useEffect(() => { if (isFirstRender.current) { setValue('description', description); isFirstRender.current = false; return; } dispatch(setDescription(desc)); }, [desc]); return ( <TextField fullWidth={true} {...register('description')} label="This is a description of my business!" multiline color="success" name="description" rows={10} variant="outlined" placeholder="Describe your business in few words" error={errors.description?.message ? true : false} helperText={errors.description?.message || `${description.length}/1000`} inputProps={{ maxLength: 1000, }} /> ); };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Youtube.com Clone</title> <link rel="stylesheet" href="styles/general.css"> <link rel="stylesheet" href="styles/header.css"> <link rel="stylesheet" href="styles/video.css"> <link rel="stylesheet" href="styles/sidebar.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet"> </head> <body> <header class="header"> <div class="left-section"> <img class="hamburger-menu" src="icons/hamburger-menu.svg"> <img class="youtube-logo" src="icons/youtube-logo.svg"> </div> <div class="middle-section"> <input class="search-bar" type="text" placeholder="Search"> <button class="search-button"> <img class="search-icon" src="icons/search.svg"> <div class="tooltip">Search</div> </button> <button class="voice-search-button"> <img class="voice-search-icon" src="icons/voice-search-icon.svg"> <div class="tooltip">Search with your voice</div> </button> </div> <div class="right-section"> <div class="upload-icon-container"> <img class="upload-icon" src="icons/upload.svg"> <div class="tooltip">Create</div> </div> <div class="youtube-apps-icon-container"> <img class="youtube-apps-icon" src="icons/youtube-apps.svg"> <div class="tooltip">YouTube Apps</div> </div> <div class="notifications-icon-container"> <img class="notifications-icon" src="icons/notifications.svg"> <div class="notifications-count">3</div> <div class="tooltip">Notifications</div> </div> <img class="current-user-picture" src="channel-pictures/my-channel.jpg"> </div> </header> <nav class="sidebar"> <div class="sidebar-link"> <img src="icons/home.svg"> <div>Home</div> </div> <div class="sidebar-link"> <img src="icons/explore.svg"> <div>Explore</div> </div> <div class="sidebar-link"> <img src="icons/subscriptions.svg"> <div>Subscriptions</div> </div> <div class="sidebar-link"> <img src="icons/originals.svg"> <div>Originals</div> </div> <div class="sidebar-link"> <img src="icons/youtube-music.svg"> <div>YouTube Music</div> </div> <div class="sidebar-link"> <img src="icons/library.svg"> <div>Library</div> </div> </nav> <main> <section class="video-grid"> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=n2RNcPRtAiY"> <img class="thumbnail" src="thumbnails/thumbnail-1.webp" alt=""> <div class="video-time">14:20</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/c/mkbhd"> <img class="profile-picture" src="channel-pictures/channel-1.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-1.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">Marques Brownlee</p> <p class="tooltip-subscribers">17.3M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=n2RNcPRtAiY"> <p class="video-title">Talking Tech and AI with Google CEO Sundar Pichai!</p> </a> <a href="https://www.youtube.com/c/mkbhd"> <p class="video-author">Marques Brownlee</p> </a> <p class="video-stats">3.4M views &#183; 6 months ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=mP0RAo9SKZk"> <img class="thumbnail" src="thumbnails/thumbnail-2.webp" alt=""> <div class="video-time">8:22</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/c/markiplier"> <img class="profile-picture" src="channel-pictures/channel-2.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-2.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">Markiplier</p> <p class="tooltip-subscribers">35.4M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=mP0RAo9SKZk"> <p class="video-title">Try Not To Laugh Challenge #9</p> </a> <a href="https://www.youtube.com/c/markiplier"> <p class="video-author">Markiplier</p> </a> <p class="video-stats">19M views &#183; 4 years ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=FgjPQQeTh1w"> <img class="thumbnail" src="thumbnails/thumbnail-3.webp" alt=""> <div class="video-time">9:13</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/user/SSSniperWolf"> <img class="profile-picture" src="channel-pictures/channel-3.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-3.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">SSSniperWolf</p> <p class="tooltip-subscribers">34M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=FgjPQQeTh1w"> <p class="video-title">Crazy Tik Toks Taken Moments Before DISASTER</p> </a> <a href="https://www.youtube.com/user/SSSniperWolf"> <p class="video-author">SSSniperWolf</p> </a> <p class="video-stats">12M views &#183; 1 year ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=094y1Z2wpJg"> <img class="thumbnail" src="thumbnails/thumbnail-4.webp" alt=""> <div class="video-time">22:09</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/c/veritasium"> <img class="profile-picture" src="channel-pictures/channel-4.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-4.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">Veritasium</p> <p class="tooltip-subscribers">14.1M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=094y1Z2wpJg"> <p class="video-title">The Simplest Math Problem No One Can Solve - Collatz Conjecture</p> </a> <a href="https://www.youtube.com/c/veritasium"> <p class="video-author">Veritasium</p> </a> <p class="video-stats">18M views &#183; 4 months ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=86CQq3pKSUw"> <img class="thumbnail" src="thumbnails/thumbnail-5.webp" alt=""> <div class="video-time">11:17</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/c/CSDojo"> <img class="profile-picture" src="channel-pictures/channel-5.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-5.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">CS Dojo</p> <p class="tooltip-subscribers">1.91M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=86CQq3pKSUw"> <p class="video-title">Kadane's Algorithm to Maximum Sum Subarray Problem</p> </a> <a href="https://www.youtube.com/c/CSDojo"> <p class="video-author">CS Dojo</p> </a> <p class="video-stats">519K views &#183; 5 years ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=yXWw0_UfSFg"> <img class="thumbnail" src="thumbnails/thumbnail-6.webp" alt=""> <div class="video-time">19:59</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/channel/UCX6OQ3DkcsbYNE6H8uQQuVA"> <img class="profile-picture" src="channel-pictures/channel-6.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-6.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">MrBeast</p> <p class="tooltip-subscribers">174M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=yXWw0_UfSFg"> <p class="video-title">Anything You Can Fit In The Circle I'll Pay For</p> </a> <a href="https://www.youtube.com/channel/UCX6OQ3DkcsbYNE6H8uQQuVA"> <p class="video-author">MrBeast</p> </a> <p class="video-stats">141M views &#183; 1 year ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=fNVa1qMbF9Y"> <img class="thumbnail" src="thumbnails/thumbnail-7.webp" alt=""> <div class="video-time">10:13</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/channel/UCP5tjEmvPItGyLhmjdwP7Ww"> <img class="profile-picture" src="channel-pictures/channel-7.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-7.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">RealLifeLore</p> <p class="tooltip-subscribers">6.98M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=fNVa1qMbF9Y"> <p class="video-title">Why Planes Don't Fly Over Tibet</p> </a> <a href="https://www.youtube.com/channel/UCP5tjEmvPItGyLhmjdwP7Ww"> <p class="video-author">RealLifeLore</p> </a> <p class="video-stats">6.6M views &#183; 1 year ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=lFm4EM1juls"> <img class="thumbnail" src="thumbnails/thumbnail-8.webp" alt=""> <div class="video-time">7:12</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/channel/UCHAK6CyegY22Zj2GWrcaIxg"> <img class="profile-picture" src="channel-pictures/channel-8.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-8.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">Tech Vision</p> <p class="tooltip-subscribers">816K subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=lFm4EM1juls"> <p class="video-title">Inside The World's Biggest Passenger Plane</p> </a> <a href="https://www.youtube.com/channel/UCHAK6CyegY22Zj2GWrcaIxg"> <p class="video-author">Tech Vision</p> </a> <p class="video-stats">3.7M views &#183; 10 months ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=ixmxOlcrlUc"> <img class="thumbnail" src="thumbnails/thumbnail-9.webp" alt=""> <div class="video-time">13:17</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/c/OFFICIALTHENXSTUDIOS"> <img class="profile-picture" src="channel-pictures/channel-9.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-9.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">ThenX</p> <p class="tooltip-subscribers">7.68M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=ixmxOlcrlUc"> <p class="video-title">The SECRET to Super Human STRENGTH</p> </a> <a href="https://www.youtube.com/c/OFFICIALTHENXSTUDIOS"> <p class="video-author">ThenX</p> </a> <p class="video-stats">20M views &#183; 3 years ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=R2vXbFp5C9o"> <img class="thumbnail" src="thumbnails/thumbnail-10.webp" alt=""> <div class="video-time">7:53</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/user/businessinsider"> <img class="profile-picture" src="channel-pictures/channel-10.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-10.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">Business Insider</p> <p class="tooltip-subscribers">8.02M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=R2vXbFp5C9o"> <p class="video-title">How The World's Largest Cruise Ship Makes 30,000 Meals Every Day</p> </a> <a href="https://www.youtube.com/user/businessinsider"> <p class="video-author">Business Insider</p> </a> <p class="video-stats">14M views &#183; 1 year ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=0nZuYyXET3s"> <img class="thumbnail" src="thumbnails/thumbnail-11.webp" alt=""> <div class="video-time">4:10</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/c/Destinationtips"> <img class="profile-picture" src="channel-pictures/channel-11.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-11.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">Destination Tips</p> <p class="tooltip-subscribers">282K subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=0nZuYyXET3s"> <p class="video-title">Dubai's Crazy Underwater Train and Other Things #Only in Dubai</p> </a> <a href="https://www.youtube.com/c/Destinationtips"> <p class="video-author">Destination Tips</p> </a> <p class="video-stats">3M views &#183; 1 year ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <a href="https://www.youtube.com/watch?v=9iMGFqMmUFs"> <img class="thumbnail" src="thumbnails/thumbnail-12.webp" alt=""> <div class="video-time">4:51</div> </a> </div> <div class="video-info-grid"> <div> <div class="channel-picture"> <a href="https://www.youtube.com/teded"> <img class="profile-picture" src="channel-pictures/channel-12.jpeg" alt=""> </a> <div class="channel-tooltip"> <div class="tooltip-image-container"> <img class="tooltip-image" src="channel-pictures/channel-12.jpeg"> </div> <div class="tooltip-info-container"> <p class="tooltip-author">TED-Ed</p> <p class="tooltip-subscribers">18.9M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <a href="https://www.youtube.com/watch?v=9iMGFqMmUFs"> <p class="video-title">What would happen if you didn't drink water? - Mia Nacamulli</p> </a> <a href="https://www.youtube.com/teded"> <p class="video-author">TED-Ed</p> </a> <p class="video-stats">12M views &#183; 5 years ago</p> </div> </div> </div> </section> </main> </body> </html>
<!DOCTYPE html> <html lang="pt-BR"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DOM</title> <style> body{ background: rgb(100, 100, 199); color: white; font: normal 18pt Arial; } </style> </head> <body> <h1>Iniciando estudos com DOM</h1> <p>Aqui vai o resultado</p> <p>Aprendendo a usar o <strong>DOM</strong> em Javascript.</p> <div id='msg'>Clique em mim</div> <script> //usar WATCH IN CHROME (pra pagina do chrome atualizar ao mesmo tempo q modificamos o arquivo aqui) //comando Ctrl + Shift + P e digitar "Watch in Chrome" //window.document.write(window.navigator.appName); //window.document.write(window.document.URL); var corpo = window.document.body; var p1 = window.document.getElementsByTagName('p')[1]; //window.document.write(p1.innerText); //var d = window.document.getElementById('msg'); //d.style.background = 'green'; //d.innerText = 'Estou aguardando...'; //window.document.getElementById('msg').innerText = 'Olá'; //assim fica mto grande //var d = window.document.getElementsByName('msg')[0] //d.innerText = 'Olá' var d = window.document.querySelector('div#msg'); //se é id bota essa #, se for class bota ponto . d.style.background = 'blue'; </script> </body> </html>
import { Card, CardContent, Typography } from "@mui/material" import React from "react" import { useSelector } from "react-redux" import "./user-info-styles.scss" export const UserInfo = () => { const currentUser = useSelector((state) => state.user.currentUser) return ( <div className="card-container"> <Card variant="outlined" className="card"> <CardContent> <Typography variant="h5" component="h2"> Signed In As: </Typography> {currentUser ? ( <div> <Typography variant="body1"> <strong>Name:</strong> {currentUser.displayName} </Typography> <Typography variant="body1"> <strong>Email:</strong> {currentUser.email} </Typography> <Typography variant="body1"> <strong>UID:</strong> {currentUser.uid} </Typography> <Typography variant="body1"> <strong>Creation Date:</strong>{" "} {new Date( currentUser.metadata.creationTime ).toLocaleDateString()} </Typography> </div> ) : ( <Typography variant="body1">Loading user information...</Typography> )} </CardContent> </Card> </div> ) }
import React, { ChangeEventHandler } from 'react'; import { Dialog, DialogContent, DialogActions, Select, InputLabel, createMuiTheme, MuiThemeProvider, MenuItem, Checkbox, ListItemText } from '@material-ui/core'; import { StyledTextField, StyledFormControl, StyledCircularProgressPrimary } from '../../../global/globalStyles'; import { StyledDialogButton } from '../productSectionForm/styles'; import { Title, RowContainer, NumberInput } from './styles'; import { ProductSection } from '../../../../domain/entities/ProductSection'; import CurrencyInput from '../../../components/CurrencyInput/CurrencyInput'; import { OptionalSection } from '../../../../domain/entities/OptionalSection'; import AvatarInput from '../../../components/AvatarInput/AvatarInput'; type ProductFormProps = { open: boolean, edit: boolean, handleClose: ChangeEventHandler, handleSave: ChangeEventHandler, handleTitleChange: ChangeEventHandler, handleDescriptionChange: ChangeEventHandler, handleAvatarChange: ChangeEventHandler, handlePriceChange: ChangeEventHandler, handleOptionalChange: ChangeEventHandler, handleProductSectionChange: ChangeEventHandler, image: string, title: string, description: string, price: string, optionals: OptionalSection[], selectedOptionals: number[], selectedProductSection: number, productSections: ProductSection[], loading: boolean, errorTitle?: string, errorDescription?: string, errorProductSection?: string, errorPrice?: string, } export default function ProductForm(props: ProductFormProps): JSX.Element { const theme = createMuiTheme({ palette: { primary: { 500: '#880e4f' } }, }); function handleCloseClick(event: any): void { props.handleClose(event) } function handleSaveClick(event: any): void { props.handleSave(event) } function handleChangeOptional(event: any): void { props.handleOptionalChange(event) } function handlePriceChange(event: any): void { props.handlePriceChange(event) } function handleProductSectionChange(event: any): void { props.handleProductSectionChange(event) } function handleAvatarChange(event: any): void { props.handleAvatarChange(event) } function renderValueOptionalsSelected(ids: number[]): string[] { const result: string[] = [] for (const i of ids) { for (const j of props.optionals) { if (i === j.id) { result.push(j.name) } } } return result } return (<div> <Dialog open={props.open} onClose={props.handleClose} aria-labelledby="form-dialog-title"> <Title>Novo produto</Title> <DialogContent> <AvatarInput variant="square" preview={props.image} handlerImageChange={handleAvatarChange}></AvatarInput> <StyledTextField error={props.errorTitle !== undefined && props.errorTitle !== ''} helperText={props.errorTitle} autoFocus variant="filled" id="name" label="Nome" type="text" fullWidth InputProps={{ classes: { underline: 'underline' }, disableUnderline: false }} value={props.title} onChange={props.handleTitleChange} /> <StyledTextField error={props.errorDescription !== undefined && props.errorDescription !== ''} helperText={props.errorDescription} variant="filled" id="name" label="Descrição" multiline rowsMax={4} type="text" fullWidth InputProps={{ classes: { underline: 'underline' }, disableUnderline: false }} value={props.description} onChange={props.handleDescriptionChange} /> <MuiThemeProvider theme={theme}> <StyledFormControl variant="filled" error={props.errorProductSection !== undefined && props.errorProductSection !== ''}> <InputLabel>Categoria</InputLabel> <Select label="Categoria" value={props.selectedProductSection || ''} onChange={handleProductSectionChange}> {props.productSections.map(section => { return (<MenuItem key={section.id} value={section.id}>{section.name}</MenuItem>); })} </Select> </StyledFormControl> </MuiThemeProvider> <RowContainer> <StyledFormControl variant="filled" > <InputLabel>Opcionais</InputLabel> <Select multiple label="Opcionais" value={props.selectedOptionals} onChange={handleChangeOptional} renderValue={(selected) => (renderValueOptionalsSelected(selected as number[])).join(', ')}> {props.optionals.map((optionalSection: OptionalSection) => ( <MenuItem key={optionalSection.id} value={optionalSection.id}> <Checkbox checked={props.selectedOptionals.findIndex(i => i === optionalSection.id) > -1} /> <ListItemText primary={optionalSection.name} /> </MenuItem> ))} </Select> </StyledFormControl> <NumberInput error={props.errorPrice !== undefined && props.errorPrice !== ''} helperText={props.errorPrice} label="Preço" variant="filled" onChange={(e) => handlePriceChange(e)} value={props.price} InputProps={{ inputComponent: CurrencyInput as any }} /> </RowContainer> </DialogContent> <DialogActions> <StyledDialogButton onClick={handleCloseClick} color="primary"> Cancelar </StyledDialogButton> <StyledDialogButton disabled={props.loading} onClick={handleSaveClick} color="primary"> {props.loading ? <StyledCircularProgressPrimary /> : <>Salvar</>} </StyledDialogButton> </DialogActions> </Dialog> </div>); }
/* * The JabaJaba class library * Copyright (C) 1997-2003 ASAMI, Tomoharu (asami@AsamiOffice.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package com.AsamiOffice.xml; import java.net.MalformedURLException; import java.net.URL; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.AsamiOffice.io.UURL; import com.AsamiOffice.text.UString; /** * UElement * * @since Jan. 17, 2000 * @version Oct. 19, 2003 * @author ASAMI, Tomoharu (asami@AsamiOffice.com) */ public final class UElement { // element public static Element[] getElements(Element element) { NodeList children = element.getChildNodes(); List list = new ArrayList(); int size = children.getLength(); for (int i = 0;i < size;i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { list.add(child); } } Element[] array = new Element[list.size()]; return ((Element[])list.toArray(array)); } public static Element[] getElements( Element element, String name ) { NodeList children = element.getChildNodes(); List list = new ArrayList(); int size = children.getLength(); for (int i = 0;i < size;i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { Element candidate = (Element)child; if (name.equals(candidate.getTagName())) { list.add(child); } } } Element[] array = new Element[list.size()]; return ((Element[])list.toArray(array)); } public static Element[] getElements( Element element, String namespaceURI, String localName ) { NodeList children = element.getChildNodes(); List list = new ArrayList(); int size = children.getLength(); for (int i = 0;i < size;i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { SmartElement candidate = new SmartElement((Element)child); if (candidate.isTag(namespaceURI, localName)) { list.add(child); } } } Element[] array = new Element[list.size()]; return ((Element[])list.toArray(array)); } public static Element getOnlyElement(Element element, String name) throws IllegalArgumentException { Element[] elements = getElements(element, name); switch (elements.length) { case 0: return (null); case 1: return (elements[0]); default: throw (new IllegalArgumentException()); } } public static Element getOnlyElement( Element element, String uri, String name ) throws IllegalArgumentException { Element[] elements = getElements(element, uri, name); switch (elements.length) { case 0: return (null); case 1: return (elements[0]); default: throw (new IllegalArgumentException()); } } public static Element[] getElementsRecursive( Element element, String name ) { NodeList nodes = element.getElementsByTagName(name); Element[] elements = new Element[nodes.getLength()]; for (int i = 0;i < elements.length;i++) { elements[i] = (Element)nodes.item(i); } return (elements); } public static Element getOnlyElementRecursive( Element element, String name ) throws IllegalArgumentException { NodeList nodes = element.getElementsByTagName(name); switch (nodes.getLength()) { case 0: return (null); case 1: break; default: throw (new IllegalArgumentException()); } return ((Element)nodes.item(0)); } // attribute operation public static String getAttributeAsCDATA(Element element, String name) { return (UString.checkNull(element.getAttribute(name))); } public static String getAttributeAsNMTOKEN(Element element, String name) { String cdata = UString.checkNull(element.getAttribute(name)); if (cdata == null) { return (null); } return (cdata.trim()); // XXX : check precise spec } public static String[] getAttributeAsNMTOKENS( Element element, String name ) { String cdata = UString.checkNull(element.getAttribute(name)); if (cdata == null) { return (null); } return (UString.getTokens(cdata)); } public static String getAttributeAsString(Element element, String name) { return (UString.checkNull(element.getAttribute(name))); } public static boolean getAttributeAsBoolean( Element element, String name ) { return (getAttributeAsBoolean(element, name, false)); } public static boolean getAttributeAsBoolean( Element element, String name, boolean defaultValue ) { String value = UString.checkNull(element.getAttribute(name)); if (value == null) { return (defaultValue); } if (value.equals("true")) { return (true); } else if (value.equals("false")) { return (false); } else { return (true); } } public static Number getAttributeAsNumber(Element element, String name) { return (getAttributeAsNumber(element, name, null)); } public static Number getAttributeAsNumber( Element element, String name, Number defaultValue ) { String value = UString.checkNull(element.getAttribute(name)); if (value == null) { return (defaultValue); } try { NumberFormat format = NumberFormat.getInstance(); Number number = format.parse(value); return (number); // XXX : Integer, Float } catch (ParseException e) { return (defaultValue); } } public static URL getAttributeAsURL(Element element, String name) throws MalformedURLException { String value = UString.checkNull(element.getAttribute(name)); if (value == null) { return (null); } return (new URL(value)); } public static URL getAttributeAsURLByFileOrURLName( Element element, String name ) throws IllegalArgumentException { String value = UString.checkNull(element.getAttribute(name)); if (value == null) { return (null); } try { return (UURL.getURLFromFileOrURLName(value)); } catch (MalformedURLException e) { throw (new InternalError()); // XXX } } public static URL getAttributeAsURLByFileOrURLNameWithXMLBase( Element element, String name ) throws IllegalArgumentException { return ( getAttributeAsURLByFileOrURLNameWithXMLBase(element, name, null) ); } public static URL getAttributeAsURLByFileOrURLNameWithXMLBase( Element element, String name, String baseURI ) throws IllegalArgumentException { String value = UString.checkNull(element.getAttribute(name)); if (value == null) { return (null); } try { URL url = new URL(value); return (url); } catch (MalformedURLException e) { } String xmlBase = UElement.getXMLBaseAsString(element); if (xmlBase != null) { if (!xmlBase.endsWith("/")) { xmlBase = xmlBase + "/"; } value = xmlBase + value; } try { URL url = new URL(value); return (url); } catch (MalformedURLException e) { } if (baseURI != null) { if (!baseURI.endsWith("/")) { baseURI = baseURI + "/"; } value = baseURI + value; } try { return (UURL.getURLFromFileOrURLName(value)); } catch (MalformedURLException e) { throw (new InternalError()); // XXX } } public static int getAttributeAsEnumerationNumber( Element element, String name, String[] candidates, int base ) { String value = UString.checkNull(element.getAttribute(name)); if (value == null) { return (-1); } for (int i = 0;i < candidates.length;i++) { if (candidates[i].equals(value)) { return (base + i); } } return (-1); } public static int getAttributeAsEnumerationNumber( Element element, String name, String[] candidates, int base, String defaultValue ) { String value = UString.checkNull(element.getAttribute(name)); if (value == null) { value = defaultValue; } for (int i = 0;i < candidates.length;i++) { if (candidates[i].equals(value)) { return (base + i); } } return (-1); } // method and attribute public static String getAttributeOfOnlyElementAsString( Element element, String tagName, String attrName ) throws IllegalArgumentException { Element target = getOnlyElement(element, tagName); if (target == null) { return (null); } return (UString.checkNull(target.getAttribute(attrName))); } public static String getAttributeOfOnlyElementRecursiveAsString( Element element, String tagName, String attrName ) throws IllegalArgumentException { Element target = getOnlyElementRecursive(element, tagName); if (target == null) { return (null); } return (UString.checkNull(target.getAttribute(attrName))); } public static Integer getAttributeOfOnlyElementAsInteger( Element element, String tagName, String attrName ) throws IllegalArgumentException { String data = getAttributeOfOnlyElementAsString( element, tagName, attrName ); if (data == null) { return (null); } return (Integer.valueOf(data)); } public static Float getAttributeOfOnlyElementAsFloat( Element element, String tagName, String attrName ) throws IllegalArgumentException { String data = getAttributeOfOnlyElementAsString( element, tagName, attrName ); if (data == null) { return (null); } return (Float.valueOf(data)); } public static Double getAttributeOfOnlyElementAsDouble( Element element, String tagName, String attrName ) throws IllegalArgumentException { String data = getAttributeOfOnlyElementAsString( element, tagName, attrName ); if (data == null) { return (null); } return (Double.valueOf(data)); } // data operation public static String getData(Element element) { return (UDOM.getDataValue(element)); } public static Number getDataAsNumber(Element element) { String data = getData(element); if (UString.isNull(data)) { return (null); } try { NumberFormat format = NumberFormat.getInstance(); Number number = format.parse(data); return (number); // XXX : Integer, Float } catch (ParseException e) { return (null); } } public static Number getDataAsNumber(Element element, String name) { NodeList nodes = element.getElementsByTagName(name); if (nodes == null) { return (null); } if (nodes.getLength() == 0) { return (null); } return (getDataAsNumber((Element)nodes.item(0))); } public static Long getDataAsLong(Element element) { String data = getData(element); if (UString.isNull(data)) { return (null); } try { Long number = Long.valueOf(data); return (number); } catch (NumberFormatException e) { return (null); } } public static Long getDataAsLong(Element element, String name) { NodeList nodes = element.getElementsByTagName(name); if (nodes == null) { return (null); } if (nodes.getLength() == 0) { return (null); } return (getDataAsLong((Element)nodes.item(0))); } // xml base public static String getXMLBaseAsString(Element root) { String uri = null; Node node = root; for (;;) { Element element = (Element)node; uri = UString.checkNull(element.getAttribute("xml:base")); if (uri != null) { try { URL url = new URL(uri); return (uri); } catch (MalformedURLException e) { } break; } node = node.getParentNode(); if (node == null) { return (null); } if (!(node instanceof Element)) { return (null); } } for (;;) { node = node.getParentNode(); if (node == null) { return (uri); } if (!(node instanceof Element)) { return (uri); } Element element = (Element)node; String base = UString.checkNull(element.getAttribute("xml:base")); if (base != null) { uri = base + uri; } try { URL url = new URL(uri); return (uri); } catch (MalformedURLException e) { } } } // update public static void appendElement( Element element, String tagName, String data ) { Document doc = element.getOwnerDocument(); Element item = doc.createElement(tagName); item.appendChild(doc.createTextNode(data)); element.appendChild(item); } public static void appendElement( Element element, String tagName, String attrName, String data ) { Document doc = element.getOwnerDocument(); Element item = doc.createElement(tagName); item.setAttribute(attrName, data); element.appendChild(item); } public static void updateElement( Element target, Element data, String keyAttr ) { updateElement(target, data, new String[] { keyAttr }); } public static void updateElement( Element target, Element data, String[] keyAttrs ) { String tagName = data.getTagName(); NodeList nodes = target.getElementsByTagName(tagName); int nNodes = nodes.getLength(); for (int i = 0;i < nNodes;i++) { Element element = (Element)nodes.item(i); if (_isSameAttrs(element, data, keyAttrs)) { target.replaceChild(data, element); return; } } target.appendChild(data); } protected static boolean _isSameAttrs( Element lhs, Element rhs, String[] attrs ) { for (int i = 0;i < attrs.length;i++) { String attr = attrs[i]; if (!lhs.getAttribute(attr).equals(rhs.getAttribute(attr))) { return (false); } } return (true); } }
import { TestBed } from '@angular/core/testing'; import { FirebaseModule } from '@app/firebase/firebase.module'; import { lastValueFrom } from 'rxjs'; import { UserService } from './user.service'; describe('UserService', () => { let service: UserService; beforeEach(() => { TestBed.configureTestingModule({ imports: [FirebaseModule], }); service = TestBed.inject(UserService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should login/register new user', async () => { expect(['Logged in successfully.', 'Registered successfully.']).toContain( await service.loginOrRegister('test@test.fm', 'test@test.fm') ); expect(await lastValueFrom(service.currentUser$)).toBeTruthy(); }); it('should logout', async () => { expect(await service.logout()).toBe('Logged out successfully.'); expect(await lastValueFrom(service.currentUser$)).toBeFalsy(); }); });
import json import pytest from pokemon import retrieve_pokemons_by_type from io import StringIO from unittest.mock import mock_open, patch from pokemon import retrieve_pokemons_by_type # Criamos o contexto de um pokemon do tipo grama @pytest.fixture def grass_type_pokemon(): return { "national_number": "001", "evolution": None, "name": "Bulbasaur", "type": ["Grass", "Poison"], "total": 318, "hp": 45, "attack": 49, "defense": 49, "sp_atk": 65, "sp_def": 65, "speed": 45, } # Criamos o contexto de um pokemon do tipo água @pytest.fixture def water_type_pokemon(): return { "national_number": "007", "evolution": None, "name": "Squirtle", "type": ["Water"], "total": 314, "hp": 44, "attack": 48, "defense": 65, "sp_atk": 50, "sp_def": 64, "speed": 43, } def test_retrieve_pokemons_by_type(grass_type_pokemon, water_type_pokemon): # criamos um arquivo em memória que o seu conteúdo são os dois pokemons fake_file = StringIO( json.dumps({"results": [grass_type_pokemon, water_type_pokemon]}) ) # quando pesquisamos por pokemons do tipo grama, # o pokemon do tipo água não deve ser retornado assert grass_type_pokemon in retrieve_pokemons_by_type("Grass", fake_file) def test_retrieve_pokemons_by_type(): # definimos um pokemon do tipo grama grass_type_pokemon = { "national_number": "001", "evolution": None, "name": "Bulbasaur", "type": ["Grass", "Poison"], "total": 318, "hp": 45, "attack": 49, "defense": 49, "sp_atk": 65, "sp_def": 65, "speed": 45, } # definimos também um pokemon do tipo água water_type_pokemon = { "national_number": "007", "evolution": None, "name": "Squirtle", "type": ["Water"], "total": 314, "hp": 44, "attack": 48, "defense": 65, "sp_atk": 50, "sp_def": 64, "speed": 43, } pokemon_json_content = json.dumps({"results": [grass_type_pokemon, water_type_pokemon]}) # substituímos a função padrão do python open por mock_open # uma versão que se comporta de forma parecida, porém simulada with patch("builtins.open", mock_open(read_data=pokemon_json_content)): # repare que o nome do arquivo não é importante aqui # a esses parâmetros não utilizados damos o nome de dummies # como neste contexto alteramos o open pelo mock_open, # o argumento "dummy" poderia ser substituído por qualquer coisa, já que não será utilizado pela função assert retrieve_pokemons_by_type("Grass", "dummy") == [ grass_type_pokemon ]
from odoo import api, fields, models from odoo.exceptions import UserError,ValidationError import math class ConcreteSplitTensileStrength(models.Model): _name = "mechanical.concrete.split.tensile" _inherit = "lerm.eln" _rec_name = "name" name = fields.Char("Name",default="Concrete Split Tensile Strength") parameter_id = fields.Many2one('eln.parameters.result',string="Parameter") sample_parameters = fields.Many2many('lerm.parameter.master',string="Parameters",compute="_compute_sample_parameters",store=True) grade = fields.Many2one('lerm.grade.line',string="Grade",compute="_compute_grade_id",store=True) eln_ref = fields.Many2one('lerm.eln',string="Eln") age_of_days = fields.Selection([ ('3days', '3 Days'), ('7days', '7 Days'), ('14days', '14 Days'), ('28days', '28 Days'), ], string='Age', default='28days',required=True,compute="_compute_age_of_days") date_of_casting = fields.Date(string="Date of Casting",compute="compute_date_of_casting") date_of_testing = fields.Date(string="Date of Testing") age_of_test = fields.Integer("Age of Test, days",compute="compute_age_of_test") difference = fields.Integer("Difference",compute="compute_difference") splite_tensile_name = fields.Char("Name",default="Concrete Split Tensile Strength") splite_tensile_visible = fields.Boolean("Concrete Split Tensile Strength Visible",compute="_compute_visible") child_lines = fields.One2many('mechanical.concrete.split.tensile.line','parent_id',string="Parameter") average_split_tensile = fields.Float(string="Average Split Tensile Strength (N/mm2)",compute="_compute_average_split_tensile") @api.onchange('eln_ref') def _compute_age_of_days(self): for record in self: if record.eln_ref.sample_id: sample_record = self.env['lerm.srf.sample'].search([('id','=', record.eln_ref.sample_id.id)]).days_casting if sample_record == '3': record.age_of_days = '3days' elif sample_record == '7': record.age_of_days = '7days' elif sample_record == '14': record.age_of_days = '14days' elif sample_record == '28': record.age_of_days = '28days' else: record.age_of_days = None else: record.age_of_days = None @api.onchange('eln_ref') def compute_date_of_casting(self): for record in self: if record.eln_ref.sample_id: sample_record = self.env['lerm.srf.sample'].search([('id','=', record.eln_ref.sample_id.id)]).date_casting record.date_of_casting = sample_record else: record.date_of_casting = None @api.depends('date_of_testing','date_of_casting') def compute_age_of_test(self): for record in self: if record.date_of_casting and record.date_of_testing: date1 = fields.Date.from_string(record.date_of_casting) date2 = fields.Date.from_string(record.date_of_testing) date_difference = (date2 - date1).days record.age_of_test = date_difference else: record.age_of_test = 0 @api.depends('age_of_test','age_of_days') def compute_difference(self): for record in self: age_of_days = 0 if record.age_of_days == '3days': age_of_days = 3 elif record.age_of_days == '7days': age_of_days = 7 elif record.age_of_days == '14days': age_of_days = 14 elif record.age_of_days == '28days': age_of_days = 28 else: age_of_days = 0 record.difference = record.age_of_test - age_of_days @api.depends('child_lines.split_strength') def _compute_average_split_tensile(self): for record in self: split_strengths = record.child_lines.mapped('split_strength') if split_strengths: record.average_split_tensile = sum(split_strengths) / len(split_strengths) else: record.average_split_tensile = 0.0 @api.depends('eln_ref') def _compute_grade_id(self): if self.eln_ref: self.grade = self.eln_ref.grade_id.id ### Compute Visible @api.depends('sample_parameters') def _compute_visible(self): for record in self: record.splite_tensile_visible = False for sample in record.sample_parameters: print("Internal Ids",sample.internal_id) if sample.internal_id == "51ff18a6-226c-4dbf-9389-7cc72b090e66": record.splite_tensile_visible = True def open_eln_page(self): # import wdb; wdb.set_trace() return { 'view_mode': 'form', 'res_model': "lerm.eln", 'type': 'ir.actions.act_window', 'target': 'current', 'res_id': self.eln_ref.id, } @api.model def create(self, vals): # import wdb;wdb.set_trace() record = super(ConcreteSplitTensileStrength, self).create(vals) # record.get_all_fields() record.eln_ref.write({'model_id':record.id}) return record @api.depends('eln_ref') def _compute_sample_parameters(self): # records = self.env['lerm.eln'].search([('id','=', record.eln_id.id)]).parameters_result # print("records",records) # self.sample_parameters = records for record in self: records = record.eln_ref.parameters_result.parameter.ids record.sample_parameters = records print("Records",records) def get_all_fields(self): record = self.env['mechanical.concrete.split.tensile'].browse(self.ids[0]) field_values = {} for field_name, field in record._fields.items(): field_value = record[field_name] field_values[field_name] = field_value return field_values class ConcreteSplitTensileStrengthLine(models.Model): _name = "mechanical.concrete.split.tensile.line" parent_id = fields.Many2one('mechanical.concrete.split.tensile',string="Parent Id") sr_no = fields.Integer(string="Sr.No.",readonly=True, copy=False, default=1) id_mark = fields.Char(string="ID MARK/ Location") wt_of_cylender = fields.Float(string="Weight of Cylinder Kg") height = fields.Float(string="Height mm") diameter = fields.Float(string="Diameter mm") breaking_load = fields.Float(string="Breaking Load KN") split_strength = fields.Float(string="Split Tensile Strength N/mm2",compute="_compute_split_strength") @api.depends('breaking_load', 'height', 'diameter') def _compute_split_strength(self): for record in self: if record.breaking_load and record.height and record.diameter: record.split_strength = (2 * record.breaking_load) / (3.14 * record.height * record.diameter) * 1000 else: record.split_strength = 0.0 @api.model def create(self, vals): # Set the serial_no based on the existing records for the same parent if vals.get('parent_id'): existing_records = self.search([('parent_id', '=', vals['parent_id'])]) if existing_records: max_serial_no = max(existing_records.mapped('sr_no')) vals['sr_no'] = max_serial_no + 1 return super(ConcreteSplitTensileStrengthLine, self).create(vals) def _reorder_serial_numbers(self): # Reorder the serial numbers based on the positions of the records in child_lines records = self.sorted('id') for index, record in enumerate(records): record.sr_no = index + 1
import { Route, Routes } from 'react-router-dom' import { useDispatch } from 'react-redux' import Home from './routes/home' import Topbar from './components/topbar' import Authentication from './routes/authentication' import Shop from './routes/shop' import Product from './routes/product' import Checkout from './routes/checkout' import Category from './routes/category' import { checkUserSession } from './store/user/userAction' import { useEffect } from 'react' function App () { const dispatch = useDispatch() // @ts-ignore useEffect(() => dispatch(checkUserSession()), []) return ( <Routes> <Route path="/" element={<Topbar />}> <Route index element={<Home />} /> <Route path="shop/*" element={<Shop />}> <Route path=":category" element={<Category />} /> </Route> <Route path="auth" element={<Authentication />} /> <Route path="product/:id" element={<Product />} /> <Route path="checkout" element={<Checkout />} /> </Route> </Routes> ) } export default App
import moment from 'moment'; import 'moment/dist/locale/es'; import 'moment/dist/locale/fr'; import 'moment/dist/locale/en-gb'; const format = 'DD MMM YYYY, hh:mm A'; const format2 = 'ddd DD MMM YYYY, hh:mm A Z'; const getLocale = () => { const localeStorage = localStorage.getItem('i18nextLng'); if (localeStorage === 'en') return 'en-gb'; if (localeStorage === 'es') return 'es'; if (localeStorage === 'fr') return 'fr'; return 'en-gb'; }; moment.locale(getLocale()); export function mapDate(object) { try { return moment(object).format(format); } catch (error) { console.error('mapDate: ', error.message); } return ''; } export function mapDatefromUtcToLocalTime(object) { try { return moment(object).format(format2); } catch (error) { console.error('mapDate: ', error.message); } return ''; } export const convertSecondsToTime = (value) => { const convertSeconds = (seconds) => { const days = Math.floor(seconds / (3600 * 24)); seconds -= days * 3600 * 24; const hrs = Math.floor(seconds / 3600); seconds -= hrs * 3600; const mnts = Math.floor(seconds / 60); seconds -= mnts * 60; return { days, hrs, mnts, seconds }; }; if (value) { const { days, hrs, mnts, seconds } = convertSeconds(value); let timeString = ''; if (days > 0) { timeString += `${days} D, `; } if (days > 0 || hrs > 0) { timeString += `${hrs} H, `; } if (days > 0 || hrs > 0 || mnts > 0) { timeString += `${mnts} M, `; } timeString += `${Number.parseFloat(seconds).toFixed(2)} S`; return timeString; } return 0; };
import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import {faClock} from "@fortawesome/free-solid-svg-icons"; import SongItemContainer from '../songs/song_item_container'; import {faPlayCircle,faPauseCircle} from "@fortawesome/free-solid-svg-icons"; import {calculateTotalTimeLength} from '../../util/helper_functions'; import {Link} from 'react-router-dom'; class ArtistShowPage extends React.Component { constructor(props){ super(props) this.state = {}; } componentDidMount() { this.props.fetchArtists(); } playSong(song, queue){ this.props.setCurrentSong(song); this.props.setQueue(queue); } handlePlayback(){ const {artist_songs,player,togglePlayback} = this.props; if(artist_songs.includes(player.currentSong)){ togglePlayback(); }else{ this.playSong(artist_songs[0], artist_songs.slice(1)); } } render(){ const {albums,artist,artist_songs,player} = this.props; if (!albums || !artist) return null; const artistAlbums = Object.values(albums).filter(album => album.artist_id === artist.id); return ( <div className="show-body"> <div className="show-page-header"> <img className="show-page-cover-img" src={artist.imageUrl} alt={artist.name}/> <div className="detail-content"> <p>ARTIST</p> <h1>{artist.name}</h1> <p> <span className="album-artist-name"> {artist.name} </span> {` • ${artist_songs.length} songs, ${calculateTotalTimeLength(artist_songs)}`} </p> </div> </div> <FontAwesomeIcon icon={player.playing && artist_songs.includes(player.currentSong) ? faPauseCircle : faPlayCircle} className="show-page play-btn" size="2xl" onClick={()=> this.handlePlayback()} /> <div className='albums-section-container'> <h1 className='section-header'>Albums</h1> <div className='search-index-grid'> { artistAlbums.length === 0 ? <p>No albums found</p> : artistAlbums.map(album => <Link to={`/home/albums/${album.id}`} key={album.id}> <div className="body-section-2"> <img src={album.imageUrl} className='body-section-2-img' alt={album.album_name}/> <h3>{album.album_name}</h3> </div> </Link> ) } </div> </div> <div className="show-content"> <h1 className='section-header songs'>Songs</h1> <div className="songs-header"> <div className='header-text-labels'> <p>#</p> <p>TITLE</p> </div> <FontAwesomeIcon className='clock-icon' icon={faClock} /> </div> <ul className='album-song-list'> {artist_songs.map((song,idx)=> <SongItemContainer key ={song.id} song={song} queue={artist_songs} idx={idx+1} /> )} </ul> </div> </div> ) } } export default ArtistShowPage
我每天使用 Git ,但是很多命令记不住。 一般来说,日常使用只要记住下图6个命令,就可以了。但是熟练使用,恐怕要记住60~100个命令。 ![img](D:%5Cdeng_de_rong%5Cdocs%5Cdoc_images_%5Cbg2015120901.png) 下面是我整理的常用 Git 命令清单。几个专用名词的译名如下。 > - Workspace:工作区 > - Index / Stage:暂存区 > - Repository:本地仓库 > - Remote:远程仓库 ## 一、新建代码库 > ```bash > # 在当前目录新建一个Git代码库 > $ git init > > # 新建一个目录,将其初始化为Git代码库 > $ git init [project-name] > > # 下载一个项目和它的整个代码历史 > $ git clone [url] > ``` ## 二、配置 Git的设置文件为`.gitconfig`,它可以在用户主目录下(全局配置),也可以在项目目录下(项目配置)。 > ```bash > # 显示当前的Git配置 > $ git config --list > > # 编辑Git配置文件 > $ git config -e [--global] > > # 设置提交代码时的用户信息 > $ git config [--global] user.name "[name]" > $ git config [--global] user.email "[email address]" > ``` ## 三、增加/删除文件 > ```bash > # 添加指定文件到暂存区 > $ git add [file1] [file2] ... > > # 添加指定目录到暂存区,包括子目录 > $ git add [dir] > > # 添加当前目录的所有文件到暂存区 > $ git add . > > # 添加每个变化前,都会要求确认 > # 对于同一个文件的多处变化,可以实现分次提交 > $ git add -p > > # 删除工作区文件,并且将这次删除放入暂存区 > $ git rm [file1] [file2] ... > > # 停止追踪指定文件,但该文件会保留在工作区 > $ git rm --cached [file] > > # 改名文件,并且将这个改名放入暂存区 > $ git mv [file-original] [file-renamed] > ``` ## 四、代码提交 > ```bash > # 提交暂存区到仓库区 > $ git commit -m [message] > > # 提交暂存区的指定文件到仓库区 > $ git commit [file1] [file2] ... -m [message] > > # 提交工作区自上次commit之后的变化,直接到仓库区 > $ git commit -a > > # 提交时显示所有diff信息 > $ git commit -v > > # 使用一次新的commit,替代上一次提交 > # 如果代码没有任何新变化,则用来改写上一次commit的提交信息 > $ git commit --amend -m [message] > > # 重做上一次commit,并包括指定文件的新变化 > $ git commit --amend [file1] [file2] ... > ``` ## 五、分支 > ```bash > # 列出所有本地分支 > $ git branch > > # 列出所有远程分支 > $ git branch -r > > # 列出所有本地分支和远程分支 > $ git branch -a > > # 新建一个分支,但依然停留在当前分支 > $ git branch [branch-name] > > # 新建一个分支,并切换到该分支 > $ git checkout -b [branch] > > # 新建一个分支,指向指定commit > $ git branch [branch] [commit] > > # 新建一个分支,与指定的远程分支建立追踪关系 > $ git branch --track [branch] [remote-branch] > > # 切换到指定分支,并更新工作区 > $ git checkout [branch-name] > > # 切换到上一个分支 > $ git checkout - > > # 建立追踪关系,在现有分支与指定的远程分支之间 > $ git branch --set-upstream [branch] [remote-branch] > > # 合并指定分支到当前分支 > $ git merge [branch] > > # 选择一个commit,合并进当前分支 > $ git cherry-pick [commit] > > # 删除分支 > $ git branch -d [branch-name] > > # 删除远程分支 > $ git push origin --delete [branch-name] > $ git branch -dr [remote/branch] > ``` ## 六、标签 > ```bash > # 列出所有tag > $ git tag > > # 新建一个tag在当前commit > $ git tag [tag] > > # 新建一个tag在指定commit > $ git tag [tag] [commit] > > # 删除本地tag > $ git tag -d [tag] > > # 删除远程tag > $ git push origin :refs/tags/[tagName] > > # 查看tag信息 > $ git show [tag] > > # 提交指定tag > $ git push [remote] [tag] > > # 提交所有tag > $ git push [remote] --tags > > # 新建一个分支,指向某个tag > $ git checkout -b [branch] [tag] > ``` ## 七、查看信息 > ```bash > # 显示有变更的文件 > $ git status > > # 显示当前分支的版本历史 > $ git log > > # 显示commit历史,以及每次commit发生变更的文件 > $ git log --stat > > # 搜索提交历史,根据关键词 > $ git log -S [keyword] > > # 显示某个commit之后的所有变动,每个commit占据一行 > $ git log [tag] HEAD --pretty=format:%s > > # 显示某个commit之后的所有变动,其"提交说明"必须符合搜索条件 > $ git log [tag] HEAD --grep feature > > # 显示某个文件的版本历史,包括文件改名 > $ git log --follow [file] > $ git whatchanged [file] > > # 显示指定文件相关的每一次diff > $ git log -p [file] > > # 显示过去5次提交 > $ git log -5 --pretty --oneline > > # 显示所有提交过的用户,按提交次数排序 > $ git shortlog -sn > > # 显示指定文件是什么人在什么时间修改过 > $ git blame [file] > > # 显示暂存区和工作区的差异 > $ git diff > > # 显示暂存区和上一个commit的差异 > $ git diff --cached [file] > > # 显示工作区与当前分支最新commit之间的差异 > $ git diff HEAD > > # 显示两次提交之间的差异 > $ git diff [first-branch]...[second-branch] > > # 显示今天你写了多少行代码 > $ git diff --shortstat "@{0 day ago}" > > # 显示某次提交的元数据和内容变化 > $ git show [commit] > > # 显示某次提交发生变化的文件 > $ git show --name-only [commit] > > # 显示某次提交时,某个文件的内容 > $ git show [commit]:[filename] > > # 显示当前分支的最近几次提交 > $ git reflog > ``` ## 八、远程同步 > ```bash > # 下载远程仓库的所有变动 > $ git fetch [remote] > > # 显示所有远程仓库 > $ git remote -v > > # 显示某个远程仓库的信息 > $ git remote show [remote] > > # 增加一个新的远程仓库,并命名 > $ git remote add [shortname] [url] > > # 取回远程仓库的变化,并与本地分支合并 > $ git pull [remote] [branch] > > # 上传本地指定分支到远程仓库 > $ git push [remote] [branch] > > # 强行推送当前分支到远程仓库,即使有冲突 > $ git push [remote] --force > > # 推送所有分支到远程仓库 > $ git push [remote] --all > ``` ## 九、撤销 > ```bash > # 恢复暂存区的指定文件到工作区 > $ git checkout [file] > > # 恢复某个commit的指定文件到暂存区和工作区 > $ git checkout [commit] [file] > > # 恢复暂存区的所有文件到工作区 > $ git checkout . > > # 重置暂存区的指定文件,与上一次commit保持一致,但工作区不变 > $ git reset [file] > > # 重置暂存区与工作区,与上一次commit保持一致 > $ git reset --hard > > # 重置当前分支的指针为指定commit,同时重置暂存区,但工作区不变 > $ git reset [commit] > > # 重置当前分支的HEAD为指定commit,同时重置暂存区和工作区,与指定commit一致 > $ git reset --hard [commit] > > # 重置当前HEAD为指定commit,但保持暂存区和工作区不变 > $ git reset --keep [commit] > > # 新建一个commit,用来撤销指定commit > # 后者的所有变化都将被前者抵消,并且应用到当前分支 > $ git revert [commit] > > # 暂时将未提交的变化移除,稍后再移入 > $ git stash > $ git stash pop > ``` ## 十、其他 > ```bash > # 生成一个可供发布的压缩包 > $ git archive > ``` ## ## Git 彻底删除某个commit的方法 如果因为一些原因,需要删除某个错误的 `commit`,而且需要干净的操作,彻底让其消失,不留痕迹,该如何操作? > 我向仓库提交了一个大文件,大约 300M,push 失败(因为 git 最大能提交 100M 文件),删除本地文件不行,尝试过修改配置文件,解除 git 只能提交小于 100M 文件的限制,但是未起作用。只能通过删除包含提交此文件的 commit 解决。 废话少说,直奔主题。 1.首先输入如下命令查看历史提交的 commit: ```javascript git log ``` > 重要的是**记下**要删除的 commit 的**上一条** commit 的 **commit号**。如下图,如果要删除箭头所指的 commit,需要记录红框中的 commit号: ![img](https://ask.qcloudimg.com/http-save/yehe-5837587/qkvwgeqqb7.png?imageView2/2/w/1620) 2.然后执行如下的命令: ```javascript git rebase -i commit号 ``` 会出现如下界面: ![img](https://ask.qcloudimg.com/http-save/yehe-5837587/v4bgnub3eu.png?imageView2/2/w/1620) 3.然后将要删除的 commit号 的前缀 `pick` 改为 `drop`。 4.然后可以通过如下命令再次查看是否已经删除: ```javascript git log ``` 5.最后通过如下命令将现在的状态推送到远程仓库即可: ```javascript git push origin master -f ``` 当我们有时候回滚了代码,想强制push到远程仓库的时候, git push origin --force 会报如下错误: You are not allowed to force push code to a protected branch on this project 如果用的是gitlab版本库,这说明gitlab对仓库启用了保护,需要在仓库中设置一下: "Settings" -> "Repository" -> scroll down to "Protected branches". ———————————————— 版权声明:本文为CSDN博主「oguro」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/oguro/article/details/103085626 ## 把远程仓库和本地同步,消除差异 git pull origin master --allow-unrelated-histories //把远程仓库和本地同步,消除差异 2、重新add和commit相应文件 3、git push origin master 4、此时就能够上传成功了 ———————————————— 版权声明:本文为CSDN博主「像孩子一样丶」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/xieneng2004/article/details/81044371 ## 【Git】pull遇到错误:error: Your local changes to the following files would be overwritten by merge: 这种情况下,如何保留本地的修改同时又把远程的合并过来呢? 首先取决于你是否想要保存本地修改。(是 /否) 是 别急我们有如下三部曲 git stash git pull origin master git stash pop git stash 的时候会把你本地快照,然后git pull 就不会阻止你了,pull完之后这时你的代码并没有保留你的修改。惊了! 别急,我们之前好像做了什么? STASH 这时候执行git stash pop你去本地看会发现发生冲突的本地修改还在,这时候你该commit push啥的就悉听尊便了。 否 既然不想保留本地的修改,那好办。直接将本地的状态恢复到上一个commit id 。然后用远程的代码直接覆盖本地就好了。 git reset --hard git pull origin mast ———————————————— 版权声明:本文为CSDN博主「转身雪人」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/nakiri_arisu/article/details/80259531
import { FieldMetadataType } from 'src/metadata/field-metadata/field-metadata.entity'; import { commentStandardFieldIds } from 'src/workspace/workspace-sync-metadata/constants/standard-field-ids'; import { standardObjectIds } from 'src/workspace/workspace-sync-metadata/constants/standard-object-ids'; import { FieldMetadata } from 'src/workspace/workspace-sync-metadata/decorators/field-metadata.decorator'; import { IsSystem } from 'src/workspace/workspace-sync-metadata/decorators/is-system.decorator'; import { ObjectMetadata } from 'src/workspace/workspace-sync-metadata/decorators/object-metadata.decorator'; import { ActivityObjectMetadata } from 'src/workspace/workspace-sync-metadata/standard-objects/activity.object-metadata'; import { BaseObjectMetadata } from 'src/workspace/workspace-sync-metadata/standard-objects/base.object-metadata'; import { WorkspaceMemberObjectMetadata } from 'src/workspace/workspace-sync-metadata/standard-objects/workspace-member.object-metadata'; @ObjectMetadata({ standardId: standardObjectIds.comment, namePlural: 'comments', labelSingular: 'Comment', labelPlural: 'Comments', description: 'A comment', icon: 'IconMessageCircle', }) @IsSystem() export class CommentObjectMetadata extends BaseObjectMetadata { @FieldMetadata({ standardId: commentStandardFieldIds.body, type: FieldMetadataType.TEXT, label: 'Body', description: 'Comment body', icon: 'IconLink', }) body: string; @FieldMetadata({ standardId: commentStandardFieldIds.author, type: FieldMetadataType.RELATION, label: 'Author', description: 'Comment author', icon: 'IconCircleUser', joinColumn: 'authorId', }) author: WorkspaceMemberObjectMetadata; @FieldMetadata({ standardId: commentStandardFieldIds.activity, type: FieldMetadataType.RELATION, label: 'Activity', description: 'Comment activity', icon: 'IconNotes', joinColumn: 'activityId', }) activity: ActivityObjectMetadata; }
<template> <div class="g-content-c p-module"> <div class="g-form-layout-m"> <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80"> <Form-item label="角色ID" prop="roleId"> <Input v-model="formValidate.roleId" :maxlength="30" placeholder="ID值请确认"></Input> </Form-item> <Form-item label="模块ID" prop="moduleId"> <Input v-model="formValidate.moduleId" :maxlength="30" placeholder="ID值请确认"></Input> </Form-item> <Form-item> <Button type="primary" @click="handleSubmit()">提交</Button> <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button> </Form-item> </Form> </div> </div> </template> <script> import { apiDoActionAdd } from '@/api' export default { data() { return { formValidate: { roleId: '', moduleId: '', }, ruleValidate: { roleId: [ { required: true, message: 'ID值不能为空', trigger: 'blur' } ], moduleId: [ { required: true, message: 'ID值不能为空', trigger: 'blur' } ] } } }, methods: { handleSubmit() { this.$refs['formValidate'].validate((valid) => { if (valid) { this.doAdd() } else { this.$Message.error('表单验证失败!') } }) }, handleReset() { this.$refs['formValidate'].resetFields() }, async doAdd() { const params = { ...this.formValidate } const resInfo = await apiDoActionAdd(params) if (resInfo.ret) { this.$Message.success('提交成功!') this.handleReset() } else { this.$Message.error('添加失败!') } } } } </script>
package com.greenfoxacademy.pirateinspring.services; import com.greenfoxacademy.pirateinspring.entities.Pirate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.ArrayList; import java.util.Optional; @Service public class PirateManagementService { private ArrayList<Pirate> pirateList; public PirateManagementService(){ pirateList = new ArrayList<>(); pirateList.add(new Pirate(true, "Captain Onedin", "src/main/resources/static/pirates/onedin.jpeg")); pirateList.add(new Pirate(true, "Popeye", "src/main/resources/static/pirates/popeye.jpg")); pirateList.add(new Pirate(true, "Captain Hook", "/home/judit/tanulas/greenfox/szutsj/week18/pirateinspring2/src/main/resources/static/pirates/hook.jpg")); pirateList.add(new Pirate(true, "Captain Jack Sparrow", "src/main/resources/static/pirates/jack sparrow.jpeg")); pirateList.add(new Pirate(true, "Quazi", "src/main/resources/static/pirates/quazi.jpeg")); pirateList.add(new Pirate(true, "Mariner form Waterworld", "src/main/resources/static/pirates/waterworld - mariner.jpg")); } public void select(Pirate pirate){ for (Pirate pirateInList: pirateList) { if (pirateInList.getName().equals(pirate.getName())){ pirateInList.setSelected(true); } } } public Pirate getMyCaptain(){ for (Pirate pirate: pirateList) { if (pirate.isSelected()){ return pirate; } } return pirateList.get(0); } @Override public String toString() { String string = ""; string += "PirateManagementService{"; for(Pirate pirate : pirateList){ string += pirate.getName(); string += ", "; } string += "}"; return string; } public ArrayList<Pirate> getPirateList() { return pirateList; } public void setPirateList(ArrayList<Pirate> pirateList) { this.pirateList = pirateList; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using Tailspin.Surveys.Data.DataModels; using Tailspin.Surveys.Data.DTOs; using Tailspin.Surveys.Web.Models; namespace Tailspin.Surveys.Web.Services { /// <summary> /// This interface defines the CRUD operations for <see cref="Survey"/>s. /// This interface also defines operations related to publishing <see cref="Survey"/>s /// and adding and processing <see cref="ContributorRequest"/>s. /// </summary> public interface ISurveyService { Task<SurveyDTO> GetSurveyAsync(Guid id); Task<UserSurveysDTO> GetSurveysForUserAsync(Guid userId); Task<TenantSurveysDTO> GetSurveysForTenantAsync(Guid tenantId); Task<SurveyDTO> CreateSurveyAsync(SurveyDTO survey); Task<SurveyDTO> UpdateSurveyAsync(SurveyDTO survey); Task<SurveyDTO> DeleteSurveyAsync(Guid id); Task<ContributorsDTO> GetSurveyContributorsAsync(Guid id); Task<ApiResult<IEnumerable<SurveyDTO>>> GetPublishedSurveysAsync(); Task<SurveyDTO> PublishSurveyAsync(Guid id); Task<SurveyDTO> UnPublishSurveyAsync(Guid id); Task ProcessPendingContributorRequestsAsync(); Task AddContributorRequestAsync(ContributorRequest contributorRequest); } }
// Copyright 2024 Peter Dimov // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt #include <boost/compat/invoke.hpp> #include <boost/core/lightweight_test_trait.hpp> #include <boost/config.hpp> #include <boost/config/workaround.hpp> struct F { void operator()() { } char operator()( char x1 ) noexcept { return x1; } int operator()( int x1, int x2 ) const { return 10*x1+x2; } double operator()( float x1, float x2, float x3 ) const noexcept { return 100*x1 + 10*x2 + x3; } }; struct X { }; int main() { using boost::compat::is_nothrow_invocable; // nonfunction BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<int, int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<int, int, int> )); // function reference BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<void(&)()> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(&)(int), char> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<int(&)(int, int), int, int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<double(&)(double, double, double), float, float, float> )); #if defined(__cpp_noexcept_function_type) BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<void(&)() noexcept> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<char(&)(int) noexcept, char> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<int(&)(int, int) noexcept, int, int> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<double(&)(double, double, double) noexcept, float, float, float> )); #endif BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<void(&)(), int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(&)(int)> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(&)(int), int, int> )); // function pointer BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<void(*)()> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(*)(int), char> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<int(*)(int, int), int, int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<double(*)(double, double, double), float, float, float> )); #if defined(__cpp_noexcept_function_type) BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<void(*)() noexcept> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<char(*)(int) noexcept, char> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<int(*)(int, int) noexcept, int, int> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<double(*)(double, double, double) noexcept, float, float, float> )); #endif BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<void(*)(), int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(*)(int)> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(*)(int), int, int> )); // object BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<F> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<F, int, int> )); #if !BOOST_WORKAROUND(BOOST_MSVC, < 1910) BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<F, char> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<F, float, float, float> )); #endif BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<F, int, int, int, int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<F const> )); // member function pointer BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<void(X::*)(), X> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(X::*)(int), X, char> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<int(X::*)(int, int), X, int, int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<double(X::*)(double, double, double), X, float, float, float> )); #if defined(__cpp_noexcept_function_type) BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<void(X::*)() noexcept, X> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<char(X::*)(int) noexcept, X, char> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<int(X::*)(int, int) noexcept, X, int, int> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<double(X::*)(double, double, double) noexcept, X, float, float, float> )); #endif BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<void(X::*)()> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<void(X::*)(), int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<void(X::*)(), X, int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(X::*)(int)> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(X::*)(int), int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(X::*)(int), X> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<char(X::*)(int), X, int, int> )); // member data pointer #if !BOOST_WORKAROUND(BOOST_MSVC, < 1910) BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<int X::*, X> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<int X::*, X const> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<int X::*, X&> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<int X::*, X const&> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<int X::*, X*> )); BOOST_TEST_TRAIT_TRUE(( is_nothrow_invocable<int X::*, X const*> )); #endif BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<int X::*> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<int X::*, int> )); BOOST_TEST_TRAIT_FALSE(( is_nothrow_invocable<int X::*, X, int> )); return boost::report_errors(); }
\documentclass[a4paper, 9pt]{article} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{xcolor} \usepackage{parskip} \usepackage{enumitem} \usepackage{graphicx} \date{\today} \author{Diedler Baptiste} \title{Réseaux} \begin{document} \maketitle \section{définition} \begin{description}[style=nextline] \item[communication de circuits:] (+) qualité de service/facturation.\\ (-) mauvaise utilisation des ressources \item[transfert de paquets:] (+) meilleur utilisation des ressources, plus rapide.\\ (-) les paquets peuvent arriver désordonnés et nécessité d'un contrôle de flux pour connaître le chemin à prendre. \item[communication:] L'adresse de destination n'intervient pas dans le processus de décision d'acheminement. \item[trame:] Paquet dont on sait reconnaître le début et la fin. \item[paquet:] Trame dont on ne sait pas reconnaître le début et la fin. \end{description} \section{classification} \subsection{type de transmision} \begin{description}[style=nextline] \item[réseau à diffusion:] Dispose d'un seul canal de transmission, qui est partagé par tous les équipements qui y sont connextés. Toutes les machines reçoivent les données et seul la destination les lit. \item[réseau point à point:] Grand nombre de connexions, chacune faisant intervenir deux machines. POur aller de la source à la destination, les données peuvent transsister par plusieurs machines. \end{description} \subsection{topologie} \begin{description}[style=nextline] \item[topologie physique:] Qui décrit comment les machines sont raccordées au réseau. \item[topologie logique:] Qui renseigne sur le mode d'échange des données dans le réseau. \end{description} La topologie du réseau est souvent influencée par différents facteurs:\\ configuration du site, nombre de stations à connecter, flux des données, coût, distance entre entités communicantes, évolution possible, résistance aux pannes et lignes de secours, administration. \begin{description}[style=nextline] \item[topologie en bus:] Une topologie en bus est l'organisation la plus simple d'un réseau. Tous les ordinateurs sont reliés à une même ligne de transmission par l'intermédiaire d’un câble, généralement coaxial. Le mot « bus » désigne la ligne physique. \end{description} \begin{figure}[ht] \centering \includegraphics[width=0.8\textwidth]{topologie_bus.png} \caption{Topologie en bus} \label{fig:topologie_bus} \end{figure} \begin{description}[style=nextline] \item[topologie en anneau:] Dans la topologie en anneau, chaque poste est connecté au suivant. L’information circule dans un seul sens. Chaque station réémet les données et les recopie si elles lui sont destinées. \end{description} \begin{figure}[ht] \centering \includegraphics[width=0.3\textwidth]{topologie_anneau.png} \caption{Topologie en anneau} \label{fig:topologie_anneau} \end{figure} \begin{description}[style=nextline] \item[topologie en étoile:] La topologie en étoile est une variante de la topologie point-à-point. Un nœud central, appelé concentrateur (hub) émule n liaisons point-à-point. Tous les nœuds du réseau sont reliés au nœud central. \end{description} \begin{figure}[ht] \centering \includegraphics[width=0.3\textwidth]{topologie_etoile.png} \caption{Topologie en étoile} \label{fig:topologie_etoile} \end{figure} \begin{description}[style=nextline] \item[topologie en arbre:] Un réseau arborescent est constitué d’un ensemble de réseaux en étoile, reliés en par des concentrateurs jusqu’à un nœud unique (nœud de tête). \end{description} \begin{figure}[ht] \centering \includegraphics[width=0.3\textwidth]{topologie_arbre.png} \caption{Topologie en arbre} \label{fig:topologie_arbre} \end{figure} \begin{description}[style=nextline] \item[topologie maillée:] Un réseau maillé est un réseau dans lequel deux stations peuvent être mises en relation par différents chemins. \end{description} \begin{figure}[ht] \centering \includegraphics[width=0.3\textwidth]{topologie_maillee.png} \caption{Topologie maillée} \label{fig:topologie_maillee} \end{figure} \subsection{taille} \begin{description} \item[PAN:] personnal area network \item[LAN:] local area network \item[MAN:] metropolitain area network \item[WAN:] wide area network \end{description} \begin{figure}[ht] \centering \includegraphics[width=0.8\textwidth]{classification_taille.png} \caption{Classification par taille} \label{fig:classification_taille} \end{figure} \section{architectures protocolaires} \subsection{modèle OSI} \begin{description} \item[couches hautes:]Les couches hautes comportent les fonctions de traitement sur les données transportées.(5.7) \item[couches basses:]Les couches basses garantissent aux couches hautes que le transfert d’information se réalise correctement. Elles comportent les fonctions de transmission de données.(1.4) \end{description} 7: application\\ 6: présentation\\ 5: session\\ 4: transport\\ 3: réseau\\ 2: liaison\\ 1: physique\\ \subsection{modèle TCP/IP} Le modèle est similèrement le même sauf qu'il possède moins de couche que le modèle précédent.\\ 4: application (5.7)\\ 3: transport (4)\\ 2: réseau (3)\\ 1: accès au réseau (1.2)\\ \subsection{autre} Les machines de système relais ne vont utiliser au maximum que les trois premières couches (physique/liaison/réseau). Car elles n'ont pas besoin de connaître le message qui se trouve à l'intérieur pour transmettre au destinataire. \section{bases théoriques de la transmission des données} \subsection{transmision des données} L’impulsion électrique représentative d’un élément binaire est affaiblie et déformée par le système de transmission.\\ Ces déformations dépendent du spectre du signal (la nature de celui-ci), ou de la bande passante (la réponse en fréquence du système).\\ La période \(T\) est définie comme : \[T = \frac{1}{f}\] avec \(f\) la fréquence. \subsection{spectre de fréquence} Un signal périodique quelconque peut donc être considéré comme une infinité de signaux sinusoïdaux.\\ Chaque composante peut être représentée par l’énergie ou la puissance qu’elle contient. On obtient ainsi le spectre du signal.\\ L’espace de fréquence occupé par le spectre se nomme largeur de bande. En théorie, la largeur de bande d’un signal non sinusoïdal est infinie. \subsection{bande passante} Un système de transmission ne transmet pas toutes les fréquences. La courbe de réponse en fréquence d’un système peut être obtenu en utilisant un générateur dont on fait varier la fréquence à tension constante.\\ le signal en sortie du système n’est plus l’image de celui en entrée. On dit qu’il y a distorsion.\\ On appelle bande passante à n décibels (dB) l’espace de fréquences tel que tout signal appartenant à cet intervalle ne subisse, au plus, qu’un affaiblissement de n dB : atténuation (dB) = 10 x log10(puissance reçue / puissance transmise).\\ La largeur de bande d’un signal correspond à la bande passante minimale que le système doit posséder pour restituer correctement l’information. \subsection{débit et temps de transfert} Le terme de bande passante est utilisé pour désigner un espace fréquentiel (Hz), mais aussi pour qualifier le débit binaire d’un système (bit/s).\\ Le débit binaire mesure la vitesse de transmission des informations sur un canal (en bit/s), c’est-à-dire le nombre de bits pouvant être transmis en une seconde.\\ Le temps nécessaire pour envoyer un message sur le canal est égal au nombre de bits à émettre, divisé par le débit binaire du canal.\\ Le temps de propagation est le temps nécessaire au signal pour parcourir le support d’un bout à l’autre de la liaison. Il dépend de la nature du support, de la distance et de la fréquence du signal.\\ Le temps de transfert est le temps nécessaire pour que le message émis à travers le réseau soit reçu complètement par le destinataire.\\ temps de transfert = temps de transmission + temps de propagation \end{document}
import speech_recognition as sr import openai from gtts import gTTS from playsound import playsound import os # Sua chave de API da OpenAI openai.api_key = "" # Inicializa o reconhecedor de fala rec = sr.Recognizer() # Função para reconhecimento de fala def recognize_speech(): with sr.Microphone(device_index=1) as mic: rec.adjust_for_ambient_noise(mic) print("Fale alguma coisa") audio = rec.listen(mic) frase = rec.recognize_google(audio, language="pt-BR") return frase # Função para converter texto em áudio e reproduzir def text_to_speech(text, speed=2.0): tts = gTTS(text, lang="pt", slow=False) # Ajuste a velocidade com o argumento 'slow' audio_file = "output.mp3" tts.save(audio_file) playsound(audio_file) os.remove(audio_file) # Exclui o arquivo de áudio após a reprodução # Limite de tokens para respostas max_tokens = 60 # Defina o número desejado de tokens aqui # Comando de ativação def wait_for_activation(): while True: user_input = recognize_speech() if "RobIA" in user_input: text_to_speech("Estou à disposição, no que posso ajudar?") break # Loop interativo while True: wait_for_activation() # Aguarda o comando de ativação while True: user_input = recognize_speech() completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": user_input}], max_tokens=max_tokens ) response = completion.choices[0].message.content print("Assistente:", response) # Converter a resposta em áudio e reproduzir com uma velocidade mais rápida (por exemplo, 1.5) text_to_speech(response, speed=2.0)
package Queue import ( "errors" "sync" "time" ) type Queue struct { exit chan bool capacity int topics map[string][]chan any sync.RWMutex //once sync.Once } func NewQueue() *Queue { return &Queue{ exit: make(chan bool), topics: make(map[string][]chan any), } } func (q *Queue) ShowExit() chan bool { return q.exit } func (q *Queue) SetConditions(capacity int) { q.capacity = capacity } func (q *Queue) Start() { select { case <-q.exit: q.exit = make(chan bool) default: return } } func (q *Queue) Close() { select { case <-q.exit: return default: close(q.exit) q.Lock() q.topics = make(map[string][]chan any) q.Unlock() } return } func (q *Queue) Publish(topic string, pub any) error { select { case <-q.exit: return errors.New("Queue is closed") default: } q.RLock() subscribers, ok := q.topics[topic] q.RUnlock() if !ok { return nil } q.Broadcast(pub, subscribers) return nil } func (q *Queue) Broadcast(msg any, subscribers []chan any) { count := len(subscribers) concurrency := 1 switch { case count > 1000: concurrency = 3 case count > 100: concurrency = 2 default: concurrency = 1 } pub := func(start int) { idleDuration := 5 * time.Millisecond ticker := time.NewTicker(idleDuration) defer ticker.Stop() for j := start; j < count; j += concurrency { select { case subscribers[j] <- msg: case <-ticker.C: case <-q.exit: return } } } for i := 0; i < concurrency; i++ { go pub(i) } } func (q *Queue) Subscribe(topic string) (<-chan any, error) { select { case <-q.exit: return nil, errors.New("Queue is closed") default: } if q.capacity == 0 { q.capacity = 100 } ch := make(chan any, q.capacity) q.Lock() q.topics[topic] = append(q.topics[topic], ch) q.Unlock() return ch, nil } func (q *Queue) Unsubscribe(topic string, sub <-chan any) error { select { case <-q.exit: return errors.New("Queue is closed") default: } q.RLock() subscribers, ok := q.topics[topic] q.RUnlock() if !ok { return nil } // delete subscriber q.Lock() var newSubs []chan any for _, subscriber := range subscribers { if subscriber == sub { continue } newSubs = append(newSubs, subscriber) } q.topics[topic] = newSubs q.Unlock() return nil } func (q *Queue) GetPayLoad(sub <-chan any) any { for val := range sub { if val != nil { return val } } return nil }
// // This file is part of Miro (The Middleware for Robots) // Copyright (C) 1999-2005 // Department of Neuroinformatics, University of Ulm, Germany // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2, or (at your option) // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // $Id$ // #ifndef Policy_h #define Policy_h #include "Pattern.h" #include "miro/Synch.h" #include <string> #include <iostream> // Forward declaration. class QDomDocument; namespace Miro { // forward declarations class StructuredPushSupplier; template<class T> class Repository; namespace BAP { // forward declarations class Arbiter; class Behaviour; typedef Repository<Arbiter> ArbiterRepository; typedef Repository<Behaviour> BehaviourRepository; class ActionPattern; class Policy; class BehaviourParameters; //! Class representing a policy. /** * A policy is a full configuration of the behaviour engine * of Miro. */ class Policy : public Pattern { //-------------------------------------------------------------------------- // private types //-------------------------------------------------------------------------- //! Type of the super class. typedef Pattern Super; //! Type forming a mapping from a (pattern, event) pair to a pattern. typedef std::map<std::pair<std::string, std::string>, std::string> TransitionMap; //! Type forming a mapping from a event to a pattern. typedef std::map<std::string, std::string> TransitionPatternMap; public: //-------------------------------------------------------------------------- // static public methods //-------------------------------------------------------------------------- //! Load a policy from disc. static void loadPolicyFile(Policy& _policy, char const * _fileName); //! Load a policy from a string. static void loadPolicy(Policy& _policy, char const * _xml); //! Parse a policy XML document. static void parsePolicy(Policy& _policy, QDomDocument const& _doc); //-------------------------------------------------------------------------- // public methods //-------------------------------------------------------------------------- //! Default constructor. Policy(StructuredPushSupplier * _pSupplier = NULL); //! Initializing constructor. Policy(QDomElement const& _doc, StructuredPushSupplier * _pSupplier = NULL); //! Copy constructor. Policy(const Policy& _rhs); //! Virtual destructor. virtual ~Policy(); //! Virtual copy constructor. virtual Policy * clone() const; //! Parse DOM node virtual void xmlInit(const QDomElement& _element); virtual void xmlAddTransitionPattern(QDomElement _element); //! Register a pattern at the policy. void registerPattern(Pattern * const _pattern); //! Lookup child pattern by name. Pattern * const getPattern(const std::string& _name); //! Lookup child pattern by name. Pattern const * const getPattern(const std::string& _name) const; //! Send a transition message, switching to another action pattern. virtual void sendTransitionMessage(const std::string& _message); //! Set the default pattern for open. void setStartPattern(Pattern * _pattern); //! Get the parameter set of an existing behaviour within an actionpattern. BehaviourParameters * const getBehaviourParameters(const std::string& _pattern, const std::string& _behaviour) const throw (BehaviourEngine::EUnknownActionPattern, BehaviourEngine::EUnknownBehaviour); //! Set the parameters of an existing behaviour within an actionpattern. /** Nested behaviours are addressed by <Subpolicy>/<Pattern> */ void setBehaviourParameters(const std::string& _pattern, const std::string& _behaviour, BehaviourParameters * _parameters) throw (BehaviourEngine::EUnknownActionPattern, BehaviourEngine::EUnknownBehaviour); //! Retrieve the active pattern of the (sub-)policy. Pattern * const currentPattern(); //! Start the policy. void open(Pattern * const _predecessor = NULL, std::string const& _transition = std::string()); //! End the policy. void close(ActionPattern * const _successor = NULL); //! Start a specific patern. void openPattern(const std::string& _pattern); //! Clear the policy. void clear(); //! Is this a valid policy? bool valid() const; //! Set validity of the policy (for debugging only!). void valid(bool flag); protected: //-------------------------------------------------------------------------- // protected methods //-------------------------------------------------------------------------- //! Retrieve the associtated successor for the transition pattern message. Pattern * const getTransitionPatternPattern(const std::string& _patternName); //! Init the childs transition tables; void lowerTransitions(); //! Set the current action pattern. void currentPattern(Pattern * const _pattern); virtual ActionPattern * currentLeafPattern(); //! Dump the policy configuration to an output stream. virtual void printToStream(std::ostream& ostr) const; //-------------------------------------------------------------------------- // protected static methods //-------------------------------------------------------------------------- //! Get the next path element of the pattern. static void splitPath(std::string const& _path, std::string& _first, std::string& _rest); //-------------------------------------------------------------------------- // protected data //-------------------------------------------------------------------------- //! Event supplier for online output. /** Default is the NULL pointer. */ StructuredPushSupplier * pSupplier_; PatternMap patterns_; PatternMap transitionPatternTable_; TransitionMap transitions_; TransitionPatternMap transitionPatterns_; //! The action pattern to start with. /** * Default is the NULL pointer. A policy is not valid * if no startPattern_ is specified. */ Pattern * startPattern_; //! The currently active action pattern. /** * Default is the NULL pointer. */ Pattern * currentPattern_; //! Flag to indicate that the object contains a valid configuration. /** Default is false. */ bool valid_; private: //-------------------------------------------------------------------------- // hidden methods //-------------------------------------------------------------------------- Policy& operator= (Policy const&); //-------------------------------------------------------------------------- // friend declarations //-------------------------------------------------------------------------- friend class Pattern; friend class ActionPattern; }; //---------------------------------------------------------------------------- // inline methods //---------------------------------------------------------------------------- inline void Policy::setStartPattern(Pattern * _pattern) { startPattern_ = _pattern; } inline bool Policy::valid() const { return valid_; } inline void Policy::valid(bool flag) { valid_ = flag; } inline Pattern * const Policy::currentPattern() { return currentPattern_; } inline void Policy::currentPattern(Pattern * const _pattern) { // std::cout << "policy: " << getName() << " current pattern " << _pattern->getName() << std::endl; currentPattern_ = _pattern; } } } #endif
import React, { useContext, useEffect, useState } from 'react' import { Container, Row, Col, Form, FormGroup, Button } from 'reactstrap' import '../styles/login.css' import { Link, redirect, useNavigate } from 'react-router-dom' import loginImg from '../assets/images/login.png' import userIcon from '../assets/images/user.png' import { AuthContext } from '../context/AuthContext' import { BASE_URL } from '../utils/config' import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; const Login = () => { useEffect(() => { window.scrollTo(0,0) }, []) const [credentials, setCredentials] = useState({ email: undefined, password: undefined }) const {dispatch} = useContext(AuthContext) const navigate = useNavigate() const handleChange = e => { setCredentials(prev => ({ ...prev, [e.target.id]: e.target.value })) } const handleClick = async e => { e.preventDefault(); dispatch({type:'LOGIN_START'}) try{ const res = await fetch(`${BASE_URL}/auth/login` ,{ method:'post', headers:{ 'content-type' : 'application/json' }, credentials:'include', body : JSON.stringify(credentials) }) const result = await res.json() if(!res.ok) { return toast.error(result.message,{ position:"top-center", theme:"dark" }); } toast.success(`Welcome ${result.data.username}`,{ position:"top-center", autoClose: 1000, theme:"dark" }); dispatch({type:'LOGIN_SUCCESS',payload:result.data}) const timeoutId = setTimeout(() => { navigate('/'); }, 2000); } catch(err) { dispatch({type:'LOGIN_FAILURE',payload:err.message}) } } return ( <> <section> <Container> <Row> <Col lg='8' className='m-auto'> <div className="login__container d-flex justify-content-between"> <div className="login__img"> <img src={loginImg} alt="" /> </div> <div className="login__form"> <div className="user"> <img src={userIcon} alt="" /> </div> <h2>Login</h2> <Form onSubmit={handleClick}> <FormGroup> <input type="email" placeholder='Email' id='email' onChange={handleChange} required /> </FormGroup> <FormGroup> <input type="password" placeholder='Password' id='password' onChange={handleChange} required /> </FormGroup> <Button className='btn secondary__btn auth__btn' type='submit'>Login</Button> </Form> <p>Don't have an account? <Link to='/register'>Create</Link></p> </div> </div> </Col> </Row> </Container> </section> <ToastContainer/> </> ) } export default Login
import React from "react"; import { Box, Button, Popover } from "@mui/material"; import MoreVertIcon from "@mui/icons-material/MoreVert"; import IconButton from "@mui/material/IconButton"; import DeleteIcon from "@mui/icons-material/Delete"; import EditIcon from "@mui/icons-material/Edit"; import { toast } from "sonner"; import AssetService from "../../../service/API/asset.service"; export default function ButtonIcon(props: any) { const { data, setLoading, getAssetCategory, setOpen, setEditData } = props; const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>( null ); const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const open = Boolean(anchorEl); const id = open ? "simple-popover" : undefined; const deleteAssetCategory = async () => { setLoading(true); let payload = { status: false, }; await AssetService.deleteAssetCategory(data?.id, payload) .then((res: any) => { setLoading(false); getAssetCategory(); toast.success(res?.data?.message); }) .catch((error: any) => { setLoading(false); toast.error(error.response.data.message); }); }; return ( <> <IconButton aria-label="delete" onClick={handleClick}> <MoreVertIcon /> </IconButton> <Popover id={id} open={open} anchorEl={anchorEl} onClose={handleClose} anchorOrigin={{ vertical: "bottom", horizontal: "left", }} > <Box> <Box> <Button color="inherit" onClick={() => { setEditData(data); setOpen(true); }} startIcon={<EditIcon />} > Edit </Button> </Box> <Box> <Box> <Button color="inherit" onClick={() => { deleteAssetCategory(); }} startIcon={<DeleteIcon />} > Delete </Button> </Box> </Box> </Box> </Popover> </> ); }
import React, { useState, useEffect } from 'react'; import ProductCard from "./ProductCard"; import { getDatabase, ref, onValue } from "firebase/database"; import { db } from "./Utils/Firebase"; import axios from 'axios'; export default function Body() { const [csvData, setCsvData] = useState([]); useEffect(() => { fetchCSVData(); // Fetch the CSV data when the component mounts }, []); // The empty array ensures that this effect runs only once, like componentDidMount const fetchCSVData = () => { const csvUrl = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRjzrX_L2MxxxDy8eZg2uq-6IfOlMaHNfdpHoc0ZWDI3CHpU6QDqER-NOeAyW-pk7ZH2fpwJPr8GeKa/pub?gid=206684609&single=true&output=csv'; // Replace with your Google Sheets CSV file URL axios.get(csvUrl) .then((response) => { const parsedCsvData = parseCSV(response.data); setCsvData(parsedCsvData); }) .catch((error) => { console.error('Error fetching CSV data:', error); }); } function parseCSV(csvText) { const rows = csvText.split(/\r?\n/); const headers = rows[0].split(','); const data = []; for (let i = 1; i < rows.length; i++) { const rowData = rows[i].split(','); const rowObject = {}; for (let j = 0; j < headers.length; j++) { rowObject[headers[j]] = rowData[j]; } data.push(rowObject); } return data; } let transformedResult = transformResult(csvData); console.log(transformedResult) const list = transformedResult.map( (iphone, index) => { if (iphone.image != "" && iphone.prices.some(item => item.status === 'DISPONIVEL')) { return( <ProductCard key={index} image={iphone.image} name={iphone.model} prices={iphone.prices} capacity={iphone.capacity} colors={iphone.color} /> ); } } ); return( <div style={style.cards}> {list} </div> ); // Função para agrupar por modelo e combinar capacidades e preços function transformResult(result) { let groupedResult = {}; result.forEach(item => { if (!groupedResult[item.model]) { groupedResult[item.model] = { model: item.model, prices: [] }; } if (item.status === 'DISPONIVEL') { groupedResult[item.model].prices.push({ capacity: item.capacity, price: item.price, status: item.status, }); } // Manter outras propriedades (imagem, status, cor) iguais para todos os itens do mesmo modelo groupedResult[item.model].image = item.image; groupedResult[item.model].color = item.color; }); return Object.values(groupedResult); } } const style = { cards: { display: 'flex', flexWrap: 'wrap', margin: '120px 30px', justifyContent: 'center' } }
package org.example.back.account; import jakarta.persistence.*; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.example.back.user.User; import org.hibernate.annotations.CreationTimestamp; import java.sql.Timestamp; import java.time.LocalDateTime; @NoArgsConstructor @Data @Table(name = "account_tb") @Entity public class Account { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(fetch = FetchType.LAZY) private User user; @Column(unique = true, nullable = false, length = 4) private Integer number; // 1111, 2222 @Column(nullable = false, length = 4) private String password; @Column(nullable = false) private Long balance; @Column(nullable = false) private Boolean status; // true, false @CreationTimestamp private Timestamp createdAt; @Builder public Account(Long id, User user, Integer number, String password, Long balance, Boolean status, Timestamp createdAt) { this.id = id; this.user = user; this.number = number; this.password = password; this.balance = balance; this.status = status; this.createdAt = createdAt; } }
package test.gui; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import javafx.stage.Stage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.testfx.api.FxRobot; import org.testfx.api.FxToolkit; import org.testfx.framework.junit5.ApplicationExtension; import org.testfx.framework.junit5.Start; import java.io.IOException; import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.testfx.assertions.api.Assertions.assertThat; @ExtendWith(ApplicationExtension.class) class AddFlowersTest { private Stage stage; @Start public void start(Stage stage) throws Exception { this.stage = stage; loadFXMLAndShowStage("/gui/addFlowers.fxml"); } @BeforeEach public void setUp() throws Exception { FxToolkit.registerPrimaryStage(); FxToolkit.setupApplication(() -> new javafx.application.Application() { @Override public void start(Stage stage) throws IOException { loadFXMLAndShowStage("/gui/addFlowers.fxml"); } }); } private void loadFXMLAndShowStage(String fxmlPath) throws IOException { Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource(fxmlPath))); stage.setScene(new Scene(root)); stage.show(); } @Test void shouldContainFlowerChoiceBox(FxRobot robot) { ChoiceBox<String> flowerChoiceBox = robot.lookup("#flowerChoiceBox").queryAs(ChoiceBox.class); assertNotNull(flowerChoiceBox); } @Test void shouldContainCountTextField(FxRobot robot) { TextField countTextField = robot.lookup("#count").queryAs(TextField.class); assertNotNull(countTextField); assertEquals("Введіть кількість квіток", countTextField.getPromptText()); } @Test void shouldContainAddFlowersButton(FxRobot robot) { Button addFlowersButton = robot.lookup("#addFlowersButton").queryAs(Button.class); assertNotNull(addFlowersButton); assertThat(addFlowersButton).hasText("Додати"); } @Test void shouldContainBackToBouquetButton(FxRobot robot) { Button backToBouquetButton = robot.lookup("#backToBouquetButton").queryAs(Button.class); assertNotNull(backToBouquetButton); assertThat(backToBouquetButton).hasText("Назад"); } }
const validatePermissions = (permissions) => { const validPermissions = [ 'CREATE_INSTANT_INVITE', 'KICK_MEMBERS', 'BAN_MEMBERS', 'ADMINISTRATOR', 'MANAGE_CHANNELS', 'MANAGE_GUILD', 'ADD_REACTIONS', 'VIEW_AUDIT_LOG', 'PRIORITY_SPEAKER', 'STREAM', 'VIEW_CHANNEL', 'SEND_MESSAGES', 'SEND_TTS_MESSAGES', 'MANAGE_MESSAGES', 'EMBED_LINKS', 'ATTACH_FILES', 'READ_MESSAGE_HISTORY', 'MENTION_EVERYONE', 'USE_EXTERNAL_EMOJIS', 'VIEW_GUILD_INSIGHTS', 'CONNECT', 'SPEAK', 'MUTE_MEMBERS', 'DEAFEN_MEMBERS', 'MOVE_MEMBERS', 'USE_VAD', 'CHANGE_NICKNAME', 'MANAGE_NICKNAMES', 'MANAGE_ROLES', 'MANAGE_WEBHOOKS', 'MANAGE_EMOJIS', ] for (const permission of permissions) { if (!validPermissions.includes(permission)) { throw new Error(`Unknown permission node "${permission}"`) } } } module.exports = (client, commandOptions) => { let { name, description = '', expectedArgs = '', category = '', permissionError = 'You do not have permission to run this command.', minArgs = 0, maxArgs = null, permissions = [], requiredRoles = [], callback, } = commandOptions // Ensure the command and aliases are in an array if (typeof name === 'string') { name = [name] } console.log(`Registering command "${name}"`) // Ensure the permissions are in an array and are all valid if (permissions.length) { if (typeof permissions === 'string') { permissions = [permissions] } validatePermissions(permissions) } // Listen for messages client.on('message', (message) => { if (message.channel.id === '789215234376073236') { return; } if (message.channel.id === '704489252125409314') { return; } const { member, content, guild } = message for (const alias of name) { const command = `p.${alias.toLowerCase()}` if ( content.toLowerCase().startsWith(`${command} `) || content.toLowerCase() === command ) { // A command has been ran // Ensure the user has the required permissions for (const permission of permissions) { if (!member.hasPermission(permission)) { message.reply(permissionError) return } } // Ensure the user has the required roles for (const requiredRole of requiredRoles) { const role = guild.roles.cache.find( (role) => role.name === requiredRole ) if (!role || !member.roles.cache.has(role.id)) { message.reply( `You must have the "${requiredRole}" role to use this command.` ) return } } // Split on any number of spaces const arguments = content.split(/[ ]+/) // Remove the command which is the first index arguments.shift() let params = message.content.split(' ').slice(1); //array containing each param let args = message.content.split(' '); //same as params but also contains command at first index args[2] == params[1] let params1 = message.content.split(' ').slice(1).join(" "); //same as params but as a string with a space in between let paramsCom = message.content.split(' ').slice(1).join(" ").split(', '); //array containing each param when set by comma if (paramsCom[0] === '') { if ( params.length < minArgs || (maxArgs !== null && params.length > maxArgs) ) { message.reply( `Error: incorrect syntax! use p.${alias} ${expectedArgs}` ) return } } // Ensure we have the correct number of arguments if ( paramsCom.length < minArgs || (maxArgs !== null && paramsCom.length > maxArgs) ) { message.reply( `Error: incorrect syntax! use p.${alias} ${expectedArgs}` ) return } // Handle the custom command code callback(message, paramsCom, client) return } } }) }
<style> #sortbuttons { user-select: none; } table, th, td { border-style: solid; border-width: 1px; border-spacing:0; border-collapse: collapse; } </style> <form id="form"> <input type="text" name="search"> <!-- <input type="submit" value="search"> --> </form> <table cellspacing="0"> <tr id="sortbuttons"> <th onclick='sort("id")' id="id">id</th> <th onclick='sort("name")' id="name">name</th> <th onclick='sort("power")' id="power">power</th> <th onclick='sort("misc")' id="misc">misc</th> </tr> <tbody id="sort"> </tbody> </table> <script> let lists = []; let templist = lists; let amount = 20; function makeid(length){ var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (var i=0; i<length; i++){ result += characters.charAt(Math.floor(Math.random() * characters.length)); } return result; } for (var i=0; i<amount; i++){ var list = new Object(); list["id"] = i+1; list["name"] = makeid(10); list["power"] = Math.round(Math.random()*1000); list["misc"] = makeid(10); lists.push(list); } function update(a){ document.getElementById("sort").innerHTML = ""; for (var i=0; i<a.length; i++){ document.getElementById("sort").innerHTML += "<tr><td>"+a[i].id+ "</td><td>"+a[i].name+ "</td><td>"+a[i].power+ "</td><td>"+a[i].misc+ "</td></tr>"; } } update(lists) function sort(type){ update(templist.sort(dynamicSort(type))); } function search(e){ e.preventDefault(); data = new FormData(document.querySelector('form')); query = data.get("search"); templist = lists.filter(o => o.name.includes(query)); update(templist); } form.addEventListener('submit', e => e.preventDefault()); form.addEventListener('input', search); var sortOrder = 1; var tempProp = ""; function dynamicSort(property){ // var sortOrder = 1; // if(property[0] === "-") { // sortOrder = -1; // property = property.substr(1); // } if(tempProp == property){ sortOrder = -sortOrder; }else{ sortOrder = 1; } tempProp = property; return function (a,b){ if(!Number.isInteger(a[property]) && !Number.isInteger(b[property])){ if(sortOrder == -1){ return b[property].localeCompare(a[property]); }else{ return a[property].localeCompare(b[property]); } }else{ if(sortOrder == -1){ return b[property]-a[property]; }else{ return a[property]-b[property]; } } } } </script>
--- title: قراءة بيانات الجدول من ملف في Aspose.Tasks linktitle: قراءة بيانات الجدول من ملف في Aspose.Tasks second_title: Aspose.Tasks جافا API description: أطلق العنان لقوة Aspose.Tasks لـ Java. تعلم كيفية استخراج بيانات الجدول من الملفات في هذا البرنامج التعليمي الشامل. type: docs weight: 17 url: /ar/java/project-data-reading/read-table-data/ --- ## مقدمة في هذا البرنامج التعليمي، سنستكشف كيفية قراءة بيانات الجدول من ملف باستخدام Aspose.Tasks لـ Java. Aspose.Tasks هي مكتبة Java قوية تتيح للمطورين العمل مع مستندات Microsoft Project برمجياً. ## المتطلبات الأساسية قبل أن نبدأ، تأكد من توفر المتطلبات الأساسية التالية: 1. Java Development Kit (JDK): تأكد من تثبيت JDK على نظامك. يمكنك تنزيله وتثبيته من موقع أوراكل. 2. Aspose.Tasks for Java JAR File: قم بتنزيل مكتبة Aspose.Tasks for Java من ملف[رابط التحميل](https://releases.aspose.com/tasks/java/) وإدراجه في مشروع Java الخاص بك. ## حزم الاستيراد قم باستيراد الحزم اللازمة للعمل مع Aspose.Tasks في مشروع Java الخاص بك: ```java import com.aspose.tasks.Project; import com.aspose.tasks.Table; import com.aspose.tasks.TableField; ``` ## الخطوة 1: إعداد دليل البيانات حدد المسار إلى الدليل الذي يوجد به ملف المشروع الخاص بك: ```java String dataDir = "Your Data Directory"; ``` يستبدل`"Your Data Directory"` مع المسار الفعلي إلى دليل البيانات الخاص بك. ## الخطوة 2: تحميل ملف المشروع قم بتحميل ملف المشروع باستخدام Aspose.Tasks: ```java Project project = new Project(dataDir + "Project2003.mpp"); ``` تأكد من استبدال`"Project2003.mpp"` مع اسم ملف المشروع الخاص بك. ## الخطوة 3: استرجاع معلومات الجدول احصل على الجدول من المشروع وكرر حقوله: ```java Table t1 = project.getTables().toList().get(0); System.out.println("Table Fields Count: " + t1.getTableFields().size()); System.out.println(); for (TableField f : t1.getTableFields()) { System.out.println("Field width: " + f.getWidth()); System.out.println("Field Title: " + f.getTitle()); System.out.println("Field Title Alignment: " + f.getAlignTitle()); System.out.println("Field Align Data: " + f.getAlignData()); System.out.println(); } ``` يسترد مقتطف التعليمات البرمجية هذا معلومات حول حقول الجدول مثل العرض والعنوان والمحاذاة. ## خاتمة في هذا البرنامج التعليمي، تعلمنا كيفية قراءة بيانات الجدول من ملف باستخدام Aspose.Tasks لـ Java. باتباع هذه الخطوات، يمكنك استخراج البيانات ومعالجتها بكفاءة من مستندات Microsoft Project في تطبيقات Java الخاصة بك. ## الأسئلة الشائعة ### س: هل Aspose.Tasks متوافق مع كافة إصدارات Microsoft Project؟ ج: يدعم Aspose.Tasks إصدارات مختلفة من Microsoft Project، بما في ذلك Project 2003 و2007 و2010 و2013 و2016. ### س: هل يمكنني تعديل بيانات الجدول وحفظها مرة أخرى في ملف المشروع؟ ج: نعم، يمكنك استخدام Aspose.Tasks لتعديل بيانات الجدول برمجياً وحفظ التغييرات في ملف المشروع الأصلي. ### س: هل يتطلب Aspose.Tasks ترخيصًا منفصلاً للاستخدام التجاري؟ ج: نعم، أنت بحاجة إلى شراء ترخيص لـ Aspose.Tasks إذا كنت تنوي استخدامه في بيئة تجارية. يمكنك الحصول على ترخيص من[صفحة الشراء](https://purchase.aspose.com/buy). ### س: هل هناك نسخة تجريبية مجانية متاحة لـ Aspose.Tasks؟ ج: نعم، يمكنك تنزيل نسخة تجريبية مجانية من Aspose.Tasks من الموقع[صفحة الإصدارات](https://releases.aspose.com/). ### س: أين يمكنني العثور على المساعدة والدعم فيما يتعلق بـ Aspose.Tasks؟ ج: يمكنك زيارة[Aspose.منتدى المهام](https://forum.aspose.com/c/tasks/15)للحصول على المساعدة والدعم من المجتمع وفريق Aspose.
// Create map to store websocket connections const connections = new Map<string, WebSocket>(); // Broadcast to connections at a pre-defined interval setInterval(() => { const now = new Date(); connections.forEach((socket) => socket.send("the current time is: " + now)); }, parseInt(Deno.env.get("PING_INTERVAL") || "10000")); for await (const conn of Deno.listen({port: 8080})) { // Handle websocket upgrade asynchronously, don't do anything with the result here upgradeWebsocket(conn) } async function upgradeWebsocket(conn: Deno.Conn) { for await (const ev of Deno.serveHttp(conn)) { const {socket, response} = Deno.upgradeWebSocket(ev.request); const uuid = crypto.randomUUID(); socket.onopen = () => { console.log("adding connection ", uuid); connections.set(uuid, socket); }; socket.onclose = () => { console.log("removing connection ", uuid); connections.delete(uuid); }; socket.onmessage = (msg) => { console.log("new message", uuid, msg.data); }; ev.respondWith(response); } }
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutterchatapp/pages/top_page.dart'; import 'package:flutterchatapp/utils/shared_prefs.dart'; import 'utils/firebase.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); await SharedPrefs.setInstance(); await checkAccount(); runApp(const MyApp()); } Future<void> checkAccount() async { String uid = SharedPrefs.getUid(); if (uid == '') { Firestore.addUser(); } } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: TopPage(), ); } }
<?php namespace App\Http\Controllers; use App\Models\Role; use Illuminate\Http\Request; class RoleController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $data = [ 'dRole' => Role::all(), ]; return view('layout.role.index', $data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('layout.role.add'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'nama_role' => 'required|min:3', ]); Role::create([ 'nama_role' => $request->nama_role, ]); return redirect()->route('role.index'); } /** * Display the specified resource. * * @param \App\Models\Role $role * @return \Illuminate\Http\Response */ public function show(Role $id) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Role $role * @return \Illuminate\Http\Response */ public function edit( $id) { $data = [ 'dRole' => Role::find($id), ]; return view('layout.role.edit', $data); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Role $role * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $request->validate([ 'nama_role' => 'required|min:3', ]); $role = Role::find($id); $role->update([ 'nama_role' => $request->nama_role ]); return redirect('/role')->with('success', 'User has been updated.'); } /** * Remove the specified resource from storage. * * @param \App\Models\Role $role * @return \Illuminate\Http\Response */ public function destroy($id) { // Temukan user yang akan dihapus $role = Role::find($id); $role->delete(); return redirect('/role')->with('success', 'User has been deleted.'); } }
""" Functions to manipulate conninfo strings """ # Copyright (C) 2020 The Psycopg Team from __future__ import annotations import re from typing import Any from . import pq from . import errors as e from . import _conninfo_utils from . import _conninfo_attempts from . import _conninfo_attempts_async # re-exoprts ConnDict = _conninfo_utils.ConnDict conninfo_attempts = _conninfo_attempts.conninfo_attempts conninfo_attempts_async = _conninfo_attempts_async.conninfo_attempts_async # Default timeout for connection a attempt. # Arbitrary timeout, what applied by the libpq on my computer. # Your mileage won't vary. _DEFAULT_CONNECT_TIMEOUT = 130 def make_conninfo(conninfo: str = "", **kwargs: Any) -> str: """ Merge a string and keyword params into a single conninfo string. :param conninfo: A `connection string`__ as accepted by PostgreSQL. :param kwargs: Parameters overriding the ones specified in `!conninfo`. :return: A connection string valid for PostgreSQL, with the `!kwargs` parameters merged. Raise `~psycopg.ProgrammingError` if the input doesn't make a valid conninfo string. .. __: https://www.postgresql.org/docs/current/libpq-connect.html #LIBPQ-CONNSTRING """ if not conninfo and not kwargs: return "" # If no kwarg specified don't mung the conninfo but check if it's correct. # Make sure to return a string, not a subtype, to avoid making Liskov sad. if not kwargs: _parse_conninfo(conninfo) return str(conninfo) # Override the conninfo with the parameters # Drop the None arguments kwargs = {k: v for (k, v) in kwargs.items() if v is not None} if conninfo: tmp = conninfo_to_dict(conninfo) tmp.update(kwargs) kwargs = tmp conninfo = " ".join(f"{k}={_param_escape(str(v))}" for (k, v) in kwargs.items()) # Verify the result is valid _parse_conninfo(conninfo) return conninfo def conninfo_to_dict(conninfo: str = "", **kwargs: Any) -> ConnDict: """ Convert the `!conninfo` string into a dictionary of parameters. :param conninfo: A `connection string`__ as accepted by PostgreSQL. :param kwargs: Parameters overriding the ones specified in `!conninfo`. :return: Dictionary with the parameters parsed from `!conninfo` and `!kwargs`. Raise `~psycopg.ProgrammingError` if `!conninfo` is not a a valid connection string. .. __: https://www.postgresql.org/docs/current/libpq-connect.html #LIBPQ-CONNSTRING """ opts = _parse_conninfo(conninfo) rv = {opt.keyword.decode(): opt.val.decode() for opt in opts if opt.val is not None} for k, v in kwargs.items(): if v is not None: rv[k] = v return rv def _parse_conninfo(conninfo: str) -> list[pq.ConninfoOption]: """ Verify that `!conninfo` is a valid connection string. Raise ProgrammingError if the string is not valid. Return the result of pq.Conninfo.parse() on success. """ try: return pq.Conninfo.parse(conninfo.encode()) except e.OperationalError as ex: raise e.ProgrammingError(str(ex)) from None re_escape = re.compile(r"([\\'])") re_space = re.compile(r"\s") def _param_escape(s: str) -> str: """ Apply the escaping rule required by PQconnectdb """ if not s: return "''" s = re_escape.sub(r"\\\1", s) if re_space.search(s): s = "'" + s + "'" return s def timeout_from_conninfo(params: ConnDict) -> int: """ Return the timeout in seconds from the connection parameters. """ # Follow the libpq convention: # # - 0 or less means no timeout (but we will use a default to simulate # the socket timeout) # - at least 2 seconds. # # See connectDBComplete in fe-connect.c value: str | int | None = _conninfo_utils.get_param(params, "connect_timeout") if value is None: value = _DEFAULT_CONNECT_TIMEOUT try: timeout = int(float(value)) except ValueError: raise e.ProgrammingError(f"bad value for connect_timeout: {value!r}") from None if timeout <= 0: # The sync connect function will stop on the default socket timeout # Because in async connection mode we need to enforce the timeout # ourselves, we need a finite value. timeout = _DEFAULT_CONNECT_TIMEOUT elif timeout < 2: # Enforce a 2s min timeout = 2 return timeout
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core'; import { ChatService } from './services/chat/chat.service'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit, AfterViewInit { @ViewChild('popup', { static: false }) popup: any; public roomId: any; public messageText: any; public messageArray: any = []; public showScreen: boolean = false; public showChat: boolean = false; public phone: any; public currentUser: any; public selectedUser: any; public formattedDate: any; private storageArray: any[] = []; public userList = [ { id: 1, name: 'Rony Weter', phone: '71644187', image: 'assets/user/rony.png', roomId: 'room1' }, { id: 2, name: 'Nathalie Nicolas', phone: '70123456', image: 'assets/user/nadine.png', roomId: 'room2' }, { id: 3, name: 'Nadine Nicolas', phone: '71932303', image: 'assets/user/nadine.png', roomId: 'room3' } ] constructor( private modalService: NgbModal, private chatService: ChatService) { } ngAfterViewInit(): void { this.openPopup(this.popup); } openPopup(content: any): void { this.modalService.open(content, { backdrop: 'static', centered: true }); } ngOnInit(): void { this.showChat = false; } login(dismiss: any): void { this.currentUser = this.userList.find(user => user.phone === this.phone.toString()); this.userList = this.userList.filter((user) => user.phone !== this.phone.toString()); if (this.currentUser) { this.showScreen = true; dismiss(); } } selectUserHandler(phone: string): void { this.selectedUser = this.userList.find(user => user.phone === phone); this.roomId = this.selectedUser.roomId; this.messageArray = []; this.storageArray = this.chatService.getStorage(); for (let i = 0; i < this.storageArray.length; i++) { const date = new Date(this.storageArray[i].chats[0].date); const hours = ("0" + date.getHours()).slice(-2); // Ensure leading zero if needed const minutes = ("0" + date.getMinutes()).slice(-2); // Ensure leading zero if needed const time = `${hours}:${minutes}`; const hours1 = date.getHours(); const period = hours1 >= 12 ? 'PM' : 'AM'; let finalDate = time + " " + period; this.formatTime(finalDate); if (this.storageArray[i].chats[0].fromRoomId == this.roomId && this.currentUser.phone == this.storageArray[i].chats[0].toPhone) { let item: any = { message: this.storageArray[i].chats[0].message, type: "from", date: this.formatTime(finalDate) }; this.messageArray.push(item); } if (this.storageArray[i].chats[0].toRoomId == this.roomId && this.currentUser.phone == this.storageArray[i].chats[0].phone) { let item: any = { message: this.storageArray[i].chats[0].message, type: "to", date: this.formatTime(finalDate) }; this.messageArray.push(item); } } console.log("this.messageArray=", this.messageArray); this.showChat = true; } sendMessage(): void { if (this.messageText) { let currentDate = new Date(); let toUser = this.userList.find(user => user.roomId === this.roomId); console.log("1111", this.currentUser); this.storageArray = this.chatService.getStorage(); const storeIndex = this.storageArray.findIndex((storage) => storage.roomId === this.roomId); console.log("storeIndex=", storeIndex); if (storeIndex > -1) { this.storageArray[storeIndex].chats.push({ user: this.currentUser.name, toRoomId: toUser?.roomId, fromRoomId: this.currentUser.roomId, message: this.messageText, phone: this.currentUser.phone, toPhone: toUser?.phone, date: currentDate.toString() }); } else { const updateStorage = { chats: [{ user: this.currentUser.name, toRoomId: toUser?.roomId, fromRoomId: this.currentUser.roomId, message: this.messageText, phone: this.currentUser.phone, toPhone: toUser?.phone, date: currentDate.toString() }] }; this.storageArray.push(updateStorage); } this.chatService.setStorage(this.storageArray); this.messageText = ''; this.selectUserHandler(this.selectedUser.phone); } } formatTime(timeString: any) { const [time, period] = timeString.split(" "); const [hoursStr, minutesStr] = time.split(":"); // Parse hours and minutes as integers let hours = parseInt(hoursStr, 10); const minutes = parseInt(minutesStr, 10); // Convert hours to 12-hour format and adjust the period let period1 = ''; if (hours >= 12) { period1 = 'pm'; if (hours > 12) { hours -= 12; } } else { period1 = 'am'; if (hours === 0) { hours = 12; } } const formattedTime = `${hours}:${minutes < 10 ? '0' : ''}${minutes} ${period}`; return formattedTime; } }
package com.example.mdbspringboot.order; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/orders") public class OrderController { @Autowired private OrderService service; @PostMapping public Order create(@RequestBody Order order){ return service.add(order); } @GetMapping public List<Order> get(){ return service.findAll(); } @PutMapping("/{id}") public Order update(@PathVariable String id, @RequestBody Order updatedOrder) { return service.update(id, updatedOrder); } @DeleteMapping("/{id}") public void delete(@PathVariable String id) { service.delete(id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using EventOrganizerDomain.Model; using EventOrganizerInfrastructure; namespace EventOrganizerInfrastructure.Controllers { public class CitiesController : Controller { private readonly DbeventOrganizerContext _context; public CitiesController(DbeventOrganizerContext context) { _context = context; } // GET: Cities public async Task<IActionResult> Index() { var dbeventOrganizerContext = _context.Cities .Include(c => c.Country) .Include(p => p.Places); return View(await dbeventOrganizerContext.ToListAsync()); } // GET: Cities/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var city = await _context.Cities .Include(c => c.Country) .FirstOrDefaultAsync(m => m.Id == id); if (city == null) { return NotFound(); } //return View(city); return RedirectToAction("Index", "Places", new { id = city.Id, name = city.Name, country = city.Country}); } // GET: Cities/Create public IActionResult Create() { ViewData["CountryId"] = new SelectList(_context.Countries, "Id", "Name"); return View(); } // POST: Cities/Create // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("CountryId,Name,Id")] City city) { if (ModelState.IsValid) { _context.Add(city); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["CountryId"] = new SelectList(_context.Countries, "Id", "Name", city.CountryId); return View(city); } // GET: Cities/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var city = await _context.Cities.FindAsync(id); if (city == null) { return NotFound(); } ViewData["CountryId"] = new SelectList(_context.Countries, "Id", "Name", city.CountryId); return View(city); } // POST: Cities/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("CountryId,Name,Id")] City city) { Country country = await _context.Countries.FindAsync(city.CountryId); city.Country = country; ModelState.Clear(); TryValidateModel(city); if (id != city.Id) { return NotFound(); } if (ModelState.IsValid) { try { var cityToUpdate = await _context.Cities.FindAsync(id); if (cityToUpdate == null) { return NotFound(); } cityToUpdate.CountryId = city.CountryId; cityToUpdate.Name = city.Name; _context.Update(cityToUpdate); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CityExists(city.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["CountryId"] = new SelectList(_context.Countries, "Id", "Name", city.CountryId); return View(city); } // GET: Cities/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var city = await _context.Cities .Include(c => c.Country) .FirstOrDefaultAsync(m => m.Id == id); if (city == null) { return NotFound(); } return View(city); } // POST: Cities/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var city = await _context.Cities.FindAsync(id); if (city != null) { _context.Cities.Remove(city); } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool CityExists(int id) { return _context.Cities.Any(e => e.Id == id); } } }
import { Article } from '@/types'; import { getArticle, getArticles } from '@/utils'; import { Box, Flex, Heading, Text, VStack, useColorModeValue, } from '@chakra-ui/react'; import Image from 'next/image'; import { GetStaticPaths, GetStaticProps } from 'next'; import format from 'date-fns/format'; import { IParams } from '@/types'; import MarkdownRenderer from '@/components/shared/UIElements/MarkdownRenderer'; export const getStaticPaths: GetStaticPaths = async () => { const { articles }: { articles: Article[] } = await getArticles(); const paths = articles.map((article: Article) => ({ params: { id: article.id.toString() }, })); return { paths, fallback: false, }; }; export const getStaticProps: GetStaticProps = async (context) => { const { id } = context.params as IParams; const { article }: { article: Article } = await getArticle(id); return { props: { article, }, revalidate: 86400, }; }; export default function BlogDetailPage({ article }: { article: Article }) { return ( <Flex flexDir='column' alignItems='center' justifyContent='center' bg={useColorModeValue('brand.100', 'gray.800')} > <Flex align='center' borderBottom='1px' borderColor={useColorModeValue('gray.200', 'gray.700')} flexDir={['column-reverse', null, 'row']} > <VStack w={['full', null, '50%']} py={[3, null, 0]} px={[4, 2, null]}> <Flex maxW='500px' flexDir='column'> <Heading>{article.attributes.title}</Heading> <Text color='gray.500'> {format(new Date(article.attributes.createdAt), 'MMMM do, yyyy')} </Text> </Flex> </VStack> <Box w={['full', null, '50%']}> <Image src={article.attributes.image.data.attributes.url} alt={article.attributes.title} width={article.attributes.image.data.attributes.width} height={article.attributes.image.data.attributes.height} priority /> </Box> </Flex> <MarkdownRenderer content={article.attributes.content} /> </Flex> ); }
# Linear regression models: Diagnostics and model-building ```{r} pacman::p_load(tidyverse, GLMsData, janitor, patchwork) ``` ```{r} data("lungcap") lung <- lungcap |> as_tibble() |> clean_names() |> mutate(smoke = factor( smoke, levels = c(0, 1), labels = c('Non-smoker', 'Smoker'))) ``` ## Residuals for non-normal linear models ```{r} model <- lung |> lm(fev ~ ht + gender + smoke, data = _) c('Residuals' = var(resid(model)), 'Stadarized residuals' = var(rstandard(model))) ``` ```{r} p1 <- resid(model) |> as_tibble() |> ggplot(aes(value)) + geom_histogram(bins = 50) p2 <- rstandard(model) |> as_tibble() |> ggplot(aes(value)) + geom_histogram(bins = 50) p1 + p2 ``` ## Leverages for linear regression models ```{r} hat_values <- hatvalues(model) # Two largest leverages sort(hat_values, decreasing = TRUE)[1:2] # Mean of leverages mean(hat_values); length(coef(model)) / length(lung$fev) sort(hat_values, decreasing = TRUE)[1:2] / mean(hat_values) ``` ```{r} sort_h <- sort(hat_values, decreasing = TRUE, index.return = TRUE) large_h <- sort_h$ix[1:2] lung[large_h, ] ``` ```{r} lung |> rowid_to_column() |> mutate(color = case_when( rowid %in% large_h ~ 1, TRUE ~ 0 )) |> filter(gender == 'M' & smoke == 'Smoker') |> ggplot(aes(ht, fev, color = color)) + geom_point() + theme(legend.position = 'none') + ggtitle('Male smokers') ``` ## Residual plots ### Residuals against $x_j$ ```{r} scatter.smooth(rstandard(model) ~ lung$ht, col = 'gray') ``` ```{r} bind_cols(lung, rstandard(model) |> as_tibble()) |> ggplot(aes(ht, value)) + geom_point(alpha = .5) + geom_smooth(method = 'loess', formula = 'y ~ x') ``` ### Partial residual plots ```{r} partial_resid <- resid(model, type = 'partial') |> as_tibble(); partial_resid ``` ```{r} termplot(model, partial.resid = TRUE, terms = 'ht', las = 1) ``` ```{r} bind_cols(lung, partial_resid |> select(partial_resid = ht)) |> ggplot(aes(ht, partial_resid)) + geom_point(alpha = .5) + geom_smooth(method = 'loess', formula = 'y ~ x') ``` ```{r} coef(summary(model)) ht_model <- bind_cols(lung, partial_resid |> select(partial_resid = ht)) |> lm(partial_resid ~ ht, data = _) coef(summary(ht_model)) ``` ### Plot residuals against $\hat{\mu}$: Constant variance ```{r} scatter.smooth(rstandard(model) ~ fitted(model), col = 'grey') ``` ```{r} bind_cols(rstandard(model), fitted(model)) |> rename(resid = 1, fitted = 2) |> ggplot(aes(fitted, resid)) + geom_point(alpha = .5) + geom_smooth(method = 'loess', formula = 'y ~ x') ``` ### Q---Q plots and normality ```{r} qqnorm(rstandard(model)) qqline(rstandard(model)) ``` ```{r} resid <- rstandard(model) |> as_tibble() p1 <- resid |> ggplot(aes(sample = value)) + stat_qq() + stat_qq_line() p2 <- resid |> ggplot(aes(value)) + geom_histogram(bins = 50) p1 + p2 ``` ## Outliers and influential observations ### Studentized residuals ```{r} summary(cbind(Standarized = rstandard(model), Studentized = rstudent(model))) ``` ### Influential observations ```{r} model <- lung |> lm(fev ~ ht + gender + smoke, data = _) ``` ```{r} # Cook' distance cooks_max <- which.max(cooks.distance(model)) cooks_min <- which.min(cooks.distance(model)) c(Min = cooks_min, Max = cooks_max) # DFFITS, CV and Cook's distance out <- cbind( DFFITS = dffits(model), Cooks = cooks.distance(model), Cov_rat = covratio(model) ) round(out[c(cooks_min, cooks_max), ], 5) ``` ```{r} model |> broom::tidy() dfbetas(model)[cooks_min, ] dfbetas(model)[cooks_max, ] ``` ```{r} influence <- influence.measures(model); names(influence) head(round(influence$infmat, 3)) head(influence$is.inf) ``` ```{r} colSums(influence$is.inf) # 7 observations have high leverage # 56 observations are identified by the coveriance ratio as influential # Cook's distance does not identify any observation as influential ``` ```{r} table(rowSums(influence$is.inf[, -8])) # 54 observations are declared as influential on just one criterion ``` #### Influence diagnostics ```{r} bind_cols( cooks.distance(model) |> as_tibble_col('cooks'), dffits(model) |> as_tibble_col('dffits'), dfbetas(model) |> as_tibble() |> select(3) ) |> rowid_to_column() |> pivot_longer(!rowid) |> ggplot(aes(rowid, value, fill = name)) + geom_col() + facet_wrap(~ name, scales = 'free_y') ``` ## Transforming the response ```{r} model_sqrt <- lung |> lm(sqrt(fev) ~ ht + gender + smoke, data = _) bind_cols( rstandard(model_sqrt) |> as_tibble_col('standardized'), fitted(model_sqrt) |> as_tibble_col('fitted') ) |> ggplot(aes(fitted, standardized)) + geom_point() ``` ```{r} model_log <- lung |> lm(log(fev) ~ ht + gender + smoke, data = _) bind_cols( rstandard(model_log) |> as_tibble_col('log'), fitted(model_log) |> as_tibble_col('fitted') ) |> ggplot(aes(fitted, log)) + geom_point() ``` #### The Box-Cox transformation ```{r} library(MASS) boxcox(fev ~ ht + gender + smoke, lambda = seq(-.25, .25, length = 11), data = lung) ``` ## Simple transformations of covariates ```{r} data('windmill') windmill <- windmill |> as_tibble() |> clean_names() ``` ```{r} transformations <- windmill |> mutate(wind_log = log(wind), wind_inv = 1/wind) models <- transformations |> map(~ lm(dc ~ .x, data = windmill)) ``` ```{r} rstandard <- models |> map_dfc(rstandard) |> rename_with(~ str_c(., '_rstandard'), .cols = contains('wind')) fitted <- models |> map_dfc(fitted) |> rename_with(~ str_c(., '_fitted'), .cols = contains('wind')) results <- windmill |> bind_cols( rstandard |> select(!dc), fitted |> select(!dc), transformations |> select(!c(dc, wind)) ) ``` ```{r} p1 <- results |> pivot_longer(!c(dc, contains('rstandard'), contains('fitted'))) |> ggplot(aes(value, dc, color = name)) + geom_point() + geom_smooth(method = 'loess', formula = 'y ~ x') + facet_wrap(~ name, scales = 'free') + theme(legend.position = 'none') ``` ```{r} results |> select(!c(dc)) |> pivot_longer(contains('rstandard'), names_to = 'rstandard', values_to = 'r_vals') |> pivot_longer(contains('fitted'), names_to = 'fitted', values_to = 'f_vals') |> pivot_longer(!c(rstandard, r_vals, fitted, f_vals), names_to = 'transformations', values_to = 'vals') |> select(!vals) |> ggplot(aes(f_vals, r_vals, color = transformations)) + geom_point() + geom_smooth(method = 'loess', formula = 'y ~ x') + facet_wrap(~ transformations, scales = 'free') + theme(legend.position = 'none') ``` ## Polynomial trends ```{r} data("heatcap") heat <- heatcap |> as_tibble() |> clean_names() ``` ```{r} heat |> ggplot(aes(temp, cp)) + geom_point() + ylab('Heat capacity (cal/(mol.K)') + xlab('Temp (Kelvin)') ``` #### Raw polynomial ```{r} model <- heat |> lm(cp ~ temp + I(temp^2), data = _) summary(model, correlation = TRUE)$correlation summary(model) ``` ```{r} heat |> bind_cols('pred' = predict(model)) |> pivot_longer(!temp) |> ggplot(aes(temp, value, color = name)) + geom_point() ``` #### Orthogonal polynomials ```{r} model_one <- heat |> lm(cp ~ poly(temp, 1), data = _) model_two <- heat |> lm(cp ~ poly(temp, 2), data = _) model_three <- heat |> lm(cp ~ poly(temp, 3), data = _) model_four <- heat |> lm(cp ~ poly(temp, 4), data = _) ``` ```{r} summary(model_two, correlation = TRUE)$correlation zapsmall(summary(model_two, correlation = TRUE)$correlation) ``` ```{r} heat |> bind_cols( 'linear' = predict(model_one), 'quadratic' = predict(model_two), 'cubic' = predict(model_three), 'quartic' = predict(model_four) ) |> pivot_longer( !c('cp', 'temp') ) |> mutate( across(name, factor, levels = c('linear', 'quadratic', 'cubic', 'quartic')) ) |> ggplot(aes(temp, cp)) + geom_point() + geom_line(aes(y = value, color = name)) + facet_wrap(~ name) + theme( legend.position = 'bottom' ) ``` ```{r} model_four |> broom::tidy() ``` #### Diagnostics for the cubic model ```{r} p1 <- bind_cols(rstandard(model_three), fitted(model_three)) |> rename(resid = 1, fitted = 2) |> ggplot(aes(fitted, resid)) + geom_point(alpha = .5) + ylab('Standardized residuals') + xlab('Fitted values') p2 <- heat |> bind_cols('resid' = rstandard(model_three)) |> ggplot(aes(temp, resid)) + geom_point(alpha = .5) + ylab('Standardized residuals') + xlab('Temp') p3 <- rstandard(model_three) |> as_tibble() |> ggplot(aes(sample = value)) + stat_qq() + stat_qq_line() p4 <- cooks.distance(model_three) |> as_tibble() |> rowid_to_column() |> ggplot(aes(rowid, value)) + geom_col() p1 + p2 / p3 + p4 ``` ## Regression splines ```{r} library(splines) bs(heat$temp, knots=quantile(heat$temp, c(.3, 0.6)), degree=2) ``` ```{r} poly <- heat |> lm(cp ~ poly(temp, 3), data = _) ns <- heat |> lm(cp ~ ns(temp, df = 3), data = _) bs <- heat |> lm(cp ~ bs(temp, df = 3), data = _) ``` ```{r} heat |> bind_cols( 'poly' = predict(poly), 'ns' = predict(ns), 'bs' = predict(bs) ) |> pivot_longer(!c('cp', 'temp')) |> ggplot() + geom_point(aes(temp, cp)) + geom_line(aes(temp, value, color = name)) + facet_wrap(~ name) ``` ```{r} extractAIC(poly); extractAIC(ns); extractAIC(bs) ``` ```{r} splines <- function(df) { heat |> ggplot(aes(temp, cp)) + geom_point() + geom_smooth( method = lm, formula = y ~ ns(x, df) ) + labs( title = glue::glue('Knots: {df}') ) } plots <- list() knots <- c(1, 4, 7) for (i in knots) { print(plots[[i]] <- splines(df = i)) } ``` ## Case study 1 ```{r} data(dental) dental <- dental |> as_tibble() |> clean_names() ``` ```{r} model <- dental |> lm(dmft ~ sugar * indus, data = _) log_model <- dental |> lm(log(dmft) ~ sugar * indus, data = _) ``` ```{r} diagnose <- function(data, model) { indicators <- data |> mutate( rstandard = rstandard(model), fitted = fitted(model), cooks = cooks.distance(model), rowid_to_column(data) ) p1 <- indicators |> ggplot(aes(fitted, rstandard)) + geom_point() + geom_smooth( formula = 'y ~ x', method = 'loess' ) + labs( x = 'Fitted values', y = 'Standardized residuals' ) p2 <- indicators |> ggplot(aes(sample = rstandard)) + stat_qq() + stat_qq_line() + labs( x = 'Theoretical quantiles', y = 'Sample quantiles' ) p3 <- indicators |> ggplot(aes(rowid, cooks)) + geom_col() + labs( x = 'Index', y = 'Cook´s distance' ) (p1 + p2) / p3 + plot_annotation( title = 'Model diagnostics', subtitle = glue::glue('Data: { str_to_title(deparse(substitute(data))) } | Model: { str_to_title(deparse(substitute(model))) }'), theme = theme( plot.title = element_text( size = 16, hjust = 0.5, margin = margin(5, 0, 0, 0) ), plot.subtitle = element_text( size = 10, hjust = 0.5, margin = margin(5, 0, 15, 0) ) ) ) } ``` ```{r} diagnose(dental, model) diagnose(dental, log_model) ``` ```{r} im <- influence.measures(log_model) colSums(im$is.inf) ``` ```{r} anova(log_model) summary(log_model) ``` The model can be written as: $$ \begin{cases} y \sim N(\mu_i, s^2 = 0.298) \\ \mu_i = 1.38711 - 0.00588x_1 - 1.29160x_2 + 0.02727x_1x_2 \end{cases} $$ The systematic component can be expanded as: $$ E[log(y_i)] = \mu_i = \begin{cases} 1.38711 - 0.00588x_1 & \text{for industrialized countries} \\ 0.09551 + 0.02139x_1 & \text{for non-industrialized countries} \end{cases} $$ ```{r} c( 'AIC (model): ' = extractAIC(model)[2], 'AIC (log_model): ' = extractAIC(log_model)[2] ) ``` ```{r} dental |> mutate( fit = fitted(model) ) |> ggplot(aes(sugar, dmft, color = indus)) + geom_point() + geom_line(aes(y = fit, color = indus)) dental |> mutate( fit = fitted(log_model), dmft = log(dmft) ) |> ggplot(aes(sugar, dmft, color = indus)) + geom_point() + geom_line(aes(y = fit, color = indus)) ``` ## Case study 2 ```{r} data(cheese) cheese <- cheese |> as_tibble() |> clean_names() ``` ```{r} cheese |> mutate(log_h2s = log(h2s)) |> pivot_longer(!taste) |> ggplot(aes(value, taste, color = name)) + geom_point() + facet_wrap(~name, scales = 'free_x') + theme(legend.position = 'none') + labs(y = 'Teste score', x = 'Values') ``` #### Interactions ```{r} full_model <- cheese |> lm(taste ~ acetic * log(h2s) * lactic, data = _) summary(full_model) drop1(full_model, test = 'F') ``` ```{r} no_inter_model <- update(full_model, . ~ (acetic + log(h2s) : + lactic)^2) summary(no_inter_model) drop1(no_inter_model, test = 'F') ``` ```{r} no_main_model <- cheese |> lm(taste ~ log(h2s) + lactic + acetic, data = _) summary(no_main_model) drop1(no_main_model, test = 'F') ``` ```{r} final_model <- cheese |> lm(taste ~ log(h2s) + lactic, data = _) summary(final_model) ``` ```{r} cheese |> mutate(log_h2s = log(h2s)) |> corrr::correlate() ``` ```{r} diagnose(cheese, final_model) ``` ```{r} cheese |> mutate( resid = rstandard(model), log_h2s = log(h2s) ) |> select(acetic, lactic, log_h2s, resid) |> pivot_longer(!resid) |> ggplot(aes(value, resid, color = name)) + geom_point() + geom_smooth(method = 'loess', formula = 'y ~ x', se = FALSE) + facet_wrap(~ name, scales = 'free_x') + theme(legend.position = 'none') ``` ```{r} im <- influence.measures(final_model); colSums(im$is.inf) ```
package main import ( "fmt" "sync" "time" ) // Paramter should have pointer to waitgroup func PrintName(s string, wg *sync.WaitGroup) { for i := 0; i < 10; i++ { fmt.Println(s) time.Sleep(100) } // Once process is done then we should mark waitgroup as done wg.Done() } func PrintNumbers(i int, wg *sync.WaitGroup) { defer wg.Done() for j := 0; j < i; j++ { fmt.Println(j) time.Sleep(100) } } func main() { // Waitgroup is like an manager which manage the go routines var wg sync.WaitGroup // We should add how many go routines will run in parallel wg.Add(2) // Go routines should have a parameter to pointer of Waitgroup go PrintName("Dinesh", &wg) go PrintName("Gaurav", &wg) //wg.Add(1) // If we don't add waitgroup // then the goroutines will work concurrently but while calling wg.wait it will check for 0 count only go PrintNumbers(100, &wg) // In the end we can call waitgroup.wait . This function will wait until all go routines are done wg.Wait() fmt.Println("Main thread") }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Product Management</title> <link rel="icon" href="/Web_Travel/2.Service/resources/images/online-shopping.png"> <link rel="icon" href="/Web_Travel/2.Service/login/assets/logo.png"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/boxicons/2.0.7/css/boxicons.min.css"> <style> .center { text-align: center; font-size: 17px; } .button-style { border-radius: 5px; color: #0a4f4f; border: none; padding: 7px 10px; text-align: center; text-decoration: none; display: inline-block; font-size: 18px; margin: 5px 3px; cursor: pointer; } .button-style:hover { box-shadow: 0px 0px 7px rgba(14, 125, 125, 0.5); } .header-row { background-color: #d1ecf1; } .pagination { justify-content: center; } .table-wrapper { margin-top: 20px; } .table-title h2 { margin: 5px 0; } .table-title .btn { font-size: 18px; margin-left: 10px; } .table-title .btn i { margin-right: 5px; } .row-hover:hover { background-color: #f2f2f2; } .deleted { display: none; } </style> </head> <body> <div class="container"> <div class="table-wrapper"> <div class="table-title"> <div class="row" style="margin-left: 400px;"> <div class="col-sm-6"> <h2 style="font-size:40px;"><b>Product List</b></h2> </div> <div class="col-sm-6"> <a href="${pageContext.request.contextPath}/add" class="btn btn-success" data-toggle="modal" style="margin-left:200px;bottom:3px;"><span>+ Create</span></a> </div> </div> </div> <table class="table table-bordered"> <thead class="header-row"> <tr> <th class="center"><input type="checkbox" id="selectAll" onclick="toggleSelectAll()"></th> <th class="center">ID</th> <th class="center">Name Tour</th> <th class="center">Image</th> <th class="center">Price</th> <th class="center">Date</th> <th class="center">Category</th> <th class="center">Actions</th> </tr> </thead> <tbody> <c:forEach var="product" items="${products}"> <tr class="row-hover"> <td style="text-align: center; vertical-align: middle;"> <input type="checkbox" name="selectProduct" value="${product.id}"> </td> <td style="text-align: center; vertical-align: middle;">${product.id}</td> <td style="text-align: center; vertical-align: middle;">${product.tourName}</td> <td style="text-align: center; vertical-align: middle;"> <img src="./2.Service/resources/images/image_tour/${product.image}" alt="${product.tourName}" style="width: 250px; height: auto; display: block; margin: 0 auto;"> </td> <td style="text-align: center; vertical-align: middle;">${product.price}</td> <td style="text-align: center; vertical-align: middle;">${product.date}</td> <td style="text-align: center; vertical-align: middle;">${product.categoryName}</td> <td style="text-align: center; vertical-align: middle;" class="action-icons"> <a href="Service_Th7_detail_Servlet?id=${product.id}" class="button-style"><i class='bx bx-info-circle'></i></a> <a href="${pageContext.request.contextPath}/edit?id=${product.id}" class="button-style"><i class='bx bx-edit'></i></a> <form class="d-inline" action="Service_Th6_DeleteProductM_Servlet" method="post"> <input type="hidden" name="id" value="${product.id}"> <input type="hidden" name="sellId" value="${product.sellId}"> <button style="border: none; background: none;" type="submit" data-toggle="tooltip" title="Delete" data-placement="bottom" onclick="return confirm('Do you really want to delete this item?')"> <span class="button-style"> <i class="bx bx-trash"></i> </span> </button> </form> </td> </tr> </c:forEach> </tbody> </table> </div> </div> <script> function toggleSelectAll() { const selectAllCheckbox = document.getElementById('selectAll'); const checkboxes = document.getElementsByName('selectProduct'); checkboxes.forEach(checkbox => { checkbox.checked = selectAllCheckbox.checked; }); } </script> </body> </html>
package com.example.s.camera2basic; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.RectF; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.CaptureResult; import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.Image; import android.media.ImageReader; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.support.annotation.NonNull; import android.support.v13.app.FragmentCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.util.Size; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class Camera2BasicFragment extends Fragment implements View.OnClickListener, FragmentCompat.OnRequestPermissionsResultCallback { //Conversion from screen rotation to JPEG orientation. //画面回転からJPEG方向への変換 private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); private static final int REQUEST_CAMERA_PERMISSION = 1; private static final String FRAGMENT_DIALOG = "dialog"; static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } //Tag for the {@link Log}. private static final String TAG = "Camera2BasicFragment"; //Camera state //STATE_PREVIEW: Showing camera preview. //STATE_WAITING_LOCK: Waiting for the focus to be locked. //STATE_WAITING_PRECAPTURE: Waiting for the exposure to be precapture state. //STATE_WAITING_NON_PRECAPTURE: Waiting for the exposure state to be something other than precapture. //STATE_PICTURE_TAKEN: Picture was taken. private static final int STATE_PREVIEW = 0; private static final int STATE_WAITING_LOCK = 1; private static final int STATE_WAITING_PRECAPTURE = 2; private static final int STATE_WAITING_NON_PRECAPTURE = 3; private static final int STATE_PICTURE_TAKEN = 4; //Camera2 APIで保証されているプレビューの最大幅と高さ private static final int MAX_PREVIEW_WIDTH = 1920; private static final int MAX_PREVIEW_HEIGHT = 1080; //TextureView.SurfaceTextureListenerは、TextureView上のいくつかのライフサイクルイベントを処理します。 private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) { openCamera(width, height); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) { configureTransform(width, height); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) { return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture texture) { } }; //ID of the current CameraDevice private String mCameraId; //AutoFitTextureView for camera preview. private AutoFitTextureView mTextureView; //CameraCaptureSession for camera preview. private CameraCaptureSession mCaptureSession; //A reference to the opened CameraDevice. private CameraDevice mCameraDevice; //The android.util.Size of camera preview. private Size mPreviewSize; //CameraDeviceが状態を変更すると、CameraDevice.StateCallbackが呼び出されます。 private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(@NonNull CameraDevice cameraDevice) { // このメソッドは、カメラを開いたときに呼び出されます。 ここでカメラのプレビューを開始します。 mCameraOpenCloseLock.release(); mCameraDevice = cameraDevice; createCameraPreviewSession(); } @Override public void onDisconnected(@NonNull CameraDevice cameraDevice) { mCameraOpenCloseLock.release(); cameraDevice.close(); mCameraDevice = null; } @Override public void onError(@NonNull CameraDevice cameraDevice, int error) { mCameraOpenCloseLock.release(); cameraDevice.close(); mCameraDevice = null; Activity activity = getActivity(); if (null != activity) { activity.finish(); } } }; //UIをブロックすべきでないタスクを実行するための追加のスレッド。 private HandlerThread mBackgroundThread; //バックグラウンドでタスク(このサンプルでは静止画の保存)を実行するためのハンドラ。 private Handler mBackgroundHandler; //静止画キャプチャを処理するImageReader。 private ImageReader mImageReader; //This is the output file for our picture. private File mFile; //これは、ImageReaderのコールバックオブジェクトです。 //静止画を保存する準備ができたら、"onImageAvailable"が呼び出されます。 private final ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() { @Override public void onImageAvailable(ImageReader reader) { mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile)); } }; //CaptureRequest.Builder for the camera preview private CaptureRequest.Builder mPreviewRequestBuilder; //CaptureRequest generated by #mPreviewRequestBuilder private CaptureRequest mPreviewRequest; //The current state of camera state for taking pictures. private int mState = STATE_PREVIEW; //カメラを閉じる前にアプリが終了しないようにするセマフォ。 private Semaphore mCameraOpenCloseLock = new Semaphore(1); //現在のカメラデバイスがFlashをサポートしているかどうか。 private boolean mFlashSupported; //カメラセンサーの向き private int mSensorOrientation; //JPEGキャプチャに関連するイベントを処理するCameraCaptureSession.CaptureCallback。 private CameraCaptureSession.CaptureCallback mCaptureCallback = new CameraCaptureSession.CaptureCallback() { private void process(CaptureResult result) { switch (mState) { case STATE_PREVIEW: { // カメラのプレビューが正常に機能しているときは、何もしません。 break; } case STATE_WAITING_LOCK: { Integer afState = result.get(CaptureResult.CONTROL_AF_STATE); if (afState == null) { captureStillPicture(); } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState || CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) { //CONTROL_AE_STATEは一部のデバイスではnullになることがあります Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); if (aeState == null || aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) { mState = STATE_PICTURE_TAKEN; captureStillPicture(); } else { runPrecaptureSequence(); } } break; } case STATE_WAITING_PRECAPTURE: { //CONTROL_AE_STATEは一部のデバイスではnullになることがあります Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); if (aeState == null || aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE || aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) { mState = STATE_WAITING_NON_PRECAPTURE; } break; } case STATE_WAITING_NON_PRECAPTURE: { //CONTROL_AE_STATEは一部のデバイスではnullになることがあります Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) { mState = STATE_PICTURE_TAKEN; captureStillPicture(); } break; } } } @Override public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) { process(partialResult); } @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { process(result); } }; //UIスレッドでtextを表示します。 private void showToast(final String text) { final Activity activity = getActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, text, Toast.LENGTH_SHORT).show(); } }); } } /** * カメラでサポートされているサイズの{@code choices}があれば、 * それぞれのテクスチャビューのサイズと少なくとも同じ大きさの最小サイズを選択します。 * サイズはそれぞれの最大サイズと同程度に大きく、アスペクト比は指定された値と一致します。 * そのようなサイズが存在しない場合は、それぞれの最大サイズと同じ大きさで、 * アスペクト比が指定された値と一致する最大サイズを選択します。 * @param choices 意図した出力クラスに対してカメラがサポートするサイズのリスト * @param textureViewWidth センサ座標に対するテクスチャビューの幅 * @param textureViewHeight センサ座標に対するテクスチャビューの高さ * @param maxWidth 選択できる最大幅 * @param maxHeight 選択できる最大の高さ * @param aspectRatio アスペクト比 * @return 最適な{@code Size}、または大きさが十分でない場合は任意のサイズ */ private static Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) { //少なくともプレビューサーフェスと同じ大きさのサポートされている解像度を収集する List<Size> bigEnough = new ArrayList<>(); //プレビューサーフェスよりも小さいサポートされた解像度を収集する List<Size> notBigEnough = new ArrayList<>(); int w = aspectRatio.getWidth(); int h = aspectRatio.getHeight(); for (Size option : choices) { if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight && option.getHeight() == option.getWidth() * h / w) { if (option.getWidth() >= textureViewWidth && option.getHeight() >= textureViewHeight) { bigEnough.add(option); } else { notBigEnough.add(option); } } } //十分大きいものの中で最小のものを選んでください。 // 十分な大きさの物がない場合は、大きくない物の中から最大のものを選びます。 if (bigEnough.size() > 0) { return Collections.min(bigEnough, new CompareSizesByArea()); } else if (notBigEnough.size() > 0) { return Collections.max(notBigEnough, new CompareSizesByArea()); } else { Log.e(TAG, "Couldn't find any suitable preview size"); return choices[0]; } } //Camera2BasicFragmentのインスタンスを作成 public static Camera2BasicFragment newInstance() { return new Camera2BasicFragment(); } //FragmentがView階層に関連付けられる時に呼ばれる。 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_camera2_basic, container, false); } @Override public void onViewCreated(final View view, Bundle savedInstanceState) { view.findViewById(R.id.picture).setOnClickListener(this); view.findViewById(R.id.info).setOnClickListener(this); mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture); } //Fragmentが関連付いているActivityのonCreate()が呼ばれた直後に呼び出される。 //ActivityのonCreate()で行なっていた処理はこのメソッドに記述しておくと良い。 @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg"); } //アプリ開始時,またはアプリ再開時 @Override public void onResume() { super.onResume(); startBackgroundThread();//BackgroundThreadを開始 //スクリーンがオフにされ、再びオンにされると、SurfaceTextureはすでに使用可能であり、 //mSurfaceTextureListener内の"onSurfaceTextureAvailable"は呼び出されません。 //その場合、カメラを開いてここからプレビューを開始することができます // (そうでない場合は、サーフェスがSurfaceTextureListenerで準備されるまで待機します) if (mTextureView.isAvailable()) { openCamera(mTextureView.getWidth(), mTextureView.getHeight()); } else { mTextureView.setSurfaceTextureListener(mSurfaceTextureListener); } } //Fragmentが置き換えられたとき @Override public void onPause() { closeCamera();//カメラを止める stopBackgroundThread();//バックグラウンドを止める super.onPause(); } private void requestCameraPermission() { if (FragmentCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { new ConfirmationDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG); } else { FragmentCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); } } //ユーザ操作により,カメラ使用許可要求の結果が返ってきたら呼ばれる @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_CAMERA_PERMISSION) { if (grantResults.length != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { ErrorDialog.newInstance(getString(R.string.request_permission)) .show(getChildFragmentManager(), FRAGMENT_DIALOG); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } //カメラに関連するメンバ変数を設定します。 //@param width カメラプレビューで使用できるサイズの幅 //@param height カメラプレビューで使用できるサイズの高さ private void setUpCameraOutputs(int width, int height) { Activity activity = getActivity(); CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { for (String cameraId : manager.getCameraIdList()) { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); //このサンプルでは、フロントカメラ(インカメラ,facing camera)は使用していません。 Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { continue;//フロントカメラならスキップ } StreamConfigurationMap map = characteristics.get( CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { continue; } //静止画キャプチャでは、使用可能な最大のサイズを使用します。 Size largest = Collections.max( Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea()); mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/2); mImageReader.setOnImageAvailableListener( mOnImageAvailableListener, mBackgroundHandler); //プレビューサイズをセンサ座標に関連付けるために寸法を交換する必要があるかどうかを調べる。 int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation(); //no inspection ConstantConditions mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); boolean swappedDimensions = false; switch (displayRotation) { case Surface.ROTATION_0: case Surface.ROTATION_180: if (mSensorOrientation == 90 || mSensorOrientation == 270) { swappedDimensions = true; } break; case Surface.ROTATION_90: case Surface.ROTATION_270: if (mSensorOrientation == 0 || mSensorOrientation == 180) { swappedDimensions = true; } break; default: Log.e(TAG, "Display rotation is invalid: " + displayRotation); } Point displaySize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(displaySize); int rotatedPreviewWidth = width; int rotatedPreviewHeight = height; int maxPreviewWidth = displaySize.x; int maxPreviewHeight = displaySize.y; if (swappedDimensions) { rotatedPreviewWidth = height; rotatedPreviewHeight = width; maxPreviewWidth = displaySize.y; maxPreviewHeight = displaySize.x; } if (maxPreviewWidth > MAX_PREVIEW_WIDTH) { maxPreviewWidth = MAX_PREVIEW_WIDTH; } if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) { maxPreviewHeight = MAX_PREVIEW_HEIGHT; } //危険、W.R.! 大きすぎるプレビューサイズを使用しようとすると、 // カメラの帯域幅の制限を超える可能性があります。 // その結果、プレビューは綺麗ですが、ガベージキャプチャデータが保存されます。 mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest); //TextureViewのアスペクト比を、私たちが選んだプレビューのサイズに合わせました。 int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mTextureView.setAspectRatio( mPreviewSize.getWidth(), mPreviewSize.getHeight()); } else { mTextureView.setAspectRatio( mPreviewSize.getHeight(), mPreviewSize.getWidth()); } //フラッシュがサポートされているか確認してください。 Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE); mFlashSupported = available == null ? false : available; mCameraId = cameraId; return; } } catch (CameraAccessException e) { e.printStackTrace(); } catch (NullPointerException e) { //現在、Camera2APIが使用されているが、 //このコードが実行されているデバイスではサポートされていない場合、NPEがスローされます。 ErrorDialog.newInstance(getString(R.string.camera_error)) .show(getChildFragmentManager(), FRAGMENT_DIALOG); } } //Camera2BasicFragment#mCameraIdで指定されたカメラを開きます。 private void openCamera(int width, int height) { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { requestCameraPermission();//カメラ使用の許可をとる return; } setUpCameraOutputs(width, height); configureTransform(width, height); Activity activity = getActivity(); CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening.", e); } } //Closes the current link CameraDevice. private void closeCamera() { try { mCameraOpenCloseLock.acquire(); if (null != mCaptureSession) { mCaptureSession.close(); mCaptureSession = null; } if (null != mCameraDevice) { mCameraDevice.close(); mCameraDevice = null; } if (null != mImageReader) { mImageReader.close(); mImageReader = null; } } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera closing.", e); } finally { mCameraOpenCloseLock.release(); } } //バックグラウンドスレッドとそのハンドラを開始します。 private void startBackgroundThread() { mBackgroundThread = new HandlerThread("CameraBackground"); mBackgroundThread.start(); mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); } //バックグラウンドスレッドとそのハンドラを停止します。 private void stopBackgroundThread() { mBackgroundThread.quitSafely(); try { mBackgroundThread.join(); mBackgroundThread = null; mBackgroundHandler = null; } catch (InterruptedException e) { e.printStackTrace(); } } //カメラのプレビュー用に新しいCameraCaptureSessionを作成します。 private void createCameraPreviewSession() { try { SurfaceTexture texture = mTextureView.getSurfaceTexture(); assert texture != null; //デフォルトバッファのサイズは、必要なカメラプレビューのサイズに設定します。 texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); //これは、プレビューを開始するために必要な出力Surfaceです。 Surface surface = new Surface(texture); //Surfaceを出力するCaptureRequest.Builderをセットアップします。 mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); mPreviewRequestBuilder.addTarget(surface); //ここでは、カメラプレビュー用のCameraCaptureSessionを作成します。 mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { //カメラがすでに閉じていたら if (null == mCameraDevice) { return; } //セッションが準備完了すると、プレビューの表示が開始されます。 mCaptureSession = cameraCaptureSession; try { //カメラのプレビューでは、オートフォーカスが連続している必要があります。 mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); //必要に応じて自動的にフラッシュが有効になります。 setAutoFlash(mPreviewRequestBuilder); //最後に、カメラプレビューの表示を開始します。 mPreviewRequest = mPreviewRequestBuilder.build(); mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed( @NonNull CameraCaptureSession cameraCaptureSession) { showToast("Failed"); } }, null ); } catch (CameraAccessException e) { e.printStackTrace(); } } /**このメソッドは、カメラのプレビューサイズがsetUpCameraOutputsで決定され、 * `mTextureView`のサイズが固定された後に呼び出される必要があります。 * @param viewWidth The width of `mTextureView` * @param viewHeight The height of `mTextureView` */ private void configureTransform(int viewWidth, int viewHeight) { Activity activity = getActivity(); if (null == mTextureView || null == mPreviewSize || null == activity) { return; } int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); Matrix matrix = new Matrix(); RectF viewRect = new RectF(0, 0, viewWidth, viewHeight); RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth()); float centerX = viewRect.centerX(); float centerY = viewRect.centerY(); if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) { bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY()); matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL); float scale = Math.max( (float) viewHeight / mPreviewSize.getHeight(), (float) viewWidth / mPreviewSize.getWidth()); matrix.postScale(scale, scale, centerX, centerY); matrix.postRotate(90 * (rotation - 2), centerX, centerY); } else if (Surface.ROTATION_180 == rotation) { matrix.postRotate(180, centerX, centerY); } mTextureView.setTransform(matrix); } //静止画キャプチャを開始します。 private void takePicture() { lockFocus(); } //静止画キャプチャの最初のステップとしてフォーカスをロックします。 private void lockFocus() { try { // This is how to tell the camera to lock focus. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START); // Tell #mCaptureCallback to wait for the lock. mState = STATE_WAITING_LOCK; mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } //静止画像をキャプチャするためのプリキャプチャシーケンスを実行します。 //このメソッドは、#mCaptureCallback#lockFocus()から応答を受け取るときに呼び出される必要があります。 private void runPrecaptureSequence() { try { // This is how to tell the camera to trigger. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START); // Tell #mCaptureCallback to wait for the precapture sequence to be set. mState = STATE_WAITING_PRECAPTURE; mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } //静止画をキャプチャします。 //このメソッドは、両方の#lockFocus()からmCaptureCallbackの応答を受け取ったときに呼び出される必要があります。 private void captureStillPicture() { try { final Activity activity = getActivity(); if (null == activity || null == mCameraDevice) { return; } // This is the CaptureRequest.Builder that we use to take a picture. final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); captureBuilder.addTarget(mImageReader.getSurface()); // Use the same AE and AF modes as the preview. captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); setAutoFlash(captureBuilder); // Orientation int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation)); CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { showToast("Saved: " + mFile); Log.d(TAG, mFile.toString()); unlockFocus(); } }; mCaptureSession.stopRepeating(); mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null); } catch (CameraAccessException e) { e.printStackTrace(); } } /**指定された画面回転からJPEG方向を取得します。 * @param rotation The screen rotation. * @return The JPEG orientation (one of 0, 90, 270, and 360) */ private int getOrientation(int rotation) { // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X) // We have to take that into account and rotate JPEG properly. // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS. // For devices with orientation of 270, we need to rotate the JPEG 180 degrees. return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360; } //フォーカスを解除します。 このメソッドは、静止画像キャプチャシーケンスが終了したときに呼び出される必要があります。 private void unlockFocus() { try { // Reset the auto-focus trigger mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL); setAutoFlash(mPreviewRequestBuilder); mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler); // After this, the camera will go back to the normal state of preview. mState = STATE_PREVIEW; mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.picture: { takePicture(); break; } case R.id.info: { Activity activity = getActivity(); if (null != activity) { new AlertDialog.Builder(activity) .setMessage(R.string.intro_message) .setPositiveButton(android.R.string.ok, null) .show(); } break; } } } private void setAutoFlash(CaptureRequest.Builder requestBuilder) { if (mFlashSupported) { requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); } } //JPEG {@link Image}を指定されたファイルに保存します。 private static class ImageSaver implements Runnable { /** * The JPEG image */ private final Image mImage; /** * The file we save the image into. */ private final File mFile; public ImageSaver(Image image, File file) { mImage = image; mFile = file; } @Override public void run() { ByteBuffer buffer = mImage.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); FileOutputStream output = null; try { output = new FileOutputStream(mFile); output.write(bytes); } catch (IOException e) { e.printStackTrace(); } finally { mImage.close(); if (null != output) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } } } //それらの領域に基づいて2つのSizeを比較します。 static class CompareSizesByArea implements Comparator<Size> { @Override public int compare(Size lhs, Size rhs) { // We cast here to ensure the multiplications won't overflow return Long.signum((long) lhs.getWidth() * lhs.getHeight() - (long) rhs.getWidth() * rhs.getHeight()); } } //エラーメッセージダイアログを表示します。 public static class ErrorDialog extends DialogFragment { private static final String ARG_MESSAGE = "message"; public static ErrorDialog newInstance(String message) { ErrorDialog dialog = new ErrorDialog(); Bundle args = new Bundle(); args.putString(ARG_MESSAGE, message); dialog.setArguments(args); return dialog; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Activity activity = getActivity(); return new AlertDialog.Builder(activity) .setMessage(getArguments().getString(ARG_MESSAGE)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { activity.finish(); } }) .create(); } } //カメラの許可に関するOK/キャンセルの確認ダイアログを表示します。 public static class ConfirmationDialog extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Fragment parent = getParentFragment(); return new AlertDialog.Builder(getActivity()) .setMessage(R.string.request_permission) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { FragmentCompat.requestPermissions(parent, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Activity activity = parent.getActivity(); if (activity != null) { activity.finish(); } } }) .create(); } } }
// NOTE: think of the store as the base, AND the state as the status of the mission // (1) store() <<--- reducer, state // (2) reducer() <<--- state, action // (3) subscribe() // get the 'current' state // (4) dispatch( ) <<--- action // const reducer = (state, action) => { // if (action.type === 'ATTACK') { // return action.payload; // latent // } // if (action.type === 'GREENATTACK') { // return action.payload(); // real-time // } // return state; // } // // (1) // const store = Redux.createStore(reducer, "Store starts: at Peace"); // // (2) reducer was moved above store // // (3) // store.subscribe( () => console.log("Store is now: ", store.getState() )); // // NOT part of this app --- just check initial state // console.log(store.getState()); // // (4) // store.dispatch({ // type: 'ATTACK', // payload: "sending Iron Man" // latent // }) // store.dispatch({ // type: 'GREENATTACK', // payload: () => "sending Hulk" // real-time // }) // Redux Analogy below /* HOW TO CHANGE LAW: (Redux Analogy) -----------------' (1) people ---> (2) Protest ---> (3) "request change" LAW ---> (4) Ministers ---> (5) Parliament ---> (6) amend law "NEVER change it" ---> (7) Notify ---> (8) Newspaper `. | `------------------------<<<<-----------<<<<-----------<<<<-------- Passes updates -------------<<<<--------------<<<<--------------<<<<-------------------------' */ /* (1) Components ---> (2) Dispatch ---> (3) "request change" Action ---> (4) Reducers ---> (5) "Central" STORE ---> (6) Triggers ---> (7) Subscription ---> Passes updated states as props `. | `--------------------------------<<<<-----------<<<<-----------<<<<-------- Passes updates -------------<<<<--------------<<<<--------------<<<<---------------------------------' */
import {Component} from 'react' import Loader from 'react-loader-spinner' import CourseItemCard from '../CourseItemCard' import FailureView from '../FailureView' import './index.css' const apiStatusConstants = { initial: 'INITIAL', success: 'SUCCESS', failure: 'FAILURE', inProgress: 'IN_PROGRESS', } class Home extends Component { state = { coursesList: [], apiStatus: apiStatusConstants.initial, } componentDidMount() { this.getCoursesList() } getCoursesList = async () => { this.setState({apiStatus: apiStatusConstants.inProgress}) const apiUrl = `https://apis.ccbp.in/te/courses` const options = { method: 'GET', } const response = await fetch(apiUrl, options) if (response.ok) { const data = await response.json() const updatedData = data.courses.map(each => ({ id: each.id, name: each.name, logoUrl: each.logo_url, })) this.setState({ coursesList: updatedData, apiStatus: apiStatusConstants.success, }) } else { this.setState({apiStatus: apiStatusConstants.failure}) } } renderCoursesList = () => { const {coursesList} = this.state return ( <div className="courseContainer"> <h1 className="courses-heading">Courses</h1> <ul className="coursesList"> {coursesList.map(each => ( <CourseItemCard key={each.id} courseDetails={each} /> ))} </ul> </div> ) } retryButtonClicked = () => { this.getCoursesList() } renderFailureView = () => ( <FailureView retryButtonClicked={this.retryButtonClicked} /> ) renderLoadingView = () => ( <div data-testid="loader" className="courses-loader"> <Loader type="ThreeDots" color="#4656a1" height="50" width="50" /> </div> ) renderPageDetails = () => { const {apiStatus} = this.state switch (apiStatus) { case apiStatusConstants.success: return this.renderCoursesList() case apiStatusConstants.failure: return this.renderFailureView() case apiStatusConstants.inProgress: return this.renderLoadingView() default: return null } } render() { return <div className="Home-container">{this.renderPageDetails()}</div> } } export default Home
import { ApiProperty } from "@nestjs/swagger"; import { IsNumber, IsString, Length } from "class-validator"; export class CreateCommentDto { @ApiProperty({ example: 'good product', description: 'message' }) @IsString({ message: 'must be string' }) @Length(2, 16, { message: 'must be 2 - 16 symbols' }) readonly message: string; @ApiProperty({ example: '42', description: 'product id' }) @IsNumber({}, { message: 'must be number' }) readonly productId: number; }
# 【动态规划】221-最大正方形 动态规划,`dp(i, j)=min(dp(i − 1, j), dp(i − 1, j − 1), dp(i, j − 1)) + 1` ```java class Solution { public int maximalSquare(char[][] matrix) { int m = matrix.length, n = matrix[0].length; int[][] dp = new int[m][n]; int maxLength = 0; for (int i = 0; i < m; i++) { if ( matrix[i][0] == '1') { dp[i][0] = 1; maxLength = 1; } } for (int j = 0; j < n; j++) { if (matrix[0][j] == '1') { dp[0][j] = 1; maxLength = 1; } } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (matrix[i][j] == '0') dp[i][j] = 0; else { dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1; maxLength = Math.max(maxLength, dp[i][j]); } } } return maxLength * maxLength; } } ```
import {useEffect, useState} from "react"; import {Button, Paper, Stack, Table, TableBody, TableCell, TableContainer, TableHead, TableRow} from "@mui/material"; import Ticket from "./Ticket"; import TicketService from "../services/TicketService" import {useNavigate} from "react-router-dom"; import * as React from "react"; export default function Tickets(){ const [loading, setLoading] = useState(true); const [tickets, setTickets] = useState<any>(); const navigate = useNavigate() const roles = localStorage.getItem("roles") useEffect(() => { if(roles == null){ console.error("Access denied") navigate("/") } else if(!roles.includes("ROLE_USER")){ console.error("Access denied") navigate("/") } const fetchData = async () => { setLoading(true); try { const response = await TicketService.getTickets(localStorage.getItem("userId")); setTickets(response.data); } catch (error) { console.log(error); } setLoading(false); }; fetchData(); }, []); return( <TableContainer component={Paper}> <Stack direction="column"> <h1 style={{textAlign: 'center', alignSelf: 'center'}}>Tickets</h1> <Table sx={{ minWidth: 650 }} aria-label="simple table"> <TableHead> <TableRow> <TableCell align={"center"}>Id</TableCell> <TableCell align={"center"}>Where</TableCell> <TableCell align={"center"}>From</TableCell> <TableCell align={"center"}>Take Off Date</TableCell> <TableCell align={"center"}>Landing Date</TableCell> <TableCell align={"center"}>Price</TableCell> </TableRow> </TableHead> {!loading && ( <TableBody> {tickets.map((ticket:any) => ( <Ticket ticket={ticket} key={ticket.id}/> ))} </TableBody> )} </Table> <Button variant="contained" style={{width:200, alignSelf:'center'}} onClick={() => navigate("/userhome")}>Home</Button> </Stack> </TableContainer> ); };
// staff.hpp #ifndef STAFF_HPP #define STAFF_HPP #include <iostream> #include <fstream> #include <iomanip> #include <vector> #include <algorithm> #include <limits> #include <set> class Staff { private: int id; std::string name; int age; std::string gender; int height; int weight; int contact_number; std::vector<Staff> staffList; public: template <typename T> bool binarySearch(T target, int (Staff::*getAttribute)() const, const std::string& attributeName) const; void displayStaffDetails() const; void enterNewDetails(); int getID() const; const std::string& getName() const; int getAge() const; const std::string& getGender() const; int getHeight() const; int getWeight() const; int getContactNumber() const; Staff(); Staff(int _id, const std::string& _name, int _age, const std::string& _gender, int _height, int _weight, int _contact_number); void addNewStaff(const Staff& newStaff); void addStaff(); bool deleteStaff(int staffId); void displayAllStaffData(); bool editStaffDetails(int staffId); bool binarySearchByAge(int targetAge) const; bool binarySearchByHeight(int targetHeight) const; bool binarySearchByWeight(int targetWeight) const; bool saveToFile(const std::string & filename) const; }; #endif // STAFF_HPP
import { createCanvas, registerFont } from "canvas"; import path from "path"; import fs from "fs"; import sharp from "sharp"; import { Currency } from './enums'; export const createTextAndImageOverlay = async (currency: Currency) => { const apiKeyToken = process.env.ETHERSCAN; const url = `https://api.etherscan.io/api?module=stats&action=ethprice&apikey=${apiKeyToken}`; try { const response = await fetch(url); if (!response.ok) { throw new Error(`Error: ${response.status}`); } const data = await response.json(); const textCurrency = currency === Currency.USD ? data.result.ethusd : data.result.ethbtc; const canvas = createCanvas(256, 417); const ctx = canvas.getContext('2d'); // Asegúrate de que la ruta al fuente es correcta y accesible registerFont(path.resolve('./public/fonts/Montserrat-BoldItalic.ttf'), { family: 'Montserrat-BoldItalic', }); ctx.fillStyle = '#FFFFFF'; ctx.font = '48px Montserrat'; ctx.fillText(textCurrency, 10, 180); const textBuffer = canvas.toBuffer('image/png'); const ethImagePath = path.resolve("./public/ETH.png"); const ethImageBuffer = fs.readFileSync(ethImagePath); // Aquí deberías usar `textBuffer` en lugar de `texCurrency` const newImageBuffer = await sharp(ethImageBuffer) .composite([{ input: textBuffer }]) .toBuffer(); return { textCurrent: textCurrency, newImageBuffer }; // Cambio aquí para retornar `textCurrent` } catch (error) { console.error('Error:', error); const ethImagePath = path.resolve('./public/ETH.png'); // Aquí deberías considerar cómo manejar el error adecuadamente return { textCurrent: 'Error', newImageBuffer: fs.readFileSync(ethImagePath) }; } };
import { Image, ScrollView, StyleSheet, Text, View } from "react-native"; import { useNavigation, useRoute } from "@react-navigation/native"; import { MEALS } from "../data/dummy-data"; import MealDetails from "../components/MealDetails"; import Subtitle from "../components/MealDetail/Subtitle"; import List from "../components/MealDetail/List"; import { useCallback, useContext, useLayoutEffect } from "react"; import IconButton from "../components/IconButton"; import { FavoritesContext } from "../store/context/favorites-context"; import { useAppDispatch, useAppSelector } from "../store/redux/store"; import { addFavorite, removeFavorite } from "../store/redux/favorites"; function MealDetailScreen() { // const favoriteMealsCtx = useContext(FavoritesContext); const { ids } = useAppSelector((state) => state.favoriteMeals); const dispatch = useAppDispatch(); const route = useRoute(); const navigation = useNavigation(); const { id } = route.params; const meal = MEALS.find((meal) => meal.id === id); const { duration, complexity, affordability, title, imageUrl, ingredients, steps, } = meal; const isFavorite = ids.includes(id); const favoritePressHandler = useCallback((): void => { if (isFavorite) { // favoriteMealsCtx.removeFavorite(id); dispatch(removeFavorite({ id })); } else { // favoriteMealsCtx.addFavorite(id); dispatch(addFavorite({ id })); } }, [isFavorite, dispatch]); useLayoutEffect(() => { navigation.setOptions({ headerRight: () => ( <IconButton icon={isFavorite ? "star" : "star-outline"} color="white" onPress={favoritePressHandler} /> ), }); }, [navigation, isFavorite]); return ( <ScrollView style={styles.rootContainer}> <Image style={styles.image} source={{ uri: imageUrl }} /> <Text style={styles.title}>{title}</Text> <MealDetails duration={duration} complexity={complexity} affordability={affordability} textStyle={styles.detailText} /> <View style={styles.listOuterContainer}> <View style={styles.listContainer}> <Subtitle>Ingredients</Subtitle> <List data={ingredients} /> <Subtitle>Steps</Subtitle> <List data={steps} /> </View> </View> </ScrollView> ); } export default MealDetailScreen; const styles = StyleSheet.create({ rootContainer: { marginBottom: 32, }, image: { width: "100%", height: 350, }, title: { fontWeight: "bold", textAlign: "center", fontSize: 24, margin: 8, color: "white", }, detailText: { color: "white", }, listOuterContainer: { alignItems: "center", }, listContainer: { width: "80%", }, });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Responsive Grid</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <link rel="stylesheet" href="../css/test.css"> </head> <body> <div class="container"> <div class="ui-input-conatiner"> <h2>Word Count</h2> <label class="ui-form-input-container"> <textarea class="ui-form-input" id="word-count-input"></textarea> <span class="form-input-label">Message</span> </label> <p aria-live="polite"> <strong> <span id="word-count">0</span> words </strong> | <strong> <span id="character-count">0</span> characters </strong>. </p> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script> <script src="https://kit.fontawesome.com/a33686bef4.js" crossorigin="anonymous"></script> <script> var countTarget = document.querySelector("#word-count-input"); var wordCount = document.querySelector("#word-count"); var characterCount = document.querySelector("#character-count"); var count = function () { var characters = countTarget.value; var characterLength = characters.length; var words = characters.split(/[nrs]+/g).filter(function (word) { return word.length > 0; }); wordCount.innerHTML = words.length; characterCount.innerHTML = characterLength; }; count(); window.addEventListener( "input", function (event) { if (event.target.matches("#word-count-input")) { count(); } }, false ); </script> </body> </html>
import { PLOP_PROMPT_TYPE, PATH, PLOP_ACTION_TYPE, BREAK_LINE } from '../constants.js'; import { getAllDirsInDirectory } from '../utils.js'; export default (plop) => ({ description: 'Remove API', prompts: [ { type: PLOP_PROMPT_TYPE.LIST, name: 'serviceName', choices: () => { const allServices = getAllDirsInDirectory(PATH.SRC.SERVICES); return allServices; }, message: 'Service name?' } ], actions: ({ serviceName }) => { const devEnvFilePath = PATH.DEVELOPMENT_ENV; const stagingEnvFilePath = PATH.STAGING_ENV; const prodEnvFilePath = PATH.PRODUCTION_ENV; const objEnvFilePath = PATH.SRC.ENV; const envVariablePattern = plop.renderString( '(VITE_{{constantCase serviceName}}_SERVICE)([\\S\\s]*)(# {{constantCase serviceName}}_SERVICE)' + BREAK_LINE, { serviceName } ); const objEnvFilePattern = plop.renderString('{{camelCase serviceName}}: {' + BREAK_LINE + " baseUrl: import.meta.env.VITE_{{constantCase serviceName}}_SERVICE ?? ''" + BREAK_LINE + '}', { serviceName }) return [ // { // type: PLOP_ACTION_TYPE.REMOVE, // path: `${PATH.SRC.SERVICES}/${serviceName}` // }, { type: PLOP_ACTION_TYPE.MODIFY, path: devEnvFilePath, pattern: new RegExp(envVariablePattern, 'g'), template: '' }, { type: PLOP_ACTION_TYPE.MODIFY, path: stagingEnvFilePath, pattern: new RegExp(envVariablePattern, 'g'), template: '' }, { type: PLOP_ACTION_TYPE.MODIFY, path: prodEnvFilePath, pattern: new RegExp(envVariablePattern, 'g'), template: '' }, { type: PLOP_ACTION_TYPE.MODIFY, path: objEnvFilePath, pattern: new RegExp('(service: {)', 'g'), template: "$1{{camelCase serviceName}}: { baseUrl: import.meta.env.VITE_{{constantCase serviceName}}_SERVICE ?? '' },", skip: () => skipAction({ when: !isUserWantCreateNewService, path: objEnvFilePath, description: 'Add new variable for new service' }) }, { type: PLOP_ACTION_TYPE.PRETTIER } ]; } });
package com.example.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import com.example.Client.entities.Client; import com.example.repositories.ClientRepository; @Service public class ClientServiceImpl implements ClientService{ @Autowired private ClientRepository clientRepository; @Override public List<Client> findAll() { return clientRepository.findAll(); } @Override public Client findById(Long id) throws Exception { return clientRepository.findById(id).orElseThrow(()->new Exception("Invalid Client ID")); } @Override public void addClient(Client client) { clientRepository.save(client); } @Override public void delete(Long id) throws Exception { Client deletedClient = clientRepository.findById(id).orElseThrow(()->new Exception("Invalid Id")); clientRepository.delete(deletedClient); } @Override public void update(Client client, Long id) throws Exception { Client currentClient = clientRepository.findById(id).orElseThrow(()->new Exception("Invalid Client ID")); currentClient.setAge(client.getAge()); currentClient.setName(client.getName()); clientRepository.save(currentClient); } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Ajax테스트</title> </head> <body> <h2 onclick="getImage();">이 행을 클릭해요. Ajax로 이미지를 요청하고 출력해요....</h2> <script> let imgname = 1; function getImage() { imgname = imgname == 10 ? 1 : imgname+1; const xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = function(e) { if (this.status == 200) { const blob = e.target.response // load 이벤트 이므로 e.target을 써도됨. e.target은 load 이벤트가 발생한 대상 객체 (httpRequest 객체) // blob -> 이진 데이터를 다룸 const img = document.createElement('img'); // 이 이미지는 서버로부터 받아온 이미지에 대한 이진 컨텐츠를 가지고 document에 출력해야하므로 img 태그를 하나 만듦 // img 태그에 대한 DOM객체를 직접 만듦 img.width=100; img.height=100; img.src = URL.createObjectURL(blob); // 응답 내용을 가지고 가상 url을 만듦 (컨텐츠를 가지고 url을 만듦) document.body.appendChild(img); // 컨텐츠를 가지고 body 태그에 append } }; xhr.open('GET', `/edu/images/${imgname}.jpg`, true); xhr.send(); // 네트워크 창의 xhr -> XMLHttpRequest를 통해 요청한 것 } </script> </body> </html>
--- title: Updated 2024 Approved VLC Trimming on Mac Made Simple Preserve Video Integrity and Quality date: 2024-04-29T13:32:52.026Z updated: 2024-04-30T13:32:52.026Z tags: - video editing software - video editing categories: - ai - video description: This Article Describes Updated 2024 Approved VLC Trimming on Mac Made Simple Preserve Video Integrity and Quality excerpt: This Article Describes Updated 2024 Approved VLC Trimming on Mac Made Simple Preserve Video Integrity and Quality keywords: vlc video cutter for mac preserve quality while trimming,vlc trimming on mac made simple preserve video integrity and quality,mac vlc trimming made easy preserve video quality with these tips,trim vlc videos like a pro on mac no quality degradation guaranteed,the ultimate guide to rapid video trimming on mac updated 2023,the ultimate guide to trimming vlc videos on mac without compromising quality,mac vlc trimming made easy preserve video quality thumbnail: https://www.lifewire.com/thmb/TKoUz7zi8lw5cyOA93bOwDLfNYs=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/the_room-56cc7f225f9b5879cc590941.png --- ## VLC Trimming on Mac Made Simple: Preserve Video Integrity and Quality # VLC Trimmer Mac: Best Way to Trim VLC Without Losing Quality ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) ##### Ollie Mattison Oct 26, 2023• Proven solutions _Is there a way to trim VLC without losing quality?_ Of course! Trimming VLC videos without losing quality can be a bit frustrating sometimes. Fortunately, there are applications available that can help you edit videos without losing quality. Wondershare Filmora is one such software that can be downloaded for free. You cannot miss it. In this article, we will introduce why trimming VLC videos will result in loss of quality, then recommend 3 video editors trim high-quality video without lowering the quality. * [Section 1\. Why trimming VLC videos will result in loss of quality](#why-trim-vlc-loss-quality) * [Section 2\. Video editor to trim VLC videos without loss of quality](#software-trim-vlc-without-loss-quality) ## Section 1. Why trimming VLC videos will result in loss of quality? To understand quality loss, you first need to understand codecs, containers, and video re-encoding. This might get a little technical, so keep sipping that coffee! #### 1\. Codec Every video has a codec and a container associated with it. A video codec is an order in which the video data is organized for playback, editing, and other functions. There are lots of different types of codecs, and each of them has different functions and advantages. #### 2\. Container A container is responsible for holding video data and other information in a single file. Containers have file extensions like .mp4, .avi, .mov, etc. Some containers can only hold videos in one specific codec, while others can hold multiple codecs. Containers are also responsible for telling media players whether a video has audio or not. Why are codecs and containers so important? Imagine if you watched a 1080p video (codec) on an old TV (container) – it would work, but would you really be interested in seeing it? Probably not. A mismatch between containers and codecs can result in poor quality, which is why you must shoot your videos in the right format and play them on the right platform. #### 3\. Video compression and re-encoding You might be wondering at what point of the whole process does the video loses quality. When you capture the video, it is of the highest quality. As soon as you compress it to share it online, some quality loss occurs, even if you convert it into a high-quality video. When you export a video that’s already been exported, you re-encode the video. **Re-encoding a VLC video can result in even more quality loss.** The truth is, you can’t reduce the video size without losing quality no matter what you do. If you’re editing a video shot in 4K, but you export it in 720p, the video will become compressed, and the original data of the video won’t get transferred to the new video, resulting in a pixelated block of mess. When you make changes to a video with a **video trimmer app**, you’re changing the data structure that holds information about the video. Why do VLC videos that are small in size appear pixelated and blurry? It’s because they don’t have as much information as videos with larger sizes. **_You may be interested in:_** [VLC media player review and alternatives](https://tools.techidaily.com/wondershare/filmora/download/) ## Section 2. The software you can use to trim VLC videos without loss of quality Fortunately, there are plenty of video editing programs available online that you can use to trim videos without losing quality. Here are three of the best video cutters: 1. [Wondershare Filmora](#way1) 2. [LosslessCut](#way2) 3. [TunesKit Video Cutter](#way3) **All three of these video trimmers can be downloaded for free.** ### 1. Trimming VLC with [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is a powerful [video editor for Mac](https://tools.techidaily.com/wondershare/filmora/download/) and Windows. It is a good choice to trim VLC video. You can cut and combine videos without losing the quality. Filmora supports pretty much every video format there is, so you don't have to worry about codecs and containers. If you’re working with a long video, you can take advantage of Filmora unique feature called “Scene Detection.” With this feature, the software will automatically detect scene changes in the VLC video and separate them, making it easy for you to trim it into multiple clips. If you want to trim your video manually, you can just drag the trimming sliders according to how you want to cut the video. #### More features of Filmora * **Effect Plugins:** Cooperate with New Blue & Boris, Filmora allows you to access and use all the fantastic effects from these two outstanding effects producers. * **Stock Media:** No need to open Chrome or other browser to search for royalty-free images/footages/gifs any more. You can find Giphy, Pixbay, Unsplash within Filmora. * **Speed Ramping**: Feel free to speed up or slow down a certain video clip. * **Green Screen:** Get more creative by using Green Screen to create your video. How to trim VLC video on Mac with Filmora step by step? The following video will introduce you to the detailed steps: [![Download Filmora9 Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/images2022/download-mac-store.png) ](https://apps.apple.com/app/apple-store/id1516822341?pt=169436&ct=pc-article-top50&mt=8) * Pros: With Filmora, you can easily edit VLC video lossless, it is free to download. * Cons: If you are not a member, the output video may have a watermark. ### 2. Trimming VLC through LosslessCut LosslessCut is an open-source video cutter that runs on Windows, Linux, and Mac. Like Filmora, this software also allows you to cut videos without re-encoding, so there is no loss of quality. It is user-friendlier than Filmora – all you have to do is drag your video to the software and then you can start trimming it by using the Arrow symbols. ![lossescut for trimming VLC video](https://images.wondershare.com/filmora/Mac-articles/lossescut.jpg) One unique feature of LosslessCut is that it lets you take JPEG screenshots of the video. It also has a portable version that doesn’t require any installation and can be started directly from a USB. * Pros: LosslessCut works best with mobile videos or action cams like GoPro. * Cons: It supports a whole range of video formats, but don’t expect to edit 4K videos using this software. It’s simple and easy to use for a reason. ### 3. Trimming VLC via [TunesKit Video Converter](https://www.tuneskit.com/video-cutter-for-win.html) TunesKit is a simple video trimmer software that’s available on both Mac and Windows. Unlike Filmora and LosslessCut, TunesKit supports a very limited number of video formats. It is mainly an MP4 video cutter. It works at a much faster speed and there is no loss of quality. ![tuneskit to trim vlc video without lossing quality](https://images.wondershare.com/filmora/Mac-articles/tuneskit.jpg) * Pros: The interface, while simpler than Filmora’s, can seem a bit confusing sometimes. TunesKit also has a video editor, which lets you add effects to different segments of the trimmed video, a feature that you probably won’t be using very often. To trim VLC videos in MP4 without re-encoding, you simply have to drag the slider that appears when you import your video. * Cons: However, its functions may not be as rich as Filmora. #### Conclusion If you trim your VLC video, it will result in data loss, which will lead to a reduction in quality. Losing quality is inevitable with most video editors, which is why you should [Download Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) as it's easy to use and has the best and most useful features. Filmora supports many popular formats like MP4, AVI, MOV, MKV, and also different screen resolutions so no matter what the format of your VLC video is, you can easily divide it by scenes using the Scene Detection feature and quickly turn those scenes into clips. **_You may like:_**[What video formats does Filmora support to import and export>>>](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Oct 26, 2023• Proven solutions _Is there a way to trim VLC without losing quality?_ Of course! Trimming VLC videos without losing quality can be a bit frustrating sometimes. Fortunately, there are applications available that can help you edit videos without losing quality. Wondershare Filmora is one such software that can be downloaded for free. You cannot miss it. In this article, we will introduce why trimming VLC videos will result in loss of quality, then recommend 3 video editors trim high-quality video without lowering the quality. * [Section 1\. Why trimming VLC videos will result in loss of quality](#why-trim-vlc-loss-quality) * [Section 2\. Video editor to trim VLC videos without loss of quality](#software-trim-vlc-without-loss-quality) ## Section 1. Why trimming VLC videos will result in loss of quality? To understand quality loss, you first need to understand codecs, containers, and video re-encoding. This might get a little technical, so keep sipping that coffee! #### 1\. Codec Every video has a codec and a container associated with it. A video codec is an order in which the video data is organized for playback, editing, and other functions. There are lots of different types of codecs, and each of them has different functions and advantages. #### 2\. Container A container is responsible for holding video data and other information in a single file. Containers have file extensions like .mp4, .avi, .mov, etc. Some containers can only hold videos in one specific codec, while others can hold multiple codecs. Containers are also responsible for telling media players whether a video has audio or not. Why are codecs and containers so important? Imagine if you watched a 1080p video (codec) on an old TV (container) – it would work, but would you really be interested in seeing it? Probably not. A mismatch between containers and codecs can result in poor quality, which is why you must shoot your videos in the right format and play them on the right platform. #### 3\. Video compression and re-encoding You might be wondering at what point of the whole process does the video loses quality. When you capture the video, it is of the highest quality. As soon as you compress it to share it online, some quality loss occurs, even if you convert it into a high-quality video. When you export a video that’s already been exported, you re-encode the video. **Re-encoding a VLC video can result in even more quality loss.** The truth is, you can’t reduce the video size without losing quality no matter what you do. If you’re editing a video shot in 4K, but you export it in 720p, the video will become compressed, and the original data of the video won’t get transferred to the new video, resulting in a pixelated block of mess. When you make changes to a video with a **video trimmer app**, you’re changing the data structure that holds information about the video. Why do VLC videos that are small in size appear pixelated and blurry? It’s because they don’t have as much information as videos with larger sizes. **_You may be interested in:_** [VLC media player review and alternatives](https://tools.techidaily.com/wondershare/filmora/download/) ## Section 2. The software you can use to trim VLC videos without loss of quality Fortunately, there are plenty of video editing programs available online that you can use to trim videos without losing quality. Here are three of the best video cutters: 1. [Wondershare Filmora](#way1) 2. [LosslessCut](#way2) 3. [TunesKit Video Cutter](#way3) **All three of these video trimmers can be downloaded for free.** ### 1. Trimming VLC with [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is a powerful [video editor for Mac](https://tools.techidaily.com/wondershare/filmora/download/) and Windows. It is a good choice to trim VLC video. You can cut and combine videos without losing the quality. Filmora supports pretty much every video format there is, so you don't have to worry about codecs and containers. If you’re working with a long video, you can take advantage of Filmora unique feature called “Scene Detection.” With this feature, the software will automatically detect scene changes in the VLC video and separate them, making it easy for you to trim it into multiple clips. If you want to trim your video manually, you can just drag the trimming sliders according to how you want to cut the video. #### More features of Filmora * **Effect Plugins:** Cooperate with New Blue & Boris, Filmora allows you to access and use all the fantastic effects from these two outstanding effects producers. * **Stock Media:** No need to open Chrome or other browser to search for royalty-free images/footages/gifs any more. You can find Giphy, Pixbay, Unsplash within Filmora. * **Speed Ramping**: Feel free to speed up or slow down a certain video clip. * **Green Screen:** Get more creative by using Green Screen to create your video. How to trim VLC video on Mac with Filmora step by step? The following video will introduce you to the detailed steps: [![Download Filmora9 Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/images2022/download-mac-store.png) ](https://apps.apple.com/app/apple-store/id1516822341?pt=169436&ct=pc-article-top50&mt=8) * Pros: With Filmora, you can easily edit VLC video lossless, it is free to download. * Cons: If you are not a member, the output video may have a watermark. ### 2. Trimming VLC through LosslessCut LosslessCut is an open-source video cutter that runs on Windows, Linux, and Mac. Like Filmora, this software also allows you to cut videos without re-encoding, so there is no loss of quality. It is user-friendlier than Filmora – all you have to do is drag your video to the software and then you can start trimming it by using the Arrow symbols. ![lossescut for trimming VLC video](https://images.wondershare.com/filmora/Mac-articles/lossescut.jpg) One unique feature of LosslessCut is that it lets you take JPEG screenshots of the video. It also has a portable version that doesn’t require any installation and can be started directly from a USB. * Pros: LosslessCut works best with mobile videos or action cams like GoPro. * Cons: It supports a whole range of video formats, but don’t expect to edit 4K videos using this software. It’s simple and easy to use for a reason. ### 3. Trimming VLC via [TunesKit Video Converter](https://www.tuneskit.com/video-cutter-for-win.html) TunesKit is a simple video trimmer software that’s available on both Mac and Windows. Unlike Filmora and LosslessCut, TunesKit supports a very limited number of video formats. It is mainly an MP4 video cutter. It works at a much faster speed and there is no loss of quality. ![tuneskit to trim vlc video without lossing quality](https://images.wondershare.com/filmora/Mac-articles/tuneskit.jpg) * Pros: The interface, while simpler than Filmora’s, can seem a bit confusing sometimes. TunesKit also has a video editor, which lets you add effects to different segments of the trimmed video, a feature that you probably won’t be using very often. To trim VLC videos in MP4 without re-encoding, you simply have to drag the slider that appears when you import your video. * Cons: However, its functions may not be as rich as Filmora. #### Conclusion If you trim your VLC video, it will result in data loss, which will lead to a reduction in quality. Losing quality is inevitable with most video editors, which is why you should [Download Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) as it's easy to use and has the best and most useful features. Filmora supports many popular formats like MP4, AVI, MOV, MKV, and also different screen resolutions so no matter what the format of your VLC video is, you can easily divide it by scenes using the Scene Detection feature and quickly turn those scenes into clips. **_You may like:_**[What video formats does Filmora support to import and export>>>](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Oct 26, 2023• Proven solutions _Is there a way to trim VLC without losing quality?_ Of course! Trimming VLC videos without losing quality can be a bit frustrating sometimes. Fortunately, there are applications available that can help you edit videos without losing quality. Wondershare Filmora is one such software that can be downloaded for free. You cannot miss it. In this article, we will introduce why trimming VLC videos will result in loss of quality, then recommend 3 video editors trim high-quality video without lowering the quality. * [Section 1\. Why trimming VLC videos will result in loss of quality](#why-trim-vlc-loss-quality) * [Section 2\. Video editor to trim VLC videos without loss of quality](#software-trim-vlc-without-loss-quality) ## Section 1. Why trimming VLC videos will result in loss of quality? To understand quality loss, you first need to understand codecs, containers, and video re-encoding. This might get a little technical, so keep sipping that coffee! #### 1\. Codec Every video has a codec and a container associated with it. A video codec is an order in which the video data is organized for playback, editing, and other functions. There are lots of different types of codecs, and each of them has different functions and advantages. #### 2\. Container A container is responsible for holding video data and other information in a single file. Containers have file extensions like .mp4, .avi, .mov, etc. Some containers can only hold videos in one specific codec, while others can hold multiple codecs. Containers are also responsible for telling media players whether a video has audio or not. Why are codecs and containers so important? Imagine if you watched a 1080p video (codec) on an old TV (container) – it would work, but would you really be interested in seeing it? Probably not. A mismatch between containers and codecs can result in poor quality, which is why you must shoot your videos in the right format and play them on the right platform. #### 3\. Video compression and re-encoding You might be wondering at what point of the whole process does the video loses quality. When you capture the video, it is of the highest quality. As soon as you compress it to share it online, some quality loss occurs, even if you convert it into a high-quality video. When you export a video that’s already been exported, you re-encode the video. **Re-encoding a VLC video can result in even more quality loss.** The truth is, you can’t reduce the video size without losing quality no matter what you do. If you’re editing a video shot in 4K, but you export it in 720p, the video will become compressed, and the original data of the video won’t get transferred to the new video, resulting in a pixelated block of mess. When you make changes to a video with a **video trimmer app**, you’re changing the data structure that holds information about the video. Why do VLC videos that are small in size appear pixelated and blurry? It’s because they don’t have as much information as videos with larger sizes. **_You may be interested in:_** [VLC media player review and alternatives](https://tools.techidaily.com/wondershare/filmora/download/) ## Section 2. The software you can use to trim VLC videos without loss of quality Fortunately, there are plenty of video editing programs available online that you can use to trim videos without losing quality. Here are three of the best video cutters: 1. [Wondershare Filmora](#way1) 2. [LosslessCut](#way2) 3. [TunesKit Video Cutter](#way3) **All three of these video trimmers can be downloaded for free.** ### 1. Trimming VLC with [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is a powerful [video editor for Mac](https://tools.techidaily.com/wondershare/filmora/download/) and Windows. It is a good choice to trim VLC video. You can cut and combine videos without losing the quality. Filmora supports pretty much every video format there is, so you don't have to worry about codecs and containers. If you’re working with a long video, you can take advantage of Filmora unique feature called “Scene Detection.” With this feature, the software will automatically detect scene changes in the VLC video and separate them, making it easy for you to trim it into multiple clips. If you want to trim your video manually, you can just drag the trimming sliders according to how you want to cut the video. #### More features of Filmora * **Effect Plugins:** Cooperate with New Blue & Boris, Filmora allows you to access and use all the fantastic effects from these two outstanding effects producers. * **Stock Media:** No need to open Chrome or other browser to search for royalty-free images/footages/gifs any more. You can find Giphy, Pixbay, Unsplash within Filmora. * **Speed Ramping**: Feel free to speed up or slow down a certain video clip. * **Green Screen:** Get more creative by using Green Screen to create your video. How to trim VLC video on Mac with Filmora step by step? The following video will introduce you to the detailed steps: [![Download Filmora9 Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/images2022/download-mac-store.png) ](https://apps.apple.com/app/apple-store/id1516822341?pt=169436&ct=pc-article-top50&mt=8) * Pros: With Filmora, you can easily edit VLC video lossless, it is free to download. * Cons: If you are not a member, the output video may have a watermark. ### 2. Trimming VLC through LosslessCut LosslessCut is an open-source video cutter that runs on Windows, Linux, and Mac. Like Filmora, this software also allows you to cut videos without re-encoding, so there is no loss of quality. It is user-friendlier than Filmora – all you have to do is drag your video to the software and then you can start trimming it by using the Arrow symbols. ![lossescut for trimming VLC video](https://images.wondershare.com/filmora/Mac-articles/lossescut.jpg) One unique feature of LosslessCut is that it lets you take JPEG screenshots of the video. It also has a portable version that doesn’t require any installation and can be started directly from a USB. * Pros: LosslessCut works best with mobile videos or action cams like GoPro. * Cons: It supports a whole range of video formats, but don’t expect to edit 4K videos using this software. It’s simple and easy to use for a reason. ### 3. Trimming VLC via [TunesKit Video Converter](https://www.tuneskit.com/video-cutter-for-win.html) TunesKit is a simple video trimmer software that’s available on both Mac and Windows. Unlike Filmora and LosslessCut, TunesKit supports a very limited number of video formats. It is mainly an MP4 video cutter. It works at a much faster speed and there is no loss of quality. ![tuneskit to trim vlc video without lossing quality](https://images.wondershare.com/filmora/Mac-articles/tuneskit.jpg) * Pros: The interface, while simpler than Filmora’s, can seem a bit confusing sometimes. TunesKit also has a video editor, which lets you add effects to different segments of the trimmed video, a feature that you probably won’t be using very often. To trim VLC videos in MP4 without re-encoding, you simply have to drag the slider that appears when you import your video. * Cons: However, its functions may not be as rich as Filmora. #### Conclusion If you trim your VLC video, it will result in data loss, which will lead to a reduction in quality. Losing quality is inevitable with most video editors, which is why you should [Download Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) as it's easy to use and has the best and most useful features. Filmora supports many popular formats like MP4, AVI, MOV, MKV, and also different screen resolutions so no matter what the format of your VLC video is, you can easily divide it by scenes using the Scene Detection feature and quickly turn those scenes into clips. **_You may like:_**[What video formats does Filmora support to import and export>>>](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Oct 26, 2023• Proven solutions _Is there a way to trim VLC without losing quality?_ Of course! Trimming VLC videos without losing quality can be a bit frustrating sometimes. Fortunately, there are applications available that can help you edit videos without losing quality. Wondershare Filmora is one such software that can be downloaded for free. You cannot miss it. In this article, we will introduce why trimming VLC videos will result in loss of quality, then recommend 3 video editors trim high-quality video without lowering the quality. * [Section 1\. Why trimming VLC videos will result in loss of quality](#why-trim-vlc-loss-quality) * [Section 2\. Video editor to trim VLC videos without loss of quality](#software-trim-vlc-without-loss-quality) ## Section 1. Why trimming VLC videos will result in loss of quality? To understand quality loss, you first need to understand codecs, containers, and video re-encoding. This might get a little technical, so keep sipping that coffee! #### 1\. Codec Every video has a codec and a container associated with it. A video codec is an order in which the video data is organized for playback, editing, and other functions. There are lots of different types of codecs, and each of them has different functions and advantages. #### 2\. Container A container is responsible for holding video data and other information in a single file. Containers have file extensions like .mp4, .avi, .mov, etc. Some containers can only hold videos in one specific codec, while others can hold multiple codecs. Containers are also responsible for telling media players whether a video has audio or not. Why are codecs and containers so important? Imagine if you watched a 1080p video (codec) on an old TV (container) – it would work, but would you really be interested in seeing it? Probably not. A mismatch between containers and codecs can result in poor quality, which is why you must shoot your videos in the right format and play them on the right platform. #### 3\. Video compression and re-encoding You might be wondering at what point of the whole process does the video loses quality. When you capture the video, it is of the highest quality. As soon as you compress it to share it online, some quality loss occurs, even if you convert it into a high-quality video. When you export a video that’s already been exported, you re-encode the video. **Re-encoding a VLC video can result in even more quality loss.** The truth is, you can’t reduce the video size without losing quality no matter what you do. If you’re editing a video shot in 4K, but you export it in 720p, the video will become compressed, and the original data of the video won’t get transferred to the new video, resulting in a pixelated block of mess. When you make changes to a video with a **video trimmer app**, you’re changing the data structure that holds information about the video. Why do VLC videos that are small in size appear pixelated and blurry? It’s because they don’t have as much information as videos with larger sizes. **_You may be interested in:_** [VLC media player review and alternatives](https://tools.techidaily.com/wondershare/filmora/download/) ## Section 2. The software you can use to trim VLC videos without loss of quality Fortunately, there are plenty of video editing programs available online that you can use to trim videos without losing quality. Here are three of the best video cutters: 1. [Wondershare Filmora](#way1) 2. [LosslessCut](#way2) 3. [TunesKit Video Cutter](#way3) **All three of these video trimmers can be downloaded for free.** ### 1. Trimming VLC with [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is a powerful [video editor for Mac](https://tools.techidaily.com/wondershare/filmora/download/) and Windows. It is a good choice to trim VLC video. You can cut and combine videos without losing the quality. Filmora supports pretty much every video format there is, so you don't have to worry about codecs and containers. If you’re working with a long video, you can take advantage of Filmora unique feature called “Scene Detection.” With this feature, the software will automatically detect scene changes in the VLC video and separate them, making it easy for you to trim it into multiple clips. If you want to trim your video manually, you can just drag the trimming sliders according to how you want to cut the video. #### More features of Filmora * **Effect Plugins:** Cooperate with New Blue & Boris, Filmora allows you to access and use all the fantastic effects from these two outstanding effects producers. * **Stock Media:** No need to open Chrome or other browser to search for royalty-free images/footages/gifs any more. You can find Giphy, Pixbay, Unsplash within Filmora. * **Speed Ramping**: Feel free to speed up or slow down a certain video clip. * **Green Screen:** Get more creative by using Green Screen to create your video. How to trim VLC video on Mac with Filmora step by step? The following video will introduce you to the detailed steps: [![Download Filmora9 Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/images2022/download-mac-store.png) ](https://apps.apple.com/app/apple-store/id1516822341?pt=169436&ct=pc-article-top50&mt=8) * Pros: With Filmora, you can easily edit VLC video lossless, it is free to download. * Cons: If you are not a member, the output video may have a watermark. ### 2. Trimming VLC through LosslessCut LosslessCut is an open-source video cutter that runs on Windows, Linux, and Mac. Like Filmora, this software also allows you to cut videos without re-encoding, so there is no loss of quality. It is user-friendlier than Filmora – all you have to do is drag your video to the software and then you can start trimming it by using the Arrow symbols. ![lossescut for trimming VLC video](https://images.wondershare.com/filmora/Mac-articles/lossescut.jpg) One unique feature of LosslessCut is that it lets you take JPEG screenshots of the video. It also has a portable version that doesn’t require any installation and can be started directly from a USB. * Pros: LosslessCut works best with mobile videos or action cams like GoPro. * Cons: It supports a whole range of video formats, but don’t expect to edit 4K videos using this software. It’s simple and easy to use for a reason. ### 3. Trimming VLC via [TunesKit Video Converter](https://www.tuneskit.com/video-cutter-for-win.html) TunesKit is a simple video trimmer software that’s available on both Mac and Windows. Unlike Filmora and LosslessCut, TunesKit supports a very limited number of video formats. It is mainly an MP4 video cutter. It works at a much faster speed and there is no loss of quality. ![tuneskit to trim vlc video without lossing quality](https://images.wondershare.com/filmora/Mac-articles/tuneskit.jpg) * Pros: The interface, while simpler than Filmora’s, can seem a bit confusing sometimes. TunesKit also has a video editor, which lets you add effects to different segments of the trimmed video, a feature that you probably won’t be using very often. To trim VLC videos in MP4 without re-encoding, you simply have to drag the slider that appears when you import your video. * Cons: However, its functions may not be as rich as Filmora. #### Conclusion If you trim your VLC video, it will result in data loss, which will lead to a reduction in quality. Losing quality is inevitable with most video editors, which is why you should [Download Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) as it's easy to use and has the best and most useful features. Filmora supports many popular formats like MP4, AVI, MOV, MKV, and also different screen resolutions so no matter what the format of your VLC video is, you can easily divide it by scenes using the Scene Detection feature and quickly turn those scenes into clips. **_You may like:_**[What video formats does Filmora support to import and export>>>](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Unlimited Fake Faces at Your Fingertips: Free Online Generators While signing up for a social media account, you may not want to use your real photograph as your profile picture, but at the same time, you might not find it ethical to use someone else’s image either. This is where a **face generation portal** comes into play. You can easily **create a virtual face** that looks almost like you and sometimes even better with a face generator. Similarly, run a business where you want to publish your clients’ reviews without showing their real photos as they might not like the idea. You can use a good face generator online tool to create a virtual face that resembles their look and post it along with their feedback. Considering the above scenarios and many others that may come up over time, the following list some of the best free online face generators to create fake faces. ### Watch Video! Best Free Online Face Generators ## Best Free Online Face Generators to Get Virtual Faces in 2022 ### 1\. Generated Photos: Faces **Website**: <https://generated.photos/faces> This online portal enables you to create virtual faces by specifying the physical attributes of a character, such as gender, age, hair color, eye color, and much more. You can be as creative as you want to generate a face that appears somewhat like you with the available options. Once a look is generated, you can download and use it as needed. The steps that are given below explain how you can use Generated Photos’ Faces section to create and download a virtual face: * Launch your favorite web browser and go to the URL given above, and then you will see all free AI-generated photos on this website. ![generated photos layout](https://images.wondershare.com/filmora/article-images/generated-photos-layout.jpg) * Use the filters given in the left pane to define your character's physical attributes and click **Apply** from the bottom to get the results. You can customize the face from its head post, gender, age, hair, eye, and emotion aspects. * Click your preferred character from the AI-generated faces, and then click **Download** from the page that opens next. Choose your preferred method to sign up, and then sign in to download the virtual face to your PC. ### 2\. Generated Photos: Anonymizer **Website**: <https://generated.photos/anonymizer> Anonymizer is another section from the Generated Photos portal that allows you to upload your image. Then it uses AI technology to generate similar virtual faces that you can download and use wherever needed. However, sometimes the pictures that the website creates may not resemble your face as closely as you expect them to be, but that’s OK. Isn’t it? The main idea is to keep your privacy intact, and that’s what Generated Photos: Anonymizer does. You can learn how to use this section by following the instructions given below: * Use the URL given above to get to the Anonymizer’s web page and then click **Upload photo;** * Select and upload your photo from your PC to the portal and wait while Anonymizer uses AI to generate similar faces. * Click the photo that you want to use, and when the next page opens up, click Sign up or sign in to download the photo and use it wherever needed ![recreate face with anonymizer online face generators](https://images.wondershare.com/filmora/article-images/recreate-face-with-anonymizer-online-face-generators.jpg) ### 3\. Generated Photos Face Generator Website: [](https://generated.photos/face-generator)<https://generated.photos/face-generator> This online face generator from Generated Photos allows you to create a unique realt-time face from scratch in one click. And if you don’t like the face generated, you can change the parameters such as gender, skin tone, hair, eye and head pose. Generated Photos Face Generator tool is a good choice for people who don’t want to upload any photos online, and need to customize the face at maximum. Below is a brief tutorial about how to generate a face with it step by step: * Go to the website give above and then click the **Generate faces** * Select the parameters accordingly based on your needs. You can generate the same face young or old with different emotions. ![generated photos face generator online](https://images.wondershare.com/filmora/article-images/generated-photos-face-generator-online.jpg) You can then download the generated photo by signing up or logging in, but you need to pay to remove the watermark. ### 4\. Massless **Website:** [https://massless.io/tool/face-maker-ai](https://massless.io/tool/face-maker-ai/) Massless allows you to use its tools to sketch a portrait, and then it uses AI technology to generate a virtual face out of your drawing. However, because you can’t always be precise while sketching with the mouse, it would be good to have access to a digital drawing pad to create the faces with a pen. With Massless, you can explore your creativity to the full and draw beautiful faces to use them as your avatar. You can follow the procedure given below to use Massless to draw virtual faces: * Open a web browser, and visit the URL given above. Click any icons from the toolbox at the top (E.g., **Nose**). * Draw a shape on its corresponding face area on the left (E.g., **Nose**), and wait while the portal automatically updates the photo on the right. * Repeat the process to sketch other parts of the face, and click the More icon (with three vertical dots) from the top-right corner. * Click **Download images** from the page that opens next to download the photo to your PC and use it wherever needed. ![massless online face generator](https://images.wondershare.com/filmora/article-images/massless-online-face-generator.jpg) ### 5\. This Person Does Not Exist **Website:** <https://thispersondoesnotexist.com/> This free online virtual face generator is probably the easiest and quickest. As you go to the website, it displays a random realistic image of a person that may not exist. If you don’t like the idea, you can change it with merely a single mouse click. Because the portal doesn’t have any Download button at the time of this writing, you must rely on the web browser’s default downloading process to get the image to your PC. You can follow the instructions that are given below to switch between the images and download the one you like: * Use your preferred web browser (Google Chrome here) to visit the URL provided above, and then notice the random image that appears on the page; * Click **Another** from the box that appears at the bottom-right corner to change the image, repeat this process until you find a good photo for your avatar, and then right-click anywhere on the image. * Click **Save image** from the context menu to save the photo. And then go to the default download folder to access the downloaded image, and use the picture wherever needed. **Note:** Different browsers may have this feature with other names ![thispersondoesnotexist free online face generators](https://images.wondershare.com/filmora/article-images/thispersondoesnotexist-free-online-face-generators.jpg) ### 6\. BoredHumans **Website**: <https://boredhumans.com/faces.php> This web portal is identical to the previous one as it generates random virtual faces with merely one mouse click. Even this website doesn’t have any Download button to help you download the image. Therefore, you must use the browser’s built-in feature to obtain the photo you want to save to your PC. You can learn how to use BoredHumans to generate virtual faces and download them to your computer by following the steps given below: * Open a web browser (Google Chrome here) and visit the URL provided above, and then click **Generate Another Fake Human** if you don’t like the one that appears; * Keep clicking the button until you find a face that can be used as your avatar. Alternatively, you can click the **Generate A Human** button to create a less realistic image of a random person. ![free online face generators boredhumans](https://images.wondershare.com/filmora/article-images/free-online-face-generators-boredhumans.jpg) * Right-click the image and click **Save image** to download the photo to your PC; and then get to the default download location to access the photo and use it wherever needed. ### 7\. faceMaker **Website**: <https://facemaker.uvrg.org/> faceMaker allows you to generate virtual faces out of the fine details that you specify during the creation process. These details are adjusted using the sliders that affect the corresponding physical attributes of the avatars. For example, you can modify the lips, eye color, hair, face roundness, mouse depth, jaw shape, etc. using their respective sliders. You can follow the steps that are given below to learn how to create a virtual face using faceMaker, and save it to your PC to use it as an avatar: * Use your preferred web browser to visit the URL given above and click **Start** from the main page. * Fill out the questionnaire by choosing your preferred options and agreeing to the term and conditions. * Click **Start** and then click **Continue** on the next page. Use the sliders on the left and right panels to customize the face as needed, and once done, you can use any screen capturing tool to take a snapshot and remove the sliders by cropping the image, thus having only the virtual face. ![free online face generators facemaker](https://images.wondershare.com/filmora/article-images/free-online-face-generators-facemaker.jpg) * Save the cropped photo on your PC, and then back on the webpage, click **Finished** from the bottom-right corner. ![facemaker online face generators face](https://images.wondershare.com/filmora/article-images/facemaker-online-face-generators-face.jpg) * On the next page, choose the radio buttons according to your choice. Once done, click **Yes, submit now** from the bottom to submit the customized virtual face to the portal. ![download facemaker online face generators face](https://images.wondershare.com/filmora/article-images/download-facemaker-online-face-generators-face.jpg) **Conclusion** With all the cybercrime reports circulating everywhere nowadays, it is important to stay cautious about what you post on any social media website. To add an extra layer of security, you can avoid using your real photograph as a profile picture, and go with the fake faces instead. You can generate these virtual faces using any of the free online face generator websites, some of which even allow you to define the shape of a face quite minutely. Because the generated faces are not of any real human, they can be used as your avatar without any risk. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More about Video Editing](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) ## Best Free Online Face Generators to Get Virtual Faces in 2022 ### 1\. Generated Photos: Faces **Website**: <https://generated.photos/faces> This online portal enables you to create virtual faces by specifying the physical attributes of a character, such as gender, age, hair color, eye color, and much more. You can be as creative as you want to generate a face that appears somewhat like you with the available options. Once a look is generated, you can download and use it as needed. The steps that are given below explain how you can use Generated Photos’ Faces section to create and download a virtual face: * Launch your favorite web browser and go to the URL given above, and then you will see all free AI-generated photos on this website. ![generated photos layout](https://images.wondershare.com/filmora/article-images/generated-photos-layout.jpg) * Use the filters given in the left pane to define your character's physical attributes and click **Apply** from the bottom to get the results. You can customize the face from its head post, gender, age, hair, eye, and emotion aspects. * Click your preferred character from the AI-generated faces, and then click **Download** from the page that opens next. Choose your preferred method to sign up, and then sign in to download the virtual face to your PC. ### 2\. Generated Photos: Anonymizer **Website**: <https://generated.photos/anonymizer> Anonymizer is another section from the Generated Photos portal that allows you to upload your image. Then it uses AI technology to generate similar virtual faces that you can download and use wherever needed. However, sometimes the pictures that the website creates may not resemble your face as closely as you expect them to be, but that’s OK. Isn’t it? The main idea is to keep your privacy intact, and that’s what Generated Photos: Anonymizer does. You can learn how to use this section by following the instructions given below: * Use the URL given above to get to the Anonymizer’s web page and then click **Upload photo;** * Select and upload your photo from your PC to the portal and wait while Anonymizer uses AI to generate similar faces. * Click the photo that you want to use, and when the next page opens up, click Sign up or sign in to download the photo and use it wherever needed ![recreate face with anonymizer online face generators](https://images.wondershare.com/filmora/article-images/recreate-face-with-anonymizer-online-face-generators.jpg) ### 3\. Generated Photos Face Generator Website: [](https://generated.photos/face-generator)<https://generated.photos/face-generator> This online face generator from Generated Photos allows you to create a unique realt-time face from scratch in one click. And if you don’t like the face generated, you can change the parameters such as gender, skin tone, hair, eye and head pose. Generated Photos Face Generator tool is a good choice for people who don’t want to upload any photos online, and need to customize the face at maximum. Below is a brief tutorial about how to generate a face with it step by step: * Go to the website give above and then click the **Generate faces** * Select the parameters accordingly based on your needs. You can generate the same face young or old with different emotions. ![generated photos face generator online](https://images.wondershare.com/filmora/article-images/generated-photos-face-generator-online.jpg) You can then download the generated photo by signing up or logging in, but you need to pay to remove the watermark. ### 4\. Massless **Website:** [https://massless.io/tool/face-maker-ai](https://massless.io/tool/face-maker-ai/) Massless allows you to use its tools to sketch a portrait, and then it uses AI technology to generate a virtual face out of your drawing. However, because you can’t always be precise while sketching with the mouse, it would be good to have access to a digital drawing pad to create the faces with a pen. With Massless, you can explore your creativity to the full and draw beautiful faces to use them as your avatar. You can follow the procedure given below to use Massless to draw virtual faces: * Open a web browser, and visit the URL given above. Click any icons from the toolbox at the top (E.g., **Nose**). * Draw a shape on its corresponding face area on the left (E.g., **Nose**), and wait while the portal automatically updates the photo on the right. * Repeat the process to sketch other parts of the face, and click the More icon (with three vertical dots) from the top-right corner. * Click **Download images** from the page that opens next to download the photo to your PC and use it wherever needed. ![massless online face generator](https://images.wondershare.com/filmora/article-images/massless-online-face-generator.jpg) ### 5\. This Person Does Not Exist **Website:** <https://thispersondoesnotexist.com/> This free online virtual face generator is probably the easiest and quickest. As you go to the website, it displays a random realistic image of a person that may not exist. If you don’t like the idea, you can change it with merely a single mouse click. Because the portal doesn’t have any Download button at the time of this writing, you must rely on the web browser’s default downloading process to get the image to your PC. You can follow the instructions that are given below to switch between the images and download the one you like: * Use your preferred web browser (Google Chrome here) to visit the URL provided above, and then notice the random image that appears on the page; * Click **Another** from the box that appears at the bottom-right corner to change the image, repeat this process until you find a good photo for your avatar, and then right-click anywhere on the image. * Click **Save image** from the context menu to save the photo. And then go to the default download folder to access the downloaded image, and use the picture wherever needed. **Note:** Different browsers may have this feature with other names ![thispersondoesnotexist free online face generators](https://images.wondershare.com/filmora/article-images/thispersondoesnotexist-free-online-face-generators.jpg) ### 6\. BoredHumans **Website**: <https://boredhumans.com/faces.php> This web portal is identical to the previous one as it generates random virtual faces with merely one mouse click. Even this website doesn’t have any Download button to help you download the image. Therefore, you must use the browser’s built-in feature to obtain the photo you want to save to your PC. You can learn how to use BoredHumans to generate virtual faces and download them to your computer by following the steps given below: * Open a web browser (Google Chrome here) and visit the URL provided above, and then click **Generate Another Fake Human** if you don’t like the one that appears; * Keep clicking the button until you find a face that can be used as your avatar. Alternatively, you can click the **Generate A Human** button to create a less realistic image of a random person. ![free online face generators boredhumans](https://images.wondershare.com/filmora/article-images/free-online-face-generators-boredhumans.jpg) * Right-click the image and click **Save image** to download the photo to your PC; and then get to the default download location to access the photo and use it wherever needed. ### 7\. faceMaker **Website**: <https://facemaker.uvrg.org/> faceMaker allows you to generate virtual faces out of the fine details that you specify during the creation process. These details are adjusted using the sliders that affect the corresponding physical attributes of the avatars. For example, you can modify the lips, eye color, hair, face roundness, mouse depth, jaw shape, etc. using their respective sliders. You can follow the steps that are given below to learn how to create a virtual face using faceMaker, and save it to your PC to use it as an avatar: * Use your preferred web browser to visit the URL given above and click **Start** from the main page. * Fill out the questionnaire by choosing your preferred options and agreeing to the term and conditions. * Click **Start** and then click **Continue** on the next page. Use the sliders on the left and right panels to customize the face as needed, and once done, you can use any screen capturing tool to take a snapshot and remove the sliders by cropping the image, thus having only the virtual face. ![free online face generators facemaker](https://images.wondershare.com/filmora/article-images/free-online-face-generators-facemaker.jpg) * Save the cropped photo on your PC, and then back on the webpage, click **Finished** from the bottom-right corner. ![facemaker online face generators face](https://images.wondershare.com/filmora/article-images/facemaker-online-face-generators-face.jpg) * On the next page, choose the radio buttons according to your choice. Once done, click **Yes, submit now** from the bottom to submit the customized virtual face to the portal. ![download facemaker online face generators face](https://images.wondershare.com/filmora/article-images/download-facemaker-online-face-generators-face.jpg) **Conclusion** With all the cybercrime reports circulating everywhere nowadays, it is important to stay cautious about what you post on any social media website. To add an extra layer of security, you can avoid using your real photograph as a profile picture, and go with the fake faces instead. You can generate these virtual faces using any of the free online face generator websites, some of which even allow you to define the shape of a face quite minutely. Because the generated faces are not of any real human, they can be used as your avatar without any risk. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More about Video Editing](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) ## Best Free Online Face Generators to Get Virtual Faces in 2022 ### 1\. Generated Photos: Faces **Website**: <https://generated.photos/faces> This online portal enables you to create virtual faces by specifying the physical attributes of a character, such as gender, age, hair color, eye color, and much more. You can be as creative as you want to generate a face that appears somewhat like you with the available options. Once a look is generated, you can download and use it as needed. The steps that are given below explain how you can use Generated Photos’ Faces section to create and download a virtual face: * Launch your favorite web browser and go to the URL given above, and then you will see all free AI-generated photos on this website. ![generated photos layout](https://images.wondershare.com/filmora/article-images/generated-photos-layout.jpg) * Use the filters given in the left pane to define your character's physical attributes and click **Apply** from the bottom to get the results. You can customize the face from its head post, gender, age, hair, eye, and emotion aspects. * Click your preferred character from the AI-generated faces, and then click **Download** from the page that opens next. Choose your preferred method to sign up, and then sign in to download the virtual face to your PC. ### 2\. Generated Photos: Anonymizer **Website**: <https://generated.photos/anonymizer> Anonymizer is another section from the Generated Photos portal that allows you to upload your image. Then it uses AI technology to generate similar virtual faces that you can download and use wherever needed. However, sometimes the pictures that the website creates may not resemble your face as closely as you expect them to be, but that’s OK. Isn’t it? The main idea is to keep your privacy intact, and that’s what Generated Photos: Anonymizer does. You can learn how to use this section by following the instructions given below: * Use the URL given above to get to the Anonymizer’s web page and then click **Upload photo;** * Select and upload your photo from your PC to the portal and wait while Anonymizer uses AI to generate similar faces. * Click the photo that you want to use, and when the next page opens up, click Sign up or sign in to download the photo and use it wherever needed ![recreate face with anonymizer online face generators](https://images.wondershare.com/filmora/article-images/recreate-face-with-anonymizer-online-face-generators.jpg) ### 3\. Generated Photos Face Generator Website: [](https://generated.photos/face-generator)<https://generated.photos/face-generator> This online face generator from Generated Photos allows you to create a unique realt-time face from scratch in one click. And if you don’t like the face generated, you can change the parameters such as gender, skin tone, hair, eye and head pose. Generated Photos Face Generator tool is a good choice for people who don’t want to upload any photos online, and need to customize the face at maximum. Below is a brief tutorial about how to generate a face with it step by step: * Go to the website give above and then click the **Generate faces** * Select the parameters accordingly based on your needs. You can generate the same face young or old with different emotions. ![generated photos face generator online](https://images.wondershare.com/filmora/article-images/generated-photos-face-generator-online.jpg) You can then download the generated photo by signing up or logging in, but you need to pay to remove the watermark. ### 4\. Massless **Website:** [https://massless.io/tool/face-maker-ai](https://massless.io/tool/face-maker-ai/) Massless allows you to use its tools to sketch a portrait, and then it uses AI technology to generate a virtual face out of your drawing. However, because you can’t always be precise while sketching with the mouse, it would be good to have access to a digital drawing pad to create the faces with a pen. With Massless, you can explore your creativity to the full and draw beautiful faces to use them as your avatar. You can follow the procedure given below to use Massless to draw virtual faces: * Open a web browser, and visit the URL given above. Click any icons from the toolbox at the top (E.g., **Nose**). * Draw a shape on its corresponding face area on the left (E.g., **Nose**), and wait while the portal automatically updates the photo on the right. * Repeat the process to sketch other parts of the face, and click the More icon (with three vertical dots) from the top-right corner. * Click **Download images** from the page that opens next to download the photo to your PC and use it wherever needed. ![massless online face generator](https://images.wondershare.com/filmora/article-images/massless-online-face-generator.jpg) ### 5\. This Person Does Not Exist **Website:** <https://thispersondoesnotexist.com/> This free online virtual face generator is probably the easiest and quickest. As you go to the website, it displays a random realistic image of a person that may not exist. If you don’t like the idea, you can change it with merely a single mouse click. Because the portal doesn’t have any Download button at the time of this writing, you must rely on the web browser’s default downloading process to get the image to your PC. You can follow the instructions that are given below to switch between the images and download the one you like: * Use your preferred web browser (Google Chrome here) to visit the URL provided above, and then notice the random image that appears on the page; * Click **Another** from the box that appears at the bottom-right corner to change the image, repeat this process until you find a good photo for your avatar, and then right-click anywhere on the image. * Click **Save image** from the context menu to save the photo. And then go to the default download folder to access the downloaded image, and use the picture wherever needed. **Note:** Different browsers may have this feature with other names ![thispersondoesnotexist free online face generators](https://images.wondershare.com/filmora/article-images/thispersondoesnotexist-free-online-face-generators.jpg) ### 6\. BoredHumans **Website**: <https://boredhumans.com/faces.php> This web portal is identical to the previous one as it generates random virtual faces with merely one mouse click. Even this website doesn’t have any Download button to help you download the image. Therefore, you must use the browser’s built-in feature to obtain the photo you want to save to your PC. You can learn how to use BoredHumans to generate virtual faces and download them to your computer by following the steps given below: * Open a web browser (Google Chrome here) and visit the URL provided above, and then click **Generate Another Fake Human** if you don’t like the one that appears; * Keep clicking the button until you find a face that can be used as your avatar. Alternatively, you can click the **Generate A Human** button to create a less realistic image of a random person. ![free online face generators boredhumans](https://images.wondershare.com/filmora/article-images/free-online-face-generators-boredhumans.jpg) * Right-click the image and click **Save image** to download the photo to your PC; and then get to the default download location to access the photo and use it wherever needed. ### 7\. faceMaker **Website**: <https://facemaker.uvrg.org/> faceMaker allows you to generate virtual faces out of the fine details that you specify during the creation process. These details are adjusted using the sliders that affect the corresponding physical attributes of the avatars. For example, you can modify the lips, eye color, hair, face roundness, mouse depth, jaw shape, etc. using their respective sliders. You can follow the steps that are given below to learn how to create a virtual face using faceMaker, and save it to your PC to use it as an avatar: * Use your preferred web browser to visit the URL given above and click **Start** from the main page. * Fill out the questionnaire by choosing your preferred options and agreeing to the term and conditions. * Click **Start** and then click **Continue** on the next page. Use the sliders on the left and right panels to customize the face as needed, and once done, you can use any screen capturing tool to take a snapshot and remove the sliders by cropping the image, thus having only the virtual face. ![free online face generators facemaker](https://images.wondershare.com/filmora/article-images/free-online-face-generators-facemaker.jpg) * Save the cropped photo on your PC, and then back on the webpage, click **Finished** from the bottom-right corner. ![facemaker online face generators face](https://images.wondershare.com/filmora/article-images/facemaker-online-face-generators-face.jpg) * On the next page, choose the radio buttons according to your choice. Once done, click **Yes, submit now** from the bottom to submit the customized virtual face to the portal. ![download facemaker online face generators face](https://images.wondershare.com/filmora/article-images/download-facemaker-online-face-generators-face.jpg) **Conclusion** With all the cybercrime reports circulating everywhere nowadays, it is important to stay cautious about what you post on any social media website. To add an extra layer of security, you can avoid using your real photograph as a profile picture, and go with the fake faces instead. You can generate these virtual faces using any of the free online face generator websites, some of which even allow you to define the shape of a face quite minutely. Because the generated faces are not of any real human, they can be used as your avatar without any risk. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More about Video Editing](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) ## Best Free Online Face Generators to Get Virtual Faces in 2022 ### 1\. Generated Photos: Faces **Website**: <https://generated.photos/faces> This online portal enables you to create virtual faces by specifying the physical attributes of a character, such as gender, age, hair color, eye color, and much more. You can be as creative as you want to generate a face that appears somewhat like you with the available options. Once a look is generated, you can download and use it as needed. The steps that are given below explain how you can use Generated Photos’ Faces section to create and download a virtual face: * Launch your favorite web browser and go to the URL given above, and then you will see all free AI-generated photos on this website. ![generated photos layout](https://images.wondershare.com/filmora/article-images/generated-photos-layout.jpg) * Use the filters given in the left pane to define your character's physical attributes and click **Apply** from the bottom to get the results. You can customize the face from its head post, gender, age, hair, eye, and emotion aspects. * Click your preferred character from the AI-generated faces, and then click **Download** from the page that opens next. Choose your preferred method to sign up, and then sign in to download the virtual face to your PC. ### 2\. Generated Photos: Anonymizer **Website**: <https://generated.photos/anonymizer> Anonymizer is another section from the Generated Photos portal that allows you to upload your image. Then it uses AI technology to generate similar virtual faces that you can download and use wherever needed. However, sometimes the pictures that the website creates may not resemble your face as closely as you expect them to be, but that’s OK. Isn’t it? The main idea is to keep your privacy intact, and that’s what Generated Photos: Anonymizer does. You can learn how to use this section by following the instructions given below: * Use the URL given above to get to the Anonymizer’s web page and then click **Upload photo;** * Select and upload your photo from your PC to the portal and wait while Anonymizer uses AI to generate similar faces. * Click the photo that you want to use, and when the next page opens up, click Sign up or sign in to download the photo and use it wherever needed ![recreate face with anonymizer online face generators](https://images.wondershare.com/filmora/article-images/recreate-face-with-anonymizer-online-face-generators.jpg) ### 3\. Generated Photos Face Generator Website: [](https://generated.photos/face-generator)<https://generated.photos/face-generator> This online face generator from Generated Photos allows you to create a unique realt-time face from scratch in one click. And if you don’t like the face generated, you can change the parameters such as gender, skin tone, hair, eye and head pose. Generated Photos Face Generator tool is a good choice for people who don’t want to upload any photos online, and need to customize the face at maximum. Below is a brief tutorial about how to generate a face with it step by step: * Go to the website give above and then click the **Generate faces** * Select the parameters accordingly based on your needs. You can generate the same face young or old with different emotions. ![generated photos face generator online](https://images.wondershare.com/filmora/article-images/generated-photos-face-generator-online.jpg) You can then download the generated photo by signing up or logging in, but you need to pay to remove the watermark. ### 4\. Massless **Website:** [https://massless.io/tool/face-maker-ai](https://massless.io/tool/face-maker-ai/) Massless allows you to use its tools to sketch a portrait, and then it uses AI technology to generate a virtual face out of your drawing. However, because you can’t always be precise while sketching with the mouse, it would be good to have access to a digital drawing pad to create the faces with a pen. With Massless, you can explore your creativity to the full and draw beautiful faces to use them as your avatar. You can follow the procedure given below to use Massless to draw virtual faces: * Open a web browser, and visit the URL given above. Click any icons from the toolbox at the top (E.g., **Nose**). * Draw a shape on its corresponding face area on the left (E.g., **Nose**), and wait while the portal automatically updates the photo on the right. * Repeat the process to sketch other parts of the face, and click the More icon (with three vertical dots) from the top-right corner. * Click **Download images** from the page that opens next to download the photo to your PC and use it wherever needed. ![massless online face generator](https://images.wondershare.com/filmora/article-images/massless-online-face-generator.jpg) ### 5\. This Person Does Not Exist **Website:** <https://thispersondoesnotexist.com/> This free online virtual face generator is probably the easiest and quickest. As you go to the website, it displays a random realistic image of a person that may not exist. If you don’t like the idea, you can change it with merely a single mouse click. Because the portal doesn’t have any Download button at the time of this writing, you must rely on the web browser’s default downloading process to get the image to your PC. You can follow the instructions that are given below to switch between the images and download the one you like: * Use your preferred web browser (Google Chrome here) to visit the URL provided above, and then notice the random image that appears on the page; * Click **Another** from the box that appears at the bottom-right corner to change the image, repeat this process until you find a good photo for your avatar, and then right-click anywhere on the image. * Click **Save image** from the context menu to save the photo. And then go to the default download folder to access the downloaded image, and use the picture wherever needed. **Note:** Different browsers may have this feature with other names ![thispersondoesnotexist free online face generators](https://images.wondershare.com/filmora/article-images/thispersondoesnotexist-free-online-face-generators.jpg) ### 6\. BoredHumans **Website**: <https://boredhumans.com/faces.php> This web portal is identical to the previous one as it generates random virtual faces with merely one mouse click. Even this website doesn’t have any Download button to help you download the image. Therefore, you must use the browser’s built-in feature to obtain the photo you want to save to your PC. You can learn how to use BoredHumans to generate virtual faces and download them to your computer by following the steps given below: * Open a web browser (Google Chrome here) and visit the URL provided above, and then click **Generate Another Fake Human** if you don’t like the one that appears; * Keep clicking the button until you find a face that can be used as your avatar. Alternatively, you can click the **Generate A Human** button to create a less realistic image of a random person. ![free online face generators boredhumans](https://images.wondershare.com/filmora/article-images/free-online-face-generators-boredhumans.jpg) * Right-click the image and click **Save image** to download the photo to your PC; and then get to the default download location to access the photo and use it wherever needed. ### 7\. faceMaker **Website**: <https://facemaker.uvrg.org/> faceMaker allows you to generate virtual faces out of the fine details that you specify during the creation process. These details are adjusted using the sliders that affect the corresponding physical attributes of the avatars. For example, you can modify the lips, eye color, hair, face roundness, mouse depth, jaw shape, etc. using their respective sliders. You can follow the steps that are given below to learn how to create a virtual face using faceMaker, and save it to your PC to use it as an avatar: * Use your preferred web browser to visit the URL given above and click **Start** from the main page. * Fill out the questionnaire by choosing your preferred options and agreeing to the term and conditions. * Click **Start** and then click **Continue** on the next page. Use the sliders on the left and right panels to customize the face as needed, and once done, you can use any screen capturing tool to take a snapshot and remove the sliders by cropping the image, thus having only the virtual face. ![free online face generators facemaker](https://images.wondershare.com/filmora/article-images/free-online-face-generators-facemaker.jpg) * Save the cropped photo on your PC, and then back on the webpage, click **Finished** from the bottom-right corner. ![facemaker online face generators face](https://images.wondershare.com/filmora/article-images/facemaker-online-face-generators-face.jpg) * On the next page, choose the radio buttons according to your choice. Once done, click **Yes, submit now** from the bottom to submit the customized virtual face to the portal. ![download facemaker online face generators face](https://images.wondershare.com/filmora/article-images/download-facemaker-online-face-generators-face.jpg) **Conclusion** With all the cybercrime reports circulating everywhere nowadays, it is important to stay cautious about what you post on any social media website. To add an extra layer of security, you can avoid using your real photograph as a profile picture, and go with the fake faces instead. You can generate these virtual faces using any of the free online face generator websites, some of which even allow you to define the shape of a face quite minutely. Because the generated faces are not of any real human, they can be used as your avatar without any risk. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More about Video Editing](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Say Goodbye to Windows Movie Maker: 10 Free Video Editing Tools We all know what a windows movie maker is, and this is one of the best editing programs for beginners. This program was pre-installed in almost all window devices, and people started preferring this program as it comes with a simple interface, additional special effects for fun, and mainly this is free. One question that was asked by almost all the windows users was whether windows **movie maker free**. However, in 2017 Microsoft stopped supporting and helping Windows movie makers. They also warned the users that downloading this movie maker from any 3rd party can contain viruses, hidden costs, and malware. Now it has become difficult to use **windows free movie maker**s. If you are a beginner and searching for a great windows movie maker alternative, stick to this blog. ## 1\. Filmora If you are not new to this editing field, you must have heard the name [Filmora](https://tools.techidaily.com/wondershare/filmora/download/). It is one of the best editing software available in the market. It is a line of editing applications and video creation and contains various products for intermediate and beginners. A few standard features of Filmora include a preview window, effects library, timeline, etc. The software library is developed to be compatible with both macOS and Windows. [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit) [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later ![filmora](https://images.wondershare.com/filmora/guide/add-and-customize-overlays-1.png) You can use the free demo feature before purchasing the original product, and you might get to see a few types. * **Filmora** is a simple video editor with preset effects and video templates. * **FilmoraPro** is a premium and better version with better industry-standard features, including keyframe-based animation, customizable effects, and color grading. * **Filmora** is a version available for mobile devices. * **FilmoraScrn** is available only for windows, a screen recording app with additional features. Pros * Great intermediate and basic features * Simple user-interface * Offers screen recording * Offers a sound support system Cons * Lack of advanced features * Contains watermark ## 2\. VSDC Free Video Editor If you plan to edit your videos with some great tools, then you need a VSDC-free video editor. As this video editor doesn't charge anything, you don't have to worry about payment, subscription, and trial period. With the help of this application, the developers are successfully building a strong community, which will help you understand troubleshoot issues and features of the program. ![vsdc free video editor](https://images.wondershare.com/filmora/article-images/vsdc-video-editing-interface.jpg) This video editor can perform various functions, including adding effects, reducing file size, a wide range of formats, etc. VSDC can also convert the files to a compatible format. The program offers different devices, including Blackberry, iPod, Xbox, iRiver, iPhone, etc. You can easily extract audio, add markers, export individual images, and perform many more functions efficiently. Pros * Simple interface * DVD burning features * Non-linear editing Cons * Common video editing features * Lack of additional editing features ## 3\. VideoPad Videopad is also free editing software that allows its users to edit videos and perform various tasks related to the editing industry. With the help of this movie maker program, you can easily create a great video and perform a few basic editing tasks. If you create videos very often for social media platforms or your friends and family, then Videopad is what you need. ![videopad](https://images.wondershare.com/filmora/article-images/videopad.jpg) Though this video maker doesn't have advanced features, its basic video editing skills are enough to create a blasting video. The simple interface of the editing platform helps the users understand the process in a simple way. This platform can be termed as one of the best **free windows movie makers.** Pros * Best free video editing application for the beginners * Supports various video formats * 360-degree editing * New updates daily Cons * Doesn’t support video animation * No collaboration tools or video capturing ## 4\. Shotcut Video Editor Shortcut is also a free editing software, available for Windows, Linux, and Mac. This application is best for the people who would prefer not to be dependent on giant software corporations but would undergo the regular upgrade of the community of dedicated and enthusiastic developers. This video editor is feature-packed, helpful, and one of the best free video editors. Moreover, if you are new to the editing industry, this application is perfect. ![shotcut](https://images.wondershare.com/filmora/article-images/shotcut-editor.jpg) This application will allow you to edit and create various audio and visual editing functionalities. This app is the perfect alternative for beginners with an engaged and active community. Also, you can also go through the tutorials if you are facing any issues. This popular multimedia store is a perfect alternative for many expensive and complicated tools like OpenShot, Lightwork, etc. Pros * Free to use * Consists of advanced tools and effects * High-quality export/input support Cons * No preview for transition and effect * No stock music ## 5\. OpenShot Video Editor Cross-platform video editing software is designed to help various businesses utilize the drag and drop interface feature to edit videos, audios, or images. Users can use this video editing software to add animation effects such as flying text, fade, bounce, snow, watermarks, audio track, 3D titles, etc. This app is perfect for the beginner as it has many valuable features, and this software costs no money. ![openshot vido editor](https://images.wondershare.com/filmora/article-images/openshot-website.jpg) This software is very easy to use and is helping various professionals all around the world with its excellent features. This website is great for both professionals and beginners; moreover, the developers are working on the system to bring up the latest version of the video editing software. Pros * 3D title * Free to use * No watermark * Update for reducing the bugs Cons * Limited editing tools * Obsolete interface * Unstable performance ## 6\. Ezvid This one is known for its power of cutting-edge features and effects. With facecam, voice synthesis, speed control, and screen drawing, Ezvid is the only best solution to make videos entertaining, enchanting, and informing your viewers. With a single click, you can record the screen using the Ezvid windows version and capture everything that appears on the computer screen; games, applications, paint programs, etc. ![ezvid](https://images.wondershare.com/filmora/article-images/ezvid-free-video-recorder.jpg) The software's revolutionary and elegant screen drawing functionality allows you to paint or draw directly on your screen; moreover, you can develop amazing screencasts and documents with an easy process. This software is also the best and the easiest screen recorder and screen capture program for windows. More than 3 million people have already downloaded the app. Pros * Offer quality and high resolution to record videos * An intuitive and simple interface for beginners * Power of controlling the speed of recording Cons * Limitation of recording timing * Unable to download and save videos ## 7\. Avidemux Avidemux is one of the best alternatives to free video editing software. This video editor is specially designed for simple cutting, encoding tasks, and filtering. It supports various files like DVD-compatible MPEG files, AVI, ASF, and MP4, using many codecs. You can also automate the task using a job queue, powerful scripting capabilities, and projects. ![avidemux](https://images.wondershare.com/filmora/article-images/avidemux.jpg) This software is available for macOS X, Windows, Linux, etc. You can use various tools to sync audio tracks or compress videos. Avidemux is an easy video editing software that comes with various useful functions. Users can use this software to cut or edit videos, encode exports, add subtitles, etc. Anyone can use it; it is the best software for editing social media websites and commercial ads. Pros * Store custom script * Add subtitles to your video * Encode your video Cons * Complex process * Confusing cutting features ## 8\. Microsoft Photos Microsoft photos allow you to edit and view your videos and photos, create an album, make movies, etc. You have various effective creative tools at your fingertips, such as video remix for the instant creation of a video from various pictures or videos, rotating and crop photos, adding a filter and a few other effects, and adjusting lighting and color. It also allows you to add different 3D effects like laser, butterfly, explosion, etc. ![microsoft photos](https://images.wondershare.com/filmora/article-images/microsoft-photos-edit.jpg) This application has no difficulty, and anyone can use it without facing any trouble; all you need to do is watch the tutorial if you are facing any trouble during the process. This app is best for editing and trimming videos for YouTube. Microsoft Photos: **free movie maker windows**. Pros * User-friendly interface * Easy to access * Bunch of basic features Cons * Lack of advanced features * Lag in the software ## 9\. FilmForth FilmForth is a software that consists of all the video editing features that allow the user to edit video without any skills. You can also save a video without a watermark and share it on any platform. The best thing about this application is that you can access all the features without paying anything. ![filmforth](https://images.wondershare.com/filmora/article-images/filmforth-change-video-speed.jpg) Whether you want to edit a video or a picture, FilmForth understands what you want, so they act accordingly and help you get the same video or image in just a few clicks. The main motive of this software is to reduce the complication during video editing. You can perform various tasks like adding logos, making a slideshow, removing or changing background, etc. Pros * Can share the media on any platform * Allows you to download without any watermark * Allows you to use the features without purchasing any package Cons * Not a great user-interface * Lag in the system ## 10\. VirtualDub VirtualDub is a processing utility and video capture licensed under the General Public license. It is designed in a way so that it can clean and trim the video before processing with another program or exporting to tape. It doesn't have the features close to Adobe premiere but is comparatively faster than all those software. ![virtualdub](https://images.wondershare.com/filmora/article-images/virtual-dub-video-to-image-control.jpg) This software can also process many files because of its batch-processing capabilities. Just like all other applications, it has its benefits, and you can use them to benefit yourself in many ways. It has a fractional frame rate, so you don't have to settle for 29 anymore. They also offer mouse and keyboard shortcuts for easy and fast operation. Pros * Integrated volume meter * Access to hidden video format * Noise reduction Cons * Slow process * Poor interface ## Conclusion Many people come up with the question, **is windows movie maker free**; yes, it is free, and anyone can use it. We also have shared some alternate solutions to the video editing process. You can use one as per your need and requirement. [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later ![filmora](https://images.wondershare.com/filmora/guide/add-and-customize-overlays-1.png) You can use the free demo feature before purchasing the original product, and you might get to see a few types. * **Filmora** is a simple video editor with preset effects and video templates. * **FilmoraPro** is a premium and better version with better industry-standard features, including keyframe-based animation, customizable effects, and color grading. * **Filmora** is a version available for mobile devices. * **FilmoraScrn** is available only for windows, a screen recording app with additional features. Pros * Great intermediate and basic features * Simple user-interface * Offers screen recording * Offers a sound support system Cons * Lack of advanced features * Contains watermark ## 2\. VSDC Free Video Editor If you plan to edit your videos with some great tools, then you need a VSDC-free video editor. As this video editor doesn't charge anything, you don't have to worry about payment, subscription, and trial period. With the help of this application, the developers are successfully building a strong community, which will help you understand troubleshoot issues and features of the program. ![vsdc free video editor](https://images.wondershare.com/filmora/article-images/vsdc-video-editing-interface.jpg) This video editor can perform various functions, including adding effects, reducing file size, a wide range of formats, etc. VSDC can also convert the files to a compatible format. The program offers different devices, including Blackberry, iPod, Xbox, iRiver, iPhone, etc. You can easily extract audio, add markers, export individual images, and perform many more functions efficiently. Pros * Simple interface * DVD burning features * Non-linear editing Cons * Common video editing features * Lack of additional editing features ## 3\. VideoPad Videopad is also free editing software that allows its users to edit videos and perform various tasks related to the editing industry. With the help of this movie maker program, you can easily create a great video and perform a few basic editing tasks. If you create videos very often for social media platforms or your friends and family, then Videopad is what you need. ![videopad](https://images.wondershare.com/filmora/article-images/videopad.jpg) Though this video maker doesn't have advanced features, its basic video editing skills are enough to create a blasting video. The simple interface of the editing platform helps the users understand the process in a simple way. This platform can be termed as one of the best **free windows movie makers.** Pros * Best free video editing application for the beginners * Supports various video formats * 360-degree editing * New updates daily Cons * Doesn’t support video animation * No collaboration tools or video capturing ## 4\. Shotcut Video Editor Shortcut is also a free editing software, available for Windows, Linux, and Mac. This application is best for the people who would prefer not to be dependent on giant software corporations but would undergo the regular upgrade of the community of dedicated and enthusiastic developers. This video editor is feature-packed, helpful, and one of the best free video editors. Moreover, if you are new to the editing industry, this application is perfect. ![shotcut](https://images.wondershare.com/filmora/article-images/shotcut-editor.jpg) This application will allow you to edit and create various audio and visual editing functionalities. This app is the perfect alternative for beginners with an engaged and active community. Also, you can also go through the tutorials if you are facing any issues. This popular multimedia store is a perfect alternative for many expensive and complicated tools like OpenShot, Lightwork, etc. Pros * Free to use * Consists of advanced tools and effects * High-quality export/input support Cons * No preview for transition and effect * No stock music ## 5\. OpenShot Video Editor Cross-platform video editing software is designed to help various businesses utilize the drag and drop interface feature to edit videos, audios, or images. Users can use this video editing software to add animation effects such as flying text, fade, bounce, snow, watermarks, audio track, 3D titles, etc. This app is perfect for the beginner as it has many valuable features, and this software costs no money. ![openshot vido editor](https://images.wondershare.com/filmora/article-images/openshot-website.jpg) This software is very easy to use and is helping various professionals all around the world with its excellent features. This website is great for both professionals and beginners; moreover, the developers are working on the system to bring up the latest version of the video editing software. Pros * 3D title * Free to use * No watermark * Update for reducing the bugs Cons * Limited editing tools * Obsolete interface * Unstable performance ## 6\. Ezvid This one is known for its power of cutting-edge features and effects. With facecam, voice synthesis, speed control, and screen drawing, Ezvid is the only best solution to make videos entertaining, enchanting, and informing your viewers. With a single click, you can record the screen using the Ezvid windows version and capture everything that appears on the computer screen; games, applications, paint programs, etc. ![ezvid](https://images.wondershare.com/filmora/article-images/ezvid-free-video-recorder.jpg) The software's revolutionary and elegant screen drawing functionality allows you to paint or draw directly on your screen; moreover, you can develop amazing screencasts and documents with an easy process. This software is also the best and the easiest screen recorder and screen capture program for windows. More than 3 million people have already downloaded the app. Pros * Offer quality and high resolution to record videos * An intuitive and simple interface for beginners * Power of controlling the speed of recording Cons * Limitation of recording timing * Unable to download and save videos ## 7\. Avidemux Avidemux is one of the best alternatives to free video editing software. This video editor is specially designed for simple cutting, encoding tasks, and filtering. It supports various files like DVD-compatible MPEG files, AVI, ASF, and MP4, using many codecs. You can also automate the task using a job queue, powerful scripting capabilities, and projects. ![avidemux](https://images.wondershare.com/filmora/article-images/avidemux.jpg) This software is available for macOS X, Windows, Linux, etc. You can use various tools to sync audio tracks or compress videos. Avidemux is an easy video editing software that comes with various useful functions. Users can use this software to cut or edit videos, encode exports, add subtitles, etc. Anyone can use it; it is the best software for editing social media websites and commercial ads. Pros * Store custom script * Add subtitles to your video * Encode your video Cons * Complex process * Confusing cutting features ## 8\. Microsoft Photos Microsoft photos allow you to edit and view your videos and photos, create an album, make movies, etc. You have various effective creative tools at your fingertips, such as video remix for the instant creation of a video from various pictures or videos, rotating and crop photos, adding a filter and a few other effects, and adjusting lighting and color. It also allows you to add different 3D effects like laser, butterfly, explosion, etc. ![microsoft photos](https://images.wondershare.com/filmora/article-images/microsoft-photos-edit.jpg) This application has no difficulty, and anyone can use it without facing any trouble; all you need to do is watch the tutorial if you are facing any trouble during the process. This app is best for editing and trimming videos for YouTube. Microsoft Photos: **free movie maker windows**. Pros * User-friendly interface * Easy to access * Bunch of basic features Cons * Lack of advanced features * Lag in the software ## 9\. FilmForth FilmForth is a software that consists of all the video editing features that allow the user to edit video without any skills. You can also save a video without a watermark and share it on any platform. The best thing about this application is that you can access all the features without paying anything. ![filmforth](https://images.wondershare.com/filmora/article-images/filmforth-change-video-speed.jpg) Whether you want to edit a video or a picture, FilmForth understands what you want, so they act accordingly and help you get the same video or image in just a few clicks. The main motive of this software is to reduce the complication during video editing. You can perform various tasks like adding logos, making a slideshow, removing or changing background, etc. Pros * Can share the media on any platform * Allows you to download without any watermark * Allows you to use the features without purchasing any package Cons * Not a great user-interface * Lag in the system ## 10\. VirtualDub VirtualDub is a processing utility and video capture licensed under the General Public license. It is designed in a way so that it can clean and trim the video before processing with another program or exporting to tape. It doesn't have the features close to Adobe premiere but is comparatively faster than all those software. ![virtualdub](https://images.wondershare.com/filmora/article-images/virtual-dub-video-to-image-control.jpg) This software can also process many files because of its batch-processing capabilities. Just like all other applications, it has its benefits, and you can use them to benefit yourself in many ways. It has a fractional frame rate, so you don't have to settle for 29 anymore. They also offer mouse and keyboard shortcuts for easy and fast operation. Pros * Integrated volume meter * Access to hidden video format * Noise reduction Cons * Slow process * Poor interface ## Conclusion Many people come up with the question, **is windows movie maker free**; yes, it is free, and anyone can use it. We also have shared some alternate solutions to the video editing process. You can use one as per your need and requirement. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Do You Have Any Idea to Save Projects on the Final Cut Pro App? If You Are in Search of This Content, Then You Are in the Right Place to Obtain the Valuable Facts About It in Detail # How to Save Final Cut Pro Project the Right Way? ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) ##### Shanoon Cox Mar 27, 2024• Proven solutions aIn the Final Cut Pro, you can find the autosave option to store the changes made on the file automatically without any manual intervention. To overcome the manual mechanism, the autosave feature in the FCP app keeps the last changes on the file precisely. In this article, you can find insightful ideas about the autosave mechanism and the manual storage process. In addition, you will learn how to save the finished projects on the external drives effortlessly. A detailed focus on saving the completed projects on the Final Cut Pro app has been highlighted in the below content. Synopsis on the usage of batch export and discovery of the missing files are discussed to enlighten you with the essential data. > * [Part 1: The autosave mechanism of FCPX and manual storage procedure](#part1) > * [Part 2: How to save FCPX projects to desktop or external drives?](#part2) > * [Part 3: Where to find missing files or projects in final cut pro?](#part3) > * [Part 3: How to use Batch Export to save multiple projects in FCPX?](#part3) ## **Part 1: The autosave mechanism of Final Cut Pro X and manual storage procedure** In this section, get some mind-blowing facts on the autosave and manual options on the Final Cut Pro app! The FCP tool autosaves the changes every 15 minutes. The saved projects are available in the libraries file as a backup for the restore process. You can go to the library folder to view the autosaved projects. The last edited changes can be reflected by tapping the undo option in the Edit menu. Stepwise instructions to modify the autosave settings in the FCPX program Step 1: Launch the FCPX app, press Ctrl+Q to open the ‘User Preferences’ window. Step 2: In the ‘User Preferences’ screen, you can find a wide range of options to modify. Alter the levels of Undo, autosave vault attributes according to your needs, and save the changes. You can witness these parameters in the General section in the User Preference screen. Use the User Preference window to make necessary changes according to your requirement. BY default, the Autosave Vault is enabled, and you can work on the projects without any hesitation. Additionally, you can modify the attributes like ‘Save a copy for every’, ‘ Keep at most’, and ‘Maximum of’ to personalize your projects. ![auto-save](https://images.wondershare.com/filmora/images/final-cut-pro/auto-save.jpg) When the FCP file is open, you need not worry about the saving procedure. The app triggers the autosave mechanism for regular intervals, and the changes will be up-to-date. If you want to store the files manually, then work with its library files. A simple operation like Ctrl+c and Ctrl+v helps you to move the autosaved projects to any storage location. Here are few tips to restore the autosaved FCP files. Detailed guidelines on the restoration of autosaved files. Step 1 Open the Final Cut Pro app on your device. Step 2 Tap the ‘Libraries Sidebar’ to choose the desired library for restore action. Now hit File -> Open Library -> Backup options on the screen. Step 3 Surf the backup files and choose the desired one that requires a view. Press the Restore from’ option from the pop-up items. Finally, press the ‘Open’ button. ![from-backup](https://images.wondershare.com/filmora/images/final-cut-pro/from-backup.jpg) The manual storage option is feasible only after deactivating the autosave mechanism on the FCPX tool. It is not advisable to carry out this activity. The autosave option keeps your works up-to-date, and you will not miss the recent changes at any cost. You can still disable the autosave option to try the manual storage process. In the FCPX app, press ‘File -> Library Properties’, then from the displayed items, select the ‘Modify Settings’ option beside the ‘Storage Location’ label. Now, in the backups option select ‘Do not Save’ to deactivate the autosave mechanism. ![modify-storage-location](https://images.wondershare.com/filmora/images/final-cut-pro/modify-storage-location.jpg) After completing this procedure, save the changes and get back to the working timeline of FCPX to continue with your projects. When you edit any projects use the save option without fail else the changes made will be lost in no time. ## **Part 2: How to save FCPX projects to desktop or external drives?** Many experts recommend opting for an external storage location to save the FCPX files. It occupies more space, and you need to be careful while selecting the drives to store the library files of the FCPX projects. While saving the files, remove the generated data to optimize the storage process. First, remove the generated files in the library Step 1: Tap the Libraries sidebar in the FCPX tool and select ‘Library’ and choose the ’Cache’ option in the property window of Library. Step 2: Next, press ‘File -> Delete Generated Library Files’. To remove the unnecessary generated files. ![delete-generated-files](https://images.wondershare.com/filmora/images/final-cut-pro/delete-generated-files.jpg) The above action helps to clear up the space occupied by the project. If you want to free up more space, then delete most of the listed generated files. Secondly, now transfer the FCPX project to external drives. Step 1 Select the Libraries Sidebar in the FCPX program and choose the desired ‘Library’. Then hit ‘File -> Reveal in Finder. Now, the file opens in the new finder window. Step 2 Close the FCPX screen and drag the library files from the Finder window to the external hard drive. ![reveal-in-finder](https://images.wondershare.com/filmora/images/final-cut-pro/reveal-in-finder.jpg) Finally, you had made it. The FCPX projects were successfully moved on to the external drives quickly. Use the above technique to carry out flawless storage or transfer process. ## **Part 3: Where to find missing files or projects in final cut pro?** Many users feel that their project files were lost in the event of renaming. It becomes a missed file, and they will feel that the files were no were on their system. To handle this scenario, you must learn to think out of the box. You can use the relink technique to find the missed files in the Final Cut Pro app. The procedure is like the method of searching a particular file in your system using the ‘Search’ option. Here, Relink file functionality is available to set up a link again with the lost file to get back its storage space. Open the application and select the clip you want to discover. Go to the File menu on the title bar and choose Relink File option from the expanded items. A bunch of files will be displayed below, and you can choose the desired missed file from the collections. There are options to filter the discovered files by choosing between Missing and All options. Click the ‘Locate All’ button available at the bottom right side of the screen and navigate the folders to link with the perfect file. Press the ‘Choose’ button after selecting the missed file from the list. From the selected options, The Final Cut Pro application analyses all the attributes in the files and lists out the original files. Now hit the ‘Relink Files’ option to complete the file hunt process. ![missing-relink-files](https://images.wondershare.com/filmora/images/final-cut-pro/missing-relink-files.jpg) ## **Part 4: How to use Batch Export to save multiple projects in FCPX?** Perform the batch export for the files that carry similar settings. You can proceed with the flawless export procedure when the project files have the same roles, captions, and settings. The export option becomes limited if the project contains a mix of these attributes. Batch Export is the processing of sharing multiple files to desired storage space from your app ambiance. Appropriate clicks on the correct controls simplify the task. This procedure requires special attention because there is a chance of data loss when you handle bulk files at a time. The purpose of opting for the bunch export option is that you can complete the transfer tasks quickly. Exporting individual files is time-consuming and requires many clicks to move the desired files to the respective destination. This Batch Export feature in FCPX program enhances the users while working with many files. Step 1 Launch the FCPX app on your device. Step 2 In the Libraries sidebar, tap the library option, and select the desired projects that require the batch export. Step 1 Now, click the File -> Share option to trigger the export process. ![share-export-file](https://images.wondershare.com/filmora/images/final-cut-pro/share-export-file.jpg) It is advisable to export the Master files to retain the quality of the project. You can share the projects without compromising their quality factors. ## **Conclusion** As you all know that saving a project after successful completion is a crucial action. Few designers, editors, and developers unknowingly ignore this step. There are many applications embeds automatic saving function to enhance the editors to store their finished tasks. Thus, this article had given valuable insights on how to save the FCPX projects and the methods to backup and restore them. You had acquired an idea about the effective way to spot the missed project files. Finally, tips and tricks associated with the batch export were discussed to ensure flawless bulk file sharing in the secure channel. Use the above content to work comfortably with the FCPX app. Stay tuned to this article to discover enlightening facts on the Final Cut Pro application. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox ##### Shanoon Cox Mar 27, 2024• Proven solutions aIn the Final Cut Pro, you can find the autosave option to store the changes made on the file automatically without any manual intervention. To overcome the manual mechanism, the autosave feature in the FCP app keeps the last changes on the file precisely. In this article, you can find insightful ideas about the autosave mechanism and the manual storage process. In addition, you will learn how to save the finished projects on the external drives effortlessly. A detailed focus on saving the completed projects on the Final Cut Pro app has been highlighted in the below content. Synopsis on the usage of batch export and discovery of the missing files are discussed to enlighten you with the essential data. > * [Part 1: The autosave mechanism of FCPX and manual storage procedure](#part1) > * [Part 2: How to save FCPX projects to desktop or external drives?](#part2) > * [Part 3: Where to find missing files or projects in final cut pro?](#part3) > * [Part 3: How to use Batch Export to save multiple projects in FCPX?](#part3) ## **Part 1: The autosave mechanism of Final Cut Pro X and manual storage procedure** In this section, get some mind-blowing facts on the autosave and manual options on the Final Cut Pro app! The FCP tool autosaves the changes every 15 minutes. The saved projects are available in the libraries file as a backup for the restore process. You can go to the library folder to view the autosaved projects. The last edited changes can be reflected by tapping the undo option in the Edit menu. Stepwise instructions to modify the autosave settings in the FCPX program Step 1: Launch the FCPX app, press Ctrl+Q to open the ‘User Preferences’ window. Step 2: In the ‘User Preferences’ screen, you can find a wide range of options to modify. Alter the levels of Undo, autosave vault attributes according to your needs, and save the changes. You can witness these parameters in the General section in the User Preference screen. Use the User Preference window to make necessary changes according to your requirement. BY default, the Autosave Vault is enabled, and you can work on the projects without any hesitation. Additionally, you can modify the attributes like ‘Save a copy for every’, ‘ Keep at most’, and ‘Maximum of’ to personalize your projects. ![auto-save](https://images.wondershare.com/filmora/images/final-cut-pro/auto-save.jpg) When the FCP file is open, you need not worry about the saving procedure. The app triggers the autosave mechanism for regular intervals, and the changes will be up-to-date. If you want to store the files manually, then work with its library files. A simple operation like Ctrl+c and Ctrl+v helps you to move the autosaved projects to any storage location. Here are few tips to restore the autosaved FCP files. Detailed guidelines on the restoration of autosaved files. Step 1 Open the Final Cut Pro app on your device. Step 2 Tap the ‘Libraries Sidebar’ to choose the desired library for restore action. Now hit File -> Open Library -> Backup options on the screen. Step 3 Surf the backup files and choose the desired one that requires a view. Press the Restore from’ option from the pop-up items. Finally, press the ‘Open’ button. ![from-backup](https://images.wondershare.com/filmora/images/final-cut-pro/from-backup.jpg) The manual storage option is feasible only after deactivating the autosave mechanism on the FCPX tool. It is not advisable to carry out this activity. The autosave option keeps your works up-to-date, and you will not miss the recent changes at any cost. You can still disable the autosave option to try the manual storage process. In the FCPX app, press ‘File -> Library Properties’, then from the displayed items, select the ‘Modify Settings’ option beside the ‘Storage Location’ label. Now, in the backups option select ‘Do not Save’ to deactivate the autosave mechanism. ![modify-storage-location](https://images.wondershare.com/filmora/images/final-cut-pro/modify-storage-location.jpg) After completing this procedure, save the changes and get back to the working timeline of FCPX to continue with your projects. When you edit any projects use the save option without fail else the changes made will be lost in no time. ## **Part 2: How to save FCPX projects to desktop or external drives?** Many experts recommend opting for an external storage location to save the FCPX files. It occupies more space, and you need to be careful while selecting the drives to store the library files of the FCPX projects. While saving the files, remove the generated data to optimize the storage process. First, remove the generated files in the library Step 1: Tap the Libraries sidebar in the FCPX tool and select ‘Library’ and choose the ’Cache’ option in the property window of Library. Step 2: Next, press ‘File -> Delete Generated Library Files’. To remove the unnecessary generated files. ![delete-generated-files](https://images.wondershare.com/filmora/images/final-cut-pro/delete-generated-files.jpg) The above action helps to clear up the space occupied by the project. If you want to free up more space, then delete most of the listed generated files. Secondly, now transfer the FCPX project to external drives. Step 1 Select the Libraries Sidebar in the FCPX program and choose the desired ‘Library’. Then hit ‘File -> Reveal in Finder. Now, the file opens in the new finder window. Step 2 Close the FCPX screen and drag the library files from the Finder window to the external hard drive. ![reveal-in-finder](https://images.wondershare.com/filmora/images/final-cut-pro/reveal-in-finder.jpg) Finally, you had made it. The FCPX projects were successfully moved on to the external drives quickly. Use the above technique to carry out flawless storage or transfer process. ## **Part 3: Where to find missing files or projects in final cut pro?** Many users feel that their project files were lost in the event of renaming. It becomes a missed file, and they will feel that the files were no were on their system. To handle this scenario, you must learn to think out of the box. You can use the relink technique to find the missed files in the Final Cut Pro app. The procedure is like the method of searching a particular file in your system using the ‘Search’ option. Here, Relink file functionality is available to set up a link again with the lost file to get back its storage space. Open the application and select the clip you want to discover. Go to the File menu on the title bar and choose Relink File option from the expanded items. A bunch of files will be displayed below, and you can choose the desired missed file from the collections. There are options to filter the discovered files by choosing between Missing and All options. Click the ‘Locate All’ button available at the bottom right side of the screen and navigate the folders to link with the perfect file. Press the ‘Choose’ button after selecting the missed file from the list. From the selected options, The Final Cut Pro application analyses all the attributes in the files and lists out the original files. Now hit the ‘Relink Files’ option to complete the file hunt process. ![missing-relink-files](https://images.wondershare.com/filmora/images/final-cut-pro/missing-relink-files.jpg) ## **Part 4: How to use Batch Export to save multiple projects in FCPX?** Perform the batch export for the files that carry similar settings. You can proceed with the flawless export procedure when the project files have the same roles, captions, and settings. The export option becomes limited if the project contains a mix of these attributes. Batch Export is the processing of sharing multiple files to desired storage space from your app ambiance. Appropriate clicks on the correct controls simplify the task. This procedure requires special attention because there is a chance of data loss when you handle bulk files at a time. The purpose of opting for the bunch export option is that you can complete the transfer tasks quickly. Exporting individual files is time-consuming and requires many clicks to move the desired files to the respective destination. This Batch Export feature in FCPX program enhances the users while working with many files. Step 1 Launch the FCPX app on your device. Step 2 In the Libraries sidebar, tap the library option, and select the desired projects that require the batch export. Step 1 Now, click the File -> Share option to trigger the export process. ![share-export-file](https://images.wondershare.com/filmora/images/final-cut-pro/share-export-file.jpg) It is advisable to export the Master files to retain the quality of the project. You can share the projects without compromising their quality factors. ## **Conclusion** As you all know that saving a project after successful completion is a crucial action. Few designers, editors, and developers unknowingly ignore this step. There are many applications embeds automatic saving function to enhance the editors to store their finished tasks. Thus, this article had given valuable insights on how to save the FCPX projects and the methods to backup and restore them. You had acquired an idea about the effective way to spot the missed project files. Finally, tips and tricks associated with the batch export were discussed to ensure flawless bulk file sharing in the secure channel. Use the above content to work comfortably with the FCPX app. Stay tuned to this article to discover enlightening facts on the Final Cut Pro application. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox ##### Shanoon Cox Mar 27, 2024• Proven solutions aIn the Final Cut Pro, you can find the autosave option to store the changes made on the file automatically without any manual intervention. To overcome the manual mechanism, the autosave feature in the FCP app keeps the last changes on the file precisely. In this article, you can find insightful ideas about the autosave mechanism and the manual storage process. In addition, you will learn how to save the finished projects on the external drives effortlessly. A detailed focus on saving the completed projects on the Final Cut Pro app has been highlighted in the below content. Synopsis on the usage of batch export and discovery of the missing files are discussed to enlighten you with the essential data. > * [Part 1: The autosave mechanism of FCPX and manual storage procedure](#part1) > * [Part 2: How to save FCPX projects to desktop or external drives?](#part2) > * [Part 3: Where to find missing files or projects in final cut pro?](#part3) > * [Part 3: How to use Batch Export to save multiple projects in FCPX?](#part3) ## **Part 1: The autosave mechanism of Final Cut Pro X and manual storage procedure** In this section, get some mind-blowing facts on the autosave and manual options on the Final Cut Pro app! The FCP tool autosaves the changes every 15 minutes. The saved projects are available in the libraries file as a backup for the restore process. You can go to the library folder to view the autosaved projects. The last edited changes can be reflected by tapping the undo option in the Edit menu. Stepwise instructions to modify the autosave settings in the FCPX program Step 1: Launch the FCPX app, press Ctrl+Q to open the ‘User Preferences’ window. Step 2: In the ‘User Preferences’ screen, you can find a wide range of options to modify. Alter the levels of Undo, autosave vault attributes according to your needs, and save the changes. You can witness these parameters in the General section in the User Preference screen. Use the User Preference window to make necessary changes according to your requirement. BY default, the Autosave Vault is enabled, and you can work on the projects without any hesitation. Additionally, you can modify the attributes like ‘Save a copy for every’, ‘ Keep at most’, and ‘Maximum of’ to personalize your projects. ![auto-save](https://images.wondershare.com/filmora/images/final-cut-pro/auto-save.jpg) When the FCP file is open, you need not worry about the saving procedure. The app triggers the autosave mechanism for regular intervals, and the changes will be up-to-date. If you want to store the files manually, then work with its library files. A simple operation like Ctrl+c and Ctrl+v helps you to move the autosaved projects to any storage location. Here are few tips to restore the autosaved FCP files. Detailed guidelines on the restoration of autosaved files. Step 1 Open the Final Cut Pro app on your device. Step 2 Tap the ‘Libraries Sidebar’ to choose the desired library for restore action. Now hit File -> Open Library -> Backup options on the screen. Step 3 Surf the backup files and choose the desired one that requires a view. Press the Restore from’ option from the pop-up items. Finally, press the ‘Open’ button. ![from-backup](https://images.wondershare.com/filmora/images/final-cut-pro/from-backup.jpg) The manual storage option is feasible only after deactivating the autosave mechanism on the FCPX tool. It is not advisable to carry out this activity. The autosave option keeps your works up-to-date, and you will not miss the recent changes at any cost. You can still disable the autosave option to try the manual storage process. In the FCPX app, press ‘File -> Library Properties’, then from the displayed items, select the ‘Modify Settings’ option beside the ‘Storage Location’ label. Now, in the backups option select ‘Do not Save’ to deactivate the autosave mechanism. ![modify-storage-location](https://images.wondershare.com/filmora/images/final-cut-pro/modify-storage-location.jpg) After completing this procedure, save the changes and get back to the working timeline of FCPX to continue with your projects. When you edit any projects use the save option without fail else the changes made will be lost in no time. ## **Part 2: How to save FCPX projects to desktop or external drives?** Many experts recommend opting for an external storage location to save the FCPX files. It occupies more space, and you need to be careful while selecting the drives to store the library files of the FCPX projects. While saving the files, remove the generated data to optimize the storage process. First, remove the generated files in the library Step 1: Tap the Libraries sidebar in the FCPX tool and select ‘Library’ and choose the ’Cache’ option in the property window of Library. Step 2: Next, press ‘File -> Delete Generated Library Files’. To remove the unnecessary generated files. ![delete-generated-files](https://images.wondershare.com/filmora/images/final-cut-pro/delete-generated-files.jpg) The above action helps to clear up the space occupied by the project. If you want to free up more space, then delete most of the listed generated files. Secondly, now transfer the FCPX project to external drives. Step 1 Select the Libraries Sidebar in the FCPX program and choose the desired ‘Library’. Then hit ‘File -> Reveal in Finder. Now, the file opens in the new finder window. Step 2 Close the FCPX screen and drag the library files from the Finder window to the external hard drive. ![reveal-in-finder](https://images.wondershare.com/filmora/images/final-cut-pro/reveal-in-finder.jpg) Finally, you had made it. The FCPX projects were successfully moved on to the external drives quickly. Use the above technique to carry out flawless storage or transfer process. ## **Part 3: Where to find missing files or projects in final cut pro?** Many users feel that their project files were lost in the event of renaming. It becomes a missed file, and they will feel that the files were no were on their system. To handle this scenario, you must learn to think out of the box. You can use the relink technique to find the missed files in the Final Cut Pro app. The procedure is like the method of searching a particular file in your system using the ‘Search’ option. Here, Relink file functionality is available to set up a link again with the lost file to get back its storage space. Open the application and select the clip you want to discover. Go to the File menu on the title bar and choose Relink File option from the expanded items. A bunch of files will be displayed below, and you can choose the desired missed file from the collections. There are options to filter the discovered files by choosing between Missing and All options. Click the ‘Locate All’ button available at the bottom right side of the screen and navigate the folders to link with the perfect file. Press the ‘Choose’ button after selecting the missed file from the list. From the selected options, The Final Cut Pro application analyses all the attributes in the files and lists out the original files. Now hit the ‘Relink Files’ option to complete the file hunt process. ![missing-relink-files](https://images.wondershare.com/filmora/images/final-cut-pro/missing-relink-files.jpg) ## **Part 4: How to use Batch Export to save multiple projects in FCPX?** Perform the batch export for the files that carry similar settings. You can proceed with the flawless export procedure when the project files have the same roles, captions, and settings. The export option becomes limited if the project contains a mix of these attributes. Batch Export is the processing of sharing multiple files to desired storage space from your app ambiance. Appropriate clicks on the correct controls simplify the task. This procedure requires special attention because there is a chance of data loss when you handle bulk files at a time. The purpose of opting for the bunch export option is that you can complete the transfer tasks quickly. Exporting individual files is time-consuming and requires many clicks to move the desired files to the respective destination. This Batch Export feature in FCPX program enhances the users while working with many files. Step 1 Launch the FCPX app on your device. Step 2 In the Libraries sidebar, tap the library option, and select the desired projects that require the batch export. Step 1 Now, click the File -> Share option to trigger the export process. ![share-export-file](https://images.wondershare.com/filmora/images/final-cut-pro/share-export-file.jpg) It is advisable to export the Master files to retain the quality of the project. You can share the projects without compromising their quality factors. ## **Conclusion** As you all know that saving a project after successful completion is a crucial action. Few designers, editors, and developers unknowingly ignore this step. There are many applications embeds automatic saving function to enhance the editors to store their finished tasks. Thus, this article had given valuable insights on how to save the FCPX projects and the methods to backup and restore them. You had acquired an idea about the effective way to spot the missed project files. Finally, tips and tricks associated with the batch export were discussed to ensure flawless bulk file sharing in the secure channel. Use the above content to work comfortably with the FCPX app. Stay tuned to this article to discover enlightening facts on the Final Cut Pro application. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox ##### Shanoon Cox Mar 27, 2024• Proven solutions aIn the Final Cut Pro, you can find the autosave option to store the changes made on the file automatically without any manual intervention. To overcome the manual mechanism, the autosave feature in the FCP app keeps the last changes on the file precisely. In this article, you can find insightful ideas about the autosave mechanism and the manual storage process. In addition, you will learn how to save the finished projects on the external drives effortlessly. A detailed focus on saving the completed projects on the Final Cut Pro app has been highlighted in the below content. Synopsis on the usage of batch export and discovery of the missing files are discussed to enlighten you with the essential data. > * [Part 1: The autosave mechanism of FCPX and manual storage procedure](#part1) > * [Part 2: How to save FCPX projects to desktop or external drives?](#part2) > * [Part 3: Where to find missing files or projects in final cut pro?](#part3) > * [Part 3: How to use Batch Export to save multiple projects in FCPX?](#part3) ## **Part 1: The autosave mechanism of Final Cut Pro X and manual storage procedure** In this section, get some mind-blowing facts on the autosave and manual options on the Final Cut Pro app! The FCP tool autosaves the changes every 15 minutes. The saved projects are available in the libraries file as a backup for the restore process. You can go to the library folder to view the autosaved projects. The last edited changes can be reflected by tapping the undo option in the Edit menu. Stepwise instructions to modify the autosave settings in the FCPX program Step 1: Launch the FCPX app, press Ctrl+Q to open the ‘User Preferences’ window. Step 2: In the ‘User Preferences’ screen, you can find a wide range of options to modify. Alter the levels of Undo, autosave vault attributes according to your needs, and save the changes. You can witness these parameters in the General section in the User Preference screen. Use the User Preference window to make necessary changes according to your requirement. BY default, the Autosave Vault is enabled, and you can work on the projects without any hesitation. Additionally, you can modify the attributes like ‘Save a copy for every’, ‘ Keep at most’, and ‘Maximum of’ to personalize your projects. ![auto-save](https://images.wondershare.com/filmora/images/final-cut-pro/auto-save.jpg) When the FCP file is open, you need not worry about the saving procedure. The app triggers the autosave mechanism for regular intervals, and the changes will be up-to-date. If you want to store the files manually, then work with its library files. A simple operation like Ctrl+c and Ctrl+v helps you to move the autosaved projects to any storage location. Here are few tips to restore the autosaved FCP files. Detailed guidelines on the restoration of autosaved files. Step 1 Open the Final Cut Pro app on your device. Step 2 Tap the ‘Libraries Sidebar’ to choose the desired library for restore action. Now hit File -> Open Library -> Backup options on the screen. Step 3 Surf the backup files and choose the desired one that requires a view. Press the Restore from’ option from the pop-up items. Finally, press the ‘Open’ button. ![from-backup](https://images.wondershare.com/filmora/images/final-cut-pro/from-backup.jpg) The manual storage option is feasible only after deactivating the autosave mechanism on the FCPX tool. It is not advisable to carry out this activity. The autosave option keeps your works up-to-date, and you will not miss the recent changes at any cost. You can still disable the autosave option to try the manual storage process. In the FCPX app, press ‘File -> Library Properties’, then from the displayed items, select the ‘Modify Settings’ option beside the ‘Storage Location’ label. Now, in the backups option select ‘Do not Save’ to deactivate the autosave mechanism. ![modify-storage-location](https://images.wondershare.com/filmora/images/final-cut-pro/modify-storage-location.jpg) After completing this procedure, save the changes and get back to the working timeline of FCPX to continue with your projects. When you edit any projects use the save option without fail else the changes made will be lost in no time. ## **Part 2: How to save FCPX projects to desktop or external drives?** Many experts recommend opting for an external storage location to save the FCPX files. It occupies more space, and you need to be careful while selecting the drives to store the library files of the FCPX projects. While saving the files, remove the generated data to optimize the storage process. First, remove the generated files in the library Step 1: Tap the Libraries sidebar in the FCPX tool and select ‘Library’ and choose the ’Cache’ option in the property window of Library. Step 2: Next, press ‘File -> Delete Generated Library Files’. To remove the unnecessary generated files. ![delete-generated-files](https://images.wondershare.com/filmora/images/final-cut-pro/delete-generated-files.jpg) The above action helps to clear up the space occupied by the project. If you want to free up more space, then delete most of the listed generated files. Secondly, now transfer the FCPX project to external drives. Step 1 Select the Libraries Sidebar in the FCPX program and choose the desired ‘Library’. Then hit ‘File -> Reveal in Finder. Now, the file opens in the new finder window. Step 2 Close the FCPX screen and drag the library files from the Finder window to the external hard drive. ![reveal-in-finder](https://images.wondershare.com/filmora/images/final-cut-pro/reveal-in-finder.jpg) Finally, you had made it. The FCPX projects were successfully moved on to the external drives quickly. Use the above technique to carry out flawless storage or transfer process. ## **Part 3: Where to find missing files or projects in final cut pro?** Many users feel that their project files were lost in the event of renaming. It becomes a missed file, and they will feel that the files were no were on their system. To handle this scenario, you must learn to think out of the box. You can use the relink technique to find the missed files in the Final Cut Pro app. The procedure is like the method of searching a particular file in your system using the ‘Search’ option. Here, Relink file functionality is available to set up a link again with the lost file to get back its storage space. Open the application and select the clip you want to discover. Go to the File menu on the title bar and choose Relink File option from the expanded items. A bunch of files will be displayed below, and you can choose the desired missed file from the collections. There are options to filter the discovered files by choosing between Missing and All options. Click the ‘Locate All’ button available at the bottom right side of the screen and navigate the folders to link with the perfect file. Press the ‘Choose’ button after selecting the missed file from the list. From the selected options, The Final Cut Pro application analyses all the attributes in the files and lists out the original files. Now hit the ‘Relink Files’ option to complete the file hunt process. ![missing-relink-files](https://images.wondershare.com/filmora/images/final-cut-pro/missing-relink-files.jpg) ## **Part 4: How to use Batch Export to save multiple projects in FCPX?** Perform the batch export for the files that carry similar settings. You can proceed with the flawless export procedure when the project files have the same roles, captions, and settings. The export option becomes limited if the project contains a mix of these attributes. Batch Export is the processing of sharing multiple files to desired storage space from your app ambiance. Appropriate clicks on the correct controls simplify the task. This procedure requires special attention because there is a chance of data loss when you handle bulk files at a time. The purpose of opting for the bunch export option is that you can complete the transfer tasks quickly. Exporting individual files is time-consuming and requires many clicks to move the desired files to the respective destination. This Batch Export feature in FCPX program enhances the users while working with many files. Step 1 Launch the FCPX app on your device. Step 2 In the Libraries sidebar, tap the library option, and select the desired projects that require the batch export. Step 1 Now, click the File -> Share option to trigger the export process. ![share-export-file](https://images.wondershare.com/filmora/images/final-cut-pro/share-export-file.jpg) It is advisable to export the Master files to retain the quality of the project. You can share the projects without compromising their quality factors. ## **Conclusion** As you all know that saving a project after successful completion is a crucial action. Few designers, editors, and developers unknowingly ignore this step. There are many applications embeds automatic saving function to enhance the editors to store their finished tasks. Thus, this article had given valuable insights on how to save the FCPX projects and the methods to backup and restore them. You had acquired an idea about the effective way to spot the missed project files. Finally, tips and tricks associated with the batch export were discussed to ensure flawless bulk file sharing in the secure channel. Use the above content to work comfortably with the FCPX app. Stay tuned to this article to discover enlightening facts on the Final Cut Pro application. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://video-content-creator.techidaily.com/new-split-and-trim-3gp-files-in-minutes-2023-guide/"><u>New Split and Trim 3GP Files in Minutes 2023 Guide</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-highlight-video-creation-made-easy-top-desktop-and-mobile-software-for-2024/"><u>Updated Highlight Video Creation Made Easy Top Desktop and Mobile Software for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-unlock-your-music-expert-advice-on-converting-soundcloud-to-mp3-for-2024/"><u>Updated Unlock Your Music Expert Advice on Converting Soundcloud to MP3 for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/windows-10-photos-not-your-cup-of-tea-try-these-8-alternatives-instead-for-2024/"><u>Windows 10 Photos Not Your Cup of Tea? Try These 8 Alternatives Instead for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-secure-your-videos-how-to-blur-faces-with-pro-editing-software-for-2024/"><u>New Secure Your Videos How to Blur Faces with Pro Editing Software for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-time-saving-tips-how-to-speed-up-or-slow-down-videos-in-camtasia/"><u>Updated Time-Saving Tips How to Speed Up or Slow Down Videos in Camtasia</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-top-cartoon-animation-software-for-mobile-devices/"><u>New Top Cartoon Animation Software for Mobile Devices</u></a></li> <li><a href="https://video-content-creator.techidaily.com/in-2024-unlocking-compressors-power-in-final-cut-pro-x/"><u>In 2024, Unlocking Compressors Power in Final Cut Pro X</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-in-2024-the-art-of-storytelling-10-famous-movies-shaped-by-final-cut-pros-creative-freedom/"><u>Updated In 2024, The Art of Storytelling 10 Famous Movies Shaped by Final Cut Pros Creative Freedom</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-video-editing-face-off-premiere-pro-vs-after-effects-whats-the-best-choice/"><u>New Video Editing Face-Off Premiere Pro vs After Effects - Whats the Best Choice?</u></a></li> <li><a href="https://video-content-creator.techidaily.com/2024-approved-the-next-generation-of-video-editing-software-10plus-alternatives/"><u>2024 Approved The Next Generation of Video Editing Software 10+ Alternatives</u></a></li> <li><a href="https://video-content-creator.techidaily.com/in-2024-subtitle-edit-not-your-cup-of-tea-try-these-mac-friendly-alternatives/"><u>In 2024, Subtitle Edit Not Your Cup of Tea? Try These Mac-Friendly Alternatives</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-2024-approved-this-article-lists-10-cool-plugins-for-final-cut-pro-they-range-in-price-but-each-creates-effects-you-just-cant-get-any-other-way/"><u>Updated 2024 Approved This Article Lists 10 Cool Plugins for Final Cut Pro. They Range in Price, but Each Creates Effects You Just Cant Get Any Other Way</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-in-2024-windows-movie-maker-essentials-editing-and-enhancing-your-videos/"><u>Updated In 2024, Windows Movie Maker Essentials Editing and Enhancing Your Videos</u></a></li> <li><a href="https://video-content-creator.techidaily.com/unlock-facebook-video-success-understanding-aspect-ratios-and-dimensions-for-2024/"><u>Unlock Facebook Video Success Understanding Aspect Ratios and Dimensions for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-2024-approved-unleash-your-creativity-3-simple-video-game-recording-tools/"><u>New 2024 Approved Unleash Your Creativity 3 Simple Video Game Recording Tools</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-2024-approved-unlocking-cloud-stop-motion-essential-features-tips-and-alternatives/"><u>Updated 2024 Approved Unlocking Cloud Stop Motion Essential Features, Tips, and Alternatives</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-replace-imovie-with-these-top-rated-windows-10-video-editors-for-2024/"><u>New Replace iMovie with These Top-Rated Windows 10 Video Editors for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-in-2024-the-art-of-effective-lower-thirds-in-final-cut-pro-x/"><u>New In 2024, The Art of Effective Lower Thirds in Final Cut Pro X</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-in-2024-time-lapse-mastery-a-step-by-step-guide-to-final-cut-pro/"><u>Updated In 2024, Time Lapse Mastery A Step-by-Step Guide to Final Cut Pro</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-in-2024-free-and-fantastic-the-top-mov-movie-editing-software/"><u>New In 2024, Free and Fantastic The Top MOV Movie Editing Software</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-2024-approved-edit-like-a-pro-setting-up-your-computer-for-premiere-pro/"><u>New 2024 Approved Edit Like a Pro Setting Up Your Computer for Premiere Pro</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-in-2024-instagram-video-dimensions-decoded-what-you-need-to-know/"><u>Updated In 2024, Instagram Video Dimensions Decoded What You Need to Know</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-in-2024-shrink-your-videos-10-best-free-online-compression-tools/"><u>New In 2024, Shrink Your Videos 10 Best Free Online Compression Tools</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-2024-approved-6-best-free-online-imovie-alternatives/"><u>Updated 2024 Approved 6 Best Free Online iMovie Alternatives</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-the-art-of-cinematic-video-production-a-final-cut-pro-x-tutorial-for-2024/"><u>Updated The Art of Cinematic Video Production A Final Cut Pro X Tutorial for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/in-2024-xml-for-fcpx-beginners-and-beyond-a-comprehensive-resource/"><u>In 2024, XML for FCPX Beginners and Beyond A Comprehensive Resource</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-2024-approved-unleash-your-creativity-35-top-video-editors-for-every-operating-system/"><u>Updated 2024 Approved Unleash Your Creativity 35 Top Video Editors for Every Operating System</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-nikon-video-workflow-efficient-editing-techniques-for-stunning-videos/"><u>Updated Nikon Video Workflow Efficient Editing Techniques for Stunning Videos</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-2024-approved-tiktok-watermark-remover-reviews-find-the-best-one-for-you/"><u>Updated 2024 Approved TikTok Watermark Remover Reviews Find the Best One for You</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-unshaking-the-camera-a-step-by-step-guide-to-video-stabilization-in-premiere-pro/"><u>Updated Unshaking the Camera A Step-by-Step Guide to Video Stabilization in Premiere Pro</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-2024-approved-produce-high-quality-videos-on-your-mac-expert-techniques-and-strategies/"><u>Updated 2024 Approved Produce High-Quality Videos on Your Mac Expert Techniques and Strategies</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-cinematic-storytelling-with-final-cut-pro-x-tips-and-tricks-for-2024/"><u>Updated Cinematic Storytelling with Final Cut Pro X Tips and Tricks for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-in-2024-free-and-fabulous-the-best-fcpx-plugins-you-need/"><u>Updated In 2024, Free and Fabulous The Best FCPX Plugins You Need</u></a></li> <li><a href="https://video-content-creator.techidaily.com/in-2024-top-rated-aspect-ratio-changer-apps/"><u>In 2024, Top-Rated Aspect Ratio Changer Apps</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-top-mobile-apps-for-converting-videos-to-audio-files-2023-update-for-2024/"><u>Updated Top Mobile Apps for Converting Videos to Audio Files (2023 Update) for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-in-2024-the-ultimate-mp4-editor-for-windows-8-fast-and-user-friendly/"><u>Updated In 2024, The Ultimate MP4 Editor for Windows 8 Fast and User-Friendly</u></a></li> <li><a href="https://video-content-creator.techidaily.com/retro-video-magic-top-apps-for-applying-vhs-effects-on-mobile-for-2024/"><u>Retro Video Magic Top Apps for Applying VHS Effects on Mobile for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-2024-approved-top-rated-video-combination-tools-you-need-to-know/"><u>Updated 2024 Approved Top-Rated Video Combination Tools You Need to Know</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-the-simple-way-to-reverse-a-video-in-final-cut-pro-2023-edition-for-2024/"><u>Updated The Simple Way to Reverse a Video in Final Cut Pro 2023 Edition for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/in-2024-the-top-windows-video-editors-you-need-to-know-about/"><u>In 2024, The Top Windows Video Editors You Need to Know About</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-in-2024-no-cost-video-magic-the-best-online-editors-ranked/"><u>New In 2024, No-Cost Video Magic The Best Online Editors Ranked</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-in-2024-instagram-video-formatting-101-a-beginners-guide-to-aspect-ratios-and-dimensions/"><u>Updated In 2024, Instagram Video Formatting 101 A Beginners Guide to Aspect Ratios and Dimensions</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-in-2024-windows-1110-video-editing-top-imovie-alternative-software/"><u>New In 2024, Windows 11/10 Video Editing Top iMovie Alternative Software</u></a></li> <li><a href="https://video-content-creator.techidaily.com/new-crop-trim-and-share-a-quick-guide-to-kapwings-video-editor-for-2024/"><u>New Crop, Trim, and Share A Quick Guide to Kapwings Video Editor for 2024</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-2024-approved-get-ahead-with-fcp-top-5-editing-shortcuts-and-workarounds/"><u>Updated 2024 Approved Get Ahead with FCP Top 5 Editing Shortcuts and Workarounds</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-best-motorola-moto-g24-pattern-lock-removal-tools-remove-android-pattern-lock-without-losing-data-by-drfone-android/"><u>In 2024, Best Motorola Moto G24 Pattern Lock Removal Tools Remove Android Pattern Lock Without Losing Data</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/1713949933628-have-you-been-looking-for-online-youtube-video-trimmer-you-will-be-introduced-to-different-ways-to-trim-youtube-videos-as-introduced-by-youtube-itself-and-s/"><u>Have You Been Looking for Online YouTube Video Trimmer? You Will Be Introduced to Different Ways to Trim YouTube Videos as Introduced by YouTube Itself and some Online and Desktop Software to Help You Learn Video Trimming in This Article for 2024</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/new-the-best-tools-to-convert-text-to-mp3-with-the-best-natural-voices/"><u>New The Best Tools to Convert Text to MP3 With the Best Natural Voices</u></a></li> <li><a href="https://android-unlock.techidaily.com/rootjunky-apk-to-bypass-google-frp-lock-for-vivo-x-fold-2-by-drfone-android/"><u>Rootjunky APK To Bypass Google FRP Lock For Vivo X Fold 2</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/new-2024-approved-looking-for-the-best-slow-motion-effect-in-premiere-pro/"><u>New 2024 Approved Looking For The Best Slow Motion Effect in Premiere Pro</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/updated-unleash-creativity-the-10-most-popular-animated-text-creators-for-2024/"><u>Updated Unleash Creativity The 10 Most Popular Animated Text Creators for 2024</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/how-to-slow-down-a-video-on-iphone-and-android-the-easy-way/"><u>How to Slow Down a Video on iPhone and Android The Easy Way</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-apple-iphone-6-plus-apples-new-iphone-drfone-by-drfone-ios/"><u>In 2024, How to Unlock Apple iPhone 6 Plus, Apples New iPhone | Dr.fone</u></a></li> <li><a href="https://bypass-frp.techidaily.com/hassle-free-ways-to-remove-frp-lock-on-infinixwithwithout-a-pc-by-drfone-android/"><u>Hassle-Free Ways to Remove FRP Lock on Infinixwith/without a PC</u></a></li> <li><a href="https://change-location.techidaily.com/in-2024-how-to-get-and-use-pokemon-go-promo-codes-on-vivo-x90s-drfone-by-drfone-virtual-android/"><u>In 2024, How to Get and Use Pokemon Go Promo Codes On Vivo X90S | Dr.fone</u></a></li> <li><a href="https://animation-videos.techidaily.com/best-10-photo-animator-templates/"><u>Best 10 Photo Animator Templates</u></a></li> <li><a href="https://apple-account.techidaily.com/in-2024-how-to-remove-the-two-factor-authentication-on-iphone-6s-by-drfone-ios/"><u>In 2024, How To Remove the Two Factor Authentication On iPhone 6s</u></a></li> <li><a href="https://screen-mirror.techidaily.com/effective-guide-to-cast-apple-iphone-13-to-macbook-without-hindrance-drfone-by-drfone-ios/"><u>Effective Guide to Cast Apple iPhone 13 to MacBook without Hindrance | Dr.fone</u></a></li> <li><a href="https://activate-lock.techidaily.com/in-2024-how-to-bypass-icloud-by-checkra1n-even-from-iphone-13-mini-if-youve-tried-everything-by-drfone-ios/"><u>In 2024, How To Bypass iCloud By Checkra1n Even From iPhone 13 mini If Youve Tried Everything</u></a></li> <li><a href="https://ai-vdieo-software.techidaily.com/kinemaster-on-mac-download-install-and-start-editing/"><u>KineMaster on Mac Download, Install, and Start Editing</u></a></li> <li><a href="https://change-location.techidaily.com/ultimate-guide-to-catch-the-regional-located-pokemon-for-vivo-y27-4g-drfone-by-drfone-virtual-android/"><u>Ultimate Guide to Catch the Regional-Located Pokemon For Vivo Y27 4G | Dr.fone</u></a></li> <li><a href="https://sim-unlock.techidaily.com/how-to-check-if-your-samsung-galaxy-f15-5g-is-unlocked-by-drfone-android/"><u>How To Check if Your Samsung Galaxy F15 5G Is Unlocked</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/2024-approved-the-best-ways-to-convert-mp4-to-mp3-on-your-iphone-or-android-device/"><u>2024 Approved The Best Ways to Convert MP4 to MP3 on Your iPhone or Android Device</u></a></li> <li><a href="https://android-unlock.techidaily.com/a-complete-guide-to-oem-unlocking-on-asus-by-drfone-android/"><u>A Complete Guide To OEM Unlocking on Asus</u></a></li> <li><a href="https://blog-min.techidaily.com/how-to-play-hevc-h-265-video-on-defy-2-by-aiseesoft-video-converter-play-hevc-video-on-android/"><u>How to play HEVC H.265 video on Defy 2?</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/updated-2024-approved-flip-it-a-step-by-step-guide-to-rotating-clips-in-fcp/"><u>Updated 2024 Approved Flip It! A Step-by-Step Guide to Rotating Clips in FCP</u></a></li> <li><a href="https://fix-guide.techidaily.com/restore-missing-app-icon-on-honor-x8b-step-by-step-solutions-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Restore Missing App Icon on Honor X8b Step-by-Step Solutions | Dr.fone</u></a></li> <li><a href="https://unlock-android.techidaily.com/how-to-reset-gmail-password-on-vivo-v30-pro-devices-by-drfone-android/"><u>How to Reset Gmail Password on Vivo V30 Pro Devices</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/new-2024-approved-top-5-best-free-wmv-video-splitters/"><u>New 2024 Approved Top 5 Best Free WMV Video Splitters</u></a></li> <li><a href="https://animation-videos.techidaily.com/ultimate-guide-to-animated-characters-drawings-for-2024/"><u>Ultimate Guide to Animated Characters Drawings for 2024</u></a></li> <li><a href="https://screen-mirror.techidaily.com/8-best-apps-for-screen-mirroring-infinix-smart-7-hd-pc-drfone-by-drfone-android/"><u>8 Best Apps for Screen Mirroring Infinix Smart 7 HD PC | Dr.fone</u></a></li> <li><a href="https://howto.techidaily.com/what-to-do-when-realme-c67-4g-has-black-screen-of-death-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>What To Do When Realme C67 4G Has Black Screen of Death? | Dr.fone</u></a></li> <li><a href="https://ios-unlock.techidaily.com/in-2024-4-ways-to-unlock-apple-iphone-se-2022-to-use-usb-accessories-without-passcode-by-drfone-ios/"><u>In 2024, 4 Ways to Unlock Apple iPhone SE (2022) to Use USB Accessories Without Passcode</u></a></li> <li><a href="https://sim-unlock.techidaily.com/easily-unlock-your-xiaomi-redmi-13c-5g-device-sim-by-drfone-android/"><u>Easily Unlock Your Xiaomi Redmi 13C 5G Device SIM</u></a></li> <li><a href="https://fake-location.techidaily.com/how-to-fix-vivo-y28-5g-find-my-friends-no-location-found-drfone-by-drfone-virtual-android/"><u>How to Fix Vivo Y28 5G Find My Friends No Location Found? | Dr.fone</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-everything-you-need-to-know-about-lock-screen-settings-on-your-oppo-f25-pro-5g-by-drfone-android/"><u>In 2024, Everything You Need to Know about Lock Screen Settings on your Oppo F25 Pro 5G</u></a></li> <li><a href="https://blog-min.techidaily.com/how-to-electronically-sign-a-xltx-using-digisigner-by-ldigisigner-sign-a-excel-sign-a-excel/"><u>How to Electronically Sign a .xltx Using DigiSigner</u></a></li> <li><a href="https://howto.techidaily.com/android-screen-stuck-general-vivo-y78plus-partly-screen-unresponsive-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Android Screen Stuck General Vivo Y78+ Partly Screen Unresponsive | Dr.fone</u></a></li> <li><a href="https://howto.techidaily.com/fix-xiaomi-redmi-note-12t-pro-android-system-webview-crash-2024-issue-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Fix Xiaomi Redmi Note 12T Pro Android System Webview Crash 2024 Issue | Dr.fone</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/how-does-the-stardust-trade-cost-in-pokemon-go-on-motorola-g24-power-drfone-by-drfone-virtual-android/"><u>How does the stardust trade cost In pokemon go On Motorola G24 Power? | Dr.fone</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-10-easy-to-use-frp-bypass-tools-for-unlocking-google-accounts-on-poco-x5-by-drfone-android/"><u>In 2024, 10 Easy-to-Use FRP Bypass Tools for Unlocking Google Accounts On Poco X5</u></a></li> <li><a href="https://techidaily.com/how-to-reset-honor-magic-6-lite-without-the-home-button-drfone-by-drfone-reset-android-reset-android/"><u>How to Reset Honor Magic 6 Lite Without the Home Button | Dr.fone</u></a></li> <li><a href="https://android-location-track.techidaily.com/how-to-track-xiaomi-14-ultra-by-phone-number-drfone-by-drfone-virtual-android/"><u>How to Track Xiaomi 14 Ultra by Phone Number | Dr.fone</u></a></li> <li><a href="https://change-location.techidaily.com/where-is-the-best-place-to-catch-dratini-on-vivo-s18-drfone-by-drfone-virtual-android/"><u>Where Is the Best Place to Catch Dratini On Vivo S18 | Dr.fone</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-top-12-prominent-samsung-galaxy-a14-5g-fingerprint-not-working-solutions-by-drfone-android/"><u>In 2024, Top 12 Prominent Samsung Galaxy A14 5G Fingerprint Not Working Solutions</u></a></li> <li><a href="https://pokemon-go-android.techidaily.com/in-2024-ultimate-guide-to-get-the-meltan-box-pokemon-go-for-poco-c50-drfone-by-drfone-virtual-android/"><u>In 2024, Ultimate guide to get the meltan box pokemon go For Poco C50 | Dr.fone</u></a></li> <li><a href="https://location-fake.techidaily.com/3-ways-to-fake-gps-without-root-on-apple-iphone-11-pro-max-drfone-by-drfone-virtual-ios/"><u>3 Ways to Fake GPS Without Root On Apple iPhone 11 Pro Max | Dr.fone</u></a></li> <li><a href="https://phone-solutions.techidaily.com/3-best-tools-to-hard-reset-zte-axon-40-lite-drfone-by-drfone-reset-android-reset-android/"><u>3 Best Tools to Hard Reset ZTE Axon 40 Lite | Dr.fone</u></a></li> <li><a href="https://android-location.techidaily.com/in-2024-getting-the-pokemon-go-gps-signal-not-found-11-error-in-vivo-v29e-drfone-by-drfone-virtual/"><u>In 2024, Getting the Pokemon Go GPS Signal Not Found 11 Error in Vivo V29e | Dr.fone</u></a></li> </ul></div>
<template> <div style="width: 100%; height: 100%" class="d-flex flex-column align-center justify-space-between" > <template v-if="!done"> <p class="font-weight-light grey--text mt-6" :class="$vuetify.breakpoint.smAndDown ? 'subtitle-1' : 'title'" > Wait for the download to start... </p> <v-progress-circular indeterminate size="64" width="2" class="mt-6" /> </template> <template v-else> <p class="font-weight-light mt-6" :class="$vuetify.breakpoint.smAndDown ? 'subtitle-1' : 'title'" > Download complete </p> <v-icon v-if="done" color="green" size="128" class="mb-6" > {{ icons.mdiCheckCircle }} </v-icon> </template> </div> </template> <script lang="ts"> import { Vue, Component, Prop } from 'vue-property-decorator' import { convert } from '@/helpers/convert' import { mdiCheckCircle } from '@/helpers/icons' import * as FileSaver from 'file-saver' @Component export default class DownloadComponent extends Vue { icons = { mdiCheckCircle } @Prop() inputType!: string @Prop() inputFilename!: string @Prop() inputData!: ArrayBuffer @Prop() outputFormat!: string done = false mounted () { this.download() } async download () { this.done = false await new Promise(resolve => setTimeout(resolve, 500)) const blob = await convert(this.inputType, this.outputFormat, this.inputData) const filename = this.inputFilename.replace(/\.[^.]+$/, `.${this.outputFormat}`) FileSaver.saveAs(blob, filename) this.done = true this.$gtag.event(`download_image_${this.inputType}_to_${this.outputFormat}`, { event_category: 'download', // eslint-disable-line event_label: `Download ${this.inputType} to ${this.outputFormat} conversion` // eslint-disable-line }) } } </script>
print ("Hola Mundo") print(3+3-2) #no hace falta estacios ya que python pone los espacios entre los valores print("hola", "como estas") #str parsea a string print("hola", str(58)) #distintas formas de imprimir variables age = 35 print(f"edad: {age}") print("edad:", age) name = "Lucia" print(f"Nombre: {name}") #la funcion input permite ingresar datos por teclado y retorna strings pedirName = input("Ingrese su Nombre:") print(pedirName) #asi parseamos a int lo que ingresa por teclado el usuario age = int(input("Ingrese su edad:" )) print(age) #con end="" escribimos todo en una linea entro de las "" podemos usar el separador que queremos print("mi nombre es:",name,end=" ") print("Mi edad es:", age) #con type podemos saber el tipo de dato que le pasamos por parametro print(type(name)) #operador in y not in para saber si el valor pasado esta en la cadena print("L" in name) print("C" not in name) #potencia print(8**2) # Los bloques se indican por indentacion, no se usan llaves en funciones # Para sentencias de mas de 72 caracteres usamos barra invertida para indicar que sigue abajo o pongo los numeros entro de [] # Las variables no se escriben con camelCase se separan las palabras con _ # Usamos mayusculas para indicarnos entre programadores las constantes, en python no existen las constantes HOLA # En vez de usa i++ se usa i+=1 # los parametros de range son(desde donde, hasta donde, de a cuanto) for i in range(20,0,-1): print(i) for ltra in name: print (ltra)
package com.example.Giinie; import android.Manifest; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.widget.ImageButton; import android.view.View; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.EditText; import com.google.android.material.appbar.MaterialToolbar; import com.google.android.material.snackbar.Snackbar; import com.google.android.material.bottomnavigation.BottomNavigationView; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class HomeActivity extends AppCompatActivity { private RecyclerView recyclerViewServices; private HomeServiceAdapter serviceAdapter; private List<Service> allHomeServices; private TextView currentLocationTextView; private LocationManager locationManager; private LocationListener locationListener; private Geocoder geocoder; private boolean isLocationPermissionGranted = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); long userId = getIntent().getLongExtra("userId", 0); MaterialToolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Enable the back button on the toolbar ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_back); // Set your back icon here } // Load the default fragment (HomeFragment) when the activity is created loadFragment(new HomeFragment()); recyclerViewServices = findViewById(R.id.recyclerViewServices); recyclerViewServices.setLayoutManager(new GridLayoutManager(this, 3)); // Initialize the database helper DatabaseHelper dbHelper = new DatabaseHelper(this); // Fetch services from the database allHomeServices = dbHelper.getAllServices(); // Initialize the class-level allHomeServices list // Create the HomeServiceAdapter and set it to the RecyclerView serviceAdapter = new HomeServiceAdapter(allHomeServices, new HomeServiceAdapter.OnItemClickListener() { @Override public void onItemClick(Service service) { openServiceDetails(service.getName()); } }); recyclerViewServices.setAdapter(serviceAdapter); EditText searchEditText = findViewById(R.id.searchEditText); searchEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { Log.d("Search", "Search query: " + charSequence.toString()); filterServices(charSequence.toString()); } @Override public void afterTextChanged(Editable editable) {} }); // Initialize the currentLocationTextView currentLocationTextView = findViewById(R.id.currentLocationTextView); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(@NonNull Location location) { updateCurrentLocation(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} @Override public void onProviderDisabled(String provider) {} }; // Create the Geocoder instance geocoder = new Geocoder(this, Locale.getDefault()); // Request location updates if (isLocationPermissionGranted()) { startLocationUpdates(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1); } // Initialize the bottom navigation view and set the item selection listener BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation); bottomNavigationView.setOnNavigationItemSelectedListener(item -> { int itemId = item.getItemId(); if (itemId == R.id.menu_home) { loadFragment(new HomeFragment()); return true; } else if (itemId == R.id.menu_cart) { // Navigate to CartActivity Intent intent = new Intent(HomeActivity.this, CartActivity.class); startActivity(intent); return true; } else if (itemId == R.id.menu_orders) { // Navigate to OrdersActivity Intent ordersIntent = new Intent(HomeActivity.this, OrdersActivity.class); startActivity(ordersIntent); return true; } else if (itemId == R.id.menu_settings) { // Navigate to SettingsActivity Intent settingsIntent = new Intent(HomeActivity.this, SettingsActivity.class); startActivity(settingsIntent); return true; } return false; }); // Find the chat button ImageButton chatButton = findViewById(R.id.chatFab); // Set a click listener for the chat button chatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openChatScreen(); } }); // Show "Need help?" text after a delay showNeedHelpText(); } private void filterServices(String query) { List<Service> filteredServices = new ArrayList<>(); for (Service service : allHomeServices) { if (service.getName().toLowerCase().contains(query.toLowerCase())) { filteredServices.add(service); } } serviceAdapter.updateServices(filteredServices); } // Method to show "Need help?" text after a delay private void showNeedHelpText() { new Handler().postDelayed(new Runnable() { @Override public void run() { TextView needHelpTextView = findViewById(R.id.needHelpTextView); needHelpTextView.setVisibility(View.VISIBLE); } }, 3000); // Delay in milliseconds (3 seconds) } // Inflate the menu to add items to the action bar (top toolbar) @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.bottom_navigation_menu, menu); return true; } // Handle actions when items in the action bar (top toolbar) are clicked @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_cart) { // Navigate to CartActivity Intent intent = new Intent(HomeActivity.this, CartActivity.class); startActivity(intent); return true; } if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } private boolean isLocationPermissionGranted() { return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; } private void startLocationUpdates() { try { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); isLocationPermissionGranted = true; } catch (SecurityException e) { // Handle the case when the location permission is not available showPermissionDeniedMessage(); } } private void updateCurrentLocation(Location location) { if (location != null) { double latitude = location.getLatitude(); double longitude = location.getLongitude(); // Get the address from the latitude and longitude String address = getAddressFromLocation(latitude, longitude); currentLocationTextView.setText("Current Location:\n" + address); currentLocationTextView.setGravity(Gravity.LEFT); // Set gravity to left } else { // Handle the case when the location is not available currentLocationTextView.setText("Current Location: N/A"); currentLocationTextView.setGravity(Gravity.LEFT); // Set gravity to left } } private String getAddressFromLocation(double latitude, double longitude) { try { List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); StringBuilder sb = new StringBuilder(); for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) { sb.append(address.getAddressLine(i)); if (i < address.getMaxAddressLineIndex()) { sb.append(", "); } } return sb.toString(); } } catch (IOException e) { e.printStackTrace(); } return "Address not found"; } // Handle the result of location permission request @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { // Permission granted, start location updates startLocationUpdates(); } else { // Permission denied, show a message to the user showPermissionDeniedMessage(); } } } private void showPermissionDeniedMessage() { // Use Snackbar to show the message Snackbar.make(findViewById(android.R.id.content), "Location permission is required to use this app", Snackbar.LENGTH_INDEFINITE) .setAction("Grant Permission", new View.OnClickListener() { @Override public void onClick(View v) { // Request location permission again ActivityCompat.requestPermissions(HomeActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1); } }) .show(); } private void openServiceDetails(String serviceName) { Intent intent = new Intent(this, ServiceDetailsActivity.class); intent.putExtra("service_name", serviceName); startActivity(intent); } private void loadFragment(Fragment fragment) { // Replace the current fragment with the given fragment FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, fragment); transaction.addToBackStack(null); transaction.commit(); } private void openChatScreen() { Intent intent = new Intent(this, ChatActivity.class); startActivity(intent); } // Stop location updates when the activity is stopped @Override protected void onStop() { super.onStop(); if (isLocationPermissionGranted) { locationManager.removeUpdates(locationListener); } } }
/* ------------------- Author:Bobby Date: 04/01/2022 ------------------- */ //Time complexity O(N*log(N)) //space complexity O(1) class Solution { private: bool isPossible(vector<int>& nums,int target,int mid){ int n=nums.size(); long long int sum=0; for(int i=0;i<mid;i++){ sum+=nums[i]; } if(sum>=target) return true; for(int i=mid;i<n;i++){ sum+=nums[i]; sum-=nums[i-mid]; if(sum>=target) {return true;break;} } return false; } public: int minSubArrayLen(int target, vector<int>& nums) { int n=nums.size(); int low=0; int high=n; int ans=0; while(low<=high){ long long mid=low+(high-low)/2; if(isPossible(nums,target,mid)){ ans=mid; high=mid-1; } else low=mid+1; } return ans; } };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../css/main.css"> <link rel="stylesheet" href="../css/header.css"> <link rel="stylesheet" href="../css/formulario.css"> <script defer src="../js/empleados/empleado.js" type="module"></script> <title>Empleado</title> </head> <body> <!--* menu del sitio --> <header class="header"> <nav class="navegacion"> <a href="../index.html" class="logo"> <img src="../img/foto-mia.jpg" width="50px" alt="logo"> <div class="logo"> Rol de Pagos </div> </a> <ul class="menu"> <li><a href="./cargo.html">Cargos</a></li> <li><a href="./departamento.html">Departamentos</a></li> <li><a href="./empleado.html">Empleados</a></li> </ul> </nav> </header> <main> <section class="form-container"> <div class="form-header"> <h2>FORMULARIO DE EMPLEADOS</h2> </div> <form id="form-empleado" class="form"> <div class="form-group"> <label for="descripcion">Nombre</label> <input type="text" class = "nombre" name="nombre" id="nombre" placeholder="Ingrese un Nombre" title="nombre del empleado" pattern="^[A-zÑñáéíóú]+((\s[A-zÑñáéíóú]+)?)+$" required /> </div> <div class="form-group"> <label for="cedula">Cedula</label> <input type="text" class = "cedula" name="cedula" id="cedula" placeholder="Ingresa la cedula del empleado" title="cedula del empleado" pattern="^[0-9]{10,10}$" required /> </div> <div class="form-group"> <label for="cargo">Cargo</label> <select name="cargo" class="cargo" id="cargo" required> </select> </div> <div class="form-group"> <label for="departamento">Departamento</label> <select name="departamento" class="departamento" id="departamento" required> </select> </div> <div class="form-group"> <label for="sueldo">Sueldo</label> <input type="number" class="sueldo" name="sueldo" id="sueldo" placeholder="sueldo" title="El sueldo deber ser de al menos tres cifras" min="100" step="any" required /> </div> <div class="form-check"> <label>Activo <input type="checkbox" class="estado" id="estado" value="activo" checked /> </label> </div> <button id="enviar" type="submit" name="enviar"> Insertar </button> </form> <div class="consulta none table-responsive" id="consulta"> <h3>Listado de Empleados</h3> <table class="consulta-empleados" id="consulta-empleados" border="1"> <thead> <tr> <th>#</th> <th>NOMBRE</th> <th>CEDULA</th> <th>CARGO</th> <th>DEPARTAMENTO</th> <th>SUELDO</th> <th>ESTADO</th> <th>ACCIONES</th> </tr> </thead> <tbody class="detalle-est" id="detalle-empleados"> <!-- <tr> <td>1</td> <td>Analista</td> <td>Activo</td> <td> <button>✏️</button> <button>❌</button> </td> </tr> --> </tbody> </table> </div> </section> </main> </body> </html>
import { IMMPosterRef } from '@wmeimob/taro-poster/src/components/poster' import { useRef } from 'react' import { isPrd } from '../../../../config' import { useToast } from '@wmeimob/taro-design/src/layout/pageContainer' import { api } from '@wmeimob/taro-api' import { GoodsVO } from '@wmeimob/taro-api' import { routeNames } from '../../../../routes' import { EGoodsType } from '@wmeimob/shop-data/goods/enums/EGoodsType' const posterStyle = { width: 335, height: 510 } /** * 海报生成业务逻辑 * @param data * @returns */ export default function useGoodPoster(data: GoodsVO) { const posterRef = useRef<IMMPosterRef>(null) const [toast] = useToast() function getPriceText() { const [int = '', dot] = `${data.salePrice}`.split('.') const common = { left: 0, top: 0, fontWeight: 'bold', color: '#FF413B' } const isIntegralGoods = data.goodsType === EGoodsType.Integral // 纯积分 const integral = [ { type: 'text', value: `${data.exchangeIntegral}`, style: { ...common, fontSize: 24 } }, { type: 'text', value: '积分', style: { ...common, top: 8, fontSize: 14 } } ] // 纯金额 const price = [ { type: 'text', value: `¥`, style: { ...common, top: 8, fontSize: 14 } }, { type: 'text', value: `${int}`, style: { ...common, fontSize: 24 } }, { type: 'text', value: `.${dot || '00'}`, style: { ...common, top: 9, fontSize: 14 } } ] // 加号 const plus = [{ type: 'text', value: ` + `, style: { ...common, top: 9, fontSize: 12 } }] // 金额+积分 const priceAndIntegral = [...price, ...plus, ...integral] return [ // 普通商品 { hit: !isIntegralGoods, value: price }, // 积分商品 纯积分 { hit: isIntegralGoods && !data.salePrice, value: integral }, // 积分商品 金额+积分 { hit: isIntegralGoods && data.salePrice, value: priceAndIntegral } ].find((item) => item.hit)!.value } async function draw() { toast?.loading('海报生成中...') try { // 获取小程序二维码 let { data: qrcode = '' } = await api['/wechat/api/qrCode/getUnlimited_POST']({ page: routeNames.goodsGoodDetail.slice(1), scene: `${data.goodsNo}`, version: isPrd ? 'release' : 'trial' }) if (qrcode) { qrcode = /^data:image/.test(qrcode) ? qrcode : `data:image/png;base64,${qrcode}` } // 绘制海报 await posterRef.current!.draw([ { type: 'image', value: data.coverImg!, style: { left: 0, top: 0, width: 335, height: 335 } }, { type: 'text', value: data.goodsName!, style: { left: 20, top: 355, width: posterStyle.width - 30, fontSize: 15, color: '#333333', lineHeight: 20, fontWeight: 'bold' } }, { type: 'list', value: getPriceText() as any, style: { left: 20, top: 355 + 20 + 8, fontSize: 24, color: '#FF413B', fontWeight: 'bold' } }, // { // type: 'text', // value: `¥${data.salePrice}`, // style: { right: 15, top: 365, fontSize: 24, color: '#F01520', lineHeight: 28, fontWeight: 'bold' } // }, // { // type: 'text', // value: `¥${data.marketPrice}`, // style: { right: 22, top: 378, fontSize: 12, color: '#999999', lineHeight: 28 } // }, { type: 'text', value: '1.保存图片到相册', style: { left: 116, top: 355 + 20 + 8 + 24 + 20 + 10, fontSize: 12, color: '#999999', lineHeight: 20 } }, { type: 'text', value: '2.打开微信识别二维码', style: { left: 116, top: 355 + 20 + 8 + 24 + 20 + 20 + 10 + 5, fontSize: 12, color: '#999999', lineHeight: 20 } }, { type: 'image', value: qrcode, style: { left: 20, top: 355 + 20 + 8 + 24 + 8, width: 80, height: 80 } } ]) await posterRef.current!.getImageSrc() posterRef.current!.show() } catch (error) {} toast?.hideLoading() } return { /** ref */ posterRef, /** 绘制方法 */ draw, /** 画布宽高 */ posterStyle } }
import { Column, Entity } from "typeorm"; import { ApiProperty } from "@nestjs/swagger"; @Entity() export class Address { @Column() @ApiProperty({ type: "string", example: "'573 route d", description: "The address of the sales-point", }) street: string; @Column() @ApiProperty({ type: "string", example: "Nice", description: "The city of the sales-point", }) city: string; @Column() @ApiProperty({ type: "string", example: "06410", description: "The city of the sales-point", }) postalCode: string; }
import { useRef } from "react"; import { useState } from "react"; import { AnimatePresence, motion } from "framer-motion"; import { Squash as Hamburger } from "hamburger-react"; import { routes } from "@/lib/constant"; import Link from "next/link"; export const NavMobile = () => { const [isOpen, setOpen] = useState(false); const ref = useRef(null); return ( <div ref={ref} className="lg:hidden "> <Hamburger toggled={isOpen} size={20} toggle={setOpen} /> <AnimatePresence> {isOpen && ( <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.2 }} className="fixed left-0 shadow-4xl right-0 top-20 bottom-0 p-5 pt-0 bg-background border-b border-b-white/20" > <ul className="grid gap-2 "> {routes.map((route, idx) => { const { Icon } = route; return ( <motion.li initial={{ scale: 0, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} transition={{ type: "spring", stiffness: 260, damping: 20, delay: 0.1 + idx / 10, }} key={route.title} className="w-full p-[0.08rem] rounded-xl" > <Link onClick={() => setOpen((prev) => !prev)} className={ "flex items-center justify-between w-full p-5 rounded-xl " } href={route.href} > <span className="flex gap-1 text-lg">{route.title}</span> <Icon className="text-xl" /> </Link> </motion.li> ); })} </ul> </motion.div> )} </AnimatePresence> </div> ); };
import meow from "meow"; import inquirer from "inquirer"; import { runTransformsOnChromeRecording } from "../transform.js"; import { expandedFiles } from "../utils.js"; import { InquirerAnswerTypes } from "../types"; const cli = meow( ` Usage $ npx webpagetest-chrome-recorder <path-of-recording.json> [options] Options -d, --dry Dry run the output of the transformed recordings -o, --output Output location of the files generated by the exporter Examples $ npx webpagetest-chrome-recorder recordings.json $ npx webpagetest-chrome-recorder recordings/*.json `, { importMeta: import.meta, flags: { dry: { type: "boolean", alias: "d", }, output: { type: "string", alias: "o", }, }, } ); inquirer .prompt([ { type: "input", name: "files", message: "Enter directory or files that should be converted from Recorder JSON to Webpagetest:", default: ".", when: () => !cli.input.length, filter(files: string) { return new Promise((resolve) => { resolve(files.split(/\s+/).filter((f) => f.trim().length > 0)); }); }, }, { type: "input", name: "outputPath", message: "Mention the output directory name?", when: () => !cli.flags.dry && !cli.flags.output, default: "webpagetest", }, ]) .then((answers: InquirerAnswerTypes) => { const { files: recordingFiles, outputPath: outputFolder } = answers; const files = cli.input.length ? cli.input : recordingFiles; const filesExpanded = expandedFiles(files); if (!filesExpanded) { console.log(`No recording files found matching ${files.join(" ")}`); return null; } const outputPath = cli.flags?.output?.length ? cli.flags.output : outputFolder; return runTransformsOnChromeRecording({ files: filesExpanded, outputPath: outputPath ?? "webpagetest", flags: cli.flags, }); }) .catch((error: any) => { if (error.isTtyError) { // Prompt couldn't be rendered in the current environment } else { console.log(error); } });
package com.billyindrai.subjetpack3.data import androidx.lifecycle.LiveData import androidx.paging.LivePagedListBuilder import androidx.paging.PagedList import com.billyindrai.subjetpack3.AppExecutors import com.billyindrai.subjetpack3.Resources import com.billyindrai.subjetpack3.data.entity.MovieEntity import com.billyindrai.subjetpack3.data.entity.TvShowsEntity import com.billyindrai.subjetpack3.data.local.LocalData import com.billyindrai.subjetpack3.data.remote.Movie import com.billyindrai.subjetpack3.data.remote.TvShows import com.billyindrai.subjetpack3.data.remote.api.RemoteDataSource import com.billyindrai.subjetpack3.data.remote.api.Responses import java.util.concurrent.Executors open class FakeRepo( private val remoteDataSource: RemoteDataSource, private val localData: LocalData, private val appExecutors: AppExecutors ) { private val executorsService = Executors.newSingleThreadExecutor() fun getMovies(): LiveData<Resources<PagedList<MovieEntity>>> { return object : NetworkBoundSource<PagedList<MovieEntity>, List<Movie>>(appExecutors){ override fun loadFromDB(): LiveData<PagedList<MovieEntity>> { val config = PagedList.Config.Builder().apply { setEnablePlaceholders(false) setInitialLoadSizeHint(4) setPageSize(4) }.build() return LivePagedListBuilder(localData.getAllMovieFavorite(), config).build() } override fun shouldFetch(data: PagedList<MovieEntity>?): Boolean { return data == null || data.isEmpty() } override fun createCall(): LiveData<Responses<List<Movie>>> { return remoteDataSource.getAllMovie() } override fun saveCallResult(data: List<Movie>) { val movieList = ArrayList<MovieEntity>() for(data in data){ val movie = MovieEntity( data.id, data.poster, data.title, data.date, data.rating, data.duration, data.overview ) movieList.add(movie) } localData.insertMovie(movieList) } }.asLiveData() } fun getTvShows(): LiveData<Resources<PagedList<TvShowsEntity>>> { return object : NetworkBoundSource<PagedList<TvShowsEntity>, List<TvShows>>(appExecutors) { override fun loadFromDB(): LiveData<PagedList<TvShowsEntity>> { val config = PagedList.Config.Builder() .setEnablePlaceholders(false) .setInitialLoadSizeHint(4) .setPageSize(4) .build() return LivePagedListBuilder(localData.getAllTvShowFavorite(), config).build() } override fun shouldFetch(data: PagedList<TvShowsEntity>?): Boolean { return data == null || data.isEmpty() } override fun createCall(): LiveData<Responses<List<TvShows>>> { return remoteDataSource.getAllTvShow() } override fun saveCallResult(data: List<TvShows>) { val tvShowList = ArrayList<TvShowsEntity>() for(data in data){ val tvShow = TvShowsEntity( data.id, data.title, data.poster, data.date, data.rating, data.episodes, data.overview ) tvShowList.add(tvShow) } localData.insertTvShow(tvShowList) } }.asLiveData() } fun setMovieFavorite(movie: MovieEntity, state: Boolean) = executorsService.execute { localData.setFavorite(movie, state) } fun setTvShowFavorite(tv: TvShowsEntity, state: Boolean) = executorsService.execute { localData.setTvShowFavorite(tv, state) } fun getListMovieFavorite(): LiveData<PagedList<MovieEntity>> { val config = PagedList.Config.Builder() .setEnablePlaceholders(false) .setInitialLoadSizeHint(4) .setPageSize(4) .build() return LivePagedListBuilder(localData.getListMovieFavorite(), config).build() } fun getListTvShowFavorite(): LiveData<PagedList<TvShowsEntity>> { val config = PagedList.Config.Builder() .setEnablePlaceholders(false) .setPageSize(4) .setInitialLoadSizeHint(4) .build() return LivePagedListBuilder(localData.getListTvShowFavorite(), config).build() } fun getMovieById(movieId: Int): LiveData<MovieEntity> = localData.getMovieById(movieId) fun getTvShowById(tvId: Int): LiveData<TvShowsEntity> = localData.getTvShowById(tvId) }
use super::cv_pipeline::manager::CVPipelineManager; use super::cv_pipeline::stages::camera_stage::OpenCVCameraSource; use super::cv_pipeline::stages::display_recorder_stage::DisplaySource; use super::cv_pipeline::stages::egui_dispatcher_stage::BGRConvertToEguiStage; use super::cv_pipeline::stages::wechat_qr_detect_stage::WeChatQRCodeDecoderStage; use super::qr_code; use std::cell::RefCell; use std::sync::mpsc; use std::rc::{Rc}; use log::{info, warn}; use super::constants::SourceType; // TODO: Replace refcell with lifetimes pub struct CVWorker{ display_source : Rc<RefCell<DisplaySource>>, camera_source : Rc<RefCell<OpenCVCameraSource>>, egui_img_converter : Rc<RefCell<BGRConvertToEguiStage>>, qr_decoder_stage : Rc<RefCell<WeChatQRCodeDecoderStage>>, rx_source : mpsc::Receiver<SourceType>, rx_camera_focus : mpsc::Receiver<u8>, tx_img : mpsc::Sender<Box<egui::ColorImage>>, tx_qr : mpsc::Sender<Box<qr_code::QRCode>>, pipeline : CVPipelineManager, } impl CVWorker{ pub fn create_pipeline(tx_img : mpsc::Sender<Box<egui::ColorImage>>, tx_qr : mpsc::Sender<Box<qr_code::QRCode>>, rx_focus : mpsc::Receiver<u8>, rx_source : mpsc::Receiver<SourceType>) -> Self { let mut pipeline_manager = CVPipelineManager::new(); let rc_source_display = Rc::new(RefCell::new(DisplaySource::primary().unwrap())); let rc_source_camera = Rc::new(RefCell::new(OpenCVCameraSource::new(Some(0)).unwrap())); let rc_egui_img_converter = Rc::new(RefCell::new(BGRConvertToEguiStage::new())); let rc_qr_decoder_stage = Rc::new(RefCell::new(WeChatQRCodeDecoderStage::new())); //let mut qr_decoder_stage = Box::new(QRCodeDecoderStage::new()); info!("Pipelines stages have been created"); pipeline_manager.set_source(rc_source_camera.clone()); pipeline_manager.add_stage(rc_qr_decoder_stage.clone()); pipeline_manager.add_stage(rc_egui_img_converter.clone()); Self { pipeline : pipeline_manager, camera_source : rc_source_camera, egui_img_converter : rc_egui_img_converter, qr_decoder_stage : rc_qr_decoder_stage, display_source : rc_source_display, rx_camera_focus : rx_focus, rx_source : rx_source, tx_img : tx_img, tx_qr : tx_qr, } } fn handle_change_source(&mut self){ if let Ok(source) = self.rx_source.try_recv(){ match source { SourceType::Camera => { self.pipeline.set_source(self.camera_source.clone()); }, SourceType::Display => { self.pipeline.set_source(self.display_source.clone()); } } info!("Source has been changed"); } } fn handle_change_focus(&mut self){ let focus = self.rx_camera_focus.try_iter().last(); if let Some(focus) = focus { self.camera_source.borrow_mut().set_focus(focus).unwrap(); } } fn handle_new_image(&mut self){ let img = self.egui_img_converter.borrow_mut().pop_last_image(); if let Some(img) = img { self.tx_img.send(img).unwrap(); } } fn handle_new_qr(&mut self){ let qr = self.qr_decoder_stage.borrow_mut().pop_last_qrs(); if let Some(qr_vec) = qr { for qr in qr_vec { self.tx_qr.send(qr).unwrap(); } } } fn handle_channels(&mut self){ self.handle_change_source(); self.handle_change_focus(); self.handle_new_image(); self.handle_new_qr(); } pub fn run(&mut self){ loop { if let Ok(frame) = self.pipeline.process(){ self.handle_channels(); }else{ warn!("Fail to process frame, skipping frame"); } self.handle_channels(); } } }
import { router, useForm } from "@inertiajs/react"; import { Trash } from "lucide-react"; import moment from "moment"; import React from "react"; import { Toaster, toast } from "sonner"; function ExpenseList({ budget }) { const Expenses = budget.expenses; const { post } = useForm(); const DeleteExpense = ($id, e) => { e.preventDefault(); post(`/dashboard/expenses/delete/${$id}`, { onSuccess: () => { toast("Expense deleted successfully"); }, }); }; return ( <div className="mt-3"> <div className="grid grid-cols-4 bg-violet-200 p-2"> <div className="font-bold">Name</div> <div className="font-bold">Amount</div> <div className="font-bold">Date</div> <div className="font-bold">Action</div> </div> {Expenses.map((expense) => ( <div className="grid grid-cols-4 border-b border-violet-200 p-2"> <div className="">{expense.name}</div> <div className="">${expense.amount}</div> <div className=""> {moment(expense.created_at).format("L")} </div> <div className=""> <Trash className="text-red-500 cursor-pointer" onClick={(e) => DeleteExpense(expense.id, e)} /> </div> </div> ))} <Toaster /> </div> ); } export default ExpenseList;
#pragma once /* File name : motor.h Author: Stephan Scholz / WilhelmKuckelsberg Project name : KuCo_Phantom 1 Date : 2022-06-14 Description : */ #include <Arduino.h> #include <RP2040_PWM.h> //#define LOCAL_DEBUG #include "myLogger.h" #include "config.h" /* #define _PWM_LOGLEVEL_ 0 #if (defined(ARDUINO_NANO_RP2040_CONNECT) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || \ defined(ARDUINO_GENERIC_RP2040)) && \ defined(ARDUINO_ARCH_MBED) #if (_PWM_LOGLEVEL_ > 3) #warning USING_MBED_RP2040_PWM #endif #elif (defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || \ defined(ARDUINO_GENERIC_RP2040)) && \ !defined(ARDUINO_ARCH_MBED) #if (_PWM_LOGLEVEL_ > 3) #warning USING_RP2040_PWM #endif #else #error This code is intended to run on the RP2040 mbed_nano, mbed_rp2040 or arduino-pico platform! Please check your Tools->Board setting. #endif */ class Motor { private: float frequency; float dutyCycle; bool _isArmed; unsigned long _lastMillis; public: typedef enum { arming = 0, power_on, power_off, busy, finished, stop, rotating } motorstate_e; protected: uint8_t _pin; RP2040_PWM *_motor; uint32_t resultingPower, _resultingPower,_lastResultingPower; int16_t _power,_lastPower,_maxPower; motorstate_e _motorState,_lastMotorState; public: Motor(uint8_t pin) : _pin(pin) { _power = 0; _maxPower = 100; // % _motorState = stop; _isArmed = false; LOGGER_NOTICE_FMT("PIN = %d", _pin); }; /*--------------------------------------------------------------*/ void setup() { LOGGER_VERBOSE("Enter...."); frequency = 400.0f; // Ist das hier richtig?? oder besser als #define _motor = nullptr; _motor = new RP2040_PWM(_pin, frequency, DUTYCYCLE_MAX/1000); // 2mS if (_motor) { LOGGER_NOTICE_FMT("_motor Pin = %d", _pin); _motor->setPWM(); }else{ LOGGER_FATAL_FMT("PWM-Pin %d not known", _pin); }; delay(20); LOGGER_VERBOSE("....leave"); } /*------------------------------- end of setup ----------------------------------*/ void update() { LOGGER_VERBOSE("Enter...."); if(_motorState!=_lastMotorState){ LOGGER_VERBOSE_FMT("*******New State to Update - Pin %d ********",_pin); } switch (_motorState) { case arming: LOGGER_NOTICE("arming begin"); resultingPower = DUTYCYCLE_MAX; _motorState = power_on; break; case power_on: delay(20); digitalWrite(PIN_ESC_ON, LOW); // ESC´s einschalten der PIN wird 4 mal auf LOW gesetzt _motorState = busy; _lastMillis = millis(); break; case power_off: digitalWrite(PIN_ESC_ON, HIGH); // ESC´s ausschalten _isArmed = false; break; case busy: LOGGER_NOTICE_CHK(_motorState,_lastMotorState,"Arming is busy"); if(millis() - _lastMillis > 2000){ _motorState = finished; resultingPower = DUTYCYCLE_MIN; _lastMillis = millis(); } break; case finished: LOGGER_NOTICE_CHK(_motorState,_lastMotorState,"Arming is finished"); if(millis() - _lastMillis > 1000){ _isArmed = true; _lastMillis = millis(); _motorState = stop; } resultingPower = DUTYCYCLE_MIN; break; case stop: LOGGER_NOTICE_CHK(_motorState,_lastMotorState,"Motor off"); _power = 0; resultingPower = DUTYCYCLE_MIN; break; case rotating: LOGGER_NOTICE_CHK(_motorState,_lastMotorState,"Motor on"); resultingPower = map(_power, 0, 100, DUTYCYCLE_MIN, DUTYCYCLE_MAX); if (resultingPower < map(BASE_MOTOR_POWER, 0, 100, DUTYCYCLE_MIN, DUTYCYCLE_MAX)) { resultingPower = map(BASE_MOTOR_POWER, 0, 100, DUTYCYCLE_MIN, DUTYCYCLE_MAX); } LOGGER_NOTICE_FMT_CHK(resultingPower, _resultingPower, "RC Throttle %d ResultingPower %d", _power, resultingPower); break; } if(_lastResultingPower!=resultingPower){ LOGGER_NOTICE_FMT("resultingPower = %d - Pin: %d",resultingPower,_pin); _motor->setPWM_Int(_pin, frequency, resultingPower); _lastResultingPower= resultingPower; } if((digitalRead(PIN_ESC_ON)==HIGH) && (_motorState!=power_on)){ _motorState= power_off; } LOGGER_VERBOSE("....leave"); } /*-------------------------- end of updateState ----------------------------------------------*/ uint16_t getPower() const { LOGGER_VERBOSE("Enter...."); return _power; LOGGER_VERBOSE("....leave"); } /*-------------------------- end of getPower -------------------------------------------------*/ String getResultingPower() const { char buffer1[20]; char buffer2[20]; LOGGER_VERBOSE("Enter...."); String One = "Resultingpower "; String ResultingPower = "Resultingpower " + _resultingPower; String Pin = " on Pin " +_pin; String Output =ResultingPower +Pin; return Output; LOGGER_VERBOSE("....leave"); } /*-------------------------- end of getResultingPower --------------------------------------*/ uint16_t setPower(int16_t power) { LOGGER_VERBOSE("Enter...."); if (power < 0) { _power = 0; LOGGER_NOTICE_FMT("Power = %d < 0 - Pin: %d",power,_pin); } else if (power > _maxPower) { _power = _maxPower; LOGGER_NOTICE_FMT("Power = %d over maxPower - Pin: %d",power,_pin); } else { _power = power; } LOGGER_NOTICE_FMT_CHK(_power,_lastPower,"setPower %d - Pin: %d", _power,_pin); LOGGER_VERBOSE("....leave"); return _power; } /*-------------------------- end of setPower ---------------------------------------------*/ uint16_t getPower(){ return _power; } uint8_t getMaxPower() const { LOGGER_VERBOSE("Enter...."); return _maxPower; LOGGER_VERBOSE("....leave"); } /*-------------------------- end of getMaxPower ------------------------------------------*/ void setMaxPower(uint8_t maxPower) { LOGGER_VERBOSE("Enter...."); if (maxPower > 100) _maxPower = 100; else _maxPower = maxPower; LOGGER_VERBOSE("....leave"); } /*-------------------------- end of setMaxPower ------------------------------------------*/ bool isArmed(){ return _isArmed; } /*-------------------------- end of isArmed ----------------------------------------------*/ bool isMotorOff() { LOGGER_VERBOSE("Enter...."); return (_motorState == stop); LOGGER_VERBOSE("....leave"); } /*-------------------------- end of isMotorOff -------------------------------------------*/ motorstate_e getMotorState() { LOGGER_VERBOSE("Enter...."); return _motorState; } /*-------------------------- end of getMotorState ---------------------------------------*/ void setMotorState(motorstate_e state) { LOGGER_VERBOSE("Enter...."); _motorState = state; LOGGER_VERBOSE("....leave"); } /*-------------------------- end of setMotorStates ---------------------------------------*/ }; /*--------------------------- end of Motor class -----------------------------------------*/
import type { Metadata } from "next"; import { Inter } from "next/font/google"; import "@/app/globals.css"; import RedProv from "../redux-service/reduxProvider"; import CheckAuthUser from "../lib/checkAuthUser"; import GoogleAuthSessionProvider from "../lib/googleAuthSessionProvider"; const inter = Inter({ subsets: ["latin"] }); export const metadata: Metadata = { title: "GT Next App - Auth", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={inter.className}> <GoogleAuthSessionProvider> <RedProv> <CheckAuthUser> {children} </CheckAuthUser> </RedProv> </GoogleAuthSessionProvider> </body> </html> ); }
import 'package:assignmen_1/Screens/Accepter/searchscreen.dart'; import 'package:assignmen_1/Screens/Accepter/send_request.dart'; import 'package:assignmen_1/repository/location_controller.dart'; import 'package:flutter/material.dart'; import 'package:geolocator/geolocator.dart'; import 'package:get/get.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import '../../model/methodefile.dart'; import '../../repository/donorrepository.dart'; import '../../singleton.dart'; class MyMap extends StatefulWidget { const MyMap({Key? key}) : super(key: key); @override _MyMapState createState() => _MyMapState(); } class _MyMapState extends State<MyMap> { LatLng? targetLatLng ; BitmapDescriptor markerIcon = BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue); List<int> distances=[]; // Step 1. int dropdownValue = 1; List<int> distanceRanges=[1, 2,3,4,5,6,7,8,9,10,11,12]; List<String> bloodGroupList = [ 'A+', 'B+', 'AB+', 'O+', 'A-', 'B-', 'AB-', 'O-', ]; String dropdownBloodValue = 'A+'; // Step 2. final Set<Marker> _markers = {}; LocationController controller=LocationController(); List<UserDonor>? donorList; final Singleton _singlton=Singleton(); @override void initState() { // TODO: implement initState targetLatLng=LatLng(_singlton.currentLat!,_singlton.currentLng!); super.initState(); } getDonorsList() async { _markers.clear(); var customMarker = Marker( markerId: const MarkerId("currentLocation"), position: LatLng( Singleton.instance.currentLat!, Singleton.instance.currentLng!), draggable: false, onDragEnd: (value) { // value is the new position }, icon: markerIcon); _markers.add(customMarker); Donorrepository().alluser().then((donorList) async { for (int i = 0; i < donorList.length; i++) { if (donorList[i].latitude != null && donorList[i].longitude != null) { var distance = Geolocator.distanceBetween(_singlton.currentLat!, _singlton.currentLng!, donorList[i].latitude!, donorList[i].longitude!); distance=distance/1000; if (distance <= dropdownValue && donorList[i].Bloodgroup==dropdownBloodValue) { print("calculated distance:$distance"); print("dropdown $dropdownValue"); _markers.add( // added markers Marker( markerId: MarkerId(i.toString()), position: LatLng( donorList[i].latitude!, donorList[i].longitude!), infoWindow: InfoWindow( title: donorList[i].Bloodgroup, snippet: donorList[i].address, onTap: (){ print("marker tapped"); String donorId = donorList[i].Donoremail; Get.to(() => const Requesttodonor(), arguments: MyPageArguments( donorid: donorId)); } ), icon: BitmapDescriptor.defaultMarker, ) ); } } if (mounted) { setState(() {}); } } }); } void _onMapCreated(GoogleMapController controller) { setState(() { getDonorsList(); }); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Stack( alignment: Alignment.topRight, children: [ GoogleMap( myLocationEnabled: true, onMapCreated: _onMapCreated, initialCameraPosition: CameraPosition( target:targetLatLng!, zoom: 11.0, ), markers: _markers, ), Container( color: Colors.white, padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton(onPressed: (){ Get.back(); }, icon: const Icon(Icons.arrow_back)), Container( color: Colors.white10, child: DropdownButton<String>( // Step 3. value: dropdownBloodValue, // Step 4. items: bloodGroupList .map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Text( value, style: const TextStyle(fontSize: 16), ), ), ); }).toList(), // Step 5. onChanged: (String? newValue) { setState(() { dropdownBloodValue = newValue!; getDonorsList(); }); }, ), ), Container( color: Colors.white10, child: DropdownButton<int>( // Step 3. value: dropdownValue, // Step 4. items: distanceRanges .map<DropdownMenuItem<int>>((int value) { return DropdownMenuItem<int>( value: value, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Text( "$value km", style: const TextStyle(fontSize: 16), ), ), ); }).toList(), // Step 5. onChanged: (int? newValue) { setState(() { dropdownValue = newValue!; getDonorsList(); }); }, ), ), ], ), ), ], ), ), ); } }
<html> <head> <title>jQuery WAI-ARIA Checkbox Demo</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="jquery.waria-checkbox.js"></script> <script type="text/javascript" src="https://raw.github.com/nylen/shiftcheckbox/gh-pages/jquery.shiftcheckbox.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('.testCheckbox').click(function(e) { e.preventDefault(); var cb_total = $(':checkbox', $(this).closest('.example')).length; var cb_checked = $(':checked', $(this).closest('.example')).length; alert('There are ' + cb_total + ' checkbox in that section. ' + cb_checked + ' are checked.') }) $('div[role=checkbox]').click(function(){ if ($(this).attr('aria-checked')==='true') { $(this).attr('aria-checked', 'false'); } else { $(this).attr('aria-checked', 'true'); } }); $('#example2 .field').shiftcheckbox({ checkboxSelector: ':checkbox', selectAll: $('#all') }); }); </script> <style type="text/css"> input[type=checkbox] + label { background-color: blue; color: white; } input[type=checkbox]:checked + label { background-color: green; color: white; } div[aria-checked=false] { background-color: blue; color: white; } div[aria-checked=true] { background-color: green; color: white; } </style> </head> <body> <div class="example" id="example1"> <h1>Basic example</h1> <p>Just testing how <code>:checked</code> and <code>:checkbox</code> works</p> <div class="field"> <input type="checkbox" id="c11" /> <label for="c11">I'm a common checkbox</label> </div> <div class="field"> <input type="checkbox" id="c12" /> <label for="c12">I'm a common checkbox</label> </div> <div class="field"> <input type="checkbox" id="c13" /> <label for="c13">I'm a common checkbox</label> </div> <div class="field"> <div role="checkbox" aria-checked="false" tabindex="0">I'm a WAI ARIA checkbox</div> </div> <div class="field"> <div role="checkbox" aria-checked="false" tabindex="0">I'm a WAI ARIA checkbox</div> </div> <div class="field"> <div role="checkbox" aria-checked="false" tabindex="0">I'm a WAI ARIA checkbox</div> </div> <div class="field"> <input type="checkbox" id="c14" /> <label for="c14">I'm a common checkbox</label> </div> <div class="field"> <div role="checkbox" aria-checked="false" tabindex="0">I'm a WAI ARIA checkbox</div> </div> <br/> <input type="button" class="testCheckbox" name="test" value="Recap" /> </div> <div class="example" id="example2"> <h1>Shift+Click support</h1> <p> Deeply testing also the <code>.prop()</code> jQuery feature, using the <a href="http://nylen.github.io/shiftcheckbox/">ShiftCheckbox jQuery plugin</a>. <br/> The plugin is unmodified but still is working properly also with HTML elements (try to shift+click or the &quot;Select all&quot; button). </p> <div class="field"> <input type="checkbox" id="c21" /> <label for="c21">I'm a common checkbox</label> </div> <div class="field"> <input type="checkbox" id="c22" /> <label for="c22">I'm a common checkbox</label> </div> <div class="field"> <input type="checkbox" id="c23" /> <label for="c23">I'm a common checkbox</label> </div> <div class="field"> <div role="checkbox" aria-checked="false" tabindex="0">I'm a WAI ARIA checkbox</div> </div> <div class="field"> <div role="checkbox" aria-checked="false" tabindex="0">I'm a WAI ARIA checkbox</div> </div> <div class="field"> <div role="checkbox" aria-checked="false" tabindex="0">I'm a WAI ARIA checkbox</div> </div> <div class="field"> <input type="checkbox" id="c24" /> <label for="c24">I'm a common checkbox</label> </div> <div class="field"> <div role="checkbox" aria-checked="false" tabindex="0">I'm a WAI ARIA checkbox</div> </div> <br/> <input type="button" class="testCheckbox" name="test" value="Recap" /> <input type="button" id="all" name="all" value="Select all" /> </div> </body> </html>
classdef behavior_funcs %behavior consists of functions used to assess locomotion of rodent % behavior % % Adapted from OF from ephys_tools by LB 12/2022 properties Property end methods(Static) %% General locomotion function length = path_length(x,y,velocity,varargin) % Computes total path length during running % inputs: % x: position vector of x-coordinates of length n % y: position vecotr of y-coordinates of length n % velocity: vector of instantaneous velocity (length of n - 1) % output: % length: total path length in cm for active motion p = inputParser; addParameter(p,'run_threshold',3,@isnumeric); parse(p,varargin{:}); run_threshold = p.Results.run_threshold; %distance formula distance_vector = sqrt((diff(x)).^2 + (diff(y)).^2); % length of path when animal is running length = sum(distance_vector(velocity >= run_threshold,1));%Total Path length for points greater than 3cm/s end function [stopIdx,startStop,endStop] = stop_epochs(velocity,varargin) % Given a vector of velocity, find when the vector falls below % input: % run_threshold: velocity that separates movement from % non-movement in same unites as xy coordinates (ie cm/s or % pixels/s) default: 3 cm/s % epoch: number of contiguous frames to search for stops. % Default is 60 frames assuming 60Hz sample rate (i.e. animal % is stopped for 1 second). % output: % stopIdx: logical index of time associated with stop % startStop: row index for start of stops % endStop: row index for end of stops p = inputParser; addParameter(p,'run_threshold',3,@isnumeric); addParameter(p,'epoch',60,@isnumeric); parse(p,varargin{:}); run_threshold = p.Results.run_threshold; epoch = p.Results.epoch; stopIdx = contiguousframes(velocity <= run_threshold,epoch); [startStop,endStop,~] = find_groups(stopIdx); end function center = center_of_mass(x,y) %Find center of mass for set of x,y coordinates % uses min_encl_ellipsoid to find center of mass of coordinates % and results [x,y] as 'center' temp=[x,y]; % remove nans temp(any(isnan(temp),2),:)=[]; % min_encl_ellipsoid requires size > 1 if ~isempty(temp) && size(temp,1)>1 [ ~,~, center] = min_encl_ellipsoid(temp(:,1),temp(:,2)); else center = [NaN,NaN]; end end function stop_measures = stops(x,y,ts,velocity,fr,epoch,varargin) % Finds when animal stop ( < 3cm/s velocity for at least 1 % second) and computes stop features. % inputs: % x: position vector for x of length n % y: position vector for y of length n % ts: timestamps of length n % fr: frame rate % velocity: instantaneous velocity of length n-1 % epoch: length of minimum stop epoch in frames % outputs: % stop_measures: structure containing outcome measures. % stopIdx: logical index of points where rat is % stopped. % stops: cell array of stop xy coordinates % timeStopped: time (seconds) of a stop % tsStop: cell array of time stamps corresponding to stop % NumStops: number of stops made % p = inputParser; addParameter(p,'run_threshold',3,@isnumeric); parse(p,varargin{:}); run_threshold = p.Results.run_threshold; [stop_measures.stopIdx,startStop,endStop] = behavior_funcs.stop_epochs(velocity,epoch,'run_threshold',run_threshold); % This finds coordinates associated with stop for ii=1:length(startStop) motionless{ii} = [x(startStop(ii):endStop(ii)),y(startStop(ii):endStop(ii))]; timeMotionless{ii} = size(motionless{ii},1)/fr; tsStop{ii} = ts(startStop(ii):endStop(ii)); end stop_measures.stops = motionless; stop_measures.timeStopped = timeMotionless; stop_measures.tsStop = tsStop; %Create Number of Stops stop_measures.NumStops = size(stop_measures.stops,2); %Find center of mass for stops. for ii=1:size(stop_measures.stops,2) center(ii) = center_of_mass(stop_measures.stops{1,ii}(:,1),stop_measures.stops{1,ii}(:,2)); end stop_measures.stopCenter = center; end function quad_measures = quadrant(x,y,fr,varargin) % Finds when animal stops ( < 3cm/s velocity for at least 1 % second) and computes stop features. % inputs: % x: vector of cordinates for x % y: vector of cordinates for y % fr: video sampling rate in Hz % outputs: % quad_measures: structure containing outcome measures. % stopIdx: logical index of points where rat is % stopped. % stops: cell array of stop xy coordinates % timeStopped: time (seconds) of a stop % tsStop: cell array of time stamps corresponding to stop % NumStops: number of stops made % % LB 2022 p = inputParser; p.addParameter('n_quadrants',4,@isnumeric) p.addParameter('run_threshold',3,@isnumeric) p.parse(varargin{:}) n_quadrants = p.Results.n_quadrants; run_threshold = p.Results.run_threshold; %squared distance between consecutive points sqrXDiff = (diff(x)).^2; sqrYDiff = (diff(y)).^2; %distance formula distance_vector = sqrt(sqrXDiff + sqrYDiff); %instanteous velocity velocity = (distance_vector)*fr; %instanteous velocity velocity = smoothdata(velocity,'sgolay',fr*.8); %smoothed with moving median window over less than 1 second clear sqrXDiff sqrYDiff [stopIdx,startStop,endStop] = behavior_funcs.stop_epochs(velocity,epoch,'run_threshold',run_threshold); % animal is stopped for in quadrant for 1 second stopIdx = contiguousframes(velocity <= run_threshold,fr); [startStop,endStop,~] = find_groups(stopIdx); % This finds coords for stopping for ii=1:length(startStop) motionless{ii}=[back(startStop(ii):endStop(ii),1),back(startStop(ii):endStop(ii),2)]; end stops = motionless; clear startStop endStop %Find center of mass for stops. for ii=1:size(stops,2) temp=[stops{1,ii}(:,1),stops{1,ii}(:,2)]; temp(any(isnan(temp),2),:)=[]; if ~isempty(temp) && size(temp,1)>1 [ ~,~, stopCenter] = min_encl_ellipsoid(temp(:,1),temp(:,2)); else stopCenter(1,1)=NaN; stopCenter(2,1)=NaN; end stop(ii,1)=stopCenter(1,1); stop(ii,2)=stopCenter(2,1); end stopCenter=stop; clear stop HD = wrapTo360(fixNLXangle(rad2deg(atan2(head(:,2)-nose(:,2),... head(:,1)-nose(:,1))),round(0.1667*30))); angVel = insta_angvel(HD',fr); %calculate verticies for quadrants quadrants = createZones([0,0],params.dia{j},'numQuad',n_quadrants,'fig',0); %16 pie shaped segments %Calculate dwell time per quadrant for i=1:size(quadrants,1)-1 tempXin = [0 quadrants(i,1) quadrants(i+1,1)]; tempYin = [0 quadrants(i,2) quadrants(i+1,2)]; [in,~] = inpolygon(back(:,1),back(:,2),tempXin,tempYin); quad_measures.dwellQuad{j}(1,i) = sum(in)/fr; % quad_measures.pathLQuad{j}(1,i) = sum(distance_vector(in(1:end-1) & velocity>3 ,1)); %mean distance when animal is in quadrant and moving >3cm/s quad_measures.pathIVQuad{j}(1,i) = nanmean(velocity(in(1:end-1),1)); %mean linear velocity quad_measures.numstopQuad{j}(1,i) = sum(inpolygon(stopCenter{j}(:,1),stopCenter{j}(:,2),tempXin,tempYin)); quad_measures.stopQuad{j}(1,i) = sum(in(1:end-1,:) & stopIdx{j})/fr; %stop duration quad_measures.angVelQuad{j}(1,i) = nanmean(abs(angVel(in(1:end-1,:)))); clear tempXin tempYin in end end function [occ,map] = occ_map(x,y,binsize,fr) % Builds an occupancy map for maze. Assums params table. % inputs: % x: position vector of x-coordinates of length n % y: position vecotr of y-coordinates of length n % binsize: how big each bin should be in cm % fr: frame rate % % output: % occ: smoothed occupancy map % map: raw occupancy map %Creates bin edges for heatmap xedge=linspace(min(x),max(x),round(range(x)/binsize)); yedge=linspace(min(y),max(y),round(range(y)/binsize)); %Bin coordinates for heat map and apply guassian filter to smooth [map] = histcounts2(x,y,xedge,yedge); map=flipud(imrotate(map,90)); map=map/fr; % smooths over 1.5 cm occ = imgaussfilt(map, 1); occ(map==0) = nan; map(map==0) = nan; end function [out] = thigmotaxis(x,y,fr,diameter,varargin) % NOT FUNCTION YET NEED TO ADJUST CREATEZONES FOR SQUARE % ENVIORNMENT LB 12/2022 % Computes time spent near outside wall p = inputParser; addParameter(p,'center_proportion',.8,@ischar); parse(p,varargin{:}); center_proportion = p.Results.center_proportion; %Create annuli for center and outter edge of maze outsideDwell = createZones([0,0],diameter,'type','annulus','fig',0,'annulusSize',center_proportion); %default annulus size is 80% for createZones %Calculate dwell time for outter edge [in,~] = inpolygon(x,y,outsideDwell(:,1),outsideDwell(:,2)); out = sum(~in)/fr; end function sa = search_area(map,varargin) % computes proportion of maze area occupied by animal given % occupancy map. % inputs: % map: raw occpancy map (n x n grid of binned occupancy % weighted by frame rate) % output: % sa: search area as a proportion (e.g. .10 = 10% % of maze searched). p = inputParser; addParameter(p,'maze_type','square',@ischar); parse(p,varargin{:}); maze_type = p.Results.maze_type; %Use meshgrid to serve as basis for logical mask. imageSizeX = size(map,1); imageSizeY = size(map,2); [columnsInImage,rowsInImage] = meshgrid(1:imageSizeX, 1:imageSizeY); clear imageSizeX imageSizeY % Next create the circle in the image. if ismember(maze_type,'circle') centerX = median(1:size(map,1)); centerY = median(1:size(map,2)); radius = median(1:size(map,2)); circlePixels = (rowsInImage - centerY).^2 ... + (columnsInImage - centerX).^2 <= radius.^2; map(~circlePixels)=NaN; %indicate area outside the maze by labelling with NaN end clear rowsInImage columnsInImage sa = sum(sum(map>0))/sum(sum(~isnan(map))); %Calculate the proportion of bins occupied by animal. end function ED = egocentric_direction(pos, object_center) ED = mod(atan2d(pos.data(:,2)-object_center(2),pos.data(:,1)-object_center(1)),rad2deg(2*pi)); % get xy as analog signal array for easy epoching ED = analogSignalArray(... 'data',ED,... 'timestamps',pos.timestamps,... 'sampling_rate',pos.sampling_rate); end function CD = cue_direction(ED, HD) % takes in egocentric direction and head direction % (analogSignalArray objects) and computes direction to cue by % taking the circular distance between the two headings. % returns analougSignalArray with cue direction. r = angle(exp(1i*deg2rad(ED.data(:,1)))./exp(1i*deg2rad(HD.data(:,1)))); % shift all by 45 r = angle(exp(1i*r)./exp(1i*deg2rad(45))); CD = rad2deg(r'); end %% Home base functions function metrics = home_base_metics(out_home,x,y,velocity,x_home,y_home,stopIdx,tsStop) % This finds stops that occur in the home base boundary [startStop,~,~] = find_groups(stopIdx); [~,~,metrics.entries] = find_groups(out_home); % total time in home base metrics.hbOcc = nansum(out_home)/fr; % average velocity in home base metrics.hbVel = nanmean(velocity(out_home(1:end-1,1),1)); %remove last tempIn idx to accomodate velocity length % time moving slow in home base in seconds metrics.slowInHB = nansum(out_home(1:end-1) & stopIdx)/fr; % time being slow in homebase % proportion of time being slow in home base metrics.HBclass= slowInHB/hbOcc; % proportion of time being slow in hb % number times an animal stoped in the home base metrics.HBstops = nansum(inpolygon(x(startStop,1),... y(startStop,2),x_home(1:end-2)',y_home(1:end-2)')); % Find number of times animals initiated a start in the home base % index for the time it takes to reach the home base time2HB_idx = inpolygon(x(startStop,1),... x(startStop,2),x_home(1:end-2)',y_home(1:end-2)'); % time to first time in home base firstIdx = find(time2HB_idx); % save time to home base time2HB_time = tsStop{1,firstIdx(1)}; metrics.time2HB = time2HB_time(1,1); end function [HBBound,HBcoords,HBcenter,out_home,x_home,y_home] = rescale_home_base(home_base_x,home_base_y,upHBmap,upFactor,diameter,fr) %rescale coordinates back to pool size x_home = rescale([home_base_x,upFactor+1,size(upHBmap,2)-upFactor],-(diameter/2),(diameter/2)); y_home = rescale([home_base_y,upFactor+1,size(upHBmap,2)-upFactor],-(diameter/2),(diameter/2)); % logical index for all coordinates inside home base in_home = inpolygon(x,y,x_home(1:end-2)',y_home(1:end-2)'); % coordinates for frames inside home base for at least 2seconds out_home = contiguousframes(in_home,fr*2); %has to be inside of hb for at least 2 sec to count as entryd % boundary of home base HBBound = [x_home(1:end-2)',y_home(1:end-2)']; % time in home base HBcoords = [x(out_home,1),y(out_home,2)]; [ ~,~, tempC] = min_encl_ellipsoid(HBBound(:,1),HBBound(:,2)); HBcenter= [tempC(1,1),tempC(2,1)]; end function [HB_stop_dist,HB_close_stop,HB_stop_dist_vector] = stops_to_homebase(HBcenter,stops) % Average Proximity of stops from hb center disttemp = zeros(size(stops,2),1); for i = 1:size(stops,2) temp = stops{1,i}; dist = sqrt((HBcenter(1,1)-temp(:,1)).^2+(HBcenter(1,2)-temp(:,2)).^2); disttemp(i,1) = nanmean(dist); end HB_stop_dist = nanmean(disttemp); %average stop distance HB_close_stop = sum(disttemp<25); %number of stops within 25cm from hb center HB_stop_dist_vector = disttemp; end function [HB_avg_dist,HB_max_dist,HB_min_dist] = distance_between_homebase(HBcenter) % input: % - HBcenter: vector of HB centers % output: % -HB_avg_dist: average distance between home bases % -HB_max_dist: maximum distance between home bases % -HB_min_dist: minimum distance between home bases % % Calculate distance measures between high occupancy coordinates centers temp = []; if size(HBcenter,2) > 1 for hb = 1:size(pHBcenter,2) temp = [temp; HBcenter{1,hb}]; end HB_avg_dist = nanmean(pdist(temp)); HB_max_dist = max(pdist(temp)); HB_min_dist = min(pdist(temp)); else HB_avg_dist = NaN; HB_max_dist = NaN; HB_min_dist = NaN; end end function HBdist2Cue = homebase_dist_from_cue(cueCM,HBcenter) % calculating proximity of high occupancy coordinates center from the % cue boundary k = convhull(cueCM(:,1),cueCM(:,2)); cueBoundary = [cueCM(k,1),cueCM(k,2)]; for r = 1:size(HBcenter,2) distances = sqrt(sum(bsxfun(@minus, cueBoundary, [HBcenter{1,r}(:,1),HBcenter{1,r}(:,2)]).^2,2)); HBdist2Cue{1,r} = unique(distances(distances == min(distances))); %Find minimum distance from cue boundary to hb center end end %% Object exploration functions function [results,results_as_cell,explore_vectors] = score_object_exploration(basepath,varargin) % within basepath, scores epochs with 'object' indicated in % session.epoch.name. Determines the time spent exploring % objects by positions listed in % session.behavioralTracking.maze_coords. % % Animal scoring adapted from Leger et al 2013, with exception % that climbing is included as exploration. % https://doi.org/10.1038/nprot.2013.155 % Output: % structure containing, % point statistics: first object explored (string), % time to object exploration (s), discrimination ratio for % first 180 and 300 seconds after first object is explored. % vectors: object A & B min distance to object boundary. % Assumes general behavior file and *maze_coords.csv is in basepath. p = inputParser; p.addParameter('distance_threshold',6,@isnumeric) %6cm as tracking is of back of electrode cage for ephys experiments p.addParameter('duration_in_seconds',300,@isnumeric) p.addParameter('heading_thresh',45,@isnumeric) p.addParameter('bin_width',5,@isnumeric)% in minutes p.addParameter('fig',false,@islogical) p.parse(varargin{:}); distance_threshold = p.Results.distance_threshold; duration_in_seconds = p.Results.duration_in_seconds; heading_thresh = p.Results.heading_thresh; bin_width = p.Results.bin_width; fig = p.Results.fig; basename = basenameFromBasepath(basepath); % load animal behavior and session files session = loadSession(basepath); try load(fullfile(basepath,[basename,'.animal.behavior.mat']),'behavior') catch disp(['No behavior file found for basepath ',basepath,'. Exiting function']) results = NaN; explore_vectors = NaN; return end % load behavior epochs behave_ep = behavior_funcs.load_epochs(basepath); % load trials epochs trial_ep = behavior_funcs.load_trials(basepath); % get xy as analog signal array for easy epoching positions = analogSignalArray(... 'data',[behavior.position.x;behavior.position.y],... 'timestamps',behavior.timestamps,... 'sampling_rate',behavior.sr); HD = behavior_funcs.load_HD(basepath); % determine which object moved moved_object_id = behavior_funcs.find_moved_object(basepath); % for each behavior epoch, get exploration of objects within % epoch results = table; results.basepath = repmat(basepath,behave_ep.n_intervals,1); for ep = 1:behave_ep.n_intervals epoch_name{ep} = session.epochs{1,session.behavioralTracking{1, ep}.epoch}.name; % get maze coords for object coordinates [object_center,object_edge,object_id] = behavior_funcs.load_object_coords_for_epoch(session,behavior,ep); obj_idx = contains(object_id,'A'); % get intervalArray of current epoch cur_ep = behave_ep(ep) & trial_ep; % animal position in epoch cur_pos = positions(cur_ep); cur_HD = HD(cur_ep); % compute cue angle for each object for obj = 1:size(object_center,1) cur_ED = behavior_funcs.egocentric_direction(cur_pos, object_center(obj,:)); cue_angle(obj,:) = behavior_funcs.cue_direction(cur_ED, cur_HD); end % cue angle % get object boundary [bound_x, bound_y] = behavior_funcs.object_boudary(object_center,object_edge); % get distances from objects object_distances = behavior_funcs.dist_from_object(cur_pos.data(:,1)... ,cur_pos.data(:,2)... ,bound_x,bound_y); % get exploration time for each object [explore_time,explore_vec] = behavior_funcs.object_explore(cur_pos,... cue_angle,... heading_thresh,... object_distances,... distance_threshold); % compute discrimination_ratio % exploration over time bin_explore = behavior_funcs.object_explore_over_time(cur_pos,... bin_width,... % time in min cue_angle,... %xy for each object center heading_thresh,...% instantaneous distance from objects object_distances,...% threshold for close enought distance_threshold); % threashold for heading % time to first object explored [start_explore, idx] = min([min(explore_vec{obj_idx}), min(explore_vec{~obj_idx})]); for obj = 1:length(object_id) object_explore_restrict(obj,:) = behavior_funcs.limit_explore_to_segment(start_explore,... duration_in_seconds,explore_vec{obj}); end % if they didn't explore any objects if ~isempty(idx) first_object_explored{ep} = object_id{idx}; time_2_object_explore(ep) = start_explore - cur_pos.timestamps(1); % first object explore ts minus start timestamps else first_object_explored{ep} = 'None'; time_2_object_explore(ep) = NaN; end % Discrimination ratio for entire session if ismember(moved_object_id,'A') DR_overall(ep) = behavior_funcs.discrimination_ratio(explore_time(~obj_idx),explore_time(obj_idx)); DR_restrict(ep) = behavior_funcs.discrimination_ratio(object_explore_restrict(~obj_idx),object_explore_restrict(obj_idx)); else DR_overall(ep) = behavior_funcs.discrimination_ratio(explore_time(obj_idx),explore_time(~obj_idx)); DR_restrict(ep) = behavior_funcs.discrimination_ratio(object_explore_restrict(obj_idx),object_explore_restrict(~obj_idx)); end % save for results obj_A_explore(ep) = explore_time(obj_idx); obj_B_explore(ep) = explore_time(~obj_idx); obj_A_explore_restrict(ep) = object_explore_restrict(obj_idx); obj_B_explore_restrict(ep) = object_explore_restrict(~obj_idx); % store vectors for each epoch explore_vectors{ep}.task_id = session.epochs{1,session.behavioralTracking{1, 1}.epoch}.name; explore_vectors{ep}.object_id = object_id; explore_vectors{ep}.bin_explore = bin_explore; explore_vectors{ep}.explore_vec = explore_vec; explore_vectors{ep}.cue_angle = cue_angle; explore_vectors{ep}.object_distances = object_distances; clear cue_angle object_distances bin_explore explore_vec end % store results results.epoch = epoch_name'; results.moved_object_id =repmat(moved_object_id,behave_ep.n_intervals,1); results.first_object_explored = first_object_explored'; results.time_2_object_explore = time_2_object_explore'; results.DR_overall = DR_overall'; results.DR_restrict = DR_restrict'; results.object_A_explore = obj_A_explore'; results.object_B_explore = obj_B_explore'; results.object_A_explore_restrict = obj_A_explore_restrict'; results.object_B_explore_restrict = obj_B_explore_restrict'; if fig plot_object_explore_results(basepath,explore_vectors,results) end results_as_cell = table2cell(results); end function [explore_time_obj,explore_vec_obj] = object_explore(cur_pos,cue_angle,heading_thresh,object_distances,distance_threshold) for i = 1:size(object_distances,1) % gather point statitics % time near each object (time when animal is within 5cm of object) [explore_time, explore_vec] = behavior_funcs.time_near_object(cur_pos,... object_distances(i,:),... distance_threshold,... cue_angle(i,:),... heading_thresh); explore_time_obj(i,:) = explore_time; explore_vec_obj{i,1} = explore_vec'; end end function bin_explore = object_explore_over_time(pos, bin_width,cue_angle,heading_thresh,object_distances,distance_threshold) for obj = 1:size(object_distances,1) % create bins with edges = pos.timestamps(1):bin_width*pos.sampling_rate:pos.timestamps(end); angle_idx = cue_angle(obj,:) >= -heading_thresh & cue_angle(obj,:) <= heading_thresh; explore_ts = pos.timestamps(object_distances(obj,:) <= distance_threshold & angle_idx); for i = 1:length(edges)-1 idx = explore_ts >= edges(i) & explore_ts <= edges(i+1); bin_explore(obj,i) = behavior_funcs.explore_time(explore_ts(idx)); end end end function moved_object_id = find_moved_object(basepath) % determines which object was moved based on distance between learning % and test center coordinates. % % input % load behavior epochs basename = basenameFromBasepath(basepath); behave_ep = behavior_funcs.load_epochs(basepath); session = loadSession(basepath); load(fullfile(basepath,[basename,'.animal.behavior.mat']),'behavior') for ep = 1:behave_ep.n_intervals % get maze coords for object coordinates [object_center{ep},~,object_id{ep}] = behavior_funcs.load_object_coords_for_epoch(session,behavior,ep); end % euclidean distance between center coordinates epoch_dist = sqrt((object_center{1}(:,1) - object_center{2}(:,1)).^2 +... (object_center{1}(:,2) - object_center{2}(:,2)).^2); % find max [~,idx] = max(epoch_dist); % identify object moved_object_id = object_id{1}{idx}; end function [object_explore,explore_ts] = time_near_object(pos,distance_vector,dist_thresh,egocentric_heading,heading_thresh) % calcultes the time near an object % input: % - pos: analogSignalArray of position (length n) % - distance_vector: instantaneous distance from object (length n) % - dist_thresh: threshold of distance in same units as position. % - egocentric_heading: relative heading of animal from object center % (degrees) % - heading_thresh: value in degrees to limit (ie 45 will give +/-45 % from object). % output: % object_explore: total time in units of timestamps that reflects angle_idx = egocentric_heading >= -heading_thresh & egocentric_heading <= heading_thresh; dist_idx = distance_vector <= dist_thresh; explore_ts = pos.timestamps(dist_idx & angle_idx); object_explore = behavior_funcs.explore_time(explore_ts); end function [bound_x, bound_y] = object_boudary(object_center,object_edge) % Given the center and edge of an object, compute and return xy % coordinates representing the radius around an object % input: % object_center: [x,y] from maze_coords.csv % object_edge: [x, y] % center of object % given camera position to objects, the radius may be % different. We'll compile the radius for both to calculate an % average that will be used for the boundary. for i = 1:size(object_center,1) x0 = object_center(i,1);%%origin y0 = object_center(i,2);%%origin % radius (difference from center to edge r(i) = abs(sqrt((object_center(i,1)-object_edge(i,1))^2+(object_center(i,2)-object_edge(i,2)).^2)); end % get mean of radius r = mean(r); % get boundary position for each object for i = 1:size(object_center,1) x0 = object_center(i,1);%%origin y0 = object_center(i,2);%%origin % create circle of 25 points around object bound_x(i,:) = cos(linspace(-pi,pi,25)) * r + x0; bound_y(i,:) = sin(linspace(-pi,pi,25)) * r + y0; end end function metrics = object_explore_vectors(object_center,object_edge,behavior,varargin) % calculate object interaction for all xy coordinates and % return as structure. LB 2022 p = inputParser; p.addParameter('near_obj_dist',3,@isnumeric) % perimeter around object in units as coordinates (default cm) p.addParameter('run_thres',5,@isnumeric) p.parse(varargin{:}) near_obj_dist = p.Results.near_obj_dist; run_thres = p.Results.run_thres; % get behavior epoch % grab xy coordinates x = behavior.position.x; y = behavior.position.y; % compute velocity [velocity, ~,~] = linear_motion(x,y,behavior.sr,1); % get object boundary [bound_x, bound_y] = behavior_funcs.object_boudary(object_center,object_edge); % distance of animal relative to object boundaries object_distances = behavior_funcs.dist_from_object(x,y,[bound_x, bound_y]); % find distances when animal was close to object and moving % slow explore_obj_idx = (object_distances <= near_obj_dist) & (velocity < run_thres); % logical index for all coordinates inside object boundary in_home = inpolygon(x,y,bound_x',bound_y'); % time moving slow for at least 1 second stopIdx = contiguousframes(velocity < run_thres,behavior.sr); % coordinates for frames inside home base for at least 0.5 seconds out_home = contiguousframes(in_home,behavior.sr/2); %has to be inside of hb for at least 1 sec to count as entryd % This finds stops that occur in the home base boundary [startStop,~,~] = find_groups(stopIdx); % get n entries into object area [~,~,metrics.entries] = find_groups(out_home); % total time near object metrics.obj_Occ = nansum(out_home)/fr; % average velocity near object metrics.obj_Vel = nanmean(velocity(out_home(1:end-1,1),1)); %remove last tempIn idx to accomodate velocity length % time moving slow near object in seconds metrics.obj_slow = nansum(out_home(1:end-1) & stopIdx)/fr; % time being slow in homebase % proportion of time being slow near object metrics.obj_class= slowInHB/obj_Occ; % proportion of time being slow in hb % number times an animal stoped in the object area metrics.HBstops = nansum(inpolygon(x(startStop,1),... y(startStop,2),bound_x(1:end-2)',bound_y(1:end-2)')); % Find number of times animals initiated a start in the home base end function dist_vec = stop_dist_from_object(object_center,stops) % mesaure time moving slow/stopped around object % input: % object_center: xy coordinates of object % stops: cell array containing xy coordinates of each stop. % output: % dist_vec: vector of length n stops containing mean distance % in xy units. % Average Proximity of stops from hb center dist_vec = zeros(size(stops,2),1); for i = 1:size(stops,2) temp = stops{1,i}; dist = sqrt((object_center(1,1)-temp(:,1)).^2+(object_center(1,2)-temp(:,2)).^2); dist_vec(i,1) = nanmean(dist); % mean distance of each stop to object end end function object_distances = dist_from_object(x,y,bound_x,bound_y) % calculating distance of xy to object boundary. for i = 1:size(bound_x,1) for ii = 1:length(bound_x(i,:)) distances(:,ii) = sqrt(sum(bsxfun(@minus, [bound_x(i,ii)',bound_y(i,ii)'], [x,y]).^2,2)); end object_distances(i,:) = min(distances,[],2)'; %Find minimum distance from cue boundary to animal location end end function [object_center,object_edge,object_id] = load_object_coords_for_epoch(session,behavior,idx) % loads the object center and edge within a given behavior % epoch. % input: % session: CellExplorer session file % behavior: CellExplorer behavior file % idx: index of cell position for % session.behavioralTracking % output: % object_center: [x, y] for each object in maze_coords % object_edge: [x, y] for edge of obejct in maze_coords % object id: cell array containing string indicating object % (either 'A' or 'B') % get maze coords for object coordinates maze_coords = session.behavioralTracking{1, idx}.maze_coords; obj_idx = contains(maze_coords.object,{'A','B'}); obj_center = contains(maze_coords.position,{'center'}); object_id = unique(maze_coords.object(obj_idx)); % fetch xy for center of object if ~contains(behavior.position.units,'pixels') % load scaled position as scaled coordinates are not in % pixels object_center = [maze_coords.x_scaled(obj_idx & obj_center), ... maze_coords.y_scaled(obj_idx & obj_center)]; object_edge = [maze_coords.x_scaled(obj_idx & ~obj_center), ... maze_coords.y_scaled(obj_idx & ~obj_center)]; else %load raw coords (in pixels) object_center = [maze_coords.x(obj_idx & obj_center), ... maze_coords.y(obj_idx & obj_center)]; object_edge = [maze_coords.x(obj_idx & ~obj_center), ... maze_coords.y(obj_idx & ~obj_center)]; end end % %% locomotion over time % function locomotion_over_epochs(x,y,[startIdx,endIdx]) % % examine path length, search area, velocity, and stops as a % % function of epoch (could be trials, behavior epochs, or time % % bins % disp('NOT FUNCTIONTIONAL LB 12/2022') % end % %% behavior utils function DR = discrimination_ratio(object_A_explore,object_B_explore) % returns the discrimination ratio that represents the relative % proportion of time spent exploring object B relative to all % object exploration. % input: % object_A_explore: total time exploring object A in seconds % object_B_explore: total time exploring object B in seconds DR = (object_B_explore - object_A_explore) / (object_B_explore + object_A_explore); end function object_explore = limit_explore_to_segment(start_time,duration_in_seconds,object_explore_vec) % limits explore vector to a specific segment, for example for the % first five minutes after object exploration. object_explore_vec = object_explore_vec(object_explore_vec >= start_time & object_explore_vec <= (start_time+duration_in_seconds)); object_explore = behavior_funcs.explore_time(object_explore_vec); end function object_explore = explore_time(explore_ts) % for a set of timestamps corresponding to object exploration % 'explore_ts', explore time computes the overall time and removes % jumps by keeping only frames with frame rates that match the mode. delta_explore = diff(explore_ts); delta_explore(delta_explore > mode(delta_explore)) = nan; object_explore = nansum(delta_explore); end function trial_ep = load_trials(basepath) basename = basenameFromBasepath(basepath); load(fullfile(basepath,[basename,'.animal.behavior.mat']),'behavior'); trial_ep = IntervalArray(behavior.trials); end function behave_ep = load_epochs(basepath) % load session session = loadSession(basepath); % loop through behavioral epochs behave_ep = []; for ep = 1:length(session.behavioralTracking) behave_ep(ep,:) = [session.epochs{1,session.behavioralTracking{1,ep}.epoch}.startTime, ... session.epochs{1,session.behavioralTracking{1,ep}.epoch}.stopTime]; end behave_ep = IntervalArray(behave_ep); end function heading_direction = load_HD(basepath) % load behavior basename = basenameFromBasepath(basepath); load(fullfile(basepath,[basename,'.animal.behavior.mat']),'behavior') % get xy as analog signal array for easy epoching heading_direction = analogSignalArray(... 'data',rad2deg(behavior.angle),... 'timestamps',behavior.timestamps,... 'sampling_rate',behavior.sr); end end end
#----------------------------------------------------------------------------- # Name: CCC '21 S2 - Modern Art (main.py) # Author: Aryan Mittal # Created: 17-Feb-2024 # Updated: 17-Feb-2024 #--------------------------------------------------------------------------- # Gets the dimensions of the canvas and the number of strokes numRowsCanvas = int(input()) numColsCanvas = int(input()) numStrokes = int(input()) # Initializes lists to keep track of the strokes of the rows and columns rowStrokeCounts = [0] * numRowsCanvas colStrokeCounts = [0] * numColsCanvas # Get strokes from the artist for _ in range(numStrokes): strokeInput = input().split() strokeDirection = strokeInput[0] strokeIndex = int(strokeInput[1]) - 1 # Updates the appropriate row or column based on the stroke direction if strokeDirection == 'R': rowStrokeCounts[strokeIndex] += 1 else: colStrokeCounts[strokeIndex] += 1 # Counts the number of cells that are gold after all strokes numGoldCells = 0 for rowIndex in range(numRowsCanvas): for colIndex in range(numColsCanvas): if (rowStrokeCounts[rowIndex] + colStrokeCounts[colIndex]) % 2 == 1: numGoldCells += 1 # Prints at last the total count of gold cells print(numGoldCells)
<!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Physique-Chimie</title> </head> <body> <header id="pc"> <div> <h1>Physique-Chimie</h1> <p>Avec Sylvie vous aimerez la physique chimie</p> </div> </header> <nav> <a href="index.html" class="nav_left"><img src="img/logo_petit.png" alt="logo petit"></a> <a href="math.html">Mathématiques</a> <a href="pc.html">Physique-Chimie</a> <a href="hg.html">Histoire-Géographie</a> <a href="anglais.html">Anglais</a> </nav> <section> <tailletextes>La physique est une science de la nature expérimentale qui étudie les phénomènes naturels et leurs évolutions. <p>Elle établit des théories qui permettent de les modéliser et, de fait, de les prévoir.</tailletextes> <tailletextes>Au lycée, la physique-chimie abord 4 grands thèmes, que l’on voit en seconde et qui sont part la suite plus détaillés. Ces quatre grand thèmes sont : <ul> <li><u>Constitution et transformations de la matière</u></li> <li><u>Mouvement et interactions</u></li> <li><u>L’énergie : conversions et transferts</u></li> <li><u>Ondes et signaux</u></li> </ul> </tailletextes> <hr> <h2><u>Chapitre 1 : Consititution et transformation de la matière</u></h2> <br><br><br><tailletextes>La matière est constituée de particules microscopiques appelées atomes. C'est la plus petite partie qui constitue la matière. Chaque atome est représenté par un symbole chimique qui est une lettre majuscule, parfois suivie d'une lettre minuscule. Ces lettres correspondent généralement aux premières lettres du nom de l'atome. Tous ces éléments sont regroupés, classés dans le tableau périodique des éléments ou table de Mendeleïev, en référence au célèbre chimiste russe Dmitri Ivanovitch Mendeleïev. Une molécule est un ensemble d’atomes liés entre eux. Les molécules sont représentées par des formules chimiques. <br>N'hésiter pas a aller voir <a href="https://www.lumni.fr/lycee/seconde/physique-chimie/constitution-et-transformations-de-la-matiere" target="blank"> ce site <style="color: "fuchsia"></a> pour découvrir plein de jeu, de videos, d'articles a ce sujet.</tailletextes> <br><br><br><br><tailletextes><u>Tableau périodique des éléments :</u></tailletextes> <br><br><br><br> <table border="0"; style="background-image:url('fondtableau.png');"> <tr> <td bgcolor="blue" width=5%>1<br><center><elementchimique>H</elementchimique></center><br><center>Hydrogène</center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="yellow" width=5%>2<br><center><elementchimique>He</elementchimique></center><br><center>Hélium</center></td> <tr> <tr> <td bgcolor="blue" width=5%>3<br><center><elementchimique>Li</elementchimique></center><br><center>Lithium</center></td> <td bgcolor="blue" width=5%>4<br><center><elementchimique>Be</elementchimique></center><br><center>Beryllium</center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="yellow"width=5%>5<br><center><elementchimique>B</elementchimique></center><br><center>Bore</center></td> <td bgcolor="yellow"width=5%>6<br><center><elementchimique>C</elementchimique></center><br><center>Carbone</center></td> <td bgcolor="yellow"width=5%>7<br><center><elementchimique>N</elementchimique></center><br><center>Azote</center></td> <td bgcolor="yellow"width=5%>8<br><center><elementchimique>O</elementchimique></center><br><center>Oxygène</center></td> <td bgcolor="yellow"width=5%>9<br><center><elementchimique>F</elementchimique></center><br><center>Fluor</center></td> <td bgcolor="yellow"width=5%>10<br><center><elementchimique>Ne</elementchimique></center><br><center>Néon</center></td> <tr> <tr> <td bgcolor="blue" width=5%>11<br><center><elementchimique>Na</elementchimique></center><br><center>Sodium</center></td> <td bgcolor="blue" width=5%>12<br><center><elementchimique>Mg</elementchimique></center><br><center>Magnésium</center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="tomato" width=5%><br><center><elementchimique></elementchimique></center><br><center></center></td> <td bgcolor="yellow"width=5%>13<br><center><elementchimique>Al</elementchimique></center><br><center>Aluminuim</center></td> <td bgcolor="yellow"width=5%>14<br><center><elementchimique>Si</elementchimique></center><br><center>Silicium</center></td> <td bgcolor="yellow"width=5%>15<br><center><elementchimique>P</elementchimique></center><br><center>Phosphore</center></td> <td bgcolor="yellow"width=5%>16<br><center><elementchimique>S</elementchimique></center><br><center>Soufre</center></td> <td bgcolor="yellow"width=5%>17<br><center><elementchimique>Cl</elementchimique></center><br><center>Chlore</center></td> <td bgcolor="yellow"width=5%>18<br><center><elementchimique>Ar</elementchimique></center><br><center>Argon</center></td> <tr> <tr> <td bgcolor="blue" width=5%>19<br><center><elementchimique>K</elementchimique></center><br><center>Potassium</center></td> <td bgcolor="blue" width=5%>20<br><center><elementchimique>Ca</elementchimique></center><br><center>Calcium</center></td> <td bgcolor="purple"width=5%>21<br><center><elementchimique>Sc</elementchimique></center><br><center>Scandium</center></td> <td bgcolor="purple"width=5%>22<br><center><elementchimique>T</elementchimique></center><br><center>Titane</center></td> <td bgcolor="purple"width=5%>23<br><center><elementchimique>V</elementchimique></center><br><center>Vanadium</center></td> <td bgcolor="purple"width=5%>24<br><center><elementchimique>Cr</elementchimique></center><br><center>Chrome</center></td> <td bgcolor="purple"width=5%>25<br><center><elementchimique>Mn</elementchimique></center><br><center>Manganèse</center></td> <td bgcolor="purple"width=5%>26<br><center><elementchimique>Fe</elementchimique></center><br><center>Fer</center></td> <td bgcolor="purple"width=5%>27<br><center><elementchimique>Co</elementchimique></center><br><center>Cobalt</center></td> <td bgcolor="purple"width=5%>28<br><center><elementchimique>Ni</elementchimique></center><br><center>Nickel</center></td> <td bgcolor="purple"width=5%>29<br><center><elementchimique>Cu</elementchimique></center><br><center>Cuivre</center></td> <td bgcolor="purple"width=5%>30<br><center><elementchimique>Zn</elementchimique></center><br><center>Zinc</center></td> <td bgcolor="yellow"width=5%>31<br><center><elementchimique>Ga</elementchimique></center><br><center>Gallium</center></td> <td bgcolor="yellow"width=5%>32<br><center><elementchimique>Ge</elementchimique></center><br><center>Germanium</center></td> <td bgcolor="yellow"width=5%>33<br><center><elementchimique>As</elementchimique></center><br><center>Arsenic</center></td> <td bgcolor="yellow"width=5%>34<br><center><elementchimique>Se</elementchimique></center><br><center>Sélénium</center></td> <td bgcolor="yellow"width=5%>35<br><center><elementchimique>Br</elementchimique></center><br><center>Brome</center></td> <td bgcolor="yellow"width=5%>36<br><center><elementchimique>Kr</elementchimique></center><br><center>Krypton</center></td> <tr> <tr> <td bgcolor="blue" width=5%>37<br><center><elementchimique>Rb</elementchimique></center><br><center>Rubidium</center></td> <td bgcolor="blue" width=5%>38<br><center><elementchimique>Sr</elementchimique></center><br><center>Strontium</center></td> <td bgcolor="purple"width=5%>39<br><center><elementchimique>Y</elementchimique></center><br><center>Yttrium</center></td> <td bgcolor="purple"width=5%>40<br><center><elementchimique>Zr</elementchimique></center><br><center>Zirconium</center></td> <td bgcolor="purple"width=5%>41<br><center><elementchimique>Nb</elementchimique></center><br><center>Niobium</center></td> <td bgcolor="purple"width=5%>42<br><center><elementchimique>Mo</elementchimique></center><br><center>Molybdène</center></td> <td bgcolor="purple"width=5%>43<br><center><elementchimique>Tc</elementchimique></center><br><center>Technétium</center></td> <td bgcolor="purple"width=5%>44<br><center><elementchimique>Ru</elementchimique></center><br><center>Rhuténium</center></td> <td bgcolor="purple"width=5%>45<br><center><elementchimique>Rh</elementchimique></center><br><center>Rhodium</center></td> <td bgcolor="purple"width=5%>46<br><center><elementchimique>Pd</elementchimique></center><br><center>Palladium</center></td> <td bgcolor="purple"width=5%>47<br><center><elementchimique>Ag</elementchimique></center><br><center>Argent</center></td> <td bgcolor="purple"width=5%>48<br><center><elementchimique>Cd</elementchimique></center><br><center>Cadmium</center></td> <td bgcolor="yellow"width=5%>49<br><center><elementchimique>In</elementchimique></center><br><center>Indium</center></td> <td bgcolor="yellow"width=5%>50<br><center><elementchimique>Sn</elementchimique></center><br><center>Etain</center></td> <td bgcolor="yellow"width=5%>51<br><center><elementchimique>Sb</elementchimique></center><br><center>Antimoine</center></td> <td bgcolor="yellow"width=5%>52<br><center><elementchimique>Te</elementchimique></center><br><center>Tellure</center></td> <td bgcolor="yellow"width=5%>53<br><center><elementchimique>I</elementchimique></center><br><center>Iode</center></td> <td bgcolor="yellow"width=5%>54<br><center><elementchimique>Xe</elementchimique></center><br><center>Xénon</center></td> <tr> <tr> <td bgcolor="blue" width=5%>55<br><center><elementchimique>Cs</elementchimique></center><br><center>Césium</center></td> <td bgcolor="blue" width=5%>56<br><center><elementchimique>Ba</elementchimique></center><br><center>Baryum</center></td> <td bgcolor="green"width=5%><center><petit>57-71</petit></center><br><center><petit>L</petit></center></td> <td bgcolor="purple"width=5%>72<br><center><elementchimique>Hf</elementchimique></center><br><center>Hafnium</center></td> <td bgcolor="purple"width=5%>73<br><center><elementchimique>Ta</elementchimique></center><br><center>Tantale</center></td> <td bgcolor="purple"width=5%>74<br><center><elementchimique>W</elementchimique></center><br><center>Tungstène</center></td> <td bgcolor="purple"width=5%>75<br><center><elementchimique>Re</elementchimique></center><br><center>Rhénium</center></td> <td bgcolor="purple"width=5%>76<br><center><elementchimique>Os</elementchimique></center><br><center>Osmium</center></td> <td bgcolor="purple"width=5%>77<br><center><elementchimique>Ir</elementchimique></center><br><center>Iridium</center></td> <td bgcolor="purple"width=5%>78<br><center><elementchimique>Pt</elementchimique></center><br><center>Platine</center></td> <td bgcolor="purple"width=5%>79<br><center><elementchimique>Au</elementchimique></center><br><center>Or</center></td> <td bgcolor="purple"width=5%>80<br><center><elementchimique>Hg</elementchimique></center><br><center>Mercure</center></td> <td bgcolor="yellow"width=5%>81<br><center><elementchimique>Tl</elementchimique></center><br><center>Thallium</center></td> <td bgcolor="yellow"width=5%>82<br><center><elementchimique>Pb</elementchimique></center><br><center>Plomb</center></td> <td bgcolor="yellow"width=5%>83<br><center><elementchimique>Bi</elementchimique></center><br><center>Bismuth</center></td> <td bgcolor="yellow"width=5%>84<br><center><elementchimique>Po</elementchimique></center><br><center>Polonium</center></td> <td bgcolor="yellow"width=5%>85<br><center><elementchimique>At</elementchimique></center><br><center>Astate</center></td> <td bgcolor="yellow"width=5%>86<br><center><elementchimique>Rn</elementchimique></center><br><center>Radon</center></td> <tr> <tr> <td bgcolor="blue" width=5%>87<br><center><elementchimique>Fr</elementchimique></center><br><center>Francium</center></td> <td bgcolor="blue" width=5%>88<br><center><elementchimique>Ra</elementchimique></center><br><center>Radium</center></td> <td bgcolor="green"width=5%><center><petit>89-103</petit></center><br><center><petit>A</petit></center></td> <td bgcolor="purple"width=5%>104<br><center><elementchimique>Rf</elementchimique></center><br><center>Rutherfordium</center></td> <td bgcolor="purple"width=5%>105<br><center><elementchimique>Db</elementchimique></center><br><center>Dubnium</center></td> <td bgcolor="purple"width=5%>106<br><center><elementchimique>Sg</elementchimique></center><br><center>Seaborgium</center></td> <td bgcolor="purple"width=5%>107<br><center><elementchimique>Bh</elementchimique></center><br><center>Bohrium</center></td> <td bgcolor="purple"width=5%>108<br><center><elementchimique>Hs</elementchimique></center><br><center>Hassium</center></td> <td bgcolor="purple"width=5%>109<br><center><elementchimique>Mt</elementchimique></center><br><center>Meitnerium</center></td> <td bgcolor="purple"width=5%>110<br><center><elementchimique>Ds</elementchimique></center><br><center>Darmstadtium</center></td> <td bgcolor="purple"width=5%>111<br><center><elementchimique>Rg</elementchimique></center><br><center>Roentgénium</center></td> <td bgcolor="purple"width=5%>112<br><center><elementchimique>Cn</elementchimique></center><br><center>Copernicium</center></td> <td bgcolor="yellow"width=5%>113<br><center><elementchimique>Nh</elementchimique></center><br><center>Nihonium</center></td> <td bgcolor="yellow"width=5%>114<br><center><elementchimique>Fl</elementchimique></center><br><center>Flérovium</center></td> <td bgcolor="yellow"width=5%>115<br><center><elementchimique>Mc</elementchimique></center><br><center>Moscovium</center></td> <td bgcolor="yellow"width=5%>116<br><center><elementchimique>Lv</elementchimique></center><br><center>Livermorium</center></td> <td bgcolor="yellow"width=5%>117<br><center><elementchimique>Ts</elementchimique></center><br><center>Tennessine</center></td> <td bgcolor="yellow" width=5%>118<br><center><elementchimique>Og</elementchimique></center><br><center>Oganesson</center></td> <tr> <center><table border="0"; style="background-image:url('fondtableau.png');"> <tr> <td bgcolor="green" width=6%>57-71<br><center><elementchimique>Lathanides</elementchimique></center> <td bgcolor="green" width=6%>57<br><center><elementchimique>La</elementchimique></center><br><center>Lathane</center></td> <td bgcolor="green" width=6%>58<br><center><elementchimique>Ce</elementchimique></center><br><center>Cérium</center></td> <td bgcolor="green" width=6%>59<br><center><elementchimique>Pr</elementchimique></center><br><center>Praséodyme</center></td> <td bgcolor="green" width=6%>60<br><center><elementchimique>Nd</elementchimique></center><br><center>Néodyme</center></td> <td bgcolor="green" width=6%>61<br><center><elementchimique>Pm</elementchimique></center><br><center>Prométhium</center></td> <td bgcolor="green" width=6%>62<br><center><elementchimique>Sm</elementchimique></center><br><center>Samarium</center></td> <td bgcolor="green" width=6%>63<br><center><elementchimique>Eu</elementchimique></center><br><center>Europium</center></td> <td bgcolor="green" width=6%>64<br><center><elementchimique>Gd</elementchimique></center><br><center>Gadolinium</center></td> <td bgcolor="green" width=6%>65<br><center><elementchimique>Tb</elementchimique></center><br><center>Terbium</center></td> <td bgcolor="green" width=6%>66<br><center><elementchimique>Dy</elementchimique></center><br><center>Dysprosium</center></td> <td bgcolor="green" width=6%>67<br><center><elementchimique>Ho</elementchimique></center><br><center>Holmium</center></td> <td bgcolor="green" width=6%>68<br><center><elementchimique>Er</elementchimique></center><br><center>Erbium</center></td> <td bgcolor="green" width=6%>69<br><center><elementchimique>Tm</elementchimique></center><br><center>Thullium</center></td> <td bgcolor="green" width=6%>70<br><center><elementchimique>Yb</elementchimique></center><br><center>Ytterbium</center></td> <td bgcolor="green" width=6%>10<br><center><elementchimique>Lu</elementchimique></center><br><center>Lutétium</center></td> </tr> <tr> <td bgcolor="green" width=6%>89-103<br><center><elementchimique>Actinides</elementchimique></center> <td bgcolor="green" width=6%>89<br><center><elementchimique>Ac</elementchimique></center><br><center>Actinium</center></td> <td bgcolor="green" width=6%>90<br><center><elementchimique>Th</elementchimique></center><br><center>Thorium</center></td> <td bgcolor="green" width=6%>91<br><center><elementchimique>Pa</elementchimique></center><br><center>Protacinium</center></td> <td bgcolor="green" width=6%>92<br><center><elementchimique>U</elementchimique></center><br><center>Uranium</center></td> <td bgcolor="green" width=6%>93<br><center><elementchimique>Np</elementchimique></center><br><center>Neptunium</center></td> <td bgcolor="green" width=6%>94<br><center><elementchimique>Pu</elementchimique></center><br><center>Plutonium</center></td> <td bgcolor="green" width=6%>95<br><center><elementchimique>Am</elementchimique></center><br><center>Américium</center></td> <td bgcolor="green" width=6%>96<br><center><elementchimique>Cm</elementchimique></center><br><center>Curium</center></td> <td bgcolor="green" width=6%>97<br><center><elementchimique>Bk</elementchimique></center><br><center>Berkélium</center></td> <td bgcolor="green" width=6%>98<br><center><elementchimique>Cf</elementchimique></center><br><center>Californium</center></td> <td bgcolor="green" width=6%>99<br><center><elementchimique>Es</elementchimique></center><br><center>Einsteinium</center></td> <td bgcolor="green" width=6%>100<br><center><elementchimique>Fm</elementchimique></center><br><center>Fermium</center></td> <td bgcolor="green" width=6%>101<br><center><elementchimique>Md</elementchimique></center><br><center>Mendelévium</center></td> <td bgcolor="green" width=6%>102<br><center><elementchimique>No</elementchimique></center><br><center>Nobélium</center></td> <td bgcolor="green" bgcolor="green" width=6%>103<br><center><elementchimique>Lr</elementchimique></center><br><center>Lawrencium</center></td> </tr> <br><br><br> </table> </center> <br><tailletextes>N'hesitez pas a check <a href="https://lelementarium.fr/" target="_blank"> l'Elementarium</a>, un tableau interactif.</tailletextes> <br><br> <center><Tailletitrepc><mark><u>Chapitre 2 : Mouvements et interactions</u></Tailletitrepc<></mark></center> <br><br><tailletextes>Ce chapitre est divisé en 3 partie: </tailletextes> <ol> <li>Décrire un mouvement</li> <li>Modélisation d'une interaction pardes forces</li> <li>Lien entre mouvement et forces</li> </ol> <center><Tailletitrepc><mark><u>Chapitre 3 : Ondes et signaux</u></Tailletitrepc<></mark></center> <br><br><tailletextes>Ce chapitre est divisé en 4 parties: </tailletextes> <br> <ol> <li>Émission et propagation d’un signal sonore</li> <li>Les sons : fréquence, intensité et perception</li> <li>Intensité et tension dans un circuit complexe</li> <li>Construction de l'image d'un objet</li> </ol> <center><Tailletitrepc><mark><u>Chapitre 4 : Vision et image</u></Tailletitrepc<></mark></center> <br><br><tailletextes>Ce chapitre est divisé en 4 parties: </tailletextes> <ol> <li>Propagation et décomposition de la lumière</li> <li>Réflexion et réfraction de la lumière, le prisme</li> <li>Les lentilles convergentes</li> <li>Construction de l'image d'un objet</li> </ol> <br><tailletextes>La suite du programme sera ajouté au fur et a mesure de l'année, mais vous pouvez vous réferer a <a href="https://www.lumni.fr/lycee/seconde/physique-chimie" target="_blank"> ce site</a> (lumni) ou <a href="http://moncoursdephysiquechimie.weebly.com/" target="_blank"> celui-ci</a> (weebly)</tailletextes> </p> </section> </body> </html>
"use client"; import { useEffect, useState } from "react"; import axios from "axios"; import styled from "styled-components"; const Container = styled.div` padding: 20px; max-width: 600px; margin: 0 auto; `; const Title = styled.h1` text-align: center; font-size: 24px; margin-bottom: 20px; `; const Input = styled.input` padding: 10px; margin-right: 10px; border: 1px solid #ddd; `; const Button = styled.button` padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; &:hover { background-color: #0056b3; } `; const TodoList = styled.ul` list-style-type: none; padding: 0; `; const TodoItem = styled.li` padding: 10px; border: 1px solid #ddd; margin-top: 10px; display: flex; justify-content: space-between; align-items: center; cursor: pointer `; const EditContainer = styled.div` margin-top: 20px; `; interface TodoProps { id: number; title: string; } const Home: React.FC = () => { const [todos, setTodos] = useState<TodoProps[]>([]); const [newTodo, setNewTodo] = useState<string>(""); const [selectedTodo, setSelectedTodo] = useState<TodoProps | null>(null); const [editTitle, setEditTitle] = useState<string>(""); const fetchTodos = async () => { try { const response = await axios.get("/todo"); setTodos(response.data); } catch (error) { console.error("Error fetching todos:", error); } }; const handleAddTodo = async () => { if (newTodo) { try { const response = await axios.post("/todo", { title: newTodo, }); const addedTodo = response.data; setTodos([...todos, addedTodo]); setNewTodo(""); } catch (error) { console.error("Error adding todo:", error); } } }; const handleShow = async (id: number) => { try { const response = await axios.get(`/todo/${id}`); setSelectedTodo(response.data); setEditTitle(response.data?.title); } catch (err) { console.error("Error fetching todo:", err); } }; const handleUpdate = async () => { if (selectedTodo && editTitle) { try { const response = await axios.put(`/todo/${selectedTodo.id}`, { title: editTitle, }); const updatedTodo = response.data; setTodos( todos.map((todo) => (todo.id === updatedTodo.id ? updatedTodo : todo)) ); setSelectedTodo(null); setEditTitle(""); } catch (error) { console.error("Error updating todo:", error); } } }; const handleDelete = async (id: number) => { try { await axios.delete(`/todo/${id}`); setTodos(todos.filter((todo) => todo.id !== id)); setSelectedTodo(null); } catch (error) { console.error("Error deleting todo:", error); } }; useEffect(() => { fetchTodos(); }, []); return ( <Container> <Title>TODO アプリ</Title> <div> <Input value={newTodo} onChange={(e) => setNewTodo(e.target.value)} placeholder="新しいタスク" /> <Button onClick={handleAddTodo}>追加</Button> </div> <TodoList> {todos.map((todo, idx) => ( <TodoItem key={idx} onClick={() => handleShow(todo.id)}> <span>{todo.title}</span> <Button onClick={() => handleDelete(todo.id)}>削除</Button> </TodoItem> ))} </TodoList> {selectedTodo && ( <EditContainer> <h2>タスクの編集</h2> <Input value={editTitle} onChange={(e) => setEditTitle(e.target.value)} placeholder="タスクのタイトルを編集" /> <Button onClick={handleUpdate}>更新</Button> </EditContainer> )} </Container> ); }; export default Home;
/* 6) Создать класс человек с возможностью ездить и останавливаться на: машине, скейтборде,велосипеде(что будет если расширить список ?). */ package gb.oop.seminars; import java.util.Objects; public class Human1 extends Animal { private final int MAX_RUN_DISTANCE = 42_000; private Vehicle curVehicle; public static int count; public Human1(String name) { super(name); this.curVehicle = null; } public void drive(Vehicle vehicle){ if (Objects.isNull(curVehicle) ) { System.out.printf("%s", getName()); vehicle.drive(); curVehicle = vehicle; } else System.out.printf(" уже едет на %s%n",curVehicle.getName()); } public void stop(Vehicle vehicle){ System.out.printf("%s", getName()); if(vehicle.equals(curVehicle)) { vehicle.stop(); curVehicle = null; System.out.println(); } else if (Objects.isNull(curVehicle)) System.out.printf(" ни на чём не едет%n"); else System.out.printf(" едет на %s", curVehicle.getName()); } @Override void run(int distance) { if (distance <= MAX_RUN_DISTANCE) { System.out.println(getName() + " пробежал: " + distance + " метров"); } else { System.out.println(getName() + " НЕ пробежал: " + distance + " метров"); } } @Override void swim(int distance) { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Nop.Core; using Nop.Services.Catalog; using Nop.Services.Customers; using Nop.Services.Localization; using Nop.Plugin.Misc.SimpleLMS.Services; using Nop.Plugin.Misc.SimpleLMS.Domains; using Nop.Plugin.Misc.SimpleLMS.Models; using Nop.Web.Framework.Models.Extensions; using Nop.Web.Areas.Admin.Infrastructure.Mapper.Extensions; using Nop.Services.Media; using Nop.Core.Domain.Customers; namespace Nop.Plugin.Misc.SimpleLMS { public partial class CourseModelFactory { private readonly CourseService _courseService; private readonly ICustomerService _customerService; private readonly ILocalizationService _localizationService; private readonly IProductService _productService; private readonly IWorkContext _workContext; private readonly IPictureService _pictureService; public CourseModelFactory( CourseService courseService, ICustomerService customerService, ILocalizationService localizationService, IProductService productService, IWorkContext workContext, IPictureService pictureService) { _courseService = courseService; _customerService = customerService; _localizationService = localizationService; _productService = productService; _workContext = workContext; _pictureService = pictureService; } public async Task<CourseSearchModel> PrepareCourseSearchModelAsync(CourseSearchModel searchModel) { if (searchModel == null) throw new ArgumentNullException(nameof(searchModel)); searchModel.CourseOverviewList = await PrepareCourseOverviewListModelAsync(searchModel); searchModel.SetGridPageSize(); return searchModel; } public async Task<CourseOverviewListModel> PrepareCourseOverviewListModelAsync(CourseSearchModel searchModel) { if (searchModel == null) throw new ArgumentNullException(nameof(searchModel)); var customer = await _workContext.GetCurrentCustomerAsync(); var courses = await _courseService.SearchCoursesAsync(pageIndex: searchModel.PageNumber - 1, pageSize: searchModel.PageSize > 0 ? searchModel.PageSize : 10, keyword: searchModel.SearchCourseName, userId: customer.Id); var model = new CourseOverviewListModel(); model.Courses = (await PrepareCourseOverviewModelsAsyns(courses, customer)).ToList(); model.LoadPagedList(courses); return model; } private async Task<IList<CourseOverviewModel>> PrepareCourseOverviewModelsAsyns(IPagedList<Course> courses, Customer customer) { if (courses == null) throw new ArgumentNullException(nameof(courses)); var models = new List<CourseOverviewModel>(); foreach (var course in courses) { var model = course.ToModel<CourseOverviewModel>(); var product = await _productService.GetProductByIdAsync(course.ProductId); model.ParentProductName = product.Name; model.CourseProgress = await _courseService.GetCourseProgressPercentByUserId(course.Id, customer.Id); var pictures = await _pictureService.GetPicturesByProductIdAsync(product.Id); if (pictures != null && pictures.Count() > 0) model.ProductMainImage = (await _pictureService.GetPictureUrlAsync(pictures[0])).Url; models.Add(model); } return models; } public async Task<CourseDetail> PrepareCourseDetailModelAsync(CourseDetail courseDetail, Course course, IList<LessonProgress> lessonProgresses) { if (courseDetail == null) throw new ArgumentNullException(nameof(courseDetail)); if (course != null) { //fill in model values from the entity if (course != null) { courseDetail = course.ToModel<CourseDetail>(); } var parentProduct = await _productService.GetProductByIdAsync(course.ProductId); if (parentProduct != null) { courseDetail.ParentProductName = parentProduct.Name; courseDetail.ProductId = parentProduct.Id; } courseDetail.Sections = (await _courseService.GetSectionsByCourseIdAsync(courseDetail.Id)).OrderBy(p => p.DisplayOrder).Select(p => new SectionDetail { CourseName = courseDetail.Name, DisplayOrder = p.DisplayOrder, Id = p.Id, IsFree = p.IsFree, Title = p.Title, CourseId = course.Id, Lessons = _courseService.GetLessonsBySectionIdAsync(p.Id) .GetAwaiter().GetResult().Select(l => l.ToModel<LessonDetail>()).ToList() }).ToList(); for (int i = 0; i < courseDetail.Sections.Count; i++) { var sectionLessons = await _courseService.GetSectionLessonsBySectionIdAsync(courseDetail.Sections[i].Id); for (int j = 0; j < courseDetail.Sections[i].Lessons.Count; j++) { courseDetail.Sections[i].Lessons[j].SectionId = courseDetail.Sections[i].Id; courseDetail.Sections[i].Lessons[j].CourseId = courseDetail.Id; courseDetail.Sections[i].Lessons[j].DisplayOrder = sectionLessons.Where(p => p.LessonId == courseDetail.Sections[i].Lessons[j].Id).SingleOrDefault().DisplayOrder; courseDetail.Sections[i].Lessons[j].Duration = courseDetail.Sections[i].Lessons[j].LessonType == LessonType.Video ? _courseService.GetVideoByLessonIdAsync(courseDetail.Sections[i].Lessons[j].Id).GetAwaiter().GetResult().Duration : 0; var lessonProgress = lessonProgresses.Where(p => p.LessonId == courseDetail.Sections[i].Lessons[j].Id).SingleOrDefault(); courseDetail.Sections[i].Lessons[j].IsCompleted = (lessonProgress != null ? lessonProgress.IsCompleted : false); if (courseDetail.Sections[i].Lessons[j].Video != null && lessonProgress.CurrentlyAt > 0) { courseDetail.Sections[i].Lessons[j].Video.TimeCode = (courseDetail.Sections[i].Lessons[j].Video.VideoType == VideoType.Vimeo ? lessonProgress.CurrentlyAt / 60 + "m" + (lessonProgress.CurrentlyAt % 60) + "s" : lessonProgress.CurrentlyAt.ToString()); } if (courseDetail.CurrentLesson == 0 && !courseDetail.Sections[i].Lessons[j].IsCompleted) { courseDetail.CurrentLesson = courseDetail.Sections[i].Lessons[j].Id; courseDetail.CurrentSection = courseDetail.Sections[i].Id; } } courseDetail.Sections[i].Lessons = courseDetail.Sections[i].Lessons.OrderBy(p => p.DisplayOrder).ToList(); } if (courseDetail.CurrentLesson == 0) { var currSection = (from p in courseDetail.Sections where p.Lessons.Count > 0 select p).FirstOrDefault(); if (currSection != null) { courseDetail.CurrentLesson = currSection.Lessons.FirstOrDefault().Id; courseDetail.CurrentSection = currSection.Id; } } } return courseDetail; } public async Task<LessonDetail> PrepareLessonModelAsync(LessonDetail lessonDetail, Lesson lesson) { if (lessonDetail == null) throw new ArgumentNullException(nameof(lessonDetail)); if (lesson != null) { lessonDetail = lesson.ToModel<LessonDetail>(); if (lesson.LessonType == LessonType.Video) { lessonDetail.Video = (await _courseService.GetVideoByLessonIdAsync(lessonDetail.Id)).ToModel<VideoDetail>(); } } return lessonDetail; } } }
//-------------------------------------------------------------------- // // Laboratory 5 stackarr.cpp // // SOLUTION: Array implementation of the Stack ADT // //-------------------------------------------------------------------- #include "stackarr.h" //-------------------------------------------------------------------- template <class DT> Stack<DT>::Stack(int maxNumber) { maxSize = maxNumber; top = -1; dataItems = new DT[maxSize]; } //-------------------------------------------------------------------- template <class DT> Stack<DT>:: ~Stack() { delete[] dataItems; } //-------------------------------------------------------------------- template <class DT> void Stack<DT>::push(const DT& newDataItem) { if (top == maxSize - 1) { cout << "Full Stack" << endl; } else { top += 1; dataItems[top] = newDataItem; } } //-------------------------------------------------------------------- template <class DT> DT Stack<DT>::pop() { DT item = NULL; if (isEmpty() == true) { cout << "Empty Stack" << endl; } else { item = dataItems[top]; top -= 1; return item; } } //-------------------------------------------------------------------- template <class DT> void Stack<DT>::clear() { top = -1; } //-------------------------------------------------------------------- template <class DT> bool Stack<DT>::isEmpty() const { if (top == -1) return true; else return false; } //-------------------------------------------------------------------- template <class DT> bool Stack<DT>::isFull() const { if (top == maxSize - 1) return true; else return false; } //-------------------------------------------------------------------- template < class DT > void Stack<DT>::showStructure() const // Array implementation. Outputs the data items in a stack. If the // stack is empty, outputs "Empty stack". This operation is intended // for testing and debugging purposes only. { int j; // Loop counter if (top == -1) cout << "Empty stack" << endl; else { cout << "top = " << top << endl; for (j = 0; j < maxSize; j++) cout << j << "\t"; cout << endl; for (j = 0; j <= top; j++) cout << dataItems[j] << "\t"; cout << endl; } }
import React from "react"; import { Container, Logo, LogoutBtn } from "../index"; import { Link, useNavigate } from "react-router-dom"; import { useSelector } from "react-redux"; function Header() { const authStatus = useSelector((state) => state.auth.status) const navigate = useNavigate() const navItems = [ { name: 'Home', slug: "/", active: true }, { name: "Login", slug: "/login", active: !authStatus, }, { name: "Signup", slug: "/signup", active: !authStatus, }, { name: "All Posts", slug: "/all-posts", active: authStatus, }, { name: "Add Post", slug: "/add-post", active: authStatus, }, ] return ( <header className='fixed top-0 left-0 right-0 z-50 text-white shadow-md bg-neutral-800'> <Container> <nav className='flex items-center'> <Link to='/' className='ml-8'> <Logo width='100px'/> </Link> <ul className='flex-grow flex items-center justify-end space-x-4'> {navItems.map((item) => item.active ? ( <li key={item.name} className='last:mr-0'> <button onClick={() => navigate(item.slug)} className='px-4 py-2 rounded-full text-white hover:bg-pink-400 transition-colors duration-200 ease-in-out font-medium' > {item.name} </button> </li> ) : null )} {authStatus && ( <li> <LogoutBtn /> </li> )} </ul> </nav> </Container> </header> ) } export default Header;
import { Button } from "@chakra-ui/button"; import { Input, InputGroup, InputLeftAddon } from "@chakra-ui/input"; import { VStack } from "@chakra-ui/layout"; import { Select } from "@chakra-ui/select"; import { Textarea } from "@chakra-ui/textarea"; import { useToast } from "@chakra-ui/toast"; import React, { memo, useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { useDispatch } from "react-redux"; import { createTask, emptyReducer, getUsers } from "../../redux/actions/task"; import CustomModal from "../common/Modal"; import CustomText from "../common/Text"; import moment from "moment"; import { getAllProjects } from "../../redux/actions/home"; import { Alert, AlertIcon } from "@chakra-ui/alert"; import microValidator from "micro-validator"; import { pxToEm } from "../../utils/commonMethods"; const AddTaskModal = (props) => { const { isOpen, onClose, id } = props; const dispatch = useDispatch(); const users = useSelector((state) => state?.task?.Users?.data?.data); const taskCreate = useSelector((state) => state?.task?.Task?.data); const [error, setError] = useState({ name: "", description: "", start_time: "", end_time: "", assign_to: "", cost: "", }); const toast = useToast(); const [message, setMessage] = useState(""); useEffect(() => { if (taskCreate?.status === 201 && taskCreate?.success) { setMessage("Task created successfully"); dispatch(getAllProjects()); dispatch(emptyReducer()); } if ( taskCreate?.status && taskCreate?.status !== 201 && taskCreate?.success === false ) { setMessage("Something went wrong"); } }, [taskCreate, emptyReducer]); const [data, setData] = useState({ projectid: id, name: "", description: "", start_time: "", end_time: "", assign_to: "", cost: "", }); const validate = (data) => { const errors = microValidator.validate( { name: { required: { errorMsg: `Name is required`, }, }, description: { required: { errorMsg: `Description is required`, }, }, start_time: { required: { errorMsg: `Start time is required`, }, }, end_time: { required: { errorMsg: `End time is required`, }, }, assign_to: { required: { errorMsg: `This field is required`, }, }, cost: { required: { errorMsg: `Cost is required`, }, }, }, data ); setError({ ...error, name: errors.name, description: errors.description, start_time: errors.start_time, end_time: errors.end_time, assign_to: errors.assign_to, cost: errors.cost, }); return errors; }; const inputChange = (e) => { console.log(e.target.name, e.target.value); setData({ ...data, [e.target.name]: e.target.name === "start_time" ? moment(e.target.value).utc().format() : e.target.name === "end_time" ? moment(e.target.value).utc().format() : e.target.value, }); }; useEffect(() => { dispatch(getUsers()); }, []); const handleTaskSubmit = (e) => { e.preventDefault(); const err_resp = validate(data) || {}; if (Object.keys(err_resp).length === 0) { dispatch(createTask(data)); } }; return ( <CustomModal isOpen={isOpen} onClose={onClose} title="Add Task"> <form onSubmit={handleTaskSubmit}> <VStack alignItems="flex-start" w="full" spacing={5}> <VStack w="full" alignItems="flex-start"> <CustomText>Name</CustomText> <Input name="name" onChange={inputChange} isInvalid={error?.name?.length ? true : false} /> {error?.name?.length > 0 && ( <CustomText mt={pxToEm(8)} color="red.400" variant="sm"> {/* <WarningFill /> */} &nbsp;{error?.name} </CustomText> )} </VStack> <VStack w="full" alignItems="flex-start"> <CustomText>Description</CustomText> <Textarea name="description" onChange={inputChange} isInvalid={error?.description?.length ? true : false} /> {error?.description?.length > 0 && ( <CustomText mt={pxToEm(8)} color="red.400" variant="sm"> {/* <WarningFill /> */} &nbsp;{error?.description} </CustomText> )} </VStack> <VStack w="full" alignItems="flex-start"> <CustomText>Start date</CustomText> <Input name="start_time" type="date" onChange={inputChange} isInvalid={error?.start_time?.length ? true : false} /> {error?.start_time?.length > 0 && ( <CustomText mt={pxToEm(8)} color="red.400" variant="sm"> {/* <WarningFill /> */} &nbsp;{error?.start_time} </CustomText> )} </VStack> <VStack w="full" alignItems="flex-start"> <CustomText>End date</CustomText> <Input name="end_time" type="date" onChange={inputChange} isInvalid={error?.end_time?.length ? true : false} /> {error?.end_time?.length > 0 && ( <CustomText mt={pxToEm(8)} color="red.400" variant="sm"> {/* <WarningFill /> */} &nbsp;{error?.end_time} </CustomText> )} </VStack> <VStack w="full" alignItems="flex-start"> <CustomText>Assign to</CustomText> <Select placeholder="Select option" name="assign_to" onChange={inputChange} isInvalid={error?.assign_to?.length ? true : false} > {(users || []).map((user) => { return ( <option value={user?._id} key={user?._id}> {user?.name} </option> ); })} </Select> {error?.assign_to?.length > 0 && ( <CustomText mt={pxToEm(8)} color="red.400" variant="sm"> {/* <WarningFill /> */} &nbsp;{error?.assign_to} </CustomText> )} </VStack> <VStack w="full" alignItems="flex-start"> <CustomText>Hourly Cost</CustomText> <InputGroup> <InputLeftAddon children="$" /> <Input name="cost" onChange={inputChange} type="number" isInvalid={error?.cost?.length ? true : false} /> </InputGroup> {error?.cost?.length > 0 && ( <CustomText mt={pxToEm(8)} color="red.400" variant="sm"> {/* <WarningFill /> */} &nbsp;{error?.cost} </CustomText> )} </VStack> {message === "Task created successfully" ? ( <Alert status="success"> <AlertIcon /> {message} </Alert> ) : message === "Something went wrong" ? ( <Alert status="error"> <AlertIcon /> {message} </Alert> ) : null} <Button colorScheme="blue" type="submit" size="sm"> Add task </Button> </VStack> </form> </CustomModal> ); }; export default memo(AddTaskModal);
/** * Feb 20, 201111:23:08 AM * gblog-core * org.gaoyoubo.core.util * ClassLoaderUtils.java * @author gaoyb */ package org.mspring.platform.utils; import java.io.IOException; import java.io.InputStream; import java.net.URL; /** * @author gaoyb * */ public class ClassLoaderUtils { /** * 获取类路径下的资源 * * @param resourceName * @param callingClass * @return */ public static URL getResource(String resourceName, Class callingClass) { URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); if (url == null) { url = ClassLoaderUtils.class.getClassLoader().getResource(resourceName); } if (url == null) { ClassLoader cl = callingClass.getClassLoader(); if (cl != null) url = cl.getResource(resourceName); } if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) { return getResource('/' + resourceName, callingClass); } return url; } /** * 获取类路径下的资源 * * @param resourceName * @param callingClass * @return */ public static InputStream getResourceAsStream(String resourceName, Class callingClass) { URL url = getResource(resourceName, callingClass); try { return ((url != null) ? url.openStream() : null); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 获取classpath下的资源 * * @param resourceName * @return */ public static URL getClasspathResource(String resourceName) { if (resourceName == null) { return null; } if (StringUtils.startsWithIgnoreCase(resourceName, "classpath:")) { resourceName = StringUtils.substringAfter(resourceName, ":"); } if (StringUtils.startsWithAny(resourceName, new String[] { "/", "\\" })) { resourceName = resourceName.substring(1); } return ClassLoader.getSystemResource(resourceName); } /** * 获取classpath下的资源 * * @param resourceName * @return */ public static InputStream getClasspathResourceAsStream(String resourceName) { URL url = getClasspathResource(resourceName); try { return ((url != null) ? url.openStream() : null); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 加载类 * * @param className * @param callingClass * @return */ public static Class loadClass(String className, Class callingClass) { try { return Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e) { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } catch (ClassNotFoundException exc) { try { return callingClass.getClassLoader().loadClass(className); } catch (ClassNotFoundException e1) { throw new RuntimeException(e1); } } } } } /** * newInstance * * @param className * @param callingClass * @return */ public static Object instantiate(String className, Class callingClass) { return instantiate(loadClass(className, callingClass)); } /** * newInstance * * @param clazz * @return */ public static Object instantiate(Class clazz) { try { return clazz.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static void printClassLoader() { System.out.println("ClassLoaderUtil.printClassLoader"); printClassLoader(Thread.currentThread().getContextClassLoader()); } public static void printClassLoader(ClassLoader cl) { System.out.println("ClassLoaderUtil.printClassLoader(cl = " + cl + ")"); if (cl != null) printClassLoader(cl.getParent()); } }
package javaComparator; import java.util.*; import java.lang.Integer; class Checker implements Comparator<Player> { public int compare(Player a, Player b) { int s1 = a.score; int s2 = b.score; String str1 = a.name; String str2 = b.name; int sCompare = Integer.compare(s2,s1); if(sCompare == 0) { return str1.compareTo(str2); } else { return sCompare; } } } class Player{ String name; int score; Player(String name, int score){ this.name = name; this.score = score; } } public class ComparatorExample { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); Player[] player = new Player[n]; Checker checker = new Checker(); for(int i = 0; i < n; i++){ player[i] = new Player(scan.next(), scan.nextInt()); } scan.close(); Arrays.sort(player, checker); for(int i = 0; i < player.length; i++){ System.out.printf("%s %s\n", player[i].name, player[i].score); } } }
package com.lyming.controller; import com.lyming.user.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; /** * description: * * @author lyming * @date 2020/8/6 2:14 上午 */ @RestController public class MovieController { private final Logger logger = LoggerFactory.getLogger(MovieController.class); @Autowired private RestTemplate restTemplate; @Autowired private LoadBalancerClient loadBalancerClient; @GetMapping("/user/{id}") public User findById(@PathVariable Long id) { return restTemplate.getForObject("http://microservice-provider-user/" + id, User.class); } @GetMapping("/log-user-instance") public void logUserInstance(){ ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user"); logger.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; namespace _26._10._23.Т8._1 { internal class Program { //1.1. Вызов пустого метода Func без возвращения значений для вычисления функции y=x^2 //and //1.2. Преобразуйте программу так, чтобы метод Func вызывался n раз. //static void Main(string[] args) //{ // Write("Введине n - "); // int n = Convert.ToInt32(ReadLine()); // for(int i=0; i<n; i++) // { // Func(); // } // Read(); //} //public static void Func() //{ // Write("Введите х - "); // int x = Convert.ToInt32(ReadLine()); // int y = x * x; // Write(y); //} //....................................// //1.3. Преобразуйте программу так, чтобы метод Func вычислял значение выражения: //static void Main(string[] args) //{ // Func(); // Read(); //} //public static void Func() //{ // Write("Введите х - "); // double x = Convert.ToInt32(ReadLine()); // double y = (3*Math.Pow(x, 2)+8*x-10)/15; // Write(y); //} //....................................// //Задача 2. Нахождение суммы двух чисел с использованием метода сложения двух чисел. //static void Main(string[] args) //{ // Write("Введите х - "); // int x = Convert.ToInt32(ReadLine()); // Write("Введите y - "); // int y = Convert.ToInt32(ReadLine()); // Write(Sum(x,y)); // Read(); //} //public static int Sum(int x,int y) //{ // return x + y; //} //....................................// //Задача 3. Вызов метода Func для вычисления функции y=x2, //в который будет передаваться значение х от a до b с шагом h, а сам метод возвращал значение y. //static void Main(string[] args) //{ // Func(); // Read(); //} //public static void Func() //{ // Write("Введите x - "); // int x=Convert.ToInt32(ReadLine()); // Write("Введите a - "); // int a = Convert.ToInt32(ReadLine()); // Write("Введите b - "); // int b = Convert.ToInt32(ReadLine()); // Write("Введите h - "); // int h = Convert.ToInt32(ReadLine()); // for(int i=a;i<=b;i+=h) // { // if (a<=x&& x<= b) // { // double y = Math.Pow(x, 2); // WriteLine($"y={y},x={x}"); // x += h; // } // else // { // WriteLine("x не в ходит в диапазон от a до b"); // } // } //} //....................................// //Задача 4. Составьте таблицу значений функции y = 5x² - 2x +1 на отрезке [-5; 5] с шагом h = 2 с использованием дополнительного метода. //static void Main(string[] args) //{ // Func(); // Read(); //} //public static void Func() //{ // Write("Введите x - "); // int x = Convert.ToInt32(ReadLine()); // for (int i = -5; i <= 5; i ++) // { // if (-5 <= x && x <= 5) // { // double y = 5*Math.Pow(x, 2)-2*x+1; // WriteLine($"y={y},x={x}"); // x += 2; // } // } //} //....................................// //Задача 5. Напишите дополнительный метод для вычисления функции: //static void Main(string[] args) //{ // Write("Введите x - "); // int x=Convert.ToInt32(Console.ReadLine()); // Func(x); // Read(); //} //public static void Func(int x) //{ // double y; // if (x < 5) // { // y = (4 * Math.Pow(x, 2) + 1) / x - 5; // } // else // { // y =3 * Math.Pow(x, 2) - 2; // } // WriteLine(y); //} //....................................// //Задача 6. Создайте приложение, которое выводит сумму, вычитание, умножение и деление двух параметров входных данных. //static void Main(string[] args) //{ // Write("Введите x - "); // int x = Convert.ToInt32(ReadLine()); // Write("Введите y - "); // int y = Convert.ToInt32(ReadLine()); // int sum = Add(x, y); // int dif = Dif(x, y); // int mult = Mult(x, y); // double delay = Delay(x, y); // WriteLine($"Сумма = {sum}\n Разность = {dif}\n Произведение = {mult}\n Деление = {delay}"); // Read(); //} //public static int Add(int x, int y) //{ // return x + y; //} //public static int Dif(int x, int y) //{ // return x - y; //} //public static int Mult(int x, int y) //{ // return x * y; //} //public static double Delay(int x, int y) //{ // return (double)x / y; //} //....................................// // Домашнее задание. //1. Нахождение максимальной величины из двух целых переменных a, b. //static void Main(string[] args) //{ // Maximum(); // ReadLine(); //} //static void Maximum() //{ // WriteLine("Введите ваши числа - "); // int[] mass = new int[3]; // int i; // for (i = 0; i < mass.Length; i++) // { // int a = Convert.ToInt32(ReadLine()); // mass[i] = a; // } // double sum = 0; // for (int b = 0; b < mass.Length; b++) // { // sum += mass[b]; // } // double cr = sum / mass.Length; // WriteLine(cr); //} //................// //2. Вычислить среднее арифметическое трех действительных чисел. //static void Main(string[] args) //{ // Arifm(); // ReadKey(); //} //static void Arifm() //{ // Write("Введите a - "); // double a = Convert.ToDouble(ReadLine()); // Write("Введите b - "); // double b = Convert.ToDouble(ReadLine()); // Write("Введите c - "); // double c = Convert.ToDouble(ReadLine()); // WriteLine("Среднее арифметич. - "+ (a + b + c)/3); //} //................// //3. Составьте таблицу значений функции y = 4x² + 5x - 10 на отрезке [-9; 9] с шагом h = 3. static void Main(string[] args) { Func(); Read(); } public static void Func() { Write("Введите x - "); int x = Convert.ToInt32(ReadLine()); for (int i = -9; i <= 9; i++) { if (-9 <= x && x <= 9) { double y = 4 * Math.Pow(x, 2) + 5 * x - 10; WriteLine($"y - {y}\t x - {x}"); x += 3; } } } } }
#3-d plot of z = 2x^2 - y^2 x_min <- -3 x_max <- 3 y_min <- -3 y_max <- 3 x <- seq(-3, 3, by = 0.1) y <- seq(-3, 3, by = 0.1) z <- matrix(nrow=length(x), ncol=length(y)) for(i in 1:length(x)){ for(j in 1:length(y)){ z[i,j] <- 2*x[i]^2 - y[j]^2 } } contour(x,y,z) library(mvtnorm) min <- -3 max <- 3 var_x <- 1.5 var_y <- 1.5 cor_xy <- 0.25 Sigma <- cbind(c(var_x,cor_xy*sqrt(var_x)*sqrt(var_y)),c(cor_xy*sqrt(var_x)*sqrt(var_y),var_y)) x <- seq(min, max, by = 0.1) y <- seq(min, max, by = 0.1) z <- matrix(nrow=length(x), ncol=length(y)) co_df <- data.frame('x', 'y', 'z') for (i in 1:length(x)){ for (j in 1:length(y)){ z[i,j] <- dmvnorm(c(x[i],y[j]),c(0,0),Sigma) } } contour(x, y, z) co_df <- data.frame('x' = x, 'y' = y) ggplot(co_df, aes(x = x, y = y, z = z)) + geom_contour() df.grad <- expand.grid(x = seq(-4,4, by = 0.1),y = seq(-4,4, by = 0.1)) dens <- cbind(df.grad, z = dmvnorm(df.grad,c(0,0), Sigma)) ggplot(dens, aes(x = x, y = y, z = z)) + geom_contour_filled() library(MASS) plot(mvrnorm(1000, mu = c(0,0), Sigma))
package com.interview.java8.flatmap; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.ConcurrentHashMap; class Employee { private String name; private int age; public Employee(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Employee [name=" + name + ", age=" + age + "]"; } } public class SortingExampleInJava { public static void main(String[] args) { List<Employee> employees = new ArrayList<>(); employees.add(new Employee("Bob", 35)); employees.add(new Employee("John", 30)); employees.add(new Employee("Alice", 25)); employees.add(new Employee("Adam", 20)); employees.add(new Employee("Baby", 25)); ConcurrentHashMap<String,String> hs=new ConcurrentHashMap<>(); System.out.println(employees); Collections.sort(employees, Comparator.comparing(Employee::getName)); System.out.println(employees); Collections.sort(employees,Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)); System.out.println(employees); } }
--- title: Recommended RBAC Configuration --- This page summarises the contents of the [securing access to the dashboard](securing-access-to-the-dashboard.mdx), [service account permissions](service-account-permissions.mdx) and [user permissions](user-permissions.mdx). They should be read in addition to this page in order to understand the suggestions made here and their ramifications. This page is purposefully vague as the intention is to give a broad idea of how such a system could be implemented, not the specifics as that will be dependent on your specific circumstances and goals. ## Summary The general recommendation is to use OIDC and a small number of groups that Weave GitOps can impersonate. OIDC is the recommended method for managing authentication as it decouples the need to manage user lists from the application, allowing it to be managed via a central system designed for that purpose (i.e. the OIDC provider). OIDC also enables the creation of groups (either via your provider's own systems or by using a connector like [Dex](../guides/setting-up-dex.md)). Configuring Weave GitOps to impersonate kubernetes groups rather than users has the following benefits: * A user's permissions for impersonation by Weave GitOps can be separate from any other permissions that they may or may not have within the cluster. * Users do not have to be individually managed within the cluster and can have their permissions managed together. ## Example set up Assume that your company has the following people in OIDC * Aisha, a cluster admin, who should have full admin access to Weave GitOps * Brian, lead of team-A, who should have admin permissions to their team's namespace in Weave GitOps and readonly otherwise * June and Jo, developers in team-A who should have read-only access to Weave GitOps You could then create 3 groups: * `wego-admin` - Bound to the `ClusterRole`, created by Helm, `wego-admin-cluster-role` - Aisha is the only member * `wego-team-a-admin` - Bound to a `Role`, using the same permissions as `wego-admin-role`, created in Team's namespace - Brian and Aisha are members * `wego-readonly` - Bound to a `ClusterRole` that matches `wego-admin-cluster-role` but with no `patch` permissions. - Aisha, Brian, June & Jo are all members The Weave GitOps service account can then be configured with: ```yaml rbac: impersonationResourceNames: ["wego-admin", "wego-team-a-admin", "wego-readonly"] impersonationResources: ["groups"] ``` so that only these three groups can be `impersonated` by the service account. :::caution Using OIDC for cluster and Weave GitOps Authentication If the same OIDC provider is used to authenticate a user with the cluster itself (e.g. for use with `kubectl`) and to Weave GitOps then, depending on OIDC configuration, they may end up with the super-set of their permissions from Weave GitOps and any other permissions granted to them. This can lead to un-intended consequences (e.g. viewing `secrets`). To avoid this OIDC providers will often let you configure which groups are returned to which clients: the Weave GitOps groups should not be returned to the cluster client (and vice versa). ::: ### Code The yaml to configure these permissions would look roughly like: <details><summary>Expand to see example RBAC</summary> ```yaml # Admin cluster role apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: wego-admin-cluster-role rules: - apiGroups: [""] resources: ["secrets", "pods" ] verbs: [ "get", "list" ] - apiGroups: ["apps"] resources: [ "deployments", "replicasets"] verbs: [ "get", "list" ] - apiGroups: ["kustomize.toolkit.fluxcd.io"] resources: [ "kustomizations" ] verbs: [ "get", "list", "patch" ] - apiGroups: ["helm.toolkit.fluxcd.io"] resources: [ "helmreleases" ] verbs: [ "get", "list", "patch" ] - apiGroups: ["source.toolkit.fluxcd.io"] resources: [ "buckets", "helmcharts", "gitrepositories", "helmrepositories", "ocirepositories" ] verbs: [ "get", "list", "patch" ] - apiGroups: [""] resources: ["events"] verbs: ["get", "watch", "list"] --- # Read only cluster role apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: wego-readonly-role rules: # All the 'patch' permissions have been removed - apiGroups: [""] resources: ["secrets", "pods" ] verbs: [ "get", "list" ] - apiGroups: ["apps"] resources: [ "deployments", "replicasets"] verbs: [ "get", "list" ] - apiGroups: ["kustomize.toolkit.fluxcd.io"] resources: [ "kustomizations" ] verbs: [ "get", "list" ] - apiGroups: ["helm.toolkit.fluxcd.io"] resources: [ "helmreleases" ] verbs: [ "get", "list" ] - apiGroups: ["source.toolkit.fluxcd.io"] resources: [ "buckets", "helmcharts", "gitrepositories", "helmrepositories", "ocirepositories" ] verbs: [ "get", "list" ] - apiGroups: [""] resources: ["events"] verbs: ["get", "watch", "list"] --- # Bind the cluster admin role to the wego-admin group apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: wego-cluster-admin subjects: - kind: Group name: wego-admin # only Aisha is a member apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: wego-admin-cluster-role apiGroup: rbac.authorization.k8s.io --- # Bind the admin role in the team-a namespace for the wego-team-a-admin group apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: wego-team-a-admin-role namespace: team-a subjects: - kind: Group name: wego-team-a-admin # Aisha & Brian are members apiGroup: rbac.authorization.k8s.io roleRef: # Use the cluster role to set rules, just bind them in the team-a namespace kind: ClusterRole name: wego-admin-role apiGroup: rbac.authorization.k8s.io --- # Bind the readonly role to the readonly group apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: wego-readonly-role subjects: - kind: Group name: wego-readonly # Everyone is a member apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: wego-readonly-role apiGroup: rbac.authorization.k8s.io --- ``` </details>
#lex import ply.lex as lex from plygenCreator import action tokens=('NUMBER','ID','DEF','TAB','RETURN','IF','ELIF','ELSE','PRINT','FOR','IN','RANGE','GREATERTHAN','MINUS','SPACE','COMMENT','AND','OR','NOT') literals=['+','(',')',':',',','<','/','*','=','!','\'','"','%'] lineCount=0 def t_newline(t): r'\n+' global lineCount lineCount=lineCount+1 def t_NUMBER(t): r'\d+' t.value = int(t.value) return t def t_IF(t): r'if' return t def t_FOR(t): r'for' return t def t_DEF(t): r'def' return t def t_TAB(t): r'\t' return t def t_SPACE(t): r'\s' return t def t_RETURN(t): r'return' return t def t_ELIF(t): r'elif' return t def t_PRINT(t): r'print' return t def t_IN(t): r'in' return t def t_RANGE(t): r'range' return t def t_AND(t): r'and' return t def t_OR(t): r'or' return t def t_NOT(t): r'not' return t def t_GREATERTHAN(t): r'>' return t def t_MINUS(t): r'-' return t def t_ID(t): r'[a-zA-Z_0-9][a-zA-Z_0-9]*' return t def t_COMMENT(t): r'\'\'\'[if|while|do|for|print|elif|def|for|in|(|)|-|[a-zA-Z0-9]+]*\'\'\'' return t '''def p_empty(p): 'empty :' pass''' def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1) lexer=lex.lex() lexer.input("def computeGCD(x, y):\ if x > y:\ small = y\ else:\ small = x\ for i in range(1, small+1):\ if((x % i == 0) and (y % i == 0)):\ gcd = i\ return gcd\ a = 60\ b= 48\ print (computeGCD(60,48))") #Tokenize '''while True: tok = lexer.token() if not tok: break # No more input print(tok.type)'''
import React from "react"; import { Accordion, AccordionItem, AccordionItemButton, AccordionItemHeading, AccordionItemPanel, } from "react-accessible-accordion" import "./forecast.css" const WEEK_DAYS = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] const Forecast = ({data}) =>{ const dayInAWeek = new Date().getDay(); const forecastDays = WEEK_DAYS.slice(dayInAWeek, WEEK_DAYS).concat(WEEK_DAYS.slice(0,dayInAWeek)); return( <> <label className="title"> <Accordion allowZeroExpanded> {data.list.slice(0,7).map((item, idx) => { <AccordionItem key={idx}> <AccordionItemHeading> <AccordionItemButton> <div className="daily-item"> <img src={`icons/${item.weather[0].icon}.png`} className="icon-small" alt="weather"/> <label className="day">{forecastDays[idx]}</label> <label className="description">{item.weather[0].description}</label> <label className="min-max">{Math.round(item.main.temp_max)}°C/{Math.round(item.main.temp_min)}°C</label> </div> </AccordionItemButton> </AccordionItemHeading> <AccordionItemPanel> <div className="daily-details-grid"> <label>Pressure:</label> <label>{item.main.pressure}</label> </div> <div className="daily-details-grid-item"> <label>Humidity:</label> <label>{item.main.humidity}</label> </div> <div className="daily-details-grid-item"> <label>Clouds:</label> <label>{item.clouds.all}%</label> </div> <div className="daily-details-grid-item"> <label>Humidity:</label> <label>{item.wind.speed} m/s</label> </div> <div className="daily-details-grid-item"> <label>Sea level:</label> <label>{item.main.sea_level}m</label> </div> <div className="daily-details-grid-item"> <label>Feels like:</label> <label>{item.main.feels_like}°C</label> </div> </AccordionItemPanel> </AccordionItem> })} </Accordion> </label> </> ) } export default Forecast;
import { matchers } from 'jest-json-schema'; import request from 'supertest'; import express from 'express'; import {itemsRouter} from '../src/items/items.router'; expect.extend(matchers); const app = express(); app.use("/items", itemsRouter); it('responds to /:id', async () => { const schema = { properties: { id: { type: 'integer' } }, required: ['id'], }; const res = await request(app).get('/items/1'); expect(res.statusCode).toBe(200); expect(res.body).toMatchSchema(schema); }); it('responds to /', async () => { const res = await request(app).get('/items'); expect(res.statusCode).toBe(200); });
import React, { useState } from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; import { useNavigate } from "react-router-dom"; /* Components */ import Course from "../../components/Course"; import { FlexContainer } from "../../components/FlexContainer"; import Review from "../../components/Review"; import Image from "../../components/Image"; import CenterModal from "../../components/CenterModal"; /* Data */ import writeReview from "../../lib/img/icon/writeReview.svg"; const Screen = styled(FlexContainer)` width: 100%; height: 100%; flex-direction: column; position: relative; padding: 1%; `; const ContentWrapper = styled(FlexContainer)` width: 100%; flex-direction: column; `; const ReviewCont = styled.div` width: 90%; height: 50vh; overflow-y: scroll; margin-top: 1%; `; const StyleTitle = styled.h1` font-size: 5vh; font-weight: 800; @media (max-width: 820px) { font-size: 5vh; font-weight: 600; } @media (max-width: 400px) { font-size: 3vh; font-weight: 600; } `; const AddCourseCont = styled(FlexContainer)` width: 5vw; height: 5vw; margin: 3%; padding: 1.2%; background-color: ${props => props.theme.screenBg}; border: 0.4vw solid #ab0000; border-radius: 50%; z-index: 10; position: absolute; bottom: 0; right: 0; transition: all 0.3s ease 0s; cursor: pointer; outline: none; &:hover { background-color: #ab0000; transform: translateY(-7px); } @media (max-width: 820px) { background-color: #ab0000; width: 8vw; height: 8vw; } @media (max-width: 400px) { background-color: #ab0000; width: 10vw; height: 10vw; width: 10vw; height: 10vw; } `; const CourseDetail = ({ courseID }) => { const [isModalShow, setIsModalShow] = useState(false); const [focusedReview, setFocusedReview] = useState(""); const navigation = useNavigate(); const _handleCreateReview = () => { navigation("/review-course"); }; const _onHideModal = () => { setIsModalShow(false); setFocusedReview(""); }; const _onDeleteReview = () => { console.log("delete review!"); // delete 'focusedReview' _onHideModal(); }; return ( <Screen> <StyleTitle>Course</StyleTitle> <ContentWrapper> <Course courseID={"111"} courseName='Genre and Historical Movements' LecturerName='Anas Sarwar' rateValue={4.5} isNavHidden={true} /> <ReviewCont> <Review courseInfo={{}} setModalShow={setIsModalShow} setFocusedReview={setFocusedReview} /> <Review courseInfo={{}} setModalShow={setIsModalShow} setFocusedReview={setFocusedReview} /> <Review courseInfo={{}} setModalShow={setIsModalShow} setFocusedReview={setFocusedReview} /> <Review courseInfo={{}} setModalShow={setIsModalShow} setFocusedReview={setFocusedReview} /> </ReviewCont> </ContentWrapper> <AddCourseCont onClick={_handleCreateReview}> <Image src={writeReview} alt={"Feather icon. Click here to write a review of the course"} style={{ width: "100%", height: "100%", }} /> </AddCourseCont> <CenterModal header='Are you sure?' desc='Do you want to delete this review?' BtnName='Delete' BtnOnClick={_onDeleteReview} isModalShow={isModalShow} onHide={_onHideModal} /> </Screen> ); }; export default CourseDetail;
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './pages/home/home.component'; import { AboutComponent } from './pages/about/about.component'; import { ContactComponent } from './pages/contact/contact.component'; import { PostsModule } from './pages/posts/posts.module'; const routes: Routes = [ { path: 'home', component: HomeComponent, }, { path: 'about', component: AboutComponent, }, { path: 'contact', component: ContactComponent, }, { path: 'posts', //loadChildren: './pages/posts/posts.module#PostsModule' loadChildren: () => import('./pages/posts/posts.module').then(m => m.PostsModule) }, { path:'** ', redirectTo:'home' } ]; @NgModule({ declarations: [], imports: [RouterModule.forRoot(routes)], exports:[RouterModule] }) export class AppRoutingModule {}
Début d'année 2021, mon objectif est clair : **Il me faut constituer un portoflio** Celui-ci se déploiera autour des différentes prestations que je propose : * **Maîtrise de la totalité des étapes du développement de projets web**, * Conception : réception du besoin, maquettage, architecture logicielle, * **Déploiement et développement de fonctionnalités spécifiques** sur CMS (WordPress) et statiques (JAMStack + CI/CD), * Développement **full-stack JavaScript** (Node.js + ES6). Pour cela ma flotille de sites (et autres productions) **doit présenter et pouvoir répondre à un ensemble de *use cases***. Heureusement, parce que je dédie mon temps aux projets dont j'ai moi-même vraiment besoin, les cas pratiques sont clairs et adressés. Faisons un point sur ces différents travaux, leurs objectifs et leur roadmap. ## [rimarok.com](/) Pour le moment, bien qu'en discutant avec ma coach [Anaëlle Sorignet](https://freetheideas.fr/) la séparation me semble moins pertinente qu'il y a quelques mois, **rimarok.com a pour vocation de présenter mon activité de freelance développeur web** (par opposition à imrok.fr, dédié lui à mes activités créatives). Les restes d'une croyance selon laquelle un employeur ne saurait apprécier les parts sensible et artistique de ma personnalité. ### Articles Très récemment, rimarok.com vient de récupérer le motif ARTICLE de [`motifs-js`](https://github.com/Skaant/motifs-js) et je commence à y ajouter des articles que je souhaite de plus en plus consistents, bien rédigés et fréquents. Les sujets en perspective : * **L'éco-conception**, évidemment, * **Le développement web**, évidemment aussi, * Les actualités "techniques" de mes sites internet, * La présentation de mes prestations secondaires. J'aimerais avoir le temps d'y **adjoindre des tutoriels**. À court terme, je souhaiterais parler de la création de thème WordPress, de thème Bootstrap et des autres sujets rencontrés lors du développement du framework `motifs-js`. ### Sujets transverses Comme pour le reste de mes sites, l'objectif est de rapidement pouvoir intégrer (toujours par le biais de `motifs-js`) : * Un générateur de sitemap (JSON vers XML) à adjoindre au script `mapping` (génération des page depuis les données et les templates) des projets, * Un backlog, une roadmap et des patch notes. Enfin, dans le but d'harmoniser les sites du réseau, un travail sur la convergence des UI est dans les tuyaux (merci de ne pas s'arrêter au design du site imrok.fr lol). *Les [sources du projet rimarok sur GitHub](https://github.com/Skaant/rimarok)*. ## [`motifs-js`](https://motifs-js-website.vercel.app/) Un [immense changement apporté récemment au framework est sa publication (voir l'article sur le site)](/blog/1) sur le [registre public npm](https://www.npmjs.com/package/motifs-js). Le projet a toujours eu pour vocation a être utilisé entre plusieurs projets, mais sa formalisation en un module Node apporte praticité ainsi qu'une touche de sérieux. ### Rédaction En conséquence, une des actions prioritaires est de corriger l'aspect présentationnel du module. Sur le README notamment, **on note beaucoup d'informations obsolètes**, à commencer par le nom affiché du package : "MOTIFS". Le chantier a pour vocation à rendre utilisable le module par d'autres que moi, même si je suis conscient qu'à l'heure actuelle monter sur ce framework est bien moins pertinent que d'autres générateurs de site. On veut faire également disparaître une bonne fois pour toute les dernières traces de `kami.js`, la version précédente du projet. ### Fiabilisation De nombreuses parties du projet demeurent non-testées. Néanmoins, je note de plus en plus de **parts du projet fréquemment utilisées dont j'aimerais fiabiliser le fonctionnement** grâce à, au moins, des tests unitaires. Les points d'intérêt majeurs sont : * **Le motif GLOBAL**, la formalisation des variables globales en instances de ce motif avec leur initialiseur, leur *getter*, leur *updater*. * **Les motifs FOLDER et FILE**, dont on aimerait alléger également la syntaxe, * **Les motifs SPEC et SPEC-SECTION**, dont on aimerait améliorer le *logging* (label fonctionnel + détails des spécifications d'instances) et son export dans des fichiers ### Autres fonctionnalités Une fonctionnalité que j'aimerais rapidement voir dans le framework est la **gestion des templates Pug**. En effet, c'est très pénible de taper du HTML dans un fichier JS (sans auto-complétion ni *hints*). L'autre option est d'utiliser la syntaxe JSX mais de souvenir, pour du SSR, Pug est plus performant ... et sa syntaxe plus light aussi. Bien entendu, **la liste des évolutions et *fixes* envisagés est disponible [sur la page *issues* du projet GitHub](https://github.com/Skaant/motifs-js/issues)**. Au passage, si tu lis ces lignes sache aussi que je suis tout à fait ouvert à la collaboration, sur ce projet ou un autre. ## [imrok.fr](https://imrok.fr) Alors là, ça ne va plus ! Pour mon site créatif, **une UI/UX aussi confuse n'est plus tolérable** : je ne sais pas où chercher quoi, et tout semble en travaux. *imrok.fr est sans doute le projet de la saison.* J'ai été récemment approché par l'[agence créative Nounours](https://www.agencenounours.com/) pour travailler sur de le déploiement de sites et l'intégration de templates, notamment sur WordPress. Touché par leur confiance, je cherche maintenant à illustrer mes compétences sur le sujet, conjointement à mes autres activités de développement. Si la boutique d'IMROK (le BAZAR, [voir dernière section de l'article, juste après](bazar.imrok.fr)) aura cette fonction de démonstration de *theming* et de boutique e-commerce (WooCommerce), **imrok.fr en lui-même a pour fonction d'attester ma capacité d'industrialiation** (JAMStack et développement modulaire). ## Identité graphique La mise au point d'**un thème SCSS/Bootstrap adaptable entre mes différents sites, et intégrable à un thème WordPress** devient nécessaire. La publication de la bêta de Bootstrap 5 me donne une bonne occasion d'imaginer des templates dans lesquelles facilement insérer l'identité graphique de chaque site. La notion de "réseau" (réseau de sites imrok/rimarok et satellites) justifie l'emploi d'éléments d'UI communs. Je dois maintenant travailler à la conception : **imaginer les symboles du site**, l'expérience de navigation (scroll, menu, cartographie), jusqu'aux couleurs, police etc. ### Exploration de l'existant Il y a déjà du contenu sur imrok.fr, mais difficile de savoir qu'est-ce qu'on peut y faire ni la qualité de ce qu'on peut y trouver (article rédigé ou simple scan sans transcription). En parlant de cartographie, **il faudrait être accueil par le panneau indicateur** plutôt que par de nombreuses lignes de contenu : ça peut être rebutant. Il semble nécessaire de mieux permettre d'identifier les différentes options proposées par le site : * Les idées (articles et carnets de pensées), * L'HIGHBS-BOK (actualités et storyboards), * La boutique, * Mes lectures, * Ma vidéothèque (YouTube seulement pour le moment). ### Funding Enfin, en décomposant les blocs créatifs je peux sans doute **proposer à la communauté du réseau de financer l'avancement des projets qui les intéresse le plus**. Un bon moyen de créer de l'échange, de l'engagement et des perspectives professionnelles disruptives ! Le concept pourrait être étendu à tous les sites et projets, notamment `motifs-js`. La difficulté majeure que je vois est la possibilité de payer directement sur le site imrok.fr. On pourrait donc envisager de passer par une plateforme de financement participatif, en proposant **différentes combinaison de tâches à réaliser et de contreparties** : * HIGHBS-BOK, un chapitre / une illustration > le livret concerné et/ou une impression, * motifs-js, une fonctionnalité achetée > la fonctionnalité disponible publiquement pour tous, * imrok.fr, un projet sponsorisé > une impression, un cadeau sur le thème financé. Je ne suis pas très à l'aise pour demander de l'argent, alors il faut que ma production soit suffisament qualitative pour le justifier. **C'est mon engagement.** ## [bazar.imrok.fr](https://bazar.imrok.fr) Le voici le site WordPress (en travaux) ! J'ai installé le module WooCommerce, je l'ai connecté à Stripe ... c'était la partie simple. ### Thème WordPress Maintenant je vais devoir m'occuper de créer un thème WordPress, ce qui implique (comme mentionné précédemment) une phase de design. Néanmoins, j'ai commencé à me renseigner plus en détails sur la création d'un thème *from scratch*, notamment avec [le thème _s](https://github.com/Automattic/_s) proposé comme *boilerplate* aux développeurs. Toutefois, après un fork puis un rapide test sur le site (navigation privée, donc sans scripts d'administration), **le thème pèse déjà 400 kb**. Deux solutions s'offrent alors à moi : * Procéder par élimination, mais le problème des frameworks est souvent de ne pas permettre de distinguer le nécessaire du superflu, * Repartir de "zéro", c'est-à-dire juste des templates et leurs fragments (*template-parts*). Dans tous les cas, je cherche à mener parallèllement la **mise au point d'un thème Bootstrap** que je pourrais ensuite décliner sur chacun de mes sites. ### Aspect matériel Ensuite, un aspect important de la boutique c'est l'alimentation du stock. Pour le moment je n'ai qu'une vague idée de comment matérialiser et envoyer **les premiers produits : les impressions** (cartes postales et formats plus larges). J'ai donc un tour à faire chez l'imprimeur et sur le site de la poste afin de tirer ça au clair avant d'aller plus loin. ### Aspect légal Enfin, dernier point mais non des moindres : le statut requis pour effectuer une activité de vente. Jusque là micro-entrepreneur du tertiaire, **je ne sais pas encore à quelle obligations légales je dois répondre pour pouvoir déclarer le chiffre d'affaire réalisé** par ce nouveau canal de vente. Là c'est un tour sur le site de l'URSSAF et sans doute à la CCI qui est de mise. Si jamais vous avez des pistes, vous trouverez bien un canal par lequel me contacter, merci ;)
export { }; const icons = document.querySelectorAll<HTMLButtonElement>("[data-icon]") icons.forEach((icon) => { const svg = icon.querySelector("[data-svg]")?.innerHTML const copy = icon.querySelector("[data-copy]") as HTMLButtonElement const download = icon.querySelector("[data-download]") as HTMLButtonElement if (!svg || !copy || !download) return copy.addEventListener("click", () => { console.log(svg) navigator.clipboard.writeText(svg) copy.blur() // show the data-copied element: set display to initial, opacity to 0, then animate opacity to 1 const copied = icon.querySelector("[data-copied]") as HTMLElement if (!copied) return copied.style.display = "initial" copied.style.opacity = "1" // force hover and focus style to be removed temporarily // with css copy.classList.add("hidden") download.classList.add("hidden") setTimeout(() => { copy.classList.remove("hidden") download.classList.remove("hidden") }, 2000) // hide the data-copied element after 2 seconds setTimeout(() => { copied.style.opacity = "0" setTimeout(() => (copied.style.display = "none"), 200) }, 2000) }) download.addEventListener("click", () => { const a = document.createElement("a") a.href = `data:image/svg+xml,${encodeURIComponent(svg)}` a.download = `${icon.dataset.icon}-icon.svg` a.click() download.blur() }) })
import { BrowserRouter, Routes, Route } from 'react-router-dom' // page components import Navbar from './components/Navbar' import Home from './pages/home/Home' import Create from './pages/create/Create' import Search from './pages/search/Search' import Recipe from './pages/recipe/Recipe' // styles import './App.css' function App() { return ( <div className="App"> <BrowserRouter> <Navbar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/create" element={<Create />} /> <Route path="/search" element={<Search />} /> <Route path="/recipes/:id" element={<Recipe />} /> </Routes> </BrowserRouter> </div> ); } export default App
import { AnimatePresence, motion, useAnimation, Variants } from "framer-motion"; import { useEffect } from "react"; import { useInView } from "react-intersection-observer"; // const boxVariant: Variants = { // visible: { opacity: 1, scale: 1, transition: { duration: 0.5 } }, // hidden: { opacity: 0, scale: 0 }, // }; // function ScrollBox({ children, id }: { children: any; id: number }) { // const control = useAnimation(); // const [ref, inView] = useInView(); // useEffect(() => { // if (inView) { // control.start("visible"); // } else { // control.start("hidden"); // } // }, [control, inView]); // return ( // <motion.div // ref={ref} // variants={boxVariant} // initial="hidden" // animate={control} // className="w-full flex flex-col justify-center items-center" // > // {children} // </motion.div> // ); // } const variants: Variants = { enter: (direction: "forward" | "backward") => { return { y: direction === "forward" ? 1000 : -1000, opacity: 0, }; }, center: { y: 0, opacity: 1, }, exit: (direction: "forward" | "backward") => { return { y: direction === "forward" ? -1000 : 1000, opacity: 0, transition: { duration: 0.5 }, }; }, }; function ScrollBox({ children, id, direction, }: { children: any; id: number; direction: "forward" | "backward"; }) { return ( <AnimatePresence initial={false} custom={direction}> <motion.div key={id} variants={variants} custom={direction} initial="enter" animate="center" exit="exit" transition={{ duration: 1 }} className="w-full flex flex-col justify-center items-center" > {children} </motion.div> </AnimatePresence> ); } export default ScrollBox;
from entity.IAdminService import IAdminService from entity.Admin import Admin from util.DBConnection import DBConnection from exception.AdminNotFoundException import AdminNotFoundException from exception.InvalidInputException import InvalidInputException class AdminService(DBConnection, IAdminService): def __init__(self): super().__init__() def authenticate_admin_data(self, username, password): self.open() select_query = f"SELECT * FROM Admin WHERE Username LIKE '{username}';" self.stmt.execute(select_query) admin_data = self.stmt.fetchone() if admin_data: admin = Admin(*admin_data) if admin.authenticate(password): print("Authentication successful!") self.close() else: raise AdminNotFoundException("Authentication failed-- Invalid password.") else: raise AdminNotFoundException("Authentication failed-- Invalid username.") def authenticate_admin(self, name): if name.isalpha(): return True else: raise InvalidInputException("Enter Correct Details...") def authenticate_phone(self, phone_number): if phone_number.isalnum() and len(phone_number) == 10: return True else: if len(phone_number) != 10: raise InvalidInputException("Enter 10 Digit PhoneNo") else: raise InvalidInputException("Enter Digits only...") def register_admin(self): admin = Admin() try: first_name = input("Enter First Name: ") if self.authenticate_admin(first_name): admin.set_first_name(first_name) except InvalidInputException as e: print(f'Invalid Input: {e}') return try: last_name = input("Enter Last Name: ") if self.authenticate_admin(last_name): admin.set_last_name(last_name) except InvalidInputException as e: print(f'Invalid Input: {e}') return admin.set_email(input("Enter Email: ")) try: phone_number = input("Enter Phone Number: ") if self.authenticate_phone(phone_number): admin.set_phone_number(phone_number) except InvalidInputException as e: print(f'Invalid Input: {e}') return admin.set_username(input("Enter Username: ")) admin.set_password(input("Enter Password: ")) admin.set_role(input("Enter Role: ")) admin.set_join_date(input("Enter Join Date (YYYY-MM-DD): ")) data = [(admin.get_first_name(), admin.get_last_name(), admin.get_email(), admin.get_phone_number(), admin.get_username(), admin.get_password(), admin.get_role(), admin.get_join_date())] insert_query = ''' INSERT INTO Admin (FirstName, LastName, Email, PhoneNumber, Username, Password, Role, JoinDate) VALUES (%s, %s, %s, %s, %s, %s, %s, %s); ''' self.open() self.stmt.executemany(insert_query, data) self.conn.commit() print("Admin registered successfully..") self.close() def update_admin(self): username = input("Enter Username: ") password = input("Enter Password: ") try: self.authenticate_admin_data(username, password) except AdminNotFoundException as e: print(e) return try: self.select_admin() admin_id = int(input("Enter AdminID to be updated: ")) query = f"SELECT AdminID FROM ADMIN WHERE AdminID={admin_id};" self.open() self.stmt.execute(query) record = self.stmt.fetchone() if record: admin = Admin() try: first_name = input("Enter First Name: ") if self.authenticate_admin(first_name): admin.set_first_name(first_name) except InvalidInputException as e: print(f'Invalid Input: {e}') return try: last_name = input("Enter Last Name: ") if self.authenticate_admin(last_name): admin.set_last_name(last_name) except InvalidInputException as e: print(f'Invalid Input: {e}') return admin.set_email(input("Enter Email: ")) try: phone_number = input("Enter Phone Number: ") if self.authenticate_phone(phone_number): admin.set_phone_number(phone_number) except InvalidInputException as e: print(f'Invalid Input: {e}') return admin.set_username(input("Enter Username: ")) admin.set_password(input("Enter Password: ")) admin.set_role(input("Enter Role: ")) admin.set_join_date(input("Enter Join Date (YYYY-MM-DD): ")) update_str = ''' UPDATE Admin SET FirstName=%s, LastName=%s, Email=%s, PhoneNumber=%s, Username=%s, Password=%s, Role=%s, JoinDate=%s WHERE AdminID=%s ''' data = [(admin.get_first_name(), admin.get_last_name(), admin.get_email(), admin.get_phone_number(), admin.get_username(), admin.get_password(), admin.get_role(), admin.get_join_date(), admin_id)] self.stmt.executemany(update_str, data) self.conn.commit() print("Admin Updated Successfully...") self.close() else: raise AdminNotFoundException("AdminID not found in Database...") except AdminNotFoundException as e: print(f"Admin Updation Failed: {e}") def delete_admin(self): username = input("Enter Username: ") password = input("Enter Password: ") try: self.authenticate_admin_data(username, password) except AdminNotFoundException as e: print(e) return try: admin_id = int(input("Enter AdminID to be deleted: ")) query = f"SELECT AdminID FROM ADMIN WHERE AdminID={admin_id};" self.open() self.stmt.execute(query) record = self.stmt.fetchone() if record: delete_str = f'DELETE FROM Admin WHERE AdminID={admin_id};' self.open() self.stmt.execute(delete_str) self.conn.commit() print("Admin Deleted Successfully...") self.close() else: raise AdminNotFoundException("AdminID not found in Database...") except AdminNotFoundException as e: print(f"Admin Not Found: {e}") def get_admin_by_id(self): try: admin_id = int(input("Enter AdminID to get details: ")) self.open() admin_str = f'SELECT * FROM Admin WHERE AdminID={admin_id};' self.stmt.execute(admin_str) record = self.stmt.fetchone() if record: print() print("...............Admin Details for AdminID: ", admin_id, "...............") print(record) print() self.close() else: raise AdminNotFoundException("AdminID not found in Database...") except AdminNotFoundException as e: print(f"Admin Not Found: {e}") def get_admin_by_username(self): try: username = input("Enter Username to get details: ") self.open() admin_str = f'SELECT * FROM Admin WHERE Username LIKE "{username}";' self.stmt.execute(admin_str) records = self.stmt.fetchall() if records: print() print("...............Admin Details for Username: ", username, "...............") for i in records: print(i) print() self.conn.commit() self.close() else: raise AdminNotFoundException("Invalid Username...") except AdminNotFoundException as e: print(f'Admin Not Found: {e}') def select_admin(self): username = input("Enter Username: ") password = input("Enter Password: ") try: self.authenticate_admin_data(username, password) except AdminNotFoundException as e: print(e) return self.open() select_str = 'SELECT * FROM Admin;' self.stmt.execute(select_str) records = self.stmt.fetchall() print() print("...............Records in Admin Table...............") for i in records: print(i) print() self.close()
--- title: js设计模式 date: 2023-11-01 15:53:12 description: 前端js总计23种设计模式简析 tags: - javascript - 设计模式 categories: - javascript - 设计模式 --- <h2>设计模式三大分类</h2> <ol> <li>创建型模式:用于描述对象的创建方式,包括单例模式、工厂模式、建造者模式、原型模式等</li> <li>结构型模式:用于描述对象之间的组合方式,包括适配器模式、桥接模式、装饰者模式、外观模式、享元模式、组合模式等。</li> <li>行为型模式:用于描述对象之间的交互方式,包括观察者模式、命令模式、迭代器模式、模板方法模式、策略模式、职责链模式、状态模式、访问者模式、中介者模式等。</li> </ol> <h3>1.单例模式</h3> <p>保证一个类仅有一个实例,并提供一个全局访问该实例的接口。</p> ```javascript class People { static instance = null constructor(name) { if (Singleton.instance !== null) { return Singleton.instance } this.name = name Singleton.instance = this } say() { console.log(`我的名字是${this.name}`) } } // 创建实例 const xiaoming = new People('小明') xiaoming.say() // 我的名字是小明 const xiaohong = new People('小红') xiaohong.say() // 我的名字是小明 ``` <h3>2.工厂模式</h3> <p>工厂模式是一种创建对象的方式,其不直接调用构造函数来创建对象,而是提供一个共同的接口来创建对象。</p> ```javascript class Man { constructor(name) { this.name = name } init() { console.log('man') } say() { console.log('我是男生,我的名字是' + name) } } class Woman { constructor(name) { this.name = name } init() { console.log('woman') } say() { console.log('我是女生,我的名字是' + name) } } class Factory { create(type,name) { switch (type) { case 'man': return new Man(name) case 'woman': return new Woman(name) default: return new Error("我是什么性别") } } } // 工厂创建 let factory = new Factory() let man = factory.create('man', '龙日天') man.init() man.say() let woman = factory.create('woman', '小甜甜') woman.init() woman.say() ``` <h3>3.观察者模式</h3> <p>当一个对象被修改时,会自动通知它的依赖者的模式</p> ```javascript class Subject { constructor() { this.state = 0 this.observers = [] } getState() { return this.state } setState(state) { this.state = state this.notify() } notify() { this.observers.forEach(observer => { observer.update() }) } add(observer) { this.observers.push(observer) } } // 观察者 class Observer { constructor(name, subject) { this.name = name this.subject = subject this.subject.add(this) } update() { console.log(`${this.name} update, state: ${this.subject.getState()}`) } } // 测试 let s = new Subject() let o1 = new Observer('o1', s) let o2 = new Observer('02', s) s.setState(111) ``` <h3>4.命令模式</h3> <p>将请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销操作的模式。命令模式将请求者和接受者解耦,使得它们不需要接触到具体的实现。</p> ```javascript // 接收者 class Receiver { login() { console.log('登录系统') } } // 命令 class Command { constructor(receiver) { this.receiver = receiver } } // 登录命令 class LoginCommand extends Command { execute() { console.log('执行登录操作') this.receiver.login() } } // 发起者 class Invoker { setCommand(command) { this.command = command } execute() { console.log('执行登录命令') this.command.execute() } } // 创建接收者 const receiver = new Receiver() // 创建命令 const command = new LoginCommand(receiver) // 创建发起者 const invoker = new Invoker() invoker.setCommand(command) // 执行命令 invoker.execute() // 执行登录操作 ``` <h3>5.状态模式</h3> <p>允许一个对象在其内部状态改变的时候改变它的行为,对象看起来似乎修改了它的类</p> ```javascript // 状态 (上架,下架,成交) class State { constructor(state) { this.state = state } handle(context) { console.log(`this is ${this.state} state`) context.setState(this) } } class Context { constructor() { this.state = null } getState() { return this.state } setState(state) { this.state = state } } // test let context = new Context() let up = new State('up') let down = new State('down') let ok = new State('ok') // 上架 up.handle(context) console.log(context.getState()) // 下架 down.handle(context) console.log(context.getState()) // 成交 ok.handle(context) console.log(context.getState()) ``` <h3>6.迭代器模式</h3> <p>提供一种方法顺序一个聚合对象中各个元素,而又不暴露该对象的内部表示。</p> ```javascript class Iterator { constructor(conatiner) { this.list = conatiner.list this.index = 0 } next() { if (this.hasNext()) { return this.list[this.index++] } return null } hasNext() { if (this.index >= this.list.length) { return false } return true } } class Container { constructor(list) { this.list = list } getIterator() { return new Iterator(this) } } // 测试代码 let container = new Container([1, 2, 3, 4, 5]) let iterator = container.getIterator() while(iterator.hasNext()) { console.log(iterator.next()) } ``` <h3>7.桥接模式</h3> <p>将抽象部分与它的实现部分分离,使它们都可以独立地变化</p> ```javascript class Color { constructor(state){ this.state = state } } class Shape { constructor(shape,color){ this.shape = shape this.color = color } desc(){ console.log(`${this.color.state} ${this.shape}`) } } //测试 let red = new Color('red') let yellow = new Color('yellow') let circle = new Shape('circle', red) circle.desc() let triangle = new Shape('triangle', yellow) triangle.desc() ``` <h3>8.组合模式</h3> <p>将对象组合成树形结构,以表示“整体-部分”的层次结构。 通过对象的多态表现,使得用户对单个对象和组合对象的使用具有一致性。</p> ```javascript // 文件夹类 class Folder { constructor(name, children) { this.name = name this.children = children } // 在文件夹下增加文件或文件夹 add(...fileOrFolder) { this.children.push(...fileOrFolder) return this } // 扫描方法 scan(cb) { this.children.forEach(child => child.scan(cb)) } } // 文件类 class File { constructor(name, size) { this.name = name this.size = size } // 在文件下增加文件,应报错 add(...fileOrFolder) { throw new Error('文件下面不能再添加文件') } // 执行扫描方法 scan(cb) { cb(this) } } const foldMovies = new Folder('电影', [ new Folder('漫威英雄电影', [ new File('钢铁侠.mp4', 1.9), new File('蜘蛛侠.mp4', 2.1), new File('金刚狼.mp4', 2.3), new File('黑寡妇.mp4', 1.9), new File('美国队长.mp4', 1.4)]), new Folder('DC英雄电影', [ new File('蝙蝠侠.mp4', 2.4), new File('超人.mp4', 1.6)]) ]) console.log('size 大于2G的文件有:') foldMovies.scan(item => { if (item.size > 2) { console.log(`name:${ item.name } size:${ item.size }GB`) } }) // size 大于2G的文件有: // name:蜘蛛侠.mp4 size:2.1GB // name:金刚狼.mp4 size:2.3GB // name:蝙蝠侠.mp4 size:2.4GB ``` <h3>9.原型模式</h3> <p>用原型实例指向创建对象的种类,并且通过拷贝这些原型创建新的对象</p> ```javascript class Person { constructor(name) { this.name = name } getName() { return this.name } } class Student extends Person { constructor(name) { super(name) } sayHello() { console.log(`Hello, My name is ${this.name}`) } } let student = new Student("xiaoming") student.sayHello() ``` <h3>10.策略模式</h3> <p>定义一系列的算法,把它们一个个封装起来,并且使它们可以互相替换</p> ```html <html> <head> <title>策略模式-校验表单</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> </head> <body> <form id = "registerForm" method="post" action="http://xxxx.com/api/register"> 用户名:<input type="text" name="userName"> 密码:<input type="text" name="password"> 手机号码:<input type="text" name="phoneNumber"> <button type="submit">提交</button> </form> <script type="text/javascript"> // 策略对象 const strategies = { isNoEmpty: function (value, errorMsg) { if (value === '') { return errorMsg; } }, isNoSpace: function (value, errorMsg) { if (value.trim() === '') { return errorMsg; } }, minLength: function (value, length, errorMsg) { if (value.trim().length < length) { return errorMsg; } }, maxLength: function (value, length, errorMsg) { if (value.length > length) { return errorMsg; } }, isMobile: function (value, errorMsg) { if (!/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|17[7]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(value)) { return errorMsg; } } } // 验证类 class Validator { constructor() { this.cache = [] } add(dom, rules) { for(let i = 0, rule; rule = rules[i++];) { let strategyAry = rule.strategy.split(':') let errorMsg = rule.errorMsg this.cache.push(() => { let strategy = strategyAry.shift() strategyAry.unshift(dom.value) strategyAry.push(errorMsg) return strategies[strategy].apply(dom, strategyAry) }) } } start() { for(let i = 0, validatorFunc; validatorFunc = this.cache[i++];) { let errorMsg = validatorFunc() if (errorMsg) { return errorMsg } } } } // 调用代码 let registerForm = document.getElementById('registerForm') let validataFunc = function() { let validator = new Validator() validator.add(registerForm.userName, [{ strategy: 'isNoEmpty', errorMsg: '用户名不可为空' }, { strategy: 'isNoSpace', errorMsg: '不允许以空白字符命名' }, { strategy: 'minLength:2', errorMsg: '用户名长度不能小于2位' }]) validator.add(registerForm.password, [ { strategy: 'minLength:6', errorMsg: '密码长度不能小于6位' }]) validator.add(registerForm.phoneNumber, [{ strategy: 'isMobile', errorMsg: '请输入正确的手机号码格式' }]) return validator.start() } registerForm.onsubmit = function() { let errorMsg = validataFunc() if (errorMsg) { alert(errorMsg) return false } } </script> </body> </html> ``` <h3>10.职责链模式</h3> <p>多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系,将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止</p> ```javascript // 请假审批,需要组长审批、经理审批、总监审批 class Action { constructor(name) { this.name = name this.nextAction = null } setNextAction(action) { this.nextAction = action } handle() { console.log( `${this.name} 审批`) if (this.nextAction != null) { this.nextAction.handle() } } } let a1 = new Action("组长") let a2 = new Action("经理") let a3 = new Action("总监") a1.setNextAction(a2) a2.setNextAction(a3) a1.handle() ```
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <map> #include <bitset> using namespace std; typedef enum { Undefined = 0, PipeLoop = 1, ZoneA = 2, ZoneB = 3, } ETileType; struct position { int x; int y; }; struct entity { position currentPosition; position lastPosition; int distanceTraveled; }; map<char, tuple<bool, bool, bool, bool>> CONNEXIONS = { {'|', {1, 1, 0, 0}}, {'-', {0, 0, 1, 1}}, {'L', {1, 0, 1, 0}}, {'J', {1, 0, 0, 1}}, {'7', {0, 1, 0, 1}}, {'F', {0, 1, 1, 0}}, {'.', {0, 0, 0, 0}}, }; char START_PIPE = 'S'; char findTileType(position p, vector<string> maze) { bool connectedNorth = p.y > 0 && get<1>(CONNEXIONS.at(maze[p.y - 1][p.x])); bool connectedSouth = p.y < maze.size() && get<0>(CONNEXIONS.at(maze[p.y + 1][p.x])); bool connectedEast = p.x < maze[0].size() && get<3>(CONNEXIONS.at(maze[p.y][p.x + 1])); bool connectedWest = p.x > 0 && get<2>(CONNEXIONS.at(maze[p.y][p.x - 1])); map<char, tuple<bool, bool, bool, bool>>::iterator it = CONNEXIONS.begin(); while (it != CONNEXIONS.end()) { tuple<bool, bool, bool, bool> shape = it->second; bool sameNorth = connectedNorth == get<0>(shape); bool sameSouth = connectedSouth == get<1>(shape); bool sameEast = connectedEast == get<2>(shape); bool sameWest = connectedWest == get<3>(shape); if (sameNorth && sameSouth && sameEast && sameWest) { return it->first; } it++; } return '.'; } void moveEntity(entity &e, vector<string> maze, vector<vector<ETileType>> &coloredMaze) { tuple<bool, bool, bool, bool> possibleMoves = CONNEXIONS.at(maze[e.currentPosition.y][e.currentPosition.x]); // When the last position is equal to the current position, we do not move the last position if (e.currentPosition.x == e.lastPosition.x && e.currentPosition.y == e.lastPosition.y) { if (get<0>(possibleMoves)) { e.currentPosition.y--; } else if (get<1>(possibleMoves)) { e.currentPosition.y++; } else if (get<2>(possibleMoves)) { e.currentPosition.x++; } else if (get<3>(possibleMoves)) { e.currentPosition.x--; } } else { if (get<0>(possibleMoves) && e.lastPosition.y != e.currentPosition.y - 1) { e.lastPosition.y = e.currentPosition.y; e.lastPosition.x = e.currentPosition.x; e.currentPosition.y--; } else if (get<1>(possibleMoves) && e.lastPosition.y != e.currentPosition.y + 1) { e.lastPosition.y = e.currentPosition.y; e.lastPosition.x = e.currentPosition.x; e.currentPosition.y++; } else if (get<2>(possibleMoves) && e.lastPosition.x != e.currentPosition.x + 1) { e.lastPosition.y = e.currentPosition.y; e.lastPosition.x = e.currentPosition.x; e.currentPosition.x++; } else if (get<3>(possibleMoves) && e.lastPosition.x != e.currentPosition.x - 1) { e.lastPosition.y = e.currentPosition.y; e.lastPosition.x = e.currentPosition.x; e.currentPosition.x--; } } if (e.lastPosition.x > e.currentPosition.x) { if (e.currentPosition.y + 1 < coloredMaze.size()) { if (coloredMaze[e.currentPosition.y + 1][e.currentPosition.x] == ETileType::Undefined) { coloredMaze[e.currentPosition.y + 1][e.currentPosition.x] = ETileType::ZoneA; } if (coloredMaze[e.lastPosition.y + 1][e.lastPosition.x] == ETileType::Undefined) { coloredMaze[e.lastPosition.y + 1][e.lastPosition.x] = ETileType::ZoneA; } } if (e.currentPosition.y > 0) { if (coloredMaze[e.currentPosition.y - 1][e.currentPosition.x] == ETileType::Undefined) { coloredMaze[e.currentPosition.y - 1][e.currentPosition.x] = ETileType::ZoneB; } if (coloredMaze[e.lastPosition.y - 1][e.lastPosition.x] == ETileType::Undefined) { coloredMaze[e.lastPosition.y - 1][e.lastPosition.x] = ETileType::ZoneB; } } } else if (e.lastPosition.x < e.currentPosition.x) { if (e.currentPosition.y + 1 < coloredMaze.size()) { if (coloredMaze[e.currentPosition.y + 1][e.currentPosition.x] == ETileType::Undefined) { coloredMaze[e.currentPosition.y + 1][e.currentPosition.x] = ETileType::ZoneB; } if (coloredMaze[e.lastPosition.y + 1][e.lastPosition.x] == ETileType::Undefined) { coloredMaze[e.lastPosition.y + 1][e.lastPosition.x] = ETileType::ZoneB; } } if (e.currentPosition.y > 0) { if (coloredMaze[e.currentPosition.y - 1][e.currentPosition.x] == ETileType::Undefined) { coloredMaze[e.currentPosition.y - 1][e.currentPosition.x] = ETileType::ZoneA; } if (coloredMaze[e.lastPosition.y - 1][e.lastPosition.x] == ETileType::Undefined) { coloredMaze[e.lastPosition.y - 1][e.lastPosition.x] = ETileType::ZoneA; } } } else if (e.lastPosition.y > e.currentPosition.y) { if (e.currentPosition.x + 1 < coloredMaze[0].size()) { if (coloredMaze[e.currentPosition.y][e.currentPosition.x + 1] == ETileType::Undefined) { coloredMaze[e.currentPosition.y][e.currentPosition.x + 1] = ETileType::ZoneB; } if (coloredMaze[e.lastPosition.y][e.lastPosition.x + 1] == ETileType::Undefined) { coloredMaze[e.lastPosition.y][e.lastPosition.x + 1] = ETileType::ZoneB; } } if (e.currentPosition.x > 0) { if (coloredMaze[e.currentPosition.y][e.currentPosition.x - 1] == ETileType::Undefined) { coloredMaze[e.currentPosition.y][e.currentPosition.x - 1] = ETileType::ZoneA; } if (coloredMaze[e.lastPosition.y][e.lastPosition.x - 1] == ETileType::Undefined) { coloredMaze[e.lastPosition.y][e.lastPosition.x - 1] = ETileType::ZoneA; } } } else if (e.lastPosition.y < e.currentPosition.y) { if (e.currentPosition.x + 1 < coloredMaze[0].size()) { if (coloredMaze[e.currentPosition.y][e.currentPosition.x + 1] == ETileType::Undefined) { coloredMaze[e.currentPosition.y][e.currentPosition.x + 1] = ETileType::ZoneA; } if (coloredMaze[e.lastPosition.y][e.lastPosition.x + 1] == ETileType::Undefined) { coloredMaze[e.lastPosition.y][e.lastPosition.x + 1] = ETileType::ZoneA; } } if (e.currentPosition.x > 0) { if (coloredMaze[e.currentPosition.y][e.currentPosition.x - 1] == ETileType::Undefined) { coloredMaze[e.currentPosition.y][e.currentPosition.x - 1] = ETileType::ZoneB; } if (coloredMaze[e.lastPosition.y][e.lastPosition.x - 1] == ETileType::Undefined) { coloredMaze[e.lastPosition.y][e.lastPosition.x - 1] = ETileType::ZoneB; } } } e.distanceTraveled++; coloredMaze[e.currentPosition.y][e.currentPosition.x] = ETileType::PipeLoop; // printf("Bougé en (%i, %i) depuis (%i, %i)\n", e.currentPosition.x, e.currentPosition.y, e.lastPosition.x, e.lastPosition.y); } void showColoredMaze(vector<vector<ETileType>> maze) { for (int i = 0; i < maze.size(); i++) { string s; for (int j = 0; j < maze[i].size(); j++) { if (maze[i][j] == ETileType::PipeLoop) { s += "#"; } else if (maze[i][j] == ETileType::Undefined) { s += "."; } else if (maze[i][j] == ETileType::ZoneA) { s += "A"; } else if (maze[i][j] == ETileType::ZoneB) { s += "B"; } } printf("%s\n", s.c_str()); } } vector<int> countColors(vector<vector<ETileType>> maze) { vector<int> colors = {0, 0, 0, 0}; for (int i = 0; i < maze.size(); i++) { for (int j = 0; j < maze[i].size(); j++) { colors[maze[i][j]]++; } } return colors; } void fillColorRec(int x, int y, vector<vector<ETileType>> &coloredMaze) { ETileType currentColor = coloredMaze[y][x]; if (x > 0 && coloredMaze[y][x - 1] == ETileType::Undefined) { coloredMaze[y][x - 1] = currentColor; fillColorRec(x - 1, y, coloredMaze); } if (x + 1 < coloredMaze[0].size() && coloredMaze[y][x + 1] == ETileType::Undefined) { coloredMaze[y][x + 1] = currentColor; fillColorRec(x + 1, y, coloredMaze); } if (y > 0 && coloredMaze[y - 1][x] == ETileType::Undefined) { coloredMaze[y - 1][x] = currentColor; fillColorRec(x, y - 1, coloredMaze); } if (y + 1 < coloredMaze.size() && coloredMaze[y + 1][x] == ETileType::Undefined) { coloredMaze[y + 1][x] = currentColor; fillColorRec(x, y + 1, coloredMaze); } } void fillColor(vector<vector<ETileType>> &coloredMaze) { for (int i = 0; i < coloredMaze.size(); i++) { for (int j = 0; j < coloredMaze[i].size(); j++) { if (coloredMaze[i][j] == ETileType::ZoneA || coloredMaze[i][j] == ETileType::ZoneB) { fillColorRec(j, i, coloredMaze); } } } } int main(int argc, char *argv[]) { ifstream file(argv[1]); string line; vector<string> maze; vector<vector<ETileType>> coloredMaze; position startPosition; entity creature; // Parse the input file int i = 0; while (file.good()) { getline(file, line); vector<ETileType> coloredLine; for (int j = 0; j < line.size(); j++) { coloredLine.push_back(ETileType::Undefined); if (line[j] == START_PIPE) { startPosition.x = j; startPosition.y = i; } } coloredMaze.push_back(coloredLine); maze.push_back(line); i++; } // Initialize the position of the entity. creature.currentPosition.x = startPosition.x; creature.currentPosition.y = startPosition.y; creature.lastPosition.x = startPosition.x; creature.lastPosition.y = startPosition.y; creature.distanceTraveled = 0; // Replace the S by the appropriate tile type maze[startPosition.y][startPosition.x] = findTileType(startPosition, maze); // Move the entity around the loop untill it is back to the starting point do { moveEntity(creature, maze, coloredMaze); } while (creature.currentPosition.x != startPosition.x || creature.currentPosition.y != startPosition.y); printf("Loop size: %i\n", creature.distanceTraveled); printf("Farthest point distance: %i\n", (creature.distanceTraveled / 2)); fillColor(coloredMaze); showColoredMaze(coloredMaze); vector<int> colorsCount = countColors(coloredMaze); printf("Il y a %i cases non définies, %i cases avec un tuyau appartenant à la boucle, %i cases dans la zone A et %i cases dans la zone B.", colorsCount[ETileType::Undefined], colorsCount[ETileType::PipeLoop], colorsCount[ETileType::ZoneA], colorsCount[ETileType::ZoneB]); }