text
stringlengths
184
4.48M
import React, { Suspense, useEffect } from 'react'; import { useSearchRestaurantByUserInfinite } from '@apis/hooks/restaurant/useSearchRestaurantByUserInfinite'; import useGetUserInfo from '@apis/hooks/user/useGetUserInfo'; import DownArrow from '@assets/icons/DownArrow'; import LeftArrowIcon from '@assets/icons/LeftArrowIcon'; import Chip from '@commons/Chip'; import FilterChip from '@commons/FilterChip'; import Tab from '@components/common/Tab/Tab'; import LikePlace from '@layouts/OtherProfile/LikePlace'; import PostPlace from '@layouts/OtherProfile/PostPlace'; import { AppScreen } from '@stackflow/plugin-basic-ui'; import { useHomeFlow } from '@stacks/homeStackFlow'; import { openBottomSheet } from '@store/bottomSheetAtom'; import { SortKey, drinkCategoryState, foodCategoryState, profileId, sortByState, } from '@store/filterAtom'; import classNames from 'classnames'; import { AnimatePresence } from 'framer-motion'; import { useAtom, useSetAtom } from 'jotai'; import { nativeInfo } from '@utils/storage'; interface OtherProfileProps { params: { userId: number; }; } const OtherProfile = ({ params }: OtherProfileProps) => { const { pop } = useHomeFlow(); const [tab, setTab] = React.useState('POST'); const { UserData } = useGetUserInfo(params.userId); const [pastId, setPastId] = useAtom(profileId); const [foodState, setFoodState] = useAtom(foodCategoryState); const [drinkState, setDrinkState] = useAtom(drinkCategoryState); const [sortState] = useAtom(sortByState); const userLocation = nativeInfo.getData().userPosition; const { restaurantData, fetchNextPage, isFetchingNextPage, isEmpty } = useSearchRestaurantByUserInfinite({ userId: params.userId, userLocation: { x: userLocation.x, y: userLocation.y, }, filter: { categoryFilter: '', }, params: { page: 0, size: 10, }, }); const totalElement = () => { if (!restaurantData) { return null; } return restaurantData[0].data.page.totalElements; }; const handleOpenBottomSheet = useSetAtom(openBottomSheet); useEffect(() => { if (pastId !== params.userId) { setPastId(params.userId); setFoodState(''); setDrinkState(''); } }, []); if (UserData === undefined) { return <>์˜ค๋ฅ˜!</>; } else { return ( <AppScreen appBar={{ title: <h1 className={'text-l-medium'}></h1>, backButton: { render: () => ( <button className={'back-button'} onClick={pop}> <LeftArrowIcon /> </button> ), }, height: '48px', }} > <main className={'safe-area-layout-container'}> <div className={'other-profile-container'}> <div className={'user-info-container'}> <img className={'user-image'} src={UserData.profileImg} /> <div className={'user-info'}> <a className={classNames('title-s-bold', 'gray900')}> {UserData.nickname} </a> <div className={'post'}> <p className={classNames('text-l-medium', 'gray500')}> ๋“ฑ๋กํ•œ ๋ง›์ง‘ </p> <p className={classNames('text-l-medium', 'gray900')}> {totalElement()} </p> </div> </div> </div> <Tab.Root defaultId={tab} setState={setTab}> <Tab id={'POST'} color={'gray900'}> ๋“ฑ๋กํ•œ ๋ง›์ง‘ </Tab> <Tab id={'LIKE'} color={'gray900'}> ์ข‹์•„ํ•œ ๋ง›์ง‘ </Tab> </Tab.Root> <br /> <aside className={'see-all-filter'}> <Chip onClick={() => handleOpenBottomSheet('SORT_BY')}> {SortKey[sortState]} <DownArrow /> </Chip> <div className={classNames('filter-divider', 'gray200')} /> <FilterChip active={foodState !== ''} onClick={() => handleOpenBottomSheet('FOOD_CATEGORY')} > ์ข…๋ฅ˜ </FilterChip> <FilterChip active={drinkState !== ''} onClick={() => handleOpenBottomSheet('DRINK_CATEGORY')} > ์ฃผ๋ฅ˜ ์—ฌ๋ถ€ </FilterChip> </aside> <AnimatePresence mode="sync"> <Suspense fallback={<></>}> {tab === 'POST' ? ( <PostPlace userId={params.userId} /> ) : ( <LikePlace /> )} </Suspense> </AnimatePresence> </div> </main> </AppScreen> ); } }; export default OtherProfile;
' ' * Copyright (C) 2012-2013 Arctium <http://arctium.org> ' * ' * 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/>. ' Imports System.Collections Imports System.Reflection Namespace Singleton Public NotInheritable Class Singleton Private Sub New() End Sub Shared ObjectList As New Hashtable() Shared Sync As New [Object]() Public Shared Function GetInstance(Of T As Class)() As T Dim typeName As String = GetType(T).FullName SyncLock Sync If ObjectList.ContainsKey(typeName) Then Return DirectCast(ObjectList(typeName), T) End If End SyncLock Dim constructorInfo As ConstructorInfo = GetType(T).GetConstructor(BindingFlags.NonPublic Or BindingFlags.Instance, Nothing, Type.EmptyTypes, Nothing) Dim instance As T = DirectCast(constructorInfo.Invoke(New Object() {}), T) ObjectList.Add(instance.ToString(), instance) Return DirectCast(ObjectList(typeName), T) End Function End Class End Namespace
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>The 4 L's of Methamphetamine</title> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet"> <style> body { font-family: 'Roboto', sans-serif; margin: 0; padding: 0; line-height: 1.6; text-align: center; background-color: #000; color: #fff; } .start-screen { display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh; } .start-button, .next-button { font-size: 18px; padding: 12px 24px; border: none; border-radius: 5px; background: #fff; color: #000; cursor: pointer; margin-top: 20px; transition: background 0.3s, color 0.3s; font-family: 'Roboto', sans-serif; } .start-button:hover, .next-button:hover { background: #ddd; color: #000; } .content-page { display: none; } .content-page.active { display: block; } header { background: rgba(0, 0, 0, 0.9); color: #fff; padding: 20px; margin-bottom: 20px; } nav ul { list-style-type: none; margin: 0; padding: 0; } nav li { display: inline; margin-right: 10px; } nav a { text-decoration: none; color: #fff; font-size: 20px; } section { max-width: 400px; margin: auto; background: rgba(255, 255, 255, 0.9); padding: 20px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); margin-bottom: 20px; text-align: left; position: relative; } h2 { margin-bottom: 10px; color: #000; } p { color: #333; } </style> </head> <body> <div class="start-screen"> <h1 style="font-size: 48px; margin-bottom: 20px;">The 4 L's of Methamphetamine</h1> <button class="start-button" onclick="start()">Start</button> </div> <div class="content-page"> <header> <h1 style="font-size: 36px;">The 4 L's of Methamphetamine</h1> </header> <nav> <ul> <li><a href="#lover">Lover</a></li> <li><a href="#liver">Liver</a></li> <li><a href="#livelihood">Livelihood</a></li> <li><a href="#law">Law</a></li> </ul> </nav> <section id="lover"> <h2 style="font-size: 24px;">Lover</h2> <p>Methamphetamine can affect peoples relationships. Meth users may experience extreme changes in behavior, emotional instability, and financial hardship, all of which can lead to the destruction of a relationship </p> <button class="next-button" onclick="showLiver()">Next</button> </section> </div> <div class="content-page"> <header> <h1 style="font-size: 36px;">The 4 L's of Methamphetamine</h1> </header> <nav> <ul> <li><a href="#lover">Lover</a></li> <li><a href="#liver">Liver</a></li> <li><a href="#livelihood">Livelihood</a></li> <li><a href="#law">Law</a></li> </ul> </nav> <section id="liver"> <h2 style="font-size: 24px;">Liver</h2> <p>methamphetamine can have both physical and psychological effects it can include severe dental problems and also psychosis, including: paranoia hallucinations repetitive motor activity changes in brain structure and function deficits in thinking and motor skills increased distractibility memory loss and weight loss</p> <button class="next-button" onclick="showLivelihood()">Next</button> </section> </div> <div class="content-page"> <header> <h1 style="font-size: 36px;">The 4 L's of Methamphetamine</h1> </header> <nav> <ul> <li><a href="#lover">Lover</a></li> <li><a href="#liver">Liver</a></li> <li><a href="#livelihood">Livelihood</a></li> <li><a href="#law">Law</a></li> </ul> </nav> <section id="livelihood"> <h2 style="font-size: 24px;">Livelihood</h2> <p>Methamphetamine can effect even home and work life it can decrease the chances of you getting a job it can also get you kicked out of your job very quickly at home it could effect the way you treat and speak to people wich could lead to issues in the home</p> <button class="next-button" onclick="showLaw()">Next</button> </section> </div> <div class="content-page"> <header> <h1 style="font-size: 36px;">The 4 L's of Methamphetamine</h1> </header> <nav> <ul> <li><a href="#lover">Lover</a></li> <li><a href="#liver">Liver</a></li> <li><a href="#livelihood">Livelihood</a></li> <li><a href="#law">Law</a></li> </ul> </nav> <section id="law"> <h2 style="font-size: 24px;">Law</h2> <p>methamphetamine can also have legal conequences such as jail time and/or heavy fines </p> <button class="next-button" onclick="showLover()">Next</button> </section> </div> <script> function start() { document.querySelector('.start-screen').style.display = 'none'; document.querySelector('.content-page').classList.add('active'); } function showLiver() { document.querySelector('#lover').parentNode.classList.remove('active'); document.querySelector('#liver').parentNode.classList.add('active'); } function showLivelihood() { document.querySelector('#liver').parentNode.classList.remove('active'); document.querySelector('#livelihood').parentNode.classList.add('active'); } function showLaw() { document.querySelector('#livelihood').parentNode.classList.remove('active'); document.querySelector('#law').parentNode.classList.add('active'); } function showLover() { document.querySelector('#law').parentNode.classList.remove('active'); document.querySelector('#lover').parentNode.classList.add('active'); } </script> </body> </html>
import React, { Component } from 'react'; import CKEditor from '@ckeditor/ckeditor5-react'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; class Editor extends Component { render() { return ( <div className="editingApp"> <h2>Using CKEditor 5 build in React</h2> <CKEditor editor={ ClassicEditor } data="<p>Hello from CKEditor 5!</p>" onInit={ editor => { console.log( 'Editor is ready to use!', editor ); } } onChange={ ( event, editor ) => { const data = editor.getData(); console.log( { event, editor, data } ); } } onBlur={ editor => { console.log( 'Blur.', editor ); } } onFocus={ editor => { console.log( 'Focus.', editor ); } } /> </div> ); } } export default Editor;
import 'package:chat/pages/login_page.dart'; import 'package:chat/pages/usuarios_page.dart'; import 'package:chat/services/auth_service.dart'; import 'package:chat/services/socket_service.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class LoadingPage extends StatelessWidget { const LoadingPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: FutureBuilder( future: checkLoginState(context), builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) { return const Center( child: Text('Espere...'), ); }, ), ); } Future checkLoginState(BuildContext context) async { final authService = Provider.of<AuthService>(context, listen: false); final socketService = Provider.of<SocketService>(context, listen: false); final autenticado = await authService.isLoggedIn(); if (autenticado) { // Navigator.pushReplacementNamed(context, 'usuarios'); socketService.connect(); Navigator.pushReplacement( context, PageRouteBuilder( pageBuilder: (_, __, ___) => const UsuariosPage(), transitionDuration: const Duration(milliseconds: 0), )); } else { Navigator.pushReplacement( context, PageRouteBuilder( pageBuilder: (_, __, ___) => const LoginPage(), transitionDuration: const Duration(milliseconds: 0), )); } } }
package main import ( "context" "fmt" ) type ReservationRepository interface { CommitPrepared(ctx context.Context, txID string) RollbackPrepared(ctx context.Context, txID string) CreatePrepared(ctx context.Context, r *Reservation, txID string) error } type defaultReservationRepository struct { db *DB } func NewReservationRepository(db *DB) ReservationRepository { return &defaultReservationRepository{db: db} } func (repo *defaultReservationRepository) CreatePrepared(ctx context.Context, r *Reservation, txID string) error { tx, err := repo.db.DB().BeginTx(ctx, nil) if err != nil { return fmt.Errorf("error begin statement %w", err) } query := ` INSERT INTO reservation (reservation_id, hotel_id, room_type_id, start_date, end_date, status) VALUES ($1, $2, $3, $4, $5, $6); ` args := []interface{}{ r.ReservationID, r.HotelID, r.RoomTypeID, r.StartDate, r.EndDate, "pending_pay", } if _, err = tx.ExecContext(ctx, query, args...); err != nil { return err } if _, err = tx.ExecContext(ctx, fmt.Sprintf("PREPARE TRANSACTION '%s';", txID)); err != nil { return err } return nil } func (repo *defaultReservationRepository) CommitPrepared(ctx context.Context, txID string) { repo.db.DB().ExecContext(ctx, fmt.Sprintf("COMMIT PREPARED '%s';", txID)) } func (repo *defaultReservationRepository) RollbackPrepared(ctx context.Context, txID string) { repo.db.DB().ExecContext(ctx, fmt.Sprintf("ROLLBACK PREPARED '%s';", txID)) }
package problem1; import java.io.PrintWriter; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class Cml { private static final Option ARG_ADD = new Option("a", "add", false, "Add to number together"); private static final Option AGE_SUB = new Option("s", "subtraction", false, "subtraction to number together"); private static final Option ARG_MUL = new Option("m", "multiplication", false, "multiple to number together"); private static final Option ARG_DIV = new Option("d", "division", false, "division to number together"); private static final Option ARG_MIN = new Option(null, "minus", false, "after result do minus operation"); private static final Option ARG_DO = new Option(null, "doit", true, " result do minus"); public static void main(String[] args) { CommandLineParser clp = new DefaultParser(); //crete a list of option Options options = new Options(); options.addOption(ARG_ADD); options.addOption(AGE_SUB); options.addOption(ARG_MUL); options.addOption(ARG_DIV); options.addOption(ARG_MIN); options.addOption(ARG_DO); int a=0,b=0; try { //change it to input, args is the list CommandLine cl = clp.parse(options, args); if(cl.getArgList().size()<2){ printHelp(options); //not a valid input System.exit(-1); } a=Integer.parseInt(cl.getArgList().get(0)); b=Integer.parseInt(cl.getArgList().get(1)); //here is command line we can work with if (cl.hasOption(ARG_ADD.getLongOpt())) { System.out.println(a+b); } else if (cl.hasOption(AGE_SUB.getLongOpt())) { System.out.println(a-b); } else if (cl.hasOption(ARG_MUL.getLongOpt())) { System.out.println(a*b); } else if (cl.hasOption(ARG_DIV.getLongOpt())) { System.out.println(a / b); } else { //print command line if we current don't have this command line printHelp(options); } if (cl.hasOption(ARG_MIN.getLongOpt())) { String val=cl.getOptionValue(ARG_MIN.getLongOpt()); int total=a-(Integer.parseInt(val)); System.out.println(total); } if (cl.hasOption(ARG_DO.getLongOpt())) { System.out.println("dooooooo!"); } } catch (ParseException e) { e.printStackTrace(); } } private static void printHelp(Options options){ HelpFormatter formatter=new HelpFormatter(); PrintWriter pw=new PrintWriter(System.out); pw.println("MathApp "+Math.class.getPackage().getImplementationVersion()); pw.println(); formatter.printUsage(pw,100,"java -jar MathAPP.jar [options] input1 input2"); formatter.printOptions(pw,100,options,2,5); pw.close(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="Number guessing game" /> <meta name="keywords" content="mths, ics2o" /> <meta name="author" content="Brayden Blank" /> <meta name="theme-color" content="#FFFFFF" /> <title>Number Guessing Game</title> <link rel="canonical" href="https://brayden-blank.github.io/ICS2O-Unit-5-01-HTML/" /> <link rel="manifest" href="/ICS2O-Unit-5-01-HTML/manifest.webmanifest" /> <link rel="stylesheet" href="./css/styles.css" /> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" media="none" onload="if(media!='all')media='all'"><noscript><link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"></noscript> <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.blue_grey-yellow.min.css" media="none" onload="if(media!='all')media='all'"><noscript><link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.blue_grey-yellow.min.css" /> </noscript> <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png" /> </head> <title>Number Guessing Game</title> <body> <script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script> <script src="./js/script.js"></script> <div class="mdl-layout mdl-js-layout mdl-layout--fixed-header"> <header class="mdl-layout__header"> <div class="mdl-layout__header-row"> <span class="mdl-layout-title">Number Guessing Game!</span> </div> </header> <main class="mdl-layout__content"> <p> Input Your Guess: </p> <div id="slider-value"> Slider's Value: ? </div> <!-- Slider --> <label> <input id = "slider" class="mdl-slider mdl-js-slider" type="range" min="1" max="6" value="2" tabindex="0" onchange = "updateSliderValue(this.value)"> </label> <!-- Raised button with ripple --> <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" onclick="guessClicked()" > Input Your Guess! </button> <br> <br> <br> <div id="user-info"> <div id="guess-result"></div> </div> </main> </div> </body> </html>
import { Routes, Route } from "react-router-dom"; import Navbar from "./routes/navbar/navbar.component"; import Home from "./routes/home/home.component"; import { Checkout } from "./routes/checkout/checkout.component"; import { useDispatch } from "react-redux"; import {GlobalStyle} from "./global.styles"; import Shop from "./routes/shop/shop.component"; import Authentication from "./routes/authentication/authentication.component"; import { useEffect } from "react"; import { checkUserSession } from "./store/user/user.action"; const App = () => { const dispatch = useDispatch(); useEffect(() => { dispatch(checkUserSession()); }, []) return ( <> <GlobalStyle /> <Routes> <Route path='/' element={<Navbar />}> <Route index element={<Home />} /> <Route path='shop/*' element={<Shop />} /> <Route path='auth' element={<Authentication />} /> <Route path='checkout' element={<Checkout />} /> </Route> </Routes> </> ); }; export default App;
// This file is part of the materials accompanying the book // "The Elements of Computing Systems" by Nisan and Schocken, // MIT Press. Book site: www.idc.ac.il/tecs // File name: projects/03/b/RAM512.hdl /** * Memory of 512 registers, each 16 bit-wide. Out holds the value * stored at the memory location specified by address. If load==1, then * the in value is loaded into the memory location specified by address * (the loaded value will be emitted to out from the next time step onward). */ CHIP RAM512 { IN in[16], load, address[9]; OUT out[16]; PARTS: // Put your code here: DMux8Way (in=load, sel=address[6..8], a=aa, b=ab, c=ac, d=ad, e=ae, f=af, g=ag, h=ah); RAM64 (in=in, load=aa, address=address[0..5], out=oa); RAM64 (in=in, load=ab, address=address[0..5], out=ob); RAM64 (in=in, load=ac, address=address[0..5], out=oc); RAM64 (in=in, load=ad, address=address[0..5], out=od); RAM64 (in=in, load=ae, address=address[0..5], out=oe); RAM64 (in=in, load=af, address=address[0..5], out=of); RAM64 (in=in, load=ag, address=address[0..5], out=og); RAM64 (in=in, load=ah, address=address[0..5], out=oh); Mux8Way16 (a=oa, b=ob, c=oc, d=od, e=oe, f=of, g=og, h=oh, sel=address[6..8], out=out); }
import React from "react"; import Slider from "react-slick"; import NewsCard from "./NewsCard"; import { useDispatch, useSelector } from "react-redux"; import { fetchBlog, getAllBlogs, getStatus } from "../features/blogSlice"; import { useEffect } from "react"; import { useTranslation } from "react-i18next"; import LoadingBox from "./LoadingBox"; const News = () => { const { t, i18n } = useTranslation(); const dispatch = useDispatch(); const blogs = useSelector(getAllBlogs); const status = useSelector(getStatus); useEffect(() => { dispatch(fetchBlog({ search: "", pageNumber: 1 })); }, [dispatch]); if (status === "loading") return <LoadingBox />; var settings = { dots: false, infinite: true, speed: 500, cssEase: "ease-in-out", autoplay: true, autoplaySpeed: 3000, slidesToShow: blogs.length < 3 ? blogs.length : 3, slidesToScroll: 1, initialSlide: 1, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 2, slidesToScroll: 1, infinite: true, dots: false, }, }, { breakpoint: 600, settings: { slidesToShow: 1, slidesToScroll: 1, initialSlide: 2, }, }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1, }, }, ], }; return ( <div className="slider-wrapper"> <Slider {...settings}> {blogs && blogs.map((blog, index) => ( <div style={{ height: "100%" }} key={index}> <NewsCard blog={blog} /> </div> ))} </Slider> </div> ); }; export default News;
' very simple TEXTWINDOW Calculator ' program by YLed ' February 11th 2017 ' Small Basic February Challenge of the Month proposed by LitDev ' program no: start: TextWindow.Clear() TextWindow.ForegroundColor="cyan" TextWindow.WriteLine("Addition Type (+) " + "Substraction (-) "+"Multiplication (*) "+"Division (/)") type = TextWindow.Read() If type = "+" Then addition() Elseif type = "-" then substraction() Elseif type = "/" then division() Elseif type = "*" then multiplication() EndIf Sub addition TextWindow.ForegroundColor="yellow" TextWindow.WriteLine(" The individual numbers being combined are called addends, and the total is called the sum") TextWindow.WriteLine("") TextWindow.ForegroundColor="magenta" TextWindow.WriteLine(" Enter the addend ") a1= TextWindow.ReadNumber() TextWindow.WriteLine(" Enter the addend ") a2= TextWindow.ReadNumber() Sum=(a1+a2) TextWindow.ForegroundColor="white" TextWindow.WriteLine("Sum is : "+sum) EndSub Sub substraction TextWindow.ForegroundColor="yellow" TextWindow.WriteLine("Subtraction is the operation of taking the difference (d=x-y) of two numbers x and y") TextWindow.WriteLine(" Here, x is called the minuend, y is called the subtrahend") TextWindow.WriteLine("") TextWindow.ForegroundColor="magenta" TextWindow.WriteLine(" Enter the minuend ") mn= TextWindow.ReadNumber() TextWindow.WriteLine(" Enter the subtrahend ") sb= TextWindow.ReadNumber() difference=(mn-sb) TextWindow.ForegroundColor="white" TextWindow.WriteLine("Difference is : "+difference) EndSub Sub division TextWindow.ForegroundColor="yellow" TextWindow.WriteLine("Taking the ratio of x/y two numbers x and y, also written x รท y") textwindow.writeline("Here, x is called the dividend, y is called the divisor and x/y is called a quotient") TextWindow.WriteLine("") TextWindow.ForegroundColor="magenta" TextWindow.WriteLine(" Enter the dividend") dvd= TextWindow.ReadNumber() retry: TextWindow.WriteLine(" Enter the divisor") dvr= TextWindow.ReadNumber() if dvr=0 then textwindow.writeline (" division y zero not allowed, try again !") For t = 1 To 4 Sound.PlayClickandwait() Program.Delay(20) endfor Goto retry endif Quotient=(dvd/dvr) TextWindow.ForegroundColor="white" TextWindow.WriteLine("Quotient is : "+quotient) EndSub Sub multiplication TextWindow.ForegroundColor="yellow" TextWindow.WriteLine("Multiplication is the process of calculating the result when a number A is taken B times") TextWindow.WriteLine(" A and B is called a factor The result of a multiplication is called the product ") TextWindow.WriteLine("") TextWindow.ForegroundColor="magenta" TextWindow.WriteLine(" Enter Factor 1 ") f1= TextWindow.ReadNumber() TextWindow.WriteLine(" Enter Factor 2 ") f2= TextWindow.ReadNumber() product=(f1*f2) TextWindow.ForegroundColor="white" TextWindow.WriteLine("Product is : "+product) EndSub Program.Delay(3000) Goto start
<!DOCTYPE html> <html> <head> <Style> .bottom-right{ position: fixed; bottom: 20px; right: 20px; background-color: black; color: white; } .right-sidebar{ position: fixed; top: 0; bottom: 0; right: 0; width: 100px; background-color: green; color: antiquewhite; } .all-black{ position: fixed; top: 0; bottom: 0; right: 0; left: 0; background-color: black; color: blue; } .modal-overlay{ position: fixed; top: 0; bottom: 0; right: 0; left: 0; background-color: rgba(0, 0, 0, 0.8); display: flex; align-items: center; justify-content: center; } .modal-box{ background-color: white; height: 75px; width: 250px; padding: 20px; font-family: Arial, Helvetica, sans-serif; border-radius: 5px; } .modal-title{ font-size: 20px; font-weight: 700; margin-bottom: 7px; margin-top: 0; } .modal-description{ font-size: 14px; margin-top: 0px; } .modal-button{ border-radius: 3px; border: 1px solid rgba(128, 128, 128, 0.421); } </Style> </head> <body style="height: 3000px;"> <!-- <div class="bottom-right">bottom-right</div> --> <div class="right-sidebar">right sidebar</div> <!-- <div class="all-black">all black</div> --> <div class="modal-overlay"> <div class="modal-box"> <p class="modal-title"> Modal Title</p> <p class="modal-description">This is a modal</p> <button class="modal-button">Close</button> </div> </div> </body> </html>
import { useState } from 'react'; import { useMedia } from 'react-use'; import { useTranslation } from 'react-i18next'; import { Logo } from 'components/Logo'; import { Social } from 'components/Social'; import { Phone } from 'components/Phone'; import { Footer, Container, Wrapper, WrapLeft, WrapRight, Menu, Link, QrCode, } from './FooterPage.styled'; import { DialogModal } from 'components/DialogModal'; const items = [ { href: '/', label: 'footer.navigation.link1', }, { href: '#portfolio', label: 'footer.navigation.link2', }, { href: '#price', label: 'footer.navigation.link3', }, { href: '#contacts', label: 'footer.navigation.link4', }, ]; export const FooterPage = () => { const isDesktop = useMedia('(min-width: 1230px)'); const [isOpened, setIsOpened] = useState(false); const { t } = useTranslation(); const toggleModal = () => setIsOpened(isShow => !isShow); return ( <Footer id="contacts"> <Container> <Wrapper> <WrapLeft> <Logo /> <Menu> {items.map(({ href, label }) => ( <li key={label}> <Link href={href}>{t(`${label}`)}</Link> </li> ))} </Menu> </WrapLeft> <WrapRight> <Social /> <Phone /> {isDesktop && ( <> <QrCode type="button" onClick={toggleModal} /> <DialogModal onToggle={toggleModal} isOpened={isOpened} /> </> )} </WrapRight> </Wrapper> </Container> </Footer> ); };
package CollectionsClassMethod; import java.util.*; public class CollectionsExample { public static void main(String[] args) { /*addAll()*/ List<String> list = new ArrayList<String>(); list.add("Rahul"); list.add("Karthik"); Collections.addAll(list, "Rahul", "OM", "Prem"); System.out.println("Collection Value: "+list); /*binarySearch()*/ int index = Collections.binarySearch(list, "Karthik"); System.out.println("index available at position: "+index); index = Collections.binarySearch(list, "Rahul", Collections.reverseOrder()); System.out.println("Index available at position: "+index); /*SortedMap()*/ SortedMap<String, Integer> smap = new TreeMap<String, Integer>(); smap.put("JavaTpoint", 1100); smap.put("Hindi100", 500); smap.put("SSSIT", 1300); smap.put("ABCD", 1200); System.out.println("Type safe view of the Sorted Map is: "+Collections.checkedSortedMap(smap,String.class,Integer.class)); /*SortedSet()*/ TreeSet<Integer> set = new TreeSet<>(); set.add(1100); set.add(100); set.add(500); set.add(200); System.out.println("Type safe view of the Sorted Set is: "+Collections.checkedSortedSet(set,Integer.class)); /*copy()*/ List<String> srclist = new ArrayList<String>(5); List<String> destlist = new ArrayList<String>(10); srclist.add("Java Tutorial"); srclist.add("is best on"); srclist.add("JavaTpoint"); destlist.add("JavaTpoint"); destlist.add("is older than"); destlist.add("SSSIT"); Collections.copy(destlist, srclist); System.out.println("Elements of source list: "+srclist); System.out.println("Elements of destination list: "+destlist); /*disjoint()*/ List<String> list1 = new ArrayList<String>(5); List<String> list2 = new ArrayList<String>(10); list1.add("Java"); list1.add("PHP"); list1.add("JavaScript"); list2.add("C++"); list2.add("C"); list2.add("C#"); //It returns true if no elements are common. boolean iscommon = Collections.disjoint(list1, list2 ); System.out.println("Output: "+iscommon); List<Integer> list3 = Arrays.asList(10, 20, 30, 40); List<Integer> list4 = Arrays.asList(10, 20, 30, 4, 5, 6); boolean b = Collections.disjoint(list3, list4); System.out.println("Output: "+b); /*fill()*/ Collections.fill(list,"JavaTpoint"); System.out.println("List elements after Replacements: "+list); /*frequency()*/ List<String> arrlist = new ArrayList<String>(); arrlist.add("Java"); arrlist.add("COBOL"); arrlist.add("Java"); arrlist.add("C++"); arrlist.add("Java"); System.out.println("Frequency of the Word: "+Collections.frequency(arrlist,"Java")); for (String i : arrlist) { System.out.println(i + ": " + Collections.frequency(arrlist, i)); } /*MAX(),MIN()*/ List<String> lis = new ArrayList<String>(); lis.add("A"); lis.add("B"); lis.add("E"); lis.add("C"); lis.add("S"); System.out.println("Max val: " + Collections.max(lis,null)); System.out.println("maximum element :"+Collections.max(lis)); System.out.println("Mininum character is: " + Collections.min(lis,null)); System.out.println("maximum element :"+Collections.min(lis)); } }
import React, { useRef, useState, useEffect } from "react"; import { useInView } from "framer-motion"; import { TestimonialsCard } from "../Components"; import { Swiper, SwiperSlide } from "swiper/react"; import "swiper/css"; import Image from "next/image"; import testimonialsImage1 from "../assets/images/Testimonials/testimonial-1-1.png"; import testimonialsImage2 from "../assets/images/Testimonials/testimonial-1-2.png"; import testimonialsImage3 from "../assets/images/Testimonials/testimonial-1-3.png"; import testimonialsImage4 from "../assets/images/Testimonials/testimonial-1-4.png"; import testimonialsImage5 from "../assets/images/Testimonials/testimonial-1-5.png"; import testimonialsImage6 from "../assets/images/Testimonials/testimonial-1-6.png"; const TESTIMONIALS_DATA = [ [ { image: testimonialsImage1, text: "Saya ingin mengambil kesempatan ini untuk berterima kasih kepada SA Places atas layanan hebat yang diberikan kepada kami dan khususnya Estelle. Anda memberi saya tempat terbaik hanya dalam beberapa saat setelah saya berbicara dengan Anda.", username: "@hello.mimmie", name: "Minnie Horn", }, { image: testimonialsImage2, text: "Terima kasih banyak atas layanan yang baik dan efisien. Saya sudah dan pasti akan terus merekomendasikan layanan Anda kepada orang lain di masa mendatang.", username: "@merryn.manley", name: "Merryn Manley", }, ], [ { image: testimonialsImage3, text: "Saya hanya ingin memuji Estelle Pestana. Dia sangat profesional dan berusaha keras untuk membantu saya. Kesabarannya terhadap saya saat saya terus mengubah rencana saya patut dipuji. Layanannya menegaskan kembali mengapa saya selalu memilih memesan melalui agen daripada langsung. Terima kasih", username: "@hi.veona", name: "Veona Watson", }, { image: testimonialsImage4, text: "Saya jarang mengalami bantuan dan dukungan yang efisien seperti dari Anda! Terima kasih banyak. Kami akan melakukan semua pemesanan selama beberapa hari ke depan dan saya akan kembali kepada Anda dengan hasil akhirnya", username: "@hey.nku", name: "Paseka Nku", }, ], [ { image: testimonialsImage5, text: "Terima kasih atas semua bantuan Anda. Layanan Anda sangat baik dan sangat CEPAT", username: "@cherice.me", name: "Cherice Justin", }, { image: testimonialsImage6, text: "Untuk perjalanan kami baru-baru ini ke SA, saya memesan beberapa akomodasi melalui SA Places. Saya hanya ingin memberi tahu Anda bahwa semuanya berjalan dengan sempurna dengan semua pemesanan dan juga pemesanan Anda sangat cepat dan profesional. Saya harap saya memiliki kesempatan untuk mengunjungi kembali Afrika Selatan segera, saya akan melakukan pemesanan dengan perusahaan Anda lagi. Saya juga akan merekomendasikan", username: "@myself.thais", name: "Thais Carballal", }, ], [ { image: testimonialsImage1, text: "Saya ingin mengambil kesempatan ini untuk berterima kasih kepada SA Places atas layanan hebat yang diberikan kepada kami dan khususnya Estelle. Anda memberi saya tempat terbaik hanya dalam beberapa saat setelah saya berbicara dengan Anda.", username: "@hello.mimmie", name: "Minnie Horn", }, { image: testimonialsImage2, text: "Terima kasih banyak atas layanan yang baik dan efisien. Saya sudah dan pasti akan terus merekomendasikan layanan Anda kepada orang lain di masa mendatang.", username: "@merryn.manley", name: "Merryn Manley", }, ], [ { image: testimonialsImage3, text: "Saya hanya ingin memuji Estelle Pestana. Dia sangat profesional dan berusaha keras untuk membantu saya. Kesabarannya terhadap saya saat saya terus mengubah rencana saya patut dipuji. Layanannya menegaskan kembali mengapa saya selalu memilih memesan melalui agen daripada langsung. Terima kasih", username: "@hi.veona", name: "Veona Watson", }, { image: testimonialsImage4, text: "Saya jarang mengalami bantuan dan dukungan yang efisien seperti dari Anda! Terima kasih banyak. Kami akan melakukan semua pemesanan selama beberapa hari ke depan dan saya akan kembali kepada Anda dengan hasil akhirnya", username: "@hey.nku", name: "Paseka Nku", }, ], [ { image: testimonialsImage5, text: " Anda untuk semua bantuan Anda. Layanan Anda sangat baik dan sangat CEPATTerima kasih.", username: "@cherice.me", name: "Cherice Justin", }, { image: testimonialsImage6, text: "Untuk perjalanan kami baru-baru ini ke SA, saya memesan beberapa akomodasi melalui SA Places. Saya hanya ingin memberi tahu Anda bahwa semuanya berjalan dengan sempurna dengan semua pemesanan dan juga pemesanan Anda sangat cepat dan profesional. Saya harap saya memiliki kesempatan untuk mengunjungi kembali Afrika Selatan segera, saya akan melakukan pemesanan dengan perusahaan Anda lagi. Saya juga akan merekomendasikan", username: "@myself.thais", name: "Thais Carballal", }, ], ]; const Testimonials = () => { const ref = useRef(null); const isInView = useInView(ref); const [domLoaded, setDomLoaded] = useState(false); useEffect(() => { setDomLoaded(true); }, []); const testimonialCarousel = { slidesPerView: 1, spaceBetween: 20, loop: true, speed: 1000, centeredSlides: true, autoHeight: true, autoplay: { waitForTransition: false, delay: 0, }, breakpoints: { 640: { slidesPerView: 2, spaceBetween: 20, }, 768: { slidesPerView: 2, spaceBetween: 20, }, 1024: { slidesPerView: 3, spaceBetween: 20, }, 1200: { slidesPerView: 4, spaceBetween: 20, }, }, }; return ( <section id="testimonials" className="w-screen h-auto"> <div className="bg-[#F4F4F6] py-24" ref={ref}> {/* Title */} <div className="flex text-center flex-col gap-5"> <p className="text-text-blue-small font-semibold text-xl md:text-xl font-dm"> Customer Testimonial </p> <h3 className="font-bold font-arvo text-xl md:text-3xl text-big-titles"> Apa pendapat client customers </h3> </div> {/* Content */} {domLoaded && ( <div className="pt-16 cursor-pointer"> <Swiper {...testimonialCarousel} style={{ transform: isInView ? "none" : "translateX(-500px)", opacity: isInView ? 1 : 0, transition: "all 0.9s cubic-bezier(0.17, 0.55, 0.55, 1) 0.5s", }} > {TESTIMONIALS_DATA.map((item, index) => ( <SwiperSlide key={index}> {item.map(({ image, text, name, username }, _index) => ( <TestimonialsCard key={_index} image={image} text={text} name={name} username={username} /> ))} </SwiperSlide> ))} </Swiper> </div> )} </div> </section> ); }; export default Testimonials;
import { CircularProgress, Container, Typography } from '@mui/material'; import { ApolloError } from 'apollo-client'; import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import AuthForm from '@/components/AuthForm'; import FormField from '@/components/AuthFormField'; import { ErrorHandler } from '@/components/ErrorHandler'; import Navbar from '@/components/Navbar'; import RegisterFormik from '@/components/RegisterFormik'; import SendButton from '@/components/SendButton'; import { useRegisterMutation } from '@/generated/graphql'; import { initialValues, registerFields, registerSchema } from '@/utils/RegisterUtils'; const Register: React.FC = () => { const [register, { loading, error }] = useRegisterMutation(); const [errorState, setError] = useState<Error | ApolloError | undefined>(error); return ( <> <Navbar /> <Container sx={{ display: 'flex', justifyContent: 'center', marginTop: '40px', width: '100px', }} > <RegisterFormik registerHook={register} setError={setError}> <AuthForm title="Register"> {registerFields.map((field) => { return ( <FormField key={field.name} name={field.name} type={field.type} placeholder={field.placeholder} label={field.label} validation={field.validation} /> ); })} {loading && <CircularProgress />} {errorState && <ErrorHandler error={errorState} />} <SendButton initialValues={initialValues} schema={registerSchema}> Register </SendButton> <Typography> Already have an account? <Link to="/login">Log in</Link> </Typography> </AuthForm> </RegisterFormik> </Container> </> ); }; export default Register;
from reporting import construct_forecasts, convert_dict_to_json_ready import pandas as pd import numpy as np import pytest def generate_dummy_forecasts(dataset, h, multiplication_factor, as_frame=False, add_nan=False): last_index = dataset.index[-1] last_value = dataset.iloc[-1] # Generate the date range for the new series new_index = pd.date_range(start=last_index + pd.DateOffset(months=1), periods=h, freq='MS') # Calculate the values for each index based on the last value new_values = (new_index.year + new_index.month + new_index.day) * last_value * multiplication_factor new_values = new_values.tolist() if add_nan: new_values[0] = np.nan # Create the new series dummy_series = pd.Series(new_values, index=new_index) if as_frame: dummy_series = pd.DataFrame(dummy_series, columns=['Value']) return dummy_series def test_construct_forecasts(): # Construct dummy data, fake models and define test dates dataset = pd.Series([1, 2, 3], index=pd.date_range(start='2019-01-01', periods=3, freq='MS')) models = {'test(1)': lambda x, y: generate_dummy_forecasts(x, y, 1), 'test(2)': lambda x, y: generate_dummy_forecasts(x, y, 2)} test_dates = dataset.index[-2::] first_indices = pd.date_range(start='2019-02-01', periods=12, freq='MS') second_indices = pd.date_range(start='2019-03-01', periods=12, freq='MS') # Expected start value for model 1: sum(date) * last value * multiplication factor expected_model_1_1 = pd.Series([(idx.year + idx.month + idx.day) * 1 * 1 for idx in first_indices], index=first_indices) expected_model_1_2 = pd.Series([(idx.year + idx.month + idx.day) * 2 * 1 for idx in second_indices], index=second_indices) # Expected start value for model 2: sum(date) * last value * multiplication factor expected_model_2_1 = pd.Series([(idx.year + idx.month + idx.day) * 1 * 2 for idx in first_indices], index=first_indices) expected_model_2_2 = pd.Series([(idx.year + idx.month + idx.day) * 2 * 2 for idx in second_indices], index=second_indices) # Construct the expected results dictionary expected_result = {} expected_result['test(1)'] = {pd.to_datetime('2019-02-01'): expected_model_1_1, pd.to_datetime('2019-03-01'): expected_model_1_2} expected_result['test(2)'] = {pd.to_datetime('2019-02-01'): expected_model_2_1, pd.to_datetime('2019-03-01'): expected_model_2_2} # Define the expected and actual JSON expected_json = convert_dict_to_json_ready(expected_result) actual_json = convert_dict_to_json_ready(construct_forecasts(dataset, models, test_dates, save_path=None)) # Check that the proper sets of forecasts are generated assert expected_json.keys() == actual_json.keys() # Check that the proper months are in the sets of forecasts for key in expected_json.keys(): assert expected_json[key].keys() == actual_json[key].keys() # Check that the proper forecasts are generated for key in expected_json.keys(): assert expected_json[key] == actual_json[key] # Check that the proper error is raised when the model outputs a DataFrame def test_non_series_error(): # Construct dummy data, fake models and define test dates dataset = pd.Series([1, 2, 3], index=pd.date_range(start='2019-01-01', periods=3, freq='MS')) models = {'test(1)': lambda x, y: generate_dummy_forecasts(x, y, 1, as_frame=True), 'test(2)': lambda x, y: generate_dummy_forecasts(x, y, 2)} test_dates = dataset.index[-2::] with pytest.raises(ValueError): construct_forecasts(dataset, models, test_dates, save_path=None)
# (c) 2015-2022 Acellera Ltd http://www.acellera.com # All Rights Reserved # Distributed under HTMD Software License Agreement # No redistribution in whole or part # from glob import glob from os import path, makedirs import numpy as np from htmd.adaptive.adaptive import AdaptiveBase from htmd.simlist import simlist, simfilter from htmd.model import Model, macroAccumulate from protocolinterface import val from htmd.projections.tica import TICA from htmd.projections.metric import Metric import logging logger = logging.getLogger(__name__) class AdaptiveMD(AdaptiveBase): """Adaptive class which uses a Markov state model for respawning AdaptiveMD uses Markov state models to choose respawning poses for the next epochs. In more detail, it projects all currently retrieved simulations according to the specified projection, clusters those and then builds a Markov model using the discretized trajectories. From the Markov model it then chooses conformations from the various states based on the chosen criteria which will be used for starting new simulations. Parameters ---------- app : :class:`SimQueue <jobqueues.simqueue.SimQueue>` object, default=None A SimQueue class object used to retrieve and submit simulations project : str, default='adaptive' The name of the project nmin : int, default=0 Minimum number of running simulations nmax : int, default=1 Maximum number of running simulations nepochs : int, default=1000 Stop adaptive once we have reached this number of epochs nframes : int, default=0 Stop adaptive once we have simulated this number of aggregate simulation frames. inputpath : str, default='input' The directory used to store input folders generatorspath : str, default='generators' The directory containing the generators dryrun : boolean, default=False A dry run means that the adaptive will retrieve and generate a new epoch but not submit the simulations updateperiod : float, default=0 When set to a value other than 0, the adaptive will run synchronously every `updateperiod` seconds coorname : str, default='input.coor' Name of the file containing the starting coordinates for the new simulations lock : bool, default=False Lock the folder while adaptive is ongoing datapath : str, default='data' The directory in which the completed simulations are stored filter : bool, default=True Enable or disable filtering of trajectories. filtersel : str, default='not water' Atom selection string for filtering. See more `here <http://www.ks.uiuc.edu/Research/vmd/vmd-1.9.2/ug/node89.html>`__ filteredpath : str, default='filtered' The directory in which the filtered simulations will be stored projection : :class:`Projection <moleculekit.projections.projection.Projection>` object, default=None A Projection class object or a list of objects which will be used to project the simulation data before constructing a Markov model truncation : str, default=None Method for truncating the prob distribution (None, 'cumsum', 'statecut' statetype : ('micro', 'cluster', 'macro'), str, default='micro' What states (cluster, micro, macro) to use for calculations. macronum : int, default=8 The number of macrostates to produce skip : int, default=1 Allows skipping of simulation frames to reduce data. i.e. skip=3 will only keep every third frame lag : int, default=1 The lagtime used to create the Markov model. The units are in frames. clustmethod : :class:`ClusterMixin <sklearn.base.ClusterMixin>` class, default=<class 'htmd.clustering.kcenters.KCenter'> Clustering algorithm used to cluster the contacts or distances method : str, default='1/Mc' Criteria used for choosing from which state to respawn from ticalag : int, default=20 Lagtime to use for TICA in frames. When using `skip` remember to change this accordinly. ticadim : int, default=3 Number of TICA dimensions to use. When set to 0 it disables TICA contactsym : str, default=None Contact symmetry save : bool, default=False Save the model generated Example ------- >>> adapt = AdaptiveMD() >>> adapt.nmin = 2 >>> adapt.nmax = 3 >>> adapt.nepochs = 2 >>> adapt.ticadim = 3 >>> adapt.projection = [MetricDistance('name CA', 'resname MOL', periodic='selections'), MetricDihedral()] >>> adapt.generatorspath = htmd.home()+'/data/dhfr' >>> adapt.app = LocalGPUQueue() >>> adapt.run() """ def __init__(self): from sklearn.base import ClusterMixin from htmd.clustering.kcenters import KCenter from moleculekit.projections.projection import Projection super().__init__() self._arg( "datapath", "str", "The directory in which the completed simulations are stored", "data", val.String(), ) self._arg( "filter", "bool", "Enable or disable filtering of trajectories.", True, val.Boolean(), ) self._arg( "filtersel", "str", "Filtering atom selection", "not water", val.String() ) self._arg( "filteredpath", "str", "The directory in which the filtered simulations will be stored", "filtered", val.String(), ) self._arg( "projection", ":class:`Projection <moleculekit.projections.projection.Projection>` object", "A Projection class object or a list of objects which will be used to project the simulation " "data before constructing a Markov model", None, val.Object(Projection), nargs="+", ) self._arg( "truncation", "str", "Method for truncating the prob distribution (None, 'cumsum', 'statecut'", None, val.String(), ) self._arg( "statetype", "str", "What states (cluster, micro, macro) to use for calculations.", "micro", val.String(), valid_values=("micro", "cluster", "macro"), ) self._arg( "macronum", "int", "The number of macrostates to produce", 8, val.Number(int, "POS"), ) self._arg( "skip", "int", "Allows skipping of simulation frames to reduce data. i.e. skip=3 will only keep every third frame", 1, val.Number(int, "POS"), ) self._arg( "lag", "int", "The lagtime used to create the Markov model", 1, val.Number(int, "POS"), ) self._arg( "clustmethod", ":class:`ClusterMixin <sklearn.base.ClusterMixin>` class", "Clustering algorithm used to cluster the contacts or distances", KCenter, val.Class(ClusterMixin), ) self._arg( "method", "str", "Criteria used for choosing from which state to respawn from", "1/Mc", val.String(), ) self._arg( "ticalag", "int", "Lagtime to use for TICA in frames. When using `skip` remember to change this accordinly.", 20, val.Number(int, "0POS"), ) self._arg( "ticadim", "int", "Number of TICA dimensions to use. When set to 0 it disables TICA", 3, val.Number(int, "0POS"), ) self._arg("contactsym", "str", "Contact symmetry", None, val.String()) self._arg("save", "bool", "Save the model generated", False, val.Boolean()) def _algorithm(self): data = self._getData(self._getSimlist()) if not self._checkNFrames(data): return False self._createMSM(data) N = self.nmax - self._running reward = self._criteria(self._model, self.method) reward = self._truncate(reward, N) relFrames, _, _ = self._getSpawnFrames(reward, self._model, self._model.data, N) self._writeInputs(self._model.data.rel2sim(np.concatenate(relFrames))) return True def _checkNFrames(self, data): if self.nframes != 0 and data.numFrames >= self.nframes: logger.info("Reached maximum number of frames. Stopping adaptive.") return False return True def _getSimlist(self): logger.info("Postprocessing new data") sims = simlist( glob(path.join(self.datapath, "*", "")), glob(path.join(self.inputpath, "*", "")), glob(path.join(self.inputpath, "*", "")), ) if self.filter: sims = simfilter(sims, self.filteredpath, filtersel=self.filtersel) return sims def _getData(self, sims): metr = Metric(sims, skip=self.skip) metr.set(self.projection) # if self.contactsym is not None: # contactSymmetry(data, self.contactsym) if self.ticadim > 0: # tica = TICA(metr, int(max(2, np.ceil(self.ticalag)))) # gianni: without project it was tooooo slow data = metr.project() data.dropTraj() # Drop before TICA to avoid broken trajectories # 1 < ticalag < (trajLen / 2) ticalag = int( np.ceil(max(2, min(np.min(data.trajLengths) / 2, self.ticalag))) ) tica = TICA(data, ticalag) datadr = tica.project(self.ticadim) else: datadr = metr.project() datadr.dropTraj() # Preferably we should do this before any projections. Corrupted sims can affect TICA return datadr def _createMSM(self, data): data.cluster(self.clustmethod(n_clusters=self._numClusters(data.numFrames))) self._model = Model(data) self._model.markovModel(self.lag, self._numMacrostates(data)) if self.save: if not path.exists("saveddata"): makedirs("saveddata") self._model.save( path.join("saveddata", f"e{self._getEpoch()}_adapt_model.dat") ) def _getSpawnFrames(self, reward, model, data, N): prob = reward / np.sum(reward) logger.debug(f"Sampling probabilities {prob}") spawncounts = np.random.multinomial(N, prob) logger.debug(f"spawncounts {spawncounts}") stateIdx = np.where(spawncounts > 0)[0] _, relFrames = model.sampleStates( stateIdx, spawncounts[stateIdx], statetype="micro", replacement=True ) logger.debug(f"relFrames {relFrames}") return relFrames, spawncounts, prob def _criteria(self, model, criteria): if criteria == "1/Mc": nMicroPerMacro = macroAccumulate(model, np.ones(model.micronum)) P_I = 1 / macroAccumulate(model, model.data.N[model.cluster_ofmicro]) P_I = P_I / nMicroPerMacro ret = P_I[model.macro_ofmicro] elif criteria == "pi/Mc": nMicroPerMacro = macroAccumulate(model, np.ones(model.micronum)) P_I = 1 / macroAccumulate(model, model.data.N[model.cluster_ofmicro]) P_I = P_I / nMicroPerMacro ret = P_I[model.macro_ofmicro] * model.msm.stationary_distribution return ret def _truncate(self, ranking, N): if self.truncation is not None and self.truncation.lower() != "none": if self.truncation == "cumsum": idx = np.argsort(ranking) idx = idx[::-1] # decreasing sort errs = ranking[idx] H = (N * errs / np.cumsum(errs)) < 1 ranking[idx[H]] = 0 if self.truncation == "statecut": idx = np.argsort(ranking) idx = idx[::-1] # decreasing sort ranking[idx[N:]] = 0 # Set all states ranked > N to zero. return ranking def _numClusters(self, numFrames): """Heuristic that calculates number of clusters from number of frames""" K = int(max(np.round(0.6 * np.log10(numFrames / 1000) * 1000 + 50), 100)) if K > numFrames / 3: # Ugly patch for low-data regimes ... K = int(numFrames / 3) return K def _numMacrostates(self, data): """Heuristic for calculating the number of macrostates for the Markov model""" macronum = self.macronum if data.K < macronum: macronum = np.ceil(data.K / 2) logger.warning( f"Using less macrostates than requested due to lack of microstates. macronum = {macronum}" ) # Calculating how many timescales are above the lag time to limit number of macrostates from deeptime.util.validation import implied_timescales from htmd.model import Model statelist = [traj.cluster for traj in data.trajectories] model = Model._get_model(statelist, self.lag) its_data = implied_timescales(model, n_its=macronum) timesc = its_data._its macronum = min(self.macronum, max(np.sum(timesc > self.lag), 2)) return macronum if __name__ == "__main__": import htmd.home import os import shutil from htmd.util import tempname from moleculekit.projections.metricdistance import MetricDistance tmpdir = tempname() shutil.copytree(htmd.home.home() + "/data/adaptive/", tmpdir) os.chdir(tmpdir) md = AdaptiveMD() # md.dryrun = True md.nmin = 1 md.nmax = 2 md.nepochs = 3 md.ticalag = 2 md.ticadim = 3 md.updateperiod = 5 md.projection = MetricDistance( "protein and name CA", "resname BEN and noh", periodic="selections" ) md.projection = [ MetricDistance( "protein and name CA", "resname BEN and noh", periodic="selections" ), MetricDistance( "protein and name CA", "resname BEN and noh", periodic="selections" ), ]
/** 1- A- Definir una clase para representar triรกngulos. Un triรกngulo se caracteriza por el tamaรฑo de sus 3 lados (double), el color de relleno (String) y el color de lรญnea (String). El triรกngulo debe saber: โ€ข Devolver/modificar el valor de cada uno de sus atributos (mรฉtodos get# y set#) โ€ข Calcular el รกrea y devolverla (mรฉtodo calcularArea) โ€ข Calcular el perรญmetro y devolverlo (mรฉtodo calcularPerimetro) NOTA: Calcular el รกrea con la fรณrmula , donde a,b y c son los lados y . La funciรณn raรญz cuadrada es Math.sqrt(#) */ public class triangulo { // instance variables - replace the example below with your own private double Lado1; private double Lado2; private double Lado3; private String ColorR; private String ColorL; /** * Constructor for objects of class triangulo */ public triangulo(Double unLado1,Double unLado2,Double unLado3,String unColorR,String unColorL){ Lado1 = unLado1; Lado2 = unLado2; Lado3 = unLado3; ColorR = unColorR; ColorL = unColorL; } public triangulo() { } public Double getLado1(){ return Lado1; } public Double getLado2(){ return Lado2; } public Double getLado3(){ return Lado3; } public String getColorR(){ return ColorR; } public String getColorL(){ return ColorR; } public void setLado1(Double unLado1){ Lado1 = unLado1; } public void setLado2(Double unLado2){ Lado2 = unLado2; } public void setLado3(Double unLado3){ Lado3 = unLado3; } public void setColorR(String unColorR){ ColorR = unColorR; } public void setColorL(String unColorL){ ColorL = unColorL; } public Double getPerimetro(){ Double Perimetro = Lado1+Lado2+Lado3; return Perimetro; } public Double getArea(){ Double s=(Lado1+Lado2+Lado3)/2; Double Area = Math.sqrt(s*(s-Lado1)*(s-Lado2)*(s-Lado3)); return Area; } @Override public String toString(){ return ("el lado uno es :"+Lado1 + " el lado dos es: " + Lado2 + " el lado tres es: " + Lado3 + " el colorR es " + ColorR+" el colorL es :"+ColorL); } }
package main import( "log" "net/http" "github.com/gorilla/websocket" ) var clients = make(map[*websocket.Conn]bool) //connected clients var broadcast = make(chan Message) //broadcast channel //configure the upgrader var upgrader = websocket.Upgrader{} //Define our message object type Message struct{ Email string `json:"email"` Username string `json:"username"` Message string `json:"message"` } func main() { //simple file fileserver fs := http.FileServer(http.Dir("./public")) http.Handle("/",fs) http.HandleFunc("/ws",handleConnections) go handleMessages() log.Println("Server running on :8080") err := http.ListenAndServe(":8080",nil) if err!=nil{ log.Fatal("ListenAndServe: ",err) } } func handleConnections(w http.ResponseWriter,r *http.Request){ //upgrade initial Get request to websocket ws,err := upgrader.Upgrade(w,r,nil) if err!=nil{ log.Fatal("Upgrade: ",err) } //close the connection when funcion returns defer ws.Close() //Register new client clients[ws] = true for{ var msg Message err:= ws.ReadJSON(&msg) if err!=nil{ log.Printf("error: %v",err) delete(clients,ws) break } broadcast <-msg } } func handleMessages(){ for{ msg := <-broadcast for client := range clients{ err := client.WriteJSON(msg) if err!=nil{ log.Printf("error: %v",err) client.Close() delete(clients,client) } } } }
""" Tests the unit functions in ch10_snippets.py for calculating bet size. """ import unittest import datetime as dt import numpy as np import pandas as pd from scipy.stats import norm from mlfinlab.bet_sizing.ch10_snippets import get_signal, avg_active_signals, mp_avg_active_signals, discrete_signal from mlfinlab.bet_sizing.ch10_snippets import (bet_size_sigmoid, bet_size_power, bet_size, get_t_pos_sigmoid, get_t_pos_power, get_t_pos, inv_price_sigmoid, inv_price_power, inv_price, limit_price_sigmoid, limit_price_power, limit_price, get_w_sigmoid, get_w_power, get_w) class TestCh10Snippets(unittest.TestCase): """ Tests the following functions in ch10_snippets.py: - get_signal - avg_active_signals - mp_avg_active_signals - discrete_signal """ def setUp(self): """ Sets up the data to be used for the following tests. """ # Unit test setup for get_signal, avg_active_signals, # mp_avg_active_signals, and discrete_signal. # Setup the array of values, length of 6 for testing. prob_arr = np.array([0.711, 0.898, 0.992, 0.595, 0.544, 0.775]) side_arr = np.array([1, 1, -1, 1, -1, 1]) dates = np.array([dt.datetime(2000, 1, 1) + i*dt.timedelta(days=1) for i in range(6)]) shift_list = [0.5, 1, 2, 1.5, 0.8, 0.2] shift_dt = np.array([dt.timedelta(days=d) for d in shift_list]) dates_shifted = dates + shift_dt # Calculate the test statistic and bet size. z_test = (prob_arr - 0.5) / (prob_arr*(1-prob_arr))**0.5 m_signal = side_arr * (2 * norm.cdf(z_test) - 1) m_discrete = np.array([max(-1, min(1, m_i)) for m_i in np.round(m_signal/0.1, 0)*0.1]) # Convert arrays to pd.Series for use as test arguments. self.prob = pd.Series(data=prob_arr, index=dates) self.side = pd.Series(data=side_arr, index=dates) self.t_1 = pd.Series(data=dates_shifted, index=dates) self.bet_size = pd.Series(data=m_signal, index=dates) self.bet_size_d = pd.Series(data=m_discrete, index=dates) # Convert pd.Series to pd.DataFrames for calculating correct results. self.events = pd.concat(objs=[self.t_1, self.prob, self.side], axis=1) self.events = self.events.rename(columns={0: 't1', 1: 'prob', 2: 'side'}) self.events_2 = self.events.copy() self.events_2['signal'] = self.bet_size # Calculation of the average active bets. t_p = set(self.events_2['t1'].to_numpy()) t_p = t_p.union(self.events_2.index.to_numpy()) t_p = list(t_p) t_p.sort() self.t_pnts = t_p.copy() avg_list = [] for t_i in t_p: avg_list.append(self.events_2[(self.events_2.index <= t_i) & (self.events_2.t1 > t_i)]['signal'].mean()) self.avg_active = pd.Series(data=np.array(avg_list), index=t_p).fillna(0) def test_get_signal(self): """ Tests calculating the bet size from probability. """ # Test get_signal when supplying a value to argument 'pred'. test_bet_size_1 = get_signal(prob=self.prob, num_classes=2, pred=self.side) self.assertEqual(self.bet_size.equals(test_bet_size_1), True) # Test get_signal when no value provided for 'pred'. test_bet_size_2 = get_signal(prob=self.prob, num_classes=2) self.assertEqual(self.bet_size.abs().equals(test_bet_size_2), True) def test_avg_active_signals(self): """ Tests the avg_active_signals function. Also implicitly tests the molecular multiprocessing function mp_avg_active_signals. """ test_avg_active = avg_active_signals(self.events_2) self.assertEqual(self.avg_active.equals(test_avg_active), True) def test_mp_avg_active_signals(self): """ An explicit test of the mp_avg_active_signals subroutine. """ test_mp_avg_active = mp_avg_active_signals(self.events_2, self.t_pnts) self.assertEqual(self.avg_active.equals(test_mp_avg_active), True) def test_discrete_signal(self): """ Tests the discrete_signal function. """ test_bet_discrete = discrete_signal(signal0=self.bet_size, step_size=0.1) self.assertEqual(self.bet_size_d.equals(test_bet_discrete), True) # Test cases for functions used in calculating dynamic bet size. class TestBetSize(unittest.TestCase): """ Test case for bet_size, bet_size_sigmoid, and bet_size_power. """ def test_bet_size_sigmoid(self): """ Tests successful execution of 'bet_size_sigmoid'. """ x_div = 15 w_param = 7.5 m_test = x_div / np.sqrt(w_param + x_div*x_div) self.assertAlmostEqual(m_test, bet_size_sigmoid(w_param, x_div), 7) def test_bet_size_power(self): """ Tests successful execution of 'bet_size_power'. """ x_div = 0.4 w_param = 1.5 m_test = np.sign(x_div) * abs(x_div)**w_param self.assertAlmostEqual(m_test, bet_size_power(w_param, x_div), 7) def test_bet_size_power_error(self): """ Tests successful raising of ValueError in 'bet_size_power'. """ self.assertRaises(ValueError, bet_size_power, 2, 1.5) def test_bet_size(self): """ Test excution in all function modes of 'bet_size'. """ x_div_sig = 25 w_param_sig = 3.5 m_test_sig = x_div_sig / np.sqrt(w_param_sig + x_div_sig*x_div_sig) self.assertAlmostEqual(m_test_sig, bet_size(w_param_sig, x_div_sig, 'sigmoid'), 7) x_div_pow = 0.7 w_param_pow = 2.1 m_test_pow = np.sign(x_div_pow) * abs(x_div_pow)**w_param_pow self.assertAlmostEqual(m_test_pow, bet_size(w_param_pow, x_div_pow, 'power'), 7) def test_bet_size_error(self): """ Tests for the KeyError in the event that an invalid function is provided to 'func'. """ self.assertRaises(KeyError, bet_size, 2, 3, 'NotAFunction') class TestGetTPos(unittest.TestCase): """ Test case for get_t_pos, get_t_pos_sigmoid, and get_t_pos_power. """ def test_get_t_pos_sigmoid(self): """ Tests successful execution of 'get_t_pos_sigmoid'. """ f_i, m_p = 34.6, 21.9 x_div = f_i - m_p w_param = 2.5 max_pos = 200 pos_test = int(max_pos*(x_div / np.sqrt(w_param + x_div*x_div))) self.assertAlmostEqual(pos_test, get_t_pos_sigmoid(w_param, f_i, m_p, max_pos), 7) def test_get_t_pos_power(self): """ Tests successful execution of 'get_t_pos_power'. """ f_i, m_p = 34.6, 34.1 x_div = f_i - m_p w_param = 2.1 max_pos = 100 pos_test = int(max_pos*(np.sign(x_div) * abs(x_div)**w_param)) self.assertAlmostEqual(pos_test, get_t_pos_power(w_param, f_i, m_p, max_pos), 7) def test_get_t_pos(self): """ Tests successful execution in 'sigmoid' and 'power' function variants of 'get_t_pos'. """ f_i_sig, m_p_sig = 31.6, 22.9 x_div_sig = f_i_sig - m_p_sig w_param_sig = 2.6 max_pos_sig = 220 pos_test_sig = int(max_pos_sig*(x_div_sig / np.sqrt(w_param_sig + x_div_sig*x_div_sig))) self.assertAlmostEqual(pos_test_sig, get_t_pos(w_param_sig, f_i_sig, m_p_sig, max_pos_sig, 'sigmoid'), 7) f_i_pow, m_p_pow = 34.8, 34.1 x_div_pow = f_i_pow - m_p_pow w_param_pow = 2.9 max_pos_pow = 175 pos_test_pow = int(max_pos_pow*(np.sign(x_div_pow) * abs(x_div_pow)**w_param_pow)) self.assertAlmostEqual(pos_test_pow, get_t_pos(w_param_pow, f_i_pow, m_p_pow, max_pos_pow, 'power'), 7) def test_get_t_pos_error(self): """ Tests for the KeyError in 'get_t_pos' in the case that an invalid value for 'func' is passed. """ self.assertRaises(KeyError, get_t_pos, 1, 2, 1, 5, 'NotAFunction') class TestInvPrice(unittest.TestCase): """ Tests for functions 'inv_price', 'inv_price_sigmoid', and 'inv_price_power'. """ def test_inv_price_sigmoid(self): """ Tests for the successful execution of 'inv_price_sigmoid'. """ f_i_sig = 35.19 w_sig = 9.32 m_sig = 0.72 inv_p_sig = f_i_sig - m_sig * np.sqrt(w_sig/(1-m_sig*m_sig)) self.assertAlmostEqual(inv_p_sig, inv_price_sigmoid(f_i_sig, w_sig, m_sig), 7) if __name__ == '__main__': unittest.main()
import React, { useEffect, useState } from 'react'; import ButtonText from '../../../../components/button/ButtonText'; import InputSelect from '../../../../components/form/InputSelect'; import Panel from '../../../../components/panel/Panel'; import PanelBody from '../../../../components/panel/PanelBody'; import CooperationDetailsAPI from '../../../../api/cooperation/CooperationDetailsAPI'; import { useFormik } from 'formik'; import { CreateCooperationHoomCampaignValidation } from '../Validation'; import axios from 'axios'; import CampaignsAPI from '../../../../api/campaign/CampaignsAPI'; import MeasureAPI from '../../../../api/measure/MeasureAPI'; function HoomCampaignsNew({ cooperationId, toggleShowNew, addResult }) { const [campaigns, setCampaigns] = useState([]); const [measures, setMeasures] = useState([]); const [isLoading, setIsLoading] = useState(true); const formData = { cooperationId: cooperationId, campaignId: '', measureId: '', }; const { values, errors, touched, handleChange, handleSubmit, setFieldValue, handleBlur } = useFormik({ initialValues: formData, validationSchema: CreateCooperationHoomCampaignValidation, onSubmit: values => { processSubmit(values); }, }); useEffect(function() { axios.all([CampaignsAPI.peekCampaigns(), MeasureAPI.peekMeasures()]).then( axios.spread((campaigns, measures) => { setCampaigns(campaigns); setMeasures(measures); setIsLoading(false); }) ); }, []); function processSubmit(values) { // Cleanup value data. Data don't needed for update. // const cleanUpFormFields = [ // 'createdAt', // 'updatedAt', // ]; // for (const item of cleanUpFormFields) { // delete values[item]; // } // // Process to formdata let formData = new FormData(); for (const [key, value] of Object.entries(values)) { formData.append(key, value); } // Send form data CooperationDetailsAPI.createHoomCampaign(formData) .then(payload => { addResult(payload.data.data); toggleShowNew(); }) .catch(error => { alert('Er is iets misgegaan met opslaan. Probeer het nogmaals'); }); } return ( <div> <Panel className={'panel-grey'}> <PanelBody> <div className="row"> <InputSelect label={'Campagne'} size={'col-sm-6'} name={'campaignId'} options={campaigns} value={values.campaignId} onChangeAction={handleChange} required={'required'} error={errors.campaignId && touched.campaignId} errorMessage={errors.campaignId} /> <InputSelect label={'Maatregel specifiek'} size={'col-sm-6'} name={'measureId'} options={measures} value={values.measureId} onChangeAction={handleChange} /> </div> <div className="pull-right btn-group" role="group"> <ButtonText buttonClassName={'btn-default'} buttonText={'Annuleren'} onClickAction={toggleShowNew} /> <ButtonText buttonText={'Opslaan'} onClickAction={handleSubmit} type={'submit'} value={'Submit'} /> </div> </PanelBody> </Panel> </div> ); } export default HoomCampaignsNew;
//jshint esversion:6 require('dotenv').config(); const express = require("express"); const bodyParser = require("body-parser"); const ejs = require ("ejs"); const app = express(); const mongoose = require("mongoose"); const encrypt = require("mongoose-encryption"); console.log(process.env.API_KEY); app.use(express.static("public")); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({extended: true})); mongoose.connect("mongodb://127.0.0.1:27017/userDB", {useNewUrlParser: true}); const userSchema = new mongoose.Schema ({ email: String, password: String }); userSchema.plugin(encrypt, {secret: process.env.SECRET, encryptedFields: ['password'] }); const User = new mongoose.model("User", userSchema); app.get("/", function(req,res){ res.render("home"); }); app.get("/login", function(req,res){ res.render("login"); }); app.get("/register", function(req,res){ res.render("register"); }); app.post("/register", function(req,res){ const newUser = new User({ email: req.body.username, password: req.body.password }); newUser.save().then(() =>{ res.render("secrets"); }).catch(err =>{ res.send(err); }) }); app.post("/login", function(req,res){ const userName = req.body.username; const password = req.body.password; User.findOne({email: userName}).then(foundUser =>{ if(foundUser.password === password){ res.render("secrets") } }).catch(err=>{ res.send(err) }) }); app.listen(3000,function(){ console.log("Server started on port 3000"); });
import React, { FC, useState } from "react"; import background from "../../../assets/stormgatebackground.png"; import BuildOrdersSearchFilters from "../../Collection/BuildOrdersSearchFilters"; import { Games, Roles, stormgateFactionsDisplay, stormgateGameModesDisplay } from "../../../Types&Globals/enums"; import { useDeleteStormgateBuildOrderMutation, useStormgateBuildOrdersQuery } from "../../../Api/Queries/BuildOrderQueries"; import { StormgateBuildOrder } from "../../../Types&Globals/BuildOrders"; import { useNavigate } from "react-router-dom"; import { AppRoutes } from "../../../Types&Globals/Routes"; import NotFound from "../../Errors/RouterError"; import { BuildOrdersSkeleton } from "../../Collection/BuildOrdersSkeleton"; import IntersectionObserverContainer from "../../Collection/IntersectionObserver"; import { VersusDisplay } from "../../Collection/VersusDisplays"; import DeleteModal from "../../Modals/DeleteModal"; import EditDeleteMenu from "../../Collection/EditDeleteMenu"; import { useUserQuery } from "../../../Api/Queries/UserQueries"; export const StormgateBuildOrders: FC = () => { const [searchFilters, setSearchFilters] = useState({ title: "", faction: "", opponentFaction: "", uploadedBy: "", gameMode: "", }); const { buildOrders, isFetching, isError, refetch, hasNextPage, fetchNextPage } = useStormgateBuildOrdersQuery(true, searchFilters); return ( <div className="flex flex-grow" data-testid="stormgate-build-orders" style={{ backgroundImage: `url(${background})`, backgroundSize: "cover", backgroundRepeat: "no-repeat", backgroundPosition: "center", }} > <div className="flex flex-grow flex-col bg-gray-900 bg-opacity-0 text-white p-4" // bg-opacity-50 sets the background opacity to 50% > <BuildOrdersSearchFilters gameFactions={stormgateFactionsDisplay} gameModes={stormgateGameModesDisplay} searchFilters={searchFilters} setSearchFilters={setSearchFilters} /> <StormgateBuildOrderList buildOrders={buildOrders as StormgateBuildOrder[]} isFetching={isFetching} hasNextPage={hasNextPage} fetchNextPage={fetchNextPage} isError={isError} refetch={refetch} /> </div> </div> ); }; type StormgateBuildOrderListProps = { buildOrders: StormgateBuildOrder[]; isFetching: boolean; hasNextPage: boolean; fetchNextPage: () => void; isError: boolean; refetch: () => void; }; export const StormgateBuildOrderList: FC<StormgateBuildOrderListProps> = ({ buildOrders, isFetching, hasNextPage, fetchNextPage, isError, refetch, }) => { const navigate = useNavigate(); const { data: user } = useUserQuery(); const [deleteModalopen, setDeleteModalOpen] = useState(false); const [deleteBuildOrder, setDeleteBuildOrder] = useState<StormgateBuildOrder | null>(null); const { mutateAsync: onConfirmDelete, isError: isDeleteError, isLoading: isDeleteLoading } = useDeleteStormgateBuildOrderMutation(false); const handleBuildOrderClick = (id: string) => { navigate(AppRoutes.StormgateBuildOrder.replace(":id", id)); }; const onDeleteClick = (buildOrder: StormgateBuildOrder) => { setDeleteBuildOrder(buildOrder); setDeleteModalOpen(true); }; const onEditClick = (id: string) => { navigate(AppRoutes.StormgateEdit.replace(":id", id)); }; if ((buildOrders.length === 0 || isError) && !isFetching) return <NotFound />; return ( <div className="flex flex-col space-y-4 text-yellow-200 p-4 font-fantasy w-full" data-testid="stormgate-build-order-list"> {buildOrders.map((buildOrder) => ( <div data-testid={`stormgate-build-order-item-${buildOrder.id}`} onClick={() => handleBuildOrderClick(buildOrder.id)} key={buildOrder.id} className="p-4 border bg-gray-800 hover:bg-green-800 border-gray-700 rounded shadow-lg cursor-pointer transition ease-in duration-200 transform hover:scale-105" > <div className="flex justify-between gap-2 flex-wrap"> <div className="w-4/6"> <h2 className="text-xl font-bold max-w-3xl">{buildOrder.name} </h2> <p className="text-l text-gray-300"> {stormgateFactionsDisplay[buildOrder.faction]} vs {stormgateFactionsDisplay[buildOrder.opponentFaction]} </p> </div> <div className="flex flex-col gap-2"> <EditDeleteMenu onEditClick={() => onEditClick(buildOrder.id)} onDeleteClick={() => { onDeleteClick(buildOrder); }} show={user?.role === Roles.ADMIN || user?.id === buildOrder.userId} /> <VersusDisplay factionNumber={buildOrder.faction} opponentFactionNumber={buildOrder.opponentFaction} imgSize="14" game={Games.Stormgate} /> </div> </div> <p className="text-sm text-gray-400">Created by: {buildOrder.createdBy}</p> </div> ))} {isFetching && <BuildOrdersSkeleton />} {hasNextPage && <IntersectionObserverContainer handleIntersection={fetchNextPage} />} {deleteModalopen && deleteBuildOrder && ( <DeleteModal open={deleteModalopen} onCancel={() => setDeleteModalOpen(false)} onConfirm={async () => { await onConfirmDelete(deleteBuildOrder?.id || ""); if (!isDeleteError) { setDeleteModalOpen(false); refetch(); } }} isError={isDeleteError} isLoading={isDeleteLoading} /> )} </div> ); };
import 'dart:io'; import 'package:dio/dio.dart'; import 'package:seecooker/utils/file_converter.dart'; class NewRecipe { /// ๅฐ้ข late File cover; /// ๆ ‡้ข˜ late String name = ""; /// ็ฎ€ไป‹ late String introduction = ""; /// ๆฏไธ€ๆญฅ็š„ๅ›พ็‰‡ List<File> stepImages = []; /// ๆฏไธ€ๆญฅ็š„ๅ†…ๅฎน List<String> stepContents = []; /// ้…ๆ–™ List<String> ingredientsName = []; List<String> ingredientsAmount = []; NewRecipe(); NewRecipe.all(this.cover, this.name, this.introduction, this.stepImages, this.stepContents); Future<FormData> toFormData() async { List<MultipartFile> s = []; for (int i = 0; i < stepImages.length; i++) { s.add(await FileConverter.file2MultipartFile(stepImages[i])); } FormData formData = FormData.fromMap({ 'name': name, 'introduction': introduction, 'stepContents': stepContents, 'cover': await FileConverter.file2MultipartFile(cover), 'stepImages': s, 'ingredients': ingredientsName, 'amounts': ingredientsAmount }); return formData; } }
var budgetController = (function() { var Expense = function(id, description, value){ this.id = id; this.description = description; this.value = value; this.percentage = -1; }; Expense.prototype.calcPercentage = function(totalIncome) { if (totalIncome > 0) { this.percentage = Math.round((this.value/totalIncome) * 100); } else { this.percentage = -1; } }; Expense.prototype.getPercentage = function() { return this.percentage; } var Income = function(id, description, value){ this.id = id; this.description = description; this.value = value; }; var calculateTotal = function(type) { var sum = 0; data.allItems[type].forEach(function(cur) { sum += cur.value; }); data.totals[type] = sum; localStorage.setItem(`totals[${type}]`, sum); }; var data = { allItems: { exp: localStorage.getItem('exp') ? JSON.parse(localStorage.getItem('exp')) : [], inc: localStorage.getItem('inc') ? JSON.parse(localStorage.getItem('inc')) : [], }, totals:{ exp: localStorage.getItem('totals[exp]') || 0, inc: localStorage.getItem('totals[inc]') || 0, }, budget: localStorage.getItem('budget') || 0, percentage: localStorage.getItem('percentage') || -1 }; return { addItem: function(type, des, val) { var newItem, ID; //Create new ID if (data.allItems[type].length > 0) { ID = data.allItems[type][data.allItems[type].length - 1].id + 1; } else { ID = 0; } //Create new item based on 'inc' or 'exp' type if (type === 'exp') { newItem = new Expense(ID, des, val); } else if (type === 'inc') { newItem = new Income(ID, des, val); } //push data into structure data.allItems[type].push(newItem); localStorage.removeItem(type); localStorage.setItem(type, JSON.stringify(data.allItems[type])); return newItem; }, deleteItem: function(type, id) { var ids, index; ids = data.allItems[type].map(function(current) { return current.id }); index = ids.indexOf(id); if (index !== -1) { data.allItems[type].splice(index, 1); localStorage.setItem(`${type}`, data.allItems[`${type}`]); } }, calculateBudget: function() { //Calculating total income and expenses calculateTotal('exp'); calculateTotal('inc'); //Calculating the budget data.budget = data.totals.inc - data.totals.exp; localStorage.setItem('budget', data.budget); //Calculating the percentage of income that we spent if (data.totals.inc > 0) { data.percentage = Math.round((data.totals.exp/data.totals.inc) * 100); } else { data.percentage = -1; } localStorage.setItem('percentage', data.percentage); }, calculatePercentages: function() { data.allItems.exp.forEach(function(cur) { if (data.totals.inc > 0) { cur.percentage = Math.round((cur.value/data.totals.inc) * 100); } else { cur.percentage = -1; } }); }, getPercentages: function() { var allPerc = data.allItems.exp.map(function(cur){ return cur.percentage; }); return allPerc; }, getBudget: function() { return { allExp: data.allItems.exp , allInc: data.allItems.inc, budget: data.budget, totalInc: data.totals.inc, totalExp: data.totals.exp, percentage: data.percentage } }, testing: function() { console.log(data); } }; })(); var UIController = (function() { var DOMstrings = { inputType: '.add__type', inputDescription: '.add__description', inputValue: '.add__value', inputButton:'.add__btn', incomeContainer: '.income__list', expenseContainer: '.expenses__list', budgetLabel: '.budget__value', incomeLabel: '.budget__income--value', expensesLabel: '.budget__expenses--value', percentageLabel: '.budget__expenses--percentage', container: '.container', expensesPercLabel: '.item__percentage', dateLabel: '.budget__title--month', }; var formatNumber = function(num, type) { var numSplit, int, dec; num = Math.abs(num); num = num.toFixed(2); numSplit = num.split('.'); int = numSplit[0]; dec = numSplit[1]; if (int.length > 3) { int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3); } return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec; }; var nodeListForEach = function(list, callback) { for (var i = 0; i < list.length; i++) { callback(list[i], i); } }; return { getInput: function() { return { type: document.querySelector(DOMstrings.inputType).value, description: document.querySelector(DOMstrings.inputDescription).value, value: parseFloat(document.querySelector(DOMstrings.inputValue).value), }; }, addListItem: function(obj, type) { var html, newHtml; //Creating HTML string with placeholder text if (type === 'inc') { element = DOMstrings.incomeContainer; html = '<div class="item clearfix" id="inc-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>'; } else if (type === 'exp') { element = DOMstrings.expenseContainer; html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>' } //Replacing the placehoder text with some actual data newHtml = html.replace('%id%', obj.id); newHtml = newHtml.replace('%description%', obj.description); newHtml = newHtml.replace('%value%', formatNumber(obj.value)); //Insert the HTML into the DOM document.querySelector(element).insertAdjacentHTML('beforeend', newHtml); }, deleteListItem: function(selectorID) { var el = document.getElementById(selectorID); el.parentNode.removeChild(el); }, clearFields: function() { var fields, fieldsArr; fields = document.querySelectorAll(DOMstrings.inputDescription + ', ' + DOMstrings.inputValue); fieldsArr = Array.prototype.slice.call(fields); fieldsArr.forEach(function(current, index, array){ current.value = ""; }); fieldsArr[0].focus(); }, displayBudget: function(obj) { var type; obj.budget > 0 ? type = 'inc' : type = 'exp'; document.querySelector(DOMstrings.budgetLabel).textContent = formatNumber(obj.budget, type); document.querySelector(DOMstrings.incomeLabel).textContent = formatNumber(obj.totalInc, 'inc'); document.querySelector(DOMstrings.expensesLabel).textContent = formatNumber(obj.totalExp, 'exp'); if (obj.percentage > 0 ) { document.querySelector(DOMstrings.percentageLabel).textContent = obj.percentage + '%'; } else { document.querySelector(DOMstrings.percentageLabel).textContent = '---' } }, displayPercentages: function(percentages) { var fields = document.querySelectorAll(DOMstrings.expensesPercLabel); nodeListForEach(fields, function(current, index) { if (percentages[index] > 0 ) { current.textContent = percentages[index] + '%'; } else { current.textContent = '---'; } }); }, displayMonth: function(){ var now, year, month, months; now = new Date(); months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] month = now.getMonth(); year = now.getFullYear(); document.querySelector(DOMstrings.dateLabel).textContent = months[month] + ' ' + year; }, changedType: function(){ var fields = document.querySelectorAll( DOMstrings.inputType + ',' + DOMstrings.inputDescription + ',' + DOMstrings.inputValue ); nodeListForEach(fields, function(cur) { cur.classList.toggle('red-focus'); }); document.querySelector(DOMstrings.inputButton).classList.toggle('red'); }, getDOMstrings: function() { return DOMstrings; } }; })(); var controller = (function(budgetCtrl, UICtrl) { var setupEventListeners = function() { var DOM = UICtrl.getDOMstrings(); document.querySelector(DOM.inputButton).addEventListener('click', ctrlAddItem); document.addEventListener('keypress', function(event) { if (event.keyCode === 13 || event.which === 13) { ctrlAddItem(); } }); document.querySelector(DOM.container).addEventListener('click', ctrlDeleteItem); document.querySelector(DOM.inputType).addEventListener('change', UICtrl.changedType); }; var updateBudget = function(){ //Caculating the budget budgetCtrl.calculateBudget(); //Returning the budget var budget = budgetCtrl.getBudget(); //Displaying the budget on the UI UICtrl.displayBudget(budget); //Calculating and updating percentages updatePercentages(); }; var updatePercentages = function() { //Calculaiting percentages budgetCtrl.calculatePercentages(); //Reading percentages from the budget controller var percentages = budgetCtrl.getPercentages(); //Updating the UI with the new percentages UICtrl.displayPercentages(percentages); } var ctrlAddItem = function() { var input, newItem, //Getting the field input data input = UICtrl.getInput(); if (input.description !== "" && !isNaN(input.value) && input.value > 0) { //Adding the item to the budget controller newItem = budgetCtrl.addItem(input.type, input.description, input.value); //Adding the item to the UI UICtrl.addListItem(newItem, input.type); //Clearing the fields UICtrl.clearFields(); //Calcuating and updating budget updateBudget(); }; }; var ctrlDeleteItem = function(event) { var itemID, splitID, type, ID; itemID = event.target.parentNode.parentNode.parentNode.parentNode.id; if (itemID) { splitID = itemID.split('-'); type = splitID[0]; ID = parseInt(splitID[1]); //Deleting the item from the data structure budgetCtrl.deleteItem(type, ID); //Deleting the item from the UI UICtrl.deleteListItem(itemID); //Updating and showing the new budget updateBudget(); } }; return { init: function() { console.log('Application has started.'); UICtrl.displayMonth(); UICtrl.displayBudget(budgetCtrl.getBudget() || { budget: 0, totalInc: 0, totalExp: 0, percentage: -1 }); let budget = budgetCtrl.getBudget(); console.log(budget); if (budget.budget) { budget.allExp.forEach(ex => UICtrl.addListItem(ex, 'exp')); budget.allInc.forEach(inc => UICtrl.addListItem(inc, 'inc')); } setupEventListeners(); } } })(budgetController, UIController); controller.init();
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddFkJobOffer extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('job_offer', function (Blueprint $table) { $table->unsignedBigInteger('company_id')->nullable(); $table->foreign('company_id')->references('id')->on('company'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('job_offer', function (Blueprint $table) { $table->dropForeign('company_id'); $table->dropIndex('company_id'); $table->dropColumn('company_id'); }); } }
scalar Decimal scalar EmailAddress scalar DateTime scalar Date scalar Currency #Common directives "The @internal directive annotates GraphQL objects that should be available internally" directive @internal repeatable on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | INTERFACE | UNION | ENUM | ENUM_VALUE | INPUT_OBJECT | INPUT_FIELD_DEFINITION "The @public directive annotates GraphQL objects that should be available publicly" directive @public(name: String!) repeatable on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | INTERFACE | UNION | ENUM | ENUM_VALUE | INPUT_OBJECT | INPUT_FIELD_DEFINITION "The @authorization directive declares the permissions required to call a GraphQL API" directive @authorization(scopes: [String!]!) on OBJECT | FIELD_DEFINITION | INTERFACE | ENUM | INPUT_OBJECT | INPUT_FIELD_DEFINITION | UNION "The @example directive will make any field that's annotated with it appear in the generated documentation" directive @example on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | INTERFACE | UNION | ENUM | ENUM_VALUE | INPUT_OBJECT | INPUT_FIELD_DEFINITION type PageInfo @public(name: "common") { "startCursor is an opaque cursor representing the first returned item" startCursor: String "endCursor is an opaque cursor representing the last returned item" endCursor: String "hasPreviousPage indicates if the connection has items before the startCursor" hasPreviousPage: Boolean! "hasNextPage indicates if the connection has items after the endCursor" hasNextPage: Boolean! } "OrderDirection defines possible sort orders" enum OrderDirection @public(name: "common") { ASC DESC }
import React, { useState } from "react"; export default function Accordion({ items }) { const [activeState, setActiveState] = useState(null); const onTitleClick = (index) => { setActiveState(index); }; const renderedItems = items.map((item, index) => { const active = index === activeState ? 'active' : ''; return ( <React.Fragment key={item.title}> <div className={`title ${active}`} onClick={() => onTitleClick(index)}> <i className="dropdown icon"></i> {item.title} </div> <div className={`content ${active}`}> <p>{item.content}</p> </div> </React.Fragment> ); }); return <div className="ui styled accordion">{renderedItems} </div>; }
import {View, Text, Image, StyleSheet, TouchableOpacity} from 'react-native'; import React from 'react'; import {COLORS, images, SIZES} from '../../constants/index'; import {useNavigation} from '@react-navigation/native'; import {FontIos} from '../../constants/theme'; interface Card { image_path: any; imageTitle: string; imageArtist: string; } const Card = ({image_path, imageTitle, imageArtist}: Card) => { const navigation = useNavigation(); // onPress={() => navigation.navigate('Zuletzt')} return ( <View style={styles.container}> <TouchableOpacity onPress={() => navigation.navigate('ZuletztScreen')}> {image_path !== null ? ( <Image source={image_path} style={styles.image} /> ) : ( <Image source={images.notFoundImage} style={styles.image} /> )} </TouchableOpacity> { <Text style={styles.imageTitle}> {imageTitle === null ? 'NONE' : imageTitle.length < 250 ? `${imageTitle}` : `${imageTitle.substring(0, 20)}...`} </Text> } <Text style={styles.imageArtist}> {imageArtist === null ? 'NONE' : imageTitle.length < 250 ? `${imageArtist}` : `${imageArtist.substring(0, 20)}...`} </Text> </View> ); }; const styles = StyleSheet.create({ container: { width: 165, height: 220, marginLeft: (SIZES.width - 165 * 2) / 3, marginTop: 10, marginBottom: 10, }, image: { borderWidth: 1, borderRadius: 10, resizeMode: 'contain', justifyContent: 'center', height: 165, width: 165, }, imageTitle: { color: '#000', fontSize: 15, fontFamily: FontIos, fontWeight: '400', lineHeight: 17.9, top: 10, }, imageArtist: { color: COLORS.artistColor, fontSize: 15, fontWeight: '400', fontFamily: FontIos, lineHeight: 17.9, top: 15, }, }); export default Card;
import * as React 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 Slide from '@mui/material/Slide'; import { useStateContext } from '../hooks/useStateContext'; const Transition = React.forwardRef(function Transition(props, ref) { return <Slide direction="up" ref={ref} {...props} />; }); export default function ConfirmDialogSlide() { const {confirmDialog,showConfirmDialog}=useStateContext(); const handleClose = () => { showConfirmDialog({text:'',confirmAction:null}) }; return ( <Dialog maxWidth="true" open={confirmDialog.text==''?false:true} TransitionComponent={Transition} keepMounted onClose={handleClose} aria-describedby="alert-dialog-slide-description" > <DialogTitle>{confirmDialog.text}</DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-slide-description"> </DialogContentText> Detail : {confirmDialog.object} </DialogContent> <DialogActions> <Button onClick={handleClose}>No</Button> <Button onClick={()=> {confirmDialog.confirmAction(); handleClose()}}>Yes</Button> </DialogActions> </Dialog> ); }
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { buildForbiddenRouteslist } from '../../functions/utils'; import { StatoEnum, TipoProcedimento } from './../../../../shared/models/models'; import { UserService } from './../../../../shared/services/user.service'; import { RoutesHandler } from './../../models/routes-handler.models'; import { DataService } from './../../services/data-service/data.service'; @Directive({ selector: '[appTabEnabler]' }) export class TabEnablerDirective { @Input("appTabEnabler") nomeTab: string; private unsubscribe$: Subject<void> = new Subject<void>(); constructor(private user: UserService, private shared: DataService, private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { } public ngOnInit(): void { this.shared.statusObservable .pipe(takeUntil(this.unsubscribe$)) .subscribe(() => this.checkVisibility()); } public ngOnDestroy(): void { this.unsubscribe$.next(); this.unsubscribe$.complete(); } private checkVisibility(): void { this.viewContainer.clear(); let authorized: boolean = this.check(); if (authorized) this.viewContainer.createEmbeddedView(this.templateRef); else this.viewContainer.clear(); } private check(): boolean { let forbiddenRoutes: RoutesHandler = buildForbiddenRouteslist(this.status, this.shared.fascicolo, this.user.groupType); return forbiddenRoutes ? forbiddenRoutes.forbiddenRoutes.every(s => s != this.nomeTab) : false; } private get status() : StatoEnum { return this.shared.status; } private get tipoProcedimento(): TipoProcedimento { return this.shared.fascicolo ? this.shared.fascicolo.tipoProcedimento : null; } }
import { Router } from 'express'; import { cartsService } from '../dao/index.js'; const router = Router(); // Ruta para obtener todos los carritos router.get("/", async(req,res)=>{ try { const carts = await cartsService.getCarts(); res.json({data:carts}); } catch (error) { res.json({error:error.message}); } }); // Ruta para crear un nuevo carrito router.post("/",async(req,res)=>{ try { const cartCreated = await cartsService.createCart(); res.json({status:"success",data: cartCreated}); } catch (error) { res.json({status:"error",error:error.message}); } }); // Ruta para obtener los productos de un carrito router.get("/:cid", async(req,res)=>{ try { const cartId = req.params.cid; const cart = await cartsService.getCartById(cartId); res.json({status:"success", data: cart}); } catch (error) { res.json({error:error.message}); } }); // Ruta para eliminar un producto del carrito router.delete('/:cid/products/:pid', async (req, res) => { try { const { cid:cartId, pid:productId } = req.params; const result = await cartsService.deleteProduct(cartId, productId); res.json({ message: 'Producto eliminado del carrito', result }); } catch (error) { res.status(500).json({ error: 'Error al eliminar el producto del carrito' }); }; }); // Ruta para actualizar el carrito con un arreglo de productos router.put('/:cid', async (req, res) => { const { cid:cartId } = req.params; const newProducts = req.body.products; try { const updatedCart = await cartsService.addProduct(cartId, newProducts); res.json({ message: 'Carrito actualizado', cart: updatedCart }); } catch (error) { res.status(500).json({ error: 'Error al actualizar el carrito' }); }; }); // Ruta para actualizar la cantidad de un producto en el carrito router.put('/:cid/products/:pid', async (req, res) => { try { const {cid:cartId,pid:productId} = req.params; const {newQuantity} = req.body; const cart = await cartsService.getCartById(cartId); const result = await cartsService.updateProductCart(cartId,productId,newQuantity); res.json({status:"success", result}); } catch (error) { res.json({error:error.message}); } }); // Ruta para eliminar todos los productos del carrito router.delete('/:cid', async (req, res) => { try { const { cid:cartId } = req.params; const result = await cartsService.deleteCart(cartId); res.json({ message: 'Carrito eliminado', result }); } catch (error) { res.status(500).json({ error: 'Error al eliminar el carrito' }); } }); // Ruta para agregar un producto al carrito router.post("/:cid/products/:pid", async (req, res) => { try { const { cid: cartId, pid: productId } = req.params; await cartsService.addProduct(cartId, productId, ); res.json({ message: 'Producto agregado al carrito con รฉxito' }); } catch (error) { res.status(500).json({ error: 'Error al agregar el producto al carrito' }); }; }); export { router as cartsRouter };
== Object expressions link:https://kotlinlang.org/docs/object-declarations.html[kotlinlang.org], link:https://developer.alexanderklimov.ru/android/kotlin/object.php[alexanderklimov] *_See:_* link:../../kotlin-basics/src/main/kotlin/common/cs026_object_expressions/ObjectExpressions.kt[ObjectExpressions.kt] === 1. ะ’ะฒะตะดะตะฝะธะต ะ˜ะฝะพะณะดะฐ ะฒะฐะผ ะฝะตะพะฑั…ะพะดะธะผะพ ัะพะทะดะฐั‚ัŒ ะพะฑัŠะตะบั‚, ะฟั€ะตะดัั‚ะฐะฒะปััŽั‰ะธะน ัะพะฑะพะน ะฝะตะฑะพะปัŒัˆัƒัŽ ะผะพะดะธั„ะธะบะฐั†ะธัŽ ะบะฐะบะพะณะพ-ะปะธะฑะพ ะบะปะฐััะฐ, ะฑะตะท ัะฒะฝะพะณะพ ะพะฑัŠัะฒะปะตะฝะธั ะดะปั ะฝะตะณะพ ะฝะพะฒะพะณะพ ะฟะพะดะบะปะฐััะฐ. Kotlin ะฟั€ะตะดะพัั‚ะฐะฒะปัะตั‚ ะดะปั ัั‚ะพะณะพ *_object expressions_* ะธ *_object declarations_*. ะ ะฐะทะฝะธั†ะฐ ะฒ ะธะฝะธั†ะธะฐะปะธะทะฐั†ะธะธ ะผะตะถะดัƒ *_object expressions_*/*_object declarations_*/*_companion objects_* ัะปะตะดัƒัŽั‰ะฐั: - Object expressions ะฒั‹ะฟะพะปะฝััŽั‚ัั (ะธ ะธะฝะธั†ะธะฐะปะธะทะธั€ัƒัŽั‚ัั) ัั€ะฐะทัƒ ะถะต ั‚ะฐะผ, ะณะดะต ะพะฝะธ ะธัะฟะพะปัŒะทัƒัŽั‚ัั. - Object declarations ะธะฝะธั†ะธะฐะปะธะทะธั€ัƒัŽั‚ัั ะปะตะฝะธะฒะพ ะฟั€ะธ ะฟะตั€ะฒะพะผ ะพะฑั€ะฐั‰ะตะฝะธะธ ะบ ะฝะธะผ. - Companion object ะธะฝะธั†ะธะฐะปะธะทะธั€ัƒะตั‚ัั, ะบะพะณะดะฐ ะทะฐะณั€ัƒะถะฐะตั‚ัั ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะธะน ะบะปะฐัั (that matches the semantics of a Java static initializer). === 2. Object expressions. ะกะพะทะดะฐะฝะธะต ะฐะฝะพะฝะธะผะฝั‹ั… ะพะฑัŠะตะบั‚ะพะฒ ั ะฝัƒะปั *_Object expressions_* ัะพะทะดะฐัŽั‚ *`ะฐะฝะพะฝะธะผะฝั‹ะต ะพะฑัŠะตะบั‚ั‹`* *_ะฐะฝะพะฝะธะผะฝั‹ั… ะบะปะฐััะพะฒ_*, ะบะพั‚ะพั€ั‹ะต ะฟะพะปะตะทะฝั‹ ะดะปั ะพะดะฝะพั€ะฐะทะพะฒะพะณะพ ะธัะฟะพะปัŒะทะพะฒะฐะฝะธั. ะ’ั‹ ะผะพะถะตั‚ะต ะพะฟั€ะตะดะตะปะธั‚ัŒ ะธั… ั ะฝัƒะปั, ะฝะฐัะปะตะดะพะฒะฐั‚ัŒ ััƒั‰ะตัั‚ะฒัƒัŽั‰ะธะต ะบะปะฐััั‹ ะธะปะธ ั€ะตะฐะปะธะทะพะฒะฐั‚ัŒ ะธะฝั‚ะตั€ั„ะตะนัั‹. ะญะบะทะตะผะฟะปัั€ั‹ ะฐะฝะพะฝะธะผะฝั‹ั… ะบะปะฐััะพะฒ - *_ะฐะฝะพะฝะธะผะฝั‹ะต ะพะฑัŠะตะบั‚ั‹_* - ะพะฟั€ะตะดะตะปััŽั‚ัั ะฒั‹ั€ะฐะถะตะฝะธะตะผ, ะฐ ะฝะต ะธะผะตะฝะตะผ. ะ•ัะปะธ ะฒะฐะผ ะฟั€ะพัั‚ะพ ะฝัƒะถะตะฝ ะพะฑัŠะตะบั‚, ะฝะต ะธะผะตัŽั‰ะธะน ะฝะตั‚ั€ะธะฒะธะฐะปัŒะฝั‹ั… ััƒะฟะตั€ั‚ะธะฟะพะฒ, ะพะฑัŠัะฒะธั‚ะต ะตะณะพ ั‡ะปะตะฝั‹ ะฒ ั„ะธะณัƒั€ะฝั‹ั… ัะบะพะฑะบะฐั… ะฟะพัะปะต ะบะปัŽั‡ะตะฒะพะณะพ ัะปะพะฒะฐ *_object_*. ะ•ัะปะธ ั‚ะธะฟ ะฝะต ะฝะฐัะปะตะดัƒะตั‚ัั ะพั‚ ััƒะฟะตั€ะบะปะฐััะฐ, ั‚ะพ ะพะฝ ะธะผะตะตั‚ ั‚ะธะฟ Any: [source, kotlin] ---- val helloWorld = object { val hello = "Hello" val world = "World" // object expressions extend Any, so // `override` is required on `toString()` override fun toString() = "$hello $world" } // helloWorld has type 'Any' print(helloWorld) ---- === 3. Object expressions. ะะฐัะปะตะดะพะฒะฐะฝะธะต ะฐะฝะพะฝะธะผะฝั‹ั… ะพะฑัŠะตะบั‚ะพะฒ ะพั‚ ััƒะฟะตั€ะบะปะฐััะพะฒ ะงั‚ะพะฑั‹ ัะพะทะดะฐั‚ัŒ ะพะฑัŠะตะบั‚ ะฐะฝะพะฝะธะผะฝะพะณะพ ะบะปะฐััะฐ, ะบะพั‚ะพั€ั‹ะน ะฝะฐัะปะตะดัƒะตั‚ัั ะพั‚ ะบะฐะบะพะณะพ-ะปะธะฑะพ ั‚ะธะฟะฐ (ะธะปะธ ั‚ะธะฟะพะฒ), ัƒะบะฐะถะธั‚ะต ัั‚ะพั‚ ั‚ะธะฟ ะฟะพัะปะต `object :`. ะ•ัะปะธ ัƒ ััƒะฟะตั€ั‚ะธะฟะฐ ะตัั‚ัŒ ะบะพะฝัั‚ั€ัƒะบั‚ะพั€, ะฟะตั€ะตะดะฐะนั‚ะต ะตะผัƒ ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะธะต ะฟะฐั€ะฐะผะตั‚ั€ั‹ ะบะพะฝัั‚ั€ัƒะบั‚ะพั€ะฐ. ะะตัะบะพะปัŒะบะพ ััƒะฟะตั€ั‚ะธะฟะพะฒ ะผะพะถะฝะพ ัƒะบะฐะทะฐั‚ัŒ ะฒ ะฒะธะดะต ัะฟะธัะบะฐ, ั€ะฐะทะดะตะปะตะฝะฝะพะณะพ ะทะฐะฟัั‚ั‹ะผะธ ะฟะพัะปะต ะดะฒะพะตั‚ะพั‡ะธั: [source, kotlin] ---- open class Car(x: Int) { public open var speed: Int = x public open var seats: Int = 4 fun printInfo() = println("Car speed: $speed, seats num: $seats") } interface Truck { val liftingCapacity: Double // ะณั€ัƒะทะพะฟะพะดัŠะตะผะฝะพัั‚ัŒ } fun anonObjDerived() { val bus = object : Car(0) { override var seats = 24 } bus.printInfo() // Car speed: 0, seats num: 24 bus.speed = 15 bus.printInfo() // Car speed: 15, seats num: 24 val truck = object : Car(0), Truck { override val liftingCapacity: Double = 1500.0 var filledCapacity: Double = 0.0 fun supply(amount : Double) { if (amount < 0.0) { println("Negative amount validation!") return } var result = filledCapacity + amount; if (result <= liftingCapacity) { filledCapacity = result println("Truck now lift $filledCapacity kg") } else { println("Truck cannot lift more than $liftingCapacity kg") } } } truck.speed = 20 truck.printInfo() // Car speed: 20, seats num: 4 truck.supply(700.0) // Truck now lift 700.0 kg truck.supply(-2.0) // Negative amount validation! truck.supply(567.0) // Truck now lift 1267.0 kg truck.supply(900.0)//Truck cannot lift more than 1500.0 kg } ---- === 4. Object expressions. ะ”ะพัั‚ัƒะฟ ะบ ั‡ะปะตะฝะฐะผ ะฐะฝะพะฝะธะผะฝั‹ั… ะบะปะฐััะพะฒ ะ•ัั‚ัŒ ะดะฒะต ะพัะฝะพะฒะฝั‹ั… ัะธั‚ัƒะฐั†ะธะธ ะธัะฟะพะปัŒะทะพะฒะฐะฝะธั ะพะฑัŠะตะบั‚ะพะฒ ะฐะฝะพะฝะธะผะฝะพะณะพ ะบะปะฐััะฐ: - 1) *_ะ›ะพะบะฐะปัŒะฝะฐั ะฟะตั€ะตะผะตะฝะฝะฐั_* ะธะปะธ *_private ะธ not inline ั„ัƒะฝะบั†ะธั ะธะปะธ ัะฒะพะนัั‚ะฒะพ_*. ะ’ ัั‚ะพะผ ัะปัƒั‡ะฐะต ะฒัะต ั‡ะปะตะฝั‹, ะพะฑัŠัะฒะปะตะฝะฝั‹ะต ะฒ ะฐะฝะพะฝะธะผะฝะพะผ ะบะปะฐััะต, ะดะพัั‚ัƒะฟะฝั‹ ั‡ะตั€ะตะท ัั‚ัƒ ะฟะตั€ะตะผะตะฝะฝัƒัŽ, ั„ัƒะฝะบั†ะธัŽ ะธะปะธ ัะฒะพะนัั‚ะฒะพ. ะžะฑั‹ั‡ะฝะพ ัั‚ะพ ัั‚ะฐะฝะดะฐั€ั‚ะฝะพะต ะฟั€ะธะผะตะฝะตะฝะธะต ะฐะฝะพะฝะธะผะฝั‹ั… ะบะปะฐััะพะฒ. - 2) ะ•ัะปะธ ั„ัƒะฝะบั†ะธั ะธะปะธ ัะฒะพะนัั‚ะฒะพ ัะฒะปัะตั‚ัั public ะธะปะธ private inline, ั‚ะพ ะพะฝะฐ ะฝะตะดะพัั‚ัƒะฟะฝะฐ ะธะทะฒะฝะต. [source, kotlin] ---- class Parking { private fun callThePolice() = object: Car(100) { val weapon: MutableList<String> = mutableListOf("PM", "PP-19 Vityaz") } fun printPoliceInfo() { val policeCar = callThePolice() println("Police car has speed ${policeCar.speed} " + "and is armoured with ${policeCar.weapon}") } fun getPoliceCar() : Car { return callThePolice() } } fun anonObjInternalPropsAccess() { val parking = Parking() parking.printPoliceInfo() val policeCar = parking.getPoliceCar() policeCar.weapon.clear() // ERROR - ะฝะตั‚ ะดะพัั‚ัƒะฟะฐ ะบ ะฟะตั€ะตะผะตะฝะฝะพะน weapon val fireTruck = object: Car(70) { var waterVolume: Int = 0 } // ะ•ัั‚ัŒ ะดะพัั‚ัƒะฟ ะบ ะฟะตั€ะตะผะตะฝะฝะพะน weapon fireTruck.waterVolume = 14 println("Fire truck water: ${fireTruck.waterVolume}") } ----
import styles from "./ProductList.module.scss"; import { useAppSelector } from "../hooks/redux-hooks"; import Product from "./Product"; interface ProductListProps { description: string; slogan: string; } const ProductList = ({ description, slogan }: ProductListProps) => { const products = useAppSelector((state) => state.main.products); return ( <div className={styles.wrapper}> <p className={styles.description}>{description}</p> <p className={styles.slogan}>{slogan}</p> <div className={styles.container}> {products.map((product) => ( <Product key={product.id} product={product} /> ))} </div> </div> ); }; export default ProductList;
import express from "express"; import axios from "axios"; import ytdl from "ytdl-core"; import {YoutubeVideosScraper} from "./Utils/YoutubeVideosScraper" import { Params } from "./Interfaces/YoutubeHomeResponse"; const app = express(); const PORT = process.env.PORT || 1025; require('dotenv').config(); app.use(express.static('public')); app.get("/v1/videoinfo/:videoId",async (req,res)=>{ let videoId = req.params.videoId; let cookies = process.env.COOKIES?process.env.COOKIES:""; let idToken = process.env.ID_TOKEN?process.env.ID_TOKEN:""; let info = await ytdl.getInfo(videoId,{ requestOptions:{ cookie:cookies, 'x-youtube-identity-token':idToken } }); let responseInfo = { details:{ thumbnail:`https://i.ytimg.com/vi/${videoId}/mqdefault.jpg`, title:info.title, description:info.description }, related:info.related_videos, formats:info.formats } res.json(responseInfo); }); app.get("/v1/trendvideos",async (req,res)=>{ axios.get('https://m.youtube.com/feed/trending') .then((axres)=>{ var scraper = new YoutubeVideosScraper(axres.data) var results = scraper.scrapYoutubeTrendsPage(); res.json(results); }).catch((err)=>{ res.status(404); }); }); app.get("/v1/suggestions/:videoId",async (req,res)=>{ axios.get(`https://m.youtube.com/watch?v=${req.params.videoId}`) .then((axres)=>{ var scraper = new YoutubeVideosScraper(axres.data) var results = scraper.scrapRelatedVideos(); res.json(results); }).catch((err)=>{ res.status(404); }); }); app.get("/v1/homevideos",async (req,res)=>{ axios.get('https://m.youtube.com') .then((axres)=>{ var scraper = new YoutubeVideosScraper(axres.data) var results = scraper.scrapYoutubeHomePage(); res.json(results); }).catch((err)=>{ res.status(404); }); }); app.listen(PORT,()=>{ console.log(`Server listening in: ${PORT}`) });
<!DOCTYPE html> <html> <head> <title></title> <style> div#canvas-frame { border: none; cursor: pointer; width: 100%; height: 600px; background-color: #EEEEEE; } </style> <!--ๅผ•ๅ…ฅthree.jsไธ‰็ปดๅผ•ๆ“Ž--> <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script> <!-- ๅผ•ๅ…ฅthreejsๆ‰ฉๅฑ•ๆŽงไปถOrbitControls.js --> <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/examples/js/controls/OrbitControls.js"></script> <script> let renderer, width, height function initThree() { width = document.getElementById("canvas-frame").clientWidth height = document.getElementById("canvas-frame").clientHeight renderer = new THREE.WebGLRenderer() renderer.setSize(width, height) renderer.setClearColor(0xb9d3ff, 1) document.getElementById("canvas-frame").appendChild(renderer.domElement) } // ๅˆ›ๅปบๅœบๆ™ฏ let scene function initScene() { scene = new THREE.Scene() } let mesh function initGeometry() { const axisHelper = new THREE.AxisHelper(200) scene.add(axisHelper) const geometry = new THREE.Geometry() // ไธ€ๆกๅ…‰ๆป‘ๆ ทๅผๆ›ฒ็บฟ // const p1 = new THREE.Vector3(-15, 20, 90) // const p2 = new THREE.Vector3(-10, 20, 20) // const p3 = new THREE.Vector3(0, 0, 0) // const p4 = new THREE.Vector3(60, -60, 0) // const p5 = new THREE.Vector3(70, 0, 80) // // ไธ‰็ปดๆ ทๅผๆ›ฒ็บฟ Catmull-Rom ็ฎ—ๆณ• // const curve = new THREE.CatmullRomCurve3([p1, p2, p3, p4, p5]) // ๅ†…ๅกžๅฐ”ๆ›ฒ็บฟ // ไธ‰็ปดไบŒๆฌก่ดๅกžๅฐ”ๆ›ฒ็บฟ // const p1 = new THREE.Vector3(-80, 0, 0) // const p2 = new THREE.Vector3(20, 100, 0) // const p3 = new THREE.Vector3(80, 0, 0) // const curve = new THREE.QuadraticBezierCurve3(p1, p2, p3) // ไธ‰็ปดไธ‰ๆฌก่ดๅกžๅฐ”ๆ›ฒ็บฟ const p1 = new THREE.Vector3(-80, 0, 0) const p2 = new THREE.Vector3(-40, 100, 0) const p3 = new THREE.Vector3(40, 100, 0) const p4 = new THREE.Vector3(80, 0, 0) const curve = new THREE.CubicBezierCurve3(p1, p2, p3, p4) // getPoints ๆ˜ฏๅŸบ็ฑป Curve ็š„ๆ–นๆณ•๏ผŒ่ฟ”ๅ›žไธ€ไธช Vector3 ๅฏน่ฑกไฝœไธบๅ…ƒ็ด ็ป„ๆˆ็š„ๆ•ฐ็ป„ const points = curve.getPoints(100) // ๅˆ†ๆฎตๆ•ฐไธบ 100๏ผŒ ่ฟ”ๅ›ž 101 ไธช้กถ็‚น // setFromPoints ๆ–นๆณ•ไปŽ points ไธญๆๅ–ๆ•ฐๆฎๆ”นๅ˜ๅ‡ ไฝ•ไฝ“็š„้กถ็‚นๅฑžๆ€ง vertices geometry.setFromPoints(points) const material = new THREE.LineBasicMaterial({ color: 0x000000 }) const line = new THREE.Line(geometry, material) scene.add(line) } // ๅ…‰ๆบ่ฎพ็ฝฎ function initLight() { // ็‚นๅ…‰ๆบ let point = new THREE.PointLight(0xffffff) point.position.set(400, 200, 300) // ็‚นๅ…‰ๆบ็š„ไฝ็ฝฎ scene.add(point) // ็Žฏๅขƒๅ…‰ let ambient = new THREE.AmbientLight(0x444444) scene.add(ambient) } // ๅˆ›ๅปบ็›ธๆœบ let camera function initCamera() { let k = width / height let s = 200 camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000) camera.position.set(250, 200, 200) camera.lookAt(scene.position) } // ๆธฒๆŸ“ function render() { renderer.render(scene, camera) // mesh.rotateY(0.01) // ๆ—‹่ฝฌ // requestAnimationFrame(render) // ไธ่ƒฝไธŽ controls ๅŒๆ—ถไฝฟ็”จ } // ๆŽงๅˆถๅ™จ function initControls() { controls = new THREE.OrbitControls(camera, renderer.domElement) controls.addEventListener('change', render) } const threeStart = () => { initThree() initScene() initGeometry() initCamera() initLight() render() initControls() } </script> </head> <body onload="threeStart();"> <div id="canvas-frame"></div> </body> </html>
//Calibration = 22.50 BoardName = ACM1 Scale 0 Baud = 19200 #include <HX711_ADC.h> #if defined(ESP8266)|| defined(ESP32) || defined(AVR) #include <EEPROM.h> #endif //pins: const int HX711_dout = 4; //mcu > HX711 dout pin const int HX711_sck = 5; //mcu > HX711 sck pin //HX711 constructor: HX711_ADC LoadCell(HX711_dout, HX711_sck); const int calVal_eepromAdress = 0; const int tareOffsetVal_eepromAdress = 4; unsigned long t = 0; float oldvalue = 0 ; void setup() { Serial.begin(19200); delay(10); LoadCell.begin(); float calibrationValue; // calibration value (see example file "Calibration.ino") calibrationValue = 22.50; //predetermined for scale 1 #if defined(ESP8266)|| defined(ESP32) EEPROM.begin(512); #endif long tare_offset = 0; EEPROM.get(tareOffsetVal_eepromAdress, tare_offset); LoadCell.setTareOffset(tare_offset); boolean _tare = false; unsigned long stabilizingtime = 2000; // preciscion for power-up start LoadCell.start(stabilizingtime, _tare); if (LoadCell.getTareTimeoutFlag()) { Serial.println("Timeout, check MCU>HX711 wiring and pin designations"); while (1); } else { LoadCell.setCalFactor(calibrationValue); // set calibration value } } void loop() { static boolean newDataReady = 0; const int serialPrintInterval = 10000; //print every 10 seconds if (LoadCell.update()) newDataReady = true; if (newDataReady) { float i = LoadCell.getData(); if (millis() > t + serialPrintInterval ) { unsigned int k = i; String strClose = String(")"); String strOpen = String("("); String test = String() ; test = strOpen + k + strClose ; Serial.print(test); //gives output oldvalue = i; newDataReady = 0; t = millis(); } } // receive command from serial terminal, send 't' to initiate tare operation: if (Serial.available() > 0) { char inByte = Serial.read(); if (inByte == 't') refreshOffsetValueAndSaveToEEprom(); } } void refreshOffsetValueAndSaveToEEprom() { long _offset = 0; LoadCell.tare(); // calculate the new tare _offset = LoadCell.getTareOffset(); // get the new tare EEPROM.put(tareOffsetVal_eepromAdress, _offset); // save the new tare #if defined(ESP8266) || defined(ESP32) EEPROM.commit(); #endif LoadCell.setTareOffset(_offset); }
package com.example.playfaircipher; import java.util.HashSet; public class PlayfairCipher { private static final char FILLER_CHAR = 'X'; private char[][] matrix; public PlayfairCipher(String keyword) { matrix = fillMatrix(keyword); } private char[][] fillMatrix(String keyword) { keyword = keyword.replaceAll("[^a-zA-Z]", "").toUpperCase(); keyword = keyword.replace("J", "I"); char[][] matrix = new char[5][5]; HashSet<Character> uniqueLetters = new HashSet<>(); for (char c : keyword.toCharArray()) { uniqueLetters.add(c); } int row = 0; int col = 0; for (char c : uniqueLetters) { matrix[row][col] = c; col++; if (col == 5) { col = 0; row++; } } char letter = 'A'; while (row < 5) { if (!uniqueLetters.contains(letter) && letter != 'J') { matrix[row][col] = letter; col++; if (col == 5) { col = 0; row++; } } letter++; } return matrix; } public String encrypt(String plaintext) { StringBuilder ciphertext = new StringBuilder(); plaintext = preprocessText(plaintext); for (int i = 0; i < plaintext.length(); i += 2) { char c1 = plaintext.charAt(i); char c2 = plaintext.charAt(i + 1); if (c1 == 'J') { c1 = 'I'; } if (c2 == 'J') { c2 = 'I'; } int row1 = -1, col1 = -1, row2 = -1, col2 = -1; for (int row = 0; row < 5; row++) { for (int col = 0; col < 5; col++) { if (matrix[row][col] == c1) { row1 = row; col1 = col; } else if (matrix[row][col] == c2) { row2 = row; col2 = col; } } } if (row1 == row2) { col1 = (col1 + 1) % 5; col2 = (col2 + 1) % 5; } else if (col1 == col2) { row1 = (row1 + 1) % 5; row2 = (row2 + 1) % 5; } else { int temp = col1; col1 = col2; col2 = temp; } ciphertext.append(matrix[row1][col1]); ciphertext.append(matrix[row2][col2]); } return ciphertext.toString(); } public String decrypt(String ciphertext) { StringBuilder plaintext = new StringBuilder(); for (int i = 0; i < ciphertext.length(); i += 2) { char c1 = ciphertext.charAt(i); char c2 = ciphertext.charAt(i + 1); int row1 = -1, col1 = -1, row2 = -1, col2 = -1; for (int row = 0; row < 5; row++) { for (int col = 0; col < 5; col++) { if (matrix[row][col] == c1) { row1 = row; col1 = col; } else if (matrix[row][col] == c2) { row2 = row; col2 = col; } } } if (row1 == row2) { col1 = (col1 - 1 + 5) % 5; col2 = (col2 - 1 + 5) % 5; } else if (col1 == col2) { row1 = (row1 - 1 + 5) % 5; row2 = (row2 - 1 + 5) % 5; } else { int temp = col1; col1 = col2; col2 = temp; } plaintext.append(matrix[row1][col1]); plaintext.append(matrix[row2][col2]); } // Remove filler characters int i = 0; while (i < plaintext.length()) { if (plaintext.charAt(i) == FILLER_CHAR) { plaintext.deleteCharAt(i); } else { i++; } } return plaintext.toString(); } private String preprocessText(String text) { text = text.replaceAll("[^a-zA-Z]", "").toUpperCase(); StringBuilder processedText = new StringBuilder(); for (int i = 0; i < text.length(); i += 2) { char c1 = text.charAt(i); char c2 = (i + 1 < text.length()) ? text.charAt(i + 1) : FILLER_CHAR; processedText.append(c1); if (c1 == c2) { processedText.append(FILLER_CHAR); } processedText.append(c2); } return processedText.toString(); } }
import { Component, OnInit } from '@angular/core'; import { Message } from './support.model'; import { SupportService } from './support.service'; import { UiService } from '../ui/ui.service'; import { AuthService } from '../auth/auth.service'; @Component({ selector: 'app-support', templateUrl: './support.component.html', styleUrls: ['./support.component.css'] }) export class SupportComponent implements OnInit { filteredMessages: Message[] = [] public currentFilter: MessageFilter = MessageFilter.All areMessagesShown: boolean = false messageFilterClass = MessageFilter constructor(private supportService: SupportService, private uiService: UiService, private authService: AuthService) { } ngOnInit(): void { } setFilteredMessages(filterString: string): void { let filter: MessageFilter = MessageFilter[filterString as keyof typeof MessageFilter] this.currentFilter = filter this.areMessagesShown = true if (filter === MessageFilter.Processed) { this.supportService.getProcessedMessages().subscribe( { next: (value) => { this.filteredMessages = value this.uiService.showPopUpWindow("ะฃัะฟะตัˆะฝะพ") }, error: (e) => this.showErrorMessageAndLogout("ะžัˆะธะฑะบะฐ", e) } ) } else if (filter === MessageFilter.Unprocessed) { this.supportService.getUnprocessedMessages().subscribe( { next: (value) => { this.filteredMessages = value this.uiService.showPopUpWindow("ะฃัะฟะตัˆะฝะพ") }, error: (e) => this.showErrorMessageAndLogout("ะžัˆะธะฑะบะฐ", e) } ) } else { this.supportService.getAllMessages().subscribe( { next: (value) => { this.filteredMessages = value this.uiService.showPopUpWindow("ะฃัะฟะตัˆะฝะพ") }, error: (e) => this.showErrorMessageAndLogout("ะžัˆะธะฑะบะฐ", e) } ) } } changeMessageVisibility() { this.areMessagesShown = false } answerMessage(messageId: number, userId: number) { let response: string | null = prompt("ะ’ะฒะตะดะธั‚ะต ะพั‚ะฒะตั‚ ะฝะฐ ัะพะพะฑั‰ะตะฝะธะต") if (response === null) { this.uiService.showPopUpWindow("ะžัˆะธะฑะบะฐ. ะŸัƒัั‚ะพะต ัะพะพะฑั‰ะตะฝะธะต") return } let support = JSON.parse(localStorage.getItem("support") || "") this.supportService.answerMessage(messageId, support.id, response).subscribe({ next: (v) => { this.setFilteredMessages(this.currentFilter) this.uiService.showPopUpWindow("ะฃัะฟะตั…") }, error: (e) => this.uiService.showPopUpWindow("ะžัˆะธะฑะบะฐ") }) } get filterOptions(): string[] { return Object.keys(MessageFilter).map(key => MessageFilter[key as keyof typeof MessageFilter]); } showErrorMessageAndLogout(message: string, error: any) { this.uiService.showPopUpWindow(message) if (error.status == 401) { this.authService.logout() } } } enum MessageFilter { All = 'All', Processed = 'Processed', Unprocessed = 'Unprocessed' }
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override State<StatefulWidget> createState()=>MyHomeState(); } class MyHomeState extends State<MyHomePage>{ var count = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Stateful"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('Counte: $count',style: TextStyle(fontSize: 34),), ElevatedButton(onPressed: (){ count++; print(count); setState(() { }); }, child: Text("Increment Count")), ], ), ), ); } }
import React, { useState } from 'react'; import headerLogo from '../../../../public/header-logo.png' import Image from "next/dist/client/legacy/image"; import SearchIcon from "../../../assets/icons/SearchIcon"; import FavoriteIcon, { FavoriteFillIcon } from "../../../assets/icons/FavoriteIcon"; import BucketIcon, { BucketFillIcon } from "../../../assets/icons/BucketIcon"; import BurgerIcon from "../../../assets/icons/BurgerIcon"; import { useRouter } from "next/router"; import { $isOpenFavorite, onChangeIsOpenBucket, onChangeIsOpenFavorite, onChangeIsOpenMobMenu, onChangeIsOpenSearch } from "../../../entety/modals/model/index"; import Link from "next/link"; import { useUnit } from "effector-react"; import { $favorites } from "../../../entety/client/favorite/model"; import { $bucket } from "../../../entety/client/bucket/model"; import Logo from "../../../assets/icons/Logo"; const Header = () => { const router = useRouter() const [bucket, favorites] = useUnit([$bucket, $favorites]) const isBucketEmpty = bucket?.length === 0 const isFavoritesEmpty = favorites?.length === 0 const nav: any = [ { id: 1, path: '/catalog', title: 'ะšะฐั‚ะฐะปะพะณ' }, { id: 2, path: '/perfumery', title: 'ะŸะฐั€ั„ัŽะผะตั€ะธั' }, { id: 3, path: '/delivery', title: 'ะ”ะพัั‚ะฐะฒะบะฐ ะธ ะพะฟะปะฐั‚ะฐ' }, { id: 4, path: '/care', title: 'ะฃั…ะพะด' }, { id: 5, path: '/contacts', title: 'ะšะพะฝั‚ะฐะบั‚ั‹' }, { id: 6, path: '/about', title: 'ะž ะบะพะผะฟะฐะฝะธะธ' }, ] return ( <div className="header"> <div className="header-wrap"> <Link href='/' className="header-logo"> {/*<Image*/} {/* src={headerLogo}*/} {/*/>*/} <Logo/> </Link> <ul className="header-nav"> { nav.map((item: any) => <li> <Link href={item.path} style={{ fontWeight: router.pathname === item.path ? 400 : 300 }} > {item.title} </Link> </li> ) } </ul> <div className="header-icons"> <button onClick={() => onChangeIsOpenSearch(true)} > <SearchIcon /> </button> <button onClick={() => onChangeIsOpenFavorite(true)} > { isFavoritesEmpty ? <FavoriteIcon /> : <FavoriteFillIcon /> } </button> <button onClick={() => onChangeIsOpenBucket(true)} > { isBucketEmpty ? <BucketIcon /> : <BucketFillIcon /> } </button> <button className="header-icons-burger" onClick={() => onChangeIsOpenMobMenu(true)} > <BurgerIcon /> </button> </div> </div> </div> ); }; export default Header;
import React from "react"; import { Query, ApolloConsumer } from "react-apollo"; import { Link } from "react-router-dom"; import Queries from "../../graphql/queries"; import CourseHeader from './CourseHeader'; import Ruby from '../../assets/ruby-logo.png'; import JavaScript from '../../assets/javascript-logo.png'; import SQL from '../../assets/sql-logo.png'; const { FETCH_COURSES } = Queries; const CourseList = (props) => { return ( <div className="course-list"> <CourseHeader /> <ul> <Query query={FETCH_COURSES}> {({ loading, error, data }) => { if (loading) return <p>Loading...</p>; if (error) return <p>Error</p>; console.log(data); return data.courses.map(({ _id, language, icon, description }) => ( <div className="courseListItemContainer" key={_id} language={language}> <Link className="courseListLink" to={{ pathname: `/courses/${language}`, state: { id: `${_id}`} }}> <div className="courseListItem"> <img src={process.env.PUBLIC_URL + icon} alt="language logo" /> <h4>{language}</h4> </div> <div className="courseRight"> {description} <h5>5,000,000,000<br></br>users learning this language!</h5> </div> </Link> </div> )); }} </Query> </ul> </div> ); }; export default CourseList;
<template> <div class="bg-secondary-light dark:bg-primary-dark min-h-screen flex flex-col" > <!-- App header --> <TheHeader /> <!-- Render contents with transition --> <transition name="fade" mode="out-in"> <slot /> </transition> <!-- App footer --> <TheFooter /> <!-- Go back to top when scrolled down --> <div class="flex space-x-2 mr-8 mb-6 right-0 bottom-0 z-50 fixed items-center sm:space-x-4" > <BackToTop /> <whatsapp-button /> </div> </div> </template> <script lang="ts"> const route = useRoute(); useHead({ //title: this.$t("seo.title"), title: "Portafolio de Laynes", meta: [ { property: "og:title", // content: this.$t("seo.content"), content: "Desarrollador Web Full-Stack con 3 aรฑos de experiencia", }, { name: "viewport", content: "width=device-width, initial-scale=1", }, { charset: "utf-8", }, ], }); import feather from "feather-icons"; import TheHeader from "~/components/shared/TheHeader.vue"; import TheFooter from "~/components/shared/TheFooter.vue"; import BackToTop from "~/components/BackToTop.vue"; import WhatsappButton from "~/components/reusable/WhatsappButton.vue"; export default { data: () => { return { // Todo }; }, mounted() { feather.replace(); }, components: { TheFooter, BackToTop, TheHeader, WhatsappButton }, }; </script> <style> .vue-back-to-top { @apply p-2 sm:p-4 bg-indigo-500 hover:bg-indigo-600 text-white; border-radius: 50%; font-size: 22px; line-height: 22px; } .fade-enter-active { animation: coming 0.4s; animation-delay: 0.2s; opacity: 0; } .fade-leave-active { animation: going 0.4s; } @keyframes going { from { transform: translateX(0); } to { transform: translateX(-10px); opacity: 0; } } @keyframes coming { from { transform: translateX(-10px); opacity: 0; } to { transform: translateX(0px); opacity: 1; } } </style>
import { Articulo } from "./articulo"; import { ArticuloVendido } from "./articuloVendido"; export class Kiosko { private articulosDisponibles: Articulo[] = []; private articulosVendidos: ArticuloVendido[] = []; constructor(articulosDisponibles: Articulo[], articulosVendidos: ArticuloVendido[]) { this.articulosDisponibles = articulosDisponibles; this.articulosVendidos = articulosVendidos; } public cargarArticulo(articulos: Articulo[]): void { this.articulosDisponibles = articulos; } public venderArticulo(nombre: string, cantidad: number): void { const articulo = this.articulosDisponibles.find((articulo: Articulo) => articulo.nombre === nombre); if (articulo) { if (cantidad <= 0) { console.log("Debe comprar una o mรกs unidades."); return; } if (cantidad > articulo.stock) { console.log("No hay suficientes productos disponibles para vender."); return; } const valorTotal = articulo.valor * cantidad; this.articulosVendidos.push(new ArticuloVendido(nombre, cantidad, articulo.valor)); articulo.stock -= cantidad; // Actualizar el stock del artรญculo console.log(`Se ha vendido ${cantidad} ${articulo.nombre}(s) por un valor total de $${valorTotal}.`); } else { console.log("El producto no estรก en stock."); } } public mostrarArticulosVendidos(): void { console.log("Productos vendidos:"); this.articulosVendidos.forEach((articulo: ArticuloVendido) => { console.log(`${articulo.cantidadVendida} ${articulo.nombre}(s) - Valor por unidad: $${articulo.valor}`); }); } }
import React, { useState } from "react"; import { FaUser } from "react-icons/fa"; import { toast } from "react-toastify"; import { useAppDispatch } from "../app/hooks"; import { createClient } from "../features/clients/clientsSlice"; export default function AddClientModal() { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [phone, setPhone] = useState(""); const dispatch = useAppDispatch(); const onSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (name === "" || email === "" || phone === "") { return toast.error("Please fill in all fields"); } dispatch(createClient({ name, email, phone })); setName(""); setEmail(""); setPhone(""); }; return ( <> <button type="button" className="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#addClientModal" > <div className="d-flex align-items-center"> <FaUser className="icon" /> <div>Add Client</div> </div> </button> <div className="modal fade" id="addClientModal" aria-labelledby="addClientModalLabel" aria-hidden="true" > <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="addClientModalLabel"> Add Client </h5> <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div className="modal-body"> <form onSubmit={onSubmit}> <div className="mb-3"> <label className="form-label">Name</label> <input type="text" className="form-control" id="name" value={name} onChange={(e) => setName(e.target.value)} /> </div> <div className="mb-3"> <label className="form-label">Email</label> <input type="email" className="form-control" id="email" value={email} onChange={(e) => setEmail(e.target.value)} /> </div> <div className="mb-3"> <label className="form-label">Phone</label> <input type="text" className="form-control" id="phone" value={phone} onChange={(e) => setPhone(e.target.value)} /> </div> <button type="submit" data-bs-dismiss="modal" className="btn btn-secondary" > Submit </button> </form> </div> </div> </div> </div> </> ); }
package com.example.forage.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.forage.model.Forageable // TODO: create the database with all necessary annotations, methods, variables, etc. @Database(entities = [Forageable::class], version = 1, exportSchema = false) abstract class ForageDatabase : RoomDatabase() { abstract fun forageableDao(): ForageableDao companion object { @Volatile private var INSTANCE: ForageDatabase? = null fun getDatabase(context: Context): ForageDatabase { return INSTANCE ?: synchronized(this) { val instane = Room.databaseBuilder( context.applicationContext, ForageDatabase::class.java, "forageable_database" ).build() INSTANCE = instane return instane } } } }
#pragma once #include "Object.h" namespace hm { class GameObject; class MonoBehavior; class Transform; class Camera; class MeshRenderer; class Light; class ParticleSystem; class Collider; class RigidBody; class Animator; class AI; class UIText; class Mirror; class AudioSound; enum class ComponentType { Light, Animator, Transform, DebugRenderer, MeshRenderer, RigidBody, Movement, Camera, Collider, NavAgent, Ai, Mirror, ParticleSystem, AudioSound, UIText, // ... MonoBehavior, End, }; enum { FIXED_COMPONENT_COUNT = static_cast<int>(ComponentType::End) - 1, }; class Component : public Object { public: Component(ComponentType _eType); virtual ~Component(); virtual void Initialize() { } virtual void Start() { } virtual void Update() { } virtual void FixedUpdate() { } virtual void FinalUpdate() { } virtual void Render() { } virtual Component* Clone(GameObject* _pGameObject) = 0; ComponentType GetComponentType() const { return meComponentType; } GameObject* GetGameObject() { return mpGameObject; } Transform* GetTransform(); Camera* GetCamera(); MeshRenderer* GetMeshRenderer(); Light* GetLight(); ParticleSystem* GetParticleSystem(); Collider* GetCollider(); RigidBody* GetRigidBody(); Animator* GetAnimator(); AI* GetAI(); UIText* GetUIText(); Mirror* GetMirror(); AudioSound* GetAudioSound(); bool IsPhysicsObject(); private: friend class GameObject; void SetGameObject(GameObject* _pGameObject) { mpGameObject = _pGameObject; } protected: ComponentType meComponentType; GameObject* mpGameObject; }; }
<?php namespace App\Http\Controllers; use App\Models\Klasifikasi; use App\Models\KlasifikasiObat; use App\Models\Obat; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; class KlasifikasiObatController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $obat = Obat::all(); // Mengirim data klasifikasi ke view return view('klasifikasiobat.index', compact('obat')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $obat = Obat::all(); $klasifikasi = Klasifikasi::all(); return view('klasifikasiobat.create',compact('obat','klasifikasi')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request,$id_obat) { $validator = Validator::make($request->all(), [ 'id_klasifikasi' => 'required', ]); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } $klasifikasiobat = KlasifikasiObat::create( [ 'id_obat' => $id_obat, 'id_klasifikasi' => $request->id_klasifikasi, 'added_by' => Auth::id(), ] ); if ($klasifikasiobat) { return redirect('/klasifikasi-obat')->withSuccess('klasifikasi berhasil ditambahkan!'); } else { return redirect()->back()->withErrors('Gagal menambahkan klasifikasi, terjadi kesalahan'); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id_klasifikasi_obat) { $klasifikasiobat = KlasifikasiObat::find($id_klasifikasi_obat); return view('klasifikasiobat.detail', compact('klasifikasiobat')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id_klasifikasi_obat) { $obat = Obat::all(); $klasifikasiobat = KlasifikasiObat::find($id_klasifikasi_obat); return view('klasifikasiobat.edit', compact('klasifikasiobat','obat')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id_klasifikasi_obat) { $validator = Validator::make($request->all(), [ 'id_obat' => 'required', 'id_klasifikasi' => 'required', ]); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } $searchklasifikasi = KlasifikasiObat::find($id_klasifikasi_obat); $klasifikasiobat = $searchklasifikasi->update( [ 'id_obat' => $request->id_obat, 'id_klasifikasi' => $request->id_klasifikasi, 'added_by' => Auth::id(), ] ); if ($klasifikasiobat) { return redirect('/klasifikasi')->withSuccess('klasifikasi berhasil diedit!'); } else { return redirect()->back()->withErrors('Gagal edit klasifikasi, terjadi kesalahan'); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id_klasifikasi_obat) { $searchklasifikasi = KlasifikasiObat::find($id_klasifikasi_obat); $klasifikasiobat = $searchklasifikasi->delete(); if ($klasifikasiobat) { return redirect('/klasifikasi-obat')->withSuccess('klasifikasi berhasil dihapus!'); } else { return redirect()->back()->withErrors('Gagal menghapus klasifikasi, terjadi kesalahan'); } } }
const db = require("../config/dbConfig") const bcrypt = require("bcrypt") const { HttpException } = require("../exceptions/HttpException") const { schema, emailValidator } = require("../middleware/validation.middleware") const getUserService = async (userId) => { const user = await db.user.findOne({ where: { userId: userId }}) if (!user) throw new HttpException(404, "This user does not exist!!!!!") return user } const getAllUserService = async () => { const users = await db.user.findAll({}) return users } const updateUserService = async (userId, userData) => { const user = await db.user.findOne({ where: { userId: userId }}) if(!user) throw new HttpException(404, "This User does not exist") if (userData.userId) throw new HttpException(401, "You are not allowed to change your user ID") if (userData.isAdmin) throw new HttpException(401, "You are not allowed to change your Admin Status") if (userData.email) { if(!emailValidator.validate(userData.email)) throw new HttpException(403, "Invalid Email Address, make sure it's in the format [email protected]") const updateUser = await db.user.update(userData, { where: { userId: userId }}) return updateUser } else if(userData.password) { if(!schema.validate(userData.password)) throw new HttpException(403, "Your Password is Invalid, it must contain uppercase letters, lowercase letters, no white spaces and at least 2 digits") const salt = await bcrypt.genSalt(10) userData.password = await bcrypt.hash(userData.password, salt) const updateUser = await db.user.update(userData, { where: { userId: userId }}) return updateUser } else { const updateUser = await db.user.update(userData, { where: { userId: userId }}) return updateUser } } const deleteUserService = async (userId) => { const user = await db.user.findOne({ where: { userId: userId }}) if(!user) throw new HttpException(404, "This user does not Exist!!!") await db.user.destroy({ where: { userId: userId }}) return user } //GET USER DATA AND IT'S CORRESPONDING TRANSACTIONS COMBINED IN ONE ENDPOINT const getUserAndTransactions = async (userId) => { const user = await db.user.findOne({ where: { userId: userId }}) if (!user) throw new HttpException(404, "This user does not exist") const userAndTransactions = await db.user.findOne( { where: { userId: userId }}, { include: db.transaction } ) return userAndTransactions } module.exports = { getUserService, getAllUserService, updateUserService, deleteUserService, getUserAndTransactions }
import java.util.ArrayList; import java.util.Arrays; import java.util.Random; /*ะ—ะฐะดะฐั‡ะฐ ะะฐ ะฒั…ะพะดะต ั„ัƒะฝะบั†ะธั ะฟะพะปัƒั‡ะฐะตั‚ ะฟะฐั€ะฐะผะตั‚ั€ n - ะฝะฐั‚ัƒั€ะฐะปัŒะฝะพะต ั‡ะธัะปะพ. ะะตะพะฑั…ะพะดะธะผะพ ัะณะตะฝะตั€ะธั€ะพะฒะฐั‚ัŒ n-ะผะฐััะธะฒะพะฒ, ะทะฐะฟะพะปะฝะธั‚ัŒ ะธั… ัะปัƒั‡ะฐะนะฝั‹ะผะธ ั‡ะธัะปะฐะผะธ, ะบะฐะถะดั‹ะน ะผะฐััะธะฒ ะธะผะตะตั‚ ัะปัƒั‡ะฐะนะฝั‹ะน ั€ะฐะทะผะตั€. ะ ะฐะทะผะตั€ั‹ ะผะฐััะธะฒะพะฒ ะฝะต ะดะพะปะถะฝั‹ ัะพะฒะฟะฐะดะฐั‚ัŒ. ะ”ะฐะปะตะต ะฝะตะพะฑั…ะพะดะธะผะพ ะพั‚ัะพั€ั‚ะธั€ะพะฒะฐั‚ัŒ ะผะฐััะธะฒั‹. ะœะฐััะธะฒั‹ ั ั‡ะตั‚ะฝั‹ะผ ะฟะพั€ัะดะบะพะฒั‹ะผ ะฝะพะผะตั€ะพะผ ะพั‚ัะพั€ั‚ะธั€ะพะฒะฐั‚ัŒ ะฟะพ ะฒะพะทั€ะฐัั‚ะฐะฝะธัŽ, ั ะฝะตั‡ะตั‚ะฝั‹ะผ ะฟะพั€ัะดะบะพะฒั‹ะผ ะฝะพะผะตั€ะพะผ - ะฟะพ ัƒะฑั‹ะฒะฐะฝะธัŽ. ะะฐ ะฒั‹ั…ะพะดะต ั„ัƒะฝะบั†ะธั ะดะพะปะถะฝะฐ ะฒะตั€ะฝัƒั‚ัŒ ะผะฐััะธะฒ ั ะพั‚ัะพั€ั‚ะธั€ะพะฒะฐะฝะฝั‹ะผะธ ะผะฐััะธะฒะฐะผะธ.*/ public class Main { public static void main(String[] args) { int n = 5; // ะบะพะปะธั‡ะตัั‚ะฒะพ ะผะฐััะธะฒะพะฒ ArrayList<int[]> arrays = sortingArrays(n); for (int i = 0; i < n; i++) { System.out.println("ะœะฐััะธะฒ " + (i+1) + " (ะดะปะธะฝะฐ " + arrays.get(i).length + "): "); for (int j = 0; j < arrays.get(i).length; j++) { System.out.print(arrays.get(i)[j] + " "); } System.out.println(); } } public static ArrayList<int[]> createArrays(int n) { ArrayList<int[]> arrays = new ArrayList<>(); ArrayList<Integer> size = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < n; i++) { int length = random.nextInt(n * 4) + 1; // ะดะปะธะฝะฐ ะผะฐััะธะฒะฐ ะพั‚ 1 ะดะพ n*4 while(size.contains(length)) { length = random.nextInt(n * 4) + 1; // // ะดะปะธะฝะฐ ะผะฐััะธะฒะฐ ะพั‚ 1 ะดะพ n*4 } size.add(length); int[] newArray = new int[length]; arrays.add(fillingArrays(newArray)); } return arrays; } public static int[] fillingArrays(int[] arr) { Random random = new Random(); for(int i = 0; i < arr.length; i++) { arr[i] = random.nextInt(100) - 50; // ะทะฐะฟะพะปะฝะตะฝะธะต ะผะฐััะธะฒะฐ ั€ะฐะฝะดะพะผะฝั‹ะผะธ ั‡ะธัะปะฐะผะธ ะพั‚ -50 ะดะพ 50 } return arr; } public static ArrayList<int[]> sortingArrays(int n) { ArrayList<int[]> SortedArrays = createArrays(n); for (int i = 0; i < SortedArrays.size(); i++) { if(i % 2 != 0) { //ะœะฐััะธะฒั‹ ั ั‡ะตั‚ะฝั‹ะผ ะฟะพั€ัะดะบะพะฒั‹ะผ ะฝะพะผะตั€ะพะผ ะพั‚ัะพั€ั‚ะธั€ะพะฒะฐั‚ัŒ ะฟะพ ะฒะพะทั€ะฐัั‚ะฐะฝะธัŽ SortedArrays.set(i, Arrays.stream(SortedArrays.get(i)).sorted().toArray()); } else { // ั ะฝะตั‡ะตั‚ะฝั‹ะผ ะฟะพั€ัะดะบะพะฒั‹ะผ ะฝะพะผะตั€ะพะผ - ะฟะพ ัƒะฑั‹ะฒะฐะฝะธัŽ SortedArrays.set(i, Arrays.stream(SortedArrays.get(i)) .boxed() .sorted((a, b) -> b - a) .mapToInt(Integer::intValue) .toArray() ); } } return SortedArrays; } }
class LocalStorageMock implements Storage { readonly length: number store: { [key: string]: string } constructor() { this.length = 0 this.store = {} } clear() { this.store = {} } getItem(key: string) { return this.store[key] || null } key(index: number) { return null } setItem(key: string, value: string) { this.store[key] = String(value) } removeItem(key: string) { delete this.store[key] } } export default LocalStorageMock
import {Schema, model} from "mongoose"; export interface Product { id: number, title: string, description: string, price: number, images: string[], category: string, rating: number, discountPercentage: number, brand: string, stock: number } const productSchema = new Schema<Product>({ id: { type: Number, required: true, }, title: { type: String, required: true, }, description: { type: String, required: true, }, price: { type: Number, required: true, }, images: [{ type: String, required: true, }], category: { type: String, required: true, }, rating: { type: Number, required: true, }, discountPercentage: { type: Number, required: true, }, brand: { type: String, required: true, }, stock: { type: Number, required: true, }, }); const ProductModel = model('product', productSchema); export default ProductModel;
//THIS FILE WAS COPIED OVER FROM GAMEMINIMAL ON 4/1/2023 public abstract class SpritePhysics extends Sprite { //This is true if this sprite flips its own orientation when an //object collides with it private boolean flip_direction = false; //The percentage of momentum kept by an object //bouncing off of this sprite. //A value over 1.0 means that this object increases //the momentum of objects that hit it. private double elasticity = 1.0; //The percentage of perpendicular momentum //lost by an object bouncing off of this sprite. private double bounce_friction = 0.0; //Whether or not you hit the floor (or are on the floor) //in the most recent frame. //This is only used for platformers. private boolean on_floor = false; //velocity of the sprite private double dx = 0; private double dy = 0; public SpritePhysics(double x, double y, double angle, String image_file, int i_am_bitmask, int i_hit_bitmask) { super(x, y, angle, image_file, i_am_bitmask, i_hit_bitmask); } public void move(double elapsed_seconds) { this.setX(this.getX() + this.dx*elapsed_seconds); this.setY(this.getY() + this.dy*elapsed_seconds); } /** This may only be getting used to have gravity affect non-ballistic objects. */ public void move(double angle, double magnitude) { this.setX(this.getX() + Math.cos(angle) * magnitude); this.setY(this.getY() + Math.sin(angle) * magnitude); } /* Move a fixed amount in the current direction. This is used for incremental movement along a grid. */ public void moveFixed(int magnitude) { this.setX(this.getX() + Math.cos(this.getAngle()) * magnitude); this.setY(this.getY() + Math.sin(this.getAngle()) * magnitude); } public void ballisticAccelerate(double accel, double elapsed_seconds) { this.changeVelocity( Math.cos(this.getAngle())*accel*elapsed_seconds, Math.sin(this.getAngle())*accel*elapsed_seconds); } /* Reduce velocity as if something like friction were applied. decel should be a number between zero and one. */ public void ballisticDecelerate(double decel, double elapsed_seconds) { /* Example: If we want to reduce velocity by 10% per second, then decel should be 0.1 and we subtract off 10% * elapsed seconds worth of velocity. dx = dx - dx*decel*elapsed_seconds or simply dx = dx*(1 - decel*elapsed_seconds) */ this.setVelocity( dx*(1-decel*elapsed_seconds), dy*(1-decel*elapsed_seconds)); } /* Reduce velocity on a smaller time scale (milliseconds) to make possible faster deceleration. decel should be a number between zero and one. */ public void ballisticDecelerateMillis(double decel, double elapsed_seconds) { /* Example: If we want to reduce velocity by 10% per millisecond, then decel should be 0.1 */ while(elapsed_seconds > 0.001) { this.setVelocity( dx*(1-decel), dy*(1-decel)); elapsed_seconds -= 0.001; } if(elapsed_seconds > 0) { this.setVelocity( dx*(1-decel*elapsed_seconds), dy*(1-decel*elapsed_seconds)); } } public void changeVelocity(double change_dx, double change_dy) { dx += change_dx; dy += change_dy; } public void setVelocity(double new_dx, double new_dy) { dx = new_dx; dy = new_dy; } /** Return the magnitude of this sprite's velocity vector. */ public double getSpeed() { return Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2)); } public double getdx(){ return dx; } public void setdx(double new_dx){ dx=new_dx; } public double getdy(){ return dy; } public void setdy(double new_dy){ dy=new_dy; } public boolean getFlipDirection(){ return flip_direction; } public void setFlipDirection(boolean flip_direction){ this.flip_direction=flip_direction; } public double getElasticity(){ return elasticity; } public void setElasticity(double elasticity){ this.elasticity=elasticity; } public double getBounceFriction(){ return bounce_friction; } public void setBounceFriction(double bounce_friction){ this.bounce_friction=bounce_friction; } public boolean getOnFloor(){ return on_floor; } public void setOnFloor(boolean on_floor){ this.on_floor=on_floor; } /** The takeDamage method does nothing but should be over-ridden by any sprites that want to implement damage taking. */ public void takeDamage(int damage, Sprite responsible_sprite) { System.out.println("WARNING: Sprite.takeDamage(int damage, Sprite responsible_sprite) called. This should be overridden."); System.exit(0); } /** This empty function is useful for some inheritors * of sprite to implement. If this is not overridden * then it throws an error and exits. */ public void takeDamage(int damage_amount) { System.out.println("WARNING: Sprite.takeDamage(int damage_amount) called. This should be overridden."); System.exit(0); } /** Get a deep copy of this sprite. If this is not overridden then it throws a error and exits. */ public SpritePhysics deepCopy() { System.out.println("WARNING: Sprite.deepCopy called. This should be overridden."); System.exit(0); return null; } /* Handle a collision between this sprite and other. */ abstract void handleCollision(SpritePhysics other); /* Returns true if this sprite collided with other. */ abstract boolean checkCollided(SpritePhysics other); /* Moves the other sprite out of collision with this sprite */ abstract void shoveOut(SpritePhysics other); }
import {C, DefaultKernel, k, X} from "../src/Kernel/DefaultKernel"; import {Mr, specr1, specr2, structure} from "../src/Repeater/Machine"; import Kernel from "../src/Kernel/Kernel"; import Entity from "../src/Entity/Entity"; import Proxy from "../src/Proxy/Proxy"; import {c, c1, H0, iH0, not0, num} from "../src/Numeric/Core"; import Debug from "../src/Debug/Debug"; DefaultKernel.extend(Mr); let MC = new Kernel; const [state, [begin, end]] = MC.label('state', ['begin', 'end']); const [op1] = MC.label('op1', []); const [op2] = MC.label('op2', []); function specC (name : string, s : Entity, o1 : Entity, o2 : Entity) { return C( name, [ C('[state]', [k(state), s]), C('[op1]', [k(op1), o1]), C('[op2]', [k(op2), o2]), ] ); } MC.state( specC('sC0', begin, Proxy, Proxy) ).relation( (s) => { return specC( 'R(sC0)', end, Proxy, C( 'R(sC0*)', [ X(s, op1), X(s, op2) ] ) ); } ); DefaultKernel.extend(MC); let A = C('A', []); let B = C('B', []); let res1 = DefaultKernel.run( specC('test1', begin, A, B) ); Debug.logStructure(X(res1, op2)); let res2 = DefaultKernel.run( specr2( 'test2', specC('C(A,B)', begin, A, B), c(3), state, begin, op1, A ) ); Debug.logStructure(X(res2, structure)); function Cop (A: Entity, B: Entity) { return X( DefaultKernel.run( specC('C()', begin, A, B) ), op2 ); } Debug.logStructure(Cop(A, B)); const Mex = new Kernel; function specex (name : string, o1: Entity, o2: Entity, n: Entity) { return C( name, [ C('[op1]', [k(op1), o1]), C('[op2]', [k(op2), o2]), C('[num]', [k(num), n]), ] ); } Mex.state( specex('sex0', Proxy, Proxy, not0) ).relation( (s) => { return specex( 'R(sex0)', X(s, op1), Cop( X(s, op1), X(s, op2) ), iH0(X(s, num)) ); } ); DefaultKernel.extend(Mex); let res3 = DefaultKernel.run( specex( 'C(A,B)x3', A, B, c(3) ) ); Debug.logStructure( X(res3, op2) );
#include "CppUnitTest.h" #include "../../../Light-Server/src/Commands/CheckPowerCommand.h" #include "../../../Light-Server/src/ValueDomainTypes.h" #include "../../mocks/Mock_WebServer.h" #include "../../../Light-Server/src/LightWebServer.h" #include "../../../Light-Server/src/Orchastrator/IOrchastor.h" #include "../../ExternalDependencies/fakeit.hpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace fakeit; // fakeit mocking framework: https://github.com/eranpeer/FakeIt #define BUFFER_JSON_RESPONSE_SIZE 200 namespace LS { namespace Commands { TEST_CLASS(CheckPower_ExecuteCommand) { public: TEST_METHOD(WhenExecuted_HttpOKSent) { // arrange Mock<ILightWebServer> mockLightWebServer; When(Method(mockLightWebServer, RespondOK)).Return(); Mock<IPixelController> mockPixelController; When(Method(mockPixelController, numPixels)).AlwaysReturn(8); When(Method(mockPixelController, getPixelColor)).AlwaysReturn(0); StaticJsonDocument<BUFFER_JSON_RESPONSE_SIZE> webDoc; FixedSizeCharBuffer webResponse = FixedSizeCharBuffer(1000); CheckPowerCommand command = CheckPowerCommand(&mockLightWebServer.get(), &mockPixelController.get(), &webDoc, &webResponse); // act command.ExecuteCommand(); // assert Verify(Method(mockLightWebServer, RespondOK)); } TEST_METHOD(WhenExecutedNoPixelsOn_CorrectReponseSent) { // arrange Mock<ILightWebServer> mockLightWebServer; When(Method(mockLightWebServer, RespondOK)).Return(); Mock<IPixelController> mockPixelController; When(Method(mockPixelController, numPixels)).AlwaysReturn(8); When(Method(mockPixelController, getPixelColor)).AlwaysReturn(0); StaticJsonDocument<BUFFER_JSON_RESPONSE_SIZE> webDoc; FixedSizeCharBuffer webResponse = FixedSizeCharBuffer(1000); CheckPowerCommand command = CheckPowerCommand(&mockLightWebServer.get(), &mockPixelController.get(), &webDoc, &webResponse); // act command.ExecuteCommand(); // assert int areEqual = strcmp("{\r\n \"power\": \"off\"\r\n}", webResponse.GetBuffer()); Assert::AreEqual<int>(0, areEqual); } TEST_METHOD(WhenExecutedPixels255_CorrectReponseSent) { // arrange Mock<ILightWebServer> mockLightWebServer; When(Method(mockLightWebServer, RespondOK)).Return(); Mock<IPixelController> mockPixelController; When(Method(mockPixelController, numPixels)).AlwaysReturn(8); When(Method(mockPixelController, getPixelColor)).AlwaysReturn(255); StaticJsonDocument<BUFFER_JSON_RESPONSE_SIZE> webDoc; FixedSizeCharBuffer webResponse = FixedSizeCharBuffer(1000); CheckPowerCommand command = CheckPowerCommand(&mockLightWebServer.get(), &mockPixelController.get(), &webDoc, &webResponse); // act command.ExecuteCommand(); // assert int areEqual = strcmp("{\r\n \"power\": \"on\"\r\n}", webResponse.GetBuffer()); Assert::AreEqual<int>(0, areEqual); } TEST_METHOD(WhenExecutedPixels1_CorrectReponseSent) { // arrange Mock<ILightWebServer> mockLightWebServer; When(Method(mockLightWebServer, RespondOK)).Return(); Mock<IPixelController> mockPixelController; When(Method(mockPixelController, numPixels)).AlwaysReturn(8); When(Method(mockPixelController, getPixelColor)).AlwaysReturn(255); StaticJsonDocument<BUFFER_JSON_RESPONSE_SIZE> webDoc; FixedSizeCharBuffer webResponse = FixedSizeCharBuffer(1000); CheckPowerCommand command = CheckPowerCommand(&mockLightWebServer.get(), &mockPixelController.get(), &webDoc, &webResponse); // act command.ExecuteCommand(); // assert int areEqual = strcmp("{\r\n \"power\": \"on\"\r\n}", webResponse.GetBuffer()); Assert::AreEqual<int>(0, areEqual); } }; } }
import React, { useState, useEffect} from 'react'; import { PageHeader } from 'antd'; import PostPreview from '../../components/post-preview/post-preview.component'; import _ from 'lodash'; import db from '../../firebase'; import './blog.style.css' /* This is Blog page, it shows all the posts from firebase and displays in post-previwe component*/ const Blog = (props) => { const [posts, setPosts] = useState([]); useEffect(() => { let postRef = db.collection('users').doc(props.user.uid).collection('posts'); postRef .onSnapshot(async posts => { let postsData = await posts.docs.map(post => { let data = post.data(); let {id} = post; let payload = {id, ...data} return payload }) setPosts(postsData); }); }, []); return ( <div className='blog-container'> <div className='page-header'> <PageHeader title="Blog" subTitle="All posts are shown here" /> </div> <div className='posts-container'> { _.map(posts, (article, index) => { return ( <PostPreview key={article.id} id={article.id} title={_.startCase(article.title)} content={article.content} user={props.user} /> ) }) } </div> </div> ) } export default Blog;
๏ปฟ@inject IAdviserService AdviserService @inject IActivityLog ActivityLog @inject ISnackbar Snack @inject AuthenticationStateProvider AuthenticationStateProvider <MudForm Model="@_adviser"> <MudCardContent> <MudTextField @bind-Value="@_adviser.Name" T="string" Class="my-2" AdornmentIcon="@Icons.Material.Filled.Title" Adornment="Adornment.End" Margin="Margin.Dense" IconSize="Size.Small" Immediate="true" Variant="Variant.Outlined" Label="Name" Required="true" RequiredError="Adviser name is required!"> </MudTextField> <MudTextField @bind-Value="@_adviser.Email" T="string" Class="my-2" AdornmentIcon="@Icons.Material.Filled.Abc" Adornment="Adornment.End" Margin="Margin.Dense" IconSize="Size.Small" Immediate="true" Variant="Variant.Outlined" Label="Email" Required="true" RequiredError="Adviser email is required!"> </MudTextField> </MudCardContent> <MudDivider DividerType="DividerType.FullWidth" /> <MudCardActions> <div class="ml-auto "> <MudButton Variant="Variant.Outlined" Color="Color.Inherit" Size="Size.Medium" Class="rounded-0" OnClick="Cancel"> Cancel </MudButton> <MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Medium" Class="rounded-0" OnClick="OnHandleSubmit"> @(AdviserId is not 0 ? "Update" : "Add") </MudButton> </div> </MudCardActions> </MudForm> @code { [CascadingParameter] public MudDialogInstance Dialog { get; set; } [CascadingParameter] Task<AuthenticationState>? Authenticate { get; set; } [Parameter] public string? Username { get; set; } [Parameter] public int AdviserId { get; set; } = new(); private Adviser _adviser = new(); private string? Actor { get; set; } private string? Role { get; set; } protected override async Task OnParametersSetAsync() { if (AdviserId is not 0) { var response = await AdviserService.GetAdviserAsync(AdviserId); _adviser = response; } var customAuthStateProvider = (CustomAuthenticationStateProvider)AuthenticationStateProvider; Authenticate = customAuthStateProvider.GetAuthenticationStateAsync(); if (Authenticate != null) { var account = await Authenticate; if (account.User.Identity?.Name != null) { Actor = account.User.Identity.Name; Role = account.User.IsInRole("Administrator") ? "Administrator" : "User"; } } } private async Task OnHandleSubmit() { if (AdviserId is not 0) { var response = await AdviserService.UpdateAdviserAsync(_adviser); if (response.IsSuccessStatusCode) { var log = await ActivityLog.WriteLog($"{Actor}", $"Add a adviser name: {_adviser.Name}", "INSERT", $"{Role}"); if (log.IsSuccessStatusCode) { Snack.Add("Adviser Edited", Severity.Info); Dialog.Close(DialogResult.Ok(true)); } } Dialog.Close(DialogResult.Ok(true)); } else { bool valid = await IsValidAsync(); if (!valid) { var response = await AdviserService.AddAdviserAsync(_adviser); // Make it this to update if (response.IsSuccessStatusCode) { var log = await ActivityLog.WriteLog($"{Actor}", $"Add a adviser name: [{_adviser.Name}]", "INSERT", $"{Role}"); if (log.IsSuccessStatusCode) { Snack.Add("Adviser program added", Severity.Success); Dialog.Close(DialogResult.Ok(true)); } } } else { Snack.Add("Error Adviser already exist", Severity.Error); Dialog.Close(DialogResult.Ok(true)); } } } void Cancel() => Dialog.Cancel(); private async Task<bool> IsValidAsync() { var advisers = await AdviserService.GetAdvisersAsync(); return advisers.Any(c => c.Name.ToLower().Equals(_adviser.Name.ToLower())); } }
import axios from "../../../api/axios"; import { useState } from "react"; import { useNavigate } from "react-router-dom"; import formbg from "../../../assets/events/formbgfinal.jpg"; import { useAuth } from "../../../context/AuthProvider"; const LoginForm = () => { const navigate = useNavigate(); const { auth, setAuth } = useAuth(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); try { const res = await axios.post( "/api/v1/auth/login", JSON.stringify({ email, password }), { headers: { "Content-Type": "application/json" }, withCredentials: true, } ); const accessToken = res?.data?.accessToken; setAuth({ email, accessToken }); console.log(auth); navigate("/protected"); console.log(JSON.stringify(res?.data)); setEmail(""); setPassword(""); } catch (error) { console.log(error); } }; return ( <> <section style={{ backgroundImage: `url(${formbg})` }} className="bg-no-repeat bg-center bg-cover " > <div className="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0 "> <div className="w-full shadow md:mt-0 sm:max-w-md xl:p-0 bg-transparent"> <div className="p-6 space-y-4 rounded-3xl md:space-y-6 sm:p-8 backdrop-blur-md bg-black/50 "> <h1 className="text-xl font-bold leading-tight tracking-tight md:text-2xl text-white"> Login </h1> <form className="space-y-4 md:space-y-6" onSubmit={(e: React.FormEvent<HTMLFormElement>) => handleSubmit(e) } > <div> <label htmlFor="email" className="block mb-2 text-sm font-medium text-white" > Your email </label> <input onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value) } type="email" name="email" id="email" className=" border sm:text-sm rounded-lg block w-full p-2.5 bg-gray-700 border-gray-600 placeholder-gray-400 text-white focus:ring-blue-500 focus:border-blue-500" placeholder="[email protected]" required /> </div> <div> <label htmlFor="password" className="block mb-2 text-sm font-medium text-white" > Password </label> <input onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value) } type="password" name="password" id="password" placeholder="โ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ข" className=" border sm:text-sm rounded-lg block w-full p-2.5 bg-gray-700 border-gray-600 placeholder-gray-400 text-white focus:ring-blue-500 focus:border-blue-500" required /> </div> <button type="submit" className="w-full text-white bg-blue-500 focus:ring-4 focus:outline-none font-medium rounded-lg text-sm px-5 py-2.5 text-center bg-primary-600 hover:bg-green-500 focus:ring-primary-800" > Login </button> <p className="text-sm font-light text-gray-400"> Don't have an account yet?{" "} <a href="#" className="font-medium hover:underline text-blue-500" > Signup here </a> </p> </form> </div> </div> </div> </section> </> ); }; export default LoginForm;
import * as core from "@actions/core"; import * as github from "@actions/github"; import { RequestError } from "@octokit/request-error"; import { Context } from "@actions/github/lib/context"; export async function requestChanges( token: string, context: Context, commentBody: string, prNumber?: number ) { if (!prNumber) { prNumber = context.payload.pull_request?.number; } if (!prNumber) { core.setFailed( "Event payload missing `pull_request` key, and no `pull-request-number` provided as input." + "Make sure you're triggering this action on the `pull_request` or `pull_request_target` events." ); return; } const client = github.getOctokit(token); core.info(`Creating request changes review for pull request #${prNumber}`); try { await client.pulls.createReview({ owner: context.repo.owner, repo: context.repo.repo, pull_number: prNumber, event: "REQUEST_CHANGES", body: commentBody, }); core.info(`Requested changes pull request #${prNumber}`); } catch (error) { if (error instanceof RequestError) { switch (error.status) { case 401: core.setFailed( `${error.message}. Please check that the \`github-token\` input ` + "parameter is set correctly." ); break; case 403: core.setFailed( `${error.message}. In some cases, the GitHub token used for actions triggered ` + "from `pull_request` events are read-only, which can cause this problem. " + "Switching to the `pull_request_target` event typically resolves this issue." ); break; case 404: core.setFailed( `${error.message}. This typically means the token you're using doesn't have ` + "access to this repository. Use the built-in `${{ secrets.GITHUB_TOKEN }}` token " + "or review the scopes assigned to your personal access token." ); break; case 422: core.setFailed( `${error.message}. This typically happens when you try to request changes the pull ` + "request with the same user account that created the pull request. Try using " + "the built-in `${{ secrets.GITHUB_TOKEN }}` token, or if you're using a personal " + "access token, use one that belongs to a dedicated bot account." ); break; default: core.setFailed(`Error (code ${error.status}): ${error.message}`); } return; } core.setFailed((error as Error).message); return; } }
import React, { useEffect, useState } from "react"; import AdminNav from "../../../components/nav/AdminNav"; import { toast } from "react-toastify"; import { useSelector } from "react-redux"; import { LoadingOutlined } from "@ant-design/icons"; import { createProduct } from "../../../functions/product"; import ProductCreateForm from "../../../components/forms/ProductCreateForm"; import FileUpload from "../../../components/forms/FileUpload"; import { getCategories, getCategorySubs } from "../../../functions/category"; const initialState = { title: "", description: "", price: "", categories: [], category: "", subs: [], shipping: "", quantity: "", images: [], colors: ["Black", "Brown", "Silver", "White", "Blue"], brands: ["Apple", "Samsung", "Microsoft", "Lenovo", "Asur"], color: "", brand: "", }; const ProductCreate = () => { const [values, setValues] = useState(initialState); const [subOptions, setSubOption] = useState([]); const [showSubs, setShowSubs] = useState(false); const [loading, setLoading] = useState(false); // redux const { user } = useSelector((state) => ({ ...state })); useEffect(() => { loadcategories(); }, []); const loadcategories = async () => { try { const res = await getCategories(); setValues({ ...values, categories: res.data }); } catch (error) { if (error.response.status === 400) toast.error(error.response.data); } }; const handleChange = (e) => { setValues({ ...values, [e.target.name]: e.target.value }); }; const handleCategoriesChange = async (e) => { e.preventDefault(); setValues({ ...values, subs: [], category: e.target.value }); const res = await getCategorySubs(e.target.value); console.log(res); setSubOption(res.data); setShowSubs(true); }; const handleSubmit = (e) => { e.preventDefault(); createProduct(values, user.token) .then((res) => { console.log(res); window.alert(`"${res.data.title}" is created`); window.location.reload(); }) .catch((err) => { console.log(err); // if (err.response.status !== 200) toast.error(err.response.data); toast.error(err.response.data.err); }); }; return ( <div className="container-fluid"> <div className="row"> <div className="col-md-2"> <AdminNav /> </div> <div className="col-md-10"> {loading ? <LoadingOutlined spin /> : <h4>Product Create</h4>} <hr /> {/* {JSON.stringify(values.images)} */} <div className="p-3"> <FileUpload values={values} setValues={setValues} setLoading={setLoading} /> </div> <ProductCreateForm handleChange={handleChange} handleSubmit={handleSubmit} values={values} setValues={setValues} handleCategoriesChange={handleCategoriesChange} subOptions={subOptions} showSubs={showSubs} /> </div> </div> </div> ); }; export default ProductCreate;
import SonComponent from "./SonComponent" import PokemonContext from "./PokemonContext" import { useContext, useState } from "react" import PokeImage from "./PokeImage" import Button from "./Button" function GrandfatherComponent() { const [index, setIndex] = useState(1) const context = { index: index, baseUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/", suffix: ".png", } const pokeContext = useContext(PokemonContext) return ( <> <PokemonContext.Provider value={context}> <Button onClick={() => setIndex(index + 3)} label="Next Gen" /> <Button onClick={() => setIndex(index - 3 < 0 ? 1 : index - 3)} label="Previous Gen" /> <h3>Grandfather</h3> <PokeImage baseUrl={pokeContext.baseUrl} index={index} suffix={pokeContext.suffix} /> <SonComponent /> </PokemonContext.Provider> </> ) } export default GrandfatherComponent
package models import ( "fmt" "time" "github.com/go-playground/validator/v10" "gorm.io/gorm" ) type User struct { gorm.Model Username string `json:"username" validate:"required,min=3,max=50" gorm:"uniqueIndex"` Email string `json:"email" gorm:"uniqueIndex" validate:"required,email"` Password string `json:"password" validate:"required,min=6"` Age int `json:"age" validate:"required,gte=18"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` Photos []Photo `json:"photos"` Comments []Comment `json:"comments"` SocialMedias []SocialMedia `json:"social_medias"` ProfileImageURL string `json:"profile_image_url" optional:"true"` } func (u *User) CustomValidationRules(v *validator.Validate) error { if u.Age < 18 { return fmt.Errorf("age must be greater than or equal to 18") } return nil }
const express = require("express"); const morgan = require('morgan') const app = express(); app.use(morgan('dev')) //Este cรณdigo utiliza el middleware morgan con el formato 'dev', que proporciona un formato de registro de solicitudes conciso y fรกcil de leer. Registra informaciรณn como el mรฉtodo HTTP, la ruta, el cรณdigo de estado y el tiempo de respuesta. //Con este cรณdigo, cuando accedes a diferentes rutas, se registrarรก la informaciรณn de la solicitud en la consola gracias a morgan, y las respuestas variarรกn segรบn las rutas y parรกmetros de consulta especificados en tu cรณdigo. app.all('/info', (req, res) => { res.send('server info') }) app.get('/search', (req, res) => { if (req.query.q === `javascript books`){ res.send('list de libros de javacript') }else { res.send('pagina normal') } }) app.get('/hello/:user', (req, res) => { console.log(req.query.user) console.log(req.query.age) res.send(`hello ${req.params.user}`) }) app.listen(3000); console.log(`server on port ${3000}`);
--- title: How to mask sensitive data on Azure Web Application Firewall on Azure Front Door (preview) description: Learn how to mask sensitive data on Azure Web Application Firewall on Azure Front Door. author: vhorne ms.author: victorh ms.service: web-application-firewall ms.topic: how-to ms.date: 04/09/2024 --- # How to mask sensitive data on Azure Web Application Firewall on Azure Front Door (preview) > [!IMPORTANT] > Web Application Firewall on Azure Front Door Sensitive Data Protection is currently in PREVIEW. > See the [Supplemental Terms of Use for Microsoft Azure Previews](https://azure.microsoft.com/support/legal/preview-supplemental-terms/) for legal terms that apply to Azure features that are in beta, preview, or otherwise not yet released into general availability. The Web Application Firewall's (WAF) Log Scrubbing tool helps you remove sensitive data from your WAF logs. It works by using a rules engine that allows you to build custom rules to identify specific portions of a request that contain sensitive data. Once identified, the tool scrubs that information from your logs and replaces it with _*******_. > [!NOTE] > When you enable the log scrubbing feature, Microsoft still retains IP addresses in our internal logs to support critical security features. The following table shows examples of log scrubbing rules that can be used to protect your sensitive data: | Match Variable | Operator | Selector | What gets scrubbed | | --- | --- | --- | --- | | Request Header Names | Equals | keytoblock | {"matchVariableName":"HeaderValue:keytoblock","matchVariableValue":"****"} | | Request Cookie Names | Equals | cookietoblock | {"matchVariableName":"CookieValue:cookietoblock","matchVariableValue":"****"} | | Request Post Arg Names | Equals | var | {"matchVariableName":"PostParamValue:var","matchVariableValue":"****"} | | Request Body JSON Arg Names | Equals | JsonValue | {"matchVariableName":"JsonValue:key","matchVariableValue":"****"} | | Query String Arg Names | Equals | foo | {"matchVariableName":"QueryParamValue:foo","matchVariableValue":"****"} | | Request IP Address* | Equals Any | NULL | {"matchVariableName":"ClientIP","matchVariableValue":"****"} | | Request URI | Equals Any | NULL | {"matchVariableName":"URI","matchVariableValue":"****"} | \* Request IP Address and Request URI rules only support the *equals any* operator and scrubs all instances of the requestor's IP address that appears in the WAF logs. For more information, see [What is Azure Web Application Firewall on Azure Front Door Sensitive Data Protection?](waf-sensitive-data-protection-frontdoor.md) ## Enable Sensitive Data Protection Use the following information to enable and configure Sensitive Data Protection. ### Portal To enable Sensitive Data Protection: 1. Open an existing Front Door WAF policy. 1. Under **Settings**, select **Sensitive data**. 1. On the **Sensitive data** page, select **Enable log scrubbing**. To configure Log Scrubbing rules for Sensitive Data Protection: 1. Under **Log scrubbing rules**, select a **Match variable**. 1. Select an **Operator** (if applicable). 1. Type a **Selector** (if applicable). 1. Select **Save**. Repeat to add more rules. ## Verify Sensitive Data Protection To verify your Sensitive Data Protection rules, open the Front Door firewall log and search for _******_ in place of the sensitive fields. ## Next steps - [Azure Web Application Firewall monitoring and logging](../afds/waf-front-door-monitor.md)
@extends('index') @section('content') <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <div class="card"> <div class="card-header"> <div style="display: flex; justify-content: space-between; align-items: center;"> <div class="panel-heading"> <h3 class="panel-title">Crear Sistema Operativo</h3> </div> <div class="float-right"> <a href="{{ route('windows.create') }}" class="btn btn-info " data-placement="left"> {{ __('Crear Nuevo') }} </a> </div> </div> </div> @if ($message = Session::get('success')) <div class="alert alert-success"> <p>{{ $message }}</p> </div> @endif <div class="panel-body"> <div class="table-responsive"> <table id="demo-dt-basic" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> <thead class="thead"> <tr> <th>No</th> <th>Sistemas Operativos</th> <th></th> </tr> </thead> <tbody> @foreach ($windows as $window) <tr> <td>{{ ++$i }}</td> <td>{{ $window->Windows ??'' }}</td> <td> <form action="{{ route('windows.destroy',$window->id) }}" method="POST"> <a class="btn btn-sm btn-success" href="{{ route('windows.edit',$window->id) }}"><i class="fa fa-fw fa-edit"></i> Editar</a> @csrf @method('DELETE') <button type="submit" class="btn btn-danger btn-sm"><i class="fa fa-fw fa-trash"></i> Eliminar</button> </form> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> {!! $windows->links() !!} </div> </div> </div> @endsection
import React, { useState, useEffect } from 'react'; import { Text, View, StyleSheet, Pressable, Image, Dimensions, ScrollView, ActivityIndicator, Platform, } from 'react-native'; import capelliLogo from '../staticImages/CapelliLogo.png'; // Capelli logo png import cart from '../staticImages/CartImage.png'; // Cart image for items in cart page import account from '../staticImages/AccountImage.png'; // Account image for account page import forwardArrow from '../staticImages/ForwardArrow.png'; // Forward arrow image for account page import accountSelected from '../staticImages/AccountImageSelected.png'; // Image to show the current page - Account page import xButton from '../staticImages/XButton.png'; // Image for x button to exit out of account and cart pages import { getUser, logout} from '../APIFunctions.js'; // Importing API/Async communication functions import { styles } from '../styles.js'; // Importing StyleSheet var { height, width } = Dimensions.get('window'); // Device dimensions export function Account({ navigation, route }) { const [currentUser, currentUserChange] = useState(''); // State for holding the current user const [userLoading, userLoadingChange] = useState(false); // State for checking if current user async function has finished useEffect(() => { // useEffect used to only get the currentUser, if it exists getUser(currentUserChange, userLoadingChange); // Called to get the current user that's logged in, if any user is logged in at all }, []); if (userLoading) { if (currentUser == null || currentUser == '') { // Checking to see if there is no user logged in navigation.replace('Login'); // Go to login page if no user is logged in } userLoadingChange(false); // Changing userLoading back to false after currentUser has loaded } // Function for creating a setting-change Pressable for scrollview function settingChangePressable(text, onpress) { return ( <> <Pressable style={styles.accountChangePressable} onPress={onpress}> <Text style={{ fontSize: 21, fontWeight: 'bold' }}>{text}</Text> <Image source={forwardArrow} style={styles.accountChangePressableArrow} /> </Pressable> {/*View for creating a space between scrollview pressables */} <View style={{ height: height * 0.02, width: '100%' }}></View> </> ); } return ( <> {/*Container for Account page*/} <View style={styles.mainPage}> {/*View for title flexbox*/} <View style={styles.titleContainer}> <Pressable // Pressable for back button onPress={() => { navigation.goBack(); }} style={styles.backButton}> <Image source={xButton} style={styles.backButtonImage} /> </Pressable> <Pressable // Pressable logo to return to home screen style={styles.capelliLogoPressable} onPress={() => { navigation.replace('Home'); }}> <Image source={capelliLogo} style={styles.capelliLogoImage} /> </Pressable> <Pressable // Pressable for shopping cart image onPress={() => { navigation.replace('CartPage'); }} style={[styles.cartPressable, { marginTop: height * -0.14 }]}> <Image source={cart} style={styles.cartImage} /> </Pressable> <Pressable // Pressable for account image - image is different color to show that user is currently on account page onPress={() => {}} style={[styles.accountPressable, { marginTop: height * -0.06 }]}> <Image source={accountSelected} style={styles.accountImage} /> </Pressable> </View> {currentUser == null || currentUser == '' ? ( // Show activity indicator while user is loading <View style={{ flex: 1, justifyContent: 'center' }}> <ActivityIndicator size="large" color="#05acbe" /> </View> ) : ( // If user does exist or is logged in - render the regular account page <View style={styles.body}> <Text style={styles.cartAccountTitle}>Account{'\n'}</Text> <ScrollView> {settingChangePressable('Edit Addresses', function () { navigation.navigate('SelectAddress', { checkout: false }); })} {settingChangePressable('Edit Credentials', function () { navigation.navigate('SelectCredential'); })} <Pressable // Logout button style={styles.submitButton} onPress={() => { logout(currentUser, currentUserChange, userLoadingChange); navigation.replace('Login'); }}> <Text style={{ fontSize: 21, fontWeight: 'bold' }}>LOGOUT</Text> </Pressable> </ScrollView> </View> )} </View> </> ); }
The factory design pattern is a creational design pattern that provides a way to create objects without explicitly specifying the class to be instantiated. It acts like a factory that manufactures different products (objects) based on the request. Here's a breakdown of the concept: ## Components: - Factory Class: This class acts as the central point for object creation. It defines a method (often called create or getProduct) that takes input (e.g., a type identifier) and returns an instance of the appropriate subclass. - Product Interface (or Abstract Class): This defines the common interface or base class for all the objects the factory can create. It specifies the methods that all products must implement. - Concrete Product Classes: These are the actual classes that implement the product interface and represent the specific objects that can be created. They extend the product interface and provide their own implementations for the defined methods. ## Benefits: - Loose Coupling: The code that uses the factory doesn't need to know about the specific concrete product classes. It just interacts with the product interface. This makes the code more flexible and easier to maintain. - Centralized Control: The factory class encapsulates the logic for object creation. You can easily add new product types by creating new concrete product classes without modifying the existing code that uses the factory. - Flexibility: You can decide at runtime which type of object to create based on some condition.
Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration duration, return the earliest time slot that works for both of them and is of duration duration. If there is no common time slot that satisfies the requirements, return an empty array. The format of a time slot is an array of two elements [start, end] representing an inclusive time range from start to end. It is guaranteed that no two availability slots of the same person intersect with each other. That is, for any two time slots [start1, end1] and [start2, end2] of the same person, either start1 > end2 or start2 > end1. Example 1: Input: slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 8 Output: [60,68] Example 2: Input: slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 12 Output: [] Constraints: 1 <= slots1.length, slots2.length <= 10^4 slots1[i].length, slots2[i].length == 2 slots1[i][0] < slots1[i][1] slots2[i][0] < slots2[i][1] 0 <= slots1[i][j], slots2[i][j] <= 10^9 1 <= duration <= 10^6 =======Solution 2===== sort slots1 and slots2 index i point to current slot1 index j point to current slot2 get available time range from slot1 and slot2 there are four available time ranges between slot1 and slot2 1. slot1: --------- slot2: --- in this case, the start time and end time of slot2 is within slot1 2. slot1: --- slot2: --------- 3. slot1: ----- slot2: ----- 4. slot1: ------ slot2: -------- By observing the 4 cases, we can get the following pattern when the time range = min(e1,e2) - max(s1, s2) >= duration, there is an available time range, return [max(s1, s2), max(s1, s2) + duration] otherwise, if e1 < e2, i++ if e1 >= e2, j++ for example, current e2 > current e1, if we move the slot2, then the next s2 > current e2 > current e1. There is definitely no intersection between the next slot2 and current slot1. Therefore, we just need move the slot with a smaller end time. Time Complexity: O(mlogm + nlogn + m + n) = O(mlogm + nlogn), m is the length of slots1, n is the length of slots2 Space Complexity: O(1) =======Solution 2====== merge slots1 and slots2 to one array slots sort slots by start time, then end time in ascending order for example, slots1 = [[10,50],[60,120],[140,210]] slots2 = [[0,15],[60,70]], duration = 8 after sorting, slots = [[0,15],[10,50],[60,70],[60,120],[140,210]] loop through slots if curr start time < previous end time the time range is [curr start time, min(prev end time, curr end time)] if time range >= duration, return [curr start time, curr start time + duration] otherwise, return [] ## Why can we merge two slots? Because it is guaranteed that no two availability slots of the same person intersect with each other. For example, slots1 = [[0,15],[20,50],[60,70]] slots2 = [[60,120],[140,210]] slots = [[0,15],[20,50],[60,70],[60,120],[140,210]] the first three slots are from slots1, and current start time is greater than previous end time. Time Complexity: O((m + n)log(m + n) + m + n) = O((m + n)log(m + n)), m is the length of slots1, n is the length of slots2 Space Complexity: O(m + n) which one is bigger? O((m + n)log(m + n)) = O(mlog(m + n) + nlog(m + n)) > O(mlogm + nlogn)
# GPU ๅŸบ็ก€ GPUๆ˜ฏGraphics Processing Unit๏ผˆๅ›พๅฝขๅค„็†ๅ™จ๏ผ‰็š„็ฎ€็งฐ๏ผŒๅฎƒๆ˜ฏ่ฎก็ฎ—ๆœบ็ณป็ปŸไธญ่ดŸ่ดฃๅค„็†ๅ›พๅฝขๅ’Œๅ›พๅƒ็›ธๅ…ณไปปๅŠก็š„ๆ ธๅฟƒ็ป„ไปถใ€‚GPU็š„ๅ‘ๅฑ•ๅކๅฒๅฏไปฅ่ฟฝๆบฏๅˆฐๅฏน่ฎก็ฎ—ๆœบๅ›พๅฝขๅค„็†้œ€ๆฑ‚็š„ไธๆ–ญๅขž้•ฟ๏ผŒไปฅๅŠๅฏนๅ›พๅƒๆธฒๆŸ“้€Ÿๅบฆๅ’Œ่ดจ้‡็š„ไธๆ–ญ่ฟฝๆฑ‚ใ€‚ไปŽๆœ€ๅˆ็š„็ฎ€ๅ•ๅ›พๅฝขๅค„็†ๅŠŸ่ƒฝๅˆฐๅฆ‚ไปŠ็š„้ซ˜ๆ€ง่ƒฝ่ฎก็ฎ—ๅ’Œๆทฑๅบฆๅญฆไน ๅŠ ้€Ÿๅ™จ๏ผŒGPU็ปๅކไบ†ไธ€็ณปๅˆ—้‡่ฆ็š„ๆŠ€ๆœฏ็ช็ ดๅ’Œๅ‘ๅฑ•่ฝฌๆŠ˜ใ€‚ ๅœจๆŽฅไธ‹ๆฅ็š„ๅ†…ๅฎนไธญ๏ผŒๆˆ‘ไปฌ่ฟ˜ๅฐ†ๆŽข่ฎจGPUไธŽCPU็š„ๅŒบๅˆซ๏ผŒไบ†่งฃๅฎƒไปฌๅœจ่ฎพ่ฎกใ€ๆžถๆž„ๅ’Œ็”จ้€”ไธŠๅญ˜ๅœจๆ˜พ่‘—ๅทฎๅผ‚ใ€‚ๆญคๅค–๏ผŒๆˆ‘ไปฌ่ฟ˜ๅฐ†็ฎ€็Ÿญไป‹็ปไธ€ไธ‹AIๅ‘ๅฑ•ๅ’ŒGPU็š„่”็ณป๏ผŒๅนถๆŽข่ฎจGPUๅœจๅ„็ง้ข†ๅŸŸ็š„ๅบ”็”จๅœบๆ™ฏใ€‚ ้™คไบ†ๅ›พๅฝขๅค„็†ๅ’Œไบบๅทฅๆ™บ่ƒฝ๏ผŒGPUๅœจ็ง‘ๅญฆ่ฎก็ฎ—ใ€ๆ•ฐๆฎๅˆ†ๆžใ€ๅŠ ๅฏ†่ดงๅธๆŒ–็Ÿฟ็ญ‰้ข†ๅŸŸไนŸๆœ‰็€ๅนฟๆณ›็š„ๅบ”็”จใ€‚ๆทฑๅ…ฅไบ†่งฃ่ฟ™ไบ›ๅบ”็”จๅœบๆ™ฏๆœ‰ๅŠฉไบŽๆˆ‘ไปฌๆ›ดๅฅฝๅœฐๅ‘ๆŒฅGPU็š„ๆฝœๅŠ›๏ผŒ่งฃๅ†ณๅ„็งๅคๆ‚่ฎก็ฎ—้—ฎ้ข˜ใ€‚็Žฐๅœจ่ฎฉๆˆ‘ไปฌๆทฑๅ…ฅไบ†่งฃGPU็š„ๅ‘ๅฑ•ๅކๅฒใ€ไธŽCPU็š„ๅŒบๅˆซใ€AIๆ‰€้œ€็š„้‡่ฆๆ€งไปฅๅŠๅ…ถๅนฟๆณ›็š„ๅบ”็”จ้ข†ๅŸŸใ€‚ ## GPU ๅ‘ๅฑ•ๅކๅฒ =======ๅŽ็ปญ่ฆๆณจๆ„ไบŒ็บง็›ฎๅฝ•ๅ’Œไธ€็บง็›ฎๅฝ•็š„ๅŒบๅˆซ ๅœจGPUๅ‘ๅฑ•ๅฒไธŠ๏ผŒ็ฌฌไธ€ไปฃGPUๅฏ่ฟฝๆบฏ่‡ณ1999ๅนดไน‹ๅ‰ใ€‚่ฟ™ไธ€ๆ—ถๆœŸ็š„GPUๅœจๅ›พๅฝขๅค„็†้ข†ๅŸŸ่ฟ›่กŒไบ†ไธ€ๅฎš็š„ๅˆ›ๆ–ฐ๏ผŒ้ƒจๅˆ†ๅŠŸ่ƒฝๅผ€ๅง‹ไปŽCPUไธญๅˆ†็ฆปๅ‡บๆฅ๏ผŒๅฎž็Žฐไบ†้’ˆๅฏนๅ›พๅฝขๅค„็†็š„็กฌไปถๅŠ ้€Ÿใ€‚ๅ…ถไธญ๏ผŒๆœ€ๅ…ทไปฃ่กจๆ€ง็š„ๆ˜ฏๅ‡ ไฝ•ๅค„็†ๅผ•ๆ“Ž๏ผŒๅณGEOMETRY ENGINEใ€‚่ฏฅๅผ•ๆ“Žไธป่ฆ็”จไบŽๅŠ ้€Ÿ3Dๅ›พๅƒๅค„็†๏ผŒไฝ†็›ธ่พƒไบŽๅŽๆฅ็š„GPU๏ผŒๅฎƒๅนถไธๅ…ทๅค‡่ฝฏไปถ็ผ–็จ‹็‰นๆ€งใ€‚่ฟ™ๆ„ๅ‘ณ็€ๅฎƒ็š„ๅŠŸ่ƒฝ็›ธๅฏนๅ—้™๏ผŒๅช่ƒฝๆ‰ง่กŒ้ข„ๅฎšไน‰็š„ๅ›พๅฝขๅค„็†ไปปๅŠก๏ผŒ่€Œๆ— ๆณ•ๅƒ็ŽฐไปฃGPU้‚ฃๆ ท็ตๆดปๅœฐ้€‚ๅบ”ไธๅŒ็š„่ฝฏไปถ้œ€ๆฑ‚ใ€‚ ็„ถ่€Œ๏ผŒๅฐฝ็ฎกๅŠŸ่ƒฝๆœ‰้™๏ผŒ็ฌฌไธ€ไปฃGPU็š„ๅ‡บ็Žฐไธบๅ›พๅฝขๅค„็†้ข†ๅŸŸ็š„็กฌไปถๅŠ ้€Ÿๆ‰“ไธ‹ไบ†้‡่ฆ็š„ๅŸบ็ก€๏ผŒๅฅ ๅฎšไบ†ๅŽ็ปญGPUๆŠ€ๆœฏๅ‘ๅฑ•็š„ๅŸบ็Ÿณใ€‚ ========ๅฐฝๅฏ่ƒฝ้ฟๅ…ไธ€ไธชๆฎต่ฝๅคช้•ฟ๏ผŒ่ฎฐๅพ—ๅˆ†ๆฎต ![็ฌฌไธ€ไปฃGPU](images/gpu/05GPUBase01.png) =======ๅ›พ็‰‡ๅ“ช้‡Œๅผ•็”จๅˆฐไบ†๏ผŸๅ›พ็‰‡ๆ˜ฏ็ฌฌไธ€ไปฃGPU่ฟ˜ๆ˜ฏ็ฌฌไบŒไปฃGPU๏ผŸๆ–‡็ซ ่ฆๅŠ ไธŠๅฆ‚ไธ‹ๅ›พๆ‰€็คบ่ฟ™็ง่‡ช็œผๅ“ˆ ็ฌฌไบŒไปฃGPU็š„ๅ‘ๅฑ•่ทจ่ถŠไบ†1999ๅนดๅˆฐ2005ๅนด่ฟ™ๆฎตๆ—ถๆœŸ๏ผŒๅ…ถ้—ดๅ–ๅพ—ไบ†ๆ˜พ่‘—็š„่ฟ›ๅฑ•ใ€‚1999ๅนด๏ผŒ่‹ฑไผŸ่พพๅ‘ๅธƒไบ†GeForce256ๅ›พๅƒๅค„็†่Šฏ็‰‡๏ผŒ่ฟ™ๆฌพ่Šฏ็‰‡ไธ“ไธบๆ‰ง่กŒๅคๆ‚็š„ๆ•ฐๅญฆๅ’Œๅ‡ ไฝ•่ฎก็ฎ—่€Œ่ฎพ่ฎกใ€‚ไธŽๆญคๅ‰็š„GPU็›ธๆฏ”๏ผŒGeForce256ๅฐ†ๆ›ดๅคš็š„ๆ™ถไฝ“็ฎก็”จไบŽๆ‰ง่กŒๅ•ๅ…ƒ๏ผŒ่€Œไธๆ˜ฏๅƒCPU้‚ฃๆ ท็”จไบŽๅคๆ‚็š„ๆŽงๅˆถๅ•ๅ…ƒๅ’Œ็ผ“ๅญ˜ใ€‚ๅฎƒๆˆๅŠŸๅœฐๅฐ†่ฏธๅฆ‚ๅ˜ๆขไธŽๅ…‰็…ง๏ผˆTRANSFORM AND LIGHTING๏ผ‰็ญ‰ๅŠŸ่ƒฝไปŽCPUไธญๅˆ†็ฆปๅ‡บๆฅ๏ผŒๅฎž็Žฐไบ†ๅ›พๅฝขๅฟซ้€Ÿๅ˜ๆข๏ผŒๆ ‡ๅฟ—็€GPU็š„็œŸๆญฃๅ‡บ็Žฐใ€‚ ้š็€ๆ—ถ้—ด็š„ๆŽจ็งป๏ผŒGPUๆŠ€ๆœฏ่ฟ…้€Ÿๅ‘ๅฑ•ใ€‚ไปŽ2000ๅนดๅˆฐ2005ๅนด๏ผŒGPU็š„่ฟ็ฎ—้€Ÿๅบฆ่ฟ…้€Ÿ่ถ…่ถŠไบ†CPUใ€‚ๅœจ2001ๅนด๏ผŒ่‹ฑไผŸ่พพๅ’ŒATIๅˆ†ๅˆซๆŽจๅ‡บไบ†GeForce3ๅ’ŒRadeon 8500๏ผŒ่ฟ™ไบ›ไบงๅ“่ฟ›ไธ€ๆญฅๆŽจๅŠจไบ†ๅ›พๅฝข็กฌไปถ็š„ๅ‘ๅฑ•ใ€‚ๅ›พๅฝข็กฌไปถ็š„ๆตๆฐด็บฟ่ขซๅฎšไน‰ไธบๆตๅค„็†ๅ™จ๏ผŒ้กถ็‚น็บงๅฏ็ผ–็จ‹ๆ€งๅผ€ๅง‹ๅ‡บ็Žฐ๏ผŒๅŒๆ—ถๅƒ็ด ็บงไนŸๅ…ทๆœ‰ไบ†ๆœ‰้™็š„็ผ–็จ‹ๆ€งใ€‚ ๅฐฝ็ฎกๅฆ‚ๆญค๏ผŒ็ฌฌไบŒไปฃGPU็š„ๆ•ดไฝ“็ผ–็จ‹ๆ€งไป็„ถ็›ธๅฏนๆœ‰้™๏ผŒไธŽ็ŽฐไปฃGPU็›ธๆฏ”ไปๆœ‰ไธ€ๅฎšๅทฎ่ทใ€‚็„ถ่€Œ๏ผŒ่ฟ™ไธ€ๆ—ถๆœŸ็š„GPUๅ‘ๅฑ•ไธบๅŽ็ปญ็š„ๆŠ€ๆœฏ่ฟ›ๆญฅๅฅ ๅฎšไบ†ๅŸบ็ก€๏ผŒไธบๅ›พๅฝขๅค„็†ๅ’Œ่ฎก็ฎ—้ข†ๅŸŸ็š„ๅ‘ๅฑ•ๆ‰“ไธ‹ไบ†ๅšๅฎž็š„ๅŸบ็ก€ใ€‚ ![GPU2](images/gpu/05GPUBase02.png) =======ๅ›พ็‰‡ๅ“ช้‡Œๅผ•็”จๅˆฐไบ†๏ผŸๆ–‡็ซ ่ฆๅŠ ไธŠๅฆ‚ไธ‹ๅ›พๆ‰€็คบ่ฟ™็ง่‡ช็œผๅ“ˆ๏ผŒไธคๅผ ๅ›พๅนถๅˆ—็š„ๅฐฝๅฏ่ƒฝๅˆๅนถๆˆไธ€ๅผ ๅ›พ ไปŽ้•ฟ่ฟœ็œ‹๏ผŒNVIDIA็š„GPUๅœจไธ€ๅผ€ๅง‹ๅฐฑ้€‰ๆ‹ฉไบ†ๆญฃ็กฎ็š„ๆ–นๅ‘MIMD๏ผŒ้€š่ฟ‡G80 Series๏ผŒFermi๏ผŒKeplerๅ’ŒMaxwellๅ››ไปฃ๏ผˆไธ‹ไธ€็ซ ่Š‚ไผšๆœ‰่งฃๆž๏ผ‰ๅคง่ทจๆญฅ่ฟ›ๅŒ–๏ผŒๅฝขๆˆไบ†ๅฎŒๅ–„ๅ’Œๅคๆ‚็š„ๅ‚จๅญ˜ๅฑ‚ๆฌก็ป“ๆž„ๅ’ŒๆŒ‡ไปคๆดพๅ‘/ๆ‰ง่กŒ็ฎก็บฟใ€‚ATI/AMDๅœจไธ€ๅผ€ๅง‹้€‰ๆ‹ฉไบ†VLIW5/4๏ผŒๅณSIMD๏ผŒ้€š่ฟ‡GCNๅ‘MIMD้ ๆ‹ข๏ผŒไฝ†ๆ˜ฏ่ฟ›ๅŒ–ไธๅคŸๅฎŒๅ…จ๏ผˆGCNไธ€ๅผ€ๅง‹ๅฐฑ่ฝๅŽไบŽKepler๏ผ‰๏ผŒๆ‰€ไปฅๅ›พๅฝขๆ€ง่ƒฝๅ’ŒGPGPUๆ•ˆ็އไฝŽไบŽๅฏนๆ‰‹ใ€‚ NVIDIA ๅ’Œ ATIไน‹ไบ‰ๆœฌ่ดจไธŠๆ˜ฏshader็ฎก็บฟไธŽๅ…ถไป–็บน็†๏ผŒROPๅ•ๅ…ƒ้…็ฝฎๆฏ”ไพ‹ไน‹ไบ‰๏ผŒA่ฎคไธบ่ฎก็ฎ—็”จshader่ถŠๅคš่ถŠๅฅฝ๏ผŒ่ฎก็ฎ—ๆ€ง่ƒฝๅผบๅคง๏ผŒN่ฎคไธบ็บน็†ๅ•ๅ…ƒ็”ฑไบŽ็ป“ๆž„ๆ›ด็ฎ€ๅ•็”ตๆ™ถไฝ“ๆ›ดๅฐ‘๏ผŒๅ•ไฝ้ข็งฏ้…็ฝฎ่ตทๆฅๆ›ดๅˆ’็ฎ—๏ผŒ่‡ณไบŽๆธธๆˆๅˆ™ๆ˜ฏ่ถŠๅŽๆœŸ้œ€่ฆ่ฎก็ฎ—็š„ๆฏ”ไพ‹่ถŠ้‡ใ€‚ ็ฌฌไธ‰ไปฃGPU็š„ๅ‘ๅฑ•ไปŽ2006ๅนดๅผ€ๅง‹๏ผŒๅธฆๆฅไบ†ๆ–นไพฟ็š„็ผ–็จ‹็Žฏๅขƒๅˆ›ๅปบ๏ผŒไฝฟๅพ—็”จๆˆทๅฏไปฅ็›ดๆŽฅ็ผ–ๅ†™็จ‹ๅบๆฅๅˆฉ็”จGPU็š„ๅนถ่กŒ่ฎก็ฎ—่ƒฝๅŠ›ใ€‚ๅœจ2006ๅนด๏ผŒ่‹ฑไผŸ่พพๅ’ŒATIๅˆ†ๅˆซๆŽจๅ‡บไบ†CUDA๏ผˆCompute Unified Device Architecture๏ผ‰ๅ’ŒCTM๏ผˆCLOSE TO THE METAL๏ผ‰็ผ–็จ‹็Žฏๅขƒใ€‚ ่ฟ™ไธ€ไธพๆŽชๆ‰“็ ดไบ†GPUไป…้™ไบŽๅ›พๅฝข่ฏญ่จ€็š„ๅฑ€้™๏ผŒๅฐ†GPUๅ˜ๆˆไบ†็œŸๆญฃ็š„ๅนถ่กŒๆ•ฐๆฎๅค„็†่ถ…็บงๅŠ ้€Ÿๅ™จใ€‚CUDAๅ’ŒCTM็š„ๆŽจๅ‡บไฝฟๅพ—ๅผ€ๅ‘่€…ๅฏไปฅๆ›ด็ตๆดปๅœฐๅˆฉ็”จGPU็š„่ฎก็ฎ—่ƒฝๅŠ›๏ผŒไธบ็ง‘ๅญฆ่ฎก็ฎ—ใ€ๆ•ฐๆฎๅˆ†ๆž็ญ‰้ข†ๅŸŸๆไพ›ไบ†ๆ›ดๅคšๅฏ่ƒฝๆ€งใ€‚ 2008ๅนด๏ผŒ่‹นๆžœๅ…ฌๅธๆŽจๅ‡บไบ†ไธ€ไธช้€š็”จ็š„ๅนถ่กŒ่ฎก็ฎ—็ผ–็จ‹ๅนณๅฐOPENCL๏ผˆOpen Computing Language๏ผ‰ใ€‚ไธŽCUDAไธๅŒ๏ผŒOPENCLๅนถไธไธŽ็‰นๅฎš็š„็กฌไปถ็ป‘ๅฎš๏ผŒ่€Œๆ˜ฏไธŽๅ…ทไฝ“็š„่ฎก็ฎ—่ฎพๅค‡ๆ— ๅ…ณ๏ผŒ่ฟ™ไฝฟๅพ—ๅฎƒ่ฟ…้€Ÿๆˆไธบ็งปๅŠจ็ซฏGPU็š„็ผ–็จ‹็Žฏๅขƒไธš็•Œๆ ‡ๅ‡†ใ€‚OPENCL็š„ๅ‡บ็Žฐ่ฟ›ไธ€ๆญฅๆŽจๅŠจไบ†GPUๅœจๅ„็งๅบ”็”จ้ข†ๅŸŸ็š„ๆ™ฎๅŠๅ’Œๅบ”็”จ๏ผŒไธบๅนฟๅคงๅผ€ๅ‘่€…ๆไพ›ไบ†ๆ›ดๅนฟ้˜”็š„ๅˆ›ๆ–ฐ็ฉบ้—ดใ€‚ ็ฌฌไธ‰ไปฃGPU็š„ๅˆฐๆฅไธไป…ๆๅ‡ไบ†GPU็š„่ฎก็ฎ—ๆ€ง่ƒฝ๏ผŒๆ›ด้‡่ฆ็š„ๆ˜ฏไธบๅ…ถๆไพ›ไบ†ๆ›ดไพฟๆทใ€็ตๆดป็š„็ผ–็จ‹็Žฏๅขƒ๏ผŒไฝฟๅพ—GPUๅœจ็ง‘ๅญฆ่ฎก็ฎ—ใ€ๆทฑๅบฆๅญฆไน ็ญ‰้ข†ๅŸŸ็š„ๅบ”็”จๅพ—ไปฅๅนฟๆณ›ๆŽจๅนฟ๏ผŒๆˆไธบ็Žฐไปฃ่ฎก็ฎ—้ข†ๅŸŸไธๅฏๆˆ–็ผบ็š„้‡่ฆ็ป„ๆˆ้ƒจๅˆ†ใ€‚ ไปฅไธ‹ไธบNvidiaๅ’ŒAMD็š„ๅทฅๅ…ท้“พๆžถๆž„็คบๆ„ๅ›พ๏ผš ![GPU4](images/gpu/05GPUBase03.png) ไปฅๅŠไบŒ่€…็š„ๅฏนๆฏ”ๅ›พ๏ผš ![GPU6](images/gpu/05GPUBase04.jpg) =======้œ€่ฆๅŠ ไธŠๆ–‡ๅญ—่งฃ้‡Šๅ›พไธญๅ†…ๅฎนๅ“ˆ ## GPU vs CPU ็ŽฐๅœจๆŽข่ฎจไธ€ไธ‹ CPU ๅ’Œ GPU ๅœจๆžถๆž„ๆ–น้ข็š„ไธป่ฆๅŒบๅˆซ๏ผŒ CPU ๅณไธญๅคฎๅค„็†ๅ•ๅ…ƒ๏ผˆCentral Processing Unit๏ผ‰๏ผŒ่ดŸ่ดฃๅค„็†ๆ“ไฝœ็ณป็ปŸๅ’Œๅบ”็”จ็จ‹ๅบ่ฟ่กŒๆ‰€้œ€็š„ๅ„็ฑป่ฎก็ฎ—ไปปๅŠก๏ผŒ้œ€่ฆๅพˆๅผบ็š„้€š็”จๆ€งๆฅๅค„็†ๅ„็งไธๅŒ็š„ๆ•ฐๆฎ็ฑปๅž‹๏ผŒๅŒๆ—ถ้€ป่พ‘ๅˆคๆ–ญๅˆไผšๅผ•ๅ…ฅๅคง้‡็š„ๅˆ†ๆ”ฏ่ทณ่ฝฌๅ’Œไธญๆ–ญ็š„ๅค„็†๏ผŒไฝฟๅพ— CPU ็š„ๅ†…้ƒจ็ป“ๆž„ๅผ‚ๅธธๅคๆ‚ใ€‚ GPU ๅณๅ›พๅฝขๅค„็†ๅ•ๅ…ƒ๏ผˆGraphics Processing Unit๏ผ‰๏ผŒๅฏไปฅๆ›ด้ซ˜ๆ•ˆๅœฐๅค„็†ๅนถ่กŒ่ฟ่กŒๆ—ถๅคๆ‚็š„ๆ•ฐๅญฆ่ฟ็ฎ—๏ผŒๆœ€ๅˆ็”จไบŽๅค„็†ๆธธๆˆๅ’ŒๅŠจ็”ปไธญ็š„ๅ›พๅฝขๆธฒๆŸ“ไปปๅŠก๏ผŒ็Žฐๅœจ็š„็”จ้€”ๅทฒ่ฟœ่ถ…ไบŽๆญคใ€‚ไธค่€…ๅ…ทๆœ‰็›ธไผผ็š„ๅ†…้ƒจ็ป„ไปถ๏ผŒๅŒ…ๆ‹ฌๆ ธๅฟƒใ€ๅ†…ๅญ˜ๅ’ŒๆŽงๅˆถๅ•ๅ…ƒใ€‚ ![GPU7](images/gpu/05GPUBase05.png) GPU ๅ’Œ CPU ๅœจๆžถๆž„ๆ–น้ข็š„ไธป่ฆๅŒบๅˆซๅŒ…ๆ‹ฌไปฅไธ‹ๅ‡ ็‚น๏ผš 1. **ๅนถ่กŒๅค„็†่ƒฝๅŠ›**๏ผš CPU ๆ‹ฅๆœ‰ๅฐ‘้‡็š„ๅผบๅคง่ฎก็ฎ—ๅ•ๅ…ƒ๏ผˆALU๏ผ‰๏ผŒๆ›ด้€‚ๅˆๅค„็†้กบๅบๆ‰ง่กŒ็š„ไปปๅŠก๏ผŒๅฏไปฅๅœจๅพˆๅฐ‘็š„ๆ—ถ้’Ÿๅ‘จๆœŸๅ†…ๅฎŒๆˆ็ฎ—ๆœฏ่ฟ็ฎ—๏ผŒๆ—ถ้’Ÿๅ‘จๆœŸ็š„้ข‘็އๅพˆ้ซ˜๏ผŒๅคๆ‚็š„ๆŽงๅˆถ้€ป่พ‘ๅ•ๅ…ƒ๏ผˆControl๏ผ‰ๅฏไปฅๅœจ็จ‹ๅบๆœ‰ๅคšไธชๅˆ†ๆ”ฏ็š„ๆƒ…ๅ†ตไธ‹ๆไพ›ๅˆ†ๆ”ฏ้ข„ๆต‹่ƒฝๅŠ›๏ผŒๅ› ๆญค CPU ๆ“…้•ฟ้€ป่พ‘ๆŽงๅˆถๅ’Œไธฒ่กŒ่ฎก็ฎ—๏ผŒๆตๆฐด็บฟๆŠ€ๆœฏ้€š่ฟ‡ๅคšไธช้ƒจไปถๅนถ่กŒๅทฅไฝœๆฅ็ผฉ็Ÿญ็จ‹ๅบๆ‰ง่กŒๆ—ถ้—ดใ€‚GPU ๆŽงๅˆถๅ•ๅ…ƒๅฏไปฅๆŠŠๅคšไธช่ฎฟ้—ฎๅˆๅนถๆˆ๏ผŒ้‡‡็”จไบ†ๆ•ฐ้‡ไผ—ๅคš็š„่ฎก็ฎ—ๅ•ๅ…ƒ๏ผˆALU๏ผ‰ๅ’Œ็บฟ็จ‹๏ผˆThread๏ผ‰๏ผŒๅคง้‡็š„ ALU ๅฏไปฅๅฎž็Žฐ้žๅธธๅคง็š„่ฎก็ฎ—ๅžๅ้‡๏ผŒ่ถ…้…็š„็บฟ็จ‹ๅฏไปฅๅพˆๅฅฝๅœฐๅนณ่กกๅ†…ๅญ˜ๅปถๆ—ถ้—ฎ้ข˜๏ผŒๅ› ๆญคๅฏไปฅๅŒๆ—ถๅค„็†ๅคšไธชไปปๅŠก๏ผŒไธ“ๆณจไบŽๅคง่ง„ๆจก้ซ˜ๅบฆๅนถ่กŒ็š„่ฎก็ฎ—ไปปๅŠกใ€‚ 2. **ๅ†…ๅญ˜ๆžถๆž„**๏ผš CPU ่ขซ็ผ“ๅญ˜ Cache ๅ ๆฎไบ†ๅคง้‡็ฉบ้—ด๏ผŒๅคง้‡็ผ“ๅญ˜ๅฏไปฅไฟๅญ˜ไน‹ๅŽๅฏ่ƒฝ้œ€่ฆ่ฎฟ้—ฎ็š„ๆ•ฐๆฎ๏ผŒๅฏไปฅ้™ไฝŽๅปถๆ—ถ๏ผ› GPU ็ผ“ๅญ˜ๅพˆๅฐ‘ไธ”ไธบ็บฟ็จ‹๏ผˆThread๏ผ‰ๆœๅŠก๏ผŒๅฆ‚ๆžœๅพˆๅคš็บฟ็จ‹้œ€่ฆ่ฎฟ้—ฎไธ€ไธช็›ธๅŒ็š„ๆ•ฐๆฎ๏ผŒ็ผ“ๅญ˜ไผšๅˆๅนถ่ฟ™ไบ›่ฎฟ้—ฎไน‹ๅŽๅ†ๅŽป่ฎฟ้—ฎ DRMA๏ผŒ่Žทๅ–ๆ•ฐๆฎไน‹ๅŽ็”ฑ Cache ๅˆ†ๅ‘ๅˆฐๆ•ฐๆฎๅฏนๅบ”็š„็บฟ็จ‹ใ€‚ GPU ๆ›ดๅคš็š„ๅฏ„ๅญ˜ๅ™จๅฏไปฅๆ”ฏๆŒๅคง้‡ Threadใ€‚ 3. **ๆŒ‡ไปค้›†**๏ผš CPU ็š„ๆŒ‡ไปค้›†ๆ›ดๅŠ ้€š็”จ๏ผŒ้€‚ๅˆๆ‰ง่กŒๅ„็ง็ฑปๅž‹็š„ไปปๅŠก๏ผ› GPU ็š„ๆŒ‡ไปค้›†ไธป่ฆ็”จไบŽๅ›พๅฝขๅค„็†ๅ’Œ้€š็”จ่ฎก็ฎ—๏ผŒๅฆ‚ CUDA ๅ’Œ OpenCLใ€‚ 4. **ๅŠŸ่€—ๅ’Œๆ•ฃ็ƒญ**๏ผšCPU ็š„ๅŠŸ่€—็›ธๅฏน่พƒไฝŽ๏ผŒๆ•ฃ็ƒญ่ฆๆฑ‚ไนŸ็›ธๅฏน่พƒไฝŽ๏ผ›็”ฑไบŽ GPU ็š„้ซ˜ๅบฆๅนถ่กŒ็‰นๆ€ง๏ผŒๅ…ถๅŠŸ่€—้€šๅธธ่พƒ้ซ˜๏ผŒ้œ€่ฆๆ›ดๅฅฝ็š„ๆ•ฃ็ƒญ็ณป็ปŸๆฅไฟๆŒ็จณๅฎš่ฟ่กŒใ€‚ ๅ› ๆญค๏ผŒCPU ๆ›ด้€‚ๅˆๅค„็†้กบๅบๆ‰ง่กŒ็š„ไปปๅŠก๏ผŒๅฆ‚ๆ“ไฝœ็ณป็ปŸใ€ๆ•ฐๆฎๅˆ†ๆž็ญ‰๏ผ›่€Œ GPU ้€‚ๅˆๅค„็†้œ€่ฆ่ฎก็ฎ—ๅฏ†้›†ๅž‹ (Compute-intensive) ็จ‹ๅบๅ’Œๅคง่ง„ๆจกๅนถ่กŒ่ฎก็ฎ—็š„ไปปๅŠก๏ผŒๅฆ‚ๅ›พๅฝขๅค„็†ใ€ๆทฑๅบฆๅญฆไน ็ญ‰ใ€‚ๅœจๅผ‚ๆž„็ณป็ปŸไธญ๏ผŒ GPU ๅ’Œ CPU ็ปๅธธไผš็ป“ๅˆไฝฟ็”จ๏ผŒไปฅๅ‘ๆŒฅๅ„่‡ช็š„ไผ˜ๅŠฟใ€‚ ## AI ๅ‘ๅฑ•ไธŽ GPU GPUไธŽไบบๅทฅๆ™บ่ƒฝ๏ผˆAI๏ผ‰็š„ๅ‘ๅฑ•ๅฏ†ไธๅฏๅˆ†ใ€‚2012ๅนด็š„ไธ€็ณปๅˆ—้‡่ฆไบ‹ไปถๆ ‡ๅฟ—็€GPUๅœจAI่ฎก็ฎ—ไธญ็š„ๅดญ้œฒๅคด่ง’ใ€‚Hintonๅ’ŒAlex Krizhevsky่ฎพ่ฎก็š„AlexNetๆ˜ฏไธ€ไธช้‡่ฆ็š„็ช็ ด๏ผŒไป–ไปฌๅˆฉ็”จไธคๅ—่‹ฑไผŸ่พพGTX 580 GPU่ฎญ็ปƒไบ†ไธคๅ‘จ๏ผŒๅฐ†่ฎก็ฎ—ๆœบๅ›พๅƒ่ฏ†ๅˆซ็š„ๆญฃ็กฎ็އๆๅ‡ไบ†ไธ€ไธชๆ•ฐ้‡็บง๏ผŒๅนถ่ตขๅพ—ไบ†2012ๅนดImageNet็ซž่ต›ๅ† ๅ†›ใ€‚่ฟ™ไธ€ๆˆๅฐฑๅ……ๅˆ†ๅฑ•็คบไบ†GPUๅœจๅŠ ้€Ÿๆทฑๅบฆๅญฆไน ๆจกๅž‹่ฎญ็ปƒไธญ็š„ๅทจๅคงๆฝœๅŠ›ใ€‚ ![GPU9](images/gpu/05GPUBase07.png) ๅŒๆ—ถ๏ผŒ่ฐทๆญŒๅ’Œๅดๆฉ่พพ็ญ‰ๅ›ข้˜Ÿ็š„ๅทฅไฝœไนŸ่ฟ›ไธ€ๆญฅๅผบ่ฐƒไบ†GPUๅœจAI่ฎก็ฎ—ไธญ็š„้‡่ฆๆ€งใ€‚่ฐทๆญŒๅˆฉ็”จ1000ๅฐCPUๆœๅŠกๅ™จๅฎŒๆˆไบ†็Œซ็‹—่ฏ†ๅˆซไปปๅŠก๏ผŒ่€Œๅดๆฉ่พพ็ญ‰ๅˆ™ๅช็”จไบ†3ๅฐGTX680-GPUๆœๅŠกๅ™จ๏ผŒๅ–ๅพ—ไบ†ๅŒๆ ท็š„ๆˆๆžœใ€‚่ฟ™ไธ€ๅฏนๆฏ”ๆ˜พ็คบไบ†GPUๅœจๆทฑๅบฆๅญฆไน ไปปๅŠกไธญ็š„ๆ˜พ่‘—ๅŠ ้€Ÿๆ•ˆๆžœ๏ผŒ่ฟ›ไธ€ๆญฅๆฟ€ๅ‘ไบ†ๅฏนGPUๅœจAI้ข†ๅŸŸ็š„ๅนฟๆณ›ๅบ”็”จใ€‚ ไปŽ2005/2006ๅนดๅผ€ๅง‹๏ผŒไธ€ไบ›็ ”็ฉถไบบๅ‘˜ๅผ€ๅง‹ๅฐ่ฏ•ไฝฟ็”จGPU่ฟ›่กŒAI่ฎก็ฎ—๏ผŒไฝ†็›ดๅˆฐ2012/2013ๅนด๏ผŒGPUๆ‰่ขซๆ›ดๅนฟๆณ›ๅœฐๆŽฅๅ—ใ€‚้š็€ๆทฑๅบฆๅญฆไน ็ฝ‘็ปœๅฑ‚ๆฌก่ถŠๆฅ่ถŠๆทฑใ€็ฝ‘็ปœ่ง„ๆจก่ถŠๆฅ่ถŠๅคง๏ผŒGPU็š„ๅŠ ้€Ÿๆ•ˆๆžœ่ถŠๆฅ่ถŠๆ˜พ่‘—ใ€‚่ฟ™ๅพ—็›ŠไบŽGPU็›ธๆฏ”CPUๆ‹ฅๆœ‰ๆ›ดๅคš็š„็‹ฌ็ซ‹ๅคงๅžๅ้‡่ฎก็ฎ—้€š้“๏ผŒไปฅๅŠ่พƒๅฐ‘็š„ๆŽงๅˆถๅ•ๅ…ƒ๏ผŒไฝฟๅ…ถๅœจ้ซ˜ๅบฆๅนถ่กŒ็š„่ฎก็ฎ—ไปปๅŠกไธญ่กจ็Žฐๅ‡บ่‰ฒใ€‚ ๅ› ๆญค๏ผŒGPUๅœจAIๅ‘ๅฑ•ไธญ็š„ไฝœ็”จๆ„ˆๅ‘ๅ‡ธๆ˜พ๏ผŒๅฎƒไธบๆทฑๅบฆๅญฆไน ็ญ‰ๅคๆ‚ไปปๅŠกๆไพ›ไบ†ๅผบๅคง็š„่ฎก็ฎ—ๆ”ฏๆŒ๏ผŒๅนถๆˆไธบไบ†AI่ฎก็ฎ—็š„ๆ ‡้…ใ€‚ไปŽๅญฆๆœฏ็•Œๅˆฐไบ’่”็ฝ‘ๅคด้ƒจๅŽ‚ๅ•†๏ผŒ้ƒฝๅผ€ๅง‹ๅนฟๆณ›้‡‡็”จGPU๏ผŒๅฐ†ๅ…ถๅผ•ๅ…ฅๅˆฐๅ„่‡ช็š„็”Ÿไบง็ ”ๅ‘็Žฏๅขƒไธญ๏ผŒไธบAIๆŠ€ๆœฏ็š„ๅฟซ้€Ÿๅ‘ๅฑ•ๅ’Œๅบ”็”จๆไพ›ไบ†ๅ…ณ้”ฎๆ”ฏๆŒใ€‚ ![GPU10](images/gpu/05GPUBase08.png) ## GPU ๅ…ถไป–ๅบ”็”จๅœบๆ™ฏ 1. ๆธธๆˆ่ฎพๅค‡๏ผšGPUๅคงไฝ“ๅ†ณๅฎšไบ†ๆธธๆˆๅˆ†่พจ็އใ€็‰นๆ•ˆ่ƒฝๅผ€ๅคš้ซ˜๏ผŒๅฏนไบŽ็”จๆˆท็š„ๆธธๆˆไฝ“้ชŒ่ตทๅˆฐๅ…ณ้”ฎๆ€งไฝœ็”จใ€‚ 2. ๆถˆ่ดน็”ตๅญ๏ผš็›ฎๅ‰ๆ™บ่ƒฝๆ‰‹ๆœบๅธ‚ๅœบๅ ๆฎไบ†ๅ…จ็ƒGPUๅธ‚ๅœบไปฝ้ข็š„ไธปๅฏผๅœฐไฝ๏ผŒๆญคๅค–๏ผŒๆ™บ่ƒฝ้Ÿณ็ฎฑใ€ๆ™บ่ƒฝๆ‰‹็Žฏ/ๆ‰‹่กจใ€VR/AR็œผ้•œ็ญ‰็งปๅŠจๆถˆ่ดน็”ตๅญ้ƒฝๆ˜ฏGPUๆฝœๅœจ็š„ๅธ‚ๅœบใ€‚ 3. ไบ‘็ซฏAIๆœๅŠกๅ™จ๏ผšAIๆœๅŠกๅ™จ้€šๅธธๆญ่ฝฝGPUใ€FPGAใ€ASIC็ญ‰ๅŠ ้€Ÿ่Šฏ็‰‡๏ผŒๅˆฉ็”จCPUไธŽๅŠ ้€Ÿ่Šฏ็‰‡็š„็ป„ๅˆๅฏไปฅๆปก่ถณ้ซ˜ๅžๅ้‡ไบ’่”็š„้œ€ๆฑ‚๏ผŒไธบ่‡ช็„ถ่ฏญ่จ€ๅค„็†ใ€่ฎก็ฎ—ๆœบ่ง†่ง‰ใ€่ฏญ้Ÿณไบคไบ’็ญ‰ไบบๅทฅๆ™บ่ƒฝๅบ”็”จๅœบๆ™ฏๆไพ›ๅผบๅคง็š„็ฎ—ๅŠ›ๆ”ฏๆŒ๏ผŒๆ”ฏๆ’‘AI็ฎ—ๆณ•่ฎญ็ปƒๅ’ŒๆŽจ็†่ฟ‡็จ‹ใ€‚ 4. ่‡ชๅŠจ้ฉพ้ฉถ๏ผšGPUๅ…ผๅ…ทๆŠ€ๆœฏๆˆๆœฌไผ˜ๅŠฟ๏ผŒๅทฒๆˆไธบ่‡ชๅŠจ้ฉพ้ฉถ้ข†ๅŸŸไธปๆตใ€‚ 5. ่พน็ผ˜่ฎก็ฎ—๏ผšๅœจ่พน็ผ˜่ฎก็ฎ—ๅœบๆ™ฏ๏ผŒAI่Šฏ็‰‡ไธป่ฆๆ‰ฟๆ‹…ๆŽจๆ–ญไปปๅŠก๏ผŒ้€š่ฟ‡ๅฐ†็ปˆ็ซฏ่ฎพๅค‡ไธŠ็š„ไผ ๆ„Ÿๅ™จ๏ผˆ้บฆๅ…‹้ฃŽ้˜ตๅˆ—ใ€ๆ‘„ๅƒๅคด็ญ‰๏ผ‰ๆ”ถ้›†็š„ๆ•ฐๆฎไปฃๅ…ฅ่ฎญ็ปƒๅฅฝ็š„ๆจกๅž‹ๆŽจ็†ๅพ—ๅ‡บๆŽจๆ–ญ็ป“ๆžœใ€‚ 6. ๆ™บๆ…งๅฎ‰้˜ฒ๏ผšๅฎ‰้˜ฒๆ‘„ๅƒๅคดๅ‘ๅฑ•็ปๅކไบ†็”ฑๆจกๆ‹Ÿๅ‘ๆ•ฐๅญ—ๅŒ–ใ€ๆ•ฐๅญ—ๅŒ–้ซ˜ๆธ…ๅˆฐ็Žฐๅœจ็š„ๆ•ฐๅญ—ๅŒ–ๆ™บ่ƒฝๆ–นๅ‘็š„ๅ‘ๅฑ•๏ผŒๆœ€ๆ–ฐ็š„ๆ™บ่ƒฝๆ‘„ๅƒๅคด้™คไบ†ๅฎž็Žฐ็ฎ€ๅ•็š„ๅฝ•ใ€ๅญ˜ๅŠŸ่ƒฝๅค–๏ผŒ่ฟ˜ๅฏไปฅๅฎž็Žฐ็ป“ๆž„ๅŒ–ๅ›พๅƒๆ•ฐๆฎๅˆ†ๆžใ€‚ 7. ๅŠ ๅฏ†่ดงๅธ๏ผšๆฏ”็‰นๅธ็ญ‰ๅŠ ๅฏ†่ดงๅธ็š„่กŒๆƒ…็ซ็ˆ†ๅธฆๅŠจ็ŸฟๅกGPU้œ€ๆฑ‚๏ผŒ็Ÿฟๆœบ็ฎ—ๅŠ›็š„ๅคงๅฐๅ†ณๅฎšๆŒ–็Ÿฟ็š„้€Ÿๅบฆ๏ผŒ็ฎ—ๅŠ›่ถŠๅคง๏ผŒๆŒ–็Ÿฟ่ถŠๅฟซใ€‚้™คไบ†ไธปๆต็š„ASIC็Ÿฟๆœบ๏ผŒๅŠ ๅฏ†่ดงๅธๆŒ–็Ÿฟ็”จ็š„ๆœ€ๅคšๅคงๆฆ‚ๆ˜ฏGPU็Ÿฟๆœบไบ†ใ€‚ 8. ๅŒป็–—ๅฝฑๅƒ่ฎพๅค‡๏ผš่ฟ‘ๅนดๆฅ๏ผŒๅœจๆทฑๅบฆๅญฆไน ๅ’ŒGPUๅŠ ้€Ÿ่ฟ็ฎ—ๅฟซ้€Ÿๅ‘ๅฑ•ไน‹ไธ‹๏ผŒไบบๅทฅๆ™บ่ƒฝๆˆไธบๆปก่ถณๅŒป็–—ๅฝฑๅƒ้œ€ๆฑ‚ๆ—ฅ็›Šๅขž้•ฟ็š„ๆŽจๆ‰‹ใ€‚ =======่ฟ™ๆฎตๆŒบๅฅฝ็š„๏ผŒๅŠ ไธŠ่‡ชๅทฑๅ–œๆฌข็š„ๅ†…ๅฎนๅ’Œ็†่งฃ็š„ๅ†…ๅฎน๏ผŒๅคšๅŠ ่‡ชๅทฑ็†่งฃๅ’Œๅ†…ๅฎนๅฐฑๅฏนไบ† ## ๅฐ็ป“ =======ๆœ€ๅฅฝๅŠ ไธ€ๆฎตไธชไบบๆ€ป็ป“ ## ๆœฌ่Š‚่ง†้ข‘ <html> <iframe src="https://player.bilibili.com/player.html?aid=527094407&bvid=BV1sM411T72Q&cid=1082002375&page=1&as_wide=1&high_quality=1&danmaku=0&t=30&autoplay=0" width="100%" height="500" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe> </html> ## ๅผ•็”จ =======ๆณจๆ„ๆ ‡ๅ‡†ๆ ผๅผๅ“Ÿ [1]. [Aๅกๅ’ŒNๅก็š„ๆžถๆž„ๆœ‰ไป€ไนˆๅŒบๅˆซ](https://www.zhihu.com/question/267104699/answer/320361801) [2]. [ไธ€ๆ–‡็œ‹ๅฎŒGPUๅ…ซๅคงๅบ”็”จๅœบๆ™ฏ๏ผŒๆŠข้ฃŸๅƒไบฟ็พŽๅ…ƒๅธ‚ๅœบ](https://zhuanlan.zhihu.com/p/442395604)
<div class="card"> <div class="card-body"> <ng-container *ngIf="btnfiltro"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-12 text-end mb-1"> <ng-container *ngIf="modelo_temp; else elseTemplate"> <button class="btn btn-sm btn-outline-primary" (click)="modelo_temp = null; aplicaFiltro();">Sin filtro {{modelo}}</button> </ng-container> <ng-template #elseTemplate> <button class="btn btn-sm btn-outline-primary" (click)="modelo_temp = modelo; aplicaFiltro();">Con filtro {{modelo}}</button> </ng-template> </div> <div class="col-lg-12 col-md-12 col-sm-12 col-12 mb-3"> <input type="text" id="busqueda-paquete" class="form-control form-control-sm" placeholder="Busqueda de paquete" (keyup)="applyFilter($event)"> </div> </div> </ng-container> <div class="table-responsive mat-elevation-z8"> <table #paquetes="matSort" matSort mat-table [dataSource]="dataSourcePaquetes" multiTemplateDataRows> <ng-container matColumnDef="index"> <th mat-header-cell *matHeaderCellDef mat-sort-header class="text-capitalize " [ngStyle]="{'min-width':(miniColumnas)*.7+'px'}"> index </th> <td mat-cell *matCellDef="let element" class="text-center"> {{element.index + 1}}</td> </ng-container> <ng-container matColumnDef="modelo"> <th mat-header-cell *matHeaderCellDef mat-sort-header class="text-capitalize " [ngStyle]="{'min-width':(miniColumnas)*.7+'px'}"> modelo </th> <td mat-cell *matCellDef="let element" class="text-start"> {{element.modelo }}</td> </ng-container> <ng-container matColumnDef="marca"> <th mat-header-cell *matHeaderCellDef mat-sort-header class="text-capitalize " [ngStyle]="{'min-width':(miniColumnas)*.7+'px'}"> marca </th> <td mat-cell *matCellDef="let element" class="text-start"> {{element.marca + 1}}</td> </ng-container> <ng-container matColumnDef="precio"> <th mat-header-cell *matHeaderCellDef mat-sort-header class="text-capitalize " [ngStyle]="{'min-width':(miniColumnas)*.7+'px'}"> precio </th> <td mat-cell *matCellDef="let element" class="text-center"> {{element.precio | monedas }}</td> </ng-container> <ng-container matColumnDef="costo"> <th mat-header-cell *matHeaderCellDef mat-sort-header class="text-capitalize " [ngStyle]="{'min-width':(miniColumnas)*.7+'px'}"> costo </th> <td mat-cell *matCellDef="let element" class="text-center"> {{element.costo | monedas }}</td> </ng-container> <ng-container matColumnDef="nombre"> <th mat-header-cell *matHeaderCellDef mat-sort-header class="text-capitalize text-end" [ngStyle]="{'min-width':(miniColumnas)*1.3+'px'}"> nombre </th> <td mat-cell *matCellDef="let element" class="td-2"> <strong [ngClass]="{'tipo-mo':element.tipo === 'mo','tipo-refaccion':element.tipo === 'refaccion','tipo-paquete':element.tipo === 'paquete'}"> {{element.nombre | capitalizarUno}}</strong> </td> </ng-container> <ng-container matColumnDef="cantidad"> <th mat-header-cell *matHeaderCellDef mat-sort-header class="text-capitalize" [ngStyle]="{'min-width':(miniColumnas)*.5+'px'}"> cantidad </th> <td mat-cell *matCellDef="let element; let indicePadre = dataIndex" class="text-center"> <input type="number" min="1" max="20" [value]="element.cantidad"> </td> </ng-container> <ng-container matColumnDef="sobrescrito"> <th mat-header-cell *matHeaderCellDef mat-sort-header class="text-capitalize" [ngStyle]="{'min-width':(miniColumnas)*1+'px'}" class="td-2"> precio sobrescrito </th> <td mat-cell *matCellDef="let element; let indicePadre = dataIndex;" class="text-end td-2"> <input type="number" min="0" max="10000" [value]="element.costo"> </td> </ng-container> <ng-container matColumnDef="normal"> <th mat-header-cell *matHeaderCellDef class="text-capitalize text-end" [ngStyle]="{'min-width':(miniColumnas)*1.2+'px'}" > <span class="pointer" style="width: 100%;">normal &nbsp; </span> </th> <td mat-cell *matCellDef="let element" class="text-end"> <ng-container *ngIf="element.costo > 0; else elseTemplate"> {{element.costo * 1.30 | monedas}} </ng-container> <ng-template #elseTemplate> {{element.precio * 1.30 | monedas}} </ng-template> </ng-container> <ng-container matColumnDef="flotilla"> <th mat-header-cell *matHeaderCellDef class="text-capitalize text-end" [ngStyle]="{'min-width':(miniColumnas)*1.2+'px'}" > <!-- (click)="ordenamiento = !ordenamiento; ordenarElementos('flotilla')" --> <span class="pointer" style="width: 100%;">flotilla &nbsp; <!-- <ng-container *ngIf="ordenamiento; else elseOrdenamiento"> <i class="fa fa-arrow-down" aria-hidden="true"></i> </ng-container> <ng-template #elseOrdenamiento> <i class="fa fa-arrow-up" aria-hidden="true"></i> </ng-template> --> </span> </th> <td mat-cell *matCellDef="let element" class="text-end"> {{element.precio | monedas}} </td> </ng-container> <ng-container matColumnDef="opciones"> <th mat-header-cell *matHeaderCellDef class="text-capitalize text-center" [ngStyle]="{'min-width':(miniColumnas)*1+'px'}"> opciones </th> <td mat-cell *matCellDef="let element; let indicePadre = dataIndex" class="text-center"> <!-- <i class="fa fa-edit btn btn-sm btn-success fa-xs m-1" (click)="agregarelementopaquete(!elementoAgregar, element.index)"></i> --> <!-- <ng-container> <i class="fa fa-trash btn btn-sm btn-danger fa-xs m-1" (click)="eliminaElemento(element['index'])"></i> </ng-container> --> <!-- <i class="fas fa-plus"></i> --> <!-- <i class="fas fa-plus btn btn-sm btn-primary" (click)="dataElement( element )"></i> --> <i class="fas fa-plus-circle pointer m-1" (click)="dataElement( element )"></i> </td> </ng-container> <ng-container matColumnDef="expand"> <th mat-header-cell *matHeaderCellDef aria-label="row actions">&nbsp;</th> <td mat-cell *matCellDef="let element"> <ng-container *ngIf="element.tipo === 'paquete'"> <button mat-icon-button aria-label="expand row" (click)="(expandedElement = expandedElement === element ? null : element); $event.stopPropagation()"> <mat-icon *ngIf="expandedElement !== element">keyboard_arrow_down</mat-icon> <mat-icon *ngIf="expandedElement === element">keyboard_arrow_up</mat-icon> </button> </ng-container> </td> </ng-container> <!-- Expanded Content Column - The detail row is made up of this one column that spans across all columns --> <ng-container matColumnDef="expandedDetail"> <td mat-cell *matCellDef="let element;let indexPadre = dataIndex" [attr.colspan]="columnsToDisplayWithExpand.length"> <div class="example-element-detail" [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'"> <div class="row" style="width: 100%;"> <!-- <div class="col-lg-12 col-md-12 col-sm-12 col-12 text-end"> <button type="button" class="btn btn-sm btn-success m-1"> <i class="fa fa-edit fa-xs m-1"></i> Agregar elemento </button> </div> --> <div class="col-lg-12 col-md-12 col-sm-12 col-12"> <div class="table-responsive"> <table class="table"> <thead> <tr> <!-- <th colspan="8" class="col text-center fs-5">U.B {{element.reporte_interno['ub'] | monedas:'%'}}</th> --> </tr> <tr> <th scope="col" class="text-capitalize">#</th> <th scope="col" class="text-capitalize">nombre</th> <th scope="col" class="text-capitalize">cantidad</th> <!-- <th scope="col" class="text-capitalize">costo</th> --> <th scope="col" class="text-capitalize">precio</th> <th scope="col" class="text-capitalize">total</th> <!-- <th scope="col" class="text-capitalize">eliminar</th> --> </tr> </thead> <tbody> <tr *ngFor="let item of element.elementos; let indexHijo = index" class="anima"> <th scope="row" class="text-center">{{indexHijo +1}}</th> <td> <strong [ngClass]="{'tipo-mo':item.tipo === 'mo','tipo-refaccion':item.tipo === 'refaccion','tipo-paquete':item.tipo === 'paquete'}"> {{item.nombre | capitalizarUno}}</strong> </td> <td class="text-center"> {{item.cantidad }} </td> <!-- <td> {{item.costo | monedas}} </td> --> <td class="text-end"> {{item.precio | monedas}} </td> <td class="text-end"> {{item.total | monedas}} </td> </tr> </tbody> </table> </div> </div> </div> <!-- <pre>{{element.elementos | json}}</pre> --> </div> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToDisplayWithExpand" class=""></tr> <tr mat-row *matRowDef="let element; columns: columnsToDisplayWithExpand;" class="example-element-row " [class.example-expanded-row]="expandedElement === element" > <!-- (click)="expandedElement = expandedElement === element ? null : element" --> </tr> <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr> </table> <mat-paginator #paquetesPaginator role="group" [pageSizeOptions]="[10,20, 50, 100]"></mat-paginator> </div> </div> </div>
package ru.yandex.practicum.filmorate.model.film; import lombok.AccessLevel; import lombok.Builder; import lombok.Data; import lombok.experimental.FieldDefaults; import ru.yandex.practicum.filmorate.model.Marker; import ru.yandex.practicum.filmorate.validation.film.FilmReleaseDateConstraint; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; import javax.validation.constraints.Size; import java.time.LocalDate; import java.util.LinkedHashSet; @Data @Builder @FieldDefaults(level = AccessLevel.PRIVATE) public class Film { @NotNull(groups = {Marker.OnUpdate.class}) Long id; @NotBlank(groups = {Marker.OnCreate.class, Marker.OnUpdate.class}) String name; @NotNull(groups = {Marker.OnCreate.class, Marker.OnUpdate.class}) @Size(groups = {Marker.OnCreate.class, Marker.OnUpdate.class}, max = 200) String description; @NotNull(groups = {Marker.OnCreate.class, Marker.OnUpdate.class}) @FilmReleaseDateConstraint(groups = {Marker.OnCreate.class, Marker.OnUpdate.class}) LocalDate releaseDate; @Positive(groups = {Marker.OnCreate.class, Marker.OnUpdate.class}) Integer duration; Double rate; @NotNull(groups = {Marker.OnCreate.class, Marker.OnUpdate.class}) Mpa mpa; LinkedHashSet<Genre> genres; LinkedHashSet<Director> directors; }
# Frontend Mentor - Expenses chart component solution This is a solution to the [Expenses chart component challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/expenses-chart-component-e7yJBUdjwt). Frontend Mentor challenges help you improve your coding skills by building realistic projects. ## Table of contents - [Overview](#overview) - [The challenge](#the-challenge) - [Screenshot](#screenshot) - [Links](#links) - [My process](#my-process) - [Built with](#built-with) - [What I learned](#what-i-learned) - [Continued development](#continued-development) - [Author](#author) ## Overview ### The challenge Users should be able to: - View the bar chart and hover over the individual bars to see the correct amounts for each day - See the current dayโ€™s bar highlighted in a different colour to the other bars - View the optimal layout for the content depending on their deviceโ€™s screen size - See hover states for all interactive elements on the page - **Bonus**: Use the JSON data file provided to dynamically size the bars on the chart ### Screenshot ![desktop design](./expenses-chart-dsk.png) ![mobile design](./expenses-chart-mobile.png) ### Links - Live Site URL: [demo here ](https://expenses-chart-gilt.vercel.app/) ## My process ### Built with - Semantic HTML5 markup - CSS custom properties - TailwindCSS - Vanilla JavaScript ### What I learned I learnt how to fetch json data using the fetch method and also convert the json file using parse method. below is a code snippet of how to fetch data.json and covert the data to an object ```js fetch("/data.json") // fetch the data from the location .then((response) => response.json()) // convert it to an object .then((data) => console.log(data)); // log it and use the data ``` ### Continued development moving on, I want to learn and practice alot on promises, try and catch etc ## Author - Frontend Mentor - [@abteck](https://www.frontendmentor.io/profile/abteck) - Twitter - [@abteck2](https://www.twitter.com/abteck2)
# FOR LOOPS print("FOR LOOP USING RANGE :") for i in range(1, 5): print(i) #FOR LOOP - LIST print("\nFOR LOOP USING LIST") fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) # WHILE LOOP print("\nWHILE LOOP:") count = 0 while count < 5: print(count) count += 1 #NESTED LOOPS print("\nNESTED LOOPS:") for i in range(1, 3): for j in range(1, 3): print(f"({i}, {j})") # LOOPS IN DICTIONARY print("\nLOOPS IN DICTIONARY:") person = {"name": "Huzair", "age": 22, "city": "Salem"} print("Keys:") for key in person: print(key) print("\nValues:") for value in person.values(): print(value) print("\nKey-Value Pairs:") for key, value in person.items(): print(f"{key}: {value}") # ENUMERATE print("\nENUMERATE:") colors = ["red", "green", "blue"] for index, color in enumerate(colors): print(f"Index {index}: {color}") # LOOP CONTROLS print("\nLOOP CONTROLS:") numbers = [1, 2, 3, 4, 5] for num in numbers: if num == 4: break if num == 2: continue print(num) else: print("Loop finished")
/**@autor Gustavo Muniz - Controle e Automaรงรฃo - mat. 818 * @since 17/11/2022 * @version 1.0 * Classe responsรกvel pela criaรงรฃo dos candidatos ร  eleiรงรฃo bem como, * as devidas implementaรงรตes responsรกveis tanto pelo armazenamento dos CPFs dos * usuรกrios quanto pela apuraรงรฃo dos votos de cada candidato. */ package model; import controler.FileManager; import java.io.IOException; import java.util.ArrayList; /** * Classe candidato, esta classe herda da Classe FileManager os mรฉtodos de leitura e escrita em arquivos. */ public class Candidato extends FileManager { private String nome; private int numero; /** * Construtor de canidatos * @param nome recebe o nome do candidato * @param numero numero de voto do candidato * writeTxt(nome, content, append) -> escreve um arquivo inicial sem nada com o nome do candidato * content = null -> arquivo vazio * append = false -> nรฃo salva as informaรงรตes que poderiam estar contidas no arquivo antes da RUN */ // Candidatos: public Candidato(String nome, int numero){ this.nome = nome; this.numero = numero; writeTxt(nome, null, false); } /** * Mรฉtodo de apuraรงรฃo dos votos: * Este mรฉtodo รฉ responsรกvel por escrever no arquivo de cada candidato, * o CPF dos usuรกrios que nele votaram. * @param users recebe todos os usuรกrios que votaram naquele determinado candidato */ public void apurarVotos(User[] users) { for (User u: users) { if(u != null){ if (u.getVoto() == numero){ writeTxt(nome, u.getCpf(), true); } } } } /** * Mรฉtodo de amostragem dos votos: * Este mรฉtodo รฉ responsรกvel por ler o arquivo de cada candidato, * armazenรก-lo em uma Coleรงรฃo e rodar a coleรงรฃo para contar quantos usuรกrios votaram * neste candidato em questรฃo. * @return retorna a quantidade de votos que o candidato teve. * @throws IOException classe que lanรงa a exception. */ public int mostrarVotosApurados() throws IOException { int quantidadeVotos = 0; ArrayList<String> cpfs = readTxt(nome); for (String s: cpfs) { if (s != null){ quantidadeVotos++; } } return quantidadeVotos; } /** * Getter de nome: * @return devolve o nome do Candidato */ public String getNome() { return nome; } /** * Getter de nรบmero: * @return devolve o nรบmero do Candidato */ public int getNumero() { return numero; } }
<template> <div> <h1>Pengelola Tugas Sederhana</h1> <!-- Form untuk menambahkan tugas baru --> <form-task :tasks="tasks" @add-task="addTask"></form-task> <!-- Daftar tugas --> <task-list :tasks="tasks" @delete-task="deleteTask"></task-list> </div> </template> <script> import FormTask from "./components/FormTask.vue"; import TaskList from "./components/ListTask.vue"; export default { components: { FormTask, TaskList, }, data() { return { tasks: [], }; }, methods: { addTask(newTask) { this.tasks.push(newTask); }, deleteTask(index) { this.tasks.splice(index, 1); }, }, }; </script>
package webdav.server.virtual.entity.local; import http.FileSystemPath; import http.server.exceptions.AlreadyExistingException; import http.server.exceptions.NotFoundException; import http.server.exceptions.UserRequiredException; import http.server.exceptions.WrongResourceTypeException; import http.server.message.HTTPEnvRequest; import java.time.Instant; import webdav.server.resource.IResource; import webdav.server.resource.ResourceType; import webdav.server.virtual.contentmutation.IContentMutation; import webdav.server.virtual.entity.standard.IRsLocksProperties; public abstract class RsLocal extends IRsLocksProperties { public RsLocal(String name) { this.name = name; this.creationDate = Instant.now(); } public RsLocal(IResource resource, HTTPEnvRequest env) { this.name = resource.getWebName(env); this.creationDate = resource.getCreationTime(env); } private String name; private final Instant creationDate; private boolean isVisible = true; public static PropertyBuilder createProperties() { return new PropertyBuilder(); } public static class PropertyBuilder extends webdav.server.virtual.entity.PropertyBuilder { public PropertyBuilder() { super("local"); } @Property(name="path") protected String path = ""; @Property(name="content::mutation") protected IContentMutation contentMutation = null; public PropertyBuilder setContentMutation(IContentMutation contentMutation) { this.contentMutation = contentMutation; return this; } public PropertyBuilder setPath(String path) { this.path = path; return this; } } @Override public boolean isVisible(HTTPEnvRequest env) throws UserRequiredException { return isVisible; } public void setVisible(boolean isVisible) { this.isVisible = isVisible; } @Override public String getWebName(HTTPEnvRequest env) throws UserRequiredException { return name; } @Override public Instant getCreationTime(HTTPEnvRequest env) throws UserRequiredException { return creationDate; } @Override public boolean rename(String newName, HTTPEnvRequest env) throws UserRequiredException { this.name = newName; return true; } @Override public boolean exists(HTTPEnvRequest env) throws UserRequiredException { return true; } @Override public boolean isOnTheSameFileSystemWith(IResource resource) { return resource.isInstanceOf(RsLocal.class); } @Override protected IResource generateUndefinedResource(FileSystemPath path, HTTPEnvRequest env) throws UserRequiredException { return new RsLocalGhost(path); } @Override public IResource creates(ResourceType resourceType, HTTPEnvRequest env) throws UserRequiredException { throw new WrongResourceTypeException(); } @Override public IResource creates(IResource resource, HTTPEnvRequest env) throws UserRequiredException { throw new WrongResourceTypeException(); } @Override public boolean moveTo(FileSystemPath oldPath, FileSystemPath newPath, HTTPEnvRequest env) throws UserRequiredException { if(!this.exists(env)) throw new NotFoundException(); IResource oldParent = env.getSettings().getFileManager().getResourceFromPath(oldPath.getParent(), env); IResource newParent = env.getSettings().getFileManager().getResourceFromPath(newPath.getParent(), env); IResource dest = env.getSettings().getFileManager().getResourceFromPath(newPath, env); if(dest.exists(env)) { if(env.getRequest().getHeader("overwrite").toLowerCase().equals("t")) { // overwrite newParent.removeChild(dest, env); dest.delete(env); dest = env.getSettings().getFileManager().getResourceFromPath(newPath, env); } else // no right to overwrite throw new AlreadyExistingException(); } if((dest = dest.creates(this, env)) != null) { oldParent.removeChild(dest, env); newParent.addChild(dest, env); return true; } else return false; } }
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class BookResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable */ public function toArray($request) { return [ 'id'=>(string)$this->id, 'type'=>'Book', 'attributes'=>[ 'name'=>$this->name, 'release_date'=>date('d-m-Y',strtotime($this->release_date)), 'price'=>$this->price, 'pages'=>$this->pages, 'cover'=>$this->cover, 'publisher'=> $this->publisher->name, 'author'=> $this->author->name, 'genre'=>$this->BookGenre, ] ]; } }
/* * IMC2 - an inter-mud communications protocol * * imc-util.c: misc utility functions for IMC * * Copyright (C) 1996,1997 Oliver Jowett <[email protected]> * * 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 (see the file COPYING); if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include "imc.h" #include "utils.h" #include "buffer.h" #include <stdarg.h> /* * I needed to split up imc.c (2600 lines and counting..) so this file now * contains: * * in general: anything which is called from more than one file and is not * obviously an interface function is a candidate for here. * * specifically: * - general string manipulation functions * - flag and state lookup functions * - error logging * - imc_reminfo creation/lookup/deletion * - imc_info lookup * - connection naming * - reconnect setup * - static buffer allocation */ char imc_lasterror[IMC_DATA_LENGTH]; /* last error reported */ /* * Static buffer allocation - greatly reduces IMC's memory footprint */ /* reserves about 64k for static buffers */ #define ssize (IMC_DATA_LENGTH * 4) static char sspace[ssize]; static int soffset; static char *lastalloc; char *imc_getsbuf(int len) { char *buf; if (soffset >= (ssize - len)) soffset = 0; buf = &sspace[soffset]; soffset = (soffset + len) % ssize; *buf = '\0'; lastalloc = buf; return buf; } void imc_shrinksbuf(char *buf) { int offset; if (!buf || buf != lastalloc) return; offset = buf - sspace; soffset = offset + strlen(buf) + 1; } /* * Key/value manipulation */ /* clone packet data */ void IMCData::Clone(const IMCData *n) { int i; for (i = 0; i < IMC_MAX_KEYS; i++) { this->key[i] = n->key[i] ? str_dup(n->key[i]) : NULL; this->value[i] = n->value[i] ? str_dup(n->value[i]) : NULL; } } /* get the value of "key" from "p"; if it isn't present, return "def" */ const char *IMCData::GetKey(const char *key, const char *def) const { int i; for (i = 0; i < IMC_MAX_KEYS; i++) if (this->key[i] && !str_cmp(this->key[i], key)) return this->value[i]; return def; } /* identical to imc_getkey, except get the integer value of the key */ SInt32 IMCData::GetKey(const char *key, int def) const { int i; for (i = 0; i < IMC_MAX_KEYS; i++) if (this->key[i] && !str_cmp(this->key[i], key)) return atoi(this->value[i]); return def; } /* add "key=value" to "p" */ void IMCData::AddKey(const char *key, const char *value) { int i; for (i = 0; i < IMC_MAX_KEYS; i++) { if (this->key[i] && !str_cmp(key, this->key[i])) { FREE(this->key[i]); FREE(this->value[i]); this->key[i] = NULL; this->value[i] = NULL; break; } } if (!value) return; for (i = 0; i < IMC_MAX_KEYS; i++) { if (!this->key[i]) { this->key[i] = str_dup(key); this->value[i] = str_dup(value); return; } } } /* add "key=value" for an integer value */ void IMCData::AddKey(const char *key, int value) { char *temp = get_buffer(20); sprintf(temp, "%d", value); this->AddKey(key, temp); release_buffer(temp); } /* clear all keys in "p" */ void IMCData::Init(void) { int i; for (i = 0; i < IMC_MAX_KEYS; i++) { this->key[i] = NULL; this->value[i] = NULL; } } /* free all the keys in "p" */ void IMCData::Free(void) { int i; for (i = 0; i < IMC_MAX_KEYS; i++) { if (this->key[i]) free(this->key[i]); this->key[i] = NULL; if (this->value[i]) free(this->value[i]); this->value[i] = NULL; } } // Error logging // log a string void imc_logstring(const char *format, ...) { va_list ap; char *buf = get_buffer(IMC_DATA_LENGTH); va_start(ap, format); vsnprintf(buf, IMC_DATA_LENGTH, format, ap); va_end(ap); imc_log(buf); release_buffer(buf); } // log an error (log string and copy to lasterror) void imc_logerror(const char *format, ...) { va_list ap; va_start(ap, format); vsnprintf(imc_lasterror, IMC_DATA_LENGTH, format, ap); va_end(ap); imc_log(imc_lasterror); } // log an error quietly (just copy to lasterror) void imc_qerror(const char *format, ...) { va_list ap; va_start(ap, format); vsnprintf(imc_lasterror, IMC_DATA_LENGTH, format, ap); va_end(ap); } /* log a system error (log string, ": ", string representing errno) */ /* this is particularly broken on SunOS (which doesn't have strerror) */ void imc_lerror(const char *format, ...) { va_list ap; va_start(ap, format); vsnprintf(imc_lasterror, IMC_DATA_LENGTH, format, ap); strcat(imc_lasterror, ": "); strcat(imc_lasterror, strerror(errno)); imc_log(imc_lasterror); } const char *imc_error(void) { return imc_lasterror; } // String manipulation functions, mostly exported // lowercase what void imc_slower(char *what) { char *p = what; while (*p) { *p = tolower(*p); p++; } } // copy src->dest, max count, null-terminate void imc_sncpy(char *dest, const char *src, int count) { strncpy(dest, src, count-1); dest[count-1] = 0; } // return 'mud' from 'player@mud' const char *imc_mudof(const char *fullname) { char *buf = imc_getsbuf(IMC_MNAME_LENGTH); char *where; where = strchr(fullname, '@'); imc_sncpy(buf, where ? where+1 : fullname, IMC_MNAME_LENGTH); imc_shrinksbuf(buf); return buf; } /* return 'player' from 'player@mud' */ const char *imc_nameof(const char *fullname) { char *buf = imc_getsbuf(IMC_PNAME_LENGTH); char *where = buf; int count = 0; while (*fullname && (*fullname != '@') && (count < IMC_PNAME_LENGTH - 1)) *where++ = *fullname++, count++; *where = 0; imc_shrinksbuf(buf); return buf; } /* return 'player@mud' from 'player' and 'mud' */ const char *imc_makename(const char *player, const char *mud) { char *buf = imc_getsbuf(IMC_NAME_LENGTH); imc_sncpy(buf, player, IMC_PNAME_LENGTH); strcat(buf, "@"); imc_sncpy(buf + strlen(buf), mud, IMC_MNAME_LENGTH); imc_shrinksbuf(buf); return buf; } /* return 'e' from 'a!b!c!d!e' */ const char *imc_lastinpath(const char *path) { const char *where; char *buf = imc_getsbuf(IMC_NAME_LENGTH); where = path + strlen(path)-1; while ((*where != '!') && (where >= path)) where--; imc_sncpy(buf, where + 1, IMC_NAME_LENGTH); imc_shrinksbuf(buf); return buf; } /* return 'a' from 'a!b!c!d!e' */ const char *imc_firstinpath(const char *path) { char *buf = imc_getsbuf(IMC_NAME_LENGTH); char *p; for (p = buf; *path && (*path != '!'); *p++ = *path++); *p = 0; imc_shrinksbuf(buf); return buf; } // imc_getarg: extract a single argument (with given max length) from // argument to arg; if arg==NULL, just skip an arg, don't copy it out const char *imc_getarg(const char *argument, char *arg, int length) { int len = 0; while (*argument && isspace(*argument)) argument++; if (arg) while (*argument && !isspace(*argument) && (len < (length - 1))) *arg++ = *argument++, len++; else while (*argument && !isspace(*argument)) argument++; while (*argument && !isspace(*argument)) argument++; while (*argument && isspace(*argument)) argument++; if (arg) *arg = '\0'; return argument; } /* Check for a name in a list */ int imc_hasname(const char *list, const char *name) { const char *p; char *arg = get_buffer(IMC_NAME_LENGTH); p = imc_getarg(list, arg, IMC_NAME_LENGTH); while (*arg) { if (!str_cmp(name, arg)) { release_buffer(arg); return 1; } p = imc_getarg(p, arg, IMC_NAME_LENGTH); } release_buffer(arg); return 0; } /* Add a name to a list */ void imc_addname(char **list, const char *name) { char *buf; if (imc_hasname(*list, name)) return; buf = get_buffer(IMC_DATA_LENGTH); if (*(*list)) sprintf(buf, "%s %s", *list, name); else strcpy(buf, name); if (*list) free(*list); *list = str_dup(buf); release_buffer(buf); } /* Remove a name from a list */ void imc_removename(char **list, const char *name) { char *buf = get_buffer(1000); char *arg = get_buffer(IMC_NAME_LENGTH); const char *p; *buf = 0; p = imc_getarg(*list, arg, IMC_NAME_LENGTH); while (*arg) { if (str_cmp(arg, name)) { if (*buf) strcat(buf, " "); strcat(buf, arg); } p = imc_getarg(p, arg, IMC_NAME_LENGTH); } if (*list) free(*list); *list = str_dup(buf); release_buffer(buf); release_buffer(arg); } /* * Flag interpretation */ /* look up a value in a table */ const char *imc_statename(int value, const IMCFlagType *table) { int i; for (i=0; table[i].name; i++) if (value == table[i].value) return table[i].name; return "unknown"; } /* return the name of a particular set of flags */ const char *imc_flagname(int value, const IMCFlagType *table) { char *buf = imc_getsbuf(100); int i; *buf = 0; for (i = 0; table[i].name; i++) { if (IS_SET(value, table[i].value) == table[i].value) { strcat(buf, table[i].name); strcat(buf, " "); REMOVE_BIT(value, table[i].value); // value &= ~table[i].value; } } if (*buf) buf[strlen(buf)-1] = 0; else strcpy(buf, "none"); imc_shrinksbuf(buf); return buf; } // return the value corresponding to a set of names int imc_flagvalue(const char *name, const IMCFlagType *table) { char *buf = get_buffer(20); int i, value = 0; while (1) { name = imc_getarg(name, buf, 20); if (!*buf) break; for (i = 0; table[i].name; i++) if (!str_cmp(table[i].name, buf)) SET_BIT(value, table[i].value); // value |= table[i].value; } release_buffer(buf); return value; } // return the value corresponding to a name int imc_statevalue(const char *name, const IMCFlagType *table) { SInt32 i, value = -1; char * buf = get_buffer(20); imc_getarg(name, buf, 20); for (i = 0; table[i].name; i++) { if (!str_cmp(table[i].name, buf)) { value = table[i].value; break; } } release_buffer(buf); return value; } // IMCRemInfo handling // find an info entry for "name" IMCRemInfo *imc_find_reminfo(const char *name, int type) { IMCRemInfo *p; LListIterator<IMCRemInfo *> iter(imc_reminfo_list); while((p = iter.Next())) { if ((p->type == IMC_REMINFO_EXPIRED) && !type) continue; if (!str_cmp(name, p->name)) return p; } return NULL; } IMCRemInfo::IMCRemInfo(void) : name(NULL), version(NULL), alive(0), ping(0), type(IMC_REMINFO_NORMAL), hide(0), route(NULL), top_sequence(0) { imc_reminfo_list.Add(this); } IMCRemInfo::~IMCRemInfo(void) { imc_reminfo_list.Remove(this); if (this->name) free(this->name); if (this->version) free(this->version); if (this->route) free(this->route); imc_cancel_event(NULL, this); } /* get info struct for given mud */ IMCInfo *imc_getinfo(const char *mud) { IMCInfo *p; START_ITER(iter, p, IMCInfo *, imc_info_list) { if (!str_cmp(mud, p->name)) break; } END_ITER(iter); return p; } /* get name of a connection */ const char *IMCConnect::GetName(void) { char *buf = imc_getsbuf(IMC_NAME_LENGTH); const char *n; if (this->info) n = this->info->name; else n = "unknown"; sprintf(buf, "%s[%d]", n, this->desc); imc_shrinksbuf(buf); return buf; } /* set up for a reconnect */ void IMCInfo::SetupReconnect(void) { time_t temp; int t; // add a bit of randomness so we don't get too many simultaneous reconnects temp = this->timer_duration + (rand() % 21) - 20; t = imc_next_event(ev_reconnect, this); if ((t >= 0) && (t < temp)) return; this->timer_duration *= 2; if (this->timer_duration > IMC_MAX_RECONNECT_TIME) this->timer_duration = IMC_MAX_RECONNECT_TIME; imc_add_event(temp, ev_reconnect, this, 1); }
import Foundation import UIKit class PetBreedsViewController: UIViewController, LoadingIndicatorViewType { var loadingIndicatorViewController: UIViewController? var petType: PetType private let presenter: PetBreedsPresenterProtocol lazy var paginationView: PaginationView = { let view = PaginationView() view.delegate = self return view }() lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) collectionView.backgroundColor = Colors.lighterBase() return collectionView }() init(presenter: PetBreedsPresenterProtocol, petType: PetType) { self.presenter = presenter self.petType = petType super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() presenter.viewDidLoad() configViews() buildViews() buildConstraints() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: true) configureNavigationBar() } private func configViews() { title = petType.name collectionView.delegate = self collectionView.dataSource = presenter collectionView.register(PetBreedViewCell.self, forCellWithReuseIdentifier: PetBreedViewCell.reuseIdentifier.identifier) } private func buildViews() { view.addSubview(paginationView) view.addSubview(collectionView) } private func buildConstraints() { paginationView.snp.makeConstraints { make in make.top.trailing.leading.equalTo(view.safeAreaLayoutGuide) make.bottom.equalTo(collectionView.snp.top) } collectionView.snp.makeConstraints { make in make.trailing.leading.bottom.equalTo(view.safeAreaLayoutGuide) } } } extension PetBreedsViewController: PetBreedsViewProtocol { func reload() { DispatchQueue.main.async { self.collectionView.reloadData() } } func firstPage() { paginationView.firstPage() } } extension PetBreedsViewController: PaginationViewDelegateProtocol { func nextPage() { presenter.nextPage() } func previousPage() { presenter.previousPage() } } extension PetBreedsViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { CollectionViewLayoutConstants.cellSize(basedOn: collectionView.frame.width) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { .init( top: CollectionViewLayoutConstants.verticalSpacing, left: CollectionViewLayoutConstants.horizontalSpacing, bottom: CollectionViewLayoutConstants.verticalSpacing, right: CollectionViewLayoutConstants.horizontalSpacing ) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { CollectionViewLayoutConstants.horizontalSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { CollectionViewLayoutConstants.verticalSpacing } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { presenter.openPetDetails(index: indexPath.item) } }
#include <array> #include <vector> #include <cmath> #include <gtest/gtest.h> #include "body.hpp" #include "n_body_system.hpp" TEST(NBodySystemTests, TestConstructor) { std::vector<Body> bodies = { Body{}, Body{}, Body{} }; NBodySystem test_system = NBodySystem(bodies); const std::vector<Body>& bodies_out = test_system.getBodies(); // Test if the bodies are the same (not same object, but same values) for (int i = 0; i < 3; i++) { const std::array<double, 3>& pos = bodies[i].position; const std::array<double, 3>& pos_out = bodies_out[i].position; for (int j = 0; j < 3; j++) { EXPECT_EQ(pos[j], pos_out[j]); } } } TEST(NBodySystemTests, TestCalcDistance) { Body body1{ "Body1", 1, {0, 0, 0}, {0, 0, 0} }; Body body2{ "Body2", 1, {1, 1, 1}, {1, 1, 1} }; std::vector<Body> bodies = { body1, body2 }; NBodySystem test_system = NBodySystem(bodies); std::array<double, 3> distance = test_system.calcDistanceVector(body1, body2); for (int i = 0; i < 3; i++) { EXPECT_EQ(distance[i], -1); } } TEST(NBodySystemTests, TestCalcDistanceMagnitude) { std::array<double, 3> distance = { 1, 1, 1 }; NBodySystem test_system = NBodySystem({ Body{}, Body{} }); double magnitude = test_system.calcDistanceMagnitude(distance); EXPECT_EQ(magnitude, std::sqrt(3)); } TEST(NBodySystemTests, TestAcceleration) { Body body1{ "Body1", 1, {0, 0, 0}, {0, 0, 0} }; Body body2{ "Body2", 1, {1, 1, 1}, {1, 1, 1} }; std::vector<Body> bodies = { body1, body2 }; NBodySystem test_system = NBodySystem(bodies); std::array<double, 3> acceleration = test_system.calcAcceleration(body1, body2); for (int i = 0; i < 3; i++) { EXPECT_NE(acceleration[i], 1); } }
contract c10769{ /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner public { // Transfer tokens to owner for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } }
import { selectIsLoggedIn } from 'Redux/Auth/selectors'; import { addContactThunk, deleteContactThunk, fetchContactsThunk, } from 'Redux/Contacts/operations'; import { addFilter } from 'Redux/Contacts/phonebookSlise'; import { selectContactsItems, selectError, selectFilter, selectIsLoading, } from 'Redux/Contacts/sellectors'; import { ContactsList } from 'components/ContactList/ContactList'; import { Filter } from 'components/Filter/Filter'; import { Input } from 'components/Input/Input'; import { Loader } from 'components/Loader/Loader'; import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { toast } from 'react-toastify'; export const Contacts = () => { const dispatch = useDispatch(); const contacts = useSelector(selectContactsItems); const filter = useSelector(selectFilter); const isLoading = useSelector(selectIsLoading); const error = useSelector(selectError); const IsLoggedIn = useSelector(selectIsLoggedIn); useEffect(() => { IsLoggedIn && dispatch(fetchContactsThunk()); }, [dispatch, IsLoggedIn]); const handleAddContact = (name, number) => { const newContact = { name, number }; if (contacts.some(contact => contact.name === name)) { toast(`${name} is already in contacts`, { autoClose: 4000 }); } else { dispatch(addContactThunk(newContact)); } }; const filterContacts = () => { return contacts.filter(contact => contact.name.toLowerCase().includes(filter.toLowerCase()) ); }; const handleSetFilter = event => { const { value } = event.target; dispatch(addFilter(value)); }; const handleDeleteContact = id => { dispatch(deleteContactThunk(id)); }; const filteredContacts = filterContacts(); return ( <div> {error ? ( <h1>{error}</h1> ) : isLoading ? ( <Loader /> ) : ( <div> <section> <div> <Input onSubmit={handleAddContact} /> </div> <ContactsList contacts={filteredContacts} onDeleteContact={handleDeleteContact} /> <Filter onFilterChange={handleSetFilter} filter={filter} /> </section> </div> )} </div> ); };
// TIPOGRAFIA "Kanit" // @import url('https://fonts.googleapis.com/css2?family=Kanit:ital,wght@1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap'); /* RESET DE MARGENES */ * { margin: 0; padding: 0; box-sizing: border-box; } // GENERAL body { background-color: rgb(22, 20, 20); font-family: 'Kanit', sans-serif; } .App { width: auto; height: auto; overflow-x: hidden; } // MOBILE FIRST /* Extra small devices (phones, 320px and down) */ // @media only screen and (max-width: 320px) {} /* PRINCIPALES CONTENEDORES - MAIN CONTAINERS */ .contentAboutme, .contentPortfolio, .contentSkills, .contentContact { & { width: 95%; margin: 5rem auto 1rem; padding: .7rem; border-radius: 1rem; } h2 { text-align: center; font-size: 2rem; font-weight: 400; padding: .3rem; margin: .5rem 0 1rem 0; } } /* BARRA DE NAVEGACION - NAVBAR */ nav { & { background-color: rgb(37, 37, 35); display: flex; justify-content: space-around; position: fixed; top: 0; left: 0; width: 100%; padding: .5rem 0; align-items: center; } /* LOGO */ .nav-logo { width: 70%; height: auto; .app-logo-image { height: 3rem; border: solid .1rem red; box-shadow: 0 0 8px #f4ecff, 0 0 8px #d43f3a, 0 0 2px #d43f3a, 0 0 10px #d43f3a, 0 0 6px #d43f3a, 0 0 20px #d43f3a, 0 0 20px #d43f3a, 0 0 1px #d43f3a, 0 0 12px #d43f3a; } } .nav-menu { & { display: flex; flex-direction: column; list-style: none; position: absolute; right: 0%; top: 4rem; width: 100%; padding: 0 1rem 1rem 1rem; background-color: rgb(37, 37, 35); transform: translateX(-100%); transition: transform 0.5s ease-in; } &.active { transform: translateX(0%); border-bottom: 0.1rem solid rgb(255, 199, 1); } .nav-link { & { display: flex; justify-content: center; align-items: center; text-align: center; height: 2.5rem; text-decoration: none; letter-spacing: .5px; color: white; border: 0.08rem solid white; border-radius: 0.5rem; transition: all 0.4s ease-in-out; } &:hover { color: #e1e446; border: 0.08rem solid rgba(248, 5, 5, 0.822); cursor: pointer; } &:focus { border: 0.2rem solid rgb(232, 248, 5); text-shadow: 0 0 1rem #fff, 0 0 5rem #fff, 0 0 5rem #fff, 0 0 10rem #e1e446, 0 0 10rem #e1e446; -webkit-text-fill-color: #f4ecff; -webkit-text-stroke-color: rgb(247, 230, 4); -webkit-text-stroke-width: 0.1rem; } } } .hamburger-toggle { cursor: pointer; color: whitesmoke; display: block; } } /* INICIO - HOME */ .contentHome { & { display: flex; flex-direction: column; min-width: 100%; min-height: 100vh; margin: 5rem auto 1rem; border-radius: 1rem; background-image: url('./assets/images_compress/doubleDragonNeonWall.avif'); background-size: cover; border: solid 0.2rem rgb(214, 12, 12); } h2 { // text-align: left; font-size: 2rem; font-weight: 900; padding-left: 1rem; margin-top: 1rem; /* utilizamos text-shadow (para dar resplandor al texto), text-fill-color (para colorear el interior del texto), text-stroke-color (para el color del borde exterior), y text-stroke-width (para el ancho del borde). */ text-shadow: 0 0 .3rem rgb(174, 9, 207), 0 0 .4rem rgb(140, 18, 189), 0 0 5rem #e44646; -webkit-text-fill-color: #10e8f0; -webkit-text-stroke-color: black; -webkit-text-stroke-width: 0.1rem; // text-shadow: // 0 0 1rem #fff, // 0 0 .2rem #fff, // 0 0 1rem #f70a51; // -webkit-text-fill-color: #fff; // -webkit-text-stroke-color: rgb(8, 0, 1); // -webkit-text-stroke-width: 0.1rem; } p { font-size: 1.95rem; font-weight: 700; // text-align: start; padding-left: 1rem; margin-bottom: .5rem; /* utilizamos text-shadow (para dar resplandor al texto), text-fill-color (para colorear el interior del texto), text-stroke-color (para el color del borde exterior), y text-stroke-width (para el ancho del borde). */ text-shadow: 0 0 .3rem rgb(174, 9, 207), 0 0 .4rem rgb(140, 18, 189), 0 0 5rem #e44646; -webkit-text-fill-color: #b7f708; -webkit-text-stroke-color: black; -webkit-text-stroke-width: 0.1rem; } .-txtHome { & { width: 95%; margin-inline: auto; padding: .7rem; } a { -webkit-text-fill-color: rgb(103, 255, 2); -webkit-text-stroke-color: rgb(236, 49, 164); -webkit-text-stroke-width: .04rem; text-shadow: 2 0 2rem black, 0 0 1rem blue, } p { font-size: 1rem; font-weight: 500; text-align: left; padding: 0; -webkit-text-fill-color: yellow; -webkit-text-stroke-color: black; -webkit-text-stroke-width: .03rem; text-shadow: 0 0 1rem black, 0 0 1rem black, 0 0 1rem blue, 0 0 3rem blue; } } } /* SOBRE MI - ABOUT ME */ .contentAboutme { & { border: solid 0.2rem rgb(234, 250, 4); } .-infoAboutMe { & { display: flex; flex-direction: column-reverse; } /* FOTO DE PERFIL */ .profilePicture { & { display: flex; justify-content: center; } img { width: 70%; height: auto; border-radius: 1rem; } } .txtAboutMe { & { display: flex; flex-direction: column; } p { font-size: 1rem; font-weight: 200; margin-bottom: .7rem; color: #f4ecff; text-align: justify; } a { font-size: 1rem; color: #f4ecff; text-shadow: 0 0 8px #d43f3a, 0 0 2px #d43f3a, 0 0 10px #d43f3a, 0 0 6px #d43f3a, 0 0 20px #d43f3a, 0 0 20px #d43f3a, 0 0 1px #d43f3a, 0 0 12px #d43f3a; } } } /* PASATIEMPOS - HOBBIES */ .containerHobbies { & { width: 100%; margin-bottom: .7rem; display: flex; flex-wrap: wrap; align-items: center; justify-content: center; border: solid .1rem mediumturquoise; } .hobbies { margin: .5rem; width: 2rem; height: 2rem; } } } /* PORTAFOLIO - PORTFOLIO */ .contentPortfolio { & { border: solid 0.2rem rgb(238, 3, 199); } /* CARDS PORTAFOLIO */ .card-deck { & { margin: 0 .5rem .5rem; } .card { & { position: inherit; } .card-body { & { background-color: black; padding: .7rem; } .card-title { color: yellow; font-weight: 300; } .card-text { font-size: 1rem; font-weight: 200; text-align: justify; margin: auto; color: whitesmoke; } .card-note { font-size: .8rem; font-weight: 300; color: wheat; -webkit-text-fill-color: #f3a108; text-align: justify; margin: .8rem; } a { font-size: .75rem; font-weight: 300; display: block; color: #10e8f0; } .chatLauncher { font-size: .75rem; font-weight: 300; color: #10e8f0; background-color: transparent; border: transparent; } } .imgChatBot { height: auto; } } } } /* HABILIDADES - SKILLS */ .contentSkills { & { border: solid 0.2rem rgb(6, 245, 66); } .-containerCardsTecSkills, .-containerCardsSoftSkills { & { display: flex; flex-direction: column; align-items: center; } .cardTecSkills, .cardSoftSkills { & { width: 85%; margin: .2rem; border: solid .1rem; border-radius: .5rem; } .list-group-flush .list-group-item { & { position: inherit; font-size: 1rem; width: 100%; height: 3.5rem; padding: .2rem; display: flex; align-items: center; background: repeating-linear-gradient(45deg, black, transparent 1rem); color: whitesmoke; text-shadow: 0 0 1rem #2cd0f0, 0 0 .1rem #2cd0f0; } .skills { width: 2.5rem; margin: 0.3rem; margin-right: 1rem; } } .item { text-align: center; justify-content: center; } } } } /* CONTACTO - CONTAC ME */ .contentContact { & { display: flex; flex-direction: column; justify-content: space-around; border: solid 0.2rem rgb(248, 7, 128); border-radius: 1rem; } h3 { font-size: 1.5rem; font-weight: 300; text-align: center; margin: 1rem auto 0; } .-contactMe { & { display: flex; flex-direction: column; justify-content: center; align-items: center; } p { font-size: 1rem; font-weight: 200; text-align: justify; padding: 0 .8rem; color: whitesmoke; // EFECTO QUE PRENDE Y APAGA TIPO NEON CON LOS KEYFRAMES DE ABAJO // color: #fff; // -webkit-transition: all 0.5s; // -moz-transition: all 0.5s; // transition: all 0.5s; // -webkit-animation: neon5 2.5s ease-in-out infinite alternate; // -moz-animation: neon5 2.5s ease-in-out infinite alternate; // animation: neon5 2.5s ease-in-out infinite alternate; } a { font-size: 1rem; color: #f4ecff; text-shadow: 0 0 8px #d43f3a, 0 0 2px #d43f3a, 0 0 10px #d43f3a, 0 0 6px #d43f3a, 0 0 20px #d43f3a, 0 0 20px #d43f3a, 0 0 1px #d43f3a, 0 0 12px #d43f3a; } } .-linksContactMe { & { display: flex; flex-direction: column; align-items: center; justify-content: center; } a { font-size: .9rem; color: #fff; -webkit-transition: all 0.5s; -moz-transition: all 0.5s; transition: all 0.5s; -webkit-animation: neon4 2.5s ease-in-out infinite alternate; -moz-animation: neon4 2.5s ease-in-out infinite alternate; animation: neon4 2.5s ease-in-out infinite alternate; margin: .5rem; cursor: pointer; } .iconPdf { width: 2rem; height: 2rem; margin: .5rem; } } } /* REDES SOCIALES - FOOTER */ .containerSocial { & { padding-top: .1rem; } p { font-size: 1rem; font-weight: 300; display: flex; justify-content: left; margin-left: .5rem; margin-bottom: .3rem; -webkit-text-fill-color: #FFFFFF; } .-footerLinks { & { display: flex; justify-content: left; } label { display: flex; align-items: center; font-size: .95rem; font-weight: 200; margin: 0 .5rem; text-decoration: underline; cursor: pointer; } a { display: flex; justify-content: flex-end; align-items: center; margin: 0 .5rem; -webkit-text-fill-color: #f4ecff; text-shadow: 0 0 8px #d43f3a, 0 0 2px #d43f3a, 0 0 10px #d43f3a, 0 0 6px #d43f3a, 0 0 20px #d43f3a, 0 0 20px #d43f3a, 0 0 1px #d43f3a, 0 0 12px #d43f3a; } img { width: 2rem; height: 2rem; margin: 0 .2rem; } .linkedIn { box-shadow: 0 0 .5rem #46aae4, 0 0 .3rem #46aae4, 0 0 .1rem #46aae4; } } } /* MEDIA QUERIES */ /* Extra small devices (phones, 320px and down) */ // @media only screen and (max-width: 320px) {} /* Extra small devices (phones, 375px and down) */ @media only screen and (max-width: 375px) and (min-width: 321px) { /* INICIO - HOME */ .contentHome { & { height: 100vh; } p { padding-left: 1rem; } .-txtHome { & { padding: .5rem; } } } /* SOBRE MI - ABOUT ME */ .contentAboutme { /* PASATIEMPOS - HOBBIES */ .containerHobbies { .hobbies { width: 2rem; height: 2rem; } } } /* PORTAFOLIO - PORTFOLIO */ .contentPortfolio { /* CARDS PORTAFOLIO */ .card-deck { .card { .card-body { & { padding: .9rem; } .card-note { font-size: .9rem; } a { font-size: .85rem; } .chatLauncher { font-size: .85rem; } } } } } /* HABILIDADES - SKILLS */ .contentSkills { .-containerCardsTecSkills, .-containerCardsSoftSkills { .cardTecSkills, .cardSoftSkills { .list-group-flush .list-group-item { & { height: 3.8rem; padding: .4rem; } .skills { width: 3rem; margin: 0.5rem 0; margin-right: 1rem; } } } } } /* CONTACTO - CONTAC ME */ .contentContact { & { height: 100vh; } .-linksContactMe { a { font-size: 1rem; } } } } /* Small devices (portrait tablets and large phones, 425px and up) */ @media only screen and (max-width: 535px) and (min-width: 376px) { /* PRINCIPALES CONTENEDORES - MAIN CONTAINERS */ .contentAboutme, .contentPortfolio, .contentSkills, .contentContact { & { margin: 5rem auto 1rem; padding: .9rem; } h2 { font-size: 2.5rem; } } /* INICIO - HOME */ .contentHome { & { margin: 5rem auto 1rem; min-height: 100vh; } h2, p { text-align: center; padding: 0; } } /* SOBRE MI - ABOUT ME */ .contentAboutme { .-infoAboutMe { .txtAboutMe { p { font-size: 1.1rem; } } } /* PASATIEMPOS - HOBBIES */ .containerHobbies { & { padding: 0 .5rem; margin: 1rem auto; justify-content: space-between; align-items: center; } } } /* PORTAFOLIO - PORTFOLIO */ .contentPortfolio { /* CARDS PORTAFOLIO */ .card-deck { .card { .card-body { & { padding: 1rem; } .card-text { font-size: 1.1rem; } .card-note { font-size: .95rem; } a { font-size: .9rem; } .chatLauncher { font-size: .9rem; } } } } } /* HABILIDADES - SKILLS */ .contentSkills { .-containerCardsTecSkills, .-containerCardsSoftSkills { & { padding: .5rem 0; } .cardTecSkills, .cardSoftSkills { & { width: 65%; } .list-group-flush .list-group-item { & { font-size: 1.1rem; height: 3.8rem; } .skills { width: 3rem; margin-left: 1rem; } } } } } /* CONTACTO - CONTAC ME */ .contentContact { & { min-height: 100vh; } h3 { margin: 1rem auto; } .-contactMe p { font-size: 1.1rem; } .-linksContactMe { a { font-size: 1rem; } } } /* REDES SOCIALES - FOOTER */ .containerSocial { p { margin-left: .8rem; font-size: 1.1rem; } .-footerLinks { & { justify-content: left; } label { margin: 0 1rem; font-size: 1rem; } a { margin: 0; } img { height: 1.8rem; } } } } /* Small devices (portrait tablets and large phones, 768px and up) */ @media only screen and (max-width: 1000px) and (min-width: 536px) { /* PRINCIPALES CONTENEDORES - MAIN CONTAINERS */ .contentAboutme, .contentPortfolio, .contentSkills, .contentContact { & { margin: 5rem auto 1rem; } h2 { font-size: 3rem; } } /* BARRA DE NAVEGACION - NAVBAR */ nav { & { height: auto; } /* LOGO */ .nav-logo { .app-logo-image { height: 3rem; } } .nav-menu { & { flex-direction: row; flex-wrap: wrap; border-bottom: 0.1rem solid rgb(255, 199, 1); top: 4rem; justify-content: space-around; padding: .5rem 1rem .5rem 1rem; } } .nav-link { font-size: .9rem; width: 8rem; height: 2.5rem; } } /* INICIO - HOME */ .contentHome { & { min-height: 100vh; margin: 5rem auto 1rem; } h2 { font-size: 3.5rem; margin-top: 5rem; padding-left: 2.5rem; } p { font-size: 2.8rem; margin-bottom: 2rem; padding-left: 2.5rem; } .-txtHome { p { font-size: 1.1rem; } } } /* SOBRE MI - ABOUT ME */ .contentAboutme { .-infoAboutMe { /* FOTO DE PERFIL */ .profilePicture img { width: 35%; margin-bottom: 1rem; } .txtAboutMe p { font-size: 1.1rem; } } /* PASATIEMPOS - HOBBIES */ .containerHobbies { & { width: fit-content; } .hobbies { margin: .5rem; width: 2.5rem; height: 2.5rem; } } } /* PORTAFOLIO - PORTFOLIO */ .contentPortfolio { /* CARDS PORTAFOLIO */ .card-deck { & { margin: 0 .5rem 1rem; } .card { & { margin: .2rem; } .card-body { & { padding: 1rem .8rem; } .card-text { font-size: 1rem; margin-bottom: .5rem; } .card-note { font-size: .8rem; } a { font-size: .9rem; } .chatLauncher { font-size: .9rem; } } } } } /* HABILIDADES - SKILLS */ .contentSkills { .-containerCardsTecSkills, .-containerCardsSoftSkills { & { flex-wrap: wrap; flex-direction: row; justify-content: space-around; } .cardTecSkills, .cardSoftSkills { & { width: 40%; margin: .3rem; } .list-group-flush .list-group-item { .skills { width: 3rem; margin: 0; margin: .5rem 1rem; } } } } } /* CONTACTO - CONTAC ME */ .contentContact { & { min-height: 100vh; } .-contactMe { & { width: 85%; margin: 0 auto; } p { padding: 0; } } .-linksContactMe { flex-direction: row; justify-content: space-evenly; } } /* REDES SOCIALES - FOOTER */ .containerSocial { p { justify-content: center; font-size: 1.1rem; } .-footerLinks { & { justify-content: center; } label { font-size: 1rem; margin: 0 .5rem; } a { margin: 0; } } } } /* Large devices (laptops/desktops, 769px and up) */ @media only screen and (max-width: 1199px) and (min-width: 1001px) { /* PRINCIPALES CONTENEDORES - MAIN CONTAINERS */ .contentAboutme, .contentPortfolio, .contentSkills, .contentContact { & { margin: 6rem auto 1rem; } h2 { font-size: 3.5rem; padding: 0; margin: 1.5rem 0 2rem 0; } } /* BARRA DE NAVEGACION - NAVBAR */ nav { & { display: flex; justify-content: space-around; height: 10vh; } /* LOGO */ .nav-logo { display: flex; width: auto; .app-logo-image { display: flex; height: 8vh; } } .nav-menu { & { flex-direction: row; justify-content: space-around; position: initial; width: 75%; padding: 1rem 0 0 0; background-color: rgb(37, 37, 35); transform: translateX(0%); transition: transform 0.5s ease-in; .nav-link { width: 9.3rem; } } &.active { border-bottom: none; } .nav-item { & { width: 9rem; } .nav-link { // padding: 0; font-size: 1.1rem; font-weight: 400; height: 2.7rem; } } } .hamburger-toggle { display: none; } } /* INICIO - HOME */ .contentHome { & { margin: 6rem auto 1rem; width: 100%; height: 100vh; } h2 { font-size: 4rem; margin-top: 6rem; padding-left: 3rem; } p { font-size: 3rem; padding-left: 3rem; margin-bottom: 3rem; } .-txtHome { & { padding: 1rem; } p { font-size: 1.1rem; margin-bottom: 1rem; } } } /* SOBRE MI - ABOUT ME */ .contentAboutme { .-infoAboutMe { & { flex-direction: row; } /* FOTO DE PERFIL */ .profilePicture { & { margin-right: 2rem; } img { width: 100%; height: 90%; } } .txtAboutMe { p { font-size: 1.1rem; margin-bottom: .5rem; } } } /* PASATIEMPOS - HOBBIES */ .containerHobbies { & { width: fit-content; margin: auto; } .hobbies { width: 2.4rem; height: 2.4rem; } } } /* PORTAFOLIO - PORTFOLIO */ .contentPortfolio { /* CARDS PORTAFOLIO */ .card-deck { & { margin: 0 .1rem 1rem; } .card { .card-body { .card-note { font-size: .96rem; } a { font-size: .9rem; } .chatLauncher { font-size: .9rem; } } } } } /* HABILIDADES - SKILLS */ .contentSkills { .-containerCardsTecSkills, .-containerCardsSoftSkills { & { flex-wrap: wrap; flex-direction: row; justify-content: space-around; } .cardTecSkills, .cardSoftSkills { & { width: 25%; } .list-group-flush .list-group-item { & { font-size: 1.1rem; padding: .2rem 1rem; height: 4rem; } .skills { width: 3rem; } } } } } /* CONTACTO - CONTAC ME */ .contentContact { & { min-height: 100vh; } h3 { font-size: 2rem; } .-contactMe { & { width: 85%; margin: 0 auto; } p { padding: 0; font-size: 1.1rem; } } .-linksContactMe { & { flex-direction: row; justify-content: space-evenly; margin-bottom: 1.5rem; } a { font-size: 1rem; } .iconPdf { width: 2.8rem; height: 2.8rem; margin: 1rem; } } } /* REDES SOCIALES - FOOTER */ .containerSocial { p { font-size: 1.1rem; justify-content: center; margin-left: 0; } .-footerLinks { & { justify-content: center; } label { display: flex; margin: .5rem; font-size: 1rem; } a { margin: 0 1rem; } } } } /* Large devices (laptops/desktops, 1440px and up) */ @media only screen and (min-width: 1200px) { /* Esta medida abarca mi compu */ /* PRINCIPALES CONTENEDORES - MAIN CONTAINERS */ .contentAboutme, .contentPortfolio, .contentSkills, .contentContact { & { margin: 7rem auto 2rem; } h2 { font-size: 3.5rem; padding: 0; margin: 1.5rem 0 2rem 0; } } /* BARRA DE NAVEGACION - NAVBAR */ nav { & { display: flex; justify-content: space-around; height: auto; } /* LOGO */ .nav-logo { display: flex; width: auto; .app-logo-image { display: flex; height: 8vh; } } .nav-menu { & { flex-direction: row; justify-content: space-around; position: initial; width: 75%; padding: 1rem 0 0 0; background-color: rgb(37, 37, 35); transform: translateX(0%); transition: transform 0.5s ease-in; } &.active { border-bottom: none; } .nav-item { & { width: 10rem; } .nav-link { font-size: 1.2rem; font-weight: 400; align-items: center; } } } .hamburger-toggle { display: none; } } /* INICIO - HOME */ .contentHome { & { margin: 7rem auto 2rem; height: calc(100vh - 8rem); } h2 { font-size: 4rem; font-weight: 800; padding-left: 4rem; margin-top: 3rem; } p { font-size: 3rem; font-weight: 600; padding-left: 4rem; margin-bottom: 5rem; } .-txtHome { & { padding: 1rem; } p { font-size: 1.35rem; margin-bottom: 1.5rem; } } } /* SOBRE MI - ABOUT ME */ .contentAboutme { .-infoAboutMe { & { flex-direction: row; } /* FOTO DE PERFIL */ .profilePicture { & { width: 50%; } img { height: 95%; } } .txtAboutMe { & { width: 90%; justify-content: space-evenly; } p { font-size: 1.2rem; font-weight: 300; margin: 0; } } } /* PASATIEMPOS - HOBBIES */ .containerHobbies { & { width: fit-content; margin-left: 20%; } .hobbies { width: 3.5rem; height: 3.5rem; } } } /* PORTAFOLIO - PORTFOLIO */ .contentPortfolio { /* CARDS PORTAFOLIO */ .card-deck { & { margin: 0 .5rem 1rem; } .card { .card-body { .card-title { font-size: 1.45rem; font-weight: 300; } .card-text { font-size: 1.2rem; font-weight: 300; } .card-note { font-size: 1rem; font-weight: 300; margin: 1rem; } a { font-size: 1.1rem; font-weight: 300; } .chatLauncher { font-size: 1.1rem; font-weight: 300; } } .imgChatBot { height: 65%; } } } } /* HABILIDADES - SKILLS */ .contentSkills { .-containerCardsTecSkills, .-containerCardsSoftSkills { & { width: 95%; margin: auto; flex-wrap: wrap; flex-direction: row; justify-content: space-around; } .cardTecSkills, .cardSoftSkills { & { width: 25%; margin: .5rem; } .list-group-flush .list-group-item { & { font-size: 1.2rem; font-weight: 300; height: 3.8rem; padding: .5rem; } .skills { width: 3rem; margin: .5rem 1rem; } } } } } /* CONTACTO - CONTAC ME */ .contentContact { & { height: calc(100vh - 10rem); } h3 { font-size: 2.5rem; } .-contactMe { & { width: 75%; margin: 0 auto; } p { font-size: 1.2rem; font-weight: 300; text-align: justify; padding: 0; } } .-linksContactMe { & { width: 60%; margin: 0 auto; flex-direction: row; justify-content: space-between; } a { font-size: 1.1rem; font-weight: 300; } .iconPdf { width: 2.5rem; height: 2.5rem; } } } /* REDES SOCIALES - FOOTER */ .containerSocial { & { display: flex; padding-top: .5rem; padding-bottom: .3rem; justify-content: center; } p { font-size: 1.35rem; font-weight: 300; align-items: center; margin: 0 2rem 0 0; } .-footerLinks { label { font-size: 1.2rem; font-weight: 200; } img { width: 2.5rem; height: 2.5rem; } } } } /* Large devices (screen 2560px and up) */ @media only screen and (min-width: 2560px) { /* PRINCIPALES CONTENEDORES - MAIN CONTAINERS */ .contentAboutme, .contentPortfolio, .contentSkills, .contentContact { & { margin: 11.5rem auto 2rem; } h2 { font-size: 5rem; padding: .5rem; margin: 2rem auto; } } /* BARRA DE NAVEGACION - NAVBAR */ nav { /* LOGO */ .nav-logo { .app-logo-image { height: 8.5vh; } } .nav-menu { .nav-item { & { width: 20rem; } .nav-link { font-size: 2.5rem; width: 20rem; height: 6rem; border-radius: 1rem; } } } } /* INICIO - HOME */ .contentHome { & { margin: 11.5rem auto 2rem; border-radius: 2rem; } h2 { text-align: left; font-size: 10rem; padding-left: 7rem; margin-top: 10rem; -webkit-text-stroke-width: 0.3rem; } p { font-size: 8rem; padding-left: 7rem; margin-bottom: 3rem; text-shadow: 0 0 1rem #fff, 0 0 .1rem #fff, 0 0 .6rem #e44646; -webkit-text-fill-color: #f4ecff; -webkit-text-stroke-color: rgb(4, 8, 247); -webkit-text-stroke-width: 0.3rem; } .-txtHome { & { padding: 3rem 2rem; } p { font-size: 2.5rem; margin-bottom: 2.5rem; -webkit-text-fill-color: #c9ff07; text-shadow: .1rem .1rem 1rem rgba(0, 0, 0, 0.781), 0 0 .07rem blue, 0 0 1rem black; } } } /* SOBRE MI - ABOUT ME */ .contentAboutme { & { height: calc(100vh - 13.5rem); } .-infoAboutMe { & { flex-direction: row; justify-content: space-evenly; padding: 0 3rem; } /* FOTO DE PERFIL */ .profilePicture { & { width: auto; } img { border-radius: 2rem; } } .txtAboutMe { & { width: 75%; justify-content: space-between; } p { font-size: 2.2rem; } } } /* PASATIEMPOS - HOBBIES */ .containerHobbies { & { width: fit-content; margin-right: auto; } .hobbies { margin: 1rem; width: 6rem; height: 6rem; } } } /* PORTAFOLIO - PORTFOLIO */ .contentPortfolio { /* CARDS PORTAFOLIO */ .card-deck { & { margin: 0 .5rem 1.5rem; } .card { .card-body { & { padding: 2.5rem; } .card-title { font-size: 2.5rem; } .card-text { font-size: 2.2rem; } .card-note { font-size: 1.7rem; margin: 2rem; } a { font-size: 1.9rem; margin: 2rem; } /* CHATBOT ICON */ /* revisar como hacer mas grande el chat */ .chatLauncher { margin: 2rem; font-size: 1.9rem; } } } } } /* HABILIDADES - SKILLS */ .contentSkills { .-containerCardsTecSkills, .-containerCardsSoftSkills { & { flex-direction: row; align-items: center; margin: auto; } .cardTecSkills, .cardSoftSkills { & { width: 25%; margin: 1rem; border: solid .2rem; border-radius: 1rem; } .list-group-flush .list-group-item { & { font-size: 2.2rem; height: 8rem; padding-top: 1.3rem; padding-bottom: 1.5rem; } .skills { width: 6rem; height: 6rem; margin: .5rem 1rem; } } } } } /* CONTACTO - CONTAC ME */ .contentContact { & { height: calc(100vh - 17rem); } h2 { margin: 0 auto; } h3 { font-size: 3.5rem; margin: 0 auto; } .-contactMe { & { width: 80%; justify-content: center; align-items: center; margin: 0 auto; } p { font-size: 2.5rem; } } .-linksContactMe { & { flex-direction: row; align-items: center; margin: 0 auto; } a { font-size: 2.2rem; } .iconPdf { width: 4rem; height: 4rem; margin: 1rem; } } } /* REDES SOCIALES - FOOTER */ .containerSocial { p { font-size: 2.5rem; margin-right: 2.5rem; } .-footerLinks { & { align-items: center; } label { font-size: 2.1rem; margin: 0 1rem; } a { margin: 0 .7rem; } img { width: 3.5rem; height: 3.5rem; } } } } // .neon { // color: #fff; // // margin-top: 30%; // text-align: center; // text-shadow: // 0 0 5px rgba(0, 178, 255, 1), // 0 0 10px rgba(0, 178, 255, 1), // 0 0 20px rgba(0, 178, 255, 1), // 0 0 40px rgba(38, 104, 127, 1), // 0 0 80px rgba(38, 104, 127, 1), // 0 0 90px rgba(38, 104, 127, 1), // 0 0 100px rgba(38, 104, 127, 1), // 0 0 140px rgba(38, 104, 127, 1), // 0 0 180px rgba(38, 104, 127, 1); // } .neon { color: #fff; text-shadow: 0 0 5px #fff, 0 0 .10px #fff, 0 0 .15px #e9e7e3, 0 0 20px #ea00ff, 0 0 25px #ea00ff, 0 0 30px #ea00ff, 0 0 35px #ea00ff; } .textoNeonAmarillo { color: #FFFFFF; text-shadow: 0 0 8px #f0ad4e, 0 0 2px #f0ad4e, 0 0 10px #f0ad4e, 0 0 6px #f0ad4e, 0 0 20px #f0ad4e, 0 0 20px #f0ad4e, 0 0 1px #f0ad4e, 0 0 12px #f0ad4e; } .textoNeonAzul { color: #FFFFFF; text-shadow: 0 0 8px #2cd0f0, 0 0 2px #2cd0f0, 0 0 10px #2cd0f0, 0 0 6px #2cd0f0, 0 0 20px #2cd0f0, 0 0 20px #2cd0f0, 0 0 1px #2cd0f0, 0 0 12px #2cd0f0; } .textoNeonRojo { color: #FFFFFF; text-shadow: 0 0 8px #d43f3a, 0 0 2px #d43f3a, 0 0 10px #d43f3a, 0 0 6px #d43f3a, 0 0 20px #d43f3a, 0 0 20px #d43f3a, 0 0 1px #d43f3a, 0 0 12px #d43f3a; } /*glow*/ @keyframes neon1 { from { text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #FF1177, 0 0 70px #FF1177, 0 0 80px #FF1177, 0 0 100px #FF1177, 0 0 150px #FF1177; } to { text-shadow: 0 0 5px #fff, 0 0 10px #fff, 0 0 15px #fff, 0 0 20px #FF1177, 0 0 35px #FF1177, 0 0 40px #FF1177, 0 0 50px #FF1177, 0 0 75px #FF1177; } } @keyframes neon2 { from { text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #228DFF, 0 0 70px #228DFF, 0 0 80px #228DFF, 0 0 100px #228DFF, 0 0 150px #228DFF; } to { text-shadow: 0 0 5px #fff, 0 0 10px #fff, 0 0 15px #fff, 0 0 20px #228DFF, 0 0 35px #228DFF, 0 0 40px #228DFF, 0 0 50px #228DFF, 0 0 75px #228DFF; } } @keyframes neon3 { from { text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #FFDD1B, 0 0 70px #FFDD1B, 0 0 80px #FFDD1B, 0 0 100px #FFDD1B, 0 0 150px #FFDD1B; } to { text-shadow: 0 0 5px #fff, 0 0 10px #fff, 0 0 15px #fff, 0 0 20px #FFDD1B, 0 0 35px #FFDD1B, 0 0 40px #FFDD1B, 0 0 50px #FFDD1B, 0 0 75px #FFDD1B; } } @keyframes neon4 { from { text-shadow: 0 0 5px #fff, // 0 0 10px #fff, // 0 0 15px #fff, 0 0 15px #00ff40, 0 0 20px #00ff40, // 0 0 .25px #00ff40, // 0 0 30px #00ff40, // 0 0 35px #00ff40; } to { text-shadow: // 0 0 5px #fff, // 0 0 10px #fff, // 0 0 15px #fff, 0 0 20px #B6FF00, 0 0 25px #B6FF00, // 0 0 30px #B6FF00, // 0 0 .35px #B6FF00, // 0 0 .45px #B6FF00; } } @keyframes neon5 { from { text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #FF9900, 0 0 70px #FF9900, 0 0 80px #FF9900, 0 0 100px #FF9900, 0 0 150px #FF9900; } to { text-shadow: 0 0 5px #fff, 0 0 10px #fff, 0 0 15px #fff, 0 0 20px #FF9900, 0 0 35px #FF9900, 0 0 40px #FF9900, 0 0 50px #FF9900, 0 0 75px #FF9900; } } @keyframes neon6 { from { text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #ff00de, 0 0 70px #ff00de, 0 0 80px #ff00de, 0 0 100px #ff00de, 0 0 150px #ff00de; } to { text-shadow: 0 0 5px #fff, 0 0 10px #fff, 0 0 15px #fff, 0 0 20px #ff00de, 0 0 35px #ff00de, 0 0 40px #ff00de, 0 0 50px #ff00de, 0 0 75px #ff00de; } } /* Small devices (portrait tablets and large phones, 600px and up) */ /* @media only screen and (max-width: 600px) {} /* Medium devices (landscape tablets, 768px and up) */ /* @media only screen and (min-width: 768px) {} */ /* Large devices (laptops/desktops, 900px and up) */ /* @media only screen and (max-width: 900px) {} */ /* Extra large devices (large laptops and desktops, 1200px and up) */ /* @media only screen and (min-width: 1024px) {} */ /* @media (max-width: 900px) { } */
package firebase.web.firestore; /** * A DocumentSnapshot contains data read from a document in your Firestore database. The data can be extracted with .data() or .get(<field>) to get a specific field. * * For a DocumentSnapshot that points to a non-existing document, any data access will return 'undefined'. You can use the exists() method to explicitly verify a document's existence. */ extern class DocumentSnapshot<T> { private function new(); /** * Property of the DocumentSnapshot that provides the document's ID. */ public var id:String; /** * Metadata about the DocumentSnapshot, including information about its source and local modifications. */ public var metadata:SnapshotMetadata; /** * The DocumentReference for the document included in the DocumentSnapshot. */ public var ref:DocumentReference<T>; /** * Retrieves all fields in the document as an Object. Returns undefined if the document doesn't exist.By default, FieldValue.serverTimestamp() values that have not yet been set to their final value will be returned as null. You can override this by passing an options object. * @param options * @return Null<T> */ public function data(?options:SnapshotOptions):Null<T>; /** * Property of the DocumentSnapshot that signals whether or not the data exists. True if the document exists. * @return QueryDocumentSnapshot<T> */ public function exists():Bool; /** * Retrieves the field specified by fieldPath. Returns undefined if the document or field doesn't exist. * By default, a FieldValue.serverTimestamp() that has not yet been set to its final value will be returned as null. You can override this by passing an options object. * @param path * @param options * @return Any */ public function get(path:String, ?options:SnapshotOptions):Any; }
# Starting your journey ## Prerequisites Ensure you have followed the steps listed on the [installation documentation](https://sitecore.github.io/Helix.Examples/install.html). The Helix examples assume you have some experience with (or at least an understanding of) Docker container-based Sitecore development. For more information, see the [Sitecore Containers Documentation](https://containers.doc.sitecore.com). ## Creating The Helix Solution ## Initialize Sitecore Open a PowerShell administrator prompt and run the following command, replacing the `-HostName` with the name of your solution and `-LicenseXmlPath` with the location of your Sitecore license file. ``` .\init.ps1 -HostName basic-company -LicenseXmlPath C:\License\license.xml ``` You can also set the Sitecore admin password using the `-SitecoreAdminPassword` parameter (default is "b"). This will perform any necessary preparation steps, such as populating the Docker Compose environment (.env) file, configuring certificates, and adding hosts file entries. A final manual step is to go to `docker/traefik/config/dynamic/cert_config.yaml` and replace `project` in the certificate names to the HostName ## Build the solution and start Sitecore Run the following command in PowerShell. ``` docker-compose up -d ``` This will download any required Docker images, build the solution and Sitecore runtime images, and then start the containers. The example uses the *Sitecore Experience Management (XM1)* topology. Once complete, you can access the instance with the following. * Sitecore Content Management: https://cm.Your-HostName.localhost * Sitecore Identity Server: https://id.Your-HostName.localhost * Basic Company site: https://www.Your-HostName.localhost ## Publish The serialized items will automatically sync when the instance is started, but you'll need to publish them. Login to Sitecore at https://cm.Your-HostName.localhost/sitecore and perform a site smart publish. Use "admin" and the password you specified on init ("b" by default). > you might also need to _Populate Solr Managed Schema_ and rebuild indexes from the Control Panel. You may also need to `docker-compose restart cd` due to workaround an issue with the Solr schema cache on CD.ad You should now be able to view the Basic Company site at https://www.Your-HostName.localhost. ## Stop Sitecore When you're done, stop and remove the containers using the following command. ``` docker-compose down ```
import React from 'react'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import Checkbox from '@material-ui/core/Checkbox'; import IconButton from '@material-ui/core/IconButton'; import DeleteIcon from '@material-ui/icons/Delete'; import List from '@material-ui/core/List'; import * as actions from "./redux/actions"; import {connect } from "react-redux"; const TodoList = ({todos, deleteTodo, toggleCompleted}) => ( <List> {todos.map((todo, index) => ( <ListItem button key={index} onClick={() => toggleCompleted(index)}> <Checkbox checked={todo.completed}/> <ListItemText primary={todo.value} /> <ListItemSecondaryAction> <IconButton onClick= {() => deleteTodo(index)}> <DeleteIcon/> </IconButton> </ListItemSecondaryAction> </ListItem> ))} </List> ); const mapStateToProps = ({todoReducer}) => { const {todos} = todoReducer; return {todos} ; }; export default connect ( mapStateToProps, actions )(TodoList);
// This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/03/b/RAM16K.hdl /** * Memory of 16K registers, each 16 bit-wide. Out holds the value * stored at the memory location specified by address. If load==1, then * the in value is loaded into the memory location specified by address * (the loaded value will be emitted to out from the next time step onward). */ CHIP RAM16K { IN in[16], load, address[14]; OUT out[16]; PARTS: // Base DMux, divides into two 4-register halves DMux(in=load, sel=address[13], a=outa, b=outb); // Second level DMux, divides into two 2-register halves DMux(in=outa, sel=address[12], a=outfsda, b=outfsdb); RAM4K(in=in, load=outfsda, address=address[0..11], out=out1); RAM4K(in=in, load=outfsdb, address=address[0..11], out=out2); DMux(in=outb, sel=address[12], a=ao, b=bo); RAM4K(in=in, load=ao, address=address[0..11], out=out3); RAM4K(in=in, load=bo, address=address[0..11], out=out4); Mux16(a=out1, b=out2, sel=address[12], out=tout1); Mux16(a=out3, b=out4, sel=address[12], out=tout2); Mux16(a=tout1, b=tout2, sel=address[13], out=out); }
import heapq from heapq import heappop, heappush def isLeaf(root): return root.left is None and root.right is None class Node: def __init__(self, ch, freq, left=None, right=None): self.ch = ch self.freq = freq self.left = left self.right = right def __lt__(self, other): return self.freq < other.freq def encode(root, s, huffman_code): if root is None: return if isLeaf(root): huffman_code[root.ch] = s if len(s) > 0 else '1' encode(root.left, s + '0', huffman_code) encode(root.right, s + '1', huffman_code) def decode(root, index, s): if root is None: return index if isLeaf(root): print(root.ch, end='') return index index = index + 1 root = root.left if s[index] == '0' else root.right return decode(root, index, s) def buildHuffmanTree(text): if len(text) == 0: return freq = {i: text.count(i) for i in set(text)} pq = [Node(k, v) for k, v in freq.items()] heapq.heapify(pq) while len(pq) != 1: left = heappop(pq) right = heappop(pq) total = left.freq + right.freq heappush(pq, Node(None, total, left, right)) root = pq[0] huffmanCode = {} choice=1 while(choice!=0): choice=int(input("\nEnter choice\n")) if(choice==1): encode(root, '', huffmanCode) print("\nHuffman Codes are:\n", huffmanCode) s = '' for c in text: s += huffmanCode.get(c) print('\nThe encoded string is:', s) elif(choice==2): huffmanCode = {} encode(root, '', huffmanCode) s = '' for c in text: s += huffmanCode.get(c) print('\nThe decoded string is:',end=' ') if isLeaf(root): while root.freq > 0: print(root.ch, end='') root.freq = root.freq - 1 else: index = -1 while index < len(s) - 1: index = decode(root, index, s) elif(choice==0): exit if __name__ == '__main__': file=input("Enter file name") with open(file) as f1: text=f1.readlines() print("1.Encoding") print("2.Decoding") print("0.Exit") buildHuffmanTree(text)
import { Single } from "../SingleTask/SingleTask" import { useEffect } from "react" import { NewModal } from "../Modals/NewModal/NewModal" import { useDispatch, useSelector } from "react-redux" import { RootState } from "../../app/store" import { getAllTasks } from "../../app/API" import { addAllTasks } from "../../app/reducer/task" import { setLoading } from "../../app/reducer/loading" import { ColorRing } from "react-loader-spinner" export const AllTasks = () => { const dispatch = useDispatch() const tasks = useSelector((state: RootState) => state.tasks) const loading = useSelector((state: RootState) => state.loading.loading) useEffect(() => { dispatch(setLoading(true)) getAllTasks().then(found => { dispatch(addAllTasks(found)) dispatch(setLoading(false)) }) console.log(tasks) }, []) return (<> {loading ? <ColorRing visible={true} height="80" width="80" ariaLabel="blocks-loading" wrapperStyle={{}} wrapperClass="blocks-wrapper" colors={['#008744', '#0057e7', '#d62d20', '#ffa700', '#ffffff']} /> : <div className="all__wrap"> <div className="all__tasks"> { /* the byDate prop is not an array, it's an object of all the different dates for which we have tasks Object.keys return an aray of object props, that we can lopo using map */ Object.keys(tasks.byDate).map((key,i) => { return <div key={i}> <h3 style={key === "expired" ? {color: "red"} : {}}> {key.replaceAll("_", " ")} </h3> {tasks.byDate[key].map((task, i) => <Single key={i} task={task} />)} </div> }) } </div> <NewModal /> </div>} </>) }
// // UserDefaultsManager.swift // SeSacSlack // // Created by ์ด์ƒ๋‚จ on 1/8/24. // import Foundation struct UserDefaultsManager { @UserDefaultsWrapper(key: "isLogin", defaultValue: false) static var isLogin @UserDefaultsWrapper(key: "token", defaultValue: "") static var token @UserDefaultsWrapper(key: "refreshToken", defaultValue: "") static var refresh @UserDefaultsWrapper(key: "id", defaultValue: 0) static var id @UserDefaultsWrapper(key: "nickname", defaultValue: "") static var nickname @UserDefaultsWrapper(key: "workSpaceId", defaultValue: 0) static var workSpaceId @UserDefaultsWrapper(key: "deviceToken",defaultValue: "") static var deviceToken static func saveUserDefaults(id: Int = 0, nickname: String = "" , token: String = "", refresh: String = "") { UserDefaultsManager.isLogin = true UserDefaultsManager.id = id UserDefaultsManager.nickname = nickname UserDefaultsManager.token = token UserDefaultsManager.refresh = refresh } static func resetUserDefaults() { UserDefaultsManager.isLogin = false UserDefaultsManager.id = 0 UserDefaultsManager.nickname = "" UserDefaultsManager.token = "" UserDefaultsManager.refresh = "" UserDefaultsManager.workSpaceId = 0 } } @propertyWrapper private struct UserDefaultsWrapper<T> { let key: String let defaultValue: T var wrappedValue: T { get { UserDefaults.standard.object(forKey: key) as? T ?? defaultValue } set { UserDefaults.standard.set(newValue, forKey: key) } } }
#include <cassert> #include <iostream> #include "ortho.h" #include "lobpcg.h" // check_init_guess // test for ortho and qr void test_ortho(){ std::cout << "\n----- Testing ortho -----" << std::endl; int n = 5; // number of rows int m = 3;//4; // number of columns Eigen::MatrixXd evec(n, m); // initialize evec with zeros // evec << 1, 2, 3, 4, // 5, 6, 7, 8, // 9, 10, 11, 12, // 13, 14, 15, 16, // 17, 18, 19, 20; evec << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15; for(int j=0; j<m; ++j){ evec.col(j).normalize(); } // evec.setRandom(); evec *= 10; auto another_vec = evec; // std::cout << evec.col(2) << std::endl; // evec.col(2).normalize(); // std::cout << evec.col(2) << std::endl; std::cout << "evec = \n" << evec << std::endl; ortho(n, m, evec); std::cout << "ortho evec = \n" << evec << std::endl; /* below will not work unless ortho is redefined as template of taking parameter of (int n, int m, Eigen::DenseBase<Derived> &u)*/ // std::cout <<"---"<< std::endl; // std::cout << "another vec = \n" << another_vec << std::endl; // // ortho(n, 3, another_vec.leftCols(3)); // std::cout << "ortho evec = \n" << another_vec << std::endl; auto overlap = evec.transpose() * evec; assert(overlap.isApprox(Eigen::MatrixXd::Identity(m, m), 1e-10) && "u'u should be approximately identity matrix"); } // test for ortho and check_init_guess void test_ortho_check_init_guess(){ std::cout << "\n----- Testing ortho and check_init_guess -----" << std::endl; int n = 4; // number of rows int m = 3; // number of columns Eigen::MatrixXd evec(n, m); // initialize evec with zeros evec << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12; std::cout << evec << std::endl; ortho(n, m, evec); // std::cout << evec << std::endl; // std::cout << "--- ortho end ---\n"; evec << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12; // std::cout << evec << std::endl; // check_init_guess(n, m, evec); // std::cout << evec << std::endl; // Check if evec is orthogonal Eigen::MatrixXd overlap = evec.transpose() * evec; std::cout << "overlap = \n" << overlap << std::endl; // std::cout << "areColumnsOrthogonal(u)" << Eigen::areColumnsOrthogonal(u) << std::endl; double diag_norm = overlap.diagonal().array().square().sum(); double out_norm = (overlap.array().square()).sum() - diag_norm; assert(std::abs(diag_norm - m) <= 1e-10); assert(std::abs(out_norm) <= 1e-10); std::cout << "----- end Testing ortho and check_init_guess -----\n" << std::endl; } // Test for b_ortho void test_b_ortho() { std::cout << "\n----- Testing b_ortho -----" << std::endl; int n = 4; // number of rows int m = 3; // number of columns Eigen::MatrixXd u(n, m); // initialize u with zeros u << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12; ortho(n, m, u); std::cout << "u = \n" << u << std::endl; // assume b = diag(1,1,2,2) Eigen::MatrixXd b(n, n); b.setZero(); b.diagonal() << 3, 1, 2, 4; std::cout << "b = \n" << b << std::endl; Eigen::MatrixXd bu(n, m); // initialize bu with zeros bu = b*u; // std::cout << "bu = \n" << bu << std::endl; // bu << 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24; std::cout << "Before b_ortho:\n"; // std::cout << "u:\n" << u << std::endl; // std::cout << "bu:\n" << bu << std::endl; std::cout << "u'u:\n" << u.transpose() * u << std::endl; std::cout << "u'bu:\n" << u.transpose() * bu << std::endl; b_ortho(n, m, u, bu); std::cout << "After b_ortho:\n"; // std::cout << "u:\n" << u << std::endl; // std::cout << "bu:\n" << bu << std::endl; // TODO: Add assertions to check the correctness of the b_ortho function Eigen::MatrixXd overlap = u.transpose() * u; std::cout << "overlap u'u = \n" << overlap << std::endl; Eigen::MatrixXd overlap_ubu = bu.transpose() * u; std::cout << "overlap u'bu = \n" << overlap_ubu << std::endl; // assert(overlap.isApprox(Eigen::MatrixXd::Identity(m, m), 1e-10) && "u'u should be approximately identity matrix"); assert(overlap_ubu.isApprox(Eigen::MatrixXd::Identity(m, m), 1e-10) && "u'bu should be approximately identity matrix"); std::cout << "----- end Testing b_ortho -----\n" << std::endl; } // Test for ortho_against_x void test_ortho_against_y() { std::cout << "\n----- Testing ortho_against_y, un-orthoganalized input -----" << std::endl; int n = 10; // number of rows int m = 3; // number of columns int k = 2; // number of vectors // Initialize x and y matrices Eigen::MatrixXd x = Eigen::MatrixXd::Random(n, k); x << 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25; // ortho(n, k, x); Eigen::MatrixXd y = Eigen::MatrixXd::Random(n, m); // y << 1, 2, 3, 4, 5, 6; // y << 1, 2, 3, 12, 5, 7, 6, 4, 8, 9, 10, 11; y << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30; // ortho(n, m, y); std::cout << "Before ortho_against_x:\n"; // std::cout << "x:\n" << x << std::endl; // std::cout << "y:\n" << y << std::endl; std::cout << "x'x = \n" << x.transpose()*x << std::endl; std::cout << "y'y = \n" << y.transpose()*y << std::endl; ortho_against_y(n, m, k, x, y); std::cout << "After ortho_against_y:\n"; // std::cout << "x:\n" << x << std::endl; // std::cout << "y:\n" << y << std::endl; // TODO: Add assertions to check the correctness of the ortho_against_x function Eigen::MatrixXd overlap = x.transpose() * x; std::cout << "overlap x'x = \n" << overlap << std::endl; Eigen::MatrixXd overlap_yx = y.transpose() * x; std::cout << "overlap y'x = \n" << overlap_yx << std::endl; assert(overlap.isApprox(Eigen::MatrixXd::Identity(k, k), 1e-10) && "x'x should be approximately Identity matrix"); // assert(overlap_yx.array().isMuchSmallerThan(Eigen::MatrixXd::Constant(m,k), ASSERT_EPSILON)); // assert(overlap_yx.array().isMuchSmallerThan(ASSERT_EPSILON) && "y'x should be approximately Zero matrix"); assert((overlap_yx.norm() < ASSERT_EPSILON) && "y'x should be approximately Zero matrix"); std::cout << "----- end Testing ortho_against_y, un-orthoganalized input -----\n" << std::endl; } void test_b_ortho_against_y(){ std::cout << "\n----- Testing b_ortho_against_y, b-orthogonalize x against given y and by -----" << std::endl; int n = 10; // number of rows int m = 3; // number of columns int k = 2; // number of vectors // Initialize x and y matrices Eigen::MatrixXd x = Eigen::MatrixXd::Random(n, k); // x << 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25; // ortho(n, k, x); Eigen::MatrixXd y = Eigen::MatrixXd::Random(n, m); // y << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30; ortho(n, m, y); Eigen::MatrixXd b(n, n); b.setZero(); b.diagonal() << 3, 1, 2, 4, 6, 3, 5, 9, 3, 10; // std::cout << "b = \n" << b << std::endl; Eigen::MatrixXd by(n, m); by = b*y; // std::cout << "by = \n" << by << std::endl; std::cout << "Before b_ortho_against_y:\n"; // std::cout << "x:\n" << x << std::endl << "y:\n" << y << std::endl; Eigen::MatrixXd overlap = y.transpose() * y; std::cout << "x'x = \n" << x.transpose()*x << std::endl; std::cout << "overlap y'y = \n" << overlap << std::endl; Eigen::MatrixXd overlap_by = by.transpose() * y; std::cout << "overlap y'by = \n" << overlap_by << std::endl; b_ortho_against_y(n, m, k, x, y, by); std::cout << "After b_ortho_against_y:\n"; // std::cout << "x:\n" << x << std::endl << "y:\n" << y << std::endl; // check the correctness after the b-ortho overlap = x.transpose() * x; std::cout << "overlap x'x = \n" << overlap << std::endl; Eigen::MatrixXd overlap_ybx = y.transpose() * b * x; std::cout << "overlap y^Tbx = \n" << overlap_ybx << std::endl; assert(overlap.isApprox(Eigen::MatrixXd::Identity(k, k), 1e-10) && "x'x should be approximately Identity matrix"); assert(overlap_ybx.isApprox(Eigen::MatrixXd::Zero(m, k), 1e-10) && "y'bx should be approximately Zero matrix"); std::cout << "----- end Testing b_ortho_against_y, b-orthogonalize x against given y and by -----\n" << std::endl; } int main() { test_ortho(); // test_ortho_check_init_guess(); // test_b_ortho(); // test_ortho_against_y(); // test_b_ortho_against_y(); }
document.addEventListener("DOMContentLoaded", () => { const { item, group } = getProductParamsFromURL(); if (group) { fetchProductDetails(group, item); } else { console.error("Grupo no especificado en la URL."); } function getProductParamsFromURL() { const urlParams = new URLSearchParams(window.location.search); return { item: urlParams.get("item"), group: urlParams.get("group"), }; } function fetchProductDetails(group, item) { fetch(`https://store-megagames.onrender.com/api/store/${group}/${item}`) .then((response) => response.json()) .then((product) => { if (product.error) { console.error(product.error); return; } setupAddToCartButton(product, group); }) .catch((error) => console.error("Error al obtener los detalles del producto:", error) ); } function setupAddToCartButton(product, group) { const addToCartButton = document.querySelector(".add_to_cart button"); addToCartButton.addEventListener("click", () => { if (product.stock <= 0) { alert("Este producto estรก agotado"); return; } const cartItem = { id: product.id, group: group, name: product.nombre, discount: product.descuento || null, originalPrice: product.precioOriginal || null, price: product.precioDescuento || product.precioOriginal, img: product.imagenAlternativa || product.imagen, background: product.background, platform: product.disponibleEn, quantity: 1, }; const cart = JSON.parse(localStorage.getItem("cart")) || []; const existingProduct = cart.find( (item) => item.id === cartItem.id && item.group === cartItem.group ); const totalQuantityInCart = existingProduct ? existingProduct.quantity : 0; fetch( `https://store-megagames.onrender.com/api/store/${group}/${product.id}` ) .then((response) => response.json()) .then((data) => { if (data.stock <= totalQuantityInCart) { alert("Este producto estรก agotado"); return; } if (existingProduct) { existingProduct.quantity++; } else { cart.push(cartItem); } localStorage.setItem("cart", JSON.stringify(cart)); updateCartCount(); reduceStock(cartItem.id, cartItem.group, 1); }) .catch((error) => console.error("Error al verificar el stock del producto:", error) ); }); } function reduceStock(productId, productGroup, quantity) { fetch( `https://store-megagames.onrender.com/api/store/reduceStock/${productId}`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ group: productGroup, quantity: quantity }), } ) .then((response) => response.json()) .then((data) => { if (data.error) { console.error(data.error); return; } console.log(`Stock reducido: ${data.stock}`); }) .catch((error) => console.error("Error al reducir el stock:", error)); } function updateCartCount() { const cart = JSON.parse(localStorage.getItem("cart")) || []; const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0); const cartCountElement = document.querySelector( "#cart_status_data .cart_link" ); if (cartCountElement) { cartCountElement.textContent = `Carro (${totalItems})`; } } updateCartCount(); });
//NPM Imports import React, { useEffect } from "react"; import { useNavigate } from "react-router-dom"; //Local Imports import Header from "./Header/Header"; import JobInfo from "./JobInfo/JobInfo"; import JobSupplyInfo from "./JobSupplyInfo/JobSupplyInfo"; import JobNotes from "./JobNotes/JobNotes"; import MaterialList from "./MaterialList/MaterialList"; import CurrentConnection from "./CurrentConnection/CurrentConnection"; import { useRootStore } from "../providers/RootStoreProvider"; import { RootStoreType } from "../models/root-store"; const RunSheet: React.FC = () => { const rootStore: RootStoreType = useRootStore(); const navigate = useNavigate(); useEffect(() => { if (rootStore.settings.dataProviders.length < 1) { navigate("/settings"); } else { if ( rootStore.settings.currentDataProvider === null || rootStore.settings.currentDataProvider === undefined ) { rootStore.settings.setCurrentDataProvider( rootStore.settings.dataProviders[0].dataProviderID ); } } }), []; useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.ctrlKey && event.shiftKey && event.code === "KeyK") { event.preventDefault(); navigate("/settings"); } }; // Add event listener window.addEventListener("keydown", handleKeyDown); // Remove event listener on cleanup return () => { window.removeEventListener("keydown", handleKeyDown); }; }, [navigate]); return ( <div className="h-screen"> <div className="h-[8%]"> <Header /> </div> <div className="h-[22%] "> <JobInfo /> </div> <div className="h-[35%] "> <MaterialList /> </div> <div className="h-[8%] "> <JobSupplyInfo /> </div> <div className="h-[22%] "> <JobNotes /> </div> <div className="h-[5%] "> <CurrentConnection /> </div> </div> ); }; export default RunSheet;
package exercise6; import aut.isp.lab4.exercise6.*; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; public class ToStringTests { @Test public void toStringSensorTest() { LevelSensor levelSensor = new LevelSensor("ABC", "Mini", 25F); String expected = "Sensor - manufacturer: ABC, model: Mini"; String actual = levelSensor.toString(); assertArrayEquals(expected.toCharArray(), actual.toCharArray()); TemperatureSensor temperatureSensor = new TemperatureSensor("ABC", "Mini", 25); expected = "Sensor - manufacturer: ABC, model: Mini"; actual = temperatureSensor.toString(); assertArrayEquals(expected.toCharArray(), actual.toCharArray()); PHSensor phSensor = new PHSensor("ABC", "Mini", 6.5F); expected = "Sensor - manufacturer: ABC, model: Mini"; actual = phSensor.toString(); assertArrayEquals(expected.toCharArray(), actual.toCharArray()); } @Test public void toStringActuatorTest() { Alarm alarm = new Alarm("MNB","Mini"); String expected = "Actuator - manufacturer: MNB, model: Mini"; String actual = alarm.toString(); assertArrayEquals(expected.toCharArray(), actual.toCharArray()); Heater heater = new Heater("MNB", "Mini"); expected = "Actuator - manufacturer: MNB, model: Mini"; actual = heater.toString(); assertArrayEquals(expected.toCharArray(), actual.toCharArray()); } @Test public void toStringFishFeederTest() { FishFeeder fishFeeder = new FishFeeder("DBS", "Medio", 10); String expected = "The manufacturer DBS makes the model Medio. It has the level of food 10"; String actual = fishFeeder.toString(); assertArrayEquals(expected.toCharArray(), actual.toCharArray()); } }
/* * CopperCore, an IMS-LD level C engine * Copyright (C) 2003 Harrie Martens and Hubert Vogten * * 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 (/license.txt); if not, * write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * Contact information: * Open University of the Netherlands * Valkenburgerweg 177 Heerlen * PO Box 2960 6401 DL Heerlen * e-mail: [email protected] or * [email protected] * * * Open Universiteit Nederland, hereby disclaims all copyright interest * in the program CopperCore written by * Harrie Martens and Hubert Vogten * * prof.dr. Rob Koper, * director of learning technologies research and development * */ package org.coppercore.component; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import javax.ejb.EJBException; import javax.ejb.FinderException; import org.apache.log4j.Logger; import org.coppercore.business.Run; import org.coppercore.business.Uol; import org.coppercore.business.User; import org.coppercore.datatypes.LDDataType; import org.coppercore.dossier.PropertyDefDto; import org.coppercore.dossier.PropertyDefFacade; import org.coppercore.dossier.PropertyEntityPK; import org.coppercore.exceptions.PropertyException; import org.coppercore.exceptions.PropertyNotFoundException; import org.coppercore.exceptions.PropertyTypeException; import org.coppercore.exceptions.TypeCastException; /** * This class implements the factory for retrieving Ccomponents. Whenever one of * the components is retrieved it should be done via this class. A cache is * maintained locally to avoid unecessary bean access. * * @author Harrie Martens * @author Hubert Vogten * @version $Revision: 1.29 $, $Date: 2008/04/28 08:00:36 $ */ public class ComponentFactory { final static int MAX_ENTRIES = 1024; private static ComponentFactory factory = null; private static final String CLASSNAME = "org.coppercore.component.ComponentFactory"; /* * Fixed: 11-10-2006. Removing the cache resulted into multiple loading of the * Expression property. This resulted into multiple java object instances of * the same ThenActions causing the firedActions filters to fail. These * filters make sure that the same actions aren't evaluated over and over * again potentially causing endless loops. Therefore the cache has been * reintroduced. However only ClassProperties and ExpressionProperties are * stored on the cache from now one. Furhtermore the cache has been limited in * size avoiding the memory leak problem connected to the cache earlier. */ private Map cache = Collections.synchronizedMap(new LinkedHashMap(MAX_ENTRIES + 1, .75F, true) { // This method is called just after a new entry has been added public boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_ENTRIES; } }); private static long propertyCounter = 0; /** * Default method for retrieving a PropertyFactory object. Because a * PropertyFactory maintains a cache, multiple instances of this class should * be avoided. This methods ensure that only one instance at a time is * instantiated (local singleton). * * @return ComponentFactory the current ComponentFactory to be used for * retrieving Components */ public static ComponentFactory getPropertyFactory() { if (factory == null) { Logger logger = Logger.getLogger(CLASSNAME); logger.debug("Creating new cache"); factory = new ComponentFactory(); } return factory; } /** * Default constructor. * */ private ComponentFactory() { // do nothing } /* * Implements a cache for ExpressionProperties. ExpressionProperties must be cached * and may not be reloaded during the evaluation of the expressions!!! This cache makes * sure this will not happen. */ private synchronized StaticProperty fetchFromCache(String key) { StaticProperty prop = (StaticProperty) cache.get(key); if (prop == null) return null; // put key on top of linked list cache.remove(key); cache.put(key, prop); return prop; // return (StaticProperty) cache.get(key); // TODO enable optional debug statement here // System.out.print(" - F:" + ++propertyCounter); // return null; } /** * Clears the cache containing the Components and their definitions. * */ public synchronized void clearCache() { cache.clear(); } /** * Clears the cache with all none static Components. * */ public synchronized void clearNonStaticCache() { /* ArrayList propsToRemove = new ArrayList(); // check which properties should be removed from the cache Iterator iter = cache.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); StaticProperty property = (StaticProperty) cache.get(key); if (property instanceof Property) { // we are dealing with a non static property, so remove it from the // cache propsToRemove.add(key); } } // remove the properties from the cache iter = propsToRemove.iterator(); while (iter.hasNext()) { String key = (String) iter.next(); cache.remove(key); } */ } private synchronized StaticProperty addToCache(String key, StaticProperty property) { // TODO remove adding the property cache.put(key, property); return property; } /** * Returns an ExplicitProperty instance based of the passed parameters. * Explicit properties have to be created via this factory because during * run-time only it's id is known. This factory determines the type of the * property by retrieving the property definition and creates the * corresponding explicit property * * @param uol * Uol the uol for which this property was defined * @param run * Run the run for which this property was instantiated * @param user * User the user who owns this property * @param propId * String the id of the property as defined in IMS-LD * @throws PropertyException * thrown when the operation fails * @return ExplicitProperty the newly created ExplicitProperty */ public ExplicitProperty getProperty(Uol uol, Run run, User user, String propId) throws PropertyException { try { String key = getKey(uol, run, user, propId); ExplicitProperty property = (ExplicitProperty) fetchFromCache(key); if (property == null) { // try to find find the property definition PropertyDefFacade pdf = new PropertyDefFacade(uol.getId(), propId); // determine the type of the property String dataType = pdf.getDto().getDataType(); // now create the property property = createProperty(uol, run, user, propId, ExplicitPropertyDef.getPropertyType(dataType)); } return property; } catch (FinderException ex) { throw new PropertyNotFoundException(ex); } } /** * This method returns the local personal content of a Component. It should be * used in situation where the type of Component is known. This method will * determine the type first and create the appropriate Component accordingly. * Finally the content is returned. * * @param uol * Uol the uol for which this component was defined * @param run * Run the run for which this component was instantiated * @param user * User the user for which this component was instantiated * @param propId * String the identifier of the Component as defined in the IMS LD * instance * @param dataType * String the data type of the Component to be fetched * @return String the XML fragment representing the local personal content * @throws PropertyException * wheneve the operation fails * @throws EJBException * if the data type was unknown */ public LocalPersonalContent getLocalPersonalContent(Uol uol, Run run, User user, String propId, String dataType) throws PropertyException { String key = getKey(uol, run, user, propId); LocalPersonalContent property = (LocalPersonalContent) fetchFromCache(key); if (property == null) { if (ActivityStructurePropertyDef.DATATYPE.equals(dataType)) { return getActivityStructure(uol, run, user, propId); } else if (LearningActivityPropertyDef.DATATYPE.equals(dataType)) { return getLearningActivity(uol, run, user, propId); } else if (SupportActivityPropertyDef.DATATYPE.equals(dataType)) { return getSupportActivity(uol, run, user, propId); } else if (RolePartPropertyDef.DATATYPE.equals(dataType)) { return getRolePart(uol, run, user, propId); } else if (ActPropertyDef.DATATYPE.equals(dataType)) { return getAct(uol, run, user, propId); } else if (PlayPropertyDef.DATATYPE.equals(dataType)) { return getPlay(uol, run, user, propId); } else if (LearningObjectPropertyDef.DATATYPE.equals(dataType)) { return getLearningObject(uol, run, user, propId); } else if (EnvironmentPropertyDef.DATATYPE.equals(dataType)) { return getEnvironment(uol, run, user, propId); } else if (UnitOfLearningPropertyDef.DATATYPE.equals(dataType)) { return getUnitOfLearning(uol, run, user, propId); } else if (SendMailPropertyDef.DATATYPE.equals(dataType)) { return getSendMail(uol, run, user, propId); } else if (MonitorPropertyDef.DATATYPE.equals(dataType)) { return getMonitorObject(uol, run, user, propId); } else { Logger logger = Logger.getLogger(this.getClass()); logger.error("Unknown datatype encountered: \"" + dataType + "\""); throw new EJBException("Unknown datatype encountered: \"" + dataType + "\""); } } return property; } /** * Return an ExplicitProperty for the passed parameters. The method acts as a * factory method in cases the type of the property is known. * * @param uol * Uol the uol for which this component was defined * @param run * Run the run for which this component was instantiated * @param user * User the user for which this component was instantiated * @param propId * String the identifier of the Component as defined in the IMS LD * instance * @param type * int the integer value for the data type of the explicit properties * @throws PropertyException * whenever the operation fails * @return ExplicitProperty the property that was found or null if no property * was found */ public ExplicitProperty getProperty(Uol uol, Run run, User user, String propId, int type) throws PropertyException { String key = getKey(uol, run, user, propId); ExplicitProperty property = (ExplicitProperty) fetchFromCache(key); if (property == null) { property = createProperty(uol, run, user, propId, type); } return property; } /** * Retrieves the ExplicitPropertyDef of a explicit property with global scope. * * @param uolId * int the database id of the Uol containing the reference to this * property * @param propId * String identifier for local reference to the explicit property as * defined in the IMS LD instance * @param uri * Sting the uri action as GUID for this global property. * @return ExplicitPropertyDef the property definition for this global * property * @throws PropertyException * whenever no existing defintion for this property could be found */ public ExplicitPropertyDef getExplicitGlobalPropertyDef(int uolId, String propId, String uri) throws PropertyException { // try to find find the property definition try { PropertyDefFacade pdf = new PropertyDefFacade(uri); return createExplicitPropertyDef(uolId, propId, pdf.getDto()); } catch (FinderException ex) { throw new PropertyException(ex); } } /** * Returns an ExplicitPropertyDef instance based of the passed parameters. * Explicit properties definition have to be created via this factory because * during run-time only it's id is known. This factory determines the type of * the property by retrieving the property definition and creates the * corresponding explicit property definition. * * @param uolId * int the unit of learning id * @param propId * String the id of the property as defined in IMS-LD * @throws PropertyException * thrown when a xml error occured when parsing the persisted data * @return ExplicitPropertyDef the newly created ExplicitPropertyDef */ public ExplicitPropertyDef getExplicitPropertyDef(int uolId, String propId) throws PropertyException { // try to find find the property definition try { PropertyDefFacade pdf = new PropertyDefFacade(uolId, propId); return createExplicitPropertyDef(uolId, propId, pdf.getDto()); } catch (FinderException ex) { throw new PropertyException(ex); } } private ExplicitPropertyDef createExplicitPropertyDef(int uolId, String propId, PropertyDefDto dto) throws PropertyException { ExplicitPropertyDef result = null; if (dto.getDataType().equals(StringPropertyDef.DATATYPE)) { result = new StringPropertyDef(uolId, propId, dto); } else if (dto.getDataType().equals(IntegerPropertyDef.DATATYPE)) { result = new IntegerPropertyDef(uolId, propId, dto); } else if (dto.getDataType().equals(TextPropertyDef.DATATYPE)) { result = new TextPropertyDef(uolId, propId, dto); } else if (dto.getDataType().equals(BooleanPropertyDef.DATATYPE)) { result = new BooleanPropertyDef(uolId, propId, dto); } else if (dto.getDataType().equals(DateTimePropertyDef.DATATYPE)) { result = new DateTimePropertyDef(uolId, propId, dto); } else if (dto.getDataType().equals(DurationPropertyDef.DATATYPE)) { result = new DurationPropertyDef(uolId, propId, dto); } else if (dto.getDataType().equals(RealPropertyDef.DATATYPE)) { result = new RealPropertyDef(uolId, propId, dto); } else if (dto.getDataType().equals(UriPropertyDef.DATATYPE)) { result = new UriPropertyDef(uolId, propId, dto); } else if (dto.getDataType().equals(FilePropertyDef.DATATYPE)) { result = new FilePropertyDef(uolId, propId, dto); } else { throw new PropertyTypeException("Property Type " + dto.getDataType() + "not known"); } return result; } /** * Returns the Component containg the class visibilities. * * @param uol * Uol which refers to the classes * @param run * Run which refered to the classes * @param user * User for which the class visibilties are set * @param propId * String the id of the component as defined by CopperCore * @return ClassProperty component containg the class visibilities * @throws PropertyException * whenever the operation fails */ public ClassProperty getClasses(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, run, user, propId); ClassProperty property = (ClassProperty) fetchFromCache(key); if (property == null) { property = new ClassProperty(uol, run, user, propId); addToCache(key, property); } return property; } /** * Return a LearningActivityProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return LearningActivtyProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public LearningActivityProperty getLearningActivity(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, run, user, propId); LearningActivityProperty property = (LearningActivityProperty) fetchFromCache(key); if (property == null) { property = new LearningActivityProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a ActivityStructureProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return ActivityStructureProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public ActivityStructureProperty getActivityStructure(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, run, user, propId); ActivityStructureProperty property = (ActivityStructureProperty) fetchFromCache(key); if (property == null) { property = new ActivityStructureProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a SupportActivityProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return SupportActivityProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public SupportActivityProperty getSupportActivity(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, run, user, propId); SupportActivityProperty property = (SupportActivityProperty) fetchFromCache(key); if (property == null) { property = new SupportActivityProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a RolePartProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return RolePartProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public RolePartProperty getRolePart(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, run, user, propId); RolePartProperty property = (RolePartProperty) fetchFromCache(key); if (property == null) { property = new RolePartProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a ActProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return ActProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public ActProperty getAct(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, run, user, propId); ActProperty property = (ActProperty) fetchFromCache(key); if (property == null) { property = new ActProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a PlayProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return PlayProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public PlayProperty getPlay(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, run, user, propId); PlayProperty property = (PlayProperty) fetchFromCache(key); if (property == null) { property = new PlayProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a LearningObjectProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return LearningObjectProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public LearningObjectProperty getLearningObject(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, propId); LearningObjectProperty property = (LearningObjectProperty) fetchFromCache(key); if (property == null) { property = new LearningObjectProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a MonitorProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return MonitorProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public MonitorProperty getMonitorObject(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, propId); MonitorProperty property = (MonitorProperty) fetchFromCache(key); if (property == null) { property = new MonitorProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a SendMailProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return SendMailProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public SendMailProperty getSendMail(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, propId); SendMailProperty property = (SendMailProperty) fetchFromCache(key); if (property == null) { property = new SendMailProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a ConferenceProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return SendMailProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public ConferenceProperty getConference(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, propId); ConferenceProperty property = (ConferenceProperty) fetchFromCache(key); if (property == null) { property = new ConferenceProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a EnvironmentProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return EnvironmentProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public EnvironmentProperty getEnvironment(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, run, user, propId); EnvironmentProperty property = (EnvironmentProperty) fetchFromCache(key); if (property == null) { property = new EnvironmentProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a ActivityTreeProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param propId * the id of the component as defined in IMS LD * @return ActivityTreeProperty the component which was requested */ public ActivityTreeProperty getActivityTree(Uol uol, String propId) { String key = getKey(uol, propId); ActivityTreeProperty property = (ActivityTreeProperty) fetchFromCache(key); if (property == null) { property = new ActivityTreeProperty(uol, propId); // addToCache(key, property); } return property; } /** * Return a EnvironmentTreeProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param propId * the id of the component as defined in IMS LD * @return EnvironmentTreeProperty the component which was requested */ public EnvironmentTreeProperty getEnvironmentTree(Uol uol, String propId) { String key = getKey(uol, propId); EnvironmentTreeProperty property = (EnvironmentTreeProperty) fetchFromCache(key); if (property == null) { property = new EnvironmentTreeProperty(uol, propId); // addToCache(key, property); } return property; } /** * Return a UnitOfLearningProperty based on the passed parameters. * * @param uol * Uol which defined this component * @param run * Run to which this component belongs * @param user * User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return UnitOfLearningProperty the component which was requested * @throws PropertyException * whenever the operation fails */ public UnitOfLearningProperty getUnitOfLearning(Uol uol, Run run, User user, String propId) throws PropertyException { String key = getKey(uol, run, user, propId); UnitOfLearningProperty property = (UnitOfLearningProperty) fetchFromCache(key); if (property == null) { property = new UnitOfLearningProperty(uol, run, user, propId); // addToCache(key, property); } return property; } /** * Return a ExpressionProperty based on the passed parameters. * * @param uol * Uol which defined this component User the owner of this component * @param propId * the id of the component as defined in IMS LD * @return ExpressionProperty the component which was requested */ public ExpressionProperty getExpression(Uol uol, String propId) { String key = getKey(uol, propId); ExpressionProperty property = (ExpressionProperty) fetchFromCache(key); if (property == null) { property = new ExpressionProperty(uol, propId); addToCache(key, property); } return property; } private String getKey(Uol uol, Run run, User user, String propId) { return uol.getId() + "." + run.getId() + "." + user.getId() + "." + propId; } private String getKey(Uol uol, String propId) { return uol.getId() + "." + propId; } private ExplicitProperty createProperty(Uol uol, Run run, User user, String propId, int type) throws PropertyException, TypeCastException { ExplicitProperty property = null; switch (type) { case LDDataType.LDSTRING: { property = new StringProperty(uol, run, user, propId); break; } case LDDataType.LDINTEGER: { property = new IntegerProperty(uol, run, user, propId); break; } case LDDataType.LDTEXT: { property = new TextProperty(uol, run, user, propId); break; } case LDDataType.LDBOOLEAN: { property = new BooleanProperty(uol, run, user, propId); break; } case LDDataType.LDDATETIME: { property = new DateTimeProperty(uol, run, user, propId); break; } case LDDataType.LDDURATION: { property = new DurationProperty(uol, run, user, propId); break; } case LDDataType.LDURI: { property = new UriProperty(uol, run, user, propId); break; } case LDDataType.LDFILE: { property = new FileProperty(uol, run, user, propId); break; } case LDDataType.LDREAL: { property = new RealProperty(uol, run, user, propId); break; } default: throw new PropertyTypeException("Property Type " + type + "not known"); } // construct the key for the cache // String key = getKey(uol, run, user, propId); // cache the create property for easy and quick retrieval // addToCache(key, property); return property; } }
package qichen.code.controller; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import qichen.code.entity.AfterSaleOrder; import qichen.code.entity.DeviseOrder; import qichen.code.entity.ModelInstall; import qichen.code.entity.dto.AfterSaleOrderDTO; import qichen.code.entity.dto.DeviseOrderDTO; import qichen.code.entity.dto.ModelInstallDTO; import qichen.code.entity.dto.UserDTO; import qichen.code.exception.BusinessException; import qichen.code.exception.ResException; import qichen.code.model.DeptTypeModel; import qichen.code.model.ResponseBean; import qichen.code.service.IAfterSaleOrderService; import qichen.code.service.IModelInstallService; import qichen.code.service.IOperationLogService; import qichen.code.utils.UserContextUtils; import javax.servlet.http.HttpServletRequest; /** * <p> * ็ปดไฟฎๅทฅๅ•่กจ ๅ‰็ซฏๆŽงๅˆถๅ™จ * </p> * * @author BloodRabbit * @since 2023-01-12 */ @Slf4j @RestController @RequestMapping("/code/after-sale-order") public class AfterSaleOrderController { @Autowired private IAfterSaleOrderService afterSaleOrderService; @Autowired private UserContextUtils userContextUtils; @Autowired private IOperationLogService operationLogService; @Autowired private IModelInstallService modelInstallService; @ResponseBody @GetMapping("/getWorkOrderModel") public ResponseBean getWorkOrderModel(HttpServletRequest request, @RequestParam(value = "number") String number){ UserDTO user = userContextUtils.getCurrentUser(request); if (user==null){ return new ResponseBean(ResException.USER_MISS); } if (user.getStatus()==1){ return new ResponseBean(ResException.USER_LOCK); } if (!user.getDeptId().equals(DeptTypeModel.DEPT_AFTER_SALE)){ return new ResponseBean(ResException.USER_PER_MISS); } try { AfterSaleOrderDTO dto = afterSaleOrderService.getWorkOrderModel(user.getId(),number); return new ResponseBean(dto); }catch (BusinessException exception){ return new ResponseBean(exception); }catch (Exception exception){ exception.printStackTrace(); log.error(exception.getMessage()); return new ResponseBean(ResException.SYSTEM_ERR); } } @ResponseBody @PostMapping("/createWorkOrder") public ResponseBean createWorkOrder(HttpServletRequest request, @RequestBody AfterSaleOrderDTO dto){ UserDTO user = userContextUtils.getCurrentUser(request); if (user==null){ return new ResponseBean(ResException.USER_MISS); } if (user.getStatus()==1){ return new ResponseBean(ResException.USER_LOCK); } if (!user.getDeptId().equals(DeptTypeModel.DEPT_AFTER_SALE)){ return new ResponseBean(ResException.USER_PER_MISS); } try { dto.setSubmitId(user.getId()); dto.setSubmitType(2); //TODO ๆญฃๅผๅˆ ้™ค /* dto.setVerifyStatus(1); dto.setVerifyId(2);*/ AfterSaleOrder afterSaleOrder = afterSaleOrderService.createWorkOrder(dto); operationLogService.saveOperationLog(user.getType(), user.getId(), "410", "ๅˆ›ๅปบใ€็ปดไฟฎๅทฅๅ•ใ€‘", "t_after_sale_order", afterSaleOrder.getId(), JSON.toJSONString(afterSaleOrder)); return new ResponseBean(); }catch (BusinessException exception){ return new ResponseBean(exception); }catch (Exception exception){ exception.printStackTrace(); log.error(exception.getMessage()); return new ResponseBean(ResException.SYSTEM_ERR); } } @ResponseBody @GetMapping("/modelInstall/getWorkOrderModel") public ResponseBean getModelInstallModel(HttpServletRequest request, @RequestParam(value = "number") String number){ UserDTO user = userContextUtils.getCurrentUser(request); if (user==null){ return new ResponseBean(ResException.USER_MISS); } if (user.getStatus()==1){ return new ResponseBean(ResException.USER_LOCK); } if (!user.getDeptId().equals(DeptTypeModel.DEPT_AFTER_SALE)){ return new ResponseBean(ResException.USER_PER_MISS); } try { ModelInstallDTO dto = modelInstallService.getWorkOrderModel(user.getId(),number); return new ResponseBean(dto); }catch (BusinessException exception){ return new ResponseBean(exception); }catch (Exception exception){ exception.printStackTrace(); log.error(exception.getMessage()); return new ResponseBean(ResException.SYSTEM_ERR); } } @ResponseBody @PostMapping("/modelInstall/createWorkOrder") public ResponseBean createModelInstallOrder(HttpServletRequest request, @RequestBody ModelInstallDTO dto){ UserDTO user = userContextUtils.getCurrentUser(request); if (user==null){ return new ResponseBean(ResException.USER_MISS); } if (user.getStatus()==1){ return new ResponseBean(ResException.USER_LOCK); } if (!user.getDeptId().equals(DeptTypeModel.DEPT_AFTER_SALE)){ return new ResponseBean(ResException.USER_PER_MISS); } try { dto.setSubmitId(user.getId()); //TODO ๆญฃๅผๅˆ ้™ค /* dto.setVerifyStatus(1); dto.setVerifyId(2);*/ ModelInstall modelInstall = modelInstallService.createWorkOrder(dto); operationLogService.saveOperationLog(user.getType(), user.getId(), "410", "ๅˆ›ๅปบใ€ๆจกๅ…ทๅฎ‰่ฃ…่ฐƒ่ฏ•ๆœๅŠกๆŠฅๅ‘Šๅ•ใ€‘", "t_model_install", modelInstall.getId(), JSON.toJSONString(modelInstall)); return new ResponseBean(); }catch (BusinessException exception){ return new ResponseBean(exception); }catch (Exception exception){ exception.printStackTrace(); log.error(exception.getMessage()); return new ResponseBean(ResException.SYSTEM_ERR); } } }
import React from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import { ImageContainer, ResponsiveImage, ContactFields } from '../atoms'; import { LabelLabel } from '../molecules'; const Wrapper = styled.div` display: flex; flex-flow: wrap; `; class ContactDetails extends React.Component { static propTypes = { contact: PropTypes.shape({ id: PropTypes.number, firstName: PropTypes.string, lastName: PropTypes.string, email: PropTypes.string, homeNumber: PropTypes.string, mobileNumber: PropTypes.string, imageHash: PropTypes.string, }), } static defaultProps = { contact: null, } render() { if (this.props.contact === null) return null; const { firstName, lastName, email, homeNumber, mobileNumber, imageHash, } = this.props.contact; const imageToUse = imageHash || 'http://www.pieglobal.com/wp-content/uploads/2015/10/placeholder-user.png'; return ( <Wrapper> <ImageContainer> <ResponsiveImage src={imageToUse} /> </ImageContainer> <ContactFields> <LabelLabel text={'First Name:'} value={firstName} /> <LabelLabel text={'Last Name:'} value={lastName} /> <LabelLabel text={'Home Number:'} value={homeNumber || '-'} /> <LabelLabel text={'Mobile Number:'} value={mobileNumber || '-'} /> <LabelLabel text={'Email'} value={email || '-'} /> </ContactFields> </Wrapper> ); } } export default ContactDetails;
## ์ž๋ฐ” ์ค‘๊ธ‰ 1ํŽธ ### String ํด๋ž˜์Šค ํ•™์Šต > 1. String ์ตœ์ ํ™” > 2. ๋ฉ”์„œ๋“œ ์ฒด์ธ๋‹ - Method Chaining --- ### 1. String ์ตœ์ ํ™” > Java ์ปดํŒŒ์ผ๋Ÿฌ๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ๋ฌธ์ž์—ด ๋ฆฌํ„ฐ๋Ÿด์„ ๋”ํ•˜๋Š” ๋ถ€๋ถ„์„ ์ž๋™์œผ๋กœ ํ•ฉ์ณ์ค€๋‹ค. #### ๋ฌธ์ž์—ด ๋ฆฌํ„ฐ๋Ÿด ์ตœ์ ํ™” - ์ž๋ฐ”๋Š” ์ปจํƒ€์ž„์— ๋ณ„๋„์˜ ๋ฌธ์ž์—ด ๊ฒฐํ•ฉ ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•˜์ง€ ์•Š๊ณ  **์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ์ง์ ‘ ๊ฒฐํ•ฉ ์—ฐ์‚ฐ์„ ํ•ด์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ์„ฑ๋Šฅ์ด ํ–ฅ์ƒ**๋œ๋‹ค. ```java String helloWorld = "Hello, " + "World!"; // ์ปดํŒŒ์ผ ์ „ String helloWorld = "Hello, World!"; // ์ปดํŒŒ์ผ ํ›„ ``` #### String ๋ณ€์ˆ˜ ์ตœ์ ํ™” - ๋ฌธ์ž์—ด ๋ฆฌํ„ฐ๋Ÿด์˜ ๊ฒฝ์šฐ ๋‹จ์ˆœํžˆ ํ•ฉ์น˜๋ฉด ๋˜์ง€๋งŒ ๋ณ€์ˆ˜์˜ ๊ฒฝ์šฐ์—๋Š” ๊ทธ ๊ฐ’์„ ์•Œ์ง€ ๋ชปํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ•ฉ์น  ์ˆ˜ ์—†๋‹ค. - ์ด๋Ÿฐ ๊ฒฝ์šฐ ์ปดํŒŒ์ผ๋Ÿฌ๋Š” `StringBuilder` ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ตœ์ ํ™”๋ฅผ ํ•œ๋‹ค(Java ๋ฒ„์ „๋ณ„๋กœ ๋‹ค๋ฅด๋‹ค) ```java String result = str1 + str2; // ๋‹จ์ˆœ ๊ฒฐํ•ฉ ๋ถˆ๊ฐ€ String result = new StringBuilder().append(str1).append(str2).toString(); // ์ตœ์ ํ™” ``` > `Java 9` ๋ถ€ํ„ฐ๋Š” `StringConcatFactory` ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ตœ์ ํ™”๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค. #### String ์ตœ์ ํ™”๊ฐ€ ์–ด๋ ค์šด ๊ฒฝ์šฐ - ๋ฌธ์ž์—ด์„ ๋ฃจํ”„์•ˆ์—์„œ ๋ฌธ์ž์—ด์„ ๋”ํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” ์ตœ์ ํ™”๊ฐ€ ์ด๋ฃจ์–ด์ง€์ง€ ์•Š๋Š”๋‹ค. - ์•„๋ž˜ ์ฝ”๋“œ๋Š” ๋ฌธ์ž์—ด ๊ฒฐํ•ฉ์„ 10๋งŒ๋ฒˆ ํ•˜๋Š”๋™์•ˆ ๊ฑธ๋ฆฐ์‹œ๊ฐ„์„ ์•Œ์•„๋ณด๋Š” ์ฝ”๋“œ๋‹ค. ```java public class LoopStringMain { public static void main(String[] args) { long startTime = System.currentTimeMillis(); // ํ˜„์žฌ ms ์‹œ๊ฐ„์„ ์–ป๋Š”๋‹ค. String result = ""; for (int i = 0; i < 100000; i++) { result += "Hello Java "; } long endTime = System.currentTimeMillis(); System.out.println("time" + (endTime - startTime) + "ms"); } } ``` ![img.png](../resources/images/chap03/img11.png) - ๊ณ ์ž‘ 10๋งŒ๋ฒˆ ์—ฐ์‚ฐํ•˜๋Š”๋ฐ 2์ดˆ๋‚˜ ๊ฑธ๋ฆฌ๋Š”๊ฑด ๋ฌธ์ž์—ด ๊ฒฐํ•ฉ์ด ๋ฃจํ”„์•ˆ์—์„œ ์ตœ์ ํ™”๊ฐ€ ์•ˆ๋œ๋‹ค๋Š”๊ฒƒ์„ ๋œปํ•œ๋‹ค. - ๋ฐ˜๋ณต๋ฌธ์—์„œ n๋ฒˆ๋™์•ˆ n๊ฐœ์˜ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. ```java String result = ""; for(int i=0;i<100000;i++){ result = new StringBuilder().append(result).append("Hello Java ").toString(); } ``` - ์ €๋ ‡๊ฒŒ `StringBuilder` ๊ฐ์ฒด๋ฅผ 10๋งŒ๋ฒˆ์„ ๋งŒ๋“ค์–ด์„œ ์˜ค๋ž˜ ๊ฑธ๋ฆฐ๊ฒƒ์ด๋‹ค. - ๋ฃจํ”„๋ฌธ์•ˆ์—์„œ ๋ฌธ์ž์—ด ๊ฒฐํ•ฉ์„ ํ•œ๋‹ค๋ฉด `String` ์ด ์•„๋‹Œ `StringBuilder` ๋ฅผ ์จ์•ผํ•œ๋‹ค. ```java public class LoopStringBuilderMain { public static void main(String[] args) { long startTime = System.currentTimeMillis(); // ํ˜„์žฌ ms ์‹œ๊ฐ„์„ ์–ป๋Š”๋‹ค. StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000; i++) { sb.append("Hello Java "); } long endTime = System.currentTimeMillis(); String result = sb.toString(); System.out.println(result); System.out.println("time" + (endTime - startTime) + "ms"); } } ``` ![img.png](../resources/images/chap03/img12.png) #### StringBuilder ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ์ข‹์€ ๊ฒฝ์šฐ 1. ๋ฐ˜๋ณต๋ฌธ์—์„œ ๋ฐ˜๋ณตํ•ด์„œ ๋ฌธ์ž๋ฅผ ์—ฐ๊ฒฐํ•  ๋•Œ 2. ์กฐ๊ฑด๋ฌธ์„ ํ†ตํ•ด ๋™์ ์œผ๋กœ ๋ฌธ์ž์—ด์„ ์กฐํ•ฉํ•  ๋•Œ 3. ๋ณต์žกํ•œ ๋ฌธ์ž์—ด์˜ ํŠน์ • ๋ถ€๋ถ„์„ ๋ณ€๊ฒฝํ•ด์•ผ ํ•  ๋•Œ 4. ๋งค์šฐ ๊ธด ๋Œ€์šฉ๋Ÿ‰ ๋ฌธ์ž์—ด์„ ๋‹ค๋ฃฐ ๋•Œ > ์ฐธ๊ณ  : `StringBuilder` VS `StringBuffer` </br> > `StringBuffer` : `StringBuilder` ์™€ ๋˜‘๊ฐ™์€ ๊ธฐ๋Šฅ์„ ์ˆ˜ํ–‰ํ•˜์ง€๋งŒ ๋‚ด๋ถ€์— ๋™๊ธฐํ™”๊ฐ€ ๋˜์–ด ์žˆ์–ด์„œ, **๋ฉ€ํ‹ฐ ์“ฐ๋ ˆ๋“œ ์ƒํ™ฉ์— ์•ˆ์ „ํ•˜์ง€๋งŒ ๋™๊ธฐํ™” ์˜ค๋ฒ„ํ—ค๋“œ๋กœ ์ธํ•ด ์„ฑ๋Šฅ์ด ๋А๋ฆฌ๋‹ค.**</br> > `StringBuilder` : **๋ฉ€ํ‹ฐ ์“ฐ๋ ˆ๋“œ ์ƒํ™ฉ์— ์•ˆ์ „ํ•˜์ง€ ์•Š์ง€๋งŒ ๋™๊ธฐํ™” ์˜ค๋ฒ„ํ—ค๋“œ๊ฐ€ ์—†์œผ๋ฏ€๋กœ ์†๋„๊ฐ€ ๋น ๋ฅด๋‹ค.** --- ### 2. ๋ฉ”์„œ๋“œ ์ฒด์ธ๋‹ - Method Chaining - ๋‹จ์ˆœํžˆ ๊ฐ’์„ ๋ˆ„์ ํ•ด์„œ ๋”ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ํด๋ž˜์Šค์ด๋‹ค. - `add()` ๋ฉ”์„œ๋“œ๋Š” ํ˜ธ์ถœํ•  ๋•Œ ๋งˆ๋‹ค value ์— ๊ฐ’์„ ๋ˆ„์ ํ•˜๊ณ  ์ž๊ธฐ ์ž์‹ (`this`)์˜ ์ฐธ์กฐ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ```java public class ValueAdder { private int value; public ValueAdder add(int addValue) { value += addValue; return this; } public int getValue() { return value; } } ``` - main() ๋ฉ”์„œ๋“œ์—์„œ add() ๊ฐ€ ValueAdder ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์„ ์ด์šฉํ•˜์—ฌ ๋ˆ„์ ๊ฐ’๊ณผ ์ฐธ์กฐ๊ฐ’์„ ๋ณด์ž ```java public class MethodChainingMain2 { public static void main(String[] args) { ValueAdder adder = new ValueAdder(); ValueAdder adder1 = adder.add(1); ValueAdder adder2 = adder1.add(2); ValueAdder adder3 = adder2.add(3); System.out.println("adder3.getValue() = " + adder3.getValue()); System.out.println("adder ์ฐธ์กฐ๊ฐ’ : " +adder); System.out.println("adder1 ์ฐธ์กฐ๊ฐ’ : " +adder1); System.out.println("adder2 ์ฐธ์กฐ๊ฐ’ : " +adder2); System.out.println("adder3 ์ฐธ์กฐ๊ฐ’ : " +adder3); } } ``` ![img.png](../resources/images/chap03/img13.png) - ๋ชจ๋“  ๊ฐ์ฒด๊ฐ€ ๊ฐ™์€ ์ฐธ์กฐ๊ฐ’์„ ๊ฐ€๋ฆฌํ‚จ๋‹ค. ๊ทธ๋ฆผ์œผ๋กœ ๋ณด๋ฉด ์•„๋ž˜์™€ ๊ฐ™๋‹ค. ![img.png](../resources/images/chap03/img14.png) - ํ•˜์ง€๋งŒ ์ด๋Ÿฐ ๋ฐฉ์‹์€ ์ฝ”๋“œ๊ฐ€๋…์„ฑ๋„ ์ข‹์ง€์•Š๊ณ  ๋ถˆํŽธํ•œ ์ฝ”๋“œ์ด๋‹ค. - ๊ทธ๋Ÿฌ๋‚˜ ์œ„ ๋ฐฉ์‹์„ ์•„๋ž˜์™€ ๊ฐ™์ด ๋ฐ”๊พธ๋ฉด ์™œ ์ €๋ ‡๊ฒŒ ์ž๊ธฐ์ž์‹ ์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์‚ฌ์šฉํ–ˆ๋Š”์ง€ ์•Œ๊ฒŒ ๋œ๋‹ค. ```java public class MethodChainingMain3 { public static void main(String[] args) { ValueAdder adder = new ValueAdder(); int result = adder.add(1).add(2).add(3).getValue(); System.out.println("result = " + result); } } ``` ![img.png](../resources/images/chap03/img15.png) - `adder` ๋ผ๋Š” ์ฐธ์กฐ๋ณ€์ˆ˜์˜ ์ฐธ์กฐ๊ฐ’์— `.` ์„ ์ฐ์–ด ์ฒด์ธ์ฒ˜๋Ÿผ ๊ณ„์† ์—ฐ๊ฒฐ๋˜์–ด ๊ฐ’์„ ๊ฐ€์ ธ์˜จ๋‹ค -> ์ด๋ฅผ `๋ฉ”์„œ๋“œ ์ฒด์ด๋‹` ์ด๋ผ ํ•œ๋‹ค!! - _**๋ฉ”์„œ๋“œ ์ฒด์ด๋‹ ๊ธฐ๋ฒ•์€ ์ฝ”๋“œ๋ฅผ ๊ฐ„๊ฒฐํ•˜๊ณ  ์ฝ๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ค์–ด์ค€๋‹ค.**_ - `StringBuilder` ํด๋ž˜์Šค๋Š” **๋ฉ”์„œ๋“œ ์ฒด์ด๋‹ ๊ธฐ๋ฒ•์„ ์ œ๊ณต**ํ•œ๋‹ค.