text
stringlengths
184
4.48M
import React from 'react'; import ReactDOM from 'react-dom'; import { AiFillQuestionCircle, AiFillCheckCircle, AiFillExclamationCircle, AiFillCloseCircle, AiFillInfoCircle, } from 'react-icons/ai'; import { domHelpers, uuid } from '../../utils'; import { Button } from '../button'; import { Icon } from '../icon'; import Modal from './modal'; import { ConfirmProps } from './typing'; const confirm = (config: ConfirmProps) => { const props = { icon: <AiFillQuestionCircle />, type: 'info', width: 400, height: 180, okText: 'OK', cancelText: 'Cancel', okCancel: true, ...config, }; const id = 'confirm_' + uuid(); const prefixCls = 'k-modal-confirm'; const div = document.createElement('div'); document.body.appendChild(div); const close = () => { const elmModal = document.getElementById(id); const elmMask = document.getElementById(`mask_${id}`); const unmount = () => { const unmountResult = ReactDOM.unmountComponentAtNode(div); if (unmountResult && div.parentNode) { div.parentNode.removeChild(div); } }; if (elmModal) { domHelpers.removeClass(elmModal, 'in'); if (elmMask) { domHelpers.removeClass(elmMask, 'fade-enter-done'); domHelpers.addClass(elmMask, 'fade-exit-active'); } setTimeout(() => { unmount(); }, 300); } else { unmount(); } }; const onCancel = () => { if (!props.onCancel || props.onCancel() !== false) { close(); } }; const onOK = () => { if (!props.onOK || props.onOK() !== false) { close(); } }; let body = ( <div className={`${prefixCls}-body`}> <Icon className={`icon-${props.type}`} color={props.type as any} children={props.icon} /> <span className={`${prefixCls}-title`}>{props.header}</span> <div className={`${prefixCls}-content`}>{props.content}</div> </div> ); let footer; if (props.okCancel) { footer = ( <div className={`${prefixCls}-btns`}> <Button onClick={onCancel}>{props.cancelText}</Button> <Button color="primary" onClick={onOK}> {props.okText} </Button> </div> ); } else { footer = ( <div className={`${prefixCls}-btns`}> <Button color="primary" onClick={onOK}> {props.okText} </Button> </div> ); } body = ( <React.Fragment> {body} {footer} </React.Fragment> ); ReactDOM.render( <Modal id={id} className={`${prefixCls}`} content={body} showHeader={false} showFooter={false} width={props.width} height={props.height} mask={true} open />, div, ); return { destory: close, }; }; export default { info(props) { const config = { type: 'info', icon: <AiFillInfoCircle />, okCancel: false, ...props, }; return confirm(config); }, success(props) { const config = { type: 'success', icon: <AiFillCheckCircle />, okCancel: false, ...props, }; return confirm(config); }, warning(props) { const config = { type: 'warning', icon: <AiFillExclamationCircle />, okCancel: false, ...props, }; return confirm(config); }, error(props) { const config = { type: 'danger', icon: <AiFillCloseCircle />, okCancel: false, ...props, }; return confirm(config); }, confirm(props) { const config = { type: 'warning', icon: <AiFillQuestionCircle />, ...props, }; return confirm(config); }, };
import { useMemo, useContext } from 'react'; import { Link } from '@inertiajs/react'; import ThemeContext from '@/Components/ThemeContext'; function Pagination({ links }) { const { theme, toggleTheme } = useContext(ThemeContext); const renderedLinks = useMemo(() => { return links.map((link, p) => { if (link.url === null) { return ( <div key={p} className="mr-1 mb-1 px-4 py-3 text-sm leading-4 text-gray-400 border rounded" dangerouslySetInnerHTML={{ __html: link.label }} /> ); } else { return ( <Link href={link.url} className={`mr-1 mb-1 px-4 py-3 text-sm leading-4 border rounded hover:bg-white ${theme === 'dark' ? '' : 'border-gray-400 text-indigo-300'} ${ link.active ? 'bg-blue-700 text-white' : '' } ${p === links.length - 1 ? 'ml-auto' : ''}`} dangerouslySetInnerHTML={{ __html: link.label }} ></Link> ); } }); }, [links]); return <div className={`py-4 ${theme === 'dark' ? 'dark:bg-gray-800' : 'bg-gray-100'}`}>{links.length > 3 && <div className="flex flex-wrap -mb-1">{renderedLinks}</div>}</div>; } export default Pagination;
//import 'package:flutter/cupertino.dart'; // ignore_for_file: avoid_print, no_duplicate_case_values import 'package:flutter/material.dart'; import 'package:food_delivery_app/models/models.dart'; import 'package:food_delivery_app/screens/basket.dart'; import 'package:food_delivery_app/screens/checkout.dart'; import 'package:food_delivery_app/screens/delivery_time.dart'; import 'package:food_delivery_app/screens/edit_basket.dart'; import 'package:food_delivery_app/screens/filter.dart'; import 'package:food_delivery_app/screens/home_screen.dart'; import 'package:food_delivery_app/screens/location_screen.dart'; import 'package:food_delivery_app/screens/login_screen.dart'; import 'package:food_delivery_app/screens/restaurant_details.dart'; import 'package:food_delivery_app/screens/restaurant_listing.dart'; import 'package:food_delivery_app/screens/signup_screen.dart'; import 'package:food_delivery_app/screens/voucher.dart'; class AppRouter { static Route onGenerateRoute(RouteSettings settings) { print('The route is : ${settings.name}'); switch (settings.name) { case LoginScreen.routeName: return LoginScreen.route(); case SignupScreen.routeName: return SignupScreen.route(); // case '/': // return HomeScreen.route(); case HomeScreen.routeName: return HomeScreen.route(); case LocationScreen.routeName: return LocationScreen.route(); case BasketScreen.routeName: return BasketScreen.route(); case CheckoutScreen.routeName: return CheckoutScreen.route(); case DeliveryTimeScreen.routeName: return DeliveryTimeScreen.route(); case EditBasketScreen.routeName: return EditBasketScreen.route(); case FilterScreen.routeName: return FilterScreen.route(); case RestaurantDetailsScreen.routeName: return RestaurantDetailsScreen.route( restaurant: settings.arguments as Restaurant); case RestaurantListingScreen.routeName: return RestaurantListingScreen.route( restaurants: settings.arguments as List<Restaurant>); case VoucherScreen.routeName: return VoucherScreen.route(); default: return _errorRoute(); } } static Route _errorRoute() { return MaterialPageRoute( builder: (_) => Scaffold( appBar: AppBar( title: const Text('Error'), ), ), settings: const RouteSettings(name: '/error')); } }
// // CustomPopover.swift // // // Created by Alexander Kraev on 29.01.2022. // import SwiftUI struct CustomPopover<Item, PopoverContent>: ViewModifier where Item : Identifiable, PopoverContent: View { var item: Binding<Item?> let onDismiss: (() -> Void)? let popoverContent: PopoverContent @State var isAlertPresented = false init(item: Binding<Item?>, onDismiss: (() -> Void)? = nil, @ViewBuilder popoverContent: (Item?) -> PopoverContent) { self.item = item self.onDismiss = onDismiss self.popoverContent = popoverContent(item.wrappedValue) } public func body(content: Content) -> some View { let isPopoverPresented = item.wrappedValue != nil return ZStack { content .layoutPriority(1) .blur(radius: isPopoverPresented ? 10 : 0) .clipped() .allowsHitTesting(!isPopoverPresented) .zIndex(0) if isPopoverPresented { /* clear background for closing alert */ Color.clear .frame(maxWidth: .infinity, maxHeight: .infinity) .contentShape(Rectangle()) .onTapGesture { withAnimation { item.wrappedValue = nil } } .zIndex(1) popoverContent .transition(.asymmetric(insertion: .scale, removal: .move(edge: .bottom))) .clipped() .onDisappear { onDismiss?() } .zIndex(2) } } } } public extension View { func customPopover<Item, Content>(item: Binding<Item?>, onDismiss: (() -> Void)? = nil, @ViewBuilder content: @escaping (Item?) -> Content) -> some View where Item : Identifiable, Content : View { modifier(CustomPopover(item: item, onDismiss: onDismiss, popoverContent: content)) } }
import { RequestHasLogin } from "../types/request.type"; import { Response, NextFunction } from "express"; import jwt, { TokenExpiredError, JsonWebTokenError, NotBeforeError } from "jsonwebtoken"; import { MyJwtPayload } from "../types/decodeToken.type"; import { db } from "../configs/db.config"; import { PrismaClientKnownRequestError } from "@prisma/client/runtime"; import configs from "../configs"; import i18n from "../utils/i18next"; export const isLogin = async (req: RequestHasLogin, res: Response, next: NextFunction) => { try { const authHeader = req.headers.authorization; const jsonWebToken = authHeader?.split(" ")[1]; if (!jsonWebToken) { res.status(401).json({ message: i18n.t("errorMessages.UnAuthorized") }); return; } else { const decodeJsonWebToken = jwt.verify(jsonWebToken, configs.general.JWT_SECRET_KEY) as MyJwtPayload; if (decodeJsonWebToken) { const isFoundUser = await db.user.findUnique({ where: { id: decodeJsonWebToken.user_id, }, }); if (isFoundUser) { req.user_id = isFoundUser.id; } } } next(); } catch (error: any) { if (error instanceof PrismaClientKnownRequestError) { return res.status(401).json({ message: error.toString() }); } if (error instanceof TokenExpiredError) { return res.status(401).json({ message: error.message }); } else if (error instanceof JsonWebTokenError) { return res.status(401).json({ message: error.message }); } else if (error instanceof NotBeforeError) { return res.status(401).json({ message: error.message }); } return res.status(500).json({ message: i18n.t("errorMessages.internalServer") }); } };
package main import ( "bufio" "fmt" "log" "os" ) var hadError = false var hadRuntimeError = false var interpreter = NewInterpreter() func LoxMain(args []string) { length := len(args) if length > 1 { fmt.Println("Usage: glox [script]") os.Exit(64) } else if length == 1 { runFile(args[0]) } else { runPrompt() } } func runFile(filePath string) { // Read the file content content, err := os.ReadFile(filePath) if err != nil { log.Fatalf("Error reading file: %v", err) } run(string(content)) if hadError { os.Exit(65) } if hadRuntimeError { os.Exit(70) } } func runPrompt() { scanner := bufio.NewScanner(os.Stdin) for { fmt.Print("> ") if !scanner.Scan() { scanner.Err() break } line := scanner.Text() run(line) hadError = false } } func run(source string) { scanner := NewScanner(source) tokens := scanner.ScanTokens() // fmt.Println("Tokens: ") // for _, token := range tokens { // fmt.Printf("Type: %-12s Lexeme: %-10s Literal: %v \n", TokenName[token.Type], token.Lexeme, token.Literal) // } // fmt.Println("") parser := NewParser(tokens) statements := parser.Parse() if hadError { return } interpreter.Interpret(statements) } func Error(line int, message string) { report(line, "", message) } func TokenError(token Token, message string) { if token.Type == EOF { report(token.Line, " at the end ", message) } else { report(token.Line, " at '"+token.Lexeme+"'", message) } } func report(line int, where string, message string) { fmt.Fprintf(os.Stderr, "[line %d] Error %s: %s\n", line, where, message) hadError = true } func ReportRuntimeError(err RuntimeError) { fmt.Fprintf(os.Stderr, "%s\n[line %d]\n", err.Message, err.Operator.Line) hadRuntimeError = true }
package river import ( "errors" "fmt" "slices" "time" "github.com/riverqueue/river/rivertype" ) // InsertOpts are optional settings for a new job which can be provided at job // insertion time. These will override any default InsertOpts settings provided // by JobArgsWithInsertOpts, as well as any global defaults. type InsertOpts struct { // MaxAttempts is the maximum number of total attempts (including both the // original run and all retries) before a job is abandoned and set as // discarded. MaxAttempts int // Metadata is a JSON object blob of arbitrary data that will be stored with // the job. Users should not overwrite or remove anything stored in this // field by River. Metadata []byte // Pending indicates that the job should be inserted in the `pending` state. // Pending jobs are not immediately available to be worked and are never // deleted, but they can be used to indicate work which should be performed in // the future once they are made available (or scheduled) by some external // update. Pending bool // Priority is the priority of the job, with 1 being the highest priority and // 4 being the lowest. When fetching available jobs to work, the highest // priority jobs will always be fetched before any lower priority jobs are // fetched. Note that if your workers are swamped with more high-priority jobs // then they can handle, lower priority jobs may not be fetched. // // Defaults to PriorityDefault. Priority int // Queue is the name of the job queue in which to insert the job. // // Defaults to QueueDefault. Queue string // ScheduledAt is a time in future at which to schedule the job (i.e. in // cases where it shouldn't be run immediately). The job is guaranteed not // to run before this time, but may run slightly after depending on the // number of other scheduled jobs and how busy the queue is. // // Use of this option generally only makes sense when passing options into // Insert rather than when a job args struct is implementing // JobArgsWithInsertOpts, however, it will work in both cases. ScheduledAt time.Time // Tags are an arbitrary list of keywords to add to the job. They have no // functional behavior and are meant entirely as a user-specified construct // to help group and categorize jobs. // // If tags are specified from both a job args override and from options on // Insert, the latter takes precedence. Tags are not merged. Tags []string // UniqueOpts returns options relating to job uniqueness. An empty struct // avoids setting any worker-level unique options. UniqueOpts UniqueOpts } // UniqueOpts contains parameters for uniqueness for a job. // // When the options struct is uninitialized (its zero value) no uniqueness at is // enforced. As each property is initialized, it's added as a dimension on the // uniqueness matrix, and with any property on, the job's kind always counts // toward uniqueness. // // So for example, if only ByQueue is on, then for the given job kind, only a // single instance is allowed in any given queue, regardless of other properties // on the job. If both ByArgs and ByQueue are on, then for the given job kind, a // single instance is allowed for each combination of args and queues. If either // args or queue is changed on a new job, it's allowed to be inserted as a new // job. // // Uniquenes is checked at insert time by taking a Postgres advisory lock, doing // a look up for an equivalent row, and inserting only if none was found. // There's no database-level mechanism that guarantees jobs stay unique, so if // an equivalent row is inserted out of band (or batch inserted, where a unique // check doesn't occur), it's conceivable that duplicates could coexist. type UniqueOpts struct { // ByArgs indicates that uniqueness should be enforced for any specific // instance of encoded args for a job. // // Default is false, meaning that as long as any other unique property is // enabled, uniqueness will be enforced for a kind regardless of input args. ByArgs bool // ByPeriod defines uniqueness within a given period. On an insert time is // rounded down to the nearest multiple of the given period, and a job is // only inserted if there isn't an existing job that will run between then // and the next multiple of the period. // // Default is no unique period, meaning that as long as any other unique // property is enabled, uniqueness will be enforced across all jobs of the // kind in the database, regardless of when they were scheduled. ByPeriod time.Duration // ByQueue indicates that uniqueness should be enforced within each queue. // // Default is false, meaning that as long as any other unique property is // enabled, uniqueness will be enforced for a kind across all queues. ByQueue bool // ByState indicates that uniqueness should be enforced across any of the // states in the given set. For example, if the given states were // `(scheduled, running)` then a new job could be inserted even if one of // the same kind was already being worked by the queue (new jobs are // inserted as `available`). // // Unlike other unique options, ByState gets a default when it's not set for // user convenience. The default is equivalent to: // // ByState: []rivertype.JobState{rivertype.JobStateAvailable, rivertype.JobStateCompleted, rivertype.JobStateRunning, rivertype.JobStateRetryable, rivertype.JobStateScheduled} // // With this setting, any jobs of the same kind that have been completed or // discarded, but not yet cleaned out by the system, won't count towards the // uniqueness of a new insert. ByState []rivertype.JobState } // isEmpty returns true for an empty, uninitialized options struct. // // This is required because we can't check against `JobUniqueOpts{}` because // slices aren't comparable. Unfortunately it makes things a little more brittle // comparatively because any new options must also be considered here for things // to work. func (o *UniqueOpts) isEmpty() bool { return !o.ByArgs && o.ByPeriod == time.Duration(0) && !o.ByQueue && o.ByState == nil } var jobStateAll = rivertype.JobStates() //nolint:gochecknoglobals func (o *UniqueOpts) validate() error { if o.isEmpty() { return nil } if o.ByPeriod != time.Duration(0) && o.ByPeriod < 1*time.Second { return errors.New("JobUniqueOpts.ByPeriod should not be less than 1 second") } // Job states are typed, but since the underlying type is a string, users // can put anything they want in there. for _, state := range o.ByState { // This could be turned to a map lookup, but last I checked the speed // difference for tiny slice sizes is negligible, and map lookup might // even be slower. if !slices.Contains(jobStateAll, state) { return fmt.Errorf("JobUniqueOpts.ByState contains invalid state %q", state) } } return nil }
import "swiper/css"; import 'swiper/css/navigation'; import 'swiper/css/pagination'; import { Swiper, SwiperSlide } from "swiper/react"; import { Autoplay, Pagination, Navigation } from 'swiper/modules'; import { useContext, useEffect, useState } from "react"; import Slider from "./Slider"; import { Helmet } from "react-helmet"; /**** DatePicker *****/ import toast from "react-hot-toast"; /** Rating **/ import { Rating } from "@mui/material"; import StarIcon from '@mui/icons-material/Star'; import { Link, useParams } from "react-router-dom"; import useAxios from "../../hooks/useAxios"; import moment from "moment"; /**** Modal ****/ import Box from '@mui/material/Box'; import Modal from '@mui/material/Modal'; import { GlobalContext } from "../../providers/GlobalProvider"; import ReviewCard from "./ReviewCard"; const RoomDetails = () => { const axios = useAxios(); const [sliders, setSliders] = useState([]); const [room, setRoom] = useState({}); const [rating, setRating] = useState(0); const [available, setAvailable] = useState('notavailable'); const [sDate, setSDate] = useState(""); const { id } = useParams(); const [validation, setValidation] = useState(moment(new Date())) const [disabled, setDisabled] = useState(true); const [availableSeat, setAvailableSeat] = useState(0); // modal const [open, setOpen] = useState(false); const handleOpen = () => setOpen(true); const handleClose = () => setOpen(false); const style = { position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: 400, bgcolor: 'background.paper', border: '2px solid #000', boxShadow: 24, p: 4, }; const currentDate = new Date().toISOString().split('T')[0]; // Get current date in format 'YYYY-MM-DD' const [selectedDate, setSelectedDate] = useState(''); const { user } = useContext(GlobalContext); useEffect(() => { axios.get(`/api/v1/rooms/${id}`) .then(res => { setSliders(res?.data?.room_images); setRoom(res.data); // setAvailableSeat(res.data.available_rooms) if (res?.data?.count_reviews != 0) { setRating(parseFloat(res?.data?.count_stars / res?.data?.count_reviews).toFixed(2)) } }) }, []); const params = useParams(); console.log(params); const [reviews, setReviews] = useState([]); useEffect(() => { // userEmail=mdabarik19@gmail.com&roomId=65480a5e9b625d184f24e99d fetch(`https://crud-jwt-server.vercel.app/reviews/${params.id}`,{credentials:'include'}) .then(res => res.json()) .then(data => { console.log(data); setReviews(data) }) }, []) const [clicked, setClicked] = useState(false); const handleRoomBooking = () => { setClicked(true) // const currentTime = moment(new Date()); // Current time // const futureTime = moment(validation); // A future time to compare with, replace it with your desired time // if (currentTime.isBefore(futureTime, 'day')) { // console.log('valid'); // } else if (currentTime.isSame(futureTime, 'day')) { // console.log('valid'); // } else { // console.log('invalid'); // toast.error("Oh, Sorry! Invalid date."); // setDisabled(true) // } let discountPrice = parseInt(room?.price_per_night - (room?.special_offers / 100) * room?.price_per_night); if (parseInt(room?.price_per_night) == 0) { discountPrice = room?.price_per_night; } const bookingInfo = { roomId: id, roomDescription: room.room_description, pricePerNight: discountPrice, bookingDate: sDate, userEmail: user?.email, userName: user?.displayName, roomImage: sliders[0] } axios.post('/api/v1/booking', bookingInfo, { withCredentials: true }) .then(res => { if (res.data.insertedId) { toast.success('Successfully booked'); setDisabled(true) setAvailable('notavailable') setAvailableSeat(0) } }) } const handleDateChange = (date) => { // const currentTime = moment(new Date()); // Current time // const futureTime = moment(validation); // A future time to compare with, replace it with your desired time // if (currentTime.isBefore(futureTime, 'day')) { // console.log('valid'); // } else if (currentTime.isSame(futureTime, 'day')) { // console.log('valid'); // } else { // console.log('invalid'); // setDisabled(true) // setAvailable("notavailable"); // return; // } console.log(date); setSDate(date); setAvailable('notavailable'); setDisabled(true); fetch(`https://crud-jwt-server.vercel.app/api/v1/booking?date=${date}&id=${id}`, {credentials: 'include'}) .then(response => response.json()) .then(res => { console.log('available room', room.available_rooms, 'booked room', res.result.length, 'diff', parseInt(room.available_rooms) - res.result.length); const diff = parseInt(room.available_rooms) - res.result.length; setAvailableSeat(diff) console.log('available diff', availableSeat); console.log('change', res); setAvailable(`Available on ${date} (${diff} seats)`) setDisabled(false) console.log('correct'); // } }) .catch(err => { console.log(err); }) } const handleDateChange1 = (event) => { setSelectedDate(event.target.value); handleDateChange(event.target.value) setValidation(event.target.value) }; return ( <div className="my-8 w-[90%] mx-auto"> <Helmet> <title>Room Details - Hotel Booking</title> </Helmet> <div className="flex flex-col "> <div className="flex flex-col items-center justify-center my-4"> <h2 className="text-2xl md:text-3xl font-semibold text-center">Location: {room?.room_location}</h2> <p className="text-center text-[12px] md:text-sm mt-2">Check the details information of this room below</p> </div> <div className="flex flex-col md:flex-row min-h-[500px] my-6 w-full"> <div className="w-full md:w-1/2"> <div className='h-[500px] relative z-0'> <Swiper loop={true} spaceBetween={30} centeredSlides={true} autoplay={{ delay: 2500, disableOnInteraction: false, pauseOnMouseEnter: true, }} pagination={{ clickable: true, }} navigation={true} modules={[Autoplay, Pagination, Navigation]} className="mySwiper" > { sliders?.map((slider, index) => { return <SwiperSlide key={index}> <Slider key={slider._id} slider={slider}></Slider> </SwiperSlide> }) } </Swiper> </div> </div> <div className="md:flex-1 w-full md:w-1/2 space-y-1 px-5 mt-6 md:mt-0"> <h2 className="text-2xl font-bold">{room?.room_description}</h2> <h3 className="font-semibold">Price Night: ${room?.price_per_night}</h3> <div className="flex items-center gap-x-2"> <p className="font-semibold">Special Price:</p> { parseInt(room?.special_offers) == 0 ? <span>No Special Offer Available Now</span> : <> <strike>${room?.price_per_night}</strike> <p>${parseInt(room?.price_per_night - (room?.special_offers / 100) * room?.price_per_night)}</p> <p>({room.special_offers}% off)</p></> } </div> <p><span className="font-semibold">Size:</span> {room?.room_size}</p> <p><span className="font-bold">Available Seat:</span> {availableSeat == 0 ? 'Please select date for available seat' : availableSeat}</p> <div className="flex items-center gap-x-2"> <p className="font-semibold">Status:</p> <p className="px-3 py-1 rounded-lg"> { available == 'notavailable' ? <span className="bg-[orangered] px-3 py-1 text-[white]">For status select valid date</span> : <span className="bg-red-500 text-white font-bold px-3 py-1">{available}</span> } </p> </div> <p><span className="font-bold">Location: </span> <span>{room?.room_location}</span></p> <div className="flex items-center gap-3"> <span className="font-bold">Rating:</span> <Rating className="py-2 rounded-lg " name="simple-controlled" value={rating} precision={0.5} emptyIcon={<StarIcon style={{ color: 'grey' }} fontSize="inherit" />} readOnly /> <span>({room.count_reviews} reviews)</span> </div> <p> <span className="font-bold">Description: </span> {room?.room_details} </p> {/* <input className="border-2 p-3 rounded-md" onChange={(e) => { handleDateChange(e.target.value) setValidation(e.target.value) } } type="date" /> */} <input className="border-2 p-3 rounded-md" type="date" id="datePicker" name="datePicker" value={selectedDate} onChange={handleDateChange1} min={currentDate} /> <div> <div className="space-y-4"> <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <div className="flex flex-col space-y-5 my-10"> <h2 className="text-2xl font-bold text-center">Confirm your booking</h2> <div> <h2 className="font-bold">{room.room_description}</h2> <p><span className="font-bold">Room Size:</span> {room?.room_size}</p> <h3><span className="font-bold">Pricing:</span> ${room.price_per_night}</h3> <p><span className="font-bold">Location: </span> <span>{room?.room_location}</span></p> <p><span className="font-bold">Booking date:</span> {sDate}</p> </div> { clicked ? <button onClick={() => handleRoomBooking()} className="btn btn-secondary text-center" disabled>Confirm Booking</button> : <button onClick={() => handleRoomBooking()} className="btn btn-secondary text-center">Confirm Booking</button> } </div> </Box> </Modal> {/* <Button className="btn btn-primary" onClick={handleOpen}>Book Now</Button> */} { !user ? <Link className="btn btn-error" to="/login">Login to Book</Link> : disabled == true || availableSeat == 0 ? <button className="btn w-1/2 mt-2" title="select date to enable" disabled>Book Now</button> : <button onClick={() => { handleOpen() setClicked(false) }} className="btn w-1/2 btn-secondary mt-2">Book Now</button> } </div> </div> </div> </div> </div> {/* Reviews Sections */} <div className="my-8"> <div> <h2 className="text-3xl font-semibold">Reviews: {reviews.length}</h2> <p>Check the review from our previous customer</p> </div> <div className="my-3 space-y-5"> {/* single comment */} { reviews.map(card => <ReviewCard key={card._id} card={card}></ReviewCard>) } </div> </div> </div> ); }; export default RoomDetails;
export type TRecipeData = { title: string; ingredients: string[]; description: string; image: string; cookingTime: number; }; const recipeData: TRecipeData[] = [ { title: "velit in aliquet", ingredients: ["pies", "pasta", "salads"], description: "scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla", image: "penatibus", cookingTime: 56, }, { title: "non, cursus non,", ingredients: ["sandwiches", "soups", "salads", "cereals", "pies"], description: "interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus", image: "magna", cookingTime: 30, }, { title: "Pellentesque ut ipsum ac", ingredients: [ "pies", "cereals", "stews", "noodles", "salads", "sandwiches", ], description: "non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis", image: "Aenean", cookingTime: 22, }, { title: "taciti sociosqu ad", ingredients: ["soups", "desserts", "pasta", "pies", "salads", "noodles"], description: "nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla", image: "semper", cookingTime: 13, }, { title: "Ut tincidunt", ingredients: [ "salads", "noodles", "pasta", "sandwiches", "pies", "seafood", "soups", ], description: "tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et,", image: "dapibus", cookingTime: 47, }, { title: "lacus. Mauris", ingredients: ["noodles", "pasta", "cereals", "sandwiches", "pies"], description: "montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh", image: "ligula.", cookingTime: 12, }, { title: "Phasellus ornare. Fusce", ingredients: ["soups", "sandwiches", "pies", "desserts", "pasta"], description: "lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo", image: "velit.", cookingTime: 33, }, { title: "urna. Nullam", ingredients: ["stews", "salads"], description: "risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque", image: "Cras", cookingTime: 44, }, { title: "sed dolor. Fusce", ingredients: ["desserts", "cereals", "stews", "sandwiches", "salads"], description: "dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec", image: "tincidunt", cookingTime: 54, }, { title: "ipsum nunc id", ingredients: ["stews", "pasta", "soups", "salads"], description: "per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula.", image: "laoreet", cookingTime: 56, }, ]; export function getRandomRecipe(): TRecipeData { return recipeData[Math.floor(Math.random() * recipeData.length)]; }
import React, { useEffect, useState } from "react"; import Table from "@mui/material/Table"; import TableBody from "@mui/material/TableBody"; import TableCell from "@mui/material/TableCell"; import TableContainer from "@mui/material/TableContainer"; import TableHead from "@mui/material/TableHead"; import TableRow from "@mui/material/TableRow"; import Paper from "@mui/material/Paper"; import { useNavigate, Link } from "react-router-dom"; import axios from "axios"; import { useDispatch, useSelector } from "react-redux"; import { getCategories, createCategory, deleteCategory, } from "../features/categorySlice"; const Category = () => { const apiurl = "http://localhost:3001"; const dispatch = useDispatch(); const navigate = useNavigate(); useEffect(() => { dispatch(getCategories()); console.log("useeffect Called"); }, []); const { categories } = useSelector((state) => state.app); console.log(categories, "categories"); // useEffect(() => { // fetch(`${apiurl}/category/getcategories`) // .then((response) => response.json()) // .then((result) => { // console.log(result); // setData(result); // }) // .catch((error) => { // console.error("Error fetching data:", error); // }); // }, []); // const AddCategory = () => { // navigate("/addcategory"); // }; const handleAddCategory = () => { navigate("/addcategory"); }; const handleDeletedata = (id) => { console.log(id); if (window.confirm("Do you want to delete the category?")) { dispatch(deleteCategory(id)); navigate("/category"); } }; return ( <> <div className="category-bar w-[80%] mx-auto h-[70px] border border-grey flex justify-between items-center px-4"> <div className="heading"> <span className="font-bold">Category</span> </div> <div className="search-input ml-20"> <input className="border border-black rounded-md w-[250px] p-2 " type="text" placeholder="Enter Text" /> </div> <div className="add-button bg-[#662671] p-[10px] rounded-md text-white"> <button onClick={handleAddCategory}>Add Category</button> </div> </div> <div className="table-container w-[80%] mx-auto mt-2"> <TableContainer component={Paper}> <Table> <TableHead> <TableRow> <TableCell style={{ width: "50px" }} align="center"> ID </TableCell> <TableCell align="center">Name</TableCell> <TableCell align="center">Description</TableCell> <TableCell align="center">Status</TableCell> <TableCell align="center">Actions</TableCell> </TableRow> </TableHead> <TableBody> {categories && categories.map((categorie) => ( <TableRow key={categorie._id}> <TableCell align="center">{categorie._id}</TableCell> <TableCell align="center">{categorie.name}</TableCell> <TableCell align="center"> {categorie.description} </TableCell> <TableCell align="center"> {categorie.status == true ? "Active" : "Not Active"} </TableCell> <TableCell align="center"> <Link className="mr-3" to={`/addcategory/${categorie._id}`} > Edit data </Link> <Link onClick={() => handleDeletedata(categorie._id)}> Delete </Link> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </div> </> ); }; export default Category;
import type { PostFrontmatter } from '../../types/Post' import { FC } from 'react' import Link from 'next/link' import { formatToReadableDate } from '../../helpers/dateHelper' interface Props { post: PostFrontmatter } const PostCard: FC<Props> = ({ post }) => { const getDateTime = () => { return new Date(post.publishedDate).toISOString() } return ( <> <Link href={`/posts/${post.slug}`} className="card"> {/* <a className={`${styles.postCard} rounded shadow-lg shadow-gray-200 dark:shadow-gray-900 bg-white dark:bg-gray-800 duration-300`}> */} <h1 className="card-title">{post.title}</h1> <div className="card-meta"> <time dateTime={getDateTime()}> {formatToReadableDate(post.publishedDate)} </time> </div> </Link> </> ) } export default PostCard
import React, { createContext, useContext, useReducer } from "react" import { lk21Reducer, initialState } from "./lk21_reducer" const LK21StateContext = createContext() const LK21DispatchContext = createContext() function LK21Provider({children}) { const [state, dispatch] = useReducer(lk21Reducer, initialState) const thunkDispatch = React.useCallback( (action) => typeof action === 'function' ? action(dispatch, state) : action, [] ); return ( <LK21StateContext.Provider value={state}> <LK21DispatchContext.Provider value={thunkDispatch}> {children} </LK21DispatchContext.Provider> </LK21StateContext.Provider> ) } function useLK21State() { const context = useContext(LK21StateContext) if (context === undefined) throw new Error('useLK21State must be within a LK21Provider') return context } function useLK21Dispatch() { const context = useContext(LK21DispatchContext) if (context === undefined) throw new Error('useLK21Dispatch must be within a LK21Provider') return context } export { LK21Provider, useLK21Dispatch, useLK21State }
#pragma once #include <glm/glm.hpp> namespace Orca { class OrthographicCamera { public: OrthographicCamera(float left, float right, float bottom, float top); void SetPosition(const glm::vec3& position) { m_Position = position; RecalculateViewMatrix(); } void SetRotation(const float rotation) { m_Rotation = rotation; RecalculateViewMatrix(); } inline const glm::vec3& GetPosition() const { return m_Position; } inline const float GetRotation() const { return m_Rotation; } void SetProjection(float left, float right, float bottom, float top); inline const glm::mat4& GetViewMatrix() const { return m_ViewMatrix; } inline const glm::mat4& GetProjectionMatrix() const { return m_ProjectionMatrix; } inline const glm::mat4& GetViewProjectionMatrix() const { return m_VPMatrix; } private: void RecalculateViewMatrix(); private: glm::mat4 m_ProjectionMatrix; glm::mat4 m_ViewMatrix; glm::mat4 m_VPMatrix; glm::vec3 m_Position; float m_Rotation = 0.0f; }; }
<script> const TYPE = { REJECTED: 'rejected', FUFILLED: 'fufilled', } function foo (type) { return new Promise((resolve, reject) => { if (type === TYPE.FUFILLED) { resolve('foo') } else { reject('err') } }) } foo(TYPE.REJECTED) .catch((err) => { console.log(err) }) .finally(() => { console.log('finally reject') }) foo(TYPE.FUFILLED) .then((res) => { console.log(res) }) .catch((err) => { console.log(err) }) .finally(() => { console.log('finally resolve') }) </script>
import React from "react"; import { Flex } from "antd"; import { SecondaryButton } from "."; import { LoadMoreText, LoadingText, NoMoreDataText, } from "@/util/language-setting/texts/TranslatedTexts"; const LoadMoreButton = ({ fetchNextPage, hasNextPage, isFetchingNextPage }) => { return ( <Flex align="center" justify="center"> <SecondaryButton clickEvent={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage} > {isFetchingNextPage ? ( <LoadingText /> ) : hasNextPage ? ( <LoadMoreText /> ) : ( <NoMoreDataText /> )} </SecondaryButton> </Flex> ); }; export default LoadMoreButton;
import 'package:firebase_auth/firebase_auth.dart'; import 'package:frederic/backend/authentication/frederic_user.dart'; abstract class FredericAuthInterface { Future<FredericUser> signUp( {required String email, required String name, required String password}); Future<FredericUser> logIn({required String email, required String password}); Future<FredericUser> logInOAuth(OAuthCredential credential, {String? name}); Future<FredericUser> getUserData(String uid, String email); Future<void> logOut(); void registerDataChangedListener( void Function(FredericUser, bool) onDataChanged); Future<void> update(FredericUser user); Future<bool> reAuthenticate(FredericUser user, String password); Future<void> changePassword(FredericUser user, String newPassword); Future<void> deleteAccount(FredericUser user); }
import React, { useState, useEffect } from 'react'; import { hello_backend } from 'declarations/hello_backend'; import ProcessingModal from './Modal'; import NewEntryModal from './NewModal'; // Import the modal component function App() { const [isProcessing, setIsProcessing] = useState(true); const [isModalOpen, setIsModalOpen] = useState(false); useEffect(() => { refreshOffers(); setIsProcessing(false); }, []); async function handleSubmit(event) { event.preventDefault(); setIsProcessing(true); refreshOffers(); setIsProcessing(false); return false; } // Function to open the modal const openModal = () => { setIsModalOpen(true); } // Function to close the modal const closeModal = () => { setIsModalOpen(false); setIsProcessing(true); refreshOffers(); setIsProcessing(false); } // call function on backend async function doAction(offernr) { setIsProcessing(true); await hello_backend.acquireOffer(offernr); refreshOffers(); setIsProcessing(false); } // Assuming you have a function to call the getOpenOffers method function refreshOffers () { hello_backend.getOpenOffers().then(offers => { // Create table let table = document.createElement('table'); table.className = 'table-community'; // Create table header let thead = document.createElement('thead'); let headerRow = document.createElement('tr'); ['Gift', 'Offered By', '', 'Description', 'Exchange', ''].forEach(headerText => { let th = document.createElement('th'); th.appendChild(document.createTextNode(headerText)); headerRow.appendChild(th); }); thead.appendChild(headerRow); table.appendChild(thead); // Create table body let tbody = document.createElement('tbody'); offers.forEach(offer => { let row = document.createElement('tr'); let img =""; if (offer.url != "") img = '<img class="img-in-table" src="' + offer.url + '">'; [offer.number, offer.offeredBy, img, offer.description ].forEach(text => { let td = document.createElement('td'); td.innerHTML = text; row.appendChild(td); }); // add price let tdPrice = document.createElement('td'); var text = "<table cellspacing=5><tr>"; if (offer.orangePrice) { text += "<td>" + offer.orangePrice + '</td><td><img src="/orange button x 42.jpg"></td>'; } if (offer.greenPrice) { if (offer.orangePrice) text += "<td>+</td>"; text += "<td>" + offer.greenPrice + '</td><td><img src="/green button x 42.jpg"></td>'; } text += "</tr></table>"; tdPrice.innerHTML = text; row.appendChild(tdPrice); // add button let tdButton = document.createElement('td'); let button = document.createElement('button'); button.className = 'button-community'; // Sets the class button.innerHTML = 'Accept'; // Add the text you want on the button button.onclick = function() { doAction(offer.number); }; tdButton.appendChild(button); row.appendChild(tdButton); // row ready tbody.appendChild(row); }); table.appendChild(tbody); let divElement = document.getElementById('offers'); divElement.innerHTML = ""; divElement.appendChild (table); }).catch(error => { console.error('Error retrieving offers:', error); }); } return ( <main> <table class="full-width-table"><tr> <td><button onClick={openModal} class="button-community">Announce&nbsp;Offer</button></td> <td><img src="/moos bazar banner.jpg" alt="Moos Bazar Banner" class="full-width-image"/></td> <td><form action="#" onSubmit={handleSubmit}><button type="submit" class="button-community">Refresh</button></form></td> </tr></table> <div id="offers"></div> <NewEntryModal isOpen={isModalOpen} onClose={closeModal} /> {isProcessing && <ProcessingModal></ProcessingModal>} </main> ); } export default App;
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <title>Управление Студентами</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-md bg-dark navbar-dark"> <a class="navbar-brand" href="#">Управление Студентами</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" th:href="@{/students}">Управление Студентами</a> </li> </ul> </div> </nav> <br> <br> <div class = "container"> <div class = "row"> <div class ="col-lg-6 col-md-6 col-sm-6 container justify-content-center card"> <h1 class = "text-center"> Добавить нового студента </h1> <div class = "card-body"> <form th:action="@{/students}" th:object = "${student}" method="POST"> <div class ="form-group"> <label> Имя </label> <input type = "text" name = "firstName" th:field = "*{firstName}" class = "form-control" placeholder="" /> </div> <div class ="form-group"> <label> Фамилия </label> <input type = "text" name = "lastName" th:field = "*{lastName}" class = "form-control" placeholder="" /> </div> <div class ="form-group"> <label> Почтовый адрес </label> <input type = "text" name = "email" th:field = "*{email}" class = "form-control" placeholder="" /> </div> <div class = "box-footer"> <button type="submit" class = "btn btn-primary"> Подтвердить </button> </div> </form> </div> </div> </div> </div> </body> </html>
import 'package:flutter_test/flutter_test.dart'; import 'package:voice_chat_app/features/talks/data/talks_repository.dart'; import 'package:fake_cloud_firestore/fake_cloud_firestore.dart'; import 'package:voice_chat_app/features/talks/domain/talk.dart'; // import 'dart:async'; // import 'dart:developer'; // import 'dart:io'; // import 'package:flutter/foundation.dart'; void main() { late FakeFirebaseFirestore mockFirestore; late TalksRepository talksRepository; late Talk talk1; late String uid; Map<String, dynamic> talkMap1 = { 'roomId': null, 'iconUrl': 'url', 'name': 'name', 'unreadCount': 5, 'updatedAt': '2023-11-12 12:10:30', 'roomType': 1, 'latestMessageType': 2, }; Map<String, dynamic> talkMap2 = { 'roomId': null, 'iconUrl': 'url', 'name': 'name', 'unreadCount': 5, 'updatedAt': '2023-11-12 18:10:22', 'roomType': 2, 'latestMessageType': 2, }; Map<String, dynamic> talkMap3 = { 'roomId': null, 'iconUrl': 'url', 'name': 'name', 'unreadCount': 4, 'updatedAt': '2023-12-12 12:10:30', 'roomType': 1, 'latestMessageType': 2, }; setUp(() { mockFirestore = FakeFirebaseFirestore(); talk1 = Talk.fromMap(talkMap1); talksRepository = TalksRepository(mockFirestore); uid = 'test-uid'; }); group('add talk', () { test('add talk to empty database', () async { // run addTalk await talksRepository.addTalk(uid: uid, talk: talk1); // check data is added to firestore final snapshot = await mockFirestore.collection('users/$uid/attendingRooms').get(); expect(snapshot.docs[0].data(), equals(talk1.toMap())); }); test('add talk to non empty database', () async { // add talk to firestore await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap2); // run addTalk await talksRepository.addTalk(uid: uid, talk: talk1); // check data is added to firestore final snapshot = await mockFirestore.collection('users/$uid/attendingRooms').get(); expect(snapshot.docs[0].data(), equals(talkMap2)); expect(snapshot.docs[1].data(), equals(talk1.toMap())); }); }); group('update talk', () { test('update', () async { // add talk to firestore await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap3); // set document id to talk final snapshot1 = await mockFirestore.collection('users/$uid/attendingRooms').get(); talk1.roomId = snapshot1.docs[0].id; // run updateTalk await talksRepository.updateTalk(uid: uid, talk: talk1); // check data is updated final snapshot2 = await mockFirestore.collection('users/$uid/attendingRooms').get(); expect(snapshot2.docs[0].data(), equals(talk1.toMap())); }); }); group('delete talk', () { test('delete', () async { // add talk to firestore await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap1); // set document id to talk final snapshot1 = await mockFirestore.collection('users/$uid/attendingRooms').get(); // run deleteTalk await talksRepository.deleteTalk(uid: uid, talkId: snapshot1.docs[0].id); // check data is deleted final snapshot2 = await mockFirestore.collection('users/$uid/attendingRooms').get(); expect(snapshot2.docs.length, 0); }); }); group('query talk', () { test('query from empty database', () async { // run queryTalks final snapshot = await talksRepository.queryTalks(uid: uid).get(); // check data is empty expect(snapshot.docs.length, 0); }); test('query from database with one entry', () async { // add talk to firestore await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap1); // run queryTalks final snapshot = await talksRepository.queryTalks(uid: uid).get(); // check data is added to firestore expect(snapshot.docs[0].data().toMap(), equals(talkMap1)); }); test('query from database with more than one entries', () async { // add talk to firestore await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap2); await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap3); await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap1); // run queryTalks final snapshot = await talksRepository.queryTalks(uid: uid).get(); // check data is added to firestore // data should be sorted by updatedAt in descending order expect(snapshot.docs[0].data().toMap(), equals(talkMap3)); expect(snapshot.docs[1].data().toMap(), equals(talkMap2)); expect(snapshot.docs[2].data().toMap(), equals(talkMap1)); }); }); group('watch talk', () { test('watch the first stream', () async { // add talk to firestore final convertedDocument = await mockFirestore .collection('users/$uid/attendingRooms') .doc('test') .withConverter<Talk>( fromFirestore: (snapshot, _) => Talk.fromMap(snapshot.data()!), toFirestore: (talk, _) => talk.toMap(), ); await convertedDocument.set(talk1); // run watchTalk final stream = talksRepository.watchTalk(uid: uid, talkId: 'test'); //check the stream expectLater( stream.first .then((value) => {expect(value.toMap(), equals(talkMap1))}), completes); }); test('watch the subsequent stream after change data in database', () async { // add talk to firestore // we need to use converted document reference to set/update data because of the issue of fake_cloud_firestore // bug report is here: https://github.com/atn832/fake_cloud_firestore/issues/254 final convertedDocument = await mockFirestore .collection('users/$uid/attendingRooms') .doc('test') .withConverter<Talk>( fromFirestore: (snapshot, _) => Talk.fromMap(snapshot.data()!), toFirestore: (talk, _) => talk.toMap(), ); //set initial data await convertedDocument.set(talk1); // run watchTalk final stream = talksRepository.watchTalk(uid: uid, talkId: 'test'); expectLater( stream, emitsInOrder([ predicate((Talk talk) => equals(talk.toMap()).matches(talkMap1, {})), predicate((Talk talk) => equals(talk.toMap()).matches(talkMap2, {})), ]), ); // update data await convertedDocument.update(talkMap2); }, timeout: const Timeout(Duration(milliseconds: 1000))); test('watch the subsequent stream after delete data in database', () async { //add talk to firestore final convertedDocument = await mockFirestore .collection('users/$uid/attendingRooms') .doc('test') .withConverter<Talk>( fromFirestore: (snapshot, _) => Talk.fromMap(snapshot.data()!), toFirestore: (talk, _) => talk.toMap(), ); //set initial data await convertedDocument.set(talk1); // run watchTalk final stream = talksRepository.watchTalk(uid: uid, talkId: 'test'); expectLater( stream, emitsInOrder([ predicate((Talk talk) => equals(talk.toMap()).matches(talkMap1, {})), ]), ); // delete data await convertedDocument.delete(); }, timeout: const Timeout(Duration(milliseconds: 1000))); }); group('watch talks', () { // cannot use fake_cloud_firestore to test this function because of the issue of fake_cloud_firestore // bug report is here: // https://github.com/atn832/fake_cloud_firestore/issues/224 test('watch the first stream', () async { // add talk to firestore // not sure we need to use converted collection reference final convertedCollection = await mockFirestore .collection('users/$uid/attendingRooms') .withConverter<Talk>( fromFirestore: (snapshot, _) => Talk.fromMap(snapshot.data()!), toFirestore: (talk, _) => talk.toMap(), ); convertedCollection.add(talk1); // // run watchTalk // final stream = talksRepository.watchTalks(uid: uid); // int num = 0; // stream.listen( // (data) { // debugPrint('Received data $num: $data'); // num += 1; // }, // onError: (error) { // debugPrint('Error: $error'); // } // ); // //check the stream // expectLater(stream.first.then((value) => { // expect(value[0].toMap(), equals(talkMap1)) // }), completes); }); test('watch the subsequent stream after add data to firestore', () async { // add talk to firestore final convertedCollection = await mockFirestore .collection('users/$uid/attendingRooms') .withConverter<Talk>( fromFirestore: (snapshot, _) => Talk.fromMap(snapshot.data()!), toFirestore: (talk, _) => talk.toMap(), ); convertedCollection.add(talk1); // // run watchTalk // final stream = talksRepository.watchTalks(uid: uid); // int num = 0; // stream.listen( // (data) { // debugPrint('Received data $num: $data'); // num += 1; // }, // onError: (error) { // debugPrint('Error: $error'); // } // ); // //check the stream // expectLater( // stream, // emitsInOrder( // [ // predicate<List<Talk>>( // (d) => equals(talkMap1).matches( // d[0].toMap(), // {}, // ), // ), // // predicate<List<Talk>>( // // (d) => equals(talkMap2).matches( // // d[0].toMap(), // // {}, // // ), // // ), // ], // ), // ); //add talk to firestore await convertedCollection.add(Talk.fromMap(talkMap2)); }); test('watch the subsequent stream after delete data in firestore', () async { // add talk to firestore await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap1); await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap2); // // run watchTalk // final stream = talksRepository.watchTalks(uid: uid); //check the stream // expectLater( // stream, // emitsInOrder( // [ // // predicate( // // (List<Talk> talks) { // // //if (talks.length != 2) return false; // // return equals(talkMap1).matches(talks[0].toMap(), {}) && // // equals(talkMap2).matches(talks[1].toMap(), {}); // // }), // // predicate<List<Talk>>( // // (list) { // // //if (list.length != 1) return false; // // return equals(talkMap1).matches(list[0].toMap(), {}); // // }), // predicate<List<Talk>>( // (d) => equals(talkMap1).matches( // d[0].toMap(), // {}, // ), // ), // ], // ), // ); // delete talk from firestore final snapshot1 = await mockFirestore.collection('users/$uid/attendingRooms').get(); await mockFirestore .collection('users/$uid/attendingRooms') .doc(snapshot1.docs[0].id) .delete(); }); }); group('fetch talks', () { test('fetch from empty database', () async { // run fetchTalks final talks = await talksRepository.fetchTalks(uid: uid); // check data is empty expect(talks.length, 0); }); test('fetch from database with one entry', () async { // add talk to firestore await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap1); // run fetchTalks final talks = await talksRepository.fetchTalks(uid: uid); // check data is added to firestore expect(talks[0].toMap(), equals(talkMap1)); }); test('fetch from database with more than one entries', () async { // add talk to firestore await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap2); await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap3); await mockFirestore.collection('users/$uid/attendingRooms').add(talkMap1); // run fetchTalks final talks = await talksRepository.fetchTalks(uid: uid); // check data is added to firestore // data should be sorted by updatedAt in descending order expect(talks[0].toMap(), equals(talkMap3)); expect(talks[1].toMap(), equals(talkMap2)); expect(talks[2].toMap(), equals(talkMap1)); }); }); }
package environs; /** * Library and license helper thread * ------------------------------------------------------------------ * Copyright (c) Chi-Tai Dang * * @author Chi-Tai Dang * @version 1.0 * @remarks * * This file is part of the Environs framework developed at the * Lab for Human Centered Multimedia of the University of Augsburg. * http://hcm-lab.de/environs * * Environ is free software; you can redistribute it and/or modify * it under the terms of the Eclipse Public License v1.0. * A copy of the license may be obtained at: * http://www.eclipse.org/org/documents/epl-v10.html * -------------------------------------------------------------------- */ import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; class LibLicThread extends Thread implements Runnable { private static final String className = "LibLicThread . . . . . ."; public String libName; public String libUrl; public String licenseUrl; public interface OnActionListener { void onAction(); } OnActionListener actionListener; public void setActionListener(OnActionListener listener) { actionListener = listener; } @Override public void run() { if (Utils.isDebug) Utils.Log ( 3, className, "Thread started"); try { final Activity act = Environs.currentActivity; if ( act == null ) { Utils.LogE ( className, "LibLicThread: We need to ask for permission, but no activity is available."); return; } if (Utils.isDebug) Utils.Log ( 3, className, "Thread ..." ); if ( !Libs.load3rd ( libName, "bz2", libUrl, licenseUrl ) ) { Utils.LogE ( className, "LibLicThread: Download or installation of " + libName + " has failed."); // Error handling ... return; } // Show license final String license = Libs.getLicense(libName); if ( license == null ) { if (Utils.isDebug) Utils.Log ( 3, className, "LibLicThread: License for " + libName + " is missing."); // Error handling ... if (actionListener != null) actionListener.onAction(); } else { //Utils.Log ( className, license); act.runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(act); String modName = libName; if (modName.startsWith("lib")) modName = modName.substring(3); alertDialog.setTitle("License " + libName); alertDialog.setMessage(license); alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (Utils.isDebug) Utils.Log ( 3, className, "LibLicThread: License for " + libName + " accepted." ); if (actionListener != null) actionListener.onAction(); } }); alertDialog.show(); } }); } } catch (Exception ex) { Utils.LogE ( className, "LibLicThread: " + ex.getMessage() ); ex.printStackTrace(); } if (Utils.isDebug) Utils.Log ( 3, className, "Thread terminated!" ); } }
import { Input } from 'antd'; import Form from 'antd/lib/form'; import Text from 'antd/lib/typography/Text'; import React from 'react'; import { Fragment } from 'react'; import { getHelp, getValidationStatus } from '../../util/formik.util'; const CustomInput = ({ formikProps, fieldName, label, size = 'small' }) => { return ( <Fragment> <Text strong>{label}</Text> <Form.Item style={{ marginTop: '4px' }} validateStatus={getValidationStatus(formikProps, fieldName)} help={getHelp(formikProps, fieldName)} > <Input style={{ paddingTop: '9px', marginBottom: '9px' }} size={size} value={formikProps.values[fieldName]} onChange={formikProps.handleChange(fieldName)} /> </Form.Item> </Fragment> ); }; export default CustomInput;
package assigment_day2_day10.bean; import java.time.LocalDate; public class Experience extends Candidate { private int ExpInYear; private String ProSkill; public Experience() { } public Experience(String fullName, LocalDate birthDay, String phone, String email, int candidate_type, int candidate_count, int expInYear, String proSkill) { super(fullName, birthDay, phone, email, candidate_type, candidate_count); ExpInYear = expInYear; ProSkill = proSkill; } public int getExpInYear() { return ExpInYear; } public void setExpInYear(int expInYear) { ExpInYear = expInYear; } public String getProSkill() { return ProSkill; } public void setProSkill(String proSkill) { ProSkill = proSkill; } @Override public void ShowInfo() { System.out.println(this.toString()); } @Override public String toString() { return super.toString() + " ||Experience{" + "ExpInYear=" + ExpInYear + ", ProSkill='" + ProSkill + '\'' + '}'; } }
--- title: PerformanceResourceTiming.connectEnd slug: Web/API/PerformanceResourceTiming/connectEnd l10n: sourceCommit: b3477f90eb235d08fe196373466a725050f43862 --- {{APIRef("Performance API")}} **`connectEnd`** は読み取り専用プロパティで、ブラウザーがリソースを取得するためにサーバーへの接続を確立し終わった直後の {{domxref("DOMHighResTimeStamp","timestamp")}} を返します。このタイムスタンプ値には、トランスポート接続を確立するための時間、TLS ハンドシェイクや [SOCKS](https://ja.wikipedia.org/wiki/SOCKS) 認証などの他の時間が含まれます。 ## 値 `connectEnd` プロパティは以下の値を取ります。 - 接続が確立された後の時間を表す {{domxref("DOMHighResTimeStamp")}}。 - リソースがキャッシュから即座に取得された場合は `0` です。 - リソースがオリジン間リクエストで取得され、HTTP の {{HTTPHeader("Timing-Allow-Origin")}} レスポンスヘッダーが使用されなかった場合は `0` となります。 ## 例 ### TCP ハンドシェイク時間の計測 `connectEnd` と {{domxref("PerformanceResourceTiming.connectStart", "connectStart")}} プロパティを使用して、 TCP ハンドシェイクが発生したときにどれくらいかかるかを計測することができます。 ```js const tcp = entry.connectEnd - entry.connectStart; ``` {{domxref("PerformanceObserver")}} を使用した例です。このオブジェクトは、新しい `resource` パフォーマンス項目がブラウザーのパフォーマンスタイムラインに記録されると、それを通知します。オブザーバーが作成される前の項目にアクセスするために `buffered` オプションを使用します。 ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { const tcp = entry.connectEnd - entry.connectStart; if (tcp > 0) { console.log(`${entry.name}: TCP handshake duration: ${tcp}ms`); } }); }); observer.observe({ type: "resource", buffered: true }); ``` {{domxref("Performance.getEntriesByType()")}} を使用した例です。このメソッドを呼び出した時点でブラウザー上のパフォーマンスタイムラインに存在する `resource` パフォーマンス項目のみを表示します。 ```js const resources = performance.getEntriesByType("resource"); resources.forEach((entry) => { const tcp = entry.connectEnd - entry.connectStart; if (tcp > 0) { console.log(`${entry.name}: TCP handshake duration: ${tcp}ms`); } }); ``` ### オリジン間のタイミング情報 `connectEnd` プロパティの値が `0` である場合、そのリソースはオリジン間リクエストである可能性があります。オリジン間のタイミング情報を見るためには、HTTP の {{HTTPHeader("Timing-Allow-Origin")}} レスポンスヘッダーを設定する必要があります。 例えば、`https://developer.mozilla.org` にタイミングリソースを見ることを許可するには、オリジン間リソースで次のものを送信する必要があります。 ```http Timing-Allow-Origin: https://developer.mozilla.org ``` ## 仕様書 {{Specifications}} ## ブラウザーの互換性 {{Compat}} ## 関連情報 - {{HTTPHeader("Timing-Allow-Origin")}}
const asyncHandler = require("express-async-handler"); const User = require("../models/userModel"); const generateToken = require("../config/generateToken"); // const expressAsyncHandler = require("express-async-handler"); // const registerUser =async(req,res)=>{ // console.log("signUP called---",req.body) // try{ // const {name,email,password,pic} = req.body // if(!name || !email || !password){ // res.status(400).json({msg:"Please Enter all the Fields"}); // throw new Error("Please Enter all the Fields") // } // const userExists = await User.findOne({email}); // if(userExists){ // res.status(400).json({msg:"User already exists"}); // throw new Error("User already exists") // } // const user = await User.create({ // name,email,password,pic:pic // }) // if(user){ // res.status(201).json({ // _id:user._id, // name:user.name, // email:user.email, // pic:user.pic, // token:generateToken(user._id) // }) // } else { // res.status(400).json({msg:"Failed to create the user"}); // throw new Error("Failed to Create the User") // } // } catch(err){ // res.status(400).json({msg:err.message}) // console.log("error-------------",err.message); // } // } const registerUser = asyncHandler(async (req, res) => { const { name, email, password, pic } = req.body; if (!name || !email || !password) { res.status(400); throw new Error("Please Enter all the Feilds"); } const userExists = await User.findOne({ email }); if (userExists) { res.status(400); throw new Error("User already exists"); } const user = await User.create({ name, email, password, pic, }); if (user) { res.status(201).json({ _id: user._id, name: user.name, email: user.email, isAdmin: user.isAdmin, pic: user.pic, token: generateToken(user._id), }); } else { res.status(400); throw new Error("User not found"); } }); const authUser = asyncHandler(async (req,res)=>{ const {email,password}=req.body; const user = await User.findOne({email}) if(user && (await user.matchPassword(password))){ res.json({ _id:user._id, name:user.name, email:user.email, pic:user.pic, token:generateToken(user._id) }) } else { res.status(400).json({msg:"Invalid email or password"}); throw new Error("Invalid email or password") } }) const allUsers = asyncHandler(async (req, res) => { const keyword = req.query.search ? { $or: [ { name: { $regex: req.query.search, $options: "i" } }, { email: { $regex: req.query.search, $options: "i" } }, //$options:"i" means caseinsensitive , $regex-->like to includes to filter data in mongodb ], } : {}; //$ne--not equal to const users = await User.find(keyword).find({ _id: { $ne: req.user._id } }); res.send(users); }); module.exports = {registerUser,authUser,allUsers}
import { FC, useEffect, useState } from 'react'; import { useSpring, animated } from 'react-spring'; import { ProductModal } from '../../../models/product/product-modal'; import { getFeaturedProduct } from '../../../utils/firebase/database/productsDatabase'; import { getProductImages } from '../../../utils/firebase/storage/productStorage'; import Loading from '../../loading/Loading'; import CallUs from './CallUs'; import QuickView from './QuickView'; interface SingleProductProps { name: string desc: string price: number discount: number uid: string colors: string[] capacity: string[] } const SingleProduct: FC<SingleProductProps> = ({ name, desc, price, discount, uid, colors, capacity }) => { const [open, setOpen] = useState<boolean>(false); const [quickViewOpen, setQuickViewOpen] = useState(false); const [buyNowToggle ,setBuyNowToggle ] = useState(false); const [images, setImages] = useState<string[]>([]) const spring = useSpring({ opacity: open ? 1 : 0, height: open ? 40 : 0, }); useEffect(() => { async function getImages() { const urls = await getProductImages(uid as string); setImages(urls); } getImages(); }) return ( <> <div className='flex flex-col p-5 items-center w-80 rounded-lg select-none cursor-pointer border hover:(shadow-lg) duration-500' onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)} > { images.length > 0 && <img src={images[0]} alt={name} className='h-56 rounded-lg' /> } <span className='font-bold uppercase my-3'>{name}</span> <span className='text-justify text-gray-500 text-sm'>{desc.substring(0, 50)}...</span> <div className='flex flex-col items-center mt-3'> <div className='flex gap-3 items-end'> <span className='text-xl text-red-500 font-bold'>{discount}%</span> <span className='text-2xl font-bold tracking-wide'>Rs. {price - (price * discount / 100)}</span> </div> <small className='line-through font-bold font-mono text-lg'>MRP. <span className='text-red-500'>{price}</span></small> </div> <animated.div className='flex gap-2 mt-5 h-auto' style={spring}> <button className='btn btn-red-outline' onClick={() => setBuyNowToggle(!buyNowToggle)}>Buy Now</button> <button className='btn btn-red-outline' onClick={() => setQuickViewOpen(!quickViewOpen)}>Quick View</button> </animated.div> </div> { quickViewOpen && <QuickView images={images!} name={name} desc={desc} price={price} discount={discount} uid={uid} colors={colors} capacity={capacity} setIsOpen={(e) => setQuickViewOpen(e)} /> } { buyNowToggle && <CallUs setIsOpen={(e) => setBuyNowToggle(e)}/> } </> ) } const FeaturedProduct = () => { const [products, setProducts] = useState<ProductModal[]>([]); const [loading, setLoading] = useState(false); useEffect(() => { async function getFeaturedProductDetails() { setLoading(true); const response = await getFeaturedProduct(); setProducts(response); setLoading(false); } getFeaturedProductDetails(); }, []) return ( <div className='py-10'> <section className='flex flex-col items-center text-center'> <span className='font-bold uppercase tracking-wide text-4xl text-red-500'>Featured Products</span> <span className='mt-2 font-mono font-xl uppercase tracking-widest'>Choose from the best heating solution</span> </section> { loading && <Loading /> } <section className='flex justify-evenly flex-wrap gap-5 my-10'> { !loading && products.map((item, key) => ( <SingleProduct key={key} name={item.name} desc={item.desc} price={item.price} discount={item.discount} uid={item.uid! as string} colors={item.colors} capacity={item.capacity} /> )) } </section> </div> ) } export default FeaturedProduct
import { color } from '@assets/styles/color'; import BorderSeparator from '@components/border_separator'; import SquareIconButton from '@components/buttons/square_icon_button/SquareIconButton'; import TextButton from '@components/buttons/text_button'; import NotAButton from '@components/not_a_button'; import TextPair from '@components/text_pair/TextPair'; import { SETTINGS } from '@stores/appSettingsStore'; import AddSelectedToQueueModal from '@containers/modals/add_selected_to_queue_modal'; import { DEFAULT_MODAL, modal } from '@libs/overlay'; import { BookedAppointment } from '@models/instance.model'; import XMark from 'toSvg/x_mark.svg?icon'; import { format } from 'date-fns'; import './style/index.scss'; import { useCancelAppointmentMutation } from '@redux/instance/Appointment/AppointmentApi'; import AlertModal from '@containers/modals/dialog_modal'; import SmallUserStatus from '@components/small_user_status'; import MemberBigCard from '@containers/modals/member_big_card'; export default function BookedAppointmentItem({ patientName, bookedFor, id, patientId, member, subject, state, }: BookedAppointment) { const [CancelAppointment] = useCancelAppointmentMutation(); return ( <div className="booked-appointment-item"> <TextPair gap={2} second="Patient" first={{ text: patientName, fontSize: 14 }} reversed /> <BorderSeparator direction="vertical" /> <TextPair gap={2} second="Booked in" first={{ text: format(bookedFor, SETTINGS.dayFormat), fontSize: 14 }} reversed /> {subject && ( <> <BorderSeparator direction="vertical" /> <TextPair gap={2} first={{ text: subject, fontSize: 14 }} second="Subject" reversed /> </> )} <BorderSeparator direction="vertical" /> { <TextPair gap={2} first={ <SmallUserStatus alt={member.name} name={member.name} imgSrc={member.avatar} onClick={() => { modal(<MemberBigCard id={member.id} />, DEFAULT_MODAL).open(); }} /> } second="Booked by" reversed /> } <BorderSeparator direction="vertical" /> {state == 'PANDING' ? ( <> <TextButton text="Assign to queue" backgroundColor={color.cold_blue} fontColor={color.white} fontSize={12} padding="5px 10px" onPress={() => { modal( () => ( <AddSelectedToQueueModal id={patientId} name={patientName} appointmentId={id} /> ), DEFAULT_MODAL, ).open(); }} /> <SquareIconButton Icon={XMark} backgroundColor={color.hot_red} onPress={() => { modal( ({ close }) => ( <AlertModal title="Are you sure you want to cancel this appointment ?" description="After confirming appointment will no longer booked" status="warning" controls={ <> <TextButton text="Cancel" backgroundColor={color.cold_blue} onPress={() => { close(); }} /> <TextButton text="Confirm" backgroundColor={color.hot_red} onPress={() => { CancelAppointment(id); close(); }} /> </> } ></AlertModal> ), { closeOnClickOutside: true, isDimmed: true, clickThrough: false, }, ).open(); }} /> </> ) : ( <NotAButton text={'In queue'} color={color.warm_orange} /> )} </div> ); }
import { Modal } from '@mantine/core'; import { ReactNode } from 'react'; type Props = { children: ReactNode; className?: string | undefined; isOpen: boolean; onClose: () => void; centered?: boolean; size: string; }; const CustomModal = ({ children, className, isOpen, onClose, centered, size }: Props) => { const modalClassNames = { root: 'z-[9999]', modal: `bg-gray-800 ${size} rounded-2xl p-0 overflow-hidden`, header: 'hidden', body: 'h-full w-full overflow-hidden', overlay: 'z-[0]' }; return ( <Modal className={className || ''} opened={isOpen} onClose={onClose} centered={centered || false} classNames={modalClassNames} overlayOpacity={0.25} overlayBlur={6} > {children} </Modal> ); }; export default CustomModal;
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ProductsComponent } from './products/products.component'; import { StoreModule} from '@ngrx/store' import { productReducer } from './store-data/product.reducer'; import { FormsModule } from '@angular/forms' import { StoreDevtoolsModule } from '@ngrx/store-devtools'; import { environment } from 'src/environments/environment'; @NgModule({ declarations: [ AppComponent, ProductsComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, StoreModule.forRoot({'products' : productReducer}, {}), StoreDevtoolsModule.instrument({ name:'sample app', maxAge: 25, logOnly: environment.production }) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateOffersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('offers', function (Blueprint $table) { $table->id(); $table->string('price'); $table->unsignedBigInteger('driver_id')->nullable(); $table->unsignedBigInteger('ride_id')->nullable(); $table->timestamps(); $table->foreign('driver_id') ->references('id')->on('users') ->onDelete('cascade'); $table->foreign('ride_id') ->references('id')->on('rides') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('offers'); } }
import asyncio import websockets from bleak import BleakClient, BleakScanner haptic_devices = {} haptic_definition_client_names = {"Haptic Definition: Hands", "Haptic Definition: Vest"} async def connect_and_setup_device(device): client = BleakClient(device) await client.connect() client_characteristics = [] print("Connected to", device.name, "Getting services...") client_services_collection = client.services client_services = client_services_collection.services for service in client_services.values(): for characteristic in service.characteristics: if "write" in characteristic.properties: await client.write_gatt_char(characteristic.uuid, "Hello World!".encode(), response=False) client_characteristics.append(characteristic) return {"client": client, "client_characteristics": client_characteristics} async def main_client(uri): print("looking for bluetooth") # scan for bluetooth devices once print("Scanning for bluetooth devices...") devices = await BleakScanner.discover() for d in devices: if d.name in haptic_definition_client_names: device_info = await connect_and_setup_device(d) haptic_devices.update({d.name: device_info}) print(haptic_devices) if (len(haptic_devices) == 0): print("No haptic devices found") return # now handle the socket events print("Ready to connect to websocket server") while True: connection_state = {"is_open": True} websocket = await websockets.connect(uri) try: async for message in websocket: print("Received message:", message) # change it to the correct formatting to understand if isinstance(message, bytes): # Decode for display purposes only message = message.decode('utf-8') print("Received message:", message) # determine which device to broadcast the message to if message == "ping": # broadcast the message to all haptic devices for device_name, device_info in haptic_devices.items(): client = device_info["client"] characteristics = device_info["client_characteristics"] for characteristic in characteristics: await client.write_gatt_char(characteristic.uuid, message.encode('utf-8'), response=False) continue # parse the message and see if it is a command to a specific device command = message.split("-") device_name = "" if len(command) == 2: # command is right format action = command[0] part = command[1] # determine body part if part == "chest": device_name = "chest" # hardcode message = "2" print("Writing to device", device_name, "with message", message) for device in haptic_devices: device_info = haptic_devices[device] client = device_info["client"] characteristics = device_info["client_characteristics"] for characteristic in characteristics: await client.write_gatt_char(characteristic.uuid, message.encode('utf-8'), response=False) continue elif part == "left_hand": device_name = "Haptic Definition: Vest" if action == "hot": message = "1" else: # impact message = "0" elif part == "right_hand": device_name = "Haptic Definition: Hands" if action == "hot": message = "1" else: # impact message = "0" # if action == "hot" and part == "chest": # # not implemented, skip # device_name = "" # elif action == "impact": # if part == "left_hand": # message = "0" # elif part == "right_hand" or part == "chest": # message = "1" # elif action == "hot": # if part == "left_hand": # message = "2" # elif part == "right_hand": # message = "3" # # Check if the message is in bytes, decode for printing, send as is for GATT char print(haptic_devices) print(len(device_name)) print(device_name in haptic_devices) if len(device_name) > 0 and device_name in haptic_devices: print("Writing to device", device_name, "with message", message) device_info = haptic_devices[device_name] client = device_info["client"] characteristics = device_info["client_characteristics"] for characteristic in characteristics: await client.write_gatt_char(characteristic.uuid, message.encode('utf-8'), response=False) except websockets.exceptions.ConnectionClosed: print("Connection closed by server.") finally: connection_state["is_open"] = False uri = "ws://localhost:5000/ws" asyncio.run(main_client(uri))
/// 名称: DHCHAI.DP.MROBSItem /// 描述: 护理项目 /// 编写者:liyi /// 编写日期: 2017-01-16 Class DHCHAI.DP.MROBSItem Extends (%Persistent, DHCHAI.Abstract, User.Abstract) [ ClassType = persistent, Not ProcedureBlock ] { /// 护理项目代码 Property BTItemCode As %String(MAXLEN = 100, TRUNCATE = 1) [ Required ]; /// 护理项目名称 Property BTItemDesc As %String(MAXLEN = 100, TRUNCATE = 1) [ Required ]; /// 护理项目分类(体温、大便次数) Property BTCatDr As DHCHAI.DP.MROBSItemCat; /// 有效标志 Property BTIsActive As %Boolean [ Required ]; /// 护理项目代码索引 Index IndexItemCode On BTItemCode As Exact; /// 护理项目名称索引 Index IndexItemDesc On BTItemDesc As Exact; /// Creator: liyi /// CreatDate: 2017-01-17 /// Description: 根据ID取护理项目 /// Table: DHCHAI.DP.MROBSItem /// Input: ID: DHCHAI.DP.MROBSItem.ID /// Return: 返回Object /// w ##class(DHCHAI.DP.MROBSItem).GetObjById(1) ClassMethod GetObjById(id As %String) As DHCHAI.DP.MROBSItem { New (id) Set return="" Quit:id="" return Quit:'##class(DHCHAI.DP.MROBSItem).%ExistsId(+id) return Set obj=##Class(DHCHAI.DP.MROBSItem).%OpenId(+id) Set return=obj Do obj.%Close() Quit return } /// Creator: liyi /// CreatDate: 2017-04-17 /// Description: 根据代码、名称取护理项目 /// Table: DHCHAI.DP.MROBSItem /// Input: aCode: 项目代码 /// aDesc: 项目名称 /// Return: 返回Object /// w ##class(DHCHAI.DP.MROBSItem).GetObjByCodeDesc("","") ClassMethod GetObjByCodeDesc(aCode As %String, aDesc As %String) As DHCHAI.DP.MROBSItem { New (aCode,aDesc) Set return="" Quit:((aCode="")&&(aDesc=""))||((aCode'="")&&(aDesc'="")) return Set id="" Set:aCode'="" id = $o(^DHCHAI.DP.MROBSItemI("IndexItemCode",aCode,0)) Set:aDesc'="" id = $o(^DHCHAI.DP.MROBSItemI("IndexItemDesc",aDesc,0)) Quit:id="" return Set return=..GetObjById(id) Quit return } /// Creator: liyi /// CreatDate: 2017-01-17 /// Description: 更新护理项目 /// Table: DHCHAI.DP.MROBSItem /// Input: 各属性列表 ^分隔 /// Return: 成功:返回id,失败:返回<0的代码 /// w ##class(DHCHAI.DP.MROBSItem).Update("^代码^名称^1") ClassMethod Update(InStr As %String, aSeparete As %String = "^") As %String { New (InStr,aSeparete) Set return=0 Quit:InStr="" return Set:$g(aSeparete)="" aSeparete=..#SEPARATE Set ID = $p(InStr,aSeparete,1) Set ItemCode = $p(InStr,aSeparete,2) Set ItemDesc = $p(InStr,aSeparete,3) Set BTCatDr = $p(InStr,aSeparete,4) Set IsActive = $p(InStr,aSeparete,5) Quit:(ItemCode="")||(ItemDesc="") return Set ItemDesc = ##Class(DHCHAI.Utils.CommonSrv).ChangeKeyStr(ItemDesc) //去掉特殊字符 //代码唯一性 Set tID =$o(^DHCHAI.DP.MROBSItemI("IndexItemCode",ItemCode,0)) Quit:(tID'="")&(ID'=tID) -100 //名称唯一性 Set tID =$o(^DHCHAI.DP.MROBSItemI("IndexItemDesc",ItemDesc,0)) Quit:(tID'="")&(ID'=tID) -100 Set objBTCat=##class(DHCHAI.DP.MROBSItemCat).GetObjById(BTCatDr) if ID="" { Set obj=##class(DHCHAI.DP.MROBSItem).%New() }else{ Set obj=##class(DHCHAI.DP.MROBSItem).%OpenId(ID) } Quit:'$IsObject(obj) return Set obj.BTItemCode = ItemCode Set obj.BTItemDesc = ItemDesc Set obj.BTCatDr = objBTCat Set obj.BTIsActive = IsActive Set sc=obj.%Save() if $system.Status.IsError(sc) { //检查Save是否成功 Do $system.OBJ.DisplayError(sc) Set return=-1 }else{ Set return=obj.%Id() } Do obj.%Close() Quit return } /// Creator: liyi /// CreatDate: 2017-01-17 /// Description: 删除护理项目 /// Table: DHCHAI.DP.MROBSItem /// Input: Id /// Return: 成功:返回0,失败:返回<0的代码 ClassMethod DeleteById(Id) { New (Id) Set Flg = ##class(DHCHAI.BT.DeleteControl).GetAllowDel("DHCHAI.DP.MROBSItem") Quit:Flg'=1 -777 Set sc = ##class(DHCHAI.DP.MROBSItem).%DeleteId(+Id) if $system.Status.IsError(sc) { //检查删除是否成功 Do $system.OBJ.DisplayError(sc) Set ret=-1 }else{ Set ret=0 } Quit ret } Storage Default { <Data name="MROBSItemDefaultData"> <Value name="1"> <Value>%%CLASSNAME</Value> </Value> <Value name="2"> <Value>BTItemCode</Value> </Value> <Value name="3"> <Value>BTItemDesc</Value> </Value> <Value name="4"> <Value>BTCatDr</Value> </Value> <Value name="5"> <Value>BTIsActive</Value> </Value> </Data> <DataLocation>^DHCHAI.DP.MROBSItemD</DataLocation> <DefaultData>MROBSItemDefaultData</DefaultData> <IdLocation>^DHCHAI.DP.MROBSItemD</IdLocation> <IndexLocation>^DHCHAI.DP.MROBSItemI</IndexLocation> <StreamLocation>^DHCHAI.DP.MROBSItemS</StreamLocation> <Type>%Storage.Persistent</Type> } }
tool extends Node const PLAYER := preload("res://player/player.tscn") const DEATH_ZONE := preload("res://death_zone/death_zone.tscn") const BALL := preload("res://ball/ball.tscn") var rng = RandomNumberGenerator.new() onready var hud_node := $HUD onready var menu_node := $Menu var player_1_node: Node = null var player_2_node: Node = null var ball_node: Node = null func _ready() -> void: if not Engine.editor_hint: get_tree().paused = true menu_node.set_visibility(true) menu_node.connect("restart_game", self, "_on_reset_game") GlobalVars.player_1_score = 0 GlobalVars.player_2_score = 0 var window_size := GlobalSettings.get_window_size() var middle_y := window_size.y / 2 player_1_node = create_player( Vector2(GlobalVars.PLAYER_POSITION_OFFSET, middle_y) , PlayerTypes.PLAYER_1 ) player_1_node.name = "Player1" add_child(player_1_node) var death_zone_1 := create_death_zone( Vector2(0 - GlobalVars.DEATH_ZONE_OFFSET, middle_y) , PlayerTypes.PLAYER_1 ) death_zone_1.name = "DeathZone1" add_child(death_zone_1) player_2_node = create_player( Vector2(window_size.x - GlobalVars.PLAYER_POSITION_OFFSET, middle_y) , PlayerTypes.PLAYER_2 ) player_2_node.name = "Player2" add_child(player_2_node) var death_zone_2 := create_death_zone( Vector2(window_size.x + GlobalVars.DEATH_ZONE_OFFSET, middle_y) , PlayerTypes.PLAYER_2 ) death_zone_2.name = "DeathZone2" add_child(death_zone_2) ball_node = create_ball(window_size / 2) add_child(ball_node) func create_player(position: Vector2, player_type: int) -> Node: var player := PLAYER.instance() player.position = position player.player_type = player_type return player func create_death_zone(position: Vector2, player_type: int) -> Node: var death_zone := DEATH_ZONE.instance() death_zone.position = position death_zone.player_type = player_type death_zone.connect("hit_death_zone", self, "_on_hit_death_zone") return death_zone func create_ball(position: Vector2) -> Node: var ball := BALL.instance() ball.position = position # TODO: need different random direction # The current will produce a bad angle to play, it should be a cone shape direct to 1 of the player rng.randomize() ball.direction = rng.randf_range(PI, 2*PI) return ball func reset_player_position() -> void: var window_size := GlobalSettings.get_window_size() var middle_y := window_size.y / 2 player_1_node.position = Vector2(GlobalVars.PLAYER_POSITION_OFFSET, middle_y) player_2_node.position = Vector2(window_size.x - GlobalVars.PLAYER_POSITION_OFFSET, middle_y) func reset_ball() -> void: remove_child(ball_node) ball_node.queue_free() var window_size := GlobalSettings.get_window_size() ball_node = create_ball(window_size / 2) add_child(ball_node) func _on_reset_game() -> void: get_tree().reload_current_scene() func _on_hit_death_zone(player_type: int) -> void: match player_type: PlayerTypes.PLAYER_1: GlobalVars.player_2_score += 1 hud_node.set_score_text(PlayerTypes.PLAYER_2, GlobalVars.player_2_score) PlayerTypes.PLAYER_2: GlobalVars.player_1_score += 1 hud_node.set_score_text(PlayerTypes.PLAYER_1, GlobalVars.player_1_score) reset_player_position() reset_ball()
// window.onload = function () { new Vue({ el: '#app', data: { running: false, playerLife: 100, monsterLife: 100, logs: [] }, computed: { hasResult() { return this.playerLife == 0 || this.monsterLife == 0; } }, methods: { startGame() { this.running = true; this.playerLife = 100; this.monsterLife = 100; this.logs = []; }, attack(isSpecial) { this.hurt('monsterLife', 5, 10, isSpecial, 'Jogador', 'Monstro', 'player'); if( this.monsterLife < 1){ return; } this.hurt('playerLife', 7, 12, false, 'Monstro', 'Jogador', 'monster'); }, hurt(target, min, max, isSpecial, from, to, cls) { const plus = isSpecial ? 5 : 0; const hurt = this.getRandom(min + plus, max + plus); this[target] = Math.max(this[target] - hurt, 0); this.registerLog(`${from} atingiu o ${to} com ${hurt}.`, cls); }, healAndHurt(min, max) { this.heal(10, 15); this.hurt('playerLife', 7, 12, false, 'Monstro', 'Jogador', 'monster'); }, heal (min, max) { const heal = this.getRandom(min, max); this.playerLife = Math.min(this.playerLife + heal, 100); this.registerLog(`Jogador recuperou ${heal} pontos de vida.`, 'player'); }, getRandom(min, max) { const value = Math.random() * (max - min) + min; return Math.round(value); }, registerLog(text, cls) { this.logs.unshift({ text, cls}); } }, watch: { hasResult(value){ if(value) this.running = false; } } }); // };
import { Model, ObjectsFactory } from "../../core"; import { BASE_ENDPOINT } from "../../endpoint"; export interface ILocation { code: string; id: number; name: string; } export interface ILocationQuery { provinceId: string | null; districtId: string | null; wardId: string | null; } export interface ILocationResponse { provinces: ILocation[]; districts: ILocation[]; wards: ILocation[]; } export const initialLocationValues: ILocationResponse = { provinces: [], districts: [], wards: [], }; export class Location extends Model { static config = { endpoint: BASE_ENDPOINT }; static objects = ObjectsFactory.factory<ILocation>(this.config); } Location.init(Location.config);
from sqlalchemy import Column, Integer, Date, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Vaccination(Base): __tablename__ = 'vaccinationTbl' vaccinationID = Column(Integer, primary_key=True, autoincrement=True) memberID = Column(Integer,nullable=False) vaccination_code = Column(Integer,nullable=False) vaccination_date = Column(Date, nullable=False) manufacturer = Column(String(20), nullable=False) def __init__(self, memberID, vaccination_code, vaccination_date, manufacturer): # self.vaccinationID = vaccinationID self.memberID = memberID self.vaccination_code = vaccination_code self.vaccination_date = vaccination_date self.manufacturer = manufacturer def to_dict(self): return { 'vaccination_id': self.vaccinationID, 'memberID': self.memberID, 'vaccination_code': self.vaccination_code, 'vaccination_date': self.vaccination_date.strftime('%d.%m.%Y'), 'manufacturer': self.manufacturer }
<div class="row animated fadeIn"> <div class="col-12"> <div class="card"> <div class="card-body"> <input #input class="form-control" placeholder="search a user" type="text" (keyup)="searchUsers(input.value,true)" /> </div> </div> </div> </div> <mat-slide-toggle (change)="slideChange($event)" [(ngModel)]="showAlerts">Show alerts</mat-slide-toggle> <ng-container *ngIf="!loading; else loadingTemplate"> <div class="row animated fadeIn mt-3"> <div class="col-12"> <div class="card"> <div class="card-body"> <h3 class="card-title">Users founded ( <small> {{totalResults}} </small> )</h3> <table class="table table-hover"> <thead> <tr> <th>Image</th> <th>Email</th> <th>Name</th> <th>Role</th> <th>Auth</th> <th>Actions</th> </tr> </thead> <tbody> <tr *ngFor="let user of users; let i = index"> <td > <img (click)="changeImage(i)" class="img img-circle" style="max-width: 50px; max-height: 50px;" [src]="user.img | image: 'user'" alt=""> </td> <td> {{user.email}} </td> <td> {{user.name}} </td> <select (change)="roleChange($event.target.value, i)" name="role" class="form-control" [(ngModel)]="user.role"> <option value="ADMIN_ROLE">ADMIN</option> <option value="USER_ROLE">USER</option> </select> <td *ngIf="user.google"> <label class="label label-danger"> {{user.google | authGoogle}} </label> </td> <td *ngIf="!user.google"> <label class="label label-info"> {{user.google | authGoogle}} </label> </td> <td> <button (click)="deleteUser(i)" class="btn btn-danger"> <i class="fa fa-trash-o"></i> </button> </td> </tr> </tbody> </table> <button (click)="prevPage()" [disabled]="!isPrev" class="btn btn-secondary mr-1"> Prev </button> <button class="btn btn-secondary" (click)="nextPage()" [disabled]="!isNext"> Next </button> </div> </div> </div> </div> </ng-container> <ng-template #loadingTemplate> <app-loading></app-loading> </ng-template> <div *ngIf="changeImageModal"> <app-modal-upload [type]="'user'" [selected]="selectedUser" (close)="closeModal($event)"></app-modal-upload> </div>
<?php namespace App\Repository; use App\Entity\User; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; /** * @extends ServiceEntityRepository<User> * @implements PasswordUpgraderInterface<User> * * @method User|null find($id, $lockMode = null, $lockVersion = null) * @method User|null findOneBy(array $criteria, array $orderBy = null) * @method User[] findAll() * @method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, User::class); } /** * Used to upgrade (rehash) the user's password automatically over time. */ public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void { if (!$user instanceof User) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class)); } $user->setPassword($newHashedPassword); $this->getEntityManager()->persist($user); $this->getEntityManager()->flush(); } /** * Permet d'obtenir le nombre d'utilisateurs */ public function countUsers(): int{ /* Query qui permet d'obtenir le nombre d'utilisateurs total */ $totalUsers = $this->createQueryBuilder('u') // Création d'un query builder avec un alias pour l'entité actuel ->select('COUNT(u.id)') // Sélection du nombre d'id des utilisateurs ->getQuery() // Obtention de la query construite ->getSingleScalarResult(); // Execution de la query et obtention du résultat sous forme d'un nombre return $totalUsers; } /** * Permet d'obtenir les utilisateurs bannis ou non bannis */ public function getUsersByStatus(bool $isBanned){ /* Query qui permet d'obtenir les utilisateurs non bannis */ $usersByStatus = $this->createQueryBuilder('u') // Création d'un query builder avec un alias pour l'entité actuel ->select('u.id, u.email, u.username, u.registrationDate, u.roles'); // Sélection de l'id, email, pseudo, date d'inscription et rôles des utilisateurs /* Si on veut les utilisateurs bannis */ if($isBanned){ $usersByStatus->andWhere('u.banned = true'); // On restreint la query aux utilisateurs bannis } else{ $usersByStatus->andWhere('u.banned = false'); // On restreint la query aux utilisateurs non bannis } return $usersByStatus->getQuery()->getResult(); // Obtention de la query construite, execution de la query et obtention du résultat } /** * Permet d'obtenir les utilisateurs non vérifiés */ public function getUnverifiedUsers(){ /* Query qui permet d'obtenir les utilisateurs non vérifiés */ $unverifiedUsers = $this->createQueryBuilder('u') // Création d'un query builder avec un alias pour l'entité actuel ->select('u.id, u.email, u.username, u.registrationDate') // Sélection de l'id, email, pseudo et date d'inscription des utilisateurs ->andWhere('u.isVerified = false') // On restreint la query aux utilisateurs non vérifié ->getQuery() // Obtention de la query construite ->getResult(); // Execution de la query et obtention du résultat return $unverifiedUsers; } // /** // * @return User[] Returns an array of User objects // */ // public function findByExampleField($value): array // { // return $this->createQueryBuilder('u') // ->andWhere('u.exampleField = :val') // ->setParameter('val', $value) // ->orderBy('u.id', 'ASC') // ->setMaxResults(10) // ->getQuery() // ->getResult() // ; // } // public function findOneBySomeField($value): ?User // { // return $this->createQueryBuilder('u') // ->andWhere('u.exampleField = :val') // ->setParameter('val', $value) // ->getQuery() // ->getOneOrNullResult() // ; // } }
"use client"; import { useLoginModal, useRegisterModal } from "@/utils/hooks"; import React, { Dispatch, FC, SetStateAction, useCallback, useState, } from "react"; import Modal from "../ui/modal"; import { useForm } from "react-hook-form"; import { z } from "zod"; import { RegisterStepOTwoSchemaType, RegisterStepOneSchemaType, registerStepOneSchema, registerStepTwoSchema, } from "@/utils/validation"; import { zodResolver } from "@hookform/resolvers/zod"; import { Form, FormControl, FormField, FormItem, FormMessage, } from "../ui/form"; import { Input } from "../ui/input"; import Button from "../ui/button"; interface DataState { name: string; email: string; } interface RegisterStepsProps { setData: Dispatch<SetStateAction<DataState>>; setStep: Dispatch<SetStateAction<number>>; } export const RegisterModal = () => { const { isOpen, onClose } = useRegisterModal(); const loginModal = useLoginModal(); const onTogle = useCallback(() => { onClose(); loginModal.onOpen(); }, [onClose, loginModal]); const [step, setStep] = useState<number>(1); const [data, setData] = useState<DataState>({ name: "", email: "", }); const body = step === 1 ? ( <RegisterStepOne setData={setData} setStep={setStep} /> ) : ( <RegisterStepTwo setData={setData} setStep={setStep} /> ); const footer = ( <div className="text-neutral-400 text-center mb-4"> <p> Already have an account?{" "} <span className="text-white cursor-pointer hover:underline" onClick={onTogle} > Sign in </span> </p> </div> ); return ( <Modal body={body} footer={footer} isOpen={isOpen} onClose={onClose} step={step} /> ); }; const RegisterStepOne: FC<RegisterStepsProps> = ({ setData, setStep }) => { const form = useForm<z.infer<RegisterStepOneSchemaType>>({ resolver: zodResolver(registerStepOneSchema), defaultValues: { email: "", name: "", }, }); const onSubmit = (values: z.infer<RegisterStepOneSchemaType>) => { setData(values); setStep(2); }; const { isSubmitting } = form.formState; return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 px-12"> <FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormControl> <Input placeholder="Name" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="email" render={({ field }) => ( <FormItem> <FormControl> <Input placeholder="Email" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <Button large fullWidth secondary label="Next" type="submit" disabled={isSubmitting} /> </form> </Form> ); }; const RegisterStepTwo: FC<RegisterStepsProps> = ({ setData, setStep }) => { const form = useForm<z.infer<RegisterStepOTwoSchemaType>>({ resolver: zodResolver(registerStepTwoSchema), defaultValues: { username: "", password: "", }, }); const onSubmit = (values: z.infer<RegisterStepOTwoSchemaType>) => { console.log(values); }; const { isSubmitting } = form.formState; return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 px-12"> <FormField control={form.control} name="username" render={({ field }) => ( <FormItem> <FormControl> <Input placeholder="Username" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="password" render={({ field }) => ( <FormItem> <FormControl> <Input placeholder="Password" type="password" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <Button large fullWidth secondary label="Register" type="submit" disabled={isSubmitting} /> </form> </Form> ); };
import { AssetFinder } from "../../client"; import { WeaponImages } from "../AssetFinder"; import { AssetFinderOptions, WeaponAPI, WeaponStatsAPI } from "../../types"; /** * A class that structures the weapon's data. */ export class Weapon { /** * The weapon's ID. */ weaponId: number; /** * The weapon's level. */ level: number; /** * The weapon's ascension level. */ ascensionLevel: number | string; /** * The weapon's refinement level. */ refinement: Refinement; /** * The weapon's name text map hash. */ nameTextMapHash: string; /** * The weapon's rank stars. */ stars: number; /** * the weapon's stats. */ weaponStats: WeaponStats[]; /** * The item type. */ itemType: string; /** * The weapon's assets. */ assets: WeaponImages; /** * The weapon's name. */ name: string; /** * Creates a new `Weapon` instance. * @param data - The data of the weapon. * @param language - The language to get the name. */ constructor(data: WeaponAPI, language: AssetFinderOptions["language"]) { const { genshin: genshinFinder } = new AssetFinder({ language }); this.weaponId = data.itemId; this.level = data.weapon.level; this.ascensionLevel = data.weapon.promoteLevel || ""; this.refinement = new Refinement(data.weapon.affixMap); this.nameTextMapHash = data.flat.nameTextMapHash; this.stars = data.flat.rankLevel; this.weaponStats = data.flat.weaponStats.map( (data) => new WeaponStats(data) ); this.itemType = data.flat.itemType; this.assets = genshinFinder.weapon(this.weaponId).assets; this.name = genshinFinder.weapon( this.weaponId ).name; } } /** * A class that structures the weapon stats. */ class WeaponStats { /** * The weapon stat. */ stat: string; /** * The weapon stat value. */ statValue: number; /** * Creates a new `WeaponStats` instance. * @param data - The data of the weapon stats. */ constructor(data: WeaponStatsAPI) { this.stat = data.appendPropId; this.statValue = data.statValue; } } /** * A class that structures the weapon's refinement data. */ class Refinement { /** * The id of the refinement. */ id: number | string; /** * The weapon's refinement level. */ level: number | string; constructor(data: any) { this.id = data ? +Object.keys(data)[0] : ""; this.level = data ? data[Object.keys(data)[0]] : ""; } }
/** * Imports */ const Common = require('../common'); /** * Export */ class ClaimDetailsPage extends Common { constructor() { super(); /** * Config */ // Side Bar Section this.sideBarSections = ['Member Details', 'Claim Details', 'Downloads']; this.sideBarAttributes = [ {label: 'Member Name'}, {label: 'Service Date', format: 'DATE'}, {label: 'Billed Amount', format: 'CURRENCY'}, {label: 'Paid Amount', format: 'CURRENCY'}, {label: 'Claim Status'}, ]; this.linkList = ['Explanation of Payments', 'Claim Reconsideration Form']; this.badges = ['Claim Number', 'Member', 'Status']; // overview Tab this.overviewSectionFields = ['Servicing Provider', 'Servicing Provider NPI', 'Paid Date', 'Number of Lines']; // Financial Information this.financialInfoSectionFields = [ {format: 'CURRENCY', label: 'Billed Amount'}, {format: 'CURRENCY', label: 'Allowed Amount'}, {format: 'CURRENCY', label: 'Denied Amount'}, {format: 'CURRENCY', label: 'Coinsurance'}, {format: 'CURRENCY', label: 'Copay'}, {format: 'CURRENCY', label: 'Deductible'}, {format: 'CURRENCY', label: 'Sequestration'}, {format: 'CURRENCY', label: 'Paid Amount'}, ]; this.financialInfoPayeeDetailsFields = ['Check Number', 'Check Issue Date', 'Check Amount']; // Claim Line Tab this.claimLineTabTableColumns = [ {name: 'Service', format: 'LINK'}, {name: 'Procedure Code', format: 'LIST'}, {name: 'Billed Amount', format: 'CURRENCY'}, {name: 'Line Number', format: 'line_number'}, {name: 'Status', format: 'text'}]; this.claimLineTabTablePagesize = 10; /** * Elements */ this.$claimNumber = number => element(by.cssContainingText('h4', number)); this.$claimMemberNameLink = $('button div span'); this.$leftPanelAttributesHeaders = headerName => element(by.xpath(`//section[contains(@class,"claim-detail__aside")]//label[.='${headerName}']`)); this.$sectionHeader = headerName => element(by.cssContainingText(`aside.layout--detail__aside header h6`, headerName)); this.$documentLink = name => element(by.cssContainingText('div.link__list a', name)); this.$badgeLabel = labelName => element(by.cssContainingText('div p.Badge__label', labelName)); this.$badgeValue = value => element(by.cssContainingText('div h4.Badge__value', value)); this.$gridItemLabel = labelName => element(by.cssContainingText('div.tab-view__tab__switch div.model-attribute__label label', labelName)); } /* * Methods */ /** * click on member name link to navigate back to member details */ async clickMemberNameLink() { log('clickMemberNameLink()'); await this.$claimMemberNameLink.click(); await this.waitForLoad(); } /** * click on document link under downloads * @param {string} documentName */ async clickDocumentLink(documentName) { log(`clickDocumentLink(${documentName})`); await this.$documentLink(documentName).click(); await this.waitForLoad(); } } module.exports = { claimDetailsPage: new ClaimDetailsPage(), };
// Sum of sequence fn main() { println!("A function returns the sum of a sequence of integers.\n"); assert_eq!(2, sequence_sum(2, 2, 2)); assert_eq!(15, sequence_sum(1, 5, 1)); assert_eq!(5, sequence_sum(1, 5, 3)); println!("Success!"); } fn sequence_sum(start: u32, end: u32, step: u32) -> u32 { (start..=end).step_by(step as usize).sum() }
const mongoose = require('mongoose'); const validator = require('validator'); const jwt = require('jsonwebtoken'); const lodash = require('lodash'); const bcrypt = require('bcryptjs'); var Schema = mongoose.Schema; //create a schema for a collection var userSchema = new Schema({ email: { type: String, required: [true, 'User email required'], trim: true, unique: true, validate: { validator: function(v) { //regex validator //return /[\w-]+@([\w-]+\.)+[\w-]+/.test(v); return validator.isEmail(v); }, message: '{VALUE} is not a valid email address!' } }, password: { type: String, required: [true, 'password is required'], minlength: 6 }, tokens: [{ access: { type: String, required: true }, token: { type: String, required: true } }] }); //override json return object userSchema.methods.toJSON = function () { var user = this; var userObject = user.toObject(); return lodash.pick(userObject, ['_id', 'email']); }; userSchema.methods.generateAuthToken = function () { var user = this; var access = 'auth'; var token = jwt.sign({_id: user._id.toHexString(), access}, process.env.JWT_SECRET).toString(); user.tokens = user.tokens.concat({access, token}); return user.save().then(() => { return token; }); }; //log out user userSchema.methods.removeToken = function (token) { var user = this; return user.update({ $pull: { tokens: { token: token } } }); }; //model method userSchema.statics.findByToken = function (token) { var User = this; var decoded; try { decoded = jwt.verify(token, process.env.JWT_SECRET); } catch (e) { return new Promise((resolve, reject) => { reject(); }); } return User.findOne({ '_id': decoded._id, 'tokens.token': token, 'tokens.access': 'auth' }); }; //method when user login userSchema.statics.findByCredentials = function(email, password) { var User = this; return User.findOne({email}).then((user) => { if (!user) { return Promise.reject(); } //create promise object return new Promise((resolve, reject) => { bcrypt.compare(password, user.password, (err, res) => { if (res) { resolve(user); } else { reject(); } }); }); }); }; //encrypt user password before saving into mongoDB userSchema.pre('save', function(next) { var user = this; if (user.isModified('password')) { bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(user.password, salt, (err, hash) => { user.password = hash; next(); }); }); } else { next(); } }); var User = mongoose.model('User', userSchema); module.exports = {User: User};
// // Utilities.swift // OnYourHeart-Pod // // Created by Curt McCune on 6/21/22. // import Foundation import UIKit import FirebaseCore import FirebaseAuth class LoginUtilities { static func styleTextField(_ textfield:UITextField) { // Create the bottom line let bottomLine = CALayer() bottomLine.frame = CGRect(x: 0, y: textfield.frame.height - 2, width: textfield.frame.width, height: 2) bottomLine.backgroundColor = Colors.titleBrown.cgColor // Remove border on text field textfield.borderStyle = .none // Add the line to the text field textfield.layer.addSublayer(bottomLine) } //Filled Button Style static func styleFilledButton(_ button:UIButton) { button.backgroundColor = Colors.titleBrown button.layer.cornerRadius = 25.0 button.tintColor = UIColor.white } //Hollow Button Style static func styleHollowButton(_ button:UIButton) { button.layer.borderWidth = 2 button.layer.borderColor = Colors.titleBrown.cgColor button.layer.cornerRadius = 25.0 button.tintColor = Colors.titleBrown } static func isPasswordValid(_ password : String) -> Bool { let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[$@$#!%*?&])(?=.*\\d)[A-Za-z\\d$@$#!%*?&]{8,}") return passwordTest.evaluate(with: password) } static func isEmailValid(_ email: String) -> Bool { let emailTest = NSPredicate(format: "SELF MATCHES %@", "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}") return emailTest.evaluate(with: email) } //Checks if user is logged in static func isUserLoggedIn() -> Bool{ return Auth.auth().currentUser != nil } //Calls tabBarController with 4 tabs with Account Page static func userIsLoggedIn(window: UIWindow?) { //Resets the lists FirebaseDataController.shared.lists = [] let storyboard = UIStoryboard(name: Constants.Storyboard.mainStoryboard, bundle: nil) guard let homeNav = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.homeNavBar) as? UINavigationController else {return} guard let listNav = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.listNavBar) as? UINavigationController else {return} guard let discoverNav = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.discoverNavBar) as? UINavigationController else {return} guard let accountNav = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.accountNavBar) as? UINavigationController else {return} guard let tabBar = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.tabBarController) as? UITabBarController else {return} tabBar.viewControllers = [homeNav, listNav, discoverNav, accountNav] tabBar.selectedIndex = 0 window?.rootViewController = tabBar window?.makeKeyAndVisible() } //Calls tabBarController with 4 tabs with Login Page static func userIsLoggedOut(window: UIWindow?) { //Sets the default list FirebaseDataController.shared.user = Constants.Firebase.defaultUser FirebaseDataController.shared.lists = FirebaseDataController.shared.user.lists //Add the correct tabBar let storyboard = UIStoryboard(name: Constants.Storyboard.mainStoryboard, bundle: nil) guard let homeNav = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.homeNavBar) as? UINavigationController else {return} guard let listNav = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.listNavBar) as? UINavigationController else {return} guard let discoverNav = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.discoverNavBar) as? UINavigationController else {return} guard let loginNav = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.loginNavController) as? UINavigationController else {return} guard let tabBar = storyboard.instantiateViewController(withIdentifier: Constants.Storyboard.tabBarController) as? UITabBarController else {return} tabBar.viewControllers = [loginNav, homeNav, listNav, discoverNav] tabBar.selectedIndex = 0 window?.rootViewController = tabBar window?.makeKeyAndVisible() } static func presentNotLoggedInAlert(viewController: UIViewController, tabbar: UITabBarController?){ let alert = UIAlertController(title: "Not Logged in", message: "Please login to access this feature", preferredStyle: .alert) let loginAction = UIAlertAction(title: "Login", style: .default) { _ in tabbar?.selectedIndex = 0 } let continueAction = UIAlertAction(title: "Continue", style: .default) alert.addAction(loginAction) alert.addAction(continueAction) viewController.present(alert, animated: true) } }
#pragma once #include <vector> #include <random> #include "IOData/Tensor.h" #include "IOData/Matrix.h" #include "NeuralModules/Neural_Module.h" #include "iostream" #include <fstream> class FullyConnectedLayer : public NeuralModule { enum class ActivationType { None, Sigmoid, Tanh, ReLU, LeakyReLU, ELU }; Tensor_size inputSize; Tensor_size outputSize; std::default_random_engine generator; std::normal_distribution<double> distribution; int inputs; int outputs; ActivationType activationType; Tensor df; Matrix Weight; Matrix d_Weight; std::vector<double> Bias; std::vector<double> d_Bias; ActivationType GetActivationType(const std::string& activationType) const; void InitWeights() override; void Activate(Tensor& output); public: FullyConnectedLayer(Tensor_size size, int outputs, const std::string& activationType = "none"); Tensor Direct_dist(const Tensor& X) override; Tensor Back_dist(const Tensor& dout, const Tensor& X) override; void UpdateWeights(double learningRate) override; void LoadWeight(const char* filename) override; void UploadWeight(const char* filename) override; };
import React from 'react' import cn from 'classnames' import { SortType } from '../../@types/common'; import { SortTypeEnum } from '../../@types/enums'; type SortPopUpProps = { sortType: SortType; handleChangeSortType: (obj: SortType) => void; } export const SortPopUp: React.FC<SortPopUpProps> = React.memo( ({ sortType, handleChangeSortType }) => { const [openPopup, setOpenPopup] = React.useState(false) const [order, setOrder] = React.useState(true) const sortByRef = React.useRef<HTMLDivElement>(null) const handlePopUpClick = () => { setOpenPopup(!openPopup) } React.useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (sortByRef.current && !sortByRef.current.contains(event.target as Node)) { setOpenPopup(false) } } document.body.addEventListener('click', handleClickOutside) return () => { document.body.removeEventListener('click', handleClickOutside) } }, []) const popupItems: SortType[] = [ { name: 'популярности', type: SortTypeEnum.RATING, order: order }, { name: 'цене', type: SortTypeEnum.PRICE, order: order }, { name: 'алфавиту', type: SortTypeEnum.NAME, order: order }, ] return ( <div ref={sortByRef} className="categories__sort-by sort-by" onClick={handlePopUpClick} > <svg className={cn('sort-by__triangle-icon', {'rotated': openPopup})} width="10" height="6" viewBox="0 0 10 6" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M10 5C10 5.16927 9.93815 5.31576 9.81445 5.43945C9.69075 5.56315 9.54427 5.625 9.375 5.625H0.625C0.455729 5.625 0.309245 5.56315 0.185547 5.43945C0.061849 5.31576 0 5.16927 0 5C0 4.83073 0.061849 4.68424 0.185547 4.56055L4.56055 0.185547C4.68424 0.061849 4.83073 0 5 0C5.16927 0 5.31576 0.061849 5.43945 0.185547L9.81445 4.56055C9.93815 4.68424 10 4.83073 10 5Z" fill="#2C2C2C" /> </svg> <div className="sort-by__choice">Сортировка по: <span className="sort-by__choice-result">{sortType.name}</span> </div> <ul className={cn('sort-by__modal', { 'opened': openPopup })} > {popupItems.map((obj: SortType) => ( <li key={obj.type} className={cn('sort-by__item', { 'active': obj.type === sortType.type })} onClick={() => handleChangeSortType(obj)} >{obj.name}</li> ))} <li className='sort-by__item'>По возростанию <input type="checkbox" checked={order} onChange={() => setOrder(!order)} /> </li> </ul> </div> ) })
--- sidebar_position: 1 --- # REACT Overview import { useState } from 'react'; import { StrictMode } from "react"; React es una libreria que posee un DOM virtual con el cual puede renderizar componentes individualmente, al ser una libreria necesita librerias extra para su completa funcionalidad. *** ## Recomendaciones Generales y Tips Alrededor de la libreria React Esta seccion esta dedicada a tips que se van aprendiendo a lo largo de la experiencia adquirida con la libreria. - (de gridder) react no puede imprimir otras cosas que no sean numeros y letras en las crulys {} de return, objetos no, arrays no, booleanos no; dentro de las curlyes se pueden meter funciones y llamadas pero que porsupuesto terminen en primitivos como numeros y letras - Ojo con la inmutabilidad cuando se trabaja con los estados (recuerda el .slide() y el ...history en el ejemplo de tick-toc). - The **spread** syntax: The dots literally mean “gather the remaining parameters into an array”. - La clave de react es la re-renderizacion de un componente y como sus estados van cambiando. - Si se llama el componente que use useState varias veces, habran varios estados diferentes. - Las funciones que utilicen "use" se consideran "hooks". - Un componente en REACT es una funcion que retorna HTML al DOM virtual. - Un componente no puede retormar mas de un tag, en caso de varios tags envolvelos en un wrapper or a fragment. - Se recomienda aplicar (ejemplo en github examples-react) atomic design in order to create the components. - Los componentes en REACT siempre deben de tener una letra mayuscula al principio para diferenciarlos de elementos HTML normales. - Una diferencia entre el JSX con HTML es que hay que cerrar todos los tags, y que solo se puede devolver un solo componente (envoltura). - Para agregar estilo se utiliza className, no se utiliza class como en html normalmente se haria. - Se puede almacenar jsx en variables y generar condicionales para que muestre uno u otro contenido, estas condiconales pueden ser incluso comparativos de tipo &&. - Se puede utilizar map para mapear todos los elementos que se encuentren en objetos, vengan de funciones, fetch, etc. (siempre agregar un key). - Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like if statements, &&, and ? : operators. - De acuerdo a como exporte el componente es como se importa en otro lado: | Syntax | Export statement | Import statement | |:-------:|:-------------------------------------:|:---------------------------------------:| | Default | `export default function Button() {}` | `import Button from './Button.js';` | | Named | `export function Button() {}` | `import { Button } from './Button.js';` | - In JSX, `{cond ? <A /> : <B />}` means “if cond, render `<A />`, otherwise `<B />`”. - In JSX, `{cond && <A />}` means “if cond, render `<A />`, otherwise nothing”. **No coloques números en el lado izquierdo del operador &&.** - The shortcuts are common, but you don’t have to use them if you prefer plain if. - Un set en react es un peticion de hacer un re-render con los nuevos states. - En react los on son los eventos html que estan listados en w3schools. - Tip acerca de imagenes, las imagenes que son de menos de 5kb son convertidas a codigo e incluidas en el jsx de react. - Los componentes que son parientes NO SE DEBEN DE COMUNICAR ENTRE ELLOS, SIEMPRE UTILIZE LOS PARENTS. *** ## Como pasar datos dinamicos - Gracias a javascript se le puede agregar datos dinamicos como en el siguiente ejemplo, esto es util cuando se extrae info desde un objeto: ```jsx return ( <h1> {user.name} </h1> ); ``` *** ## Como pasar atributos - Este es un ejemplo de como pasar atributos a un JSX tag ```jsx return ( <img className="avatar" src={user.imageUrl} /> ); ``` *** ## Como pasar children **Importante**: Los children cuando se pasan al componente, solo se pasa el children el componente que manda el children, asi llega al componente y sigue derecho al menos que se le quiera hacer algo. ```jsx export const Highlight = ({children, color}) => ( <span style={{ backgroundColor: color, borderRadius: '5px', color: '#fff', padding: '0.2rem', }}> {children} </span> ); <Highlight color="#25c2a0">Docusaurus green</Highlight> and <Highlight color="#1877F2">Facebook blue</Highlight> are my favorite colors. ``` *** ## Ejemplo basico de state con botones Este es otro ejemplo, este es un ejemplo basico de state con botones Este primer ejemplo es un solo componente (funcion que retorna jsx) que retorna un boton y utiliza el useState por medio de un eventHandler. Este componente va solito: ```jsx import { useState } from 'react'; export const MyButton = () => { const [count, setCount] = useState(2); function handleClick() { setCount(count + 1); } return ( <button onClick={handleClick} > esto es un boton {count} </button> ); } <MyButton /> ``` Para manejar MDX que es react components en markdown, consultar [MDX Official](https://mdxjs.com/) import MyButton from '@site/src/components/react-components/simpleButton.jsx'; ### Este Boton tiene su propio state <StrictMode> <MyButton /> </StrictMode> *** ## Ejemplo de botones actualizandosen separadamente (Cada uno con su propio state) Ahora este ejemplo es un componente (App) que llama el componente de arriba y utiliza el otro componente (Button2) que se encuentra como funcion dentro de app y renderiza desde app ```jsx export const MyApp = () => { //Esta funcion es otro componente dentro del componente app function MyButton2() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return ( <button onClick={handleClick}> Clicked {count} times </button> ); } //Como se observa se utiliza el boton de mas arriba y el nuevo boton en el return. return ( <div> <h6>Counters that update separately</h6> <MyButton /> <MyButton2 /> </div> ); } <MyApp /> ``` import MyButton2 from '@site/src/components/react-components/simpleButton2.jsx'; ### Este Boton tiene states independientes <StrictMode> <MyButton2 /> </StrictMode> *** ## Botones actualizandosen al mismo tiempo (Lifting the state up) - **Importante:** Para compartir estados entre componentes, SE DEBE DE MOVER EL STATE AL COMPONENTE SUPERIOR MAS CERCANO y los states pasan como props a cada boton y cada boton queda atado al state principal, a esto se le llama "lifting state up". Se observa dos botones pero con state diferente, el siguiente ejemplo posee states independientes: Se lleva el state a la app de donde se renderiza y se pasan los props a los componentes hijos. ```jsx export const MyButton3 = ({ count, onClick }) => { return ( <button onClick={onClick}> Clicked {count} times </button> ); } export const MyApp2 = () => { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return ( <div> <h4>Counters that update together</h4> <MyButton3 count={count} onClick={handleClick} /> <MyButton3 count={count} onClick={handleClick} /> </div> ); } <MyApp2 /> ``` import MyApp2 from '@site/src/components/react-components/liftingState.jsx'; ### Este Boton tiene states sincronizados <StrictMode> <MyApp2 /> </StrictMode> *** ## Componente importado externamente El siguiente es un ejemplo de como importar un componente y utilizarlo en el mdx ```jsx import Game from '@site/src/components/tick-toc.js'; import { StrictMode } from "react"; <StrictMode> <Game /> </StrictMode> ``` El codigo se encuentra en tick-toc.js y es importado gracias a un feature de mdx (el @site) **Importante:** Ojo con la inmutabilidad de los estados, hacer copia mas no modificar. import Game from '@site/src/components/tick-toc.jsx'; <StrictMode> <Game /> </StrictMode> *** Este codigo de abajo es el principio del tutorial de react el cual muestra un ejemplo basico de como asignar props y children ademas de una muestra de validacion de props que recomendo el eslint de react. import Board from '@site/src/components/tick-toc-build.jsx'; <StrictMode> <Board /> </StrictMode> ***
<div class="container register"> <form #addForm="ngForm" > <div class="row"> <div class="col-md-3 register-left"> <img src="https://image.ibb.co/n7oTvU/logo_white.png" alt=""/> <h3>Welcome</h3> <p>You have to login before, Only provider can add new product</p> </div> <div class="col-md-9 register-right"> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab"> <h3 class="register-heading">Add new product</h3> <div class="row register-form"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" placeholder="Wording *" name="wording" required [(ngModel)]="product.wording" /> </div> <div class="form-group"> <input type="number" class="form-control" placeholder="Quantity *" name="quantity" required [(ngModel)]="product.quantity" /> </div> <div class="form-group"> <input class="form-control" type="text" onfocus="(this.type='date')" placeholder=" Date manufacture *" name="fabDate" required [(ngModel)]="product.fabDate" > </div> <div class="form-group"> <input class="form-control" type="text" onfocus="(this.type='date')" placeholder=" Expiration date *" name="expDate" required [(ngModel)]="product.expDate"> </div> </div> <div class="col-md-6"> <div class="form-group"> <input type="number" step="0.1" min="0" class="form-control" placeholder="Unit price *" name="price" required [(ngModel)]="product.price"/> </div> <div class="form-group"> <select class="form-control" name="category" [(ngModel)]="product.category" > <option class="hidden" selected disabled>Please select your product category</option> <option>drink</option> <option>Fruits and vegetables</option> <option>Cereals</option> <option>Dairy products</option> <option>Meat fish egg</option> <option>Fatty products</option> <option>Pasta</option> <option>Pastry product</option> <option>Other</option> </select> </div> <div class="form-group"> <textarea class="form-control" maxlength="600" placeholder="Description *" name="description" required [(ngModel)]="product.description"></textarea> </div> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <img [src]="imgURL" style="max-height: 160px" alt=""> <input type="file" name="photo" #file accept='image/*' (change)="updatePreview(file.files)" ng2FileSelect [uploader]="uploader" /> </div> <div class="col-md-4"> <input type="submit" class="btnRegister" value="Add" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length || addForm.invalid"/> </div> </div> </div> </div> </div> </div> </form> </div>
{% extends 'bootstrap.tmpl' %} {% load staticfiles %} {% block title %}Genome Graphic{% endblock %} {% block stylesheet %} <link rel="stylesheet" href="{% static 'editpages/css/style.css' %}?via=html"> {% endblock %} {% block content %} <div class="container"> <header> <h1 id="title">Genome Graphic Generator</h1> </header> <section id="abstract" class="panel"> <div class="panel-heading"> <h3>Summary</h3> </div> <div class="panel-body"> <p>This is a write-up of a tool I made to represent personal genomes in a single, nice-looking graphic. It can turn any sequence into a graphic, but the focus is on representing whole genomes and the minute differences between them that make them unique. You can read the explanation below, skip to the <a href="#result">examples</a>, or to the <a href="http://toolshed.g2.bx.psu.edu/repository/display_tool?repository_id=4e3c152c0ec46a29&amp;render_repository_actions_for=tool_shed&amp;tool_config=database%2Fcommunity_files%2F000%2Frepo_895%2Fvisualize.xml&amp;changeset_revision=abed07ebeac7">tool itself</a>, now an installable <a href="https://usegalaxy.org/">Galaxy</a> tool.</p> </div> </section> <section id="rationale" class="panel"> <div class="panel-heading"> <h3>Rationale</h3> </div> <div class="panel-body"> <p>The cost of DNA sequencing has been plummeting in the last few years. More than plummeting. It dropped through the floor, and then said a quick hello to Moore's Law as it flew straight past even <span class="em">that</span> exponential trend. The best way to emphasize this is with a chart from the NHGRI's page at <a href="http://www.genome.gov/sequencingcosts">genome.gov/sequencingcosts</a>.</p> <p>This looks like a logarithmic trend, but note that it's already on a logarithmic scale. Moore's Law is a straight line. And before 2007 the cost per genome was already keeping pace with it. At that point a genome would cost you 10 million dollars. But then the price went off a cliff, and within four short years it was under 10 <span class="em">thousand</span> dollars:</p> <div class="gallery center-hack"> <div class="center-block"> <a href="/img/sequencingcosts.jpg"> <img class="img-responsive img-thumbnail w512" src="/img/sequencingcosts.jpg?via=html" alt="note the &quot;Moore's Law&quot; line."/> </a> </div> </div> <p>This means that my longtime desire to have my own genome sequenced is quickly becoming possible. And when I think about the moment I finally get my genome, I realized that what would really be nice is some way to visualize the whole thing at once. Some image that I can say is <span class="em">me</span>. That poses two problems: how do you generate some sort of graphic that both summarizes a whole genome <span class="em">and</span> retains the rare differences between it and everyone else's? With 3 billion nucleotides, obviously not all of them can be shown in a graphic that will fit in one screen. But if you squash it down to a manageable size, averaging thousands of bases into each pixel, you will inevitably get the same result for every human you run into. That's because the differences that make you unique are so rare that they're swamped by the bases common to everyone.</p> <p>That's why this is a difficult problem to solve. It's especially difficult to solve it in a simple way that requires no more than a single file with your genome sequence. I've taken a crack at it, and here I'm showing what I've come up with. My approach takes into account every single nucleotide, while still emphasizing the small amount of variation in every genome. Simply put, a change in any single nucleotide will produce a wildly different image. So your graphic will be uniquely yours and represent <span class="em">you</span>.</p> </div> </section> <section id="result" class="panel"> <div class="panel-heading"> <h3>The Result</h3> </div> <div class="panel-body"> <p>Here is the product of my approach. Since I don't yet have my genome, this was produced from the standard reference genome, hg19.</p> <p></p> <div class="gallery center-hack"> <div class="center-block"> <a href="/img/hg19-opacity2.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-opacity2.png?via=html" alt="hg19.fa"/> </a> </div> </div> <p>I use a recursive algorithm that partitions the image into eighths, colors them, then partitions each eighth, colors those sub-partitions, then mixes them with the first level, and so on. This prevents the random noise you would get by breaking it into tiny bits and coloring each one independently. Instead, there are larger regions which maintain some continuity even though their constituent parts diverge.</p> </div> </section> <section id="features" class="panel"> <div class="panel-heading"> <h3>Features</h3> </div> <div class="panel-body"> <p>Just to show how much the image changes with a different genome, here are two different genomes side-by-side. The first is the same as above, and the second has one chromosome replaced with a <a href="https://en.wikipedia.org/wiki/Cambridge_Reference_Sequence">version</a> that differs by only a few tiny mutations.</p> <div class="gallery center-hack"> <div class="center-block"> <a href="/img/hg19-256.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-256.png?via=html" alt="hg19.fa"/> </a> <a href="/img/hg19-rCRS-256.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-rCRS-256.png?via=html" alt="hg19.fa with the rCRS mitochondrial genome"/> </a> </div> </div> <p>And because of the recursive nature of the algorithm, the image can be generated at smaller or larger sizes and maintain the same level of detail. Here is the same genome at a number of different sizes. Note that this is not simply zoomed out. That would lose too much sharpness by averaging pixels. These are generated specially at each size, with only the necessary pixels added.</p> <div class="gallery center-hack"> <div class="center-block"> <a href="/img/hg19-256.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-256.png?via=html" alt="256x256"/> </a> <a href="/img/hg19-128.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-128.png?via=html" alt="128x128"/> </a> <a href="/img/hg19-64.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-64.png?via=html" alt="64x64"/> </a> <a href="/img/hg19-32.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-32.png?via=html" alt="32x32"/> </a> <a href="/img/hg19-16.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-16.png?via=html" alt="16x16"/> </a> </div> </div> </div> </section> <section id="experiments" class="panel"> <div class="panel-heading"> <h3>Early Experiments</h3> </div> <div class="panel-body"> <p>Because of the way the algorithm generates multiple layers which have to be mixed, an important tuning factor is the weight given to each layer. I tried several different algorithms to determine the weighting, and the result I've shown is what I thought worked the best. But here I'll show some other options I tried, some of which I think would be better in certain contexts. Feedback is definitely appreciated, since I know I don't have the most artistic eye.</p> <p>This version emphasizes the small details, and I think it really shows the vast amount of information I'm attempting to summarize.</p> <div class="gallery center-hack"> <div class="center-block"> <a href="/img/hg19-opacity4.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-opacity4.png?via=html" alt="hg19.fa"/> </a> </div> </div> <p>This one is on the other extreme, but it does make the pattern very clear and identifiable. It might work best for small icons.</p> <div class="gallery center-hack"> <div class="center-block"> <a href="/img/hg19-opacity1.png"> <img class="img-responsive img-thumbnail" src="/img/hg19-opacity1.png?via=html" alt="hg19.fa"/> </a> </div> </div> </div> </section> </div> {% endblock content %}
import {auth} from '@/firebase/firebase'; import { createUserWithEmailAndPassword, signInWithEmailAndPassword, sendEmailVerification, type UserCredential, type User } from 'firebase/auth'; import type { iUser } from '../firestore/users'; import { createUser, getUser } from '../firestore/users'; export interface AuthUser { user?: iUser; userFirebase?: User error?: string; errorCode?: AuthError; } export enum AuthError { EMAIL_EXISTS = 'auth/email-already-in-use', INVALID_EMAIL = 'auth/invalid-email', USER_NOT_VERIFIED = 'auth/user-not-verified', OPERATION_NOT_ALLOWED = 'auth/operation-not-allowed', WEAK_PASSWORD = 'auth/weak-password', USER_DISABLED = 'auth/user-disabled', USER_NOT_FOUND = 'auth/user-not-found', WRONG_PASSWORD = 'auth/wrong-password', UNKNOWN = 'auth/unknown', } const matchAndFormatErrorCode = (errorCode: string): string => { switch (errorCode) { case AuthError.EMAIL_EXISTS: return 'Email already exists'; case AuthError.INVALID_EMAIL: return 'Invalid email'; case AuthError.USER_NOT_VERIFIED: return 'User not verified'; case AuthError.OPERATION_NOT_ALLOWED: return 'Operation not allowed'; case AuthError.WEAK_PASSWORD: return 'Weak password'; case AuthError.USER_DISABLED: return 'User disabled'; case AuthError.USER_NOT_FOUND: return 'User not found'; case AuthError.WRONG_PASSWORD: return 'Wrong password'; default: return 'Unknown error'; } } // registerUser function // This function takes in an email and password and creates a new user in Firebase Authentication. // It returns a promise that resolves with the user object. export const registerUser = async (email: string, password: string, userData:iUser): Promise<AuthUser> => { try { const userCredential = await createUserWithEmailAndPassword(auth, email, password); const user = userCredential.user; userData.userID = user.uid; await createUser(userData); await sendEmailVerification(user); const authUser = { user:userData, userFirebase:userCredential.user, error: undefined }; return authUser; } catch (error:any) { const formattedError = matchAndFormatErrorCode(error.code); const authUser = { user: undefined, error: formattedError, errorCode: error.code }; return authUser; } }; //login a user //This function takes in an email and password and signs in the user in Firebase Authentication. //It returns a promise that resolves with the user object. export const loginUser = async (email: string, password: string): Promise<AuthUser> => { try { const userCredential = await signInWithEmailAndPassword(auth, email, password); const user = userCredential.user; const userVerified = user.emailVerified if (!userVerified) { await logoutUser(); const authUser = { user: undefined, error: 'User is not verified, please check your email and verify your account', errorCode: AuthError.USER_NOT_VERIFIED}; return authUser; } const userData = await getUser(user.uid); if(!userData) { return { user: undefined, error: 'User not found in database' }; } localStorage.setItem('user', JSON.stringify(userData)); return { user: userData, userFirebase: userCredential.user, error: undefined }; } catch (error:any) { const authUser = { user: undefined, error: error.message }; return authUser; } }; // logout a user // This function signs out the user from Firebase Authentication. // It returns a promise that resolves with the user object. export const logoutUser = async () => { try { await auth.signOut(); localStorage.removeItem('user'); } catch (error:any) { throw new Error(error.message); } }; // get current user // This function returns the current user object from Firebase Authentication. // It returns a promise that resolves with the user object. // fetches their data from Firestore and returns the user object. export const getCurrentUser = async () => { try { const user = auth.currentUser; if (user) { const userData = await getUser(user.uid); console.log(userData); return userData; } else { return null; } } catch (error:any) { return null; } };
import paddle import os import json import argparse import itertools import math import commons import utils from data_utils import TextAudioLoader, TextAudioCollate, DistributedBucketSampler from models import SynthesizerTrn, MultiPeriodDiscriminator from losses import generator_loss, discriminator_loss, feature_loss, kl_loss from mel_processing import mel_spectrogram_torch, spec_to_mel_torch from text.symbols import symbols from visualdl import LogWriter global_step = 0 def main(): """Assume Single Node Multi GPUs Training Only""" assert paddle.device.cuda.device_count( ) >= 1, 'CPU training is not allowed.' n_gpus = paddle.device.cuda.device_count() os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = '11266' hps = utils.get_hparams() # paddle.distributed.spawn(func=run, args=(n_gpus, hps,), nprocs = n_gpus) run(rank=0, n_gpus=1, hps=hps) def run(rank, n_gpus, hps): global global_step if rank == 0: logger = utils.get_logger(hps.model_dir) logger.info(hps) utils.check_git_hash(hps.model_dir) # writer = torch.utils.tensorboard.SummaryWriter(log_dir=hps.model_dir) # writer_eval = torch.utils.tensorboard.SummaryWriter(log_dir=os.path # .join(hps.model_dir, 'eval')) writer = LogWriter(logdir=hps.model_dir) writer_eval = LogWriter(logdir=os.path .join(hps.model_dir, 'eval')) paddle.distributed.init_parallel_env() paddle.seed(seed=hps.train.seed) paddle.device.set_device('gpu') train_dataset = TextAudioLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler(train_dataset, batch_size=hps.train.batch_size, boundaries=[32, 300, 400, 500, 600, 700, 800, 900, 1000],num_replicas=n_gpus, rank=rank, shuffle=True) collate_fn = TextAudioCollate() train_loader = paddle.io.DataLoader(train_dataset, num_workers=0, shuffle=False, collate_fn=collate_fn, batch_sampler=train_sampler) if rank == 0: eval_dataset = TextAudioLoader(hps.data.validation_files, hps.data) eval_loader = paddle.io.DataLoader(eval_dataset, num_workers =0, shuffle=False, batch_size=hps.train.batch_size, drop_last=False, collate_fn=collate_fn) net_g = SynthesizerTrn(len(symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, **hps.model) net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm) optim_g = paddle.optimizer.AdamW(parameters=net_g.parameters(), learning_rate=hps.train.learning_rate, epsilon=hps.train.eps, beta1 =hps.train.betas[0], beta2=hps.train.betas[1], weight_decay=0.0) optim_d = paddle.optimizer.AdamW(parameters=net_d.parameters(), learning_rate=hps.train.learning_rate, epsilon=hps.train.eps, beta1 =hps.train.betas[0], beta2=hps.train.betas[1], weight_decay=0.0) net_g = paddle.DataParallel(layers=net_g) net_d = paddle.DataParallel(layers=net_d) try: _, _, _, epoch_str = utils.load_checkpoint(utils. latest_checkpoint_path(hps.model_dir, 'G_*.pdparams'), net_g, optim_g) _, _, _, epoch_str = utils.load_checkpoint(utils. latest_checkpoint_path(hps.model_dir, 'D_*.pdparams'), net_d, optim_d) global_step = (epoch_str - 1) * len(train_loader) except: epoch_str = 1 global_step = 0 tmp_lr = paddle.optimizer.lr.ExponentialDecay(gamma=hps.train.lr_decay, last_epoch=epoch_str - 2, learning_rate=optim_g.get_lr()) optim_g.set_lr_scheduler(tmp_lr) scheduler_g = tmp_lr tmp_lr = paddle.optimizer.lr.ExponentialDecay(gamma=hps.train.lr_decay, last_epoch=epoch_str - 2, learning_rate=optim_d.get_lr()) optim_d.set_lr_scheduler(tmp_lr) scheduler_d = tmp_lr scaler = paddle.amp.GradScaler(enable=hps.train.fp16_run, incr_every_n_steps=2000, init_loss_scaling=65536.0) for epoch in range(epoch_str, hps.train.epochs + 1): if rank == 0: train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, eval_loader], logger, [writer, writer_eval]) else: train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, None], None, None) scheduler_g.step() scheduler_d.step() def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers): net_g, net_d = nets optim_g, optim_d = optims scheduler_g, scheduler_d = schedulers train_loader, eval_loader = loaders if writers is not None: writer, writer_eval = writers train_loader.batch_sampler.set_epoch(epoch) global global_step net_g.train() net_d.train() for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths ) in enumerate(train_loader): x, x_lengths = x, x_lengths spec, spec_lengths = spec, spec_lengths y, y_lengths = y, y_lengths with paddle.amp.auto_cast(enable=hps.train.fp16_run): y_hat, l_length, attn, ids_slice, x_mask, z_mask, (z, z_p, m_p, logs_p, m_q, logs_q) = net_g(x, x_lengths, spec, spec_lengths) mel = spec_to_mel_torch(spec, hps.data.filter_length, hps.data. n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax) y_mel = commons.slice_segments(mel, ids_slice, hps.train. segment_size // hps.data.hop_length) y_hat_mel = mel_spectrogram_torch(y_hat.squeeze(axis=1), hps. data.filter_length, hps.data.n_mel_channels, hps.data. sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax) y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with paddle.amp.auto_cast(enable=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss( y_d_hat_r, y_d_hat_g) loss_disc_all = loss_disc optim_d.clear_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with paddle.amp.auto_cast(enable=hps.train.fp16_run): y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) with paddle.amp.auto_cast(enable=False): loss_dur = paddle.sum(x=l_length.astype(dtype='float32')) loss_mel = paddle.nn.functional.l1_loss(input=y_mel, label= y_hat_mel) * hps.train.c_mel loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask ) * hps.train.c_kl loss_fm = feature_loss(fmap_r, fmap_g) loss_gen, losses_gen = generator_loss(y_d_hat_g) loss_gen_all = (loss_gen + loss_fm + loss_mel + loss_dur + loss_kl) optim_g.clear_grad() scaler.scale(loss_gen_all).backward() scaler.unscale_(optim_g) grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None) scaler.step(optim_g) scaler.update() if rank == 0: if global_step % hps.train.log_interval == 0: lr = optim_g.get_lr() losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_dur, loss_kl] logger.info('Train Epoch: {} [{:.0f}%]'.format(epoch, 100.0 * batch_idx / len(train_loader))) logger.info([x.item() for x in losses] + [global_step, lr]) scalar_dict = {'loss/g/total': loss_gen_all, 'loss/d/total': loss_disc_all, 'learning_rate': lr, 'grad_norm_d': grad_norm_d, 'grad_norm_g': grad_norm_g} scalar_dict.update({'loss/g/fm': loss_fm, 'loss/g/mel': loss_mel, 'loss/g/dur': loss_dur, 'loss/g/kl': loss_kl}) scalar_dict.update({'loss/g/{}'.format(i): v for i, v in enumerate(losses_gen)}) scalar_dict.update({'loss/d_r/{}'.format(i): v for i, v in enumerate(losses_disc_r)}) scalar_dict.update({'loss/d_g/{}'.format(i): v for i, v in enumerate(losses_disc_g)}) image_dict = {'slice/mel_org': utils. plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()), 'slice/mel_gen': utils.plot_spectrogram_to_numpy( y_hat_mel[0].data.cpu().numpy()), 'all/mel': utils. plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()), 'all/attn': utils.plot_alignment_to_numpy(attn[0, 0]. data.cpu().numpy())} utils.summarize(writer=writer, global_step=global_step, images=image_dict, scalars=scalar_dict) if global_step % hps.train.eval_interval == 0: evaluate(hps, net_g, eval_loader, writer_eval) utils.save_checkpoint(net_g, optim_g, hps.train. learning_rate, epoch, os.path.join(hps.model_dir, 'G_{}.pdparams'.format(global_step))) utils.save_checkpoint(net_d, optim_d, hps.train. learning_rate, epoch, os.path.join(hps.model_dir, 'D_{}.pdpatams'.format(global_step))) global_step += 1 if rank == 0: logger.info('====> Epoch: {}'.format(epoch)) def evaluate(hps, generator, eval_loader, writer_eval): generator.eval() with paddle.no_grad(): for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths ) in enumerate(eval_loader): x, x_lengths = x, x_lengths spec, spec_lengths = spec, spec_lengths y, y_lengths = y, y_lengths x = x[:1] x_lengths = x_lengths[:1] spec = spec[:1] spec_lengths = spec_lengths[:1] y = y[:1] y_lengths = y_lengths[:1] break y_hat, attn, mask, *_ = generator._layers.infer(x, x_lengths, max_len=1000) y_hat_lengths = mask.sum(axis=[1, 2]).astype(dtype='int64' ) * hps.data.hop_length mel = spec_to_mel_torch(spec, hps.data.filter_length, hps.data. n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps. data.mel_fmax) y_hat_mel = mel_spectrogram_torch(y_hat.squeeze(axis=1).astype( dtype='float32'), hps.data.filter_length, hps.data. n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax) image_dict = {'gen/mel': utils.plot_spectrogram_to_numpy(y_hat_mel[0]. cpu().numpy())} audio_dict = {'gen/audio': y_hat[(0), :, :y_hat_lengths[0]]} if global_step == 0: image_dict.update({'gt/mel': utils.plot_spectrogram_to_numpy(mel[0] .cpu().numpy())}) audio_dict.update({'gt/audio': y[(0), :, :y_lengths[0]]}) utils.summarize(writer=writer_eval, global_step=global_step, images= image_dict, audios=audio_dict, audio_sampling_rate=hps.data. sampling_rate) generator.train() if __name__ == '__main__': main()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes // https://www.runoob.com/w3cnote/es6-class.html // class关键字定义类,本质是function // 和函数不同,类的声明不会被提升,因此必须先声明后使用 let Example = class { // constructor方法用于创建和初始化一个Class对象,一个类只能有一个 // 可以通过super关键字调用父类的构造函数 constructor(a='构造体内部函数运行') { this.a = a; console.log(`Example${this.a}`) } } // 两种类定义的方式等价 let Example1 = class Example1 { constructor(a='构造体内部函数运行') { this.a = a; console.log(`Example1${this.a}`) } showMessage() { console.log('类中的方法不需要function关键字') } } let a = new Example('类声明时传入的变量'); // Example类声明时传入的变量 let b = new Example1(); // Example1构造体内部函数运行 b.showMessage() // 类中的方法不需要function关键字 // 向类中添加方法的两种途径 Example1.prototype.addMethods1 = function() { console.log('CLASS_NAME.prototype.FUNCTION_NAME可以通过该方法覆盖/初始化添加方法') } Object.assign(Example1.prototype,{ addMethods2() { console.log('Object.assign(CLASS_NAME.prototype,function name() {})方法也可以添加/覆盖方法') } }) b.addMethods1() // CLASS_NAME.prototype.FUNCTION_NAME可以通过该方法覆盖/初始化添加方法 b.addMethods2() // Object.assign(CLASS_NAME.prototype,function name() {})方法也可以添加/覆盖方法 </script> </body> </html>
import { base_user_data, user_data } from "./basics"; export { months, dateComparison, yearOnlyDate, normalDates, trashDate, hasMonth, }; // Array of months for tests. var months = [ "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", ]; // A function that will allow us to sort dates in order. function hasMonth(a: user_data) { return months.some((month) => { var RegExMonth = new RegExp("\\b" + month + "\\b"); return RegExMonth.test(a.BirthdayDate.toLowerCase()); }); } class trashDate { a: any; b: any; constructor( a: user_data = { ...base_user_data }, b: user_data = { ...base_user_data } ) { this.a = a; this.b = b; } dateCheck(a: user_data) { if ( isNaN(new Date(a.BirthdayDate) as unknown as number) && !months.some((month) => { var RegExMonth = new RegExp("\\b" + month + "\\b"); return RegExMonth.test(a.BirthdayDate.toLowerCase()); }) ) { return true; } else { return false; } } find() { if (this.dateCheck(this.a)) { if (this.dateCheck(this.b)) { return this.a.BirthdayDate.localeCompare(this.b.BirthdayDate); } else { return 1; } } else if (this.dateCheck(this.b)) { if (this.dateCheck(this.a)) { return this.b.BirthdayDate.localeCompare(this.a.BirthdayDate); } else { return -1; } } } } class yearOnlyDate { a: any; b: any; constructor( a: user_data = { ...base_user_data }, b: user_data = { ...base_user_data } ) { this.a = a; this.b = b; } dateCheck(a: user_data) { if ( !months.some((month) => { var RegExMonth = new RegExp("\\b" + month + "\\b"); return RegExMonth.test(a.BirthdayDate.toLowerCase()); }) && /^\d{4}$/.test(a.BirthdayDate) ) { return true; } else { return false; } } find() { const date1 = new Date(this.a.BirthdayDate); const date2 = new Date(this.b.BirthdayDate); if ( // All "Year only" dates get sorted down but above trash dates. this.dateCheck(this.a) ) { if (!this.dateCheck(this.b)) { return 1; } else { return date1.getFullYear() - date2.getFullYear(); } } else if (this.dateCheck(this.b)) { if (!this.dateCheck(this.a)) { return -1; } else { return date2.getFullYear() - date1.getFullYear(); } } } } class normalDates { a: any; b: any; constructor( a: user_data = { ...base_user_data }, b: user_data = { ...base_user_data } ) { this.a = a; this.b = b; } dateCheck(a: user_data, b: user_data) { if ( new trashDate(a, b).dateCheck(this.a) || new trashDate(a, b).dateCheck(this.b) || new yearOnlyDate(a, b).dateCheck(this.a) || new yearOnlyDate(a, b).dateCheck(this.b) ) { return true; } else { return false; } } find() { let date1 = new Date(this.a.BirthdayDate); let date2 = new Date(this.b.BirthdayDate); if (this.dateCheck(this.a, this.b)) { return; } if (!/\d/.test(this.a.BirthdayDate)) { date1 = new Date( months.find((month) => { var RegExMonth = new RegExp("\\b" + month + "\\b"); return RegExMonth.test(this.a.BirthdayDate.toLowerCase()); }) + "1" ); } if (!/\d/.test(this.b.BirthdayDate)) { date2 = new Date( months.find((month) => { var RegExMonth = new RegExp("\\b" + month + "\\b"); return RegExMonth.test(this.b.BirthdayDate.toLowerCase()); }) + "1" ); } if (date1.getMonth() != date2.getMonth()) { if (new Date().getMonth() >= date1.getMonth()) { if ( new Date().getMonth() == date1.getMonth() && new Date().getDate() <= date1.getDate() ) { return -1; } if ( new Date().getMonth() > date1.getMonth() && new Date().getMonth() > date2.getMonth() ) { return date1.getMonth() - date2.getMonth(); } return 1; } else if (new Date().getMonth() >= date2.getMonth()) { if ( new Date().getMonth() == date2.getMonth() && new Date().getDate() <= date2.getDate() ) { return 1; } if ( new Date().getMonth() > date1.getMonth() && new Date().getMonth() > date2.getMonth() ) { return date1.getMonth() - date2.getMonth(); } return -1; } return date1.getMonth() - date2.getMonth(); } if (date1.getMonth() == date2.getMonth()) { if (date1.getDate() == date2.getDate()) { if (hasMonth(this.a) && !/\d/.test(this.a.BirthdayDate)) { return -1; } else if (hasMonth(this.b) && !/\d/.test(this.b.BirthdayDate)) { return 1; } return date1.getFullYear() - date2.getFullYear(); } if ( new Date().getMonth() == date1.getMonth() && new Date().getDate() > date1.getDate() ) { if ( new Date().getMonth() == date2.getMonth() && new Date().getDate() > date2.getDate() ) { return date1.getDate() - date2.getDate(); } return 1; } else if ( new Date().getMonth() == date2.getMonth() && new Date().getDate() > date2.getDate() ) { if ( new Date().getMonth() == date1.getMonth() && new Date().getDate() > date1.getDate() ) { return date1.getDate() - date2.getDate(); } return -1; } return date1.getDate() - date2.getDate(); } } } function dateComparison( a: user_data = { ...base_user_data }, b: user_data = { ...base_user_data } ) { // All "Trash dates" get sorted down if (new trashDate(a, b).dateCheck(a) || new trashDate(a, b).dateCheck(b)) { return new trashDate(a, b).find(); } // All "Year only dates" get sorted down if ( new yearOnlyDate(a, b).dateCheck(a) || new yearOnlyDate(a, b).dateCheck(b) ) { return new yearOnlyDate(a, b).find(); } // All normal months with dates get sorted includeing sorted by year with the same date return new normalDates(a, b).find(); }
<!DOCTYPE html> {% load staticfiles %} <html> <head> <meta charset="UTF-8"> <title>Basic Panel - jQuery EasyUI Demo</title> <link rel="stylesheet" type="text/css" href="{% static 'themes/default/easyui.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'themes/icon.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'demo.css' %}"> <script type="text/javascript" src="{% static 'jquery.min.js' %}"></script> <script type="text/javascript" src="{% static 'jquery.easyui.min.js' %}"></script> </head> <body class="easyui-layout"> <div data-options="region:'north',border:false" style="height:100px;background:#B3DFDA;padding:10px"> <div class="easyui-panel" style="height:100px;background:#B3DFDA;padding:10px"> <a href="{% url 'index' %}" class="easyui-linkbutton" data-options="plain:true">Home</a> <a href="{% url 'users:logout' %}" class="easyui-linkbutton" data-options="plain:true">Exit</a> <a href="#" class="easyui-splitbutton" data-options="menu:'#mm1',iconCls:'icon-edit'">Edit</a> <a href="#" class="easyui-splitbutton" data-options="menu:'#mm2',iconCls:'icon-ok'">Ok</a> <a href="#" class="easyui-menubutton" data-options="menu:'#mm3',iconCls:'icon-help'">Help</a> </div> <div id="mm1" style="width:150px;"> <div data-options="iconCls:'icon-undo'">Undo</div> <div data-options="iconCls:'icon-redo'">Redo</div> <div class="menu-sep"></div> <div>Cut</div> <div>Copy</div> <div>Paste</div> <div class="menu-sep"></div> <div> <span>Toolbar</span> <div> <div>Address</div> <div>Link</div> <div>Navigation Toolbar</div> <div>Bookmark Toolbar</div> <div class="menu-sep"></div> <div>New Toolbar...</div> </div> </div> <div data-options="iconCls:'icon-remove'">Delete</div> <div>Select All</div> </div> <div id="mm2" style="width:100px;"> <div data-options="iconCls:'icon-ok'">Ok</div> <div data-options="iconCls:'icon-cancel'">Cancel</div> </div> <div id="mm3" style="width:150px;"> <div>Help</div> <div>Update</div> <div> <span>About</span> <div class="menu-content" style="padding:10px;text-align:left"> <img src="http://www.jeasyui.com/images/logo1.png" style="width:150px;height:50px"> <p style="font-size:14px;color:#444">Try jQuery EasyUI to build your modern, interactive, javascript applications.</p> </div> </div> </div> </div> <div data-options="region:'west',split:true,title:'West'" style="width:150px;padding:10px;">west content</div> <div data-options="region:'east',split:true,collapsed:true,title:'East'" style="width:100px;padding:10px;">east region</div> <div data-options="region:'south',border:false" style="height:50px;background:#A9FACD;padding:10px;">south region</div> <div data-options="region:'center',title:'Center'"> <div style="margin:20px 0;"></div> <table id="dg" title="Custom DataGrid Pager" style="width:700px;height:250px" data-options="rownumbers:true,singleSelect:true,pagination:true,url:'datagrid_data1.json',method:'get'"> <thead> <tr> <th data-options="field:'itemid',width:80">Item ID</th> <th data-options="field:'productid',width:100">Product</th> <th data-options="field:'listprice',width:80,align:'right'">List Price</th> <th data-options="field:'unitcost',width:80,align:'right'">Unit Cost</th> <th data-options="field:'attr1',width:240">Attribute</th> <th data-options="field:'status',width:60,align:'center'">Status</th> </tr> </thead> </table> <script type="text/javascript"> $(function(){ var pager = $('#dg').datagrid().datagrid('getPager'); // get the pager of datagrid pager.pagination({ buttons:[{ iconCls:'icon-search', handler:function(){ alert('search'); } },{ iconCls:'icon-add', handler:function(){ alert('add'); } },{ iconCls:'icon-edit', handler:function(){ alert('edit'); } }] }); }) </script> </div> </body> </html>
import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.time.LocalTime; import java.util.Scanner; public class PlanGenerator { String IMAGE_NAME = "Grundrissplan"; String FILE_EXTENSION = "jpg"; // jpg has 72ppi = 2835 pixel per m String VISA = "fe"; String PATH = "."; int NBR_ROOMS; int APARTMENT_WIDTH_IN_M; int APARTMENT_HEIGHT_IN_M = 5; int FACTOR_M_IN_PIXEL = 100; int APARTMENT_WIDTH_IN_PIXEL; int APARTMENT_HEIGHT_IN_PIXEL; int MARGIN_IN_PIXEL = 100; boolean IS_DARK_MODE = true; double FACTOR_LIVING_ROOM_BATHROOM = 0.7; double FACTOR_BEDROOM_KITCHEN = 0.6; public void generateImage() { long start = System.currentTimeMillis(); Scanner scanner = new Scanner(System.in); System.out.println("Breite:"); //APARTMENT_WIDTH_IN_M = scanner.nextInt(); APARTMENT_WIDTH_IN_M = 10; System.out.println("Höhe:"); //APARTMENT_HEIGHT_IN_M = scanner.nextInt(); APARTMENT_HEIGHT_IN_M = 5; scanner.close(); NBR_ROOMS = calculateNbrOfRooms(APARTMENT_WIDTH_IN_M, APARTMENT_HEIGHT_IN_M); APARTMENT_WIDTH_IN_PIXEL = APARTMENT_WIDTH_IN_M * FACTOR_M_IN_PIXEL; APARTMENT_HEIGHT_IN_PIXEL = APARTMENT_HEIGHT_IN_M * FACTOR_M_IN_PIXEL; int imageWidthInPixel = APARTMENT_WIDTH_IN_PIXEL + 2 * MARGIN_IN_PIXEL; int imageHeightInPixel = APARTMENT_HEIGHT_IN_PIXEL + 2 * MARGIN_IN_PIXEL; BufferedImage bufferedImage = new BufferedImage(imageWidthInPixel, imageHeightInPixel, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = bufferedImage.createGraphics(); Image.switchDarkMode(graphics2D, IS_DARK_MODE, imageWidthInPixel, imageHeightInPixel); // Header graphics2D.drawString("Grundrissplan für " + NBR_ROOMS + " Zimmer mit " + APARTMENT_WIDTH_IN_M * APARTMENT_HEIGHT_IN_M + "m^2", 20, 35); graphics2D.drawLine(0, MARGIN_IN_PIXEL / 2 + 10, imageWidthInPixel, MARGIN_IN_PIXEL / 2 + 10); // Ground plan graphics2D.drawRect(MARGIN_IN_PIXEL, MARGIN_IN_PIXEL, APARTMENT_WIDTH_IN_PIXEL, APARTMENT_HEIGHT_IN_PIXEL); graphics2D.drawString(String.valueOf(APARTMENT_WIDTH_IN_PIXEL), MARGIN_IN_PIXEL - 5 + APARTMENT_WIDTH_IN_PIXEL / 2, MARGIN_IN_PIXEL - 10); graphics2D.drawString(String.valueOf(APARTMENT_HEIGHT_IN_PIXEL), MARGIN_IN_PIXEL - 30, MARGIN_IN_PIXEL + 5 + APARTMENT_HEIGHT_IN_PIXEL / 2); // Rooms drawRoom("Wohnzimmer", MARGIN_IN_PIXEL, MARGIN_IN_PIXEL + APARTMENT_HEIGHT_IN_PIXEL / 2, (int) (FACTOR_LIVING_ROOM_BATHROOM * APARTMENT_WIDTH_IN_PIXEL), APARTMENT_HEIGHT_IN_PIXEL / 2, graphics2D); drawRoom("Badezimmer", MARGIN_IN_PIXEL + (int) (FACTOR_LIVING_ROOM_BATHROOM * APARTMENT_WIDTH_IN_PIXEL), MARGIN_IN_PIXEL + APARTMENT_HEIGHT_IN_PIXEL / 2, (int) (APARTMENT_WIDTH_IN_PIXEL * (1 - FACTOR_LIVING_ROOM_BATHROOM)), APARTMENT_HEIGHT_IN_PIXEL / 2, graphics2D); drawRoom("Schlafzimmer", MARGIN_IN_PIXEL, MARGIN_IN_PIXEL, (int) (APARTMENT_WIDTH_IN_PIXEL * FACTOR_BEDROOM_KITCHEN), APARTMENT_HEIGHT_IN_PIXEL / 2, graphics2D); drawRoom("Küche", MARGIN_IN_PIXEL + (int) (APARTMENT_WIDTH_IN_PIXEL * FACTOR_BEDROOM_KITCHEN), MARGIN_IN_PIXEL, (int) (APARTMENT_WIDTH_IN_PIXEL * (1 - FACTOR_BEDROOM_KITCHEN)), APARTMENT_HEIGHT_IN_PIXEL / 2, graphics2D); // Footer graphics2D.drawLine(0, imageHeightInPixel - MARGIN_IN_PIXEL / 2 - 10, imageWidthInPixel, imageHeightInPixel - MARGIN_IN_PIXEL / 2 - 10); graphics2D.drawString("Gezeichnet: " + getCurrentTime(), 20, imageHeightInPixel - 25); graphics2D.drawLine(300, imageHeightInPixel - MARGIN_IN_PIXEL / 2 - 10, 300, imageHeightInPixel); graphics2D.drawString("Author: " + VISA, 310, imageHeightInPixel - 25); graphics2D.drawLine(500, imageHeightInPixel - MARGIN_IN_PIXEL / 2 - 10, 500, imageHeightInPixel); graphics2D.drawString("M: 1:" + 100, 510, imageHeightInPixel - 25); graphics2D.drawLine(700, imageHeightInPixel - MARGIN_IN_PIXEL / 2 - 10, 700, imageHeightInPixel); graphics2D.dispose(); File file = new File(PATH + File.separator + IMAGE_NAME + "." + FILE_EXTENSION); try { ImageIO.write(bufferedImage, "jpg", file); } catch (IOException e) { throw new RuntimeException(e); } long timeElapsed = System.currentTimeMillis() - start; System.out.println("Generated image in \u001B[34m" + timeElapsed / 1000.0 + "s\u001B[0m at path " + file.getAbsolutePath()); } private void drawRoom(String roomName, int roomX, int roomY, int roomWidth, int roomHeight, Graphics2D graphics2D) { int roomArea = roomWidth * roomHeight / (FACTOR_M_IN_PIXEL * FACTOR_M_IN_PIXEL); String livingRoomText = roomName + " " + roomArea + "m^2"; graphics2D.drawRect(roomX, roomY, roomWidth, roomHeight); graphics2D.drawString(livingRoomText, roomX + roomWidth / 2 - graphics2D.getFontMetrics().stringWidth(livingRoomText) / 2, roomY + roomHeight / 2 - 5); } private int calculateNbrOfRooms(int width, int height) { int area = width * height; int averageAreaKitchen = 12; int averageAreaBath = 8; int averageAreaRoom = 15; int areaRooms = area - averageAreaKitchen - averageAreaBath; return areaRooms / averageAreaRoom; } private String getCurrentTime() { LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); return date.getDayOfMonth() + "." + date.getMonthValue()+ "." + date.getYear() + " " + time.getHour() + ":" + time.getMinute() + ":" + time.getSecond(); } }
import React from "react"; import { useState } from "react"; import { View, Image, StyleSheet, Animated, TouchableOpacity, } from "react-native"; import Modal from "./Modal.js"; function header() { const [modalVisible, setModalVisible] = useState(false); const rotateAnim = new Animated.Value(0); const startRotation = () => { rotateAnim.setValue(0); // 애니메이션 Animated.timing(rotateAnim, { toValue: 1, duration: 1000, useNativeDriver: true, }).start(); }; // 회전 값 인터폴레이션 const rotate = rotateAnim.interpolate({ inputRange: [0, 1], outputRange: ["0deg", "360deg"], }); // 애니메이션 스타일 const rotationStyles = { transform: [{ rotate }], }; return ( // 상단 헤더 부분 화면 <View> <View style={styles.header}> <TouchableOpacity onPress={startRotation}> <Animated.Image source={require("../assets/header/refreash.png")} style={[{ width: 40, height: 40, marginLeft: 5 }, rotationStyles]} /> </TouchableOpacity> <Image source={require("../assets/header/applogo.png")} style={{ width: 100, height: 40, marginLeft: 10 }} /> <View> <TouchableOpacity onPress={() => setModalVisible(true)}> <Image source={require("../assets/header/report.png")} style={{ width: 45, height: 45 }} /> </TouchableOpacity> <Modal modalVisible={modalVisible} setModalVisible={setModalVisible} /> </View> </View> <View style={styles.underbar} /> </View> ); } // 스타일 정의 const styles = StyleSheet.create({ header: { marginTop: 50, width: 350, flexDirection: "row", alignItems: "center", justifyContent: "space-between", backgroundColor: "#fff", }, underbar: { marginTop: 20, height: 4, borderRadius: 5, backgroundColor: "#61677A", width: 350, }, }); export default header;
/*var jogador1 = 0; var jogador2 = 1; var placar; //----------------------------------------IFs---------------------------------------------------------// //aninhamento de ifs if(jogador1 != -1){ if(jogador1>0){ console.log('Jogador 1 marcou ponto!'); }else if(jogador2>0){ console.log('Jogador 2 marcou ponto!'); } else{ console.log('Ninguem marcou ponto.'); } } //if ternario jogador1 != -1 && jogador2 != -1 ? console.log('Os jogadores são validos') : console.log('Jogadores invalidos.'); //usando if if(jogador1 > 0 && jogador2 == 0){ console.log('Jogador 1 marcou ponto!'); placar = jogador1 > jogador2; //usando else if }else if(jogador2 > 0 && jogador1 == 0){ console.log('Jogador 2 marcou ponto!'); placar = jogador2 > jogador1; //usando else } else{ console.log('Ninguem marcou ponto.'); } switch(placar){ case placar = jogador1 > jogador2: console.log('jogador 1 ganhou'); break; case placar = jogador2 > jogador1: console.log('Jogador 2 ganhou'); break; default: console.log('Ninguem ganhou'); }*/ //-----------------------------------------ESTRUTURAS DE REPETICAO------------------------------------------// let array = ['valor1', 'valor2', 'valor3', 'valor4', 'valor5',]; let object = { propriedade1: 'valor1', propriedade2: 'valor2', propriedade3: 'valor3',} //-----------------------------------------------FOR---------------------------------------------------// //for - executa uma instrucao até que ela seja falsa /*for(let indice = 0; indice < array.length; indice++){ console.log(indice); }*/ //for in - executa repeticao a partir de uma propriedade //com array /*for(i in array){ console.log(i); }*/ //com object /*for(i in object){ console.log(i); }*/ //for of - execcuta repeticao a partir de valor //com array /*for(i of array){ console.log(i); }*/ //com object /*for(i of object.propriedade1){ console.log(i); }*/ var a = 0; //-------------------------------------WHILE--------------------------------------------------// /*while(a < 10){ a++; console.log(a); }*/ //------------------------------------DO WHILE ------------------------------------------------// do{ a++; console.log(a); }while(a < 10)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; using WpfInterface.Animated; using WpfInterface.Interfaces; namespace WpfInterface.Transformations { /// <summary> /// Custom animation class for uniform 6D motion /// </summary> public class Uniform6DTransformation : AnimationTimeline { #region Fields /// <summary> /// Full transformation /// </summary> Transform3DGroup transform = new Transform3DGroup(); /// <summary> /// Translation /// </summary> TranslateTransform3D translation = new TranslateTransform3D(); /// <summary> /// Constant rotation /// </summary> RotateTransform3D rotate_const = new RotateTransform3D(); /// <summary> /// Uniform rotation /// </summary> RotateTransform3D rotate_uniform = new RotateTransform3D(); /// <summary> /// Quaternion of constant rotation /// </summary> QuaternionRotation3D quaternionConstRotation = new QuaternionRotation3D(); /// <summary> /// Axis angle rotation for uniform rotation /// </summary> AxisAngleRotation3D angle_uniform = new AxisAngleRotation3D(); /// <summary> /// Calculator /// </summary> Motion6D.Uniform6D.Uniform6DMotion calculator; double[] rotationAxis = new double[3]; object loc = new object(); private Queue<Tuple<TimeSpan, double[], double[]>> queue = new Queue<Tuple<TimeSpan, double[], double[]>>(); public static readonly DependencyProperty FromProperty; public static readonly DependencyProperty ToProperty; AnimatableWrapper wrapper; IAnimatable animatable; DependencyProperty dependencyProperty; private bool isStopped = false; private double currentTime; private Motion6D.Interfaces.ReferenceFrame frame; private DateTime startTime; private TimeSpan forecast; private IAnimatedObject animated; private bool realtime; private double[] changeFrameTime; #endregion #region Ctor internal Uniform6DTransformation(AnimatableWrapper wrapper, Motion6D.Interfaces.ReferenceFrame frame, bool realtime, double[] changeFrameTime, TimeSpan forecastTime) { transform.Children.Add(rotate_uniform); // Adds uniform rotation transform.Children.Add(rotate_const); // Adds constant rptation transform.Children.Add(translation); // Adds translation rotate_const.Rotation = quaternionConstRotation; // Setting quaterion for constant rotation rotate_uniform.Rotation = angle_uniform; // Setting axis rotation for uniform rotation this.wrapper = wrapper; animatable = wrapper.Animatable; dependencyProperty = wrapper.DependencyProperty; this.frame = frame; this.changeFrameTime = changeFrameTime; From = 0; To = 1; calculator = new Motion6D.Uniform6D.Uniform6DMotion(frame, rotationAxis, changeFrameTime, forecastTime.TotalSeconds, wrapper.Animated.CoordinateError, wrapper.Animated.AngleError); animated = wrapper.Animated; forecast = animated.ForecastTime; this.realtime = realtime; if (realtime) { calculator.InitializePrediction(forecast.TotalSeconds); } calculator.Change += Motion_Change; } private Uniform6DTransformation(Uniform6DTransformation lm) : this(lm.wrapper, lm.frame, lm.realtime, lm.changeFrameTime, lm.forecast) { rotationAxis = lm.rotationAxis; queue = lm.queue; calculator = lm.calculator; currentTime = lm.currentTime; startTime = lm.startTime; From = lm.From; To = lm.To; Set(); } #endregion #region Public Members /// <summary> /// From /// </summary> public double From { get { return (double)GetValue(Uniform6DTransformation.FromProperty); } set { SetValue(Uniform6DTransformation.FromProperty, value); } } /// <summary> /// To /// </summary> public double To { get { return (double)GetValue(Uniform6DTransformation.ToProperty); } set { SetValue(Uniform6DTransformation.ToProperty, value); } } #endregion #region Overriden Members /// <summary> /// Overriden calculation of current value /// </summary> /// <param name="defaultOriginValue">Default Origin Value</param> /// <param name="defaultDestinationValue">Default Destination Value</param> /// <param name="animationClock">Animation Clock</param> /// <returns>Transformation</returns> public override object GetCurrentValue(object defaultOriginValue, object defaultDestinationValue, AnimationClock animationClock) { SetProgressTime(animationClock.CurrentProgress.Value); return transform; } /// <summary> /// Type of target property /// </summary> public override Type TargetPropertyType { get { return typeof(Transform3D); } } /// <summary> /// Creates freezable instance /// </summary> /// <returns>Instance</returns> protected override Freezable CreateInstanceCore() { Uniform6DTransformation l = new Uniform6DTransformation(this); l.queue = queue; l.currentTime = currentTime; return l; } #endregion #region Internal Members /// <summary> /// Adds animation parameters /// </summary> /// <param name="parameters">Parameters</param> internal void Enqueue(Tuple<TimeSpan, double[], double[]> parameters) { lock (loc) { if (isStopped) { return; } queue.Enqueue(parameters); } } internal void Stop() { lock (loc) { if (!isStopped) { isStopped = true; if (realtime) { this.Completed -= Linear6DMotion_RealtimeAnimationCompleted; animatable.BeginAnimation(dependencyProperty, null); } else { this.Completed -= Linear6DMotion_RealtimeAnimationCompleted; queue.Clear(); animatable.BeginAnimation(dependencyProperty, null); isStopped = true; wrapper.Finish(); } } } } internal void StartAnimation(double[] coord, double[] quaternion, DateTime start) { Action action = () => { StartAnimationPrivate(coord, quaternion, start); }; this.Dispatcher.Invoke(action); } internal void StartRealtime(double time, DateTime start) { Action action = () => { StartRealtimePrivate(time, start); }; this.Dispatcher.Invoke(action); } /// <summary> /// Time /// </summary> internal double Time { get { // lock (loc) // { return currentTime; // } } } /// <summary> /// Inits itself /// </summary> /// <param name="coord">Coordinates</param> /// <param name="quaternion">Quaternion</param> internal void Init(double[] coord, double[] quaternion) { calculator.Init(coord, quaternion); } internal void Event() { double time = (DateTime.Now - startTime).TotalSeconds; calculator.Interrupt(time); } #endregion #region Private Members static Uniform6DTransformation() { FromProperty = DependencyProperty.Register("From", typeof(double), typeof(Uniform6DTransformation)); ToProperty = DependencyProperty.Register("To", typeof(double), typeof(Uniform6DTransformation)); } void Motion_Change() { Dispatcher.Invoke(MotionChange); } void MotionChange() { animatable.BeginAnimation(dependencyProperty, null); animatable.BeginAnimation(dependencyProperty, this); } private void Set() { double[] quater1 = calculator.QuaternionBegin; Quaternion qua = new Quaternion(quater1[1], quater1[2], quater1[3], quater1[0]); SetProgressTime(currentTime); quaternionConstRotation.Quaternion = qua; System.Windows.Media.Media3D.Vector3D v = new System.Windows.Media.Media3D.Vector3D(rotationAxis[0], rotationAxis[1], rotationAxis[2]); angle_uniform.Axis = v; From = 0; To = 1; } /// <summary> /// Sets progress time /// </summary> /// <param name="progressTime">Progress time</param> private void SetProgressTime(double progressTime) { double angle; // Angle of rotation double x, y, z; // Coordinates of transformation calculator.SetTime(progressTime, out angle, out x, out y, out z); // Calculation of coordinates and angle angle_uniform.Angle = (180 / Math.PI) * angle; // Sets value of rotation angle double fromVal = From; double toVal = To; // Setting of coordinates of transformation translation.OffsetX = x; translation.OffsetY = y; translation.OffsetZ = z; } private void StartAnimationPrivate(double[] coord, double[] quaternion, DateTime start) { Tuple<TimeSpan, double[], double[]> parameters; lock (loc) { parameters = queue.Dequeue(); } startTime = start; this.Duration = parameters.Item1; this.RepeatBehavior = new RepeatBehavior(1); calculator.Set(parameters.Item2, parameters.Item3); this.Completed += Linear6DMotion_AnimationCompleted; System.Windows.Media.Media3D.Vector3D v = new System.Windows.Media.Media3D.Vector3D(rotationAxis[0], rotationAxis[1], rotationAxis[2]); angle_uniform.Axis = v; angle_uniform.Angle = 0; Quaternion qua = new Quaternion(quaternion[1], quaternion[2], quaternion[3], quaternion[0]); quaternionConstRotation.Quaternion = qua; translation.OffsetX = coord[0]; translation.OffsetY = coord[1]; translation.OffsetZ = coord[2]; From = 0; To = 1; animatable.BeginAnimation(dependencyProperty, this); } private void StartRealtimePrivate(double time, DateTime start) { startTime = start; this.Duration = forecast; this.RepeatBehavior = new RepeatBehavior(1); calculator.StartRealtime(time); this.Completed += Linear6DMotion_RealtimeAnimationCompleted; System.Windows.Media.Media3D.Vector3D v = new System.Windows.Media.Media3D.Vector3D(rotationAxis[0], rotationAxis[1], rotationAxis[2]); angle_uniform.Axis = v; angle_uniform.Angle = 0; double[] quaternion = calculator.QuaternionBegin; double[] coord = calculator.Begin; Quaternion qua = new Quaternion(quaternion[1], quaternion[2], quaternion[3], quaternion[0]); quaternionConstRotation.Quaternion = qua; translation.OffsetX = coord[0]; translation.OffsetY = coord[1]; translation.OffsetZ = coord[2]; From = 0; To = 1; animatable.BeginAnimation(dependencyProperty, this); } void Linear6DMotion_RealtimeAnimationCompleted(object sender, EventArgs e) { if (isStopped) { return; } double time = (DateTime.Now - startTime).TotalSeconds; calculator.StepRealtime(time); Action action = () => { animatable.BeginAnimation(dependencyProperty, this); }; Dispatcher.Invoke(action); } void Linear6DMotion_AnimationCompleted(object sender, EventArgs e) { Tuple<TimeSpan, double[], double[]> parameters; lock (loc) { if (queue.Count == 0) { wrapper.Finish(); return; } parameters = queue.Dequeue(); } calculator.SetNew(parameters.Item2, parameters.Item3); TimeSpan ts = startTime + parameters.Item1 - DateTime.Now; if (ts.Ticks < 0) { return; } Action action = () => { Duration = ts; animatable.BeginAnimation(dependencyProperty, this); }; Dispatcher.Invoke(action); } #endregion } }
import React, { useState } from "react"; import styles from "../../styles/news.module.scss"; // Image import news1 from "../../assets/images/news1.svg"; import news2 from "../../assets/images/news2.svg"; import news3 from "../../assets/images/news3.svg"; // Components import NewsCard from "./news_card"; // React Intl import { useTranslations } from "next-intl"; import Link from "next/link"; const News = () => { const t = useTranslations("News"); const NewsList = [ { image: news1, title: t("News1Title"), tag: t("Technology"), date: "january 20, 2023", }, { image: news2, title: t("News2Title"), tag: t("Technology"), date: "March 14, 2023", }, { image: news3, title: t("News3Title"), tag: t("Technology"), date: "May 03, 2023", }, ]; return ( <> <div className={styles.news}> <div className={styles.news_wrapper}> <div className={styles.news_title}> <p>{t("News")}</p> <h2> <span>{t("Explore FDT latest news and insights")}</span> <Link href={"/blog"}>{t("View All")}</Link> </h2> </div> <div className={styles.news_cols}> {NewsList?.map((item, index) => ( <div className={styles.news_col} key={index}> <NewsCard data={{ image: item.image, title: item.title, tag: item.tag, date: item.date, }} /> </div> ))} </div> </div> </div> </> ); }; export default News;
#include <stdio.h> #include <stdlib.h> struct P{ int at,bt,wt,tat; }; float avgWT(struct P p[],int n); float avgTAT(struct P p[],int n); int main(){ int n,comp=0; float avg_wt,avg_tat; printf("Enter number of processes:\n"); scanf("%d",&n); struct P p[n]; printf("Enter arrival and burst times for all processes:\n"); for(int i=0;i<n;i++){ printf("Arrival time for P%d:\n",i+1); scanf("%d",&p[i].at); printf("Burst time for P%d:\n",i+1); scanf("%d",&p[i].bt); comp+=p[i].bt; p[i].tat=comp-p[i].at; p[i].wt=p[i].tat-p[i].bt; } avg_wt=avgWT(p,n); printf("\nAvg WT: %.2f\n",avg_wt); avg_tat=avgTAT(p, n); printf("\nAvg TAT: %.2f\n",avg_tat); return 0; } float avgWT(struct P p[],int n){ int wt=0; for (int i=0;i<n;i++){ wt+=p[i].wt; } return (float)wt/n; } float avgTAT(struct P p[],int n){ int tat=0; for(int i=0;i<n;i++){ tat+=p[i].tat; } return (float)tat/n; }
import { PrismaClient } from '@prisma/client'; import dotenv from 'dotenv'; import moment from 'moment-timezone'; import supertest from 'supertest'; import app from '../../src/app'; import { AuthHelper } from '../../src/middleware/AuthHelper'; import { AddUser } from '../../src/validations/UserValidation'; import { Payload } from '../payloads/Payload'; import { createHabit } from '../utils/HabitUtil'; import { createUserWithFCM } from '../utils/UserUtil'; dotenv.config({ path: `${__dirname}/../../.env.test` }); moment.tz.setDefault('Asia/Seoul'); describe('testHabit', () => { const testClient = supertest(app); const prisma = new PrismaClient(); let habitId: number, token: string; beforeEach(async done => { await prisma.commitHistory.deleteMany({}); await prisma.habit.deleteMany({}); await prisma.userItem.deleteMany({}); await prisma.item.deleteMany({}); await prisma.user.deleteMany({}); await prisma.scheduler.deleteMany({}); const user = await createUserWithFCM(prisma, new AddUser({ name: '김건훈', oauthKey: 'dnatuna123@gmail.com' })); token = AuthHelper.makeAccessToken(user.userId); habitId = await createHabit(prisma, user); done(); }); // POST creatHabits test('createHabits', async () => { for (let i = 0; i < 3; i += 1) { const payload = Payload.habitOriginalPayloads[i]; const res = await testClient.post('/habits').set('Authorization', `Bearer ${token}`).send(payload); if (i === 0) { habitId = res.body.habitId; } expect(res.status).toBe(201); expect(res.body).toMatchObject({ habitId: habitId + i, userId: AuthHelper.extractUserFromToken(token), title: payload.title, category: payload.category, description: payload.description, dayOfWeek: payload.dayOfWeek, alarmTime: payload.alarmTime, continuousCount: 0, }); } }); // GET getHabits test('getHabits', async () => { const res = await testClient.get('/habits').set('Authorization', `Bearer ${token}`); expect(res.status).toBe(200); expect(res.body).toMatchObject({ comment: res.body.comment, habits: Payload.habitGetPayloads(habitId), }); }); // GET getHabit test('getHabit', async () => { for (let i = 0; i < 3; i += 1) { const payload = Payload.habitOriginalPayloads[i]; const year = parseInt(moment().format('YYYY')); const month = parseInt(moment().format('MM')); const res = await testClient.get(`/habits/${habitId + i}/calendar/${year}/${month}`).set('Authorization', `Bearer ${token}`); expect(res.status).toBe(200); expect(res.body).toMatchObject({ habit: { habitId: habitId + i, userId: AuthHelper.extractUserFromToken(token), title: payload.title, category: payload.category, description: payload.description, dayOfWeek: payload.dayOfWeek, alarmTime: payload.alarmTime, continuousCount: 0, commitHistory: [], }, commitFullCount: 0, }); } }); // PUT updateHabit test('updateHabit', async () => { for (let i = 0; i < 3; i += 1) { const payload = Payload.habitUpdatePayloads[i]; const res = await testClient .put(`/habits/${habitId + i}`) .set('Authorization', `Bearer ${token}`) .send(payload); if (i === 0) { habitId = res.body.habitId; } expect(res.status).toBe(201); expect(res.body).toMatchObject({ habitId: habitId + i, userId: AuthHelper.extractUserFromToken(token), title: payload.title, category: payload.category, description: payload.description, dayOfWeek: payload.dayOfWeek, alarmTime: payload.alarmTime, continuousCount: 0, }); } }); // DELETE deleteHabit test('deleteHabit', async () => { const res = await testClient.delete(`/habits/${habitId}`).set('Authorization', `Bearer ${token}`); expect(res.status).toBe(200); expect(res.body).toMatchObject({ message: 'success', }); }); afterAll(async done => { // Closing the DB connection allows Jest to exit successfully. await prisma.disconnect(); done(); }); });
import 'package:chitto_tatto/features/category/data/repository/category_local_repo_impl.dart'; import 'package:chitto_tatto/features/category/domain/entity/category_entity.dart'; import 'package:chitto_tatto/features/food/domain/entity/food_entity.dart'; import 'package:dartz/dartz.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../../core/common/provider/internet_connectivity.dart'; import '../../../../core/failure/failure.dart'; import '../../data/repository/category_remote_repo_impl.dart'; final categoryRepositoryProvider = Provider<ICategoryRepository>( (ref) { // return ref.watch(batchLocalRepoProvider); // // Check for the internet final internetStatus = ref.watch(connectivityStatusProvider); if (ConnectivityStatus.isConnected == internetStatus) { // If internet is available then return remote repo return ref.watch(categoryRemoteRepoProvider); } else { // If internet is not available then return local repo return ref.watch(categoryLocalRepoProvider); } }, ); abstract class ICategoryRepository { Future<Either<Failure, List<CategoryEntity>>> getAllCategories(); Future<Either<Failure, bool>> addCategory(CategoryEntity category); Future<Either<Failure, List<FoodEntity>>> getAllFoodsByCategory( String categoryId); Future<Either<Failure, bool>> deleteCategory(String id); }
import React, { useState } from "react"; import Header from "./components/Header"; import Home from "./components/Home"; import About from "./components/About"; import Menu from "./components/Menu"; import Products from "./components/Products"; import Review from "./components/Review"; import Contact from "./components/Contact"; import Blogs from "./components/Blogs"; import Footer from "./components/Footer"; const App = () => { const [navbarActive, setNavbarActive] = useState(false); const [searchFormActive, setSearchFormActive] = useState(false); const [cartItemActive, setCartItemActive] = useState(false); const [cartItems, setCartItems] = useState([]); const handleNavbarClick = () => { setNavbarActive(!navbarActive); setSearchFormActive(false); setCartItemActive(false); }; const handleSearchFormClick = () => { setSearchFormActive(!searchFormActive); setNavbarActive(false); setCartItemActive(false); }; const handleCartItemClick = () => { setCartItemActive(!cartItemActive); setNavbarActive(false); setSearchFormActive(false); }; const handleAddToCart = (product) => { setCartItems([...cartItems, product]); }; const handleScroll = () => { setNavbarActive(false); setSearchFormActive(false); setCartItemActive(false); }; window.onscroll = handleScroll; return ( <div className="App"> <Header onNavbarClick={handleNavbarClick} onSearchFormClick={handleSearchFormClick} onCartItemClick={handleCartItemClick} navbarActive={navbarActive} searchFormActive={searchFormActive} cartItemActive={cartItemActive} cartItems={cartItems} /> <Home /> <About /> <Menu onAddToCart={handleAddToCart} /> <Products /> <Review /> <Contact /> <Blogs /> <Footer /> </div> ); }; export default App;
<template> <div class="app-container"> <div class="filter-container" style="margin-bottom:10px;"> <router-link :to="'/trade/mallorder'"> <el-button type="primary" icon="el-icon-back">返回列表</el-button> </router-link> </div> <el-table ref="multipleTable" :data="list" v-loading="listLoading" element-loading-text="Loading" @selection-change="handleSelectionChange" border fit highlight-current-row> <el-table-column type="selection" width="35"></el-table-column> <el-table-column prop="order_sn" label="订单编号" width="130"> <template slot-scope="scope"> <span class="link-type"> {{scope.row.order_code}} </span> </template> </el-table-column> <el-table-column prop="mall_name" label="商城" width="80"></el-table-column> <el-table-column label="商品名称"> <template slot-scope="scope"> <a class="link-type" v-for="item in scope.row.products" :title="item.name" :href="item.url"> {{item.name|titleFilter}}<br> </a> </template> </el-table-column> <el-table-column prop="product_code" label="商品ID" width="110"> <template slot-scope="scope"> <span v-for="item in scope.row.products"> {{item.code}}<br> </span> </template> </el-table-column> <el-table-column prop="platform" label="来源" width="70"> <template slot-scope="scope"> {{scope.row.platform|platformFilter}} </template> </el-table-column> <el-table-column prop="item_count" label="数量" width="60"></el-table-column> <el-table-column prop="item_price" label="单价(元)" width="70"></el-table-column> <el-table-column prop="sales" label="总额(元)" width="70"></el-table-column> <el-table-column prop="commission" label="佣金" width="60"> <template slot-scope="scope"> <span v-if="scope.row.commission>0">{{scope.row.commission}}</span> <span v-else>--</span> </template> </el-table-column> <el-table-column prop="fxje" label="返利" width="60"></el-table-column> <el-table-column prop="jifen" label="积分" width="60"></el-table-column> <el-table-column label="会员" width="100"> <template slot-scope="scope"> <a v-if="scope.row.user != null" class="link-type"> {{scope.row.user.ddusername}} </a> </template> </el-table-column> <el-table-column prop="status" label="状态" width="100"> <template slot-scope="scope"> {{scope.row.status|statusFilter}} </template> </el-table-column> <el-table-column label="时间" width="200"> <template slot-scope="scope"> <span style="color: blue">下单:{{scope.row.order_time|parseTime}}</span><br> <span style="color: green">更新:{{scope.row.update_time}}</span><br> <span v-if="scope.row.pay_time!='0000-00-00'" style="color: red">结算:{{scope.row.pay_time}}</span> <span v-else style="color: red">结算:--</span> </template> </el-table-column> <el-table-column prop="operate" label="操作" width="60"> <template slot-scope="scope"> </template> </el-table-column> </el-table> <div class="pagination-container"> <el-checkbox v-if="checkAll==0" :indeterminate="isIndeterminate" @change="toggleSelection(list)">全选</el-checkbox> <el-checkbox v-else-if="checkAll==1" :indeterminate="isIndeterminate" @change="toggleSelection(list)">反选</el-checkbox> <el-checkbox v-else @change="toggleSelection()" :indeterminate="isIndeterminate">取消全选</el-checkbox> <el-button type="danger" size="mini" @click="handleDelete()">彻底删除</el-button> <el-pagination background @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[listQuery.limit]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination> </div> </div> </template> <script> import { getList,deleteData } from '@/api/mallorder' import { parseTime, parseDate} from '@/utils' const fieldOptions = [ { key: 'order_code', name: '订单号' }, { key: 'title', name: '商品名' }, { key: 'product_code', name: '商品ID' }, { key: 'uname', name: '会员名' }, { key: 'uid', name: '会员id' }, ] const platformOptions = [ { key: 1, name: '电脑' }, { key: 2, name: '手机' }, { key: null, name: '全部' }, ] const statusOptions = [ { key: -1, name: '订单已失效' }, { key: 0, name: '订单未确认' }, { key: 1, name: '订单已确认' }, { key: null, name: '全部订单' }, ] //将platformOptions对象转换成数组 const platformArray = platformOptions.reduce((acc, cur) => { acc[cur.key] = cur.name return acc }, {}) //将statusOptions对象转换成数组 const statusArray = statusOptions.reduce((acc, cur) => { acc[cur.key] = cur.name return acc }, {}) export default { data() { return { tableKey: 0, list: null, total: null, listLoading: true, listQuery: { page: 1, limit: 15, searchJoin: 'and', search: 'del:1;', searchFields: 'del:=;', orderBy: 'id', sortedBy: 'desc', filter: '' }, searchQuery: { search: 'del:1;', searchFields: 'del:=;', field: '',//搜索字段 keyword: '',//搜索字段对应关键词 status: '',//搜索订单状态 platform: '',//搜索来源 }, fieldOptions, statusOptions, platformOptions, multipleSelection: [], checkAll: 0, isIndeterminate: false, } }, filters: { //截取前20位 titleFilter(str) { return str.length>10?str.substr(0,26)+'...':str }, statusFilter(type) { return statusArray[type] }, platformFilter(type) { return platformArray[type] }, }, //添加后重载列表 created() { this.getList() }, methods: { //获取列表 getList() { this.listLoading = true getList(this.listQuery).then(response => { this.list = response.data.data this.total = response.data.total this.listLoading = false }) }, //更换页面 handleCurrentChange(val) { this.listQuery.page = val this.getList() }, //全选、反选、取消全选 toggleSelection(rows) { if (rows) { rows.forEach(row => { this.$refs.multipleTable.toggleRowSelection(row) }); } else { this.$refs.multipleTable.clearSelection() } }, //获取选中对象 handleSelectionChange(val) { this.multipleSelection = val; if(this.multipleSelection.length == this.list.length){ this.checkAll = 2 this.isIndeterminate = true }else if (this.multipleSelection.length > 0) { this.checkAll = 1 this.isIndeterminate = true }else{ this.checkAll = 0 this.isIndeterminate = false } }, //批量删除 handleDelete () { if(this.multipleSelection.length<=0){ this.$notify({ title: '警告', message: '请选择要删除的条目', type: 'warning' }); return false } this.$confirm('此操作将数据彻底删除, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'error' }).then(() => { let ids = '' for (const v of this.multipleSelection) { ids += v.id + ',' } this.listLoading = true deleteData(ids).then(response => { this.$message({ type: 'success', message: response.data.message }) //重载数据 this.getList() this.listLoading = false }) }).catch(() => { //取消后的操作 }) }, } } </script> <style scoped> .pagination-container{ margin-top: 10px; } .el-pagination{ float: right; } .el-form-item{ margin-bottom: 10px; } </style>
syntax = "proto3"; option java_package = "org.oliverlittle.clusterprocess"; // DataSource and PartialDataSource messages message DataSource { oneof source { CassandraDataSource cassandra = 1; GroupByDataSource group_by = 2; } } message PartialDataSource { oneof source { PartialCassandraDataSource cassandra = 1; PartialGroupByDataSource group_by = 2; } } message CassandraDataSource { string keyspace = 1; string table = 2; } message PartialCassandraDataSource { string keyspace = 1; string table = 2; repeated CassandraTokenRange token_ranges = 3; } message CassandraTokenRange { sint64 start = 1; sint64 end = 2; } message InetSocketAddress { string host = 1; int32 port = 2; } message GroupByDataSource { Table table = 1; repeated NamedExpression unique_fields = 2; repeated AggregateExpression aggregate_fields = 3; } message PartialGroupByDataSource { GroupByDataSource parent = 1; PartitionInformation partition = 2; } message PartitionInformation { uint32 partition_number = 1; uint32 total_partitions = 2; } // Table and FieldExpression messages // Represents some value accepted by the system. message Value { oneof value { string field = 1; string string = 2; string datetime = 3; sint64 int = 4; double double = 5; bool bool = 6; bool null = 7; // Not sure if this is needed } } // Represents an arbitrary field expression. // To represent references to tables on their own, this would be an Expression containing a single value with a table_field in it. message Expression { // Recursive step - an argument to an expression is either a value, or a Function Call containing other expressions. message FunctionCall { string function_name = 1; repeated Expression arguments = 2; } oneof expr { FunctionCall function = 1; Value value = 2; } } // Represents a field expression that has been assigned a name message NamedExpression { string name = 1; Expression expr = 2; } // Represents an transformation that can be applied to the table. message TableTransformation { oneof instruction { Select select = 1; Filter filter = 2; Join join = 3; GroupBy group_by = 4; Aggregate aggregate = 5; OrderBy order_by = 6; Window window = 7; } } message Table { DataSource data_source = 1; repeated TableTransformation transformations = 2; } message PartialTable { PartialDataSource data_source = 1; repeated TableTransformation transformations = 2; } // A Select statement is made up of any number of Fields (calculated or not) message Select { repeated NamedExpression fields = 1; } // A Filter Statement is made up of two arguments message Filter { oneof expression { FilterExpression filter = 1; CombinedFilterExpression combined_filter = 2; } } message CombinedFilterExpression { enum BooleanOperator { UNKNOWN_TYPE = 0; AND = 1; OR = 2; } Filter left_expression = 1; BooleanOperator operator = 2; Filter right_expression = 3; } message FilterExpression { enum FilterType { option allow_alias = true; UNKNOWN_TYPE = 0; EQUAL = 1; EQ = 1; NOT_EQUAL = 2; NE = 2; LESS_THAN = 3; LT = 3; LESS_THAN_EQUAL = 4; LTE = 4; GREATER_THAN = 5; GT = 5; GREATER_THAN_EQUAL = 6; GTE = 6; IS_NULL = 7; NULL = 7; IS_NOT_NULL = 8; NOT_NULL = 8; CONTAINS = 9; ICONTAINS = 10; STARTS_WITH = 11; ISTARTS_WITH = 12; ENDS_WITH = 13; IENDS_WITH = 14; } Expression left_value = 1; FilterType filter_type = 2; optional Expression right_value = 3; // Right value is optional as null and not null do not require it } // A Join statement is made up of two table names, and a join type. message Join { enum JoinType { option allow_alias = true; UNKNOWN_TYPE = 0; FULL_OUTER_JOIN = 1; OUTER_JOIN = 1; INNER_JOIN = 2; LEFT_JOIN = 3; RIGHT_JOIN = 4; CROSS_JOIN = 5; } JoinType join_type = 2; string table_name = 3; } // A GroupBy statement is made up a series of Fields (calculated or not) message GroupBy { repeated Expression group_by_fields = 1; } // An Aggregate statement is made up of any number of UnnamedFields (which should use Aggregate functions) message Aggregate { repeated AggregateExpression aggregate_fields = 1; } message AggregateExpression { enum AggregateType { UNKNOWN_TYPE = 0; MIN = 1; MAX = 2; SUM = 3; AVG = 4; COUNT = 5; COUNT_DISTINCT = 6; STRING_CONCAT = 7; STRING_CONCAT_DISTINCT = 8; } AggregateType aggregate_type = 1; NamedExpression expr = 2; optional string arg = 3; // Used for optional args - e.g: STRING_AGG delimiter } // An OrderBy is made up of any number of Fields, with an ascending/descending flag message OrderBy { enum OrderByType { option allow_alias = true; UNKNOWN_TYPE = 0; ASC = 1; ASCENDING = 1; DESC = 2; DESCENDING = 2; } message OrderByField { Expression field = 1; OrderByType order_by_type = 2; } repeated OrderByField order_by_fields = 1; } // A Window Function is a function (using a Window/Aggregate type, a number of fields to partition on, and a number of fields to order on) message Window { repeated Expression window_function = 1; repeated string partition_fields = 2; optional OrderBy order_by_fields = 3; } // Result messages // TableResult can be used optionally as it might be better to instead use message TableResult { TableResultHeader headers = 1; repeated TableResultRow rows = 2; } // Represents data types the system supports enum DataType { UNKNOWN = 0; STRING = 1; DATETIME = 2; INT = 3; DOUBLE = 4; BOOL = 5; } // Headers defining the data types of a table message TableResultHeader { message Header { string fieldName = 1; DataType dataType = 2; } repeated Header fields = 1; } // A single row result in a table message TableResultRow { repeated Value values = 1; } message StreamedTableResult { oneof data { TableResultHeader header = 1; TableResultRow row = 2; } }
import { useState } from 'react'; import PropTypes from 'prop-types'; import Box from '@mui/material/Box'; import DialogTitle from '@mui/material/DialogTitle'; import Dialog from '@mui/material/Dialog'; import IconButton from '@mui/material/IconButton'; import CloseIcon from '@mui/icons-material/Close'; import Typography from '@mui/material/Typography'; import Chip from '@mui/material/Chip'; import { Button, DialogContent } from '@mui/material'; const TagsDialogTitle = function TagsDialogTitle(props) { const { children, onClose, ...other } = props; return ( <DialogTitle sx={{ m: 0, p: 2 }} {...other}> {children} {onClose ? ( <IconButton aria-label="close" onClick={onClose} sx={{ position: 'absolute', right: 8, top: 8, color: (theme) => theme.palette.grey[500], }} > <CloseIcon /> </IconButton> ) : null} </DialogTitle> ); }; TagsDialogTitle.propTypes = { children: PropTypes.node, onClose: PropTypes.func.isRequired, }; const TagsDialog = function TagsDialog(props) { const { tags, onClose, open } = props; const handleClose = () => { onClose(); }; return ( <Dialog onClose={handleClose} open={open}> <TagsDialogTitle onClose={onClose}>Currency&apos;s Tags:</TagsDialogTitle> <DialogContent> <Box mt={1} display="flex" sx={{ flexWrap: 'wrap' }}> {tags.map( (tag) => tag !== null && ( <Box mb={1} mr={1}> <Chip color="primary" label={tag} /> </Box> ) )} </Box> </DialogContent> </Dialog> ); }; TagsDialog.propTypes = { onClose: PropTypes.func.isRequired, open: PropTypes.bool.isRequired, tags: PropTypes.arrayOf(PropTypes.string).isRequired, }; const CurrencyCategoryTags = function CurrencyCategoryTags({ data }) { const [open, setOpen] = useState(false); const handleOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <Box display="flex" justifyContent="center" flexDirection="column" sx={{ width: '100%' }}> <Box display="flex" flexDirection="column" justifyContent="left" alignContent="middle"> <Typography variant="body4" align="left" color="secondary.main" sx={{ maxWidth: 200 }}> Tags: </Typography> </Box> {data?.categories.length > 0 && data?.categories[0] !== null && ( <> <Box mt={1} display="flex" sx={{ flexWrap: 'wrap' }}> {data?.categories.slice(0, 3).map( (category) => category !== null && ( <Box mb={1} mr={1}> <Chip color="secondary" label={ <Typography variant="body" noWrap sx={{ maxWidth: 160 }}> {category} </Typography> } size="small" sx={{ maxWidth: 160 }} /> </Box> ) )} </Box> <Box> <Button variant="contained" size="small" color="info" onClick={handleOpen}> View All </Button> </Box> </> )} {(!data?.categories.length || data?.categories[0] === null) && ( <Box my={2}> <Typography variant="body" color="secondary"> -- </Typography> </Box> )} <TagsDialog tags={data?.categories} open={open} onClose={handleClose} /> </Box> ); }; export default CurrencyCategoryTags;
/*! * Fresns 微信小程序 (https://fresns.cn) * Copyright 2021-Present 唐杰 * Licensed under the Apache-2.0 license */ import { fresnsApi } from '../../../sdk/services/api'; import { fresnsLang } from '../../../sdk/helpers/configs'; import { callPageFunction } from '../../../sdk/utilities/toolkit'; Component({ /** 组件的属性列表 **/ properties: { group: { type: Object, value: null, }, }, /** 组件的初始数据 **/ data: { buttonIcons: { like: '/assets/images/interaction/like.png', likeActive: '/assets/images/interaction/like-active.png', dislike: '/assets/images/interaction/dislike.png', dislikeActive: '/assets/images/interaction/dislike-active.png', follow: '/assets/images/interaction/follow.png', followActive: '/assets/images/interaction/follow-active.png', block: '/assets/images/interaction/block.png', blockActive: '/assets/images/interaction/block-active.png', }, }, /** 组件数据字段监听器 **/ observers: { group: async function (group) { if (!group) { return; } // buttonIcons const checkButtonIcons = group.operations && group.operations.buttonIcons; if (!checkButtonIcons) { return; } const buttonIconsArr = group.operations.buttonIcons; if (buttonIconsArr.length > 0) { const likeItem = buttonIconsArr.find((item) => item.code === 'like'); const dislikeItem = buttonIconsArr.find((item) => item.code === 'dislike'); const followItem = buttonIconsArr.find((item) => item.code === 'follow'); const blockItem = buttonIconsArr.find((item) => item.code === 'block'); const buttonIcons = { like: likeItem ? likeItem.imageUrl : '/assets/images/interaction/like.png', likeActive: likeItem ? likeItem.imageActiveUrl : '/assets/images/interaction/like-active.png', dislike: dislikeItem ? dislikeItem.imageUrl : '/assets/images/interaction/dislike.png', dislikeActive: dislikeItem ? dislikeItem.imageActiveUrl : '/assets/images/interaction/dislike-active.png', follow: followItem ? followItem.imageUrl : '/assets/images/interaction/follow.png', followActive: followItem ? followItem.imageActiveUrl : '/assets/images/interaction/follow-active.png', block: blockItem ? blockItem.imageUrl : '/assets/images/interaction/block.png', blockActive: blockItem ? blockItem.imageActiveUrl : '/assets/images/interaction/block-active.png', }; this.setData({ buttonIcons: buttonIcons, }); } }, }, /** 组件功能 **/ methods: { // 赞 onClickGroupLike: async function () { const group = this.data.group; const initialGroup = JSON.parse(JSON.stringify(this.data.group)); // 拷贝一个小组初始数据 if (group.interaction.likeStatus) { group.interaction.likeStatus = false; // 取消赞 group.likeCount = group.likeCount ? group.likeCount - 1 : group.likeCount; // 计数减一 } else { group.interaction.likeStatus = true; // 赞 group.likeCount = group.likeCount ? group.likeCount + 1 : group.likeCount; // 计数加一 if (group.interaction.dislikeStatus) { group.interaction.dislikeStatus = false; // 取消踩 group.dislikeCount = group.dislikeCount ? group.dislikeCount - 1 : group.dislikeCount; // 计数减一 } } // mixins/fresnsInteraction.js callPageFunction('onChangeGroup', group); const resultRes = await fresnsApi.user.mark({ markType: 'like', type: 'group', fsid: group.gid, }); // 接口请求失败,数据还原 if (resultRes.code != 0) { callPageFunction('onChangeGroup', initialGroup); } }, // 踩 onClickGroupDislike: async function () { const group = this.data.group; const initialGroup = JSON.parse(JSON.stringify(this.data.group)); // 拷贝一个小组初始数据 if (group.interaction.dislikeStatus) { group.interaction.dislikeStatus = false; // 取消踩 group.dislikeCount = group.dislikeCount ? group.dislikeCount - 1 : group.dislikeCount; // 计数减一 } else { group.interaction.dislikeStatus = true; // 踩 group.dislikeCount = group.dislikeCount ? group.dislikeCount + 1 : group.dislikeCount; // 计数加一 if (group.interaction.likeStatus) { group.interaction.likeStatus = false; // 取消赞 group.likeCount = group.likeCount ? group.likeCount - 1 : group.likeCount; // 计数减一 } } // mixins/fresnsInteraction.js callPageFunction('onChangeGroup', group); const resultRes = await fresnsApi.user.mark({ markType: 'dislike', type: 'group', fsid: group.gid, }); // 接口请求失败,数据还原 if (resultRes.code != 0) { callPageFunction('onChangeGroup', initialGroup); } }, // 关注 onClickGroupFollow: async function () { const group = this.data.group; if (group.interaction.followMethod == 'page') { // 扩展 Web-View 数据 const navigatorData = { title: group.name, url: group.interaction.followAppUrl, gid: group.gid, postMessageKey: 'fresnsFollowGroup', }; // 将链接数据赋予到全局数据中 const app = getApp(); app.globalData.navigatorData = navigatorData; // 访问扩展页面选择用户 wx.navigateTo({ url: '/sdk/extensions/webview', }); return; } const initialGroup = JSON.parse(JSON.stringify(this.data.group)); // 拷贝一个小组初始数据 if (group.interaction.followStatus) { group.interaction.followStatus = false; // 取消关注 group.followCount = group.followCount ? group.followCount - 1 : group.followCount; // 计数减一 } else { group.interaction.followStatus = true; // 关注 group.followCount = group.followCount ? group.followCount + 1 : group.followCount; // 计数加一 if (group.interaction.blockStatus) { group.interaction.blockStatus = false; // 取消屏蔽 group.blockCount = group.blockCount ? group.blockCount - 1 : group.blockCount; // 计数减一 } } // mixins/fresnsInteraction.js callPageFunction('onChangeGroup', group); const resultRes = await fresnsApi.user.mark({ markType: 'follow', type: 'group', fsid: group.gid, }); // 接口请求失败,数据还原 if (resultRes.code != 0) { callPageFunction('onChangeGroup', initialGroup); } }, // 屏蔽 onClickGroupBlock: async function () { const group = this.data.group; const initialGroup = JSON.parse(JSON.stringify(this.data.group)); // 拷贝一个小组初始数据 // 取消屏蔽 if (group.interaction.blockStatus) { group.interaction.blockStatus = false; // 取消屏蔽 group.blockCount = group.blockCount ? group.blockCount - 1 : group.blockCount; // 计数减一 // mixins/fresnsInteraction.js callPageFunction('onChangeGroup', group); const resultRes = await fresnsApi.user.mark({ markType: 'block', type: 'group', fsid: group.gid, }); // 接口请求失败,数据还原 if (resultRes.code != 0) { callPageFunction('onChangeGroup', initialGroup); } return; } // 屏蔽操作,二次确认 wx.showModal({ title: group.interaction.blockName, cancelText: await fresnsLang('cancel'), confirmText: await fresnsLang('confirm'), success: async (res) => { // 确认 if (res.confirm) { group.interaction.blockStatus = true; // 屏蔽 group.blockCount = group.blockCount ? group.blockCount + 1 : group.blockCount; // 计数加一 if (group.interaction.followStatus) { group.interaction.followStatus = false; // 取消关注 group.followCount = group.followCount ? group.followCount - 1 : group.followCount; // 计数减一 } // mixins/fresnsInteraction.js callPageFunction('onChangeGroup', group); const resultRes = await fresnsApi.user.mark({ markType: 'block', type: 'group', fsid: group.gid, }); // 接口请求失败,数据还原 if (resultRes.code != 0) { callPageFunction('onChangeGroup', initialGroup); } } }, }); }, }, });
import { fetchChargerList, findChargerAdapter, findMapCharger } from '@/services/resourceService'; import { dealResponse } from '@/utils/util'; export default { namespace: 'chargerList', state: { showRegisterPanel: false, addRegistrationModalShown: false, registerChargerModalShown: false, allAdaptors: [], //充电桩适配器 allChargers: [], //充电桩列表 allMapChargers: [], // 地图充电桩列表 searchParams: { id: [], chargerStatus: [] }, }, effects: { *fetchInitialData(_, { put }) { const [allChargers, allAdaptors, allMapChargers] = yield Promise.all([ fetchChargerList(), findChargerAdapter(), findMapCharger(), ]); if (!dealResponse(allChargers) && !dealResponse(allAdaptors)) { yield put({ type: 'saveState', payload: { allChargers: [...allChargers], allAdaptors: [...allAdaptors], allMapChargers: [...allMapChargers], }, }); } }, }, reducers: { saveState(state, action) { return { ...state, ...action.payload, }; }, saveAllVehicles(state, action) { return { ...state, allChargers: action.payload, }; }, updateSearchParams(state, action) { return { ...state, searchParams: action.payload, }; }, updateShowRegisterPanel(state, action) { return { ...state, showRegisterPanel: action.payload, }; }, updateAddRegistrationModalShown(state, action) { return { ...state, addRegistrationModalShown: action.payload, }; }, updateRegisterChargerModalShown(state, action) { return { ...state, registerChargerModalShown: action.payload, }; }, }, };
<script> export default { data() { return { username: "", gender: "", interests: [], occupation: "", intro: "", }; }, methods: { handleSubmit(e) { // 阻止跳轉 // e.preventDefault(); console.log( this.username, this.gender, this.interests, this.occupation, this.introe ); }, }, }; </script> <template> <div class="box"> <form @submit.prevent="handleSubmit"> <label for="username">用戶名:</label> <input id="username" type="text" v-model="username" /> <label for="gender">性別:</label> <div id="gender" class="radio-group" > <input name="gender" type="radio" value="male" v-model="gender" /><span>男性</span> <input name="gender" type="radio" value="female" v-model="gender" /><span>女性</span> </div> <label for="interest">興趣:</label> <div id="interest" class="checkbox-group" > <input type="checkbox" name="interests" value="frontend" v-model="interests" /><span>前端</span> <input type="checkbox" name="interests" value="backend" v-model="interests" /><span>後端</span> <input type="checkbox" name="interests" value="fullstack" v-model="interests" /><span>全端</span> </div> <label for="occupation">職業:</label> <select name="occupation" id="occupation" v-model="occupation" > <option value="frontend">前端工程師</option> <option value="backend">後端工程師</option> <option value="fullstack">全端工程師</option> </select> <label for="intro">自我介紹:</label> <textarea id="intro" rows="10" v-model="intro" ></textarea> <button type="submit">提交</button> </form> <div class="result"> <ul> <li>用戶名: {{ username }}</li> <li>性別: {{ gender }}</li> <li>興趣: {{ interests }}</li> <li>職業: {{ occupation }}</li> <li>自我介紹: {{ intro }}</li> </ul> </div> </div> </template> <style scoped> .box { width: 100vw; height: 100vh; max-width: 100%; display: grid; place-items: center; } input, textarea, select { padding: 8px 14px; border: 1px solid hsl(280deg, 50%, 50%); border-radius: 4px; margin-left: 8px; outline: none; background: hsl(280deg, 50%, 30%, 0.2); color: white; } form { display: grid; grid-template-columns: 80px 1fr; row-gap: 14px; width: 50%; } label { text-align: right; } form > :is(input, select, div) { grid-column: 2 / 3; } .radio-group, .checkbox-group { display: grid; grid-template-columns: max-content max-content; align-items: center; column-gap: 12px; } :is(.radio-group, .checkbox-group) > span { grid-column: 2 / 3; } button { border: none; background: linear-gradient( 90deg, hsl(240deg, 50%, 50%), hsl(280deg, 50%, 50%) ); padding: 12px 18px; margin-top: 12px; border-radius: 4px; color: white; } .result { align-self: start; } .result ul { list-style: none; } </style>
import React, { useRef } from 'react' import { FieldValues, UseFormRegister } from 'react-hook-form' import ITransactionData from 'types/transaction' import Input from '../Input' import Button from '../Button' import Select from '../Select' import crossIcon from '../../../assets/images/black_cross.svg' interface ModalProps { open: boolean onClose: () => void select: { id: string label: string placeholder: string name: string options: Array<{ value: string; label: string }> value?: string }[] inputs: { id: string label: string placeholder: string name: string type: string value?: string onClick: () => void }[] buttons: { background: string; textColor: string; children: string; onClick: () => void }[] title: string close: string filter: boolean register: UseFormRegister<FieldValues> transaction?: ITransactionData } const ModalTransactions = ({ ...props }: ModalProps) => { const dialogContentRef = useRef<HTMLDivElement>(null) const dialogRef = useRef<HTMLDialogElement>(null) function handleClose() { if (dialogRef.current) { dialogRef.current.close() } props.onClose() } function onClick() { // здесь действие при нажатии на кнопку } document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { handleClose() } }) const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault() props.onClose() } return props.open ? ( <dialog ref={dialogRef} className="inset-0 mt-12 flex items-center justify-center bg-transparent" role="dialog" > <div className="fixed top-0 left-0 z-10 h-screen w-screen backdrop-blur backdrop-opacity-100" /> <div ref={dialogContentRef} className="relative z-20 flex max-w-full flex-col gap-6 rounded-3xl bg-[#e5e5e5]/50 px-6 py-4 shadow-[0_0_40px_4px_rgba(0,0,0,0.25)] backdrop-blur backdrop-opacity-80 sm:py-10 sm:px-16 md:px-9 md:py-14 lg:py-9 lg:px-14" > <div className="flex justify-center"> <span className="text-xl text-black sm:text-2xl">{props.title}</span> {props.close === '' ? ( <button autoFocus className="absolute top-2 right-2 p-2 focus:outline-none focus-visible:outline-white" onClick={handleClose} > <img alt="Close modal" className="w-4" src={crossIcon} /> </button> ) : null} </div> <form onSubmit={handleSubmit}> {props.select.map((select, index) => ( <Select key={index} error={false} id={select.id} label={select.label} name={select.name} options={select.options} placeholder={select.placeholder} register={props.register} value={select.value ?? ''} /> ))} {props.inputs.map((input, index) => ( <Input key={index} error={false} id={input.id} label={input.label} name={input.name} placeholder={input.placeholder} register={props.register} type={input.type} value={input.value ?? ''} onClick={() => { input.onClick() }} /> ))} {props.filter === false ? ( <> <div className="flex flex-col md:flex-row md:justify-between md:gap-10"> <div className="mb-2 flex flex-col md:w-32"> <Input error={false} id="date" label="Дата" name="date" register={props.register} type="date" value={props.transaction?.date ?? new Date().toISOString().split('T')[0]} onClick={() => { null }} /> </div> <div className="mb-2 flex flex-col md:w-32"> <Input error={false} id="time" label="Время" name="time" register={props.register} type="time" value={props.transaction?.time ?? ''} onClick={() => { null }} /> </div> <div className="mb-2 flex flex-col md:w-32"> <Input error={false} id="amount" label="Сумма" name="amount" placeholder="0" register={props.register} type="number" value={ props.transaction?.amount ? Math.abs(parseFloat(props.transaction?.amount)).toString() : '' } onClick={() => { null }} /> </div> </div> <div className="mb-2 flex flex-col"> <Input error={false} id="description" label="Описание" name="description" placeholder="Не указано" register={props.register} type="text" value={props.transaction?.description} onClick={() => { null }} /> </div> </> ) : ( <> <div className="flex flex-row justify-around"> <div className="mb-2 flex w-24 flex-col sm:w-32"> <Input error={false} id="amount_min" label="От:" name="amount_min" placeholder={'100 руб'} register={props.register} type="number" onClick={() => { null }} /> </div> <div className="mb-2 flex w-24 flex-col sm:w-32"> <Input error={false} id="amount_max" label="До:" name="amount_max" placeholder={'5000 руб'} register={props.register} type="number" onClick={() => { null }} /> </div> </div> <div className="flex flex-row justify-around"> <div className="mb-2 flex w-24 flex-col sm:w-32"> <Input error={false} id="date_min" label="Дата(от):" name="date_min" register={props.register} type="date" onClick={() => { null }} /> </div> <div className="mb-2 flex w-24 flex-col sm:w-32"> <Input error={false} id="date_max" label="Дата(до):" name="date_max" register={props.register} type="date" value={new Date().toISOString().split('T')[0]} onClick={() => { null }} /> </div> </div> </> )} <div className="flex flex-row justify-center"> {props.buttons.map((button, index) => ( <Button key={index} background={button.background} textColor={button.textColor} onClick={() => { if (props.close === button.children) { handleClose() } else { onClick() } button.onClick() }} > {button.children} </Button> ))} </div> </form> </div> </dialog> ) : null } export default ModalTransactions
// Import necessary libraries for GUI, event handling, image processing, and file handling import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.ArrayList; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; // Main class for the landing page, extending JFrame for GUI window public class LandingPage extends JFrame { // Lists to store user and admin data private List<User> userList; private List<User> adminList; // Constructor for the LandingPage class public LandingPage(List<User> userList, List<User> adminList) { this.userList = userList; this.adminList = adminList; // Create a custom panel for the background image BackgroundPanel backgroundPanel = new BackgroundPanel(); backgroundPanel.setLayout(new BorderLayout()); // Create a top panel for the heading JPanel topPanel = new JPanel(); topPanel.setBackground(new Color(0, 0, 0, 0)); // Transparent background topPanel.setLayout(new FlowLayout(FlowLayout.CENTER)); // Label for the heading JLabel headingLabel = new JLabel("WELCOME TO UIC MED SALES"); headingLabel.setFont(new Font("Serif", Font.BOLD, 40)); headingLabel.setForeground(Color.white); // Set the text color to white topPanel.add(headingLabel); // Create a center panel for the buttons JPanel centerPanel = new JPanel(); centerPanel.setBackground(new Color(0, 0, 0, 0)); // Transparent background centerPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20)); // Add spacing between components // Icons for the buttons ImageIcon userIcon = new ImageIcon("resources/images/icons8-user-icon-70.png"); ImageIcon adminIcon = new ImageIcon("resources/images/icons8-administrator-male-70.png"); // Buttons for customer and admin JButton customerButton = new JButton("I am a customer", userIcon); JButton adminButton = new JButton("I am an admin", adminIcon); // Action listener for the customer button customerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { LandingPage.this.setVisible(false); CRMForm crmForm = new CRMForm(userList, LandingPage.this); } }); // Action listener for the admin button adminButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inputName = JOptionPane.showInputDialog(LandingPage.this, "Enter Username:"); String inputPassword = JOptionPane.showInputDialog(LandingPage.this, "Enter Password:"); if (inputName != null && inputPassword != null && inputName.equals("admin") && inputPassword.equals("admin")) { LandingPage.this.setVisible(false); AdminPage adminPage = new AdminPage(adminList, userList, LandingPage.this); } else { JOptionPane.showMessageDialog(LandingPage.this, "Invalid username or password!", "Error", JOptionPane.ERROR_MESSAGE); } } }); // Add buttons to the center panel centerPanel.add(customerButton); centerPanel.add(adminButton); // Add the top and center panels to the background panel backgroundPanel.add(topPanel, BorderLayout.NORTH); backgroundPanel.add(centerPanel, BorderLayout.CENTER); // Add the main background panel to the JFrame add(backgroundPanel); setTitle("Landing Page"); setSize(700, 350); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } // Custom JPanel for background image class BackgroundPanel extends JPanel { private BufferedImage background; // Constructor for the BackgroundPanel class public BackgroundPanel() { try { // Load the background image background = ImageIO.read(new File("resources/images/UI background.jpg")); } catch (IOException e) { e.printStackTrace(); } } // Override the paintComponent method to draw the background image @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(background, 0, 0, getWidth(), getHeight(), this); } } }
package ar.edu.itba.sia.gps; import ar.edu.itba.sia.gps.api.Heuristic; import ar.edu.itba.sia.gps.api.Problem; import ar.edu.itba.sia.gps.api.Rule; import ar.edu.itba.sia.gps.api.State; import java.util.*; public class GPSEngine { Queue<GPSNode> open; List<GPSNode> tiedNodes; Map<State, Integer> bestCosts, bestCostsIddfsRun; Map<State, Integer> generatedStates; Problem problem; long explosionCounter; long borderNodes; long analizedStates; boolean finished; boolean failed; GPSNode solutionNode; Optional<Heuristic> heuristic; // IDDFS-specific fields private int iddfsDepth, previousIddfsDepth, depthReachedCurrentRun, depthReachedPreviousRun; // Use this variable in open set order. protected SearchStrategy strategy; public GPSEngine(Problem problem, SearchStrategy strategy, Heuristic heuristic) { // TODO: open = *Su queue favorito, TENIENDO EN CUENTA EL ORDEN DE LOS NODOS* if(strategy.equals(SearchStrategy.BFS) || strategy.equals(SearchStrategy.DFS) || strategy.equals(SearchStrategy.IDDFS)) { open = new ArrayDeque<>(); } else { Objects.requireNonNull(heuristic); if(strategy.equals(SearchStrategy.ASTAR)) { open = new PriorityQueue<>(10, Comparator // Compare by H + G first .comparingInt((GPSNode o) -> o.getHeuristicValue() + o.getCost()) // If tied, compare only by H .thenComparingInt(GPSNode::getHeuristicValue) // Still tied? Break ties randomly .thenComparing(_unused -> Math.random() - 0.5) ); } else { open = new PriorityQueue<>(10, Comparator .comparingInt(GPSNode::getHeuristicValue) // Tied? Break ties randomly .thenComparing(_unused -> Math.random() - 0.5)); } } borderNodes = 0; analizedStates = 0; bestCosts = new HashMap<>(); bestCostsIddfsRun = new HashMap<>(); generatedStates = new HashMap<>(); tiedNodes = new ArrayList<>(); this.problem = problem; this.strategy = strategy; this.heuristic = Optional.ofNullable(heuristic); explosionCounter = 0; iddfsDepth = 16; depthReachedCurrentRun = 0; depthReachedPreviousRun = -1; finished = false; failed = false; } public void findSolution() { GPSNode rootNode = new GPSNode(problem.getInitState(), 0, null); open.add(rootNode); generatedStates.put(problem.getInitState(), 0); boolean done = false; do { GPSNode currentNode = open.remove(); if (problem.isGoal(currentNode.getState())) { setSolution(currentNode); borderNodes = open.size(); if (strategy == SearchStrategy.IDDFS) { /* Discard unvisited nodes for this depth, all other solutions will be at greater or equal depth. Do this to avoid the IllegalArgumentException thrown by iddfsReset() which will be called during the binary search. */ open.clear(); Optional<GPSNode> binarySearchSolution = iddfsBinarySearch(rootNode, previousIddfsDepth+1, currentNode.getDepth()-1); if (binarySearchSolution.isPresent()) { GPSNode newSolution = binarySearchSolution.get(); if (newSolution.getDepth() >= currentNode.getDepth()) { throw new IllegalStateException(String.format( "Solution found in IDDFS binary search doesn't have less depth than original solution (%d < %d)", newSolution.getDepth(), currentNode.getDepth()) ); } setSolution(binarySearchSolution.get()); } } return; } else { explode(currentNode); } if (open.isEmpty()) { if (strategy == SearchStrategy.IDDFS) { if (depthReachedPreviousRun != -1 && depthReachedCurrentRun == depthReachedPreviousRun) { done = true; } else { depthReachedPreviousRun = depthReachedCurrentRun; // Reset and try again with increased depth iddfsReset(rootNode); iddfsDepth *= 2; previousIddfsDepth = depthReachedPreviousRun; done = false; } } else { done = true; } } } while (!done); failed = true; finished = true; } /** * Perform different DFS runs within the given depth floor and ceiling, using binary search. The objective of this * solution is to find a solution more optimal than the original one found by IDDFS since depth doesn't increase by * 1 but rather exponentially. * This should be called with {@code floor = previousIddfsDepth+1; ceiling = solutionDepth-1 }. * * @param rootNode Root node to start DFS runs with. * @param iddfsDepthFloor Lower bound for the depth. * @param iddfsDepthCeil Upper bound for the depth. * @return Optional with found solution, if any. */ private Optional<GPSNode> iddfsBinarySearch(GPSNode rootNode, int iddfsDepthFloor, int iddfsDepthCeil) { if (iddfsDepthFloor > iddfsDepthCeil) { throw new IllegalArgumentException(String.format("Floor (%d) > ceil (%d) in IDDFS binary search", iddfsDepthFloor, iddfsDepthCeil)); } List<Integer> depths = new ArrayList<>(iddfsDepthCeil - iddfsDepthFloor + 1); Set<Integer> excludedDepths = new HashSet<>(); binarySearchBounds(iddfsDepthFloor, iddfsDepthCeil, depths); Optional<GPSNode> result = Optional.empty(); for (int depth : depths) { if (excludedDepths.contains(depth)) { continue; } // Reset, update depth, and perform search iddfsReset(rootNode); iddfsDepth = depth; while (!open.isEmpty()) { GPSNode currentNode = open.remove(); if (problem.isGoal(currentNode.getState())) { result = Optional.of(currentNode); if (depth == iddfsDepthFloor) { return result; // There's not a better solution, stop here } else { // Don't keep exploring further down this tree open.clear(); break; } } else { explode(currentNode); } } // Discard depths that we won't need to try final Optional<GPSNode> finalResult = result; depths.stream() .filter(d -> finalResult // Solution found? Don't try IDDFS with equal or greater depth, the same solution will be found .map(gpsNode -> d >= gpsNode.getDepth()) // Solution not found? We explored the whole tree. Don't try with less depth, there will be no solution there either .orElseGet(() -> d <= depth)) .forEach(excludedDepths::add); } return result; } private void binarySearchBounds(int left, int right, List<Integer> result) { binarySearchBoundsRec(left, right, left, right, result); } /** * Recursively generate depths in binary search order (assuming the solution is never found, so all depths are * attempted) between the given floor and ceiling. * * @param left Current lower bound * @param right Current upper bound * @param floor Global lower bound * @param ceil Global upper bound * @param result Result where to add depths. */ private void binarySearchBoundsRec(int left, int right, int floor, int ceil, List<Integer> result) { if (left < floor || right > ceil || right < left) { return; } int middle = (left+right)/2; if (!result.contains(middle)) { result.add(middle); } binarySearchBoundsRec(left, middle-1, floor, ceil, result); binarySearchBoundsRec(middle+1, right, floor, ceil, result); } private void explode(GPSNode node) { Collection<GPSNode> newCandidates; double number; int index; switch (strategy) { case BFS: if (bestCosts.containsKey(node.getState())) {//TODO: add comparison of costs. return; } analizedStates++; newCandidates = new ArrayList<>(); addCandidates(node, newCandidates); newCandidates.forEach(gpsNode -> open.offer(gpsNode)); break; case DFS: if (bestCosts.containsKey(node.getState())) {//TODO: add comparison of costs. return; } analizedStates++; newCandidates = new ArrayList<>(); addCandidates(node, newCandidates); newCandidates.forEach(((Deque<GPSNode>) open)::addFirst); break; case IDDFS: if ((bestCosts.containsKey(node.getState()) && node.getCost() > bestCosts.get(node.getState())) || (bestCostsIddfsRun.containsKey(node.getState()) && node.getCost() >= bestCostsIddfsRun.get(node.getState()))) { return; } if (node.getDepth() >= iddfsDepth) { return; } analizedStates++; newCandidates = new ArrayList<>(); addCandidatesIddfs(node, newCandidates); depthReachedCurrentRun = Math.max( depthReachedCurrentRun, newCandidates.stream().map(GPSNode::getDepth).max(Comparator.naturalOrder()).orElse(depthReachedCurrentRun) ); newCandidates.forEach(((Deque<GPSNode>) open)::addFirst); break; case GREEDY: if (!isBest(node.getState(), node.getCost())) { return; } newCandidates = new ArrayList<>(); addCandidates(node, newCandidates); open.addAll(newCandidates); break; case ASTAR: if (!isBest(node.getState(), node.getCost())) { return; } newCandidates = new ArrayList<>(); addCandidates(node, newCandidates); open.addAll(newCandidates); break; } } /** * Resets exploration variables. Called when using {@link SearchStrategy#IDDFS} before restarting search with a new * depth. * * @param rootNode Root node to be added to {@link #open}. * @throws IllegalStateException If called when {@link #open} is not empty. */ private void iddfsReset(GPSNode rootNode) throws IllegalStateException { if (!open.isEmpty()) { throw new IllegalStateException("Attempted IDDFS reset when open was not empty"); } generatedStates.clear(); bestCostsIddfsRun.clear(); depthReachedCurrentRun = 0; open.add(rootNode); generatedStates.put(rootNode.getState(), 0); analizedStates = 0; } protected void addCandidates(GPSNode node, Collection<GPSNode> candidates) { int heursiticValue; explosionCounter++; updateBest(node); generatedStates.remove(node.getState()); for (Rule rule : problem.getRules()) { Optional<State> newState = rule.apply(node.getState()); if (newState.isPresent()) { int newCost = node.getCost() + rule.getCost(); State state = newState.get(); if ((!bestCosts.containsKey(state) && !generatedStates.containsKey(state)) || (bestCosts.containsKey(state) && newCost < bestCosts.get(state)) || (generatedStates.containsKey(state) && newCost < generatedStates.get(state))) { GPSNode newNode; if (strategy == SearchStrategy.GREEDY || strategy == SearchStrategy.ASTAR) { heursiticValue = heuristic.get().getValue(state); newNode = new GPSNode(state, newCost, rule, heursiticValue); } else { newNode = new GPSNode(state, newCost, rule); } generatedStates.put(newState.get(), newCost); newNode.setParent(node); candidates.add(newNode); } } } } /** * Same as {@link #addCandidates(GPSNode, Collection)} but for IDDFS. Slight but crucial differences. */ protected void addCandidatesIddfs(GPSNode node, Collection<GPSNode> candidates) { explosionCounter++; updateBest(node); bestCostsIddfsRun.put(node.getState(), node.getCost()); generatedStates.remove(node.getState()); for (Rule rule : problem.getRules()) { Optional<State> newState = rule.apply(node.getState()); if (newState.isPresent()) { int newCost = node.getCost() + rule.getCost(); State state = newState.get(); if ((!bestCosts.containsKey(state) && !generatedStates.containsKey(state)) || (bestCosts.containsKey(state) && newCost <= bestCosts.get(state)) || (generatedStates.containsKey(state) && newCost <= generatedStates.get(state))) { GPSNode newNode = new GPSNode(state, newCost, rule); generatedStates.put(newState.get(), newCost); newNode.setParent(node); candidates.add(newNode); } } } } private boolean isBest(State state, Integer cost) { if(!bestCosts.containsKey(state)) { analizedStates++; return true; } return cost < bestCosts.get(state); } private void updateBest(GPSNode node) { bestCosts.put(node.getState(), node.getCost()); } /** * Sets {@link #solutionNode} to the specified node and sets {@link #finished} to true. * * @param solutionNode Solution node */ protected void setSolution(GPSNode solutionNode) { this.solutionNode = solutionNode; this.finished = true; } public void printSolution() { System.out.println(solutionNode.getSolution()); } // GETTERS FOR THE PEOPLE! public Queue<GPSNode> getOpen() { return open; } public Map<State, Integer> getBestCosts() { return bestCosts; } public Problem getProblem() { return problem; } public long getExplosionCounter() { return explosionCounter; } public boolean isFinished() { return finished; } public boolean isFailed() { return failed; } public GPSNode getSolutionNode() { return solutionNode; } public SearchStrategy getStrategy() { return strategy; } public long getAnalizedStates() { return analizedStates; } public long getBorderNodes() { return borderNodes; } }
/* eslint-disable @typescript-eslint/no-unsafe-member-access */ import { findPath } from "common/findPath"; import { Log } from "./Log"; export class BaseCreep { public constructor(creep: Creep) { // } public checkIfFull(creep: Creep, resource: ResourceConstant): void { if (creep.memory.status === "fetchingResource") { if (creep.store[resource] === creep.store.getCapacity(resource)) { creep.memory.status = "working"; } } else if (creep.memory.status === "working") { if (creep.store[resource] === 0) { creep.memory.status = "fetchingResource"; } } } public moveHome(creep: Creep): void { if (creep.memory.status === "working" || creep.memory.status === "fetchingResource") { if (creep.pos.roomName !== creep.memory.room) { creep.memory.status = "movingIntoRoom"; } } if (creep.memory.status === "movingIntoRoom") { if (creep.pos.roomName === creep.memory.room) { creep.memory.status = "working"; } else { const safeRouteHome = findPath.findSafePathToRoom(creep.pos.roomName, creep.memory.room); if (safeRouteHome !== -2) { this.moveCreep(creep, new RoomPosition(25, 25, safeRouteHome[0].room)); } else { Log.Warning(`${creep.memory.jobType} creep with UUID ${creep.name} returned ${safeRouteHome}`); } } } } public moveCreep(creep: Creep, destination: RoomPosition): ScreepsReturnCode { const moveResult = creep.moveTo(destination, { visualizePathStyle: { fill: "transparent", stroke: "#efefef", lineStyle: "dashed", strokeWidth: 0.15, opacity: 0.6 } }); return moveResult; } public harvestSource(creep: Creep, source: Source): ScreepsReturnCode { const harvestResult = creep.harvest(source); if (harvestResult === ERR_NOT_IN_RANGE) { const moveResult = this.moveCreep(creep, source.pos); return moveResult; } else { return harvestResult; } } public pickupResource(creep: Creep, origin: Resource<ResourceConstant>): ScreepsReturnCode { const pickupResult = creep.pickup(origin); if (pickupResult === ERR_NOT_IN_RANGE) { const moveResult = this.moveCreep(creep, origin.pos); return moveResult; } else return pickupResult; } public withdrawResource( creep: Creep, origin: StructureStorage | StructureContainer | StructureLink, resource: ResourceConstant ): ScreepsReturnCode { const withdrawResult = creep.withdraw(origin, resource); if (withdrawResult === ERR_NOT_IN_RANGE) { const moveResult = this.moveCreep(creep, origin.pos); return moveResult; } else return withdrawResult; } public fetchSource(creep: Creep, forceStorage = false): void { const linkDistances: { [key: Id<StructureLink>]: number } = {}; let sortedLinkDistances: [string, number][] = []; let storageUsable = false; let linksUsable = false; let useStorage = false; let useLinks = false; if (forceStorage) { useStorage = true; } else { if (creep.room.memory.monitoring.structures.links) { if ( Object.entries(creep.room.memory.monitoring.structures.links).filter( ([, cachedLink]) => cachedLink.mode === "rx" && cachedLink.energy.energyAvailable > 0 ).length > 0 ) { linksUsable = true; } } if (creep.room.memory.monitoring.structures.storage) { if (creep.room.memory.monitoring.structures.storage.resources[RESOURCE_ENERGY]) { if ( creep.room.memory.monitoring.structures.storage.resources[RESOURCE_ENERGY].resourceAmount >= creep.store.getFreeCapacity(RESOURCE_ENERGY) ) { storageUsable = true; } } } } if (storageUsable || linksUsable) { if (!linksUsable) { useStorage = true; } else { if (!storageUsable) { useLinks = true; } else { Object.entries(creep.room.memory.monitoring.structures.links) .filter(([, cachedLink]) => cachedLink.mode === "rx" && cachedLink.energy.energyAvailable > 0) .forEach(([cachedLinkIdString]) => { const cachedLinkId = cachedLinkIdString as Id<StructureLink>; const cachedLink = Game.getObjectById(cachedLinkId); if (cachedLink) { linkDistances[cachedLinkId] = creep.pos.getRangeTo(cachedLink); } }); if (Object.entries(linkDistances).length > 0) { sortedLinkDistances = Object.entries(linkDistances).sort( ([, linkDistanceA], [, linkDistanceB]) => linkDistanceA - linkDistanceB ); if (sortedLinkDistances[0]) { if (creep.room.storage) { const storageDistance = creep.pos.getRangeTo(creep.room.storage.pos); if (storageDistance <= sortedLinkDistances[0][1]) { useStorage = true; } else { useLinks = true; } } } } } } } if (useLinks === true) { if (Object.entries(sortedLinkDistances)[0]) { const linkId = sortedLinkDistances[0][0] as Id<StructureLink>; const link = Game.getObjectById(linkId); if (link) { this.withdrawResource(creep, link, RESOURCE_ENERGY); } } } else { if (useStorage === true) { if (creep.room.memory.monitoring.structures.storage) { const storageId = creep.room.memory.monitoring.structures.storage.id; const storage = Game.getObjectById(storageId); if (storage) { this.withdrawResource(creep, storage, RESOURCE_ENERGY); } } } else { const droppedResourceArray: Resource<ResourceConstant>[] = []; Object.entries(creep.room.memory.monitoring.droppedResources) .filter(DroppedResource => DroppedResource[1].resourceType === RESOURCE_ENERGY) .forEach(([droppedResourceId]) => { const droppedResource = Game.getObjectById(droppedResourceId as Id<Resource<ResourceConstant>>); if (droppedResource) { droppedResourceArray.push(droppedResource); } }); if (droppedResourceArray.length > 0) { const closestDroppedEnergy = creep.pos.findClosestByPath(droppedResourceArray); if (closestDroppedEnergy) { this.pickupResource(creep, closestDroppedEnergy); } } } } } public depositResource( creep: Creep, destination: Structure<StructureConstant> | AnyCreep, resource: ResourceConstant ): ScreepsReturnCode { const depositResult = creep.transfer(destination, resource); if (depositResult === ERR_NOT_IN_RANGE) { const moveResult = this.moveCreep(creep, destination.pos); return moveResult; } else return depositResult; } }
package com.bitstudy.app.domain; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; public class UserDto { private Integer user_no; private String user_id; private String user_pw; private String user_name; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date user_birth; private String user_call; private String user_email; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date user_joindate; private int user_state; public UserDto() { } public UserDto(Integer user_no, String user_id, String user_pw, String user_name, Date user_birth, String user_call, String user_email, Date user_joindate) { this.user_no = user_no; this.user_id = user_id; this.user_pw = user_pw; this.user_name = user_name; this.user_birth = user_birth; this.user_call = user_call; this.user_email = user_email; this.user_joindate = user_joindate; } public Integer getUser_no() { return user_no; } public void setUser_no(Integer user_no) { this.user_no = user_no; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getUser_pw() { return user_pw; } public void setUser_pw(String user_pw) { this.user_pw = user_pw; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public Date getUser_birth() { return user_birth; } public void setUser_birth(Date user_birth) { this.user_birth = user_birth; } public String getUser_call() { return user_call; } public void setUser_call(String user_call) { this.user_call = user_call; } public String getUser_email() { return user_email; } public void setUser_email(String user_email) { this.user_email = user_email; } public Date getUser_joindate() { return user_joindate; } public void setUser_joindate(Date user_joindate) { this.user_joindate = user_joindate; } public int getUser_state() { return user_state; } public void setUser_state(int user_state) { this.user_state = user_state; } @Override public String toString() { return "UserDto{" + "user_no=" + user_no + ", user_id='" + user_id + '\'' + ", user_pw='" + user_pw + '\'' + ", user_name='" + user_name + '\'' + ", user_birth=" + user_birth + ", user_call='" + user_call + '\'' + ", user_email='" + user_email + '\'' + ", user_joindate=" + user_joindate + ", user_state=" + user_state + '}'; } }
import { DateTime } from 'luxon' import { BaseModel, BelongsTo, HasMany, HasOne, beforeSave, belongsTo, column, hasMany, hasOne, } from '@ioc:Adonis/Lucid/Orm' import Post from './Post' import Profile from './Profile' import Role from './Role' import Hash from '@ioc:Adonis/Core/Hash' export default class User extends BaseModel { @column({ isPrimary: true }) public id: number @column() public email: string @column() public username: string @column({ serializeAs: null }) public password: string @column() public remenber_me_token: string | null @column() public rolesId: string @column.dateTime({ autoCreate: true }) public createdAt: DateTime @column.dateTime({ autoCreate: true, autoUpdate: true }) public updatedAt: DateTime @hasMany(() => Post) public posts: HasMany<typeof Post> @hasOne(() => Profile) public profile: HasOne<typeof Profile> @belongsTo(() => Role) public role: BelongsTo<typeof Role> @beforeSave() public static async hashPassword(user: User) { if (user.$dirty.password) { user.password = await Hash.make(user.password) } } }
const MAX_WEIGHT = 20.0 const MATRÍCULA = "2020041973" function read_weights(file::IOStream, size::Int64)::Vector{Float64} weights::Vector{Float64} = zeros(size) for line in eachline(file) data = split(line, "\t") weights[parse(Int64, data[2])+1] = parse(Float64, data[3]) end return weights end function main() if length(ARGS) == 0 return end input_file::IOStream = open(ARGS[1], "r") num_objects::Int64 = parse(Int64, split(readline(input_file), "\t")[2]) weights::Vector{Float64} = read_weights(input_file, num_objects) capacities::Vector{Float64} = fill(MAX_WEIGHT, size(weights)) bins_content::Vector{Vector{Int64}} = Vector{Vector{Int64}}(undef, 0) sort!(weights, rev=true) for (i, w) in enumerate(weights) added_to_existing_bin = false for (j, c) in enumerate(capacities) if c - w >= 0 capacities[j] = c - w if isempty(bins_content) || length(bins_content) < j push!(bins_content, [i]) else push!(bins_content[j], i) end added_to_existing_bin = true break end end if !added_to_existing_bin push!(bins_content, [i]) end end num_bins::Int64 = length(bins_content) println("TP2 $MATRÍCULA = $num_bins") for (_, bin_content) in enumerate(bins_content) for b in bin_content print("$b\t") end println() end end main()
import { useEffect, useRef, useState } from 'react'; import { Dimensions, SafeAreaView, StyleSheet } from 'react-native'; import Video, { OnBufferData, OnLoadData, OnProgressData, VideoProperties, } from 'react-native-video'; import { ActivityIndicator } from '@lib/ui/components/ActivityIndicator'; import { Col } from '@lib/ui/components/Col'; import { useStylesheet } from '@lib/ui/hooks/useStylesheet'; import { useNavigation } from '@react-navigation/native'; import { throttle } from 'lodash'; import { negate } from '../../utils/predicates'; import { displayTabBar } from '../../utils/tab-bar'; import { useFullscreenUi } from '../hooks/useFullscreenUi'; import { VideoControls } from './VideoControls'; const playbackRates = [1, 1.5, 2, 2.5]; /** * Wraps react-native-video with custom controls for Android * * In order for fullscreen to work correctly, this component's parent should * have a minHeight=100% of the available window height */ export const VideoPlayer = (props: VideoProperties) => { const { width, height } = Dimensions.get('screen'); const styles = useStylesheet(createStyles); const navigation = useNavigation(); const playerRef = useRef<Video>(null); const [paused, setPaused] = useState(false); const [fullscreen, setFullscreen] = useState(false); const [duration, setDuration] = useState(0); const [ready, setReady] = useState(false); const [buffering, setBuffering] = useState(false); const [progress, setProgress] = useState(0); const [playbackRate, setPlaybackRate] = useState(1); useFullscreenUi(fullscreen); const handleLoad = (meta: OnLoadData) => { setDuration(meta.duration); }; useEffect(() => { const navRoot = navigation.getParent()!; return () => displayTabBar(navRoot); }, [navigation]); const togglePlaybackRate = () => { const actualRateIndex = playbackRates.findIndex( rate => rate === playbackRate, ); const newIndex = (actualRateIndex + 1) % 4; setPlaybackRate(playbackRates[newIndex]); }; const onProgressChange = throttle((newProgress: number) => { try { const newSeekValue = newProgress * duration; if (playerRef && playerRef.current) { playerRef.current.seek(newSeekValue); } setProgress(newProgress); } catch (e) { console.debug('Cannot seek video', e); } }, 200); const handleProgress = (videoProgress: OnProgressData) => { const p = videoProgress.currentTime / duration; if (p === Infinity || isNaN(p)) { return; } setProgress(p); }; // noinspection JSSuspiciousNameCombination return ( <SafeAreaView style={[ styles.container, fullscreen && { position: 'absolute', width, height, zIndex: 1, }, ]} > <Video ref={playerRef} controls={false} paused={paused} style={[ { width: '100%', minHeight: (width / 16) * 9, }, fullscreen && styles.fullHeight, ]} rate={playbackRate} resizeMode="contain" onLoad={handleLoad} onReadyForDisplay={() => setReady(true)} onProgress={handleProgress} onEnd={() => { setPaused(true); onProgressChange(0); }} onBuffer={(data: OnBufferData) => setBuffering(data.isBuffering)} fullscreen={fullscreen} onFullscreenPlayerDidPresent={() => setFullscreen(true)} onFullscreenPlayerDidDismiss={() => setFullscreen(false)} {...props} /> {ready ? ( <VideoControls buffering={buffering} fullscreen={fullscreen} toggleFullscreen={() => { if (fullscreen) { playerRef.current?.dismissFullscreenPlayer(); } else { playerRef.current?.presentFullscreenPlayer(); } setFullscreen(negate); }} progress={progress} onProgressChange={onProgressChange} paused={paused} togglePaused={(_paused?: boolean) => setPaused(old => (_paused === undefined ? !old : _paused)) } duration={duration} playbackRate={playbackRate} setPlaybackRate={togglePlaybackRate} /> ) : ( <Col align="center" justify="center" style={StyleSheet.absoluteFill}> <ActivityIndicator size="large" /> </Col> )} </SafeAreaView> ); }; const createStyles = () => StyleSheet.create({ // eslint-disable-next-line react-native/no-color-literals container: { backgroundColor: 'black', }, fullHeight: { height: '100%', }, });
import axios from 'axios'; const BASE_URL = 'https://pixabay.com/api/'; const searchParams = new URLSearchParams({ key: '34443697-d9f859220b94cfe4401518737', image_type: 'photo', orientation: 'horizontal', safesearch: 'true', per_page: 40, }); export default class ImgApiSrv { constructor() { this.SearchQuery = ''; this.page = 1; } async getImages() { try { const response = await axios.get( `${BASE_URL}?${searchParams}&q=${this.SearchQuery}&page=${this.page}` ); this.page += 1; return response; } catch (error) { console.log(error); } } resetPage() { this.page = 1; } get query() { return this.SearchQuery; } set query(newSearchQueary) { return (this.SearchQuery = newSearchQueary); } }
//cách để import PrismaClient từ gói @prisma/client. PrismaClient là một class được cung cấp bởi Prisma để tương tác với cơ sở dữ liệu. import {PrismaClient} from "@prisma/client" //Dòng declare global và khối code liền sau đó: Đoạn code này được sử dụng để khai báo một biến toàn cục prisma. //Việc khai báo biến này giúp chúng ta có thể truy cập vào PrismaClient từ bất kỳ đâu trong ứng dụng của mình. declare global { var prisma : PrismaClient | undefined } //Đây là cách tạo một phiên bản của PrismaClient. Nếu biến prisma đã được định nghĩa (thường là trong môi trường development), //chúng ta sử dụng phiên bản đó. Nếu không, chúng ta tạo một phiên bản mới của PrismaClient. const prismadb = globalThis.prisma || new PrismaClient(); //iểm tra xem chúng ta đang ở môi trường phát triển hay không. Nếu là môi trường phát triển, //chúng ta gán biến prisma là prismadb, cho phép chúng ta truy cập vào PrismaClient từ bất kỳ đâu trong ứng dụng. if(process.env.NODE_ENV !== 'production') globalThis.prisma = prismadb; export default prismadb
<!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>Mehedy Shop</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/all.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet"> </head> <body class="container"> <header> <section style="position:-webkit-sticky; position:sticky; top: 0; background-color: rgb(245, 187, 187);" class="row"> <div class="col-6 d-flex align-items-center"> <i><a href="" style="text-decoration:none"><i class="fas fa-store"></i> Mehedy Shops</a></i> </div> <div class="col-6"> <nav class="navbar text-end navbar-expand-lg navbar-light"> <div class="container-fluid"> <a class="navbar-brand" href="#"></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link active" aria-current="page" href="#">Home</a> <a class="nav-link" href="#porductg">Product</a> <a class="nav-link" href="#about">About us</a> <a class="nav-link" href="#contact">Contact us</a> </div> </div> </div> </nav> </div> </section> <div class="row pt-5 pb-5"> <div class="col-md-6 d-flex align-items-center"> <div> <h1>BE THE PENGUINS OF WINTER</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vero, recusandae.</p> <button class="btn btn-success"><i class="fas fa-shopping-cart"></i> BYE NOW</button> </div> </div> <div class="col-md-6"> <img class="w-100" src="./images/mehedy.png" alt=""> </div> </div> </header> <main> <section class="pt-2 mt-5" id="porductg"> <h2>WOMAN JACKET</h2> <div class="row row-cols-1 row-cols-md-3 g-4 text-info"> <div class="col"> <div class="card h-100 card-div-shadow"> <img src="./images/girl-1.png" class="card-img-top p-5 w-100 h-75 " alt="..."> <div class="card-body"> <h4 class="card-title"><b>Woman Leather Jacket</b></h4> <p class="card-text text-secondary">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dicta, tenetur.</p> </div> <div class="card-footer border-0 m-1 bg-white row"> <h2 class="col-6"><b>$ 234</b></h2> <button class="btn btn-success col-6"><i class="fas fa-shopping-cart"></i> BYE NOW</button> </div> </div> </div> <div class="col"> <div class="card h-100 card-div-shadow"> <img src="./images/girl-2.png" class="card-img-top p-5 w-100 h-75 " alt="..."> <div class="card-body"> <h4 class="card-title"><b>Woman Leather Jacket</b></h4> <p class="card-text text-secondary">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dicta, tenetur.</p> </div> <div class="card-footer border-0 m-1 bg-white row"> <h2 class="col-6"><b>$ 234</b></h2> <button class="btn btn-success col-6"><i class="fas fa-shopping-cart"></i> BYE NOW</button> </div> </div> </div> <div class="col"> <div class="card h-100 card-div-shadow"> <img src="./images/girl-3.png" class="card-img-top p-5 w-100 h-75 " alt="..."> <div class="card-body"> <h4 class="card-title"><b>Woman Leather Jacket</b></h4> <p class="card-text text-secondary">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dicta, tenetur.</p> </div> <div class="card-footer border-0 m-1 bg-white row"> <h2 class="col-6"><b>$ 234</b></h2> <button class="btn btn-success col-6"><i class="fas fa-shopping-cart"></i> BYE NOW</button> </div> </div> </div> </div> </section> <section class="pt-2 mt-5 mb-5"> <h2>MAN JACKET</h2> <div class="row row-cols-1 row-cols-md-3 g-4 text-info"> <div class="col"> <div class="card h-100 card-div-shadow"> <img src="./images/boy-1.png" class="card-img-top p-5 w-100 h-75 " alt="..."> <div class="card-body"> <h4 class="card-title"><b>Snowboard Jacket Mens</b></h4> <p class="card-text text-secondary">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dicta, tenetur.</p> </div> <div class="card-footer border-0 m-1 bg-white row"> <h2 class="col-6"><b>$ 234</b></h2> <button class="btn btn-success col-6"><i class="fas fa-shopping-cart"></i> BYE NOW</button> </div> </div> </div> <div class="col"> <div class="card h-100 card-div-shadow"> <img src="./images/boy-3.png" class="card-img-top p-5 w-100 h-75 " alt="..."> <div class="card-body"> <h4 class="card-title"><b>Man Leather Jackets</b></h4> <p class="card-text text-secondary">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dicta, tenetur.</p> </div> <div class="card-footer border-0 m-1 bg-white row"> <h2 class="col-6"><b>$ 234</b></h2> <button class="btn btn-success col-6"><i class="fas fa-shopping-cart"></i> BYE NOW</button> </div> </div> </div> <div class="col"> <div class="card h-100 card-div-shadow"> <img src="./images/boy-2.png" class="card-img-top p-5 w-100 h-75 " alt="..."> <div class="card-body"> <h4 class="card-title"><b>Man Casual Jackets</b></h4> <p class="card-text text-secondary">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dicta, tenetur.</p> </div> <div class="card-footer border-0 m-1 bg-white row"> <h2 class="col-6"><b>$ 234</b></h2> <button class="btn btn-success col-6"><i class="fas fa-shopping-cart"></i> BYE NOW</button> </div> </div> </div> </div> </section> <div class="row mt-5 mb-5 flex-md-row-reverse" id="about"> <div class="col-md-7 p-3 d-flex align-items-center justify-content-center"> <img src="./icon/shops.png" class="w-100" alt=""> </div> <div class="col-md-5 p-3"> <div class="last-div-shadow row text-center text-md-start p-3 mt-3 mb-3"> <div class="col-md-3 d-flex align-items-center justify-content-center"> <img src="./icon/icon-1.png" style="width: 70px;" alt=""> </div> <div class="col-md-9"> <h4><b>Find the Perfect Fit</b></h4> <p>Everybody is different, which is why we offer styles for every body.</p> </div> </div> <div class="last-div-shadow row text-center text-md-start p-3 mt-3 mb-3"> <div class="col-md-3 d-flex align-items-center justify-content-center"> <img src="./icon/icon-2.png" style="width: 70px;" alt=""> </div> <div class="col-md-9"> <h4><b>Free Exchanges</b></h4> <p>One of the many reasons you can shop with peace of mind.</p> </div> </div> <div class="last-div-shadow row text-center text-md-start p-3 mt-3 mb-3"> <div class="col-md-3 d-flex align-items-center justify-content-center"> <img src="./icon/icon-3.png" style="width: 70px;" alt=""> </div> <div class="col-md-9"> <h4><b>Contact Our Seller</b></h4> <p>They are here to help you. That s quite literally what we pay them for.</p> </div> </div> </div> </div> </main> <footer> <div class="p-5 d-flex align-items-center justify-content-center" style="background-color: rgb(238, 194, 242); border-radius: 20px;"> <div> <h2>LET'S STAY IN TOUCH</h2> <h5>Get updates on sales, specials and more</h5> <input class="w-50" type="text"> <button class="btn btn-primary">SUBMIT</button> </div> </div> <div class="text-center pt-4"> <small>@2021. Mehedy shop</small> </div> </footer> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>
import React, { useState } from 'react'; import { Link, useHistory } from 'react-router-dom'; import { FiLogIn } from 'react-icons/fi'; import './styles.css'; import '../../services/api'; import heroesImg from '../../assets/heroes.png'; import logoImg from '../../assets/logo.svg'; import api from '../../services/api'; export default function Logon() { const [id, setId] = useState(''); const history = useHistory(); async function handleLogin(e) { e.preventDefault(); try{ const response = await api.post('sessions', { id }); // Salvar esse dado para toda a aplicação pois é o usuário logado localStorage.setItem('ongId', id); localStorage.setItem('ongName', response.data.name); // redireciona a rota profile history.push('/profile'); } catch (err) { alert('Falha no Login, tente novamente'); } } return ( <div className="logon-container"> <section className="form"> <img src={ logoImg } alt="Be The Hero" /> <form onSubmit={ handleLogin }> <h1>Faça seu Logon</h1> <input placeholder="Sua ID" value={id} onChange={e => setId(e.target.value)} /> <button className="button" type="submit">Entrar</button> <Link className="back-link" to="/register"> <FiLogIn size={16} color="#e02041" /> Não tenho Cadastro </Link> </form> </section> <img src={ heroesImg } alt="Heroes" /> </div> ); }
import math # used for sqrt class Obj: def __init__(self, name, x=0, y=0): """ An Object, also called point :param name: String, either "Rock", "Paper", or "Scissors" :param x: the x center of the point :param y: the y center of the point """ self.name = name self.x = x self.y = y self.a = [0, 0] # acceleration vector self.v = [0, 0] # velocity vector def __repr__(self): return f"name: {self.name}, x:{self.x}, y:{self.y}, v:{self.v}, a:{self.a};" def move(self, eat): """ Makes the Object decide its next move by setting acceleration values. :param eat: list of other Objects that self can eat :return: Nothing """ # Constants SCREENSIZE = 800 FPS = 150 MAXV = 180 # Maximum velocity AMULT = 10 # Multiplier for acceleration DIST2KILL = 3 # Distance to which other Objects have to be to be "killed" tick = 1 / FPS # tick time target = self.nearest(eat) """ Here follows a bunch of math to understand how I calculated the two acceleration components. I wanted them to be in such a way that the resultant sum vector was of length one. Hence sqrt(ax^2 + ay^2) = 1. Calculations follow: sqrt(ax^2 + ay^2) = 1 and ax/dx = ay/dy so ay = axdy/dx so sqrt(ax^2+(axdy/dx)^2) = 1 take sqrt off (square both sides) ax**2 + ax^2*dy^2/dx^2 = 1 ax**2(1+dy^2/dx^2) = 1 ax**2 = 1/(1+dy^2/dx^2) ax = sqrt(1/(1+dy^2/dx^2) ay = axdy/dx for brevity and clarity sake, let t = dy/dx and let k = t^2 """ try: # see except to understand why t = (target.y - self.y) / (target.x - self.x) k = t ** 2 self.a[0] = math.sqrt(1 / (1 + k)) self.a[1] = self.a[0] * t self.a[0] *= AMULT if self.x < target.x else -AMULT self.a[1] *= AMULT if self.y < target.y else -AMULT # update velocity self.v[0] += self.a[0] self.v[1] += self.a[1] if self.v[0] > MAXV: self.v[0] = MAXV if self.v[1] > MAXV: self.v[1] = MAXV if self.v[0] < -MAXV: self.v[0] = -MAXV if self.v[1] < -MAXV: self.v[1] = -MAXV # update position self.x += self.v[0] * tick self.y += self.v[1] * tick if not SCREENSIZE > self.x > 0: self.v[0] *= -1 if not SCREENSIZE > self.y > 0: self.v[1] *= -1 except ZeroDivisionError: # this happens if target.x == self.x. In that case, don't accelerate the Object pass # if nearest prey is touched, transform it into an ally if -DIST2KILL < self.x - target.x < DIST2KILL and -DIST2KILL < self.y - target.y < DIST2KILL: target.name = self.name def nearest(self, eatlist: list): """ Returns the nearest object in eatlist from self :param eatlist: list of Obj's :return: Obj """ # Constant SCREENSIZE = 800 x = self.x y = self.y def calcDistance(other: Obj): # helper dist = math.sqrt((x - other.x) ** 2 + (y - other.y) ** 2) return dist res = [] for d in eatlist: res.append(calcDistance(d)) # get index of the nearest item try: i = res.index(min(res)) return eatlist[i] except ValueError as e: # eatlist is empty, make the Object go to the center return Obj("", SCREENSIZE//2, SCREENSIZE//2)
USE investigacion; -- ESTUDIANTE, PROFESOR Y EMPLEADO CREATE INDEX index_est_correo ON estudiante(est_correo); CREATE INDEX index_est_cedula ON estudiante(est_cedula); CREATE INDEX index_pro_correo ON profesor(pro_correo); CREATE INDEX index_pro_cedula ON profesor(pro_cedula); CREATE INDEX index_emp_correo ON empleado(emp_correo); CREATE INDEX index_emp_cedula ON empleado(emp_cedula); /*Para estas tres tablas se consideran los indices sobre la cédula y el correo, ya que para muchas de las consultas se requiere la cedula o id de estas tablas, y un índice mejoraría el tiempo de respuesta. Además sobre la columna correo, ya que pensando en la implementación de la interfaz, será necesario que estos usuarios se registren y hagan log in, y para esto será necesario hacer consultas a esta columna en especifico.*/ -- GRUPO CREATE INDEX index_gru_numProyectos ON grupo_investigacion(gru_numProyectos); CREATE INDEX index_gru_numPapers ON grupo_investigacion(gru_numPapers); CREATE INDEX index_gru_area ON grupo_investigacion(gru_area); /* Para la tabla de grupo de investigación se consideran estos tres índices: sobre la columna de número de proyectos, ya que es una columna sobre la cual se pueden hacer una buena cantidad de consultas interesantes y actualizaciones, al igual que el número de papers. Por otro lado, para la columna de área se considera un índice, ya que puede ser útil para consultas en las que se quiera saber el área de algun grupo de investigación.*/ -- PROYECTO CREATE INDEX index_pry_estado ON proyecto(pry_estado); CREATE INDEX index_pry_id ON proyecto(pry_id); /*Para la tabla de proyectos se considera un índice sobre la columna id, ya que muchas consultas y join se realizan con este atributo, y sobre la columna estado, ya que en el modelo es relevante saber si un proyecto se encuentra activo. principalemte para las consultas */ -- PAPER CREATE INDEX index_pap_tema ON paper(pap_tema); CREATE INDEX index_pap_id ON paper(pap_id); /*Para la tabla paper se considerán índices sobre las columnas id y tema, id ya que se hacen joins y consultas sobre este atributo, y el tema, ya que es una columna de interés para las consultas, y por ello un índice facilitaría el tiempo que se tarda en acceder a la columna */ -- EDITORIAL CREATE INDEX index_edi_numPapers ON editorial(edi_numPapers); /*Para la tabla editorial se considera un índice sobre la columa del número de papers, ya que en las consultas que se plantean, este es un atributo bastante usado y por lo tanto un índice podría mejorar su rendimiento*/ -- DEPARTAMENTO CREATE INDEX index_dep_numGrupos ON departamento(dep_numGrupos); /*Para la tabla departamento se considera un índice sobre la columna del número de grupos, ya que con respecto al modulo de investigación, es el atributo con el que más se harían consultas.*/ -- LABORATORIO CREATE INDEX index_lab_id ON laboratorio(lab_id); /*Para la tabla de laboratorio se considera un índice sobre la columna de id, ya que se usa bastante para hacer joins y consultas*/
"use client"; import { Copy, ServerIcon } from "lucide-react"; import { Alert, AlertDescription, AlertTitle } from "./alert"; import { Badge, BadgeProps } from "./badge"; import { Button } from "./button"; import { toast } from "react-hot-toast"; interface ApiAlertProps{ title: string; description: string; variant : "public" | "admin" }; const textMap: Record<ApiAlertProps["variant"], string> = { public : "Public", admin : "Admin" } const variantMap: Record<ApiAlertProps["variant"], BadgeProps['variant']> = { public : "secondary", admin : "destructive" } export const ApiAlert: React.FC<ApiAlertProps> = ({ title, description, variant }) => { const onCopy = () => { navigator.clipboard.writeText(description); toast.success("API route copied to clipboard") } return ( <Alert> <ServerIcon className="h-4 w-4" /> <AlertTitle className="flex items-center gap-x-2"> {title} <Badge variant={variantMap[variant]}> {textMap[variant]} </Badge> </AlertTitle> <AlertDescription className="mt-4 flex items-center justify-between"> <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold"> {description} </code> <Button size="icon" variant="outline" onClick={() => onCopy()}> <Copy className="h-4 w-4"/> </Button> </AlertDescription> </Alert> ) }
from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save # Create your models here. class CustomUser(AbstractUser): username = models.CharField(max_length=150, unique=True) def profile(self): profile = Profile.objects.get(user=self) class Meta: verbose_name_plural = "User" class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) full_name = models.CharField(max_length=1000, null=True, blank=True) bio = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(upload_to='user_images', default='default.jpg') verified = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.full_name == "" or self.full_name == None: self.full_name = self.user.username super(Profile, self).save(*args, **kwargs) def __str__(self) -> str: return f'{self.full_name}' def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) def save_user_profile(sender, instance, **kwargs): instance.profile.save() post_save.connect(create_user_profile, sender=CustomUser) post_save.connect(save_user_profile, sender=CustomUser) class Message(models.Model): content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) sender = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='sender') receiver = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='receiver') is_read = models.BooleanField(default=False) class Meta: ordering = ['created_at'] def __str__(self) -> str: return f'From: {self.sender.username} - To: {self.receiver.username} - {self.created_at}' @property def sender_profile(self): sender_profile = Profile.objects.get(user=self.sender) return sender_profile @property def receiver_profile(self): receiver_profile = Profile.objects.get(user=self.receiver) return receiver_profile
import { strict as assert } from 'assert'; /** 要組合的對象 */ export interface Item { /** 種類,不得重複 */ type: string; /** 數量,需為正整數 */ amount: number; } /** * 列出所有組合 * @param items 要撿的東西 * @param pick 要挑幾個 */ function combination<T extends Item = Item>( items: Array<T>, pick: number, ): Array<Array<T>> { const typeList: string[] = []; const list: Array<Array<T>> = []; for (const item of items) { for (let i = 0; i < item.amount; i++) { typeList.push(item.type); } } const backtrack = ( list: Array<Array<T>>, childList: string[], start: number, ) => { if (childList.length === pick) { const item = []; childList.forEach((child) => { const lastItem = item[item.length - 1]; if (lastItem && lastItem.type === child) { lastItem.amount++; } else { item.push({ type: child, amount: 1 }); } }); list.push(item); } for (let i = start; i < typeList.length; i++) { if (i > start && typeList[i] === typeList[i - 1]) continue; childList.push(typeList[i]); backtrack(list, childList, i + 1); childList.pop(); } }; backtrack(list, [], 0); return list; } let result = combination( [ { type: 'Apple', amount: 2 }, { type: 'Banana', amount: 3 }, { type: 'Cat', amount: 2 }, { type: 'Dog', amount: 4 }, { type: 'Egg', amount: 1 }, ], 12, ); assert(result.length === 1); result = combination( [ { type: 'Apple', amount: 2 }, { type: 'Banana', amount: 3 }, { type: 'Cat', amount: 2 }, { type: 'Dog', amount: 4 }, { type: 'Egg', amount: 1 }, ], 7, ); result.forEach((ans) => { const sum = ans.reduce((prev, curr) => { return prev + curr.amount; }, 0); assert(sum === 7); }); result = combination( [ { type: 'Apple', amount: 2 }, { type: 'Banana', amount: 3 }, { type: 'Cat', amount: 2 }, { type: 'Dog', amount: 4 }, { type: 'Egg', amount: 1 }, ], 13, ); assert(result.length === 0); result = combination( [ { type: 'Apple', amount: 1 }, { type: 'Banana', amount: 2 }, { type: 'Cat', amount: 3 }, ], 2, ); /** A1B1 A1C1 B1C1 B2 C2 */ assert(result.length === 5);
#include <netinet/in.h> // sockaddr_in; INADDR_ANY #include <stdio.h> // printf #include <sys/socket.h> // socket, bind, listen, accept, AF_INET, SOCK_STREM #include <sys/types.h> // htonl, htons, socklen_t #include <unistd.h> // read, write, close // This is used to pre-allocate the char array size // For our use case, we will accept that it's not possible to read messages // larger then this #define MAX_MESSAGE_SIZE 256 int main(void) { // Initialize the details of the server socket struct sockaddr_in server_sockaddr_in; // Define socket family AF_INET = internetwork: URD, TCP, etc. server_sockaddr_in.sin_family = AF_INET; // https://linux.die.net/man/3/htonl // The htonl() function converts the unsigned integer hostlong from host byte // order to network byte order. server_sockaddr_in.sin_addr.s_addr = htonl(INADDR_ANY); // Defines the port we want to open this socket on const int port = 3000; // The htons() function converts the unsigned short integer hostshort from // host byte order to network byte order. server_sockaddr_in.sin_port = htons(port); // https://man7.org/linux/man-pages/man2/socket.2.html // creates an endpoint for communication and returns a file descriptor that // refers to that endpoint SOCK_STREM defines that this should communicate // over TCP int socket_file_descriptor = socket(AF_INET, SOCK_STREAM, 0); // https://man7.org/linux/man-pages/man2/bind.2.html // bind() assigns the address specified by server_sockaddr_in to the socket // socket_file_descriptor bind(socket_file_descriptor, (struct sockaddr *)&server_sockaddr_in, sizeof(server_sockaddr_in)); // https://man7.org/linux/man-pages/man2/listen.2.html // listen() marks the socket referred to by sockfd as a passive socket // the second parameter (5) defines the maximum length to which the queue of // pending connections for socket_file_descriptor may grow listen(socket_file_descriptor, 5); struct sockaddr_in client_sockaddr_in; socklen_t len = sizeof(client_sockaddr_in); // https://man7.org/linux/man-pages/man2/accept4.2.html // accept() extracts the first connection request on the queue of pending // connections for the listening socket The address info from the client will // be stored in client_sockaddr_in int connection_file_descriptor = accept( socket_file_descriptor, (struct sockaddr *)&client_sockaddr_in, &len); char buffer[MAX_MESSAGE_SIZE] = {}; // https://man7.org/linux/man-pages/man2/read.2.html // read() attempts to read up to MAX_MESSAGE_SIZE bytes from file descriptor // connection_file_descriptor into buffer read(connection_file_descriptor, buffer, sizeof(buffer)); printf("%s", buffer); char status = 0; // https://man7.org/linux/man-pages/man2/write.2.html // write(fd, buf, count) writes up to count bytes from buffer starting at // the file descriptor fd In this case we simply send a single byte 0 to // indicate we have received the message write(connection_file_descriptor, &status, 1); // https://man7.org/linux/man-pages/man2/close.2.html // close() closes a file descriptor, so that it no loger refers to ant file // and may be reused close(socket_file_descriptor); return 0; }
package api import ( "bytes" "database/sql" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" "time" mockdb "github.com/Anderson-kariuki/simplebank/db/mock" db "github.com/Anderson-kariuki/simplebank/db/sqlc" "github.com/Anderson-kariuki/simplebank/token" "github.com/Anderson-kariuki/simplebank/util" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) func TestGetAccountAPI(t *testing.T) { user, _ := randomUser(t) account := randomAccount(user.Username) testCases := []struct { name string accountID int64 setupAuth func(t *testing.T, request *http.Request, tokenMaker token.Maker) buildStubs func(store *mockdb.MockStore) checkResponse func(t *testing.T, recorder *httptest.ResponseRecorder) }{ { name: "OK", accountID: account.ID, setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute) }, buildStubs: func(store *mockdb.MockStore) { store.EXPECT(). GetAccount(gomock.Any(), gomock.Eq(account.ID)). Times(1). Return(account, nil) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusOK, recorder.Code) requireBodyMatchAccount(t, recorder.Body, account) }, }, { name: "UnauthorisedUser", accountID: account.ID, setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { addAuthorization(t, request, tokenMaker, authorizationTypeBearer, "unauthorised_user", time.Minute) }, buildStubs: func(store *mockdb.MockStore) { store.EXPECT(). GetAccount(gomock.Any(), gomock.Eq(account.ID)). Times(1). Return(account, nil) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusUnauthorized, recorder.Code) }, }, { name: "NoAuthorization", accountID: account.ID, setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { }, buildStubs: func(store *mockdb.MockStore) { store.EXPECT(). GetAccount(gomock.Any(), gomock.Any()). Times(0) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusUnauthorized, recorder.Code) }, }, { name: "NotFound", accountID: account.ID, setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute) }, buildStubs: func(store *mockdb.MockStore) { store.EXPECT(). GetAccount(gomock.Any(), gomock.Eq(account.ID)). Times(1). Return(db.Account{}, sql.ErrNoRows) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusNotFound, recorder.Code) }, }, { name: "InternalError", accountID: account.ID, setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute) }, buildStubs: func(store *mockdb.MockStore) { store.EXPECT(). GetAccount(gomock.Any(), gomock.Eq(account.ID)). Times(1). Return(db.Account{}, sql.ErrConnDone) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusInternalServerError, recorder.Code) }, }, { name: "InvalidID", accountID: 0, setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) { addAuthorization(t, request, tokenMaker, authorizationTypeBearer, user.Username, time.Minute) }, buildStubs: func(store *mockdb.MockStore) { store.EXPECT(). GetAccount(gomock.Any(), gomock.Any()). Times(0). Return(db.Account{}, sql.ErrNoRows) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusBadRequest, recorder.Code) }, }, } for i := range testCases { tc := testCases[i] t.Run(tc.name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() store := mockdb.NewMockStore(ctrl) // build stubs tc.buildStubs(store) // start test server and send request server := newTestServer(t, store) recorder := httptest.NewRecorder() url := fmt.Sprintf("/accounts/%d", tc.accountID) request, err := http.NewRequest(http.MethodGet, url, nil) require.NoError(t, err) tc.setupAuth(t, request, server.tokenMaker) server.router.ServeHTTP(recorder, request) // check response tc.checkResponse(t, recorder) }) } } // func TestCreateAccountAPI(t *testing.T) { // account := randomAccount() // testCases := []struct { // name string // body gin.H // buildStubs func(store *mockdb.MockStore) // checkResponse func(t *testing.T, recorder *httptest.ResponseRecorder) // }{ // { // name: "OK", // body: gin.H{ // "currency": account.Currency, // }, // buildStubs: func(store *mockdb.MockStore) { // arg := db.CreateAccountParams{ // Owner: account.Owner, // Currency: account.Currency, // Balance: 0, // } // store.EXPECT(). // CreateAccount(gomock.Any(), gomock.Eq(arg)). // Times(1). // Return(account, nil) // }, // checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { // require.Equal(t, http.StatusOK, recorder.Code) // requireBodyMatchAccount(t, recorder.Body, account) // }, // }, // } // for i := range testCases { // tc := testCases[i] // t.Run(tc.name, func(t *testing.T) { // ctrl := gomock.NewController(t) // defer ctrl.Finish() // store := mockdb.NewMockStore(ctrl) // // build stubs // tc.buildStubs(store) // // start test server and send request // server := NewServer(store) // recorder := httptest.NewRecorder() // // Marshal body data to JSON // data, err := json.Marshal(tc.body) // require.NoError(t, err) // url := "/accounts" // request, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) // require.NoError(t, err) // server.router.ServeHTTP(recorder, request) // // check response // tc.checkResponse(t, recorder) // }) // } // } func randomAccount(owner string) db.Account { return db.Account{ ID: util.RandomInt(1, 1000), Owner: owner, Balance: util.RandomMoney(), Currency: util.RandomCurrency(), } } func requireBodyMatchAccount(t *testing.T, body *bytes.Buffer, account db.Account) { data, err := ioutil.ReadAll(body) require.NoError(t, err) var gotAccount db.Account err = json.Unmarshal(data, &gotAccount) require.NoError(t, err) require.Equal(t, account, gotAccount) }
import { oneLine, stripIndents } from "common-tags"; import { Message, MessageEmbed } from "discord.js"; import { equipGear, unequipGear } from "../db/gear"; import { addGem } from "../db/gem"; import { addInventory, removeInventory } from "../db/inventory"; import { ButtonHandler } from "../internals/ButtonHandler"; import { Chest } from "../internals/Chest"; import Command from "../internals/Command"; import { Fragment, FragmentID } from "../internals/Fragment"; import { Gear } from "../internals/Gear"; import { Inventory } from "../internals/Inventory"; import { List } from "../internals/List"; import { Gem, Legendary, MiningPick, RoughStone, Stone } from "../internals/Mining"; import { upgrade } from "../internals/multipleUpgrade"; import { Pet, PetID } from "../internals/Pet"; import { Player } from "../internals/Player"; import { aggregateBy, ATTOM_BUTTON, BLACK_BUTTON, BLUE_BUTTON, bold, BROWN, capitalize, GOLD, NUMBER_BUTTONS, RED_BUTTON, RETURN_BUTTON, sleep, STAR, toList, WHITE_BUTTON, } from "../internals/utils"; import { client } from "../main"; export default class extends Command { name = "inventory"; aliases = ["inv"]; private inventory!: Inventory; async exec(msg: Message, args: string[]) { const player = await Player.getPlayer(msg.member!); const inv = player.inventory; this.inventory = inv; const itemsList = [ ...inv.chests.aggregate(), ...inv.fragments.aggregate(), ...inv.gears.aggregate(), ...inv.picks.aggregate(), ...inv.stones.aggregate(), ...inv.gems.aggregateBy(x => x.quality), ...inv.scrolls.aggregate(), ]; const [index] = args; if (index) { const i = parseInt(index) - 1; if (Number.isNaN(i)) return msg.channel.send("Please give valid index"); const accItem = itemsList[i]; if (!accItem) return msg.channel.send(`No item found at index ${index}`); const item = inv.all.get(accItem.value.id)!; const itemCount = accItem.count; if (item instanceof Fragment) { const pet = player.pets.get(item.pet.id); if (pet) { item.pet = pet; } } let button = new ButtonHandler(msg, item.show(itemCount), player.id); // attach handlers to every types of item if (item instanceof Chest) { this.handleChest(button, item, player, msg); } else if (item instanceof Fragment) { this.handleFragment(button, item, player, msg); } else if (item instanceof Gear) { const scrollCount = player.inventory.all.count(item.scroll.id); button = new ButtonHandler(msg, item.inspect(scrollCount), player.id); this.handleGear(button, item, player, msg); } else if (item instanceof MiningPick) { this.handlePick(button, item, player, msg); } else if (item instanceof Gem) { this.handleGem(item, msg); return; } else if (item instanceof RoughStone) { this.handleStone(button, item, player, msg); } button.addButton(RETURN_BUTTON, "return to inventory list", () => { this.exec(msg, []); }); button.addCloseButton(); await button.run(); return; } const chestList = []; const fragmentList = []; const gearList = []; const stoneList = []; const pickList = []; const othersList = []; let i = 1; for (const { value: item, count } of itemsList) { let line = `${i}. \`x${count} ${item.name}\``; switch (true) { case item instanceof Chest: chestList.push(line); break; case item instanceof Fragment: fragmentList.push(line); break; case item instanceof Gear: line = `${i}. \`x${count} ${item.name} Lvl ${(item as Gear).level}\``; gearList.push(line); break; case item instanceof RoughStone: stoneList.push(line); break; case item instanceof Gem: { const rarity = capitalize((item as Gem).quality); line = `${i}. \`x${count} ${rarity} Gem\``; stoneList.push(line); } break; case item instanceof MiningPick: pickList.push(line); break; default: othersList.push(line); } i++; } const list = stripIndents` **Treasure Chests** ${toList(chestList)} **Pet Fragments** ${toList(fragmentList)} **Gear** ${toList(gearList)} `; const list2 = stripIndents` **Gems and Mining Equipment** ${toList([...pickList, ...stoneList])} **Other Materials** ${toList(othersList)} **Coins** \`${player.coins}\` Coins \`${player.arenaCoins}\` Arena Coins ` const embed = new MessageEmbed() .setColor(GOLD) .addField("Inventory", list) const embed2 = new MessageEmbed() .setColor(GOLD) .addField("\u200b", list2) .addField( "\u200b", stripIndents` Use command \`${client.prefix}inventory <number>\` to inspect item in the inventory. Use command \`${client.prefix}gear\` to see your current equipped gear. ` ); await msg.channel.send(embed); await msg.channel.send(embed2); } private async handleGem( item: Gem, msg: Message, ) { const { quality, attribute } = item; const gems = this.inventory.gems.filter(x => x.quality === quality); const gemList = List.from(gems).aggregate(); let i = 0; for (const { value: gem, count } of gemList) { i++; const info = gem.inspect(count, i); await msg.channel.send(info); } let descText = oneLine`You can combine 5 ${quality} gems into a random higher quality gem. To combine, use command \`${client.prefix}combine ${quality} <number> <number> <number> <number> <number>\``; descText += `\nExample command: \`${client.prefix}combine ${quality} 1 1 2 2 3\``; const legendary = new Legendary(attribute); if (quality === legendary.quality) { descText = oneLine`You can combine 3 legendary gems into a legendary gem of choice. To combine, use command \`${client.prefix}combine legendary <number> <number> <number>\``; descText += `\nExample command: \`${client.prefix}combine legendary 1 1 2\``; } const helperText1 = new MessageEmbed() .setColor(BROWN) .setDescription(descText) const helperText2 = new MessageEmbed(helperText1) .setDescription( oneLine`You can socket a gem in your equipped helmet, chest piece or pants. You can do this by using the command: \`${client.prefix}socket ${quality} <number>\`` ) await msg.channel.send(helperText1); await msg.channel.send(helperText2); } handlePick( button: ButtonHandler, item: MiningPick, player: Player, msg: Message, ) { const mineHandler = async () => { const gem = Stone.random(); const miningMsg = await msg.channel.send(item.showMiningAnimation()); await sleep(4000); await addGem(player.id, gem.id); await removeInventory(player.id, item.id); miningMsg.edit(`You obtained ${bold(gem.name)}!`); const gemShow = new MessageEmbed(gem.show(-1)); const newDesc = oneLine`${gemShow.description} You can do this by inspecting a group of gems in your inventory.`; gemShow.setDescription(newDesc); msg.channel.send(gem.show(-1)); }; const itemCount = player.inventory.all.count(item.id); const multiMine = (count: number) => { return async () => { if (itemCount < count) { msg.channel.send(`Insufficient mining pick`); return; } const safeFnID = `handle_pick_${count}_${player.id}`; client.safeFn.add(safeFnID, mineHandler); try { for (let i = 0; i < count; i++) { await client.safeFn.exec(safeFnID); } } catch { msg.channel.send("There is already instance of mining command running"); } } } const pickCount = player.inventory.all.count(item.id); button.addButton(BLUE_BUTTON, "mine", multiMine(1)); button.addButton(RED_BUTTON, "mine 5", multiMine(5)); button.addButton(WHITE_BUTTON, "mine 10", multiMine(10)); button.addButton(ATTOM_BUTTON, "use all picks", multiMine(pickCount)); } private handleChest( button: ButtonHandler, item: Chest, player: Player, msg: Message ) { button.addButton(BLUE_BUTTON, "use the item", async () => { const result = await item.use(player); await player.sync(); const chestOpening = await msg.channel.send(item.openChestAnimation()); await sleep(6000); await chestOpening.delete(); const cards: MessageEmbed[] = []; const aggregated = aggregateBy(result, (x) => x.id); const fragment = Object.entries(aggregated) .map(([id, count]) => { const fragment = new Fragment(id as FragmentID); const ownedPet = player.pets.get(fragment.pet.id); const pet = ownedPet || fragment.pet; const ownedFragmentCount = player.inventory.all.count(id); cards.push(pet.fragmentCard(ownedFragmentCount)); return `\`x${count}\` **${fragment.name}**`; }) .join(" "); msg.channel.send(`You got ${fragment}!`); cards.forEach((x) => msg.channel.send(x)); }); } private handleStone( button: ButtonHandler, item: RoughStone, player: Player, msg: Message ) { button.addButton(BLUE_BUTTON, "combine 12 rough stones", async () => { const gem = item; // check for gem upgrade requirement const count = player.inventory.all.count(gem.id); if (count < gem.requirement) { const errMsg = oneLine`${gem.requirement} Rough Stones are required to upgrade to 1 ${capitalize(gem.product.quality)} Gem`; msg.channel.send(errMsg); return; } await removeInventory(player.id, gem.id, gem.requirement); const combineAnimation = gem.showCombineAnimation(); const animation = await msg.channel.send(combineAnimation); await sleep(4000); await animation.delete(); const upgrade = gem.product; await addGem(player.id, upgrade.id); await msg.channel.send(`You obtained ${upgrade.name}!`); await msg.channel.send(upgrade.show(-1)); }); } private handleFragment( button: ButtonHandler, item: Fragment, player: Player, msg: Message ) { const ownedPet = player.pets.get(item.pet.id); if (!ownedPet || ownedPet.star < 5) { button.addButton(BLUE_BUTTON, "use the item", async () => { const pet = item.pet; const ownedFragmentCount = this.inventory.all.count(item.id); let ownedPet = player.pets.get(pet.id); // if own the pet but does not have enough fragment to upgrade if (ownedPet && ownedFragmentCount < ownedPet.upgradeCost) { return msg.channel.send(oneLine`Insufficient fragments to upgrade ${ownedPet.name} \`${ownedFragmentCount}/${ownedPet.upgradeCost}\``); // if player does not own the pet but has less fragments than required // fragment in order to obtain the pet } else if (ownedFragmentCount < Fragment.minFragments) { return msg.channel.send(oneLine`Insufficient fragments to summon ${pet.name} \`${ownedFragmentCount}/${Fragment.minFragments}\``); } else if (ownedPet && ownedPet.star >= 5) { return msg.channel.send("Your pet is already at max star"); } const result = await item.use(player); await player.sync(); ownedPet = player.pets.get(pet.id)!; const fragmentCount = player.inventory.all.count(item.id); if (result === "obtain") { const summonAnimation = await msg.channel.send( item.summonAnimation() ); await sleep(8000); await summonAnimation.delete(); msg.channel.send(`${player.name} has obtained **${pet.name}**!`); msg.channel.send(ownedPet.card(fragmentCount, true)); } else if (result === "upgrade") { const ownedPet = player.pets.get(pet.id)!; const upgradeAnimation = await msg.channel.send( item.upgradeAnimation() ); await sleep(8000); await upgradeAnimation.delete(); msg.channel.send(`${pet.name} is now **${ownedPet.star}** ${STAR}!`); msg.channel.send(ownedPet.card(fragmentCount, true)); } }); } button.addButton( WHITE_BUTTON, "convert this fragment to other fragment of choice", () => { const ownedFragmentCount = this.inventory.all.count(item.id); if (ownedFragmentCount < 2) { return msg.channel.send( "Two fragments needed to convert to another pet fragment" ); } const embed = new MessageEmbed().setColor(BROWN).addField( "Select which pet fragments you want to convert to", oneLine`This will replace \`x2\` or \`x3\` ${item.pet.name}'s fragment with the selected fragment depending on the ratio` ); const choiceButton = new ButtonHandler(msg, embed, player.id); Pet.all.forEach((pet, i) => { const isDragon = pet.id === PetID.Dragon; const button = NUMBER_BUTTONS[i + 1]; const label = isDragon ? `${pet.fragment.name} - Ratio 3:1` : `${pet.fragment.name} - Ratio 2:1`; choiceButton.addButton(button, label, async () => { if (isDragon && ownedFragmentCount < 3) { return msg.channel.send("Dragon requires 3 fragments"); } await removeInventory(player.id, item.id); await removeInventory(player.id, item.id); if (isDragon) { await removeInventory(player.id, item.id); } const convertAnimation = item.convertAnimation(pet.fragment.name); const animation = await msg.channel.send(convertAnimation); await sleep(8000); await animation.delete(); await addInventory(player.id, pet.fragment.id); msg.channel.send(oneLine` Successfully converted \`x${ isDragon ? 3 : 2 }\` **${item.name}** into \`x1\` **${pet.fragment.name}**!`); }); }); choiceButton.addCloseButton(); choiceButton.run(); } ); } private handleGear(button: ButtonHandler, item: Gear, player: Player, msg: Message) { button.addButton(BLUE_BUTTON, "equip gear", async () => { const currentPiece = player.equippedGears.find( (x) => x.constructor.name === item.constructor.name ); // unequip gear if piece is the same for example Arena Armor and // Apprentice Armor if (currentPiece) { await unequipGear(player.id, currentPiece.id); } await equipGear(player.id, item.id); msg.channel.send(`Successfully equipped **${item.name}**!`); }); if (item.level < 10) { button.addButton( WHITE_BUTTON, "upgrade item using 1 scroll", upgrade(item, msg, player, 1) ); button.addButton( RED_BUTTON, "upgrade item using 10 scroll", upgrade(item, msg, player, 10) ); button.addButton( BLACK_BUTTON, "upgrade item using 50 scrolls", upgrade(item, msg, player, 50) ); } } }
/** * v0 by Vercel. * @see https://v0.dev/t/0knIycQozGW */ import Link from "next/link"; import { Button } from "@/components/ui/button"; import { CardTitle, CardDescription, CardHeader, CardContent, CardFooter, Card, } from "@/components/ui/card"; export default function Dashboard() { return ( <div key="1" className="flex flex-col w-full min-h-screen p-10"> <header className="flex items-center h-16 px-4 border-b shrink-0 md:px-6"> <nav className="flex-col hidden gap-6 text-lg font-medium md:flex md:flex-row md:items-center md:gap-5 md:text-sm lg:gap-6"> <Link className="flex items-center gap-2 text-lg font-semibold md:text-base" href="#" > <Package2Icon className="w-6 h-6" /> <span className="sr-only">Acme Inc</span> </Link> <Link className="font-bold" href="#"> Reviews </Link> </nav> <div className="flex items-center w-full gap-4 md:ml-auto md:gap-2 lg:gap-4"> <Button className="rounded-full" size="icon" variant="ghost"> <img alt="Avatar" className="rounded-full" height="32" src="/placeholder.svg" style={{ aspectRatio: "32/32", objectFit: "cover", }} width="32" /> <span className="sr-only">Toggle user menu</span> </Button> </div> </header> <main className="flex min-h-[calc(100vh_-_theme(spacing.16))] flex-1 flex-col gap-4 p-4 md:gap-8 md:p-10"> <Card> <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0"> <CardTitle className="text-sm font-medium">John Doe</CardTitle> <CardDescription className="text-xs text-gray-500 dark:text-gray-400"> Dec 7, 2023 </CardDescription> </CardHeader> <CardContent> <p className="text-sm"> This is a fantastic product. I would definitely recommend it to others. </p> </CardContent> <CardFooter> <Button className="text-fuchsia-100">Approve</Button> <Button className="ml-4" variant="outline"> Reject </Button> </CardFooter> </Card> <Card> <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0"> <CardTitle className="text-sm font-medium">John Doe</CardTitle> <CardDescription className="text-xs text-gray-500 dark:text-gray-400"> Dec 7, 2023 </CardDescription> </CardHeader> <CardContent> <p className="text-sm"> This is a fantastic product. I would definitely recommend it to others. </p> </CardContent> <CardFooter> <Button className="text-fuchsia-100">Approve</Button> <Button className="ml-4" variant="outline"> Reject </Button> </CardFooter> </Card> <Card> <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0"> <CardTitle className="text-sm font-medium">John Doe</CardTitle> <CardDescription className="text-xs text-gray-500 dark:text-gray-400"> Dec 7, 2023 </CardDescription> </CardHeader> <CardContent> <p className="text-sm"> This is a fantastic product. I would definitely recommend it to others. </p> </CardContent> <CardFooter> <Button className="text-fuchsia-100">Approve</Button> <Button className="ml-4" variant="outline"> Reject </Button> </CardFooter> </Card> </main> </div> ); } function Package2Icon(props: any) { return ( <svg {...props} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" > <path d="M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z" /> <path d="m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9" /> <path d="M12 3v6" /> </svg> ); }
import * as React from 'react' import Input from './input' import TaskCheckbox from './taskCheckbox' import TaskRadio from './taskRadio' import TaskSave from './taskSave' import TaskCancel from './taskCancel' import Edit from '../icons/edit' import { Form } from 'remix' interface Tasks { id: string completed?: boolean statusId?: string name: string actualTime: string goalTime: string timeTracker: number type: string } export default function TaskElement({ id, name, goalTime, actualTime, timeTracker, type, }: Tasks) { // this controls changes for all elements. Pass this as a prop as needed let [formState, setFormState] = React.useState('default') let defaultDiv = 'border-0 rounded ' let editDiv = 'border-0 bg-grey-200 rounded shadow-lg' let [currentStateDiv, setCurrentStateDiv] = React.useState(defaultDiv) let defaultButtons = 'hidden' let editButtons = 'display' let [currentStateButtons, setCurrentStateButtons] = React.useState(defaultButtons) React.useEffect(() => { if (formState === 'edit') { setCurrentStateButtons(editButtons) setCurrentStateDiv(editDiv) } if (formState === 'default') { setCurrentStateDiv(defaultDiv) setCurrentStateButtons(defaultButtons) } }, [formState, currentStateDiv, currentStateButtons, setCurrentStateButtons]) function clickHandler() { console.log('child input clicked') setFormState('edit') } return ( <div className={`mb-3 ${currentStateDiv}`}> <Form method="post" action="/daily/planner"> <input type="hidden" name="formType" value="task" /> <input type="hidden" name="id" value={id} /> <input type="hidden" name="type" value={type} /> <div className="p-2 grid grid-cols-10"> <div className="flex flex-row items-center col-span-7 pr-4"> <Input value={name} formState={formState} name="taskname" placeholder="Enter your task here..." setFormState={setFormState} width="flex-grow" /> </div> <div className="row-start-1 row-end-3 col-start-8 col-end-11"> <div className="flex flex-row items-center"> <Input value={goalTime} formState={formState} name="goaltime" placeholder="" setFormState={setFormState} width="w-14" /> <div className="w-36 flex flex-row justify-center px-4"> <TaskRadio /> <TaskRadio /> <TaskRadio /> <TaskRadio /> <TaskRadio /> </div> <Input value={actualTime} formState={formState} name="actualtime" placeholder="" setFormState={setFormState} width="w-14" /> <div className="w-12 first:w-7 text-purple h-auto flex justify-center"> <button type="button" className="border-1 border-orange first:w-6 w-full " onClick={() => setFormState('edit')} > <Edit /> </button> </div> </div> <div className="flex flex-row items-center"> <div className="text-sm w-14 flex flex-row justify-center "> Target </div> <div className="text-sm w-36 flex flex-row justify-center "> Track your time </div> <div className="text-sm w-14 flex flex-row justify-center "> Actual </div> <div className="text-sm w-12 flex flex-row justify-center "> Edit </div> </div> </div> <div className={`${currentStateButtons} col-span-7`}> <TaskSave /> <TaskCancel setFormState={setFormState} /> </div> </div> </Form> </div> ) }
/* 1. Crear una vista que muestre el nombre del cliente, título del libro y fechas de préstamo y devolución de todos los préstamos realizados. La vista debería ordenarse por el nombre del cliente. */ create view prestamos as select c.nombre, l.titulo, p.fecha_prestamo, p.fecha_devolucion from clientes c inner join prestamos p on c.id_cliente = p.id_cliente inner join libros l on l.id_libro = p.id_libro order by c.nombre; /* 2. Vista que muestra la cantidad total de libros prestados por cada cliente. */ create view librosprestados as select p.id_cliente, count(p.id_libro) from clientes c inner join prestamos p on c.id_cliente = p.id_cliente group by p.id_cliente; /* 3. Vista que muestra el total de compras realizadas por categoría. */ create view totalcompras as select ca.id_categoria, ca.nombre, count(*) from clientes c inner join compras co on c.id_cliente = co.id_cliente inner join libros l on l.id_libro = co.id_libro inner join libro_categoria lc on lc.id_libro = l.id_libro inner join categoria ca on ca.id_categoria = lc.id_categoria group by co.id_compra; /* 4. Crear un índice en la tabla "libros" para acelerar las búsquedas por título. */ create index titulos on libros(titulo); /* 5. Crear un usuario “dam1” con permisos de solo lectura en todas las tablas de la base de datos, y con contraseña “dam1” concatenando año actual (usa una función para esto) */ create user 'dam1'; set @password = concat('dam1', year(now())) grant select on libreria.* to 'dam1'; /* 6. Crear un usuario “dam2” identificado por "contraseña", con permisos de escritura y lectura en la tabla "libro_categoria" de la base de datos. */ create user 'dam2' identified by 'contrasenia'; grant select, update, insert, delete on libreria.libro_categoria to 'dam2'; /* 7. Revocar los permisos de escritura del usuario “dam2” de la tabla "libro_categoria" de la base de datos. */ revoke update, insert, delete on libreria.libro_categoria to 'dam2'; /* 8. Crear un nuevo usuario en localhost “nuevo_usuario” con todos los permisos y permisos para dar permisos. */ create user 'nuevo_usuario'@'localhost'; grant all PRIVILEGES on *.* to 'nuevo_usuario'@'localhost' with grant option; /* 9. Listar todos los usuarios existentes en la base de datos y sus respectivos permisos. */ select * from mysql.server; /* 1. Procedure-> ObtenerCantidadStock , recibe un parámetro de entrada "libro_id" que representa el identificador del libro y tiene un parámetro de salida "stock" que almacenará la cantidad de stock actual del libro. */ DELIMITER $$ CREATE PROCEDURE ObtenerCantidadStock(IN libro_id int, out stock int) BEGIN -- Contar la cantidad de stock SELECT cantidad_stock INTO stock FROM libros WHERE id_libro = libro_id; END $$ DELIMITER ; call ObtenerCantidadStock(1, @stock); select @stock; /* 2. Procedure-> CalcularDescuento, recibe dos parámetros de entrada: "precio_unitario" que representa el precio unitario de un producto y "cantidad" que indica la cantidad comprada. El parámetro de salida "descuento" almacenará el descuento calculado según la cantidad comprada. */ DELIMITER $$ CREATE PROCEDURE CalcularDescuento(IN precio_unitario decimal(10,2)) BEGIN declare total decimal(10,2); END $$ DELIMITER ; call ObtenerCantidadStock(1); /* 3. Procedure->VerificarDisponibilidad, recibe dos parámetros de entrada: "libro_id" que representa el identificador del libro y "cantidad_solicitada" que indica la cantidad de libros solicitada. El parámetro de salida "disponibilidad" indica si la cantidad solicitada está disponible o no. */ DELIMITER $$ CREATE PROCEDURE VerificarDisponibilidad(IN libro_id int, in cantidad_solicitada int, out disponibilidad varchar(250)) BEGIN declare stock_actual int; select cantidad_stock into stock_actual from libros where id_libro = libro_id; if stock_actual >= canttidad_solicitada THEN select 'DISPONIBLE' into disponibilidad else select 'NO DISPONIBLE' into disponibilidad end if; END $$ DELIMITER ;
// Example 1: // Input: words = ["bella","label","roller"] // Output: ["e","l","l"] // Example 2: // Input: words = ["cool","lock","cook"] // Output: ["c","o"] class Solution { public: vector<string> commonChars(vector<string>& words) { //to store the count of common element vector<int>common(26,INT_MAX); //to stroe the result vector<string>res; for(auto s :words){ //to stroe the count of each element vector<int>count(26,0); //to count the frequency for(auto c:s) count[c-'a']++; // to store the min count of elements //as we find the common elements in each string //so we need to stroe the min freq of them //eg ["cool","lock","cook"] //in cool count of l -1, lock count of l-1 , cook of l -0 //min count is-->0 so we store common[i]=0 for count of l for(int i=0;i<26;++i){ common[i]=min(common[i],count[i]); } } //store the ouput in result for(int i=0;i<26;++i){ //if common[i] is not 0 we have store it common[i] times as it includes duplicates if(common[i]>0){ while(common[i]--)res.push_back(string(1,i+'a'));//it means we are storing string size 1 } } return res; } };
Program Structure The organizational concepts in C# are programs, namespaces, types, members, and assemblies. Programs decalre teypes, which contain members and can be organized into namespaces. * Classes, structs, and interfaces are examples of types. * Fields, methods, properties, and events are examples of members. When C# programs are compiled, they're physically packaged into assemblies, which typically have extension .exe or .dll depending on whether they implement applications or libraries, respectively Assemblies contain executable code in the form of Intermediate Language (IL) instructions, and symbolic information in the form of metadata. Before it's executed, the Just-In-Time(JIT) compiler of .NET Common Language Runtime converts the IL code in an assembly to processor-specific code. Because an assembly is a self-describing unit of functionality containing both code and metadata, there's no need for "#include" directives and header files in C#. The public types and members contained in a particular assembly are made available in C# program simply by referencing that assembly when compilling the program ex.) this program uses the Acme.Collections.Stack class from the acme.dll assembly
// built in flutter packages import 'dart:convert'; import 'package:consult_24/models/call_api.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:http/http.dart' as http; import 'package:sizer/sizer.dart'; // a single widget to do search only class SearchBar extends StatefulWidget { @override State<SearchBar> createState() => _SearchBarState(); } class _SearchBarState extends State<SearchBar> { int? roleId; int? id; String? zipCode; bool onFocus = true; final TextEditingController searchText = TextEditingController(); final TextEditingController _getZipCode = TextEditingController(); var allSuggestions = []; var recentSearch = [ 'Air Cooler Cleaning', 'Roof painting', 'office decoration', 'Fitness trainer', 'Floor Cleaning', 'Dogs Care', 'Desktop clean', ]; @override void didChangeDependencies() async { SharedPreferences successLogin = await SharedPreferences.getInstance(); var roleJson = successLogin.getInt('role'); var roleDecode = json.decode(json.encode(roleJson)); var logId = successLogin.getInt('loginId'); var loginId = json.decode(json.encode(logId)); setState(() { roleId = roleDecode; _getUserZip(loginId); }); _getAllKeyword(); super.didChangeDependencies(); } _getAllKeyword() async { final keywordApi = Uri.parse('https://c24apidev.accelx' '.net/api/servicekeywordlistAPI_View/'); try { var responseKeyword = await http.get(keywordApi); var keyWordBody = json.decode(responseKeyword.body); // print(keyWordBody?['service_keyword_list']); if (responseKeyword.statusCode == 200) { setState(() { allSuggestions = keyWordBody?['service_keyword_list']; print(allSuggestions); }); } } catch (error) { print('Keyword list get error: $error'); } } _getUserZip(int? userId) async { try { var responseZip = await CallApi().getData( '/auth_api/UserIDWiseAddressZipCodeAPIView/?user_id=$userId'); print('user id:${responseZip.statusCode}'); var responseZipBody = json.decode(responseZip.body); if (responseZip.statusCode == 200) { var userZipCode = responseZipBody?[0]?['zip_code']; setState(() { zipCode = userZipCode; }); } } catch (error) { print('Getting error on userID: $error'); } } _getServiceList() async { var getServiceApi = Uri.parse( 'https://c24apidev.accelx.net/api/SearchServiceList/?zip_code=$zipCode&search=${searchText.text}'); try { var responseServiceGet = await http.get(getServiceApi); print('Searching result: ${responseServiceGet.statusCode}'); } catch (error) { print('service get result error: $error'); } } @override void dispose() { searchText.dispose(); super.dispose(); } // @override // void initState() { // // TODO: implement initState // super.initState(); // searchText.addListener(_printLatestValue); // } _fetchSearch(String input) {} void _printLatestValue() { print('Second text field: ${searchText.text}'); } onTextFieldSubmitted(String input) async {} @override Widget build(BuildContext context) { // final height = MediaQuery.of(context).size.height; // final width = MediaQuery.of(context).size.width; print(zipCode); return SafeArea( child: SizedBox( width: 100.w, height: 6.h, child: Row( children: [ SizedBox( width: 76.w, child: TextFormField( // onChanged: (String input) { // recentValues.add(input); // print('Search value: $input'); // }, autofocus: false, enableSuggestions: true, controller: searchText, cursorColor: Theme.of(context).colorScheme.primary, cursorHeight: 3.h, textAlignVertical: TextAlignVertical.center, onTap: buildSuggetions, decoration: InputDecoration( hintText: 'Search for getting help...', hintStyle: TextStyle( fontSize: 2.h, fontFamily: GoogleFonts.montserrat().fontFamily, letterSpacing: -0.5, wordSpacing: 0.5, ), fillColor: Colors.white, contentPadding: const EdgeInsets.symmetric( horizontal: 20, ), focusedBorder: const OutlineInputBorder(borderSide: BorderSide.none), prefixIcon: IconButton( icon: Icon( Icons.arrow_back, size: 3.h, ), onPressed: () { searchText.clear(); searchText.text = ''; buildSuggetions(); }, ), ), ), ), SizedBox( width: 24.w, child: Row( children: [ IconButton( onPressed: showDialogForZip, icon: Icon( Icons.location_on_sharp, size: 3.h, color: Colors.black87, ), padding: EdgeInsets.symmetric( vertical: 1.2.h, ), alignment: Alignment.center, color: Colors.red, ), IconButton( padding: EdgeInsets.symmetric( vertical: 1.2.h, ), onPressed: () { if (zipCode == '' && searchText == '') { if (searchText == '') { showDialogSearch(); } else if (zipCode == '') { showDialogForZip(); } } else { _getServiceList(); } }, icon: Icon( Icons.search_outlined, color: Theme.of(context).colorScheme.primary, size: 3.h, ), ), ], ), ), // ElevatedButton(onPressed: () { // onTextFieldSubmitted(input); // }, child: child) ], ), ), ); } _searchOperation(String searchText) { // searchResult.clear(); } buildActions(BuildContext context) => [ IconButton( onPressed: searchText.clear, icon: Icon( Icons.clear, size: 3.h, color: Colors.red, ), ), ]; // Widget buildLeading(BuildContext context) => IconButton( // onPressed: () {}, // icon: Icon( // Icons.arrow_back, // size: 3.h, // color: Colors.black87, // ), // ); buildResults() => Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [], ), ); buildSuggetions() { var suggestions = searchText.text.toString().isEmpty ? recentSearch : allSuggestions.where((suggestionResult) { final suggestionLower = suggestionResult.toString().toLowerCase(); final searchTextLower = searchText.text.toLowerCase(); return suggestionLower.contains(searchTextLower); }).toList(); return buildSuggestionsSuccess(suggestions); } buildSuggestionsSuccess(var suggestions) { print('suggestion building....'); print(suggestions); return ListView.builder( itemCount: suggestions.length, itemBuilder: (BuildContext context, index) { var suggestion = suggestions[index]; return ListTile( onTap: () { searchText.text = suggestion; }, leading: const Icon(Icons.search_sharp), title: Text(suggestion), ); }, ); } showDialogSearch() { return showDialog( context: context, builder: (BuildContext context) { return Center( child: Card( child: Container( height: 20.h, width: 70.w, padding: EdgeInsets.symmetric( horizontal: 5.w, vertical: 2.h, ), color: Colors.transparent, child: Stack( children: [ Positioned( top: 2, right: 2, child: InkWell( onTap: Navigator.of(context).pop, child: const Text('X'), ), ), const Center( child: Text('Please write something to search' ' or' ' accept our suggesstion'), ), ], ), ), ), ); }); } showDialogForZip() { return showDialog( context: context, builder: (BuildContext contex) { return Center( child: Card( child: Container( height: 28.h, width: 80.w, padding: EdgeInsets.symmetric( vertical: 5.w, ), color: Colors.transparent, child: Stack( children: [ Column( // mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only( left: 3.w, ), child: Text( 'Please enter your local or desire zip code.', softWrap: true, style: Theme.of(context).textTheme.bodyText2, ), ), SizedBox( height: 3.h, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Zip: ', style: TextStyle( fontSize: 1.8.h, fontWeight: FontWeight.bold, color: Colors.black87, letterSpacing: 1.2.w, ), ), SizedBox( width: 3.w, ), SizedBox( width: 50.w, child: TextFormField( controller: _getZipCode, autofocus: true, keyboardType: TextInputType.streetAddress, decoration: InputDecoration( border: OutlineInputBorder( gapPadding: 10.w, ), filled: true, prefixIcon: Icon( Icons.location_on, size: 3.h, ), ), ), ), ], ), SizedBox( height: 3.h, ), ElevatedButton( onPressed: () { setState(() { zipCode = _getZipCode.text; if (searchText != null) { _getServiceList; } Navigator.pop(context); }); }, child: Padding( padding: EdgeInsets.symmetric( horizontal: 5.w, vertical: 1.h, ), child: Text( 'Save', style: TextStyle( fontSize: 2.h, color: Colors.white70, ), ), ), ), ], ), ], ), ), ), ); }, ); } } // https://c24apidev.accelx.net/api/SearchServiceList/?zip_code=1229&search=gardening
import useToggle from "../../hooks/useToggle"; import { ToggleBtnProps } from "../../models/props"; const ToggleBtn = ({ text, icon, isActive, onClick }: ToggleBtnProps) => { const [active, toggleActive] = useToggle(isActive); const iconCSS = `toggle-btn__icon ${active && "toggle-btn__icon--active"}`; const textCSS = `toggle-btn__text ${active && "toggle-btn__text--active"}`; const handleClick = () => { toggleActive(); onClick(); }; return ( <button className="toggle-btn btn" onClick={handleClick}> <i className={iconCSS}>{icon}</i> <span className={textCSS}>{text}</span> </button> ); }; export default ToggleBtn;
import React, { useReducer, useState } from "react"; import tableStyle from "style/layout/dataTable/table.module.css"; import listStyle from "style/layout/dataTable/listTableData.module.css"; import HelperModal from "component/common/helper/HelperModal"; const HELPER_KEY = 113; export default function ListTable({ headers, items }) { const modalInit = { showModal: false, codeValue: "", // codeName: "", }; //모달 끄고 닫는 핸들러 const onModalHanlder = ( codeValue, codeName) => { // console.log('onmodalHandler',value) dispatch({ type: "ON_MODAL", codeValue, codeName }); }; const offModalHandler = () => { dispatch({ type: "OFF_MODAL" }); }; //모달 reducer (on/off, 코드 타입) const modalReducer = (state, action) => { if (action.type === "ON_MODAL") { console.log(action); return { showModal: true, codeValue: action.codeValue, codeName: action.codeName, }; } if (action.type === "OFF_MODAL") { return { showModal: false, codeValue: "", codeName: "" }; } }; const [modalState, dispatch] = useReducer(modalReducer, modalInit); const [currentCol, setCurrentCol] = useState(); const keyUpHandler = (e, colInfo) => { if (e.which === HELPER_KEY && colInfo.helper) { console.log(e, colInfo); setCurrentCol(e.target); onModalHanlder(colInfo.value, colInfo.text); } }; return ( <> {modalState.showModal && ( <HelperModal modalState={modalState} offModal={offModalHandler} // onSearchCode={searchHandler} /> )} {items.map((item, idx) => ( <tr key={idx}> {headers.map((header) => //선택 컬럼 header.value === "select" ? ( <td key={header.value + idx}> <input type="checkbox"></input> </td> ) : //순번 컬럼 header.value === "index" ? ( <td key={header.value + idx}>{idx + 1}</td> ) : ( <td key={header.value + idx}> {/* headerKey를 key로 가진 item 값을 출력 */} <input defaultValue={item[header.value]} onKeyUp={(e) => { keyUpHandler(e,header); }} ></input> </td> ) )} </tr> ))} </> ); }
import screenPointVert from './shaders/screen-point.vert'; import screenPointFrag from './shaders/screen-point.frag'; import pixelateFrag from './shaders/pixelate.frag'; import pixelateVert from './shaders/pixelate.vert'; import { configureProgram } from '../program'; import { getCanvas } from '../canvas/element'; const RAD_PER_DEGREE = Math.PI / 180; interface SceneData { gl: WebGL2RenderingContext; geoProgram: WebGLProgram; pixelateProgram: WebGLProgram; geoTexture: WebGLTexture; geoFramebuffer: WebGLFramebuffer; geometry: WebGLBuffer; canvasBuffer: WebGLBuffer; width: number; height: number; start_time: number; current_angle: number; attribs: { geometryVertexPosition: number; canvasVertexPosition: number; canvasTexturePosition: WebGLUniformLocation; worldRotationMatrixPosition: WebGLUniformLocation; // rotationVectorPosition: WebGLUniformLocation; geoResVectorPosition: WebGLUniformLocation; pixelResVectorPosition: WebGLUniformLocation; pixelSizePosition: WebGLUniformLocation; }; } const state = { scene: null as SceneData | null, pixelation: 3, }; export function runRenderToTexture() { window.addEventListener('keydown', (e) => { if (e.key === 'ArrowUp') { state.pixelation += 2; } else if (e.key === 'ArrowDown') { state.pixelation -= 2; state.pixelation = state.pixelation < 1 ? 1 : state.pixelation; } }); const cx = getCanvas(); const gl = cx.getContext('webgl2'); if (!gl) { return console.error('Unable to load webgl2 contex in canvas'); } gl.enable(gl.BLEND); const rect = cx.getBoundingClientRect(); const width = rect.width; const height = rect.height; // gl.viewport(0, 0, cx.height, cx.width); // gl.clear(gl.COLOR_BUFFER_BIT); // gl.blendFunc(gl.SRC_ALPHA, gl.ONE); // gl.enable(gl.BLEND); const geoProgram = configureProgram(gl, { vert: screenPointVert, frag: screenPointFrag, }); if (!geoProgram) { throw new Error('Failed to create the geometry program'); } const pixelateProgram = configureProgram(gl, { vert: pixelateVert, frag: pixelateFrag, }); if (!pixelateProgram) { console.error('Failed creating the pixellate program'); return; } // gl.disable(gl.DEPTH_TEST); const geometryVertexPosition = gl.getAttribLocation( geoProgram, 'aVertexPosition' ); const worldRotationMatrixPosition = gl.getUniformLocation( geoProgram, 'u_worldMatrix' ); const canvasVertexPosition = gl.getAttribLocation( pixelateProgram, 'aVertexPosition' ); const canvasTexturePosition = gl.getUniformLocation( pixelateProgram, 'u_texture' ); // const rotationVectorPosition = gl.getUniformLocation( // geoProgram, // 'u_rotation' // ); const pixelResVectorPosition = gl.getUniformLocation( pixelateProgram, 'u_resolution' ); const geoResVectorPosition = gl.getUniformLocation( geoProgram, 'u_resolution' ); const pixelSizePosition = gl.getUniformLocation(pixelateProgram, 'u_pixel'); if ( !canvasTexturePosition || // !rotationVectorPosition || !worldRotationMatrixPosition || !pixelResVectorPosition || !geoResVectorPosition || !pixelSizePosition ) { throw new Error('Missing location information'); } const canvasBuffer = createCanvasBuffer(gl); const geometry = createGeometryBuffer(gl); const texture = createTexture(gl, width, height); const framebuffer = createFramebuffer(gl, texture); state.scene = { gl: gl, geoProgram, pixelateProgram, canvasBuffer, geoTexture: texture, geoFramebuffer: framebuffer, geometry, width, height, start_time: 0, current_angle: 0, attribs: { canvasTexturePosition, geometryVertexPosition, canvasVertexPosition, worldRotationMatrixPosition, // rotationVectorPosition, pixelSizePosition, pixelResVectorPosition, geoResVectorPosition, }, }; loop(); } function createTexture( gl: WebGL2RenderingContext, width: number, height: number ) { const texture = gl.createTexture(); if (!texture) { throw new Error('Failed ot create texture'); } gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); return texture; } function createFramebuffer(gl: WebGL2RenderingContext, texture: WebGLTexture) { const fb = gl.createFramebuffer(); if (!fb) { throw new Error('Failed to create framebuffer'); } gl.bindFramebuffer(gl.FRAMEBUFFER, fb); const attachmentPoint = gl.COLOR_ATTACHMENT0; gl.framebufferTexture2D( gl.FRAMEBUFFER, attachmentPoint, gl.TEXTURE_2D, texture, 0 ); return fb; } function createZRotationMatrix(angleInDegrees: number) { const radians = angleInDegrees * RAD_PER_DEGREE; return [ Math.cos(radians), -Math.sin(radians), 0, 0, Math.sin(radians), Math.cos(radians), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, ]; // var cos = Math.cos; // var sin = Math.sin; // return [ // ]; } export function createGeometryBuffer(gl: WebGL2RenderingContext) { // Create a buffer and put three 2d clip space points in it const positionBuffer = gl.createBuffer(); if (!positionBuffer) { throw new Error('Failed to create geometry buffer'); } // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer) gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); // const positions = [-0.1, 0, 0, 0.5, 0.7, 0.1]; const positions = [ 0, 0, 0, -0.7, -0.7, -0.7, 0, 0, 0, 0.7, 0.7, 0.7, 0, 0, -0.7, 0, -0.7, 0.7, 0, 0, 0.7, -0.7, 0.7, 0, ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); return positionBuffer; } export function createCanvasBuffer(gl: WebGL2RenderingContext) { // Create a buffer and put three 2d clip space points in it const positionBuffer = gl.createBuffer(); if (!positionBuffer) { throw new Error('Failed to create canvas buffer'); } // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer) gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); const positions = [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); return positionBuffer; } export function loop() { const scene = state.scene; if (!scene) { throw new Error('Missing scene information'); } const current_time = new Date().getTime(); if (scene.start_time === 0) { scene.start_time = current_time; } const next_time = current_time - scene.start_time; scene.start_time = current_time; const DEGREES_PER_SECOND = 50; const next_time_seconds = next_time * 0.001; const delta_angle = next_time_seconds * DEGREES_PER_SECOND; const new_angle = (scene.current_angle + delta_angle) % 360; scene.current_angle = new_angle; drawTriangle(scene); drawCanvas(scene); requestAnimationFrame(loop); } export function drawCanvas(scene: SceneData) { if (state.pixelation < 3) { return; } const { gl } = scene; gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindTexture(gl.TEXTURE_2D, scene.geoTexture); gl.viewport(0, 0, scene.width, scene.height); gl.clearColor(1, 1, 1, 1); // clear to white gl.clear(gl.COLOR_BUFFER_BIT); gl.useProgram(scene.pixelateProgram); gl.bindBuffer(gl.ARRAY_BUFFER, scene.canvasBuffer); gl.enableVertexAttribArray(scene.attribs.canvasVertexPosition); gl.vertexAttribPointer( scene.attribs.canvasVertexPosition, 2, gl.FLOAT, false, 0, 0 ); const primitiveType = gl.TRIANGLES; // Tell the shader to use texture unit 0 for u_texture gl.uniform1i(scene.attribs.canvasTexturePosition, 0); gl.uniform2fv( scene.attribs.pixelResVectorPosition, new Float32Array([scene.width, scene.height]) ); gl.uniform1f(scene.attribs.pixelSizePosition, state.pixelation); const count = 6; gl.drawArrays(primitiveType, 0, count); } export function drawTriangle(scene: SceneData) { const { gl, geoProgram } = scene; if (state.pixelation >= 3) { gl.bindFramebuffer(gl.FRAMEBUFFER, scene.geoFramebuffer); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); } gl.viewport(0, 0, scene.width, scene.height); gl.clearColor(0, 0, 0, 1); // clear to blue gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.useProgram(geoProgram); gl.bindBuffer(gl.ARRAY_BUFFER, scene.geometry); gl.enableVertexAttribArray(scene.attribs.geometryVertexPosition); gl.vertexAttribPointer( scene.attribs.geometryVertexPosition, 2, gl.FLOAT, false, 0, 0 ); // const radians = (scene.current_angle * Math.PI) / 180.0; // gl.uniform2fv( // scene.attribs.rotationVectorPosition, // new Float32Array([Math.sin(radians), Math.cos(radians)]) // ); gl.uniformMatrix4fv( scene.attribs.worldRotationMatrixPosition, false, new Float32Array(createZRotationMatrix(45)), 0, 16 ); gl.uniform2fv( scene.attribs.geoResVectorPosition, new Float32Array([scene.width, scene.height]) ); gl.drawArrays(gl.TRIANGLES, 0, 12); }
#include <bits/stdc++.h> using namespace std; struct Item{ int value; int weight; }; // } Driver Code Ends //class implemented /* struct Item{ int value; int weight; }; */ class Solution { public: //Function to get the maximum total value in the knapsack. static bool cmp(struct Item a, struct Item b) { double r1 = (double)a.value / a.weight; double r2 = (double)b.value / b.weight; return r1 > r2; } double fractionalKnapsack(int W, Item arr[], int n) { sort(arr, arr + n, cmp); double finalvalue = 0.0; for (int i = 0; i < n; i++){ if ( arr[i].weight <= W) { W-= arr[i].weight; finalvalue += arr[i].value; } else { finalvalue += arr[i].value * ((double) W / arr[i].weight); break; } } return finalvalue; } }; // { Driver Code Starts. int main() { int t; //taking testcases cin>>t; cout<<setprecision(2)<<fixed; while(t--){ //size of array and weight int n, W; cin>>n>>W; Item arr[n]; //value and weight of each item for(int i=0;i<n;i++){ cin>>arr[i].value>>arr[i].weight; } //function call Solution ob; cout<<ob.fractionalKnapsack(W, arr, n)<<endl; } return 0; } // } Driver Code Ends
package inventory import ( "encoding/json" "fmt" "time" ) // ScryfallDate represents a date as represented in Scryfall type ScryfallDate struct { Value string Time time.Time } // UnmarshalJSON implements json.Unmarshaler func (sd *ScryfallDate) UnmarshalJSON(b []byte) error { var str string err := json.Unmarshal(b, &str) if err != nil { return fmt.Errorf("error unmarshaling date %q into string: %w", b, err) } t, err := time.Parse(time.DateOnly, str) if err != nil { return fmt.Errorf("error parsing string %q as date: %w", str, err) } *sd = ScryfallDate{ Value: str, Time: t, } return nil } // ScryfallCardFace represents one of the faces of a Card type ScryfallCardFace struct { Name string `json:"name"` OracleID string `json:"oracle_id"` } // ScryfallCard represents a card object retrieved from Scryfall type ScryfallCard struct { // Core Card Fields ID string `json:"id"` Language string `json:"lang"` OracleID string `json:"oracle_id"` // Gameplay fields Name string `json:"name"` // Print fields CollectorNumber string `json:"collector_number"` ReleasedAt ScryfallDate `json:"released_at"` Set string `json:"set"` // Card Face Objects CardFaces []ScryfallCardFace `json:"card_faces"` } // Scryfall describes the interface with something that returns Scryfall data, // whether it's a cache or the REST API. type Scryfall interface { GetCard(name, set, language, collectorNumber string) (*ScryfallCard, error) GetCardByName(string) (*ScryfallCard, error) GetCardByOracleID(string) (*ScryfallCard, error) GetCardByID(string) (*ScryfallCard, error) }
import React, {useEffect, useState, ReactNode} from "react"; import styled from "styled-components"; const Wrapper = styled.div` border: 1px solid lightgrey; border-radius: 5px; min-height: 0; display: flex; flex-direction: column; `; const Table2 = styled.div<{cols: string}>` display: grid; grid-template-columns: ${props => props.cols}; overflow-y: auto; `; export const Cell = styled.div` padding: 4px 8px; display: flex; justify-content: space-between; gap: 4px; `; const HeaderCell = styled(Cell)` border-bottom: 1px solid lightgrey; position: sticky; top: 0; z-index: .5; background: white; &:not(:last-child) { border-right: 1px solid lightgrey; } `; const Title = styled.div` grid-column: 1/-1; background: grey; color: white; padding: 1px 5px; `; export function Table({data, cols, render, expand, title}: {data: {[key: string]: any}[]; cols: string[]; render?: (row: any) => (ReactNode|string)[]; expand?: string; title: string}) { if (!data) return <>No data</>; return <Wrapper> <Title>{title}</Title> <Table2 cols={cols.map(c => c===expand? '1fr' : 'auto').join(' ')}> {cols.map(c => <HeaderCell>{c}</HeaderCell>)} {data.flatMap(row => { if (render) return render(row).map(cell => typeof cell === 'string'? <Cell>{row[cell]}</Cell> : cell); else return cols.map(c => <Cell>{row[c]}</Cell>); })} </Table2> </Wrapper>; };