text
stringlengths
184
4.48M
import sys import traceback try: from io import StringIO except ImportError: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO if sys.version_info[0] < 3: def u(strs): return strs.decode('utf-8') else: def u(strs): return strs _tmp_stream = StringIO() def w(write_method, s): try: write_method(s) except BaseException: write_method(unicode(s)) def print_exc_plus(stream=sys.stdout): '''print normal traceback information with some local arg values''' # code of this mothod is mainly from <Python Cookbook> def write(s): return w(stream.write, s) # assert the mothod exists # stream.write = write flush = stream.flush tp, value, tb = sys.exc_info() if tb is None: return False while tb.tb_next: tb = tb.tb_next stack = list() f = tb.tb_frame while f: stack.append(f) f = f.f_back stack.reverse() try: info = traceback.format_exc() except BaseException as e: try: info = u('FAILED PRINTING TRACE: %s\n\n%s\n\n' % (e, value)) except: info = u('') try: write(info) except: pass finally: flush() write(u('Locals by frame, innermost last\n')) for frame in stack: write(u('\nFrame %s in %s at line %s\n' % (frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno))) for key, value, in frame.f_locals.items(): write(u('\t%20s = ' % key)) try: value = u(str(value)) except BaseException: value = u('<ERROR WHILE PRINTING VALUE>') else: if len(value) > 100: value = value[:100] + '...' write(value) write(u('\n')) flush() return True def get_exc_plus(): _tmp_stream.seek(0) _tmp_stream.truncate() if print_exc_plus(_tmp_stream): _tmp_stream.seek(0) return _tmp_stream.read() return None if __name__ == '__main__': def zero_error(): local_1 = range(5) local_2 = 'a local arg' 1 / 0 stream = StringIO() try: zero_error() except Exception: print_exc_plus(stream) print('Err from stream:') print(stream.getvalue()) stream.close() try: zero_error() except Exception: print('Err from get_exc_plus():') print(get_exc_plus())
import React, { useEffect, useRef, useState } from "react"; import { Animated, Easing, Image, TouchableOpacity, StatusBar, } from "react-native"; import { NavigationContainer } from "@react-navigation/native"; import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; import { createStackNavigator } from "@react-navigation/stack"; import Ionicons from "react-native-vector-icons/Ionicons"; import LandingScreen from "../screens/LandingScreen"; import ProfileScreen from "../screens/ProfileScreen"; import FavoritesScreen from "../screens/FavoritesScreen"; import MangaDetailsScreen from "../screens/MangaDetailsScreen"; import { images } from "../constants"; const Tab = createBottomTabNavigator(); const Stack = createStackNavigator(); const MangaStack = () => ( <Stack.Navigator> <Stack.Screen name="Landing" component={LandingScreen} options={{ headerShown: false }} /> <Stack.Screen name="MangaDetails" component={MangaDetailsScreen} options={{ title: "Manga Details", headerStyle: { backgroundColor: "#242424" }, headerTintColor: "#fff", headerShown: false, }} /> </Stack.Navigator> ); const AnimatedIcon = ({ name, size, color, focused, activeTab, routeName }) => { const shakeAnimation = useRef(new Animated.Value(0)).current; useEffect(() => { if (focused && activeTab === routeName) { Animated.sequence([ Animated.timing(shakeAnimation, { toValue: 1, duration: 100, easing: Easing.linear, useNativeDriver: true, }), Animated.timing(shakeAnimation, { toValue: -1, duration: 100, easing: Easing.linear, useNativeDriver: true, }), Animated.timing(shakeAnimation, { toValue: 0, duration: 100, easing: Easing.linear, useNativeDriver: true, }), ]).start(); } }, [focused, activeTab, routeName, shakeAnimation]); const shake = shakeAnimation.interpolate({ inputRange: [-1, 1], outputRange: [-5, 5], }); return ( <Animated.View style={{ transform: [{ translateY: shake }] }}> <Ionicons name={name} size={size} color={color} /> </Animated.View> ); }; const TabBarButton = ({ children, onPress }) => ( <TouchableOpacity onPress={onPress} style={{ flex: 1 }}> {children} </TouchableOpacity> ); const AppNavigator = () => { const [activeTab, setActiveTab] = useState("Manga"); const handleTabPress = (routeName) => { setActiveTab(routeName); }; return ( <NavigationContainer> {/* Set the StatusBar color */} <StatusBar barStyle="light-content" backgroundColor="#242424" /> <Tab.Navigator screenOptions={({ route }) => ({ headerStyle: { backgroundColor: "#242424", }, headerTintColor: "#fff", headerTitle: () => ( <Image source={images.mound} style={{ width: 60, height: 80, objectFit: "cover", }} /> ), tabBarActiveTintColor: "red", tabBarInactiveTintColor: "gray", tabBarHideOnKeyboard: true, tabBarStyle: { backgroundColor: "#242424", borderTopWidth: 1, borderTopColor: "grey", }, tabBarIcon: ({ focused, color, size }) => { let iconName; if (route.name === "Manga") { iconName = focused ? "book" : "book-outline"; } else if (route.name === "Favorites") { iconName = focused ? "heart" : "heart-outline"; } else if (route.name === "Profile") { iconName = focused ? "person" : "person-outline"; } return ( <AnimatedIcon name={iconName} size={size} color={color} focused={focused} activeTab={activeTab} routeName={route.name} /> ); }, tabBarButton: (props) => ( <TabBarButton {...props} onPress={() => { handleTabPress(route.name); props.onPress(); }} /> ), })} > <Tab.Screen name="Manga" component={MangaStack} /> <Tab.Screen name="Favorites" component={FavoritesScreen} /> <Tab.Screen name="Profile" component={ProfileScreen} /> </Tab.Navigator> </NavigationContainer> ); }; export default AppNavigator;
import React,{Component} from 'react'; import {storeProducts, detailProduct} from './data.js' const ProductContext = React.createContext(); //provider //consumer class ProductProvider extends Component{ state = { products: [], detailProduct : detailProduct, cart : [], modalOpen : false, modalProduct : detailProduct, cartSubTotal : 0, cartTax : 0, cartTotal : 0 } componentDidMount(){ this.setProducts(); } setProducts = () => { let tempProducts = []; storeProducts.forEach(item => { const singleItem = {...item}; tempProducts = [...tempProducts,singleItem]; }) this.setState(()=>{ return {products: tempProducts}; }); }; getItem = (id) => { const product = this.state.products.find(item => item.id ===id); return product; } handleDetail = (id) => { const product = this.getItem(id); this.setState(()=>{ return {detailProduct : product} }) } addToCart = (id) => { let tempProducts = [...this.state.products]; const index = tempProducts.indexOf(this.getItem(id)); const product = tempProducts[index]; product.inCart = true; product.count = 1; const price = product.price; product.total = price; this.setState(() => { return {products: tempProducts, cart: [...this.state.cart,product]} },() => { this.addTotals(); }) } openModal = (id) => { const product = this.getItem(id); this.setState(() => { return {modalProduct: product,modalOpen:true} }) } closeModal = () => { this.setState(() => { return {modalOpen : false} }) } increment = (id) =>{ let tempCart = [...this.state.cart]; const selectedProduct = tempCart.find(item => item.id === id); const index = tempCart.indexOf(selectedProduct); const product = tempCart[index]; product.count = product.count + 1; product.total = product.count * product.price; this.setState( () =>{ return{ cart:[...tempCart] } }, () =>{this.addTotals()} ) } decrement = (id) =>{ let tempCart = [...this.state.cart]; const selectedProduct = tempCart.find(item => item.id === id); const index = tempCart.indexOf(selectedProduct); const product = tempCart[index]; product.count = product.count - 1; if(product.count === 0){ this.removeItem(id) } else{ product.total = product.count * product.price; this.setState( () =>{ return{ cart:[...tempCart] } }, () =>{this.addTotals()} ) } } removeItem = (id) =>{ let tempProducts = [...this.state.products]; let tempCart = [...this.state.cart]; tempCart = tempCart.filter(item => item.id !== id); const index = tempProducts.indexOf(this.getItem(id)); let removedProduct = tempProducts[index]; removedProduct.inCart = false; removedProduct.count = 0; removedProduct.total = 0; this.setState(() => { return{ cart: [...tempCart], products: [...tempProducts] } },() => { this.addTotals(); }) } clearCart = () => { this.setState(() => { return {cart: []}; },() =>{ this.setProducts(); this.addTotals(); }) } addTotals = () => { let subTotal = 0; this.state.cart.map(item => (subTotal += item.total)); const tempTax = subTotal * 0.1; const tax = parseFloat(tempTax.toFixed(2)); const total = subTotal + tax; this.setState(() => { return{ cartSubTotal: subTotal, cartTax: tax, cartTotal: total } }) } render(){ return( <ProductContext.Provider value={{ ...this.state, handleDetail : this.handleDetail, addToCart : this.addToCart, openModal : this.openModal, closeModal : this.closeModal, increment : this.increment, decrement : this.decrement, removeItem : this.removeItem, clearCart : this.clearCart }}> {this.props.children} </ProductContext.Provider> ) } } const ProductConsumer = ProductContext.Consumer; export { ProductProvider , ProductConsumer };
import Box from '@mui/material/Box'; import Button from '@mui/material/Button'; import Typography from '@mui/material/Typography'; import Modal from '@mui/material/Modal'; import { useSelector, useDispatch } from 'react-redux' import { useState } from 'react' import { useHistory } from 'react-router-dom'; import DeleteIcon from '@mui/icons-material/Delete'; const style = { position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '75%', bgcolor: 'background.paper', border: '2px solid #000', boxShadow: 24, p: 4, }; export default function DeleteItemFromAllItems() { const itemDetail = useSelector(store => store.itemDetail[0]) const dispatch = useDispatch(); const history = useHistory(); const [open, setOpen] = useState(false); const handleOpen = () => {setOpen(true)} const handleClose = () => setOpen(false); const ConfirmDelete = (e) => { e.preventDefault(); dispatch({ type: 'DELETE_ITEM_FROM_ALL_ITEMS', payload: itemDetail.id}) setOpen(false) history.push('/allitems') } return ( <> {/* <div className='btn-container-no-margin'> */} <Button endIcon={<DeleteIcon />} variant="contained" color="secondary" sx={{m: 1, width: 300}} className='admin-btn' onClick={handleOpen}>Delete Item From All Items</Button> {/* </div> */} <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <Typography id="modal-modal-title" variant="h6" component="h2"> Delete Item </Typography> {/* <Typography id="modal-modal-description" sx={{ mt: 2 }}> */} <form onSubmit={ConfirmDelete}> <h3>Are you quite sure you'd like to remove this item from the master list?</h3> <div className='confirmBtn'> <Button sx={{ marginLeft: 2, marginTop: 1 }} type='submit' variant='contained'>Delete</Button> <Button sx={{ marginLeft: 2, marginTop: 1 }} type='button' color='secondary' variant='contained' onClick={()=> setOpen(false)}>Cancel</Button> </div> </form> {/* </Typography> */} </Box> </Modal> </> ); }
import { Flex, Icon, Box, Button, useBreakpointValue, } from '@chakra-ui/react'; import { useScrollPosition } from '@n8tb1t/use-scroll-position'; import { useEffect, useState } from 'react'; import { RiMenu3Fill, RiCloseFill } from 'react-icons/ri'; import { useSidebarData } from '../../hooks/useSidebarData'; import { LogoIcon } from '../../icons/Logo'; import { Navbar } from './Navbar/Navbar'; export function Header() { const [hiddenHeader, setHiddenHeader] = useState(false); const [isSettingHidden, setIsSettingHidden] = useState(false); const { onToggle, isOpen } = useSidebarData(); const isWideVersion = useBreakpointValue({ base: false, lg: true }); useScrollPosition(({ currPos }) => { if (currPos.y <= -38) { setHiddenHeader(true); } else { setHiddenHeader(false); } }); useEffect(() => { const timeout = setTimeout(() => { setIsSettingHidden(true); }, 500); return () => clearTimeout(timeout); }, [isSettingHidden]); return ( <> <Flex as="nav" justify="space-between" py="10" px={{ base: 6, md: 12, lg: 16, }} position="fixed" left={0} right={0} top={hiddenHeader ? -122 : 0} transition="all 0.3s" boxShadow={isSettingHidden ? '#E94560 0px 10px 20px -10px' : ''} alignItems="center" zIndex={100} pos="relative" > <Box as="a" href="/"> <Icon as={LogoIcon} /> </Box> {isWideVersion && <Navbar />} </Flex> {!isWideVersion && ( <Button variant="none" p={0} onClick={onToggle} pos="absolute" right={{ base: 6, md: 12, lg: 16, xl: 0, }} zIndex={1500} top={hiddenHeader && !isOpen ? -122 : 41} transition="transform 0.5s ease-in-out, top 0.3s" transform={isOpen ? 'rotate(180deg)' : 'rotate(0deg)'} > <Icon as={isOpen ? RiCloseFill : RiMenu3Fill} boxSize="2.25rem" color="brandRed.500" /> </Button> )} </> ); }
"""project_tasks URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views from tasks_app import views as app_views urlpatterns = [ url(r'^$', app_views.index, name='index'), url(r'^admin/', admin.site.urls), url(r'^tasks/', include('tasks_app.urls')), url(r'^register/$', app_views.signup, name='register'), url(r'^accounts/login/$', views.login, name='login'), url(r'^accounts/logout/$', views.logout, name='logout', kwargs={'next_page': '/'}), # Added url(r'^oauth/', include('social_django.urls', namespace='social')), # <-- ]
import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App.tsx"; import "./index.css"; import { HashRouter, Route, Routes } from "react-router-dom"; import Home from "./routes/home/Home.tsx"; import CardInfo from "./routes/card-info/CardInfo.tsx"; import { CartProvider } from "./context/CartContext.tsx"; import Cart from "./routes/cart/Cart.tsx"; import Checkout from "./routes/checkout/Checkout.tsx"; import OrderReview from "./routes/order-review/PurchaseReview.tsx"; import { OrderReviewProvider } from "./context/OrderReviewContext.tsx"; ReactDOM.createRoot(document.getElementById("root")!).render( <React.StrictMode> <CartProvider> <OrderReviewProvider> <HashRouter> <Routes> <Route path="/" element={<App />}> <Route index path="/" element={<Home />} /> <Route path="/card/:name" element={<CardInfo />} /> <Route path="/cart" element={<Cart />} /> <Route path="/checkout" element={<Checkout />} /> <Route path="/review" element={<OrderReview />} /> </Route> </Routes> </HashRouter> </OrderReviewProvider> </CartProvider> </React.StrictMode> );
import tkinter as tk from tkinter import * # make this a csv file # a list of dictionaries of locations LOCATIONS_DICT = [ { "name": "cell", "desc": "Your prison cell. It contains a sink, a toilet, your bed, a desk, and a chair. Outside of your cell is the prison hallway.", "dests": ["hallway"], "inspectables": {"sink": "The sink is made of stainless steel and has a leaky faucet.", "bed": "Under the mattress, you find a crudely made steel crowbar. It is wide and thin, seemingly left behind by whoever previously lived in your cell.", "desk": "It is a simple wooden table bolted to the walls.", "chair": "The wooden chair is bolted to the floor."}, "items": ["crowbar"] }, { "name": "hallway", "desc": "A dimly lit hallway with doors leading to different areas of the prison.", "dests": ["cafeteria", "yard", "cell"], "inspectables": {}, "items": [] }, { "name": "cafeteria", "desc": "The prison cafeteria.", "dests": ["hallway"], "inspectables": {}, "items": ["bread"] }, { "name": "yard", "desc": "An enclosed outdoor area surrounded by barbed wire, where inmates get their daily exercise.", "dests": ["hallway"], "inspectables": {}, "items": [] }, { "name": "workshop", "desc": "A noisy room for manual labour.", "dests": ["hallway"], "inspectables": {}, "items": [] } ] # what's the point of this class Map: """Class for the map""" def __init__(self, locations): self.locations = locations class Location: """A class for locations. Stores location name, description, destinations, items.""" def __init__(self, name, desc, dests, inspectables, items): self.name = name self.desc = desc self.dests = dests self.inspectables = inspectables self.items = items def __str__(self): """Returns a string containing the information for each location""" return f"You are at {str(self.name)}. \n{str(self.desc)} \nYou can go to {', '.join(str(dest) for dest in self.dests)}." locations = [Location(**location) for location in LOCATIONS_DICT] # splits key value pairs from LOCATIONS_DICT to create location objects stored in the list locations def get_loc(input_loc): """Gets a location object for the name of location""" for location in locations: if location.name == input_loc: return location # else return None # player's starting location START_LOC = get_loc("cell") class Player: """Class for the player. Stores the player's current location and inventory.""" def __init__(self, inv, current_loc=START_LOC): # current_loc will be the starting location if not otherwise defined self.inv = inv self.current_loc = current_loc def move(self, input_dest): """Changes the player's current_loc to the new location that they input.""" # if the destination that the player inputs is valid, if input_dest in self.current_loc.dests: # get new location object using get_loc new_loc = get_loc(input_dest) self.current_loc = new_loc return player.current_loc # return description of location else: return "That is not a valid move." def take(self, input_item): """If the input item matches an item in the location, append the item to the player inventory and remove from location items""" if input_item in self.current_loc.items: player.inv.append(input_item) self.current_loc.items.remove(input_item) def inspect(self, input_item): """Prints out more information about an item in the location.""" if input_item in self.current_loc.inspectables: print(self.current_loc.inspectables[input_item]) player = Player([]) # ------------Tkinter stuff--------------------- # create tkinter window root = tk.Tk() # changes title of the window root.title('Game Window') # EDIT this # changes size of the window root.geometry('600x400') root.resizable(True, True) # create text widget and specify size main_text = Text(root, fg="blue", height="1px") # place at row0, sticky="nsew" makes it fill the whole grid main_text.grid(row=0, column=0, sticky="nsew") # insert text that i want to display main_text.insert('1.0', player.current_loc) # user can't edit the text main_text['state'] = 'disabled' # create a vertical scrollbar for the text box next to it text_scrollbar = Scrollbar(root, orient="vertical", command=main_text.yview) # sticks the scrollbar to north and south of its grid text_scrollbar.grid(row=0, column=1, sticky="ns") # configure the text widget to use the scrollbar main_text.config(yscrollcommand=text_scrollbar.set) # create frame around buttons button_frame = tk.Frame(root, bg="light grey") button_frame.grid(row=1, column=0, columnspan=2, sticky="nsew") # -----------------ratios/weights of grid--------- # makes text row and buttons row the same ratio root.grid_rowconfigure(0, weight=1) root.grid_rowconfigure(1, weight=1) # gives the text column (column0) priority over the scrollbar column root.grid_columnconfigure(0, weight=1) def clear_button_frame(): """Clears the button frame after a button is clicked""" for widget in button_frame.winfo_children(): # .winfo_children gets each children widget of the frame widget.destroy() def tkinter_update_move(dest): """Moves player when button is clicked, adds new text, and replaces buttons""" player.move(dest) update_loc_text() clear_button_frame() create_main_move_button() def create_move_buttons(): """"Makes separate buttons for each location. Runs after main move button is clicked""" num_buttons = len(player.current_loc.dests) button_height = 1 / num_buttons for i, dest in enumerate(player.current_loc.dests): rely_value = (i + 0.5) * button_height # Center each button vertically sub_move_button = tk.Button( button_frame, text=f"move to {dest}", command=lambda dest=dest: tkinter_update_move(dest) ) # Place the button with adjusted rely value sub_move_button.place(relx=0.5, rely=rely_value, relwidth=1, relheight=button_height, anchor="c") def update_loc_text(): """Adds new text to the main text box when the player moves.""" main_text.config(state='normal') # enables the text widget # inserts new text at end of old text with 2 new lines main_text.insert('end', '\n\n' + str(player.current_loc)) main_text.see('end') # scrolls to end of text box main_text.config(state='disabled') # re-disables the text widget def create_main_move_button(): """Creates main move button""" main_move_button = tk.Button( button_frame, text='Move', # command = creates new buttons for each direction command=lambda: [clear_button_frame(), create_move_buttons()] ) # main_move_button.place(relx=.5, rely=.5, anchor="c") #centres the move button in its grid main_move_button.pack(fill=BOTH, expand=True, padx=10, pady=10) # creates main move button create_main_move_button() # keeps the tkinter window displaying root.mainloop()
@charset "utf-8"; /*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */ /** * 1. Set default font family to sans-serif. * 2. Prevent iOS and IE text size adjust after device orientation change, * without disabling user zoom. */ html { font-family: sans-serif; /* 1 */ -ms-text-size-adjust: 100%; /* 2 */ -webkit-text-size-adjust: 100%; /* 2 */ } /** * Remove default margin. */ body { margin: 0; } /* HTML5 display definitions /** * Correct `block` display not defined for any HTML5 element in IE 8/9. * Correct `block` display not defined for `details` or `summary` in IE 10/11 * and Firefox. * Correct `block` display not defined for `main` in IE 11. */ article, aside, details, figcaption, figure, footer, header, hgroup, main, menu, nav, section, summary { display: block; } /** * 1. Correct `inline-block` display not defined in IE 8/9. * 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera. */ audio, canvas, progress, video { display: inline-block; /* 1 */ vertical-align: baseline; /* 2 */ } /** * Prevent modern browsers from displaying `audio` without controls. * Remove excess height in iOS 5 devices. */ audio:not([controls]) { display: none; height: 0; } /** * Address `[hidden]` styling not present in IE 8/9/10. * Hide the `template` element in IE 8/9/10/11, Safari, and Firefox < 22. */ [hidden], template { display: none; } /* Links /** * Remove the gray background color from active links in IE 10. */ a { background-color: transparent; } /** * Improve readability of focused elements when they are also in an * active/hover state. */ a:active, a:hover { outline: 0; } /* Text-level semantics /** * Address styling not present in IE 8/9/10/11, Safari, and Chrome. */ abbr[title] { border-bottom: 1px dotted; } /** * Address style set to `bolder` in Firefox 4+, Safari, and Chrome. */ b, strong { font-weight: bold; } /** * Address styling not present in Safari and Chrome. */ dfn { font-style: italic; } /** * Address variable `h1` font-size and margin within `section` and `article` * contexts in Firefox 4+, Safari, and Chrome. */ h1 { font-size: 2em; margin: 0.67em 0; } /** * Address styling not present in IE 8/9. */ mark { background: #ff0; color: #000; } /** * Address inconsistent and variable font size in all browsers. */ small { font-size: 80%; } /** * Prevent `sub` and `sup` affecting `line-height` in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } /* Embedded content /** * Remove border when inside `a` element in IE 8/9/10. */ img { border: 0; } /** * Correct overflow not hidden in IE 9/10/11. */ svg:not(:root) { overflow: hidden; } /* Grouping content /** * Address margin not present in IE 8/9 and Safari. */ figure { margin: 1em 40px; } /** * Address differences between Firefox and other browsers. */ hr { box-sizing: content-box; height: 0; } /** * Contain overflow in all browsers. */ pre { overflow: auto; } /** * Address odd `em`-unit font size rendering in all browsers. */ code, kbd, pre, samp { font-family: monospace, monospace; font-size: 1em; } /* Forms /** * Known limitation: by default, Chrome and Safari on OS X allow very limited * styling of `select`, unless a `border` property is set. */ /** * 1. Correct color not being inherited. * Known issue: affects color of disabled elements. * 2. Correct font properties not being inherited. * 3. Address margins set differently in Firefox 4+, Safari, and Chrome. */ button, input, optgroup, select, textarea { color: inherit; /* 1 */ font: inherit; /* 2 */ margin: 0; /* 3 */ } /** * Address `overflow` set to `hidden` in IE 8/9/10/11. */ button { overflow: visible; } /** * Address inconsistent `text-transform` inheritance for `button` and `select`. * All other form control elements do not inherit `text-transform` values. * Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera. * Correct `select` style inheritance in Firefox. */ button, select { text-transform: none; } /** * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` * and `video` controls. * 2. Correct inability to style clickable `input` types in iOS. * 3. Improve usability and consistency of cursor style between image-type * `input` and others. */ button, html input[type="button"], /* 1 */ input[type="reset"], input[type="submit"] { -webkit-appearance: button; /* 2 */ cursor: pointer; /* 3 */ } /** * Re-set default cursor for disabled elements. */ button[disabled], html input[disabled] { cursor: default; } /** * Remove inner padding and border in Firefox 4+. */ button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } /** * Address Firefox 4+ setting `line-height` on `input` using `!important` in * the UA stylesheet. */ input { line-height: normal; } /** * It's recommended that you don't attempt to style these elements. * Firefox's implementation doesn't respect box-sizing, padding, or width. * * 1. Address box sizing set to `content-box` in IE 8/9/10. * 2. Remove excess padding in IE 8/9/10. */ input[type="checkbox"], input[type="radio"] { box-sizing: border-box; /* 1 */ padding: 0; /* 2 */ } /** * Fix the cursor style for Chrome's increment/decrement buttons. For certain * `font-size` values of the `input`, it causes the cursor style of the * decrement button to change from `default` to `text`. */ input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button { height: auto; } /** * 1. Address `appearance` set to `searchfield` in Safari and Chrome. * 2. Address `box-sizing` set to `border-box` in Safari and Chrome. */ input[type="search"] { -webkit-appearance: textfield; /* 1 */ box-sizing: content-box; /* 2 */ } /** * Remove inner padding and search cancel button in Safari and Chrome on OS X. * Safari (but not Chrome) clips the cancel button when the search input has * padding (and `textfield` appearance). */ input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } /** * Define consistent border, margin, and padding. */ fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } /** * 1. Correct `color` not being inherited in IE 8/9/10/11. * 2. Remove padding so people aren't caught out if they zero out fieldsets. */ legend { border: 0; /* 1 */ padding: 0; /* 2 */ } /** * Remove default vertical scrollbar in IE 8/9/10/11. */ textarea { overflow: auto; } /** * Don't inherit the `font-weight` (applied by a rule above). * NOTE: the default cannot safely be changed in Chrome and Safari on OS X. */ optgroup { font-weight: bold; } /* Tables /** * Remove most spacing between table cells. */ table { border-collapse: collapse; border-spacing: 0; } td, th { padding: 0; } html { background: #222 -webkit-linear-gradient(90deg, #222 50%, #272727 50%); background: #222 linear-gradient(90deg, #222 50%, #272727 50%); background-size: 3em 100%; } * { box-sizing: border-box; margin: 0; padding: 0; } ul, li { list-style: none; } .wrapper { margin: 0 auto; position: relative; z-index: 10; } #bgb { position: fixed; width: 100%; height: 100%; z-index: -1; left: 0; top: 0; -webkit-filter: blur(5px); filter: blur(5px); } .bg { background: #f7f2ec url(/assets/images/letter_bg.png); border: 1px solid #fff; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; box-shadow: 0px 0px 3px #9d9d9d, inset 0px 0px 27px #fff; -moz-box-shadow: 0px 0px 3px #9d9d9d, inset 0px 0px 14px #fff; -webkit-box-shadow: 0px 0px 3px #9d9d9d, inset 0px 0px 27px #fff; -webkit-transition: all 1s ease-in-out .3s; -moz-transition: all 1s ease-in-out .3s; -o-transition: all 1s ease-in-out .3s; transition: all 1s ease-in-out .3s; } @font-face { font-family: 'Abel'; font-style: normal; font-weight: 400; src: local('Abel'), local('Abel-Regular'), url(/assets/abel.woff) format("woff"); } @font-face { font-family: 'Rock Salt'; font-style: normal; font-weight: 400; src: local('Rock Salt'), local('RockSalt'), url(/assets/rock-salt.woff) format('woff'); } @font-face { font-family: 'ecoico'; src: local("ecoico"), url(/assets/ecoico.woff) format('woff'); font-weight: 400; font-style: normal; } body { font-family: 'Abel', Arial, sans-serif; font-weight: 300; font-size: 12px; overflow-y: scroll; overflow-x: hidden; color: #333; text-shadow: 0 1px 1px #ccc; } #forkme { position: fixed; top: 0; right: 0; border: 0; z-index: 999; } .hide { display: none; } .center { text-align: center; margin: 0 auto; display: block; } .count { vertical-align: super; font-size: 0.8em; } #gotop, #gohome { width: 50px; background: none repeat scroll 0% 0% #FFF; text-align: center; padding: 5px; position: fixed; bottom: 13px; right: 30px; cursor: pointer; display: none; color: #333; font-family: verdana; font-size: 11px; border-bottom: 3px solid #f60; border-radius: 3px; transition: all 0.3s linear 0s; z-index: 999; } #gohome { bottom: 45px; display: block; } header { text-align: center; } a { text-decoration: none; color: #69f; } a:hover { color: #eee; } header h1 { font-family: 'Rock Salt', Arial, sans-serif; font-size: 3.5em; display: inline-block; } header h1 a { color: #f06; text-shadow: 2px 2px 4px #333, 2px 2px 0px #69f; animation: skewtext 1s ease 0s alternate none infinite; -webkit-animation: skewtext 1s ease 0s alternate none infinite; -moz-animation: skewtext 1s ease 0s alternate none infinite; display: block; } header h1 a:hover { color: #f06; text-shadow: 4px 4px 0px #333, 2px 2px 0px #69f; transition: all 1s; -webkit-animation: 0; -moz-animation: 0; animation: 0; } header h2 { text-shadow: 0px 1px 2px #f06; } header h1 a::before, header h1 a::after { display: inline-block; opacity: 0; -webkit-transition: -webkit-transform 0.3s, opacity 0.2s; -moz-transition: -moz-transform 0.3s, opacity 0.2s; transition: transform 0.3s, opacity 0.2s; } header h1 a::before { margin-right: 10px; content: '['; -webkit-transform: translateX(20px); -moz-transform: translateX(20px); transform: translateX(20px); } header h1 a::after { margin-left: 10px; content: ']'; -webkit-transform: translateX(-20px); -moz-transform: translateX(-20px); transform: translateX(-20px); } header h1 a:hover::before, header h1 a:hover::after, header h1 a:focus::before, header h1 a:focus::after { opacity: 1; -webkit-transform: translateX(0px); -moz-transform: translateX(0px); transform: translateX(0px); } @keyframes skewtext { from { transform: skewX(0deg); } 25% { transform: skewX(30deg); } 50% { transform: skewX(0deg); } 75% { transform: skewX(-30deg); } to { transform: skewX(0deg); } } @-webkit-keyframes skewtext { from { -webkit-transform: skewX(0deg); } 25% { -webkit-transform: skewX(30deg); } 50% { -webkit-transform: skewX(0deg); } 75% { -webkit-transform: skewX(-30deg); } to { -webkit-transform: skewX(0deg); } } @-moz-keyframes skewtext { from { -moz-transform: skewX(0deg); } 25% { -moz-transform: skewX(30deg); } 50% { -moz-transform: skewX(0deg); } 75% { -moz-transform: skewX(-30deg); } to { -moz-transform: skewX(0deg); } } #content{ width: calc(100% - 333px); width: -webkit-calc(100% - 350px); width: -moz-calc(100% - 350px); width: -o-calc(100% - 350px); width: -ms-calc(100% - 350px); padding:10px; } #content .pagination{ display: block; text-align: center; padding: 10px 0; } #content .pagination li{ display: inline; margin:5px; padding: 5px; background: rgba(255,0,102,0.5); } /* Timeline */ .timeline { margin: 30px 0 0 0; padding: 0; position: relative; display: block; } .timeline > li { padding-bottom: 10px; display: list-item; text-align: -webkit-match-parent; } article img{ max-width:100%; margin:10px auto; display: block; } article p{ padding:5px 0; text-indent: 2em; } article h2 a,article section a:hover,#content .pagination li a{ color: #eee; text-shadow: 2px 2px 5px #f06; } article h2 a:hover,article section a,article .meta span{ color: #f06; text-shadow: 2px 2px 5px #eee; } .timeline:before{ content:' '; top:0; bottom:0; background: rgba(255,0,102,0.5);; position: absolute; width:10px; left:20%; margin-left: -10px; } .timeline > li > .meta { display: block; width: 20%; padding-right: 50px; position: absolute; text-align: right; } .timeline > li .device { width: 40px; height: 40px; font-family: 'ecoico'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; font-size: 1.4em; line-height: 40px; -webkit-font-smoothing: antialiased; position: absolute; color: #fff; background: #46a4da; border-radius: 50%; box-shadow: 0 0 0 8px rgba(255,0,102,0.5);; text-align: center; left: 20%; margin: 0 0 0 -25px; } .mobile:before { content: "\e000"; } .desktop:before { content: "\e001"; } .mail:before { content: "\e002"; } .earth:before { content: "\e003"; } .timeline > li .meta time { font-size: 0.9em; color: #bdd0db; } .timeline > li .meta address { font-size: 2.9em; color: #3594cb; } .timeline > li:nth-child(odd) .meta address { color: #6cbfee; } /* Right content */ .timeline > li .mrright { margin: 0 50px 75px 25%; color: #fff; font-size: 1.2em; font-weight: 300; line-height: 1.4; position: relative; border-radius: 5px; perspective: 600px; -webkit-perspective: 600px; -moz-perspective: 600px; -o-perspective: 600px; -ms-perspective: 600px; } .timeline > li.post .mrright{ perspective: none; -webkit-perspective: none; -moz-perspective: none; -o-perspective: none; -ms-perspective: none; } .timeline > li.current .mrright{ margin:0px 0 15px 0; padding-top: 100px; } .timeline >li article{ background: rgba(53,148,203,0.5); padding: 2em; transition: transform 0.8s cubic-bezier(.59,1.45,.69,.98) 0.2s; -webkit-transition: -webkit-transform 0.8s cubic-bezier(.59,1.45,.69,.98) 0.2s; -moz-transition: -moz-transform 0.8s cubic-bezier(.59,1.45,.69,.98) 0.2s; -o-transition: -o-transform 0.8s cubic-bezier(.59,1.45,.69,.98) 0.2s; -ms-transition: -ms-transform 0.8s cubic-bezier(.59,1.45,.69,.98) 0.2s; transform-origin: 0 0; -webkit-transform-origin: 0 0; -moz-transform-origin: 0 0; -o-transform-origin: 0 0; -ms-transform-origin: 0 0; transform-style: preserve-3d; -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; -ms-transform-style: preserve-3d; -o-transform-style: preserve-3d; transform:rotateX(10deg); -webkit-transform:rotateX(10deg); -moz-transform:rotateX(10deg); -o-transform:rotateX(10deg); -ms-transform:rotateX(10deg); } .timeline > li.current article{ transform:rotateX(-5deg); -webkit-transform:rotateX(-5deg); -moz-transform:rotateX(-5deg); -o-transform:rotateX(-5deg); -ms-transform:rotateX(-5deg); background: #f60 !important; } .timeline > li:nth-child(odd) article { background: rgba(108,191,238,0.5); } .timeline > li article h2 { margin-top: 0px; padding: 0 0 10px 0; border-bottom: 1px solid rgba(255,255,255,0.4); } /* The triangle */ .timeline > li article:after { right: 100%; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-right-color: rgba(53,148,203,0.5); border-width: 10px; top: 10px; } .timeline > li:nth-child(odd) article:after { border-right-color: rgba(108,191,238,0.5); } .timeline > li.current article:after { border-right-color: transparent; border-bottom-color: rgba(255,0,102,0.5); top:-20px; right: 90%; } .timeline >li article cite{ color:#333; text-shadow: 0 0 1px #f06; } .timeline >li article section.meta{ color:#bdd0db; } .timeline >li article section h1,.timeline >li article section h2,.timeline >li article section h3,.timeline >li article section h4,.timeline >li article section h5, .timeline >li article section h6{ color:#69f; text-shadow: 1px 1px 1px #000; } .timeline >li article section ul li{ margin-left:2em; list-style: square; } .timeline >li article section ol li{ margin-left:2em; list-style: decimal; } .timeline >li article section blockquote,.timeline >li article section b{ background: #eee; padding:10px; color:#333; position: relative; text-indent: 20px; } .timeline >li article section blockquote:before,.timeline >li article section b:before{ content: '“'; display: block; position: absolute; color:#f60; font-size:30px; top: 0; left:0; } .timeline >li article section blockquote:after,.timeline >li article section b:after{ content: '”'; display: block; position: absolute; color:#f60; font-size:30px; bottom: -15px; right:5px; } /* Example Media Queries */ @media screen and (max-width: 65.375em) { .timeline > li .meta address { font-size: 1.5em; } } @media screen and (max-width: 47.2em) { #forkme{ display: none; } .timeline:before{ left:auto; right:45px; } .timeline > li > .meta { width: 100% ; position: relative ; padding: 0 0 20px 0; text-indent: 2em; text-align: left; } .timeline > li .mrright { margin: 0 5px 30px 5px; padding: 1em; font-weight: 400; font-size: 95%; } .timeline > li.current .mrright{ padding-top: 2.5em; } .timeline > li article:after { right: auto; left: 20px; border-right-color: transparent; border-bottom-color: rgba(53,148,203,0.5); top: -20px; } .timeline > li:nth-child(odd) article:after { border-right-color: transparent; border-bottom-color: rgba(108,191,238,0.5); } .timeline > li.current article:after { border-right-color: transparent; border-bottom-color: #f60; } .timeline > li .device { position: relative; float: right; left: auto; margin: -55px 30px 0 0px; } } #sidebar, article { background: rgba(255,0,102,0.5); } #sidebar { width: 336px; overflow: hidden; position: absolute; top: 30px; right: 0; padding: 0; } .widget { clear: both; } .widget img { margin: 5px auto; display: block; } .widget > div { padding: 10px; } .widget h3 { background: #69f; padding: 10px; display: inline-block; border-radius: 0 0 20px 0; -webkit-border-radius: 0 0 20px 0; -moz-border-radius: 0 0 20px 0; -o-border-radius: 0 0 20px 0; -ms-border-radius: 0 0 20px 0; color: #eee; box-shadow: 2px 2px 0 #333; } .widget li { margin: 10px; } .widget .language li, .widget .tags li { float: left; } .widget a { line-height: 2em; -webkit-perspective: 800px; -moz-perspective: 800px; perspective: 800px; } .widget a span { position: relative; display: inline-block; padding: 3px 15px 0; background: rgba(0, 0, 0, 0.1); box-shadow: inset 0 3px rgba(102, 153, 255, 0.5); -webkit-transition: background 0.6s; -moz-transition: background 0.6s; transition: background 0.6s; -webkit-transform-origin: 50% 0; -moz-transform-origin: 50% 0; transform-origin: 50% 0; -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; -webkit-transform-origin: 0% 50%; -moz-transform-origin: 0% 50%; transform-origin: 0% 50%; } .widget a span::before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(102, 153, 255, 0.5); color: #fff; content: attr(data-hover); -webkit-transform: rotateX(270deg); -moz-transform: rotateX(270deg); transform: rotateX(270deg); -webkit-transition: -webkit-transform 0.6s; -moz-transition: -moz-transform 0.6s; transition: transform 0.6s; -webkit-transform-origin: 0 0; -moz-transform-origin: 0 0; transform-origin: 0 0; pointer-events: none; } .widget a:hover span, .widget a:focus span { background: #2f4351; } .widget a:hover span::before, .widget a:focus span::before { -webkit-transform: rotateX(10deg); -moz-transform: rotateX(10deg); transform: rotateX(10deg); } #footer { clear: both; text-align: center; color: #fff; } #loading { position: fixed; width: 40px; height: 40px; top: 10px; right: 10px; z-index: 9999; background: url(/assets/images/loading.png) no-repeat; animation: rotate 2s ease-out; -webkit-animation: rotate 2s ease-out infinite; -moz-animation: rotate 2s ease-out infinite; } @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(359deg); } } @-webkit-keyframes rotate { from { -webkit-transform: rotate(0deg); } to { -webkit-transform: rotate(359deg); } } @-moz-keyframes rotate { from { -moz-transform: rotate(0deg); } to { -moz-transform: rotate(359deg); } } /* Responsive */ @media screen and (max-width: 767px) { .hide-for-small { display: none; } #sidebar { display: none; } } @media screen and (max-width: 959px) { #content, #sidebar { width: 100%; position: relative; } #loading { position: fixed; top: 1px !important; right: 1px !important; } } @media screen and (min-width: 768px) { .wrapper { width: 93.75%; max-width: 1280px; } }
import React from "react"; import { ScrollView } from "react-native-gesture-handler"; import { useTheme } from "styled-components"; import styled from "styled-components/native"; import Icons from "../../components/atoms/Icons"; import BadgeItemForAll from "../../components/organisms/Badge/BadgeItemForAll"; import { spacing } from "../../constants/spacing"; import useResponsiveFontSize from "../../utils/useResponsiveFontSize"; import Margin from "../../components/atoms/Margin"; import useHeight from "../../hooks/useHeight"; import { Platform } from "react-native"; const Container = styled.View` background-color: ${({ theme }) => theme.background}; flex: 1; `; const SHeader = styled.View` padding: ${spacing.offset}px; `; const Header = ({ theme, onPress }) => ( <SHeader> <Icons type="feather" name="chevron-left" size={35} color={theme.text} onPress={onPress} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }} /> </SHeader> ); const Wrapper = styled.View` padding: ${spacing.offset}px; flex: 1; flex-direction: row; flex-wrap: wrap; gap: ${useResponsiveFontSize(15)}px; `; const BadgeAllScreen = ({ route, navigation }) => { const { type, badges: allBadges } = route.params; const theme = useTheme(); const { NOTCH_TOP } = useHeight(); return ( <Container style={{ paddingTop: Platform.OS === "android" ? NOTCH_TOP : 0 }} > <Header theme={theme} onPress={() => navigation.goBack()} /> <ScrollView> <Wrapper> {allBadges.map((badge) => ( <BadgeItemForAll key={badge.type} item={badge} type={type} /> ))} </Wrapper> <Margin margin={100} /> </ScrollView> </Container> ); }; export default BadgeAllScreen;
package tests; import java.io.IOException; import java.util.Arrays; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class AddCategoryTest { WebDriver driver; @BeforeMethod @Parameters({ "browser", "url", "username", "password" }) public void beforeMethod(String browser, String url, String username, String password) { System.out.println("start"); if (browser.equals("chrome")) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\SWHIZZ TECHNOLOGIES\\Downloads\\jars\\chromedriver.exe"); driver = new ChromeDriver(); } else if (browser.equals("gecko")) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\SWHIZZ TECHNOLOGIES\\Downloads\\jars\\geckodriver.exe"); driver = new FirefoxDriver(); } else if (browser.equals("edge")) { System.setProperty("webdriver.edge.driver", "C:\\Users\\SWHIZZ TECHNOLOGIES\\Downloads\\jars\\msedgedriver.exe"); driver = new EdgeDriver(); } driver.manage().window().maximize(); driver.get(url); driver.findElement(By.name("email")).sendKeys(username); driver.findElement(By.name("password")).sendKeys(password); driver.findElement(By.name("submit")).click(); } @DataProvider public String[][] dp() throws IOException { return getData(); } @Test(dataProvider = "dp") public void addCategoryTestCase(String CategoryName, String SortOrder, String MetaTitle, String MetaDescription, String MetaKeywords, String results) { driver.findElement(By.xpath("//span[contains(text(),'Categories List')]")).click(); driver.findElement(By.xpath("//header/div[1]/div[1]/div[1]/a[1]")).click(); driver.findElement(By.xpath( "//body/div[1]/section[1]/div[1]/div[1]/section[1]/div[1]/div[1]/div[1]/form[1]/div[1]/input[1]")) .sendKeys(CategoryName); driver.findElement(By.xpath( "//body/div[1]/section[1]/div[1]/div[1]/section[1]/div[1]/div[1]/div[1]/form[1]/div[2]/input[1]")) .sendKeys(SortOrder); driver.findElement(By.xpath( "//body/div[1]/section[1]/div[1]/div[1]/section[1]/div[1]/div[1]/div[1]/form[1]/div[3]/input[1]")) .sendKeys(MetaTitle); driver.findElement(By.xpath( "//body/div[1]/section[1]/div[1]/div[1]/section[1]/div[1]/div[1]/div[1]/form[1]/div[4]/input[1]")) .sendKeys(MetaDescription); driver.findElement(By.xpath( "//body/div[1]/section[1]/div[1]/div[1]/section[1]/div[1]/div[1]/div[1]/form[1]/div[5]/input[1]")) .sendKeys(MetaKeywords); driver.findElement(By.xpath( "//body/div[1]/section[1]/div[1]/div[1]/section[1]/div[1]/div[1]/div[1]/form[1]/div[6]/input[1]")) .click(); String message = driver .findElement(By.xpath("//body/div[1]/section[1]/div[1]/div[1]/section[1]/div[1]/div[1]/div[1]")) .getText(); System.out.println("message"); if ("pass".equals(results)) { Assert.assertTrue(message.contains("successfully")); } else { Assert.assertTrue(message == null || message.trim().isEmpty()); } } @AfterMethod public void afterMethod() { driver.close(); } public String[][] getData() throws IOException { XLUtility xl = new XLUtility( "C:\\Users\\SWHIZZ TECHNOLOGIES\\eclipse-workspace1\\Java_Training\\excelFiles\\testdata.xlsx"); int rowcount = xl.getRowCount("addCategory"); int colcount = xl.getCellCount("addCategory", 2); System.out.println("rows:" + rowcount + " cols: " + colcount); String data[][] = new String[rowcount][colcount]; for (int i = 0; i < rowcount; i++) { for (int j = 0; j < colcount; j++) { data[i][j] = xl.getCellData("addCategory", i + 2, j); } System.out.println(Arrays.toString(data[i])); } System.out.println("Number of records: " + data.length); return data; } }
import re from urllib.parse import urljoin from bs4 import BeautifulSoup, Tag from tqdm import tqdm from parse_utils import * import os import json import argparse LOG_PATH = "parse_log.txt" TITLEPAGE_INFO = [] TITLEPAGE_WORD_COUNT_CUTOFF = 300 GENRE_LIST = [ "Romane, Novellen und Erzählungen", "Historische Romane und Erzählungen", "Anthologien", "Romanhafte Biographien", "Märchen, Sagen, Legenden", "Spannung und Abenteuer", "Krimis, Thriller, Spionage", "Historische Kriminalromane und -fälle", "Science Fiction", "Phantastische Literatur", "Horror", "Humor, Satire", "Kinderbücher bis 11 Jahre", "Kinderbücher ab 12 Jahren", ] def parse_single_book(work_dict, titlepage_info=False): printf = open(LOG_PATH, "a") book_path = work_dict["filepath"] with open(book_path, "r", encoding="utf-8") as f: work_html = BeautifulSoup(f, features="lxml") pages = work_html.find(class_="dropdown-content") pages = [] if pages == None else pages.findChildren("li") pages = [ch.a["href"] for ch in pages] # allow for single-page no dropdown works (e.g. Hugo Salus - Der Spiegel) pages = [book_path] if len(pages) == 0 else pages chapter_idx = 0 chapters = [] for page_idx, page in enumerate(pages): page_path = os.path.normpath(os.path.join(os.path.dirname(book_path), page)) with open(page_path, "r", encoding="utf-8") as f: page_html = BeautifulSoup(f, features="lxml") # skip first page if < 300 words (titlepage, not a real chapter) if page_idx == 0: raw_paragraphs = page_html.find_all("p") raw_paragraphs = [tag_to_text(p) for p in raw_paragraphs] raw_paragraphs = [ p.strip() for p in raw_paragraphs if not p.isspace() and not p == "" ] word_count = sum([len(p.split(" ")) for p in raw_paragraphs]) if word_count < TITLEPAGE_WORD_COUNT_CUTOFF: continue # skip dedication chapters if page_path.endswith("dedication.html"): continue if titlepage_info: titlepage_info_dict = { "page_idx": page_idx, "filepath": page_path, "toc": page_html.find(True, class_="toc") is not None, "dedication_class": page_html.find(True, class_="dedication"), "titlepage": page_path.endswith("titlepage.html"), "dedication": page_path.endswith("dedication.html"), "paragraph_stats": [len(p.split(" ")) for p in raw_paragraphs], } TITLEPAGE_INFO.append(titlepage_info_dict) clean_page(page_html) chapter_headlines = page_html.find_all(is_headline_before_text) # can't safely assume that none-headline pages are new chapters # e.g. Christian Reuter - Schelmuffsky, Eufemia von Adlersfeld-Ballestrem - Der Maskenball in der Ca' Torcelli # append to previous chapter if len(chapter_headlines) == 0: paragraphs = page_html.find_all("p") paragraphs = [tag_to_text(p) for p in paragraphs] paragraphs = [ p.strip() for p in paragraphs if not p.isspace() and not p == "" ] if len(paragraphs) > 0: if chapter_idx == 0: chapter_dict = { "name": None, "idx": chapter_idx, "paragraphs": paragraphs, } chapters.append(chapter_dict) chapter_idx += 1 else: # concatenate to previous chapter # dont increment chapter idx chapters[chapter_idx - 1]["paragraphs"] = ( chapters[chapter_idx - 1]["paragraphs"] + paragraphs ) else: for ch in chapter_headlines: chapter_dict = {"name": ch.text, "idx": chapter_idx} paragraphs = [] # iterate through consecutive p-tags el = ch.find_next_sibling(True) while el != None and el.name == "p": paragraphs.append(tag_to_text(el)) el = el.find_next_sibling(True) # element is not P tag # for troubleshooting/finding edge cases: if el != None: current_el = el next_sibling = el.find_next_sibling(True) if ( not is_headline_before_text(current_el) and next_sibling != None and next_sibling.name == "p" ): print( f"SPACER FOUND: {current_el} -> {next_sibling}. Path: {page_path}", file=printf, ) # filter empty paragraphs paragraphs = [ p.strip() for p in paragraphs if not p.isspace() and not p == "" ] if len(paragraphs) > 0: chapter_dict["paragraphs"] = paragraphs chapters.append(chapter_dict) chapter_idx += 1 work_dict["chapters"] = chapters printf.close() def allowed_genre(tag: Tag) -> bool: return tag.name == "a" and re.sub(r"\s+", " ", tag.text) in GENRE_LIST if __name__ == "__main__": # cleanup log file with open(LOG_PATH, "w") as f: f.write("") if not os.path.isdir("corpus"): os.mkdir("corpus") parser = argparse.ArgumentParser( description="Parse dataset from raw GutenbergDE HTML." ) parser.add_argument( "base_path", type=str, help="path to the GutenbergDE folder, e.g. ~/gutenberg-edition16", ) parser.add_argument( "--titlepage-info", action="store_true", help="collect chapter statistics (default: False)", ) parser.add_argument( "--test-single", type=str, help="Path to a single book for testing purposes" ) args = parser.parse_args() if args.test_single is not None: work_dict = { "author": "Test Author", "title": "Test Title", "genre": "Test Genre", "webpath": "Test Path", "filepath": args.test_single, } parse_single_book(work_dict) with open("test_single_book_parse.json", "w", encoding="utf-8") as f: json.dump(work_dict, f, ensure_ascii=False) else: root_path = os.path.join(args.base_path, "info/texte/lesetips.html") with open(root_path, "r", encoding="ISO-8859-1") as f: soup = BeautifulSoup(f, features="lxml") fiction_genre_list = soup.find("p", string="Belletristik").find_next_sibling( "dl" ) genre_links = fiction_genre_list.find_all(allowed_genre) work_dicts = [] for genre_link in genre_links: anchor_id = genre_link["href"].split("#")[-1] book_list = soup.find("a", id=anchor_id).parent.find_next_sibling("dl") current = book_list.find(["dt", "dd"]) while current != None: # skip interspersed book covers if current.name == "dt" and current.find("img") != None: current = current.find_next_sibling("dt") else: # remove alphabetic marks in Romane, Novellen und Erzählungen alphabetic_marks = current.find_all("b") [am.decompose() for am in alphabetic_marks] author = normalize_author(current.text) book_link = current.find_next_sibling("dd").a title = book_link.text relative_path = book_link["href"] work_dict = { "author": author, "title": title, "genre": re.sub(r"\s+", " ", genre_link.text), "webpath": urljoin( "https://www.projekt-gutenberg.org/info/texte/allworka.html", relative_path, ), "filepath": os.path.normpath( os.path.join(os.path.dirname(root_path), relative_path) ), } work_dicts.append(work_dict) # continue loop current = current.find_next_sibling("dt") for work in tqdm(work_dicts): try: parse_single_book(work, titlepage_info=args.titlepage_info) if len(work["chapters"]) > 1: with open( f'corpus/{filename_from_path(work["filepath"])}', "w", encoding="utf-8", ) as f: json.dump(work, f, ensure_ascii=False) except UnicodeDecodeError: print("DECODE ERROR: ", work["filepath"]) except FileNotFoundError: print("FILE NOT FOUND: ", work["filepath"]) if args.titlepage_info: with open("non_book_chapter_data.json", "w", encoding="utf-8") as f: json.dump(TITLEPAGE_INFO, f, ensure_ascii=False)
import datetime as dt import os import pandas as pd import numpy as np import itertools from keras.models import Sequential from keras.layers import LSTM, Bidirectional, Dropout, Dense, Input from keras.callbacks import EarlyStopping, TensorBoard from keras.regularizers import l2 from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score from sklearn.model_selection import train_test_split import json import time from keras.src.callbacks import History from lstm_plotter import LSTMPlotter from lstm_database import LSTMDatabase from typing import Dict, Any, Tuple from datetime import datetime class Model: def __init__(self, model_type, params_json): self.model_type = model_type self.params_json = params_json self.input_folder = 'input' self.output_folder = self.get_output_folder_name() self.ticker_name = self.get_ticker_name() self.input_data = os.path.join(self.input_folder, 'csv_files', f'{self.get_ticker_name()}.csv') def get_output_folder_name(self): # return os.path.join('Volumes', 'DATA', 'lstmmodel', 'output') return 'output' @staticmethod def create_folder(folder_path: str): """ Create a folder. Parameters: - folder_path (str): The path to the folder to be created. """ if not os.path.exists(folder_path): try: os.makedirs(folder_path) # print(f"Folder '{folder_path}' created successfully.") except Exception as e: print(f"An error occurred while creating folder '{folder_path}': {e}") exit(1) else: print(f"Folder '{folder_path}' already exists.") def create_initial_folders(self): """ Create initial folders for output. """ self.ticker_path = os.path.join(self.output_folder, self.ticker_name) self.fig_path = os.path.join(self.ticker_path, "fig") self.logs_path = os.path.join(self.ticker_path, "logs") self.model_path = os.path.join(self.ticker_path, "model") # TODO - Make this code idiotproof by using lists below. # fig_folders = ["training_validation_loss", "inferences_and_predictions", "future_predictions", "residual"] # logs_folders = ['my_logs'] # model_folders = [] folders = { self.ticker_path: { "fig": { "training_validation_loss": None, "inferences_and_predictions": None, "future_predictions": None, "residual": None }, "logs": { "my_logs": None }, "model": None } } try: for folder, subfolders in folders.items(): try: Model.create_folder(folder) except Exception as e: print(f"An error occurred while creating folder '{folder}': {e}") for subfolder, subsubfolders in subfolders.items(): subfolder_path = os.path.join(folder, subfolder) try: Model.create_folder(subfolder_path) except Exception as e: print(f"An error occurred while creating folder '{subfolder_path}': {e}") if subsubfolders: for subsubfolder in subsubfolders: try: Model.create_folder(os.path.join(subfolder_path, subsubfolder)) except Exception as e: print(f"An error occurred while creating folder '{os.path.join(subfolder_path, subsubfolder)}': {e}") print("All initial folders created successfully") except Exception as e: print(f"An error occurred while creating initial folders: {e}") exit(1) @staticmethod def save_to_csv(df: pd.DataFrame, filename: str) -> str: """ Saves a pandas DataFrame to a CSV file. If the file already exists, it creates a new file with an incremented suffix. Parameters: - df (pandas.DataFrame): The DataFrame to save to CSV. - filename (str): The name of the file to save the DataFrame to. Returns: - str: The final filename where the DataFrame was saved. """ try: if os.path.exists(filename): base, ext = os.path.splitext(filename) i = 2 while os.path.exists(f"{base}{i}{ext}"): i += 1 filename = f"{base}{i}{ext}" df.to_csv(filename, index=False) return filename except Exception as e: print(f"An error occurred when saving dataframe to {filename} file: {str(e)}") @staticmethod def dict_to_tuple(dict: dict) -> tuple: """ Convert a dictionary to a tuple. Parameters: - dict (dict): The dictionary to convert. Returns: - tuple: The tuple containing dictionary values. """ return tuple(dict.values()) def load_params(self): """ Load parameters from a JSON file. This function loads parameters required for the model and input data from a JSON file. Returns: None Raises: FileNotFoundError: If the JSON file specified in self.params_json does not exist. KeyError: If the required keys are not found in the loaded JSON. """ # Error validation for file existence if not os.path.exists(self.params_json): raise FileNotFoundError(f"JSON file '{self.params_json}' not found.") params = Model.load_json_data(self.params_json) # Type validation for params if not isinstance(params, dict): raise TypeError("Expected 'params' to be a dictionary.") # Type validation for keys required_keys = ['model_params', 'data', 'database_name'] for key in required_keys: if key not in params: raise KeyError(f"Key '{key}' not found in the loaded JSON.") # Assigning values to class attributes self.model_params = params['model_params'] self.input_params = params['data'] self.database_name = os.path.join(self.output_folder, params['database_name']) @staticmethod def load_csv(file_path: str) -> pd.DataFrame: """ Loads a CSV file into a pandas DataFrame. Parameters: - file_path (str): The path to the CSV file to load. Returns: - pandas.DataFrame: The loaded DataFrame. Raises: - FileNotFoundError: If the file specified by file_path does not exist. - Exception: For any other exceptions that occur during file loading. """ try: df = pd.read_csv(file_path) return df except FileNotFoundError as e: raise FileNotFoundError(f"File '{file_path}' not found. Detail: {str(e)}") except Exception as e: print(f"An error occurred in load_csv function: {e}") exit(1) def get_input_data(self) -> pd.DataFrame: try: df = pd.read_csv(self.input_data) df = self.split_input_data(df) # Converting date column to datetime to fix the x axis dates on the graphs. Store them as pd.datetime instead of str. df['date'] = pd.to_datetime(df['date']) # Extracting close data self.close_data = df[['close']] # print(f"close_data shape: {self.close_data.shape}") return df except Exception as e: print(f"An error occurred when getting input data: {str(e)}") exit(1) def split_input_data(self, input_data: pd.DataFrame) -> pd.DataFrame: try: # split last time_step element for residual calculations max_time_step = max([x for x in self.model_params['time_step'] if isinstance(x, int)]) model_df, control_df = Model.split_df(input_data, max_time_step) control_filename = os.path.join(self.ticker_path, f'{self.ticker_name}_control_data.csv') self.control_file = Model.save_to_csv(control_df, control_filename) return model_df except Exception as e: print(f"An error occurred when splitting input data: {str(e)}") exit(1) @staticmethod def split_df(df: pd.DataFrame, n: int): # Check if n is within the bounds of the DataFrame length try: if n >= len(df): print("Error: The given value of n is greater than or equal to the length of the DataFrame.") exit(1) # Split the DataFrame df1 = df.iloc[:-n] df2 = df.iloc[-n:] return df1, df2 except Exception as e: print(f"An error occurred when splitting the df: {str(e)}") exit(1) def get_ticker_name(self) -> str: """ Get the ticker name based on input parameters. This function constructs the ticker name using security, interval, and data_type from input_params. Returns: str: The constructed ticker name. """ try: self.load_params() # Retrieving required parameters from input_params security = self.input_params['security'] interval = self.input_params['interval'] data_type = self.input_params['data_type'] # Constructing the ticker name return f"{security}_{interval}_{data_type}" except KeyError as e: raise KeyError(f"KeyError: {e}. Required key not found in input_params.") from e except Exception as e: raise Exception(f"An error occurred while constructing the ticker name: {e}") from e @staticmethod def load_json_data(json_file: str) -> dict: """ Load parameters from a JSON file. Parameters: - json_file (str): Path to the JSON file containing parameters. Returns: - dict: Dictionary containing parameter configurations. """ try: with open(json_file, 'r') as file: params = json.load(file) return params except FileNotFoundError: print(f"File '{json_file}' not found.") exit(1) except json.JSONDecodeError: print(f"Error decoding JSON in file '{json_file}'. Please check the file format.") exit(1) except Exception as e: print(f"An error occurred in load_json_data function: {e}") exit(1) @staticmethod def generate_dataset(dataset: np.ndarray, time_step: int) -> tuple[np.ndarray, np.ndarray]: """ Generate input-output pairs for LSTM training from the dataset. Parameters: - dataset (numpy.ndarray): Input dataset. - time_step (int): Number of time steps to use for each input sequence. Returns: - numpy.ndarray, numpy.ndarray: Input-output pairs for LSTM training. """ assert isinstance(dataset, np.ndarray), "Input dataset must be a numpy array." assert isinstance(time_step, int) and time_step > 0, "time_step must be a positive integer." try: X, y = [], [] # TODO - Evaluate which one is better choice # for i in range(len(dataset)-2*time_step) # I removed the -1. for i in range(len(dataset) - 2 * time_step - 1): X.append(dataset[i:(i + time_step), 0]) y.append(dataset[(i + time_step):(i + 2 * time_step), 0]) X, y = np.array(X), np.array(y) X = X.reshape(X.shape[0], X.shape[1], 1) # X.reshape(X.shape[0], time_step, X.shape[1]) # Alternate code, with same output according to GPT return X, y except Exception as e: print(f"An error occurred in generate_dataset: {e}") exit(1) def prepare_model(self, params: Dict[str, Any]) -> MinMaxScaler: """ Prepare data and scaler for the model training. Parameters: - params (dict): Parameters for data preparation and model training. Returns: - sklearn.preprocessing.MinMaxScaler: Scaler used for data normalization. """ assert isinstance(params, dict), "params must be a dictionary." assert 'train_rate' in params and 'time_step' in params, "train_rate and time_step are required parameters in params." train_data, test_data = train_test_split(self.close_data.values.reshape(-1, 1), train_size=params['train_rate'], shuffle=False) # # Original code, CHANGED, but they return the exact same results # train_size = int(len(self.close_data) * params['train_rate']) # train_data = np.array(self.close_data[:train_size]) # test_data = np.array(self.close_data[train_size:]) scaler = MinMaxScaler() self.train_data_scaled = scaler.fit_transform(train_data) self.test_data_scaled = scaler.transform(test_data) # Generate datasets self.X_train, self.y_train = self.generate_dataset(self.train_data_scaled, params['time_step']) self.X_test, self.y_test = self.generate_dataset(self.test_data_scaled, params['time_step']) return scaler def build_model(self, params: Dict[str, Any]) -> Sequential: """ Build a neural network model based on the provided parameters. Parameters: - params (Dict[str, any]): Parameters for building the model. Returns: - keras.models.Sequential: Compiled neural network model. """ assert isinstance(params, dict), "params must be a dictionary." assert 'dropout_rate' in params and 'neuron' in params and 'activation' in params \ and 'kernel_regularizer' in params and 'loss_function' in params and 'optimizer' in params \ and 'time_step' in params, "Required parameters are missing in params." core_layers = [ Input(shape=(None, 1)), Dropout(params['dropout_rate'], name="dropout_1"), Dense(params['time_step'], name="dense_1") ] if self.model_type == 'BILSTM': core_layers.insert(1, Bidirectional(LSTM(params['neuron'], activation=params['activation'], kernel_regularizer=l2(params['kernel_regularizer'])), name="bilstm_1")) elif self.model_type == 'LSTM': core_layers.insert(1, LSTM(params['neuron'], activation=params['activation'], kernel_regularizer=l2(params['kernel_regularizer']), name="lstm_1")) else: print(f"Unknown model_type: {self.model_type}") exit(0) model = Sequential(core_layers) model.compile(loss=params['loss_function'], optimizer=params['optimizer']) return model def train_model(self, model: Sequential, params: Dict[str, Any], run_name: str) -> History: """ Train a neural network model. Parameters: - model (Sequential): The neural network model to be trained. - params (Dict[str, Any]): Parameters for training the model. - run_name (str): Name of the training run for logging purposes. Returns: - keras.src.callbacks.History: Training history containing loss and metric values. """ assert isinstance(params, dict), "params must be a dictionary." assert 'patience' in params and 'epoch' in params and 'batch_size' in params, "Required parameters are missing in params." early_stopping = EarlyStopping(monitor='val_loss', patience=params['patience'], restore_best_weights=True) log_dir = os.path.join(self.logs_path, run_name) logger = TensorBoard( log_dir=log_dir, histogram_freq=1, write_graph=True, write_images=True, # write_steps_per_second=True, update_freq='epoch', profile_batch=f"0, {params['batch_size']}" ) history = model.fit(self.X_train, self.y_train, validation_data=(self.X_test, self.y_test), epochs=params['epoch'], batch_size=params['batch_size'], verbose=1, callbacks=[early_stopping, logger]) return history def evaluate_model(self, model: Sequential, scaler: MinMaxScaler) -> Dict[str, np.ndarray]: """ Evaluate a trained model. Parameters: - model (keras.models.Sequential): The trained neural network model to be evaluated. - scaler (sklearn.preprocessing.MinMaxScaler): The scaler used for normalization during training. Returns: - Dict[str, np.ndarray]: A dictionary containing evaluation results, including train and test predictions and test loss. """ train_predict = model.predict(self.X_train) test_predict = model.predict(self.X_test) train_predict = scaler.inverse_transform(train_predict) test_predict = scaler.inverse_transform(test_predict) test_loss = model.evaluate(self.X_test, self.y_test.reshape(self.y_test.shape[0], self.y_test.shape[1])) return { 'train_predict': train_predict, 'test_predict': test_predict, 'test_loss': test_loss } def train_test_dates(self, df: pd.DataFrame, params: Dict[str, Any], model_evaluation: dict) -> Tuple[pd.Series, pd.Series]: """ Extract train and test dates. Parameters: - df (pd.DataFrame): DataFrame containing date information. - params (dict): Parameters used for modeling. - model_evaluation (dict): Evaluation results of the trained model. Returns: - Tuple[pd.Series, pd.Series]: Train and test dates. """ time_step = params['time_step'] train_predict = model_evaluation['train_predict'] test_predict = model_evaluation['test_predict'] train_date = df['date'].iloc[time_step : time_step + len(train_predict)] # TODO - Take a good look at the line below, make sure that it's right and optimized. test_date = df['date'].iloc[len(train_predict) + 2*time_step + time_step : len(train_predict) + 2*time_step + time_step + len(test_predict)] return train_date, test_date def future_predicts(self, model: Sequential, params: Dict[str, Any], scaler: MinMaxScaler) -> np.ndarray: """ Generate future predictions using the trained model. Parameters: - model (keras.models.Sequential): The trained neural network model. - params (dict): Parameters used for modeling. - scaler (sklearn.preprocessing.MinMaxScaler): The scaler used for normalization during training. Returns: - np.ndarray: Future predictions. """ last_data = self.test_data_scaled[-params['time_step']:] last_data = last_data.reshape(1, params['time_step'], 1) predictions = model.predict(last_data) predictions = predictions.reshape(-1, 1) predictions = scaler.inverse_transform(predictions) return predictions def calculate_metrics(self, y_test: np.ndarray, predictions: np.ndarray) -> Dict[str, float]: """ Calculate evaluation metrics. Parameters: - y_test: True target values. - predictions: Predicted values. Returns: - Dict[str, float]: Evaluation metrics including MAE, MSE, and R-squared. """ # Calculate metrics mae_score = mean_absolute_error(y_test, predictions) mse_score = mean_squared_error(y_test, predictions) r2 = r2_score(y_test, predictions) return { 'mae_score': mae_score, 'mse_score': mse_score, 'r2_score': r2 } def append_to_times_and_epochs(self, folder_path: str, index: int, total_combinations: int, elapsed_minutes: int, elapsed_seconds: int, params_str: str, saved_data: Dict[str, Any]): """ Append the progress information to 'times_and_epochs.txt'. Parameters: - folder_path (str): The path to the folder containing the log file. - index (int): Current iteration index. - total_combinations (int): Total number of combinations. - elapsed_minutes (int): Current iteration elapsed_minutes. - elapsed_seconds (int): Current iteration elapsed_seconds. - params_str (str): String representation of model parameters. - saved_data (Dict[str, Any]): Dictionary containing saved data. """ # Assert statements to validate input parameters assert isinstance(folder_path, str), "folder_path must be a string." assert isinstance(index, int), "index must be an integer." assert isinstance(total_combinations, int), "total_combinations must be an integer." assert isinstance(elapsed_minutes, int), "elapsed_minutes must be an integer." assert isinstance(elapsed_seconds, int), "elapsed_seconds must be an integer." assert isinstance(params_str, str), "params_str must be a string." assert isinstance(saved_data, dict), "saved_data must be a dictionary." try: text_file = os.path.join(folder_path, f'{self.ticker_name}_logs.txt') epoch_used, epoch = saved_data['training_data']['epoch_used'], saved_data['params_dict']['epoch'] current_time = LSTMPlotter.get_current_time() with open(text_file, 'a+') as file: file.write(f"[{self.model_type}] {index}/{total_combinations} finished in {elapsed_minutes}m {elapsed_seconds}s. Params: {params_str} ({epoch_used}/{epoch} epoch. Current time: {current_time})\n") print(f"Data appended to {text_file} successfully.") except Exception as e: print(f"An error occurred while appending data to {text_file}: {str(e)}") @staticmethod def calculate_times(start_time: float, end_time: float) -> dict: """ Calculate various time-related values based on start and end timestamps. Parameters: - start_time (float): Start timestamp. - end_time (float): End timestamp. Returns: - dict: Dictionary containing calculated time values. """ assert isinstance(start_time, float), "start_time must be an float." assert isinstance(end_time, float), "end_time must be an float." try: # Convert timestamps to datetime objects start_date = datetime.utcfromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S') end_date = datetime.utcfromtimestamp(end_time).strftime('%Y-%m-%d %H:%M:%S') except Exception as e: print("An error occurred when converting timestamps to dates: ", e) return None try: # Calculate total time in seconds total_time = end_time - start_time except Exception as e: print("An error occurred when calculating total time: ", e) return None return { 'start_timestamp': start_time, 'end_timestamp': end_time, 'total_time': total_time, 'start_date': start_date, 'end_date': end_date } def get_control_data(self, params): control_df = Model.load_csv(self.control_file) control_df = control_df.head(params['time_step']) control_df = control_df[['close']] actual_values = control_df.values.reshape(-1, 1) return actual_values @staticmethod def determine_frequency(last_date: pd.Timestamp, interval: str) -> str: """ Determine the frequency of timestamps based on the interval string. Args: last_date (pandas.Timestamp): timestamp of the last date of the data interval (str): Interval string in the format "{x}{y}", where "x" is an integer and "y" represents the interval type. Returns: str: Frequency of timestamps. """ try: # Validate input data type if not isinstance(interval, str): raise TypeError("Interval must be a string.") if not interval: raise ValueError("Invalid interval format. It should not be empty.") # Parse the integer part x = '' for char in interval: if char.isdigit(): x += char else: break assert int(x) >= 1, 'Integer part of interval should be at least 1.' # Parse the string part y = interval[len(x):] # Mapping of interval type to frequency string interval_mapping = { 'mo': 'M', # Monthly 'w': 'W', # Weekly 'd': 'D', # Calendar Daily # Use `B` for business day 'h': 'h', # Hourly 'm': 'min', # Minutely 's': 's', # Secondly 'ms': 'ms' # Millisecondly } x = "" if int(x) == 1 else int(x) if y == 'w': # Get the day of the week for the last date day_of_week = last_date.day_name()[:3].upper() return f'{x}W-{day_of_week}' elif y in interval_mapping: return f"{x}{interval_mapping[y]}" else: raise ValueError(f"Invalid interval type: {y}") except TypeError as te: print(f"TypeError: {te}") except ValueError as ve: print(f"ValueError: {ve}") except Exception as e: print('An error occurred when determining frequency: ', e) def calculate_residuals(self, predictions: np.ndarray, params: Dict[str, Any]): try: # control_df = Model.load_csv(self.control_file) # control_df = control_df.head(params['time_step']) # control_df = control_df[['close']] # if len(control_df) != len(predictions): # print("Error: Lengths of control_df and predictions do not match.") # exit(1) # # Assuming control_df has only one column actual_values = self.get_control_data(params) residuals = actual_values - predictions residuals_percentage = (residuals / actual_values) * 100 # sum_residuals = np.sum(residuals) # sum_abs_residuals = np.sum(np.abs(residuals)) # sum_residual_percentage = np.sum(residuals_percentage) # sum_abs_residual_percentage = np.sum(np.abs(residuals_percentage)) return { 'residuals': residuals, 'residuals_percentage': residuals_percentage, # 'sum_residuals': sum_residuals, # 'sum_abs_residuals': sum_abs_residuals, # 'sum_residual_percentage': sum_residual_percentage, # 'sum_abs_residual_percentage': sum_abs_residual_percentage } except Exception as e: print(f"An error occurred when calculating residuals: {str(e)}") def save_results(self, times: dict, history: History, model_evaluation: np.ndarray, evaluation_metrics: Dict[str, Any], predictions: np.ndarray, residuals: np.ndarray, params: Dict[str, Any]) -> dict: """ Saves model data to the database. Parameters: - Various parameters related to model configuration and training. """ data = { 'params_dict': params, 'training_data': { 'start_timestamp': times['start_timestamp'], 'end_timestamp': times['end_timestamp'], 'total_time': times['total_time'], 'start_date': times['start_date'], 'end_date': times['end_date'], 'epoch_used': len(history.history['loss']), 'test_loss': model_evaluation['test_loss'], 'mae_score': evaluation_metrics['mae_score'], 'mse_score': evaluation_metrics['mse_score'], 'r2_score': evaluation_metrics['r2_score'], 'training_loss': json.dumps(history.history['loss']), 'validation_loss': json.dumps(history.history['val_loss']), 'close_data': json.dumps([item for sublist in self.close_data.values.tolist() for item in sublist]), 'train_predict': json.dumps(model_evaluation['train_predict'].tolist()), 'test_predict': json.dumps(model_evaluation['test_predict'].tolist()), 'predictions': json.dumps([item for sublist in predictions.tolist() for item in sublist]), 'residuals': json.dumps(residuals['residuals'].tolist()) }, 'table_name': f'{self.ticker_name}_{self.model_type}' } return data def run(self): fig_folders = ["training_validation_loss", "inferences_and_predictions", "future_predictions", "residual"] logs_folders = ['my_logs'] self.load_params() self.create_initial_folders() df = self.get_input_data() param_keys = list(self.model_params.keys()) param_values = list(self.model_params.values()) param_combinations = [dict(zip(param_keys, values)) for values in itertools.product(*param_values)] # param_combinations = list(itertools.product(*self.model_params.values())) total_combinations = len(param_combinations) print(f"Total combinations: {total_combinations} different combinations") for i, params in enumerate(param_combinations): params_str = str(Model.dict_to_tuple(params)) RUN_NAME = f"run_{self.model_type}_{params_str}" start_time = time.time() scaler = self.prepare_model(params) # plotter = LSTMPlotter() # - - - - - - - - - - - - - - - - - - - M O D E L - - - - - - - - - - - - - - - - - - - - - - - - - - - - - model = self.build_model(params) history = self.train_model(model, params, RUN_NAME) tra_val_path = os.path.join(self.fig_path, fig_folders[0]) LSTMPlotter.plot_training_validation_loss(tra_val_path, self.model_type, i+1, params_str, history.history['loss'], history.history['val_loss']) # - - - - - - - - - - - - I N F E R E N C E S A N D P R E D I C T I O N S - - - - - - - - - - - - - - - - - - model_evaluation = self.evaluate_model(model, scaler) evaluation_metrics = self.calculate_metrics(self.y_test, model_evaluation['test_predict']) train_date, test_date = self.train_test_dates(df, params, model_evaluation) close_pred_path = os.path.join(self.fig_path, fig_folders[1]) LSTMPlotter.plot_close_and_predictions(close_pred_path, self.model_type, i+1, params_str, df, self.close_data, train_date, model_evaluation['train_predict'], test_date, model_evaluation['test_predict']) # - - - - - - - - - - - - - - - - - - - - F U T U R E P R E D I C T I O N S - - - - - - - - - - - - - - - - - - predictions = self.future_predicts(model, params, scaler) last_date = df['date'].iloc[-1] freq = Model.determine_frequency(last_date, self.input_params['interval']) future_dates = pd.date_range(start=last_date, periods=params['time_step']+1, freq=freq)[1:] future_pred_path = os.path.join(self.fig_path, fig_folders[2]) control_data = self.get_control_data(params) # LSTMPlotter.plot_future_predictions(future_pred_path, self.model_type, i+1, params_str, future_dates, predictions) LSTMPlotter.plot_future_predictions(future_pred_path, self.model_type, i+1, params_str, future_dates, control_data, predictions) residuals = self.calculate_residuals(predictions, params) residuals_path = os.path.join(self.fig_path, fig_folders[3]) LSTMPlotter.plot_residuals(residuals_path, self.ticker_name, self.model_type, i+1, params_str, predictions, residuals['residuals'], residuals['residuals_percentage']) end_time = time.time() times = self.calculate_times(start_time, end_time) data = self.save_results(times, history, model_evaluation, evaluation_metrics, predictions, residuals, params) db = LSTMDatabase(self.database_name) db.save_data(data['params_dict'], data['training_data'], data['table_name']) # Convert elapsed time to minutes and seconds elapsed_time_seconds = end_time - start_time elapsed_minutes = int(elapsed_time_seconds // 60) elapsed_seconds = int(elapsed_time_seconds % 60) current_time = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print(f'{i+1}/{total_combinations} finished in {elapsed_minutes}m {elapsed_seconds}s. Current time: {current_time}') # Append progress information to file # text_file_folder = os.path.join(self.output_folder, self.ticker_name) model_path = os.path.join(self.model_path, f"{self.model_type}_{params_str}.keras") model.save(model_path) # append_to_times_and_epochs(i, total_combinations, params_str, elapsed_minutes, elapsed_seconds, current_time, data, self.model_type, text_file_folder, self.ticker_name) text_folder_path = os.path.join(self.logs_path, logs_folders[0]) self.append_to_times_and_epochs(text_folder_path, i+1, total_combinations, elapsed_minutes, elapsed_seconds, params_str, data)
import { View, Text, Image, TouchableOpacity } from 'react-native' import React from 'react' import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons' export const localRestaurants = [ { name: "Beachside Bar", image_url: "https://static.onecms.io/wp-content/uploads/sites/9/2020/04/24/ppp-why-wont-anyone-rescue-restaurants-FT-BLOG0420.jpg", categories: ["Cafe", "Bar"], price: "$$", reviews: 1244, rating: 4.5, }, { name: "Benihana", image_url: "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cmVzdGF1cmFudCUyMGludGVyaW9yfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80", categories: ["Cafe", "Bar"], price: "$$", reviews: 1244, rating: 3.7, }, { name: "India's Grill", image_url: "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cmVzdGF1cmFudCUyMGludGVyaW9yfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80", categories: ["Indian", "Bar"], price: "$$", reviews: 700, rating: 4.9, }, ]; const RestaurantItems = ({ navigation }) => { return ( <> {localRestaurants.map((item, index) => ( <TouchableOpacity key={index} activeOpacity={0.8} onPress= {() => navigation.navigate('RestaurantInfo', item)}> <View style={{ padding: 10, backgroundColor: 'white', marginTop: 7 }}> <RestaurantImage image={item.image_url} /> <RestaurantInfo restaurant={item} /> </View> </TouchableOpacity> ))} </> ) } export default RestaurantItems const RestaurantImage = ({ image }) => ( <> <Image source={{ uri: image }} style={{ width: '100%', height: 180, borderRadius: 10 }} /> <TouchableOpacity style={{ position: 'absolute', right: 20, top: 17 }}> <MaterialCommunityIcons name="heart-outline" size={30} color="white" /> </TouchableOpacity> </> ) const RestaurantInfo = ({ restaurant }) => ( <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 }}> <View> <Text style={{ fontSize: 15, fontWeight: 'bold' }}>{restaurant.name}</Text> <Text style={{ fontSize: 13, color: 'gray' }}>30-45 min</Text> </View> <View style={{ backgroundColor: '#eee', height: 35, width: 35, borderRadius: 30, alignItems: 'center', justifyContent: 'center' }}> <Text>{restaurant.rating}</Text> </View> </View> )
import 'package:application_edspert/core/themes/app_grayscale.dart'; import 'package:application_edspert/domain/entity/course/course_question_response_entity.dart'; import 'package:flutter/material.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../core/themes/app_colors.dart'; import '../../core/themes/app_fonts.dart'; class QuestionWidget extends StatefulWidget { final int index; final CourseQuestionDataEntity question; final bool isLastPage; final Function() onTap; const QuestionWidget({ Key? key, required this.index, required this.question, required this.onTap, required this.isLastPage, }) : super(key: key); @override State<QuestionWidget> createState() => _QuestionWidgetState(); } class _QuestionWidgetState extends State<QuestionWidget> { @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(16.w), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Soal Nomor ${widget.index + 1}', style: AppFonts.appFont.bodyMedium!.copyWith( color: AppGrayscale.placeholder, ), ), SizedBox(height: 12.h), if (widget.question.questionTitleImg != null) Image.network( widget.question.questionTitleImg, errorBuilder: (context, error, stackTrace) { return const Text( 'No IMG', ); }, ), Html( data: widget.question.questionTitle, style: { 'body': Style( textAlign: TextAlign.justify, fontSize: FontSize(12.sp), ), }, ), SizedBox(height: 12.h), GestureDetector( onTap: () { setState(() { widget.question.studentAnswer = 'A'; }); }, child: Container( decoration: BoxDecoration( color: widget.question.studentAnswer == 'A' ? AppColors.primary : AppGrayscale.off, borderRadius: BorderRadius.circular(10), border: Border.all( color: AppGrayscale.placeholder, ), ), child: Html( data: widget.question.optionA, style: { 'body': Style( padding: HtmlPaddings.symmetric(horizontal: 20.w), fontSize: FontSize(12.sp), alignment: Alignment.topLeft, width: Width(320.w), color: widget.question.studentAnswer == 'A' ? AppGrayscale.off : AppColors.primary, ), }, ), ), ), SizedBox(height: 8.h), GestureDetector( onTap: () { setState(() { widget.question.studentAnswer = 'B'; }); }, child: Container( decoration: BoxDecoration( color: widget.question.studentAnswer == 'B' ? AppColors.primary : AppGrayscale.off, borderRadius: BorderRadius.circular(10), border: Border.all( color: AppGrayscale.placeholder, ), ), child: Html( data: widget.question.optionB, style: { 'body': Style( padding: HtmlPaddings.symmetric(horizontal: 20.w), fontSize: FontSize(12.sp), alignment: Alignment.topLeft, width: Width(320.w), color: widget.question.studentAnswer == 'B' ? AppGrayscale.off : AppColors.primary, ), }, ), ), ), SizedBox(height: 8.h), GestureDetector( onTap: () { setState(() { widget.question.studentAnswer = 'C'; }); }, child: Container( decoration: BoxDecoration( color: widget.question.studentAnswer == 'C' ? AppColors.primary : AppGrayscale.off, borderRadius: BorderRadius.circular(10), border: Border.all( color: AppGrayscale.placeholder, ), ), child: Html( data: widget.question.optionC, style: { 'body': Style( padding: HtmlPaddings.symmetric(horizontal: 20.w), fontSize: FontSize(12.sp), alignment: Alignment.topLeft, width: Width(320.w), color: widget.question.studentAnswer == 'C' ? AppGrayscale.off : AppColors.primary, ), }, ), ), ), SizedBox(height: 8.h), GestureDetector( onTap: () { setState(() { widget.question.studentAnswer = 'D'; }); }, child: Container( decoration: BoxDecoration( color: widget.question.studentAnswer == 'D' ? AppColors.primary : AppGrayscale.off, borderRadius: BorderRadius.circular(10), border: Border.all( color: AppGrayscale.placeholder, ), ), child: Html( data: widget.question.optionD, style: { 'body': Style( padding: HtmlPaddings.symmetric(horizontal: 20.w), fontSize: FontSize(12.sp), alignment: Alignment.topLeft, width: Width(320.w), color: widget.question.studentAnswer == 'D' ? AppGrayscale.off : AppColors.primary, ), }, ), ), ), SizedBox(height: 8.h), GestureDetector( onTap: () { setState(() { widget.question.studentAnswer = 'E'; }); }, child: Container( width: double.infinity, decoration: BoxDecoration( color: widget.question.studentAnswer == 'E' ? AppColors.primary : AppGrayscale.off, borderRadius: BorderRadius.circular(10), border: Border.all( color: AppGrayscale.placeholder, ), ), child: Html( data: widget.question.optionE, style: { 'body': Style( padding: HtmlPaddings.symmetric(horizontal: 20.w), fontSize: FontSize(12.sp), alignment: Alignment.topLeft, width: Width(320.w), color: widget.question.studentAnswer == 'E' ? AppGrayscale.off : AppColors.primary, ), }, ), ), ), SizedBox(height: 20.h), Align( alignment: Alignment.centerRight, child: ElevatedButton( onPressed: widget.onTap, style: ElevatedButton.styleFrom( backgroundColor: AppColors.primary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(14), ), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), child: widget.isLastPage ? const Text('Kumpulin') : const Text('Selanjutnya'), ), ), ), ], ), ), ); } }
*** PROGRAM 7.7 *** *** DIFFERENTIAL EQUATION *** * PROGRAM F7X7 REAL FUNC EXTERNAL FUNC *微分方程式を解く CALL RUNGE(FUNC,0.0,1.0,2.0,0.2) * STOP END ***FUNC:dy/dx REAL FUNCTION FUNC(X,Y) REAL X,Y * FUNC=(Y*Y-2.0*X)/(Y*Y+X) * RETURN END ***SUB:ルンゲクッタ法 SUBROUTINE RUNGE(FUNC,X0,Y0,XEND,H) REAL FUNC,X0,Y0,XEND,H,X,Y,K1,K2,K3,K4 *ヘッダ行の出力 WRITE(6,10) 10 FORMAT(' ',6X,'X',13X,'Y',11X,'F(X,Y)') * X=X0 Y=Y0 *近似値を徐々に求めていく 20 CONTINUE WRITE(6,30)X,Y,FUNC(X,Y) 30 FORMAT(' ',3E14.6) IF(X .GT. XEND)RETURN K1=H*FUNC(X,Y) K2=H*FUNC(X+H/2.0,Y+K1/2.0) K3=H*FUNC(X+H/2.0,Y+K2/2.0) K4=H*FUNC(X+H,Y+K3) Y=Y+(K1+2.0*(K2+K3)+K4)/6.0 X=X+H GO TO 20 END
package pl.devcezz.day20; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class JurassicJigsawSecond { // private static final String[][] MONSTER = new String[][] { // { " ", " ", "#", "#" }, // { " ", " ", " ", "#" }, // { "#", "#", "#", " " } // }; private static final String[][] MONSTER = new String[][] { { " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "#", " " }, { "#", " ", " ", " ", " ", "#", "#", " ", " ", " ", " ", "#", "#", " ", " ", " ", " ", "#", "#", "#" }, { " ", "#", " ", " ", "#", " ", " ", "#", " ", " ", "#", " ", " ", "#", " ", " ", "#", " ", " ", " " } }; public static List<String> readData(String path) { try { return Files.readAllLines(Path.of(path)); } catch (IOException e) { throw new IllegalArgumentException("Not found file: " + path); } } public static void main(String[] args) { List<Tile> tiles = JurassicJigsawFirst.matchPiecesOfMap("2020-java/data/day20/task.txt"); String[][] map = makeMap(tiles); boolean properPosition = false; for (int i = 0; i < 8; i++) { System.out.println(i); print(map); for (int topLeftMonsterY = 0; topLeftMonsterY < map.length - MONSTER.length + 1; topLeftMonsterY++) { for (int topLeftMonsterX = 0; topLeftMonsterX < map[0].length - MONSTER[0].length + 1; topLeftMonsterX++) { boolean match = true; for (int y = 0; y < MONSTER.length; y++) { for (int x = 0; x < MONSTER[0].length; x++) { if (MONSTER[y][x].equals("#") && !MONSTER[y][x].equals(map[topLeftMonsterY + y][topLeftMonsterX + x])) { match = false; break; } } } if (match) { properPosition = true; for (int y = 0; y < MONSTER.length; y++) { for (int x = 0; x < MONSTER[y].length; x++) { if (MONSTER[y][x].equals("#")) { map[topLeftMonsterY + y][topLeftMonsterX + x] = "O"; } } } } } } if (properPosition) { print(map); break; } if (i == 3) { map = flip(map); } else { map = rotate(map); } } System.out.println(count(map)); } private static String[][] rotate(String[][] map) { String[][] rotated = new String[map.length][map[0].length]; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[0].length; j++) { rotated[j][map[0].length - 1 - i] = map[i][j]; } } return rotated; } private static String[][] flip(String[][] map) { String[][] flipped = new String[map.length][map[0].length]; for (int i = 0; i < map[0].length; i++) { for (int j = 0; j < map[0].length; j++) { flipped[i][map[0].length - 1 - j] = map[i][j]; } } return flipped; } private static String[][] makeMap(List<Tile> tiles) { Tile first = tiles.stream() .filter(tile -> tile.neighbours.size() == 2 && tile.neighbours.get(Neighbour.DOWN) != null && tile.neighbours.get(Neighbour.RIGHT) != null) .findFirst() .orElseThrow(IllegalArgumentException::new); int sqrt = (int) Math.sqrt(tiles.size()); int side = tiles.get(0).pieceOfMap[0].length - 2; String[][] map = new String[sqrt * side][sqrt * side]; int x = 0; int y = 0; while (first != null) { Tile right = first; while (right != null) { for (int i = 0; i < side; i++) { for (int j = 0; j < side; j++) { map[x + i][y + j] = right.pieceOfMap[i + 1][j + 1]; } } y += side; Integer rightId = right.neighbours.get(Neighbour.RIGHT); if (rightId == null) { break; } right = tiles.stream() .filter(tile -> tile.id == rightId) .findFirst() .orElse(null); } x += side; y = 0; Integer downId = first.neighbours.get(Neighbour.DOWN); if (downId == null) { break; } first = tiles.stream() .filter(tile -> tile.id == downId) .findFirst() .orElse(null); } return map; } public static void print(String[][] map) { for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { System.out.print(map[i][j]); } System.out.println(); } System.out.println(); } public static long count(String[][] map) { long count = 0; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { if (map[i][j].equals("#")) { count++; } } } return count; } }
<!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>esm</title> </head> <body> <script type="module"> // 导出的是接口的概念 import { foo, bar, baz } from './esm-export.js' import { x, y, z } from './esm-export.js' // import { default as d } from './esm-export.js' // 下面是上面的缩写 import d from './esm-export.js' // 上面都是接口,下面是整个模块的导出 import * as all from './esm-export.js' // 转发 import { n } from './esm-export-import.js' console.log(foo, bar, baz) console.log(x, y, z) console.log(d) console.log(all) console.log(n) </script> </body> </html>
#include "common.h" // 使用二维dp数组 void test() { vector<int> weight = { 1, 3, 4 }; vector<int> value = { 15, 20, 30 }; int bag_size = 4; vector<vector<int>> dp(weight.size() + 1, vector<int>(bag_size + 1, 0)); dp[0][0] = 0; // or 1 in some case. for (int i = 1; i <= weight.size(); ++i) { // start from 1 for (int j = 0; j <= bag_size; ++j) { // start from 0 if (weight[i-1] > j) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i-1]] + value[i]); } } cout << dp; } // 使用一维滚动dp数组 (更好) void test1(){ vector<int> weight = {1, 3, 4}; vector<int> value = {15, 20, 30}; int bagWeight = 4; // 初始化 vector<int> dp(bagWeight + 1, 0); dp[0] = 0; // or 1 in some case. for (int i = 0; i < weight.size(); i++) { // 遍历物品 start from 0 for (int j = bagWeight; j >= weight[i]; j--) { // 遍历背包容量 start from back dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); } } cout << dp[bagWeight] << endl;
import 'dart:convert'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:geocoding/geocoding.dart'; import 'package:geolocator/geolocator.dart'; import 'package:homestayraya/config.dart'; import 'package:homestayraya/modals/homestay.dart'; import 'package:homestayraya/modals/user.dart'; import 'package:homestayraya/views/screens/loginscreen.dart'; import 'package:homestayraya/views/screens/newhomestay.dart'; import 'package:homestayraya/views/screens/registrationscreen.dart'; import 'package:homestayraya/views/shared/mainmenu.dart'; import 'package:intl/intl.dart'; import 'package:http/http.dart' as http; class OwnerScreen extends StatefulWidget { final User user; const OwnerScreen({super.key, required this.user}); @override State<OwnerScreen> createState() => _OwnerScreenState(); } class _OwnerScreenState extends State<OwnerScreen> { var _lat, _lng; late Position _position; List<Homestay> homestayList = <Homestay>[]; String titlecenter = "Loading..."; var placemarks; final df = DateFormat('dd/MM/yyyy hh:mm a'); late double screenHeight, screenWidth, resWidth; int rowcount = 2; @override void initState() { super.initState(); _loadHomestays(); } @override void dispose() { homestayList = []; print("dispose"); super.dispose(); } @override Widget build(BuildContext context) { screenHeight = MediaQuery.of(context).size.height; screenWidth = MediaQuery.of(context).size.width; if (screenWidth <= 600) { resWidth = screenWidth; rowcount = 2; } else { resWidth = screenWidth * 0.75; rowcount = 3; } return WillPopScope( onWillPop: () async => false, child: Scaffold( appBar: AppBar(title: const Text("Owner", style: TextStyle(fontSize: 25, fontStyle: FontStyle.normal),), actions: [ IconButton(onPressed: _registrationForm, icon: const Icon(Icons.app_registration)), IconButton(onPressed: _loginForm, icon: const Icon(Icons.login)), IconButton(onPressed: _addHomestay, icon: const Icon(Icons.add_box_outlined))], ), body: homestayList.isEmpty ? Center( child: Text(titlecenter, style: const TextStyle( fontSize: 22, fontWeight: FontWeight.bold))) : Column( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text( "Your current homestay (${homestayList.length} found)", style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold), ), ), const SizedBox( height: 4, ), Expanded( child: GridView.count( crossAxisCount: rowcount, children: List.generate(homestayList.length, (index) { return Card( elevation: 8, child: InkWell( onTap: () { // _showDetails(index); }, onLongPress: () { _deleteDialog(index); }, child: Column(children: [ const SizedBox( height: 8, ), Flexible( flex: 6, child: CachedNetworkImage( width: resWidth / 2, fit: BoxFit.cover, imageUrl: "${Config.SERVER}/assets/homestayimages/${homestayList[index].homestayId}_1.png", placeholder: (context, url) => const LinearProgressIndicator(), errorWidget: (context, url, error) => const Icon(Icons.error), ), ), Flexible( flex: 4, child: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ Text( truncateString( homestayList[index] .homestayName .toString(), 15), style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold), ), const SizedBox(height: 4,), Text( truncateString( homestayList[index] .homestayAddress .toString(), 15), ), Text( "RM ${double.parse(homestayList[index].homestayPrice.toString()).toStringAsFixed(2)}"), ], ), )) ]), ), ); }), ), ) ], ), drawer: MainMenuWidget(user: widget.user,), ), ); } void _registrationForm() { Navigator.push(context, MaterialPageRoute(builder: (content) => const RegistrationScreen())); } void _loginForm() { Navigator.push(context, MaterialPageRoute(builder: (content) => const LoginScreen())); } Future<void> _addHomestay() async { if (widget.user.id == "0") { Fluttertoast.showToast( msg: "Please login/register", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, fontSize: 14.0); return; } if (await _checkPermissionGetLoc()) { Navigator.push( context, MaterialPageRoute( builder: (content) => NewHomestayScreen(position: _position, user: widget.user, placemarks: placemarks,))); } else { Fluttertoast.showToast( msg: "Please allow the app to access the location", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, fontSize: 14.0); return; } } Future<bool> _checkPermissionGetLoc() async { bool serviceEnabled; LocationPermission permission; serviceEnabled = await Geolocator.isLocationServiceEnabled(); if (!serviceEnabled) { return Future.error('Location services are disabled.'); } permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { Fluttertoast.showToast( msg: "Please allow the app to access the location", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, fontSize: 14.0); Geolocator.openLocationSettings(); return false; } } if (permission == LocationPermission.deniedForever) { Fluttertoast.showToast( msg: "Please allow the app to access the location", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, fontSize: 14.0); Geolocator.openLocationSettings(); return false; } _position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.best); try { placemarks = await placemarkFromCoordinates( _position.latitude, _position.longitude); } catch (e) { Fluttertoast.showToast( msg: "Error in fixing your location. Make sure internet connection is available and try again.", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, fontSize: 14.0); return false; } return true; } void _loadHomestays() { if (widget.user.id == "0") { //check if the user is registered or not Fluttertoast.showToast( msg: "Please register an account first", //Show toast toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, fontSize: 14.0); return; //exit method if true } //if registered user, continue get request http .get( Uri.parse( "${Config.SERVER}/php/loadhomestays.php?userid=${widget.user.id}"), ) .then((response) { // wait for response from the request if (response.statusCode == 200) { //if statuscode OK var jsondata = jsonDecode(response.body); //decode response body to jsondata array if (jsondata['status'] == 'success') { //check if status data array is success var extractdata = jsondata['data']; //extract data from jsondata array if (extractdata['homestay'] != null) { //check if array object is not null homestayList = <Homestay>[]; //complete the array object definition extractdata['homestay'].forEach((v) { //traverse homestay array list and add to the list object array homestayList homestayList.add(Homestay.fromJson( v)); //add each homestay array to the list object array homestayList }); titlecenter = "Found"; } else { titlecenter = "No Homestay Available"; //if no data returned show title center homestayList.clear(); } } else { titlecenter = "No Homestay Available"; } } else { titlecenter = "No Homestay Available"; //status code other than 200 homestayList.clear(); //clear homestayList array } setState(() {}); //refresh UI }); } String truncateString(String str, int size) { if (str.length > size) { str = str.substring(0, size); return "$str..."; } else { return str; } } _deleteDialog(int index) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20.0))), title: Text( "Delete ${truncateString(homestayList[index].homestayName.toString(), 15)}", style: const TextStyle(), ), content: const Text("Are you sure?", style: TextStyle()), actions: <Widget>[ TextButton( child: const Text( "Yes", style: TextStyle(), ), onPressed: () async { Navigator.of(context).pop(); _deleteHomestay(index); }, ), TextButton( child: const Text( "No", style: TextStyle(), ), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } void _deleteHomestay(index) { try { http.post(Uri.parse("${Config.SERVER}/php/delete_homestay.php"), body: { "homestayid": homestayList[index].homestayId, }).then((response) { var data = jsonDecode(response.body); if (response.statusCode == 200 && data['status'] == "success") { Fluttertoast.showToast( msg: "Success", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, fontSize: 14.0); _loadHomestays(); return; } else { Fluttertoast.showToast( msg: "Failed", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, fontSize: 14.0); return; } }); } catch (e) { print(e.toString()); } } }
#include "doctest/doctest.h" #include "lockfree_queues/sp_broadcast_queue.h" #include <array> #include <memory> #include <set> #include <thread> #include <vector> TEST_SUITE_BEGIN("SPBroadcastQueue"); using namespace lockfree_queues; // TestType tracks correct usage of constructors and destructors struct SPBQTestType { static std::set<SPBQTestType const*> constructed; SPBQTestType(size_t v) noexcept { x = v; REQUIRE_EQ(constructed.count(this), 0); constructed.insert(this); }; SPBQTestType() noexcept { REQUIRE_EQ(constructed.count(this), 0); constructed.insert(this); }; SPBQTestType(const SPBQTestType& other) noexcept { REQUIRE_EQ(constructed.count(this), 0); REQUIRE_EQ(constructed.count(&other), 1); constructed.insert(this); }; SPBQTestType(SPBQTestType&& other) noexcept { REQUIRE_EQ(constructed.count(this), 0); REQUIRE_EQ(constructed.count(&other), 1); constructed.insert(this); }; SPBQTestType& operator=(const SPBQTestType& other) noexcept { REQUIRE_EQ(constructed.count(this), 1); REQUIRE_EQ(constructed.count(&other), 1); return *this; }; SPBQTestType& operator=(SPBQTestType&& other) noexcept { REQUIRE_EQ(constructed.count(this), 1); REQUIRE_EQ(constructed.count(&other), 1); return *this; } ~SPBQTestType() noexcept { REQUIRE_EQ(constructed.count(this), 1); constructed.erase(this); }; size_t x; }; std::set<const SPBQTestType*> SPBQTestType::constructed; /***/ TEST_CASE("basic_produce_full_queue") { { SPBroadcastQueue<SPBQTestType> q{16}; size_t const rid = q.subscribe(); REQUIRE_EQ(q.front(rid), nullptr); REQUIRE_EQ(q.capacity(), 16); for (size_t iter = 0; iter < 3; ++iter) { for (size_t i = 0; i < 16; i++) { REQUIRE_EQ(q.try_emplace(), true); } REQUIRE(q.front(rid)); REQUIRE_EQ(SPBQTestType::constructed.size(), 16); REQUIRE_EQ(q.try_emplace(), false); for (size_t i = 0; i < 16; i++) { q.pop(rid); } } } REQUIRE_EQ(SPBQTestType::constructed.size(), 0); } /***/ TEST_CASE("basic_produce_partial_queue") { { SPBroadcastQueue<SPBQTestType> q{16}; size_t const rid = q.subscribe(); REQUIRE_EQ(q.front(rid), nullptr); REQUIRE_EQ(q.capacity(), 16); for (size_t i = 0; i < 10; i++) { q.emplace(); } REQUIRE(q.front(rid)); REQUIRE_EQ(SPBQTestType::constructed.size(), 10); } REQUIRE_EQ(SPBQTestType::constructed.size(), 0); } /***/ TEST_CASE("over_subscribe") { constexpr size_t MAX_CONSUMERS = 2; SPBroadcastQueue<size_t, MAX_CONSUMERS> q{10}; size_t rid1 = q.subscribe(); size_t rid2 = q.subscribe(); REQUIRE_THROWS((void)q.subscribe()); q.unsubscribe(rid1); REQUIRE_NOTHROW((void)q.subscribe()); } /***/ TEST_CASE("single_produce_single_consumers") { const size_t iter = 1'000'000; SPBroadcastQueue<size_t> q{1024}; std::atomic<bool> flag(false); std::thread producer{[&q, &flag, iter] { while (!flag) ; for (size_t i = 0; i < iter; ++i) { q.emplace(i); } }}; size_t rid = q.subscribe(); size_t sum = 0; flag = true; for (size_t i = 0; i < iter; ++i) { while (!q.front(rid)) ; sum += *q.front(rid); q.pop(rid); } REQUIRE_EQ(q.front(rid), nullptr); REQUIRE_EQ(sum, iter * (iter - 1) / 2); q.unsubscribe(rid); producer.join(); } /***/ TEST_CASE("single_produce_multiple_consumers") { // All Consumers subscribe before producer starts producing const size_t iter = 1'000'000; constexpr size_t MAX_CONSUMERS = 4; SPBroadcastQueue<size_t, MAX_CONSUMERS> q{1024}; std::array<std::atomic<bool>, MAX_CONSUMERS> flags = {false}; std::thread producer{[&q, &flags, iter]() { for (auto const& flag : flags) { while (!flag) ; } for (size_t i = 0; i < iter; ++i) { q.emplace(i); } }}; std::vector<std::thread> consumers; for (size_t tid = 0; tid < MAX_CONSUMERS; ++tid) { consumers.emplace_back( [&q, &flags, tid, iter]() { size_t rid = q.subscribe(); size_t sum = 0; flags[tid] = true; for (size_t i = 0; i < iter; ++i) { while (!q.front(rid)) ; sum += *q.front(rid); q.pop(rid); } REQUIRE_EQ(q.front(rid), nullptr); REQUIRE_EQ(sum, iter * (iter - 1) / 2); q.unsubscribe(rid); }); } for (auto& c : consumers) { c.join(); } producer.join(); } /***/ TEST_CASE("single_produce_multiple_consumers_2") { // All Consumers subscribe before producer starts producing // Same as single_produce_multiple_consumers but with MAX_CONSUMERS == 8 const size_t iter = 1'000'000; constexpr size_t MAX_CONSUMERS = 8; SPBroadcastQueue<size_t, MAX_CONSUMERS> q{1024}; std::array<std::atomic<bool>, MAX_CONSUMERS> flags = {false}; std::thread producer{[&q, &flags, iter]() { for (auto const& flag : flags) { while (!flag) ; } for (size_t i = 0; i < iter; ++i) { q.emplace(i); } }}; std::vector<std::thread> consumers; for (size_t tid = 0; tid < MAX_CONSUMERS; ++tid) { consumers.emplace_back( [&q, &flags, tid, iter]() { size_t rid = q.subscribe(); size_t sum = 0; flags[tid] = true; for (size_t i = 0; i < iter; ++i) { while (!q.front(rid)) ; sum += *q.front(rid); q.pop(rid); } REQUIRE_EQ(q.front(rid), nullptr); REQUIRE_EQ(sum, iter * (iter - 1) / 2); q.unsubscribe(rid); }); } for (auto& c : consumers) { c.join(); } producer.join(); } /***/ TEST_CASE("single_produce_multiple_consumers_subscribe") { // Consumers subscribe after the producer starts const size_t iter = 1'000'000; constexpr size_t MAX_CONSUMERS = 4; SPBroadcastQueue<SPBQTestType, MAX_CONSUMERS> q{1024}; std::thread producer{[&q, iter]() { for (size_t i = 0; i < iter; ++i) { q.emplace(i); } }}; // let the producer thread start, // the producer waits for at least one consumer before it is able to emplace std::this_thread::sleep_for(std::chrono::nanoseconds{200}); std::vector<std::thread> consumers; for (size_t tid = 0; tid < MAX_CONSUMERS; ++tid) { consumers.emplace_back( [&q, iter]() { size_t rid = q.subscribe(); while (true) { SPBQTestType const* item = q.front(rid); while (!item) { item = q.front(rid); } if (item->x == iter - 1) { // last item q.pop(rid); break; } q.pop(rid); } REQUIRE_EQ(q.front(rid), nullptr); q.unsubscribe(rid); }); } for (auto& c : consumers) { c.join(); } producer.join(); } TEST_SUITE_END();
package ${config.serviceApiPackage}; import org.zongf.helper.mybatis.pager.PageBounds; import org.zongf.helper.mybatis.pager.PageResult; import org.zongf.helper.spring.dto.BaseQuery; import ${config.entityPackage}.${meta.name}Entity; import java.util.List; public interface I${meta.name}Service { /** 保存实体 * @param entity 数据库实体 * @return boolean * @author zongf * @date${createDate} */ boolean save(${meta.name}Entity entity); /** 批量保存. 需要注意保存数量, 单条sql长度有限制 * @param entityList 实体列表 * @return int * @author zongf * @date${createDate} */ int batchSave(List<${meta.name}Entity> entityList); /** 根据主键ID 删除记录 * @param id 主键ID * @return boolean 记录不存在返回false * @author zongf * @date${createDate} */ boolean deleteById(Long id); /** 根据主键ID列表批量删除 * @param idList 主键列表,不能为空 * @return int 成功删除的数量 * @author zongf * @date${createDate} */ int batchDeleteByIds(List<Long> idList); /** 更新实体, 只更新所有非null 属性 * @param entity 包含ID属性的实体 * @return boolean 如果记录不存在, 返回false * @author zongf * @date${createDate} */ boolean updateNotNull(${meta.name}Entity entity); /** 通过主键ID查询记录, 查询所有字段 * @param id 主键ID * @return ${meta.name}Entity 实体 * @author zongf * @date${createDate} */ ${meta.name}Entity queryById(Long id); /** 查询列表 * @param query 请求对象 * @return List<${meta.name}Entity> * @author zongf * @date${createDate} */ List<${meta.name}Entity> queryList(BaseQuery query); /** 分页查询列表 * @param query 请求对象 * @param pageBounds 分页对象 * @return PageResult<${meta.name}Entity> * @author zongf * @date${createDate} */ PageResult<${meta.name}Entity> queryPager(BaseQuery query, PageBounds pageBounds); }
package eCommerceApp; import java.time.Duration; import java.util.Arrays; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import io.github.bonigarcia.wdm.WebDriverManager; public class AddingItems { public static void main(String[] args) { WebDriver driver =WebDriverManager.chromedriver().create(); //WebDriver driver = new ChromeDriver(); driver.get("https://rahulshettyacademy.com/seleniumPractise/"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3)); //driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //array having expected list List<String> items = Arrays.asList("cucumber", "beetroot", "carrot","mushroom"); addItems(driver,items); //click on cart driver.findElement(By.cssSelector("img[alt='Cart']")).click(); driver.findElement(By.xpath("//button[text()='PROCEED TO CHECKOUT']")).click(); //apply promocode driver.findElement(By.cssSelector("input.promocode")).sendKeys("rahulshettyacademy"); driver.findElement(By.cssSelector("button.promoBtn")).click(); //Explicit wait WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5)); wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("span.promoInfo"))); Assert.assertEquals(driver.findElement(By.cssSelector("span.promoInfo")).getText(),"Code applied ..!"); driver.quit(); } //method to add items into cart public static void addItems(WebDriver driver,List<String> items) { //getting the list of product names List<WebElement> products =driver.findElements(By.cssSelector("h4.product-name")); /* * products.stream().forEach(p -> { * if(items.contains(p.getText().split("")[0].toLowerCase())) { * driver.findElements(By.xpath("//button[text()='ADD TO CART']")); } }); */ int count =0; for(int i=0;i<products.size();i++) { //checking if the item name is present in the list if(items.contains(products.get(i).getText().split("-")[0].toLowerCase().trim())){ driver.findElements(By.xpath("//div[@class='product-action']/button")).get(i).click(); count++; if(count==items.size()) break; } } } }
package com.example.demo.controller; import com.example.demo.dtos.UserRegistrationRequestDTO; import com.example.demo.entities.dato.User; import com.example.demo.security.JwtRequest; import com.example.demo.security.JwtResponse; import com.example.demo.security.JwtTokenUtil; import com.example.demo.serviceimplements.JwtUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin public class JwtAuthenticationController { @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private JwtUserDetailsService userDetailsService; @PostMapping("/authenticate") public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception { authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword()); final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails); return ResponseEntity.ok(new JwtResponse(token)); } private void authenticate(String username, String password) throws Exception { try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (DisabledException e) { throw new Exception("USER_DISABLED", e); } catch (BadCredentialsException e) { throw new Exception("INVALID_CREDENTIALS", e); } } @PostMapping("/register") public ResponseEntity<?> registerUser(@RequestBody UserRegistrationRequestDTO registrationRequestDTO){ try { User newUser = userDetailsService.registroUser(registrationRequestDTO.getUsername(),registrationRequestDTO.getPassword()); UserDetails userDetails = userDetailsService.loadUserByUsername(newUser.getUsername()); String token = jwtTokenUtil.generateToken(userDetails); return ResponseEntity.ok(new JwtResponse(token)); }catch (Exception e){ return ResponseEntity.badRequest().body("Error al registrar el usuario:" + e.getMessage()); } } }
import axios from 'axios'; import { useState, useEffect, useContext, Fragment } from 'react'; import { useParams } from "react-router-dom"; import { Modal } from 'react-bootstrap'; import CurrencyInput from 'react-currency-input-field'; import { VariableBudgetContext, FixedBudgetContext, IncomeBudgetContext, VariableTotalContext, FixedTotalContext, IncomeTotalContext } from '../../contexts/MainBudgetContext'; import ReadIndividualBudgetRow from './ReadIndividualBudgetRow'; import EditIndividualBudgetRow from './EditIndividualBudgetRow'; import AlertComponent from '../../AlertComponent'; function IndividualBudget() { const { type } = useParams(); const initialData = { category: '', expense: null } const [title, setTitle] = useState(type); const [totalBudgeted, setTotalBudgeted] = useState(0); const [variableTotal, setVariableTotal] = useContext(VariableTotalContext); const [fixedTotal, setFixedTotal] = useContext(FixedTotalContext); const [incomeTotal, setIncomeTotal] = useContext(IncomeTotalContext); const [variableBudget, setVariableBudget] = useContext(VariableBudgetContext); const [fixedBudget, setFixedBudget] = useContext(FixedBudgetContext); const [incomeBudget, setIncomeBudget] = useContext(IncomeBudgetContext); const [individualBudget, setIndividualBudget] = useState([]); const [showAddForm, setShowAddForm] = useState(false); const [addFormData, setAddFormData] = useState(initialData); const [editBudgetId, setEditBudgetId] = useState(null); const [editFormData, setEditFormData] = useState(initialData); const [alert, setAlert] = useState({ show: false, message: '', type: '' }); useEffect(() => { switch(type) { case "variable": setIndividualBudget(variableBudget); setTotalBudgeted(variableTotal); break; case "fixed": setIndividualBudget(fixedBudget); setTotalBudgeted(fixedTotal); break; case "income": setIndividualBudget(incomeBudget); setTotalBudgeted(incomeTotal); break; default: break; } setTitle(type.charAt(0).toUpperCase() + type.slice(1)); }, [type, variableBudget, fixedBudget, incomeBudget, variableTotal, fixedTotal, incomeTotal]) // Add functions const handleShowAddForm = () => { setShowAddForm(!showAddForm); } const handleAddFormCat = (event) => { event.preventDefault(); const value = event.target.value; const newFormData = {...addFormData}; newFormData.category = value; setAddFormData(newFormData); } const handleAddFormExpense = (value) => { const newFormData = {...addFormData}; newFormData.expense = value; setAddFormData(newFormData); } const handleAddFormSubmit = (event) => { event.preventDefault(); axios.defaults.withCredentials = true; const newBudget = { id: -1, category: addFormData.category, expense: addFormData.expense }; axios.post(`/api/${type}Budget/save`, newBudget) .then((res) => { if (res.data.success) { newBudget.id = res.data.budgetId; const newMainBudget = [...individualBudget, newBudget]; setIndividualBudget(newMainBudget); console.log('Successfully added to db.'); } else { setAddFormData(initialData); console.log(res.data.message); }; }) .catch((err) => { console.log(err); console.log("Cannot add"); }); setShowAddForm(!showAddForm); }; // Edit Functions const handleEditFormCat = (event) => { event.preventDefault(); const value = event.target.value; const newFormData = {...editFormData}; newFormData.category = value; setEditFormData(newFormData); } const handleEditFormExpense = (value) => { const newFormData = {...editFormData}; newFormData.expense = value; setEditFormData(newFormData); } const handleEditFormSubmit = (event) => { event.preventDefault(); const editedBudget = { id: editBudgetId, category: editFormData.category, expense: editFormData.expense }; setEditBudgetId(null); axios.post(`/api/${type}Budget/edit`, editedBudget) .then((res) => { if (res.data.success) { const newMainBudget = [...individualBudget]; const index = individualBudget.findIndex((budget) => budget.id === editBudgetId); newMainBudget[index] = editedBudget; setIndividualBudget(newMainBudget); console.log('Successfully edited to db.'); } else { console.log(res.data.message); }; }) .catch((err) => { console.log("Cannot edit"); }) }; const handleEditClick = (event, budget) => { event.preventDefault(); setEditBudgetId(budget.id); const formValues = { category: budget.category, expense: budget.expense } setEditFormData(formValues); }; const handleEditCancelClick = () => { setEditBudgetId(null); }; // Delete Functions const handleDeleteClick = (budgetId) => { const newMainBudget = [...individualBudget]; const index = individualBudget.findIndex((budget) => budget.id === budgetId); newMainBudget.splice(index, 1); setIndividualBudget(newMainBudget); axios.delete(`/api/${type}Budget/delete`, {data: {id: budgetId}}) .then((res) => { console.log('Successfully deleted from db.'); }) .catch((err) => { console.log("Cannot delete"); }) }; return ( <> { alert.show && <AlertComponent alert={alert} setAlert={setAlert} /> } <div className='container d-flex flex-column mt-3' style={{ width: '75%' }}> <h2 className="card-header text-center"> { title } Budget </h2> <h5 className='text-center mt-3'> ${totalBudgeted} budgeted </h5> <button onClick={handleShowAddForm} className="btn btn-primary m-3"> Add a Budget </button> <form onSubmit={ handleEditFormSubmit }> <table className='table table-bordered table-responsive' style={{ tableLayout: 'fixed' }}> <thead className='table-light'> <tr> <th>Category</th> <th>Set BudGet</th> <th className='text-center'>Actions</th> </tr> </thead> <tbody> {individualBudget.map((data) => ( <Fragment key={ data.id }> { data.id === editBudgetId ? <EditIndividualBudgetRow editFormData={ editFormData } handleEditFormCat={ handleEditFormCat } handleEditFormExpense={ handleEditFormExpense } handleEditCancelClick={ handleEditCancelClick } /> : <ReadIndividualBudgetRow data={ data } handleEditClick={ handleEditClick } handleDeleteClick={ handleDeleteClick }/> } </Fragment> ))} </tbody> </table> </form> { showAddForm && <Modal show={showAddForm} onHide={handleShowAddForm} size="lg" centered > <Modal.Header closeButton> <Modal.Title> Add a Budget </Modal.Title> </Modal.Header> <Modal.Body className="m-auto"> <form onSubmit={ handleAddFormSubmit }> <div className='form-group mb-3'> <input type='text' placeholder='Category' value={addFormData.category} onChange={handleAddFormCat} required/> </div> <div className='form-group mb-3'> <CurrencyInput placeholder='$100 Budgeted' value={addFormData.expense} step={.01} fixedDecimalLength={2} prefix={'$'} onValueChange={handleAddFormExpense} required /> </div> <button type='submit' className='btn btn-primary' style={{ width: '100%' }}> Add </button> </form> </Modal.Body> </Modal> } </div> </> ) } export default IndividualBudget;
<template> <img class="logo" alt="resto logo" src="../assets/logo.png" /> <h1>Hellow {{ name }},Wellcome on Update restuarant page</h1> <div class="update"> <input type="text" v-model="restaurant.rname" name="rname" placeholder="name" /> <input type="text" v-model="restaurant.address" name="address" placeholder="address" /> <input type="number" v-model="restaurant.contact" name="contact" placeholder="contact" /> <button type="button" v-on:click="updateResto">Update Restaurunt</button> </div> </template> <script> import axios from 'axios' export default { name: 'updateResto', data() { return { name: '', restaurant: { rname: '', address: '', contact: '' } } }, methods: { async updateResto() { let res = await axios.put(`http://localhost:3000/restarunt/${this.$route.params.id}`, { rname: this.restaurant.rname, address: this.restaurant.address, contact: this.restaurant.contact, }); // console.log(res); if (res.status == 200) { alert("Successfully Updated your Data"); // localStorage.setItem('restaurant-info', JSON.stringify(res.data)) this.$router.push({ name: 'homePage' }) } // console.log('update',this.restaurant) } }, async mounted() { let user = localStorage.getItem('user-info'); if (!user) { this.$router.push({ name: 'loginPage' }) } else { this.name = JSON.parse(user).name; // console.warn(this.$route.params.id) const res = await axios.get(`http://localhost:3000/restarunt/${this.$route.params.id}`) // console.log(res.data) this.restaurant = res.data } } } </script>
** ในนี้ถ้าไม่ตกหล่นไรไม่มีแค่ไฟล์ build.gradle (Module: {nameProject}.app) อันเดียว ** ** แก้ build.gradle (Module: {nameProject}.app) ด้วย ** ** ในนี้มีชื่อไฟล์ทุกอัน Ctrl+F หาเอาได้ ** MeFragment.kt package com.example.ass6menufragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup class MeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_me, container, false) } } -------------------------------------------------------------------------------------------- Friend1Fragment.kt package com.example.ass6menufragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.ass6menufragment.databinding.ActivityMainBinding import com.example.ass6menufragment.databinding.FragmentFriend1Binding import com.example.ass6menufragment.databinding.FragmentFriend2Binding class Friend1Fragment : Fragment() { private lateinit var bindingFirstFriendFragment: FragmentFriend1Binding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { bindingFirstFriendFragment = FragmentFriend1Binding.inflate(layoutInflater) bindingFirstFriendFragment.btnFriend1Button.setOnClickListener() { var fragment: Fragment? = null fragment = MeFragment() replaceFragment(fragment) } return bindingFirstFriendFragment.root } fun replaceFragment(someFragment: Fragment){ var binding: ActivityMainBinding binding = ActivityMainBinding.inflate(layoutInflater) val transaction = requireActivity().supportFragmentManager.beginTransaction() transaction.replace(binding.frameLayout.id, someFragment) transaction.addToBackStack(null) transaction.commit() } } --------------------------------------------------------------------------------------------   Friend2Fragment.kt package com.example.ass6menufragment import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.ass6menufragment.databinding.ActivityMainBinding import com.example.ass6menufragment.databinding.FragmentFriend1Binding import com.example.ass6menufragment.databinding.FragmentFriend2Binding class Friend2Fragment : Fragment() { private lateinit var bindingSecondFriendFragment: FragmentFriend2Binding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { bindingSecondFriendFragment = FragmentFriend2Binding.inflate(layoutInflater) bindingSecondFriendFragment.btnFriend2Button.setOnClickListener() { var fragment: Fragment? = null fragment = MeFragment() replaceFragment(fragment) } return bindingSecondFriendFragment.root } fun replaceFragment(someFragment: Fragment) { var binding: ActivityMainBinding binding = ActivityMainBinding.inflate(layoutInflater) val transaction = requireActivity().supportFragmentManager.beginTransaction() transaction.replace(binding.frameLayout.id, someFragment) transaction.addToBackStack(null) transaction.commit() } } --------------------------------------------------------------------------------------------  MainActivity.kt package com.example.ass6menufragment import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.fragment.app.Fragment import com.example.ass6menufragment.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) //Show FirstFragment if(savedInstanceState==null) { replaceFragment(MeFragment()) } } //// Option Menu override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.my_menu,menu) return super.onCreateOptionsMenu(menu) } //// Click on Option Menu override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId){ R.id.friend_menu1 -> replaceFragment(Friend1Fragment()) R.id.friend_menu2 -> replaceFragment(Friend2Fragment()) } return super.onOptionsItemSelected(item) } private fun replaceFragment(someFragment: Fragment){ val fragmentManager = supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() fragmentTransaction.replace(R.id.frameLayout, someFragment) fragmentTransaction.commit() } } --------------------------------------------------------------------------------------------   fragment_Me.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#141861" android:padding="15dp" tools:context=".MeFragment"> <TextView android:id="@+id/textmename" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="นายเจษฎาภรณ์ ศิริเกตุ" android:textColor="@color/white" android:shadowColor="#FFFFFF" android:shadowDx="1.5" android:shadowDy="1.3" android:shadowRadius="1.6" android:textStyle="bold" android:layout_marginBottom="10dp" android:layout_centerHorizontal="true" android:layout_below="@id/imgme" android:paddingTop="20dp" android:textSize="25sp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="643020359-3" android:textColor="@color/white" android:shadowColor="#FFFFFF" android:shadowDx="1.5" android:shadowDy="1.3" android:shadowRadius="1.6" android:textStyle="bold" android:layout_marginBottom="10dp" android:layout_centerHorizontal="true" android:layout_below="@id/textmename" android:textSize="25sp"/> <androidx.appcompat.widget.AppCompatImageView android:id="@+id/imgme" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerInParent="true" android:src="@drawable/cartoon_cat" /> </RelativeL -------------------------------------------------------------------------------------------- fragment_Friend1.xml   <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Friend1Fragment"> <androidx.appcompat.widget.AppCompatImageView android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/bearbg" android:scaleType="centerCrop"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:padding="15dp"> <TextView android:id="@+id/textf1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ชื่อ1" android:textColor="@color/white" android:shadowColor="#000000" android:shadowDx="1.5" android:shadowDy="1.3" android:shadowRadius="20" android:textStyle="bold" android:layout_marginBottom="10dp" android:layout_centerHorizontal="true" android:layout_below="@id/imgf1" android:paddingRight="10dp" android:paddingLeft="10dp" android:paddingBottom="10dp" android:paddingTop="10dp" android:textSize="25sp"/> <androidx.appcompat.widget.AppCompatButton android:id="@+id/btnFriend1Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textf1" android:text="Go Back To My Fragment" android:textSize="20sp" android:textAllCaps="false" android:layout_centerHorizontal="true"/> <androidx.appcompat.widget.AppCompatImageView android:id="@+id/imgf1" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerInParent="true" android:src="@drawable/cartoon_cat" /> </RelativeLayout> </RelativeLayout> -------------------------------------------------------------------------------------------- fragment_Friend2.xml   <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Friend2Fragment"> <androidx.appcompat.widget.AppCompatImageView android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/bearbg" android:scaleType="centerCrop"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:padding="15dp"> <TextView android:id="@+id/textf2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ชื่อ2" android:textColor="@color/white" android:shadowColor="#000000" android:shadowDx="1.5" android:shadowDy="1.3" android:shadowRadius="20" android:textStyle="bold" android:layout_marginBottom="10dp" android:layout_centerHorizontal="true" android:layout_below="@id/imgf2" android:paddingRight="10dp" android:paddingLeft="10dp" android:paddingBottom="10dp" android:paddingTop="10dp" android:textSize="25sp"/> <androidx.appcompat.widget.AppCompatButton android:id="@+id/btnFriend2Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textf2" android:text="Go Back To My Fragment" android:textSize="20sp" android:textAllCaps="false" android:layout_centerHorizontal="true"/> <androidx.appcompat.widget.AppCompatImageView android:id="@+id/imgf2" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerInParent="true" android:src="@drawable/cartoon_cat" /> </RelativeLayout> </RelativeLayout> -------------------------------------------------------------------------------------------- activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <FrameLayout android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> --------------------------------------------------------------------------------------------   my_menu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/friend_menu1" app:showAsAction="always" android:title="First Friend" android:icon="@drawable/fbutton"/> <item android:id="@+id/friend_menu2" app:showAsAction="always" android:title="Second Friend" android:icon="@drawable/dbutton"/> </menu> --------------------------------------------------------------------------------------------
from typing import List from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import (StaleElementReferenceException, ElementClickInterceptedException, TimeoutException) from selenium.webdriver.common.by import By class BasePage(object): """Класс предоставляющий методы для взаимодействия с драйвером""" def __init__(self, driver): self.driver = driver self.overlay = (By.XPATH, "//div[@id='overlay']") self.popup_window = (By.XPATH, "//div[@class='modal-content']") self.popup_ok_btn = (By.XPATH, "//button[@type='submit']") def wait_element_present(self, locator: tuple, timeout=25) -> WebElement: """ Ожидание представление элемента. :param locator: Локатор элемента. :param timeout: Ожидание элемента. :return: Элемент возвращения данных после выполнения ожидания. """ return WebDriverWait(self.driver, timeout, ignored_exceptions=StaleElementReferenceException) \ .until(EC.presence_of_element_located(locator)) def wait_clickable(self, locator: tuple, timeout=25) -> True or TimeoutException: """ Ожидание клика по элементу. :param locator: :param timeout: :return: """ return WebDriverWait(self.driver, timeout, ignored_exceptions=ElementClickInterceptedException) \ .until(EC.element_to_be_clickable(locator)) def click_element(self, locator: tuple, timeout=25) -> True or TimeoutException: """ Выбор элемента. :param locator: :param timeout: :return: """ return WebDriverWait(self.driver, timeout, ignored_exceptions=ElementClickInterceptedException) \ .until(EC.element_to_be_clickable(locator)).click() def find_element(self, locator: tuple or WebElement) -> WebElement: """ Поиск элемента. :param by: Метод поиска элемента. :param locator: Локатор элемента. :return: Элемент возвращения данных после поиска.. """ return self.driver.find_element(*locator) def find_elements(self, locator: tuple or WebElement) -> List[WebElement]: """ Поиск элементов. :param by: :param locator: :return: """ return self.driver.find_elements(*locator) def get_element_text(self, locator: tuple or WebElement) -> str: """ :param locator: :return: """ if isinstance(locator, tuple): return self.wait_element_present(locator).text elif isinstance(locator, WebElement): return locator.text def wait_invisibility(self, locator: tuple, timeout=25) -> True or TimeoutException: return WebDriverWait(self.driver, timeout).until(EC.invisibility_of_element(locator)) def wait_text_in_element(self, locator: tuple, text: str, timeout=25) -> True or TimeoutException: return WebDriverWait(self.driver, timeout).until(EC.text_to_be_present_in_element(locator, text)) def send_value_by_input_text(self, locator: WebElement, value: str): return self.wait_element_present(locator).send_keys(value) def check_element_for_activity(self, locator: tuple or WebElement) -> True: return self.find_element(locator).is_enabled()
<!DOCTYPE html> <!-- Template Name: Foxclore Author: <a href="https://www.os-templates.com/">OS Templates</a> Author URI: https://www.os-templates.com/ Copyright: OS-Templates.com Licence: Free to use under our free template licence terms Licence URI: https://www.os-templates.com/template-terms --> <html lang=""> <!-- To declare your language - read more here: https://www.w3.org/International/questions/qa-html-language-declarations --> <head> <title>Homepage | Masjid Darul Ulum Universitas Pamulang</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="{{ URL::asset('css/layout.css') }}" rel="stylesheet" type="text/css" media="all"> <link href="{{ URL::asset('css/modified.css') }}" rel="stylesheet" type="text/css" media="all"> <link href="{{ URL::asset('css/animate.css') }}" rel="stylesheet" type="text/css" media="all"> </head> <body id="top"> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- Top Background Image Wrapper --> <div class="bgded overlay hero" style="background-image:url('https://www.free-css.com/assets/files/free-css-templates/preview/page271/foxclore/images/live-demo/background-01.jpg');"> <!-- ################################################################################################ --> <header id="header" class="hoc clear"> <!-- ################################################################################################ --> <div id="logo" class="one_quarter first"> <h1><a href="{{ route('homepage') }}">Masjid</a></h1> <p>DARUL ULUM UNIVERSITAS PAMULANG</p> </div> <div class="three_quarter"> <ul class="nospace clear"> <li class="one_third first"> <div class="block clear"><a href="#"><i class="fas fa-phone"></i></a> <span><strong>Telepon:</strong> 085719448568</span></div> </li> <li class="one_third"> <div class="block clear"><a href="#"><i class="fas fa-envelope"></i></a> <span><strong>Email:</strong> upz@unpam.com</span></div> </li> <li class="one_third"> <div class="block clear"><a href="#"><i class="fas fa-clock"></i></a> <span><strong> Sen. - Sel.:</strong> 08.00 - 18.00</span></div> </li> </ul> </div> <!-- ################################################################################################ --> </header> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <section id="navwrapper" class="hoc clear"> <!-- ################################################################################################ --> <nav id="mainav"> <ul class="clear"> <li class="{{ route_name() == 'homepage' ? 'active' : '' }}"><a href="{{ route('homepage') }}">Beranda</a></li> <li class="{{ route_name() == 'categories' ? 'active' : '' }}"><a class="drop" href="#">Jurnal</a> <ul> @foreach ($categories as $key => $value) @php $hashed_id = \Illuminate\Support\Facades\Crypt::encryptString($key.'_'.$value); @endphp <li><a href="{{ route('categories', ['id' => $hashed_id]) }}">{{ $value }}</a></li> @endforeach </ul> </li> <li class="{{ route_name() == 'program' ? 'active' : '' }}"><a class="drop" href="#">Program</a> <ul> @foreach ($programs as $key => $value) @php $hashed_id = \Illuminate\Support\Facades\Crypt::encryptString($key.'_'.$value); @endphp <li><a href="{{ route('program', ['id' => $hashed_id]) }}">{{ $value }}</a></li> @endforeach </ul> </li> </ul> </nav> <!-- ################################################################################################ --> </section> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <div id="pageintro" class="hoc clear slider"> <div class="slide"> <article> <h3 class="title" id="title" data-wow-duration="1s">Magna feugiat pulvinar</h3> <p id="subtitle" data-wow-duration="1s">At dapibus ac velit cum sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus mus maecenas ut</p> <footer> <a class="btn" id="btn" href="">Klik Ini</a> </footer> </article> <div class="box"> {{ Form::open(['route' => 'transaction.create', 'method' => 'POST', 'class' => 'form-header']); }} <div class="form-group"> <label>Jenis Pembayaran</label> <select name="id_transaction_type" id=""> @foreach ($transaction_type as $transaction) <option value="{{ $transaction->id }}">{{ $transaction->name }}</option> @endforeach </select> @error('id_transaction_type') <span class="error-message">{{ $message }}</span> @enderror </div> <div class="form-group"> <label>Nama</label> <input type="text" name="name"> @error('name') <span class="error-message">{{ $message }}</span> @enderror </div> <div class="form-group"> <label>Email</label> <input type="email" name="email"> @error('email') <span class="error-message">{{ $message }}</span> @enderror </div> <div class="form-group"> <button type="submit">Submit</button> </div> {{ Form::close() }} </div> </div> <!-- ################################################################################################ --> <!-- ################################################################################################ --> </div> <!-- ################################################################################################ --> </div> <!-- End Top Background Image Wrapper --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <div class="wrapper row3"> <main class="hoc container clear"> <!-- main body --> <!-- ################################################################################################ --> <section id="introblocks"> <ul class="nospace group"> @foreach($posts as $post) <li class="one_third"> <figure> <img src="{{ $post->banner }}" alt=""> <figcaption> @php $hashed_id = \Illuminate\Support\Facades\Crypt::encryptString($post->id.'_'.$post->title); $route = 'detail.categories'; if (in_array($post->category, array_values(\App\Util\Common::getPrograms()))) $route = 'detail.program'; @endphp <a href="{{ route($route, ['id' => $hashed_id]) }}" class="heading" style="color: black;">{{ read_more($post->title, 100) }}</a> <p>{!! read_more(html_entity_decode($post->content), 100) !!}</p> </figcaption> </figure> </li> @endforeach </ul> </section> <!-- ################################################################################################ --> <!-- / main body --> <div class="clear"></div> </main> </div> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <div class="wrapper row2"> <section class="hoc container clear"> <!-- ################################################################################################ --> <div class="sectiontitle"> <p class="nospace font-xs">Jenis Kegiatan</p> <h6 class="heading">Daftar kegiatan</h6> </div> <ul class="nospace group center activity"> @foreach ($activity as $index => $item ) <li class="one_third <?php echo $index == 0 ? 'first' : '' ?>"> <article> <img src="{{ $item->icon }}" alt=""> <h6 class="heading"> {{ $item->name }} </h6> <p class="btmspace-30">{!! read_more($item->description, 100) !!}</p> </article> </li> @endforeach </ul> <!-- ################################################################################################ --> </section> </div> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <div class="wrapper row3"> <section class="hoc container clear"> <!-- ################################################################################################ --> <div class="sectiontitle"> <p class="nospace font-xs">Keuanga</p> <h6 class="heading">Rangkuman Laporan Keuangan</h6> </div> <ul id="stats" class="nospace group"> <li><i class="fas fa-id-badge"></i> <p><a href="#">{{ $summary_transaction['month']['in'] }}</a></p> <p>Total dana masuk bulan ini</p> </li> <li><i class="fas fa-inbox"></i> <p><a href="#">{{ $summary_transaction['month']['out'] }}</a></p> <p>Totan dana keluar bulan ini</p> </li> <li><i class="fas fa-store-alt"></i> <p><a href="#">{{ $summary_transaction['total'] }}</a></p> <p>Semua Dana Terkumpul</p> </li> </ul> <!-- ################################################################################################ --> </section> </div> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <div class="wrapper coloured"> <section id="testimonials" class="hoc container clear"> <!-- ################################################################################################ --> <div class="sectiontitle"> <p class="nospace font-xs">Struktur Organisasi</p> <h6 class="heading">Keanggotaan Masjid Darul Ulum Universitas Pamulang</h6> </div> <div class="organization"> @foreach($structure as $item) <div class="item"> <img width="100" height="100" alt="" src="{{ $item->avatar }}"> <h6 class="heading">{{ $item->name }}</h6> <em>{{ $item->title }}</em> </div> @endforeach </div> {{--<article class="one_half first"><img width="100" height="100" alt=""> <h6 class="heading">J. Doe</h6> <em>Nulla mauris hendrerit</em></article> <article class="one_half"><img src="images/demo/100x100.png" alt=""> <h6 class="heading">G. Doe</h6> <em>Aenean vestibulum mattis</em></article> <article class="one_half"><img src="images/demo/100x100.png" alt=""> <h6 class="heading">G. Doe</h6> <em>Aenean vestibulum mattis</em></article>--}} <!-- ################################################################################################ --> </section> </div> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <div class="bgded overlay row4" style="background-image:url('images/demo/backgrounds/01.png');"> <footer id="footer" class="hoc clear"> <!-- ################################################################################################ --> <div class="center btmspace-50"> <h6 class="heading">Masjid DARUL ULUM</h6> <p class="nospace">UNIVERSITAS PAMULANG KAMPUS VIKTOR</p> </div> <!-- ################################################################################################ --> <hr class="btmspace-50"> <!-- ################################################################################################ --> <div class="three_quarter first"> <h6 class="heading">Ingin mengirim pesan ?</h6> <p class="nospace btmspace-15">Kirimkan pesan</p> <form action="#" method="post"> <fieldset> <legend>Pesan:</legend> <input class="btmspace-15" type="text" value="" placeholder="Nama"> <textarea class="btmspace-15" rows="10" cols="100"></textarea> <button type="submit" value="submit">Submit</button> </fieldset> </form> </div> <!-- ################################################################################################ --> </footer> </div> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <div class="wrapper row5"> <div id="copyright" class="hoc clear"> <!-- ################################################################################################ --> <p class="fl_left">Copyright &copy; 2018 - All Rights Reserved - <a href="#">Domain Name</a></p> <p class="fl_right">Template by <a target="_blank" href="https://www.os-templates.com/" title="Free Website Templates">OS Templates</a></p> <!-- ################################################################################################ --> </div> </div> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <!-- ################################################################################################ --> <a id="backtotop" href="#top"><i class="fas fa-chevron-up"></i></a> <!-- JAVASCRIPTS --> <script src="{{ URL::asset('js/jquery.min.js') }}"></script> <script src="{{ URL::asset('js/jquery.backtotop.js') }}"></script> <script src="{{ URL::asset('js/jquery.mobilemenu.js') }}"></script> <script src="{{ URL::asset('js/wow.min.js') }}"></script> <script type="text/javascript"> new WOW().init(); $.ajax({ url: '{{ route('banner') }}', // Replace with your API endpoint method: 'GET', dataType: 'json', // Set the expected data type success: function(response) { // Handle the successful response const heroes = response.data let currentIndex = 0; function updateHeroes(item) { const wow = new WOW() const element = ['title', 'subtitle']; element.forEach(eachElement => { const div = $('.slide').find(`#${eachElement}`) div.html(item[eachElement]) $('#btn').attr('href', item.link) if (item.link == '') { $('#btn').hide() } $('.hero').css({ 'background-image': `url(${item.image})` }) }) console.log($('.slide').find('#content')) console.log($('.slide').find('#btn')) } function showSlide(currentIndex) { heroes.forEach((item, index) => { if (currentIndex == index) updateHeroes(item) }); } function nexSlide() { currentIndex = (currentIndex + 1) % heroes.length; showSlide(currentIndex); } showSlide(currentIndex) setInterval(nexSlide, 5000); }, error: function(xhr, status, error) { // Handle the error console.log('Error:', error); } }); </script> </body> </html>
package com.skybooking.skypointservice.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.skybooking.skypointservice.httpstatus.BadRequestException; import org.json.JSONObject; import org.springframework.web.multipart.MultipartFile; import java.math.BigDecimal; import java.util.List; public class ValidateKeyUtil { public static void validateKey(Object object, List<String> keyList) { try { ObjectMapper mapper = new ObjectMapper(); //======= Converting the Object to JSONString String jsonString = mapper.writeValueAsString(object); //======= Convert jsonStrong to JSONObject JSONObject json = new JSONObject(jsonString); keyList.forEach(key -> { if (json.isNull(key)) { throw new BadRequestException("key_" + key + "_not_null", null); } else { if (String.valueOf(json.get(key)).length() == 0) { throw new BadRequestException("key_" + key + "_not_null", null); } } }); } catch (JsonProcessingException e) { e.printStackTrace(); throw new BadRequestException("validate_key_failed", null); } } public static void validateMultipartFile(List<MultipartFile> file, String key) { if (file == null) { throw new BadRequestException("key_" + key + "_not_null", null); } else { if (file.isEmpty()) { throw new BadRequestException("key_" + key + "_not_null", null); } } } public static void validatePhoneNumber(String number) { if (!number.matches("[0-9]+")) { throw new BadRequestException("phone_number_not_valid", null); } else if (number.length() < 6 || number.length() > 14) { throw new BadRequestException("phone_number_not_valid", null); } } public static void validateAmountNotNegative(BigDecimal amount) { if (amount.compareTo(new BigDecimal(0)) <= 0) { throw new BadRequestException("amount_not_negative", null); } } public static void validateEmail(String email) { String regex = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"; if (!email.matches(regex)) { throw new BadRequestException("email_not_valid", null); } } public static void validatePhoneCode(String phoneCode) { if (!phoneCode.substring(0, 1).equalsIgnoreCase("+") || !phoneCode.substring(1, phoneCode.length() - 1).matches("[0-9]+") || phoneCode.length() < 2 || phoneCode.length() > 6) { throw new BadRequestException("phone_code_not_valid", null); } } }
<mat-card> <div class="info-text"> <!-- <p> <mat-icon class="warning">warning</mat-icon>Masuratorile trebuie sa fie in metri (ex. 10.44 metri) </p> <p> <mat-icon class="warning">warning</mat-icon>Pierderile sunt calculate automat (unde e cazul) si incluse in suprafata finala </p> --> <p> <mat-icon class="warning">arrow_downward</mat-icon> Mai jos regasiti un clip video explicativ care o sa va ajute in transmiterea datelor corecte catre noi. <b class="warning">Vizionati-l cu atentie!</b> </p> </div> <iframe style="margin-left:50px;" width="600" height="315" src="https://www.youtube.com/embed/RUzuaNqmVNA" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen ></iframe> <hr /> <form #cpForm="ngForm" [formGroup]="cpFg" (ngSubmit)="submitCp()"> <mat-form-field appearance="outline"> <mat-label>Nume</mat-label> <input matInput formControlName="nume" required /> <mat-error *ngIf="cpFg.get('nume')?.invalid"> Numele este necesar </mat-error> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Prenume</mat-label> <input matInput formControlName="prenume" required /> <mat-error *ngIf="cpFg.get('prenume')?.invalid"> Prenumele este necesar </mat-error> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Email</mat-label> <input matInput type="email" formControlName="email" required /> <mat-error *ngIf="cpFg.get('email')?.invalid"> Email-ul este necesar </mat-error> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Adresa</mat-label> <input matInput type="adresa" formControlName="adresa" required /> <mat-error *ngIf="cpFg.get('adresa')?.invalid"> Adresa este necesara </mat-error> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Telefon</mat-label> <input matInput formControlName="telefon" required /> <mat-error *ngIf="cpFg.get('telefon')?.invalid"> Numarul de telefon este necesar </mat-error> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Incarca masuratorile</mat-label> <input matInput disabled /> <button type="button" mat-icon-button matSuffix (click)="fileInput.click()"> <mat-icon>attach_file</mat-icon> </button> <input #fileInput type="file" multiple="true" (change)="onFileChanged($event)" hidden /> </mat-form-field> <div class="file-el" *ngFor="let file of fileList; let index = index"> <span> - {{ file.name }}</span> <button mat-icon-button (click)="removeSelectedFile(index)" style="position: absolute; margin-top: -15px" > <mat-icon class="color-danger">close</mat-icon> </button> </div> <button mat-raised-button color="primary" type="submit">Trimite</button> </form> </mat-card>
import React from "react"; import style from "../../styles/Login.module.scss"; import { useDispatch, useSelector } from "react-redux"; import { Link, Navigate } from "react-router-dom"; import { useForm } from "react-hook-form"; import { fetchAuth, selectIsAuth } from "../../redux/slices/auth"; import LOGO from "../../assets/logo.png"; export const Login = () => { const dispatch = useDispatch(); const { register, handleSubmit, setError, formState: { errors, isValid }, } = useForm({ defaultValues: { email: "", password: "", }, mode: "onChange", }); const isAuth = useSelector(selectIsAuth); const onSubmit = async (values) => { const data = await dispatch(fetchAuth(values)); console.log(values); if (!data.payload) { return alert("Не удалось авторизоваться"); } if (data.payload.user) { localStorage.setItem("token", data.payload.accessToken); } }; if (isAuth) { return <Navigate to="/" />; } return ( <div> <form className={style.form} onSubmit={handleSubmit(onSubmit)}> <img src={LOGO} alt="" className={style.logo} /> <h2>Войти в аккаунт</h2> <input className={style.input} type="email" placeholder="Почта" {...register("email", { required: "Укажите почту" })} /> <input className={style.input} type="password" placeholder="Пароль" {...register("password", { required: "Укажите пароль" })} /> <button className={style.button} type="submit"> Войти </button> <Link to="/register" className={style.text}> У вас еще нету аккаунта ? </Link> </form> </div> ); };
import { useState } from "react"; import "./App.css"; import data from "./data/data.json"; enum Difficulty { SUPER_EASY = "super_easy", EASY = "easy", MEDIUM = "medium", HARD = "hard", SUPER_HARD = "super_hard", } type Star = { picture: string; name: string; difficulty?: Difficulty; }; function App() { const dataStars = data.data.reduce((acc: Star[], curr) => { const currentAlreadyInStars = acc.some((star) => star.name === curr.name); if (currentAlreadyInStars) { return acc; } return [...acc, { name: curr.name, picture: curr.img }]; }, []); const [stars, setStars] = useState<Star[]>(dataStars); const [validatedStars, setValidatedStars] = useState<Star[]>([]); const validateStar = (star: Star, difficulty: Difficulty, index: number) => { const validatedStarIndex = validatedStars.findIndex( (currentStar) => currentStar.name === star.name ); setValidatedStars([ ...(validatedStarIndex !== -1 ? validatedStars : validatedStars.splice(validatedStarIndex, 1)), { ...star, difficulty }, ]); }; const handleDownload = () => { const element = document.createElement("a"); const fileContent = JSON.stringify({ stars: validatedStars }); const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(fileContent); element.setAttribute("href", dataStr); element.setAttribute("download", "stars.json"); document.body.appendChild(element); element.click(); }; return ( <div className="App"> <header className="App-header"> <p> Il y a actuellement {validatedStars.length}/{stars.length} stars validées </p> <div className="stargrid"> {stars.map((star, index) => ( <div className="star" key={star.name}> <img src={star.picture} alt={star.name} /> <p>{star.name}</p> <div className="difficultyPicker"> <button name="difficulty" onClick={() => validateStar(star, Difficulty.SUPER_EASY, index) } > 1 </button> <button name="difficulty" onClick={() => validateStar(star, Difficulty.EASY, index)} > 2 </button> <button name="difficulty" onClick={() => validateStar(star, Difficulty.MEDIUM, index)} > 3 </button> <button name="difficulty" onClick={() => validateStar(star, Difficulty.HARD, index)} > 4 </button> <button name="difficulty" onClick={() => validateStar(star, Difficulty.SUPER_HARD, index) } > 5 </button> </div> </div> ))} </div> <button name="validate" onClick={() => handleDownload()}> Download </button> </header> </div> ); } export default App;
# Translation ## Links [Tutorial Link](https://www.youtube.com/watch?v=FsgdjUK9b5Q) [Package Link](https://github.com/MohmmedAshraf/laravel-translations) ## How To Add To Project First install the package with this command : ``` composer require outhebox/laravel-translations --with-all-dependencies ``` Then run the command to install the transaltor and migrate the tables : ``` php artisan translations:install ``` Now import your tranlsation files using this command : ``` php artisan translations:import ``` For Production Env we need to create a owner user first, for that we can use this command : ``` php artisan translations:contributor ``` You can access the Translation UI : ``<YOUR APP URL>/translations`` . Login with the user u have created and see the languages. You can add a language and add the translations for it (custom or from google translate) and then publish it so it can be viewed. I also added a middleware to automatically change the locale of app based on a query param or a header value. ```php class SetLocaleMiddleware { public function handle(Request $request, Closure $next): Response { if($request->has('locale')) { app()->setLocale($request->get('locale')); } if($request->hasHeader('locale')) { app()->setLocale($request->get('locale')); } return $next($request); } } ```
// // AutocorectionViewController.m // iDoctor // // Created by Stanimir Nikolov on 1/17/14. // Copyright (c) 2014 Stanimir Nikolov. All rights reserved. // #import "AutocorectionViewController.h" #import "EditDistance.h" #import "Constants.h" @interface AutocorectionViewController ()<UITableViewDataSource, UITableViewDelegate> { set<string> allMedicineNamesWords; NGramsOverlapWordFinder *ngramOverlap; dispatch_queue_t workingQueue; } @property (nonatomic, strong) IBOutlet UITableView* autocorectionTableView; @property (nonatomic, strong) NSMutableArray* autocorectedMedicineNames; @property (nonatomic, strong) NSString* typedText; @property (nonatomic, strong) NSUserDefaults* standartsDefaults; @property (strong, nonatomic) IBOutlet UINavigationItem *navigationTitleItem; @end @implementation AutocorectionViewController #pragma mark - view lifecycle - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; [self.view.layer setCornerRadius:6.0]; [self.view.layer setBorderColor:[[UIColor grayColor] CGColor]]; [self.view.layer setBorderWidth:1.0]; self.standartsDefaults = [NSUserDefaults standardUserDefaults]; // Do any additional setup after loading the view from its nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Setters -(void)setNGramDataStructure:(NGramsOverlapWordFinder*)_ngramOverlap { ngramOverlap = _ngramOverlap; } -(void)setAllMedicineNamesWords:(set<string>)_allMedicineNamesWords { allMedicineNamesWords = _allMedicineNamesWords; } #pragma mark - Autocorection methods -(void)populateAutoCorectionsWordsViaNgrams { NSArray* allTypedWords = [self.typedText.lowercaseString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; for (NSString* word in allTypedWords) { if(![word isEqualToString:@""]){ NSMutableArray* autocorectionForWord = [NSMutableArray array]; string cpp_typed_word([word UTF8String], [word lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); vector<pair<string, float> > words = ngramOverlap->getNearestWordsForWord(cpp_typed_word); for(int i = 0; i < words.size(); i++){ if(cpp_typed_word.compare(words[i].first) == 0){ autocorectionForWord = nil; break; } NSString* string = [NSString stringWithCString:words[i].first.c_str() encoding:NSUTF8StringEncoding]; [autocorectionForWord addObject:@{kWrongWordKey: word, kAutoCorrectedWordKey: string}]; } [self.autocorectedMedicineNames addObjectsFromArray:autocorectionForWord]; } } } -(void)populateAutoCorectionsWordsViaEdigDistance { NSArray* allTypedWords = [self.typedText.lowercaseString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; for (NSString* word in allTypedWords) { if(![word isEqualToString:@""]){ int minEditDistance = (int)word.length; string cpp_typed_word([word UTF8String], [word lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); NSMutableArray* autocorectionForWord = [NSMutableArray array]; for (set<string>::iterator it=allMedicineNamesWords.begin(); it!=allMedicineNamesWords.end(); ++it){ string existing_word = *it; if(existing_word.compare(cpp_typed_word) == 0){ autocorectionForWord = nil; break; } int current_distance = edit_distance(cpp_typed_word, existing_word); BOOL areTypedTextCloseToExistingWord = current_distance <= existing_word.length() / 3; if(current_distance < minEditDistance && areTypedTextCloseToExistingWord){ NSString* existingWord = [NSString stringWithCString:existing_word.c_str() encoding:NSUTF8StringEncoding]; autocorectionForWord = [NSMutableArray arrayWithObject:@{kWrongWordKey: word, kAutoCorrectedWordKey: existingWord}]; minEditDistance = current_distance; } else if(current_distance == minEditDistance && areTypedTextCloseToExistingWord){ NSString* existingWord = [NSString stringWithCString:existing_word.c_str() encoding:NSUTF8StringEncoding]; [autocorectionForWord addObject:@{kWrongWordKey: word, kAutoCorrectedWordKey: existingWord}]; } } [self.autocorectedMedicineNames addObjectsFromArray:autocorectionForWord]; } } } -(void)tryToAutoCorrectTheTypedText { self.typedText = nil; if([self.delegate respondsToSelector:@selector(typedTextForTypingHelper)]){ self.typedText = [self.delegate typedTextForTypingHelper]; } if(!self.typedText || [self.typedText isEqualToString:@""]){ if([self.delegate respondsToSelector:@selector(hideTypingHelperViewController:)]){ [self.delegate hideTypingHelperViewController:self]; } return; } if(!workingQueue){ workingQueue = dispatch_queue_create("AutocorectionQueue", DISPATCH_QUEUE_SERIAL); } dispatch_async(workingQueue, ^{ self.autocorectedMedicineNames = [[NSMutableArray alloc] init]; if ([self.standartsDefaults integerForKey:kAutocorectionType] == AutocorectionEditDistance) { [self populateAutoCorectionsWordsViaEdigDistance]; } else if([self.standartsDefaults integerForKey:kAutocorectionType] == AutocorectionTypeNGram){ [self populateAutoCorectionsWordsViaNgrams]; } //update UI dispatch_async(dispatch_get_main_queue(), ^{ if(self.autocorectedMedicineNames.count > 0){ if ([self.delegate respondsToSelector:@selector(presentTypingHelperViewController:)]) { [self.delegate presentTypingHelperViewController:self]; } [self.autocorectionTableView reloadData]; } else{ if ([self.delegate respondsToSelector:@selector(hideTypingHelperViewController:)]) { [self.delegate hideTypingHelperViewController:self]; } } }); }); } #pragma mark - UITableView data source -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.autocorectedMedicineNames.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString* autocorectionCellIdentifier = @"AutocorectedMedicineCell"; UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:autocorectionCellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:autocorectionCellIdentifier]; } NSString* wrongWord =[self.autocorectedMedicineNames[indexPath.row] objectForKey:kWrongWordKey]; NSString* autocorection =[self.autocorectedMedicineNames[indexPath.row] objectForKey:kAutoCorrectedWordKey]; NSString* medicineTitle = [NSString stringWithFormat:@"not %@ but %@", wrongWord, autocorection]; NSMutableAttributedString* medicineAttributedTitle = [[NSMutableAttributedString alloc] initWithString:medicineTitle attributes:nil]; //add bigger font and colors [medicineAttributedTitle setAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:22], NSForegroundColorAttributeName: [UIColor redColor]} range: NSMakeRange(4, wrongWord.length)]; [medicineAttributedTitle setAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:22], NSForegroundColorAttributeName: [UIColor blackColor]} range: NSMakeRange(4 + wrongWord.length + 5, autocorection.length)]; cell.textLabel.attributedText = medicineAttributedTitle; return cell; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; if([self.delegate respondsToSelector:@selector(replaceWrongWords:withAutocorectedWords:)]){ NSString* wrongWord =[self.autocorectedMedicineNames[indexPath.row] objectForKey:kWrongWordKey]; NSString* autocorection =[self.autocorectedMedicineNames[indexPath.row] objectForKey:kAutoCorrectedWordKey]; [self.delegate replaceWrongWords:wrongWord withAutocorectedWords:autocorection]; } if ([self.delegate respondsToSelector:@selector(hideTypingHelperViewController:)]) { [self.delegate hideTypingHelperViewController:self]; } } @end
import { createFeature, createReducer, on } from '@ngrx/store'; import { IHoliday } from 'src/app/models/Trip'; import * as HolidayActions from '../Ngrx-actions/holiday.actions'; export const holidayFeatureKey = 'holiday'; export interface HolidayState { holidays: IHoliday[]; selectedHolidayID: string; errorMessage: string; status: 'success' | 'error' | 'idle' | 'loading'; } export const initialState: HolidayState = { holidays: [], selectedHolidayID: '', errorMessage: '', status: 'idle', }; export const reducer = createReducer( initialState, on(HolidayActions.setSelectedHolidayID, (state, { idHoliday }) => { return { ...state, selectedHolidayID: idHoliday } }), on(HolidayActions.addHoliday, (state, { newHoliday }) => { return { ...state, holidays: [...state.holidays, newHoliday] } }), on(HolidayActions.deleteHoliday, (state, { idHoliday }) => { return { ...state, holidays: state.holidays.filter(holiday => holiday.id !== idHoliday) } }), on(HolidayActions.loadHolidays, state => ({ ...state, status: 'loading' })), on(HolidayActions.loadHolidaysSuccess, (state, { holidays }) => ({ ...state, holidays, error: null, status: 'success' })), on(HolidayActions.loadHolidaysFailure, (state, { error }) => ({ ...state, error: error, status: 'error' })) ); export const holidayFeature = createFeature({ name: holidayFeatureKey, reducer, });
# JavaFX Starter Template Dieses JavaFX Starter Template nutzt das Build-System [Gradle](https://gradle.org), um einfach ein Java Projekt mit Java 21 und JavaFX zu starten. ## Anleitung 1. Diesen Projektordner kopieren und beliebig benennen 2. (optional) in `settings.gradle` Eintrag `rootProject.name` an App-Namen anpassen 3. Projekt in beliebiger IDE/Text-Editor öffnen: 1. Eclipse: `File/Import/Gradle/Existing Gradle Project` 2. IntelliJ `File/Open` (dann ggf. `Import as Gradle Project`) 4. Gradle Dependencies installieren 1. Terminal Linux/MacOS: `./gradlew install`\ 2. Terminal Windows: `gradlew.bat install` 3. Mit Eclipse: Rechtsklick auf das Projekt, dann `Gradle/Refresh Gradle Project` 4. In IntelliJ: Rechts in der vertikalen Toolbar auf den Gradle-Elefanten klicken und dann auf das Reload Symbol 5. Sicherstellen, dass Project SDK korrekt gesetzt ist 1. In Eclipse unter `File/Properties/Java Build Path/Libraries` nachsehen 2. In IntellIJ unter `File/Project Structure/Project/SDK` nachsehen 6. JavaFX App starten: 1. Terminal Linux/MacOS: `./gradlew run` 2. Terminal Windows: `gradlew.bat run` 3. Eclipse: Im Menü unten auf `Gradle Tasks` dann `<app name>/application/run` 4. IntelliJ: Im Gradle-Menü rechts auf `<app name>/Tasks/application/run`
import { TestBed } from '@angular/core/testing'; import { HttpResponse } from '@angular/common/http'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ActivatedRouteSnapshot, ActivatedRoute, Router, convertToParamMap } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of } from 'rxjs'; import { ITicketEast } from '../ticket-east.model'; import { TicketEastService } from '../service/ticket-east.service'; import { TicketEastRoutingResolveService } from './ticket-east-routing-resolve.service'; describe('TicketEast routing resolve service', () => { let mockRouter: Router; let mockActivatedRouteSnapshot: ActivatedRouteSnapshot; let routingResolveService: TicketEastRoutingResolveService; let service: TicketEastService; let resultTicketEast: ITicketEast | null | undefined; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([])], providers: [ { provide: ActivatedRoute, useValue: { snapshot: { paramMap: convertToParamMap({}), }, }, }, ], }); mockRouter = TestBed.inject(Router); jest.spyOn(mockRouter, 'navigate').mockImplementation(() => Promise.resolve(true)); mockActivatedRouteSnapshot = TestBed.inject(ActivatedRoute).snapshot; routingResolveService = TestBed.inject(TicketEastRoutingResolveService); service = TestBed.inject(TicketEastService); resultTicketEast = undefined; }); describe('resolve', () => { it('should return ITicketEast returned by find', () => { // GIVEN service.find = jest.fn(id => of(new HttpResponse({ body: { id } }))); mockActivatedRouteSnapshot.params = { id: 123 }; // WHEN routingResolveService.resolve(mockActivatedRouteSnapshot).subscribe(result => { resultTicketEast = result; }); // THEN expect(service.find).toBeCalledWith(123); expect(resultTicketEast).toEqual({ id: 123 }); }); it('should return null if id is not provided', () => { // GIVEN service.find = jest.fn(); mockActivatedRouteSnapshot.params = {}; // WHEN routingResolveService.resolve(mockActivatedRouteSnapshot).subscribe(result => { resultTicketEast = result; }); // THEN expect(service.find).not.toBeCalled(); expect(resultTicketEast).toEqual(null); }); it('should route to 404 page if data not found in server', () => { // GIVEN jest.spyOn(service, 'find').mockReturnValue(of(new HttpResponse<ITicketEast>({ body: null }))); mockActivatedRouteSnapshot.params = { id: 123 }; // WHEN routingResolveService.resolve(mockActivatedRouteSnapshot).subscribe(result => { resultTicketEast = result; }); // THEN expect(service.find).toBeCalledWith(123); expect(resultTicketEast).toEqual(undefined); expect(mockRouter.navigate).toHaveBeenCalledWith(['404']); }); }); });
package com.ivanajocovic.weather.usecase import com.ivanajocovic.weather.networking.dto.WeatherResponse import com.ivanajocovic.weather.ui.CityWeatherUi import javax.inject.Inject class TransformWeatherResponseToWeatherUiUseCase @Inject constructor() { operator fun invoke(response: WeatherResponse): CityWeatherUi { return CityWeatherUi( cityName = response.name ?: "", temperature = response.main?.temp ?: 0.0, description = response.weather.firstOrNull()?.description ?: "", icon = response.weather.firstOrNull()?.icon ?: "" ) } }
import { ChangeEvent, useEffect, useState } from 'react'; import Button from '@mui/material/Button'; import Dialog from '@mui/material/Dialog'; import DialogActions from '@mui/material/DialogActions'; import DialogContent from '@mui/material/DialogContent'; import DialogContentText from '@mui/material/DialogContentText'; import DialogTitle from '@mui/material/DialogTitle'; import { useUpdateUserMutation } from './queries.generated' import { TextField } from '@mui/material'; interface UpdateUserModalProps { userId: string; userName: string; onClose: () => void; onComplete: () => void; } export const UpdateUserModal = ({ userId, userName, onClose, onComplete }: UpdateUserModalProps) => { const [inputValue, setInputValue] = useState<string>(userName); const [updateUser, { loading }] = useUpdateUserMutation({ onError: alert, onCompleted: onComplete, variables: { where: { id: userId, }, data: { name: { set: inputValue } } } }) const onSubmit = () => { updateUser() } const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => { setInputValue(event.target.value) } return ( <Dialog open aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title"> Update user? </DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> <TextField value={inputValue} onChange={handleInputChange} /> </DialogContentText> </DialogContent> <DialogActions> <Button onClick={onClose}>Disagree</Button> <Button onClick={onSubmit} autoFocus disabled={loading}> {loading ? "Updating" : "Agree"} </Button> </DialogActions> </Dialog> ); }
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import{HomeComponent} from './home/home.component'; import{TarefaComponent} from './tarefa/tarefa.component'; import{BuscaComponent} from './busca/busca.component'; const routes: Routes = [ {path: '', redirectTo: 'home', pathMatch: 'full'}, {path:'home', component: HomeComponent}, {path:'tarefa', component: TarefaComponent}, {path:'busca', component: BuscaComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
package com.example.lesson05; import java.util.*; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/lesson05") public class Lesson05Controller { // http://localhost/lesson05/ex01 @GetMapping("/ex01") public String ex01() { return "lesson05/ex01"; } @GetMapping("/ex02") public String ex02(Model model) { // List<String> List<String> fruits = new ArrayList<>(); fruits.add("apple"); fruits.add("melon"); fruits.add("mango"); fruits.add("orange"); fruits.add("peach"); model.addAttribute("fruits", fruits); // List<map> List<Map<String, Object>> users = new ArrayList<>(); Map<String, Object> user = new HashMap<>(); user.put("name", "이한민"); user.put("age", 22); user.put("hobby", "독서"); users.add(user); user = new HashMap<>(); user.put("name", "이찬민"); user.put("age", 21); user.put("hobby", "사냥하기"); users.add(user); model.addAttribute("users", user); return "lesson05/ex02"; } @GetMapping("/ex03") public String ex03(Model model) { Date now = new Date(); model.addAttribute("today", now); return "lesson05/ex03"; } @GetMapping("/ex04") public String ex04() { return "lesson05/ex04"; } }
import { StatusBar } from 'expo-status-bar' import * as Location from 'expo-location' import { Ionicons } from '@expo/vector-icons' import { StyleSheet, Text, View, ScrollView, Dimensions, ActivityIndicator, } from 'react-native' import React, { useState, useEffect } from 'react' import { Fontisto } from '@expo/vector-icons' import { DrawerLayoutAndroid } from 'react-native-web' const { width: SCREEN_WIDTH } = Dimensions.get('window') const API_KEY = 'e3fda37f28575ccc297f5fd81464fc73' const icons = { Clouds: 'cloudy', Clear: 'day-sunny', Atmosphere: 'cloudy-gusts', Snow: 'snow', Rain: 'rains', Drizzle: 'rain', Thunderstorm: 'lightning', } export default function App() { const [city, setCity] = useState('Loading...') const [days, setDays] = useState([]) const [ok, setOk] = useState(true) const getWeather = async () => { const { granted } = await Location.requestForegroundPermissionsAsync() if (!granted) { setOk(false) } const { coords: { latitude, longitude }, } = await Location.getCurrentPositionAsync({ accuracy: 5 }) const location = await Location.reverseGeocodeAsync( { latitude, longitude }, { useGoogleMaps: false }, ) setCity(location[0].name) const response = await fetch( `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=alerts&appid=${API_KEY}&units=metric`, ) const json = await response.json() setDays(json.daily) } useEffect(() => { getWeather() }, []) return ( <View style={styles.container}> <View style={styles.city}> <Text style={styles.cityName}>{city}</Text> </View> <ScrollView pagingEnabled horizontal contentContainerstyle={styles.weather} showsHorizontalScrollIndicator={false} > {days.length === 0 ? ( <View style={{ ...styles.day, alignItems: 'center' }}> <ActivityIndicator color="white" size="large" style={{ marginTop: 10 }} /> </View> ) : ( days.map((day, index) => ( <View key={index} style={styles.day}> <Text style={styles.tinyText}> {new Date(day.dt * 1000).toString().substring(0, 10)} </Text> <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', width: '100%', }} > <Text style={styles.temp}> {parseFloat(day.temp.day).toFixed(1)} </Text> <Fontisto name={icons[day.weather[0].main]} size={68} color="white" /> </View> <Text style={styles.description}>{day.weather[0].main}</Text> <Text style={styles.tinyText}>{day.weather[0].description}</Text> </View> )) )} </ScrollView> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#55D030', }, city: { flex: 1, justifyContent: 'center', alignItems: 'center', }, cityName: { fontSize: 48, fontWeight: '500', color: 'white', }, weather: {}, day: { width: SCREEN_WIDTH, alignItems: 'flex-start', paddingHorizontal: 20, }, temp: { marginTop: 50, fontWeight: '600', fontSize: 100, color: 'white', }, description: { marginTop: -10, fontSize: 30, color: 'white', fontWeight: '500', }, tinyText: { marginTop: -5, fontSize: 25, color: 'white', fontWeight: '500', }, })
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Top city</title> <jsp:include page="header.jsp" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" /> </head> <body> <section id="detail-page"> <nav> <div id="check" class="logo"> <a href="/PhoneAccessories/"><img id="image-logo" src='<c:url value="/resources/Image/YOP.png"/>' /></a> </div> <ul> <li><a href="/PhoneAccessories/">Home</a></li> <li><a href="#Products">Products</a></li> <li><a href="#Servises">Servises</a></li> <li> <div class="dropdown"> <button onclick="DropdownFunction()" class="note_dropdown">Catalouge</button> <div class="content_dropdown"> <c:forEach var="category" items="${categories}"> <a href='<c:url value="/category/${category.getCategory_id()}/${category.getCategory_name()}"/>'>${category.getCategory_name()}</a> </c:forEach> </div> </div> </li> </ul> <div class="icons"> <a id="cart-a" href="/PhoneAccessories/cart/"> <i id="addQuantity" class="fa-solid fa-cart-shopping"> <c:if test="${NumberOfProduct > 0}"> <div id="cart-number"> <span>${NumberOfProduct}</span> </div> </c:if> <c:if test="${NumberOfProduct <=0 || NumberOfProduct == null }"> <div id="cart-number"> <span>0</span> </div> </c:if> </i> </a> <c:choose> <c:when test="${fc != null}"> <a id="first-char" href="login/"> ${fc} </i></a> </c:when> <c:otherwise> <a href="/PhoneAccessories/login/"><i class="fa-solid fa-user"></i></a> </c:otherwise> </c:choose> </div> </nav> </section> <!-- Detail Product --> <div id="container-detail" class="container"> <div class="row"> <div id="product-category" class="col-sm-2 col-md-2"> <div> <span id="product-category-titile">Product Catalogue</span> </div> <ul id="product-category-ul"> <c:forEach var="category" items="${categories}"> <li><a href="#">${category.getCategory_name()}</a></li> </c:forEach> </ul> </div> <div class="col-sm-10 col-md-10"> <div class="products" id="Products"> <h1>${category_name}</h1> <div style="grid-template-columns: 1fr 1fr 1fr 1fr;" class="box "> <c:forEach var="product" items="${ListProducts}"> <div class="card"> <a href="/PhoneAccessories/detailproduct/${product.product_id}"> <div class="image"> <img src='<c:url value="/resources/Image/products/${product.getProduct_image()}"/>' /> </div> <div class="products_text"> <h2>${product.getProduct_name()}</h2> <h3>${product.getProduct_price()} <span>VND</span> </h3> <div class="products_star"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> </a> </div> </c:forEach> </div> </div> </div> </div> </div> <!--Footer--> <footer> <div class="footer_main"> <div class="tag"> <h1>Contact</h1> <a href="#"><i class="fa-solid fa-house"></i>123 - Ha Noi</a> <a href="#"><i class="fa-solid fa-phone"></i>0999 999 999</a> <a href="#"><i class="fa-solid fa-envelope"></i>topcity@gmail.com</a> </div> <div class="tag"> <h1>Get Help</h1> <a href="#" class="center">FAQ</a> <a href="#" class="center">Shipping</a> <a href="#" class="center">Returns</a> <a href="#" class="center">Payment Options</a> </div> <div class="tag"> <h1>Our Stores</h1> <a href="#" class="center">Ha Noi</a> <a href="#" class="center">TP Ho Chi Minh</a> <a href="#" class="center">Da Nang</a> <a href="#" class="center">Can Tho</a> </div> <div class="tag"> <h1>Follw Us</h1> <div class="social_link"> <a href="#"><i class="fa-brands fa-facebook-f"></i></a> <a href="#"><i class="fa-brands fa-twitter"></i></a> <a href="#"><i class="fa-brands fa-instagram"></i></a> <a href="#"><i class="fa-brands fa-linkedin-in"></i></a> </div> </div> <div class="tag"> <h1>For FeedBack</h1> <div class="search_bar"> <input type="text" placeholder="Enter the review"> <button type="submit">Submit</button> </div> </div> </div> </footer> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <jsp:include page="footer.jsp" /> </body> </html>
<template> <Transition name="slide-fade"> <div v-if="selectedResult != null && showPopup" class="popup"> <!--Popup Details--> <img :src="selectedResult.image" alt="Product Image" /> <div class="popup-details"> <p class="product-name">{{ selectedResult.name }}</p> <p class="product-category">{{ selectedResult.category }}</p> <p class="product-description">{{ selectedResult.description }}</p> <p class="product-price">${{ selectedResult.price.toFixed(2) }}</p> <div class="product_ratings"> <StarRating class="rating" :rating="selectedResult.ratings" /> </div> <!-- Additional Info --> <template v-if=" selectedResult.additionalOptions && selectedResult.additionalOptions.length > 0 " > <div v-for="option in selectedResult.additionalOptions" :key="option.Optionid" class="additional-options" > <p>{{ option.OptionName }}</p> <ul> <li v-for="item in option.items" :key="item.name"> <label class="checkbox style-c"> <input type="checkbox" v-model="item.selected" @change="handleOptionSelection(option, item)" :disabled="disableCheckbox(option, item)" /> <div class="checkbox__checkmark"></div> <div class="checkbox__body"> {{ item.name }} - ${{ item.price.toFixed(2) }} </div> </label> </li> </ul> </div> </template> <!-- Popup Buttons --> <button @click="addToCart(selectedResult)">Add to Cart</button> <button class="cross_btn" @click="closePopup"> <font-awesome-icon :icon="['fas', 'xmark']" class="Cross_icon" /> </button> </div> </div> </Transition> </template> <script setup lang="ts"> // Import necessary components import { ref, defineProps } from "vue"; import { useCartStore } from "../store/cart"; import StarRating from "./StarRating.vue"; // Initialize the cart store and other reactive variables const cartStore = useCartStore(); const { selectedResult } = defineProps(["selectedResult", "closePopup"]); const showPopup = ref(true); const selectedItems = ref([]); const disableCheckbox = (option, item) => { const selectedItemsCount = option.items.filter((i) => i.selected).length; return option.MultipleSelection && selectedItemsCount >= 3 && !item.selected; }; const handleOptionSelection = (option, selectedItem) => { const itemIndex = option.items.findIndex((item) => item === selectedItem); const selectedItemsCount = selectedItems.value.length; if (option.MultipleSelection) { } else { // Handle single selection logic option.items.forEach((item, index) => { item.selected = index === itemIndex; }); // Update the selectedItems array for single selection selectedItems.value = [option.items[itemIndex]]; } }; // Initialize the addToCart function const addToCart = (item: any) => { cartStore.addToCart(item); }; </script> <style lang="scss" scoped> @use "../styles/scss/utils/mixins" as mixins; .popup { max-height: 80vh; overflow-y: auto; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: white; padding: 20px; border: 1px solid #ccc; border-radius: 8px; z-index: 10011; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); max-width: 450px; width: 100%; text-align: center; img { max-width: 300px; height: 200px; border-radius: 4px; margin-bottom: 10px; } .popup-details { display: flex; flex-direction: column; .product-name { font-size: 28px; font-weight: bold; margin: 0px; } .product-category { font-size: 16px; font-weight: bold; margin: 0px; } .product-price { font-size: 16px; margin: 0px; } .product-description { font-size: 14px; color: #666; } .product_ratings { display: flex; justify-content: center; align-items: center; font-size: medium; } .additional-options { padding: 10px; text-align: start; p { font-size: 16px; font-weight: bold; margin: 0px; } ul { margin: 0px; padding: 0px; list-style: none; li { font-size: 14px; margin: 0px; padding: 0px; .checkbox.style-c { display: inline-block; position: relative; padding-left: 30px; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } input { position: absolute; opacity: 0; cursor: pointer; height: 0; width: 0; } .checkbox.style-c input:checked ~ .checkbox__checkmark { background-color: #f7cb15; } .checkbox.style-c input:checked ~ .checkbox__checkmark:after { opacity: 1; } .checkbox.style-c:hover input ~ .checkbox__checkmark { background-color: #eee; } .checkbox.style-c:hover input:checked ~ .checkbox__checkmark { background-color: #f7cb15; } .checkbox.style-c .checkbox__checkmark { position: absolute; top: 2px; left: 0; height: 20px; width: 20px; background-color: #eee; transition: background-color 0.25s ease; border-radius: 4px; } .checkbox.style-c .checkbox__checkmark:after { content: ""; position: absolute; left: 8px; top: 4px; width: 5px; height: 10px; border: solid #333; border-width: 0 2px 2px 0; transform: rotate(45deg); opacity: 0; transition: opacity 0.25s ease; } .checkbox.style-c .checkbox__body { color: #333; line-height: 1.4; font-size: 16px; } } } } button { margin-top: 10px; padding: 8px 16px; font-size: 14px; cursor: pointer; background-color: #ff8800; color: white; border: none; border-radius: 4px; font-family: "poppins"; transition: background-color 0.3s ease; &:hover { background-color: #df7804; } } .cross_btn { position: absolute; top: 15px; right: 20px; background-color: transparent; border: none; &:hover { background-color: #e9e9e9; } .Cross_icon { color: #ff8800; font-size: 20px; } } } .slide-fade-enter-active { transition: all 0.3s ease-out; } .slide-fade-leave-active { transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1); } .slide-fade-enter-from, .slide-fade-leave-to { transform: translateX(20px); opacity: 0; } } @include mixins.respond-to(0px, 768px) { .popup { max-width: 350px; width: 100%; .popup-details { .product-name { font-size: 24px; font-weight: bold; margin: 0px; } } } } @include mixins.respond-to(769px, 1024px) { .popup { max-width: 400px; width: 100%; .popup-details { .product-name { font-size: 28px; } } } } </style>
import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import Mask from '../Mask'; class Toast extends Component { constructor(props) { super(props); this.state = { isShow: false, timer: undefined }; } componentDidMount() { if (this.props.visible) { this.enter(); } } componentWillReceiveProps (nextProps) { clearTimeout(this.state.timer); if (!this.props.visible && nextProps.visible) { this.enter(); } else if (this.props.visible && !nextProps.visible) { this.leave(); } } componentWillUnmount() { clearTimeout(this.state.timer); } render () { const { visible, children, onMaskClick, className, ...others } = this.props; const cls = classnames({ 'ui-toast' : true, 'ui-toast-open' : this.state.isShow, [className] : !!className, }); return ( <div {...others} className={cls}> <div className="ui-toast-container"> {children} </div> <Mask visible={visible} type="transparent" onClose={onMaskClick} /> </div> ) } enter() { const { duration, onMaskClick } = this.props; this.setState({ isShow: true }); this.state.timer = setTimeout(() => { onMaskClick(); clearTimeout(this.state.timer); }, duration); } leave() { this.setState({ isShow: false }); } } Toast.propTypes = { visible : PropTypes.bool, duration : PropTypes.number, onMaskClick : PropTypes.func, }; Toast.defaultProps = { visible : false, duration : 3000, onMaskClick : () => {}, }; export default Toast;
import React, { useEffect, useRef, useState } from "react"; import "./categorylist.css"; import { SiKashflow } from "react-icons/si"; import { GrFilter } from "react-icons/gr"; import { toast } from "react-toastify"; import axios from "axios"; import Skeleton from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; import { Modal, Slider, InputNumber } from "antd"; import { NavLink } from "react-router-dom"; const CategoryList = ({ onCategoryClick, onAllClick, products, setPriceRange, }) => { // State to manage loading state of category list const [isLoading, setIsLoading] = useState(true); // State to store the category list const [categoryList, setCategoryList] = useState([]); // State to manage the visibility of the filter modal const [isFilterModalVisible, setIsFilterModalVisible] = useState(false); // State to manage the price range filter const [priceRange, setPriceRangeLocal] = useState([0, 30000]); // State to store the currently selected category const [selectedCategory, setSelectedCategory] = useState(null); // Effect to fetch category data when the component mounts useEffect(() => { getAllCategory(); }, []); // Ref to get the container element for smooth scrolling const containerRef = useRef(null); // Function to handle smooth scrolling of category list const handleMouseMove = (e) => { const container = containerRef.current; if (container) { // ... (existing smooth scrolling logic) } }; // Function to fetch all categories from the server const getAllCategory = async () => { try { const response = await axios.get( `${import.meta.env.VITE_REACT_APP_URL}/api/v1/category/allCategory` ); if (response.data.success) { // Set the fetched category list to state setCategoryList(response.data.allCategory); } } catch (error) { // Handle errors during category fetching if (error.response) { toast.error(error.response.data.message); } else { toast.error("Something went wrong"); } } finally { // Set loading state to false after category data is fetched setIsLoading(false); } }; // Function to show the filter modal const showFilterModal = () => { setIsFilterModalVisible(true); }; // Function to handle the OK action in the filter modal const handleFilterOk = () => { // Apply filter logic here setPriceRangeLocal(priceRange); // Update the local state setPriceRange(priceRange); // Update the parent state setIsFilterModalVisible(false); }; // Function to handle the Cancel action in the filter modal const handleFilterCancel = () => { setIsFilterModalVisible(false); }; // Function to filter products based on the price range const filteredProducts = products.filter((product) => { const productPrice = product.price; return productPrice >= priceRange[0] && productPrice <= priceRange[1]; }); // Log the current price range for debugging // console.log("Price Range in CategoryList:", priceRange); // Function to handle the reset of the filter const handleResetFilter = () => { window.location.reload(); // Reload the entire page }; // Function to handle a category click const handleCategoryClick = (category) => { setSelectedCategory(category); onCategoryClick(category); }; return ( <> {/* Main Category Section */} <section className="mainCategory"> {/* Left Section for Category List */} <div className="leftSection category " ref={containerRef} onMouseMove={handleMouseMove} > {/* Render skeleton loading or category list based on loading state */} {isLoading ? ( <div className="skeleton"> {[...Array(11)].map((_, index) => ( <div className="chilCategory" key={index}> <i> <Skeleton circle={true} height={30} width={30} /> </i> <p> <Skeleton height={10} width={55} /> </p> </div> ))} </div> ) : ( <> {/* Render "All" button */} <div className={`chilCategory ${ selectedCategory === null ? "activeCategory" : "" }`} onClick={() => { setSelectedCategory(null); onAllClick(); }} > {/* <i> <SiKashflow /> </i> */} <div> <p>All</p> </div> </div> {/* Render category list */} {categoryList?.length > 0 ? ( categoryList.map((category) => ( <div className={`chilCategory ${ selectedCategory === category ? "activeCategory" : "" }`} key={category._id} onClick={() => handleCategoryClick(category)} > {/* <i> <SiKashflow /> //this is for icon </i> */} <div className="categoryName"> <p>{category.name}</p> </div> </div> )) ) : ( <p>No categories available</p> )} </> )} </div> {/* Right Section for Filter */} <div className="righSection"> <div className="filter" onClick={showFilterModal}> <div className="filterbyPrice"> {/* <div className="filterIonc"><GrFilter className='icon' /></div> */} <div className="filterIonc"><img className="filterImg" src="/img/filter2.png" alt="" /></div> <span className="filterText"> Filters</span> </div> </div> </div> </section> {/* Ant Design Modal for Price Range Filter */} <Modal title="Filter By Price Range" open={isFilterModalVisible} onOk={handleFilterOk} onCancel={handleFilterCancel} okButtonProps={{ style: { backgroundColor: '#7571F9' } }} // Set background color for the Ok button cancelButtonProps={{ style: { backgroundColor: 'transparent', borderColor: '#7571F9', color: '#7571F9' } }} // Set styles for the Cancel button > {/* Slider for selecting price range */} <Slider range step={100} defaultValue={priceRange} min={0} max={30000} onChange={(value) => setPriceRangeLocal(value)} trackStyle={[{ backgroundColor: '#7571F9' }]} // Set track color for the Slider /> {/* InputNumber components for fine-tuning the selected price range */} <div style={{ display: "flex", justifyContent: "space-between" }}> <InputNumber style={{ width: 100, borderColor: '#7571F9'}} value={priceRange[0]} onChange={(value) => setPriceRangeLocal([value, priceRange[1]])} /> <InputNumber style={{ width: 100, borderColor: '#7571F9' }} value={priceRange[1]} onChange={(value) => setPriceRangeLocal([priceRange[0], value])} /> </div> {/* Reset button to reset the filter and reload the page */} <div style={{ marginTop: 16 }}> <button className="resetBtn" onClick={handleResetFilter}>Reset</button> </div> </Modal> </> ); }; export default CategoryList;
/* * Copyright (C) 2023 Guido Günther * * SPDX-License-Identifier: GPL-3-or-later */ /* This examples launches phosh and phoc emulationg the display of the given device tree compatible */ #define GMOBILE_USE_UNSTABLE_API #include "gmobile.h" #include <glib-unix.h> #include <glib/gstdio.h> #include <gio/gio.h> #include <glib/gprintf.h> #define PHOSH_BIN "/usr/libexec/phosh" GMainLoop *loop; GSubprocess *phoc; G_NORETURN static void print_version (void) { g_printf ("gm-emu-device--panel %s\n", GM_VERSION); exit (0); } static gboolean on_shutdown_signal (gpointer unused) { g_autoptr (GError) err = NULL; gboolean success; success = g_subprocess_wait (phoc, NULL, &err); if (!success) g_warning ("Failed to terminate phoc: %s", err->message); g_main_loop_quit (loop); return G_SOURCE_REMOVE; } static char * write_phoc_ini (GmDisplayPanel *panel, gdouble scale) { g_autoptr (GError) err = NULL; g_autoptr (GString) content = g_string_new ("[output:WL-1]\n"); g_autofree char *phoc_ini = NULL; int xres = gm_display_panel_get_x_res (panel); int yres = gm_display_panel_get_y_res (panel); int fd; g_string_append_printf (content, "mode = %dx%d\n", xres, yres); g_string_append_printf (content, "scale = %.2f\n", scale); fd = g_file_open_tmp ("phoc_XXXXXX.ini", &phoc_ini, &err); if (fd < 0) { g_critical ("Failed to open %s: %s", phoc_ini, err->message); return NULL; } if (write (fd, content->str, strlen (content->str)) < 0) { g_critical ("Failed to write %s", strerror (errno)); return NULL; } return g_steal_pointer (&phoc_ini); } int main (int argc, char **argv) { g_autoptr (GOptionContext) opt_context = NULL; gboolean version = FALSE; g_autoptr (GError) err = NULL; g_autoptr (GmDeviceInfo) info = NULL; g_auto (GStrv) compatibles = NULL; GmDisplayPanel *panel = NULL; GStrv compatibles_opt = NULL; g_autofree char *phoc_ini = NULL; g_autoptr (GSubprocessLauncher) phoc_launcher = NULL; double scale_opt; const GOptionEntry options [] = { {"compatible", 'c', 0, G_OPTION_ARG_STRING_ARRAY, &compatibles_opt, "Device tree compatibles to use for panel lookup ", NULL}, {"scale", 's', 1.0, G_OPTION_ARG_DOUBLE, &scale_opt, "The display scale", NULL }, {"version", 0, 0, G_OPTION_ARG_NONE, &version, "Show version information", NULL}, { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL } }; opt_context = g_option_context_new ("- emulate display panel"); g_option_context_add_main_entries (opt_context, options, NULL); if (!g_option_context_parse (opt_context, &argc, &argv, &err)) { g_warning ("%s", err->message); g_clear_error (&err); return EXIT_FAILURE; } if (version) print_version (); if (compatibles_opt && compatibles_opt[0]) { compatibles = g_strdupv (compatibles_opt); } else { compatibles = gm_device_tree_get_compatibles (NULL, &err); if (compatibles == NULL) { g_critical ("Failed to get compatibles: %s", err->message); return EXIT_FAILURE; } } info = gm_device_info_new ((const char *const *)compatibles); panel = gm_device_info_get_display_panel (info); if (panel == NULL) { g_critical ("Failed to find any panel"); return EXIT_FAILURE; } phoc_ini = write_phoc_ini (panel, scale_opt); if (!phoc_ini) return EXIT_FAILURE; g_message ("Using %s as phoc config", phoc_ini); phoc_launcher = g_subprocess_launcher_new (G_SUBPROCESS_FLAGS_SEARCH_PATH_FROM_ENVP); g_subprocess_launcher_set_environ (phoc_launcher, NULL); g_subprocess_launcher_setenv (phoc_launcher, "WLR_BACKENDS", "wayland", TRUE); g_subprocess_launcher_setenv (phoc_launcher, "GSETTINGS_BACKEND", "memory", TRUE); g_subprocess_launcher_setenv (phoc_launcher, "PHOC_DEBUG", "cutouts", TRUE); g_subprocess_launcher_setenv (phoc_launcher, "PHOSH_DEBUG", "fake-builtin", TRUE); g_subprocess_launcher_setenv (phoc_launcher, "G_MESSAGES_DEBUG", "phosh-layout-manager", TRUE); if (compatibles_opt && compatibles_opt[0]) { g_autofree char *opt = g_strjoinv (",", compatibles_opt); g_subprocess_launcher_setenv (phoc_launcher, "GMOBILE_DT_COMPATIBLES", opt, TRUE); } g_subprocess_launcher_setenv (phoc_launcher, "WLR_BACKENDS", "wayland", TRUE); phoc = g_subprocess_launcher_spawnv (phoc_launcher, (const char * const []) { "phoc", "-C", phoc_ini, "-E", PHOSH_BIN, NULL }, &err); g_unix_signal_add (SIGTERM, on_shutdown_signal, NULL); g_unix_signal_add (SIGINT, on_shutdown_signal, NULL); loop = g_main_loop_new (NULL, FALSE); g_message ("Launching phosh and phoc, hit CTRL-C to quit"); g_main_loop_run (loop); g_unlink (phoc_ini); g_clear_object (&phoc); g_clear_object (&loop); return EXIT_SUCCESS; }
#include "hash_tables.h" /** * hash_table_get - retrieves a value from the hash table * @ht: the hash table * @key: key associated with the value * * Return: key if succeed, NULLL if fail */ char *hash_table_get(const hash_table_t *ht, const char *key) { hash_node_t *node; unsigned long int i; if (ht == NULL || key == NULL || *key == '\0') return (NULL); i = key_index((const unsigned char *)key, ht->size); if (i >= ht->size) return (NULL); node = ht->array[i]; while (node && strcmp(node->key, key) != 0) node = node->next; return ((node == NULL) ? NULL : node->value); }
{ ********************************************************************* Copyright (C) 1997, 1998 Gertjan Schouten This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ********************************************************************* System Utilities For Free Pascal } { internal functions } Function DoEncodeDate(Year, Month, Day: Word): longint; Var D : TDateTime; begin If TryEncodeDate(Year,Month,Day,D) then Result:=Trunc(D) else Result:=0; end; function DoEncodeTime(Hour, Minute, Second, MilliSecond: word): TDateTime; begin If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then Result:=0; end; { Public functions } { ComposeDateTime converts a Date and a Time into one TDateTime } function ComposeDateTime(Date,Time : TDateTime) : TDateTime; begin if Date < 0 then Result := trunc(Date) - frac(Time) else Result := trunc(Date) + frac(Time); end; { DateTimeToTimeStamp converts DateTime to a TTimeStamp } function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp; begin result.Time := Trunc(abs(Frac(DateTime)) * MSecsPerDay); result.Date := DateDelta + trunc(DateTime); end ; { TimeStampToDateTime converts TimeStamp to a TDateTime value } function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime; begin Result := ComposeDateTime(TimeStamp.Date - DateDelta,TimeStamp.Time / MSecsPerDay) end; { MSecsToTimeStamp } function MSecsToTimeStamp(MSecs: comp): TTimeStamp; begin result.Date := Trunc(msecs / msecsperday); msecs:= comp(msecs-result.date*msecsperday); result.Time := Round(MSecs); end ; { TimeStampToMSecs } function TimeStampToMSecs(const TimeStamp: TTimeStamp): comp; begin result := TimeStamp.Time + comp(timestamp.date)*msecsperday; end ; Function TryEncodeDate(Year,Month,Day : Word; Var Date : TDateTime) : Boolean; var c, ya: cardinal; begin Result:=(Year>0) and (Year<10000) and (Month in [1..12]) and (Day>0) and (Day<=MonthDays[IsleapYear(Year),Month]); If Result then begin if month > 2 then Dec(Month,3) else begin Inc(Month,9); Dec(Year); end; c:= Year DIV 100; ya:= Year - 100*c; Date := (146097*c) SHR 2 + (1461*ya) SHR 2 + (153*cardinal(Month)+2) DIV 5 + cardinal(Day); // Note that this line can't be part of the line above, since TDateTime is // signed and c and ya are not Date := Date - 693900; end end; function TryEncodeTime(Hour, Min, Sec, MSec:word; Var Time : TDateTime) : boolean; begin Result:=(Hour<24) and (Min<60) and (Sec<60) and (MSec<1000); If Result then Time:=(Hour*3600000+Min*60000+Sec*1000+MSec)/MSecsPerDay; end; { EncodeDate packs three variables Year, Month and Day into a TDateTime value the result is the number of days since 12/30/1899 } function EncodeDate(Year, Month, Day: word): TDateTime; begin If Not TryEncodeDate(Year,Month,Day,Result) then Raise EConvertError.CreateFmt('%d-%d-%d is not a valid date specification', [Year,Month,Day]); end; { EncodeTime packs four variables Hour, Minute, Second and MilliSecond into a TDateTime value } function EncodeTime(Hour, Minute, Second, MilliSecond:word):TDateTime; begin If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then Raise EConvertError.CreateFmt('%d:%d:%d.%d is not a valid time specification', [Hour,Minute,Second,MilliSecond]); end; { DecodeDate unpacks the value Date into three values: Year, Month and Day } procedure DecodeDate(Date: TDateTime; var Year, Month, Day: word); var ly,ld,lm,j : cardinal; begin if Date <= -datedelta then // If Date is before 1-1-1 then return 0-0-0 begin Year := 0; Month := 0; Day := 0; end else begin j := pred((Trunc(System.Int(Date)) + 693900) SHL 2); ly:= j DIV 146097; j:= j - 146097 * cardinal(ly); ld := j SHR 2; j:=(ld SHL 2 + 3) DIV 1461; ld:= (cardinal(ld) SHL 2 + 7 - 1461*j) SHR 2; lm:=(5 * ld-3) DIV 153; ld:= (5 * ld +2 - 153*lm) DIV 5; ly:= 100 * cardinal(ly) + j; if lm < 10 then inc(lm,3) else begin dec(lm,9); inc(ly); end; year:=ly; month:=lm; day:=ld; end; end; function DecodeDateFully(const DateTime: TDateTime; var Year, Month, Day, DOW: Word): Boolean; begin DecodeDate(DateTime,Year,Month,Day); DOW:=DayOfWeek(DateTime); Result:=IsLeapYear(Year); end; { DecodeTime unpacks Time into four values: Hour, Minute, Second and MilliSecond } procedure DecodeTime(Time: TDateTime; var Hour, Minute, Second, MilliSecond: word); Var l : cardinal; begin l := Round(abs(Frac(time)) * MSecsPerDay); Hour := l div 3600000; l := l mod 3600000; Minute := l div 60000; l := l mod 60000; Second := l div 1000; l := l mod 1000; MilliSecond := l; end; { DateTimeToSystemTime converts DateTime value to SystemTime } procedure DateTimeToSystemTime(DateTime: TDateTime; var SystemTime: TSystemTime); begin DecodeDate(DateTime, SystemTime.Year, SystemTime.Month, SystemTime.Day); DecodeTime(DateTime, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond); end ; { SystemTimeToDateTime converts SystemTime to a TDateTime value } function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime; begin result := ComposeDateTime(DoEncodeDate(SystemTime.Year, SystemTime.Month, SystemTime.Day), DoEncodeTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond)); end ; { DayOfWeek returns the Day of the week (sunday is day 1) } function DayOfWeek(DateTime: TDateTime): integer; begin Result := 1 + (Abs(Trunc(DateTime) - 1) mod 7); end ; { Date returns the current Date } function Date: TDateTime; var SystemTime: TSystemTime; begin GetLocalTime(SystemTime); result := DoEncodeDate(SystemTime.Year, SystemTime.Month, SystemTime.Day); end ; { Time returns the current Time } function Time: TDateTime; var SystemTime: TSystemTime; begin GetLocalTime(SystemTime); Result := DoEncodeTime(SystemTime.Hour,SystemTime.Minute,SystemTime.Second,SystemTime.MilliSecond); end ; { Now returns the current Date and Time } function Now: TDateTime; var SystemTime: TSystemTime; begin GetLocalTime(SystemTime); result := systemTimeToDateTime(SystemTime); end; { IncMonth increments DateTime with NumberOfMonths months, NumberOfMonths can be less than zero } function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime; var Year, Month, Day : word; S : Integer; begin If NumberOfMonths>=0 then s:=1 else s:=-1; DecodeDate(DateTime, Year, Month, Day); inc(Year,(NumberOfMonths div 12)); inc(Month,(NumberOfMonths mod 12)-1); // Mod result always positive if Month>11 then begin Dec(Month, S*12); Inc(Year, S); end; Inc(Month); { Months from 1 to 12 } If (Day>MonthDays[IsLeapYear(Year)][Month]) then Day:=MonthDays[IsLeapYear(Year)][Month]; result := Frac(DateTime) + DoEncodeDate(Year, Month, Day); end ; { IsLeapYear returns true if Year is a leap year } function IsLeapYear(Year: Word): boolean; begin Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0)); end; { DateToStr returns a string representation of Date using ShortDateFormat } function DateToStr(Date: TDateTime): string; begin result := FormatDateTime('ddddd', Date); end ; { TimeToStr returns a string representation of Time using ShortTimeFormat } function TimeToStr(Time: TDateTime): string; begin result := FormatDateTime('t', Time); end ; { DateTimeToStr returns a string representation of DateTime using ShortDateTimeFormat } function DateTimeToStr(DateTime: TDateTime): string; begin result := FormatDateTime('c', DateTime); end ; { StrToDate converts the string S to a TDateTime value if S does not represent a valid date value an EConvertError will be raised } function StrToDate(const S: string): TDateTime; var df:string; d,m,y,ly:word; n,i:longint; c:word; dp,mp,yp,which : Byte; s1:string[4]; values:array[1..3] of longint; LocalTime:tsystemtime; begin df := UpperCase(ShortDateFormat); { Determine order of D,M,Y } yp:=0; mp:=0; dp:=0; Which:=0; i:=0; while (i<Length(df)) and (Which<3) do begin inc(i); Case df[i] of 'Y' : if yp=0 then begin Inc(Which); yp:=which; end; 'M' : if mp=0 then begin Inc(Which); mp:=which; end; 'D' : if dp=0 then begin Inc(Which); dp:=which; end; end; end; if Which<>3 then Raise EConvertError.Create('Illegal format string'); { Get actual values } for i := 1 to 3 do values[i] := 0; s1 := ''; n := 0; for i := 1 to length(s) do begin if (s[i] in ['0'..'9']) then s1 := s1 + s[i]; if (s[i] in [dateseparator,' ']) or ((i = length(s)) and (s[i] in ['0'..'9'])) then begin inc(n); if n>3 then Raise EConvertError.Create('Invalid date format'); val(s1, values[n], c); if c<>0 then Raise EConvertError.Create('Invalid date format'); s1 := ''; end else if not (s[i] in ['0'..'9']) then Raise EConvertError.Create('Invalid date format'); end ; // Fill in values. getLocalTime(LocalTime); ly := LocalTime.Year; If N=3 then begin y:=values[yp]; m:=values[mp]; d:=values[dp]; end Else begin Y:=ly; If n<2 then begin d:=values[1]; m := LocalTime.Month; end else If dp<mp then begin d:=values[1]; m:=values[2]; end else begin d:=values[2]; m:=values[1]; end; end; if (y >= 0) and (y < 100) then begin ly := ly - TwoDigitYearCenturyWindow; Inc(Y, ly div 100 * 100); if (TwoDigitYearCenturyWindow > 0) and (Y < ly) then Inc(Y, 100); end; Result := EncodeDate(y, m, d); end ; { StrToTime converts the string S to a TDateTime value if S does not represent a valid time value an EConvertError will be raised } function StrToTime(const s: string): TDateTime; var Len, Current: integer; PM: boolean; function GetElement: integer; var j: integer; c: word; begin result := -1; Inc(Current); while (result = -1) and (Current < Len) do begin if S[Current] in ['0'..'9'] then begin j := Current; while (Current < Len) and (s[Current + 1] in ['0'..'9']) do Inc(Current); val(copy(S, j, 1 + Current - j), result, c); end else if (S[Current] = TimeAMString[1]) or (S[Current] in ['a', 'A']) then begin Current := 1 + Len; end else if (S[Current] = TimePMString[1]) or (S[Current] in ['p', 'P']) then begin Current := 1 + Len; PM := True; end else if (S[Current] = TimeSeparator) or (S[Current] = ' ') then Inc(Current) else raise EConvertError.Create('Invalid Time format'); end ; end ; var i: integer; TimeValues: array[0..4] of integer; begin Current := 0; Len := length(s); PM := False; for i:=0 to 4 do timevalues[i]:=0; i := 0; TimeValues[i] := GetElement; while (i < 5) and (TimeValues[i] <> -1) do begin i := i + 1; TimeValues[i] := GetElement; end ; If (i<5) and (TimeValues[I]=-1) then TimeValues[I]:=0; if PM then Inc(TimeValues[0], 12); result := EncodeTime(TimeValues[0], TimeValues[1], TimeValues[2], TimeValues[3]); end ; { StrToDateTime converts the string S to a TDateTime value if S does not represent a valid date and time value an EConvertError will be raised } function StrToDateTime(const s: string): TDateTime; var i: integer; begin i := pos(' ', s); if i > 0 then result := ComposeDateTime(StrToDate(Copy(S, 1, i - 1)), StrToTime(Copy(S, i + 1, length(S)))) else result := StrToDate(S); end ; { FormatDateTime formats DateTime to the given format string FormatStr } function FormatDateTime(FormatStr: string; DateTime: TDateTime): string; var ResultLen: integer; ResultBuffer: array[0..255] of char; ResultCurrent: pchar; procedure StoreStr(Str: pchar; Len: integer); begin if ResultLen + Len < SizeOf(ResultBuffer) then begin StrMove(ResultCurrent, Str, Len); ResultCurrent := ResultCurrent + Len; ResultLen := ResultLen + Len; end ; end ; procedure StoreString(const Str: string); var Len: integer; begin Len := Length(Str); if ResultLen + Len < SizeOf(ResultBuffer) then begin StrMove(ResultCurrent, pchar(Str), Len); ResultCurrent := ResultCurrent + Len; ResultLen := ResultLen + Len; end; end; procedure StoreInt(Value, Digits: integer); var S: string; Len: integer; begin S := IntToStr(Value); Len := Length(S); if Len < Digits then begin S := copy('0000', 1, Digits - Len) + S; Len := Digits; end ; StoreStr(pchar(@S[1]), Len); end ; Function TimeReFormat(Const S : string) : string; // Change m into n for time formatting. Var i : longint; begin Result:=S; For I:=1 to Length(Result) do If Result[i]='m' then result[i]:='n'; end; var Year, Month, Day, DayOfWeek, Hour, Minute, Second, MilliSecond: word; procedure StoreFormat(const FormatStr: string); var Token,lastformattoken: char; FormatCurrent: pchar; FormatEnd: pchar; Count: integer; Clock12: boolean; P: pchar; tmp:integer; begin FormatCurrent := Pchar(FormatStr); FormatEnd := FormatCurrent + Length(FormatStr); Clock12 := false; P := FormatCurrent; while P < FormatEnd do begin Token := UpCase(P^); if Token in ['"', ''''] then begin P := P + 1; while (P < FormatEnd) and (P^ <> Token) do P := P + 1; end else if Token = 'A' then begin if (StrLIComp(P, 'A/P', 3) = 0) or (StrLIComp(P, 'AMPM', 4) = 0) or (StrLIComp(P, 'AM/PM', 5) = 0) then begin Clock12 := true; break; end ; end ; P := P + 1; end ; token:=#255; lastformattoken:=' '; while FormatCurrent < FormatEnd do begin Token := UpCase(FormatCurrent^); Count := 1; P := FormatCurrent + 1; case Token of '''', '"': begin while (P < FormatEnd) and (p^ <> Token) do P := P + 1; P := P + 1; Count := P - FormatCurrent; StoreStr(FormatCurrent + 1, Count - 2); end ; 'A': begin if StrLIComp(FormatCurrent, 'AMPM', 4) = 0 then begin Count := 4; if Hour < 12 then StoreString(TimeAMString) else StoreString(TimePMString); end else if StrLIComp(FormatCurrent, 'AM/PM', 5) = 0 then begin Count := 5; if Hour < 12 then StoreStr('am', 2) else StoreStr('pm', 2); end else if StrLIComp(FormatCurrent, 'A/P', 3) = 0 then begin Count := 3; if Hour < 12 then StoreStr('a', 1) else StoreStr('p', 1); end else Raise EConvertError.Create('Illegal character in format string'); end ; '/': StoreStr(@DateSeparator, 1); ':': StoreStr(@TimeSeparator, 1); ' ', 'C', 'D', 'H', 'M', 'N', 'S', 'T', 'Y','Z' : begin while (P < FormatEnd) and (UpCase(P^) = Token) do P := P + 1; Count := P - FormatCurrent; case Token of ' ': StoreStr(FormatCurrent, Count); 'Y': begin if Count>2 then StoreInt(Year, 4) else StoreInt(Year mod 100, 2); end; 'M': begin if lastformattoken='H' then begin if Count = 1 then StoreInt(Minute, 0) else StoreInt(Minute, 2); end else begin case Count of 1: StoreInt(Month, 0); 2: StoreInt(Month, 2); 3: StoreString(ShortMonthNames[Month]); 4: StoreString(LongMonthNames[Month]); end; end; end; 'D': begin case Count of 1: StoreInt(Day, 0); 2: StoreInt(Day, 2); 3: StoreString(ShortDayNames[DayOfWeek]); 4: StoreString(LongDayNames[DayOfWeek]); 5: StoreFormat(ShortDateFormat); 6: StoreFormat(LongDateFormat); end ; end ; 'H': begin if Clock12 then begin tmp:=hour mod 12; if tmp=0 then tmp:=12; if Count = 1 then StoreInt(tmp, 0) else StoreInt(tmp, 2); end else begin if Count = 1 then StoreInt(Hour, 0) else StoreInt(Hour, 2); end ; end ; 'N': begin if Count = 1 then StoreInt(Minute, 0) else StoreInt(Minute, 2); end ; 'S': begin if Count = 1 then StoreInt(Second, 0) else StoreInt(Second, 2); end ; 'Z': begin if Count = 1 then StoreInt(MilliSecond, 0) else StoreInt(MilliSecond, 3); end ; 'T': begin if Count = 1 then StoreFormat(timereformat(ShortTimeFormat)) else StoreFormat(TimeReformat(LongTimeFormat)); end ; 'C': begin StoreFormat(ShortDateFormat); if (Hour<>0) or (Minute<>0) or (Second<>0) then begin StoreString(' '); StoreFormat(TimeReformat(ShortTimeFormat)); end; end; end; lastformattoken:=token; end; else StoreStr(@Token, 1); end ; FormatCurrent := FormatCurrent + Count; end ; end ; begin DecodeDateFully(DateTime, Year, Month, Day, DayOfWeek); DecodeTime(DateTime, Hour, Minute, Second, MilliSecond); ResultLen := 0; ResultCurrent := @ResultBuffer; StoreFormat(FormatStr); ResultBuffer[ResultLen] := #0; result := StrPas(@ResultBuffer); end ; { DateTimeToString formats DateTime to the given format in FormatStr } procedure DateTimeToString(var Result: string; const FormatStr: string; const DateTime: TDateTime); begin Result := FormatDateTime(FormatStr, DateTime); end ; Function DateTimeToFileDate(DateTime : TDateTime) : Longint; Var YY,MM,DD,H,m,s,msec : Word; begin Decodedate (DateTime,YY,MM,DD); DecodeTime (DateTime,h,m,s,msec); {$ifndef unix} If (YY<1980) or (YY>2099) then Result:=0 else begin Result:=(s shr 1) or (m shl 5) or (h shl 11); Result:=Result or DD shl 16 or (MM shl 21) or ((YY-1980) shl 25); end; {$else unix} Result:=LocalToEpoch(yy,mm,dd,h,m,s); {$endif unix} end; function CurrentYear:Word; var yy,mm,dd : word; begin Decodedate(now,yy,mm,dd); Result:=yy; end; Function FileDateToDateTime (Filedate : Longint) : TDateTime; {$ifndef unix} Var Date,Time : Word; begin Date:=FileDate shr 16; Time:=FileDate and $ffff; Result:=ComposeDateTime(EncodeDate((Date shr 9) + 1980,(Date shr 5) and 15, Date and 31), EncodeTime(Time shr 11, (Time shr 5) and 63, (Time and 31) shl 1,0)); end; {$else unix} var y, mon, d, h, min, s: word; begin EpochToLocal(FileDate,y,mon,d,h,min,s); Result:=ComposeDateTime(EncodeDate(y,mon,d),EncodeTime(h,min,s,0)); end; {$endif unix} function TryStrToDate(const S: string; out Value: TDateTime): Boolean; begin result:=true; try value:=StrToDate(s); except on EConvertError do result:=false end; end; // function TryStrToDate(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean; function TryStrToTime(const S: string; out Value: TDateTime): Boolean; begin result:=true; try value:=StrToTime(s); except on EConvertError do result:=false end; end; // function TryStrToTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean; function TryStrToDateTime(const S: string; out Value: TDateTime): Boolean; begin result:=true; try value:=StrToDateTime(s); except on EConvertError do result:=false end; end; // function TryStrToDateTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
Nhom 9: Sciprt # dim date CREATE TABLE [Dim_Date] ( [Full Day] datetime, [Year] int, [Quarter] int, [Month] int, [Day] int, [Hour] int, [Minute] int, [Date Key] nvarchar(70), CONSTRAINT PK_Date PRIMARY KEY ([Date Key]) ) # dim category CREATE TABLE [Dim_Category] ( [Category Id] int, [Category Name] varchar(50), CONSTRAINT PK_Category PRIMARY KEY ([Category Id]) ) # dim location CREATE TABLE [Dim_Location] ( [Location Id] int not null, [Customer Street] varchar(50), [Customer City] varchar(50), [Customer Country] varchar(50), [Customer State] varchar(50), CONSTRAINT PK_Location PRIMARY KEY ([Location Id]) ) # date key (DT_STR,14,1252)DATEPART("yyyy", [Full Day]) + RIGHT("0" + (DT_STR,2,1252)DATEPART("mm", [Full Day]), 2) + RIGHT("0" + (DT_STR,2,1252)DATEPART("dd", [Full Day]), 2) + RIGHT("0" + (DT_STR,2,1252)DATEPART("hh", [Full Day]), 2) + RIGHT("0" + (DT_STR,2,1252)DATEPART("mi", [Full Day]), 2) # dim department CREATE TABLE [Dim_Department] ( [Department Id] int, [Department Name] varchar(50), CONSTRAINT PK_Department PRIMARY KEY ([Department Id]) ) # dim ship CREATE TABLE [Dim_Ship] ( [Ship Key] int identity not null, [Delivery Status] varchar(50), [Shipping Mode] varchar(50), [Ship Id] int, [Days for shipping (real)] int, [Days for shipment (scheduled)] int, CONSTRAINT PK_Ship PRIMARY KEY ([Ship Key]) ) # dim status CREATE TABLE [Dim_Status] ( [Status Key] int identity not null, [Order Status] varchar(50), [Status Id] int, CONSTRAINT PK_Status PRIMARY KEY ([Status Key]) ) # dim purchase CREATE TABLE [Dim_Purchase] ( [Purchase Key] int identity not null, [Type] varchar(50), [Type Id] int, CONSTRAINT PK_Purchase PRIMARY KEY ([Purchase Key]) ) # dim customer CREATE TABLE [Dim_Customer] ( [Customer Key] int identity not null, [Customer Id] int, [Customer Fname] varchar(50), [Customer Lname] varchar(50), [Location Id] int, CONSTRAINT PK_Customer PRIMARY KEY ([Customer Key]), constraint FK_LocationId foreign key ([Location Id]) references Dim_Location ([Location Id]) ) # dim product CREATE TABLE [Dim_Product] ( [Product Key] int identity not null, [Product Card Id] int, [Product Name] varchar(50), [Product Price] real, [Product Image] varchar(255), [Product Category Id] int, [Department Id] int, CONSTRAINT PK_Product PRIMARY KEY ([Product Key]), constraint FK_Category foreign key ([Product Category Id]) references Dim_Category ([Category Id]), constraint FK_Department foreign key ([Department Id]) references Dim_Department ([Department Id]) ) # fact sale CREATE TABLE [FactSale] ( [Order Item Id] int not null, [Order Id] int, [Customer Key] int, [Product Key] int, [Ship Key] int, [Status Key] int, [Purchase Key] int, [Date Key] nvarchar(70), [SoldAmount] real, [DiscountAmount] real, [ProfitAmount] real, [OrderToShippedLagInDays] int, CONSTRAINT PK_FactSale PRIMARY KEY ([Order Item Id]) ) # excute query task alter table FactSale add constraint FK_ProductKey FOREIGN KEY ([Product Key]) references Dim_Product ([Product Key]) alter table FactSale add constraint FK_StatusKey FOREIGN KEY ([Status Key]) references Dim_Status ([Status Key]) alter table FactSale add constraint FK_ShipKey FOREIGN KEY ([Ship Key]) references Dim_Ship ([Ship Key]) alter table FactSale add constraint FK_CustomerKey FOREIGN KEY ([Customer Key]) references Dim_Customer ([Customer Key]) alter table FactSale add constraint FK_PurchaseKey FOREIGN KEY ([Purchase Key]) references Dim_Purchase ([Purchase Key]) alter table FactSale add constraint FK_DateKey FOREIGN KEY ([Date Key]) references Dim_Date ([Date Key]) # drop constraint
"""Implement the following view functions. """ from flask import Flask from webargs import fields from webargs.flaskparser import use_kwargs from lesson_04_hw_04.execute_query import execute_query from lesson_04_hw_04.format import format_records app = Flask(__name__) @app.route("/order-price") @use_kwargs( { 'country': fields.Str( load_default=None) }, location='query' ) def order_price(country): """ Function calculate sales by country on page / if no country show all sales by all counties. """ if country: query = "SELECT SUM(invoice_items.UnitPrice * invoice_items.Quantity) AS Sales, invoices.BillingCountry" \ " FROM invoice_items JOIN invoices ON invoice_items.InvoiceId==invoices.InvoiceId " \ f"GROUP BY invoices.BillingCountry HAVING invoices.BillingCountry=='{country}'" else: query = "SELECT SUM(invoice_items.UnitPrice * invoice_items.Quantity) AS Sales, invoices.BillingCountry" \ " FROM invoice_items JOIN invoices ON invoice_items.InvoiceId==invoices.InvoiceId " \ "GROUP BY invoices.BillingCountry" records = execute_query(query) return format_records(records) @app.route("/track-info") @use_kwargs( { 'id': fields.Int( required=True ) }, location='query' ) def get_all_info_about_track(id): """Function gives information about track. """ query = "SELECT tracks.TrackId, tracks.Name, tracks.Composer, albums.Title," \ " artists.Name, genres.Name, media_types.Name" \ " FROM tracks JOIN albums ON tracks.AlbumId = albums.AlbumId" \ " JOIN artists ON albums.ArtistId = artists.ArtistId" \ " JOIN genres ON tracks.GenreId = genres.GenreId" \ " JOIN media_types ON tracks.MediaTypeId = media_types.MediaTypeId" \ f" GROUP BY tracks.TrackId HAVING tracks.TrackId=='{id}'" records = execute_query(query) if len(records) == 0: return f'Track {id} is not exist!' else: return records @app.route("/track-time") def get_all_info_about_track_time(): """Function calculate all track time in albums. """ query = "SELECT albums.Title, (SUM(tracks.Milliseconds) / 1000.0 / 3600.0)" \ " FROM tracks JOIN albums ON tracks .AlbumId = albums.AlbumId" \ " GROUP BY albums.Title" records = execute_query(query) return format_records(records) app.run(port=5000, debug=True)
import { motion, } from 'framer-motion' import { twMerge } from 'tailwind-merge' import { styles } from '../styles' import { staggerContainer, slideRightVariant, scaleHeight } from '../utils/motion' const SectionWrapper = (Component, idName) => function HOC() { return ( <> <motion.section variants={staggerContainer()} initial="hidden" whileInView="show" viewport={{ once: false }} // viewport={{ once: false, amount: 0.25 }} className={twMerge(styles.padding, "max-w-7xl mx-auto z-0")} > {/* scrolls to this invisible span via scroll button */} <motion.span className="hash-span" id={idName} > &nbsp; </motion.span> <motion.div className="relative"> <motion.i variants={slideRightVariant("spring", 0.2)} className="dark:text-accent-2 text-accent-2-lt absolute -top-6 md:-left-10 hidden md:block" > {`<${idName || 'section'}>`} </motion.i> <motion.div variants={scaleHeight("tween", 0.2)} className="w-[1.5px] dark:bg-accent-1 bg-accent-1-lt h-full absolute md:-left-8 hidden md:block" /> <motion.i variants={slideRightVariant("spring", 0.4)} className="dark:text-accent-2 text-accent-2-lt absolute -bottom-6 md:-left-10 hidden md:block" > {`</${idName || 'section'}>`} </motion.i> <Component /> </motion.div> </motion.section> </> ) } export default SectionWrapper
package co.iostream.apps.android.io_private.ui.composables import android.widget.Toast import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.slideInVertically import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import kotlinx.coroutines.delay @Composable fun FloatButtonX(){ val contextForToast = LocalContext.current.applicationContext var visible by remember { mutableStateOf(true) } LaunchedEffect(Unit) { delay(300) visible = true } AnimatedVisibility( visible = visible, enter = fadeIn() + slideInVertically { fullHeight -> fullHeight }, ) { FloatingActionButton( onClick = { Toast.makeText(contextForToast, "FAB", Toast.LENGTH_SHORT) .show() } ) { Icon(imageVector = Icons.Default.Add, contentDescription = "add icon") } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <link rel="stylesheet" type="text/css" href="./assets/styles/main.scss" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Alfa+Slab+One&display=swap" rel="stylesheet" /> <link rel="icon" href="./assets/images/photo-band3.jpg" /> <!-- do not remove this line! --> <title>Rock & Rolla</title> </head> <body> <header> <nav class="navbar navbar-expand-md navbar-light bg-light mx-sm-5 mt-sm-5" > <div class="container-fluid"> <a class="navbar-brand" href="/"> <img src="./assets/images/photo-band3.jpg" alt="Guitar photo logo" width="80" height="80" class="align-text-center rounded-circle" /> <span class="brand-font">R & R</span> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse flex-sm-grow-0" id="navbarNav" > <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="./members.html" >The Band</a > </li> <li class="nav-item"> <a class="nav-link" href="./info.html">News</a> </li> <li class="nav-item"> <a class="nav-link" href="./form.html" >Something to say?</a > </li> </ul> </div> </div> </nav> </header> <main> <section class="hero"> <img class="hero__img" src="./assets/images/photo-band4.jpg" alt="Band photo" /> <h1 class="brand-font title"> <span class="title__one">Rock</span> <span class="title__two">&</span> <span class="title__three">Rolla</span> </h1> </section> <section class="card w-75 mt-5 mx-auto"> <h2 class="card-header text-center bg-band-color"> Next Events </h2> <div class="card-body"> <p class="events__text"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> <p class="events__text"> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> <p class="events__text"> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p> </div> </section> </main> <footer class="footer"> <nav class="navbar nav-bottom navbar-light bg-light"> <div class="nav-bottom"> <a class="navbar-brand me-5" href="/"> <img src="./assets/images/photo-band3.jpg" alt="Guitar photo logo" width="80" height="80" class="align-text-center rounded-circle" /> <span class="brand-font">R & R</span> </a> <ul class="navbar-nav nav-bottom"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/" >Home</a > </li> <li class="nav-item"> <a class="nav-link" aria-current="page" href="./members.html" >The Band</a > </li> <li class="nav-item"> <a class="nav-link" href="./info.html">News</a> </li> <li class="nav-item"> <a class="nav-link" href="./form.html" >Something to say?</a > </li> </ul> <div class="social-links"> <span class="navbar-text"> <a class="nav-link" href="#" ><i class="fab fa-google-plus-g"></i ></a> </span> <span class="navbar-text"> <a class="nav-link" href="#" ><i class="fab fa-facebook-f"></i ></a> </span> <span class="navbar-text"> <a class="nav-link" href="#" ><i class="fab fa-twitter"></i ></a> </span> </div> </div> </nav> </footer> <script src="./assets/scripts/main.js"></script> <!-- do not remove this line! --> </body> </html>
<template> <div class="app-navbar"> <div class="left-wrapper"> <div class="logo-wrapper"> <img class="logo" src="/images/logo/logo-with-text-small.png" /> </div> <menu-main v-if="navbarMenuShow"></menu-main> </div> <div class="right-wrapper"> <ul class="right-side"> <li> <a-tooltip content="搜索"> <a-button class="nav-btn" type="outline" :shape="'circle'" @click="showAppSearch"> <template #icon> <a-icon-search /> </template> </a-button> </a-tooltip> </li> <li> <a-tooltip content="消息通知"> <div class="message-box-trigger"> <a-badge :count="9" dot> <a-button class="nav-btn" type="outline" :shape="'circle'" @click="setPopoverVisible"> <a-icon-notification /> </a-button> </a-badge> </div> </a-tooltip> <a-popover trigger="click" :arrow-style="{ display: 'none' }" :content-style="{ padding: 0, minWidth: '400px' }" content-class="message-popover"> <div ref="refBtn" class="ref-btn"></div> <template #content> <message-box /> </template> </a-popover> </li> </ul> <a-avatar> <img class="avatar" alt="avatar" :src="userInfo.avatar" /> </a-avatar> <div class="username">{{ userInfo.realName }}</div> <a-dropdown @popup-visible-change="getDropDownState" @select="tagSelect"> <a-button type="primary" class="arco-btn-only-icon"> <template #icon> <a-icon-down v-if="!dropDownState" /> <a-icon-up v-else /> </template ></a-button> <template #content> <a-doption value="logout">登出</a-doption> <a-doption>修改密码</a-doption> <a-doption>个人信息</a-doption> </template> </a-dropdown> </div> <app-search ref="appSearch"></app-search> </div> </template> <script lang="ts"> import { defineComponent, ref } from "vue" import type { Ref } from "vue" import { useUserHook } from "@/hooks/user" import { useAppHook } from "@/hooks/app" import ArcoModal from "@arco-design/web-vue/es/modal" import menuMain from "./menu-main.vue" import messageBox from "./message-box/index.vue" import appSearch from "@/components/search/index.vue" export default defineComponent({ components: { menuMain, messageBox, appSearch }, setup() { let { navbarMenuShow } = useAppHook() let { logoutEvent, userInfo } = useUserHook() let dropDownState = ref(false) const getDropDownState = function (status: boolean) { dropDownState.value = status } const logOutHand = function () { ArcoModal.warning({ title: "确认登出", content: "是否确认登出?", cancelText: "取消", closable: true, hideCancel: false, onOk: () => { logoutEvent() } }) } const tagSelect = function (tagValue: string) { if (tagValue === "logout") { logOutHand() } } const refBtn = ref() const setPopoverVisible = () => { const event = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }) refBtn.value.dispatchEvent(event) } const appSearch: Ref<ElRef> = ref(null) const showAppSearch = () => { ;(appSearch as any).value.showSearch() } return { getDropDownState, dropDownState, tagSelect, userInfo, setPopoverVisible, refBtn, navbarMenuShow, appSearch, showAppSearch } } }) </script> <style lang="less" scoped> .app-navbar { display: flex; justify-content: space-between; .left-wrapper { display: flex; flex: auto; flex-wrap: nowrap; align-items: center; width: 0; .logo-wrapper { width: @app-sidebar-width; height: 100%; line-height: @app-navbar-height; text-align: center; white-space: pre; .logo { width: 130px; vertical-align: middle; } } } .right-wrapper { position: relative; display: flex; align-items: center; padding-right: 18px; .username { padding: 0 10px; font-size: 14px; line-height: 19px; color: var(--color-white); } .avatar { } .right-side { display: flex; padding-right: 20px; list-style: none; :deep(.locale-select) { border-radius: 20px; } li { display: flex; align-items: center; padding: 0 10px; } .nav-btn { font-size: 16px; color: var(--color-white); border-color: var(--color-white); } .trigger-btn, .ref-btn { position: absolute; bottom: 14px; } .trigger-btn { margin-left: 14px; } } } } </style>
// src/components/OrderForm.js import React, { useState, useEffect } from 'react'; // import { useNavigate } from 'react-router-dom'; import axios from 'axios'; function OrderForm() { const [foodItems, setFoodItems] = useState([]); const [selectedItems, setSelectedItems] = useState([]); const [totalPrice, setTotalPrice] = useState(0); useEffect(() => { // Fetch food items from the backend axios.get('http://127.0.0.1:3002/admin-food-router/:add-food-item') .then((response) => { setFoodItems(response.data); }) .catch((error) => { console.error('Error fetching food items: ', error); }); }, []); const handleFoodItemSelection = (foodItem) => { // Add the selected food item to the order setSelectedItems([...selectedItems, foodItem]); setTotalPrice(totalPrice + foodItem.price); }; const handleSubmitOrder = () => { // Send the order to the backend const orderData = { customerId: 'customer_id', // Replace with the actual customer ID orderItems: selectedItems, total: totalPrice, }; axios.post('http://127.0.0.1:3002/restaurantorders/orders', orderData) .then((response) => { console.log('Order created successfully:', response.data); // Reset the order form or navigate to a confirmation page }) .catch((error) => { console.error('Error creating the order: ', error); }); }; return ( <div> <h2>Create Your Order</h2> <div> <h3>Select Food Items</h3> <ul> {foodItems.map((foodItem) => ( <li key={foodItem._id}> {foodItem.name} - ${foodItem.price} <button onClick={() => handleFoodItemSelection(foodItem)}>Add to Order</button> </li> ))} </ul> </div> <div> <h3>Your Order</h3> <ul> {selectedItems.map((foodItem) => ( <li key={foodItem._id}> {foodItem.name} - ${foodItem.price} </li> ))} </ul> <p>Total Price: ${totalPrice.toFixed(2)}</p> <button onClick={handleSubmitOrder}>Place Order</button> </div> </div> ); } export default OrderForm;
/* * CRUK-CI Clarity REST API Java Client. * Copyright (C) 2013 Cancer Research UK Cambridge Institute. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.genologics.ri.process; import java.io.Serializable; import java.net.URI; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlSchemaType; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.XmlValue; import com.genologics.ri.LimsLink; import com.genologics.ri.Linkable; import com.genologics.ri.processtype.ProcessType; /** * * Process-type is a child element of process that identifies and provides a URI * linking to the detailed representation of the process type that the process * is associated with. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "process-type") public class ProcessTypeLink implements LimsLink<ProcessType>, Serializable { private static final long serialVersionUID = 1852325206868769788L; @XmlAttribute(name = "uri") @XmlSchemaType(name = "anyURI") protected URI uri; @XmlValue protected String name; public ProcessTypeLink() { } public ProcessTypeLink(URI uri) { this.uri = uri; } public ProcessTypeLink(URI uri, String name) { this.uri = uri; this.name = name; } public ProcessTypeLink(Linkable<ProcessType> link) { this.uri = link.getUri(); } public ProcessTypeLink(ProcessType pt) { this.uri = pt.getUri(); this.name = pt.getName(); } @Override public Class<ProcessType> getEntityClass() { return ProcessType.class; } public String getName() { return name; } public void setName(String name) { this.name = name; } public URI getUri() { return uri; } public void setUri(URI uri) { this.uri = uri; } @Override public String toString() { return name; } }
package ua.gov.diia.ui_base.fragments.errordialog import androidx.annotation.Keep import retrofit2.HttpException import ua.gov.diia.core.network.Http.HTTP_400 import ua.gov.diia.core.network.Http.HTTP_403 import ua.gov.diia.core.network.Http.HTTP_404 import ua.gov.diia.core.network.Http.HTTP_422 import java.net.ConnectException import java.net.UnknownHostException import java.util.concurrent.TimeoutException enum class DialogErrorFlow { GENERAL, ADD_DOC, PAYMENT, ASSIST } @Keep enum class DialogError { CHECK_TIMEOUT, REQUEST_NOT_REGISTERED, UNKNOWN_ERROR_RECOVERABLE, UNKNOWN_ERROR_UNRECOVERABLE, NO_INTERNET, PAYMENT_ERROR, PAYMENT_FORBIDDEN, DRIVER_LICENSE_REPLACE, CRITICAL_ERROR_DEEP_LINK_NOT_REGISTERED, REQUESTED_DOCUMENTS_NOT_FOUND, DOCUMENT_REQUEST_EXPIRED, SPECIFIED_DOCUMENT_NOT_FOUND, SERVICE_UNAVAILABLE, ADD_DOC_TOO_MANY_ATTEMPTS; companion object { private const val MAX_TRY_COUNT_TO_REPEAT_REQUEST = 1 fun fromException( e: Exception, tryCountTracker: RequestTryCountTracker = RequestTryCountTracker(), flow: DialogErrorFlow = DialogErrorFlow.GENERAL ): DialogError { return if (e is HttpException) { when (e.code()) { HTTP_400 -> { CHECK_TIMEOUT } HTTP_404 -> { if (flow == DialogErrorFlow.ADD_DOC) { SPECIFIED_DOCUMENT_NOT_FOUND } else { REQUEST_NOT_REGISTERED } } HTTP_422 -> { if (flow == DialogErrorFlow.ADD_DOC) { SPECIFIED_DOCUMENT_NOT_FOUND } else { returnUndefinedError(tryCountTracker) } } HTTP_403 -> { when (flow) { DialogErrorFlow.PAYMENT -> { PAYMENT_FORBIDDEN } DialogErrorFlow.ADD_DOC -> { UNKNOWN_ERROR_RECOVERABLE } DialogErrorFlow.ASSIST -> { ADD_DOC_TOO_MANY_ATTEMPTS } else -> { returnUndefinedError(tryCountTracker) } } } else -> { returnUndefinedError(tryCountTracker) } } } else { return if (e is TimeoutException || e is UnknownHostException || e is ConnectException) { NO_INTERNET } else { if (tryCountTracker.tryCount < MAX_TRY_COUNT_TO_REPEAT_REQUEST) { tryCountTracker.increment() UNKNOWN_ERROR_RECOVERABLE } else { UNKNOWN_ERROR_UNRECOVERABLE } } } } private fun returnUndefinedError(tryCountTracker: RequestTryCountTracker): DialogError { return if (tryCountTracker.tryCount < MAX_TRY_COUNT_TO_REPEAT_REQUEST) { tryCountTracker.increment() UNKNOWN_ERROR_RECOVERABLE } else { UNKNOWN_ERROR_UNRECOVERABLE } } } }
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>CHOHEE.ME</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/agency.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Raleway:600' rel='stylesheet' type='text/css'> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top" class="index"> <!-- Navigation --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand page-scroll" href="#page-top"> <i class="fa fa-play-circle"></i> <span class="light">CHOHEE.ME </span> </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="#about">ABOUT</a> </li> <li> <a class="page-scroll" href="#portfolio">PROJECT</a> </li> <li> <a class="page-scroll" href="#contact">Contact</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <!-- Header --> <header> <div class="container"> <div class="intro-text"> <h1 class = "intro-lead-in" id="change-Text">Test</h1> <br/> <a href="#about" class="btn btn-circle page-scroll"> <i class="fa fa-angle-double-down animated"></i> </a> </div> </div> </header> <!---About --> <section id="about"> <!-- Page Content --> <div class="container"> <!-- Page Header --> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">ABOUT ME </h1> </div> </div> <!-- /.row --> <!-- Projects Row --> <div class="row"> <div class="col-md-6 portfolio-item " width = "400px"> <p id="hello"> Hello there!</p> <img class = "image" alt ="profile picture" src = "img/profile.jpg" /> <div id="profile"> <p id="myname"> <b>Chohee Kim</b></p> <p> Student @San Francisco State University <br> kch5559(at)gmail.com </p> </div> </div> <div class="col-md-6 portfolio-item about-right" width = "800px"> <p class="label">Education </p> <br/><br/> <p class="experience"> San Francisco State University - SF GPA 3.95 </br>B.S Computer Science, Minor in Mathematics</p> <p class="period"> August 2014 - Present ( December 2017 expected) <br /> Introduction to Programming, Data Structure, Discrete Mathematics, Machine Structure, Programming Methodology,Probability and Statistics with Computing</p> <br /> <p class="label">Experience </p> <br /> <br /> <p class="experience">CodeU Fellow at Google <br ><span class="period"> March 2016 - Present </span></p> <p class="experience">Mathematics Tutor at Kongreung Middle School <br ><span class="period">August 2012 - Dec 2012</span></p> <p class="experience">Vice President for Student Council at Seoul Women's University <br > <span class="period">Jan 2012 - Dec 2012</span></p> <p class="experience">Administrator for Student Council at Seoul Women's University <br ><span class="period">Mar 2010 - Dec 2011</span></p> <br /> <p class="label">Skill</p><br /><br /> <p class="experience lang"> <strong>JAVA</strong> HTML/CSS BOOTSTRAP PYTHON C++ C MongoDB Jetbrains </p> <br/> <p class="label">Resume</p> <br/> <a id = "resume" href="resume.pdf" download > resume.pdf </a> </div> </div> <!-- /.row --> </div> </section> <br/><br/> <!-- Portfolio Grid Section --> <section id="portfolio" class="bg-light-gray"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Project</h2> <h3 class="section-subheading text-muted">Click to see more details about a project</h3> </div> </div> <div class="row"> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal1" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <p>A program that analyzes and provides average waiting time, teller serving times, and so on, by a given time unit with random chance of customer showing up and random transaction time.</p> </div> </div> <center><img src="img/portfolio/bank.png" class="img-responsive" alt=""></center> <br/> </a> <div class="portfolio-caption"> <h4>BANK SIMULATION</h4> <a class="text-muted" href = "https://github.com/kch5559/Java-220/tree/master/PJ3" target = "_blank">Java</a> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal2" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <p> A simple chess game that is played by two people on a given chess board with initial setup. It checks for illegal moves and position. The code is written in Java using 2D array.</p> </div> </div> <center><img src="img/portfolio/chess.png" class="img-responsive" alt=""></center> <br/> </a> <div class="portfolio-caption"> <h4>Simple chess game</h4> <a class="text-muted" href = "https://github.com/kch5559/Java-CSC210-/blob/master/ImprovedChess/src/ImprovedChess/ImprovedChess.java" target = "_blank">Java</a> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal3" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <p>A simple single poker game. I used ArrayList to track and save cards that are randomly generated for a player, and visualize it using Java Swing.</p> </div> </div> <center><img class ="pokergame_image" src="img/portfolio/pokergame.jpg" class="img-responsive" alt=""></center> </br> </a> <div class="portfolio-caption"> <h4>Poker game</h4> <a class="text-muted" href = "https://github.com/kch5559/Java-220/tree/master/PJ4" target = "_blank">Java</a> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal4" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <p>My first personal website built by HTML/CSS, Javascript, Bootstrap, and PHP.</p> </div> </div> <img src="img/portfolio/myWebsite" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>My website</h4> <a class="text-muted" href = "https://github.com/kch5559/Java-220/tree/master/PJ4" target = "_blank"> html/css js bootstrap and more </a> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal5" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <p>A web application that provides private photo sharing, chat, events for a group.</p> </div> </div> <img src="img/portfolio/group-icon.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>BUTZ</h4> <p class="text-muted">Coming soon</p> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="https://github.com/kch5559" class="portfolio-link" data-toggle="modal"> <img src="img/portfolio/github-icon.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>github page</h4> <p class="text-muted">Visit to see more projects</p> </div> </div> </div> </div> </section> <!-- Contact Section --> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <br/> <h2 class="section-heading">Contact me</h2> </div> </div> <div class="row"> <div class="col-lg-12"> <form name="sentMessage" id="contactForm" novalidate> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="tel" class="form-control" placeholder="Your Phone (Optional)" id="phone"> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group"> <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea> <p class="help-block text-danger"></p> </div> </div> <div class="clearfix"></div> <div class="col-lg-12 text-center"> <div id="success"></div> <button type="submit" class="btn btn-xl">Send Message</button> </div> </div> </form> </div> </div> </div> </section> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="js/classie.js"></script> <script src="js/cbpAnimatedHeader.js"></script> <!-- Contact Form JavaScript --> <script src="js/jqBootstrapValidation.js"></script> <script src="js/contact_me.js"></script> <!-- Custom Theme JavaScript --> <script src="js/agency.js"></script> </body> </html>
#include "variadic_functions.h" /** * print_strings - prints strings * @separator: comma * @n: no of arguments * Return: void */ void print_strings(const char *separator, const unsigned int n, ...) { va_list arg; unsigned int i; char *s; va_start(arg, n); for (i = 0; i < n; i++) { s = va_arg(arg, char *); if (s == NULL) s = "(nil)"; if (!separator) printf("%s", s); else if (separator && i == 0) printf("%s", s); else printf("%s%s", separator, s); } va_end(arg); printf("\n"); }
# frozen_string_literal: true module Api module V1 class GroupsController < ApplicationController before_action :authenticate_api_v1_user!, only: %i[index create] def index @groups = search_groups.sort_by { |group| group[:group].id } end def create user = User.find_by(id: group_params[:user_id]) unless user render json: { errors: 'ユーザーが見つかりません' }, status: :not_found return end group = current_api_v1_user.find_or_create_group(user) render json: { group: }, status: :ok end private def search_groups entries = Entry.where(group: current_api_v1_user.groups).where.not(user_id: current_api_v1_user.id).preload(:user, :group) entries.map do |entry| { group: entry.group, user: entry.user } end end def group_params params.permit(:user_id) end end end end
<html> <head> <meta charset="utf-8"> <title>Пошук записів</title> </head> <body> <h1>Пошук записів</h1> <a href='population.php'>🢠 Список населення</a><p> <?php $db_host = 'localhost'; // хост бази даних $db_name = 'census'; // назва бази даних $db_user = 'root'; // користувач бази даних $db_pass = '123456'; // пароль бази даних $table = 'population'; // Перевірка, чи дані надійшли з форми if ($_SERVER["REQUEST_METHOD"] == "POST") { $searchTerm = $_POST['search_term']; // Створення з'єднання з базою даних $conn = new mysqli($db_host, $db_user, $db_pass, $db_name); // Перевірка з'єднання з базою даних if ($conn->connect_error) { die("Помилка з'єднання з базою даних." . $conn->connect_error); } // Підготовка запиту до бази даних для пошуку громадянина за ПІБ $query = "SELECT * FROM $table WHERE PIB LIKE '%$searchTerm%'"; $result = mysqli_query($conn, $query); // Перевірка результату запиту if ($result && mysqli_num_rows($result) > 0) { echo "<h2>Результати пошуку:</h2>"; echo "<table>"; echo "<tr>"; echo "<th>ID</th>"; echo "<th>ПІБ</th>"; echo "<th>Стать</th>"; echo "<th>Дата народження</th>"; echo "<th>Дата смерті</th>"; echo "<th>Сімейний стан</th>"; echo "<th>Національність</th>"; echo "<th>Номер телефону</th>"; echo "<th>Місце проживання</th>"; echo "<th>Місце народження</th>"; print "<th>Редагувати</th>"; print "<th>Видалити</th>"; echo "</tr>"; while ($row = mysqli_fetch_assoc($result)) { $id = $row['id']; $PIB = $row['PIB']; $gender = $row['gender']; $dateofbirth = $row['dateofbirth']; $dateofdeath = $row['dateofdeath']; $marital_status = $row['marital_status']; $nationality = $row['nationality']; $phone_number = $row['phone_number']; $residenceId = $row['residence_id']; $birthplaceId = $row['birthplace_id']; // Отримання даних про місце проживання $residence_query = "SELECT * FROM residence WHERE id = $residenceId"; $residence_result = mysqli_query($conn, $residence_query); $residenceData = mysqli_fetch_assoc($residence_result); $residenceCity = $residenceData['city_r']; $residenceAddress = $residenceData['adres_r']; // Отримання даних про місце народження $birthplace_query = "SELECT * FROM birthplace WHERE id = $birthplaceId"; $birthplace_result = mysqli_query($conn, $birthplace_query); $birthplaceData = mysqli_fetch_assoc($birthplace_result); $birthplaceCity = $birthplaceData['city_b']; $birthplaceAddress = $birthplaceData['adres_b']; echo "<tr>"; echo "<td>" . $id . "</td>"; echo "<td>" . $PIB . "</td>"; echo "<td>" . $gender . "</td>"; echo "<td>" . $dateofbirth . "</td>"; echo "<td>" . $dateofdeath . "</td>"; echo "<td>" . $marital_status . "</td>"; echo "<td>" . $nationality . "</td>"; echo "<td>" . $phone_number . "</td>"; echo "<td>" . $residenceCity . ", " . $residenceAddress . "</td>"; echo "<td>" . $birthplaceCity . ", " . $birthplaceAddress . "</td>"; print "<td><a href='edit_population.php?id=" . $row['id'] . "'>✍️Редагувати</td>"; print "<td><a href='delete_population.php?id=" . $row['id'] . "'>❌Видалити</td></tr>"; } echo "</table>"; } else { echo "Немає результатів."; } // Закриття з'єднання з базою даних $conn->close(); } ?> <!-- HTML форма для введення ПІБ для пошуку --> <form action="" method="POST"> <br><label>ПІБ: </label> <input type="text" name="search_term" placeholder="Введіть ПІБ" required> <input type="submit" value="Пошук"><br><br> </form> </body> </html>
#include <LiquidCrystal.h> //Library LiquidCrystal const int rs = 12, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); const int Up_buttonPin = 2; const int Down_buttonPin = 3; int buttonPushCounter = 0; // counter for the number of button presses int up_buttonState = 0; // current state of the up button int up_lastButtonState = 0; // previous state of the up button int down_buttonState = 0; // current state of the up button int down_lastButtonState = 0; // previous state of the up button bool bPress = false; void setup() { Serial.begin(9600); pinMode( Up_buttonPin , INPUT_PULLUP); pinMode( Down_buttonPin , INPUT_PULLUP); lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print("Counter Value:"); lcd.setCursor(2, 1); lcd.print(buttonPushCounter); } void loop() { checkUp(); checkDown(); if ( bPress) { bPress = false; lcd.setCursor(2, 1); lcd.print(" "); lcd.setCursor(2, 1); lcd.print(buttonPushCounter); } } void checkUp() { up_buttonState = digitalRead(Up_buttonPin); if (up_buttonState != up_lastButtonState) // compare the buttonState to its previous state { if (up_buttonState == LOW) // if the state has changed, increment the counter { bPress = true; // if the current state is HIGH then the button went from off to on: buttonPushCounter++; Serial.println("on"); Serial.print("number of button pushes: "); Serial.println(buttonPushCounter); } else { Serial.println("off"); // if the current state is LOW then the button went from on to off: } delay(50); // Delay a little bit to avoid bouncing } up_lastButtonState = up_buttonState; // save the current state as the last state, for next time through the loop } void checkDown() { down_buttonState = digitalRead(Down_buttonPin); if (down_buttonState != down_lastButtonState) // compare the buttonState to its previous state { if (down_buttonState == LOW) // if the state has changed, increment the counter { bPress = true; buttonPushCounter--; // if the current state is HIGH then the button went from off to on: Serial.println("on"); Serial.print("number of button pushes: "); Serial.println(buttonPushCounter); } else { Serial.println("off"); // if the current state is LOW then the button went from on to off: } delay(50); // Delay a little bit to avoid bouncing } down_lastButtonState = down_buttonState; // save the current state as the last state, for next time through the loop }
import Foundation public struct Parser<Input, Output> { private let fn: (Iterated<Input>) throws -> Iterated<Output> public let name: String public let description: String public init(name: String = "", description: String = "", fn: @escaping (Iterated<Input>) throws -> Iterated<Output>) { self.name = name self.description = description self.fn = fn } public func parse(_ input: Iterated<Input>) throws -> Iterated<Output> { input.context.logger(.init(status: .enter, parser: self, input: input)) let context = input.context.push(call: .init(name: name, value: description)) let input2 = Iterated(value: input.value, position: input.position, context: context) do { let result = try fn(input2) input.context.logger(.init(status: .success, parser: self, input: input)) return Iterated(value: result.value, position: result.position, context: result.context.pop()) } catch { input.context.logger(.init(status: .failure, parser: self, input: input)) throw error } } public func callAsFunction(_ input: Iterated<Input>) throws -> Iterated<Output> { try parse(input) } } extension String: LocalizedError { public var errorDescription: String? { self } } public typealias Logger = (Log) -> Void public struct Log { public let status: Status public let parserName: String public let parserDescription: String public let position: Int public let context: Context init<Input, Output>(status: Status, parser: Parser<Input, Output>, input: Iterated<Input>) { self.status = status self.parserName = parser.name self.parserDescription = parser.description self.position = input.position self.context = input.context } public enum Status { case enter case success case failure } } public struct Context { public let logger: Logger public let callStack: [Call] public init(logger: @escaping Logger = { _ in }, callStack: [Call] = []) { self.logger = logger self.callStack = callStack } public func push(call: Call) -> Context { .init(logger: logger, callStack: callStack + [call]) } public func pop() -> Context { .init(logger: logger, callStack: callStack.dropLast()) } public struct Call { public let name: String public let value: String } var stackTrace: String { callStack .map { "- \($0.name)() \($0.value)" } .joined(separator: "\n") } } public struct Iterated<T> { public let value: T public let position: Int public let context: Context public init(value: T, position: Int = 0, context: Context = .init()) { self.value = value self.position = position self.context = context } }
package chain_of_inheritance; import java.util.Scanner; public class ExamDemo{ public static void main(String[] args) { int questions; //number of questions int missed; //number of questions missed Scanner keyboard = new Scanner (System.in); System.out.println("How many questions in the final exam? "); questions = keyboard.nextInt(); System.out.println("How many questions missed in the final? "); missed = keyboard.nextInt(); //create a final exam object FinalExam finalexam = new FinalExam(questions, missed); //Display the test results System.out.printf("\nFinalExam:\n Each question counts: %.2f points", finalexam.getPointsEach() ); System.out.printf("%n The final exam score is : %.2f out of 100", finalexam.getScore() ); System.out.printf("%n The final exam grade is : %s\n", finalexam.getGrade() ); //create a PassFail exam object System.out.println("How many questions in the pass or fail exam? "); questions = keyboard.nextInt(); System.out.println("How many questions missed in the pass or fail exam? "); missed = keyboard.nextInt(); System.out.println("What is the minimum passing score? "); double passScore = keyboard.nextDouble(); PassFailExam newExam = new PassFailExam(questions, missed, passScore); //Display the test results System.out.printf("\nPassFailExam:\n Each question counts: %.2f points", newExam.getPointsEach() ); System.out.printf("%n The PassFail exam score is : %.2f out of 100", newExam.getScore() ); System.out.printf("%n The PassFail exam grade is : %s", newExam.getGrade() ); keyboard.close(); } }
""" Problem: LeetCode 54 - Spiral Matrix Key Idea: To traverse a matrix in a spiral order, we can iterate through each layer of the matrix and extract the elements in the desired order: top row, right column, bottom row, and left column. We update the boundaries of each layer as we traverse. Time Complexity: - We visit each element in the matrix exactly once. Therefore, the time complexity is O(m * n), where m is the number of rows and n is the number of columns in the matrix. Space Complexity: - The space complexity is O(1), as we use a constant amount of space to store the result. """ class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix: return [] rows, cols = len(matrix), len(matrix[0]) result = [] # Define the boundaries of the current layer top, bottom, left, right = 0, rows - 1, 0, cols - 1 while top <= bottom and left <= right: # Traverse the top row for j in range(left, right + 1): result.append(matrix[top][j]) top += 1 # Traverse the right column for i in range(top, bottom + 1): result.append(matrix[i][right]) right -= 1 # Traverse the bottom row if top <= bottom: # Avoid duplicate traversal for j in range(right, left - 1, -1): result.append(matrix[bottom][j]) bottom -= 1 # Traverse the left column if left <= right: # Avoid duplicate traversal for i in range(bottom, top - 1, -1): result.append(matrix[i][left]) left += 1 return result
@extends('layouts.master') @section('title') | Create Category @endsection @section('content') <div class="row"> <div class="col-xl-6 mx-auto"> <form action="{{ route('category.update', $category->id) }}" method="post" enctype="multipart/form-data"> @csrf @method('PUT') <div class="card"> <div class="card-header"> <h5 class="card-title"> Edit Category </h5> </div> <div class="card-body"> <div class="form-group my-3"> <label for="title"> Title </label> <input type="text" name="title" id="title" class="form-control" placeholder="Title" value="{{ $category ? $category->title : '' }}" /> </div> <div class="form-group my-3"> <label for="desc"> Desc </label> <input type="text" name="desc" id="desc" class="form-control" placeholder="Desc" value="{{ $category ? $category->desc : '' }}" /> </div> <div class="custom-file"> <label class="custom-file-label" for="image">Select file</label> <input type="file" name="image" class="custom-file-input" id="image"> </div> <div class="form-group"> <img src="{{ Storage::url($category->image) }}" height="200" width="200" alt="" /> </div> <div class="form-group"> <button type="submit" class="btn btn-success"> Save </button> </div> </div> </div> </form> </div> </div> @endsection
const { expect } = require('chai') const setupDriver = require('../utils/setupDriver') const LoginPage = require('../pagesObject/LoginPage') const CatalogPage = require('../pagesObject/CatalogPage') const DetailProductPage = require('../pagesObject/DetailProductPage') const CartPage = require('../pagesObject/CartPage') const CheckoutPage = require('../pagesObject/CheckoutPage') describe('FT_003_Cart_Page',function(){ /**@type {WebdriverIO.Browser} */ let driver /**@type {LoginPage} */ let loginPage /**@type {CatalogPage} */let catalogPage /**@type {DetailProductPage} */let detailProductPage /**@type {CartPage} */let cartPage /**@type {CheckoutPage} */ let checkoutPage before(async function(){ driver = await setupDriver() loginPage = new LoginPage(driver) catalogPage = new CatalogPage(driver) detailProductPage = new DetailProductPage(driver) checkoutPage = new CheckoutPage(driver) cartPage = new CartPage(driver) await loginPage.openPage() await loginPage.loginProcess() await catalogPage.productName1.click() await driver.pause(500) await detailProductPage.addToCart() await cartPage.cartButton.click() await driver.pause(500) }) describe('CP_001 Mencoba mengurangi quantity product menjadi 0',function(){ it('Product akan terhapus',async function(){ await cartPage.decreaseQtyButton.click() await driver.pause(500) const title = await cartPage.cartTitle.getText() expect(title).to.equal('No Items') await cartPage.shoppingButton.click() await catalogPage.productName1.click() await detailProductPage.addToCart() await cartPage.cartButton.click() }) }) describe('CP_002 Mencoba menambah quantity product menjadi 2',function(){ it('Total product bertambah menjadi 2',async function(){ await cartPage.increaseQtyButton.click() await driver.pause(500) const totalQty = await cartPage.totalQty.getText() expect(totalQty).to.equal('2 items') }) it('Total harga menjdai 2x lipat',async function(){ const totalPirce = await cartPage.totalPrice.getText() expect(totalPirce).to.equal('$59.98') await cartPage.decreaseQtyButton.click() }) }) describe('CP_003 Mencoba remove item',function(){ it('Item berhasil dihapus',async function(){ await cartPage.removeItemButton.click() await driver.pause(500) const title = await cartPage.cartTitle.getText() expect(title).to.equal('No Items') await cartPage.shoppingButton.click() await catalogPage.productName1.click() await detailProductPage.addToCart() await cartPage.cartButton.click() }) }) describe('CP_004 Mencoba menambahkan 1 item lagi',function(){ it('Product berhasil ditambahkan',async function(){ await catalogPage.burgerButton.click() await catalogPage.catalogButton.click() const productName = await catalogPage.productName2.getText() await catalogPage.productName2.click() await driver.pause(500) await detailProductPage.addToCart() await driver.pause(500) await cartPage.cartButton.click() const cartPorductName = await cartPage.getProductNameMoreThanOne('2') expect(productName).to.equal(cartPorductName) }) it('Total quantity bertambah menjadi 2',async function(){ await driver.pause(500) const totalQty = await cartPage.totalQty.getText() expect(totalQty).to.equal('2 items') }) }) describe('CP_005 Mencoba checkout',function(){ it('berhasil masuk ke halaman checkout',async function(){ await cartPage.checkoutButton.click() await driver.pause(1000) const title = await checkoutPage.checkoutTitle.getText() expect(title).to.equal('Checkout') }) }) afterEach(async function(){ await driver.pause(1000) }) after(async function(){ await driver.deleteSession() }) })
# GenDiff Hexlet tests and linter status [![Actions Status](https://github.com/c0rnoTa/frontend-project-46/actions/workflows/hexlet-check.yml/badge.svg)](https://github.com/c0rnoTa/frontend-project-46/actions) [![tests](https://github.com/c0rnoTa/frontend-project-46/actions/workflows/tests.yml/badge.svg)](https://github.com/c0rnoTa/frontend-project-46/actions/workflows/tests.yml) [![eslint](https://github.com/c0rnoTa/frontend-project-46/actions/workflows/linter.yml/badge.svg)](https://github.com/c0rnoTa/frontend-project-46/actions/workflows/linter.yml) [![Maintainability](https://api.codeclimate.com/v1/badges/3a2cbf12eabe0fcc1378/maintainability)](https://codeclimate.com/github/c0rnoTa/frontend-project-46/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/3a2cbf12eabe0fcc1378/test_coverage)](https://codeclimate.com/github/c0rnoTa/frontend-project-46/test_coverage) ### gendiff JSON [![asciicast](https://asciinema.org/a/pdqEddzfdDvZAP65OwI6L2dgb.svg)](https://asciinema.org/a/pdqEddzfdDvZAP65OwI6L2dgb) ### gendiff YAML [![asciicast](https://asciinema.org/a/z2GoaBOrr2qreDEuJbkAtDUET.svg)](https://asciinema.org/a/z2GoaBOrr2qreDEuJbkAtDUET) ### gediff stylish format [![asciicast](https://asciinema.org/a/nyquPJyGNoQgQf1LF0c63cGa4.svg)](https://asciinema.org/a/nyquPJyGNoQgQf1LF0c63cGa4) ### gediff plain format [![asciicast](https://asciinema.org/a/sxtqz4imseduvaDgq5rJ1XvO1.svg)](https://asciinema.org/a/sxtqz4imseduvaDgq5rJ1XvO1) ### gendiff JSON format [![asciicast](https://asciinema.org/a/fMWCol6gaWgxHqJI388EbMvM5.svg)](https://asciinema.org/a/fMWCol6gaWgxHqJI388EbMvM5) ## AST design В каждом узле AST мне нужно знать: 1. Имя ключа - тип "срока". 2. Статус ключа - тип "строка", где значение может быть одно из следующих: - "неизменён" - ключ есть в исходном и в целевом сравниваемом объекте одинакого типа, тип значения ключа простой или массив; - "добавлен" - ключ есть только в целевом объекте; - "удалён" - ключ есть только в исходном объекте; - "изменён" - ключ есть в исходном и в целевом сравниваемом объекте; либо тип значения ключа одинаковый: простой или массив, и поменялось его содержимое, либо изменился тип значения ключа; - "объект" - ключ есть в исходном и в целевом сравниваемом объекте, тип значения ключа одинковый - объект (не массив). 3. Значение ключа (для ключа со статусом "изменён" будет значение ДО и значение ПОСЛЕ той же структуры, что представлено ниже) - тип "объект", где атрибутами объекта являются: 3.1. Тип данных - тип "строка", где значение может быть одного из следующих: - "простое значение" (для данных в виде строки, числа, null и всяких undefined, при рендере будут выводиться такие данные как есть и переходить к следующему узлу AST) - "массив" (для массива, при рендере будут выводиться только значения из массива, обёрнутые в []) - "объект" (для объекта, при рендере будет выводиться каждый элемент массива как ключ и значение, обёрнут в {}, такой тип данных может быть только при изменении типа данных и нужен для сортировки ключей) 3.1.1. Если тип данных (пункт 3.1) - "массив", то данные в значении ключа AST (пункт 3.2) - это массив объектов, где каждый объект имеет атрибуты "тип данных" и "данные", по аналогии с значением ключа AST (пункт 3). 3.1.2. Для типа данных (пункт 3.1) - "объект", то данные в значении ключа AST (пункт 3.2) - это двумерный массив, где каждый элемент массива - это массив из имени ключа объекта (отсортирован) и объекта с атрибутами "тип данных" и "данные", по аналогии с значением ключа AST (пункт 3). 3.2. Данные - это либо простое значение (типа строка, число, null и всякие undefined), либо массив (3.1.1 и 3.1.2). 4. Дочерний узел AST (если статус ключа, пункт 2 - "объект") ``` [ { имя: "addedComplex", статус: "добавлен", значение: { тип: "массив", данные: [ { тип: "простое значение", данные: "a" }, { тип: "объект", данные: [ ["object", { тип: "простое значение", данные: "bar" }], ["unsorted", { тип: "простое значение", данные: "foo" }] ] } ] } }, { имя: "sameSimple", статус: "неизменён", значение: { тип: "простое значение", данные: 1 } } ] ```
<script lang="ts"> import RefreshIcon from '$icons/arrow-path.svg'; import PauseIcon from '$icons/pause.svg'; import PlayIcon from '$icons/play.svg'; import TrashIcon from '$icons/trash.svg'; import ActionButton from '$lib/client/components/ActionButton.svelte'; import RemoveModal from '$lib/client/components/RemoveModal.svelte'; import { enhance } from '$app/forms'; import type { PageData } from './$types'; export let data: PageData; let loading = false; let removeModal = false; </script> <svelte:head> <title>Container - Light-Whale</title> </svelte:head> <div class="card shadow-md bg-base-100 mb-6"> <div class="card-body p-6 pt-5"> <h2 class="card-title text-xl">State: {data.container?.state.toUpperCase()}</h2> <p>Status: {data.container?.status}</p> <form class="card-actions mt-2" method="POST" use:enhance={() => { loading = true; return ({ update }) => { loading = false; update(); }; }} > <ActionButton icon={PlayIcon} {loading} disabled={data.container?.state === 'running'} class="w-auto px-3" formaction="?/start" > Start </ActionButton> <ActionButton icon={PauseIcon} {loading} disabled={data.container?.state !== 'running'} class="w-auto px-3" formaction="?/stop" > Stop </ActionButton> <ActionButton icon={RefreshIcon} {loading} disabled={data.container?.state !== 'running'} class="w-auto px-3" formaction="?/restart" > Restart </ActionButton> <ActionButton icon={TrashIcon} on:click={() => (removeModal = true)} {loading} disabled={data.container?.state === 'running'} class="w-auto px-3" type="button" > Remove </ActionButton> <RemoveModal label="container" name={data.container?.name} formaction="?/remove" bind:open={removeModal} bind:loading /> </form> </div> </div> <div class="card shadow-md bg-base-100 mb-6"> <div class="card-body p-6 pt-5"> <h2 class="card-title text-xl">Information</h2> <p> Name: <span class="font-bold">{data.container?.name.substring(1)}</span> </p> <p> ID: <span class="font-bold">{data.container?.id}</span> </p> <p> Short ID: <span class="font-bold">{data.container?.id.substring(0, 12)}</span> </p> </div> </div> <div class="card shadow-md bg-base-100 mb-6"> <a class="card-body p-6 pt-5 hover:text-primary-focus" href="/images/{data.container.imageId.substring(7, 19)}" > <h2 class="card-title text-xl">Image</h2> <!-- <p>--> <!-- Name:--> <!-- <span class="font-bold">{image?.tags.join(',')}</span>--> <!-- </p>--> <p> ID: <span class="font-bold">{data.container?.imageId}</span> </p> </a> </div>
import pick from 'lodash/pick' import { GetStaticPropsContext } from 'next' import Root from 'components/Layout/Root' import Image from 'next/image' import { useTranslations } from 'next-intl' import { FeaturedPosts } from 'components/Blocks/FeaturedPosts' import { getPostBySlug } from 'lib/blog' import { NextSeo } from 'next-seo' import { generateImage } from 'lib/og-generator' export type Props = { featuredPosts: any[] ogImage: string } function HomePage(props: Props) { const t = useTranslations('Home') const tog = useTranslations('SocialImage') return ( <> <NextSeo openGraph={{ title: tog('home.title'), description: tog('home.subtitle'), images: [ { url: props.ogImage, width: 1200, height: 630, alt: 'Marcos Bérgamo memoji smiling', type: 'image/png', }, ], }} /> <div className="w-full flex flex-col"> <section className="mb-16 flex flex-col text-center items-center"> <div className="items-center"> <Image src="/avatar-hello.png" width="124" height="124" alt="Marcos Bérgamo memoji smiling" /> </div> <div className="flex flex-col"> <h1>{t('greeting')}</h1> <h2 className="text-zinc-700 dark:text-zinc-200 text-lg mb-4"> {t('work-title')} <span className="font-semibold">{t('company')}</span> </h2> <p className="text-zinc-600 dark:text-zinc-400 max-w-lg"> {t('description')} </p> </div> </section> <FeaturedPosts blockName="Featured Posts" posts={props.featuredPosts} /> </div> </> ) } export default HomePage HomePage.messages = ['Home', 'Post', ...Root.messages] export async function getStaticProps({ locale }: GetStaticPropsContext) { const tMessages = await import(`../messages/${locale}.json`) const featuredParams = [ 'date', 'slug', 'title', 'image', 'content', 'description', ] // TODO: have a better way to handle featured posts and limit const featuredPosts = [ getPostBySlug('create-next-og-image-at-build-time', featuredParams), getPostBySlug('micro-front-ends-key-takeaways', featuredParams), getPostBySlug('generate-social-images-as-a-service', featuredParams), getPostBySlug( 'precisamos-falar-sobre-os-novos-desevolvedores', featuredParams ), getPostBySlug( 'you-might-not-need-a-computer-science-degree', featuredParams ), getPostBySlug('uma-visao-sobre-nosql', featuredParams), ] const ogImage = await generateImage({ data: { title: 'home.title', subtitle: 'home.subtitle', imagePath: 'avatar-hello.png', translate: true, locale, }, outputName: `${locale}_home`, options: { width: 1200, height: 630, }, }) return { props: { featuredPosts, ogImage, messages: pick(tMessages, HomePage.messages), }, } }
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:project/Screens/Introduction/introduction.dart'; import 'package:project/Screens/splash/splash_screen.dart'; import 'package:project/bindings/initial_bindings.dart'; import 'package:project/configs/themes/app_dark_theme.dart'; import 'package:project/configs/themes/app_light_theme.dart'; import 'package:project/controllers/theme_controller.dart'; import 'package:project/data_uploader_screen.dart'; import 'package:project/firebase_options.dart'; import 'package:get/get.dart'; import 'package:project/routes/app_routes.dart'; import 'dart:async'; import 'package:firebase_auth/firebase_auth.dart' hide EmailAuthProvider, PhoneAuthProvider; import 'package:firebase_ui_auth/firebase_ui_auth.dart'; import 'package:provider/provider.dart'; Future<void> main() async{ WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); InitailBindings().dependencies(); runApp(MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return GetMaterialApp( theme: Get.find<ThemeController>().lightTheme, getPages: AppRoutes.routes(), ); } } // Future<void> main() async { // WidgetsFlutterBinding.ensureInitialized(); // await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); // // await Firebase.initializeApp(); // runApp(GetMaterialApp(home: DataUploaderScreen())); // }
import React from "react"; import { useState } from "react"; import { useNavigate } from "react-router-dom"; import * as AiIcons from "react-icons/ai"; import { useForm } from "react-hook-form"; import { useDispatch, useSelector } from "react-redux"; import { login } from "../../../../redux/actions/authActions"; import { useEffect } from "react"; import { EMAIL } from "../../../../utils/constants"; export const LoginForm = () => { const formLogin = document.getElementById("form-login"); const btnLogin = document.getElementById("btn-login-submit"); const [isPassword, setIsPassword] = useState(true); const navigate = useNavigate(); const dispatch = useDispatch(); const error = useSelector((store) => store.login?.error?.message); const isFetching = useSelector((store) => store.login?.isFetching); const isLoggin = useSelector((store) => store.login?.isLoggin); const token = useSelector((store) => store.login?.user?.access); console.log(useSelector((store) => store)); const { register, handleSubmit, watch, reset, formState: { errors }, } = useForm(); const email = watch("email"); const password = watch("password"); const onSubmit = async () => { reset(); await dispatch(login(email, password)); localStorage.setItem(EMAIL, JSON.stringify(email)); }; // Se não houver error. Não estiver esperando resposta da api // Se estiver logado e houver o token... navegue o usuário para página privada; useEffect(() => { if (!error && !isFetching && isLoggin && token) { navigate("/tarefas"); } }, [error, isFetching, isLoggin, navigate, token]); // Pressionar Enter para entrar; formLogin?.addEventListener("keypress", (e) => { if (e.key === "Enter") { e.preventDefault(); btnLogin?.click(); } }); const handlePasswordTypeInput = () => setIsPassword((prev) => !prev); return ( <React.Fragment> <form id="form-login" className="form" onSubmit={handleSubmit(onSubmit)}> <div className="form__form-group"> <span className="form__form-group-label">Email do Usuário</span> <input {...register("email", { required: true })} name="email" className="input-modal-form" placeholder="Email de usuário" required disabled={isFetching} type="email" /> {errors.email && ( <span className="span-validation">Campo 'Email' é obrigatório</span> )} </div> <div className="form__form-group"> <span className="form__form-group-label">Senha</span> <div className="form__form-group-field"> <input {...register("password", { required: true })} name="password" className="input-modal-form" placeholder="Digite sua Senha" disabled={isFetching} required type={isPassword ? "password" : "text"} /> <button onClick={handlePasswordTypeInput} type="button" disabled={isFetching} className="button-password" > {isPassword ? ( <AiIcons.AiOutlineEye /> ) : ( <AiIcons.AiOutlineEyeInvisible /> )} </button> </div> </div> {error && ( <div className="container-span-validation"> <span className="span-validation"> {error || "Erro de Autenticação"} </span> </div> )} <button className="button-primary-confirm" id="btn-login-submit" onClick={handleSubmit} type="submit" disabled={isFetching} > {isFetching ? "Aguardando..." : "Entrar"} </button> </form> <p className="acesso-restrito" style={{ cursor: "pointer", color: "blue", textDecoration: "underline blue", }} onClick={() => navigate("/criar/usuario")} > Não Possui Cadastro? </p> </React.Fragment> ); };
<template> <div v-if="showContent" class="container" > <div> <h1 class="setup"> {{ $t('completeSetup') }} </h1> </div> <div class="slide-wrapper"> <div class="icon-wrapper"> <q-icon name="wifi" size="10rem" color="white" class="temp-ill" /> </div> <p> {{ $t('reconnectToInternet') }} </p> </div> <div class="btns-wrapper"> <q-btn :disabled="!online" :label="$t('activateYourWallet')" color="primary" text-color="blueish" @click="complete" /> </div> </div> </template> <script> import { mapState } from 'vuex'; import { Network } from '@/helpers'; import Wallet from '@/store/wallet/entities/wallet'; import Address from '@/store/wallet/entities/address'; import Tx from '@/store/wallet/entities/tx'; export default { name: 'Complete', data() { return { online: null, account: null, showContent: false, }; }, computed: { ...mapState({ authenticatedAccount: (state) => { return state.settings.authenticatedAccount; }, setup: (state) => { return state.setup; }, delay: (state) => { return state.settings.delay; }, }), supportedCoins() { return this.$store.state.settings.supportedCoins; }, }, async mounted() { this.network = new Network(this.$q.platform.is); this.online = this.network.isOnline(); this.network .on('offline', () => { this.online = false; }) .on('online', () => { this.online = true; }); if (!this.setup.accountCreated) { console.log('this.setup: ', this.setup); if (this.online) { await this.complete(); } else { this.showContent = true; } } }, methods: { async storeTransactions(txs, id) { if (txs.length > 0) { const transactions = txs.map((tx) => { tx.account_id = this.authenticatedAccount; tx.wallet_id = id; return tx; }); transactions.sort((a, b) => { return this.createDate(b.confirmedTime) - this.createDate(a.confirmedTime); }); await Tx.$insert({ data: transactions }); } }, async enableCatalyst(initializedWallet, wallet) { const coinSDK = this.coinSDKS[wallet.sdk]; const { txHistory, accounts, balance, } = await this.discoverWallet(initializedWallet, coinSDK, wallet.network, wallet.sdk); Wallet.$update({ where: (record) => { return record.id === wallet.id; }, data: { externalChainAddressIndex: 0, internalChainAddressIndex: 0, confirmedBalance: balance, externalAddress: accounts[0].address, }, }); const newAddress = { account_id: this.authenticatedAccount, wallet_id: wallet.id, chain: 'external', address: accounts[0].address, index: 0, }; await Address.$insert({ data: newAddress }); await this.storeTransactions(txHistory.txs, wallet.id); }, /** * complete setup and store account entity. */ async complete() { this.$store.dispatch('settings/setLoading', true); setTimeout(async () => { try { const account = await this.accountInitializer.createAccount(this.setup); this.$store.dispatch('settings/setSelectedAccount', this.setup.accountName); await this.accountInitializer.createWallets(this.setup, account.id, this.supportedCoins); await this.accountInitializer.createERC20Wallets( this.setup, account.id, this.supportedCoins, ); this.$store.dispatch('setup/setAccountCreated'); this.$store.dispatch('settings/setAuthenticatedAccount', account.id); const wallet = Wallet.query().where((wal) => { return wal.name === 'Catalyst' && wal.account_id === account.id; }).get()[0]; const initializedWallet = wallet.hdWallet; if (!this.activeWallets[account.id]) { this.activeWallets[account.id] = {}; } this.activeWallets[account.id][wallet.name] = initializedWallet; let success = true; try { await this.enableCatalyst(initializedWallet, wallet); } catch (err) { success = false; } Wallet.$update({ where: (record) => { return record.id === wallet.id; }, data: { imported: success, enabled: success }, }); // Object.getPrototypeOf(this.$root).backEndService = // new this.BackEndService // (this.$root, this.authenticatedAccount, this.setup.pinArray.join('')); // await this.backEndService.connect(); // await this.backEndService.loadPriceFeed(); this.$store.dispatch('setup/clearSetupData'); this.$store.dispatch('settings/setLayout', 'light'); this.$router.push({ path: '/wallet' }); } catch (err) { this.errorHandler(err); } setTimeout(() => { this.$store.dispatch('settings/setLoading', false); }, this.delay.normal); }, this.delay.normal); }, }, }; </script> <style> .icon-wrapper { text-align: center; } .slide-wrapper { width: 100%; height: calc(100% - 7rem); display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 0 .5rem; } </style>
import React from "react"; import styled from "styled-components"; import { observer } from "mobx-react"; import FolderInput from "./FolderInput"; import { FolderItem } from "."; import { Folder } from "../models"; import FolderStore from "../stores/folder"; import { useStores } from "../stores"; const StyledFolderListContainer = styled.section` display: flex; flex-direction: column; justify-content: center; max-width: 1010px; width: 100%; margin: 20px 0; `; const StyledFolderList = styled.ul` margin: 0 auto; padding: 0; `; export interface FolderListProps { data: FolderStore; } const FolderList: React.FC<FolderListProps> = observer(({ data }) => { const { folderStore } = useStores(); folderStore.initialize(data.folders); return ( <StyledFolderListContainer> <FolderInput newFolder={folderStore.newFolder} /> <StyledFolderList> {folderStore.folders.map((folder: Folder) => ( <FolderItem {...folder} key={folder.id} editFolder={folderStore.editFolder} deleteFolder={folderStore.deleteFolder} /> ))} </StyledFolderList> </StyledFolderListContainer> ); }); export default FolderList;
from rest_framework import serializers from .models import DroneCategory, Drone, Pilot, Competition import drones.views from django.contrib.auth.models import User class DroneCategorySerializer(serializers.HyperlinkedModelSerializer): drones = serializers.HyperlinkedRelatedField( many = True, read_only = True, view_name='drone-detail' ) class Meta: model = DroneCategory fields = ( 'url', 'pk', 'name', 'drones', ) class DroneSerializer(serializers.HyperlinkedModelSerializer): # Display the category name drone_category = serializers.SlugRelatedField( queryset=DroneCategory.objects.all(), slug_field='name' ) # Display the owner's username (read_only) owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Drone fields = ( 'url', 'name', 'drone_category', 'owner', 'manufacturing_date', 'has_it_competed', 'inserted_timestamp', ) class CompetitionSerializer(serializers.HyperlinkedModelSerializer): # Display all the details for the related drone drone = DroneSerializer() class Meta: model = Competition fields = ( 'url', 'pk', 'distance_in_feet', 'distance_achievement_date', 'drone', ) class PilotSerializer(serializers.HyperlinkedModelSerializer): competitions = CompetitionSerializer( many = True, read_only=True, ) gender = serializers.ChoiceField( choices=Pilot.GENDER_CHOICES ) gender_description = serializers.CharField( source = 'get_gender_display', read_only=True ) class Meta: model = Pilot fields = ( 'url', 'name', 'gender', 'gender_description', 'races_count', 'inseted_timestamp', 'competitions', ) class PilotCompetitionSerializer(serializers.ModelSerializer): # Display the pilot's name pilot = serializers.SlugRelatedField( queryset = Pilot.objects.all(), slug_field = 'name' ) # Display the drone's name drone = serializers.SlugRelatedField( queryset=Drone.objects.all(), slug_field='name' ) class Meta: model = Competition fields = ( 'url', 'pk', 'distance_in_feet', 'distance_achievement_date', 'pilot', 'drone', ) class UserDroneSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Drone fields = ( 'url', 'name' ) class UserSerializer(serializers.HyperlinkedModelSerializer): drones = UserDroneSerializer( many = True, read_only = True, ) class Meta: model = User fields = ( 'url', 'pk', 'username', 'drone' )
import { Injectable } from "@nestjs/common"; import { Assistant } from "./dto/models"; import Message from "openai"; import OpenAI from "openai"; const mm = "🍎🍎🍎 AssistantService : "; import { ThreadCreateParams } from "openai/resources/beta/threads/threads"; import * as fs from "fs"; import * as path from "path"; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); console.log(`${mm} ... my key : ${process.env.OPENAI_API_KEY}`); /** * AssistantService implements the OpenAI Assistant API */ @Injectable() export class AssistantService { async createAssistant( assistant: Assistant ): Promise<Message.Beta.Assistants.Assistant> { console.log( `${mm} ... creating assistant : 🔵 ${JSON.stringify(assistant)}` ); const fileIds = []; if (assistant.fileIds.length > 0) { assistant.fileIds.forEach((a) => { fileIds.push(a); }); } const ass: Message.Beta.Assistants.AssistantCreateParams = { model: assistant.model, file_ids: fileIds, description: assistant.description, name: assistant.name, tools: [{ type: "retrieval" }], instructions: assistant.instructions, }; // const assistantCreated = await openai.beta.assistants.create(ass); console.log( `${mm} assistant created: 🔵 ${JSON.stringify(assistantCreated)}` ); return assistantCreated; } async createAssistantFile( assistantId: string, fileId: string ): Promise<Message.Beta.Assistants.Files.AssistantFile> { const myAssistantFile = await openai.beta.assistants.files.create( assistantId, { file_id: fileId, } ); return myAssistantFile; } async getAssistantFiles( assistantId: string ): Promise<Message.Beta.Assistants.Files.AssistantFilesPage> { const myAssistantFiles = await openai.beta.assistants.files.list(assistantId); return myAssistantFiles; } async listAssistants(): Promise<Message.Beta.Assistants.AssistantsPage> { const params: Message.Beta.Assistants.AssistantListParams = { order: "desc", limit: 100, }; const myAssistants = await openai.beta.assistants.list(params); console.log( `${mm} Assistants found: 🔵 🔵 🔵 ${myAssistants.data.length} 🔵` ); myAssistants.data.forEach((ass) => { console.log( `${mm} Assistant: 🔵 ${ass.name} 🔵 model: ${ass.model} 🔵 ${ass.description}` ); }); return myAssistants; } async createMessage( threadId: string, content: string, fileId: string ): Promise<Message.Beta.Threads.Messages.ThreadMessage> { let msgCreateParams: Message.Beta.Threads.MessageCreateParams = { content: content, role: "user", file_ids: fileId == null? []: [fileId], }; console.log(`${mm} ... creating message : ${threadId} - ${content}`); const threadMessage = await openai.beta.threads.messages.create( threadId, msgCreateParams ); return threadMessage; } async runThread( threadId: string, assistantId: string, ): Promise<Message.Beta.Threads.Runs.Run> { console.log( `${mm} ... runThread : assistantId: ${assistantId} threadId: ${threadId} ` ); const run = await openai.beta.threads.runs.create(threadId, { assistant_id: assistantId, }); return run; } async checkRunStatus( threadId: string, runId: string ): Promise<Message.Beta.Threads.Runs.Run> { console.log( `${mm} getting thread run status ... threadId: ${threadId} runId: ${runId}` ); const run = await openai.beta.threads.runs.retrieve(threadId, runId); return run; } async getAssistants(): Promise<Message.Beta.Assistants.AssistantsPage> { console.log(`${mm} getting assistants ...`); const assistants = await openai.beta.assistants.list(); return assistants; } async getThread(threadId: string): Promise<Message.Beta.Threads.Thread> { console.log(`${mm} getThread ...`); const thread = await openai.beta.threads.retrieve(threadId); return thread; } async createThread( messages: any[] ): Promise<Message.Beta.Threads.Thread> { console.log(`${mm} creating thread with messages : ${messages.length}...`); const params: Message.Beta.Threads.ThreadCreateParams = { messages: messages, }; const thread = await openai.beta.threads.create(params); console.log(`${mm} thread created: 🍎🍎🍎 ${JSON.stringify(thread)} ...`); return thread; } async uploadFile( path: string, name: string ): Promise<Message.Files.FileObject> { const mFile: File = new File([fs.readFileSync(path)], name); console.log( `${mm} assistant file to upload, name: 🍎 ${mFile.name} ${mFile.size} bytes 🍎` ); try { const fileResult = await openai.files.create({ file: mFile, purpose: "assistants", }); console.log( `${mm} assistant file uploaded, status: 🍎 ${fileResult.status} 🍎` ); return fileResult; } catch (error) { console.error("Error uploading file:", error); throw error; } } async listModels(): Promise<Message.Models.ModelsPage> { const list = await openai.models.list(); console.log(`${mm} OpenAI models found: 🔵 🔵 ${list.data.length} 🍎`); list.data.forEach((model) => { console.log(`${mm} OpenAI model: 🔵 🔵 🔵 ${JSON.stringify(model)} 🔵`); }); return list; } async getThreadMessages( threadId: string ): Promise<Message.Beta.Threads.Messages.ThreadMessagesPage> { const messages = await openai.beta.threads.messages.list(threadId); console.log( `${mm} Thread result Messages: 🍎 ${JSON.stringify(messages)} 🍎 ` ); return messages; } }
// // NotificationListViewModel.swift // MovieShare // // Created by Rio Nagasaki on 2023/07/27. // import Foundation import Combine @MainActor final class NotificationListViewModel: ObservableObject { enum NoticeType: String, CaseIterable { case good = "いいね" case comment = "コメント" case friend = "フレンド" } let noticeSections:[NoticeType] = NoticeType.allCases private let noticeService = NoticeFirestoreService() private var cancellable = Set<AnyCancellable>() @Published var isLoading: Bool = false @Published var activeNoticeType: [NoticeType] = [] @Published var allNotices:[Notice] = [] @Published var likeNotices: [LikeNoticeObservableModel] = [] @Published var commentNotices: [CommentNoticeObservableModel] = [] @Published var followNotices: [RequestNoticeObservableModel] = [] @Published var selectedCategory: Int = 0 @Published var isUpdateReadStatus: Bool = false @Published var isErrorAlert: Bool = false @Published var errorMessage: String = "" func getNotice(appState: AppState, userID: String) async { self.noticeService.getAllNotices(userID: userID) .sink { [weak self] completion in guard let self = self else { return } switch completion { case .finished: self.confirmNotice(appState: appState) case .failure(let error): self.isErrorAlert = true self.errorMessage = error.errorMessage } } receiveValue: { [weak self] (likeNotices, commentNotices, followNotices) in guard let self = self else { return } self.likeNotices = [] self.commentNotices = [] self.followNotices = [] self.likeNotices = likeNotices self.commentNotices = commentNotices self.followNotices = followNotices } .store(in: &self.cancellable) } func confirmNotice(appState: AppState) { let commentNoticeReadStatus:[Bool] = self.commentNotices.map { $0.isRead } let followNoticeReadStatus:[Bool] = self.followNotices.map { $0.isRead } let allNoticesReadStatus:[Bool] = commentNoticeReadStatus + followNoticeReadStatus if commentNoticeReadStatus.contains(false) { self.activeNoticeType.append(.comment) } else { self.activeNoticeType = self.activeNoticeType.compactMap { notice in if notice == .comment { return nil } else { return notice } } } if followNoticeReadStatus.contains(false) { self.activeNoticeType.append(.friend) } else { self.activeNoticeType = self.activeNoticeType.compactMap { notice in if notice == .friend { return nil } else { return notice } } } if allNoticesReadStatus.contains(false) { if !appState.tabWithNotice.contains(.notification) { appState.tabWithNotice.append(.notification) } } else { if appState.tabWithNotice.contains(.notification) { appState.tabWithNotice = appState.tabWithNotice.compactMap { notice in if notice == .notification { return nil } else { return notice } } } } } func getCommentNotice(userID: String, appState: AppState){ self.noticeService.getCommentNoticeInfo(userID: userID) .sink { [weak self] completion in guard let self = self else { return } switch completion { case .finished: self.confirmNotice(appState: appState) case .failure(let error): self.isErrorAlert = true self.errorMessage = error.errorMessage } } receiveValue: { [weak self] commentNotices in guard let self = self else { return } self.commentNotices = [] self.commentNotices = commentNotices self.confirmNotice(appState: appState) } .store(in: &self.cancellable) } func getLikeNotice(userID: String) { self.noticeService.getLikeNoticeInfo(userID: userID) .sink { [weak self] completion in guard let self = self else { return } switch completion { case .finished: print("finished") case .failure(let error): self.isErrorAlert = true self.errorMessage = error.errorMessage } } receiveValue: { [weak self] likeNotices in guard let self = self else { return } self.likeNotices = [] self.likeNotices = likeNotices } .store(in: &self.cancellable) } func getRequestNotice(userID: String, appState: AppState) { self.noticeService.getRequestNoticeInfo(userID: userID) .sink { [weak self] completion in guard let self = self else { return } switch completion { case .finished: self.confirmNotice(appState: appState) case .failure(let error): self.isErrorAlert = true self.errorMessage = error.errorMessage } } receiveValue: { [weak self] followNotices in guard let self = self else { return } self.followNotices = [] self.followNotices = followNotices self.confirmNotice(appState: appState) } .store(in: &self.cancellable) } func updateReadStatus( noticeType:String, noticeID: String, userID: String, appState: AppState ) { self.noticeService .updateReadStatus( noticeType: noticeType, userID: userID, noticeID: noticeID ) .sink { [weak self] completion in guard let self = self else { return } switch completion { case .finished: self.confirmNotice(appState: appState) case .failure(let error): self.isErrorAlert = true self.errorMessage = error.errorMessage } } receiveValue: { _ in } .store(in: &self.cancellable) } // 一括既読機能 func updateAllNoticeReadStatus(userID: String, appState: AppState) { self.isLoading = true let unreadCommentNoticeIDs = self.commentNotices.filter { $0.isRead == false }.map { $0.id } let unreadRequestNoticeIDs = self.followNotices.filter { $0.isRead == false }.map { $0.id } let commentUpdatePublisher:[AnyPublisher<Void, AppError>] = unreadCommentNoticeIDs.map { id in self.noticeService.updateReadStatus(noticeType: "CommentNotice", userID: userID, noticeID: id) } let requestUpdatePublisher:[AnyPublisher<Void, AppError>] = unreadRequestNoticeIDs.map { id in self.noticeService.updateReadStatus(noticeType: "RequestNotice", userID: userID, noticeID: id) } // set publisher to concurrent let updatePublisher = Publishers.MergeMany(commentUpdatePublisher + requestUpdatePublisher) // subscribe updatePublisher.sink { [weak self] completion in guard let self = self else { return } switch completion { case .finished: self.isLoading = false // self.getNotice(appState:appState, userID: userID) case .failure(let error): self.errorMessage = error.errorMessage self.isErrorAlert = true } } receiveValue: { _ in }.store(in: &self.cancellable) } }
from rest_framework.response import Response from rest_framework.permissions import AllowAny from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes from django.contrib.auth import get_user_model, authenticate from .serializers import ConsumableSerializer from .models import Consumable @api_view(['GET']) def get_routes(request): routes = [ { 'Endpoint': '/', 'method': '', 'body': '', 'description': '', } ] return Response(routes) @api_view(['POST']) @permission_classes([AllowAny]) def register(request): user = get_user_model().objects.create_user( username = request.data['username'], password = request.data['password'], ) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}) @api_view(['POST']) @permission_classes([AllowAny]) def login(request): username = request.data['username'] password = request.data['password'] user = authenticate(username=username, password=password) if user: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) return Response({'error': 'Invalid credentials.'}, status=400) @api_view(['GET']) @permission_classes([AllowAny]) def get_consumables(request): consumables = Consumable.objects.all() serializer = ConsumableSerializer(consumables, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes([AllowAny]) def get_consumable(request, pk): consumable = Consumable.objects.get(id=pk) serializer = ConsumableSerializer(consumable, many=False) return Response(serializer.data) @api_view(['POST']) @permission_classes([AllowAny]) def create_consumable(request): data = request.data consumable = Consumable.objects.create( name = data['name'], description = data['description'], price = data['price'], ) serializer = ConsumableSerializer(consumable, many=False) return Response(serializer.data) @api_view(['PUT']) def update_consumable(request, pk): data = request.data consumable = Consumable.objects.get(id=pk) serializer = ConsumableSerializer(consumable, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @api_view(['DELETE']) @permission_classes([AllowAny]) def delete_consumable(request, pk): data = request.data consumable = Consumable.objects.get(id=pk) consumable.delete() return Response("Consumable was deleted!")
import React from "react"; import { Link } from "react-router-dom"; import { Rating } from "@mui/material"; function ProductCard(props) { const options = { value: props.product.rating, readOnly: true, precision: 0.5, }; return ( <Link className="productCard" to={`/product/${props.product._id}`}> {props.product.images[0] && ( <img src={props.product.images[0].url} alt={props.product.name} /> )} <p>{props.product.name}</p> <div> <Rating {...options} />{" "} <span className="productCardSpan"> ({props.product.numOfReviews} reviews) </span> </div> <span>&#x20b9;{props.product.price}</span> </Link> ); } export default ProductCard;
# Copyright 2024 The Wordcab Team. All rights reserved. # # Licensed under the MIT License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://github.com/Wordcab/wordcab-transcribe/blob/main/LICENSE # # Except as expressly provided otherwise herein, and to the fullest # extent permitted by law, Licensor provides the Software (and each # Contributor provides its Contributions) AS IS, and Licensor # disclaims all warranties or guarantees of any kind, express or # implied, whether arising under any law or from any usage in trade, # or otherwise including but not limited to the implied warranties # of merchantability, non-infringement, quiet enjoyment, fitness # for a particular purpose, or otherwise. # # See the License for the specific language governing permissions # and limitations under the License. """Dependencies module.""" import asyncio from contextlib import asynccontextmanager from fastapi import FastAPI from loguru import logger from my_project.config import settings from my_project.utils import retrieve_user_platform from my_project.services.example_service import ExampleService # Define the maximum number of files to pre-download download_limit = asyncio.Semaphore(10) # Define the ASR service to use depending on the settings service = ExampleService() @asynccontextmanager async def lifespan(app: FastAPI) -> None: """Context manager to handle the startup and shutdown of the application.""" if retrieve_user_platform() != "linux": logger.warning( "You are not running the application on Linux.\nThe application was tested" " on Ubuntu 22.04, so we cannot guarantee that it will work on other" " OS.\nReport any issues with your env specs to:" " https://github.com/Wordcab/wordcab-transcribe/issues" ) logger.info("Warmup initialization...") await service.inference_warmup() yield # This is where the execution of the application starts
<template> <BaseModalMobilePage @back="screenSlider!.slideBack()" :title="slideTitle" :show-back-button="canGoBack" > <div class="relative pb-9 pt-16"> <div class="container"> <div class="mx-auto flex h-[128px] w-[128px] items-center justify-center rounded-full bg-aist-grey-light text-[85px] text-aist-grey" > <i class="icon-user block"></i> </div> </div> <div class="mt-9"> <ScreenSliderWrapper ref="screenSliderWrapper"> <ScreenSliderSlide :id="'main'" :title="'Авторизация'" > <div class="container pb-3 pt-3"> <FormAuth @want-to-register="screenSlider!.slideTo('register')" /> </div> </ScreenSliderSlide> <ScreenSliderSlide :id="'register'" :title="'Регистрация'" > <div class="container pb-3 pt-3"> <FormRegistration @registrated="onRegistration" /> </div> </ScreenSliderSlide> </ScreenSliderWrapper> </div> <Transition appear-active-class="transition duration-100" appear-from-class="opacity-0" leave-active-class="transition duration-100" leave-from-class="opacity-0" > <div v-if="authIsLoading" class="absolute left-0 top-0 h-full w-full bg-white/50" > <div class="absolute left-1/2 top-1/2 block h-10 w-10 -translate-x-1/2 -translate-y-1/2" > <BaseLoading /> </div> </div> </Transition> </div> </BaseModalMobilePage> </template> <script setup lang="ts"> import ScreenSlider from '~/utils/ScreenSlider/ScreenSlider'; import type { ScreenSliderWrapper } from '#components'; const slideTitle = ref<string>('Авторизация'); const canGoBack = ref<boolean>(false); let screenSlider: ScreenSlider | null = null; const screenSliderWrapper = ref<InstanceType<typeof ScreenSliderWrapper> | null>(null); onMounted(() => { screenSlider = new ScreenSlider(screenSliderWrapper.value!.$el, { onScreenChange: () => { slideTitle.value = screenSlider!.currentSlide.title ?? ''; canGoBack.value = screenSlider!.canGoBack; }, }); }); const { form, auth, isLoading: authIsLoading } = useAuthorization(); async function onRegistration(phone: string, password: string) { form.phone.value = phone; form.password.value = password; await auth(); } </script>
import { useEffect, useState } from "react"; import Table from "react-bootstrap/Table"; import jwt_decode from "jwt-decode"; import axios from "axios"; import { useNavigate } from "react-router-dom"; import { useDispatch } from "react-redux"; import { selectReceiver, selectUser, } from "../../Redux/slices/userSelectedSlice"; import SidebarApp from "../FormsComponent/SidebarApp"; function PatientList() { const dispatch = useDispatch(); const [User, setUser] = useState({}); const navigate = useNavigate(); const [patients, setPatients] = useState([]); const token = localStorage.getItem("jwtToken"); var decodedToken = jwt_decode(token); useEffect(() => { axios .get(`${process.env.REACT_APP_BACKEND_URL}/patient/getUserById/${decodedToken.id}`) .then((response) => { setUser(response.data); }) .catch((error) => { console.error(error); }); }, []); useEffect(() => { axios .get(`${process.env.REACT_APP_BACKEND_URL}/listUser`, { doctorId: decodedToken.id, }) .then((response) => { setPatients(response.data); }) .catch((error) => { console.log(error.message); }); }, []); useEffect(() => { axios .post(`${process.env.REACT_APP_BACKEND_URL}/doctor/getPatientList`, { doctorId: decodedToken.id, }) .then((response) => { setPatients(response.data); }) .catch((error) => { console.log(error.message); }); }, []); const handleClick = async (patient) => { dispatch(selectUser(patient.userName)); dispatch(selectReceiver(patient)); await axios.post(`${process.env.REACT_APP_BACKEND_URL}/chat`, { userId: patient._id, userConnectedId: decodedToken.id, }); navigate("/UpdateProfile/chat"); }; return ( <> <div className="container pt-5 pb-5"> <div className=" row "> <div className="col-lg-4"> <SidebarApp user={User}></SidebarApp> </div> <div className="col-lg-8 mb-5"> <div className="card cardMD cardRes "> <div className="card-header "> <i className="fas fa-plus-square" /> Liste des utilisateurs </div> <div className="card-body"> <Table striped style={{ borderCollapse: "collapse", width: "100%", marginBottom: "1rem", backgroundColor: "#fff", color: "#212529", fontSize: "0.875rem", fontWeight: "400", lineHeight: "1.5", border: "1px solid #dee2e6", borderRadius: "0.25rem", overflow: "auto" }}> <thead style={{ backgroundColor: "#f5f5f5" }}> <tr> <th style={{ padding: "0.75rem", textAlign: "left", fontWeight: "700", textTransform: "uppercase", letterSpacing: "1px", borderBottom: "1px solid #dee2e6", }} > Patient Name </th> <th style={{ padding: "0.75rem", textAlign: "left", fontWeight: "700", textTransform: "uppercase", letterSpacing: "1px", borderBottom: "1px solid #dee2e6", }} > Role </th> <th style={{ padding: "0.75rem", textAlign: "center", fontWeight: "700", textTransform: "uppercase", letterSpacing: "1px", borderBottom: "1px solid #dee2e6", }} > Action </th> </tr> </thead> <tbody> {patients.map((patient, index) => ( <tr key={index} style={{ ':hover': { backgroundColor: "#f5f5f5" } }}> <td style={{ padding: "0.75rem", borderBottom: "1px solid #dee2e6", fontWeight: "bold", textTransform: "capitalize", }} > {patient.userName} </td> <td style={{ padding: "0.75rem", borderBottom: "1px solid #dee2e6", fontWeight: "bold", textTransform: "capitalize", }} > {patient.role} </td> <td style={{ padding: "0.75rem", textAlign: "center", borderBottom: "1px solid #dee2e6", }} > <button onClick={() => handleClick(patient)} style={{ padding: "0.375rem 0.75rem", border: "none", borderRadius: "0.25rem", backgroundColor: "#007bff", color: "#fff", cursor: "pointer", boxShadow: "0px 4px 4px rgba(0, 0, 0, 0.25)", transition: "all 0.3s ease", }} > <i className="bi bi-chat"></i> </button> </td> </tr> ))} </tbody> </Table> </div> </div> </div> </div> </div> </> ); } export default PatientList;
#!/usr/bin/env python3 """ Measure the average time taken to run an async task. """ import asyncio import time wait_n = __import__('1-concurrent_coroutines').wait_n def measure_time(n: int, max_delay: int) -> float: """Measure the average time taken to call wait_n.""" t0 = time.perf_counter() asyncio.run(wait_n(n, max_delay)) t = time.perf_counter() - t0 return t / n
import React, { useState } from 'react'; import { moneySuffix, roundToNumber, setCurrency } from '../utils'; import { Profile } from '../features/portfolio'; import { FaTrash } from 'react-icons/fa'; import { TickerSymbolDown, TickerSymbolUp } from './icons/TickerSymbol'; import { useAppSelector } from '../redux/app/hooks'; interface ProgressBarProps { widthPercentage: number; className?: string; } interface PortfolioCardProps { profile: Profile; idx: number; onDelete: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void; onEdit: () => void; } const PortfolioCard = ({ profile, idx, onDelete, onEdit }: PortfolioCardProps) => { const { darkMode } = useAppSelector((state) => state.theme); const currency = useAppSelector((state) => state.currency.value); const [displayTrashIcon, setDisplayTrashIcon] = useState(false); const marketCapToTotalVol = roundToNumber((profile.totalVolume * 100) / profile.marketCap, 0); const ProgressBar = ({ className, widthPercentage }: ProgressBarProps) => ( <div className={`flex flex-col w-14 justify-center items-center ${className}`}> <div className={`relative bg-cryptoGreen h-3 w-full rounded-full overflow-hidden border-black`} > <div className={`absolute top-0 left-0 h-full ${ darkMode ? 'bg-cryptoSliderWhite' : 'bg-black' } rounded-full`} style={{ width: `${widthPercentage}%` }} /> </div> </div> ); const keyNumber = Math.trunc(Math.random() * (100 - 1) + 1); return ( <div key={profile.id + keyNumber} className={`${idx !== 0 && 'mt-6'} flex md:justify-between flex-col lg:flex-row`} > <div className="bg-lightModeWhite dark:bg-darkNonIntComponentBg ml-5 flex flex-col justify-center items-center rounded-lg sm:items-center cursor-pointer lg:px-8 lg:pb-5 py-10" onMouseOver={() => setDisplayTrashIcon(true)} onMouseOut={() => setDisplayTrashIcon(false)} onClick={onEdit} > <div className="mt-6 flex flex-col justify-center items-center"> <div className="bg-lightModeBgGray dark:bg-darkIntComponentBg rounded-lg justify-center flex p-4"> <img src={profile.image} alt={`${profile.name} logo`} /> </div> <div className="text-xs mt-2 text-center"> <span id="profile_name_cryptoTitle"> {profile.name} {profile.name.length > 7 && <br />} </span> <span id="profile_symbol_cryptoTitle"> {profile.symbol && ` (${profile.symbol.toUpperCase()})`} </span> </div> <button onClick={(e) => { onDelete(e); }} className="text-xs lg:text-[0.5rem] text-center mt-2 h-8 flex justify-center items-center hover:w-16 hover:dark:bg-darkIntComponentBg rounded-lg hover:bg-lightModeBgGray" > <span id="asset-last-updated" className="w-16 flex justify-center"> {displayTrashIcon ? <FaTrash size={'0.5rem'} /> : `Updated: ${profile.purchase_date}`} </span> </button> </div> </div> <div className="flex flex-col text-sm lg:text-[0.6rem] ml-5 mt-3 lg:mt-0"> <h6 className="mb-2">Market Price:</h6> <div className="flex flex-col lg:flex-row justify-around bg-lightModeWhite dark:bg-darkNonIntComponentBg rounded-lg"> <div className="flex p-3 items-center"> <p>Current price: </p>{' '} <p className="text-cryptoGreen ml-2"> {setCurrency(currency)} {moneySuffix(roundToNumber(profile.currentPrice, 2))} </p> </div> <div className="flex p-3 items-center"> <p>Price change 24h: </p>{' '} <p className="flex items-center ml-2"> {profile.priceChange24h > 0 ? <TickerSymbolUp /> : <TickerSymbolDown />} <span className={`${profile.priceChange24h > 0 ? 'text-cryptoGreen' : 'text-cryptoRed'}`} > {roundToNumber(profile.priceChange24h, 2)} </span> </p> </div> <div className="flex p-3 items-center"> <p className="mr-2">Market Cap vs Volume: </p> <p className="mr-1 text-cryptoGreen"> {isNaN(marketCapToTotalVol) ? ( <span className="text-lg">∞</span> ) : ( `${marketCapToTotalVol}%` )} </p> <span> <ProgressBar widthPercentage={marketCapToTotalVol} /> </span> </div> <div className="flex p-3 items-center"> <p>Circ Supply vs Max Supply: </p>{' '} <span className="text-cryptoGreen ml-2"> {profile.maxSupply !== null && profile.circulatingSupply !== null ? ( `${((profile.circulatingSupply * 100) / profile.maxSupply).toFixed(0)}%` ) : ( <span className="text-lg">∞</span> )} </span> </div> </div> <h6 className="my-2">Your Coin:</h6> <div className="flex flex-col lg:flex-row justify-around bg-lightModeWhite dark:bg-darkNonIntComponentBg rounded-lg"> <div className="flex p-3 items-center"> <p className="mr-1">Coin Amount: </p>{' '} <span className="text-cryptoGreen">{profile.coinAmount}</span> </div> <div className="flex p-3 items-center"> <p className="mr-1">Amount Value: </p>{' '} <span className="text-cryptoGreen"> {setCurrency(currency)} {moneySuffix(profile.total)} </span> </div> <div className="flex p-3"> <p>Change Since Purchase: </p>{' '} <p className={`${ profile.priceChange > 0 ? 'text-cryptoGreen ' : 'text-cryptoRed' } flex items-center`} > {profile.priceChange > 0 ? <TickerSymbolUp /> : <TickerSymbolDown />} {setCurrency(currency)} {moneySuffix(roundToNumber(profile.priceChange, 2))} </p> </div> <div className="flex p-3 items-center"> <p className="mr-1">Purchase Date: </p>{' '} <span className="text-cryptoGreen">{profile.purchase_date}</span> </div> </div> </div> </div> ); }; export default PortfolioCard;
import prisma from 'lib/prisma'; import Container from 'components/Container'; import Guestbook from 'components/Guestbook'; export default function GuestbookPage({ fallbackData }) { return ( <Container title={`Guestbook`} description="Sign my digital guestbook and share some wisdom." preTitle="Sign my Guestbook" image="unsplash/photo-1627056503679-34051c0122c5" > <div className="mx-auto mb-16 flex max-w-2xl flex-col items-start justify-center"> <h1 className="mb-4 text-3xl font-bold tracking-tight text-black dark:text-white md:text-5xl"> /guestbook </h1> <p className="mb-4 text-gray-600 dark:text-gray-400"> Leave a comment below. It could be anything – appreciation, information, wisdom, or even humor. Surprise me! </p> <Guestbook fallbackData={fallbackData} /> </div> </Container> ); } export async function getStaticProps() { const entries = await prisma.guestbook.findMany({ orderBy: { updated_at: 'desc' } }); const fallbackData = entries.map((entry) => ({ id: entry.id.toString(), body: entry.body, created_by: entry.created_by.toString(), updated_at: entry.updated_at.toString() })); return { props: { fallbackData }, revalidate: 60 }; }
--- title: "[Recommended] Akamai Security Events via AMA connector for Microsoft Sentinel" description: "Learn how to install the connector [Recommended] Akamai Security Events via AMA to connect your data source to Microsoft Sentinel." author: cwatson-cat ms.topic: how-to ms.date: 10/23/2023 ms.service: microsoft-sentinel ms.author: cwatson --- # [Recommended] Akamai Security Events via AMA connector for Microsoft Sentinel Akamai Solution for Microsoft Sentinel provides the capability to ingest [Akamai Security Events](https://www.akamai.com/us/en/products/security/) into Microsoft Sentinel. Refer to [Akamai SIEM Integration documentation](https://developer.akamai.com/tools/integrations/siem) for more information. ## Connector attributes | Connector attribute | Description | | --- | --- | | **Log Analytics table(s)** | CommonSecurityLog (AkamaiSecurityEvents)<br/> | | **Data collection rules support** | [Azure Monitor Agent DCR](/azure/azure-monitor/agents/data-collection-rule-azure-monitor-agent) | | **Supported by** | [Microsoft Corporation](https://support.microsoft.com) | ## Query samples **Top 10 Countries** ```kusto AkamaiSIEMEvent | summarize count() by SrcGeoCountry | top 10 by count_ ``` ## Prerequisites To integrate with [Recommended] Akamai Security Events via AMA make sure you have: - ****: To collect data from non-Azure VMs, they must have Azure Arc installed and enabled. [Learn more](/azure/azure-monitor/agents/azure-monitor-agent-install?tabs=ARMAgentPowerShell,PowerShellWindows,PowerShellWindowsArc,CLIWindows,CLIWindowsArc) - ****: Common Event Format (CEF) via AMA and Syslog via AMA data connectors must be installed [Learn more](/azure/sentinel/connect-cef-ama#open-the-connector-page-and-create-the-dcr) ## Vendor installation instructions > [!NOTE] > This data connector depends on a parser based on a Kusto Function to work as expected which is deployed as part of the solution. To view the function code in Log Analytics, open Log Analytics/Microsoft Sentinel Logs blade, click Functions and search for the alias Akamai Security Events and load the function code or click [here](https://aka.ms/sentinel-akamaisecurityevents-parser), on the second line of the query, enter the hostname(s) of your Akamai Security Events device(s) and any other unique identifiers for the logstream. The function usually takes 10-15 minutes to activate after solution installation/update. 2. Secure your machine Make sure to configure the machine's security according to your organization's security policy [Learn more >](https://aka.ms/SecureCEF) ## Next steps For more information, go to the [related solution](https://azuremarketplace.microsoft.com/en-us/marketplace/apps/azuresentinel.azure-sentinel-solution-akamai?tab=Overview) in the Azure Marketplace.
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.tamatem.filescateg; /** * * @author BasharOthman */ import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FileCategorizer { public static void main(String[] args) { Path sourceDirectory = Paths.get(args[0]); Path destinationBaseDirectory = Paths.get(args[1]); int numThreads = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(numThreads); try { Set<String> prefixes = FilePrefixLister.prefixesList(args); for (String pref : prefixes) { Files.walkFileTree(sourceDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file)) { String fileName = file.getFileName().toString(); String prefix = pref; // getPrefix(fileName); if (!fileName.contains(prefix)) { return FileVisitResult.CONTINUE; } if (prefix != null) { Path destinationDirectory = destinationBaseDirectory.resolve(prefix); if (!Files.exists(destinationDirectory)) { Files.createDirectories(destinationDirectory); } executor.execute(() -> { try { copyFile(file, destinationDirectory.resolve(fileName)); } catch (IOException e) { e.printStackTrace(); } }); } } return FileVisitResult.CONTINUE; } }); } System.out.println("Cpying files completed successfully "); } catch (IOException e) { e.printStackTrace(); } // Shut down the executor executor.shutdown(); } private static void copyFile(Path sourceFile, Path destinationFile) throws IOException { System.out.println("Cpying file " + sourceFile + " to " + destinationFile); Files.copy(sourceFile, destinationFile, StandardCopyOption.REPLACE_EXISTING); } }
import gradio as gr from generate_image import generate_and_save_image #import random def generate_images(prompt, negative_prompt, width, height, guidance_scale, num_inference_steps, seed, batch_size,): # if seed == 0: # seed = random.randint(0, 9999999999) print(f"Using seed: {seed}") image_paths = generate_and_save_image(prompt, negative_prompt, width, height, guidance_scale, num_inference_steps, seed, batch_size) return image_paths with gr.Blocks() as app: with gr.Row(): with gr.Column(): image_display = gr.Gallery(show_label=False, allow_preview=True, columns=4, rows=4, scale=2) with gr.Column(): prompt_input = gr.Textbox(label="Prompt") negative_prompt_input = gr.Textbox(label="Negative Prompt") width_slider = gr.Slider(minimum=512, maximum=4096, step=64, label="Width", value=1024) height_slider = gr.Slider(minimum=512, maximum=4096, step=64, label="Height", value=1024) batch_size_slider = gr.Slider(minimum=1, maximum=50, step=1, label="Batch Size", value=1) guidance_scale_slider = gr.Slider(minimum=0.0, maximum=20.0, step=0.1, label="Guidance Scale", value=4.0) num_inference_steps_slider = gr.Slider(minimum=1, maximum=100, step=1, label="Inference Steps", value=20) seed_input = gr.Number(label="Seed (enter 0 for random)", value=0) generate_button = gr.Button("Generate") generate_button.click( generate_images, inputs=[prompt_input, negative_prompt_input, width_slider, height_slider, guidance_scale_slider, num_inference_steps_slider, seed_input, batch_size_slider], outputs=image_display ) app.launch()
import { CardTheme } from "@/components"; import { useChoiceTheme } from "@/hooks/useChoiceTheme"; import React from "react"; import { useTrail, animated } from "react-spring"; import { ContainerChoiceTheme } from "./style"; export function ChoiceTheme(): JSX.Element { const { themes } = useChoiceTheme(); const amoutThemes = themes.length; const animation = useTrail(amoutThemes, { from: { opacity: 0, scale: 0 }, to: { opacity: 1, scale: 1 }, config: { duration: 130 } }); return ( <ContainerChoiceTheme> <h1 className="theme__title">ESCOLHA O ASSUNTO</h1> <div className="theme__items"> {themes.map(({ id, label, image, destiny }, index) => ( <animated.div key={id} style={animation[index]}> <CardTheme label={label} image={image} destiny={destiny} /> </animated.div> ))} </div> </ContainerChoiceTheme> ); }
package repository import ( "context" "database/sql" "errors" "fmt" "github.com/halllllll/surume-local/internal/models" ) type EntraIder interface { Count() (int, error) GetEntraIdInfo(context.Context) (*models.EntraIdApp, error) SetEntraIdInfo(context.Context, *models.EntraIdApp) error UpdateEntraIdInfo(context.Context, *models.EntraIdApp) error SetAccountID(context.Context, *models.AccountID) error GetAccountID(context.Context, *models.AccountID) (*models.User, error) } type entraIdRepository struct { db *sql.DB } func NewEntraIdRepository(db *sql.DB) EntraIder { return &entraIdRepository{ db, } } func (er *entraIdRepository) Count() (int, error) { var count int err := er.db.QueryRow("SELECT COUNT (*) FROM entraid_info").Scan(&count) if err != nil { return 0, err } return count, nil } func (er *entraIdRepository) GetEntraIdInfo(ctx context.Context) (*models.EntraIdApp, error) { var data models.EntraIdApp tx, err := er.db.BeginTx(ctx, nil) if err != nil { return nil, err } defer tx.Rollback() stmt := ` SELECT client_id, authority, created_at, localhost_port, updated_at FROM entraid_info ` if err := tx.QueryRowContext(ctx, stmt).Scan(&data.ClientID, &data.Authority, &data.Created, &data.Port, &data.Updated); err != nil { return nil, err } if err := tx.Commit(); err != nil { return nil, err } return &data, nil } func (er *entraIdRepository) SetEntraIdInfo(ctx context.Context, data *models.EntraIdApp) error { stmt := ` INSERT INTO entraid_info (client_id, authority, localhost_port) VALUES (?, ?, ?) ` _, err := er.db.ExecContext(ctx, stmt, data.ClientID, data.Authority, data.Port) if err != nil { return err } return nil } func (er *entraIdRepository) UpdateEntraIdInfo(ctx context.Context, data *models.EntraIdApp) error { stmt := ` UPDATE entraid_info SET client_id = ?, authority = ?, localhost_port = ? ` _, err := er.db.ExecContext(ctx, stmt, data.ClientID, data.Authority, data.Port) if err != nil { return err } return nil } func (er *entraIdRepository) GetAccountID(ctx context.Context, id *models.AccountID) (*models.User, error) { var user models.User tx, err := er.db.BeginTx(ctx, nil) if err != nil { return nil, err } defer tx.Rollback() stmt := ` SELECT user_id FROM user WHERE user_id = ? ` if err := tx.QueryRowContext(ctx, stmt, id).Scan(&user); err != nil { if errors.Is(err, sql.ErrNoRows) { return nil, nil } return nil, err } fmt.Println("やったね!") return &user, nil } func (er *entraIdRepository) SetAccountID(ctx context.Context, id *models.AccountID) error { stmt := ` INSERT INTO user (user_id) VALUES (?) ON CONFLICT (user_id) DO NOTHING ` _, err := er.db.ExecContext(ctx, stmt, id) if err != nil { return err } return nil }
<%@ page import="demo.house.model.User" %> <!DOCTYPE html> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; session.removeAttribute("jiuzhouUser"); %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>租房</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <!-- Styles --> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700|Poppins:400,600" rel="stylesheet"> <link rel="shortcut icon" href="../img/logo.jpg"> <link href="../css/style1.css" rel="stylesheet" type="text/css" media="all" /> <!-- favicon and touch icons --> <link rel="shortcut icon" href="../js/assets/images/favicon.png"> <!-- Bootstrap --> <link href="../js/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"> <link href="../js/plugins/slick/slick.css" rel="stylesheet"> <link href="../js/plugins/slick-nav/slicknav.css" rel="stylesheet"> <link href="../js/plugins/wow/animate.css" rel="stylesheet"> <link href="../js/assets/css/bootstrap.css" rel="stylesheet"> <link href="../js/assets/css/theme.css" rel="stylesheet"> </head> <body class="listing-template"> <div id="page-loader"> <div class="loaders"> <img src="../js/assets/images/loader/3.gif" alt="First Loader"> <img src="../js/assets/images/loader/4.gif" alt="First Loader"> </div> </div> <header id="site-header"> <div id="site-header-top"> <div class="container"> <div class="row"> <div class="col-md-5"> <div class="clearfix"> <button class="btn btn-warning btn-lg header-btn visible-sm pull-right">List your Property for Free </button> <p class="timing-in-header">周一-周六:9:00 - 18:00</p> </div> </div> <div class="col-md-7"> <div class="clearfix"> <button class="btn btn-warning btn-lg header-btn hidden-sm" onclick="location.href='${ pageContext.request.contextPath }/pages/register.jsp'">注册 </button> <button class="btn btn-warning btn-lg header-btn hidden-sm" onclick="location.href='${ pageContext.request.contextPath }/pages/login.jsp'">登录 </button> <div class="language-in-header"> <i class="fa fa-globe"></i> <label for="language-dropdown"> 语言:</label> <select name="currency" id="language-dropdown"> <option value="CN">中文</option> <option value="AR">英语</option> </select> </div> </div> </div> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-md-3"> <figure id="site-logo"> <a href="index.html"><img src="../js/assets/images/logo.png" alt="Logo"></a> </figure> </div> <div class="col-md-6 col-sm-8"> <nav id="site-nav" class="nav navbar-default"> <ul class="nav navbar-nav"> <li><a href="./">首页</a></li> <li><a href="${ pageContext.request.contextPath }/pages/property-listing.jsp">租房</a></li> <li><a href="single-property.html">二手房</a></li> <li><a href="gallery.html">新房</a></li> <li><a href="${ pageContext.request.contextPath }/pages/contact.jsp">联系我们</a></li> </ul> </nav> </div> <div class="col-md-3 col-sm-4"> <div class="contact-in-header clearfix"> <i class="fa fa-mobile"></i> <span> 联系我们 <br> <strong>111 222 333 444</strong> </span> </div> </div> </div> </div> </header> <div id="site-banner" class="text-center clearfix"> <div class="container"> <h1 class="title wow slideInLeft">注册</h1> <ol class="breadcrumb wow slideInRight"> <li><a href="index.html">Home</a></li> <li><a href="property-map-view.html">Listing</a></li> <li class="active">Properties Grid</li> </ol> </div> </div> <div class="login-right"> <div class="container"> <h3>注册</h3> <div class="login-top"> <ul class="login-icons"> <li><a href="#" ><i class="facebook"> </i><span>Facebook</span></a></li> <li><a href="#" class="twit"><i class="twitter"></i><span>Twitter</span></a></li> <li><a href="#" class="go"><i class="google"></i><span>Google +</span></a></li> <li><a href="#" class="in"><i class="linkedin"></i><span>Linkedin</span></a></li> <div class="clearfix"> </div> </ul> <div class="form-info"> <form> <input type="text" placeholder="账号"id="userName" > <input type="text" placeholder="电子邮件" id="email" > <input type="password" placeholder="密码" id="pwd" > <input type="text" placeholder="手机号" id="phone"> <input type="text" placeholder="地址" id="address"> <label class="hvr-sweep-to-right"> <input type="button" id="submit" value="注册"> </label> </form> <div id="registerError"></div> <p>已有账号? <a href="login.jsp">登录</a></p> </div> </div> </div> </div> <footer id="footer"> <div class="site-footer"> <div class="container"> <div class="row"> <div class="col-md-4 col-sm-6"> <section class="widget about-widget clearfix"> <h4 class="title hide">关于我们</h4> <a class="footer-logo" href="#"><img src="../js/assets/images/footer-logo.png" alt="Footer Logo"></a> <p>我们是一家租房中介服务公司,为每一位顾客真诚服务!</p> <ul class="social-icons clearfix"> <li><a href="#"><i class="fa fa-twitter"></i></a></li> <li><a href="#"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-pinterest"></i></a></li> <li><a href="#"><i class="fa fa-youtube-play"></i></a></li> </ul> </section> </div> <div class="col-md-4 col-sm-6"> <section class="widget twitter-widget clearfix"> <h4 class="title">最新消息</h4> <%--<div id="twitter-feeds" class="clearfix"></div>--%> </section> </div> <div class="col-md-4 col-sm-6"> <section class="widget address-widget clearfix"> <h4 class="title">联系信息</h4> <ul> <li><i class="fa fa-map-marker"></i>上海市闵行区东川路500号信息楼316室</li> <li><i class="fa fa-phone"></i> (123) 45678910</li> <li><i class="fa fa-envelope"></i> a847323482@163.com</li> <li><i class="fa fa-fax"></i> +84 962 216 601</li> <li><i class="fa fa-clock-o"></i> 周一 - 周六: 9:00 - 18:00</li> </ul> </section> </div> </div> </div> </div> </footer> <a href="#top" id="scroll-top"><i class="fa fa-angle-up"></i></a> <!-- jQuery (necessary for Bootstrap's JavaScript ../js/plugins) --> <script src="../js/assets/js/jquery.min.js"></script> <script src="../js/assets/js/jquery.migrate.js"></script> <script src="../js/assets/js/bootstrap.min.js"></script> <script src="../js/plugins/slick-nav/jquery.slicknav.min.js"></script> <script src="../js/plugins/slick/slick.min.js"></script> <script src="../js/plugins/jquery-ui/jquery-ui.min.js"></script> <script src="../js/plugins/tweetie/tweetie.js"></script> <script src="../js/plugins/forms/jquery.form.min.js"></script> <script src="../js/plugins/forms/jquery.validate.min.js"></script> <script src="../js/plugins/modernizr/modernizr.custom.js"></script> <script src="../js/plugins/wow/wow.min.js"></script> <script src="../js/plugins/zoom/zoom.js"></script> <script src="../js/plugins/mixitup/mixitup.min.js"></script> <!---<script src="http://ditu.google.cn/maps/api/js?key=AIzaSyD2MtZynhsvwI2B40juK6SifR_OSyj4aBA&libraries=places"></script>---> <script src="../js/plugins/whats-nearby/source/WhatsNearby.js"></script> <script src="../js/assets/js/theme.js"></script> <script type="text/javascript"> $(function () { var username = $("#userName"); var password = $("#pwd"); var email = $("#email"); var phone = $("#phone"); var address = $("#address"); var error = $("#registerError"); $('#submit').click(function () { if(username.val()==null || username.val().trim()==""){ error.text("User name cannot be empty."); return false; } if(password.val()==null || password.val().trim()==""){ error.text("Password cannot be empty."); return false; } if(email.val()==null || email.val().trim()==""){ error.text("Email cannot be empty."); return false; } if(phone.val()==null || phone.val().trim()==""){ error.text("Phone cannot be empty."); return false; } if(address.val()==null || address.val().trim()==""){ error.text("Address cannot be empty."); return false; } if(!isEmail(email.val())){ error.text("Email format error"); return false; } if(!isMobile(phone.val().trim())){ error.text("Phone format error"); return false; } error.text(""); $.ajax({ type: "GET", url: "user/register", data: { userName: username.val(), pwd: password.val(), phone: phone.val(), email: email.val(), address: address.val() }, success: function (result) { if (result.flag) { window.location = window.location = "<%=basePath%>/admin"; } else { error.text(result.message); } }, error: function (e) { alert("cannot to sever"); } }); }); function isEmail(str){ var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/; return reg.test(str); } function isMobile(str) { var re = /^1\d{10}$/ return re.test(str); } }); </script> </body> </html>
#include <iostream> #include <map> #include <stack> #include <string> using namespace std; class Solution { public: bool isValid(string s) { stack<char> order; map<char, char> opposite_symbol = {{'(', ')'}, {'[', ']'}, {'{', '}'}, {')', '('}, {']', '['}, {'}', '{'}}; for (auto elem : s) { if (elem == '(' || elem == '[' || elem == '{') { order.push(elem); } else { if (order.empty()) { return false; } if (order.top() == opposite_symbol[elem]) { order.pop(); } else { return false; } } } if (!order.empty()) { return false; } return true; } };
/* Copyright (C) 2023 National Center for Atmospheric Research, * * SPDX-License-Identifier: Apache-2.0 * * Much of this solver was formulated and implemented from this book: * Hairer, E., Wanner, G., 1996. Solving Ordinary Differential Equations II: Stiff and Differential-Algebraic Problems, 2nd * edition. ed. Springer, Berlin ; New York. The source code for many (all?) of the solvers in that book can be found here: * http://www.unige.ch/~hairer/software.html * * Some extensions to the rosenbrock solver formulated there were formulated in this paper * Sandu, A., Verwer, J.G., Blom, J.G., Spee, E.J., Carmichael, G.R., Potra, F.A., 1997. Benchmarking stiff ode solvers for * atmospheric chemistry problems II: Rosenbrock solvers. Atmospheric Environment 31, 3459–3472. * https://doi.org/10.1016/S1352-2310(97)83212-8 * */ #pragma once #include <chrono> #include <ctime> #include <micm/jit/jit_compiler.hpp> #include <micm/jit/jit_function.hpp> #include <micm/process/jit_process_set.hpp> #include <micm/solver/jit_linear_solver.hpp> #include <micm/solver/rosenbrock.hpp> #include <micm/util/random_string.hpp> #include <micm/util/sparse_matrix_vector_ordering.hpp> #include <micm/util/vector_matrix.hpp> namespace micm { template< template<class> class MatrixPolicy = VectorMatrix, template<class> class SparseMatrixPolicy = VectorSparseMatrix, class LinearSolverPolicy = JitLinearSolver<DEFAULT_VECTOR_SIZE, SparseMatrixPolicy>, class ProcessSetPolicy = JitProcessSet<DEFAULT_VECTOR_SIZE>> class JitRosenbrockSolver : public RosenbrockSolver<MatrixPolicy, SparseMatrixPolicy, LinearSolverPolicy, ProcessSetPolicy> { std::shared_ptr<JitCompiler> compiler_; llvm::orc::ResourceTrackerSP function_resource_tracker_; using FuncPtr = void (*)(double*, const double); FuncPtr alpha_minus_jacobian_ = nullptr; public: JitRosenbrockSolver(const JitRosenbrockSolver&) = delete; JitRosenbrockSolver& operator=(const JitRosenbrockSolver&) = delete; JitRosenbrockSolver(JitRosenbrockSolver&& other) : RosenbrockSolver<MatrixPolicy, SparseMatrixPolicy, LinearSolverPolicy, ProcessSetPolicy>(std::move(other)), compiler_(std::move(other.compiler_)), function_resource_tracker_(std::move(other.function_resource_tracker_)), alpha_minus_jacobian_(std::move(other.alpha_minus_jacobian_)) { other.alpha_minus_jacobian_ = NULL; } JitRosenbrockSolver& operator=(JitRosenbrockSolver&& other) { RosenbrockSolver<MatrixPolicy, SparseMatrixPolicy, LinearSolverPolicy, ProcessSetPolicy>::operator=(std::move(other)); compiler_ = std::move(other.compiler_); function_resource_tracker_ = std::move(other.function_resource_tracker_); alpha_minus_jacobian_ = std::move(other.alpha_minus_jacobian_); other.alpha_minus_jacobian_ = NULL; return *this; } /// @brief Builds a Rosenbrock solver for the given system, processes, and solver parameters /// @param system The chemical system to create the solver for /// @param processes The collection of chemical processes that will be applied during solving JitRosenbrockSolver( std::shared_ptr<JitCompiler> compiler, const System& system, const std::vector<Process>& processes, const RosenbrockSolverParameters& parameters) : RosenbrockSolver<MatrixPolicy, SparseMatrixPolicy, LinearSolverPolicy, ProcessSetPolicy>( system, processes, parameters, [&](const SparseMatrixPolicy<double>& matrix, double initial_value) -> LinearSolverPolicy { return LinearSolverPolicy{ compiler, matrix, initial_value }; }, [&](const std::vector<Process>& processes, const std::map<std::string, std::size_t>& variable_map) -> ProcessSetPolicy { return ProcessSetPolicy{ compiler, processes, variable_map }; }), compiler_(compiler) { MatrixPolicy<double> temp{}; if (temp.GroupVectorSize() != parameters.number_of_grid_cells_) { throw std::runtime_error("Number of grid cells for JitRosenbrockSolver must match template parameter."); } this->GenerateAlphaMinusJacobian(); } ~JitRosenbrockSolver() { if (function_resource_tracker_ != NULL) { llvm::ExitOnError exit_on_error; exit_on_error(function_resource_tracker_->remove()); } } /// @brief compute [alpha * I - dforce_dy] /// @param jacobian Jacobian matrix (dforce_dy) /// @param alpha void AlphaMinusJacobian(SparseMatrixPolicy<double>& jacobian, const double& alpha) const { double a = alpha; if (alpha_minus_jacobian_) { for (auto& elem : jacobian.AsVector()) elem = -elem; alpha_minus_jacobian_(jacobian.AsVector().data(), a); } else { throw std::runtime_error("Failed to generate the alpha minus jacobia JIT function."); } } private: void GenerateAlphaMinusJacobian() { auto jacobian = this->GetState().jacobian_; // save sizes needed throughout the function std::size_t n_cells = jacobian.GroupVectorSize(); std::size_t number_of_nonzero_jacobian_elements = jacobian.AsVector().size(); // Create the JitFunction with the modified name JitFunction func = JitFunction::create(compiler_) .name("alpha_minus_jacobian") .arguments({ { "jacobian", JitType::DoublePtr }, { "alpha", JitType::Double } }) .return_type(JitType::Void); // constants llvm::Value* zero = llvm::ConstantInt::get(*(func.context_), llvm::APInt(64, 0)); llvm::Value* negative_one = llvm::ConstantFP::get(*(func.context_), llvm::APFloat(-1.0)); llvm::Value* jacobian_size = llvm::ConstantInt::get(*(func.context_), llvm::APInt(64, number_of_nonzero_jacobian_elements)); // types llvm::Type* double_type = func.GetType(JitType::Double); // iterative over the blocks of the jacobian and add the alpha value // jacobian_vector[i_elem + i_cell] += alpha; for (const auto& i_elem : this->state_parameters_.jacobian_diagonal_elements_) { llvm::Value* ptr_index[1]; auto cell_loop = func.StartLoop("add alpha", 0, n_cells); llvm::Value* elem_id = llvm::ConstantInt::get(*(func.context_), llvm::APInt(64, i_elem)); ptr_index[0] = func.builder_->CreateNSWAdd(cell_loop.index_, elem_id); llvm::Value* indexer = func.builder_->CreateGEP(double_type, func.arguments_[0].ptr_, ptr_index, "index jacobian array"); llvm::Value* jacobian_element = func.builder_->CreateLoad(double_type, indexer, "load jacobian element"); jacobian_element = func.builder_->CreateFAdd(jacobian_element, func.arguments_[1].ptr_, "add alpha"); func.builder_->CreateStore(jacobian_element, indexer); func.EndLoop(cell_loop); } func.builder_->CreateRetVoid(); auto target = func.Generate(); alpha_minus_jacobian_ = (FuncPtr)(intptr_t)target.second; function_resource_tracker_ = target.first; } }; } // namespace micm
package com.example.backend.application.controllers; import com.example.backend.application.dto.BookDTO; import com.example.backend.application.dto.requests.BookRequest; import com.example.backend.application.mappers.BookMapper; import com.example.backend.domain.model.Book; import com.example.backend.domain.repositories.BookRepository; import jakarta.validation.Valid; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static java.lang.Long.parseLong; @RestController @AllArgsConstructor @RequestMapping("/books") public class BookController { private BookRepository repository; private BookMapper mapper; @GetMapping("/user/{userId}/book/{bookId}") public BookDTO getBookById(@PathVariable Long userId, @PathVariable Long bookId) { Book selectedBook = findBookById(userId, bookId); return selectedBook != null ? mapper.toDTO(selectedBook) : null; } @GetMapping("/user/{userId}") public List<Book> findAllByUser(@PathVariable Long userId) { return repository.findAllByUserId(userId); } @GetMapping("/user/{userId}/{status}") public List<Book> findAllByStatus(@PathVariable Long userId, @PathVariable String status) { List<Book> books = repository.findAllByUserId(userId); List<Book> booksByStatus = new ArrayList<>(); for (Book book : books) { if (Objects.equals(book.getStatus(), status.toUpperCase())) { booksByStatus.add(book); } } return booksByStatus; } @PostMapping @ResponseStatus(HttpStatus.CREATED) public void save(@RequestBody @Valid BookRequest bookRequest) { Book book = mapper.toDomain(bookRequest); repository.save(book); } @PutMapping("/user/{userId}/book/{bookId}") public void update(@RequestBody @Valid BookRequest bookRequest, @PathVariable Long userId, @PathVariable Long bookId) { var selectedBook = findBookById(userId, bookId); if (selectedBook != null) { mapper.copyToDomain(bookRequest, selectedBook); repository.save(selectedBook); } } @DeleteMapping("{bookId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable String bookId) { repository.deleteById(parseLong(bookId)); } private Book findBookById(Long userId, Long bookId) { List<Book> books = repository.findAllByUserId(userId); return books.stream() .filter(book -> Objects.equals(book.getId(), bookId)) .findFirst() .orElse(null); } }
import React, { useState, useEffect } from "react"; import { Button, Card, CardHeader, CardBody, Container, Row, Col, } from "reactstrap"; import UserHeader from "components/Headers/UserHeader.js"; import axiosInstance from "api/axiosInstance"; const EmployeeDetail = () => { const [employeeData, setEmployeeData] = useState(null); useEffect(() => { const fetchEmployeeData = async () => { try { const response = await axiosInstance.get("/intimar/employee/profile"); setEmployeeData(response.data); } catch (error) { console.error("Error fetching employee data:", error); } }; fetchEmployeeData(); }, []); return ( <> <UserHeader /> <Container className="mt--7" fluid> <Row className="justify-content-center"> {/* Centra la tarjeta */} <Col lg="6" md="8"> {employeeData && ( <Card className="card-profile shadow"> <CardHeader className="text-center border-0 pt-8 pt-md-4 pb-0 pb-md-4"> {/* <div className="d-flex justify-content-between"> <Button className="mr-4" color="info" href="#pablo" onClick={(e) => e.preventDefault()} size="sm" > Regresar a inicio </Button> </div> */} </CardHeader> <CardBody className="pt-0 pt-md-4"> <div className="text-center"> <Row className="justify-content-center mb-9"> <Col lg="3"> <div className="card-profile-image"> <a href="#pablo" onClick={(e) => e.preventDefault()}> <img alt="..." className="rounded-circle" src={require("../../assets/img/theme/team-4-800x800.png")} /> </a> </div> </Col> </Row> <h3> {employeeData.name} {employeeData.lastname} </h3> <div className="h5 mt-4"> <i className="ni business_briefcase-24 mr-2" /> {employeeData.roles ? employeeData.roles.join(", ") : ""} </div> <hr className="my-4" /> <p><strong> Email: </strong> {employeeData.email} </p> <p> <strong> Teléfono: </strong> {employeeData.cellphone} </p> </div> </CardBody> </Card> )} </Col> </Row> </Container> </> ); }; export default EmployeeDetail;
export class Vector2D { public x: number; public y: number; protected mod: number | undefined; protected normal: Vector2D | undefined; constructor(); constructor(x: number, y: number); constructor(x?: number, y?: number) { this.x = x || 0; this.y = y || 0; } public equals(v: Vector2D): boolean { return this.x === v.x && this.y === v.y; } public clone(): Vector2D { return new Vector2D(this.x, this.y); } public normalize(): void { const mod = this.getMod(); if (mod === 0 || mod === 1) return; this.x /= mod; this.y /= mod; this.mod = 1; } public set(v: Vector2D): void { this.x = v.x; this.y = v.y; this.mod = v.mod; this.normal = v.normal; } /** * ``` * [A, B] + [C, D] = [A + C, B + D] * ``` */ public add(v: Vector2D): Vector2D { return new Vector2D(this.x + v.x, this.y + v.y); } /** * ``` * [A, B] - [C, D] = [A - C, B - D] * ``` */ public substract(v: Vector2D): Vector2D { return new Vector2D(this.x - v.x, this.y - v.y); } /** * ``` * N * [X, Y] = [N * X, N * Y] * ``` */ public scale(n: number): Vector2D { return new Vector2D(n * this.x, n * this.y); } /** * ``` * V・W = |V| * |W| * cos(Θ) * ``` */ public dotProduct(v: Vector2D): number { return this.getMod() * v.getMod() * this.cos(v); } /** * Returns `cos(Θ)` being `Θ` the angle between this and the given vector */ public cos(v: Vector2D): number { return (this.x * v.x + this.y * v.y) / (this.getMod() * v.getMod()); } /** * Returns the length of this vector |V| */ public getMod(): number { if (!this.mod) { this.mod = Math.sqrt(this.x * this.x + this.y * this.y); } return this.mod; } /** * Returns the normalized perpendicular vector `W` that asserts `V・W == 0` */ public getNormal(): Vector2D { if (!this.normal) { this.normal = new Vector2D(-this.y, this.x); this.normal.normalize(); } return this.normal; } /** * Reflects or "bounces" the current vector against a givel surface. * Return the resulting direction vector * ``` * R = V - 2 * (V・N) * ``` */ public bounce(surface: Vector2D): Vector2D { return this.bounceWithNormal(surface.getNormal()); } public bounceWithNormal(normal: Vector2D): Vector2D { return this.substract(normal.scale(2 * this.dotProduct(normal))); } public clampAngle(min: number, max: number): void { const mod = this.getMod(); const currentAngle = Math.atan2(this.y, this.x); const clampedAngle = Math.max(min, Math.min(max, currentAngle)); this.x = Math.cos(clampedAngle) * mod; this.y = Math.sin(clampedAngle) * mod; this.normal = undefined; } }
 using Application.DTO; using Cliente.Acess.Util; using Newtonsoft.Json; namespace Cliente.Acess { public class ClientAPIService { private AuthenticateResponse _token; private AuthenticateResponse token { get { if (_token == null || _token?.expira < DateTime.Now) _token = GetToken(); return _token; } } public ClientAPIService() { _token = GetToken(); } const string url = "https://localhost:7138"; const string controller = "/api/client"; private async Task<RestBase> CreateBaseRequest(string path, string token, bool buscaComtoken = true) { var rest = new RestBase($"{url}{path}"); if (buscaComtoken && !string.IsNullOrEmpty(token)) rest.AddHeaders("Authorization", $"Bearer {token}"); rest.AddHeaders("Content-Type", "application/json"); rest.AddHeaders("Accept", "*/*"); rest.AddHeaders("Accept", "application/json"); return rest; } public async Task<ClientDTO> GetCliente(int id) { try { var rest = await CreateBaseRequest(controller + "/"+ id, token.token); var response = rest.Client.Execute(rest.Request); if (response.IsSuccessful) { return JsonConvert.DeserializeObject<ClientDTO>(response.Content); } else { return null; } } catch (Exception ex) { throw (new Exception($"Erro ao buscar cliente ${ex.Message}")); } return null; } public AuthenticateResponse GetToken() { try { var rest = CreateBaseRequest(controller + "/autenticar", "",false); var response = rest.Result.Client.Execute(rest.Result.Request); if (response.IsSuccessful) { return JsonConvert.DeserializeObject<AuthenticateResponse>(response.Content); } else { return null; } } catch (Exception ex) { throw (new Exception($"Erro ao buscar token ${ex.Message}")); } return null; } public async Task<List<ClientDTO>> GetAll() { try { var rest = await CreateBaseRequest(controller+ "/all", token.token); var response = rest.Client.Execute(rest.Request); if (response.IsSuccessful) { return JsonConvert.DeserializeObject<List<ClientDTO>>(response.Content); } else { return null; } } catch (Exception ex) { throw (new Exception($"Erro ao buscar cliente ${ex.Message}")); } return null; } public async Task<bool> Post(ClientDTO cliente) { try { var rest = await CreateBaseRequest(controller , token.token); var json = JsonConvert.SerializeObject(cliente); var response = await rest.PostAsync(cliente, useRetry: true); if (response.IsSuccessful && response.StatusCode == System.Net.HttpStatusCode.Created) { return true; } else if (response?.StatusCode == System.Net.HttpStatusCode.BadRequest) { return false; } else throw (new Exception($"Erro ao Incluir client . ${response?.StatusCode.ToString()}")); } catch (Exception ex) { throw (new Exception($"Erro ao incluir client. ${ex.Message}")); } return false; } public async Task<bool> Delete(int id) { try { var rest = await CreateBaseRequest(controller +"/"+ id, token.token); var response = rest.Delete(); if (response.IsSuccessful) { return true; } else if (response?.StatusCode == System.Net.HttpStatusCode.BadRequest) { return false; } else throw (new Exception($"Erro ao excluir . ${response?.StatusCode.ToString()}")); } catch (Exception ex) { throw (new Exception($"Erro ao excluir. ${ex.Message}")); } return false; } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device --> <link rel="icon" type="image/png" sizes="32x32" href="./assets/images/favicon-32x32.png"> <title>Frontend Mentor | Results summary component</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <!-- Feel free to remove these styles or customise in your own stylesheet 👍 --> <link rel="stylesheet" href="style.css"> <style> .attribution { font-size: 11px; text-align: center; } .attribution a { color: hsl(228, 45%, 44%); } </style> </head> <body> <div class="container d-flex p-2 rounded-5"> <main class="result d-flex flex-column justify-content-between align-items-center p-3 rounded-5"> Your Result <div class="score rounded-circle d-flex flex-column justify-content-center"> <p class="number fs-1">76</p> <span class="hundred" style="color: hsl(241, 100%, 89%);">of 100</span> </div> <div class="message m-3 d-flex flex-column align-items-center "> <p class="comment fs-3">Great</p> <p class="text">You scored higher than 65% of the people who have taken these tests.</p> </div> </main> <aside class="summary p-5 d-flex flex-column"> <p class="summary fs-4">Summary</p> <div class="reaction bg-danger-subtle rounded m-3 d-flex gap-5 p-2"> <div class="text"> <img src="./assets/images/icon-reaction.svg" alt=""> <span class="reaction text-danger p-2">Reaction</span> </div> <span class="number d-flex">80 <span class="number d-flex align-items-center" style="color: grey;">/100</span></span> </div> <div class="memory bg-warning-subtle rounded m-3 d-flex gap-5 p-2 "> <div class="text"> <img src="./assets/images/icon-memory.svg" alt=""> <span class="memory text-warning">Memory</span> </div> <span class="number d-flex">92 <span class="number d-flex align-items-center" style="color: grey;">/100</span></span> </div> <div class="verbal bg-success-subtle rounded m-3 d-flex justify-content-between gap-5 p-2"> <div class="text"> <img src="./assets/images/icon-verbal.svg" alt=""> <span class="verbal text-success">Verbal</span> </div> <span class="number">61 <span class="number" style="color: grey;">/100</span></span> </div> <div class="visual bg-primary-subtle rounded m-3 d-flex justify-content-between gap-5 p-2"> <div class="text"> <img src="./assets/images/icon-visual.svg" alt=""> <span class="visual text-primary-emphasis">Visual</span> </div> <span>72 <span class="number" style="color: grey;">/100</span></span> </div> <button type="button" class="btn custom-btn rounded-pill m-3">Continue</button> </aside> </div> <div class="attribution"> Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>. Coded by <a href="#">Prayush Hada</a>. </div> </body> </html>