text
stringlengths
184
4.48M
import React from 'react'; import html2canvas from "html2canvas"; import { jsPDF } from "jspdf"; const MyResume = ({rootElementId , downloadFileName}) => { const downloadPdfDocument = () => { const input = document.getElementById(rootElementId); // Adjust the scale factor for a larger size (e.g., 3) const scaleFactor = 5; html2canvas(input, { scale: scaleFactor }) .then((canvas) => { const imgData = canvas.toDataURL('image/png'); // Adjust the width and height based on the scale factor const pdf = new jsPDF({ unit: 'px', format: 'a4', orientation: 'portrait' }); const pdfWidth = pdf.internal.pageSize.getWidth(); const pdfHeight = pdf.internal.pageSize.getHeight(); const imgWidth = pdfWidth - 20; // Adjust the width const imgHeight = (canvas.height * imgWidth) / canvas.width; // Maintain aspect ratio pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight); // Adjust the position pdf.save(`${downloadFileName}.pdf`); }); }; return <> <button className='btn btn-add px-3' onClick={downloadPdfDocument}> DOWNLOAD RESUME <i className=" mx-2 fa-solid fa-download" /> </button> </> } export default MyResume;
// opgave 1A function ShakeFunctie(woordDatGeschudtMoetWorden){ const characters = woordDatGeschudtMoetWorden.split(''); for (let i = characters.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [characters[i], characters[j]] = [characters[j], characters[i]]; } const geschudWoord = characters.join(''); return geschudWoord } var woord1 = ShakeFunctie("Boekenkast"); console.log(woord1); var woord2 = ShakeFunctie("Spiderman"); console.log(woord2); var woord3 = ShakeFunctie("Parasonic"); console.log(woord3); // opgrave B //Inhoud kubus function berekenKubusInhoud(lengte, breedte, diepte) { var inhoud = lengte * breedte * diepte; return inhoud; } var lengte = 3; var breedte = 2; var diepte = 5; var resultaat = berekenKubusInhoud(lengte, breedte, diepte); console.log("De inhoud van de kubus is: " + resultaat); //Cilinder berekenen /* function berekenCilinderInhoud(diameter, hoogte) { var inhoud = radius² * π * hoogte; return inhoud; } var hoogte = 6; var radius² = 10; var π = Math.PI var resultaat = berekenCilinderInhoud(diameter, hoogte); console.log("De inhoud van de cilinder is: " + resultaat); */ function berekenCilinderInhoud(diameter, hoogte) { var straal = diameter / 2; var inhoud = Math.PI * Math.pow(straal, 2) * hoogte; return inhoud; } var diameter = 6; var hoogte = 10; var resultaat = berekenCilinderInhoud(diameter, hoogte); console.log("De inhoud van de cilinder is: " + resultaat); //Zijden berekenen function berekenLangeZijde(lengte, hoogte) { var korteZijde = Math.pow(lengte, 2); var hoogteZijde = Math.pow(hoogte, 2); var langeZijde = Math.sqrt(korteZijde + hoogteZijde); return langeZijde; } var lengte = 3; var hoogte = 4; var resultaat = berekenLangeZijde(lengte, hoogte); console.log("De lengte van de lange zijde is: " + resultaat); // Gemideld berekenen function berekenGemiddelde(getal1, getal2, getal3, getal4, getal5, getal6, getal7) { var som = getal1 + getal2 + getal3 + getal4 + getal5 + getal6 + getal7; var gemiddelde = som / 7; return gemiddelde; } var getal1 = 1; var getal2 = 2; var getal3 = 3; var getal4 = 4; var getal5 = 5; var getal6 = 6; var getal7 = 7; var resultaat = berekenGemiddelde(getal1, getal2, getal3, getal4, getal5, getal6, getal7); console.log("Het gemiddelde van de 7 getallen is: " + resultaat); // opgave 2 function generateFibonacci(limit) { let a = 0; let b = 1; console.log(a); console.log(b); while (true) { const next = a + b; if (next > limit) { break; } console.log(next); a = b; b = next; } } generateFibonacci(10000000); // opgrave 3 const minNumber = 0; const maxNumber = 100; const secretNumber = Math.floor(Math.random() * (maxNumber - minNumber + 1)) + minNumber; const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function guessNumber() { rl.question('Raad een getal tussen 0 en 100: ', (userInput) => { const userGuess = parseInt(userInput, 10); if (isNaN(userGuess)) { console.log('Dit is geen geldig getal. Probeer opnieuw.'); } else if (userGuess < minNumber || userGuess > maxNumber) { console.log('Het getal moet tussen 0 en 100 liggen. Probeer opnieuw.'); } else if (userGuess < secretNumber) { console.log('Het geraden getal is te laag. Probeer opnieuw.'); guessNumber(); } else if (userGuess > secretNumber) { console.log('Het geraden getal is te hoog. Probeer opnieuw.'); guessNumber(); } else { console.log(`Gefeliciteerd! Je hebt het juiste getal geraden: ${secretNumber}`); rl.close(); } }); } guessNumber();
package java2; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * 创建线程的方式三:实现Callable接口. ---JDK 5.0新增 * * * 如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大? * 1.call()方法可以有返回值的。 * 2.call()可以抛出异常,被外面的操作捕获,获取异常的信息 * 3.Callable是支持泛型的 * * * * @author shkstart * @create 2021-12-08 15:07 */ //1.创建一个实现Callable的实现类 class NumThread implements Callable{ //2.实现call方法,将此线程需要执行的操作声明在call()中 @Override public Object call() throws Exception { int sum = 0; for (int i = 1; i <=100 ; i++) { if (i % 2 == 0){ System.out.println(i); sum += i; } } return sum; } } public class ThreadNew { public static void main(String[] args) { //3.创建Callable接口实现类的对象 NumThread numThread =new NumThread(); //4将此Callable接口实现类的对象作为传递到FutrueTask的构造器中,创建FutureTask的对象 FutureTask futureTask = new FutureTask(numThread); //5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()方法 new Thread(futureTask).start(); try { //6.get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值. Object sum = futureTask.get(); System.out.println("总和为:"+sum); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
import React, { useState } from "react"; import { Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField, } from "@mui/material"; import axios from "axios"; const ProductCreationPopup = ({ open, handleClose, refreshProducts }) => { const [productDetails, setProductDetails] = useState({ name: "", description: "", price: "", category: "", imageUrls: [], }); const [expirationDate, setExpirationDate] = useState(""); const handleChange = (e) => { if (e.target.name === "imageUrls") { setProductDetails({ ...productDetails, [e.target.name]: e.target.value.split(","), }); } else { setProductDetails({ ...productDetails, [e.target.name]: e.target.value }); } }; const handleSubmit = async () => { try { const ownerId = localStorage.getItem("_id"); // Retrieve the owner's _id from local storage if (!ownerId) { alert("User ID not found. Please log in again."); return; } const token = localStorage.getItem("userToken"); // Ensure this is the correct key for the stored token const productDataWithOwner = { ...productDetails, owner: ownerId, // Add owner _id to the product details expiresAt: expirationDate, // Include the expiration date }; const response = await axios.post( "https://ecomm-app-6ov7.onrender.com/products/register", productDataWithOwner, { headers: { Authorization: `Bearer ${token}`, }, } ); if (response.status === 201) { alert("Product created successfully"); refreshProducts(); handleClose(); } } catch (error) { alert( "Error creating product: " + (error.response?.data.message || error.message) ); console.error("Error creating product:", error); } }; return ( <Dialog open={open} onClose={handleClose}> <DialogTitle>Create New Product</DialogTitle> <DialogContent> <TextField autoFocus margin="dense" name="name" label="Product Name" type="text" fullWidth variant="standard" value={productDetails.name} onChange={handleChange} /> <TextField margin="dense" name="description" label="Description" type="text" fullWidth variant="standard" value={productDetails.description} onChange={handleChange} /> <TextField margin="dense" name="price" label="Price" type="number" fullWidth variant="standard" value={productDetails.price} onChange={handleChange} /> <TextField margin="dense" name="category" label="Category" type="text" fullWidth variant="standard" value={productDetails.category} onChange={handleChange} /> <TextField margin="dense" name="imageUrls" label="Image URLs (comma-separated)" type="text" fullWidth variant="standard" value={productDetails.imageUrls.join(",")} onChange={handleChange} helperText="Enter image URLs separated by commas" /> <TextField label="Expiration Date" type="date" value={expirationDate} onChange={(e) => setExpirationDate(e.target.value)} InputLabelProps={{ shrink: true }} fullWidth margin="normal" placeholder="yyyy-mm-dd" // Format placeholder /> </DialogContent> <DialogActions> <Button onClick={handleClose}>Cancel</Button> <Button onClick={handleSubmit}>Create</Button> </DialogActions> </Dialog> ); }; export default ProductCreationPopup;
import React, { useState, ChangeEvent } from 'react'; import TextField from '@mui/material/TextField'; import Button, { ButtonProps } from '@mui/material/Button'; import Grid from '@mui/material/Grid'; import Box from '@mui/material/Box'; import Select, { SelectChangeEvent } from '@mui/material/Select'; import MenuItem from '@mui/material/MenuItem'; import { Alert, CircularProgress } from '@mui/material'; import { useParams } from 'react-router-dom'; interface Field { name: string; label: string; type: 'text' | 'dropdown' | 'number' | 'date'; options?: string[]; } interface ButtonConfig extends Omit<ButtonProps, 'onClick'> { label: string; onClick?: (formData: Record<string, string>) => void; } interface DynamicMaterialUIFormProps { onSubmit: (formData: Record<string, string>) => void; fields: Field[]; buttons: ButtonConfig[]; isLoading: boolean; // eslint-disable-next-line @typescript-eslint/no-explicit-any error: any; successMessage?: string; } const DynamicMaterialUIForm: React.FC<DynamicMaterialUIFormProps> = ({ onSubmit, fields, buttons, isLoading, error, successMessage }) => { const [formData, setFormData] = useState<Record<string, string>>({}); const { streamId, studentId } = useParams(); const handleChange = (e: ChangeEvent<{ name?: string; value: unknown }> | SelectChangeEvent<string>, name: string) => { const value = typeof e === 'string' ? e : e.target.value; setFormData((prevFormData) => ({ ...prevFormData, [name]: value as string })); }; // if (successMessage) { // setFormData({}); // } const handleSubmit = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => { e.preventDefault(); if (streamId) { const formDataWithStreamid = { ...formData, streamId }; onSubmit(formDataWithStreamid); } else if (studentId) { const formDataWithStudentid = { ...formData, student: studentId }; onSubmit(formDataWithStudentid); } else { onSubmit(formData); } }; return ( <form> <Box p={3} boxShadow={2} borderRadius={4}> <Grid container spacing={3} justifyContent="center"> {fields.map(({ name, label, type, options }) => ( <Grid item xs={12} sm={6} key={name}> {type === 'dropdown' ? ( <Select fullWidth label={label} id={name} name={name} value={formData[name] || ''} onChange={(e) => handleChange(e, name)} variant="outlined" size="small" > {options?.map((option) => ( <MenuItem key={option} value={option}> {option} </MenuItem> ))} </Select> ) : ( <TextField required={true} fullWidth label={label} type={type} id={name} name={name} value={formData[name] || ''} onChange={(e) => handleChange(e, name)} variant="outlined" size="small" /> )} </Grid> ))} </Grid> <Box mt={3} textAlign="center"> {buttons.map(({ label, variant = 'contained', color = 'primary', type = 'button', onClick }, index) => ( <Button key={index} variant={variant} color={color} type={type} onClick={(e) => { console.log('Called'); console.log('Called'); console.log('Called'); onClick && handleSubmit(e); }} style={{ margin: '0 10px' }} > {isLoading ? <CircularProgress size={24} color="inherit" /> : label} </Button> ))} </Box> {!isLoading && error && <Alert severity="error">{error}</Alert>} {!isLoading && successMessage && <Alert severity="success">{successMessage}</Alert>} </Box> </form> ); }; export default DynamicMaterialUIForm;
import ActionTypes, { Action, IPost } from "../actions/types"; export interface IPostState { posts?: IPost[]; post?: IPost; loading: boolean; error: {}; } const initialState = { posts: [], loading: true, error: {}, }; export const post = (state: IPostState = initialState, action: Action): IPostState => { const { type, payload } = action; switch (type) { case ActionTypes.GET_POSTS: return { ...state, posts: payload, loading: false, }; case ActionTypes.GET_POST: return { ...state, post: payload, loading: false, }; case ActionTypes.CLEAR_POST: return { ...state, post: undefined, loading: true, }; case ActionTypes.POST_ERROR: return { ...state, error: payload, loading: false, }; case ActionTypes.UPDATE_LIKES: return { ...state, posts: state && state.posts && state.posts.map((post) => post._id === payload._id ? { ...post, likes: payload.likes } : post ), loading: false, }; case ActionTypes.DELETE_POST: return { ...state, posts: state.posts?.filter((post) => post._id !== payload), loading: false, }; case ActionTypes.ADD_POST: return { ...state, posts: state.posts && [...state.posts, payload], loading: false, }; case ActionTypes.ADD_COMMENT: return { ...state, post: state.post && { ...state.post, comments: [payload.comment, ...state.post.comments] }, loading: false, }; case ActionTypes.DELETE_COMMENT: return { ...state, post: state.post && { ...state.post, comments: state.post.comments.filter((comment) => comment._id !== payload), }, loading: false, }; default: return state; } };
import React from 'react'; import { useDataPlanets } from '../context/TableProvider'; import { useFilterPlanets } from '../context/FilterProvider'; import tableHeader from '../public/tableHeader'; function Table() { const { planetFilter } = useFilterPlanets(); const { data } = useDataPlanets(); let planetsFromData = data.filter( (planet) => planet.name.toLowerCase() .includes(planetFilter.filterByName.name.toLowerCase()), ); planetFilter.filterByNumericValues.forEach((filters) => { const { column, value, comparison } = filters; if (comparison === 'maior que') { planetsFromData = planetsFromData.filter( (planet) => Number(planet[column]) > Number(value), ); } if (comparison === 'menor que') { planetsFromData = planetsFromData.filter( (planet) => Number(planet[column]) < Number(value), ); } if (comparison === 'igual a') { planetsFromData = planetsFromData.filter( (planet) => Number(planet[column]) === Number(value), ); } }); return ( <div> <table> { <thead> <tr> {tableHeader.map((header) => (<th key={ header }>{header}</th>))} </tr> </thead> } {planetsFromData.map((planet) => ( <tbody key={ planet.name }> <tr> <td>{planet.name}</td> <td>{planet.rotation_period}</td> <td>{planet.orbital_period}</td> <td>{planet.diameter}</td> <td>{planet.climate}</td> <td>{planet.gravity}</td> <td>{planet.terrain}</td> <td>{planet.surface_water}</td> <td>{planet.population}</td> <td>{planet.films}</td> <td>{planet.created}</td> <td>{planet.edited}</td> <td>{planet.url}</td> </tr> </tbody> ))} </table> </div> ); } export default Table;
#![feature(is_sorted, let_chains, new_uninit, maybe_uninit_write_slice)] use base_case::sort_simple_cases; use constants::{BASE_CASE_MULTIPLIER, BASE_CASE_SIZE, BLOCK_SIZE, MIN_PARALLEL_BLOCKS_PER_THREAD}; use parallel::parallel_ips4o; use rayon::current_num_threads; use sequential::sequential_ips4o; use std::{cmp::Ordering, fmt::Debug, mem::size_of}; mod base_case; mod bucket_pointers; mod classifier; mod constants; mod parallel; mod permute_blocks; mod sequential; mod storage; mod util; pub(crate) trait Sortable: Clone + Debug + Default {} impl<T: Clone + Debug + Default> Sortable for T {} pub(crate) trait Less<T>: Fn(&T, &T) -> bool {} impl<T, F: Fn(&T, &T) -> bool> Less<T> for F {} pub(crate) trait PSortable: Sortable + Send + Sync + Copy {} impl<T: Sortable + Send + Sync + Copy> PSortable for T {} pub(crate) trait PLess<T>: Less<T> + Sync {} impl<T, F: Less<T> + Sync> PLess<T> for F {} #[inline] pub fn sort<T>(v: &mut [T]) where T: Ord + Debug + Default + Clone, { ips4o(v, T::lt); debug_assert!(v.is_sorted()); } #[inline] pub fn sort_by<T, F>(v: &mut [T], compare: F) where T: Debug + Default + Clone, F: Fn(&T, &T) -> Ordering, { ips4o(v, |a, b| compare(a, b) == Ordering::Less); debug_assert!(v.is_sorted_by(|a, b| Some(compare(a, b)))); } #[inline] pub fn sort_by_key<T, K, F>(v: &mut [T], f: F) where T: Debug + Default + Clone, F: Fn(&T) -> K, K: Ord, { ips4o(v, |a, b| f(a).lt(&f(b))); let is_less = |a, b| f(a).lt(&f(b)); debug_assert!(v.is_sorted_by(is_less_to_compare!(is_less))); } #[inline] pub fn sort_par<T>(v: &mut [T]) where T: Ord + Debug + Default + Clone + Copy + Send + Sync, { ips4o_par(v, T::lt); debug_assert!(v.is_sorted()); } fn ips4o<T, F>(v: &mut [T], is_less: F) where T: Sortable, F: Less<T>, { // Sorting has no meaningful behavior on zero-sized types. Do nothing. if size_of::<T>() == 0 { return; } if sort_simple_cases(v, &is_less) { return; } if v.len() <= BASE_CASE_MULTIPLIER * BASE_CASE_SIZE { base_case::base_case_sort(v, &is_less); return; } sequential_ips4o(v, &is_less); } #[inline] #[allow(unused)] fn ips4o_par<T, F>(v: &mut [T], mut is_less: F) where T: PSortable, F: Fn(&T, &T) -> bool + Sync, { // Sorting has no meaningful behavior on zero-sized types. Do nothing. if size_of::<T>() == 0 { return; } if sort_simple_cases(v, &is_less) { return; } if v.len() <= BASE_CASE_MULTIPLIER * BASE_CASE_SIZE { base_case::base_case_sort(v, &is_less); return; } // Sorting in parallel makes no sense with only one thread if current_num_threads() == 1 { ips4o(v, is_less); return; } if v.len() <= current_num_threads() * MIN_PARALLEL_BLOCKS_PER_THREAD * BLOCK_SIZE { sequential_ips4o(v, &is_less); return; } parallel_ips4o(v, &is_less); } #[cfg(test)] mod tests { use std::{ cmp::{max, min}, fs, panic, }; use rand::{distributions::Uniform, rngs::StdRng, seq::SliceRandom, Rng, SeedableRng}; use crate::{debug, sort, sort_par, PSortable}; const TEST_PARALLEL: bool = false; const FAILING_INPUT: &str = "./target/failing_input.json"; fn sort_test<T>(input: &mut [T]) where T: Ord + PSortable, { if TEST_PARALLEL { sort_par(input) } else { sort(input) } } fn sort_and_save_to_file_if_failed(mut input: Vec<u64>) { let clone = input.clone(); let result = panic::catch_unwind(move || { sort_test(&mut input); input }); match result { Ok(sorted_input) => { let mut sorted = clone.clone(); sorted.sort(); if sorted != sorted_input { let data = serde_json::to_string(&clone).expect("unable to serialize failing slice"); fs::write(FAILING_INPUT, data).expect("unable to write failing slice to file"); panic!("result is not a sorted permutation of its input") } } Err(_e) => { let data = serde_json::to_string(&clone).expect("unable to serialize failing slice"); fs::write(FAILING_INPUT, data).expect("unable to write failing slice to file"); panic!() } } } #[test] fn simple_test1() { let mut input = some_vec(); input.append(&mut some_vec()); input.append(&mut some_vec()); input.append(&mut some_vec()); input.append(&mut some_vec()); debug!(input); sort_test(&mut input); debug!(input); } #[test] fn simple_test2() { let mut input = [ 1, 9, 26, 29, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, ]; debug!(input); sort_test(&mut input); debug!(input); assert!(input.is_sorted()); } #[test] fn simple_test3() { let mut input = [4, 4, 4, 4, 4, 4, 1, 2]; debug!(input); sort_test(&mut input); debug!(input); assert!(input.is_sorted()); } #[test] fn simple_test4() { let mut input = some_vec(); input.append(&mut some_vec()); debug!(input); sort_test(&mut input); debug!(input); assert!(input.is_sorted()); } #[test] fn fuzz() { // let mut rng = rand::thread_rng(); let mut rng = StdRng::seed_from_u64(0); for _ in 0..5000 { let len: usize = rng.gen_range(0..10000); let (a, b) = ( rng.gen_range(u64::MIN..u64::MAX), rng.gen_range(u64::MIN..u64::MAX), ); let (lower, upper) = (min(a, b), max(a, b)); let input: Vec<_> = (0..len).map(|_| rng.gen_range(lower..upper)).collect(); sort_and_save_to_file_if_failed(input); } } #[ignore = "only used to reproduce failing test"] #[test] fn test_json_input() { let input = fs::read_to_string(FAILING_INPUT).expect("no file found at given path"); let mut input: Vec<u64> = serde_json::from_str(&input).unwrap(); let mut sorted = input.clone(); sorted.sort(); sort_test(&mut input); assert!(input.is_sorted()); assert!(input == sorted); } #[test] fn test_block_aligned_buckets() { // blocks of size 8 let mut v = vec![]; for i in 0..200 { v.append(&mut vec![i, i, i, i, i, i, i, i]); } let mut rng = StdRng::seed_from_u64(0); for _ in 0..1 { v.shuffle(&mut rng); sort_test(&mut v); assert!(v.is_sorted()); } } #[test] fn big_test() { let len = 1usize << 20; let mut rng = StdRng::seed_from_u64(0); let range = Uniform::from(0..10_000); let mut v: Vec<u32> = (0..len).map(|_| rng.sample(&range)).collect(); let mut sorted = v.clone(); sorted.sort(); sort_test(&mut v); assert!(v.is_sorted()); assert!(v == sorted); } fn some_vec() -> Vec<i32> { vec![5, 5, 35, 7, 4, 4, 4, 7, 67, 7, 7, 6] // 3*4 + 2*5 + 1*6 + 4*7 + 1*35 + 1*67 // times 2: 6*4 + 4*5 + 2*6 + 8*7 + 2*35 + 2*67 // times 3: 9*4 + 6*5 + 3*6 + 12*7 + 3*35 + 3*67 // times 4: 12*4 + 8*5 + 4*6 + 16*7 + 4*35 + 4*67 // times 5: 15*4 + 10*5 + 5*6 + 20*7 + 5*35 + 5*67 } }
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.views.decorators.cache import cache_control from mariadmin.models import MessageFlow, WebsiteHeadingImage from django.db.models import Q class ProcessingUtilities: def getUserMessageFlows(self, userName): # get the lookup parameters parameterOne = f"admin>>>{userName}" parameterTwo = f"{userName}>>>admin" # create the lookup queries lookupQuery = Q(fromToMeta=parameterOne) | Q(fromToMeta=parameterTwo) # execute the query userMessageFlow = MessageFlow.objects.filter(lookupQuery) return userMessageFlow def deleteAllMessageForUser(self, userName): userMessageFlow = self.getUserMessageFlows(userName=userName) # delete if userMessageFlow: userMessageFlow.delete() else: pass return def getTheAvailableMessagesFlow(self, userName): # get the messages userMessageFlow = self.getUserMessageFlows(userName=userName) # results messageFlowData = [ { 'time': eachMessageObject.dateSent.strftime("%d-%m-%Y, %H:%M %p"), 'message': eachMessageObject.messageMeta, 'userGroup': 1 if (eachMessageObject.fromToMeta == f"admin>>>{userName}") else 2 } for eachMessageObject in userMessageFlow ] return messageFlowData @login_required(login_url="messenger:home") @cache_control(no_cache=True, must_revalidate=True, no_store=True) def accountsHomePage(request): # context={'avatar': request.session['avatar']} if request.user.is_superuser: return redirect("admin_panel:admin-home") else: # get user messages loggedInUserName = request.user.username # load initials if 'avatar' in request.session: # print('url:', request.session['avatar']) pass else: # add the initials userInitials = loggedInUserName.strip()[0].upper() request.session['initials'] = userInitials # get all messages availableMessages = ProcessingUtilities().getTheAvailableMessagesFlow(userName=loggedInUserName) bannerImage = WebsiteHeadingImage.objects.all().first() pageContext = { 'chat_messages': availableMessages, 'banner_image': bannerImage.imageUrl if bannerImage else None } # print("Image:", request.session['avatar']) # chat-page.html return render(request, "mariadmin/profile-page.html", context=pageContext)
"use strict"; /** * This file contains all the global local storage variables that need to be accessed on startup or during the app lifecycle. These are the variables that are not sent by the renderer process but are the localstorage variables used by the main process. * Our goal is to send as many variables as possible from the renderer process to the main process to avoid using local storage variables. */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchLocalStorage = exports.setChildProcesses = exports.setStopped = exports.setTurnOffNotifications = exports.turnOffNotifications = exports.childProcesses = exports.stopped = exports.setSavedCustomModelsPath = exports.savedCustomModelsPath = exports.setSavedBatchUpscaylFolderPath = exports.savedBatchUpscaylFolderPath = exports.setSavedImagePath = exports.savedImagePath = void 0; const main_window_1 = require("../main-window"); const logit_1 = __importDefault(require("./logit")); /** * The saved image path so that the select image dialog can open to the last used path. */ exports.savedImagePath = ""; function setSavedImagePath(value) { exports.savedImagePath = value; (0, logit_1.default)("🖼️ Updating Image Path: ", exports.savedImagePath); } exports.setSavedImagePath = setSavedImagePath; /** * The saved folder path so that the select folder to upscayl dialog can open to the last used path. */ exports.savedBatchUpscaylFolderPath = undefined; function setSavedBatchUpscaylFolderPath(value) { exports.savedBatchUpscaylFolderPath = value; (0, logit_1.default)("📁 Updating Folder Path: ", exports.savedBatchUpscaylFolderPath); } exports.setSavedBatchUpscaylFolderPath = setSavedBatchUpscaylFolderPath; /** * The saved custom models folder path so that we can load the list of custom models from that folder on startup. */ exports.savedCustomModelsPath = undefined; function setSavedCustomModelsPath(value) { exports.savedCustomModelsPath = value; (0, logit_1.default)("📁 Updating Custom Models Folder Path: ", exports.savedCustomModelsPath); } exports.setSavedCustomModelsPath = setSavedCustomModelsPath; /** * The stopped variable to stop the batch upscayl process. */ exports.stopped = false; /** * The child processes array to store the spawned upscayl processes. */ exports.childProcesses = []; /** * The turn off notifications variable, so that we can load this value on startup. */ exports.turnOffNotifications = false; function setTurnOffNotifications(value) { exports.turnOffNotifications = value; (0, logit_1.default)("🔕 Updating Turn Off Notifications: ", exports.turnOffNotifications); } exports.setTurnOffNotifications = setTurnOffNotifications; // SETTERS function setStopped(value) { exports.stopped = value; (0, logit_1.default)("🛑 Updating Stopped: ", exports.stopped); } exports.setStopped = setStopped; function setChildProcesses(value) { exports.childProcesses.push(value); (0, logit_1.default)("👶 Updating Child Processes: ", JSON.stringify({ binary: exports.childProcesses[0].process.spawnfile, args: exports.childProcesses[0].process.spawnargs, })); } exports.setChildProcesses = setChildProcesses; // LOCAL STORAGE function fetchLocalStorage() { const mainWindow = (0, main_window_1.getMainWindow)(); if (!mainWindow) return; // GET LAST IMAGE PATH TO LOCAL STORAGE mainWindow.webContents .executeJavaScript('localStorage.getItem("lastImagePath");', true) .then((lastImagePath) => { if (lastImagePath && lastImagePath.length > 0) { setSavedImagePath(lastImagePath); } }); // GET LAST FOLDER PATH TO LOCAL STORAGE mainWindow.webContents .executeJavaScript('localStorage.getItem("lastSavedBatchUpscaylFolderPath");', true) .then((lastSavedBatchUpscaylFolderPath) => { if (lastSavedBatchUpscaylFolderPath && lastSavedBatchUpscaylFolderPath.length > 0) { setSavedBatchUpscaylFolderPath(lastSavedBatchUpscaylFolderPath); } }); // GET LAST CUSTOM MODELS FOLDER PATH TO LOCAL STORAGE mainWindow.webContents .executeJavaScript('localStorage.getItem("customModelsFolderPath");', true) .then((value) => { if (value && value.length > 0) { setSavedCustomModelsPath(value); } }); // GET TURN OFF NOTIFICATIONS (BOOLEAN) FROM LOCAL STORAGE mainWindow.webContents .executeJavaScript('localStorage.getItem("turnOffNotifications");', true) .then((lastSaved) => { if (lastSaved !== null) { setTurnOffNotifications(lastSaved === "true"); } }); } exports.fetchLocalStorage = fetchLocalStorage;
<template> <div> <form @submit.prevent="submitForm"> <div> <label for="name">Nom:</label> <input type="text" id="name" v-model="form.name"> </div> <div> <label for="email">Email:</label> <input type="email" id="email" v-model="form.email"> </div> <div> <label for="subject">Sujet:</label> <input type="text" id="subject" v-model="form.subject"> </div> <div> <label for="message">Message:</label> <textarea id="message" v-model="form.message"></textarea> </div> <button type="submit">Envoyer</button> </form> <div v-if="submitted"> <h3>Données Soumises :</h3> <p>Nom: {{ form.name }}</p> <p>Email: {{ form.email }}</p> <p>Sujet: {{ form.subject }}</p> <p>Message: {{ form.message }}</p> </div> </div> </template> <script setup> import { reactive, ref } from 'vue'; const form = reactive({ name: '', email: '', subject: '', message: '' }); const submitted = ref(false); function submitForm() { submitted.value = true; } </script> <style> /* Ajoutez ici le style de votre choix */ </style>
//: [Previous](@previous) /* Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. ``` Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] ``` */ import Foundation func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { var ocurrences : [Int:Int] = [:] var freq: [[Int]] = Array(repeating: [], count: nums.count+1) for num in nums { if let tableValue = ocurrences[num] { ocurrences[num] = tableValue + 1 } else { ocurrences[num] = 1 } } for (key, value) in ocurrences { freq[value].append(key) } var result = [Int]() for i in (0..<freq.count).reversed() { if !freq[i].isEmpty { result.append(contentsOf: freq[i]) if result.count == k { return result } } } return result } topKFrequent([1,1,1,2,2,2,3],3) //: [Next](@next)
#' Hard clustering using k-means #' #' This function expects output from custom minimap test dataset that contains original locations of mapped reads in the genome. #' #' @param counts.l A \code{list} of directional read counts per long read/contig per library. #' @param num.clusters Desired number of clusters or cluster centers (k-means clustering). #' @param nstart Number of random sets to choose cluster centers (k-means clustering). #' @param iter.max A maximum number of allowed interations (k-means clustering). #' @return A \code{list} of estimated theta values for every cluster and cell. #' @importFrom stats kmeans #' @author David Porubsky #' @export #' @examples #'## Get an example file #'exampleFile <- system.file("extdata/data", "rawCounts_5e+06bp_dynamic.RData", package = "SaaRclust") #'## Load BAM count table #'counts.l <- get(load(exampleFile)) #'## Get hard clustering results #'hardClust.ord <- hardClust(counts.l, num.clusters=100, nstart = 100) #' hardClust <- function(counts.l=NULL, num.clusters=NULL, nstart=10, iter.max=10) { message("Hard clustering") ptm <- startTimedMessage(" Kmeans clustering for ",num.clusters," clusters") ratios.l <- list() for (j in 1:length(counts.l)) { #lib.name <- names(tab.l[j]) #message("\tWorking on ",lib.name) counts <- counts.l[[j]] ratios <- (counts[,2]-counts[,1])/(counts[,2]+counts[,1]) #calculate ratio of WW reads ratios[is.nan(ratios)] <- 0 ratios.l[[j]] <- ratios } ratios.m <- do.call(cbind, ratios.l) #ratios.m[ratios.m < 0.5] <- -1 #ratios.m[ratios.m > 0.5] <- 1 ratios.m[] <- as.numeric(findInterval(ratios.m, c(-0.5, 0.5))) #hard clustering using kmeans km <- suppressWarnings( stats::kmeans(ratios.m, centers = num.clusters, nstart = nstart, iter.max = iter.max) ) ord <- km$cluster #ratios.m.ord <- ratios.m[order(ord),] stopTimedMessage(ptm) return(ord) } #' Estimate theta values based on hard clustering #' #' This function takes results of hard clustering and estimates majority cell types for each Strand-seq library #' #' @param hard.clust A \code{integer} of cluster assignments for each long read or contig. #' @inheritParams hardClust #' @inheritParams countProb #' @return A \code{list} of estimated theta values for every cluster and cell. #' @author David Porubsky #' @export #' @examples #'## Get an example file #'exampleFile <- system.file("extdata/data", "rawCounts_5e+06bp_dynamic.RData", package = "SaaRclust") #'## Load BAM count table #'counts.l <- get(load(exampleFile)) #'## Get hard clustering results #'hardClust.ord <- hardClust(counts.l, num.clusters=100, nstart = 100) #'## Estimate theta parameter #'theta.param <- estimateTheta(counts.l, hard.clust=hardClust.ord, alpha=0.1) #' estimateTheta <- function(counts.l=NULL, hard.clust=NULL, alpha=0.1) { ptm <- startTimedMessage("Estimate theta values") theta.estim <- list() for (j in 1:length(counts.l)) { minus.c <- split(counts.l[[j]][,1], hard.clust) plus.c <- split(counts.l[[j]][,2], hard.clust) #minus.counts <- sapply(minus.c, sum) #plus.counts <- sapply(plus.c, sum) #probs <- countProb2(minusCounts = minus.counts, plusCounts = plus.counts) clust.prob <- mapply(function(X,Y) { countProb(X,Y) }, X=minus.c, Y=plus.c) clust.prob.norm <- lapply(clust.prob, function(x) colSums(log(x))) estimates <- sapply(clust.prob.norm, which.max) #Assign cell type probs based on the majority type in each cluster probs <- list() for (i in 1:length(clust.prob)) { estim <- estimates[i] if (estim == 1) { theta <- c(1-alpha, alpha/2, alpha/2) } else if (estim == 2) { theta <- c(alpha/2, 1-alpha, alpha/2) } else { theta <- c(alpha/2, alpha/2, 1-alpha) } probs[[i]] <- theta } probs <- do.call(rbind, probs) theta.estim[[j]] <- probs } stopTimedMessage(ptm) return(theta.estim) } #' Hierarchical clustering for merging the kmeans clusters. #' #' This function takes as input the kmeans hard clustering output and the initialized thetas and merges the kmeans clusters based on thetas #' #' @param theta.param A \code{list} of estimated theta values for each cluster and cell. #' @param k Desired number of clusters after merging. #' @inheritParams estimateTheta #' @return A new hard clustering with the correct number of clusters #' @importFrom stats dist hclust cutree #' @author Maryam Ghareghani, David Porubsky #' mergeClusters <- function(hard.clust, theta.param, k=46) { ptm <- startTimedMessage("Merging clusters") theta.all <- do.call(cbind, theta.param) hc <- stats::hclust(stats::dist(theta.all)) hc.clust <- stats::cutree(hc, k=k) stopTimedMessage(ptm) return(sapply(hard.clust, function(i) hc.clust[i])) }
package com.cursoandroid.servicesapp import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.util.Log import android.view.View import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { var isBound = false var boundedService: BoundedService? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Vinculacion al servicio val intent = Intent(this, BoundedService::class.java) bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE) } private val serviceConnection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { val binder = service as BoundedService.MyBinder boundedService = binder.getService() Log.i("MyService", "Service connected") isBound = true } override fun onServiceDisconnected(name: ComponentName?) { Log.i("MyService", "Service disconnected") isBound = false } } fun showTime(view: View) { if (isBound) { val currentTime = boundedService?.getCurrentTime() Log.d("MyService", "Current time: $currentTime") } } fun initService(view: View) { val serviceIntent = Intent(this, MyService::class.java) startService(serviceIntent) } fun disconnectService(view: View) { if (isBound) { unbindService(serviceConnection) isBound = false } } }
import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; class MyAppointment extends StatefulWidget { const MyAppointment({Key? key}) : super(key: key); @override State<MyAppointment> createState() => _MyAppointmentState(); } class _MyAppointmentState extends State<MyAppointment> { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( title: Text('My Appointments'), ), body: Appointments(), ), ); } } class Appointments extends StatelessWidget { @override Widget build(BuildContext context) { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final FirebaseAuth _auth = FirebaseAuth.instance; String doctor_uid; String doctor_appointment_id; return StreamBuilder( stream: _firestore .collection('users') .doc(_auth.currentUser!.uid) .collection('myAppointments') .snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator(), ); } else if (snapshot.hasError) { return Center( child: Text('Error: ${snapshot.error}'), ); } else if (!snapshot.hasData || snapshot.data!.docs.isEmpty) { return Center( child: Text('No appointments found.'), ); } return ListView( children: snapshot.data!.docs.map((DocumentSnapshot document) { Map<String, dynamic> data = document.data() as Map<String, dynamic>; // Extracting appointment details String patientName = data['patient name'] ?? 'Unknown'; String doctor = data['doctor'] ?? 'Unknown'; String date = data['date'] ?? 'Unknown'; String time = data['time'] ?? 'Unknown'; String patientNumber = data['phone'] ?? 'Unknown'; return Container( padding: EdgeInsets.all(8.0), margin: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), decoration: BoxDecoration( color: Colors.blueGrey[50], border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(8.0), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Patient: $patientName', style: TextStyle(fontWeight: FontWeight.bold), ), SizedBox(height: 4.0), Text('Date: $date, Time: $time'), Text('Doctor: $doctor'), Text('Patient Number: $patientNumber'), SizedBox(height: 8.0), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ ElevatedButton( onPressed: () { // Show confirmation dialog showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Confirm Appointment Cancellation'), content: Text( 'Are you sure you want to cancel this appointment?'), actions: <Widget>[ TextButton( child: Text('Cancel'), onPressed: () { Navigator.of(context) .pop(); // Close the dialog }, ), TextButton( child: Text('Confirm'), onPressed: () { doctor_uid = data['doc_uid'] ?? 'Unknown'; doctor_appointment_id = data['doc_appointment_id'] ?? 'Unknown'; _firestore .collection('Doctors') .doc(doctor_uid) .collection('myAppointments') .doc(doctor_appointment_id) .delete(); // Delete the appointment document from Firestore document.reference.delete(); Navigator.of(context) .pop(); // Close the dialog // Show Snackbar ScaffoldMessenger.of(context) .showSnackBar( SnackBar( content: Text( 'Appointment cancelled successfully.'), ), ); }, ), ], ); }, ); }, style: ElevatedButton.styleFrom( primary: Colors.red, ), child: Text( 'Cancel', style: TextStyle(color: Colors.white), ), ), ], ), ], ), ); }).toList(), ); }, ); } } void main() { runApp(MaterialApp( title: 'My Appointments', home: MyAppointment(), )); }
<%= form_with(model: message, class: "px-8 pt-6 pb-8 mb-4") do |form| %> <% if message.errors.any? %> <div class="text-red-500 bg-red-100 border border-red-500 p-3 rounded mb-2"> <h2><%= pluralize(message.errors.count, "error") %> prohibited this message from being saved:</h2> <ul> <% message.errors.each do |error| %> <li><%= error.full_message %></li> <% end %> </ul> </div> <% end %> <div class="mb-4"> <%= form.label :text, "Your message", class: "block text-gray-700 text-sm font-bold mb-2" %> <%= form.text_area( :text, class: "shadow appearance-none border #{message.errors.has_key?(:text) ? "border-red-500 " : " "}rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline", rows: "10", ) %> <% if message.errors.has_key?(:text) %> <p class="text-red-500 text-xs italic"> <%= message.errors[:text].join %> </p> <% end %> </div> <div class="mb-4"> <%= form.label :name, "Name", class: "block text-gray-700 text-sm font-bold mb-2" %> <%= form.text_field( :name , class: "shadow appearance-none border #{message.errors.has_key?(:text) ? "border-red-500 " : " "}rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline", ) %> <% if message.errors.has_key?(:name) %> <p class="text-red-500 text-xs italic"> <%= message.errors[:name].join %> </p> <% end %> </div> <div class="mb-4"> <%= form.label :picture, "Photo", class: "block text-gray-700 text-sm font-bold mb-2" %> <%= form.file_field :picture, class: "shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" %> </div> <div class="flex items-center justify-between"> <%= form.submit class: "bg-slate-200 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline", disabled: true, id: "submit" %> </div> <% end %> <script type="text/javascript"> //this is not working if the page is reloaded const messageInput = document.querySelector('#message_text'); const nameInput = document.querySelector('#message_name'); const buttonGo = document.querySelector('#submit') messageInput.addEventListener('input', updateButton); nameInput.addEventListener('input', updateButton); function updateButton() { const messageInput = document.querySelector('#message_text'); const nameInput = document.querySelector('#message_name'); let countMessage = messageInput.value.length; let countName = nameInput.value.length; if ( countMessage <= 260 && countMessage >= 5 && countName > 4 ) { document.querySelector("#submit").disabled=false buttonGo.style.backgroundColor = "blue"; } else { document.querySelector("#submit").disabled=true buttonGo.style.backgroundColor = "grey"; } } </script>
/* Copyright 2016 Codependable, LLC and Jonathan David Guerin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "PlotsFactory.h" #include "XYPlot.h" //resource init must be outside namespace and needed when used in a library void TerbitPlotsResourceInitialize() { Q_INIT_RESOURCE(plots); } namespace terbit { PlotsFactory::PlotsFactory() { TerbitPlotsResourceInitialize(); m_provider = "Terbit"; m_name = "Plots"; m_description = QObject::tr("Connector plotting library."); QString display, description; display = QObject::tr("Line Plot"); description = QObject::tr("Line plot with support for multiple series and zooming."); m_typeList.push_back(new FactoryTypeInfo(QString(XYPLOT_TYPENAME), DATA_CLASS_KIND_DISPLAY, QIcon(":/images/32x32/linechart.png"),display,description,BuildScriptDocumentationXYPlot())); } PlotsFactory::~PlotsFactory() { for(std::vector<FactoryTypeInfo*>::iterator i = m_typeList.begin(); i != m_typeList.end(); ++i) { delete *i; } } const QString &PlotsFactory::GetProviderName() const { return m_provider; } const std::vector<FactoryTypeInfo*>& PlotsFactory::GetTypeList() const { return m_typeList; } const QString &PlotsFactory::GetDescription() const { return m_description; } DataClass* PlotsFactory::CreateInstance(const QString& typeName) { if (typeName == XYPLOT_TYPENAME) { return new XYPlot(); } else { return NULL; } } }
import NaturalLanguage import Foundation public class SwiftTfIdf { public var rawSentences = [String]() // raw sentences public var topN: Int // how many top word want to get public var stopWords: [String] // the stop word :) public init(text: String, stopWords: [String], topN: Int) { self.stopWords = stopWords self.topN = topN // just another normal looping to get get the rawsentences from rawraw text (paradox heh :v) text.enumerateSubstrings(in: text.startIndex..., options: [.localized, .bySentences]) { (tag, _, _, _) in self.rawSentences.append(tag?.lowercased() ?? "") } } // Convert a bunch of sentences to array of words func sentences2ArrayOfWords(sentences: [String]) -> [[String]]{ var arrayOfWordInSentences = [[String]]() let syncQueue1 = DispatchQueue(label: "level1") for sentence in sentences { var words = [String]() let tokenizer = NLTokenizer(unit: .word) tokenizer.string = sentence tokenizer.enumerateTokens(in: sentence.startIndex..<sentence.endIndex) { tokenRange, _ in let word = String(sentence[tokenRange]) // check if the word is stopword let isStopWord = stopWords.contains(word) if !isStopWord { words.append(word) } return true } syncQueue1.sync { arrayOfWordInSentences.append(words) } } return arrayOfWordInSentences } // calc the TF value func calcTf(document: [String]) -> [String: Float] { var TF_dict = [String: Float]() for term in document { let isKeyExist = TF_dict[String(term)] != nil if isKeyExist { TF_dict[String(term)]! += 1 } else { TF_dict[String(term)] = 1 } } for (key, _) in TF_dict { TF_dict[String(key)] = TF_dict[String(key)]! / Float(document.count) } return TF_dict } // calc the DF value func calcDF(tfDict: [[String: Float]]) -> [String: Float] { var countDF = [String: Float]() for document in tfDict { for term in document { let isKeyExist = countDF[term.key] != nil if isKeyExist { countDF[term.key]! += 1 } else { countDF[term.key] = 1 } } } return countDF } // calc the IDF value func calcIDF(nDocument: Int, df: [String: Float]) -> [String: Float] { var idfDict = [String: Float]() for term in df { idfDict[term.key] = logf(Float(nDocument) / (df[term.key]! + 1)) } return idfDict } // calc the TFIDF value func calcTfIdf(TF: [String: Float], IDF: [String: Float]) -> [String: Float] { var tfIdfDict = [String: Float]() for term in TF { tfIdfDict[term.key] = TF[term.key]! * IDF[term.key]! } return tfIdfDict } // calc the TFIDF vector func calcTFIDFVec(tfIdfDict: [String: Float], uniqueTerm: [String]) -> [Float] { var tfIdfVec = [Float]() for _ in 1...uniqueTerm.count { tfIdfVec.append(Float(0)) } var initVal = 0 for term in uniqueTerm { let isKeyExist = tfIdfDict[term] != nil if isKeyExist { tfIdfVec[initVal] = tfIdfDict[term]! } initVal += 1 } return tfIdfVec } // final calculation to get the tf, df, idf and tfidf value public func finalCount() -> [(key: String, value: Float)] { // convert raw sentences to array of sentences let dictOfWordInSentences = sentences2ArrayOfWords(sentences: rawSentences) // initalize the tf value as dictionary var dictOfTF = [[String: Float]]() let nDocument = dictOfWordInSentences.count // looping for calc the tf value var initValue = 0 for document in dictOfWordInSentences { let tf_dict = calcTf(document: document) dictOfTF.append(tf_dict) } // calc the df value let dictOfDf = calcDF(tfDict: dictOfTF) _ = calcIDF(nDocument: nDocument, df: dictOfDf) // initial dictionary of tf idf value var dictOfTFIDF = [[String: Float]]() // calc the tf idf value for document in dictOfTF { dictOfTFIDF.append(calcTfIdf(TF: document, IDF: dictOfDf)) } // sorting the results let sortedDF = dictOfDf.sorted { return $0.value > $1.value } // get topN var uniqueTerm = [String]() initValue = 0 for term in sortedDF { if initValue > self.topN { break } uniqueTerm.append(term.key) initValue += 1 } // calc the tfidf vector var tfIdfVec = [[String: [Float]]]() initValue = 0 for documents in dictOfTFIDF { var initVec = [String: [Float]]() for document in documents { initVec[document.key] = calcTFIDFVec(tfIdfDict: documents, uniqueTerm: uniqueTerm) } tfIdfVec.append(initVec) initValue += 1 } // ranking the results var rawRanking = [String: Float]() for terms in tfIdfVec { var rankingValue: Float = Float(0.0) for dict in terms { for i in dict.value { rankingValue += i } rawRanking[String(dict.key)] = rankingValue } } // combine the ranking and its value var ranking = [String: Float]() for i in uniqueTerm { let isKeyExist = rawRanking[i] != nil if isKeyExist { ranking[String(i)] = rawRanking[String(i)] } } // again.. just another sorting let sortedRanking = ranking.sorted { return $0.value > $1.value } return sortedRanking } }
// // UIPinchGestureRecognizerDemoController.swift // SwiftHelper (iOS) // // Created by sauron on 2022/6/23. // Copyright © 2022 com.teenloong. All rights reserved. // import SwiftUI import SnapKit class UIPinchGestureRecognizerDemoController: SUIBaseViewController { private var label: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "UIPinchGestureRecognizerDemo" configurePinchGestureLabel() } private func configurePinchGestureLabel() { label = UILabel() label.backgroundColor = .systemPink label.isUserInteractionEnabled = true label.text = "UIPinchGestureRecognizer" view.addSubview(label) label.snp.remakeConstraints { make in make.center.equalToSuperview() make.size.equalTo(CGSize(width: 100, height: 100)) } let pinch = UIPinchGestureRecognizer( target: self, action: #selector(handlePinch)) label.addGestureRecognizer(pinch) } @objc func handlePinch(sender: UIPinchGestureRecognizer) { #if DEBUG print("\(#function) state: \(sender.state)") #endif switch sender.state { case .began: #if DEBUG print("\(#function) state: began") #endif break case .possible: #if DEBUG print("\(#function) state: possible") #endif break case .changed: #if DEBUG print("\(#function) state: changed") #endif let w = label.frame.width * sender.scale let h = label.frame.height * sender.scale if w >= 50 && w <= 300 && h >= 50 && h <= 300 { label.snp.remakeConstraints { make in make.center.equalToSuperview() make.size.equalTo(CGSize(width: w, height: h)) } } break case .ended: #if DEBUG print("\(#function) state: ended") #endif // label.snp.remakeConstraints { make in // make.center.equalToSuperview() // make.size.equalTo(CGSize(width: 100, height: 100)) // } break case .cancelled: #if DEBUG print("\(#function) state: cancelled") #endif break case .failed: #if DEBUG print("\(#function) state: failed") #endif break @unknown default: #if DEBUG print("\(#function) state: @unknown default") #endif break } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } #if DEBUG struct UIPinchGestureRecognizerDemoController_Previews: PreviewProvider { static var previews: some View { PlatformViewControllerRepresent(UIPinchGestureRecognizerDemoController()) } } #endif
# Gitのリポジトリをクローンしてmainブランチをチェックアウト $ git clone -b main https://git.kernel.org/pub/scm/git/git.git $ cd git $ git checkout v2.9.0-rc2 Note: switching to 'v2.9.0-rc2'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by switching back to a branch. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -c with the switch command. Example: git switch -c <new-branch-name> Or undo this operation with: git switch - Turn off this advice by setting config variable advice.detachedHead to false HEAD is now at 49fa3dc761 Git 2.9-rc2 $ git checkout -b new_branch $ git branch * (HEAD detached at 49fa3dc761) main $ git checkout main Updating files: 100% (3013/3013), done. Previous HEAD position was 49fa3dc761 Git 2.9-rc2 Switched to branch 'main' Your branch is up to date with 'origin/main'. $ git branch * main
<template> <div class="project-page-style"> <FoldingCard title="基础配置"> <el-form ref="refForm" label-width="115px" :inline="true" :model="basicConfig" class="pr-5"> <div class="mb-10px"> <el-form-item label="选择回显配置" label-position="left"> <el-select v-model="chooseTmp" filterable placeholder="选择回显配置" class="w-300px"> <el-option v-for="item in configList" :key="item.id" :label="item.name" :value="item.id" @click="reshowConfig(item)" /> </el-select> </el-form-item> </div> <el-form-item label="作者" prop="author" :rules="formRules.isNotNull('不能为空')"> <el-input v-model="basicConfig.author" placeholder="请输入作者" class="w-300px" /> </el-form-item> <el-form-item label="生成的api文件名" prop="apiFileName" :rules="formRules.isNotNull('不能为空')"> <el-input v-model="basicConfig.apiFileName" placeholder="生成的api文件名" class="w-300px" /> </el-form-item> <div class="rowSC mt-20px"> <el-form-item label="是否modal" prop="isImport" :rules="formRules.isNotNull('不能为空')" label-position="left" > <el-switch v-model="basicConfig.isModal" inline-prompt active-color="#13ce66" inactive-color="#ff4949" active-value="true" inactive-value="false" /> </el-form-item> <div v-if="basicConfig.isModal === 'true'" class="rowSC"> <el-form-item label="modal标题" prop="modalTitle" :rules="formRules.isNotNull('不能为空')"> <el-input v-model="basicConfig.modalTitle" placeholder="modal标题" class="w-200px" /> </el-form-item> <el-form-item label="modal宽度" prop="modalWidth" :rules="formRules.isNotNull('不能为空')"> <el-input v-model="basicConfig.modalWidth" placeholder="modal宽度" class="w-100px" /> </el-form-item> </div> </div> </el-form> </FoldingCard> <FoldingCard title="接口配置"> <el-form ref="refForm" label-width="120px" :inline="true" :model="apiConfig" class="pr-5"> <el-form-item label="详情接口" prop="detailApi" :rules="formRules.isNotNull('不能为空')" label-position="left"> <el-input v-model="apiConfig.detailApi" placeholder="详情接口" class="w-380px" /> </el-form-item> <el-form-item label="详情方法" prop="detailMethod" :rules="formRules.isNotNull('不能为空')" label-position="left" > <el-input v-model="apiConfig.detailMethod" placeholder="详情方法" class="w-80px" /> </el-form-item> </el-form> </FoldingCard> <FoldingCard title="字段配置"> <div class="rowSC mb-40px"> <span class="mr-10px">几个模块:</span> <el-select v-model="choosePie" placeholder="选择几份"> <el-option key="1" label="1" :value="1" @click="choosePieClick(1)" /> <el-option key="2" label="2" :value="2" @click="choosePieClick(2)" /> <el-option key="3" label="3" :value="3" @click="choosePieClick(3)" /> <el-option key="4" label="4" :value="4" @click="choosePieClick(4)" /> </el-select> </div> <div v-for="(item, index) in choosePieArr" :key="index" :class="[choosePieArr.length - 1 !== index && 'mb-50px']"> <DetailTableConfig ref="refDetailTableConfig" :item="item" /> </div> </FoldingCard> <FoldingCard title="保存和生成模板"> <div class="rowSS mb-20px"> <el-input v-model="saveFileName" class="wi-200px mr-10px" placeholder="保存文件名(可以不填写)" /> <el-button type="primary" @click="saveTmp">保存配置</el-button> <el-button type="primary" @click="copyJson">复制json数据</el-button> </div> <div> <div class="mb-10px">选择模板文件</div> <TemplateConfig ref="refTemplateConfig" /> </div> <div class="mt-20px"> <div class="mt-10px mb-20px"> <el-image style="width: 100px; height: 100px" src="./pre-image/settle-detail.png" :preview-src-list="['./pre-image/settle-detail.png']" :initial-index="1" fit="cover" /> </div> <el-button type="primary" @click="generatorBaseModelTemp">点击生成模板</el-button> </div> </FoldingCard> </div> </template> <script setup lang="ts"> import DetailTableConfig from './DetailTableConfig.vue' import {changeWordToCase} from "@/components/TableExtra/front-extra-code"; import {copyReactive, downLoadTempByApi} from '@/hooks/use-common' const { formRules } = useElement() /*项目和作者信息配置*/ const basicConfig = reactive({ author: '', apiFileName: '', apiFileNameCase: '', dataTime: getCurrentTime(), modalTitle: '', modalWidth: 500, isModal: 'false' }) /*前端api接口配置*/ const apiConfig = reactive({ detailApi: '', detailMethod: 'get' }) /*表字段信息(可多选)*/ //Search const refDetailTableConfig = ref([]) const copyJson = async () => { const subData = await generatorSubData() copyValueToClipboard(JSON.stringify(subData)) elMessage('复制成功') } //生成模板 const generatorSubData = () => { const saveArr: Array<any> = [] return new Promise((resolve) => { refDetailTableConfig.value.forEach((fItem:any) => { const pieItem = fItem.getSearchTableData() saveArr.push(pieItem) }) basicConfig.apiFileNameCase = changeWordToCase(basicConfig.apiFileName) const generatorData = { basicConfig, apiConfig, saveFileName:saveFileName.value, tableConfigArr: saveArr } if (!saveFileName) { saveFileName.value = basicConfig.apiFileName } resolve(generatorData) }) } const refTemplateConfig = ref() const generatorBaseModelTemp = async () => { const subData: any = await generatorSubData() const { id } = refTemplateConfig.value.returnData() const subFormData = new FormData() //获取edit里的数据 subFormData.append('id', id) subFormData.append('jsonData', JSON.stringify(subData)) subFormData.append('fileNamePre', basicConfig.apiFileName) const reqConfig = { url: '/basis-func/templateFile/generatorTemplateFileByConfig', method: 'post', data: subFormData } downLoadTempByApi(reqConfig) } //保存模板 const saveFileName:any = ref() const saveName = 'settle-first-detail' const saveTmp = async () => { const subData = await generatorSubData() const reqConfig = { url: '/basis-func/configSave/insert', method: 'post', data: { name: `${saveFileName.value}-${saveName}(${getCurrentTime()})`, generatorConfig: JSON.stringify(subData) } } axiosReq(reqConfig).then(() => { elMessage('配置保存成功') getSaveTmp() }) } //获取模板 onMounted(() => { getSaveTmp() }) //查询模板 const configList:any = ref([]) const chooseTmp = ref('') const getSaveTmp = () => { const reqConfig = { url: '/basis-func/configSave/selectPage', method: 'get', bfLoading: true, data: { pageSize: 200, pageNum: 1, name: saveName } } axiosReq(reqConfig).then(({ data }) => { configList.value = data?.records //回显第一个元素 for (const fItem of configList.value) { if (fItem.name?.includes(saveName)) { chooseTmp.value = fItem.name reshowData(fItem) return } } }) } //配置选择 const reshowConfig = (item) => { reshowData(item) } const reshowData = (item) => { const generatorConfig = JSON.parse(item.generatorConfig) copyReactive(basicConfig,generatorConfig.basicConfig || generatorConfig.poaForm) copyReactive(apiConfig,generatorConfig.apiConfig || {}) saveFileName.value = generatorConfig.saveFileName choosePie.value = generatorConfig.tableConfigArr.length choosePieClick(choosePie.value) //回显table的数据 nextTick(() => { refDetailTableConfig.value.forEach((fItem:any, fIndex) => { fItem.reshowSearchTableData(generatorConfig.tableConfigArr[fIndex] || []) }) }) } const choosePie = ref(1) //1.文字-横向 2.文字-纵向 3.表格 const choosePieArr:any = ref([]) const choosePieClick = (value) => { choosePieArr.value = [] for (let i = 0; i < value; i++) { choosePieArr.value.push({ direction: '1', tableDataType: 2, field: '', method: '', api: '', splitNum: 2, cartTitle: '', columnArr: [], dillColumnArr: [] }) } } defineExpose({ generatorSubData }) </script> <style scoped lang="scss"></style>
import 'dart:developer'; import 'package:allxclusive/core/utills/platform/platform.dart'; import 'package:flutter/material.dart'; import 'package:gradient_borders/input_borders/gradient_outline_input_border.dart'; import '../../../../core/theme/colors.dart'; import '../../../../core/theme/gradients.dart'; class AuthDatePicker extends StatelessWidget { final String hint; final IconData? icon; final double iconSize; final Widget? suffixIcon; final String? error; final bool pickTime; final Function(DateTime) onDateSelected; final DateTime? initial; final DateTime? startDate; final DateTime? endDate; final TextEditingController? controller; const AuthDatePicker({Key? key, required this.hint, this.iconSize = 16, this.icon, this.suffixIcon, this.error, this.controller, required this.onDateSelected, this.initial, this.pickTime = false, this.startDate, this.endDate}) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: () async{ final DateTime? date; date = pickTime ? await AppPlatformUtils.instance.showTimePicker(context, initial ?? DateTime.now().subtract(Duration(days: 50)), startDate ?? DateTime(1920), endDate ?? DateTime.now().subtract(Duration(days: 30))) : await AppPlatformUtils.instance.showDatePicker(context, initial ?? DateTime.now().subtract(Duration(days: 50)), startDate ?? DateTime(1920), endDate ?? DateTime.now().subtract(Duration(days: 30))); if(date == null){ return; } onDateSelected.call(date); }, child: TextField( controller: controller, enabled: false, style: TextStyle(fontSize: 14, color: KColors.textColor), decoration: InputDecoration( errorText: error, isDense: true, errorStyle: TextStyle(color: KColors.errorColor), prefixIcon: icon == null ? null : Icon(icon, color: KColors.lightGrey, size: iconSize,), suffixIcon: suffixIcon, contentPadding: const EdgeInsets.symmetric( vertical: 15, horizontal: 20 ), hintText: hint, hintStyle: TextStyle(color: KColors.lightGrey, fontSize: 14), border: OutlineInputBorder( borderRadius: BorderRadius.circular(16), borderSide: BorderSide( color: KColors.darkGrey, width: 1 ) ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(16), borderSide: BorderSide( color: KColors.darkGrey, width: 1 ) ), disabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(16), borderSide: BorderSide( color: KColors.darkGrey, width: 1 ) ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: KColors.errorColor,width: 2), borderRadius: BorderRadius.circular(16), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: KColors.errorColor,width: 2), borderRadius: BorderRadius.circular(16), ), focusedBorder: GradientOutlineInputBorder( width: 2, borderRadius: BorderRadius.circular(16), gradient: KGradient.authFieldSelectedGradient, ), ) ), ); } }
package com.NewProject.NewPage.service.Impl; import com.NewProject.NewPage.entity.Post; import com.NewProject.NewPage.exception.ResourceNotFoundException; import com.NewProject.NewPage.payload.PostDto; import com.NewProject.NewPage.repository.PostRepository; import com.NewProject.NewPage.service.PostService; import org.modelmapper.ModelMapper; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service public class PostServiceImpl implements PostService { private PostRepository postRepository; private ModelMapper modelMapper; public PostServiceImpl(PostRepository postRepository,ModelMapper modelMapper) { this.postRepository = postRepository; this.modelMapper = modelMapper; } @Override public PostDto createPost(PostDto postDto) { Post post = mapToEntity(postDto); // Post post = new Post(); // // post.setTitle(postDto.getTitle()); // post.setDescription(postDto.getDescription()); // post.setContent(postDto.getContent()); Post savedPost = postRepository.save(post); PostDto dto = mapToDto(savedPost); // dto.setTitle(savedPost.getTitle()); // dto.setDescription(savedPost.getDescription()); // dto.setContent(savedPost.getContent()); return dto; } @Override public PostDto getPostById(long id) { Post post = postRepository.findById(id).orElseThrow( ()-> new ResourceNotFoundException("Post not found with id:"+id) ); PostDto dto = mapToDto(post); return dto; } @Override public List<PostDto> getAllPost(int pageNo, int pageSize, String sortBy, String sortDir) { Sort sort = (sortDir.equalsIgnoreCase(Sort.Direction.ASC.name())) ? Sort.by(sortBy).ascending() : Sort.by(sortBy).descending(); Pageable pageable = PageRequest.of(pageNo,pageSize, sort); Page<Post> pagePost = postRepository.findAll(pageable); List<Post> content = pagePost.getContent(); List<PostDto> collect = content.stream().map(post -> mapToDto(post)).collect(Collectors.toList()); return collect; } PostDto mapToDto(Post post) { PostDto dto = modelMapper.map(post, PostDto.class); // PostDto dto = new PostDto(); // // dto.setTitle(post.getTitle()); // dto.setDescription(post.getDescription()); // dto.setContent(post.getContent()); return dto; } Post mapToEntity(PostDto postDto){ Post post = modelMapper.map(postDto, Post.class); // Post post = new Post(); // // post.setTitle(postDto.getTitle()); // post.setDescription(postDto.getDescription()); // post.setContent(postDto.getContent()); return post; } } // crud Repository not help you to do pagination // pagination concept in crud repository is not there // if you want to apply pagination and sorting then use JPA Repository // java library they help us to copy the code one library to another library
# Subscribers API Documentation ## Base URL `http://localhost:3000/` `https://subscribe-0cjn.onrender.com/` ## Endpoints ### 1. Get All Subscribers **URL:** `/subscribers` **Method:** `GET` **Description:** Retrieves an array of all subscribers. **Response:** [ { "_id": "60c72b2f9f1b8b001c8e4a2b", "name": "Jeread Krus", "subscribedChannel": "CNET" }, { "_id": "60c72b2f9f1b8b001c8e4a2c", "name": "John Doe", "subscribedChannel": "freeCodeCamp.org" }, { "_id": "60c72b2f9f1b8b001c8e4a2d", "name": "Lucifer", "subscribedChannel": "Sentex" } ] ### 2. Get Subscriber Names and Channels URL: /subscribers/names Method: GET Description: Retrieves an array of all subscribers with only name and subscribedChannel fields. Response: [ { "name": "Jeread Krus", "subscribedChannel": "CNET" }, { "name": "John Doe", "subscribedChannel": "freeCodeCamp.org" }, { "name": "Lucifer", "subscribedChannel": "Sentex" } ] Sure, here's a markdown file documenting the API endpoints: markdown Copy code ### 3. Get Subscriber by ID URL: /subscribers/:id Method: GET Description: Retrieves a subscriber by the given ID. URL Parameters: id: The ID of the subscriber to retrieve. Response: Success (200): { "_id": "60c72b2f9f1b8b001c8e4a2b", "name": "Jeread Krus", "subscribedChannel": "CNET" } Error (400): { "message": "Subscriber not found" }
<%@ page import = "java.sql.*, java.util.*"%> <%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>產品</title> <link rel="stylesheet" href="assets/css/main.css"> </head> <body> <header class="navFixed" > <div > <h1><a href="index.jsp">伍壹零</a></h1> <div class="wrap"> <form action="search.jsp" method="POST"> <div class="search"> <input class="search-bar" type="search" name="search" id="search" placeholder="請輸入商品名稱"> <button class="search-btn" type="submit" name="search" value=""><img src="assets/images/search.jpg"></button> </div> </form> </div> <nav> <ul class="drop-down-menu"> <li> <a href="#">產品選購</a> <ul class="dropdown"> <li><a href="chinese.jsp">華語專輯</a></li> <li><a href="japan.jsp">日文專輯</a></li> <li><a href="korea.jsp">韓語專輯</a></li> <li><a href="english.jsp">英文專輯</a></li> </ul> </li> <li> <a href="#">會員中心</a> <ul class="dropdown"> <li><%@ include file="issignin.jsp" %></li> <li><a href="order.jsp">訂單</a></li> <li><a href="setup.jsp">修改資料</a></li> </ul> </li> <li><a href="aboutus.jsp">關於我們</a></li> <li><a href="car.jsp">購物車</a></li> </ul> </nav> </div> </header> <main> <article> <% String pro_id = request.getParameter("gopro"); try { //Step 1: 載入資料庫驅動程式 Class.forName("com.mysql.jdbc.Driver"); try { //Step 2: 建立連線 String url="jdbc:mysql://localhost/?serverTimezone=UTC"; Connection con = DriverManager.getConnection(url,"root","1234"); if(con.isClosed()) out.println("連線建立失敗"); else { //Step 3: 選擇資料庫 String sql = "USE album"; con.createStatement().execute(sql); sql = "SELECT * FROM `product` WHERE `id` = '"+pro_id+"'"; ResultSet rs = con.createStatement().executeQuery(sql); rs.next(); out.print("<section>"); out.print("<div class='blank'></div>"); out.print("<div class='procenter'>"); out.print("<div class='pro'>"); out.print("<img class='proimg' src='"+rs.getString(2)+"'>"); out.print("<div class='prodetail'>"); out.print("<div class='protext'>"); out.print("<span>"); out.print("<h3>"+rs.getString(3)+"</h3>"); out.print("<h4> NT$"+rs.getInt(7)+"&nbsp; &nbsp; &nbsp; 庫存數:"+rs.getInt(8)+"</h4>"); out.print("<hr><p>商品資訊</p>"); out.print("<h5>"+rs.getString(9)+"</h5>"); out.print("<div class='carreducea'>"); out.print("<p>購買數量:</p>"); out.print("<form action='addtocar.jsp' method='POST'>"); out.print("<input type='number' value='1' min='1' name='count' class='num'>"); out.print("<input type='hidden' name='pro_id' value='"+pro_id+"'>"); out.print("<button type='submit' class='carreducecar'>加入購物車</button>"); out.print("</form>"); out.print("</div>"); out.print("</span>"); out.print("</div>"); out.print("</div>"); out.print("</div>"); out.print("</div>"); out.print("</section>"); } //Step 6: 關閉連線 con.close(); } catch (SQLException sExec) { out.println("SQL錯誤"+sExec.toString()); } } catch (ClassNotFoundException err) { out.println("class錯誤"+err.toString()); } %> <hr> <section> <div class="content"> <div class="contentblock"> <div class="con"> <span> <h2>評論區</h2> </span> <hr> <% try { //Step 1: 載入資料庫驅動程式 Class.forName("com.mysql.jdbc.Driver"); try { //Step 2: 建立連線 String url="jdbc:mysql://localhost/?serverTimezone=UTC"; String sql=""; Connection con=DriverManager.getConnection(url,"root","1234"); if(con.isClosed()) out.println("連線建立失敗"); else { //Step 3: 選擇資料庫 sql="USE `album`"; con.createStatement().execute(sql); //Step 4: 執行 SQL 指令, 若要操作記錄集, 需使用executeQuery, 才能傳回ResultSet String comm = request.getParameter("gopro"); sql="SELECT * FROM `message` WHERE `id` = '"+pro_id+"'"; //算出共幾筆留言 ResultSet rs=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY).executeQuery(sql); rs.last(); int total_content = rs.getRow(); //Step 5: 顯示結果 sql = "SELECT * FROM `message` WHERE `id` = '"+pro_id+"' ORDER BY `message_id` DESC"; rs = con.createStatement().executeQuery(sql); while(rs.next()){ out.print("<div class='condetail'>"); out.print("<img class='conimg' src='assets/images/person.png'>"); out.print("<span><div class='flexblock'><h3>"+rs.getString(3)+"</h3><p>"+rs.getString(4)+"</p></div>"); out.print("<div class='star'><img class='default' src='assets/images/star.png'><img class='default' src='assets/images/star.png' ><img class='default' src='assets/images/star.png' ><img class='default' src='assets/images/star.png' ><img class='default' src='assets/images/star.png' ></div>"); out.print("<h4>"+rs.getString(5)+"</h4></span></div><hr>"); } //Step 6: 關閉連線 con.close(); } } catch (SQLException sExec) { out.println("SQL錯誤"+sExec.toString()); } } catch (ClassNotFoundException err) { out.println("class錯誤"+err.toString()); } %> <div class="condetail1"> <form action="add.jsp" method="POST"> <input class="namebar" name="namebar" type="text" placeholder="請輸入名稱"> <div id="stars" class="star1"> <img class="default" src="assets/images/star2.png" > <img class="default" src="assets/images/star2.png" > <img class="default" src="assets/images/star2.png" > <img class="default" src="assets/images/star2.png" > <img class="default" src="assets/images/star2.png" > </div> <div class="submit"><textarea name="content" class="area" cols="80" rows="5"></textarea></div> <input type="hidden" name="com" value="<%=pro_id%>"> <button type="submit" class="btn" >送出</button> <button type="reset" class="btn" >重填</button> </form> </div> </div> </div> </div> </section> </article> </main> <footer> <h5>Copyrgiht @ 2022 All rights reserved</h5> </footer> <script type="text/javascript" src="assets/js/star.js"></script> </body> </html>
// ==UserScript== // @name Add Custom Repositories to GitHub Profile // @namespace http://tampermonkey.net/ // @version 1.0 // @description Add custom GitHub repositories to the profile page // @author imekaku // @icon https://github.githubassets.com/favicons/favicon.png // @match https://github.com/* // @grant GM_xmlhttpRequest // ==/UserScript== (function() { 'use strict'; // Add YOUR NAME! var username = 'username'; // Get the current page URL var currentPageUrl = window.location.href; // Check if the current URL contains the specified username if (!currentPageUrl.includes(`github.com/${username}`)) { // If it does not contain, do not execute the script return; } // Add YOUR REPOSITORIES! var repoNames = ['repository-name-01', 'repository-name-02']; repoNames.forEach(function(repoName) { var repoURL = `https://github.com/${username}/${repoName}`; GM_xmlhttpRequest({ method: "GET", url: repoURL, onload: function(response) { var parser = new DOMParser(); var doc = parser.parseFromString(response.responseText, "text/html"); // Some repositories may not have description information var repoDescriptionElement = doc.querySelector("div.hide-sm.hide-md p.f4.my-3"); var repoDescription = repoDescriptionElement ? repoDescriptionElement.textContent.trim() : ''; var repoVisibility = doc.querySelector("span.Label.Label--secondary.v-align-middle.mr-1.d-none.d-md-block")?.textContent.trim() || 'Public'; // Some repositories may not have language information var languageElement = doc.querySelector("div.BorderGrid-cell li.d-inline"); var language, languageColor; if (languageElement) { language = languageElement.querySelector("span.color-fg-default.text-bold")?.textContent.trim(); var color = languageElement.querySelector("svg.octicon-dot-fill")?.getAttribute("style"); var colorMatch = color ? color.match(/color:([^;]+)/) : null; languageColor = colorMatch ? colorMatch[1].trim() : ''; } else { language = ''; languageColor = ''; } // Add repository information to github profile page addRepoToProfile(repoName, repoDescription, repoURL, language, languageColor, repoVisibility); } }); }); function addRepoToProfile(repoName, repoDescription, repoURL, language, languageColor, repoVisibility) { var listItem = document.createElement("li"); listItem.className = "mb-3 d-flex flex-content-stretch col-12 col-md-6 col-lg-6"; var descriptionHTML = repoDescription ? `<p class="pinned-item-desc color-fg-muted text-small mt-2 mb-0">${repoDescription}</p>` : ''; var languageHTML = language ? ` <p class="mb-0 mt-2 f6 color-fg-muted"> <span class="d-inline-block mr-3"> <span class="repo-language-color" style="background-color: ${languageColor}"></span> <span itemprop="programmingLanguage">${language}</span> </span> </p>` : ''; listItem.innerHTML = ` <div class="Box d-flex p-3 width-full public source"> <div class="pinned-item-list-item-content"> <div class="d-flex width-full position-relative"> <div class="flex-1"> <span class="position-relative"> <a href="${repoURL}" class="Link mr-1 text-bold wb-break-word"> <span class="repo">${repoName}</span> </a> </span> <span class="Label Label--secondary v-align-middle mt-1 no-wrap v-align-baseline Label--inline">${repoVisibility}</span> </div> </div> ${descriptionHTML} ${languageHTML} </div> </div>`; // Get current ol list, and then add the new list var ol = document.querySelector(".js-pinned-items-reorder-list"); if (ol) { ol.appendChild(listItem); } } })();
import { useEffect, useState } from "react"; import { Flex, Image, Text } from "@chakra-ui/react"; export const UserPage = ({ userId }) => { const [user, setUser] = useState(null); useEffect(() => { //Fetching user info based on userId const fetchUser = async () => { try { const response = await fetch("http://localhost:3000/users/" + userId); const userData = await response.json(); setUser(userData); } catch (error) { console.error("Error fetching data from user:", error); } }; fetchUser(); }, [userId]); if (!user) { return <div>Loading user data ...</div>; } return ( <div> <Flex direction={"column"} alignItems={"center"} position={"relative"} right={"3rem"} mb={{ base: "1rem", md: "1rem" }} > <Text color={"teal.300"} fontWeight={"bold"} marginBottom={2} marginLeft={"5rem"} > Event Creator </Text> <Image src={user.image} alt={user.name} w={{ base: "3rem", md: "5rem" }} h={{ base: "3rem", md: "5rem" }} borderRadius={"full"} marginBottom={1} marginLeft={"5.5rem"} /> <Text fontSize={{ base: "0.7rem", md: "0.8rem" }} marginLeft={"5rem"}> {user.name} </Text> </Flex> </div> ); }; export default UserPage;
using Auth.Data; using Auth.Extensions; using Auth.Services; using Auth.Services.IServices; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using System; using System.Text; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //add connetion to database builder.Services.AddDbContext<MyDbContext>(options => { options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")); }); //services builder.Services.AddScoped<IUserService, UserService>(); //AutoMapper builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //authentication builder.Services.AddAuthentication("Bearer").AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = builder.Configuration["TokenSecurity:Issuer"], ValidAudience = builder.Configuration["TokenSecurity:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["TokenSecurity:SecretKey"])) }; }); //authorization builder.Services.AddAuthorization(options => { options.AddPolicy("Admin", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim("Role", "Admin"); }); }); builder.AddSwaggenGenExtension(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.ApplyMigration(); app.Run();
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core';import { IReceipt } from '../models/Receipt'; import { Observable } from 'rxjs'; import { config } from '../config/config'; const url = `${config.backendUrl}/receipts` @Injectable({ providedIn: 'root' }) export class ReceiptsService { constructor(private httpClient: HttpClient) { } newReceipt(tableId: string): Observable<IReceipt>{ return this.httpClient.post<IReceipt>(`${url}`, {tableId}); } getReceipts(filter: string = ''): Observable<IReceipt[]>{ return this.httpClient.get<IReceipt[]>(`${url}${filter}`); } getReceiptById(receiptId: string): Observable<IReceipt>{ return this.httpClient.get<IReceipt>(`${url}/${receiptId}`); } updateOrderById(receiptId: string, body: {}): Observable<IReceipt>{ return this.httpClient.patch<IReceipt>(`${url}/${receiptId}`, body); } deleteOrderById(receiptId: string): Observable<IReceipt>{ return this.httpClient.delete<IReceipt>(`${url}/${receiptId}`); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.shuffle.sort; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.LinkedList; import scala.Tuple2; import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.spark.SparkConf; import org.apache.spark.TaskContext; import org.apache.spark.executor.ShuffleWriteMetrics; import org.apache.spark.memory.MemoryConsumer; import org.apache.spark.memory.TaskMemoryManager; import org.apache.spark.serializer.DummySerializerInstance; import org.apache.spark.serializer.SerializerInstance; import org.apache.spark.storage.BlockManager; import org.apache.spark.storage.DiskBlockObjectWriter; import org.apache.spark.storage.TempShuffleBlockId; import org.apache.spark.unsafe.Platform; import org.apache.spark.unsafe.array.LongArray; import org.apache.spark.unsafe.memory.MemoryBlock; import org.apache.spark.util.Utils; /** * An external sorter that is specialized for sort-based shuffle. * <p> * Incoming records are appended to data pages. When all records have been inserted (or when the * current thread's shuffle memory limit is reached), the in-memory records are sorted according to * their partition ids (using a {@link ShuffleInMemorySorter}). The sorted records are then * written to a single output file (or multiple files, if we've spilled). The format of the output * files is the same as the format of the final output file written by * {@link org.apache.spark.shuffle.sort.SortShuffleWriter}: each output partition's records are * written as a single serialized, compressed stream that can be read with a new decompression and * deserialization stream. * <p> * Unlike {@link org.apache.spark.util.collection.ExternalSorter}, this sorter does not merge its * spill files. Instead, this merging is performed in {@link UnsafeShuffleWriter}, which uses a * specialized merge procedure that avoids extra serialization/deserialization. */ final class ShuffleExternalSorter extends MemoryConsumer { private final Logger logger = LoggerFactory.getLogger(ShuffleExternalSorter.class); @VisibleForTesting static final int DISK_WRITE_BUFFER_SIZE = 1024 * 1024; private final int numPartitions; private final TaskMemoryManager taskMemoryManager; private final BlockManager blockManager; private final TaskContext taskContext; private final ShuffleWriteMetrics writeMetrics; /** Force this sorter to spill when there are this many elements in memory. For testing only */ private final long numElementsForSpillThreshold; /** The buffer size to use when writing spills using DiskBlockObjectWriter */ private final int fileBufferSizeBytes; /** * Memory pages that hold the records being sorted. The pages in this list are freed when * spilling, although in principle we could recycle these pages across spills (on the other hand, * this might not be necessary if we maintained a pool of re-usable pages in the TaskMemoryManager * itself). */ private final LinkedList<MemoryBlock> allocatedPages = new LinkedList<MemoryBlock>(); private final LinkedList<SpillInfo> spills = new LinkedList<SpillInfo>(); /** Peak memory used by this sorter so far, in bytes. **/ private long peakMemoryUsedBytes; // These variables are reset after spilling: @Nullable private ShuffleInMemorySorter inMemSorter; @Nullable private MemoryBlock currentPage = null; private long pageCursor = -1; public ShuffleExternalSorter( TaskMemoryManager memoryManager, BlockManager blockManager, TaskContext taskContext, int initialSize, int numPartitions, SparkConf conf, ShuffleWriteMetrics writeMetrics) { super(memoryManager, (int) Math.min(PackedRecordPointer.MAXIMUM_PAGE_SIZE_BYTES, memoryManager.pageSizeBytes())); this.taskMemoryManager = memoryManager; this.blockManager = blockManager; this.taskContext = taskContext; this.numPartitions = numPartitions; // Use getSizeAsKb (not bytes) to maintain backwards compatibility if no units are provided this.fileBufferSizeBytes = (int) conf.getSizeAsKb("spark.shuffle.file.buffer", "32k") * 1024; this.numElementsForSpillThreshold = conf.getLong("spark.shuffle.spill.numElementsForceSpillThreshold", Long.MAX_VALUE); this.writeMetrics = writeMetrics; this.inMemSorter = new ShuffleInMemorySorter(this, initialSize); this.peakMemoryUsedBytes = getMemoryUsage(); } /** * Sorts the in-memory records and writes the sorted records to an on-disk file. * This method does not free the sort data structures. * * @param isLastFile if true, this indicates that we're writing the final output file and that the * bytes written should be counted towards shuffle spill metrics rather than * shuffle write metrics. */ private void writeSortedFile(boolean isLastFile) throws IOException { final ShuffleWriteMetrics writeMetricsToUse; if (isLastFile) { // We're writing the final non-spill file, so we _do_ want to count this as shuffle bytes. writeMetricsToUse = writeMetrics; } else { // We're spilling, so bytes written should be counted towards spill rather than write. // Create a dummy WriteMetrics object to absorb these metrics, since we don't want to count // them towards shuffle bytes written. writeMetricsToUse = new ShuffleWriteMetrics(); } // This call performs the actual sort. final ShuffleInMemorySorter.ShuffleSorterIterator sortedRecords = inMemSorter.getSortedIterator(); // Currently, we need to open a new DiskBlockObjectWriter for each partition; we can avoid this // after SPARK-5581 is fixed. DiskBlockObjectWriter writer; // Small writes to DiskBlockObjectWriter will be fairly inefficient. Since there doesn't seem to // be an API to directly transfer bytes from managed memory to the disk writer, we buffer // data through a byte array. This array does not need to be large enough to hold a single // record; final byte[] writeBuffer = new byte[DISK_WRITE_BUFFER_SIZE]; // Because this output will be read during shuffle, its compression codec must be controlled by // spark.shuffle.compress instead of spark.shuffle.spill.compress, so we need to use // createTempShuffleBlock here; see SPARK-3426 for more details. final Tuple2<TempShuffleBlockId, File> spilledFileInfo = blockManager.diskBlockManager().createTempShuffleBlock(); final File file = spilledFileInfo._2(); final TempShuffleBlockId blockId = spilledFileInfo._1(); final SpillInfo spillInfo = new SpillInfo(numPartitions, file, blockId); // Unfortunately, we need a serializer instance in order to construct a DiskBlockObjectWriter. // Our write path doesn't actually use this serializer (since we end up calling the `write()` // OutputStream methods), but DiskBlockObjectWriter still calls some methods on it. To work // around this, we pass a dummy no-op serializer. final SerializerInstance ser = DummySerializerInstance.INSTANCE; writer = blockManager.getDiskWriter(blockId, file, ser, fileBufferSizeBytes, writeMetricsToUse); int currentPartition = -1; while (sortedRecords.hasNext()) { sortedRecords.loadNext(); final int partition = sortedRecords.packedRecordPointer.getPartitionId(); assert (partition >= currentPartition); if (partition != currentPartition) { // Switch to the new partition if (currentPartition != -1) { writer.commitAndClose(); spillInfo.partitionLengths[currentPartition] = writer.fileSegment().length(); } currentPartition = partition; writer = blockManager.getDiskWriter(blockId, file, ser, fileBufferSizeBytes, writeMetricsToUse); } final long recordPointer = sortedRecords.packedRecordPointer.getRecordPointer(); final Object recordPage = taskMemoryManager.getPage(recordPointer); final long recordOffsetInPage = taskMemoryManager.getOffsetInPage(recordPointer); int dataRemaining = Platform.getInt(recordPage, recordOffsetInPage); long recordReadPosition = recordOffsetInPage + 4; // skip over record length while (dataRemaining > 0) { final int toTransfer = Math.min(DISK_WRITE_BUFFER_SIZE, dataRemaining); Platform.copyMemory( recordPage, recordReadPosition, writeBuffer, Platform.BYTE_ARRAY_OFFSET, toTransfer); writer.write(writeBuffer, 0, toTransfer); recordReadPosition += toTransfer; dataRemaining -= toTransfer; } writer.recordWritten(); } if (writer != null) { writer.commitAndClose(); // If `writeSortedFile()` was called from `closeAndGetSpills()` and no records were inserted, // then the file might be empty. Note that it might be better to avoid calling // writeSortedFile() in that case. if (currentPartition != -1) { spillInfo.partitionLengths[currentPartition] = writer.fileSegment().length(); spills.add(spillInfo); } } inMemSorter.reset(); if (!isLastFile) { // i.e. this is a spill file // The current semantics of `shuffleRecordsWritten` seem to be that it's updated when records // are written to disk, not when they enter the shuffle sorting code. DiskBlockObjectWriter // relies on its `recordWritten()` method being called in order to trigger periodic updates to // `shuffleBytesWritten`. If we were to remove the `recordWritten()` call and increment that // counter at a higher-level, then the in-progress metrics for records written and bytes // written would get out of sync. // // When writing the last file, we pass `writeMetrics` directly to the DiskBlockObjectWriter; // in all other cases, we pass in a dummy write metrics to capture metrics, then copy those // metrics to the true write metrics here. The reason for performing this copying is so that // we can avoid reporting spilled bytes as shuffle write bytes. // // Note that we intentionally ignore the value of `writeMetricsToUse.shuffleWriteTime()`. // Consistent with ExternalSorter, we do not count this IO towards shuffle write time. // This means that this IO time is not accounted for anywhere; SPARK-3577 will fix this. writeMetrics.incShuffleRecordsWritten(writeMetricsToUse.shuffleRecordsWritten()); taskContext.taskMetrics().incDiskBytesSpilled(writeMetricsToUse.shuffleBytesWritten()); } } /** * Sort and spill the current records in response to memory pressure. */ @Override public long spill(long size, MemoryConsumer trigger) throws IOException { if (trigger != this || inMemSorter == null || inMemSorter.numRecords() == 0) { return 0L; } logger.info("Thread {} spilling sort data of {} to disk ({} {} so far)", Thread.currentThread().getId(), Utils.bytesToString(getMemoryUsage()), spills.size(), spills.size() > 1 ? " times" : " time"); writeSortedFile(false); final long spillSize = freeMemory(); taskContext.taskMetrics().incMemoryBytesSpilled(spillSize); return spillSize; } private long getMemoryUsage() { long totalPageSize = 0; for (MemoryBlock page : allocatedPages) { totalPageSize += page.size(); } return ((inMemSorter == null) ? 0 : inMemSorter.getMemoryUsage()) + totalPageSize; } private void updatePeakMemoryUsed() { long mem = getMemoryUsage(); if (mem > peakMemoryUsedBytes) { peakMemoryUsedBytes = mem; } } /** * Return the peak memory used so far, in bytes. */ long getPeakMemoryUsedBytes() { updatePeakMemoryUsed(); return peakMemoryUsedBytes; } private long freeMemory() { updatePeakMemoryUsed(); long memoryFreed = 0; for (MemoryBlock block : allocatedPages) { memoryFreed += block.size(); freePage(block); } allocatedPages.clear(); currentPage = null; pageCursor = 0; return memoryFreed; } /** * Force all memory and spill files to be deleted; called by shuffle error-handling code. */ public void cleanupResources() { freeMemory(); if (inMemSorter != null) { inMemSorter.free(); inMemSorter = null; } for (SpillInfo spill : spills) { if (spill.file.exists() && !spill.file.delete()) { logger.error("Unable to delete spill file {}", spill.file.getPath()); } } } /** * Checks whether there is enough space to insert an additional record in to the sort pointer * array and grows the array if additional space is required. If the required space cannot be * obtained, then the in-memory data will be spilled to disk. */ private void growPointerArrayIfNecessary() throws IOException { assert(inMemSorter != null); if (!inMemSorter.hasSpaceForAnotherRecord()) { long used = inMemSorter.getMemoryUsage(); LongArray array; try { // could trigger spilling array = allocateArray(used / 8 * 2); } catch (OutOfMemoryError e) { // should have trigger spilling assert(inMemSorter.hasSpaceForAnotherRecord()); return; } // check if spilling is triggered or not if (inMemSorter.hasSpaceForAnotherRecord()) { freeArray(array); } else { inMemSorter.expandPointerArray(array); } } } /** * Allocates more memory in order to insert an additional record. This will request additional * memory from the memory manager and spill if the requested memory can not be obtained. * * @param required the required space in the data page, in bytes, including space for storing * the record size. This must be less than or equal to the page size (records * that exceed the page size are handled via a different code path which uses * special overflow pages). */ private void acquireNewPageIfNecessary(int required) { if (currentPage == null || pageCursor + required > currentPage.getBaseOffset() + currentPage.size() ) { // TODO: try to find space in previous pages currentPage = allocatePage(required); pageCursor = currentPage.getBaseOffset(); allocatedPages.add(currentPage); } } /** * Write a record to the shuffle sorter. */ public void insertRecord(Object recordBase, long recordOffset, int length, int partitionId) throws IOException { // for tests assert(inMemSorter != null); if (inMemSorter.numRecords() > numElementsForSpillThreshold) { spill(); } growPointerArrayIfNecessary(); // Need 4 bytes to store the record length. final int required = length + 4; /* 判断是否需要分配新的一页 */ acquireNewPageIfNecessary(required); assert(currentPage != null); final Object base = currentPage.getBaseObject(); final long recordAddress = taskMemoryManager.encodePageNumberAndOffset(currentPage, pageCursor); Platform.putInt(base, pageCursor, length); pageCursor += 4; Platform.copyMemory(recordBase, recordOffset, base, pageCursor, length); pageCursor += length; inMemSorter.insertRecord(recordAddress, partitionId); } /** * Close the sorter, causing any buffered data to be sorted and written out to disk. * * @return metadata for the spill files written by this sorter. If no records were ever inserted * into this sorter, then this will return an empty array. * @throws IOException */ public SpillInfo[] closeAndGetSpills() throws IOException { try { if (inMemSorter != null) { // Do not count the final file towards the spill count. writeSortedFile(true); freeMemory(); inMemSorter.free(); inMemSorter = null; } return spills.toArray(new SpillInfo[spills.size()]); } catch (IOException e) { cleanupResources(); throw e; } } }
<?php if( ! function_exists( 'cleverfox_gradiant_dynamic_styles' ) ): function cleverfox_gradiant_dynamic_styles() { $output_css = ''; /** * Logo Width */ $logo_width = get_theme_mod('logo_width','140'); if($logo_width !== '') { $output_css .=".logo img, .mobile-logo img { max-width: " .esc_attr($logo_width). "px; }\n"; } /** * Slider */ $slider_opacity = get_theme_mod('slider_opacity','0.6'); $output_css .=".theme-slider { background: rgba(0, 0, 0, $slider_opacity); }\n"; /** * CTA */ $cta_bg_setting = get_theme_mod('cta_bg_setting',esc_url(CLEVERFOX_PLUGIN_URL . 'inc/gradiant/images/slider/img01.jpg')); $cta_bg_position = get_theme_mod('cta_bg_position','scroll'); $output_css .=".cta-section { background-image: url(".esc_url($cta_bg_setting)."); background-attachment: " .esc_attr($cta_bg_position). "; }\n"; /** * Typography Body */ $gradiant_body_text_transform = get_theme_mod('gradiant_body_text_transform','inherit'); $gradiant_body_font_style = get_theme_mod('gradiant_body_font_style','inherit'); $gradiant_body_font_size = get_theme_mod('gradiant_body_font_size','15'); $gradiant_body_line_height = get_theme_mod('gradiant_body_line_height','1.5'); $output_css .=" body{ font-size: " .esc_attr($gradiant_body_font_size). "px; line-height: " .esc_attr($gradiant_body_line_height). "; text-transform: " .esc_attr($gradiant_body_text_transform). "; font-style: " .esc_attr($gradiant_body_font_style). "; }\n"; /** * Typography Heading */ for ( $i = 1; $i <= 6; $i++ ) { $gradiant_heading_text_transform = get_theme_mod('gradiant_h' . $i . '_text_transform','inherit'); $gradiant_heading_font_style = get_theme_mod('gradiant_h' . $i . '_font_style','inherit'); $gradiant_heading_font_size = get_theme_mod('gradiant_h' . $i . '_font_size'); $gradiant_heading_line_height = get_theme_mod('gradiant_h' . $i . '_line_height'); $output_css .=" h" . $i . "{ font-size: " .esc_attr($gradiant_heading_font_size). "px; line-height: " .esc_attr($gradiant_heading_line_height). "; text-transform: " .esc_attr($gradiant_heading_text_transform). "; font-style: " .esc_attr($gradiant_heading_font_style). "; }\n"; } wp_add_inline_style( 'gradiant-style', $output_css ); } endif; add_action( 'wp_enqueue_scripts', 'cleverfox_gradiant_dynamic_styles' ); ?>
import { Component, OnInit } from "@angular/core"; import { GroupService } from "src/app/services/group.service"; import { LocalStorageService } from "src/app/services/local-storage.service"; import { MatDialog } from '@angular/material/dialog'; import { CreateGroupDialogComponent } from "src/app/components/create-group-dialog/create-group-dialog.component"; import { JoinGroupDialogComponent } from "src/app/components/join-group-dialog/join-group-dialog.component"; import { MatSnackBar } from "@angular/material/snack-bar"; import { Router } from "@angular/router"; import { GroupWithUserCount } from "src/app/model/types/group-with-user-count"; import { TranslateService } from "@ngx-translate/core"; import { NavigationService } from "src/app/services/navigation.service"; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { groups: GroupWithUserCount[] = []; userId?: number; constructor( public dialog: MatDialog, private localStorageService: LocalStorageService, private groupService: GroupService, private snackBar: MatSnackBar, private router: Router, public translateService: TranslateService, private navigationService: NavigationService) {} ngOnInit(): void { this.navigationService.notifyAboutInitRoute('home'); const isAdmin = this.localStorageService.getIsAdmin(); if(isAdmin && isAdmin === 1) { this.router.navigate(['seasons']); } else { this.getGroupsForUser(); } } handleLeaveGroupClick(groupId: number): void { if(this.userId != null) { this.groupService.removeUserFromGroup(groupId, this.userId).subscribe((group) => { const groupIndex = this.groups.findIndex(mGroup => mGroup.id === group.id); if(groupIndex >= 0) { this.groups.splice(groupIndex, 1); const msg = this.translateService.instant('group.leftGroup', { groupName: group.name }); this.showSnackBar(msg); } }); } } openCreateGroupDialog(): void { const dialogRef = this.dialog.open(CreateGroupDialogComponent, { data: { userId: this.userId } }); dialogRef.afterClosed().subscribe((group: GroupWithUserCount) => { if(group) { this.groups.push(group); } }); } openJoinGroupDialog(): void { const dialogRef = this.dialog.open(JoinGroupDialogComponent, { data: { userId: this.userId } }); dialogRef.afterClosed().subscribe((group) => { if(group) { this.groups.push(group); } }); } private getGroupsForUser(): void { const userId = this.localStorageService.getUserId(); if(userId) { this.userId = userId; this.groupService.getGroupsForUser(userId).subscribe(groups => { this.groups = groups; }); } } private showSnackBar(msg: string): void { this.snackBar.open(msg, 'OK', { duration: 3000 }); } }
# Migración Para crear una migración nos movemos dentro de la carpeta del proyecto y ejecutamos el comando: ```php php artisan make:model Task -m ``` Esto automáticamente crea un fichero en la carpeta `database/migrations/<timestap>_create_tasks_table.php`. Dentro de este fichero php se define la estructura que va a tomar la tabla tarea en la base de datos. La del ejemplo queda de la siguiente forma: ```php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('tasks', function (Blueprint $table) { $table->id(); $table->string('name'); $table->boolean('completed')->default(false); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('tasks'); } }; ``` ### Explicación detallada Este código es una migración de Laravel escrita utilizando la sintaxis de migraciones anónimas introducida en Laravel 8. Explicaré cada parte del código detalladamente: 1. **Importaciones**: ```php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; ``` - `use Illuminate\Database\Migrations\Migration`: Esto importa la clase base `Migration` que proporciona Laravel para crear migraciones. Esta clase contiene los métodos necesarios para realizar y revertir migraciones. - `use Illuminate\Database\Schema\Blueprint`: Esto importa la clase `Blueprint`, que es utilizada para definir la estructura de una tabla en la base de datos. - `use Illuminate\Support\Facades\Schema`: Esto importa la fachada `Schema`, que proporciona una interfaz sencilla para interactuar con el sistema de migraciones. 2. **Creación de la Migración Anónima**: ```php return new class extends Migration { // ... }; ``` Esto define una nueva clase anónima que hereda de la clase `Migration`. En este caso, se está creando una migración anónima. Esta es una característica introducida en Laravel 8 que permite definir una migración dentro de un solo archivo PHP sin necesidad de crear un archivo separado. 3. **Método `up()`**: ```php public function up(): void { Schema::create('tasks', function (Blueprint $table) { $table->id(); $table->string('name'); $table->boolean('completed')->default(false); $table->timestamps(); }); } ``` - `up()`: Este es el método que se ejecuta cuando se aplica la migración. En este caso, se está creando una nueva tabla llamada `tasks` utilizando el objeto `Schema`. - `Schema::create('tasks', ...)`: Esto crea una nueva tabla llamada `tasks`. La función de callback toma un objeto `Blueprint` que te permite definir la estructura de la tabla. - `$table->id()`: Este método agrega un campo de tipo clave primaria `id` a la tabla. Es comúnmente utilizado para identificar de forma única cada fila en la tabla. - `$table->string('name')`: Este método agrega un campo de tipo cadena (`VARCHAR`) llamado `name`. - `$table->boolean('completed')->default(false)`: Este método agrega un campo de tipo booleano llamado `completed` con un valor predeterminado de `false`. - `$table->timestamps()`: Este método agrega dos campos `created_at` y `updated_at` que registran la fecha y hora de creación y actualización de cada registro en la tabla. Es una característica comúnmente utilizada para llevar un registro de la última vez que se modificó un registro. 4. **Método `down()`**: ```php public function down(): void { Schema::dropIfExists('tasks'); } ``` - `down()`: Este es el método que se ejecuta cuando se revierte la migración. En este caso, se está eliminando la tabla `tasks` utilizando el objeto `Schema`. - `Schema::dropIfExists('tasks')`: Esto elimina la tabla `tasks` si existe. Si la tabla no existe, no ocurre ningún error. En resumen, este código define una migración que crea una nueva tabla llamada `tasks` con tres campos (`id`, `name` y `completed`) y dos timestamps (`created_at` y `updated_at`). Si alguna vez necesitas revertir esta migración, se eliminará la tabla `tasks` de la base de datos. # Otros datos ### Blueprint Object En el contexto de Laravel y las migraciones de bases de datos, un "Blueprint" es una clase que proporciona una interfaz orientada a objetos para definir la estructura de una tabla de base de datos. La clase `Blueprint` se utiliza en las migraciones para especificar cómo se deben crear o modificar las tablas en la base de datos. Permite a los desarrolladores definir columnas, índices, claves foráneas y otras configuraciones de una manera programática y legible. Algunas de las acciones comunes que puedes realizar con un `Blueprint` incluyen: 1. **Agregar Columnas**: ```php $table->string('nombre'); ``` Esto agrega una columna de tipo string llamada "nombre" a la tabla. 2. **Definir Claves Primarias**: ```php $table->primary('id'); ``` Esto define la columna "id" como clave primaria. 3. **Agregar Índices**: ```php $table->index('email'); ``` Esto agrega un índice a la columna "email" para mejorar la eficiencia de las consultas. 4. **Definir Claves Foráneas**: ```php $table->foreign('user_id')->references('id')->on('users'); ``` Esto define una clave foránea llamada "user_id" que referencia la columna "id" en la tabla "users". 5. **Definir Columnas de Timestamps**: ```php $table->timestamps(); ``` Esto agrega dos columnas llamadas "created_at" y "updated_at" que registrarán la fecha y hora de creación y actualización de cada registro. 6. **Definir Columnas de Soft Deletes**: ```php $table->softDeletes(); ``` Esto agrega una columna "deleted_at" para implementar la eliminación suave (soft delete) en la tabla. El uso de un `Blueprint` hace que la definición de la estructura de la base de datos sea más legible y mantenible, especialmente en aplicaciones con bases de datos complejas o con múltiples desarrolladores que colaboran en el proyecto. En resumen, un `Blueprint` en Laravel proporciona una forma programática y orientada a objetos de definir la estructura de una tabla de base de datos, lo que facilita la gestión y mantenimiento de la base de datos en el contexto de las migraciones. ### Definición formal de migraciones En Laravel, una migración es una forma de interactuar con la base de datos utilizando código PHP en lugar de SQL directo. Proporciona una manera conveniente y controlada de modificar la estructura de la base de datos. En términos simples, una migración en Laravel es un archivo de PHP que contiene instrucciones para crear o modificar tablas y columnas en tu base de datos. Cada migración es una clase PHP que utiliza el sistema de migración de Laravel. Aquí hay una explicación más detallada: 1. **Definición**: Una migración en Laravel se define como una clase PHP que hereda de la clase `Migration`. Esta clase tiene dos métodos importantes: `up` y `down`. - `up`: Contiene las instrucciones para realizar la migración (por ejemplo, crear una nueva tabla, agregar una columna, etc.). - `down`: Contiene las instrucciones para deshacer la migración (es decir, revertir los cambios realizados en `up`). 2. **Uso**: Las migraciones se utilizan para mantener un control de la estructura de la base de datos a lo largo del tiempo, permitiendo a los desarrolladores trabajar de manera colaborativa y mantener un historial de los cambios en la base de datos. Por ejemplo, supongamos que estás trabajando en un equipo y necesitas agregar una nueva columna a una tabla existente en la base de datos. En lugar de instrucciones SQL directas, puedes crear una migración que contenga las instrucciones para agregar la nueva columna. Luego, puedes compartir la migración con tu equipo, y cada miembro puede aplicarla a su propia base de datos de desarrollo. Además, las migraciones facilitan la implementación y actualización de aplicaciones en diferentes entornos (como desarrollo, pruebas y producción), ya que puedes ejecutar las migraciones en cada entorno para asegurarte de que la base de datos esté configurada correctamente. También, las migraciones permiten realizar un seguimiento de los cambios en el esquema de la base de datos a lo largo del tiempo, lo que facilita la reversión a versiones anteriores si es necesario. En resumen, las migraciones en Laravel son una herramienta poderosa para gestionar la estructura de tu base de datos de una manera controlada y colaborativa, lo que facilita el desarrollo y mantenimiento de aplicaciones web.
// @testmode wasi import Int32 "mo:base/Int32"; import Order "mo:base/Order"; import Iter "mo:base/Iter"; import Suite "mo:matchers/Suite"; import T "mo:matchers/Testable"; import M "mo:matchers/Matchers"; let { run; test; suite } = Suite; let maximumInt32asInt = +2 ** 31 - 1 : Int; let maximumInt32asNat32 = 2 ** 31 - 1 : Nat32; let minimumInt32asInt = -2 ** 31 : Int; let maximumNat32 = 4_294_967_295 : Nat32; class Int32Testable(number : Int32) : T.TestableItem<Int32> { public let item = number; public func display(number : Int32) : Text { debug_show (number) }; public let equals = func(x : Int32, y : Int32) : Bool { x == y } }; class Nat32Testable(number : Nat32) : T.TestableItem<Nat32> { public let item = number; public func display(number : Nat32) : Text { debug_show (number) }; public let equals = func(x : Nat32, y : Nat32) : Bool { x == y } }; type Order = { #less; #equal; #greater }; class OrderTestable(value : Order) : T.TestableItem<Order> { public let item = value; public func display(value : Order) : Text { debug_show (value) }; public let equals = func(x : Order, y : Order) : Bool { x == y } }; /* --------------------------------------- */ run( suite( "constants", [ test( "minimum value", Int32.minimumValue, M.equals(Int32Testable(Int32.fromInt(-2 ** 31))) ), test( "maximum value", Int32.maximumValue, M.equals(Int32Testable(Int32.fromInt(+2 ** 31 - 1))) ), ] ) ); /* --------------------------------------- */ run( suite( "toInt", [ test( "maximum number", Int32.toInt(Int32.maximumValue), M.equals(T.int(maximumInt32asInt)) ), test( "minimum number", Int32.toInt(Int32.minimumValue), M.equals(T.int(minimumInt32asInt)) ), test( "one", Int32.toInt(1), M.equals(T.int(1)) ), test( "minus one", Int32.toInt(-1), M.equals(T.int(-1)) ), test( "zero", Int32.toInt(0), M.equals(T.int(0)) ) ] ) ); /* --------------------------------------- */ run( suite( "fromInt", [ test( "maximum number", Int32.fromInt(maximumInt32asInt), M.equals(Int32Testable(Int32.maximumValue)) ), test( "minimum number", Int32.fromInt(minimumInt32asInt), M.equals(Int32Testable(Int32.minimumValue)) ), test( "one", Int32.fromInt(1), M.equals(Int32Testable(1)) ), test( "minus one", Int32.fromInt(-1), M.equals(Int32Testable(-1)) ), test( "zero", Int32.fromInt(0), M.equals(Int32Testable(0)) ) ] ) ); /* --------------------------------------- */ run( suite( "fromIntWrap", [ test( "maximum number", Int32.fromIntWrap(maximumInt32asInt), M.equals(Int32Testable(Int32.maximumValue)) ), test( "minimum number", Int32.fromIntWrap(minimumInt32asInt), M.equals(Int32Testable(Int32.minimumValue)) ), test( "one", Int32.fromIntWrap(1), M.equals(Int32Testable(1)) ), test( "minus one", Int32.fromIntWrap(-1), M.equals(Int32Testable(-1)) ), test( "zero", Int32.fromIntWrap(0), M.equals(Int32Testable(0)) ), test( "overflow", Int32.fromIntWrap(maximumInt32asInt + 1), M.equals(Int32Testable(Int32.minimumValue)) ), test( "underflow", Int32.fromIntWrap(minimumInt32asInt - 1), M.equals(Int32Testable(Int32.maximumValue)) ) ] ) ); /* --------------------------------------- */ run( suite( "fromNat32", [ test( "maximum number", Int32.fromNat32(maximumInt32asNat32), M.equals(Int32Testable(Int32.maximumValue)) ), test( "one", Int32.fromNat32(1), M.equals(Int32Testable(1)) ), test( "zero", Int32.fromNat32(0), M.equals(Int32Testable(0)) ), test( "overflow", Int32.fromNat32(maximumInt32asNat32 + 1), M.equals(Int32Testable(Int32.minimumValue)) ) ] ) ); /* --------------------------------------- */ run( suite( "toNat32", [ test( "maximum number", Int32.toNat32(Int32.maximumValue), M.equals(Nat32Testable(maximumInt32asNat32)) ), test( "one", Int32.toNat32(1), M.equals(Nat32Testable(1)) ), test( "zero", Int32.toNat32(0), M.equals(Nat32Testable(0)) ), test( "underflow", Int32.toNat32(-1), M.equals(Nat32Testable(maximumNat32)) ) ] ) ); /* --------------------------------------- */ run( suite( "toText", [ test( "positive", Int32.toText(123456), M.equals(T.text("123456")) ), test( "negative", Int32.toText(-123456), M.equals(T.text("-123456")) ), test( "zero", Int32.toText(0), M.equals(T.text("0")) ), test( "maximum number", Int32.toText(Int32.maximumValue), M.equals(T.text("2147483647")) ), test( "minimum number", Int32.toText(Int32.minimumValue), M.equals(T.text("-2147483648")) ) ] ) ); /* --------------------------------------- */ run( suite( "abs", [ test( "positive number", Int32.abs(123), M.equals(Int32Testable(123)) ), test( "negative number", Int32.abs(-123), M.equals(Int32Testable(123)) ), test( "zero", Int32.abs(0), M.equals(Int32Testable(0)) ), test( "maximum number", Int32.abs(Int32.maximumValue), M.equals(Int32Testable(Int32.maximumValue)) ), test( "smallest possible", Int32.abs(-Int32.maximumValue), M.equals(Int32Testable(Int32.maximumValue)) ) ] ) ); /* --------------------------------------- */ run( suite( "min", [ test( "both positive", Int32.min(2, 3), M.equals(Int32Testable(2)) ), test( "positive, negative", Int32.min(2, -3), M.equals(Int32Testable(-3)) ), test( "both negative", Int32.min(-2, -3), M.equals(Int32Testable(-3)) ), test( "negative, positive", Int32.min(-2, 3), M.equals(Int32Testable(-2)) ), test( "equal values", Int32.min(123, 123), M.equals(Int32Testable(123)) ), test( "maximum and minimum number", Int32.min(Int32.maximumValue, Int32.minimumValue), M.equals(Int32Testable(Int32.minimumValue)) ) ] ) ); /* --------------------------------------- */ run( suite( "max", [ test( "both positive", Int32.max(2, 3), M.equals(Int32Testable(3)) ), test( "positive, negative", Int32.max(2, -3), M.equals(Int32Testable(2)) ), test( "both negative", Int32.max(-2, -3), M.equals(Int32Testable(-2)) ), test( "negative, positive", Int32.max(-2, 3), M.equals(Int32Testable(3)) ), test( "equal values", Int32.max(123, 123), M.equals(Int32Testable(123)) ), test( "maximum and minimum number", Int32.max(Int32.maximumValue, Int32.minimumValue), M.equals(Int32Testable(Int32.maximumValue)) ) ] ) ); /* --------------------------------------- */ run( suite( "equal", [ test( "positive equal", Int32.equal(123, 123), M.equals(T.bool(true)) ), test( "negative equal", Int32.equal(-123, -123), M.equals(T.bool(true)) ), test( "zero", Int32.equal(0, 0), M.equals(T.bool(true)) ), test( "positive not equal", Int32.equal(123, 124), M.equals(T.bool(false)) ), test( "negative not equal", Int32.equal(-123, -124), M.equals(T.bool(false)) ), test( "mixed signs", Int32.equal(123, -123), M.equals(T.bool(false)) ), test( "maxmimum equal", Int32.equal(Int32.maximumValue, Int32.maximumValue), M.equals(T.bool(true)) ), test( "minimum equal", Int32.equal(Int32.minimumValue, Int32.minimumValue), M.equals(T.bool(true)) ), test( "minimum and maximum", Int32.equal(Int32.minimumValue, Int32.maximumValue), M.equals(T.bool(false)) ) ] ) ); /* --------------------------------------- */ run( suite( "notEqual", [ test( "positive equal", Int32.notEqual(123, 123), M.equals(T.bool(false)) ), test( "negative equal", Int32.notEqual(-123, -123), M.equals(T.bool(false)) ), test( "zero", Int32.notEqual(0, 0), M.equals(T.bool(false)) ), test( "positive not equal", Int32.notEqual(123, 124), M.equals(T.bool(true)) ), test( "negative not equal", Int32.notEqual(-123, -124), M.equals(T.bool(true)) ), test( "mixed signs", Int32.notEqual(123, -123), M.equals(T.bool(true)) ), test( "maxmimum equal", Int32.notEqual(Int32.maximumValue, Int32.maximumValue), M.equals(T.bool(false)) ), test( "minimum equal", Int32.notEqual(Int32.minimumValue, Int32.minimumValue), M.equals(T.bool(false)) ), test( "minimum and maximum", Int32.notEqual(Int32.minimumValue, Int32.maximumValue), M.equals(T.bool(true)) ) ] ) ); /* --------------------------------------- */ run( suite( "less", [ test( "positive equal", Int32.less(123, 123), M.equals(T.bool(false)) ), test( "positive less", Int32.less(123, 245), M.equals(T.bool(true)) ), test( "positive greater", Int32.less(245, 123), M.equals(T.bool(false)) ), test( "negative equal", Int32.less(-123, -123), M.equals(T.bool(false)) ), test( "negative less", Int32.less(-245, -123), M.equals(T.bool(true)) ), test( "negative greater", Int32.less(-123, -245), M.equals(T.bool(false)) ), test( "zero", Int32.less(0, 0), M.equals(T.bool(false)) ), test( "mixed signs less", Int32.less(-123, 123), M.equals(T.bool(true)) ), test( "mixed signs greater", Int32.less(123, -123), M.equals(T.bool(false)) ), test( "minimum and maximum", Int32.less(Int32.minimumValue, Int32.maximumValue), M.equals(T.bool(true)) ), test( "maximum and minimum", Int32.less(Int32.maximumValue, Int32.minimumValue), M.equals(T.bool(false)) ), test( "maximum and maximum", Int32.less(Int32.maximumValue, Int32.maximumValue), M.equals(T.bool(false)) ), test( "minimum and minimum", Int32.less(Int32.minimumValue, Int32.minimumValue), M.equals(T.bool(false)) ) ] ) ); /* --------------------------------------- */ run( suite( "lessOrEqual", [ test( "positive equal", Int32.lessOrEqual(123, 123), M.equals(T.bool(true)) ), test( "positive less", Int32.lessOrEqual(123, 245), M.equals(T.bool(true)) ), test( "positive greater", Int32.lessOrEqual(245, 123), M.equals(T.bool(false)) ), test( "negative equal", Int32.lessOrEqual(-123, -123), M.equals(T.bool(true)) ), test( "negative less", Int32.lessOrEqual(-245, -123), M.equals(T.bool(true)) ), test( "negative greater", Int32.lessOrEqual(-123, -245), M.equals(T.bool(false)) ), test( "zero", Int32.lessOrEqual(0, 0), M.equals(T.bool(true)) ), test( "mixed signs less", Int32.lessOrEqual(-123, 123), M.equals(T.bool(true)) ), test( "mixed signs greater", Int32.lessOrEqual(123, -123), M.equals(T.bool(false)) ), test( "minimum and maximum", Int32.lessOrEqual(Int32.minimumValue, Int32.maximumValue), M.equals(T.bool(true)) ), test( "maximum and minimum", Int32.lessOrEqual(Int32.maximumValue, Int32.minimumValue), M.equals(T.bool(false)) ), test( "maximum and maximum", Int32.lessOrEqual(Int32.maximumValue, Int32.maximumValue), M.equals(T.bool(true)) ), test( "minimum and minimum", Int32.lessOrEqual(Int32.minimumValue, Int32.minimumValue), M.equals(T.bool(true)) ) ] ) ); /* --------------------------------------- */ run( suite( "greater", [ test( "positive equal", Int32.greater(123, 123), M.equals(T.bool(false)) ), test( "positive less", Int32.greater(123, 245), M.equals(T.bool(false)) ), test( "positive greater", Int32.greater(245, 123), M.equals(T.bool(true)) ), test( "negative equal", Int32.greater(-123, -123), M.equals(T.bool(false)) ), test( "negative less", Int32.greater(-245, -123), M.equals(T.bool(false)) ), test( "negative greater", Int32.greater(-123, -245), M.equals(T.bool(true)) ), test( "zero", Int32.greater(0, 0), M.equals(T.bool(false)) ), test( "mixed signs less", Int32.greater(-123, 123), M.equals(T.bool(false)) ), test( "mixed signs greater", Int32.greater(123, -123), M.equals(T.bool(true)) ), test( "minimum and maximum", Int32.greater(Int32.minimumValue, Int32.maximumValue), M.equals(T.bool(false)) ), test( "maximum and minimum", Int32.greater(Int32.maximumValue, Int32.minimumValue), M.equals(T.bool(true)) ), test( "maximum and maximum", Int32.greater(Int32.maximumValue, Int32.maximumValue), M.equals(T.bool(false)) ), test( "minimum and minimum", Int32.greater(Int32.minimumValue, Int32.minimumValue), M.equals(T.bool(false)) ) ] ) ); /* --------------------------------------- */ run( suite( "greaterOrEqual", [ test( "positive equal", Int32.greaterOrEqual(123, 123), M.equals(T.bool(true)) ), test( "positive less", Int32.greaterOrEqual(123, 245), M.equals(T.bool(false)) ), test( "positive greater", Int32.greaterOrEqual(245, 123), M.equals(T.bool(true)) ), test( "negative equal", Int32.greaterOrEqual(-123, -123), M.equals(T.bool(true)) ), test( "negative less", Int32.greaterOrEqual(-245, -123), M.equals(T.bool(false)) ), test( "negative greater", Int32.greaterOrEqual(-123, -245), M.equals(T.bool(true)) ), test( "zero", Int32.greaterOrEqual(0, 0), M.equals(T.bool(true)) ), test( "mixed signs less", Int32.greaterOrEqual(-123, 123), M.equals(T.bool(false)) ), test( "mixed signs greater", Int32.greaterOrEqual(123, -123), M.equals(T.bool(true)) ), test( "minimum and maximum", Int32.greaterOrEqual(Int32.minimumValue, Int32.maximumValue), M.equals(T.bool(false)) ), test( "maximum and minimum", Int32.greaterOrEqual(Int32.maximumValue, Int32.minimumValue), M.equals(T.bool(true)) ), test( "maximum and maximum", Int32.greaterOrEqual(Int32.maximumValue, Int32.maximumValue), M.equals(T.bool(true)) ), test( "minimum and minimum", Int32.greaterOrEqual(Int32.minimumValue, Int32.minimumValue), M.equals(T.bool(true)) ) ] ) ); /* --------------------------------------- */ run( suite( "compare", [ test( "positive equal", Int32.compare(123, 123), M.equals(OrderTestable(#equal)) ), test( "positive less", Int32.compare(123, 245), M.equals(OrderTestable(#less)) ), test( "positive greater", Int32.compare(245, 123), M.equals(OrderTestable(#greater)) ), test( "negative equal", Int32.compare(-123, -123), M.equals(OrderTestable(#equal)) ), test( "negative less", Int32.compare(-245, -123), M.equals(OrderTestable(#less)) ), test( "negative greater", Int32.compare(-123, -245), M.equals(OrderTestable(#greater)) ), test( "zero", Int32.compare(0, 0), M.equals(OrderTestable(#equal)) ), test( "mixed signs less", Int32.compare(-123, 123), M.equals(OrderTestable(#less)) ), test( "mixed signs greater", Int32.compare(123, -123), M.equals(OrderTestable(#greater)) ), test( "minimum and maximum", Int32.compare(Int32.minimumValue, Int32.maximumValue), M.equals(OrderTestable(#less)) ), test( "maximum and minimum", Int32.compare(Int32.maximumValue, Int32.minimumValue), M.equals(OrderTestable(#greater)) ), test( "maximum and maximum", Int32.compare(Int32.maximumValue, Int32.maximumValue), M.equals(OrderTestable(#equal)) ), test( "minimum and minimum", Int32.compare(Int32.minimumValue, Int32.minimumValue), M.equals(OrderTestable(#equal)) ) ] ) ); /* --------------------------------------- */ run( suite( "neg", [ test( "positive number", Int32.neg(123), M.equals(Int32Testable(-123)) ), test( "negative number", Int32.neg(-123), M.equals(Int32Testable(123)) ), test( "zero", Int32.neg(0), M.equals(Int32Testable(0)) ), test( "maximum number", Int32.neg(Int32.maximumValue), M.equals(Int32Testable(-Int32.maximumValue)) ), test( "smallest possible", Int32.neg(-Int32.maximumValue), M.equals(Int32Testable(Int32.maximumValue)) ) ] ) ); /* --------------------------------------- */ run( suite( "add", [ test( "positive", Int32.add(123, 123), M.equals(Int32Testable(246)) ), test( "negative", Int32.add(-123, -123), M.equals(Int32Testable(-246)) ), test( "mixed signs", Int32.add(-123, 223), M.equals(Int32Testable(100)) ), test( "zero", Int32.add(0, 0), M.equals(Int32Testable(0)) ), test( "minimum and maximum", Int32.add(Int32.minimumValue, Int32.maximumValue), M.equals(Int32Testable(-1)) ) ] ) ); /* --------------------------------------- */ run( suite( "sub", [ test( "positive", Int32.sub(123, 123), M.equals(Int32Testable(0)) ), test( "negative", Int32.sub(-123, -123), M.equals(Int32Testable(0)) ), test( "mixed signs", Int32.sub(-123, 223), M.equals(Int32Testable(-346)) ), test( "zero", Int32.sub(0, 0), M.equals(Int32Testable(0)) ), test( "maximum and maximum", Int32.sub(Int32.maximumValue, Int32.maximumValue), M.equals(Int32Testable(0)) ) ] ) ); /* --------------------------------------- */ run( suite( "mul", [ test( "positive", Int32.mul(123, 234), M.equals(Int32Testable(28782)) ), test( "negative", Int32.mul(-123, -234), M.equals(Int32Testable(28782)) ), test( "mixed signs", Int32.mul(-123, 234), M.equals(Int32Testable(-28782)) ), test( "zeros", Int32.mul(0, 0), M.equals(Int32Testable(0)) ), test( "zero and maximum", Int32.mul(0, Int32.maximumValue), M.equals(Int32Testable(0)) ), test( "minimum and zero", Int32.mul(Int32.minimumValue, 0), M.equals(Int32Testable(0)) ), test( "one and maximum", Int32.mul(1, Int32.maximumValue), M.equals(Int32Testable(Int32.maximumValue)) ), test( "minimum and one", Int32.mul(Int32.minimumValue, 1), M.equals(Int32Testable(Int32.minimumValue)) ) ] ) ); /* --------------------------------------- */ run( suite( "div", [ test( "positive multiple", Int32.div(156, 13), M.equals(Int32Testable(12)) ), test( "positive remainder", Int32.div(1234, 100), M.equals(Int32Testable(12)) ), test( "negative multiple", Int32.div(-156, -13), M.equals(Int32Testable(12)) ), test( "negative remainder", Int32.div(-1234, -100), M.equals(Int32Testable(12)) ), test( "mixed signs", Int32.div(-123, 23), M.equals(Int32Testable(-5)) ), test( "zero and number", Int32.div(0, -123), M.equals(Int32Testable(0)) ), test( "zero and maximum", Int32.div(0, Int32.maximumValue), M.equals(Int32Testable(0)) ), test( "zero and minimum", Int32.div(0, Int32.minimumValue), M.equals(Int32Testable(0)) ), test( "maximum and maximum", Int32.div(Int32.maximumValue, Int32.maximumValue), M.equals(Int32Testable(1)) ), test( "minimum and minimum", Int32.div(Int32.minimumValue, Int32.minimumValue), M.equals(Int32Testable(1)) ) ] ) ); /* --------------------------------------- */ run( suite( "rem", [ test( "positive multiple", Int32.rem(156, 13), M.equals(Int32Testable(0)) ), test( "positive/positive remainder", Int32.rem(1234, 100), M.equals(Int32Testable(34)) ), test( "positive/negative remainder", Int32.rem(1234, -100), M.equals(Int32Testable(34)) ), test( "negative multiple", Int32.rem(-156, -13), M.equals(Int32Testable(0)) ), test( "negative/positive remainder", Int32.rem(-1234, 100), M.equals(Int32Testable(-34)) ), test( "negative/negative remainder", Int32.rem(-1234, -100), M.equals(Int32Testable(-34)) ), test( "zero and maximum", Int32.rem(0, Int32.maximumValue), M.equals(Int32Testable(0)) ), test( "zero and minimum", Int32.rem(0, Int32.minimumValue), M.equals(Int32Testable(0)) ), test( "maximum and maximum", Int32.rem(Int32.maximumValue, Int32.maximumValue), M.equals(Int32Testable(0)) ), test( "minimum and minimum", Int32.rem(Int32.minimumValue, Int32.minimumValue), M.equals(Int32Testable(0)) ) ] ) ); /* --------------------------------------- */ run( suite( "pow", [ test( "positive base, positive exponent", Int32.pow(72, 3), M.equals(Int32Testable(373248)) ), test( "positive base, zero exponent", Int32.pow(72, 0), M.equals(Int32Testable(1)) ), test( "negative base, odd exponent", Int32.pow(-72, 3), M.equals(Int32Testable(-373248)) ), test( "negative base, even exponent", Int32.pow(-72, 2), M.equals(Int32Testable(5184)) ), test( "negative base, zero exponent", Int32.pow(-72, 0), M.equals(Int32Testable(1)) ), test( "maximum and zero", Int32.pow(Int32.maximumValue, 0), M.equals(Int32Testable(1)) ), test( "minimum and zero", Int32.pow(Int32.minimumValue, 0), M.equals(Int32Testable(1)) ), test( "plus one and maximum", Int32.pow(1, Int32.maximumValue), M.equals(Int32Testable(1)) ), test( "minus one and maximum", Int32.pow(-1, Int32.maximumValue), M.equals(Int32Testable(-1)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitnot", [ test( "zero", Int32.bitnot(0), M.equals(Int32Testable(-1)) ), test( "minus 1", Int32.bitnot(-1), M.equals(Int32Testable(0)) ), test( "maximum", Int32.bitnot(Int32.maximumValue), M.equals(Int32Testable(Int32.minimumValue)) ), test( "minimum", Int32.bitnot(Int32.minimumValue), M.equals(Int32Testable(Int32.maximumValue)) ), test( "arbitrary", Int32.bitnot(1234), M.equals(Int32Testable(-1235)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitand", [ test( "inverted", Int32.bitand(0xf0f0, 0x0f0f), M.equals(Int32Testable(0)) ), test( "overlap", Int32.bitand(0x0ff0, 0xffff), M.equals(Int32Testable(0xff0)) ), test( "arbitrary", Int32.bitand(0x1234_5678, 0x7654_3210), M.equals(Int32Testable(0x1214_1210)) ), test( "negative", Int32.bitand(-123, -123), M.equals(Int32Testable(-123)) ), test( "mixed signs", Int32.bitand(-256, 255), M.equals(Int32Testable(0)) ), test( "zero", Int32.bitand(0, 0), M.equals(Int32Testable(0)) ), test( "zero and maximum", Int32.bitand(0, Int32.maximumValue), M.equals(Int32Testable(0)) ), test( "minimum and zero", Int32.bitand(Int32.minimumValue, 0), M.equals(Int32Testable(0)) ), test( "minimum and maximum", Int32.bitand(Int32.minimumValue, Int32.maximumValue), M.equals(Int32Testable(0)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitor", [ test( "inverted", Int32.bitor(0xf0f0, 0x0f0f), M.equals(Int32Testable(0xffff)) ), test( "overlap", Int32.bitor(0x0ff0, 0xffff), M.equals(Int32Testable(0xffff)) ), test( "arbitrary", Int32.bitor(0x1234_5678, 0x7654_3210), M.equals(Int32Testable(0x7674_7678)) ), test( "negative", Int32.bitor(-123, -123), M.equals(Int32Testable(-123)) ), test( "mixed signs", Int32.bitor(-256, 255), M.equals(Int32Testable(-1)) ), test( "zero", Int32.bitor(0, 0), M.equals(Int32Testable(0)) ), test( "zero and maximum", Int32.bitor(0, Int32.maximumValue), M.equals(Int32Testable(Int32.maximumValue)) ), test( "minimum and zero", Int32.bitor(Int32.minimumValue, 0), M.equals(Int32Testable(Int32.minimumValue)) ), test( "minimum and maximum", Int32.bitor(Int32.minimumValue, Int32.maximumValue), M.equals(Int32Testable(-1)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitxor", [ test( "inverted", Int32.bitxor(0xf0f0, 0x0f0f), M.equals(Int32Testable(0xffff)) ), test( "overlap", Int32.bitxor(0x0ff0, 0xffff), M.equals(Int32Testable(0xf00f)) ), test( "arbitrary", Int32.bitxor(0x1234_5678, 0x7654_3210), M.equals(Int32Testable(0x6460_6468)) ), test( "negative", Int32.bitxor(-123, -123), M.equals(Int32Testable(0)) ), test( "mixed signs", Int32.bitxor(-256, 255), M.equals(Int32Testable(-1)) ), test( "zero", Int32.bitxor(0, 0), M.equals(Int32Testable(0)) ), test( "zero and maximum", Int32.bitxor(0, Int32.maximumValue), M.equals(Int32Testable(Int32.maximumValue)) ), test( "minimum and zero", Int32.bitxor(Int32.minimumValue, 0), M.equals(Int32Testable(Int32.minimumValue)) ), test( "minimum and maximum", Int32.bitxor(Int32.minimumValue, Int32.maximumValue), M.equals(Int32Testable(-1)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitshiftLeft", [ test( "positive number", Int32.bitshiftLeft(0xf0f0, 4), M.equals(Int32Testable(0xf_0f00)) ), test( "negative number", Int32.bitshiftLeft(-256, 4), M.equals(Int32Testable(-4096)) ), test( "arbitrary", Int32.bitshiftLeft(1234_5678, 7), M.equals(Int32Testable(1_580_246_784)) ), test( "zero shift", Int32.bitshiftLeft(1234, 0), M.equals(Int32Testable(1234)) ), test( "one maximum shift", Int32.bitshiftLeft(1, 31), M.equals(Int32Testable(Int32.minimumValue)) ), test( "minimum number", Int32.bitshiftLeft(-1, 31), M.equals(Int32Testable(Int32.minimumValue)) ), test( "discard overflow", Int32.bitshiftLeft(0x7fff_0000, 16), M.equals(Int32Testable(0)) ), test( "beyond bit length positive", Int32.bitshiftLeft(0x1234_5678, 64 + 7), M.equals(Int32Testable(Int32.bitshiftLeft(0x1234_5678, 7))) ), test( "beyond bit length negative", Int32.bitshiftLeft(-0x1234_5678, 32 + 7), M.equals(Int32Testable(Int32.bitshiftLeft(-0x1234_5678, 7))) ), test( "negative shift argument", Int32.bitshiftLeft(0x1234_5678, -7), M.equals(Int32Testable(Int32.bitshiftLeft(0x1234_5678, 32 - 7))) ) ] ) ); /* --------------------------------------- */ run( suite( "bitshiftRight", [ test( "positive number", Int32.bitshiftRight(0xf0f0, 4), M.equals(Int32Testable(0x0f0f)) ), test( "negative number", Int32.bitshiftRight(-256, 4), M.equals(Int32Testable(-16)) ), test( "arbitrary", Int32.bitshiftRight(1234_5678, 7), M.equals(Int32Testable(96_450)) ), test( "zero shift", Int32.bitshiftRight(1234, 0), M.equals(Int32Testable(1234)) ), test( "minus one maximum shift", Int32.bitshiftRight(-1, 31), M.equals(Int32Testable(-1)) ), test( "minimum number", Int32.bitshiftRight(Int32.minimumValue, 31), M.equals(Int32Testable(-1)) ), test( "discard underflow", Int32.bitshiftRight(0x0000_ffff, 16), M.equals(Int32Testable(0)) ), test( "beyond bit length positive", Int32.bitshiftRight(0x1234_5678, 64 + 7), M.equals(Int32Testable(Int32.bitshiftRight(0x1234_5678, 7))) ), test( "beyond bit length negative", Int32.bitshiftRight(-0x1234_5678, 32 + 7), M.equals(Int32Testable(Int32.bitshiftRight(-0x1234_5678, 7))) ), test( "negative shift argument", Int32.bitshiftRight(0x1234_5678, -7), M.equals(Int32Testable(Int32.bitshiftRight(0x1234_5678, 32 - 7))) ) ] ) ); /* --------------------------------------- */ run( suite( "bitrotLeft", [ test( "positive number non-overflow", Int32.bitrotLeft(0xf0f0, 4), M.equals(Int32Testable(0xf_0f00)) ), test( "positive number overflow", Int32.bitrotLeft(0x5600_1234, 8), M.equals(Int32Testable(0x12_3456)) ), test( "negative number", Int32.bitrotLeft(-256, 4), M.equals(Int32Testable(-4081)) ), test( "arbitrary", Int32.bitrotLeft(1_234_567_890, 7), M.equals(Int32Testable(-889_099_996)) ), test( "zero shift", Int32.bitrotLeft(1234, 0), M.equals(Int32Testable(1234)) ), test( "minus one maximum rotate", Int32.bitrotLeft(-1, 31), M.equals(Int32Testable(-1)) ), test( "maximum number", Int32.bitrotLeft(Int32.maximumValue, 1), M.equals(Int32Testable(-2)) ), test( "minimum number", Int32.bitrotLeft(1, 31), M.equals(Int32Testable(Int32.minimumValue)) ), test( "opposite rotation", Int32.bitrotLeft(256, -2), M.equals(Int32Testable(64)) ), test( "rotate beyond bit length", Int32.bitrotLeft(128, 34), M.equals(Int32Testable(512)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitrotRight", [ test( "positive number non-underflow", Int32.bitrotRight(0xf0f0, 4), M.equals(Int32Testable(0x0f0f)) ), test( "positive number underflow", Int32.bitrotRight(0x5600_1234, 8), M.equals(Int32Testable(0x3456_0012)) ), test( "negative number", Int32.bitrotRight(-256, 8), M.equals(Int32Testable(0x00ff_ffff)) ), test( "arbitrary", Int32.bitrotRight(1_234_567_890, 7), M.equals(Int32Testable(-1_533_858_811)) ), test( "zero shift", Int32.bitrotRight(1234, 0), M.equals(Int32Testable(1234)) ), test( "minus one maximum rotate", Int32.bitrotRight(-1, 31), M.equals(Int32Testable(-1)) ), test( "maximum number", Int32.bitrotRight(-2, 1), M.equals(Int32Testable(Int32.maximumValue)) ), test( "minimum number", Int32.bitrotRight(Int32.minimumValue, 31), M.equals(Int32Testable(1)) ), test( "opposite rotation", Int32.bitrotRight(256, -2), M.equals(Int32Testable(1024)) ), test( "rotate beyond bit length", Int32.bitrotRight(128, 34), M.equals(Int32Testable(32)) ) ] ) ); /* --------------------------------------- */ run( suite( "bittest", [ test( "set bit", Int32.bittest(128, 7), M.equals(T.bool(true)) ), test( "cleared bit", Int32.bittest(-129, 7), M.equals(T.bool(false)) ), test( "all zero", do { let number = 0 : Int32; var count = 0; for (index in Iter.range(0, 31)) { if (Int32.bittest(number, index)) { count += 1 } }; count }, M.equals(T.int(0)) ), test( "all one", do { let number = -1 : Int32; var count = 0; for (index in Iter.range(0, 31)) { if (Int32.bittest(number, index)) { count += 1 } }; count }, M.equals(T.int(32)) ), test( "set bit beyond bit length", Int32.bittest(128, 32 + 7), M.equals(T.bool(true)) ), test( "cleared bit beyond bit length", Int32.bittest(-129, 64 + 7), M.equals(T.bool(false)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitset", [ test( "set bit", Int32.bitset(0, 7), M.equals(Int32Testable(128)) ), test( "minus one", Int32.bitset(-129, 7), M.equals(Int32Testable(-1)) ), test( "no effect", Int32.bitset(128, 7), M.equals(Int32Testable(128)) ), test( "set all", do { var number = 0 : Int32; for (index in Iter.range(0, 31)) { number := Int32.bitset(number, index) }; number }, M.equals(Int32Testable(-1)) ), test( "all no effect", do { var number = -1 : Int32; for (index in Iter.range(0, 31)) { number := Int32.bitset(number, index) }; number }, M.equals(Int32Testable(-1)) ), test( "set bit beyond bit length", Int32.bitset(0, 32 + 7), M.equals(Int32Testable(128)) ), test( "minus one beyond bit length", Int32.bitset(-129, 64 + 7), M.equals(Int32Testable(-1)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitclear", [ test( "clear bit", Int32.bitclear(128, 7), M.equals(Int32Testable(0)) ), test( "minus one", Int32.bitclear(-1, 7), M.equals(Int32Testable(-129)) ), test( "no effect", Int32.bitclear(0, 7), M.equals(Int32Testable(0)) ), test( "clear all", do { var number = -1 : Int32; for (index in Iter.range(0, 31)) { number := Int32.bitclear(number, index) }; number }, M.equals(Int32Testable(0)) ), test( "all no effect", do { var number = 0 : Int32; for (index in Iter.range(0, 31)) { number := Int32.bitclear(number, index) }; number }, M.equals(Int32Testable(0)) ), test( "clear bit beyond bit length", Int32.bitclear(128, 32 + 7), M.equals(Int32Testable(0)) ), test( "minus one beyond bit length", Int32.bitclear(-1, 64 + 7), M.equals(Int32Testable(-129)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitflip", [ test( "clear bit", Int32.bitflip(255, 7), M.equals(Int32Testable(127)) ), test( "set bit", Int32.bitflip(127, 7), M.equals(Int32Testable(255)) ), test( "double flip", Int32.bitflip(Int32.bitflip(0x1234_5678, 13), 13), M.equals(Int32Testable(0x1234_5678)) ), test( "clear all", do { var number = -1 : Int32; for (index in Iter.range(0, 31)) { number := Int32.bitflip(number, index) }; number }, M.equals(Int32Testable(0)) ), test( "set all", do { var number = 0 : Int32; for (index in Iter.range(0, 31)) { number := Int32.bitflip(number, index) }; number }, M.equals(Int32Testable(-1)) ), test( "clear bit beyond bit length", Int32.bitflip(255, 32 + 7), M.equals(Int32Testable(127)) ), test( "set bit beyond bit length", Int32.bitflip(127, 64 + 7), M.equals(Int32Testable(255)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitcountNonZero", [ test( "zero", Int32.bitcountNonZero(0), M.equals(Int32Testable(0)) ), test( "minus one", Int32.bitcountNonZero(-1), M.equals(Int32Testable(32)) ), test( "minus two", Int32.bitcountNonZero(-2), M.equals(Int32Testable(31)) ), test( "one", Int32.bitcountNonZero(1), M.equals(Int32Testable(1)) ), test( "minimum value", Int32.bitcountNonZero(Int32.minimumValue), M.equals(Int32Testable(1)) ), test( "maximum value", Int32.bitcountNonZero(Int32.maximumValue), M.equals(Int32Testable(31)) ), test( "alternating bits positive", Int32.bitcountNonZero(0x5555_5555), M.equals(Int32Testable(16)) ), test( "alternating bits negative", Int32.bitcountNonZero(-0x5555_5556), M.equals(Int32Testable(16)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitcountLeadingZero", [ test( "zero", Int32.bitcountLeadingZero(0), M.equals(Int32Testable(32)) ), test( "minus one", Int32.bitcountLeadingZero(-1), M.equals(Int32Testable(0)) ), test( "minus two", Int32.bitcountLeadingZero(-2), M.equals(Int32Testable(0)) ), test( "one", Int32.bitcountLeadingZero(1), M.equals(Int32Testable(31)) ), test( "two", Int32.bitcountLeadingZero(2), M.equals(Int32Testable(30)) ), test( "arbitrary", Int32.bitcountLeadingZero(0x0000_1020), M.equals(Int32Testable(19)) ), test( "minimum value", Int32.bitcountLeadingZero(Int32.minimumValue), M.equals(Int32Testable(0)) ), test( "maximum value", Int32.bitcountLeadingZero(Int32.maximumValue), M.equals(Int32Testable(1)) ), test( "alternating bits positive", Int32.bitcountLeadingZero(0x5555_5555), M.equals(Int32Testable(1)) ), test( "alternating bits negative", Int32.bitcountLeadingZero(-0x5555_5556), M.equals(Int32Testable(0)) ) ] ) ); /* --------------------------------------- */ run( suite( "bitcountTrailingZero", [ test( "zero", Int32.bitcountTrailingZero(0), M.equals(Int32Testable(32)) ), test( "minus one", Int32.bitcountTrailingZero(-1), M.equals(Int32Testable(0)) ), test( "minus two", Int32.bitcountTrailingZero(-2), M.equals(Int32Testable(1)) ), test( "one", Int32.bitcountTrailingZero(1), M.equals(Int32Testable(0)) ), test( "two", Int32.bitcountTrailingZero(2), M.equals(Int32Testable(1)) ), test( "arbitrary", Int32.bitcountTrailingZero(0x5060_0000), M.equals(Int32Testable(21)) ), test( "minimum value", Int32.bitcountTrailingZero(Int32.minimumValue), M.equals(Int32Testable(31)) ), test( "maximum value", Int32.bitcountTrailingZero(Int32.maximumValue), M.equals(Int32Testable(0)) ), test( "alternating bits positive", Int32.bitcountTrailingZero(0x5555_5555), M.equals(Int32Testable(0)) ), test( "alternating bits negative", Int32.bitcountTrailingZero(-0x5555_5556), M.equals(Int32Testable(1)) ) ] ) ); /* --------------------------------------- */ run( suite( "addWrap", [ test( "positive", Int32.addWrap(123, 123), M.equals(Int32Testable(246)) ), test( "negative", Int32.addWrap(-123, -123), M.equals(Int32Testable(-246)) ), test( "mixed signs", Int32.addWrap(-123, 223), M.equals(Int32Testable(100)) ), test( "zero", Int32.addWrap(0, 0), M.equals(Int32Testable(0)) ), test( "minimum and maximum", Int32.addWrap(Int32.minimumValue, Int32.maximumValue), M.equals(Int32Testable(-1)) ), test( "small overflow", Int32.addWrap(Int32.maximumValue, 1), M.equals(Int32Testable(Int32.minimumValue)) ), test( "large overflow", Int32.addWrap(Int32.maximumValue, Int32.maximumValue), M.equals(Int32Testable(-2)) ), test( "small underflow", Int32.addWrap(Int32.minimumValue, -1), M.equals(Int32Testable(Int32.maximumValue)) ), test( "large underflow", Int32.addWrap(Int32.minimumValue, Int32.minimumValue), M.equals(Int32Testable(0)) ), ] ) ); /* --------------------------------------- */ run( suite( "subWrap", [ test( "positive", Int32.subWrap(123, 123), M.equals(Int32Testable(0)) ), test( "negative", Int32.subWrap(-123, -123), M.equals(Int32Testable(0)) ), test( "mixed signs", Int32.subWrap(-123, 223), M.equals(Int32Testable(-346)) ), test( "zero", Int32.subWrap(0, 0), M.equals(Int32Testable(0)) ), test( "maximum and maximum", Int32.subWrap(Int32.maximumValue, Int32.maximumValue), M.equals(Int32Testable(0)) ), test( "small overflow", Int32.subWrap(Int32.maximumValue, -1), M.equals(Int32Testable(Int32.minimumValue)) ), test( "large overflow", Int32.subWrap(Int32.maximumValue, Int32.minimumValue), M.equals(Int32Testable(-1)) ), test( "small underflow", Int32.subWrap(Int32.minimumValue, 1), M.equals(Int32Testable(Int32.maximumValue)) ), test( "large underflow", Int32.subWrap(Int32.minimumValue, Int32.maximumValue), M.equals(Int32Testable(1)) ), ] ) ); /* --------------------------------------- */ run( suite( "mulWrap", [ test( "positive", Int32.mulWrap(123, 234), M.equals(Int32Testable(28782)) ), test( "negative", Int32.mulWrap(-123, -234), M.equals(Int32Testable(28782)) ), test( "mixed signs", Int32.mulWrap(-123, 234), M.equals(Int32Testable(-28782)) ), test( "zeros", Int32.mulWrap(0, 0), M.equals(Int32Testable(0)) ), test( "zero and maximum", Int32.mulWrap(0, Int32.maximumValue), M.equals(Int32Testable(0)) ), test( "minimum and zero", Int32.mulWrap(Int32.minimumValue, 0), M.equals(Int32Testable(0)) ), test( "one and maximum", Int32.mulWrap(1, Int32.maximumValue), M.equals(Int32Testable(Int32.maximumValue)) ), test( "minimum and one", Int32.mulWrap(Int32.minimumValue, 1), M.equals(Int32Testable(Int32.minimumValue)) ), test( "small overflow", Int32.mulWrap(2, Int32.maximumValue), M.equals(Int32Testable(-2)) ), test( "large overflow", Int32.mulWrap(Int32.maximumValue, Int32.maximumValue), M.equals(Int32Testable(1)) ), test( "small underflow", Int32.mulWrap(Int32.minimumValue, 2), M.equals(Int32Testable(0)) ), test( "large underflow", Int32.mulWrap(Int32.minimumValue, Int32.minimumValue), M.equals(Int32Testable(0)) ), ] ) ); /* --------------------------------------- */ run( suite( "powWrap", [ test( "positive base, positive exponent", Int32.powWrap(72, 3), M.equals(Int32Testable(373248)) ), test( "positive base, zero exponent", Int32.powWrap(72, 0), M.equals(Int32Testable(1)) ), test( "negative base, positive exponent", Int32.powWrap(-72, 3), M.equals(Int32Testable(-373248)) ), test( "negative base, zero exponent", Int32.powWrap(-72, 0), M.equals(Int32Testable(1)) ), test( "maximum and zero", Int32.powWrap(Int32.maximumValue, 0), M.equals(Int32Testable(1)) ), test( "minimum and zero", Int32.powWrap(Int32.minimumValue, 0), M.equals(Int32Testable(1)) ), test( "plus one and maximum", Int32.powWrap(1, Int32.maximumValue), M.equals(Int32Testable(1)) ), test( "minus one and maximum", Int32.powWrap(-1, Int32.maximumValue), M.equals(Int32Testable(-1)) ), test( "minimum value", Int32.powWrap(-2, 31), M.equals(Int32Testable(Int32.minimumValue)) ), test( "small overflow", Int32.powWrap(2, 31), M.equals(Int32Testable(Int32.minimumValue)) ), test( "large overflow", Int32.powWrap(Int32.maximumValue, 10), M.equals(Int32Testable(1)) ), test( "small underflow", Int32.powWrap(-2, 33), M.equals(Int32Testable(0)) ), test( "large underflow", Int32.powWrap(Int32.minimumValue, 10), M.equals(Int32Testable(0)) ), ] ) )
{\rtf1\ansi\deff0\nouicompat{\fonttbl{\f0\fnil\fcharset0 Courier New;}} {\colortbl ;\red0\green0\blue255;} {\*\generator Riched20 10.0.16299}\viewkind4\uc1 \pard\f0\fs22\lang1033\par WELCOME TO DROIDS 1.20\par \par Our main goal is to try to visualize the impact of one of the longest time scale processes in the universe (i.e molecular evolution over 100s millions of years) on one of the shortest time scale processes (i.e. molecular motion over femtoseconds). To achieve this goal we use state-of-the-art biophysical simulations and graphics to design a gaming PC into a computational microscope that is capable seeing how mutations and other molecular events like binding, bending and bonding affect the functioning of proteins and nucleic acids. If you find this idea exciting, consider joining our coding efforts on GitHub. DROIDS-1.20 (Detecting Relative Outlier Impacts in molecular Dynamic Simulation) is a GUI-based pipeline that works with AMBER16, Chimera 1.11 and CPPTRAJ to analyze and visualize comparative protein dynamics on GPU accelerated Linux graphics workstations. DROIDS employs a statistical method (multiple test corrected KS tests on all backbone atoms of each amino acid) to detect significant changes in molecular dynamics simulated on two homologous PDB structures. Quantitative differences in atom fluctuation (i.e. calculated from vector trajectories) are displayed graphically and mapped onto movie images of the protein dynamics at the level of individual residues. P values indicating significant changes are also able to be similarly mapped. DROIDS is useful for examining how mutations, epigenetic changes, or binding interactions affect protein dynamics. DROIDS was produced by student effort at the Rochester Institute of Technology under the direction of Dr. Gregory A. Babbitt as a collaborative project between the Gosnell School of Life Sciences and the Biomedical Engineering Dept. Visit our lab website ({{\field{\*\fldinst{HYPERLINK https://people.rit.edu/gabsbi/ }}{\fldrslt{https://people.rit.edu/gabsbi/\ul0\cf0}}}}\f0\fs22 ) and download DROIDS 1.20 from Github at {{\field{\*\fldinst{HYPERLINK https://github.com/gbabbitt/DROIDS-1.0 }}{\fldrslt{https://github.com/gbabbitt/DROIDS-1.0\ul0\cf0}}}}\f0\fs22 . We will be posting video results periodically on our youtube channel at {{\field{\*\fldinst{HYPERLINK https://www.youtube.com/channel/UCJTBqGq01pBCMDQikn566Kw }}{\fldrslt{https://www.youtube.com/channel/UCJTBqGq01pBCMDQikn566Kw\ul0\cf0}}}}\f0\fs22 \par \par INSTALLATION INSTRUCTIONS FOR DROIDS v1.20\par \par DROIDS is primarily a backend statistical analysis and visualization tool for comparative protein dynamics. Some very fine tools already exist for running GPU accelerated molecular dynamic (MD) simulation, vector trajectory analysis, and visualizing structures. Our philosophy is not to reinvent these tools but rather to create a user friendly GUI-based pipeline to enable these tools to be used in concert to statistically compare the stability of motion on the polypeptide backbone for two homologous structures.\par \par DROIDS requires a Linux OS with one or two high end CUDA enabled GPU graphics cards installed. As of 2018, our preferred GPU is the GeForce GTX 1080 card with roughly 2500 cores. With two of these installed, most single chain protein comparisons can be run in 12-48 hours. For very small structures, the program 'sander' in Ambertools17 can be called in place of pmemd.cuda and run without needing GPUs or the Amber16 license. To enable this, the user can rewrite the following lines below in MD_proteinReference.pl, MD_proteinQuery.pl, MD_proteinReference_dualGPU.pl, MD_proteinQuery_dualGPU.pl replacing "pmemd.cuda_SPFP" with "sander". Given the efficiency of modern GPU acceleration for MD, this is not generally recommended. \par \par \par my $run_method = "pmemd1.cuda_SPFP"; # "sander" for CPU or "pmemd.cuda" for GPU;\par my $method_ID = "pmemd1";\par \par \par The primary software tools that must be installed on the Linux platform are\par \par Chimera 1.11 or later\par Amber16\par Ambertools17 (this will also give cpptraj)\par CUDA 8.0\par R-base language with the R packages 'ggplot2' and 'gridExtra'\par Perl 5.12 or later\par Python 2.7 or later (not python 3.0)\par perl-tk\par python-tk\par python-gi\par evince (a Linux pdf viewer)\par \par We highly recommend Linux Mint OS over Ubuntu as it provides more direct guidance via GUI for updating GPU graphics drivers when building the system. Generally, upon installation of the GPUs, the onboard graphics (on the motherboard) must be disabled via the BIOS or physical jumper and the monitor cable moved to the GPU card. In Linux Mint, the system will recommend driver updates upon rebooting via a pop-up GUI. In Ubuntu, the user usually needs to go to console (ctrl+alt+F1/F7), disable the x driver (e.g. sudo service lightdm stop/start), and install driver updates from the command line as root user. \par \par Once the GPU and graphics are properly configured, then the CUDA libraries must be installed (use CUDA 8.0 or higher)\par \par ...FIRST get some dependencies\par \par $ sudo apt-get install csh flex patch gfortran g++ make xorg-dev bison libbz2-dev \par \par \par ...TO INSTALL CUDA FROM LINUX CONSOLE\par \par ...PRE-INSTALLATION\par $ lspci | grep -i nvidia # check for GPU\par $ gcc --version # must be v4.9 or lower for AMBER14\par $ uname -r # check kernel \par $ sudo apt-get install linux-headers-$(uname -r) # to install kernel headers if needed (usually can skip this)\par \par ...INSTALLATION from CONSOLE (first go to NVIDIA and download CUDA 8.0 for Linux to your desktop)\par $ ctrl+alt+F1 then login\par $ cd Desktop\par $ sudo sh NVIDIA-Linux-x86_64-367.57.run # 1080 driver if needed...refuse generally\par $ sudo sh cuda_8.0.44_linux.run # CUDA plus drivers NOTE: do not install from terminal\par $ ctl ctrl+alt+F8\par # RUN deviceQuery in CUDA SAMPLES under UTILITIES\par \par ...POST INSTALLATION\par TO SET CUDA ENV in .bashrc file\par $ export CUDA_HOME=/usr/local/cuda-8.0\par $ export PATH=$CUDA_HOME/bin:/usr/local/cuda-8.0/bin:$PATH\par $ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$\{AMBERHOME\}/lib:$CUDA_HOME/lib64:$CUDA_H$\par \par ...CHECK YOUR GPU - here you should see your GPU hardware details\par $ nvidia-smi\par \par if you have problems at this point, double check to make sure you have all CUDA developer tools installed\par \par \par ################################################################################\par \par ...TO INSTALL AMBER16 and AMBERTOOLS17 (Amber16 must be purchased from \par \par ...quoting from the AMBER developers\par \par "The resulting file, "Amber16.tar.bz2" is about 62 Mbytes in size, and must be\par uncompressed with bunzip2, and extracted with "tar". On most systems, the\par command 'tar xvfj Amber16.tar.bz2' should work.\par \par [Specifically, the size of the file should be 62444314 bytes, and the\par md5sum should be 2d52556093a8c878b64f35b2ac2aae20.]\par \par Please note: you also need to download and extract AmberTools16 from this\par site:\par {{\field{\*\fldinst{HYPERLINK http://ambermd.org/AmberTools16-get.html }}{\fldrslt{http://ambermd.org/AmberTools16-get.html\ul0\cf0}}}}\f0\fs22\par \par Both Amber16 and AmberTools16 should be extracted into the same directory\par tree, whose head will be 'amber16'. [Please do *not* extract these files\par into an existing 'amber12' or 'amber14' directory.]\par \par If you have problems with the download itself, please send email to\par amber-license@biomaps.rutgers.edu. If you have questions or problems about\par installing or running the codes, please subscribe to the amber mailing list,\par as described at {{\field{\*\fldinst{HYPERLINK http://lists.ambermd.org/mailman/listinfo/amber }}{\fldrslt{http://lists.ambermd.org/mailman/listinfo/amber\ul0\cf0}}}}\f0\fs22 ."\par ###############################################################################\par \par ...FIRST CHECK for CUDA and C compilers\par $ nvcc -V \par $ gcc --version\par ...install compilers if necessary\par \par ...TO INSTALL AMBERTOOLS16/17\par $ cd Desktop\par $ tar jxvf AmberTools17.tar.bz2 # note: dont do this as root user\par $ cd amber16\par $ export AMBERHOME=`pwd`\par $ ./configure -noX11 gnu\par # We recommend you say "yes" when asked to apply updates\par $ source amber.sh # Use amber.csh if you use tcsh or csh\par $ make install\par $ echo "source $AMBERHOME/amber.sh" >> ~/.bashrc # Add Amber to your environment\par $ make test\par \par ...TO INSTALL AMBER16 # for pmemd.cuda\par $ cd Desktop\par $ tar jxvf Amber16.tar.bz2 # note dont untar, configure or install as root\par $ cd $AMBERHOME\par $ ./configure -cuda gnu\par $ make install\par $ make test\par \par IMPORTANT - IF YOU PLAN ON RUNNING DROIDS ON 2 GPUs.\par Go to the Amber16/bin file and copy the pmemd.cuda file twice and rename these files\par \par pmemd0.cuda\par pmemd1.cuda\par \par NOTE: do not use SLI connection between cards. The script GUI_START_DROIDS_dualGPU.pl will send\par the protein query simulation to the CUDA device = 0 and the protein reference simulation to CUDA device = 1 \par \par \par \par \par NOW YOU MUST MAKE SURE YOUR ENVIRONMENT IS SET\par ...open .bashrc in gedit \par \par $gedit .bashrc\par \par ...at this point you should see a large text file with your initial boot up conditions\par you need to add the following lines below to the botton of the script and save and exit\par \par ...EXAMPLE .bashrc lines to add\par \par source /home/gabsbi/Desktop/amber16/amber.sh\par export AMBERHOME=/home/gabsbi/Desktop/amber16\par export PATH=$PATH:$AMBERHOME/bin\par \par export CUDA_HOME=/usr/local/cuda-8.0\par export PATH=$CUDA_HOME/bin:/usr/local/cuda-8.0/bin:$PATH\par export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$\{AMBERHOME\}/lib:$CUDA_HOME/lib64:$CUDA_H$\par \par \par \par ...Now CHECK system state GPU on 30 second loop\par $ nvidia-smi -l 30\par $ ctrl+C\par \par ...CHECK system processes\par $ top\par $ ctrl+C\par \par ...NOW INSTALL YOUR OTHER STUFF\par \par $ sudo apt-get install perl-tk\par $ sudo apt-get install python-tk\par $ sudo apt-get install python-gi\par $ sudo apt-get install krusader (optional - a useful file transfer GUI)\par $ sudo apt-get install evince\par \par ...download Chimera (Linux version) from the the current UCSF Chimera website\par $ cd Desktop\par $ sudo ./chimera-1.11-linux_x86_64.bin (make sure the permissions on this file are set to run it as executable after the download)\par also untar and install Komodo Edit 10 from ActiveState's website if you would like a nice free editor for opening scripts\par \par \par ...TO INSTALL R and R STUDIO \par \par $ sudo apt-get install r-base r-base-dev\par \par ...IF YOU LIKE Rstudio (optional)\par $ sudo apt-get install gdebi-core\par $ wget {{\field{\*\fldinst{HYPERLINK https://download1.rstudio.org/rstudio-0.99.896-amd64.deb }}{\fldrslt{https://download1.rstudio.org/rstudio-0.99.896-amd64.deb\ul0\cf0}}}}\f0\fs22\par $ sudo gdebi -n rstudio-0.99.896-amd64.deb\par $ rm rstudio-0.99.896-amd64.deb\par \par ...TO GET ggplot2 package\par \par ...open R on command line\par \par $ R\par \par ...then type \par \par >install.packages("ggplot2")\par \par ...and follow directions\par \par >install.packages("gridExtra")\par \par ...and follow directions\par \par NOTE: teLeap_proteinQuery and teLeap_proteinReference have hard coded paths to the forcefield libraries in Amber16 ($AMBERHOME). You will need to change these to match the path on your system. \par \par ########################################################\par ...TO START DROIDS from terminal (on single GPU)\par \par $ perl GUI_START_DROIDS.pl\par \par ...TO START DROIDS from terminal (on two GPU)\par \par $ perl GUI_START_DROIDSdual GPU.pl\par ########################################################\par \par \par }
using Microsoft.EntityFrameworkCore; using sultan.Domain.Models; namespace sultan.Service.Impls; public class BookService : IBookService { private static readonly Context Db = new Context(); /// <summary> /// Возвращает список всех книг из бд. /// </summary> /// <returns>Список книг.</returns> public override async Task<List<Books>> GetBookAsync() { var orderedBooks = from i in await Db.Books.ToListAsync() orderby i.Id select i; return new List<Books>(orderedBooks); } /// <summary> /// Добавляет начальные книги в бд. /// </summary> /// <returns>Список книг.</returns> public override async Task<List<Books>> FillLibrary() { List<Books> books = new List<Books> { new Books {Name = "Путь Абая", Author = "Мухтар Ауэзов", Presence = 3}, new Books {Name = "Бегущий за ветром", Author = "Халед Хоссейни", Presence = 4}, new Books {Name = "Раскол", Author = "Кристи Голден" , Presence = 1}, new Books {Name = "кровью и честью", Author = "Крис Мэтцен", Presence = 10}, new Books {Name = "Путешествие к центру Земли", Author = "Жюль Верн", Presence = 5}, new Books {Name = "Python для чайников", Author = "Мюллер", Presence = 7}, new Books {Name = "По ту сторону темного портала", Author = "Кристи Голден", Presence = 3}, new Books {Name = "Преступление и наказание", Author = "Достоевский", Presence = 5}, new Books {Name = "Богатый папа бедный папа", Author = "Роберт Кийосаки", Presence = 7}, new Books {Name = "Великий Гэтсби", Author = "Фрэнсис Скотт", Presence = 1}, new Books {Name = "7 навыков высокоэффективных людей", Author = "Стивен Кови", Presence = 10 }, new Books {Name = "Тысяча сияющих солнц", Author = "Халед Хоссейни", Presence = 4 } }; Db.Books.AddRange(books); await Db.SaveChangesAsync(); return await GetBookAsync(); } }
# frozen_string_literal: true module Langchain # Langchain::Message are the messages that are sent to LLM chat methods class Message attr_reader :role, :content, :tool_calls, :tool_call_id ROLES = %w[ system assistant user tool ].freeze # @param role [String] The role of the message # @param content [String] The content of the message # @param tool_calls [Array<Hash>] Tool calls to be made # @param tool_call_id [String] The ID of the tool call to be made def initialize(role:, content: nil, tool_calls: [], tool_call_id: nil) # TODO: Implement image_file: reference (https://platform.openai.com/docs/api-reference/messages/object#messages/object-content) raise ArgumentError, "Role must be one of #{ROLES.join(", ")}" unless ROLES.include?(role) raise ArgumentError, "Tool calls must be an array of hashes" unless tool_calls.is_a?(Array) && tool_calls.all? { |tool_call| tool_call.is_a?(Hash) } @role = role # Some Tools return content as a JSON hence `.to_s` @content = content.to_s @tool_calls = tool_calls @tool_call_id = tool_call_id end # Convert the message to an OpenAI API-compatible hash # # @return [Hash] The message as an OpenAI API-compatible hash def to_openai_format {}.tap do |h| h[:role] = role h[:content] = content if content # Content is nil for tool calls h[:tool_calls] = tool_calls if tool_calls.any? h[:tool_call_id] = tool_call_id if tool_call_id end end def assistant? role == "assistant" end def system? role == "system" end def user? role == "user" end def tool? role == "tool" end end end
= Device handling This document describes how the IEC or IEEE488 device handling is done. == Overview The Commodore computers use a standard protocol on either the serial IEC (C64, VIC20, ...) or the parallel IEEE488 (PET, CBM-II) busses. The protocol can handle devices on the bus using an address between 0 and 30. Typically these devices are used:: * 4-5 - printer and plotter * 8-11 - disk drives and hard disks Other devices known to exist for the IEC/IEEE488 bus are modems. This emulator currently simulates disk drives only, using the host filesystem as source for the files. It is planned to add a "true drive emulation" at least for the parallel IEEE488 disk drives. In the emulator, two ways are used to talk to the devices: Traps:: In the ROM certain addresses are marked and the emulator traps out into native code when the emulated CPU tries to execute code on these addresses. This way the emulator can emulate the communication with the devices in native code. For this, the traps are located e.g. when the CPU tries to send bytes under ATN, and interprets the bytes appropriately to forward the data to the correct emulated device. This is mainly used for the serial IEC bus on the C64 emulation. Direct:: In this mode the bus hardware lines are emulated as a shared bus between the emulated CPU (e.g. a PET), and either virtual drives that listen on the bus or true disk emulation drives that listen to the bus as well. This does away with the traps, and is thus a much less intrusive emulation mode. This is mainly used for the IEEE488 bus on the PET emulation. == Code Structure The following diagram shows how the code parts play together. ---- C64 emu traps -> c64/iec64.c -+-> devices.c -+-> vdrive.c ^ | | +-> (other simulated devices, TODO) PET PIA/VIA IO -> parallel.c -+ | V +-> (true emulated devices, TODO) ---- In the C64, c64/iec64.c traps the kernal, and forwards the requests to the devices layer. This dispatches it to the virtual (simulated) disk drives (or, at some point in the future, other devices). The PET uses standard I/O from its PIA and VIA chips to handle IEEE488 lines in the parallel.c code. This interprets the IEEE488 commands and hooks into the devices code to forward when a virtual device is accessed. At some point in the future, other true emulated devices may listen on the same IEEE488 signal lines and handle them themselves.
import _ from "lodash"; import { useEffect, useRef, useState } from "react"; import DrinkList from "./components/DrinkList"; import Header from "./components/Header"; import IngredientsList from "./components/IngredientsList"; import InputIngredient from "./components/InputIngredient"; const fetchDrink = async (name: string) => { const API = "https://www.thecocktaildb.com/api/json/v1/1/filter.php?i="; const response = await fetch(API + name); const data = await response.json(); const drinks = data.drinks; const drinksWithIngredients = await Promise.all( _.map(drinks, async (drink: any) => { const ingredientsResponse = await fetchIngredients(drink.idDrink); const ingredients = ingredientsResponse.drinks[0]; return { ...drink, ingredients }; }) ); return drinksWithIngredients; }; async function fetchIngredients(drinkId: string) { const response = await fetch( `https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${drinkId}` ); const data = await response.json(); return data; } const App = () => { const [ingredients, setIngredients] = useState<Ingredient[]>([]); const [drinkLists, setDrinkLists] = useState<any[]>([]); const [errorMessage, setErrorMessage] = useState<string | null>(null); const clearErrorMessage = () => { setErrorMessage(null); }; useEffect(() => { const timeOut = setTimeout(() => { clearErrorMessage(); }, 3000); return () => clearTimeout(timeOut); }, [errorMessage]); const drinksRef = useRef<null | HTMLDivElement>(null); const ingredientsRef = useRef<null | HTMLDivElement>(null); useEffect(() => { const visibleIngredients = ingredients.filter((ingredient) => { if (ingredient.isVisible) { return ingredient; } }); let allDrinks: any = []; visibleIngredients.forEach((ingredient) => { allDrinks.push(...ingredient.drinks); }); allDrinks = _.uniqBy(allDrinks, "idDrink"); allDrinks = _.sortBy(allDrinks, (drink) => { let count = 0; Object.keys(drink.ingredients).forEach((key) => { if (key.startsWith("strIngredient") && drink.ingredients[key]) { const hasIngredient = visibleIngredients.find((ingredient) => { if ( ingredient.name.toLowerCase() === drink.ingredients[key].toLowerCase() ) { if (ingredient.isVisible) { return 1; } return 2; } }); if (hasIngredient) { count++; } } }); return count; }).reverse(); setDrinkLists(allDrinks); }, [ingredients]); const addIngredient = async (ingredient: string) => { ingredient = ingredient.charAt(0).toUpperCase() + ingredient.slice(1); try { const drinks = await fetchDrink(ingredient); setIngredients((prevState) => [ ...prevState, { name: ingredient, isVisible: true, id: crypto.randomUUID(), drinks }, ]); } catch (error) { setErrorMessage(`${ingredient} is not an ingredient!`); setTimeout(clearErrorMessage, 3000); } }; const toggleIngredientVisibility = (id: string) => { const foundIndexKey = _.findIndex(ingredients, { id: id }); const updatedIngredients = ingredients.map((ingredient, index) => { if (index === foundIndexKey) { return { name: ingredient.name, id: ingredient.id, isVisible: !ingredient.isVisible, drinks: ingredient.drinks, }; } return ingredient; }); setIngredients(updatedIngredients); }; const removeIngredient = (id: string) => { const foundIndexKey = _.findIndex(ingredients, { id: id }); const temp = [...ingredients]; const updatedIngredients = temp.filter((ingredient, index) => { if (index === foundIndexKey) { return; } return ingredient; }); setIngredients(updatedIngredients); }; const [currentPage, setCurrentPage] = useState<string>("ingredients"); const handleScroll = (e: React.UIEvent<HTMLDivElement>) => { if (e.currentTarget.scrollLeft < window.innerWidth / 2) { setCurrentPage("drinks"); } else { setCurrentPage("ingredients"); } }; useEffect(() => { ingredientsRef.current && ingredientsRef.current.scrollIntoView({ block: "start", }); }, []); return ( <div className="flex h-screen w-screen snap-x snap-mandatory flex-row gap-4 overflow-y-hidden overflow-x-scroll" onScroll={handleScroll} > <Header currentPage={currentPage} ingredientsScrollHandler={() => { ingredientsRef.current && ingredientsRef.current.scrollIntoView({ behavior: "smooth", block: "start", }); }} drinksScrollHandler={() => { drinksRef.current && drinksRef.current.scrollIntoView({ behavior: "smooth", block: "start", }); }} errorMessage={errorMessage} clearErrorMessage={clearErrorMessage} /> <div className="min-w-full snap-center md:w-2/3 md:min-w-0" ref={drinksRef} > <DrinkList drinkList={drinkLists} ingredients={ingredients} /> </div> <div className="flex min-w-full snap-center flex-col gap-8 overflow-y-scroll bg-zinc-50 px-4 pt-24 md:w-1/3 md:min-w-0 md:px-8 md:shadow-md" ref={ingredientsRef} > <InputIngredient onSubmit={addIngredient} minimumLength={2} maximumLength={20} setError={setErrorMessage} /> <IngredientsList ingredients={ingredients} toggleIngredientVisibility={toggleIngredientVisibility} removeIngredient={removeIngredient} /> </div> </div> ); }; export default App;
package com.ganak.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.ganak.R; import com.ganak.common.Common; import com.ganak.common.PrefManager; import com.ganak.model.ForgotPasswordResponse; import com.ganak.rest.API; import retrofit2.Call; import retrofit2.Response; public class OtpActivity extends AppCompatActivity { private Context mContext; private Button send_otp; private android.support.v7.app.ActionBar actionBar; private EditText etEmail; private PrefManager prefManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_otp); prefManager = new PrefManager(mContext); mContext = this; actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle("Forgot Password"); // send_otp = findViewById(R.id.btn_update_and_login); etEmail = findViewById(R.id.etEmail); etEmail.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (etEmail != null && !etEmail.equals("")) { if (Common.validateEmail(etEmail.getText().toString().trim())) { etEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_true_green, 0); } else { etEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_true_blue, 0); } } } }); send_otp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (checkValidation()) { if (Common.isConnectingToInternet(mContext)) { SendOtp(); } } } }); } private void SendOtp() { Common.showProgressDialog(mContext); API.user().getNewPassword(etEmail.getText().toString().trim()).enqueue(new retrofit2.Callback<ForgotPasswordResponse>() { @Override public void onResponse(Call<ForgotPasswordResponse> call, Response<ForgotPasswordResponse> response) { Common.errorLog("RegistrationResponse", response.toString() + "--"); ForgotPasswordResponse forgotPasswordResponse = response.body(); if (response.body().getErrorCode() == 200) { if (etEmail.getText().toString().trim().equals(prefManager.getUserEmail())) { Intent intent = new Intent(mContext, ForgotPasswordActivity.class); startActivity(intent); finish(); finishAffinity(); } else { Common.showToast(mContext, "Please Enter Correct Email Address"); } } else { if (forgotPasswordResponse.getError() != null && !forgotPasswordResponse.getError().equals("")) { Common.showToast(mContext, forgotPasswordResponse.getError() + ""); } } Common.dismissDialog(); } @Override public void onFailure(Call<ForgotPasswordResponse> call, Throwable t) { Common.dismissDialog(); Common.showToast(mContext, "Please try again later!!"); } }); } private boolean checkValidation() { if (!Common.isNotNullEditTextBox(etEmail)) { etEmail.requestFocus(); Common.showToast(mContext, "Please Enter Email"); return false; } return true; } }
import 'react-native-gesture-handler'; import { StatusBar } from 'expo-status-bar'; import React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import Homepage from './Home'; import { Platform } from 'react-native'; import { useFonts } from 'expo-font'; import { AppLoading } from 'expo'; import Header from './Header'; const Stack = createStackNavigator(); export default function App() { let [fontsLoaded] = useFonts({ 'OpenSans': require('./assets/fonts/OpenSans-Regular.ttf'), }); if(!fontsLoaded) { return <AppLoading />; } else { return ( <NavigationContainer style={{paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight: 0}} > <Stack.Navigator initialRouteName="Globomantics" headerMode="screen" > <Stack.Screen name="Globomantics" component={Homepage} options={{ header: () => <Header headerDisplay="Globomantics" /> }} /> </Stack.Navigator> </NavigationContainer> ); } }
<p> </p> <div class="warning"> <p>Support for extensions using XUL/XPCOM or the Add-on SDK was removed in Firefox 57, released November 2017. As there is no supported version of Firefox enabling these technologies, this page will be removed by December 2020.</p> <p>Add-ons using the techniques described in this document are considered a legacy technology in Firefox. Don't use these techniques to develop new add-ons. Use <a href="/en-US/Add-ons/WebExtensions">WebExtensions</a> instead. If you maintain an add-on which uses the techniques described here, consider migrating it to use WebExtensions.</p> <p><strong>Starting from <a href="https://wiki.mozilla.org/RapidRelease/Calendar">Firefox 53</a>, no new legacy add-ons will be accepted on addons.mozilla.org (AMO) for desktop Firefox and Firefox for Android.</strong></p> <p><strong>Starting from <a href="https://wiki.mozilla.org/RapidRelease/Calendar">Firefox 57</a>, only extensions developed using WebExtensions APIs will be supported on Desktop Firefox and Firefox for Android. </strong></p> <p>Even before Firefox 57, changes coming up in the Firefox platform will break many legacy extensions. These changes include multiprocess Firefox (e10s), sandboxing, and multiple content processes. Legacy extensions that are affected by these changes should migrate to use WebExtensions APIs if they can. See the <a href="https://blog.mozilla.org/addons/2017/02/16/the-road-to-firefox-57-compatibility-milestones/">"Compatibility Milestones" document</a> for more information.</p> <p>A wiki page containing <a href="https://wiki.mozilla.org/Add-ons/developer/communication">resources, migration paths, office hours, and more</a>, is available to help developers transition to the new technologies.</p> </div> <section class="Quick_links" id="Quick_Links"> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions"><strong>Browser extensions</strong></a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#Getting_started">Getting started</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions">What are extensions?</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension">Your first extension</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_second_WebExtension">Your second extension</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension">Anatomy of an extension</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples">Example extensions</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/What_next_">What next?</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#Concepts">Concepts</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Using_the_JavaScript_APIs">Using the JavaScript APIs</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts">Content scripts</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns">Match patterns</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_files">Working with files</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization">Internationalization</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Security_best_practices">Security best practices</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy">Content Security Policy</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging">Native messaging</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#User_Interface">User interface</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface">User Interface</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_action">Toolbar button</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions">Address bar button</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars">Sidebars</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items">Context menu items</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages">Options page</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages">Extension pages</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Notifications">Notifications</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Omnibox">Address bar suggestions</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels">Developer tools panels</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#How_to">How to</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests">Intercept HTTP requests</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Modify_a_web_page">Modify a web page</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Safely_inserting_external_content_into_a_page">Insert external content</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar">Add a button to the toolbar</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Implement_a_settings_page">Implement a settings page</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_the_Tabs_API">Work with the Tabs API</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Bookmarks_API">Work with the Bookmarks API</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Cookies_API">Work with the Cookies API</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities">Work with contextual identities</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#Porting">Porting</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension">Porting a Google Chrome extension</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on">Porting a legacy Firefox extension</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Embedded_WebExtensions">Embedded WebExtensions</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Comparison_with_the_Add-on_SDK">Comparison with the Add-on SDK</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Comparison_with_XUL_XPCOM_extensions">Comparison with XUL/XPCOM extensions</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities">Chrome incompatibilities</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Differences_between_desktop_and_Android">Differences between desktop and Android</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#Firefox_workflow">Firefox workflow</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/User_experience_best_practices">User Experience</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Temporary_Installation_in_Firefox">Temporary Installation in Firefox</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Debugging">Debugging</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Testing_persistent_and_restart_features">Testing persistent and restart features</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Developing_WebExtensions_for_Firefox_for_Android">Developing for Firefox for Android</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext">Getting started with web-ext</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/web-ext_command_reference">web-ext command reference</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID">Extensions and the Add-on ID</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Request_the_right_permissions">Request the right permissions</a></li> </ol> </li> <li data-default-state="closed"><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API">JavaScript APIs</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs">Browser support for JavaScript APIs</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms">alarms</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/bookmarks">bookmarks</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction">browserAction</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserSettings">browserSettings</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browsingData">browsingData</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/clipboard">clipboard</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/commands">commands</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contentScripts">contentScripts</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contextualIdentities">contextualIdentities</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies">cookies</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.inspectedWindow">devtools.inspectedWindow</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.network">devtools.network</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.panels">devtools.panels</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns">dns</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads">downloads</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/events">events</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/extension">extension</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/extensionTypes">extensionTypes</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/find">find</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history">history</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n">i18n</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/identity">identity</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/idle">idle</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management">management</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus">menus</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications">notifications</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/omnibox">omnibox</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction">pageAction</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions">permissions</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pkcs11">pkcs11</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/privacy">privacy</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy">proxy</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime">runtime</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/search">search</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/sessions">sessions</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/sidebarAction">sidebarAction</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage">storage</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs">tabs</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/theme">theme</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/topSites">topSites</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/types">types</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation">webNavigation</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest">webRequest</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/windows">windows</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">Manifest keys</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/applications">applications</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/author">author</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/background">background</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action">browser_action</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_settings_overrides">chrome_settings_overrides</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_url_overrides">chrome_url_overrides</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/commands">commands</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts">content_scripts</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy">content_security_policy</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/default_locale">default_locale</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/description">description</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/developer">developer</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page">devtools_page</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/homepage_url">homepage_url</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons">icons</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/incognito">incognito</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version">manifest_version</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name">name</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/omnibox">omnibox</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions">optional_permissions</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui">options_ui</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action">page_action</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">permissions</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/protocol_handlers">protocol_handlers</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/short_name">short_name</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action">sidebar_action</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme">theme</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version">version</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version_name">version_name</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources">web_accessible_resources</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/Themes"><strong>Themes</strong></a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Theme_concepts">Browser themes</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Theme_concepts">Browser theme concepts</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Lightweight_themes">Lightweight themes</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Lightweight_themes">Lightweight themes</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Lightweight_Themes/FAQ">Lightweight themes FAQ</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution"><strong>Publishing and Distribution</strong></a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution">Publishing add-ons</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution">Signing and distribution overview</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Package_your_extension_">Package your extension</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution/Submitting_an_add-on">Submit an add-on</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/Source_Code_Submission">Source code submission</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution/Resources_for_publishers">Resources for publishers</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/Listing">Creating an appealing listing</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/AMO/Policy/Reviews">Review policies</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/AMO/Policy/Agreement">Developer agreement</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/AMO/Policy/Featured">Featured add-ons</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution/Retiring_your_extension">Retiring your extension</a></li> </ol> </li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Alternative_distribution_options">Distributing add-ons</a> <ol> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Alternative_distribution_options/Sideloading_add-ons">For sideloading</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Alternative_distribution_options/Add-ons_for_desktop_apps">For desktop apps</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Alternative_distribution_options/Add-ons_in_the_enterprise">For an enterprise</a></li> </ol> </li> <li><a href="https://discourse.mozilla.org/c/add-ons"><strong>Community and Support</strong></a></li> <li><a href="#">Channels</a> <ol> <li><a href="https://blog.mozilla.org/addons">Add-ons blog</a></li> <li><a href="https://discourse.mozilla.org/c/add-ons">Add-on forums</a></li> <li><a href="http://stackoverflow.com/questions/tagged/firefox-addon">Stack Overflow</a></li> <li><a href="/en-US/docs/Mozilla/Add-ons/#Contact_us">Contact us</a></li> </ol> </li> </ol> </section> <p> </p> <p>A class is a blueprint from which individual objects are created. These individual objects are the instances of the class. Each class defines one or more members, which are initialized to a given value when the class is instantiated. Data members are properties that allow each instance to have their own state, whereas member functions are properties that allow instances to have behavior. Inheritance allows classes to inherit state and behavior from an existing classes, known as the base class. Unlike languages like C++ and Java, JavaScript does not have native support for classical inheritance. Instead, it uses something called prototypal inheritance. As it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code.</p> <p>Classes in JavaScript are defined using constructor functions. Each constructor function has an associated object, known as its prototype, which is shared between all instances of that class. We will show how to define classes using constructors, and how to use prototypes to efficiently define member functions on each instance. Classical inheritance can be implemented in JavaScript using constructors and prototypes. We will show how to make inheritance work correctly with respect to constructors, prototypes, and the instanceof operator, and how to override methods in subclasses. The SDK uses a special constructor internally, known as <code>Class</code>, to create constructors that behave properly with respect to inheritance. The last section shows how to work with the <code>Class</code> constructor. It is possible to read this section on its own. However, to fully appreciate how <code>Class</code> works, and the problem it is supposed to solve, it is recommended that you read the entire article.</p> <h2 id="Constructors">Constructors</h2> <p>Before the ECMASCript 6 standard, a JavaScript class was defined by creating a constructor function for that class. To illustrate this, let's define a simple constructor for a class <code>Shape</code>:</p> <pre><code>function Shape(x, y) { this.x = x; this.y = y; } </code></pre> <p>We can now use this constructor to create instances of <code>Shape</code>:</p> <pre><code>let shape = new Shape(2, 3); shape instanceof Shape; // =&gt; true shape.x; // =&gt; 2 shape.y; // =&gt; 3 </code></pre> <p>The keyword new tells JavaScript that we are performing a constructor call. Constructor calls differ from ordinary function calls in that JavaScript automatically creates a new object and binds it to the keyword this for the duration of the call. Moreover, if the constructor does not return a value, the result of the call defaults to the value of this. Constructors are just ordinary functions, however, so it is perfectly legal to perform ordinary function calls on them. In fact, some people (including the Add-on SDK team) prefer to use constructors this way. However, since the value of this is undefined for ordinary function calls, we need to add some boilerplate code to convert them to constructor calls:</p> <pre><code>function Shape(x, y) { if (!this) return new Shape(x, y); this.x = x; this.y = y; } </code></pre> <h2 id="Prototypes">Prototypes</h2> <p>Every object has an implicit property, known as its prototype. When JavaScript looks for a property, it first looks for it in the object itself. If it cannot find the property there, it looks for it in the object's prototype. If the property is found on the prototype, the lookup succeeds, and JavaScript pretends that it found the property on the original object. Every function has an explicit property, known as <code>prototype</code>. When a function is used in a constructor call, JavaScript makes the value of this property the prototype of the newly created object:</p> <pre><code>let shape = Shape(2, 3); Object.getPrototypeOf(shape) == Shape.prototype; // =&gt; true </code></pre> <p>All instances of a class have the same prototype. This makes the prototype the perfect place to define properties that are shared between instances of the class. To illustrate this, let's add a member function to the class <code>Shape</code>:</p> <pre><code>Shape.prototype.draw = function () { throw Error("not yet implemented"); } let shape = Shape(2, 3); Shape.draw(); // =&gt; Error: not yet implemented </code></pre> <h2 id="Inheritance_and_Constructors">Inheritance and Constructors</h2> <p>Suppose we want to create a new class, <code>Circle</code>, and inherit it from <code>Shape</code>. Since every <code>Circle</code> is also a <code>Shape</code>, the constructor for <code>Shape</code> must be called every time we call the constructor for <code>Circle</code>. Since JavaScript does not have native support for inheritance, it doesn't do this automatically. Instead, we need to call the constructor for <code>Shape</code> explicitly. The resulting constructor looks as follows:</p> <pre><code>function Circle(x, y, radius) { if (!this) return new Circle(x, y, radius); Shape.call(this, x, y); this.radius = radius; } </code></pre> <p>Note that the constructor for <code>Shape</code> is called as an ordinary function, and reuses the object created for the constructor call to <code>Circle</code>. Had we used a constructor call instead, the constructor for <code>Shape</code> would have been applied to a different object than the constructor for <code>Circle</code>. We can now use the above constructor to create instances of the class <code>Circle</code>:</p> <pre><code>let circle = Circle(2, 3, 5); circle instanceof Circle; // =&gt; true circle.x; // =&gt; 2 circle.y; // =&gt; 3 circle.radius; // =&gt; 5 </code></pre> <h2 id="Inheritance_and_Prototypes">Inheritance and Prototypes</h2> <p>There is a problem with the definition of <code>Circle</code> in the previous section that we have glossed over thus far. Consider the following:</p> <pre><code>let circle = Circle(2, 3, 5); circle.draw(); // =&gt; TypeError: circle.draw is not a function </code></pre> <p>This is not quite right. The method <code>draw</code> is defined on instances of <code>Shape</code>, so we definitely want it to be defined on instances of <code>Circle</code>. The problem is that <code>draw</code> is defined on the prototype of <code>Shape</code>, but not on the prototype of <code>Circle</code>. We could of course copy every property from the prototype of <code>Shape</code> over to the prototype of <code>Circle</code>, but this is needlessly inefficient. Instead, we use a clever trick, based on the observation that prototypes are ordinary objects. Since prototypes are objects, they have a prototype as well. We can thus override the prototype of <code>Circle</code> with an object which prototype is the prototype of <code>Shape</code>.</p> <pre><code>Circle.prototype = Object.create(Shape.prototype); </code></pre> <p>Now when JavaScript looks for the method draw on an instance of Circle, it first looks for it on the object itself. When it cannot find the property there, it looks for it on the prototype of <code>Circle</code>. When it cannot find the property there either, it looks for it on <code>Shape</code>, at which point the lookup succeeds. The resulting behavior is what we were aiming for.</p> <h2 id="Inheritance_and_Instanceof">Inheritance and Instanceof</h2> <p>The single line of code we added in the previous section solved the problem with prototypes, but introduced a new problem with the <strong>instanceof</strong> operator. Consider the following:</p> <pre><code>let circle = Circle(2, 3, 5); circle instanceof Shape; // =&gt; false </code></pre> <p>Since instances of <code>Circle</code> inherit from <code>Shape</code>, we definitely want the result of this expression to be true. To understand why it is not, we need to understand how <strong>instanceof</strong> works. Every prototype has a <code>constructor</code> property, which is a reference to the constructor for objects with this prototype. In other words:</p> <pre><code>Circle.prototype.constructor == Circle // =&gt; true </code></pre> <p>The <strong>instanceof</strong> operator compares the <code>constructor</code> property of the prototype of the left hand side with that of the right hand side, and returns true if they are equal. Otherwise, it repeats the comparison for the prototype of the right hand side, and so on, until either it returns <strong>true</strong>, or the prototype becomes <strong>null</strong>, in which case it returns <strong>false</strong>. The problem is that when we overrode the prototype of <code>Circle</code> with an object whose prototype is the prototype of <code>Shape</code>, we didn't correctly set its <code>constructor</code> property. This property is set automatically for the <code>prototype</code> property of a constructor, but not for objects created with <code>Object.create</code>. The <code>constructor</code> property is supposed to be non-configurable, non-enumberable, and non-writable, so the correct way to define it is as follows:</p> <pre><code>Circle.prototype = Object.create(Shape.prototype, { constructor: { value: Circle } }); </code></pre> <h2 id="Overriding_Methods">Overriding Methods</h2> <p>As a final example, we show how to override the stub implementation of the method <code>draw</code> in <code>Shape</code> with a more specialized one in <code>Circle</code>. Recall that JavaScript returns the first property it finds when walking the prototype chain of an object from the bottom up. Consequently, overriding a method is as simple as providing a new definition on the prototype of the subclass:</p> <pre><code>Circle.prototype.draw = function (ctx) { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); ctx.fill(); }; </code></pre> <p>With this definition in place, we get:</p> <pre><code>let shape = Shape(2, 3); shape.draw(); // Error: not yet implemented let circle = Circle(2, 3, 5); circle.draw(); // TypeError: ctx is not defined </code></pre> <p>which is the behavior we were aiming for.</p> <h2 id="Classes_in_the_Add-on_SDK">Classes in the Add-on SDK</h2> <p>We have shown how to emulate classical inheritance in JavaScript using constructors and prototypes. However, as we have seen, this takes a significant amount of boilerplate code. The Add-on SDK team consists of highly trained professionals, but they are also lazy: that is why the SDK contains a helper function that handles this boilerplate code for us. It is defined in the module “core/heritage”:</p> <pre><code>const { Class } = require('sdk/core/heritage'); </code></pre> <p>The function <code>Class</code> is a meta-constructor: it creates constructors that behave properly with respect to inheritance. It takes a single argument, which is an object which properties will be defined on the prototype of the resulting constructor. The semantics of <code>Class</code> are based on what we've learned earlier. For instance, to define a constructor for a class <code>Shape</code> in terms of <code>Class</code>, we can write:</p> <pre><code>let Shape = Class({ initialize: function (x, y) { this.x = x; this.y = y; }, draw: function () { throw new Error("not yet implemented"); } }); </code></pre> <p>The property <code>initialize</code> is special. When it is present, the call to the constructor is forwarded to it, as are any arguments passed to it (including the this object). In effect, initialize specifies the body of the constructor. Note that the constructors created with <code>Class</code> automatically check whether they are called as constructors, so an explicit check is no longer necessary.</p> <p>Another special property is <code>extends</code>. It specifies the base class from which this class inherits, if any. <code>Class</code> uses this information to automatically set up the prototype chain of the constructor. If the extends property is omitted, <code>Class</code> itself is used as the base class:</p> <pre><code>var shape = new Shape(2, 3); shape instanceof Shape; // =&gt; true shape instanceof Class; // =&gt; true </code></pre> <p>To illustrate the use of the <code>extends</code> property, let's redefine the constructor for the class <code>Circle</code> in terms of <code>Class</code>:</p> <pre><code>var Circle = Class({ extends: Shape, initialize: function(x, y, radius) { Shape.prototype.initialize.call(this, x, y); this.radius = radius; }, draw: function (<code>context</code>) { context.beginPath(); context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); context.fill(); } }); </code></pre> <p>Unlike the definition of <code>Circle</code> in the previous section, we no longer have to override its prototype, or set its <code>constructor</code> property. This is all handled automatically. On the other hand, the call to the constructor for <code>Shape</code> still has to be made explicitly. This is done by forwarding to the initialize method of the prototype of the base class. Note that this is always safe, even if there is no <code>initialize</code> method defined on the base class: in that case the call is forwarded to a stub implementation defined on <code>Class</code> itself.</p> <p>The last special property we will look into is <code>implements</code>. It specifies a list of objects, which properties are to be copied to the prototype of the constructor. Note that only properties defined on the object itself are copied: properties defined on one of its prototypes are not. This allows objects to inherit from more than one class. It is not true multiple inheritance, however: no constructors are called for objects inherited via <code>implements</code>, and <strong>instanceof</strong> only works correctly for classes inherited via <code>extends</code>.</p>
int numberOfApples = 12; decimal pricePerApple = 0.35M; Console.WriteLine( "{0} apples cost {1:C}", arg0: numberOfApples, arg1: pricePerApple * numberOfApples); string formatted = string.Format( "{0} apples cost {1:C}", arg0: numberOfApples, arg1: pricePerApple * numberOfApples); //WriteToFile(formatted); // Writes the string into a file. // Three parameter values can use named arguments. WriteLine("{0} {1} lived in {2}.", arg0: "Roger", arg1: "Cevung", arg2: "Stockholm"); // Four or more parameter values cannot use named arguments. WriteLine("{0} {1} lived in {2} and worked in the {3} team at {4}.", "Roger", "Cevung", "Stockholm", "Education", "Optimizely"); // The following statement must be all on one line when using C# 10 // or earlier. If using C# 11 or later, we can include a line break // in the middle of an expression but not in the string text. WriteLine($"{numberOfApples} apples cost {pricePerApple * numberOfApples:C}"); string applesText = "Apples"; int applesCount = 1234; string bananasText = "Bananas"; int bananasCount = 56789; WriteLine(); WriteLine("{0,-10} {1,6}", arg0: "Name", arg1: "Count"); WriteLine("{0,-10} {1,6:N0}", arg0: applesText, arg1: applesCount); WriteLine("{0,-10} {1,6:N0}", arg0: bananasText, arg1: bananasCount); Write("Type your first name and press ENTER: "); string? firstName = ReadLine(); Write("Type your age and press ENTER: "); string age = ReadLine()!; WriteLine($"Hello {firstName}, you look good for {age}."); Write("Press any key combination: "); ConsoleKeyInfo key = ReadKey(); WriteLine(); WriteLine("Key: {0}, Char: {1}, Modifiers: {2}", arg0: key.Key, arg1: key.KeyChar, arg2: key.Modifiers);
package Bulls_and_Cows_299; import java.util.*; public class Solution { public static String getHint(String secret, String guess) { HashMap<Character, Integer> h = new HashMap(); for (char s : secret.toCharArray()) { h.put(s, h.getOrDefault(s, 0) + 1); } int bulls = 0, cows = 0; int n = guess.length(); for (int idx = 0; idx < n; ++idx) { char ch = guess.charAt(idx); if (h.containsKey(ch)) { // corresponding characters match if (ch == secret.charAt(idx)) { // update the bulls bulls++; // update the cows // if all ch characters from secret // were used up if (h.get(ch) <= 0) cows--; // corresponding characters don't match } else { // update the cows if (h.get(ch) > 0) cows++; } // ch character was used h.put(ch, h.get(ch) - 1); } } return Integer.toString(bulls) + "A" + Integer.toString(cows) + "B"; } public static void main(String[] args) { String secret = "1807"; String guess = "7810"; System.out.println(getHint(secret, guess)); } }
//jshint esversion:6 require("dotenv").config(); const express = require("express"); const bodyParser = require("body-parser"); const ejs = require("ejs"); const mongoose = require("mongoose") const encrypt = require("mongoose-encryption") const app = express(); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("public")); mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true}); const userSchema = new mongoose.Schema({ email:String, password:String }) userSchema.plugin(encrypt,{secret:process.env.SECRET,encryptedFields:["password"]}) const User = mongoose.model("User",userSchema) app.get("/",function(req,res){ res.render("home") }) app.get("/login",function(req,res){ res.render("login") }) app.get("/register",function(req,res){ res.render("register") }) app.post("/register",function(req,res){ const newUser = new User({ email:req.body.username, password:req.body.password }) newUser.save(function(err){ if (!err){ res.render("secrets") } }) }) app.post("/login",function(req,res){ const username = req.body.username; const password = req.body.password; User.findOne({email:username},function(err,foundUser){ if (!err){ if (foundUser){ if (foundUser.password === password){ res.render("secrets") } } } }) }) app.listen(3000, function() { console.log("Server started on port 3000"); });
import React from 'react'; import { useDispatch } from 'react-redux'; import { Link } from 'react-router-dom'; import Swal from 'sweetalert2'; import { startRegister } from '../../actions/auth'; import { useForm } from '../../hooks/useForm'; export const RegisterScreen = () => { const dispatch = useDispatch(); const [formValues, handleInputChange] = useForm({ name: '', email: '', password1: '', password2: '' }); const { name, email, password1, password2 } = formValues; const handleRegister = (e) => { e.preventDefault(); if (password1 !== password2) { return Swal.fire({ icon: 'info', title: 'Advertencia', text: 'Las contraseñas deben de ser iguales', }); } dispatch(startRegister(name, email, password1)) } return ( <div className="register-container"> <div className="col-md-6 col-lg-3"> <div className="card card-register mb-3"> <div className="card-header bg-white"> <h3 className="text-center mb-0">Crea tu cuenta</h3> </div> <div className="card-body"> <form onSubmit={handleRegister}> <div className="input-group mb-2"> <div className="input-group-prepend"> <div className="input-group-text"> <i className="fas fa-user"></i> </div> </div> <input type="text" name="name" className="form-control" placeholder="Nombre" onChange={handleInputChange} /> </div> <div className="input-group mb-2"> <div className="input-group-prepend"> <div className="input-group-text"> <i className="fas fa-envelope"></i> </div> </div> <input type="email" name="email" className="form-control" placeholder="nombre@gmail.com" onChange={handleInputChange} /> </div> <div className="input-group mb-2"> <div className="input-group-prepend"> <div className="input-group-text"> <i className="fas fa-lock"></i> </div> </div> <input type="password" name="password1" className="form-control" placeholder="Contraseña" onChange={handleInputChange} /> </div> <div className="input-group mb-2"> <div className="input-group-prepend"> <div className="input-group-text"> <i className="fas fa-lock"></i> </div> </div> <input type="password" name="password2" className="form-control" placeholder="Repita la contraseña" onChange={handleInputChange} /> </div> <div className="form-group"> <button type="submit" className="btn btn-primary btn-block mt-3" > Crear cuenta </button> </div> </form> <div> <span className="mr-2">¿Ya tienes cuenta?</span> <Link to="/login">Iniciar sesión</Link> </div> </div> </div> </div> </div> ) }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <input type="text" id="giNum" readonly><br> <input type="text" id="giName"><br> <textarea id="giDesc"></textarea><br> <div id="fileDiv" style="border:1px solid blue"> <!--<input type="file" id="file1"><input type="number" id="sort1" value="1"><button onclick="addFileInput(this)">+</button><br>--> </div> <button onclick="addGoodsInfo()">등록</button> <script> let goodsFiles; window.addEventListener('load', async function () { const res = await fetch('/goodsInfos/[[${param.giNum}]]'); const goodsInfo = await res.json(); goodsFiles = goodsInfo.goodsFiles; document.querySelector('#giNum').value = goodsInfo.giNum; document.querySelector('#giName').value = goodsInfo.giName; document.querySelector('#giDesc').value = goodsInfo.giDesc; for (let i = 0; i < goodsInfo.goodsFiles.length; i++) { const goodsFile = goodsInfo.goodsFiles[i]; const html = `<div id="fileDiv${i + 1}">` + `<img src="${goodsFile.gfiPath}" style="width:100px" id="img${i + 1}">` + `<input type="file" id="file${i + 1}" onchange="preview(this,'img${i + 1}', ${goodsFile.gfiNum})">` + `<button onclick="removeFileInput('fileDiv${i + 1}', ${goodsFile.gfiNum})">-</button>` + `</div>`; document.querySelector('#fileDiv').insertAdjacentHTML('beforeend', html); } }); //프리뷰 function preview(fileInput, imgId, gfiNum) { for (const goodsFile of goodsFiles) { if (gfiNum === goodsFile.gfiNum) { goodsFile.status = 'UPDATE'; break; } } document.querySelector(`#${imgId}`).src = URL.createObjectURL(fileInput.files[0]); } function addFileInput(button) { const files = document.querySelectorAll('input[type=file]'); const fileId = 'file' + (files.length + 1); const html = `<div id="fileDiv${files.length + 1}"><input type="file" id="${fileId}"><input type="number" id="sort${files.length + 1}" value="${files.length + 1}"><button onclick="removeFileInput('fileDiv${files.length + 1}')">-</button>${button.outerHTML}</div>`; button.remove(); document.querySelector('#fileDiv').insertAdjacentHTML('beforeend', html); } function removeFileInput(divId, gfiNum) { for (const goodsFile of goodsFiles) { if (gfiNum === goodsFile.gfiNum) { goodsFile.status = 'DELETE'; break; } } document.querySelector(`#${divId}`).remove(); } function addGoodsInfo() { const files = document.querySelectorAll('input[type=file]'); const sorts = document.querySelectorAll('input[id^=sort]'); const formData = new FormData(); formData.append('giName',document.querySelector('#giName').value); formData.append('giDesc',document.querySelector('#giDesc').value); //formData.append('giName', '홍게라면'); //formData.append('giDesc', '맛있다'); let i = 0; for (; i < files.length; i++) { if(files[i].files.length){ formData.append(`goodsFiles[${i}].file`, files[i].files[0]); } formData.append(`goodsFiles[${i}].gfiSort`, sorts[i].value); if(files[i].getAttribute('data-gfi-num')){ formData.append(`goodsFiles[${i}].status`,'UPDATE'); }else{ formData.append(`goodsFiles[${i}].status`, 'INSERT'); } } for(const goodsFile of goodsFiles){ if(goodsFile.status==='DELETE'){ formData.append(`goodsFiles[${i}].status`, 'DELETE'); formData.append(`goodsFiles[${i}].gfiNum`, `${goodsFile.gfiNum}`); formData.append(`goodsFiles[${i++}].gfiPath`, `${goodsFile.gfiPath}`); } } const xhr = new XMLHttpRequest(); xhr.open('POST', '/goods-infos'); xhr.onreadystatechange = function () { if (xhr.readyState === xhr.DONE) { if (xhr.status === 200) { alert(xhr.responseText); } } } xhr.send(formData); } </script> </body> </html>
<?php /** * baseinstall Theme Customizer * * @package baseinstall */ /** * Add postMessage support for site title and description for the Theme Customizer. * * @param WP_Customize_Manager $wp_customize Theme Customizer object. */ function baseinstall_customize_register( $wp_customize ) { $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; $wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage'; if ( isset( $wp_customize->selective_refresh ) ) { $wp_customize->selective_refresh->add_partial( 'blogname', array( 'selector' => '.site__title a', 'render_callback' => 'baseinstall_customize_partial_blogname', ) ); $wp_customize->selective_refresh->add_partial( 'blogdescription', array( 'selector' => '.site__description', 'render_callback' => 'baseinstall_customize_partial_blogdescription', ) ); } } add_action( 'customize_register', 'baseinstall_customize_register' ); /** * Render the site title for the selective refresh partial. * * @return void */ function baseinstall_customize_partial_blogname() { bloginfo( 'name' ); } /** * Render the site tagline for the selective refresh partial. * * @return void */ function baseinstall_customize_partial_blogdescription() { bloginfo( 'description' ); } /** * Binds JS handlers to make Theme Customizer preview reload changes asynchronously. */ function baseinstall_customize_preview_js() { wp_enqueue_script( 'baseinstall-customizer', get_template_directory_uri() . '/assets/vendor/js/customizer.js', array( 'customize-preview' ), _S_VERSION, true ); } add_action( 'customize_preview_init', 'baseinstall_customize_preview_js' );
import React, { useState, useEffect } from "react"; import { Paper } from "@mui/material"; import Box from "@mui/material/Box"; import Container from "@mui/material/Container"; import { styled } from "@mui/material/styles"; import { over } from "stompjs"; import SockJS from "sockjs-client"; import SideNavBarPatient from "../../components/SideNavBarPatient"; import ChatSidePanel from "./ChatSidePanel"; import ChatContent from "./ChatContent"; import SideNavBarDoctor from "../../components/SideNavBarDoctor"; import { getAllChats, getCurrentUser } from "../../services/ChatService"; // create object of stompClient var stompClient = null; const DrawerHeader = styled("div")(({ theme }) => ({ display: "flex", alignItems: "center", justifyContent: "flex-end", padding: theme.spacing(0, 1), ...theme.mixins.toolbar, })); export default function ChatRoot({ isPatient }) { // state which manages the all chats const [chats, setChats] = useState([]); // state which holds the username of the current user const [senderId, setSenderId] = useState(""); // state which manages the connection and receiver user information const [roomData, setRoomData] = useState({ connected: false, room: null, receiver: {}, }); // make a connection with web socket const connect = () => { let Sock = new SockJS("http://172.17.0.96:8080/ws"); stompClient = over(Sock); stompClient.connect({}, onConnected, onError); }; // if connection with web socket got successful const onConnected = () => { // make connected to true as connection is established setRoomData((prevRoomData) => ({ ...prevRoomData, connected: true })); // if username of the current user exist if (senderId) { // subscribe to common channel to listen for real time message stompClient.subscribe(`/user/${senderId}/private`, onPrivateMessage); console.log("connection is successful!!"); } }; // once message is broadcasted to common channel, fetch it and update the chats state const onPrivateMessage = (payload) => { const payloadData = JSON.parse(payload.body); setChats((prevChats) => [...prevChats, payloadData]); }; // if error while making connection with web socket const onError = (err) => { console.error(err); }; // get the username of the current user from the backend useEffect(() => { const initChat = async () => { try { const res = await getCurrentUser(); setSenderId(res.senderUsername); } catch (err) { console.error(err); } }; initChat(); }, []); // call method to make connection with websocket when username of the current user is fetched from the backend useEffect(() => { if (senderId) { connect(); } }, [senderId]); // if connection is successful and we have receiver user information fetch the previous chats of the between sender and receiver useEffect(() => { if (roomData.connected && senderId && roomData.receiver.username) { fetchAllChats(); } }, [roomData.connected, senderId, roomData.receiver.username]); // function to fetch the all chats from the backend between current username and receiver and update the chats state const fetchAllChats = async () => { try { const res = await getAllChats(roomData.receiver.username); setChats(res.chats); } catch (err) { console.error(err); } }; const handleSendMessage = (msg) => { if (stompClient && roomData.receiver.username) { // const currentDate = new Date(); // const currentTimestamp = currentDate.getTime(); const chatMessage = { senderId: senderId, receiverId: roomData.receiver.username, content: msg, // timestamp: currentTimestamp, }; setChats((prevChats) => [...prevChats, chatMessage]); stompClient.send('/app/chat/send', {}, JSON.stringify(chatMessage)); // fetchAllChats(); } }; return ( <Box sx={{ display: "flex" }}> {isPatient ? <SideNavBarPatient /> : <SideNavBarDoctor />} <Box component="main" sx={{ backgroundColor: (theme) => theme.palette.mode === "light" ? theme.palette.grey[100] : theme.palette.grey[900], flexGrow: 1, height: "100vh", overflow: "auto", }} > <DrawerHeader /> <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}> <Paper elevation={0} sx={{ display: "flex" }}> <ChatSidePanel roomData={roomData} setRoomData={setRoomData} /> <ChatContent roomData={roomData} handleSendMessage={handleSendMessage} chats={chats} senderId={senderId} /> </Paper> </Container> </Box> </Box> ); }
"""Pokemon Battle Simulator This module simulates a battle between two pokenon, given their names It uses flask to create a local server and routes localhost:5000/battle and localhost:5000/show_previous_battles It save all battle logs to a mysql database Functions: battle: routes localhost:5000/battle show_previous_battles store_battle_to_db """ from flask import Flask, request, jsonify import mysql.connector import copy import json from pokemon import Pokemon, connection_error, http_error app = Flask(__name__) # MySQL connection configuration db_config = { "host": "mysql_db", # Docker container name for mysql "user": "battle_user", "password": "battle_password", "database": "battle_db", } @app.route('/battle') def battle(): """Simulates the battle between two pokemon. routes localhost:5000/battle?<pokemon1>&<pokemon2> Pokemon attack in sequence. A pokemon wins if the other pokemon's hitpoint reach 0. After 6 turns (3 attacks from each pokemon) if no pokemon has reach 0 hitpoint, the pokemon with highest remaining hitpoints wins. Parameters: - pokemon1: Name of the first Pokemon in: path type:str required:true - pokemon2: Name of the second Pokemon in: path type:str required:true Responses: 200: Returns a json with the battle logs and the winner 400: Returns a json with bad request 404: Return a json being unable to find the pokemon in pokeapi """ try: # Get Pokemon names from URL parameters pokemon1_name = request.args.get('pokemon1') pokemon2_name = request.args.get('pokemon2') #Check if any of the pokemon names are None if not pokemon1_name or not pokemon2_name: raise ValueError("/battle requires two pokemon names") # Create Pokemon instances pokemon1 = Pokemon(pokemon1_name) pokemon2 = Pokemon(pokemon2_name) # Create a non memory shared instance if the two pokemons are the same if pokemon1_name == pokemon2_name: pokemon2 = copy.deepcopy(pokemon1) pokemon2.name = f'{pokemon2.name}2' except ValueError as e: return jsonify({"Error": str(e)}) , 400 except (connection_error, http_error) as e: return jsonify({"Error": str(e)}), 404 # Perform battle simulation battle_log = [] attacker, defender = Pokemon.select_attacker_defender(pokemon1, pokemon2) attacker.current_hp = attacker.stats['hp'] defender.current_hp = defender.stats['hp'] for turn in range(6): attack_info = attacker.attack(defender) battle_log.append(attack_info) if defender.current_hp <= 0: winner = attacker.name break attacker, defender = defender, attacker # switch attacker and defender # If no pokemon won after 6 turns, check pokemon with highest hp wins if pokemon1.current_hp > pokemon2.current_hp: winner = f'{pokemon1.name} is the winner by having the highest remaining hp after 6 turns' elif pokemon2.current_hp > pokemon1.current_hp: winner = f'{pokemon2.name} is the winner by having the highest remaining hp after 6 turns' else: winner= "It's a draw" store_battle_to_db(winner, battle_log) battle_result = { "pokemon1": Pokemon.get_pokemon_info(pokemon1), "pokemon2": Pokemon.get_pokemon_info(pokemon2), "winner": winner, "battle_log": battle_log } # Return battle result as JSON response return jsonify(battle_result) @app.route('/show_previous_battles') def show_previous_battles(): """Access mysql database and shows all previous battles Returns: json: A json with all the database logs """ try: # Connect to the MySQL database conn = mysql.connector.connect(**db_config) cursor = conn.cursor() # Fetch data from the database cursor.execute("SELECT * FROM battles") data = cursor.fetchall() # Close the database connection cursor.close() conn.close() # Render the HTML template and pass the data return jsonify(data) except Exception as e: return f"An error occurred: {str(e)}" def store_battle_to_db(winner, battle_log): """Stores battle logs to mysql database Args: winner (str): name of the pokemon that won the battle battle_log (dict): battle log with all attacks made during the battle """ try: conn = mysql.connector.connect(**db_config) cursor = conn.cursor() # Assuming you have a table named "battles" cursor.execute( "INSERT INTO battles (winner, battle_log) VALUES (%s, %s)", (winner, json.dumps(battle_log)), ) conn.commit() cursor.close() conn.close() except Exception as e: raise ValueError("Could not store in database") from e if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=5000)
package factory; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import car.Car; import car.Lodgy; import resources.Color; import resources.Level; import resources.Type; @Component @Profile("lodgy") public class LodgyFactory implements Factory{ @Autowired private Level level; @Autowired private Color color; @Autowired public List<Car> cars; public void setColor(Color color) { this.color = color; } public void setLevel(Level level) { this.level = level; } public void produce(int n){ for (int i =0;i<n;i++){ cars.add(new Lodgy(level,color)); } } @Override public List<Car> getCars() { return cars; }; @Override public void setType(Type type) { System.out.println("Lodgy have only one type: VAN"); }; }
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%> <%@ taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt"%> <!DOCTYPE html> <html lang="en"> <head> <title>Index</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/png" href="Style/images/icons/favicon.ico"/> <link rel="stylesheet" type="text/css" href="Style/vendor/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="Style/fonts/font-awesome-4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="Style/vendor/animate/animate.css"> <link rel="stylesheet" type="text/css" href="Style/vendor/css-hamburgers/hamburgers.min.css"> <link rel="stylesheet" type="text/css" href="Style/vendor/select2/select2.min.css"> <link rel="stylesheet" type="text/css" href="Style/css/util.css"> <link rel="stylesheet" type="text/css" href="Style/css/main.css"> </head> <body> <div class="limiter"> <div class="container-login100"> <div class="col-12" style="justify-content: center; display: flex;"> <c:if test="${auth == 'false'}"> <div class="alert alert-warning col-6"> <strong>Warning!</strong> vous devez être connecté pour accéder à votre compte. </div> </c:if> <c:if test="${logout == 'true'}"> <div class="alert alert-success col-6"> <strong>Success!</strong> vous avez été déconnecté. </div> </c:if> <c:if test="${invalide == 'true'}"> <div class="alert alert-danger col-6"> <strong>Danger!</strong> Email ou mot de passe invalide. </div> </c:if> </div> <div class="wrap-login100"> <div class="login100-pic js-tilt" data-tilt> <img src="Style/images/img-03.png" alt="IMG"> </div> <form class="login100-form validate-form" method="POST" action="/ProjetFootNewsUser/login?auth=true"> <span class="login100-form-title"> Authentification </span> <div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex@abc.xyz"> <input class="input100" type="text" name="email" placeholder="Email"> <span class="focus-input100"></span> <span class="symbol-input100"> <i class="fa fa-envelope" aria-hidden="true"></i> </span> </div> <div class="wrap-input100 validate-input" data-validate = "Password is required"> <input class="input100" type="password" name="password" minlength="8" placeholder="Mot de passe"> <span class="focus-input100"></span> <span class="symbol-input100"> <i class="fa fa-lock" aria-hidden="true"></i> </span> </div> <div class="container-login100-form-btn"> <button class="login100-form-btn"> Connexion </button> </div> <br> <!-- <a href=""><center><b>Oublier le mot de passe ?</b></center></a> --> <br><br> </form> </div> </div> </div> <script src="Style/vendor/jquery/jquery-3.2.1.min.js"></script> <script src="Style/vendor/bootstrap/js/popper.js"></script> <script src="Style/vendor/bootstrap/js/bootstrap.min.js"></script> <script src="Style/vendor/select2/select2.min.js"></script> <script src="Style/vendor/tilt/tilt.jquery.min.js"></script> <script > $('.js-tilt').tilt({ scale: 1.1 }) </script> <script src="Style/js/main.js"></script> </body> </html>
from abc import ABC, abstractmethod from functools import wraps, partial from typing import Callable import gymnasium as gym import jax from chex import dataclass, PRNGKey, ArrayTree from reinforced_lib.utils.exceptions import UnimplementedSpaceError from reinforced_lib.utils import is_array, is_dict @dataclass class AgentState: """ Base class for agent state containers. """ class BaseAgent(ABC): """ Base interface of agents. """ @staticmethod @abstractmethod def init(key: PRNGKey, *args, **kwargs) -> AgentState: """ Creates and initializes instance of the agent. """ pass @staticmethod @abstractmethod def update(state: AgentState, key: PRNGKey, *args, **kwargs) -> AgentState: """ Updates the state of the agent after performing some action and receiving a reward. """ pass @staticmethod @abstractmethod def sample(state: AgentState, key: PRNGKey, *args, **kwargs) -> any: """ Selects the next action based on the current environment and agent state. """ pass @staticmethod def parameter_space() -> gym.spaces.Dict: """ Parameters of the agent constructor in Gymnasium format. Type of returned value is required to be ``gym.spaces.Dict`` or ``None``. If ``None``, the user must provide all parameters manually. """ return None @property def update_observation_space(self) -> gym.spaces.Space: """ Observation space of the ``update`` method in Gymnasium format. Allows to infer missing observations using an extensions and easily export the agent to TensorFlow Lite format. If ``None``, the user must provide all parameters manually. """ return None @property def sample_observation_space(self) -> gym.spaces.Space: """ Observation space of the ``sample`` method in Gymnasium format. Allows to infer missing observations using an extensions and easily export the agent to TensorFlow Lite format. If ``None``, the user must provide all parameters manually. """ return None @property def action_space(self) -> gym.spaces.Space: """ Action space of the agent in Gymnasium format. """ raise NotImplementedError() def export(self, init_key: PRNGKey, state: AgentState = None, sample_only: bool = False) -> tuple[any, any, any]: """ Exports the agent to TensorFlow Lite format. Parameters ---------- init_key : PRNGKey Key used to initialize the agent. state : AgentState, optional State of the agent to be exported. If not specified, the agent is initialized with ``init_key``. sample_only : bool, optional If ``True``, the exported agent will only be able to sample actions, but not update its state. """ try: import tensorflow as tf except ModuleNotFoundError: raise ModuleNotFoundError('TensorFlow installation is required to export agents to TensorFlow Lite.') @dataclass class TfLiteState: state: ArrayTree key: PRNGKey def append_value(value: any, value_name: str, args: any) -> any: if args is None: raise UnimplementedSpaceError() elif is_dict(args): return {value_name: value} | args elif is_array(args): return [value] + list(args) else: return [value, args] def flatten_args(tree_args_fun: Callable, treedef: ArrayTree) -> Callable: @wraps(tree_args_fun) def flat_args_fun(*leaves): tree_args = jax.tree_util.tree_unflatten(treedef, leaves) if is_dict(tree_args): tree_ret = tree_args_fun(**tree_args) else: tree_ret = tree_args_fun(*tree_args) return jax.tree_util.tree_leaves(tree_ret) return flat_args_fun def make_converter(fun: Callable, arguments: any) -> tf.lite.TFLiteConverter: leaves, treedef = jax.tree_util.tree_flatten(arguments) flat_fun = flatten_args(fun, treedef) inputs = [[(f'arg{i}', l) for i, l in enumerate(leaves)]] converter = tf.lite.TFLiteConverter.experimental_from_jax([flat_fun], inputs) converter.target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops. tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops. ] return converter def init() -> TfLiteState: return TfLiteState( state=self.init(init_key), key=init_key ) def sample(state: TfLiteState, *args, **kwargs) -> tuple[any, TfLiteState]: sample_key, key = jax.random.split(state.key) action = self.sample(state.state, sample_key, *args, **kwargs) return action, TfLiteState(state=state.state, key=key) def update(state: TfLiteState, *args, **kwargs) -> TfLiteState: update_key, key = jax.random.split(state.key) new_state = self.update(state.state, update_key, *args, **kwargs) return TfLiteState(state=new_state, key=key) def get_key() -> PRNGKey: return init_key def sample_without_state(state: AgentState, key: PRNGKey, *args, **kwargs) -> tuple[any, PRNGKey]: sample_key, key = jax.random.split(key) action = self.sample(state, sample_key, *args, **kwargs) return action, key if not sample_only: if state is None: state = init() else: state = TfLiteState(state=state, key=init_key) update_args = append_value(state, 'state', self.update_observation_space.sample()) sample_args = append_value(state, 'state', self.sample_observation_space.sample()) init_tfl = make_converter(init, []).convert() update_tfl = make_converter(update, update_args).convert() sample_tfl = make_converter(sample, sample_args).convert() return init_tfl, update_tfl, sample_tfl elif state is not None: sample_args = append_value(init_key, 'key', self.sample_observation_space.sample()) init_tfl = make_converter(get_key, []).convert() sample_tfl = make_converter(partial(sample_without_state, state), sample_args).convert() return init_tfl, None, sample_tfl else: raise ValueError('Either `state` must be provided or `sample_only` must be False.')
package com.itinerant.service; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Stack; import javax.persistence.EntityManager; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.itinerant.dao.ChatDAO; import com.itinerant.dao.ChatMensajeDAO; import com.itinerant.dao.UsuarioInternoDAO; import com.itinerant.entity.Alerta; import com.itinerant.entity.Chat; import com.itinerant.entity.ChatMensaje; import com.itinerant.entity.UsuarioInterno; import com.itinerant.enums.MessageStatus; import org.apache.commons.text.StringEscapeUtils; import org.json.JSONArray; import org.json.JSONObject; public class MensajeServicios { private ChatDAO chatDAO; private UsuarioInternoDAO usuarioInternoDAO; private HttpServletRequest request; private HttpServletResponse response; private ChatMensajeDAO chatMensajeDAO; public MensajeServicios(EntityManager entityManager, HttpServletRequest request, HttpServletResponse response) { chatDAO = new ChatDAO(entityManager); chatMensajeDAO = new ChatMensajeDAO(entityManager); usuarioInternoDAO = new UsuarioInternoDAO(entityManager); this.request = request; this.response = response; } public void inicializarMensajes(Integer idChat) { HashMap<Integer, List<ChatMensaje>> mensajesChat = (HashMap<Integer, List<ChatMensaje>>) request.getSession().getServletContext().getAttribute("mensajesChat"); List<ChatMensaje> mensajes; mensajes = mensajesChat.get(idChat); if(mensajes == null) { mensajes = new ArrayList<>(); List<ChatMensaje> mensajesBD = chatMensajeDAO.findAllByChatId(idChat); if(mensajesBD != null) { mensajes.addAll(mensajesBD); } } request.getSession().setAttribute("mensajes", mensajes); mensajesChat.put(idChat, mensajes); request.getSession().getServletContext().setAttribute("mensajesChat", mensajesChat); } public void getMensajes() throws IOException { String idChatText = request.getParameter("id"); if(idChatText != null && !idChatText.isBlank() && !idChatText.isEmpty()) { Integer idChat = Integer.parseInt(idChatText); HashMap<Integer, List<ChatMensaje>> mensajesChat = (HashMap<Integer, List<ChatMensaje>>) request.getSession().getServletContext().getAttribute("mensajesChat"); List<ChatMensaje> mensajes = mensajesChat.get(idChat); mensajesToJSON(mensajes, mensajesChat); } } private void mensajesToJSON(List<ChatMensaje> mensajes, HashMap<Integer, List<ChatMensaje>> mensajesChat) throws IOException { JSONArray jsArray = new JSONArray(); String login = (String) request.getSession().getAttribute("userLogin"); if(mensajes != null && mensajes.size() >0) { for(ChatMensaje mensaje: mensajes) { String senderId = mensaje.getUsuarioInternoByIdSender().getLogin(); JSONObject jobj = new JSONObject(); jobj.put("idChat", mensaje.getChat().getIdChat()); jobj.put("sender", senderId); jobj.put("recipient", mensaje.getUsuarioInternoByIdRecipient().getLogin()); jobj.put("cuerpo", mensaje.getCuerpo()); jobj.put("status", mensaje.getStatus().toString()); jobj.put("hora", mensaje.getHora()); jobj.toString(); jsArray.put(jobj); if(!senderId.equals(login) && !mensaje.getStatus().equals(MessageStatus.READ)) { mensaje.setStatus(MessageStatus.READ);; chatMensajeDAO.update(mensaje); actualizarMensajeEnLista(mensaje.getChat().getIdChat(), mensaje, mensajes, mensajesChat); } } } request.setAttribute("mensajes", mensajes); response.getWriter().write(jsArray.toString()); } public void actualizarMensajeEnLista(Integer chatId, ChatMensaje mensaje, List<ChatMensaje> mensajes, HashMap<Integer, List<ChatMensaje>> mensajesChat) { boolean encontrado = false; for(int i = 0; !encontrado && i < mensajes.size(); i++) { if(mensaje.getIdMensaje() == mensajes.get(i).getIdMensaje()) { encontrado = true; mensajes.set(i, mensaje); } } mensajesChat.put(chatId, mensajes); request.getSession().getServletContext().setAttribute("mensajesChat", mensajesChat); } public void sendMensaje() { String oricuerpoMensaje = request.getParameter("mensaje"); System.out.println(oricuerpoMensaje); String cuerpoMensaje = StringEscapeUtils.escapeHtml4(request.getParameter("mensaje")); System.out.println(cuerpoMensaje); if(!cuerpoMensaje.isBlank() && !cuerpoMensaje.isEmpty() && cuerpoMensaje != null) { Integer idChat = Integer.parseInt(request.getParameter("id")); Chat chat = chatDAO.get(idChat); //String recipientLogin = StringEscapeUtils.escapeHtml4(request.getParameter("usuario")); String recipientLogin = request.getParameter("usuario"); UsuarioInterno recipient = usuarioInternoDAO.get(recipientLogin); String senderLogin = (String) request.getSession().getAttribute("userLogin"); UsuarioInterno sender = usuarioInternoDAO.get(senderLogin); HashMap<Integer, List<ChatMensaje>> mensajesChat = (HashMap<Integer, List<ChatMensaje>>) request.getSession().getServletContext().getAttribute("mensajesChat"); List<ChatMensaje> mensajes; mensajes = mensajesChat.get(idChat); ChatMensaje mensaje = new ChatMensaje(chat, recipient, sender, cuerpoMensaje); chatMensajeDAO.create(mensaje); mensajes.add(mensaje); mensajesChat.put(idChat, mensajes); request.getSession().getServletContext().setAttribute("mensajesChat", mensajesChat); } } public int mensajesPendientes(Chat chat) { String login = (String) request.getSession().getAttribute("userLogin"); HashMap<Integer, List<ChatMensaje>> mensajesChat = (HashMap<Integer, List<ChatMensaje>>) request.getSession().getServletContext().getAttribute("mensajesChat"); List<ChatMensaje> mensajes = mensajesChat.get(chat.getIdChat()); int mensajes_pendientes = 0; if(mensajes != null && mensajes.size() >0) { for(ChatMensaje mensaje: mensajes) { if(login.equals(mensaje.getUsuarioInternoByIdRecipient().getLogin()) && !mensaje.getStatus().equals(MessageStatus.READ)) { mensajes_pendientes++; } } } return mensajes_pendientes; } public void getNumeroMensajes() throws IOException { String login = (String) request.getSession().getAttribute("userLogin"); HashMap<String, List<Chat>> chats = (HashMap<String, List<Chat>>) request.getSession().getServletContext().getAttribute("chats"); List<Chat> misChats = chats.get(login); int numeroMensajes = 0; if(misChats != null && misChats.size() > 0) { for(Chat chat : misChats) { numeroMensajes += mensajesPendientes(chat); } } JSONArray jsArray = new JSONArray(); JSONObject jobj = new JSONObject(); jobj.put("numeroMensajes", numeroMensajes); jobj.toString(); jsArray.put(jobj); response.getWriter().write(jsArray.toString()); } public int getNumeroMensajesChat(Chat chat) throws IOException { HashMap<Integer, List<ChatMensaje>> mensajesChat = (HashMap<Integer, List<ChatMensaje>>) request.getSession().getServletContext().getAttribute("mensajesChat"); List<ChatMensaje> mensajes = mensajesChat.get(chat.getIdChat()); return mensajes.size(); } }
import { Interval } from "../utils/Interval"; import Heap from 'collections/heap'; //http://www.collectionsjs.com const commonFreeTime = (schedules: Array<Array<Interval>>): Array<Interval> => { const commonIntervals: Array<Interval> = []; const combinedSchedules: Array<Interval> = schedules.reduce((previous: Array<Interval>, current: Array<Interval>): Array<Interval> => [...previous, ...current], []) combinedSchedules.sort((a, b) => a.start - b.start); let counter = 1; while (counter < combinedSchedules.length) { let previous = combinedSchedules[counter - 1]; let current = combinedSchedules[counter]; if (previous.end < current.start) { commonIntervals.push(new Interval(previous.end, current.start)); } counter++; } return commonIntervals; } type EmployeeSchedule = { interval: Interval, employeeNumber: number, currentInterval: number } class EmployeeInterval { interval: Interval; employeeIndex: number; intervalIndex: number; constructor(interval, employeeIndex, intervalIndex) { this.interval = interval; // interval representing employee's working hours // index of the list containing working hours of this employee this.employeeIndex = employeeIndex; this.intervalIndex = intervalIndex; // index of the interval in the employee list } } const commonFreeTimeUsingMinHeap = (schedules: Array<Array<Interval>>): Array<Interval> => { let n = schedules.length; const result: Array<Interval> = []; if (schedules === null || n === 0) { return result; } const minHeap = new Heap([], null, ((a: EmployeeInterval, b: EmployeeInterval) => b.interval.start - a.interval.start)); // insert the first interval of each employee to the queue for (let i = 0; i < n; i++) { minHeap.push(new EmployeeInterval(schedules[i][0], i, 0)); } let previousInterval = minHeap.peek().interval; while (minHeap.length > 0) { const queueTop = minHeap.pop(); // if previousInterval is not overlapping with the next interval, insert a free interval if (previousInterval.end < queueTop.interval.start) { result.push(new Interval(previousInterval.end, queueTop.interval.start)); previousInterval = queueTop.interval; } else { // overlapping intervals, update the previousInterval if needed if (previousInterval.end < queueTop.interval.end) { previousInterval = queueTop.interval; } } // if there are more intervals available for(the same employee, add their next interval const employeeSchedule = schedules[queueTop.employeeIndex]; if (employeeSchedule.length > queueTop.intervalIndex + 1) { minHeap.push(new EmployeeInterval( employeeSchedule[queueTop.intervalIndex + 1], queueTop.employeeIndex, queueTop.intervalIndex + 1, )); } } return result; }
import React, {useState} from "react"; type EnderecoTipo = { uf: string, setUf: React.Dispatch<React.SetStateAction<string>>, cidade: string, setCidade: React.Dispatch<React.SetStateAction<string>>, bairro: string, setBairro: React.Dispatch<React.SetStateAction<string>> rua: string, setRua: React.Dispatch<React.SetStateAction<string>>, cep: string, setCep: React.Dispatch<React.SetStateAction<string>>, } export const Contexto = React.createContext({} as EnderecoTipo) export default function ContextoProvider(props: React.PropsWithChildren) { const [uf, setUf] = useState("") const [cidade, setCidade] = useState("") const [bairro, setBairro] = useState("") const [rua, setRua] = useState("") const [cep, setCep] = useState("") return ( <Contexto.Provider value = {{ uf, setUf, cidade, setCidade, bairro, setBairro, rua, setRua, cep, setCep }}> {props.children} </Contexto.Provider> ) }
import type { Metadata } from "next"; import { Poppins } from "next/font/google"; import "./globals.css"; import { CartProvider } from "@/context/CartContext"; import Footer from "@/components/shared/Footer"; import Navbar from "@/components/shared/Navbar"; const poppins = Poppins({ subsets: ["latin"], display: "swap", variable: "--font-poppins", weight: ["300", "400", "500", "600", "700", "800", "900"], }); export const metadata: Metadata = { title: "Products List", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={poppins.className}> <Navbar /> <CartProvider>{children}</CartProvider> <Footer /> </body> </html> ); }
package main import ( "drexel.edu/voter-api/api" "fmt" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/recover" "github.com/redis/go-redis/v9" "log" "os" ) // Global variables to hold the command line flags to drive the voter CLI // application var ( redisAddr string listenAddr string ) func getEnvOrDefault(key, defaultValue string) string { value := os.Getenv(key) if value == "" { value = defaultValue } return value } func processEnvVars() { redisAddr = getEnvOrDefault("VOTER_API_REDIS_ADDR", "0.0.0.0:6379") listenAddr = getEnvOrDefault("VOTER_API_LISTEN_ADDR", "0.0.0.0:1080") } func addRoutes(app *fiber.App, apiHandler *api.VoterAPI) { //HTTP Standards for "REST" APIS //GET - Read/Query //POST - Create //PUT - Update //DELETE - Delete app.Get("/voters", apiHandler.GetAllVoters) app.Delete("/voters", apiHandler.DeleteAllVoters) app.Get("/voters/:id<int;min(0)>", apiHandler.GetVoter) app.Post("/voters/:id<int;min(0)>", apiHandler.AddVoter) app.Put("/voters/:id<int;min(0)>", apiHandler.UpdateVoter) app.Delete("/voters/:id<int;min(0)>", apiHandler.DeleteVoter) app.Get("/voters/:id<int;min(0)>/polls", apiHandler.GetVoterHistory) app.Get("/voters/:id<int;min(0)>/polls/:pollid<int;min(0)>", apiHandler.GetVoterHistoryPoll) app.Post("/voters/:id<int;min(0)>/polls/:pollid<int;min(0)>", apiHandler.AddVoterHistoryPoll) app.Put("/voters/:id<int;min(0)>/polls/:pollid<int;min(0)>", apiHandler.UpdateVoterHistoryPoll) app.Delete("/voters/:id<int;min(0)>/polls/:pollid<int;min(0)>", apiHandler.DeleteVoterHistoryPoll) app.Get("/voters/health", apiHandler.HealthCheck) } // main is the entry point for our voter API application. It processes // the command line flags and then uses the db package to perform the // requested operation func main() { processEnvVars() app := fiber.New() app.Use(cors.New()) app.Use(recover.New()) app.Use(logger.New()) log.Println("Connecting to Redis on ", redisAddr) redisClient := redis.NewClient(&redis.Options{ Addr: redisAddr, Password: "", DB: 0, }) apiHandler, err := api.New(redisClient) if err != nil { fmt.Println(err) os.Exit(1) } addRoutes(app, apiHandler) log.Println("Starting server on ", listenAddr) app.Listen(listenAddr) }
'use client'; import { Box, Button, Container, Grid, Stack, Typography, } from '@mui/material'; import Image from 'next/image'; import { useRouter } from 'next/navigation'; import { useState } from 'react'; import { FieldValues } from 'react-hook-form'; import { z } from 'zod'; import logo from '@/assets/logo3.png'; import ReuseableForm from '@/components/Forms/ReuseableForm'; import { zodResolver } from '@hookform/resolvers/zod'; import ReuseableInput from '@/components/Forms/ReuseableInput'; import Link from 'next/link'; import { userLogin } from '@/services/actions/userLogin'; import { toast } from 'sonner'; import { storeUserInfo } from '@/services/auth.services'; const validationSchemaForLogin = z.object({ email: z .string() .email({ message: 'Please Enter Your Valida Email Address'! }), password: z.string().min(6, ' Must be at least 6 characters '), }); const LoginPage = () => { const router = useRouter(); const [error, setError] = useState(''); const hanldeLoginSubmit = async (data: FieldValues) => { console.log(data); try { const res = await userLogin(data); if (res?.data?.accessToken) { toast.success(res?.message); storeUserInfo({ accessToken: res?.data?.accessToken }); // router.push('/'); } else { setError(res.message); } } catch (error) { console.log(error); } }; return ( <div className=" h-full w-screen bg-gradient-to-r from-violet-900 to-fuchsia-900 py-24"> <Container> <Stack sx={{ height: '100vh', alignItems: 'center', justifyContent: 'center', }} > <Box sx={{ maxWidth: 600, width: '100%', boxShadow: '0px 3px 1px -2px black,0px 2px 2px 0px rgba(62, 52, 25, 0.9),0px 1px 5px 0px rgba(74, 54, 49, 0.448)', borderRadius: 1, p: 4, textAlign: 'center', }} > <Stack sx={{ justifyContent: 'center', alignItems: 'center', }} > <Box> <Image src={logo} width={50} height={50} alt="logo" /> </Box> <Box> <Typography variant="h4" color={'white'} component="h1" fontWeight={600} > Lon-In Found Way </Typography> </Box> </Stack> {/* For Error Message show in Server */} <Box> {error && ( <Box> <Typography sx={{ color: 'red', textAlign: 'center' }}> {error} </Typography> </Box> )} </Box> <Box> <ReuseableForm onSubmit={hanldeLoginSubmit} resolver={zodResolver(validationSchemaForLogin)} defaultValues={{ email: '', password: '', }} > <Grid container spacing={2} my={1}> <Grid item md={6} xs={12}> <ReuseableInput name="email" fullWidth={true} label="Email" type="email" sx={{ color: 'white' }} /> </Grid> <Grid item md={6} xs={12}> <ReuseableInput name="password" fullWidth={true} label="Password" type="password" size="small" /> </Grid> </Grid> <Typography sx={{ marginBottom: '10px', }} textAlign="end" component="p" fontWeight={300} > <Link href="/"> <span className="text-blue-200"> Forget Password ?</span> </Link> </Typography> <Button sx={{ margin: '10px 0px', }} type="submit" fullWidth={true} > LogIn </Button> <Typography component="h6" color={'yellow'} fontWeight={300}> Don&apos;t have an account ? <Link className="text-blue-200" href="/register"> <span> Create Account</span> </Link> </Typography> </ReuseableForm> </Box> </Box> </Stack> </Container> </div> ); }; export default LoginPage;
package ru.kata.spring.boot_security.demo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import ru.kata.spring.boot_security.demo.service.UserService; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { private final UserService userService; private final SuccessUserHandler successUserHandler; private final String LOGIN = "/login"; @Autowired public SecurityConfig(UserService userService, SuccessUserHandler successUserHandler) { this.userService = userService; this.successUserHandler = successUserHandler; } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", LOGIN).permitAll() .antMatchers("/admin").access("hasAnyAuthority('ADMIN')") .anyRequest().authenticated() .and() .formLogin().loginPage(LOGIN) .loginProcessingUrl(LOGIN) .successHandler(successUserHandler) .failureUrl("/login?error") .and() .logout().logoutUrl("/logout").logoutSuccessUrl(LOGIN); } @Bean public DaoAuthenticationProvider daoAuthenticationProvider() { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setPasswordEncoder(getPasswordEncoder()); daoAuthenticationProvider.setUserDetailsService(userService); return daoAuthenticationProvider; } @Bean public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); } }
import { GET_PUZZLE_REQUEST, GET_PUZZLE_SUCCESS, GET_PUZZLE_FAILURE, CREATE_PUZZLE_REQUEST, CREATE_PUZZLE_SUCCESS, CREATE_PUZZLE_FAILURE, RESET_RECENT_PUZZLE, SOLVE_PUZZLE_REQUEST, SOLVE_PUZZLE_SUCCESS, SOLVE_PUZZLE_FAILURE, SELECT_PUZZLE } from "./actionTypes"; export interface Puzzle { id: string, solved: number, invalid: number, valid: number, output: { [address: string]: string }, input: { address: string; description: string, hash: string, public_key: string, timestamp: string, } } export interface PuzzleState { loading: boolean; pending: boolean; recent: Puzzle | null; current: Puzzle | null; pool: Puzzle[]; error: string | null; } export interface SelectPuzzle { type: typeof SELECT_PUZZLE; payload: SelectPuzzlePayload; } export interface GetPuzzleRequest { type: typeof GET_PUZZLE_REQUEST; } export interface ResetRecentPuzzle { type: typeof RESET_RECENT_PUZZLE; } export interface GetPuzzleSuccessPayload { pool: Puzzle[]; } export interface GetPuzzleFailurePayload { error: string; } export interface CreatePuzzleRequest { type: typeof CREATE_PUZZLE_REQUEST; payload: CreatePuzzleRequestPayload; } export interface CreatePuzzleRequestPayload { description: string; answer: string; } export interface SelectPuzzlePayload { puzzle: Puzzle; } export interface SolvePuzzleRequest { type: typeof SOLVE_PUZZLE_REQUEST; payload: SolvePuzzleRequestPayload; } export interface SolvePuzzleRequestPayload { puzzle_id: string; solution: string; invalid: boolean; } export type GetPuzzleSuccess = { type: typeof GET_PUZZLE_SUCCESS, payload: GetPuzzleSuccessPayload, }; export type GetPuzzleFailure = { type: typeof GET_PUZZLE_FAILURE, payload: GetPuzzleFailurePayload, }; export interface CreatePuzzleSuccessPayload { puzzle: Puzzle; } export interface CreatePuzzleFailurePayload { error: string; } export type CreatePuzzleSuccess = { type: typeof CREATE_PUZZLE_SUCCESS, payload: CreatePuzzleSuccessPayload, }; export type CreatePuzzleFailure = { type: typeof CREATE_PUZZLE_FAILURE, payload: CreatePuzzleFailurePayload, }; export interface SolvePuzzleSuccessPayload { status: boolean; } export interface SolvePuzzleFailurePayload { error: string; } export type SolvePuzzleSuccess = { type: typeof SOLVE_PUZZLE_SUCCESS, payload: SolvePuzzleSuccessPayload, }; export type SolvePuzzleFailure = { type: typeof SOLVE_PUZZLE_FAILURE, payload: SolvePuzzleFailurePayload, }; export type PuzzleActions = | GetPuzzleRequest | GetPuzzleSuccess | GetPuzzleFailure | CreatePuzzleRequest | CreatePuzzleSuccess | CreatePuzzleFailure | SolvePuzzleRequest | SolvePuzzleSuccess | SolvePuzzleFailure | ResetRecentPuzzle | SelectPuzzle;
package org.hyunggi.mygardenbe.common.exception.controlleradvice; import net.gpedro.integrations.slack.SlackApi; import org.hyunggi.mygardenbe.IntegrationTestSupport; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.BDDMockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mock.web.MockHttpServletRequest; class ServerErrorDetectControllerAdviceTest extends IntegrationTestSupport { @MockBean private SlackApi slackApi; private ServerErrorDetectControllerAdvice serverErrorDetectControllerAdvice; @BeforeEach void setUp() { serverErrorDetectControllerAdvice = new ServerErrorDetectControllerAdvice(slackApi); } @Test @DisplayName("Exception 발생 시 Slack으로 알림을 보냄") void handleException() { final RuntimeException testException = new RuntimeException("test exception"); // when try { serverErrorDetectControllerAdvice.handleException(new MockHttpServletRequest(), testException); } catch (Exception ignored) { } // then BDDMockito.then(slackApi).should().call(BDDMockito.any()); } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pjoseth <pjoseth@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/09 13:30:24 by pjoseth #+# #+# */ /* Updated: 2019/09/20 16:10:23 by pjoseth ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static const char *skip(const char *str, int *neg, int *count) { while (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\v' || *str == '\f' || *str == '\f' || *str == '\r') str++; if (*str == '+' || *str == '-') { if (*str == '-') *neg = -1; str++; } while (ft_isdigit(*str)) { str++; (*count)++; } str = str - (*count); return (str); } int ft_atoi(const char *str) { int count; int neg; long long int result; long long int buf; count = 0; neg = 1; result = 0; buf = 0; str = skip(str, &neg, &count); while (*str >= 48 && *str <= 57) { result = (result * 10) + (long long int)(*str - 48); if ((result / 10) != buf) { if (neg == 1 && count > 19) return (-1); return (0); } buf = result; str++; } return (result * neg); }
import { ExclamationCircleFilled, ReloadOutlined } from '@ant-design/icons' import { Card, List, message, Modal, Tooltip } from 'antd' import React, { useEffect, useState } from 'react' import { TODO_URL } from '../../../../constant/APIConstant' import { TodoStatus } from '../../../../interface/TodoTypes' import styles from './trash.module.css' const { confirm } = Modal export const Trash: React.FC = () => { const [loadingCard, setLoadingCard] = useState<boolean>(false) const [listTodo, setListTodo] = useState<any>([]) const reloadCardComponent = () => { setLoadingCard(true) setTimeout(() => { setLoadingCard(false) }, 3000) } const getTodoList = () => { try { fetch(`${TODO_URL}?status.equal=deleted`) .then(async res => { const response = await res.json() if (!res.ok) { message.error(response.detail) } else { setListTodo(response) reloadCardComponent() } }) } catch (err) { console.log('ERORR_FETCH_TODO >>', err) } } useEffect(() => { getTodoList() }, []) const restoreTodo = (data: any) => { const payload = { ...data, status: TodoStatus.ACTIVE } confirm({ title: `Do you want to restore ${data.title}?`, icon: <ExclamationCircleFilled />, content: 'This todo will be restored into Note pages', onOk() { try { fetch(`${TODO_URL}/${data.id}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify(payload), }) .then(async res => { const response = await res.json() if (!res.ok) { message.error(response.detail) } else { message.success('To-do list deleted!') getTodoList() } }) } catch (err) { console.log('ERROR_DELETE_TODO >>', err) } }, onCancel() { }, }); } return ( <div className={styles.filterContainer}> <List style={{ marginTop: '12px', textAlign: 'left' }} dataSource={listTodo} renderItem={(item: any) => ( <List.Item> <Card title={item.title} className={styles.cardContent} loading={loadingCard} extra={ <Tooltip title="Restore Todo"> <ReloadOutlined onClick={() => restoreTodo(item)} /> </Tooltip> } > <List itemLayout='horizontal' dataSource={item.todoList} renderItem={(data: any) => ( <List.Item> <List.Item.Meta description={ data.isDone ? <span className={styles.striketrought}> {data.description} </span> : <span>{data.description}</span> } /> </List.Item> )} /> </Card> </List.Item> )} /> </div> ) }
import { ReactNode, useRef } from 'react'; import { useClickAway } from 'react-use'; import styled, { useTheme } from 'styled-components'; import { Text } from '../common/Text/Text.styles'; export interface ModalBaseProps { title: string; onDismiss?: () => void; } interface LocalModalBaseProps extends ModalBaseProps { children: ReactNode; } const StyledModalBase = styled.div` position: fixed; inset: 0; border-radius: ${props => props.theme.borderRadius}; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); padding: ${props => props.theme.spacing[6]}; background-color: ${props => props.theme.color.neutralMedium25}; height: fit-content; width: fit-content; max-width: calc(100vw - ${props => props.theme.spacing[4]}); ${props => props.theme.mediaQuery.sm} { max-width: calc(100vw - ${props => props.theme.spacing[6]}); } `; const StyledModalHeader = styled.div` display: flex; width: 100%; align-items: center; justify-content: center; `; const ModalBase = ({ title, onDismiss, children }: LocalModalBaseProps) => { const theme = useTheme(); const ref = useRef<HTMLDivElement>(null); useClickAway(ref, () => { onDismiss && onDismiss(); }); return ( <StyledModalBase ref={ref}> <StyledModalHeader> <Text variant='header2' color='text1' margin={`0 0 ${theme.spacing[6]} 0`}> {title} </Text> </StyledModalHeader> {children} </StyledModalBase> ); }; export default ModalBase;
# react/no-set-state-in-component-did-update ## Rule category Suspicious. ## What it does Disallows calling `this.setState` in `componentDidUpdate` outside of functions, such as callbacks. ## Why is this bad? Updating the state after a component mount will trigger a second render() call and can lead to property/layout thrashing. ## Examples ### Failing ```tsx import React from "react"; class MyComponent extends React.Component { componentDidUpdate() { this.setState({ name: "John" }); } render() { return <div>Hello {this.state.name}</div>; } } ``` ### Passing ```tsx import React from "react"; class MyComponent extends React.Component { componentDidUpdate() { this.onMount(function callback(newName) { this.setState({ name: newName, }); }); } render() { return <div>Hello {this.state.name}</div>; } } ```
import { useForm } from "react-hook-form"; import * as s from "../../styles/bamboo/modal"; interface props { onClick: (e: React.MouseEvent) => void; } export default function Modal({ onClick }: props) { interface FormData { content: string; } const { register, handleSubmit, formState: { errors }, } = useForm<FormData>({}); const onSubmit = (data: FormData) => { fetch(`https://i10c208.p.ssafy.io/api/mindLetGo`, { method: "POST", headers: { "Content-Type": "application/json", "Access_Token": `${sessionStorage.getItem("Access_Token")}`, }, body: JSON.stringify(data), }).then((res) => { if (res.status === 200) { window.location.reload(); } }); }; return ( <s.Wrapper> <s.ToolBox> <span onClick={onClick}>x</span> </s.ToolBox> <s.Form onSubmit={handleSubmit(onSubmit)}> <s.Input {...register("content", { required: "내용을 입력해 주세요." })} placeholder="메시지를 작성해 주세요." /> <s.Submit type="submit" value="작성" /> </s.Form> </s.Wrapper> ); }
/********************************************************************** Audacity: A Digital Audio Editor Dominic Mazzoni *******************************************************************//*! \class Resample \brief Combined interface to libresample and libsamplerate. This class abstracts the interface to two different resampling libraries: libresample, written by Dominic Mazzoni based on Resample-1.7 by Julius Smith. LGPL. libsamplerate, written by Erik de Castro Lopo. GPL. The author of libsamplerate requests that you not distribute a binary version of Audacity that links to libsamplerate and also has plug-in support. *//*******************************************************************/ #include "Resample.h" #include "Prefs.h" #include <wx/intl.h> int Resample::GetFastMethod() { return gPrefs->Read(GetFastMethodKey(), GetFastMethodDefault()); } int Resample::GetBestMethod() { return gPrefs->Read(GetBestMethodKey(), GetBestMethodDefault()); } void Resample::SetFastMethod(int index) { gPrefs->Write(GetFastMethodKey(), (long)index); gPrefs->Flush(); } void Resample::SetBestMethod(int index) { gPrefs->Write(GetBestMethodKey(), (long)index); gPrefs->Flush(); } #if USE_LIBRESAMPLE #include "libresample.h" bool Resample::ResamplingEnabled() { return true; } wxString Resample::GetResamplingLibraryName() { return _("Libresample by Dominic Mazzoni and Julius Smith"); } int Resample::GetNumMethods() { return 2; } wxString Resample::GetMethodName(int index) { if (index == 1) return _("High-quality Sinc Interpolation"); return _("Fast Sinc Interpolation"); } const wxString Resample::GetFastMethodKey() { return wxT("/Quality/LibresampleSampleRateConverter"); } const wxString Resample::GetBestMethodKey() { return wxT("/Quality/LibresampleHQSampleRateConverter"); } int Resample::GetFastMethodDefault() { return 0; } int Resample::GetBestMethodDefault() { return 1; } Resample::Resample(bool useBestMethod, double minFactor, double maxFactor) { if (useBestMethod) mMethod = GetBestMethod(); else mMethod = GetFastMethod(); mHandle = resample_open(mMethod, minFactor, maxFactor); } bool Resample::Ok() { return (mHandle != NULL); } int Resample::Process(double factor, float *inBuffer, int inBufferLen, bool lastFlag, int *inBufferUsed, float *outBuffer, int outBufferLen) { return resample_process(mHandle, factor, inBuffer, inBufferLen, (int)lastFlag, inBufferUsed, outBuffer, outBufferLen); } Resample::~Resample() { resample_close(mHandle); } #elif USE_LIBSAMPLERATE #include <samplerate.h> bool Resample::ResamplingEnabled() { return true; } wxString Resample::GetResamplingLibraryName() { return _("Libsamplerate by Erik de Castro Lopo"); } int Resample::GetNumMethods() { int i = 0; while(src_get_name(i)) i++; return i; } wxString Resample::GetMethodName(int index) { return wxString(wxString::FromAscii(src_get_name(index))); } const wxString Resample::GetFastMethodKey() { return wxT("/Quality/SampleRateConverter"); } const wxString Resample::GetBestMethodKey() { return wxT("/Quality/HQSampleRateConverter"); } int Resample::GetFastMethodDefault() { return SRC_SINC_FASTEST; } int Resample::GetBestMethodDefault() { return SRC_SINC_BEST_QUALITY; } Resample::Resample(bool useBestMethod, double minFactor, double maxFactor) { if (!src_is_valid_ratio (minFactor) || !src_is_valid_ratio (maxFactor)) { fprintf(stderr, "libsamplerate supports only resampling factors between 1/SRC_MAX_RATIO and SRC_MAX_RATIO.\n"); // FIX-ME: Audacity will hang after this if branch. mHandle = NULL; return; } if (useBestMethod) mMethod = GetBestMethod(); else mMethod = GetFastMethod(); int err; SRC_STATE *state = src_new(mMethod, 1, &err); mHandle = (void *)state; mInitial = true; } bool Resample::Ok() { return (mHandle != NULL); } int Resample::Process(double factor, float *inBuffer, int inBufferLen, bool lastFlag, int *inBufferUsed, float *outBuffer, int outBufferLen) { if (mInitial) { src_set_ratio((SRC_STATE *)mHandle, factor); mInitial = false; } SRC_DATA data; data.data_in = inBuffer; data.data_out = outBuffer; data.input_frames = inBufferLen; data.output_frames = outBufferLen; data.input_frames_used = 0; data.output_frames_gen = 0; data.end_of_input = (int)lastFlag; data.src_ratio = factor; int err = src_process((SRC_STATE *)mHandle, &data); if (err) { wxFprintf(stderr, _("Libsamplerate error: %d\n"), err); return 0; } *inBufferUsed = (int)data.input_frames_used; return (int)data.output_frames_gen; } Resample::~Resample() { src_delete((SRC_STATE *)mHandle); } #else // No resampling support bool Resample::ResamplingEnabled() { return false; } wxString Resample::GetResamplingLibraryName() { return _("Resampling disabled."); } int Resample::GetNumMethods() { return 1; } wxString Resample::GetMethodName(int index) { return _("Resampling disabled."); } const wxString Resample::GetFastMethodKey() { return wxT("/Quality/DisabledConverter"); } const wxString Resample::GetBestMethodKey() { return wxT("/Quality/DisabledConverter"); } int Resample::GetFastMethodDefault() { return 0; } int Resample::GetBestMethodDefault() { return 0; } Resample::Resample(bool, double, double) { } bool Resample::Ok() { return false; } int Resample::Process(double factor, float *inBuffer, int inBufferLen, bool lastFlag, int *inBufferUsed, float *outBuffer, int outBufferLen) { int i; int len = inBufferLen; if (len > outBufferLen) len = outBufferLen; for(i=0; i<len; i++) outBuffer[i] = inBuffer[i]; return len; } Resample::~Resample() { } #endif // Indentation settings for Vim and Emacs and unique identifier for Arch, a // version control system. Please do not modify past this point. // // Local Variables: // c-basic-offset: 3 // indent-tabs-mode: nil // End: // // vim: et sts=3 sw=3 // arch-tag: ceb8c6d0-3df6-4b6f-b763-100fe856f6fb
import Head from "next/head"; import { Inter } from "next/font/google"; import Dex from "./components/Dex"; import { DeDustClient } from '@dedust/sdk'; import { Spinner, Flex } from "@chakra-ui/react"; import { useState, useEffect } from "react"; import 'react-toastify/dist/ReactToastify.css'; const inter = Inter({ subsets: ["latin"] }); export default function Home() { const [coins, setCoins] = useState(null); const [loading, setLoading] = useState(true); const getPools = async () => { try { const dedustClient = new DeDustClient({ endpointUrl: 'https://api.dedust.io' }); const pools = await dedustClient.getPools(); // Filter pools with totalSupply more than 1000 and non-null metadata const filteredPools = pools.filter(pool => parseInt(pool.totalSupply) > 10 && pool.assets[0].metadata !== null); // Create a Map to store unique names and their corresponding image URLs and symbols const uniqueNamesWithImages = new Map(); console.log(filteredPools) // Extract and store unique names and their corresponding image URLs from filtered pools filteredPools.forEach(pool => { const metadata = pool.assets[0].metadata; const address = pool.assets[0].address if (metadata) { const name = metadata.name; const imageUrl = metadata.image; const symbol = metadata.symbol; const contractAddress = address const combinedInfo = { imageUrl, symbol, contractAddress }; if (!uniqueNamesWithImages.has(name)) { uniqueNamesWithImages.set(name, combinedInfo); } } }); // Convert the Map to an array of objects for easier handling const uniqueNamesArray = Array.from(uniqueNamesWithImages, ([name, info]) => ({ name, ...info })); return uniqueNamesArray; } catch (error) { console.log(error); return []; // Return an empty array in case of error } } useEffect(() => { getPools().then(uniqueNamesArray => { setCoins(uniqueNamesArray); setLoading(false); // Set loading to false when data is loaded console.log('Unique Names with Images:', uniqueNamesArray); }); }, []); return ( <> <Head> <title>NutSwap</title> <meta name="description" content="A dex built with precision by NUTCOIN" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> {loading ? ( <Flex height="100vh" alignItems="center" justifyContent="center" > <Spinner thickness="4px" speed="0.65s" emptyColor="gray.200" color="blue.500" size="xl" /> </Flex> ) : ( <Dex coins={coins} /> )} </main> </> ); }
# Projeto e Modelagem de Bancos de Dados - 2024.1 - turma A ## Projeto AV2 ### Equipe: Arthur Wolmer e Diego Peter O processo de desenvolvimento da aplicação cobriu os pontos de 1. a 4. aproximadamente em sequência, com a exploração das tecnologias correndo em paralelo. # 1. **Análise de requisitos** Minimundo (criado pela equipe): Um **armazém de produtos de informática** precisa controlar seu e**stoque ao longo do tempo e gerenciar aspectos logísticos** relacionados ao fluxo de mercadorias. O que o armazém armazena são itens, que representam uma "instância" de um produto, fornecido por um fornecedor. É possível que o mesmo produto seja fornecido por mais de um fornecedor, como no caso de GPUs de marcas distintas com o mesmo chipset, ou um mesmo periférico fornecido por importadores distintos. Cada item presente no banco de dados precisa ter um funcionário associado, responsável pelo cadastro, e um timestamp (data e hora) relativo ao cadastro. Produtos representam um modelo de produto e tem nome, categoria e uma descrição (opcional). Cada produto pode ou não ser frágil. Um produto deve pertencer a uma ou mais categorias. Categorias possuem nome e descrição (opcional). Fornecedores têm cnpj, nome e dados de contato (telefone e e-mail). A perda de itens do estoque relaciona o item perdido, funcionário responsável pela identificação e um timestamp (data e hora) para a perda. Só podem ser perdidos itens previamente cadastrados no banco e que não foram expedidos em algum pedido (vendidos). Além disso, deve ser registrado um motivo para a perda, o qual só pode assumir alguns valores distintos: extravio, dano de acondicionamento (armazém), problema de fabricação ou transporte (fornecedor). Por fim, um ou mais itens cadastrados podem ser expedidos como parte de um pedido (venda). Deve ser relacionado o funcionário responsável, os itens envolvidos (entre os cadastrados e não perdidos), um timestamp (data e hora) e o cliente que realizou o pedido. Funcionários têm cpf, nome e dados de contato (telefone e email). Podem ser gerentes ou não. Todo funcionário gerente pode ser supervisor de outros funcionários e todo funcionário não-gerente deve ter um outro funcionário, gerente, como supervisor. Clientes têm nome, dados de contato (telefone e e-mail) e podem ser pessoas físicas ou pessoas jurídicas; pessoas físicas têm cpf e pessoas jurídicas, cnpj. Cada cliente pode ter um número arbitrário de endereços de entrega. Endereços de entrega são compostos pelo nome do destinatário e endereço (com estado, municipio, CEP, logradouro, numero e complemento). Cada pedido expedido, além de cliente e funcionário, também está relacionado a um endereço de entrega, uma transportadora e possui código de rastreamento. Transportadoras têm cpnj, nome, dados de contato (telefone e e-mail). <div style="page-break-after: always;"></div> # 2. Modelagem Conceitual <div style="page-break-after: always;"></div> # 3. Mapeamento Lógico-relacional <div style="page-break-after: always;"></div> # 4. Modelagem física (inclusive init.sql e povoamento) ## Script de criação ``` CREATE TABLE IF NOT EXISTS category ( id CHAR(23) NOT NULL, cat_name VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id) ); CREATE TABLE IF NOT EXISTS product ( id CHAR(23) NOT NULL, prod_name VARCHAR(255) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE IF NOT EXISTS classification ( product_id CHAR(23) NOT NULL, category_id CHAR(23) NOT NULL, PRIMARY KEY (product_id, category_id), FOREIGN KEY (product_id) REFERENCES product(id), FOREIGN KEY (category_id) REFERENCES category(id) ); CREATE TABLE IF NOT EXISTS product_supplier ( cnpj CHAR(18) NOT NULL, name VARCHAR(255) NOT NULL, phone CHAR(15) NOT NULL UNIQUE, email VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY(cnpj) ); CREATE TABLE IF NOT EXISTS employee ( cpf CHAR(14) NOT NULL, name VARCHAR(255) NOT NULL, phone CHAR(15) NOT NULL UNIQUE, email VARCHAR(255) NOT NULL UNIQUE, passwordHash VARCHAR(255) NOT NULL, is_manager BOOLEAN NOT NULL, manager_cpf VARCHAR(14), PRIMARY KEY(cpf), FOREIGN KEY(manager_cpf) REFERENCES employee(cpf) ); CREATE TABLE IF NOT EXISTS item ( id CHAR(23) NOT NULL, product_id CHAR(23) NOT NULL, supplier_cnpj CHAR(18) NOT NULL, employee_cpf CHAR(14) NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), FOREIGN KEY (product_id) REFERENCES product(id), FOREIGN KEY (supplier_cnpj) REFERENCES product_supplier(cnpj), FOREIGN KEY (employee_cpf) REFERENCES employee(cpf) ); CREATE TABLE IF NOT EXISTS discard ( employee_cpf CHAR(14) NOT NULL, item_id CHAR(23) NOT NULL, discard_reason VARCHAR(255) NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (item_id), FOREIGN KEY (employee_cpf) REFERENCES employee(cpf), FOREIGN KEY (item_id) REFERENCES item(id), CONSTRAINT discardOptions CHECK (discard_reason='Loss' OR discard_reason='Bad Conditioning' OR discard_reason='Fabrication/Transport') ); CREATE TABLE IF NOT EXISTS carrier ( cnpj CHAR(18) NOT NULL, name VARCHAR(255) NOT NULL UNIQUE, phone CHAR(15) NOT NULL UNIQUE, email VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY(cnpj) ); CREATE TABLE IF NOT EXISTS client ( id CHAR(23) NOT NULL, name VARCHAR(255) NOT NULL, phone CHAR(15) NOT NULL UNIQUE, email VARCHAR(255) NOT NULL UNIQUE, cpf CHAR(14), -- uniqueness guaranteed by custom trigger on create/update cnpj CHAR(18), -- uniqueness guaranteed by custom trigger on create/update PRIMARY KEY(id) ); CREATE TABLE IF NOT EXISTS delivery_address ( id CHAR(23) NOT NULL, recipient_name VARCHAR(255) NOT NULL, state CHAR(2) NOT NULL, city VARCHAR(100) NOT NULL, zip CHAR(9) NOT NULL, street VARCHAR(255) NOT NULL, number VARCHAR(50) NOT NULL, details VARCHAR(100) NOT NULL, client_id CHAR(23) NOT NULL, PRIMARY KEY(id), FOREIGN KEY(client_id) REFERENCES client(id) ); CREATE TABLE IF NOT EXISTS orders ( id CHAR(23) NOT NULL, client_id CHAR(23) NOT NULL, employee_cpf CHAR(14) NOT NULL, delivery_address_id CHAR(23) NOT NULL, carrier_cnpj CHAR(18) NOT NULL, tracking_code VARCHAR(255) NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY(id), FOREIGN KEY(client_id) REFERENCES client(id), FOREIGN KEY(employee_cpf) REFERENCES employee(cpf), FOREIGN KEY(delivery_address_id) REFERENCES delivery_address(id), FOREIGN KEY(carrier_cnpj) REFERENCES carrier(cnpj) ); CREATE TABLE IF NOT EXISTS ordered_item ( item_id CHAR(23) NOT NULL, order_id CHAR(23) NOT NULL, PRIMARY KEY(item_id, order_id), FOREIGN KEY(item_id) REFERENCES item(id), FOREIGN KEY(order_id) REFERENCES orders(id) ); CREATE TABLE IF NOT EXISTS refresh_token ( id BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY, employee_cpf CHAR(14) NOT NULL, token VARCHAR(255) NOT NULL UNIQUE, expiry_date DATETIME(6) NOT NULL, CONSTRAINT fk_employee FOREIGN KEY (employee_cpf) REFERENCES employee(cpf) ON DELETE CASCADE ON UPDATE CASCADE ); ``` ## Consultas (ligadas a operações CRUD) ``` -- CATEGORIAS - Insere uma nova categoria na tabela 'category' INSERT INTO category (id, cat_name) VALUES (?, ?); -- Seleciona todas as categorias da tabela 'category' SELECT * FROM category; -- Deleta uma categoria pelo seu ID na tabela 'category' DELETE FROM category WHERE id = ?; -- Atualiza o nome de uma categoria pelo seu ID na tabela 'category' UPDATE category SET cat_name = ? WHERE id = ?; -- Seleciona uma categoria pelo seu nome na tabela 'category' SELECT * FROM category WHERE cat_name = ?; -- Seleciona uma categoria pelo seu ID na tabela 'category' SELECT * FROM category WHERE id = ?; -- PRODUTOS -- Insere um novo produto na tabela 'product' INSERT INTO product (id, prod_name) VALUES (?, ?); -- Seleciona todos os produtos da tabela 'product' SELECT * FROM product; -- Seleciona um produto pelo seu ID na tabela 'product' SELECT * FROM product WHERE id = ?; -- Atualiza o nome de um produto pelo seu ID na tabela 'product' UPDATE product SET prod_name = ? WHERE id = ?; -- Deleta um produto pelo seu ID na tabela 'product' DELETE FROM product WHERE id = ?; -- FORNECEDOR -- Insere um novo fornecedor na tabela 'product_supplier' INSERT INTO product_supplier (cnpj, name, email, phone) VALUES (?, ?, ?, ?); -- Seleciona todos os fornecedores da tabela 'product_supplier' SELECT * FROM product_supplier; -- Seleciona um fornecedor pelo seu CNPJ na tabela 'product_supplier' SELECT * FROM product_supplier WHERE cnpj = ?; -- Atualiza os dados de um fornecedor pelo seu CNPJ na tabela 'product_supplier' UPDATE product_supplier SET name = ?, email = ?, phone = ? WHERE cnpj = ?; -- Deleta um fornecedor pelo seu CNPJ na tabela 'product_supplier' DELETE FROM product_supplier WHERE cnpj = ?; -- FUNCIONÁRIO -- Seleciona um empregado pelo seu CPF na tabela 'employee' SELECT * FROM employee WHERE cpf = ?; -- Insere um novo empregado na tabela 'employee' INSERT INTO employee (cpf, name, email, phone, is_manager, manager_cpf, passwordHash) VALUES (?, ?, ?, ?, ?, ?, ?); -- Seleciona todos os empregados da tabela 'employee' SELECT * FROM employee; -- Atualiza os dados de um empregado pelo seu CPF na tabela 'employee' UPDATE employee SET name = ?, email = ?, phone = ?, is_manager = ?, manager_cpf = ?, passwordHash = ? WHERE cpf = ?; -- Deleta um empregado pelo seu CPF na tabela 'employee' DELETE FROM employee WHERE cpf = ?; -- ITEM CADASTRADO -- Insere um novo item na tabela 'item' INSERT INTO item (id, product_id, supplier_cnpj, employee_cpf) VALUES (?, ?, ?, ?); -- Seleciona um item pelo seu ID na tabela 'item' SELECT * FROM item WHERE id = ?; -- Seleciona todos os itens da tabela 'item' SELECT * FROM item; -- Deleta um item pelo seu ID na tabela 'item' DELETE FROM item WHERE id = ?; -- Seleciona todos os itens do estoque atual da tabela 'current_stock' SELECT * FROM current_stock; -- (ITEM) DESCARTADO -- Insere um novo descarte na tabela 'discard' INSERT INTO discard (employee_cpf, item_id, discard_reason) VALUES (?, ?, ?); -- Seleciona um descarte pela combinação de CPF do empregado e ID do item na tabela 'discard' SELECT * FROM discard WHERE employee_cpf = ? AND item_id = ?; -- Seleciona todos os descartes da tabela 'discard' SELECT * FROM discard; -- Deleta um descarte pela combinação de CPF do empregado e ID do item na tabela 'discard' DELETE FROM discard WHERE employee_cpf = ? AND item_id = ?; -- Deleta um descarte pelo ID do item na tabela 'discard' DELETE FROM discard WHERE item_id = ?; -- TRANSPORTADORA -- Insere uma nova transportadora na tabela 'carrier' INSERT INTO carrier (cnpj, name, email, phone) VALUES (?, ?, ?, ?); -- Seleciona uma transportadora pelo seu CNPJ na tabela 'carrier' SELECT * FROM carrier WHERE cnpj = ?; -- Atualiza os dados de uma transportadora pelo seu CNPJ na tabela 'carrier' UPDATE carrier SET name = ?, email = ?, phone = ? WHERE cnpj = ?; -- Deleta uma transportadora pelo seu CNPJ na tabela 'carrier' DELETE FROM carrier WHERE cnpj = ?; -- Seleciona todas as transportadoras da tabela 'carrier' SELECT * FROM carrier; -- CLIENTE -- Insere um novo cliente na tabela 'client' usando CPF INSERT INTO client (id, name, phone, email, cpf) VALUES (?, ?, ?, ?, ?); -- Insere um novo cliente na tabela 'client' usando CNPJ INSERT INTO client (id, name, phone, email, cnpj) VALUES (?, ?, ?, ?, ?); -- Seleciona um cliente pelo seu ID na tabela 'client' SELECT * FROM client WHERE id = ?; -- Atualiza os dados de um cliente pelo seu ID na tabela 'client' UPDATE client SET name = ?, phone = ?, email = ?, cpf = ?, cnpj = ? WHERE id = ?; -- Deleta um cliente pelo seu ID na tabela 'client' DELETE FROM client WHERE id = ?; -- Seleciona todos os clientes da tabela 'client' SELECT * FROM client; -- ENDEREÇO ENTREGA -- Insere um novo endereço de entrega na tabela 'delivery_address' INSERT INTO delivery_address (id, recipient_name, state, city, zip, street, number, details, client_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?); -- Seleciona um endereço de entrega pelo seu ID na tabela 'delivery_address' SELECT * FROM delivery_address WHERE id = ?; -- Atualiza os dados de um endereço de entrega pelo seu ID na tabela 'delivery_address' UPDATE delivery_address SET recipient_name = ?, state = ?, city = ?, zip = ?, street = ?, number = ?, details = ?, client_id = ? WHERE id = ?; -- Deleta um endereço de entrega pelo seu ID na tabela 'delivery_address' DELETE FROM delivery_address WHERE id = ?; -- Seleciona todos os endereços de entrega da tabela 'delivery_address' SELECT * FROM delivery_address; -- PEDIDO -- Insere um novo pedido na tabela 'orders' INSERT INTO orders (id, client_id, delivery_address_id, employee_cpf, carrier_cnpj, tracking_code) VALUES (?, ?, ?, ?, ?, ?); -- Seleciona um pedido pelo seu ID na tabela 'orders' SELECT * FROM orders WHERE id = ?; -- Atualiza os dados de um pedido pelo seu ID na tabela 'orders' UPDATE orders SET client_id = ?, delivery_address_id = ?, employee_cpf = ?, carrier_cnpj = ?, tracking_code = ?, created_at = ?, updated_at = ? WHERE id = ?; -- Deleta um pedido pelo seu ID na tabela 'orders' DELETE FROM orders WHERE id = ?; -- Seleciona todos os pedidos da tabela 'orders' SELECT * FROM orders; -- RELAÇÃO ITEM-PEDIDO -- Insere um novo item ordenado na tabela 'ordered_item' INSERT INTO ordered_item (item_id, order_id) VALUES (?, ?); -- Deleta um item ordenado pela combinação de ID do item e ID do pedido na tabela 'ordered_item' DELETE FROM ordered_item WHERE item_id = ? AND order_id = ?; ``` ## Consultas (relatórios) ``` -- PROCEDURES -- procedure to get all items ever registered, able to filter by date, product, supplier, employee or category -- all filters optional -- CALL GetStockHistory(NULL, NULL, NULL, NULL, NULL, NULL); DELIMITER // CREATE PROCEDURE GetStockHistory ( IN startDate DATETIME, IN endDate DATETIME, IN productId CHAR(23), IN supplierCnpj CHAR(18), IN employeeCpf CHAR(14), IN categoryId CHAR(23) ) BEGIN SELECT i.id AS item_id, i.product_id, p.prod_name, i.supplier_cnpj, s.name AS supplier_name, i.employee_cpf, e.name AS employee_name, CASE WHEN d.item_id IS NOT NULL THEN 'Discarded' WHEN oi.item_id IS NOT NULL THEN 'Ordered' ELSE 'In Stock' END AS status, CASE WHEN d.item_id IS NOT NULL THEN d.updated_at WHEN oi.item_id IS NOT NULL THEN o.updated_at ELSE i.updated_at END AS last_update FROM item i JOIN product p ON i.product_id = p.id JOIN product_supplier s ON i.supplier_cnpj = s.cnpj JOIN employee e ON i.employee_cpf = e.cpf JOIN classification c ON p.id = c.product_id JOIN category cat ON c.category_id = cat.id LEFT JOIN discard d ON i.id = d.item_id LEFT JOIN ordered_item oi ON i.id = oi.item_id LEFT JOIN orders o ON oi.order_id = o.id WHERE (startDate IS NULL OR i.created_at >= startDate) AND (endDate IS NULL OR i.created_at <= endDate) AND (productId IS NULL OR i.product_id = productId) AND (supplierCnpj IS NULL OR i.supplier_cnpj = supplierCnpj) AND (employeeCpf IS NULL OR i.employee_cpf = employeeCpf) AND (categoryId IS NULL OR cat.id = categoryId) ORDER BY i.created_at DESC; END // DELIMITER ; -- VIEWS -- view to call for items currently in stock, doubles as the list of items eligible for removal CREATE VIEW current_stock AS SELECT i.id, i.product_id, i.supplier_cnpj, i.employee_cpf, i.created_at, i.updated_at FROM item i LEFT JOIN discard d ON i.id = d.item_id LEFT JOIN ordered_item oi ON i.id = oi.item_id WHERE d.item_id IS NULL AND oi.item_id IS NULL; ``` ## Triggers, procedures e views ``` -- triggers DELIMITER // -- cpf xor cnpj for new client CREATE TRIGGER before_client_insert BEFORE INSERT ON client FOR EACH ROW BEGIN DECLARE cpf_count INT; DECLARE cnpj_count INT; IF (NEW.cpf IS NOT NULL AND NEW.cnpj IS NOT NULL) OR (NEW.cpf IS NULL AND NEW.cnpj IS NULL) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'A client must have either CPF or CNPJ, but not both'; END IF; IF NEW.cpf IS NOT NULL THEN SELECT COUNT(*) INTO cpf_count FROM client WHERE cpf = NEW.cpf; IF cpf_count > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Duplicate CPF not allowed'; END IF; END IF; IF NEW.cnpj IS NOT NULL THEN SELECT COUNT(*) INTO cnpj_count FROM client WHERE cnpj = NEW.cnpj; IF cnpj_count > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Duplicate CNPJ not allowed'; END IF; END IF; END // -- cpf xor cnpj for updated client CREATE TRIGGER before_client_update BEFORE UPDATE ON client FOR EACH ROW BEGIN DECLARE cpf_count INT; DECLARE cnpj_count INT; IF (NEW.cpf IS NOT NULL AND NEW.cnpj IS NOT NULL) OR (NEW.cpf IS NULL AND NEW.cnpj IS NULL) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'A client must have either CPF or CNPJ, but not both'; END IF; IF NEW.cpf IS NOT NULL THEN SELECT COUNT(*) INTO cpf_count FROM client WHERE cpf = NEW.cpf AND id != OLD.id; IF cpf_count > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Duplicate CPF not allowed'; END IF; END IF; IF NEW.cnpj IS NOT NULL THEN SELECT COUNT(*) INTO cnpj_count FROM client WHERE cnpj = NEW.cnpj AND id != OLD.id; IF cnpj_count > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Duplicate CNPJ not allowed'; END IF; END IF; END // -- don't allow category deletion if it would leave products without any category CREATE TRIGGER before_category_delete BEFORE DELETE ON category FOR EACH ROW BEGIN DECLARE orphan_count INT; -- Count the number of products exclusively associated with the category being deleted SELECT COUNT(*) INTO orphan_count FROM product p WHERE NOT EXISTS ( SELECT 1 FROM classification c WHERE c.product_id = p.id AND c.category_id != OLD.id ); -- If there are any products exclusively associated with the category being deleted, prevent deletion IF orphan_count > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete category because it would leave one or more products without any categories'; END IF; END // CREATE TRIGGER before_product_delete BEFORE DELETE ON product FOR EACH ROW BEGIN DECLARE has_orphaned_items BOOLEAN DEFAULT FALSE; -- Check if there are any items that would be left without a product SELECT EXISTS ( SELECT 1 FROM item WHERE product_id = OLD.id ) INTO has_orphaned_items; -- If there are orphaned items, prevent deletion IF has_orphaned_items THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete product because it would leave one or more items without a product'; ELSE -- If no orphaned items, proceed with deletion DELETE FROM classification WHERE product_id = OLD.id; -- Example deletion from classification table END IF; END // CREATE TRIGGER before_supplier_delete BEFORE DELETE ON product_supplier FOR EACH ROW BEGIN DECLARE has_orphaned_items BOOLEAN DEFAULT FALSE; -- Check if there are any items that would be left without a supplier SELECT EXISTS ( SELECT 1 FROM item WHERE supplier_cnpj = OLD.cnpj ) INTO has_orphaned_items; -- If there are orphaned items, prevent deletion IF has_orphaned_items THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete supplier because it would leave one or more items without a supplier'; END IF; END // CREATE TRIGGER before_employee_delete BEFORE DELETE ON employee FOR EACH ROW BEGIN DECLARE has_orphans BOOLEAN DEFAULT FALSE; -- Check if there are any related rows (items, discards, or orders) associated with the employee being deleted SELECT EXISTS ( SELECT 1 FROM item WHERE employee_cpf = OLD.cpf UNION ALL SELECT 1 FROM discard WHERE employee_cpf = OLD.cpf UNION ALL SELECT 1 FROM orders WHERE employee_cpf = OLD.cpf ) INTO has_orphans; -- If there are orphaned items, discards, or orders, prevent deletion IF has_orphans THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete employee because it would leave related items, discards, or orders orphaned'; END IF; END // CREATE TRIGGER before_item_delete BEFORE DELETE ON item FOR EACH ROW BEGIN DECLARE has_orphans BOOLEAN DEFAULT FALSE; -- Check if there are any related rows (items, discards, or orders) associated with the employee being deleted SELECT EXISTS ( SELECT 1 FROM discard WHERE item_id = OLD.id UNION ALL SELECT 1 FROM ordered_item WHERE item_id = OLD.id ) INTO has_orphans; -- If there are orphaned items, discards, or orders, prevent deletion IF has_orphans THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete item because it would leave related discards or ordered items orphaned'; END IF; END // CREATE TRIGGER before_client_delete BEFORE DELETE ON client FOR EACH ROW BEGIN DECLARE has_orphaned_orders BOOLEAN DEFAULT FALSE; -- Check if there are any orders that would be left without a client SELECT EXISTS ( SELECT 1 FROM orders WHERE client_id = OLD.id ) INTO has_orphaned_orders; -- If there are orphaned orders, prevent deletion IF has_orphaned_orders THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete client because it would leave one or more orders without a client'; ELSE -- If no orphaned orders, proceed with deletion DELETE FROM delivery_address WHERE client_id = OLD.id; END IF; END // CREATE TRIGGER before_address_delete BEFORE DELETE ON delivery_address FOR EACH ROW BEGIN DECLARE has_orphaned_orders BOOLEAN DEFAULT FALSE; -- Check if there are any orders that would be left without a client SELECT EXISTS ( SELECT 1 FROM orders WHERE delivery_address_id = OLD.id ) INTO has_orphaned_orders; -- If there are orphaned orders, prevent deletion IF has_orphaned_orders THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete delivery address because it would leave one or more orders without a delivery address'; END IF; END // CREATE TRIGGER before_carrier_delete BEFORE DELETE ON carrier FOR EACH ROW BEGIN DECLARE has_orphaned_orders BOOLEAN DEFAULT FALSE; -- Check if there are any orders that would be left without a client SELECT EXISTS ( SELECT 1 FROM orders WHERE carrier_cnpj = OLD.cnpj ) INTO has_orphaned_orders; -- If there are orphaned orders, prevent deletion IF has_orphaned_orders THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete carrier because it would leave one or more orders without a carrier'; END IF; END // -- triggers to make sure an item to be discarded has not been previously shipped (for creation and update of entries on discard) CREATE TRIGGER before_discard_insert BEFORE INSERT ON discard FOR EACH ROW BEGIN IF EXISTS ( SELECT 1 FROM ordered_item oi WHERE oi.item_id = NEW.item_id ) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Item has already been shipped and cannot be discarded.'; END IF; END // CREATE TRIGGER before_discard_update BEFORE UPDATE ON discard FOR EACH ROW BEGIN IF EXISTS ( SELECT 1 FROM ordered_item oi WHERE oi.item_id = NEW.item_id ) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Item has already been shipped and cannot be discarded.'; END IF; END // -- triggers to make sure an item to be shipped has not been previously discarded (for creation and update of entries on ordered_items) CREATE TRIGGER before_ordered_item_insert BEFORE INSERT ON ordered_item FOR EACH ROW BEGIN IF EXISTS ( SELECT 1 FROM discard d WHERE d.item_id = NEW.item_id ) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Item has already been discarded and cannot be shipped.'; END IF; END // CREATE TRIGGER before_ordered_item_update BEFORE UPDATE ON ordered_item FOR EACH ROW BEGIN IF EXISTS ( SELECT 1 FROM discard d WHERE d.item_id = NEW.item_id ) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Item has already been discarded and cannot be shipped.'; END IF; END // DELIMITER ; ``` - Nota: para as id's das entidades, quando não naturais (cpf/cnpj), foram utilizados identificadores únicos no padrão NanoId (strings curtas, seguras, amigáveis à URL e customizáveis com baixa chance de colisão). Para mais especificações: https://github.com/ai/nanoid <div style="page-break-after: always;"></div> # 5. Desenvolvimento da aplicação 1. Front-end - Framework: React com Vite (https://vitejs.dev/) - Shadcn para componentes de UI (https://ui.shadcn.com/) e TanStack para roteamento, queries, tabelas e forms (https://tanstack.com/) 2. Back-end - Framework: SpringBoot (Maven). - Sem uso de ORM, mas preservando arquitetura do Springboot (controllers-services-repositories), classes JDBC para acesso direto ao banco de dados com queries SQL escritas à mão. 3. Banco de dados: - Docker Compose para orquestrar o containers do banco de dados (inclusive execução automática do script de inicialização) - Triggers para garantir integridade do banco dentro das regras de negócio e impedir a invalidação da funcionalidade do histórico de estoque - Procedures e views para extração de relatórios
import React, { useState } from 'react' import { useDispatch } from 'react-redux' import { useTypedSelector } from '../../hooks/useTypedSelector' import { GoodsActionCreator } from '../../store/action-creators/goodsActionCreator' import MyInput from '../ui/MyInput/MyInput' import style from './SearchInput.module.css' const SearchInput: React.FC = () => { const [search, setSearch] = useState('') const authors = useTypedSelector(state => state.genreAuthor.author) const { limit, page } = useTypedSelector(state => state.goods) const dispatch = useDispatch() const filterAuthorByName = authors.filter(author => { return author.name.toLowerCase().includes(search.toLowerCase()) }) const selectAuthor = (id: number) => { dispatch(GoodsActionCreator.getAllGoods(id, null, limit, page)) setSearch('') } return ( <form className={style.searchBlock}> <i> </i> <MyInput value={search} type='text' placeholder='Поиск по имени автора' onChange={e => setSearch(e.target.value)} /> <ul className={style.autocomplete}> { search ? filterAuthorByName.map(item => { return <li key={item.id} className={style.autocomleteItem} onClick={() => selectAuthor(item.id)} > {item.name} </li> }) : null } </ul> </form> ); }; export default SearchInput;
<?php /** * The template for displaying all single posts * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post * * @package adria */ get_header(); ?> <main id="main" class="site-main transition-opacity ease-in delay-100 duration-300" style="opacity: 0" role="main"> <?php while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content', get_post_type() ); the_post_navigation( array( 'prev_text' => '<span class="nav-subtitle">' . esc_html__( 'Previous:', 'adria' ) . '</span> <span class="nav-title">%title</span>', 'next_text' => '<span class="nav-subtitle">' . esc_html__( 'Next:', 'adria' ) . '</span> <span class="nav-title">%title</span>', ) ); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) : comments_template(); endif; endwhile; // End of the loop. ?> </main><!-- #main --> <?php get_footer();
syntax = "proto3"; package categoryapi; service CategoryService { rpc AddCategory(AddCategoryRequest) returns (Category) {} rpc GetCategory(GetCategoryRequest) returns (Category) {} rpc UpdateCategory(UpdateCategoryRequest) returns (UpdateCategoryResponse) {} rpc DeleteCategory(DeleteCategoryRequest) returns (DeleteCategoryResponse) {} rpc ListCategories(ListCategoriesRequest) returns (ListCategoriesResponse) {} } message Category { int32 id = 1; string name = 2; string description = 3; } message AddCategoryRequest { string token = 1; string name = 2; string description = 3; } message GetCategoryRequest { int32 id = 1; } message UpdateCategoryRequest { string token = 1; int32 id = 2; string name = 3; string description = 4; } message UpdateCategoryResponse { bool success = 1; } message DeleteCategoryRequest { string token = 1; int32 id = 2; } message DeleteCategoryResponse { bool success = 1; } message ListCategoriesRequest {} message ListCategoriesResponse { repeated Category categories = 1; } message ApiError { int32 code = 1; string message = 2; }
import React, { useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { NavBar } from "../NavBar/NavBar"; import { search_pokemons } from "../../actions/index"; import "./search.css"; /* import { CardDetail } from "./CardDetail";*/ import { CardsPokemons } from "../CardsPokemons/CardsPokemons"; export const SearchScreen = () => { const img = "https://d26bwjyd9l0e3m.cloudfront.net/wp-content/uploads/2016/08/Pikachu-Gif-Animation.gif"; const dispatch = useDispatch(); const [Pokemon, setPokemon] = useState(""); const e = useSelector((state) => state.searchPok); const handleInputChange = (e) => { e.preventDefault(); setPokemon(e.target.value); }; const onSubmit = (e) => { e.preventDefault(); setPokemon(""); dispatch(search_pokemons(Pokemon)); }; return ( <div className="search-container"> <NavBar /> <div className="search-screen"> <div className="busqueda"> <form onSubmit={(e) => onSubmit(e)}> <input type="text" placeholder="Pikachu is searching a friend..." className="form-imput" value={Pokemon} onChange={(e) => handleInputChange(e)} required={true} /> <input type="submit" value="🔎" className="btn-search" /> </form> <img src={img} alt="no image" /> </div> <div className="resultados"> <h4>Resultados</h4> { <CardsPokemons key={e.id} name={e.name} img={e.img} types={e.types} /> } </div> </div> </div> ); };
import { Ionicons } from "@expo/vector-icons"; import { CommonActions, useNavigation } from "@react-navigation/native"; import React, { useState } from "react"; import { Alert, Button, SafeAreaView, StyleSheet, Text, TextInput, TouchableOpacity, View, } from "react-native"; import { GLOBALS } from "../Globals"; import { Api } from "../utils/Api"; import * as Clipboard from "expo-clipboard"; export const Input = () => { const defaultSessionUrl: string = GLOBALS.TEST_CHECKOUT_SESSION_URL ? GLOBALS.TEST_CHECKOUT_SESSION_URL : ""; const navigation = useNavigation(); const [apiKey, onApiKeyChange] = useState(""); const [customerHandle, onChangeCustomer] = useState(""); const [orderHandle, onChangeOrder] = useState(""); const [sessionUrl, onChangedSession] = useState(defaultSessionUrl); const [sessionId, setId] = useState(""); function getCustomer(): void { Api.getCustomer(customerHandle).then( (handle: string) => { if (!handle) { Alert.alert("Error", "Customer not found"); return; } createChargeSession(handle); }, (error) => { Alert.alert("Error", JSON.stringify(error)); } ); } function getRecentCustomer(): void { Api.getCustomers().then( (customers: any[]) => { if (!customers?.length) { Alert.alert("No customers found"); return; } onChangeCustomer(customers[0].handle as string); Alert.alert( `Added recent customer handle (${new Date(customers[0].created)}):\n`, customers[0].handle ); }, (error) => { Alert.alert("Error", JSON.stringify(error)); } ); } function createChargeSession(customerHandle: string): void { Api.getChargeSession(customerHandle, orderHandle) .then((session: { id: string; url: string; customerHandle: string }) => { onSessionSuccess(session); }) .catch((rejected) => { onSessionError(rejected); }); } function onSessionSuccess(session: { id: string; url: string; customerHandle: string; }): void { Alert.alert("Response", JSON.stringify(session), [ { text: "Enter session", onPress: () => { console.log("Session:", session); onChangeCustomer(session.customerHandle); onChangedSession(session.url); setId(session.id); }, }, ]); } function onSessionError(rejected: any): void { Alert.alert("Error", JSON.stringify(rejected), [ { text: "OK", onPress: () => { console.error("Rejected:", rejected); }, }, ]); } function copyToClipboard(): void { if (sessionUrl && sessionId) { Clipboard.setStringAsync(sessionUrl); Alert.alert("Copied to Clipboard", `${sessionUrl}`); } } return ( <SafeAreaView> <View> <Button title="Reset example" onPress={() => { onApiKeyChange(""); onChangeOrder(""); onChangeCustomer(""); onChangedSession(defaultSessionUrl); setId(""); }} color={"#194c85"} ></Button> </View> {GLOBALS.REEPAY_PRIVATE_API_KEY ? ( <Text style={styles.header}>API key added</Text> ) : ( <View> <Text>Private API Key</Text> <TextInput clearButtonMode="always" style={styles.input} onChangeText={onApiKeyChange} value={apiKey} placeholder="<your private api key>" /> </View> )} <Text>Order handle</Text> <TextInput clearButtonMode="always" style={styles.input} onChangeText={onChangeOrder} value={orderHandle} placeholder="<optional>" /> <Text> Customer handle <Text> </Text> {!customerHandle ? ( <Ionicons name="repeat-outline" size={16} color="#194c85" onPress={getRecentCustomer} /> ) : null} </Text> <View> <TextInput clearButtonMode="always" style={styles.input} onChangeText={onChangeCustomer} value={customerHandle} placeholder="<optional existing customer>" /> </View> <Button title="Generate session" onPress={() => { if (apiKey) { Api.setApiKey(apiKey.trim()); } if (customerHandle) { getCustomer(); } else { createChargeSession(""); } }} color={"#194c85"} disabled={sessionUrl.length > 0} ></Button> <View style={styles.separator} /> <Text>Generated checkout session</Text> <TextInput clearButtonMode="always" style={styles.input} onChangeText={(text: string) => { onChangedSession(text); if (!text) { setId(""); } }} value={sessionUrl} placeholder="https://checkout.reepay.com/#/<id>" /> <TouchableOpacity onPress={copyToClipboard}> <Text style={styles.disabledText}> {sessionId ? sessionId : "<generated session id>"} <Text> </Text> {sessionId ? <Ionicons name="copy-outline" size={12} /> : null} </Text> </TouchableOpacity> <Button title="Create checkout webview" onPress={() => { if (!sessionUrl.startsWith("https://" || "http://")) { Alert.alert("Error", "Url must start with https:// or http://"); onChangedSession(`https://${sessionUrl}`); return; } navigation.dispatch( CommonActions.navigate({ name: "Checkout", params: { previousScreen: "CardCheckoutScreen", url: sessionUrl.trim(), id: sessionId.trim(), }, }) ); }} disabled={!sessionUrl} color={"#194c85"} ></Button> </SafeAreaView> ); }; const styles = StyleSheet.create({ header: { margin: 20, textAlign: "center", color: "#1eaa7d", fontSize: 17, }, input: { width: 300, height: 50, margin: 10, borderWidth: 1, padding: 10, }, separator: { marginTop: 10, marginBottom: 30, borderBottomColor: "#737373", borderBottomWidth: StyleSheet.hairlineWidth, }, disabledText: { width: 300, height: 35, margin: 10, borderWidth: 0.2, borderColor: "#737373", padding: 10, color: "#737373", fontSize: 12, textAlign: "center", }, });
# As expression statement without ; var a1 = 0; loop { if a1 == 3 { break; } std_println(a1); a1 = a1 + 1; } # expect: 0 # expect: 1 # expect: 2 # As expression statement with ; var a2 = 0; loop { if a2 == 3 { break; } std_println(a2); a2 = a2 + 1; }; # expect: 0 # expect: 1 # expect: 2 # As expression with implicit nil value var a3 = 0; var b1 = loop { if a3 == 3 { break; } std_println(a3); a3 = a3 + 1; }; std_println(b1); # expect: 0 # expect: 1 # expect: 2 # expect: nil # As expression with explicit value var a4 = 0; var b2 = loop { if a4 == 3 { break a4; } std_println(a4); a4 = a4 + 1; }; std_println(b2); # expect: 0 # expect: 1 # expect: 2 # expect: 3 # continue var a5 = 0; loop { if a5 == 3 { break; } std_println(a5); a5 = a5 + 1; continue; std_println("bad"); } # expect: 0 # expect: 1 # expect: 2 # Statement in bodies. loop { if true { break; } if true { 1; } else { 2; } } loop { if true { break; } while true { 1;} }
import productModel from "../models/productModel.js"; const addProduct = async (req, res) => { try { const { name, price, image, descrip, about, catogary } = req.body; if (!name || !price || !image || !descrip || !catogary) { return res.status(400).json({ error: "All Fields Are Mandatory" }); } const newProduct = new productModel({ name, price, image, descrip, catogary, about }); await newProduct.save(); return res.status(201).json({ message: "Product added Successfully", product: newProduct }); } catch (error) { console.error("Error adding product:", error); return res.status(500).json({ error: "Internal Server Error" }); } } const getAllProduct = async (req, res) => { try { const products = await productModel.find(); return res.status(200).json({ message: "Get All Products", products }); } catch (error) { res.status(500).json({ error: "Internal server error", details: error }); } }; const getSingleProduct = async (req, res) => { try { const id = req.params.id; const product = await productModel.findById(id).lean(); if (!product) { return res.status(404).json({ error: "Product not available" }); } res.json(product); } catch (error) { console.log("Error from single product id", error); res.status(500).json({ error: "Internal server error" }); } }; export { addProduct, getAllProduct, getSingleProduct };
/* eslint-disable react/prop-types */ import React, { useState } from 'react'; import { Text } from '../../atoms'; import { Column, Flex } from '../../pages/layout'; import styles from './input.module.scss'; import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons'; interface IInputProps extends React.ComponentPropsWithoutRef<'input'> { messagge?: string; status?: 'success' | 'error'; classNameInput?: string; classNameContainer?: string; } interface IInputPropsSubComponent { Password: React.FC<IInputProps>; } const Password: React.FC<IInputProps> = ({ status, messagge, classNameContainer, classNameInput, ...rest }) => { const [visible, setVisible] = useState(false); return ( <Column> <Flex alignItems={'center'} className={`${styles.inputStylePasswordContainer} ${classNameContainer}`} > <input className={`${styles.inputStylePassword} ${classNameInput}`} {...rest} type={visible ? 'text' : 'password'} /> {visible ? ( <EyeOutlined onClick={() => setVisible(false)} /> ) : ( <EyeInvisibleOutlined onClick={() => setVisible(true)} /> )} </Flex> {messagge ? ( <Text className={styles.containerMessage} color={status === 'success' ? 'success' : 'error'} > {messagge} </Text> ) : null} </Column> ); }; const Input: React.FC<IInputProps> & IInputPropsSubComponent = ({ status, messagge, classNameContainer, classNameInput, ...rest }) => { return ( <div className={classNameContainer}> <input className={`${styles.inputStyle} ${classNameInput}`} {...rest} /> {messagge ? ( <Text className={styles.containerMessage} color={status === 'success' ? 'success' : 'error'} > {messagge} </Text> ) : null} </div> ); }; Input.Password = Password; export default Input;
<template> <a-card hoverable class="visit-count"> <a-skeleton active v-if="loading" /> <apexchart ref="count" type=bar height=300 :options="chartOptions" :series="series"/> </a-card> </template> <script> export default { name: 'TrendTop', data () { return { loading: false, series: [{ data: [] }], chartOptions: { chart: { height: 350, type: 'bar', }, plotOptions: { bar: { borderRadius: 10, dataLabels: { position: 'top', }, } }, dataLabels: { enabled: true, formatter: function (val) { return val + "元"; }, offsetY: -20, }, xaxis: { categories: [], position: 'top', axisBorder: { show: false }, axisTicks: { show: false }, tooltip: { enabled: true, } }, yaxis: { axisBorder: { show: false }, axisTicks: { show: false, }, labels: { show: false, formatter: function (val) { return val + "元"; } } } }, } }, mounted () { this.fetch() }, methods: { fetch () { this.loading = true this.$get('/cos/house-price-trend/trend/top').then((r) => { if (r.data == null || r.data.length === 0) { this.loading = false return false } let label = [] let value = [] r.data.forEach(item => { label.push(item.name) value.push(item.trend) }) this.series[0].data = value this.chartOptions.xaxis.categories = label setTimeout(() => { this.loading = false }, 200) }) } } } </script> <style scoped> </style>
package it.polimi.ingsw.client; import it.polimi.ingsw.requests.*; import it.polimi.ingsw.responses.Response; import it.polimi.ingsw.timers.ConnectionClientTimer; import it.polimi.ingsw.view.View; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.rmi.RemoteException; import java.util.List; import java.util.Timer; /**ClientSocket class used to manage the Socket connection to the server.*/ public class ClientSocket implements IClientConnection { /**logger to keep track of events, such as errors and info about parameters*/ private static final Logger fileLog = LogManager.getRootLogger(); /**master used to invoke methods of the ClientController*/ private final ClientController master; /**token used to identify the client to the server*/ private String token; /**ip of the server*/ private final String ip; /** port of the server */ private final int port; private Socket socket; private ObjectInputStream socketIn; private ObjectOutputStream socketOut; /**boolean signalling whether the client is connected or not*/ private boolean amIconnected; private Thread receiving; /**responseDecoder used to decode the responses received from the server via socket * @see ResponseDecoder*/ private ResponseDecoder responseDecoder; /**boolean notReceivingResponse used to wait for a response from the server*/ private boolean notReceivingResponse; /**boolean syn used to know whether the client has received the ping message from the server*/ private boolean syn; private final int synCheckTime = 5000; private Timer synCheckTimer; /**currentView parameter used to invoke the method of the View (GUI or TUI)*/ private View currentView; /**ClientSocket constructor. * @param ip - the server's ip address. * @param port - the server's port. * @param cController - the clientController*/ public ClientSocket(String ip, int port, ClientController cController) throws IOException { this.ip = ip; this.port = port; this.master = cController; this.notReceivingResponse = true; } /**openStreams method creates a new socket and initializes it. Then it starts the startReceiving method*/ public void openStreams() throws IOException { socket = new Socket(ip, port); this.socketOut = new ObjectOutputStream(socket.getOutputStream()); this.socketIn = new ObjectInputStream(socket.getInputStream()); amIconnected= true; startReceiving(); } /**startReceiving method is basically a loop in which the socket keeps listening. Each time something is read * from the stream, it is handled.*/ private void startReceiving() { receiving = new Thread( () -> { Response response = null; do{ response = readResponse(); //if i get a response and the client controller doesn't tell me to close the connection if(response != null && !master.isToClose()){ try{ response.handleResponse(responseDecoder); }catch(RemoteException e){ fileLog.error(e.getMessage()); } } }while(response!=null); } ); receiving.start(); } /** * readResponse method is used to actually read from the socket stream * @return the response message sent by the server socket */ private Response readResponse() { try{ return ((Response) socketIn.readObject()); }catch(ClassNotFoundException e){ //if the serialization went wrong or if the class doesn't exist fileLog.error(e.getMessage()); }catch (IOException e){ fileLog.error(e); //if the connection is lost currentView.printError("Connection lost. Please try again later."); } return null; } /**startClient method is used to start the client. It opens the streams and then calls the userLogin method*/ public void startClient() { try { openStreams(); currentView.displayNotification("Connection successful"); master.userLogin(); } catch (IOException e) { fileLog.error(e); currentView.printError("Connection failed"); currentView.askConnectionServer(); } } /**closeStreams method is used to close the streams*/ public void closeStreams() throws IOException { //closing streams socketIn.close(); socketOut.close(); } /** * setViewClient method is used to set the view (TUI or GUI) of the client * @param cView - the view chosen by the user (TUI or GUI) */ @Override public void setViewClient(View cView) { this.currentView = cView; } /**chooseTiles method is used to create a request with the choice of tiles to be sent to the server. * After sending the request, it begins waiting for a response. * @param tilesChosen - the choice of tiles. * @param token - the token used to identify the client.*/ @Override public synchronized void chooseTiles(String token, List<String> tilesChosen) { setReceivedResponse(true); request(new ChooseTilesRequest(token, tilesChosen)); while(notReceivingResponse){ try { this.wait(); } catch (InterruptedException e) { fileLog.error(e.getMessage()); currentView.printError("Connection error. Please try again later."); } } } /**login method is used to create a login request and pass the username to the server. After sending the request, * it begins waiting for a response. * @param name - username chosen by the client.*/ @Override public synchronized void login(String name) { setReceivedResponse(true); request(new LoginRequest(name)); while(notReceivingResponse){ try{ this.wait(); }catch (InterruptedException e){ fileLog.error(e.getMessage()); currentView.printError("Connection error. Please try again later."); } } } /**request method is used to write the request on the stream * @param request - generic request instance that needs to be sent to the server.*/ private void request(Request request) { fileLog.info("I'm sending a request"); try{ socketOut.writeObject(request); socketOut.reset(); }catch (IOException e){ fileLog.error(e.getMessage()); currentView.printError("Connection error. Please try again later."); } } /** * method setUserToken is used to set a token to a user * @param tokenA - the user token, it is used to recognize a user uniquely */ @Override public void setUserToken(String tokenA) { this.token = tokenA; } /**setReceivedResponse signals whether a response has been received. If so, it stops the waits. * @param b - boolean used to know whether the socket has received a response or not*/ @Override public void setReceivedResponse(boolean b) { notReceivingResponse = b; } /**numberOfPlayers method generates a request to create the waiting room. * @param name - username of the client. * @param tokenA - token used to identify the client who's sending the request. * @param number - number of players for the next match.*/ @Override public synchronized void numberOfPlayers(String name, String tokenA, int number) { fileLog.debug("numberOfPlayers"); setUserToken(tokenA); setReceivedResponse(true); request(new WaitingRoomRequest(tokenA, name, number)); while(notReceivingResponse){ try{ this.wait(); }catch (InterruptedException e){ fileLog.error(e.getMessage()); currentView.printError("Connection error. Please try again later."); } } } /**chooseColumn method creates a request to send the choice of column to the server. * @param column - number of column in which the tiles will be placed.*/ @Override public synchronized void chooseColumn(int column) { setReceivedResponse(true); request(new ColumnRequest(token, column)); while(notReceivingResponse){ try{ this.wait(); }catch (InterruptedException e){ fileLog.error(e.getMessage()); currentView.printError("Connection error. Please try again later."); } } } @Override public void close() { try { closeStreams(); } catch (IOException e) { throw new RuntimeException(e); } } /** * setResponseDecoder method is used to set the response decoder for the client socket * @param responseDecoder - the response decoder */ public void setResponseDecoder(ResponseDecoder responseDecoder) { this.responseDecoder = responseDecoder; } /**isConnected method returns a boolean signalling whether the client is connected or not*/ @Override public boolean isConnected() { return amIconnected; } /**setConnected method is used to keep track of whether the client has lost connection to the server * @param b - boolean signalling whether the client is connected to the server or not*/ @Override public void setConnected(boolean b) { amIconnected = b; } /**rearrangeTiles method generates a request to send the re-arranged tiles to the server. * @param userToken - token used to identify the client. * @param multipleChoiceNumber - list of the positions of the re-arranged tiles.*/ @Override public synchronized void rearrangeTiles(String userToken, List<String> multipleChoiceNumber) { setReceivedResponse(true); request(new RearrangeTilesRequest(userToken, multipleChoiceNumber)); while(notReceivingResponse){ try{ this.wait(); }catch (InterruptedException e){ fileLog.error(e.getMessage()); currentView.printError("Connection error. Please try again later."); } } } /**sendChat method used to generate a chat request. * @param receiver - the receiver of the chat message. * @param username - the sender of the chat message. * @param toString - the text of the message.*/ @Override public void sendChat(String username, String toString, String receiver) { setReceivedResponse(true); request(new ChatMessageRequest(username, toString, receiver)); } /**quit method used to quit the game. * @param token - token used to identify the client.*/ @Override public void quit(String token) { setReceivedResponse(true); request(new QuitRequest(token)); try { closeStreams(); } catch (IOException e) { throw new RuntimeException(e); } } /**setSyn method is used to set the value syn to true when the client received a ping from the server*/ @Override public void setSyn(boolean b) { syn = b; } /**isSyn method is used to check whether the client has received a ping from the server*/ @Override public boolean isSyn() { return syn; } /**method setSynCheckTimer starts a timer waiting for the ping from the server. When a ping is received, the timer * is reset. If the timer expires and no ping has been received by the client, it means that the server * is unreachable * @param startTimer - boolean signalling whether to start the timer or to reset it*/ @Override public void setSynCheckTimer(boolean startTimer) { if(startTimer){ synCheckTimer = new Timer(); synCheckTimer.scheduleAtFixedRate(new ConnectionClientTimer(this), (synCheckTime/2)+synCheckTime, synCheckTime); } else{ synCheckTimer.purge(); synCheckTimer.cancel(); } } /**method sendAck is used to send a response ack message to the server after receiving a ping*/ @Override public void sendAck() { request(new AckPing(token)); } }
/* * Lilith - a log event viewer. * Copyright (C) 2007-2017 Joern Huxhorn * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.huxhorn.lilith.services.clipboard; import de.huxhorn.lilith.services.BasicFormatter; import java.io.Serializable; public interface ClipboardFormatter extends BasicFormatter,Serializable { /** * The name of this formatter. * It is used as the name of the menu item. * * @return the name of this formatter. */ String getName(); /** * The description of this formatter. * It is used as the tooltip in the menu. * * @return the description of this formatter. */ String getDescription(); /** * * @return the accelerator of this formatter, can be null. */ String getAccelerator(); default Integer getMnemonic() { return null; } /** * Returns true, if this is a native Lilith formatter, i.e. the formatter is part * of Lilith itself so a match against Lilith accelerator keystrokes should not be * considered a problem. * * Default implementation returns false. * * @return true, if this is a native Lilith formatter. false otherwise */ default boolean isNative() { return false; } }
/* * * This source code is part of * * G R O M A C S * * GROningen MAchine for Chemical Simulations * * VERSION 3.2.0 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others. * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team, * check out http://www.gromacs.org for more information. * 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. * * If you want to redistribute modifications, please consider that * scientific software is very special. Version control is crucial - * bugs must be traceable. We will be happy to consider code for * inclusion in the official distribution, but derived work must not * be called official GROMACS. Details are found in the README & COPYING * files - if they are missing, get the official version at www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the papers on the package - you can find them in the top README file. * * For more info, check our website at http://www.gromacs.org * * And Hey: * Gromacs Runs On Most of All Computer Systems */ #ifndef _oenv_h #define _oenv_h #include "typedefs.h" #ifdef __cplusplus extern "C" { #endif #if 0 /* avoid screwing up indentation */ } #endif /* output_env member functions */ /* The output_env structure holds information about program name, cmd line, default times, etc. There are still legacy functions for the program name, and the command line, but the output_env versions are now preferred.*/ typedef enum { timeNULL, time_fs, time_ps, time_ns, time_us, time_ms, time_s } time_unit_t; /* the time units. For the time being, ps means no conversion. */ typedef enum { exvgNULL, exvgXMGRACE, exvgXMGR, exvgNONE } xvg_format_t; /* the xvg output formattings */ struct output_env { time_unit_t time_unit; /* the time unit, enum defined in statuti.h */ gmx_bool view; /* view of file requested */ xvg_format_t xvg_format; /* xvg output format, enum defined in statutil.h */ int verbosity; /* The level of verbosity for this program */ int debug_level; /* the debug level */ char *program_name; /* the program name */ char *cmd_line; /* the re-assembled command line */ }; void output_env_init(output_env_t oenv, int argc, char *argv[], time_unit_t tmu, gmx_bool view, xvg_format_t xvg_format, int verbosity, int debug_level); /* initialize an output_env structure, setting the command line, the default time value a gmx_boolean view that is set to TRUE when the user requests direct viewing of graphs, the graph formatting type, the verbosity, and debug level */ void output_env_init_default(output_env_t oenv); /* initialize an output_env structure, with reasonable default settings. (the time unit is set to time_ps, which means no conversion). */ void output_env_done(output_env_t oenv); /* free memory allocated for an output_env structure. */ int output_env_get_verbosity(const output_env_t oenv); /* return the verbosity */ int output_env_get_debug_level(const output_env_t oenv); /* return the debug level */ const char *output_env_get_time_unit(const output_env_t oenv); /* return time unit (e.g. ps or ns) */ const char *output_env_get_time_label(const output_env_t oenv); /* return time unit label (e.g. "Time (ps)") */ const char *output_env_get_xvgr_tlabel(const output_env_t oenv); /* retrun x-axis time label for xmgr */ real output_env_get_time_factor(const output_env_t oenv); /* return time conversion factor from ps (i.e. 1e-3 for ps->ns) */ real output_env_get_time_invfactor(const output_env_t oenv); /* return inverse time conversion factor from ps (i.e. 1e3 for ps->ns) */ real output_env_conv_time(const output_env_t oenv, real time); /* return converted time */ void output_env_conv_times(const output_env_t oenv, int n, real *time); /* convert array of times */ gmx_bool output_env_get_view(const output_env_t oenv); /* Return TRUE when user requested viewing of the file */ xvg_format_t output_env_get_xvg_format(const output_env_t oenv); /* Returns enum (see above) for xvg output formatting */ const char *output_env_get_program_name(const output_env_t oenv); /* return the program name */ const char *output_env_get_cmd_line(const output_env_t oenv); /* return the command line */ const char *output_env_get_short_program_name(const output_env_t oenv); /* get the short version (without path component) of the program name */ #ifdef __cplusplus } #endif #endif
<!doctype html><html lang="zh-tw"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="物體碰撞前後總動能不變稱為彈性碰撞(Elastic collision),在維基百科〈Elastic collision〉中可以查詢到,二維的彈性碰撞在位置及速度以向量表示時,公式會如下,其中角括號表..."> <meta property="og:locale" content="zh_TW"> <meta property="og:title" content="彈性碰撞"> <meta property="og:type" content="article"> <meta property="og:url" content="https://openhome.cc/Gossip/P5JS/Collision.html"> <meta property="og:image" content="https://openhome.cc/Gossip/images/caterpillar_small.jpg"> <meta property="og:site_name" content="OPENHOME.CC"> <meta property="og:description" content="物體碰撞前後總動能不變稱為彈性碰撞(Elastic collision),在維基百科〈Elastic collision〉中可以查詢到,二維的彈性碰撞在位置及速度以向量表示時,公式會如下,其中角括號表..."> <title>彈性碰撞</title> <link rel="stylesheet" href="../css/pure-0.6.0/pure-min.css"> <!--[if lte IE 8]> <link rel="stylesheet" href="../css/layouts/side-menu-old-ie.css"> <![endif]--> <!--[if gt IE 8]><!--> <link rel="stylesheet" href="../css/layouts/side-menu.css"> <!--<![endif]--> <link rel="stylesheet" href="../css/caterpillar.css"> <script async src="../google-code-prettify/run_prettify.js"></script> <!-- 網頁層級廣告 --><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle =window.adsbygoogle || []).push({google_ad_client: "ca-pub-9750319131714390",enable_page_level_ads: true });</script></head> <body> <div id="layout"> <!-- Menu toggle --> <a href="Collision.html#menu" id="menuLink" class="menu-link"> <!-- Hamburger icon --> <span></span> </a> <div id="menu"> <div class="pure-menu"> <a class="pure-menu-heading" href="index.html">回 p5.js</a> <ul class="pure-menu-list"> <li class="pure-menu-item"><br><div class="social" style="text-align: center;"><a href="http://twitter.com/caterpillar"><img title="Twitter" alt="Twitter" src="../images/twitter.png"></a> <a href="http://www.facebook.com/openhome.cc"><img title="Facebook" alt="Facebook" src="../images/facebook.png"></a></div><br> <div id="search box"><script>(function() {var cx = 'partner-pub-9750319131714390:3926766884';var gcse = document.createElement('script');gcse.type = 'text/javascript';gcse.async = true;gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx;var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(gcse, s);})();</script><gcse:searchbox-only></gcse:searchbox-only></div><br><div class="ad" style="text-align: center;"><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- 2015 新版型 160 x 600 廣告 --> <ins class="adsbygoogle" style="display:inline-block;width:160px;height:600px" data-ad-client="ca-pub-9750319131714390" data-ad-slot="3747048883"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script></div></li> </ul> </div> </div> <main id="main"> <header class="header"> <h1>彈性碰撞</h1> </header> <article class="content"> <br><div class="ad-3" style="text-align: center;"><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><!-- 2015 新版型回應式廣告 --><ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-9750319131714390" data-ad-slot="7104125683" data-ad-format="auto"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div> <p>物體碰撞前後總動能不變稱為彈性碰撞(Elastic collision),在維基百科〈<a href="https://en.wikipedia.org/wiki/Elastic_collision">Elastic collision</a>〉中可以查詢到,二維的彈性碰撞在位置及速度以向量表示時,公式會如下,其中角括號表示向量內積:</p> <p><div class="pure-g"><div class="pure-u-1"><img class="pure-img-responsive" src="images/Collision-1.JPG" alt="彈性碰撞" /></div></div></p> <p>根據這個公式,可以在 <code>Body</code> 定義 <code>collideWith</code> 方法:</p> <pre class="prettyprint"><code lang="javascript">class Body { constructor(coordinate, velocity, mass = 1) { this.coordinate = coordinate; this.velocity = velocity; this.mass = mass; } ... collideWith(body) { const d = sub(this.coordinate, body.coordinate); const m = body.mass / (this.mass + body.mass); this.velocity = sub( this.velocity, d.mult( 2 * m / pow(d.mag(), 2) * p5.Vector.dot( sub(this.velocity, body.velocity), sub(this.coordinate, body.coordinate) ) ) ); } ... } </code></pre> <p>問題在於如何判斷何時發生碰撞?直覺的想法是兩個圓的圓心距離等於半徑時,可惜的是,如同〈<a href="Bounce.html">邊界反彈</a>〉談過的,因為影格在時間上是不連續的,真正的碰撞時間可能發生在影格之間,也就是兩個圓的圓心距離等於半徑時可能發生在影格之間,這你是要怎麼呼叫 <code>collideWith</code> 呢?</p> <p>那就在下個影格時,看看兩個圓的圓心距離是否小於等於半徑呢?例如:</p> <script type="text/p5" data-p5-version="1.1.9" data-height="400" data-preview-width="400">let c1; let c2; function setup() { createCanvas(300, 300); const r1 = 20; const r2 = 25; c1 = new Circle( new Body( createVector(width / 2 - r2 * 3, height / 4), createVector(3, 2), PI * r1 * r1 ), r1 ); c2 = new Circle( new Body( createVector(width / 2, height / 4), createVector(0, 0), PI * r2 * r2 ), r2 ); } function draw() { background(220); c1.update(); c2.update(); checkCollision(c1, c2); checkEdges(c1); checkEdges(c2); c1.draw(); c2.draw(); } function checkCollision(c1, c2) { const b1 = c1.body.copy(); const b2 = c2.body.copy(); if(p5.Vector.sub(b1.coordinate, b2.coordinate).mag() <= (c1.radius + c2.radius)) { c1.body.collideWith(b2); c2.body.collideWith(b1); } } class Body { constructor(coordinate, velocity, mass = 1) { this.coordinate = coordinate; this.velocity = velocity; this.mass = mass; } applyForce(force) { this.velocity.add(force.acceleration); } collideWith(body) { const d = p5.Vector.sub(this.coordinate, body.coordinate); const m = body.mass / (this.mass + body.mass); this.velocity = p5.Vector.sub( this.velocity, d.mult( 2 * m / pow(d.mag(), 2) * p5.Vector.dot( p5.Vector.sub(this.velocity, body.velocity), p5.Vector.sub(this.coordinate, body.coordinate) ) ) ); } update() { this.coordinate.add(this.velocity); } copy() { return new Body( this.coordinate.copy(), this.velocity.copy(), this.mass ); } } function checkEdges(circle) { const r = circle.radius; const body = circle.body; const {x, y} = body.coordinate; if(x + r > width) { const nx = 2 * width - x - 2 * r; body.coordinate.x = nx; body.velocity.mult([-1, 1]); } if(x - r < 0) { const nx = 2 * r - x; body.coordinate.x = nx; body.velocity.mult([-1, 1]); } if(y + r > height) { const ny = 2 * height - y - 2 * r; body.coordinate.y = ny; body.velocity.mult([1, -1]); } if(y - r < 0) { const ny = 2 * r - y; body.coordinate.y = ny; body.velocity.mult([1, -1]); } } class Shape { constructor(body) { this.body = body; } update() { this.body.update(); } } class Circle extends Shape { constructor(body, radius) { super(body); this.radius = radius; } draw() { circle(this.body.coordinate.x, this.body.coordinate.y, 2 * this.radius); } } class Force { constructor(mass, acceleration) { this.mass = mass; this.acceleration = acceleration; } } </script> <p>乍看是還行,不過程式運行一段時間後,可能會發生兩個圓碰撞後糾纏在一起的情況,這是因為兩個圓其實是彼此穿透,然後才碰撞交換動能,在接下來的影格以碰撞後的速度移動後,移動距離不夠,造成兩個圓仍然彼此穿透,這時又判斷是該發生碰撞了…結果就一直黏在一起了…XD</p> <p>解決的方式其實類似〈<a href="Bounce.html">邊界反彈</a>〉的出發點,穿透後必須自行修正座標,然而顯然地,這邊不能單純地用反射的方式來計算,怎麼辦呢?</p> <p>這邊的做法是,若判斷兩個圓的圓心距離小於等於半徑和時,表示直接繪製的話,會是穿透的狀態,這時計算上一影格時的位置:</p> <p><div class="pure-g"><div class="pure-u-1"><img class="pure-img-responsive" src="images/Collision-2.JPG" alt="彈性碰撞" /></div></div></p> <p>接著計算這時圓心間的距離,兩個圓的相對速度大小,求得接下來還要多久會發生碰撞,以程式碼表示的話會是:</p> <pre class="prettyprint"><code lang="javascript">// sub 是 p5.Vector.sub 的封裝 function timeBeforeCollision(b1, b2, d, tolerant) { // 退回 const preC1 = sub(b1.coordinate, b1.velocity); const preC2 = sub(b2.coordinate, b2.velocity); // 相對速度 const rv = sub(b1.velocity, b2.velocity).mag(); // 還要多久碰撞 return (sub(preC1, preC2).mag() + tolerant - d) / rv; } </code></pre> <p>因為浮點數計算會有誤差,這會導致糾纏還是會發生一下,這部份可以用 <code>tolerant</code> 設定容許的誤差來克服。</p> <p>若求得的時間差是 <code>t</code>,接下來就可以求得兩個圓發生碰撞時的圓心位置:</p> <pre class="prettyprint"><code lang="javascript">function coordinateAfterTime(b, t) { return add(b.coordinate, p5.Vector.mult(b.velocity, t)); } function collisionCoordinate(b, t) { const preC = coordinateAfterTime(b, -1) return add(preC, p5.Vector.mult(b.velocity, t)); } </code></pre> <p>將圓移動至求得的位置後,就可以呼叫 <code>collideWith</code> 進行動能交換了,接下來離下個影格的時間還剩 <code>1 - t</code>(在我們模擬的世界中,影格間的時間就是一個時間單位),利用這段時間,以及動能交換後的速度來移動,就會是碰撞後,在下個影格時該有的位置:</p> <pre class="prettyprint"><code lang="javascript">// 用剩餘時間移動 c1.body.coordinate = coordinateAfterTime(b1, 1 - t); c2.body.coordinate = coordinateAfterTime(b2, 1 - t); </code></pre> <p>記得!碰撞的時間發生在兩個影格間時,你是看不到兩個圓接觸的畫面的,只會看到碰撞後下個影格時該在的位置,底下是完整的程式示範:</p> <script type="text/p5" data-p5-version="1.1.9" data-height="400" data-preview-width="400">let c1; let c2; function setup() { createCanvas(300, 300); const r1 = 20; const r2 = 25; c1 = new Circle( new Body( createVector(width / 2 - r2 * 3, height / 4), createVector(3, 2), PI * r1 * r1 ), r1 ); c2 = new Circle( new Body( createVector(width / 2, height / 4), createVector(0, 0), PI * r2 * r2 ), r2 ); } function draw() { background(220); c1.update(); c2.update(); checkCollision(c1, c2); checkEdges(c1); checkEdges(c2); c1.draw(); c2.draw(); } function add(v1, v2) { return p5.Vector.add(v1, v2); } function sub(v1, v2) { return p5.Vector.sub(v1, v2); } function checkCollision(c1, c2, tolerant = 0.5) { const b1 = c1.body.copy(); const b2 = c2.body.copy(); const d = c1.radius + c2.radius; if(sub(b1.coordinate, b2.coordinate).mag() <= d) { // 還要多久碰撞 const t = timeBeforeCollision(b1, b2, d, tolerant); // 碰撞時的位置 c1.body.coordinate = b1.coordinate = collisionCoordinate(b1, t); c2.body.coordinate = b2.coordinate = collisionCoordinate(b2, t); // 碰撞 c1.body.collideWith(b2); c2.body.collideWith(b1); // 用剩餘時間移動 c1.body.coordinate = coordinateAfterTime(b1, 1 - t); c2.body.coordinate = coordinateAfterTime(b2, 1 - t); } } function timeBeforeCollision(b1, b2, d, tolerant) { // 退回 const preC1 = sub(b1.coordinate, b1.velocity); const preC2 = sub(b2.coordinate, b2.velocity); // 相對速度 const rv = sub(b1.velocity, b2.velocity).mag(); // 還要多久碰撞 return (sub(preC1, preC2).mag() + tolerant - d) / rv; } function coordinateAfterTime(b, t) { return add(b.coordinate, p5.Vector.mult(b.velocity, t)); } function collisionCoordinate(b, t) { const preC = coordinateAfterTime(b, -1) return add(preC, p5.Vector.mult(b.velocity, t)); } function checkEdges(circle) { const r = circle.radius; const body = circle.body; const {x, y} = body.coordinate; if(x + r > width) { const nx = 2 * width - x - 2 * r; body.coordinate.x = nx; body.velocity.mult([-1, 1]); } if(x - r < 0) { const nx = 2 * r - x; body.coordinate.x = nx; body.velocity.mult([-1, 1]); } if(y + r > height) { const ny = 2 * height - y - 2 * r; body.coordinate.y = ny; body.velocity.mult([1, -1]); } if(y - r < 0) { const ny = 2 * r - y; body.coordinate.y = ny; body.velocity.mult([1, -1]); } } class Body { constructor(coordinate, velocity, mass = 1) { this.coordinate = coordinate; this.velocity = velocity; this.mass = mass; } applyForce(force) { this.velocity.add(force.acceleration); } collideWith(body) { const d = sub(this.coordinate, body.coordinate); const m = body.mass / (this.mass + body.mass); this.velocity = sub( this.velocity, d.mult( 2 * m / pow(d.mag(), 2) * p5.Vector.dot( sub(this.velocity, body.velocity), sub(this.coordinate, body.coordinate) ) ) ); } update() { this.coordinate.add(this.velocity); } copy() { return new Body( this.coordinate.copy(), this.velocity.copy(), this.mass ); } } class Shape { constructor(body) { this.body = body; } update() { this.body.update(); } } class Circle extends Shape { constructor(body, radius) { super(body); this.radius = radius; } draw() { circle(this.body.coordinate.x, this.body.coordinate.y, 2 * this.radius); } } class Force { constructor(mass, acceleration) { this.mass = mass; this.acceleration = acceleration; } } </script> <p>可以將以上的 <code>checkCollision</code>,擴展為支援多個圓:</p> <pre class="prettyprint"><code lang="javascript">function checkCollision(circles, tolerant = 0.5) { const copied = circles.map(c =&gt; c.body.copy()); for(let i = 0; i &lt; copied.length; i++) { const b1 = circles[i].body; for(let j = 0; j &lt; copied.length; j++) { if(i != j) { // 不與自身碰撞 const b2 = copied[j]; const d = circles[i].radius + circles[j].radius; if(sub(b1.coordinate, b2.coordinate).mag() &lt;= d) { // 還要多久碰撞 const t = timeBeforeCollision(b1, b2, d, tolerant); // 碰撞時的位置 b1.coordinate = collisionCoordinate(b1, t); b2.coordinate = collisionCoordinate(b2, t); circles[i].body.collideWith(b2); // 用剩餘時間移動 b1.coordinate = coordinateAfterTime(b1, 1 - t); } } } } } </code></pre> <p>底下是四個圓的模擬:</p> <script type="text/p5" data-p5-version="1.1.9" data-height="400" data-preview-width="400">let circles; function setup() { createCanvas(300, 300); const r1 = 15; const r2 = 20; const r3 = 25; const r4 = 30; circles = [ new Circle( new Body( createVector(width / 2 - r2 * 3, height / 4), createVector(3, 2), PI * r1 * r1 ), r1 ), new Circle( new Body( createVector(width / 2, height / 4), createVector(2, 3), PI * r2 * r2 ), r2 ), new Circle( new Body( createVector(width / 2, height / 2), createVector(1, 2), PI * r3 * r3 ), r3 ), new Circle( new Body( createVector(width * 1.5, height * 1.5), createVector(-1, 2), TWO_PI * r4 ), r4 ) ]; } function draw() { background(220); circles.forEach(c => c.update()); checkCollision(circles); circles.forEach(c => checkEdges(c)); circles.forEach(c => c.draw()); } function add(v1, v2) { return p5.Vector.add(v1, v2); } function sub(v1, v2) { return p5.Vector.sub(v1, v2); } function checkCollision(circles, tolerant = 0.5) { const copied = circles.map(c => c.body.copy()); for(let i = 0; i < copied.length; i++) { const b1 = circles[i].body; for(let j = 0; j < copied.length; j++) { if(i != j) { const b2 = copied[j]; const d = circles[i].radius + circles[j].radius; if(sub(b1.coordinate, b2.coordinate).mag() <= d) { const t = timeBeforeCollision(b1, b2, d, tolerant); b1.coordinate = collisionCoordinate(b1, t); b2.coordinate = collisionCoordinate(b2, t); circles[i].body.collideWith(b2); b1.coordinate = coordinateAfterTime(b1, 1 - t); } } } } } function timeBeforeCollision(b1, b2, d, tolerant) { const preC1 = sub(b1.coordinate, b1.velocity); const preC2 = sub(b2.coordinate, b2.velocity); const rv = sub(b1.velocity, b2.velocity).mag(); return (sub(preC1, preC2).mag() + tolerant - d) / rv; } function coordinateAfterTime(b, t) { return add(b.coordinate, p5.Vector.mult(b.velocity, t)); } function collisionCoordinate(b, t) { const preC = coordinateAfterTime(b, -1) return add(preC, p5.Vector.mult(b.velocity, t)); } function checkEdges(circle) { const r = circle.radius; const body = circle.body; const {x, y} = body.coordinate; if(x + r > width) { const nx = 2 * width - x - 2 * r; body.coordinate.x = nx; body.velocity.mult([-1, 1]); } if(x - r < 0) { const nx = 2 * r - x; body.coordinate.x = nx; body.velocity.mult([-1, 1]); } if(y + r > height) { const ny = 2 * height - y - 2 * r; body.coordinate.y = ny; body.velocity.mult([1, -1]); } if(y - r < 0) { const ny = 2 * r - y; body.coordinate.y = ny; body.velocity.mult([1, -1]); } } class Body { constructor(coordinate, velocity, mass = 1) { this.coordinate = coordinate; this.velocity = velocity; this.mass = mass; } applyForce(force) { this.velocity.add(force.acceleration); } collideWith(body) { const d = sub(this.coordinate, body.coordinate); const m = body.mass / (this.mass + body.mass); this.velocity = sub( this.velocity, d.mult( 2 * m / pow(d.mag(), 2) * p5.Vector.dot( sub(this.velocity, body.velocity), sub(this.coordinate, body.coordinate) ) ) ); } update() { this.coordinate.add(this.velocity); } copy() { return new Body( this.coordinate.copy(), this.velocity.copy(), this.mass ); } } class Shape { constructor(body) { this.body = body; } update() { this.body.update(); } } class Circle extends Shape { constructor(body, radius) { super(body); this.radius = radius; } draw() { circle(this.body.coordinate.x, this.body.coordinate.y, 2 * this.radius); } } class Force { constructor(mass, acceleration) { this.mass = mass; this.acceleration = acceleration; } } </script> <p>來點有趣的事好了,如果有個圓是被釘死而無法撼動的話會怎樣呢?如果自身就是無法撼動的圓,就不用動態交換,也就是 <code>collideWith</code> 直接 <code>return</code>,如果碰撞的對象無法撼動,可以將對方的質量當成無限大來看,也就是碰撞公式的 <code>m2/(m1 + m2)</code>,也就是 <code>1 / (m1/m2 + 1)</code> 中的 <code>m2</code> 會是無限大,這時結果就是 1。</p> <pre class="prettyprint"><code lang="javascript">class Body { constructor(coordinate, velocity, mass = 1, shakable = true) { this.coordinate = coordinate; this.velocity = velocity; this.mass = mass; this.shakable = shakable; } … collideWith(body) { if(!this.shakable) { return; } const d = sub(this.coordinate, body.coordinate); const m = body.shakable ? body.mass / (this.mass + body.mass) : 1; this.velocity = sub( this.velocity, d.mult( 2 * m / pow(d.mag(), 2) * p5.Vector.dot( sub(this.velocity, body.velocity), sub(this.coordinate, body.coordinate) ) ) ); } … } </code></pre> <p>結果就是,當一個圓撞上一個無法撼動的圓時,就是直接反彈,來看看模擬結果:</p> <script type="text/p5" data-p5-version="1.1.9" data-height="400" data-preview-width="400">let circles; function setup() { createCanvas(300, 300); const r1 = 15; const r2 = 20; const r3 = 25; const r4 = 30; circles = [ new Circle( new Body( createVector(width / 2 - r2 * 3, height / 4), createVector(3, 2), PI * r1 * r1 ), r1 ), new Circle( new Body( createVector(width / 2, height / 4), createVector(2, 3), PI * r2 * r2 ), r2 ), new Circle( new Body( createVector(width / 2, height / 2), createVector(0, 0), PI * r3 * r3, false ), r3 ), new Circle( new Body( createVector(width * 1.5, height * 1.5), createVector(-1, 2), TWO_PI * r4 ), r4 ) ]; } function draw() { background(220); circles.forEach(c => c.update()); checkCollision(circles); circles.forEach(c => checkEdges(c)); circles.forEach(c => c.draw()); } function add(v1, v2) { return p5.Vector.add(v1, v2); } function sub(v1, v2) { return p5.Vector.sub(v1, v2); } function checkCollision(circles, tolerant = 0.5) { const copied = circles.map(c => c.body.copy()); for(let i = 0; i < copied.length; i++) { const b1 = circles[i].body; for(let j = 0; j < copied.length; j++) { if(i != j) { const b2 = copied[j]; const d = circles[i].radius + circles[j].radius; if(sub(b1.coordinate, b2.coordinate).mag() <= d) { const t = timeBeforeCollision(b1, b2, d, tolerant); b1.coordinate = collisionCoordinate(b1, t); b2.coordinate = collisionCoordinate(b2, t); circles[i].body.collideWith(b2); b1.coordinate = coordinateAfterTime(b1, 1 - t); } } } } } function timeBeforeCollision(b1, b2, d, tolerant) { const preC1 = sub(b1.coordinate, b1.velocity); const preC2 = sub(b2.coordinate, b2.velocity); const rv = sub(b1.velocity, b2.velocity).mag(); return (sub(preC1, preC2).mag() + tolerant - d) / rv; } function coordinateAfterTime(b, t) { return add(b.coordinate, p5.Vector.mult(b.velocity, t)); } function collisionCoordinate(b, t) { const preC = coordinateAfterTime(b, -1) return add(preC, p5.Vector.mult(b.velocity, t)); } function checkEdges(circle) { const r = circle.radius; const body = circle.body; const {x, y} = body.coordinate; if(x + r > width) { const nx = 2 * width - x - 2 * r; body.coordinate.x = nx; body.velocity.mult([-1, 1]); } if(x - r < 0) { const nx = 2 * r - x; body.coordinate.x = nx; body.velocity.mult([-1, 1]); } if(y + r > height) { const ny = 2 * height - y - 2 * r; body.coordinate.y = ny; body.velocity.mult([1, -1]); } if(y - r < 0) { const ny = 2 * r - y; body.coordinate.y = ny; body.velocity.mult([1, -1]); } } class Body { constructor(coordinate, velocity, mass = 1, shakable = true) { this.coordinate = coordinate; this.velocity = velocity; this.mass = mass; this.shakable = shakable; } applyForce(force) { this.velocity.add(force.acceleration); } collideWith(body) { if(!this.shakable) { return; } const d = sub(this.coordinate, body.coordinate); const m = body.shakable ? body.mass / (this.mass + body.mass) : 1; this.velocity = sub( this.velocity, d.mult( 2 * m / pow(d.mag(), 2) * p5.Vector.dot( sub(this.velocity, body.velocity), sub(this.coordinate, body.coordinate) ) ) ); } update() { this.coordinate.add(this.velocity); } copy() { return new Body(this.coordinate.copy(), this.velocity.copy(), this.mass, this.shakable); } } class Shape { constructor(body) { this.body = body; } update() { this.body.update(); } } class Circle extends Shape { constructor(body, radius) { super(body); this.radius = radius; } draw() { circle(this.body.coordinate.x, this.body.coordinate.y, 2 * this.radius); } } class Force { constructor(mass, acceleration) { this.mass = mass; this.acceleration = acceleration; } } </script> <p>一個有趣的結果是,如果圓無法撼動,它又有速度會如何?這像是有個被釘在移動帶的圓,可以移動,但其他圓無法撼動它,在其他圓撞上無法撼動的圓時,無法撼動的圓基於自身速度與質量的動能,會附加至撞上的圓,這些圓自身的動能,又會被反射回自身,結果就會越來越快。</p> <p>這並不是奇怪的結果,被釘在移動帶的圓,就相當於移動帶在提供穩定的動能,其他圓撞上後會吸收這些動能,結果就會越來越快。</p> <p>如果你想要一個會移動的圓,又不想要撞上它的圓越來越快,就是讓該圓無法撼動,速度為 0,每次的影格都直接改變該圓座標就可以了。</p> <br><br><div class="ad336-280" style="text-align: center;"><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><!-- 2015 新版型廣告 336 x 280 --><ins class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-9750319131714390" data-ad-slot="9976409681"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div><br><div class="recommend" style="text-align: center;"><hr><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><!-- 自動大小回應相符內容 --><ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-9750319131714390" data-ad-slot="4953478487" data-ad-format="autorelaxed"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div> </article> </main> </div></body> </html> <script src="https://toolness.github.io/p5.js-widget/p5-widget.js"></script> <script src="../js/ui.js"></script> <div class="analytics"><script async src="https://www.googletagmanager.com/gtag/js?id=G-QVQQYFSC8J"></script><script>window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', 'G-QVQQYFSC8J');</script></div>
package com.metalbear.mirrord import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationType private const val NOTIFY_AFTER: Int = 100 private const val NOTIFY_EVERY: Int = 30 private const val COUNTER_KEY: String = "mirrordForTeamsCounter" private const val DEPLOYMENT_EXEC_MESSAGE: String = "When targeting multi-pod deployments, mirrord impersonates the first pod in the deployment. Support for multi-pod impersonation requires the mirrord operator, which is part of mirrord for Teams." private const val REGULAR_EXEC_MESSAGE: String = "For more features of mirrord, including multi-pod impersonation, check out mirrord for Teams." class MirrordRunCounter(private val service: MirrordProjectService) { private fun showNotification(message: String) { service.notifier.notification(message, NotificationType.INFORMATION).withLink("Try it now", MIRRORD_FOR_TEAMS_URL).withDontShowAgain(MirrordSettingsState.NotificationId.MIRRORD_FOR_TEAMS).fire() } fun bump(isDeploymentExec: Boolean) { val pc = PropertiesComponent.getInstance() val previousRuns = pc.getInt(COUNTER_KEY, 0) pc.setValue(COUNTER_KEY, (previousRuns + 1).toString()) if (isDeploymentExec) { this.showNotification(DEPLOYMENT_EXEC_MESSAGE) } else if (previousRuns >= NOTIFY_AFTER) { if (previousRuns == NOTIFY_AFTER || (previousRuns - NOTIFY_AFTER) % NOTIFY_EVERY == 0) { this.showNotification(REGULAR_EXEC_MESSAGE) } } } }
import PropTypes from 'prop-types'; import { useEffect, useState } from 'react'; import { useLocation } from 'react-router-dom'; // @mui import { styled, alpha } from '@mui/material/styles'; import { Box, Link, Drawer, Typography, Avatar } from '@mui/material'; // mock // hooks import useResponsive from '../../../hooks/useResponsive'; // components import Logo from '../../../components/logo'; import Scrollbar from '../../../components/scrollbar'; import NavSection from '../../../components/nav-section'; // // import navConfig from './configManager'; import { useSelector } from 'react-redux'; import { selectCurrentRoles, selectCurrentEmail, selectCurrentUser } from '../../../redux/features/auth/authSlice'; import navConfigAdmin from './configAdmin'; import navConfigManager from './configManager'; import navConfigBank from './configBank'; import * as Constants from "../../../Constants/constants" // ---------------------------------------------------------------------- const NAV_WIDTH = 310; const StyledAccount = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', padding: theme.spacing(2, 2.5), borderRadius: Number(theme.shape.borderRadius) * 1.5, backgroundColor: alpha(theme.palette.grey[500], 0.12), })); // ---------------------------------------------------------------------- Nav.propTypes = { openNav: PropTypes.bool, onCloseNav: PropTypes.func, }; export default function Nav({ openNav, onCloseNav }) { const { pathname } = useLocation(); const roles = useSelector(selectCurrentRoles); const email =useSelector(selectCurrentEmail) const user = useSelector(selectCurrentUser) const isDesktop = useResponsive('up', 'lg'); const [navConfiguration,setNavConfiguration] = useState(); const navigationConfiguration =()=>{ if(roles.includes("ADMIN")) setNavConfiguration(navConfigAdmin) else if(roles.includes("STORE_MANAGER")) setNavConfiguration(navConfigManager) else if(roles.includes("BANK_AGENT")) setNavConfiguration(navConfigBank) else console.log("no access") } useEffect(()=>{ navigationConfiguration() },roles) useEffect(() => { if (openNav) { onCloseNav(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [pathname]); const renderContent = ( <Scrollbar sx={{ height: 1, '& .simplebar-content': { height: 1, display: 'flex', flexDirection: 'column' }, }} > <Box sx={{ px: 2.5, py: 3, display: 'inline-flex' }}> {/* <Logo /> */} </Box> <Box sx={{ mb: 5, mx: 2.5 }}> <Link underline="none"> <StyledAccount> {/* <Avatar src={account.photoURL} alt="photoURL" /> */} <Avatar src={user.avatar?Constants.BASE_URL+user.avatar.split('\\')[1]:"avatar"} alt="photoURL" /> <Box sx={{ ml: 2 }}> <Typography variant="subtitle2" sx={{ color: 'text.primary' }}> {email} </Typography> <Typography variant="body2" sx={{ color: 'text.secondary' }}> {roles} </Typography> </Box> </StyledAccount> </Link> </Box> <NavSection data={navConfiguration} /> <Box sx={{ flexGrow: 1 }} /> </Scrollbar> ); return ( <Box component="nav" sx={{ flexShrink: { lg: 0 }, width: { lg: NAV_WIDTH }, }} > {isDesktop ? ( <Drawer open variant="permanent" PaperProps={{ sx: { width: NAV_WIDTH, bgcolor: 'background.default', borderRightStyle: 'dashed', }, }} > {renderContent} </Drawer> ) : ( <Drawer open={openNav} onClose={onCloseNav} ModalProps={{ keepMounted: true, }} PaperProps={{ sx: { width: NAV_WIDTH }, }} > {renderContent} </Drawer> )} </Box> ); }
<template> <div> <article id="site-modal" class="modal fade"> <div class="modal-dialog modal-dialog-centered modal-xl"> <div class="modal-content"> <img data-bs-dismiss class="img-fluid" :src="modalPhoto" alt="Product Photo large" /> </div> </div> </article> <transition-group name="fade" tag="div" @beforeEnter="beforeEnter" @enter="enter" @leave="leave" > <div class="row d-flex mb-3 align-items-center" :data-index="index" v-for="(item, index) in products" :key="item.id" > <div class="col-1 m-auto"> <button class="btn btn-info" @click="$parent.$emit('add', item)"> + </button> </div> <div class="col-2"> <img data-bs-toggle="modal" data-bs-target="#site-modal" class="lowres img-fluid d-block" :src="item.image" :alt="item.name" @click="$parent.$emit('setCurrentPhoto', item.image)" /> </div> <div class="col"> <h3 class="text-info">{{ item.name }}</h3> <p class="mb-0">{{ item.description }}</p> <div class="h5 float-right"> <price :value="Number(item.price)"></price> </div> </div> </div> </transition-group> </div> </template> <script> import Price from "./PriceView.vue"; export default { name: "product-list", components: { Price }, props: ["products", "modalPhoto"], methods: { beforeEnter: function (el) { el.className = "d-none"; }, enter: function (el) { var delay = el.dataset.index * 100; setTimeout(function () { el.className = "row d-flex mb-3 align-items-center animated fadeInRight"; }, delay); }, leave: function (el) { var delay = el.dataset.index * 100; setTimeout(function () { el.className = "row d-flex mb-3 align-items-center animated fadeOutRight"; }, delay); }, }, }; </script> <style> .lowres:hover { cursor: pointer; } </style>
package com.fangzhouwang.Server; //package com.fangzhouwang; import java.awt.*; import java.rmi.RemoteException; import java.util.*; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @Author Fangzhou Wang * @Date 2023/9/28 15:12 **/ public class Game { private final Player player1; private final Player player2; private final char[][] board; private List<String> chatMessages = new ArrayList<>(); private final char player1Symbol; private final char player2Symbol; private Player currentPlayer; private static final int TOTAL_STEP_TIME = 20; // 总时间为30秒 private int remainingStepTime = TOTAL_STEP_TIME; // 剩余时间初始化为30秒 private boolean pauseFlag = false; private String status; private ScheduledExecutorService stepExecutor; public Game(Player player1, Player player2) { this.player1 = player1; this.player2 = player2; board = new char[3][3]; // 随机分配符号 Random random = new Random(); if (random.nextBoolean()) { player1Symbol = 'X'; player2Symbol = 'O'; currentPlayer = player1; } else { player1Symbol = 'O'; player2Symbol = 'X'; currentPlayer = player2; } status= "In Progress"; stepExecutor = Executors.newSingleThreadScheduledExecutor(); stepExecutor.scheduleAtFixedRate(() -> { try { decreaseStepTime(); } catch (RemoteException e) { throw new RuntimeException(e); } }, 0, 1, TimeUnit.SECONDS); // 每秒执行一次 } private synchronized void decreaseStepTime() throws RemoteException { if(pauseFlag){return;} if (!"In Progress".equals(status)) { // 如果游戏状态不是"In Progress",则重置步数时间并返回时间为99 remainingStepTime = 99; } else { if (remainingStepTime > 0) { remainingStepTime--; } else { randomMove(); } } } public synchronized void randomMove() throws RemoteException { if(pauseFlag){return;} // 获取所有尚未被占用的位置 List<Point> availableMoves = new ArrayList<>(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '\0') { // 如果位置为空 availableMoves.add(new Point(i, j)); } } } // 如果没有可用的位置,直接返回 if (availableMoves.isEmpty()) { return; } // 随机选择一个位置 Random random = new Random(); Point randomMove = availableMoves.get(random.nextInt(availableMoves.size())); // 为当前玩家放置一个符号 char currentSymbol = (currentPlayer == player1) ? player1Symbol : player2Symbol; board[randomMove.x][randomMove.y] = currentSymbol; remainingStepTime = TOTAL_STEP_TIME; updateClientsBoard(); // 更新游戏状态 status = checkStatus(); // 切换玩家 switchPlayer(); } public synchronized int getRemainingStepTime() { return remainingStepTime; } public synchronized String makeMove(String username, int row, int col) throws RemoteException { // 验证username是否与currentPlayer匹配 if(pauseFlag){return "";} if(!(status.equals( "In Progress"))){ return "Game is Over"; } if (!currentPlayer.getName().equals(username)) { return "It's not your turn!"; } char currentSymbol = (currentPlayer == player1) ? player1Symbol : player2Symbol; if (board[row][col] == '\0') { board[row][col] = currentSymbol; updateClientsBoard(); } else { return "Invalid move!"; } remainingStepTime = TOTAL_STEP_TIME; status = checkStatus(); switchPlayer(); return "Move made by " + currentPlayer.getName(); } public String checkStatus() throws RemoteException { if (isWinner()) { if (currentPlayer == player1) { player1.addScore(5); player2.subtractScore(5); // player1.getClient().updateGameResult("GM: Win"); // player2.getClient().updateGameResult("GM: Lose"); return "Player " + player1.getName() + " wins!"; } else { player2.addScore(5); player1.subtractScore(5); // player2.getClient().updateGameResult("GM: Win"); // player1.getClient().updateGameResult("GM: Lose"); return "Player " + player2.getName() + " wins!"; } } if (isDraw()) { player1.addScore(2); player2.addScore(2); // player1.getClient().updateGameResult("Draw"); // player1.getClient().updateGameResult("Draw"); return "It's a draw!"; } return "In Progress"; } private synchronized boolean isDraw() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '\0') { return false; } } } return true; } private synchronized boolean isWinner() { char currentSymbol = (currentPlayer == player1) ? player1Symbol : player2Symbol; // 检查每一行 for (int i = 0; i < 3; i++) { if (board[i][0] == currentSymbol && board[i][1] == currentSymbol && board[i][2] == currentSymbol) { return true; } } // 检查每一列 for (int i = 0; i < 3; i++) { if (board[0][i] == currentSymbol && board[1][i] == currentSymbol && board[2][i] == currentSymbol) { return true; } } // 检查对角线 if (board[0][0] == currentSymbol && board[1][1] == currentSymbol && board[2][2] == currentSymbol) { return true; } if (board[0][2] == currentSymbol && board[1][1] == currentSymbol && board[2][0] == currentSymbol) { return true; } return false; } private void switchPlayer() { if(pauseFlag){return;} currentPlayer = (currentPlayer == player1) ? player2 : player1; } public void addChatMessage(String message) throws RemoteException { chatMessages.add(message); player1.getClient().updateChat(message); player2.getClient().updateChat(message); } public List<String> getChatMessages() { return chatMessages; } public void updateClientsBoard() throws RemoteException { if(pauseFlag){return;} player1.getClient().updateBoard(board); player2.getClient().updateBoard(board); } public String getStatus() { return status; } public Player getCurrentPlayer() { return currentPlayer; } public Player getPlayer1() { return player1; } public Player getPlayer2() { return player2; } public char getPlayer1Symbol(){ return player1Symbol; } public char getPlayer2Symbol(){ return player2Symbol; } public void makeOpponentPlayerWin(String quittingPlayerName) { Player opponent; if (player1.getName().equals(quittingPlayerName)) { opponent = player2; } else { opponent = player1; } status = "Player " + opponent.getName() + " wins due to opponent's forfeit!"; } public void makeDraw(){ status = "It's a draw!"; } public void stopForWait(){ status = "Pause"; } public void setPauseFlag(Boolean flag){ this.pauseFlag = flag; } public boolean getPauseFlag(){ return this.pauseFlag; } public List<String> getAllChatHistory(){ return chatMessages; } }
package com.assignment.media.chat.jbehave; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Date; import org.jbehave.core.annotations.Given; import org.jbehave.core.annotations.Named; import org.jbehave.core.annotations.Then; import org.jbehave.core.annotations.When; import org.springframework.boot.test.TestRestTemplate; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import com.assignment.media.dto.ChatDTO; @Steps public class SaveChatSteps { private RestTemplate restTemplate; private ChatDTO chatDto; @Given("a registered company tries to register chat with user as $user and password as $password") public void createNewChat(@Named("user") String user, @Named("password") String password) { restTemplate = new TestRestTemplate(user, password); chatDto = new ChatDTO(); } @When("company tries to send in a new chat with title as $title parent as $parentId author as $authorId and content as $content") public void fillChat(@Named("title") String title, @Named("parentId") String parentId, @Named("authorId") String authorId, @Named("content") String content) { chatDto.setTitle(title); chatDto.setParentId(parentId); chatDto.setAuthorId(authorId); chatDto.setContent(content); chatDto.setPostedDateTime(new Date().getTime()); } @Then("user should be allowed to push the data") public void registerChat() { final ResponseEntity<ChatDTO> entity = restTemplate.postForEntity("http://localhost:8080/api/chat", chatDto, ChatDTO.class); assertTrue(entity.getStatusCode().is2xxSuccessful()); assertNotNull(entity.getBody().getId()); assertEquals(chatDto.getTitle(), entity.getBody().getTitle()); assertEquals(chatDto.getAuthorId(), entity.getBody().getAuthorId()); assertEquals(chatDto.getPostedDateTime(), entity.getBody().getPostedDateTime()); assertEquals(chatDto.getContent(), entity.getBody().getContent()); } }
/* * GDevelop JS Platform * Copyright 2013-present Florian Rival (Florian.Rival@gmail.com). All rights reserved. * This project is released under the MIT License. */ namespace gdjs { const logger = new gdjs.Logger('Spine Manager'); const resourceKinds: ResourceKind[] = ['spine']; /** * SpineManager manages pixi spine skeleton data. */ export class SpineManager implements gdjs.ResourceManager { private _spineAtlasManager: SpineAtlasManager; private _resourceLoader: ResourceLoader; private _loadedSpines = new gdjs.ResourceCache<pixi_spine.ISkeletonData>(); /** * @param resourceDataArray The resources data of the game. * @param resourcesLoader The resources loader of the game. */ constructor( resourceLoader: gdjs.ResourceLoader, spineAtlasManager: SpineAtlasManager ) { this._resourceLoader = resourceLoader; this._spineAtlasManager = spineAtlasManager; } getResourceKinds(): ResourceKind[] { return resourceKinds; } async processResource(resourceName: string): Promise<void> { // Do nothing because pixi-spine parses resources by itself. } async loadResource(resourceName: string): Promise<void> { const resource = this._getSpineResource(resourceName); if (!resource) { return logger.error( `Unable to find spine json for resource ${resourceName}.` ); } try { const game = this._resourceLoader.getRuntimeGame(); const embeddedResourcesNames = game.getEmbeddedResourcesNames( resource.name ); // there should be exactly one file which is pointing to atlas if (embeddedResourcesNames.length !== 1) { return logger.error( `Unable to find atlas metadata for resource spine json ${resourceName}.` ); } const atlasResourceName = game.resolveEmbeddedResource( resource.name, embeddedResourcesNames[0] ); const spineAtlas = await this._spineAtlasManager.getOrLoad( atlasResourceName ); const url = this._resourceLoader.getFullUrl(resource.file); PIXI.Assets.setPreferences({ preferWorkers: false, crossOrigin: this._resourceLoader.checkIfCredentialsRequired(url) ? 'use-credentials' : 'anonymous', }); PIXI.Assets.add(resource.name, url, { spineAtlas }); const loadedJson = await PIXI.Assets.load(resource.name); if (loadedJson.spineData) { this._loadedSpines.set(resource, loadedJson.spineData); } else { logger.error( `Loader cannot process spine resource ${resource.name} correctly.` ); } } catch (error) { logger.error( `Error while preloading spine resource ${resource.name}: ${error}` ); } } /** * Get the object for the given resource that is already loaded (preloaded or loaded with `loadJson`). * If the resource is not loaded, `null` will be returned. * * @param resourceName The name of the spine skeleton. * @returns the spine skeleton if loaded, `null` otherwise. */ getSpine(resourceName: string): pixi_spine.ISkeletonData | null { return this._loadedSpines.getFromName(resourceName); } /** * Check if the given spine skeleton was loaded. * @param resourceName The name of the spine skeleton. * @returns true if the content of the spine skeleton is loaded, false otherwise. */ isSpineLoaded(resourceName: string): boolean { return !!this._loadedSpines.getFromName(resourceName); } private _getSpineResource(resourceName: string): ResourceData | null { const resource = this._resourceLoader.getResource(resourceName); return resource && this.getResourceKinds().includes(resource.kind) ? resource : null; } } }
import React, { useCallback, useEffect, useRef } from "react"; export const useModal = (hide: () => void) => { const modalRef = useRef<HTMLDivElement>(null); const closeButtonRef = useRef<HTMLButtonElement>(null); const hiddenButtonRef = useRef<HTMLButtonElement>(null); const handleOverlayClose = (e: React.MouseEvent<HTMLDivElement>) => { const target = e.target as HTMLDivElement; if (modalRef.current === target.closest("div[data-name='modal']")) return; hide(); }; const handleKeyDown = useCallback( (e: KeyboardEvent) => { if (e.key === "Escape") { hide(); } }, [hide] ); const handleFocus = (e: FocusEvent) => { closeButtonRef.current?.focus(); }; useEffect(() => { closeButtonRef.current?.focus(); }, []); useEffect(() => { window.addEventListener("keydown", handleKeyDown); const hiddenButton = hiddenButtonRef.current; hiddenButton?.addEventListener("focus", handleFocus); return () => { window.removeEventListener("keydown", handleKeyDown); hiddenButton?.removeEventListener("focus", handleFocus); }; }, [handleKeyDown]); return { modalRef, closeButtonRef, hiddenButtonRef, handleOverlayClose: (e: React.MouseEvent<HTMLDivElement>) => handleOverlayClose(e), }; };
package com.example.demo.Logic; import com.example.demo.Collection.ApplicationSubmission; import com.example.demo.Repository.ApplicationSubmissionRepository; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import java.util.*; @AllArgsConstructor @Service public class ApplicationSubmissionService { private final ApplicationSubmissionRepository applicationSubmissionRepository; // Method to get an application submission by student number public ApplicationSubmission getApplicationSubmission(String studentNumber) { Optional<ApplicationSubmission> optionalApplicationSubmission = applicationSubmissionRepository.findApplicationSubmissionByStudentNumber(studentNumber); return optionalApplicationSubmission.orElse(null); } // Method to get all application submissions public List<ApplicationSubmission>getAllApplicationSubmissions(){ return applicationSubmissionRepository.findAll(); } // Method to add an application submission public void addApplicationSubmission(ApplicationSubmission applicationSubmission){ applicationSubmissionRepository.insert(applicationSubmission); } // Method to delete an application submission by student number public void deleteApplicationSubmission (String studentNumber){ applicationSubmissionRepository.deleteById(studentNumber); } }
package com.example.oops.classes; import java.util.Objects; public class ClassExample { public static void main(String[] args) { var teacher1 = new Teacher("Karim", "Amini", "Elementary School Teacher", 20000.0); System.out.println(teacher1); } } abstract class Person { protected String fname; protected String lname; protected Person(String fname, String lname){ this.fname = fname; this.lname = lname; } protected Person(String fname){ this(fname, null); } } interface Responsbilities { void work(); } class Teacher extends Person implements Responsbilities { private double salary; private String title; public Teacher(String fname, String lname, String title, double salary){ super(fname, lname); this.salary = salary; this.title = title; } @Override public void work() { System.out.println("Teaching..."); } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Teacher teacher = (Teacher) o; return Double.compare(teacher.salary, salary) == 0 && title.equals(teacher.title); } @Override public int hashCode() { return Objects.hash(salary, title); } @Override public String toString() { return "Teacher{" + "fname='" + fname + '\'' + ", lname='" + lname + '\'' + ", salary=" + salary + ", title='" + title + '\'' + '}'; } }
defmodule MalanWeb.PaginationController do import Plug.Conn import Malan.Utils.Phoenix.Controller import Ecto.Changeset, only: [apply_action: 2] require Logger alias Malan.Pagination @doc """ Validate that the current user is authenticated """ def is_paginated(conn, _opts) do Logger.debug("[is_paginated]: Validating pagination params") case conn.assigns do %{pagination_error: nil} -> conn %{pagination_error: {:error, :page_num}} -> halt_status(conn, 422) %{pagination_error: {:error, :page_size}} -> halt_status(conn, 422) _ -> halt_status(conn, 422) end end @doc """ validate_pagination/2 is a plug function that will: 1. Take in a conn 2. Extract the page parameters 3. If valid, add the page num and page size to conn.assigns 4. If invalid will halt the connection Returns `conn` """ def validate_pagination(conn, opts \\ []) do {default_page_size, max_page_size} = cond do is_list(opts) -> { Keyword.get(opts, :default_page_size, nil), Keyword.get(opts, :max_page_size, nil) } true -> {nil, nil} end with {:ok, pagination_info} <- extract_page_info(conn, default_page_size, max_page_size) do conn |> assign(:pagination_error, nil) |> assign(:pagination_info, pagination_info) else {:error, changeset} -> Logger.info("[validate_pagination]: pagination error: #{changeset}") conn |> assign(:pagination_error, changeset) |> assign(:pagination_info, nil) end end def require_pagination(conn), do: require_pagination(conn, nil) def require_pagination(conn, opts) do conn |> validate_pagination(opts) |> is_paginated(opts) end def extract_page_info(%Plug.Conn{params: params}, %Pagination{} = pagination) do extract_page_info(params, pagination) end def extract_page_info(%{} = params, %Pagination{} = pagination) do pagination |> Pagination.changeset(params) |> apply_action(:update) |> case do {:ok, pagination} -> {:ok, pagination} {:error, changeset} -> {:error, changeset} end end def extract_page_info(%Plug.Conn{params: params}, default_page_size, max_page_size) do extract_page_info(params, %Pagination{ max_page_size: max_page_size, default_page_size: default_page_size }) end def extract_page_info(%{} = params, default_page_size, max_page_size) do extract_page_info(params, %Pagination{ max_page_size: max_page_size, default_page_size: default_page_size }) end def extract_page_info(%{} = params) do extract_page_info(params, %Pagination{}) end @doc """ Take a `%Plug.Conn{}` called `conn` and return `{page_num, page_size}` """ def pagination_info(conn) do case conn.assigns do %{pagination_info: %{page_num: page_num, page_size: page_size}} -> {page_num, page_size} _ -> Logger.warning( "[pagination_info]: pagination info retrieved from conn that hasn't been through the plug `validate_pagination` or `require_pagination`. There may be an endpoint that expects to be paginated but doesn't require the Plug correctly. Because of this it will always und up with the default page num and default page size even if those params are included in the query string" ) {Pagination.default_page_num(), Pagination.default_page_size()} end end @doc """ Take a `%Plug.Conn{}` called `conn` and return `{page_num, page_size}` """ def pagination_info!(conn) do case pagination_info(conn) do {page_num, page_size} -> {page_num, page_size} _ -> raise Pagination.NotPaginated, conn: conn end end end
/**************************************************************************** ** ** Copyright (C) VCreate Logic Private Limited, Bangalore ** ** Use of this file is limited according to the terms specified by ** VCreate Logic Private Limited, Bangalore. Details of those terms ** are listed in licence.txt included as part of the distribution package ** of this file. This file may not be distributed without including the ** licence.txt file. ** ** Contact info@vcreatelogic.com if any conditions of this licensing are ** not clear to you. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include <QtGlobal> #include <QString> #include <QtTest> #include <GCF3/GuiApplication> #include <GCF3/Component> class BasicGuiApplicationTest : public QObject { Q_OBJECT public: BasicGuiApplicationTest(); private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void cleanup(); void testgAppPointer(); void testLoadNonGuiComponent(); void testLoadMultipleNonGuiComponentInstances(); void testLoadHigherVersionNonGuiComponent(); void testLoadLowerVersionNonGuiComponent(); void testLoadInvalidNonGuiComponent(); void testLoadNonGCFLibrary(); private: QString logFileContents(bool deleteFile=true) const; }; BasicGuiApplicationTest::BasicGuiApplicationTest() { } void BasicGuiApplicationTest::initTestCase() { qDebug("Running tests on GCF-%s built on %s", qPrintable(GCF::version()), qPrintable(GCF::buildTimestamp())); } void BasicGuiApplicationTest::cleanupTestCase() { qDebug("Executed tests on GCF-%s built on %s", qPrintable(GCF::version()), qPrintable(GCF::buildTimestamp())); } void BasicGuiApplicationTest::cleanup() { QFile::remove( GCF::Log::instance()->logFileName() ); } void BasicGuiApplicationTest::testgAppPointer() { QVERIFY(gApp != 0); QVERIFY(QString::fromLatin1(gApp->metaObject()->className()) == "GCF::GuiApplication"); } void BasicGuiApplicationTest::testLoadNonGuiComponent() { QVERIFY(gApp->components().count() == 0); QPointer<GCF::Component> component = gApp->loadComponent("Components/SimpleComponent"); QVERIFY(component.data() != 0); QVERIFY(component->name() == "SimpleComponent"); QVERIFY(gApp->components().count() == 1); component->unload(); QVERIFY(component.data() == 0); QVERIFY(gApp->components().count() == 0); } void BasicGuiApplicationTest::testLoadMultipleNonGuiComponentInstances() { GCF::ObjectList components; for(int i=0; i<20; i++) { GCF::Component *comp = gApp->instantiateComponent("Components/SimpleComponent"); QVERIFY(comp->isLoaded() == false); QVERIFY(comp->isActive() == false); comp->setProperty("name", QString("SimpleComponent%1").arg(i+1)); comp->load(); QVERIFY(comp->isLoaded() == true); QVERIFY(comp->isActive() == true); QVERIFY(gApp->components().count() == i+1); components.add(comp); } for(int i=0; i<20; i++) { QString name = QString("SimpleComponent%1").arg(i+1); QString path = QString("Application.%1").arg(name); QVERIFY(gApp->objectTree()->object(path) == components.at(i)); } while(components.count()) { GCF::Component *comp = (GCF::Component*)components.last(); comp->unload(); QVERIFY(gApp->objectTree()->rootNode()->children().count() == components.count()); QVERIFY(gApp->components().count() == components.count()); } } void BasicGuiApplicationTest::testLoadHigherVersionNonGuiComponent() { QString lib = GCF::findLibrary("Components/HigherVersionComponent"); QVERIFY( QFile::exists(lib) ); GCF::Component *component = 0; // Load using GCF::Application::loadComponent() component = gApp->loadComponent("Components/HigherVersionComponent"); QVERIFY(component == 0); QString errLog = QString("Component is built for a higher version of GCF3 than the one used by this application. " "This application uses GCF %1, whereas the component uses %2.") .arg(GCF::version()).arg("4.0.0"); QVERIFY(this->logFileContents().contains(errLog)); // Load using GCF::Application::instantiateComponent() component = gApp->instantiateComponent("Components/HigherVersionComponent"); QVERIFY(component == 0); QVERIFY(this->logFileContents().contains(errLog)); if(component) component->unload(); } void BasicGuiApplicationTest::testLoadLowerVersionNonGuiComponent() { QString lib = GCF::findLibrary("Components/LowerVersionComponent"); QVERIFY( QFile::exists(lib) ); GCF::Component *component = 0; // Load using GCF::Application::loadComponent() component = gApp->loadComponent("Components/LowerVersionComponent"); QVERIFY(component == 0); QString errLog = QString("Component is built for a lower version of GCF3 than the one used by this application. " "This application uses GCF %1, whereas the component uses %2.") .arg(GCF::version()).arg("2.0.0"); QVERIFY(this->logFileContents().contains(errLog)); // Load using GCF::Application::instantiateComponent() component = gApp->instantiateComponent("Components/LowerVersionComponent"); QVERIFY(component == 0); QVERIFY(this->logFileContents().contains(errLog)); if(component) component->unload(); } void BasicGuiApplicationTest::testLoadInvalidNonGuiComponent() { QString lib = GCF::findLibrary("Components/InvalidComponent"); QVERIFY( QFile::exists(lib) ); GCF::Component *component = 0; // Load using GCF::Application::loadComponent() component = gApp->loadComponent("Components/InvalidComponent"); QVERIFY(component == 0); QString errLog = QString("Component library did not return any component object."); QVERIFY(this->logFileContents().contains(errLog)); // Load using GCF::Application::instantiateComponent() component = gApp->instantiateComponent("Components/InvalidComponent"); QVERIFY(component == 0); QVERIFY(this->logFileContents().contains(errLog)); if(component) component->unload(); } void BasicGuiApplicationTest::testLoadNonGCFLibrary() { #ifdef Q_OS_WIN32 #if QT_VERSION >= 0x050000 QString library = "sqldrivers/qsqlite"; #else QString library = "sqldrivers/qsqlite4"; #endif #else QString library = "sqldrivers/qsqlite"; #endif qDebug() << library << GCF::findLibrary(library); QVERIFY( QFile::exists( GCF::findLibrary(library) ) ); GCF::Component *component = 0; // Load using GCF::Application::loadComponent() component = gApp->loadComponent(library); QVERIFY(component == 0); QString errLog = QString("Library doesn't contain a GCF3 component"); QVERIFY(this->logFileContents().contains(errLog)); // Load using GCF::Application::instantiateComponent() component = gApp->instantiateComponent(library); QVERIFY(component == 0); QVERIFY(this->logFileContents().contains(errLog)); if(component) component->unload(); } QString BasicGuiApplicationTest::logFileContents(bool deleteFile) const { QString retString; { QFile file( GCF::Log::instance()->logFileName() ); file.open( QFile::ReadOnly ); retString = file.readAll(); } if(deleteFile) QFile::remove( GCF::Log::instance()->logFileName() ); return retString; } int main(int argc, char *argv[]) { GCF::GuiApplication app(argc, argv); BasicGuiApplicationTest tc; return QTest::qExec(&tc, argc, argv); } #include "tst_BasicGuiApplicationTest.moc"
/** * ResearchSpace * Copyright (C) 2020, © Trustees of the British Museum * Copyright (C) 2015-2019, metaphacts GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.researchspace.data.rdf; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.inject.Inject; import javax.inject.Singleton; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.rio.ParserConfig; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFParseException; import org.eclipse.rdf4j.rio.RDFWriter; import org.eclipse.rdf4j.rio.Rio; import org.eclipse.rdf4j.rio.UnsupportedRDFormatException; import org.eclipse.rdf4j.rio.helpers.BasicParserSettings; import org.eclipse.rdf4j.rio.helpers.BasicWriterSettings; import org.eclipse.rdf4j.rio.helpers.ParseErrorLogger; import org.researchspace.config.NamespaceRegistry; /** * @author Artem Kozlov <ak@metaphacts.com> */ @Singleton public class RioUtils { @Inject private NamespaceRegistry ns; /** * Namespaces aware RIO parser. */ public Model parse(InputStream io, String baseURI, RDFFormat dataFormat, Resource... contexts) throws RDFParseException, UnsupportedRDFormatException, IOException { ParserConfig config = new ParserConfig(); config.set(BasicParserSettings.NAMESPACES, ns.getRioNamespaces()); return Rio.parse(io, baseURI, dataFormat, config, SimpleValueFactory.getInstance(), new ParseErrorLogger(), contexts); } /** * Basic RIO writer */ public void write(RDFFormat format, Model model, OutputStream out) { RDFWriter writer = Rio.createWriter(format, out); writer.startRDF(); ns.getRioNamespaces().stream() .forEach(namespace -> writer.handleNamespace(namespace.getPrefix(), namespace.getName())); writer.set(BasicWriterSettings.PRETTY_PRINT, true); for (final Statement st : model) { writer.handleStatement(st); } writer.endRDF(); } }
"use client"; import React, { ElementRef, useRef, useState } from "react"; import ListWrapper from "./listWrapper"; import FormInput from "@/components/form/formInput"; import { useEventListener } from "usehooks-ts"; import { useAction } from "@/hooks/useAction"; import { updateList } from "@/actions/updateList"; import ListOptions from "./listOptions"; import CreateCard from "./createCard"; import ActionTooltip from "@/components/actionTooltip"; import { cn } from "@/lib/utils"; import { Separator } from "@/components/ui/separator"; import CardItem from "./cardItem"; import { Droppable } from "@hello-pangea/dnd"; import { useToast } from "@/components/ui/use-toast"; import { ListWithCards } from "@/type"; import { useRouter } from "next/navigation"; import { useQueryClient } from "@tanstack/react-query"; interface ListHeaderProps { list: ListWithCards; } const ListHeader = ({ list }: ListHeaderProps) => { const [isEditing, setIsEditing] = useState(false); const [isCreatingCard, setIsCreatingCard] = useState(false); const formRef = useRef<ElementRef<"form">>(null); const inputRef = useRef<ElementRef<"input">>(null); const { toast } = useToast(); const router = useRouter(); const queryClient = useQueryClient(); const { execute, fieldsErrors } = useAction(updateList, { onSuccess: (data) => { toast({ title: `Successfully updated "${data.title}"`, }); router.refresh(); disableEditing(); }, onError: (e) => { toast({ title: e, }); }, }); //! need to clear error message from FromError when close the form function disableEditing() { setIsEditing(false); } function enableEditing() { setIsEditing(true); setTimeout(() => { inputRef?.current?.focus(); inputRef?.current?.select(); }, 0); } function onKeyDown(event: KeyboardEvent) { if (event.key === "Escape") { disableEditing(); } } function onSubmit(formData: FormData) { const title = formData.get("title") as string; const boardId = formData.get("boardId") as string; const id = formData.get("id") as string; if (list.title === title) { return disableEditing(); } execute({ title, boardId, id, }); } useEventListener("keydown", onKeyDown); function onBlur() { formRef?.current?.requestSubmit(); } if (isEditing) { return ( <ListWrapper> <form action={onSubmit} ref={formRef} className="space-y-4 rounded-md w-full bg-white/90 text-black px-3 py-2" > <FormInput ref={inputRef} id="title" className="w-full" placeholder="Enter list title..." onBlur={onBlur} defaultValue={list.title} errors={fieldsErrors} /> <input type="hidden" name="boardId" value={list.boardId} /> <input type="hidden" name="id" value={list.id} /> </form> </ListWrapper> ); } return ( <> <div className="flex items-center justify-between"> <ActionTooltip title="click to edit title"> <div role="button" className="flex truncate items-center w-full flex-1 justify-start gap-x-1 h-10 px-4 py-2 cursor-pointer font-bold" onClick={enableEditing} > {list.title} </div> </ActionTooltip> <ListOptions list={list} setIsCreatingCard={setIsCreatingCard} isCreatingCard={isCreatingCard} /> </div> {list.cards.length ? ( <Separator className="w-[90%] mx-auto h-[1.4px]" /> ) : null} <Droppable droppableId={list.id} type="card"> {(provided) => ( <ol {...provided.droppableProps} ref={provided.innerRef} className={cn( "flex flex-col gap-y-2 px-3 py-2", list.cards.length > 0 ? "my-2" : "my-0 px-0 py-0" )} > {list.cards.map((card, index) => ( <CardItem key={card.id} card={card} index={index} /> ))} {provided.placeholder} </ol> )} </Droppable> {list.cards.length ? ( <Separator className="w-[90%] mx-auto h-[1.4px]" /> ) : null} <div className="w-full"> <CreateCard list={list} isCreatingCard={isCreatingCard} setIsCreatingCard={setIsCreatingCard} /> </div> </> ); }; export default ListHeader;
(require "cairo") (use-package :cairo) (use-package :cairo.ext) (defvar *snippet-filename-regexp* '("examples/.+\\.l$")) (defun snippet-p (filename) (some #'(lambda (re) (string-matchp re filename)) *snippet-filename-regexp*)) (defun snippet-filename () (or (and (boundp '*snippet*) ; run-all-snippets *snippet*) (and (snippet-p *load-pathname*) ; load-file *load-pathname*) (and (snippet-p (get-buffer-file-name)) ; eval-buffer (get-buffer-file-name)) (plain-error "unknown snippet filename."))) (defun snippet-directory (snippet) (directory-namestring snippet)) (defun output-filename (snippet &optional (ext ".png")) (substitute-string snippet "\\(\\.l$\\)?$" ext)) (defun snippet-normalize (cr width height) (cairo-scale cr width height) (cairo-set-line-width cr 0.04)) (defmacro do-snippets0 ((&key (height 256) (width 256) (ext ".png")) &body body) `(let* ((snippet-filename (snippet-filename)) (snippet-directory (snippet-directory snippet-filename)) (output-filename (output-filename snippet-filename ,ext))) (let* ((height ,height) (width ,width)) ,@body))) (setf (get 'do-snippets0 'ed::lisp-indent-hook) 'with-output-to-string) (defmacro do-snippets ((&key (height 256) (width 256) (ext ".png") (normalize t)) &body body) (let ((start (gensym)) (elapsed (gensym))) `(do-snippets0 (:height ,height :width ,width :ext ,ext) (delete-file output-filename :if-does-not-exist :skip :if-access-denied :skip) (let ((,start (get-internal-real-time))) (with-cairo-surface (surface (cairo-image-surface-create :argb32 width (+ height 15))) (with-cairo (cr (cairo-create surface)) (with-output-to-png (surface output-filename) (with-cairo-save (cr) (when ,normalize (snippet-normalize cr width height)) (with-cairo-save (cr) (cairo-set-source-rgb cr 1 1 1) (cairo-paint cr)) (progn ,@body)) ;; Elapsed Time (let ((,elapsed (- (get-internal-real-time) ,start))) (with-cairo-save (cr) (cairo-set-source-rgba cr 0 0 0 0.8) (cairo-set-font-size cr 10) (cairo-move-to cr 3 (+ ,height 10)) (cairo-show-text cr (format nil "Elapsed: ~,2F" (/ ,elapsed 1000.0)))))))))))) (setf (get 'do-snippets 'ed::lisp-indent-hook) 'with-output-to-string) (defun scan-snippets-file (dir) (remove-if #'(lambda (l) (string-matchp "^_" l)) (directory dir :wild "*.l" :file-only t :absolute t))) (defun clean-all-snippet-outputs (dir) (interactive "DSnippet Directory: " :default0 (default-directory)) (dolist (snippet (scan-snippets-file dir)) (dolist (out (directory dir :wild (format nil "~A.*" (pathname-name snippet)) :absolute t :fileonly t)) (unless (string= (pathname-type out) "l") (delete-file out :if-does-not-exist :skip :if-access-denied :skip))))) (defun run-all-snippets (dir) (interactive "DSnippet Directory: " :default0 (default-directory)) (dolist (snippet (scan-snippets-file dir)) (message snippet) (let ((*snippet* snippet)) (declare (special *snippet*)) (handler-case (load snippet) (error (c) (msgbox "Error: ~S" c)))))) (defun run-current-snippet-and-view () (interactive) (eval-buffer (selected-buffer)) (shell-execute (output-filename (get-buffer-file-name))))
import React from 'react'; import { StyleSheet, Text, View, Modal, Image, SafeAreaView, TouchableOpacity, } from 'react-native'; import LottieView from 'lottie-react-native'; const ModalHistory = ({ setModalVisible, modalVisible, entry }) => { const emojiMapping = { 'U+1F622': '😢', 'U+1F614': '😔', 'U+1F610': '😐', 'U+1F60C': '😌', 'U+1F601': '😁', }; //if entry is empty for the day, render out appropriate modal if (Object.keys(entry).length === 0) { return ( <SafeAreaView style={styles.modalContainer}> <Modal animationType="slide" visible={modalVisible} onRequestClose={() => { Alert.alert('Modal has been closed.'); setModalVisible(!modalVisible); }} > <LottieView style={styles.lottieMountain} source={require('../assets/lottie/mountain.json')} autoPlay /> <View style={styles.centeredView}> <View style={styles.modalView}> <View style={styles.cancelContainer}> <TouchableOpacity onPress={() => setModalVisible(!modalVisible)} > <Image source={require('../assets/icons/cancel.png')} /> </TouchableOpacity> </View> <View style={styles.lottieContainer}> <LottieView style={styles.noResult} source={require('../assets/lottie/no-result.json')} autoPlay /> <Text style={styles.noJournalText}> Sorry, you don't have a journal entry for this day </Text> </View> </View> </View> </Modal> </SafeAreaView> ); } return ( <SafeAreaView style={styles.modalContainer}> <Modal animationType="slide" visible={modalVisible} onRequestClose={() => { Alert.alert('Modal has been closed.'); setModalVisible(!modalVisible); }} > <LottieView style={styles.lottieMountain} source={require('../assets/lottie/mountain.json')} autoPlay /> <View style={styles.centeredView}> <View style={styles.modalView}> <View style={styles.cancelContainer}> <TouchableOpacity onPress={() => setModalVisible(!modalVisible)}> <Image source={require('../assets/icons/cancel.png')} /> </TouchableOpacity> </View> <View> <View style={styles.modalHeaderMainContainer}> <Text style={styles.modalHeaderMain}> Entry for {entry.createdAt}{' '} </Text> </View> {/* Photo */} {!!entry.photoURL && ( <View style={styles.imageContainer}> <Image style={styles.displayImage} source={{ uri: entry.photoURL }} /> </View> )} {/* Text Input */} {!!entry.textInput && ( <View style={styles.imageContainer}> <Text style={styles.modalText}>{entry.textInput}</Text> </View> )} {/* Mood */} <Text style={styles.modalHeader}> Mood: {emojiMapping[entry.mood.imageUrl]} </Text> {/* Activities */} <Text style={styles.modalHeaderActivities}>Activities</Text> {entry.activities.map((activity) => { return ( <Text key={activity.id} style={styles.modalActivities}> {activity.activityName} {activity.image} </Text> ); })} </View> </View> </View> </Modal> </SafeAreaView> ); }; export default ModalHistory; const styles = StyleSheet.create({ modalContainer: { position: 'absolute', }, centeredView: { flex: 1, justifyContent: 'center', alignItems: 'center', marginTop: 22, }, lottieMountain: { width: 500, height: 900, position: 'absolute', }, modalView: { margin: '2.5%', backgroundColor: 'white', borderRadius: 20, padding: 35, // alignItems: 'center', shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 4, elevation: 5, }, button: { borderRadius: 20, padding: 10, elevation: 2, }, buttonOpen: { backgroundColor: '#F194FF', }, buttonClose: { backgroundColor: '#2196F3', }, textStyle: { color: 'white', fontWeight: 'bold', textAlign: 'center', }, modalText: { marginBottom: 15, fontSize: 18, }, modalHeader: { marginBottom: 15, fontSize: 20, }, modalHeaderActivities: { // marginBottom: 10, fontSize: 20, textDecorationLine: 'underline', }, modalActivities: { position: 'relative', fontSize: 17, }, modalHeaderMain: { padding: 15, fontSize: 20, }, modalHeaderMainContainer: { borderColor: '#F9ECEC', borderWidth: 4, padding: 2, shadowColor: '#000', shadowOffset: { width: 0, height: 0.5, }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3, marginBottom: 15, }, noJournalText: { display: 'flex', color: '#b5179e', alignContent: 'center', textAlign: 'center', }, displayImage: { width: 200, height: 200, marginBottom: 5, borderRadius: 20, }, imageContainer: { alignItems: 'center', justifyContent: 'center', }, noResult: { width: 150, height: 150, }, lottieContainer: { alignItems: 'center', }, cancelContainer: { position: 'absolute', alignSelf: 'flex-end', padding: 10, }, });
// Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause #include "birthdayparty.h" #include "person.h" #include <QCoreApplication> #include <QDebug> #include <QQmlComponent> #include <QQmlEngine> int main(int argc, char **argv) { QCoreApplication app(argc, argv); QQmlEngine engine; QQmlComponent component(&engine); component.loadFromModule("People", "Main"); std::unique_ptr<BirthdayParty> party{ qobject_cast<BirthdayParty *>(component.create()) }; if (party && party->host()) { qInfo() << party->host()->name() << "is having a birthday!"; if (qobject_cast<Boy *>(party->host())) qInfo() << "He is inviting:"; else qInfo() << "She is inviting:"; Person *bestShoe = nullptr; for (qsizetype ii = 0; ii < party->guestCount(); ++ii) { Person *guest = party->guest(ii); qInfo() << " " << guest->name(); if (!bestShoe || bestShoe->shoe()->price() < guest->shoe()->price()) bestShoe = guest; } if (bestShoe) qInfo() << bestShoe->name() << "is wearing the best shoes!"; return EXIT_SUCCESS; } qWarning() << component.errors(); return EXIT_FAILURE; }
package com.example.ecomapplication; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.ecomapplication.db.Product; import java.util.ArrayList; import java.util.List; public class CartActivity extends AppCompatActivity { CartAdapter adapter; ProductViewModel viewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cart); setTitle("Cart"); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); viewModel = new ViewModelProvider(this).get(ProductViewModel.class); RecyclerView recyclerView = findViewById(R.id.recyclerView); LinearLayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); adapter = new CartAdapter(new ArrayList<>()); recyclerView.setAdapter(adapter); viewModel.getCartItems().observe(this, products -> { Log.e("CartCount", "" + products.size()); adapter.updateList(products); calculateTotal(products); }); } private void calculateTotal(List<Product> products) { int total = 0; for (Product product : products) { total += Integer.parseInt(product.getPrice().replace("₹", "").replace(",", "")) * product.getCount(); } ((TextView) findViewById(R.id.total)).setText("₹" + total); } public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> { private List<Product> products; public CartAdapter(List<Product> data) { this.products = data; } public void updateList(final List<Product> streamList) { this.products.clear(); this.products = streamList; notifyDataSetChanged(); } @NonNull @Override public CartAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_cart, parent, false); return new CartAdapter.ViewHolder(v); } @Override public void onBindViewHolder(@NonNull CartAdapter.ViewHolder holder, int position) { Product product = products.get(position); holder.name.setText(product.getName()); holder.price.setText(product.getPrice()); holder.count.setText("" + product.getCount()); int total = Integer.parseInt(product.getPrice().replace("₹", "").replace(",", "")) * product.getCount(); holder.itemTotal.setText("₹" + total); Glide.with(CartActivity.this) .load(product.getImage()) .placeholder(R.drawable.ic_launcher_background) .into(holder.imageView); holder.inc.setOnClickListener(v -> { viewModel.updateCart(product, product.getCount() + 1); notifyItemChanged(position); }); holder.dec.setOnClickListener(v -> { viewModel.updateCart(product, product.getCount() - 1); notifyItemChanged(position); }); } @Override public int getItemCount() { if (products != null) { return products.size(); } else { return 0; } } public class ViewHolder extends RecyclerView.ViewHolder { public TextView name, price, count, itemTotal; public ImageView imageView; public View add, inc, dec, root; public ViewHolder(View v) { super(v); root = v; name = v.findViewById(R.id.name); price = v.findViewById(R.id.price); count = v.findViewById(R.id.count); itemTotal = v.findViewById(R.id.itemTotal); add = v.findViewById(R.id.addButton); inc = v.findViewById(R.id.inc); dec = v.findViewById(R.id.dec); imageView = v.findViewById(R.id.imageView); } } } }